@tbox.cn/app-sdk-server 0.24.0 → 0.24.1
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.
- package/dist/server/index.d.ts +96 -91
- package/dist/server/index.js +1 -1
- package/package.json +6 -6
package/dist/server/index.d.ts
CHANGED
|
@@ -136,7 +136,7 @@ declare const SKILL_LIMITS: {
|
|
|
136
136
|
};
|
|
137
137
|
|
|
138
138
|
/**
|
|
139
|
-
* SkillRegistry:本地 skill 注册表(模块声明式主通道
|
|
139
|
+
* SkillRegistry:本地 skill 注册表(模块声明式主通道 ,与 CardRegistry 对齐)。
|
|
140
140
|
* - name 非法(非 ^[a-z0-9-]{1,64}$)→ warn 跳过(reminder 解析安全锚);
|
|
141
141
|
* - 重名 → warn 覆盖(模块先插、应用覆盖由 build-engine 合并保证,此处仅兜底);
|
|
142
142
|
* - references key 非 .md 结尾 → warn(skill_read 引用键约定)。
|
|
@@ -166,26 +166,26 @@ declare class SkillRegistry {
|
|
|
166
166
|
|
|
167
167
|
/**
|
|
168
168
|
* 前置工具声明(模块 serverModule.preTools / 应用级 BuildEngineOptions.preTools)。
|
|
169
|
-
* tool 引用工具实例 = 单一真源(id/description
|
|
169
|
+
* tool 引用工具实例 = 单一真源(id/description 派生);key 约定 = tool.id(与 cards key=cardType 对齐)。
|
|
170
170
|
*/
|
|
171
171
|
interface PreToolDef<T extends RegistryTool = RegistryTool, TArgs extends Record<string, unknown> = Record<string, unknown>> {
|
|
172
|
-
/** 工具实例引用(build-engine 校验 tools[def.tool.id] === def.tool
|
|
172
|
+
/** 工具实例引用(build-engine 校验 tools[def.tool.id] === def.tool 实例一致性) */
|
|
173
173
|
tool: T;
|
|
174
174
|
/**
|
|
175
|
-
*
|
|
175
|
+
* 结构化路由:
|
|
176
176
|
* - { mode: 'always' }:必选候选(每轮进入 decide;执行与否由 decide 门控——慎用,防噪音);
|
|
177
177
|
* - { mode: 'keywords'; terms }: 宽召回词表(与 skill 同源打分),命中 score > 0 才候选。
|
|
178
178
|
*/
|
|
179
179
|
routing: PreToolRouting;
|
|
180
180
|
/**
|
|
181
|
-
*
|
|
181
|
+
* 决策即构造:返回 { decision: 'run', args } → 预执行该工具;
|
|
182
182
|
* { decision: 'skip', reason? } → 本轮不生效(reason 仅 span 观测,不刷日志)。
|
|
183
183
|
* 运行期(run 窗口内)调用;不得抛(SDK 兜底 warn + skip);args 必须 JSON 可序列化;
|
|
184
|
-
* 坏形状返回(非对象/run 缺 args)→ warn + skip
|
|
184
|
+
* 坏形状返回(非对象/run 缺 args)→ warn + skip。
|
|
185
185
|
*/
|
|
186
186
|
decide: (input: PreToolDecideInput) => PreToolDecision<TArgs> | Promise<PreToolDecision<TArgs>>;
|
|
187
187
|
/**
|
|
188
|
-
*
|
|
188
|
+
* 静默前置工具(/FAQ 检索通道):
|
|
189
189
|
* - 不发 START/ARGS/END 前端事件(无「自动查询中」spinner);
|
|
190
190
|
* - 结果不落 inputs.preTools(历史不重建 tool-call 表达);
|
|
191
191
|
* - 仅本轮 `<system-reminder pre-tool="...">` 数据块注入 LLM 上下文。
|
|
@@ -209,14 +209,14 @@ interface PreToolDef<T extends RegistryTool = RegistryTool, TArgs extends Record
|
|
|
209
209
|
accepts?: (result: unknown) => boolean;
|
|
210
210
|
};
|
|
211
211
|
}
|
|
212
|
-
/**
|
|
212
|
+
/** 路由判别联合:字符串字面量,非 enum */
|
|
213
213
|
type PreToolRouting = {
|
|
214
214
|
mode: 'always';
|
|
215
215
|
} | {
|
|
216
216
|
mode: 'keywords';
|
|
217
217
|
terms: string[];
|
|
218
218
|
};
|
|
219
|
-
/**
|
|
219
|
+
/** 决策结果判别联合:skip = 不执行(reason 仅 span 观测);run = 执行 + 强类型参数 */
|
|
220
220
|
type PreToolDecision<Args extends Record<string, unknown>> = {
|
|
221
221
|
decision: 'skip';
|
|
222
222
|
reason?: string;
|
|
@@ -318,7 +318,7 @@ declare class ApiRouteRegistry {
|
|
|
318
318
|
/**
|
|
319
319
|
* CardSnapshotStore 接口:卡片快照持久化。
|
|
320
320
|
* 业务模块可提供实现,SDK 默认提供内存实现。
|
|
321
|
-
* 006 评审
|
|
321
|
+
* 006 评审 `sessionId` 键语义 = 会话键(conversationId);接口名保留兼容。
|
|
322
322
|
*/
|
|
323
323
|
interface CardSnapshotStore {
|
|
324
324
|
save(sessionId: string, card: TboxCardPayload): Promise<void>;
|
|
@@ -334,7 +334,7 @@ declare class InMemoryCardSnapshotStore implements CardSnapshotStore {
|
|
|
334
334
|
}
|
|
335
335
|
|
|
336
336
|
/**
|
|
337
|
-
* 幂等存储(
|
|
337
|
+
* 幂等存储(C3)。
|
|
338
338
|
* 接口化 + InMemory(键 → 结果缓存,TTL + LRU 上限),可换 Redis。
|
|
339
339
|
* 语义:幂等 = "写几次"(业务一致性);幂等键命中且 payload 一致 → 返回首次结果(200-cached)。
|
|
340
340
|
*/
|
|
@@ -378,11 +378,11 @@ declare class InMemoryIdempotencyStore implements IdempotencyStore {
|
|
|
378
378
|
declare function hashPayload(payload: unknown): string;
|
|
379
379
|
|
|
380
380
|
/**
|
|
381
|
-
*
|
|
381
|
+
* 业务动作网关(/ C2):卡片/业务写操作的全局分发器。
|
|
382
382
|
* - POST /api/action:SDK 黑盒唯一写入口(新增写动作自动进入校验链,不可绕过)
|
|
383
|
-
* - 校验链槽位化、策略随动作注册:幂等槽
|
|
384
|
-
* - 匿名写拒绝(006
|
|
385
|
-
* - 工厂形态(消灭
|
|
383
|
+
* - 校验链槽位化、策略随动作注册:幂等槽 落地;签名/时效槽 填(API 预留不破坏)
|
|
384
|
+
* - 匿名写拒绝(006):identity.source=anonymous 的写操作一律 403,**不随 AUTH_MODE 变**
|
|
385
|
+
* - 工厂形态(消灭 模块级单例):多实例/测试互不污染
|
|
386
386
|
*
|
|
387
387
|
* 错误语义:400(缺参)/ 403(校验失败 / 匿名写)/ 404(未知 action)/ 409(幂等键被不同 payload 复用)/
|
|
388
388
|
* 500(handler 异常)/ 幂等键命中且 payload 一致 → 200 返回缓存结果(非 403)
|
|
@@ -390,7 +390,7 @@ declare function hashPayload(payload: unknown): string;
|
|
|
390
390
|
type ActionHandler = (payload: unknown, ctx: ActionContext) => Promise<ActionResult>;
|
|
391
391
|
interface ActionContext {
|
|
392
392
|
sessionId: string;
|
|
393
|
-
/**
|
|
393
|
+
/** 当前请求的运行上下文(authMiddleware 注入;未鉴权为 undefined) */
|
|
394
394
|
requestContext?: RequestContext;
|
|
395
395
|
emit: (event: ServerEvent) => void;
|
|
396
396
|
}
|
|
@@ -399,7 +399,7 @@ interface ActionResult {
|
|
|
399
399
|
data?: unknown;
|
|
400
400
|
error?: string;
|
|
401
401
|
}
|
|
402
|
-
/** 校验链槽位(签名/时效/主体槽
|
|
402
|
+
/** 校验链槽位(签名/时效/主体槽 填) */
|
|
403
403
|
interface ActionCheck {
|
|
404
404
|
check: (req: Request) => Promise<{
|
|
405
405
|
ok: boolean;
|
|
@@ -410,9 +410,9 @@ interface ActionCheck {
|
|
|
410
410
|
interface ActionPolicy {
|
|
411
411
|
/** 是否写操作(true 时幂等槽生效:缺 idempotencyKey → 400) */
|
|
412
412
|
write?: boolean;
|
|
413
|
-
/**
|
|
413
|
+
/** 幂等槽(落地):命中且 payload 一致 → 200-cached;不同 payload → 409 */
|
|
414
414
|
idempotent?: boolean;
|
|
415
|
-
/**
|
|
415
|
+
/** 校验槽(填签名/时效/主体) */
|
|
416
416
|
checks?: ActionCheck[];
|
|
417
417
|
}
|
|
418
418
|
interface ActionGateway {
|
|
@@ -509,15 +509,15 @@ declare function recordCall<T>(kind: CallKind, name: string, fn: () => Promise<T
|
|
|
509
509
|
/**
|
|
510
510
|
* 外部接口传输观测(单方法包装):请求行先于 await(调用挂起可见"只出不进"),
|
|
511
511
|
* 响应行带 durMs(>EXTERNAL_SLOW_MS 升 WARN),body 脱敏+截断;logger 缺席直通(单测路径)。
|
|
512
|
-
* run 作用域内额外发 external-call span
|
|
512
|
+
* run 作用域内额外发 external-call span(纪律:trace 平面只属引擎 run——作用域外只发行不发 span)。
|
|
513
513
|
*/
|
|
514
514
|
declare function withCallLog(logger: TboxLogger | undefined, transport: AuthenticatedTransport): AuthenticatedTransport;
|
|
515
515
|
|
|
516
516
|
/**
|
|
517
|
-
*
|
|
517
|
+
* 组件状态存储基元(/H2):
|
|
518
518
|
* get / put / compareAndSet / consume + TTL + 深冻结。
|
|
519
519
|
*
|
|
520
|
-
* - 默认 memory 实现(单实例边界明示:多副本需 shared
|
|
520
|
+
* - 默认 memory 实现(单实例边界明示:多副本需 shared 实现,等真实需求);
|
|
521
521
|
* - CAS revision 从 1 递增,用于 ActionGrant 签发竞态与幂等;
|
|
522
522
|
* - consume 原子读删(single-use token 消费语义)。
|
|
523
523
|
*/
|
|
@@ -541,7 +541,7 @@ declare function createInMemoryStateStore(now?: () => Date): ComponentStateStore
|
|
|
541
541
|
declare function hashStateRef(input: string): string;
|
|
542
542
|
|
|
543
543
|
/**
|
|
544
|
-
* Provider
|
|
544
|
+
* Provider 认证策略:credentialType → apply 注册点。
|
|
545
545
|
* - SDK 内置 'static-headers-v1'(静态头注入);
|
|
546
546
|
* - 模块自定义(如 joycity 签名算法)经注册点注入,SDK 不 import 模块。
|
|
547
547
|
*/
|
|
@@ -572,7 +572,7 @@ interface ProviderAuthStrategy {
|
|
|
572
572
|
declare const STATIC_HEADERS_CREDENTIAL_TYPE = "static-headers-v1";
|
|
573
573
|
/** 内置静态头策略:credential.value 原样映射为请求头 */
|
|
574
574
|
declare const staticHeadersStrategy: ProviderAuthStrategy;
|
|
575
|
-
/**
|
|
575
|
+
/** 可变认证策略注册表——模块 register 期注册(如 joycity-c-signed-v1),transportFactory 动态查 */
|
|
576
576
|
interface AuthStrategyRegistry {
|
|
577
577
|
get(credentialType: string): ProviderAuthStrategy | undefined;
|
|
578
578
|
/** 重复注册同名策略 → 后者覆盖 + warn(模块双装配场景) */
|
|
@@ -583,13 +583,13 @@ interface AuthStrategyRegistry {
|
|
|
583
583
|
declare function createAuthStrategyRegistry(strategies?: readonly ProviderAuthStrategy[]): AuthStrategyRegistry;
|
|
584
584
|
|
|
585
585
|
/**
|
|
586
|
-
* 换码器注册表(provider
|
|
586
|
+
* 换码器注册表(provider 拆包):可变 + 惰性查找。
|
|
587
587
|
*
|
|
588
588
|
* 背景(第五轮评审发现):options.exchanges 静态注入在 createAuthRuntime 构造期展开——
|
|
589
589
|
* provider 包 register(registerServerModules 内)晚于构造,其 authExchanges.register
|
|
590
590
|
* 静默断裂。本注册表持引用惰性查找:登录请求期才 get(platform),register 晚于构造仍生效。
|
|
591
591
|
*
|
|
592
|
-
*
|
|
592
|
+
* 三层解析(模板中立化):get(platform, context?) 按「注册通道」分层归属(非谓词形态)——
|
|
593
593
|
* ① 显式 scoped 候选:register 注册且声明 matches,注册序 first-match;
|
|
594
594
|
* ② 显式无条件候选:register 注册且无 matches(兜底位),最早注册者优先;
|
|
595
595
|
* ③ 构造期 initial 填充(内置 alipay/weapp)恒最后——内置永不遮蔽显式候选。
|
|
@@ -605,7 +605,7 @@ declare function createAuthStrategyRegistry(strategies?: readonly ProviderAuthSt
|
|
|
605
605
|
|
|
606
606
|
interface ScopedIdentityExchange extends IdentityExchange {
|
|
607
607
|
/**
|
|
608
|
-
*
|
|
608
|
+
* 谓词路由:纯函数——只读归一化 context、零 IO、不得抛;返回 false = 本候选不命中。
|
|
609
609
|
* 缺省 = 无条件候选(落第②层兜底位)。
|
|
610
610
|
*
|
|
611
611
|
* 统一范式(商圈 provider 候选):业务域依赖缺失(如未选择商场/未指定作用域)时
|
|
@@ -651,7 +651,7 @@ interface AuthExchangeRegistry {
|
|
|
651
651
|
declare function createAuthExchangeRegistry(initial?: Record<string, IdentityExchange>): AuthExchangeRegistry;
|
|
652
652
|
|
|
653
653
|
/**
|
|
654
|
-
*
|
|
654
|
+
* 环境机密解析:credentialRef → ProviderCredential。
|
|
655
655
|
* - credentialRef 形态 'secret://{env}/{seg...}'({env} 为部署环境键,剩余为分段路径);
|
|
656
656
|
* - 生产 credentialRef 缺失 → fail-fast(PROVIDER_CREDENTIAL_REF_MISSING);
|
|
657
657
|
* - scope 严格匹配(凭证 scope 与实例 scope 键值一致才可用);
|
|
@@ -684,10 +684,13 @@ interface EnvironmentSecretProviderOptions {
|
|
|
684
684
|
declare function createEnvironmentSecretProvider(opts: EnvironmentSecretProviderOptions): EnvironmentSecretProvider;
|
|
685
685
|
|
|
686
686
|
/**
|
|
687
|
-
*
|
|
687
|
+
* 认证传输层工厂:熔断(3 连败开闸 30s,半开单请求试水)+ 超时上限 + 1MB 响应体上限 +
|
|
688
|
+
* 强制 HTTPS(localhost http 豁免)+ X-Trace-Id 透传。
|
|
688
689
|
*
|
|
689
|
-
*
|
|
690
|
-
*
|
|
690
|
+
* adapter 全部 HTTP 调用经此通道:`await transport.request({ path, method, body, query })`——
|
|
691
|
+
* path 相对实例 config.baseUrl;认证头/签参由 credentialType 对应策略注入;响应体超限/
|
|
692
|
+
* 非 HTTPS/熔断开闸即抛 ProviderError。缓存责任在 registry(key 含 scope 与凭据版本),
|
|
693
|
+
* 本工厂产出单实例 transport。
|
|
691
694
|
*/
|
|
692
695
|
|
|
693
696
|
interface CircuitBreakerConfig {
|
|
@@ -744,7 +747,10 @@ declare function createAuthenticatedTransportFactory(opts: TransportFactoryOptio
|
|
|
744
747
|
* (scope) => scope.mallId),缺省 stableSerializeScope。错误上下文统一 `service@instanceId`。
|
|
745
748
|
*/
|
|
746
749
|
|
|
747
|
-
/**
|
|
750
|
+
/**
|
|
751
|
+
* adapter 构造输入(provider 包 factory 的唯一依赖面)——
|
|
752
|
+
* 自定义 API 实施指引见 provider-custom 包 INTEGRATION.md。
|
|
753
|
+
*/
|
|
748
754
|
interface ServiceAdapterInput {
|
|
749
755
|
transport: AuthenticatedTransport;
|
|
750
756
|
config: Readonly<Record<string, unknown>>;
|
|
@@ -752,13 +758,12 @@ interface ServiceAdapterInput {
|
|
|
752
758
|
scope: Readonly<Record<string, string>>;
|
|
753
759
|
instanceId: string;
|
|
754
760
|
request: RequestContext;
|
|
755
|
-
/** 本次解析的 service 槽 id
|
|
756
|
-
* 单 Port 产物;其余工厂忽略。 */
|
|
761
|
+
/** 本次解析的 service 槽 id:多槽共享 factory 时按此分支返回对应 Port 产物;单槽工厂忽略。 */
|
|
757
762
|
service: string;
|
|
758
763
|
/**
|
|
759
|
-
* 惰性凭据 getter
|
|
760
|
-
*
|
|
761
|
-
*
|
|
764
|
+
* 惰性凭据 getter:调用才解析(ref → 文件/环境),未调用零成本。
|
|
765
|
+
* 返回 ProviderCredential(含 value 机密)。credentialRef 缺席 → undefined
|
|
766
|
+
* (调用方按自身语义降级)。
|
|
762
767
|
*/
|
|
763
768
|
credential?: () => Readonly<ProviderCredential>;
|
|
764
769
|
}
|
|
@@ -804,7 +809,7 @@ interface IntegrationsRegistry {
|
|
|
804
809
|
/** 诊断快照(doctor/调试用) */
|
|
805
810
|
listAdapters(): readonly string[];
|
|
806
811
|
/**
|
|
807
|
-
*
|
|
812
|
+
* 原始装载产物(-④ 中立通道):zod 解析产物 + 源定位原样透传——
|
|
808
813
|
* 装配消费(app-config modules 资源节自动装配;域装配投影如 mallControlPlaneOf(raw.config))。
|
|
809
814
|
* SDK 零域语义:不解释 config 内容,只透传。
|
|
810
815
|
*/
|
|
@@ -828,7 +833,7 @@ interface IntegrationsRegistryOptions {
|
|
|
828
833
|
instanceIdOf?: (scope: Record<string, string>) => string;
|
|
829
834
|
/** 日志器(缺省静默;在场时 factory 收到的 transport 包 withCallLog 外部调用观测) */
|
|
830
835
|
logger?: TboxLogger;
|
|
831
|
-
/**
|
|
836
|
+
/** 配置源路径(-④ raw 通道:装配消费如 app-config 台账目录派生;缺省 undefined) */
|
|
832
837
|
source?: string;
|
|
833
838
|
/**
|
|
834
839
|
* v6 服务归属表(service → moduleId;buildOwnershipMap 产物——装配期显式注入)。
|
|
@@ -840,10 +845,10 @@ interface IntegrationsRegistryOptions {
|
|
|
840
845
|
declare function createIntegrationsRegistry(opts: IntegrationsRegistryOptions): IntegrationsRegistry;
|
|
841
846
|
|
|
842
847
|
/**
|
|
843
|
-
* Scope
|
|
848
|
+
* Scope 会话注册表(//):
|
|
844
849
|
* 会话 id 生成 + scope 键绑定 + 请求匹配护栏。
|
|
845
850
|
*
|
|
846
|
-
* SDK
|
|
851
|
+
* SDK 参数化:extractScopeKey/validateScope 由装配层注入
|
|
847
852
|
* (mall 场景经 contracts-mall createMallRuntimeAssembly),本文件零领域语义。
|
|
848
853
|
*
|
|
849
854
|
* 实现说明:连接级短命状态(TTL 30min,重启即连接全断),
|
|
@@ -856,7 +861,7 @@ interface ScopeSession {
|
|
|
856
861
|
scopeKey: string;
|
|
857
862
|
/** 完整 attributes 快照(审计用) */
|
|
858
863
|
scope: Record<string, unknown>;
|
|
859
|
-
/**
|
|
864
|
+
/** 领域扁平 scope(HelloAck 回显 + ActionGrant 签发/校验的单一来源) */
|
|
860
865
|
scopeFlat: Record<string, string>;
|
|
861
866
|
createdAt: number;
|
|
862
867
|
expiresAt: number;
|
|
@@ -876,7 +881,7 @@ interface ScopeSessionRegistryOptions {
|
|
|
876
881
|
extractScopeKey(ctx: RequestContext): string;
|
|
877
882
|
/** scope 白名单校验(接收 ctx.attributes 原样;注入方自行解析,如 parseMallScope) */
|
|
878
883
|
validateScope(attributes: Record<string, unknown>): boolean;
|
|
879
|
-
/**
|
|
884
|
+
/** 领域扁平 scope 构建(如 { miniAppId, mallId };回显 + grant 校验单一来源) */
|
|
880
885
|
buildScope(attributes: Record<string, unknown>): Record<string, string>;
|
|
881
886
|
/** 会话 TTL(缺省 30min) */
|
|
882
887
|
ttlMs?: number;
|
|
@@ -894,7 +899,7 @@ interface ActionGrantService {
|
|
|
894
899
|
moduleId: string;
|
|
895
900
|
actionId: string;
|
|
896
901
|
cardType: string;
|
|
897
|
-
/** 目标卡实例 id
|
|
902
|
+
/** 目标卡实例 id(原地更新授权锚定:token 只能作用于该卡;hidden 回调签发缺省) */
|
|
898
903
|
cardId?: string;
|
|
899
904
|
sessionId: string;
|
|
900
905
|
scope: Record<string, string>;
|
|
@@ -906,19 +911,19 @@ interface ActionGrantService {
|
|
|
906
911
|
actionId: string;
|
|
907
912
|
sessionId: string;
|
|
908
913
|
scope: Record<string, string>;
|
|
909
|
-
/** 期望目标卡实例 id(
|
|
914
|
+
/** 期望目标卡实例 id(undefined 表示签发时未锚定——hidden 回调路径) */
|
|
910
915
|
cardId?: string;
|
|
911
916
|
}): Promise<Readonly<GrantRecord>>;
|
|
912
917
|
/** 失败(execute 抛错)后恢复 single-use 令牌(业务可重试) */
|
|
913
918
|
restore(token: string): Promise<void>;
|
|
914
919
|
}
|
|
915
920
|
interface GrantRecord {
|
|
916
|
-
/**
|
|
921
|
+
/** 修复:grant 唯一 id(同参数重签互不覆盖消费标记) */
|
|
917
922
|
grantId: string;
|
|
918
923
|
moduleId: string;
|
|
919
924
|
actionId: string;
|
|
920
925
|
cardType: string;
|
|
921
|
-
/** 目标卡实例 id
|
|
926
|
+
/** 目标卡实例 id(原地更新授权锚定;进 HMAC 规范串防篡改) */
|
|
922
927
|
cardId?: string;
|
|
923
928
|
sessionId: string;
|
|
924
929
|
scope: Record<string, string>;
|
|
@@ -941,10 +946,10 @@ declare function deriveActionGrantKey(secret: Uint8Array): Uint8Array;
|
|
|
941
946
|
declare function createActionGrantService(opts: ActionGrantOptions): ActionGrantService;
|
|
942
947
|
|
|
943
948
|
/**
|
|
944
|
-
*
|
|
945
|
-
* - 类型封闭集合 + navigation 白名单;协议单源 import 自 contracts
|
|
946
|
-
* - 纯投影:效果 → tbox:effect CUSTOM 事件下行,无宿主处理器(011 占位 handler
|
|
947
|
-
* - payment/authorization 回调补签在 dispatcher step7(component-action.ts
|
|
949
|
+
* 宿主效果运行时(/E6; 纯化):
|
|
950
|
+
* - 类型封闭集合 + navigation 白名单;协议单源 import 自 contracts
|
|
951
|
+
* - 纯投影:效果 → tbox:effect CUSTOM 事件下行,无宿主处理器(011 占位 handler 已删)
|
|
952
|
+
* - payment/authorization 回调补签在 dispatcher step7(component-action.ts)
|
|
948
953
|
* 无 custom 槽位(011 I14)——新效果类型须走提案扩展 contracts 联合。
|
|
949
954
|
*/
|
|
950
955
|
|
|
@@ -979,7 +984,7 @@ interface RegisteredModuleAction {
|
|
|
979
984
|
cardType: string;
|
|
980
985
|
/** 按钮文案(payload.actions[].label) */
|
|
981
986
|
label?: string;
|
|
982
|
-
/** 按钮呈现(
|
|
987
|
+
/** 按钮呈现(kind/style/enabled 等透传 payload.actions;缺省 kind=moduleAction) */
|
|
983
988
|
kind?: 'moduleAction' | 'sendMessage' | 'openLink';
|
|
984
989
|
value?: string;
|
|
985
990
|
visible?: boolean;
|
|
@@ -987,7 +992,7 @@ interface RegisteredModuleAction {
|
|
|
987
992
|
style?: 'primary' | 'secondary' | 'link';
|
|
988
993
|
enabled?: boolean;
|
|
989
994
|
disabledReason?: string;
|
|
990
|
-
/**
|
|
995
|
+
/** 效果回调动作:不进按钮条;grant 由 dispatcher 补签 */
|
|
991
996
|
hidden?: boolean;
|
|
992
997
|
inputSchema?: z.ZodTypeAny;
|
|
993
998
|
singleUse?: boolean;
|
|
@@ -1006,7 +1011,7 @@ interface ModuleActionDispatcher {
|
|
|
1006
1011
|
actionId: string;
|
|
1007
1012
|
/** WS 连接绑定的 scope 会话 id(HELLO bootstrap 产物) */
|
|
1008
1013
|
sessionId: string;
|
|
1009
|
-
/** 动作来源卡实例 id
|
|
1014
|
+
/** 动作来源卡实例 id(原地更新目标;host-effect 回传缺省 '') */
|
|
1010
1015
|
surfaceId?: string;
|
|
1011
1016
|
ctx: RequestContext;
|
|
1012
1017
|
formData?: unknown;
|
|
@@ -1018,7 +1023,7 @@ interface ModuleActionDispatcherOptions {
|
|
|
1018
1023
|
sessions: ScopeSessionRegistry;
|
|
1019
1024
|
state: ComponentStateStore;
|
|
1020
1025
|
effects: EffectRuntime;
|
|
1021
|
-
/**
|
|
1026
|
+
/** 卡片动作注册表(结果卡签发 token 用) */
|
|
1022
1027
|
actions: CardActionRegistry;
|
|
1023
1028
|
/** 卡片 meta 注册表(CardEmitter 校验 schema 用) */
|
|
1024
1029
|
cardRegistry: Record<string, _tbox_cn_app_contracts.CardMeta>;
|
|
@@ -1028,7 +1033,7 @@ interface ModuleActionDispatcherOptions {
|
|
|
1028
1033
|
declare function createModuleActionDispatcher(opts: ModuleActionDispatcherOptions): ModuleActionDispatcher;
|
|
1029
1034
|
|
|
1030
1035
|
/**
|
|
1031
|
-
*
|
|
1036
|
+
* 域装配注册表(单一模板统一化):域模块 register 期注册、消费点运行期惰性查表。
|
|
1032
1037
|
*
|
|
1033
1038
|
* 消费点(全部运行期查表——register 顺序无关:registerAll 先于 listen;
|
|
1034
1039
|
* authExchanges 同款「晚于构造仍生效」先例):
|
|
@@ -1055,7 +1060,7 @@ interface FlowStateStore {
|
|
|
1055
1060
|
clear(sessionId: string): void;
|
|
1056
1061
|
}
|
|
1057
1062
|
/**
|
|
1058
|
-
*
|
|
1063
|
+
* 卡片动作注册表(模块声明式 CardAction 收集处)。
|
|
1059
1064
|
* 装配端把 cardActions.getAll() 交给 ModuleActionDispatcher + 卡片出卡时签发 token。
|
|
1060
1065
|
*/
|
|
1061
1066
|
interface CardActionRegistry {
|
|
@@ -1090,45 +1095,45 @@ interface ServerContext {
|
|
|
1090
1095
|
bus: TypedBus<EventMap>;
|
|
1091
1096
|
/** 卡片快照存储 */
|
|
1092
1097
|
snapshotStore: CardSnapshotStore;
|
|
1093
|
-
/**
|
|
1098
|
+
/** 业务动作网关(/C2):registerAction(action, handler, policy);组装端一次挂载 POST /api/action */
|
|
1094
1099
|
actions: ActionGateway;
|
|
1095
1100
|
/** 结构类型子集接口查找(= services.resolve;参数 = 服务 id——v7 词汇统一) */
|
|
1096
1101
|
resolveService<T>(id: string): T | undefined;
|
|
1097
1102
|
/** 业务自管的分会话状态(ALS DeviceContext 简化版) */
|
|
1098
1103
|
flowStates: FlowStateStore;
|
|
1099
|
-
/**
|
|
1104
|
+
/** 组件状态存储基元:CAS/TTL/consume;默认内存单实例边界 */
|
|
1100
1105
|
state: ComponentStateStore;
|
|
1101
1106
|
/**
|
|
1102
1107
|
* Agent 长期记忆存储(017,可选装配)。应用引擎与业务模块共享同一实例,模块仅在运行期
|
|
1103
1108
|
* 按可信身份与 scope 读写;未装配或 memory-off 时为 undefined。
|
|
1104
1109
|
*/
|
|
1105
1110
|
memory?: MemoryStore;
|
|
1106
|
-
/**
|
|
1111
|
+
/** 卡片写动作注册表:模块 CardAction 声明收集 */
|
|
1107
1112
|
cardActions: CardActionRegistry;
|
|
1108
|
-
/**
|
|
1113
|
+
/** Provider 认证策略注册表(模块 register 期注册;与 transportFactory 同引用) */
|
|
1109
1114
|
authStrategies: AuthStrategyRegistry;
|
|
1110
1115
|
/**
|
|
1111
|
-
* 换码器注册表(provider 拆包
|
|
1116
|
+
* 换码器注册表(provider 拆包 惰性查找):模块/provider register 期注册登录换码器
|
|
1112
1117
|
* (key = exchange.provider,如 alipay)。模板装配应传 authRuntime.exchanges 同引用——
|
|
1113
1118
|
* 缺省独立空注册表(直构 ctx 不炸,但注册不达登录路由)。
|
|
1114
1119
|
*/
|
|
1115
1120
|
authExchanges: AuthExchangeRegistry;
|
|
1116
1121
|
/**
|
|
1117
|
-
*
|
|
1122
|
+
* 域事实中立注入件读取视图(模板中立化; getter 化):域装配注册表
|
|
1118
1123
|
* (scope-assembly.scopeDefaults)惰性读取优先,装配 opts.scopeDefaults 静态回落。
|
|
1119
1124
|
* provider 包经 getter 登录期求值读取(register 期零读——域模块注册晚于 provider
|
|
1120
|
-
* register 仍生效,
|
|
1125
|
+
* register 仍生效, 反例修复);缺省空视图(读取 undefined)。
|
|
1121
1126
|
*/
|
|
1122
1127
|
scopeDefaults?: Readonly<Record<string, unknown>>;
|
|
1123
1128
|
/**
|
|
1124
|
-
*
|
|
1129
|
+
* 域装配注册表(-③):域模块 register 期注册(如
|
|
1125
1130
|
* `ctx.domainAssemblies.register(SCOPE_ASSEMBLY_KIND, assembly)`),消费点运行期
|
|
1126
1131
|
* 惰性查表(register 顺序无关)。SDK 只消费 scopeDefaults 成员(scopeDefaults 视图);
|
|
1127
1132
|
* 其余成员由模板装配点按 TIER1 形状读取。
|
|
1128
1133
|
*/
|
|
1129
1134
|
domainAssemblies: DomainAssemblyRegistry;
|
|
1130
1135
|
/**
|
|
1131
|
-
* Integrations 注册表(provider 拆包
|
|
1136
|
+
* Integrations 注册表(provider 拆包 槽位解析轴):provider 包 register 期注册 adapter
|
|
1132
1137
|
* (ctx.integrations.registerAdapter),模块 ports 运行期 resolveService({service, scope, request})。
|
|
1133
1138
|
* 模板装配应传 createIntegrationsRegistry 产物同引用;缺省 undefined(探测链回退——旧链路兼容)。
|
|
1134
1139
|
*/
|
|
@@ -1136,7 +1141,7 @@ interface ServerContext {
|
|
|
1136
1141
|
/**
|
|
1137
1142
|
* 模块日志器(registerServerModules 逐模块注入,tag=module:<moduleId>;可选——
|
|
1138
1143
|
* 旧 SDK 混装/直构 ctx 时缺省,模块侧用可选链 ctx.logger?.warn(...))。
|
|
1139
|
-
*
|
|
1144
|
+
* 日志规范:只经 register 期 ctx 闭包获取(多 SDK 副本下请求关联不分裂),禁模块顶层 createLogger。
|
|
1140
1145
|
*/
|
|
1141
1146
|
logger?: ServerLogger;
|
|
1142
1147
|
}
|
|
@@ -1166,7 +1171,7 @@ interface ServerModule<C extends Record<string, CardMeta> = Record<string, CardM
|
|
|
1166
1171
|
moduleId: string;
|
|
1167
1172
|
};
|
|
1168
1173
|
/**
|
|
1169
|
-
* 模块 skill
|
|
1174
|
+
* 模块 skill 声明(与 cards 对齐):key 约定 = skill.name(纯数据,零 mastra 依赖)。
|
|
1170
1175
|
* 装配端 registerAll 自动注册(ctx.skills.registerAll),register 内无需代码;
|
|
1171
1176
|
* 命令式 ctx.skills.register(...) 兜底。
|
|
1172
1177
|
*/
|
|
@@ -1183,7 +1188,7 @@ interface ServerModule<C extends Record<string, CardMeta> = Record<string, CardM
|
|
|
1183
1188
|
}
|
|
1184
1189
|
/**
|
|
1185
1190
|
* 创建 ServerContext(组装端调用一次)。
|
|
1186
|
-
*
|
|
1191
|
+
* 注入件:state(缺省 memory)。
|
|
1187
1192
|
*/
|
|
1188
1193
|
declare function createServerContext(opts?: {
|
|
1189
1194
|
snapshotStore?: CardSnapshotStore;
|
|
@@ -1194,7 +1199,7 @@ declare function createServerContext(opts?: {
|
|
|
1194
1199
|
authStrategies?: AuthStrategyRegistry;
|
|
1195
1200
|
/** 换码器注册表(模板装配传 authRuntime.exchanges 同引用;缺省独立空注册表) */
|
|
1196
1201
|
authExchanges?: AuthExchangeRegistry;
|
|
1197
|
-
/**
|
|
1202
|
+
/** 域事实中立注入件:控制面域默认值(如 { defaultMallId });缺省 undefined */
|
|
1198
1203
|
scopeDefaults?: Readonly<Record<string, unknown>>;
|
|
1199
1204
|
/** Integrations 注册表(模板装配传 createIntegrationsRegistry 产物;缺省 undefined 探测链回退) */
|
|
1200
1205
|
integrations?: IntegrationsRegistry;
|
|
@@ -1228,7 +1233,7 @@ interface HandlerDefinition {
|
|
|
1228
1233
|
/** 业务唯一标识,如 "rental" / "purchase" / "points-parking" */
|
|
1229
1234
|
id: string;
|
|
1230
1235
|
/**
|
|
1231
|
-
*
|
|
1236
|
+
* 意图声明(/意图与处理器同处定义)。
|
|
1232
1237
|
* 装配端从注册 handlers 收集构造 intentRoutes(chat 先 matchIntent——确定性档
|
|
1233
1238
|
* exact/prefix 优先,BM25 语义档兜底;缺省零 LLM,continueWith 可续接 Agent;
|
|
1234
1239
|
* match:'exact' 整句全等 / 'prefix' 模板句头前缀(均不入 BM25 词袋);
|
|
@@ -1247,7 +1252,7 @@ interface HandlerDefinition {
|
|
|
1247
1252
|
*/
|
|
1248
1253
|
handle(action: string, payload: unknown, ctx: ServerContext, reqCtx?: RequestContext): Promise<HandlerResult>;
|
|
1249
1254
|
}
|
|
1250
|
-
/** 从已注册 handlers
|
|
1255
|
+
/** 从已注册 handlers 收集意图路由(装配端调用;match 透传——exact/prefix 走洋葱确定性档) */
|
|
1251
1256
|
declare function collectIntentRoutes(handlers: ReadonlyMap<string, HandlerDefinition> | Record<string, HandlerDefinition>): {
|
|
1252
1257
|
id: string;
|
|
1253
1258
|
keywords: string[];
|
|
@@ -1272,7 +1277,7 @@ declare class HandlerRegistry {
|
|
|
1272
1277
|
interface EmitCardSpec {
|
|
1273
1278
|
cardType: string;
|
|
1274
1279
|
data: Record<string, unknown>;
|
|
1275
|
-
/** 目标会话(
|
|
1280
|
+
/** 目标会话(conversationId 唯一会话键) */
|
|
1276
1281
|
conversationId: string;
|
|
1277
1282
|
messageId?: string;
|
|
1278
1283
|
id?: string;
|
|
@@ -1280,22 +1285,22 @@ interface EmitCardSpec {
|
|
|
1280
1285
|
/**
|
|
1281
1286
|
* CardEmitter:卡片下发机制(001 §2.4 / 003 §4.2 独立化)。
|
|
1282
1287
|
* - emit:按 CardRegistry 校验 data schema 后下发 CUSTOM('tbox:card') 事件;
|
|
1283
|
-
* 填充 schemaVersion + meta.createdAt
|
|
1288
|
+
* 填充 schemaVersion + meta.createdAt(供快照持久化与迁移使用)。
|
|
1284
1289
|
* - 返回下发后的 TboxCardPayload(含填充字段),chat-engine 据此写入本轮 run 的卡片缓冲
|
|
1285
|
-
*
|
|
1290
|
+
* (写入缓冲而非即时落库)。
|
|
1286
1291
|
*/
|
|
1287
1292
|
declare class CardEmitter {
|
|
1288
1293
|
private cardRegistry;
|
|
1289
1294
|
constructor(cardRegistry: Record<string, CardMeta>);
|
|
1290
1295
|
emit(spec: EmitCardSpec, onEvent: (event: ServerEvent) => void): TboxCardPayload | undefined;
|
|
1291
|
-
/**
|
|
1296
|
+
/** 两段式——只校验 + 构造 payload(不发送);token 签发等预处理后经 send 下发 */
|
|
1292
1297
|
build(spec: EmitCardSpec): TboxCardPayload | undefined;
|
|
1293
1298
|
/** 发送 CUSTOM('tbox:card') 事件(build 产物;dispatcher 直发同用) */
|
|
1294
1299
|
send(payload: TboxCardPayload, onEvent: (event: ServerEvent) => void): TboxCardPayload;
|
|
1295
1300
|
}
|
|
1296
1301
|
|
|
1297
1302
|
/**
|
|
1298
|
-
* 防重放存储(
|
|
1303
|
+
* 防重放存储(C3)。
|
|
1299
1304
|
* 接口化 + InMemory LRU(TTL + 上限),可换 Redis。
|
|
1300
1305
|
* 语义:时间窗内同一 key 的重复请求视为重放。
|
|
1301
1306
|
*/
|
|
@@ -1318,7 +1323,7 @@ declare class InMemoryLruReplayStore implements ReplayStore {
|
|
|
1318
1323
|
}
|
|
1319
1324
|
|
|
1320
1325
|
/**
|
|
1321
|
-
* 服务端模块装配框架(010
|
|
1326
|
+
* 服务端模块装配框架(010 下沉):遍历模块 + 声明式字段自动注册 + register。
|
|
1322
1327
|
* - skills(009)/ preTools(010)声明式字段在此自动注册,模块 register 内无需代码;
|
|
1323
1328
|
* - 未来新增声明式字段只在此处加一行,模板装配零改动;
|
|
1324
1329
|
* - `await m.register(ctx)`:模块 register 可为 async——模板旧装配为 sync 循环不等待
|
|
@@ -1326,7 +1331,7 @@ declare class InMemoryLruReplayStore implements ReplayStore {
|
|
|
1326
1331
|
* - 模块级 logger 注入:每模块浅拷贝 ctx(注册表共享引用不变)挂 logger
|
|
1327
1332
|
* (tag=module:<moduleId>);模块闭包捕获即获 tag + req/conv 关联(对象注入
|
|
1328
1333
|
* 免疫多 SDK 副本,模块不 import SDK 单例——与"禁 import SDK 全局单例"铁律一致)。
|
|
1329
|
-
* - app-config
|
|
1334
|
+
* - app-config 自动装配(-④):模块资源消费入口无条件注册(与控制面正交——防无控制面
|
|
1330
1335
|
* 启动静默丢失;参数经 ctx.integrations.raw 派生:modules 资源节 + 源目录台账锚,
|
|
1331
1336
|
* registry 缺席 → 空资源零 IO)。显式注册优先(过渡期模板自注册在位不拆)。
|
|
1332
1337
|
*/
|
|
@@ -1796,7 +1801,7 @@ interface TokenServiceOptions {
|
|
|
1796
1801
|
/** 是否允许签发携带 external claim(AUTH_EMBED_EXTERNAL_TOKEN,默认开) */
|
|
1797
1802
|
embedExternalToken?: boolean;
|
|
1798
1803
|
/**
|
|
1799
|
-
* external 原始 token 上限(bytes
|
|
1804
|
+
* external 原始 token 上限(bytes,评审-H)。
|
|
1800
1805
|
* external claim 使自有 JWT 膨胀 ~1.4x(base64url),大 token 会逼近网关/代理 header 上限
|
|
1801
1806
|
* (nginx 单 header 默认 8KB;Node http 默认 16KB)。超限拒签(防发出必败请求 + 网关日志泄漏)。
|
|
1802
1807
|
* 默认 16KB,可经 AUTH_EXTERNAL_TOKEN_MAX_BYTES 调整。
|
|
@@ -1855,7 +1860,7 @@ declare const CONTEXT_ENVELOPE_MAX_BYTES = 4096;
|
|
|
1855
1860
|
declare function normalizeContextEnvelope(raw: unknown): Record<string, unknown> | undefined;
|
|
1856
1861
|
|
|
1857
1862
|
/**
|
|
1858
|
-
* HTTP
|
|
1863
|
+
* HTTP 鉴权中间件。
|
|
1859
1864
|
* - 读取 `Authorization: Bearer <token>`,校验后把 RequestContext 挂到 req(tboxAuthContext)。
|
|
1860
1865
|
* - AUTH_MODE=optional 时缺失 token → 服务端生成匿名身份(不签发 JWT)。
|
|
1861
1866
|
* - 白名单路径(登录/健康等)直接放行。
|
|
@@ -1885,7 +1890,7 @@ declare function createAnonymousIdentity(now?: number): Identity;
|
|
|
1885
1890
|
declare function createAuthMiddleware(tokenService: TokenService, opts?: AuthMiddlewareOptions): RequestHandler;
|
|
1886
1891
|
|
|
1887
1892
|
/**
|
|
1888
|
-
* WebSocket
|
|
1893
|
+
* WebSocket 鉴权(//)。
|
|
1889
1894
|
* - HELLO 消息体携带 token(不拼 URL,防日志/Referer 泄漏)。
|
|
1890
1895
|
* - 校验成功后返回连接级身份(Identity + 可选外部凭据),由 ws-server 绑定到连接。
|
|
1891
1896
|
* - optional 模式:无 token 的 HELLO → 匿名身份(服务端生成,不签发 JWT)。
|
|
@@ -1906,7 +1911,7 @@ interface WsAuthOptions {
|
|
|
1906
1911
|
declare function createWsAuthenticator(tokenService: TokenService, opts?: WsAuthOptions): WsAuthenticator;
|
|
1907
1912
|
|
|
1908
1913
|
/**
|
|
1909
|
-
* Provider dev fixture +
|
|
1914
|
+
* Provider dev fixture + 内存传输测试工具:
|
|
1910
1915
|
* - registerDevProviderFixture:非生产挂载点(模块注册假数据处理器);
|
|
1911
1916
|
* - createInMemoryTransport:测试工具(脚本化响应/请求记录/故障注入)。
|
|
1912
1917
|
*/
|
|
@@ -1926,7 +1931,7 @@ declare function runDevProviderFixture(templateId: string, req: {
|
|
|
1926
1931
|
}): unknown;
|
|
1927
1932
|
/** fixture 传输工厂:命中 fixture 的 templateId 走 fixture,其余走真实工厂 */
|
|
1928
1933
|
declare function createFixtureTransportFactory(real: TransportFactory): TransportFactory;
|
|
1929
|
-
/** 内存传输测试工具:脚本化响应 / 请求记录 /
|
|
1934
|
+
/** 内存传输测试工具:脚本化响应 / 请求记录 / 故障注入 */
|
|
1930
1935
|
interface InMemoryTransport extends AuthenticatedTransport {
|
|
1931
1936
|
mock(path: string, respond: (body: unknown) => unknown): void;
|
|
1932
1937
|
requests(): Array<{
|
|
@@ -1938,12 +1943,12 @@ interface InMemoryTransport extends AuthenticatedTransport {
|
|
|
1938
1943
|
declare function createInMemoryTransport(): InMemoryTransport;
|
|
1939
1944
|
|
|
1940
1945
|
/**
|
|
1941
|
-
* 卡片动作 token
|
|
1946
|
+
* 卡片动作 token 签发(/B3 修复):出卡时按 cardType 匹配注册动作,
|
|
1942
1947
|
* 附加 payload.actions(声明)与 payload.actionTokens(HMAC 授权 token)。
|
|
1943
1948
|
* - 单一签发点:chat-engine 出卡与 dispatcher 结果卡/原地更新共用本函数;
|
|
1944
1949
|
* - 无匹配动作 → 原样返回(零开销);
|
|
1945
1950
|
* - 签发失败(如密钥缺失)→ warn + 跳过该动作(不阻断出卡);
|
|
1946
|
-
* -
|
|
1951
|
+
* - 富形状:kind/style/enabled 等呈现字段透传 payload.actions;仅 moduleAction
|
|
1947
1952
|
* (含缺省)签发 token——sendMessage/openLink 为纯客户端语义,不进授权链。
|
|
1948
1953
|
*/
|
|
1949
1954
|
|
|
@@ -1986,7 +1991,7 @@ declare class KnowledgeError extends Error {
|
|
|
1986
1991
|
declare function createKnowledgeClient(opts?: KnowledgeClientOptions): KnowledgeClient;
|
|
1987
1992
|
|
|
1988
1993
|
/**
|
|
1989
|
-
*
|
|
1994
|
+
* 平台支付客户端(首期纳入支付,SDK 通道层,业务闭环二期)。
|
|
1990
1995
|
* 支付宝收银台薄客户端:创建收银台 + 结果查询。
|
|
1991
1996
|
* 平台支付 API 未就绪前 createCashier 抛「未装配」;就绪后经平台接口对接。
|
|
1992
1997
|
*/
|
|
@@ -2042,7 +2047,7 @@ type ResolvedResource = {
|
|
|
2042
2047
|
};
|
|
2043
2048
|
/** resolver 服务契约(app-config 服务注册物;键 = 模块 install id) */
|
|
2044
2049
|
type ModuleResourceResolver = (moduleId: string) => Readonly<Record<string, ResolvedResource>>;
|
|
2045
|
-
/** 占位 datasetId 哨兵单源(模块占位常量 + smoke
|
|
2050
|
+
/** 占位 datasetId 哨兵单源(模块占位常量 + smoke 判定共用;'faq'/'mall-knowledge' 历史值) */
|
|
2046
2051
|
declare const KNOWLEDGE_PLACEHOLDER_DATASET_IDS: readonly ["faq", "mall-knowledge"];
|
|
2047
2052
|
/**
|
|
2048
2053
|
* 预计算工厂。modules 缺席(裸跑态/无资源应用)→ 空 resolver 零 IO;
|
|
@@ -2141,7 +2146,7 @@ interface AuthRuntime {
|
|
|
2141
2146
|
/** 是否启用外部 provider 换发 */
|
|
2142
2147
|
externalEnabled: boolean;
|
|
2143
2148
|
/**
|
|
2144
|
-
*
|
|
2149
|
+
* 换码器注册表(惰性查找):登录请求期 get(platform)。模板装配应将其传入
|
|
2145
2150
|
* createServerContext({ authExchanges })——模块/provider register 期注册晚于本构造仍生效。
|
|
2146
2151
|
*/
|
|
2147
2152
|
exchanges: AuthExchangeRegistry;
|
|
@@ -2174,7 +2179,7 @@ declare class LocalAlipayExchange implements IdentityExchange {
|
|
|
2174
2179
|
}
|
|
2175
2180
|
|
|
2176
2181
|
/**
|
|
2177
|
-
*
|
|
2182
|
+
* 外部身份字段映射(修订):外部返回的原始身份对象 → 自有 Identity。
|
|
2178
2183
|
* - **userId 原样保留**(不加 ext_ 前缀、不做前缀归一化——外部系统自管命名空间,
|
|
2179
2184
|
* 平台不改造外部 id,便于与外部体系直接对应);
|
|
2180
2185
|
* - source 恒为 'external'(来源由 source 字段区分,不依赖 userId 前缀);
|
|
@@ -2219,7 +2224,7 @@ declare class ExternalIdentityExchange implements IdentityExchange {
|
|
|
2219
2224
|
exchangeByCode({ code, platform }: ExchangeRequest): Promise<ExchangeResult>;
|
|
2220
2225
|
private postOnce;
|
|
2221
2226
|
/**
|
|
2222
|
-
* 重试语义(评审
|
|
2227
|
+
* 重试语义(评审 修复):HTTP 4xx 不重试(外部业务拒绝);
|
|
2223
2228
|
* HTTP 5xx / 网络错误(fetch reject)/ 超时(AbortError)→ 单次重试。
|
|
2224
2229
|
* 换码幂等,重试安全;timestamp/sign 复用不影响(防重放窗口 5min >> 重试间隔)。
|
|
2225
2230
|
*/
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AsyncLocalStorage as hr}from"async_hooks";import{createCoreLogger as xr,detailForLog as Te,resolveLevel as Rr,setLogContextProvider as Tr}from"@tbox.cn/app-sdk-core";var D=new hr;Tr(()=>D.getStore());function Sr(t,e){return D.run(t,e)}var Ie=()=>{};function Ir(t){Ie=t}function Ve(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Se(){return new Date}function ze(t){let e=t;return{message:e?.message||String(t??"unknown"),...e?.name?{type:e.name}:{},...e?.stack?{stack:e.stack}:{}}}function y(t){return{...xr({tag:t,getLevel:()=>Rr(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>D.getStore()}),span(r,n){let o=D.getStore();Ie({spanId:Ve(`sp_${t.replace(/[^a-zA-Z0-9]/g,"")}`),traceId:o?.requestId??"no-req",name:r,startTime:Se(),endTime:Se(),...n?.metadata!==void 0?{metadata:n.metadata}:{},...n?.error!==void 0?{errorInfo:ze(n.error)}:{},requestId:o?.requestId??"no-req",...o?.conversationId?{conversationId:o.conversationId}:{},...o?.threadKey?{sessionId:o.threadKey}:{}})}}}var re=3e3;async function Er(t,e,r,n){let o=Date.now();try{let s=await r(),i=Date.now()-o;if(n?.onDone?.(i),n?.logger&&t==="tool"){let a=n.detail?.args!==void 0?` args=${Te(n.detail.args)}`:"",d=` result=${Te(s)}`;n.logger.info(`${e} ok durMs=${i}${a}${d}`)}else n?.logger&&t==="op"&&n.logger.info(`${e} ok durMs=${i}`);return n?.emitSpan&&Ct(t,e,{durMs:i}),s}catch(s){let i=Date.now()-o;if(n?.onDone?.(i),n?.logger){let a=t==="tool"?"error":"warn",d=` err=${s?.message??String(s)}`;n.logger[a](`${e} fail durMs=${i}${d}`)}throw n?.emitSpan&&Ct(t,e,{durMs:i,error:s}),s}}function Ct(t,e,r){let n=D.getStore();Ie({spanId:Ve("sp_call"),traceId:n?.requestId??"no-req",name:`${t}:${e}`,startTime:Se(),endTime:Se(),metadata:{durMs:r.durMs,kind:t},...r.error!==void 0?{errorInfo:ze(r.error)}:{},requestId:n?.requestId??"no-req",...n?.conversationId?{conversationId:n.conversationId}:{},...n?.threadKey?{sessionId:n.threadKey}:{}})}function Ee(t,e){return t?{async request(r){t.info(`→ ${r.path} body=${Te(r.body)}`);let n=Date.now(),o=D.getStore(),s=o?new Date(n):void 0;try{let i=await e.request(r),a=Date.now()-n,d=`← ${r.path} durMs=${a} body=${Te(i)}`;return a>re?t.warn(`SLOW ${d}`):t.info(d),_t(o,s,r.path,a),i}catch(i){let a=Date.now()-n;throw t.warn(`← ${r.path} durMs=${a} err=${i?.message??String(i)}`),_t(o,s,r.path,a,i),i}}}:e}function _t(t,e,r,n,o){!t||!e||Ie({spanId:Ve("sp_ext"),traceId:t.requestId??"no-req",name:"external-call",startTime:e,endTime:new Date(e.getTime()+n),metadata:{path:r,durMs:n,...n>re?{slow:!0}:{}},...o!==void 0?{errorInfo:ze(o)}:{},requestId:t.requestId??"no-req",...t.conversationId?{conversationId:t.conversationId}:{},...t.threadKey?{sessionId:t.threadKey}:{}})}var kt=y("HandlerRegistry");function vr(t){let e=[],r=t instanceof Map?[...t.values()]:Object.values(t);for(let o of r)for(let s of o.intents??[])e.push({id:`${o.id}:${s.patterns[0]??"intent"}`,keywords:s.patterns,handlerId:o.id,action:"intent",...s.match?{match:s.match}:{}});let n=e.filter(o=>o.match===void 0||o.match==="bm25");return n.length>0&&kt.warn(`顶层意图路由非确定性档(${n.map(o=>o.id).join(", ")}):语义分类职责归 skill 路由与 LLM 工具编排——建议声明 match:"exact"/"prefix"(详见 prompt-pipeline「declaration 与 intents」)`),e}var ne=class{handlers=new Map;register(e){this.handlers.has(e.id)&&kt.warn(`overwriting existing handler: ${e.id}`),this.handlers.set(e.id,e)}resolve(e){return this.handlers.get(e)}getAll(){return Object.fromEntries(this.handlers)}has(e){return this.handlers.has(e)}get size(){return this.handlers.size}async dispatch(e,r,n,o,s){let i=this.handlers.get(e);return i?i.handle(r,n,o,s):{cards:[],text:`未知的服务:${e}`}}};var Pt=y("ToolRegistry"),oe=class{tools=new Map;disabled=new Set;disable(e){e&&(this.disabled.add(e),this.tools.delete(e))}register(e){let r=e.id;if(!r){Pt.warn("tool without id skipped:",e.description);return}this.disabled.has(r)||(this.tools.has(r)&&Pt.warn(`overwriting existing tool: ${r}`),this.tools.set(r,e))}registerAll(e){for(let r of e)this.register(r)}resolve(e){return this.tools.get(e)}getAll(){return Object.fromEntries(this.tools)}has(e){return this.tools.has(e)}get size(){return this.tools.size}};var ve=y("CardRegistry"),se=class{cards=new Map;disabled=new Set;owners=new Map;disable(e){e&&(this.disabled.add(e),this.cards.delete(e))}register(e){if(!e.cardType){ve.warn("meta without cardType skipped");return}if(this.disabled.has(e.cardType)){ve.debug(`disabled cardType skipped: ${e.cardType}`);return}this.cards.has(e.cardType)&&ve.warn(`overwriting existing cardType: ${e.cardType}`),this.cards.set(e.cardType,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e))r!==n.cardType&&ve.warn(`registerMap key "${r}" !== meta.cardType "${n.cardType}", registered as meta.cardType`),this.register(n)}resolve(e){return this.cards.get(e)}recordOwner(e,r){!e||!r||this.owners.set(e,r)}ownerOf(e){return this.owners.get(e)}getAll(){return Object.fromEntries(this.cards)}has(e){return this.cards.has(e)}get size(){return this.cards.size}};import{Router as wr}from"express";var Ot=y("ApiRouteRegistry"),ie=class{root=wr();moduleIds=[];register(e,r){let n=e.replace(/^\/+|\/+$/g,"");if(!n){Ot.warn("register with empty moduleId skipped");return}this.moduleIds.includes(n)&&Ot.warn(`overwriting existing module: ${n}`),this.root.use(`/${n}`,r),this.moduleIds.includes(n)||this.moduleIds.push(n)}mount(){return this.root}getModuleIds(){return[...this.moduleIds]}};var Ar=y("ServiceRegistry"),W=class{services=new Map;register(e,r){this.services.has(e)&&Ar.warn(`overwriting existing service: ${e}`),this.services.set(e,r)}resolve(e){return this.services.get(e)}clear(){this.services.clear()}getAll(){return Object.fromEntries(this.services)}},Xe=new W;function br(t,e){Xe.register(t,e)}function Cr(t){return Xe.resolve(t)}function _r(){Xe.clear()}import{SCOPE_ASSEMBLY_KIND as kr}from"@tbox.cn/app-contracts";var Pr=y("DomainAssemblyRegistry"),ae=class{assemblies=new Map;register(e,r){this.assemblies.has(e)&&Pr.warn(`overwriting existing domain assembly: ${e}`),this.assemblies.set(e,r)}resolve(e){return this.assemblies.get(e)}scopeAssembly(){return this.resolve(kr)}get size(){return this.assemblies.size}};var Nt=y("EventBus");function We(){let t=new Map;return{on(e,r){t.has(e)||t.set(e,new Set);let n=t.get(e);return n.add(r),()=>n.delete(r)},emit(e,r){let n=t.get(e);if(n)for(let o of n)try{o(r)}catch(s){Nt.error(`handler error for "${String(e)}":`,s)}},off(e,r){let n=t.get(e);n&&n.delete(r)},clear(){t.clear()},async publish(e,r){let n=t.get(e);if(!n||n.size===0)return;let o=[];for(let s of n)try{let i=s(r);i&&typeof i.then=="function"&&o.push(i)}catch(i){Nt.error(`handler error for "${String(e)}":`,i)}o.length>0&&await Promise.allSettled(o)},subscribe(e,r){return this.on(e,r)}}}function Mt(t){let e=0;for(let r=0;r<t.length;r++)e=e*31+t.charCodeAt(r)|0;return String(e)}var ce=class{store=new Map;ttlMs;maxEntries;constructor(e){this.ttlMs=e?.ttlMs??1440*60*1e3,this.maxEntries=e?.maxEntries??1e4}async tryAcquire(e,r){let n=Date.now(),o=this.store.get(e);return o&&o.expiresAt>n?{acquired:!1,result:o.result}:(this.store.set(e,{payloadHash:r,result:void 0,expiresAt:n+this.ttlMs}),this.evict(n),{acquired:!0})}async commit(e,r){let n=this.store.get(e);this.store.set(e,{payloadHash:n?.payloadHash??"",result:r,expiresAt:n?.expiresAt??Date.now()+this.ttlMs})}getPayloadHash(e){let r=this.store.get(e);if(!(!r||r.expiresAt<=Date.now()))return r.payloadHash}release(e){this.store.delete(e)}evict(e){for(let[r,n]of this.store)n.expiresAt<=e&&this.store.delete(r);for(;this.store.size>this.maxEntries;){let r=this.store.keys().next().value;if(r===void 0)break;this.store.delete(r)}}clear(){this.store.clear()}};function Ye(t){try{return Mt(JSON.stringify(t??{}))}catch{return Mt(String(t))}}import{AUTH_ERROR_CODES as F,authCodeToStatus as Or}from"@tbox.cn/app-contracts";var w=class t extends Error{code;status;constructor(e,r){super(r||e),this.name="AuthError",this.code=e,this.status=Or(e)}static unauthorized(e){return new t(F.UNAUTHORIZED,e)}static tokenExpired(e){return new t(F.TOKEN_EXPIRED,e)}static forbidden(e){return new t(F.FORBIDDEN,e)}static methodRequired(e){return new t(F.METHOD_REQUIRED,e)}static browserLoginDisabled(e){return new t(F.BROWSER_LOGIN_DISABLED,e)}static externalError(e){return new t(F.EXTERNAL_ERROR,e)}static missingSecret(e){return new t(F.MISSING_SECRET,e)}};var Nr=y("AUTH");async function de(t,e,r){if(!e){if(r==="optional")return{identity:Je()};throw w.unauthorized("missing Bearer token")}let n=await t.verify(e);return{identity:{userId:n.sub,source:n.source},...n.external?{credentials:n.external}:{}}}var Lt=4096;function ue(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>Lt){Nr.warn("context envelope dropped (>4KB): treated as absent (fail-soft)");return}return t}catch{return}}import{AsyncLocalStorage as Mr}from"async_hooks";import{networkInterfaces as Lr}from"os";import{createCoreLogger as Dr,resolveLevel as Ur}from"@tbox.cn/app-sdk-core";var Ut="sofa-traceid",$t="sofa-rpcid",Kt="traceid",Ht="rpcid",Dt=/^[\w.-]{1,64}$/,$r=["tbox.cn"],be=new Mr,Kr=Dr({tag:"SOFA",getLevel:()=>Ur(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>{}});function Hr(t){let e=t.split(".");if(e.length!==4)return"ffffffff";let r="";for(let n of e){let o=Number(n);if(!Number.isInteger(o)||o<0||o>255)return"ffffffff";let s=o.toString(16);r+=s.length===1?`0${s}`:s}return r}function Fr(){try{for(let t of Object.values(Lr()))for(let e of t??[])if(e.family==="IPv4"&&!e.internal)return Hr(e.address)}catch{}return"ffffffff"}var qr=Fr(),we=1e3;function jr(){return we=we>9e3?1e3:we+1,String(we)}function Qe(){return qr+Date.now()+jr()+process.pid}function Br(){be.enterWith({traceId:Qe(),parentRpcId:"0",childSeq:0})}function Ae(t){return Array.isArray(t)?t[0]:t}function Ze(t){let e=Ae(t[Ut])??Ae(t[Kt]),r;if(e!==void 0&&Dt.test(e)){let n=Ae(t[$t])??Ae(t[Ht]);r={traceId:e,parentRpcId:n!==void 0&&Dt.test(n)?n:"0",childSeq:0}}else r={traceId:Qe(),parentRpcId:"0",childSeq:0};return be.enterWith(r),r.traceId}function Gr(){return be.getStore()?.traceId}function Vr(){let t=process.env.TBOX_SOFA_TRACE_HOSTS;return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[]}function zr(t){return[...$r,...Vr()].some(r=>t===r||t.endsWith(`.${r}`))}function et(t){if(process.env.TBOX_SOFA_TRACE==="off")return{};let e,r;try{let i=new URL(t);e=i.hostname.toLowerCase(),r=i.pathname}catch{return{}}if(!zr(e))return{};let n=be.getStore(),o=n?.traceId??Qe(),s=n?`${n.parentRpcId}.${++n.childSeq}`:"0.1";return Kr.debug(`out traceId=${o} rpcId=${s} host=${e} path=${r}`),{[Ut]:o,[Kt]:o,[$t]:s,[Ht]:s}}var Ft=y("HTTP");function Xr(t){if(typeof t!="string")return;let e=t.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:void 0}function Wr(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var qt="tboxAuthContext";function jt(t,e){Object.defineProperty(t,qt,{value:e,enumerable:!0,configurable:!0})}function Y(t){return t[qt]}function Je(t=Date.now()){return{userId:`anonymous_${t}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"}}function tt(t,e={}){let r=e.mode??"required",n=(e.publicPaths??[]).map(s=>s.replace(/\/+$/,""));function o(s){let i=(s.originalUrl||s.url||"").split("?")[0].replace(/\/+$/,"");return n.some(a=>i===a||i.startsWith(`${a}/`))}return async(s,i,a)=>{let d=Xr(s.headers["x-request-id"])??Wr();i.setHeader?.("X-Request-ID",d),D.enterWith({requestId:d});let f=Ze(s.headers),c=Date.now();if(i.on?.("finish",()=>{let u=Date.now()-c,p=`${s.method} ${s.originalUrl||s.url} ${i.statusCode} durMs=${u} sofa=${f}`,l=(s.originalUrl||s.url||"").split("?")[0];/\/health(z)?$/.test(l)?Ft.debug(p):Ft.info(p)}),o(s))return a();try{let u=s.headers.authorization,p=u?.startsWith("Bearer ")?u.slice(7).trim():void 0,l=await de(t,p,r),g=s.body?.context,m=s.method==="POST"&&g!==void 0?ue(g):void 0;if(m&&e.validateContext&&!e.validateContext(m)){i.status(403).json({error:"context validation failed",code:"AUTH_FORBIDDEN"});return}return jt(s,{identity:l.identity,...l.credentials?{credentials:l.credentials}:{},...m?{attributes:m}:{}}),a()}catch(u){if(u instanceof w){i.status(u.status).json({error:u.message,code:u.code});return}i.status(401).json({error:u.message,code:"AUTH_UNAUTHORIZED"})}}}var Bt=y("ActionGateway");function rt(t){let e=new Map,r=t?.idempotencyStore??new ce;function n(c){return{sessionId:(c?.body??{})?.sessionId??"",requestContext:c?Y(c):void 0,emit:()=>{}}}async function o(c,u){for(let p of u.checks??[]){let l=await p.check(c);if(!l.ok)return l}return null}async function s(c,u,p,l){let g=c.policy,m=g.write??!1,h=g.idempotent??!1;if(m&&h){if(!l)return{status:400,body:{success:!1,error:"Missing idempotencyKey (write action)"}};let S=Ye(u),I=await r.tryAcquire(l,S);if(!I.acquired){let E=r.getPayloadHash?.(l);return E&&E!==S?{status:409,body:{success:!1,error:"Idempotency key reused with different payload"}}:I.result!==void 0?{status:200,body:{...I.result,cached:!0}}:{status:200,body:{success:!0,pending:!0,cached:!0}}}try{let E=await c.handler(u,p);return await r.commit(l,E),{status:200,body:E}}catch(E){throw r.release?.(l),E}}return{status:200,body:await c.handler(u,p)}}async function i(c,u,p){if(!c||typeof c!="string")return{status:400,body:{success:!1,error:"Missing action"}};let l=e.get(c);if(!l)return{status:404,body:{success:!1,error:`Unknown action: ${c}`}};if(l.policy.write&&Y(p)?.identity?.source==="anonymous")return{status:403,body:{success:!1,error:"anonymous write is forbidden"}};let g=await o(p,l.policy);if(g)return{status:g.code??403,body:{success:!1,error:g.message}};let m=p.body??{};return s(l,u,n(p),m.idempotencyKey)}function a(){return async(c,u,p)=>{try{let l=c.body??{},g=await i(l.action,l.payload,c);u.status(g.status).json(g.body)}catch(l){Bt.error("handler error:",l),u.status(500).json({success:!1,error:l?.message||"Internal error"})}}}function d(c={}){return async(u,p,l)=>{try{let g=await o(u,c);if(g){p.status(g.code??403).json({success:!1,error:g.message});return}l()}catch(g){l(g)}}}async function f(c,u,p){let l=e.get(c);if(!l)return{success:!1,error:`Unknown action: ${c}`};let g=p?.requestContext?.identity??p?.identity;if(l.policy.write&&g?.source==="anonymous")return{success:!1,error:"anonymous write is forbidden"};let m=await o({},l.policy);return m?{success:!1,error:m.message}:(await s(l,u,{sessionId:p?.sessionId??"",requestContext:p?.requestContext?p.requestContext:p?.identity?{identity:p.identity}:void 0,emit:()=>{}},p?.idempotencyKey)).body}return{registerAction(c,u,p={}){e.has(c)&&Bt.warn(`overwriting existing action: ${c}`),e.set(c,{handler:u,policy:p})},middleware:a,validateAction:d,dispatch:f,getActions:()=>new Map(e)}}var pe=class{store=new Map;async save(e,r){let n=this.store.get(e)??[],o=n.findIndex(s=>s.id===r.id);o>=0?n[o]=r:n.push(r),this.store.set(e,n)}async load(e){return this.store.get(e)??[]}async clear(e){this.store.delete(e)}};import{EventType as Yr}from"@ag-ui/core";import{TBOX_CARD_EVENT_NAME as Jr}from"@tbox.cn/app-contracts";var Gt=y("CARD");function Vt(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var J=class{constructor(e){this.cardRegistry=e}cardRegistry;emit(e,r){let n=this.build(e);if(n)return this.send(n,r)}build(e){let r=this.cardRegistry[e.cardType];if(!r){Gt.warn(`unknown cardType: ${e.cardType}`);return}let n=r.dataSchema.safeParse(e.data);return n.success?{id:e.id||Vt("card"),messageId:e.messageId,cardType:e.cardType,data:n.data,status:"ready",schemaVersion:r.schemaVersion??1,meta:{createdAt:Date.now()},...r.project?.(n.data)??{}}:(Gt.warn(`data schema mismatch for ${e.cardType}:`,n.error.message),{id:e.id||Vt("card"),messageId:e.messageId,cardType:e.cardType,data:{},status:"error",error:"卡片数据不符合约定",schemaVersion:r.schemaVersion??1,meta:{createdAt:Date.now()}})}send(e,r){let n={type:Yr.CUSTOM,name:Jr,value:e};return r(n),e}};var nt=class{store=new Map;ttlMs;maxEntries;constructor(e){this.ttlMs=e?.ttlMs??300*1e3,this.maxEntries=e?.maxEntries??1e4}async checkAndSet(e,r){let n=Date.now(),o=this.store.get(e);return o&&o.expiresAt>n?!0:(this.store.set(e,{expiresAt:n+(r??this.ttlMs)}),this.evict(n),!1)}evict(e){for(let[r,n]of this.store)n.expiresAt<=e&&this.store.delete(r);for(;this.store.size>this.maxEntries;){let r=this.store.keys().next().value;if(r===void 0)break;this.store.delete(r)}}clear(){this.store.clear()}};import{SKILL_NAME_PATTERN as ot}from"@tbox.cn/app-contracts";var Qr={description:1024,instructions:32*1024,references:64,referenceSize:32*1024};var Ce=y("SkillRegistry"),le=class{skills=new Map;register(e){if(!ot.test(e.name)){Ce.warn(`非法 skill 名 "${e.name}" 跳过(须匹配 ^[a-z0-9-]{1,64}$)`);return}for(let r of Object.keys(e.references))r.endsWith(".md")||Ce.warn(`skill "${e.name}" reference key "${r}" 非 .md 结尾`);this.skills.has(e.name)&&Ce.warn(`覆盖已注册 skill: ${e.name}`),this.skills.set(e.name,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e))r!==n.name&&Ce.warn(`registerMap key "${r}" !== skill.name "${n.name}", registered as skill.name`),this.register(n)}getAll(){return[...this.skills.values()]}has(e){return this.skills.has(e)}get size(){return this.skills.size}};import{PRE_TOOL_NAME_PATTERN as Zr}from"@tbox.cn/app-contracts";var _e=y("PreToolRegistry"),ge=class{preTools=new Map;register(e){let r=e?.tool?.id;if(!r||!Zr.test(r)){_e.warn(`非法 toolId "${r}" 跳过(须匹配 ^[A-Za-z0-9_-]{1,64}$)`);return}if(e.routing.mode==="keywords"&&e.routing.terms.length===0){_e.warn(`keywords 路由空 terms 跳过: ${r}(恒不命中;如须每轮候选请用 always 模式)`);return}this.preTools.has(r)&&_e.warn(`覆盖已注册 pre-tool: ${r}`),this.preTools.set(r,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e)){let o=n?.tool?.id;r!==o&&_e.warn(`registerMap key "${r}" !== tool.id "${o}", registered as tool.id`),this.register(n)}}getAll(){return[...this.preTools.values()]}has(e){return this.preTools.has(e)}get size(){return this.preTools.size}};import{createHash as en,randomUUID as Ks}from"crypto";var q=(t,e)=>`${t}\0${e}`;function st(t){if(t!==null&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))st(e)}return t}function it(t=()=>new Date){let e=new Map,r=(n,o)=>n.expiresAt===void 0||n.expiresAt>o;return{async get(n,o){let s=e.get(q(n,o));return s?r(s,t().getTime())?s.value:(e.delete(q(n,o)),null):null},async getEntry(n,o){let s=e.get(q(n,o));return s?r(s,t().getTime())?{value:s.value,revision:s.revision,expiresAt:s.expiresAt}:(e.delete(q(n,o)),null):null},async put(n,o,s,i){let a=q(n,o),d=(e.get(a)?.revision??0)+1;return e.set(a,{value:st(structuredClone(s)),revision:d,expiresAt:i>0?t().getTime()+i:void 0}),!0},async compareAndSet(n,o,s,i,a){let d=q(n,o),f=t().getTime(),c=e.get(d),u=c&&r(c,f)?c.revision:0;return u!==s?!1:(e.set(d,{value:st(structuredClone(i)),revision:u+1,expiresAt:a>0?f+a:void 0}),!0)},async consume(n,o){let s=q(n,o),i=e.get(s);return i?r(i,t().getTime())?(e.delete(s),i.value):(e.delete(s),null):null}}}function tn(t){return en("sha256").update(t).digest("hex").slice(0,32)}var rn=y("PROVIDER"),zt="static-headers-v1",Xt={credentialType:zt,apply(t){let e={};for(let[r,n]of Object.entries(t.credential.value))typeof n=="string"&&(e[r]=n);return e}};function at(t=[Xt]){let e=new Map;for(let r of t)e.set(r.credentialType,r);return{get:r=>e.get(r),register:r=>{e.get(r.credentialType)!==r&&(e.has(r.credentialType)&&rn.warn(`认证策略重复注册(后者覆盖):${r.credentialType}`),e.set(r.credentialType,r))},list:()=>[...e.values()]}}var ke=y("auth-exchanges");function j(t){let e=new Map;for(let[n,o]of Object.entries(t??{}))e.set(n,o);let r=[];return{register(n){if(n.matches){r.includes(n)||r.push(n);return}let o=r.findIndex(s=>!s.matches&&s.provider===n.provider);if(o>=0){r[o]=n;return}r.push(n)},get(n,o){let s=r.filter(d=>d.provider===n);for(let d of s){if(!d.matches)continue;let f=!1;try{f=d.matches(o)!==!1}catch(c){ke.warn(`matches threw for ${n}(谓词违约视为不命中):`,c.message)}if(f)return ke.debug("resolve",n,"source=scoped"),d}let i=s.find(d=>!d.matches);if(i)return ke.debug("resolve",n,"source=fallback"),i;let a=e.get(n);return ke.debug("resolve",n,a?"source=builtin":"source=none",`explicit=${s.length}`),a},list(){return[...r,...e.values()]}}}function nn(t){let e=new W,r=t?.snapshotStore??new pe,n=new Map,o=rt({idempotencyStore:t?.idempotencyStore}),s=new ae,i=t?.scopeDefaults,a=new Proxy({},{get:(x,S)=>{if(typeof S!="string")return;let I=s.scopeAssembly()?.scopeDefaults?.[S];return I!==void 0?I:i?.[S]},has:(x,S)=>typeof S!="string"?!1:s.scopeAssembly()?.scopeDefaults?.[S]!==void 0||i?.[S]!==void 0}),d=t?.state??it(),f=t?.authStrategies??at(),c=t?.authExchanges??j(),u=new Map,p={register:x=>{if((!x.kind||x.kind==="moduleAction")&&!x.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${x.moduleId}:${x.actionId}`);u.set(x.actionId,x)},get:x=>u.get(x),getAll:()=>new Map(u)},l=x=>e.resolve(x),g=(x,S)=>n.get(x)?.[S],m=(x,S,I)=>{let E=n.get(x)??{};E[S]=I,n.set(x,E)},h=x=>{n.delete(x)};return{handlers:new ne,tools:new oe,cards:new se,skills:new le,preTools:new ge,routes:new ie,services:e,bus:We(),snapshotStore:r,actions:o,resolveService:l,flowStates:{get:g,set:m,clear:h},state:d,...t?.memory?{memory:t.memory}:{},cardActions:p,authStrategies:f,authExchanges:c,domainAssemblies:s,...t?.integrations?{integrations:t.integrations}:{},scopeDefaults:a}}import ln from"path";import{readFileSync as sn}from"fs";import{join as an}from"path";import{z as U}from"zod";import{expandEnvVars as on}from"@tbox.cn/app-toolkit";function ct(t,e=process.env,r="<config>"){let n=on(t,e);if(n.missing.length>0){let o={file:r,missing:n.missing};throw new Error(`配置文件 ${o.file} 引用的环境变量缺失:${o.missing.join("、")}(先 source .real-env/env.sh <vendor>[-<variant>] 或由部署链注入后重试;缺变量集中报错而非静默空值,防带错配置启动)`)}return n.text}var dt=y("app-config"),Wt=U.object({topK:U.number().int().positive().optional(),scoreThreshold:U.number().optional()}).passthrough(),cn=U.object({datasetId:U.string().min(1),retrieve_config:Wt.optional()}).passthrough(),dn=U.object({defaults:Wt.optional(),knowledge_bases:U.record(U.string(),cn).optional()}).passthrough(),fe={bases:{},defaults:{}};function ut(t){let e=an(t,"knowledge.json"),r;try{r=JSON.parse(ct(sn(e,"utf8"),process.env,e))}catch(s){return s.code==="ENOENT"?(dt.warn(`knowledge.json 不存在(文件:${e})——ref 引用将降级缺失(台账锚 = integrations.json 同目录,检查壳 source 传参)`),fe):(dt.warn(`knowledge.json 解析失败(${s.message},文件:${e})——ref 引用将降级缺失`),fe)}let n=dn.safeParse(r);if(!n.success)return dt.warn(`knowledge.json 校验失败(${n.error.message},文件:${e})——ref 引用将降级缺失`),fe;let o={};for(let[s,i]of Object.entries(n.data.knowledge_bases??{}))o[s]={datasetId:i.datasetId,...i.retrieve_config?.topK!==void 0?{topK:i.retrieve_config.topK}:{},...i.retrieve_config?.scoreThreshold!==void 0?{scoreThreshold:i.retrieve_config.scoreThreshold}:{}};return{bases:o,defaults:{...n.data.defaults?.topK!==void 0?{topK:n.data.defaults.topK}:{},...n.data.defaults?.scoreThreshold!==void 0?{scoreThreshold:n.data.defaults.scoreThreshold}:{}}}}var pt=y("app-config"),un=["faq","mall-knowledge"],Yt={};function lt(t,e){if(!t)return()=>Yt;let n=Object.values(t).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))?ut(e):fe,o=new Map;for(let[s,i]of Object.entries(t)){let a={};for(let[d,f]of Object.entries(i.resources??{})){let c=pn(s,d,f,n,e);c&&(a[d]=c)}o.set(s,a)}return s=>o.get(s)??Yt}function pn(t,e,r,n,o){if(r.datasetId!==void 0)return r.ref!==void 0&&pt.warn(`模块 ${t} 资源 ${e} 同时声明 datasetId 与 ref——datasetId 优先,ref 忽略`),{type:"knowledge",datasetId:r.datasetId,...r.topK!==void 0?{topK:r.topK}:{},...r.scoreThreshold!==void 0?{scoreThreshold:r.scoreThreshold}:{}};if(r.ref!==void 0){let s=n.bases[r.ref];if(!s){pt.warn(`模块 ${t} 资源 ${e} ref="${r.ref}" 在 knowledge.json 注册表未命中(目录锚:${o})——资源缺失,走模块占位回退`);return}return{type:"knowledge",datasetId:s.datasetId,topK:r.topK??s.topK??n.defaults.topK,scoreThreshold:r.scoreThreshold??s.scoreThreshold??n.defaults.scoreThreshold}}pt.warn(`模块 ${t} 资源 ${e} 无 datasetId/ref(zod 已拦,防御分支)——资源缺失`)}var gn=y("app-config");async function fn(t,e){if(!t.services.resolve("app-config")){let r=t.integrations?.raw,n=r?.source?ln.dirname(r.source):"";Object.values(r?.config.modules??{}).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))&&!r?.source&&gn.warn("integrations.raw.source 未传——模块资源 ref 将按空目录锚解析(通常落空):请在 createIntegrationsRegistry({ source: <integrations.json 源路径> }) 传参"),t.services.register("app-config",lt(r?.config.modules,n))}for(let r of e){let n={...t,logger:y(`module:${r.declaration?.moduleId??"anonymous"}`)};if("skills"in r&&r.skills&&n.skills.registerMap(r.skills),"preTools"in r&&r.preTools&&n.preTools.registerMap(r.preTools),r.declaration?.moduleId)for(let o of Object.values(r.cards))t.cards.recordOwner(o.cardType,r.declaration.moduleId);await r.register(n)}}var M="https://o.tbox.cn",gt="1.0.0",ft="X-Tbox-SDK-Version";var Jt=null;function Qt(){if(Jt)return Jt;if(typeof fetch<"u")return fetch;throw new Error("[@tbox-dev-js/sdk] No fetcher available. In mini-program environments, call setFetcher() before using SDK clients.")}function Zt(t){let e=t.success!==!1,r=t.data??t.resultObj??t.result,n=t.errorCode??t.code??t.resultCode,o=t.errorMsg??t.msg??t.resultDesc,s=t.traceId;return e?{success:!0,data:r,traceId:s}:{success:!1,errorCode:n,errorMsg:o,traceId:s}}var b=class{_baseUrl;timeout;auth;constructor(e){this._baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,"auth"in e&&e.auth?this.auth=e.auth:this.auth={type:"apiKey",apiKey:e.apiKey??""}}get baseUrl(){return this._baseUrl}getAuthHeaders(){return this.buildAuthHeaders()}buildAuthHeaders(){return this.auth.type==="session"?{TBOXSESSIONID:this.auth.session.sessionId,"X-Tbox-Channel":this.auth.session.channel,"X-Tbox-AppId":this.auth.session.appId}:{Authorization:this.auth.apiKey}}buildHeaders(e){return{"Content-Type":"application/json;charset=UTF-8",[ft]:gt,...this.buildAuthHeaders(),...e}}buildHeadersForFormData(e){return{[ft]:gt,...this.buildAuthHeaders(),...e}}async fetchWithTimeout(e,r){let n=et(e);if(Object.keys(n).length>0){let a=new Headers(r?.headers);for(let[d,f]of Object.entries(n))a.has(d)||a.set(d,f);r={...r,headers:a}}let o=Qt();if(!this.timeout||typeof AbortController>"u")return o(e,r);let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeout);try{return await o(e,{...r,signal:s.signal})}finally{clearTimeout(i)}}async post(e,r,n){let o=this.buildUrl(e,n),s;try{s=await this.fetchWithTimeout(o,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(r)})}catch(i){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:i instanceof Error?i.message:String(i)}}return this.parseResponse(s)}async postFormData(e,r,n){let o=this.buildUrl(e,n),s;try{s=await this.fetchWithTimeout(o,{method:"POST",headers:this.buildHeadersForFormData(),body:r})}catch(i){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:i instanceof Error?i.message:String(i)}}return this.parseResponse(s)}async get(e,r){let n=this.buildUrl(e,r),o;try{o=await this.fetchWithTimeout(n,{method:"GET",headers:this.buildHeaders()})}catch(s){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:s instanceof Error?s.message:String(s)}}return this.parseResponse(o)}buildUrl(e,r){let n;if(e.startsWith("http://")||e.startsWith("https://")?n=e:n=`${this._baseUrl}${e}`,!r||Object.keys(r).length===0)return n;let o=new URLSearchParams(r).toString();return`${n}?${o}`}async parseResponse(e){let r;try{r=await e.text()}catch{try{let o=await e.arrayBuffer();r=new TextDecoder("utf-8").decode(o)}catch{return{success:!1,errorCode:`HTTP_${e.status}`,errorMsg:`HTTP error: ${e.status} ${e.statusText}`}}}if(!e.ok)try{let o=JSON.parse(r),s=o.errorCode??o.code??o.resultCode??`HTTP_${e.status}`,i=o.errorMsg??o.msg??o.resultDesc??`HTTP error: ${e.status} ${e.statusText}`;return{success:!1,errorCode:s,errorMsg:i,traceId:o.traceId}}catch{return{success:!1,errorCode:`HTTP_${e.status}`,errorMsg:`HTTP error: ${e.status} ${e.statusText}`}}let n;try{n=JSON.parse(r)}catch{return{success:!1,errorCode:"PARSE_ERROR",errorMsg:"Failed to parse response JSON"}}return Zt(n)}};var Q=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,apiKey:e.apiKey,timeout:e.timeout})}async generateSession(e){return this.http.post("/openapi/v1/app/generate_session",e)}};var Pe="/openapi/v1/conversation",Oe=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,apiKey:e.apiKey,timeout:e.timeout})}async createConversation(e){return this.http.post(`${Pe}/create`,e)}async listConversations(e){return this.http.post(`${Pe}/list`,e)}async listMessages(e){return this.http.post(`${Pe}/message/list`,e)}async saveMessage(e){return this.http.post(`${Pe}/message/save`,e)}};var mn={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","audio/webm":".webm","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","application/pdf":".pdf","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","text/plain":".txt"};function yn(t,e){if(/\.\w+$/.test(t))return t;let r=e?mn[e]:void 0;return r?`${t}${r}`:t}var Ne=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,auth:{type:"session",session:e.session},timeout:e.timeout})}async upload(e){let r=yn(e.fileName??"upload",e.file.type),n=new FormData;return n.append("file",e.file,r),n.append("fileType",e.fileType==="video"?"vedio":e.fileType),this.http.postFormData("/api/files/afts/upload",n)}};var hn="wss://mediafeature.alipay.com:443/tts_stream",mt={voiceCode:"lingyue",voiceType:"SYSTEM",sampleRate:24e3,volume:50,speechRate:0,pitchRate:0},Me=class t{appId;appkey;authUrl;sessionId;channel;upstreamUrl;timeout;constructor(e){this.appId=e.appId,this.appkey=e.appkey,this.authUrl=e.authUrl,this.sessionId=e.sessionId,this.channel=e.channel,this.upstreamUrl=e.upstreamUrl??hn,this.timeout=e.timeout}static async create(e){let n=await new Q({apiKey:e.apiKey,baseUrl:e.baseUrl,timeout:e.timeout}).generateSession({appId:e.appId,userId:e.userId});if(!n.success||!n.data?.sessionId||!n.data?.channel)throw new Error(`Failed to generate session: ${n.errorCode??"UNKNOWN"} - ${n.errorMsg??"No session data returned"}`);return new t({appId:e.appId,appkey:e.appkey,authUrl:e.authUrl,sessionId:n.data.sessionId,channel:n.data.channel??e.channel,upstreamUrl:e.upstreamUrl,baseUrl:e.baseUrl,timeout:e.timeout})}async fetchAuth(){if(!this.authUrl)return{success:!1,errorCode:"CONFIGURATION_ERROR",errorMsg:"TTS authUrl is required"};if(!this.appkey)return{success:!1,errorCode:"CONFIGURATION_ERROR",errorMsg:"TTS appkey is required"};let e={"Content-Type":"application/json;charset=UTF-8","X-Tbox-AppId":this.appId};this.channel&&(e["X-Tbox-Channel"]=this.channel),this.sessionId&&(e.TBOXSESSIONID=this.sessionId);let r;try{let d={method:"POST",headers:e,body:JSON.stringify({appkey:this.appkey})};if(this.timeout){let f=new AbortController,c=setTimeout(()=>f.abort(),this.timeout);try{r=await fetch(this.authUrl,{...d,signal:f.signal})}finally{clearTimeout(c)}}else r=await fetch(this.authUrl,d)}catch(d){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:d instanceof Error?d.message:String(d)}}let n;try{n=await r.text()}catch{return{success:!1,errorCode:`HTTP_${r.status}`,errorMsg:`Failed to read response body: ${r.status} ${r.statusText}`}}if(!r.ok)try{let d=JSON.parse(n);return{success:!1,errorCode:d.errorCode??d.code??`HTTP_${r.status}`,errorMsg:d.errorMsg??d.msg??`TTS auth failed: ${r.status} ${r.statusText}`}}catch{return{success:!1,errorCode:`HTTP_${r.status}`,errorMsg:`TTS auth failed: ${r.status} - ${n}`}}let o;try{o=JSON.parse(n)}catch{return{success:!1,errorCode:"PARSE_ERROR",errorMsg:"Failed to parse TTS auth response JSON"}}let s=o.result??o,i=s.timestamp,a=s.digest;return!i||!a?{success:!1,errorCode:"INVALID_RESPONSE",errorMsg:"TTS auth response missing timestamp or digest"}:{success:!0,data:{timestamp:i,digest:a}}}buildUpstreamUrl(e){let r=new URLSearchParams({"Alipay-Mf-Appkey":this.appkey,"Alipay-Mf-Timestamp":e.timestamp,"Alipay-Mf-Digest":e.digest});return`${this.upstreamUrl}?${r.toString()}`}static buildPayload(e){let r={...mt,...e};return{sdk_language:"javascript",sdk_version:"1.0",tts_voice:r.voiceCode,sample_rate:`RATE_${r.sampleRate}`,format:"pcm",task_id:t.generateTaskId(),tts_volume:r.volume,tts_speech_rate:r.speechRate,tts_pitch_rate:r.pitchRate,tts_enable_timelines:!1,is_upload_to_afts:!1,is_blank_space_break:!1,tts_voice_type:r.voiceType,tts_style_code:"",api:"STREAM_TTS",action:"start",ext_info:"{}"}}static buildTextPayload(e){return JSON.stringify({tts_text:`<speak>${e}</speak>`})}static buildStopPayload(){return JSON.stringify({action:"stop"})}static generateTaskId(){let e="0123456789ABCDEF",r="";for(let n=0;n<32;n++)r+=e[Math.floor(Math.random()*16)];return r}};var xn="https://api.tbox.cn",me=class{http;defaultDatasetId;defaultTopK;defaultScoreThreshold;constructor(e){this.http=new b({baseUrl:e.baseUrl??"https://o.tbox.cn",apiKey:e.apiKey,timeout:e.timeout}),this.defaultDatasetId=e.datasetId,this.defaultTopK=e.topK??5,this.defaultScoreThreshold=e.scoreThreshold}async retrieve(e,r){let n=r?.datasetId??this.defaultDatasetId;if(!n)return{success:!1,errorCode:"MISSING_DATASET_ID",errorMsg:"datasetId is required. Set it in constructor config or pass it in options."};let o={datasetId:n,query:e,topK:r?.topK??this.defaultTopK,scoreThreshold:r?.scoreThreshold??this.defaultScoreThreshold},s=await this.http.post(`${xn}/api/datasets/retrieve`,o,void 0);return s.success&&s.data?{success:!0,data:s.data}:{success:!1,errorCode:s.errorCode,errorMsg:s.errorMsg}}};var er="/openapi/v1/plugin",Le=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,apiKey:e.apiKey,timeout:e.timeout})}async run(e,r){return this.http.post(`${er}/run/${encodeURIComponent(e)}`,r)}async getPluginInfo(e){return this.http.get(`${er}/info/${encodeURIComponent(e)}`)}};var De=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,auth:{type:"session",session:e.session},timeout:e.timeout})}async recognize(e){let r={base64_audio:e.base64_audio,sample_rate:e.sample_rate??"16000",audio_format:e.audio_format??"webm",enable_inverse_text:!0};return this.http.post("/agent/v1/plugin/asrBase64",r)}};var Ue=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,auth:{type:"session",session:e.session},timeout:e.timeout})}async addTag(e){let r={apiName:"agtprod.agtProdMessageFacade.addTag",requestObj:{requestId:e.requestId,feedback:e.feedback}};return this.http.post("/agent/v1/plugin/proxy",r)}};import{createHmac as Tn,hkdfSync as tr,timingSafeEqual as Sn,randomUUID as In}from"crypto";import{stableSerializeScope as En}from"@tbox.cn/app-contracts";import{randomBytes as Rn}from"crypto";function $e(t=process.env,e={}){let r=e.firstKeyName?t[e.firstKeyName]?.trim():void 0,n=t.AUTH_TOKEN_SECRET?.trim(),o=t.TBOX_API_KEY?.trim();return r?{secret:r,source:"explicit"}:n?{secret:n,source:"platform"}:o&&o.length>=32?{secret:o,source:"apiKey"}:t.NODE_ENV!=="production"?{secret:Rn(32).toString("hex"),source:"dev-temp"}:null}var C=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ActionGrantError"}code},Ke=900*1e3,ye="action-grant",rr="action-grant";function nr(t){let e=Buffer.from(t);if(e.length<32){let r=Buffer.alloc(32);return e.copy(r),new Uint8Array(tr("sha256",r,Buffer.alloc(0),Buffer.from(rr),32))}return new Uint8Array(tr("sha256",e,Buffer.alloc(0),Buffer.from(rr),32))}function vn(){let t=$e(process.env,{firstKeyName:"ACTION_TOKEN_SECRET"});if(!t)throw new C("TOKEN_INVALID","密钥链缺失:ACTION_TOKEN_SECRET/AUTH_TOKEN_SECRET");return new TextEncoder().encode(t.secret)}function wn(t){let e=t.store,r=nr(t.secret??vn()),n=t.now??(()=>Date.now());function o(a){let d=[a.moduleId,a.actionId,a.cardType,a.cardId??"",a.sessionId,En(a.scope),String(a.singleUse),String(a.expiresAt)].join("\0");return Tn("sha256",r).update(d).digest("base64url")}function s(a,d){return`${d}.${Buffer.from(JSON.stringify(a),"utf8").toString("base64url")}`}async function i(a){let d=a.indexOf(".");if(d<=0)throw new C("TOKEN_INVALID","令牌格式非法");let f=a.slice(0,d),c;try{c=JSON.parse(Buffer.from(a.slice(d+1),"base64url").toString("utf8"))}catch{throw new C("TOKEN_INVALID","令牌载荷非法")}let u=o(c),p=Buffer.from(f),l=Buffer.from(u);if(p.length!==l.length||!Sn(p,l))throw new C("TOKEN_INVALID","签名校验失败");if(c.expiresAt<=n())throw new C("TOKEN_EXPIRED","令牌已过期");return{record:c,signature:f}}return{async issue(a){let d=Math.min(a.ttlMs??Ke,Ke),f=n(),c={grantId:In(),moduleId:a.moduleId,actionId:a.actionId,cardType:a.cardType,...a.cardId!==void 0?{cardId:a.cardId}:{},sessionId:a.sessionId,scope:{...a.scope},...a.input!==void 0?{input:a.input}:{},singleUse:a.singleUse??!1,expiresAt:f+d},u=s(c,o(c));return c.singleUse&&await e.put(ye,c.grantId,{consumed:!1},d),u},async authorize(a,d){let{record:f}=await i(a);if(f.actionId!==d.actionId||f.sessionId!==d.sessionId)throw new C("GRANT_MISMATCH","授权与期望不匹配");if((f.cardId??void 0)!==(d.cardId??void 0))throw new C("GRANT_MISMATCH","授权 cardId 不匹配");let c=Object.keys(d.scope).sort(),u=Object.keys(f.scope).sort();if(c.length!==u.length||!c.every((l,g)=>l===u[g]&&d.scope[l]===f.scope[l]))throw new C("GRANT_MISMATCH","授权 scope 不匹配");let p=f.grantId;if(f.singleUse){let l=await e.getEntry(ye,p);if(!l)throw new C("TOKEN_CONSUMED","令牌已消费");if(l.value.consumed)throw new C("TOKEN_CONSUMED","令牌已消费");if(!await e.compareAndSet(ye,p,l.revision,{consumed:!0},Ke))throw new C("TOKEN_CONSUMED","令牌已消费")}return Object.freeze({...f})},async restore(a){let{record:d}=await i(a);if(!d.singleUse)return;let f=await e.get(ye,d.grantId);!f||!f.consumed||await e.put(ye,d.grantId,{consumed:!1},Math.max(d.expiresAt-n(),1e3))}}}var A=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ModuleActionError"}code};var yt=200;function He(t){return t.length>yt?`${t.slice(0,yt)}…`:t}function An(t){if(t instanceof C)return{level:"error",text:{TOKEN_EXPIRED:"操作已过期,请重新查询后再试",TOKEN_CONSUMED:"该操作已执行,请刷新卡片后重试"}[t.code]??"卡片数据已过期,为保护用户安全,请您重新唤起最新卡片数据操作"};if(t instanceof A&&t.code==="INPUT_INVALID")return{level:"error",text:"输入格式不正确,请检查后重试"};let e=t?.message??"";return{level:"error",text:He(e)||"操作执行失败,请稍后重试"}}import{SignJWT as bn,jwtVerify as Cn}from"jose";var _n=7200*1e3,kn="agent",Pn=30,or=16*1024,On={local:"local_",external:void 0,guest:"guest_",anonymous:"anonymous_"},sr=720*60*60*1e3;function ht(t){let e=new TextEncoder().encode(t.secret),r=t.issuer??kn,n=t.ttlMs??_n,o=t.clockToleranceSec??Pn,s=t.embedExternalToken??!0,i=new Set(["local","external","guest","anonymous"]);async function a(u,p){if(u.source==="anonymous")throw w.forbidden("anonymous identity cannot be issued a token");if(p?.external){let S=Buffer.byteLength(p.external.token,"utf8");if(S>(t.maxExternalTokenBytes??or))throw w.externalError(`external token too large (${S} bytes > ${t.maxExternalTokenBytes??or}); 请精简外部 claims,或由外部返回 identity 而非透传 token`)}let l=p?.now??Date.now(),g=Math.floor(l/1e3),m=Math.floor((l+n)/1e3);return{token:await new bn({source:u.source,...s&&p?.external?{external:p.external}:{}}).setProtectedHeader({alg:"HS256"}).setSubject(u.userId).setIssuer(r).setIssuedAt(g).setExpirationTime(m).sign(e),expiresAt:m*1e3}}async function d(u,p){try{let{payload:l}=await Cn(u,e,{issuer:r,algorithms:["HS256"],clockTolerance:o,...p?{ignoreExpiration:!0}:{}}),g=l.sub,m=l.source;if(!g||typeof g!="string")throw w.unauthorized("token subject missing");if(!m||!i.has(m))throw w.unauthorized("token source missing");let h=On[m];if(h&&!g.startsWith(h))throw w.unauthorized("token subject/source mismatch");return{sub:g,iss:l.iss??r,iat:typeof l.iat=="number"?l.iat*1e3:0,exp:typeof l.exp=="number"?l.exp*1e3:0,source:m,...l.external?{external:l.external}:{}}}catch(l){throw l instanceof w?l:l.code==="ERR_JWT_EXPIRED"?w.tokenExpired("token expired"):w.unauthorized(`invalid token: ${l.message}`)}}async function f(u){return d(u,!1)}async function c(u){return d(u,!0)}return{issue:a,verify:f,verifyIgnoringExpiration:c}}function xt(t,e={}){let r=e.mode??"required";return{async authenticate(n){return de(t,n,r)}}}import{createLogger as cd}from"@tbox.cn/app-sdk-core";import{randomUUID as Nn}from"crypto";var Z=class extends Error{constructor(r,n){super(r);this.code=n;this.name="ScopeSessionError"}code};function Mn(t){let e=t.ttlMs??18e5,r=t.now??(()=>Date.now()),n=new Map;return{bootstrap(o){let s=o.attributes??{};if(!t.validateScope(s))throw new Z("Scope 形状校验未通过(v4:mallId 会话边界键非空——白名单判定已退役)","SCOPE_INVALID");let i=t.extractScopeKey(o),a=r(),d={sessionId:Nn(),scopeKey:i,scope:structuredClone(s),scopeFlat:t.buildScope(s),createdAt:a,expiresAt:a+e};return n.set(d.sessionId,d),d},get(o){let s=n.get(o);return s?s.expiresAt<=r()?(n.delete(o),null):s:null},assertCurrent(o,s){let i=this.get(o);if(!i)throw new Z("会话不存在或已过期","SESSION_NOT_FOUND");if(i.scopeKey!==s)throw new Z("会话 scope 不匹配(跨 mall 需新会话)","SESSION_SCOPE_MISMATCH");return i},sweep(){let o=r();for(let[s,i]of n)i.expiresAt<=o&&n.delete(s)}}}import{PROVIDER_ERROR_CODES as $}from"@tbox.cn/app-contracts";import{existsSync as Ln,readFileSync as Dn}from"fs";import Un from"path";var R=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ProviderError"}code};function $n(t){let e=new Set(t.allowedHeaderNames??[]),r=t.production??process.env.NODE_ENV==="production";return{resolve(n,o){if(!n)throw r?new R($.CREDENTIAL_REF_MISSING,"credentialRef 缺失(生产 fail-fast)"):new R($.CREDENTIAL_REF_MISSING,"credentialRef 缺失");if(!n.startsWith("secret://"))throw new R($.CREDENTIAL_REF_MISSING,`非法 credentialRef 前缀:${n.split("://")[0]}`);let s=n.slice(9),i;if(t.files){let p=Un.join(t.files,`${s.toLowerCase().replaceAll("_","-")}.json`);if(Ln(p))try{i=Dn(p,"utf8")}catch{i=void 0}}if(i??=t.source[s.replaceAll("-","_").toUpperCase()],i??=t.source[s],!i)throw new R($.CREDENTIAL_REF_MISSING,`机密环境键缺失:${s}`);let a;try{a=JSON.parse(i)}catch{throw new R($.CREDENTIAL_REF_MISSING,`机密环境键非法 JSON:${s}`)}let d=a;if(!d||typeof d!="object")throw new R($.CREDENTIAL_REF_MISSING,`机密形状非法:${s}`);let f={};for(let[p,l]of Object.entries(d.scope??{}))typeof l=="string"&&(f[p]=l);if(Object.keys(f).length>0){for(let[p,l]of Object.entries(o))if(f[p]!==l)throw new R($.CREDENTIAL_SCOPE_MISMATCH,`凭证 scope 与实例 scope 不匹配:${p}`)}let c=typeof d.type=="string"?d.type:"static-headers-v1",u=d.value&&typeof d.value=="object"?d.value:{};if(c==="static-headers-v1"){for(let p of Object.keys(u))if(!e.has(p.toLowerCase()))throw new R($.CREDENTIAL_REF_MISSING,`头名不在白名单:${p}`)}return{scope:f,type:c,value:u}}}}import{PROVIDER_ERROR_CODES as k}from"@tbox.cn/app-contracts";import{randomUUID as Kn}from"crypto";function Rt(t){let e=t.circuitBreaker?.failureThreshold??3,r=t.circuitBreaker?.openMs??3e4,n=t.maxResponseBytes??1024*1024,o=t.maxTimeoutMs??15e3,s=t.now??(()=>Date.now());return{create:(a,d)=>{let f={failures:0,openedAt:0},c=t.strategies.get(d.credentialType);if(!c)throw new R(k.TRANSPORT_FAILURE,`未知认证类型:${d.credentialType}`);let p=(a.config??{}).baseUrl??"",l=a.scope??{},g=c.placement??"header";return{async request(m){if(f.openedAt>0){if(s()-f.openedAt<r)throw new R(k.CIRCUIT_OPEN,"熔断开闸");f.openedAt=0,f.failures=e-1}let h=m.method??"POST",x;try{x=Hn(p,m.path,m.query)}catch{throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,"URL 构造失败")}Fn(x);let S;try{S=t.secretProvider.resolve(a.credentialRef??"",l)}catch(T){throw T instanceof R&&T.code===k.CREDENTIAL_REF_MISSING?T:new R(k.TRANSPORT_FAILURE,`凭证解析失败:${T.message}`)}let I;try{I=c.apply({method:h,url:x,body:m.body,credential:S,headers:m.extraHeaders})}catch{throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,"认证参数构造失败")}let E=g==="body"&&(h==="POST"||h==="PUT");if((g==="query"||g==="body"&&!E)&&Object.keys(I).length>0)try{let T=new URL(x);for(let[L,Re]of Object.entries(I))T.searchParams.set(L,Re);x=T.toString()}catch{throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,"认证 query 追加失败")}let v={"content-type":"application/json","x-trace-id":Kn(),...g==="header"?I:{},...m.extraHeaders},N=m.body;E&&Object.keys(I).length>0&&(N={...m.body&&typeof m.body=="object"&&!Array.isArray(m.body)?m.body:{},...I});let _=Math.min(m.timeoutMs??o,o),O=new AbortController,mr=setTimeout(()=>O.abort(),_),Be=h==="GET"||N===void 0?void 0:JSON.stringify(N);t.logger?.debug("[transport] 最终请求",JSON.stringify({method:h,url:x,body:Be?JSON.parse(Be):null,headers:Object.fromEntries(Object.entries(v).map(([T,L])=>T.toLowerCase()==="token"||T.toLowerCase()==="authorization"||T.toLowerCase()==="visitortoken"?[T,typeof L=="string"?`${L.slice(0,20)}...(len=${L.length})`:L]:[T,L]))}));try{let T=await fetch(x,{method:h,headers:v,body:Be,signal:O.signal}),L=T.status>=500||T.status===429;if(!T.ok&&!L)throw new R(k.TRANSPORT_FAILURE,`HTTP ${T.status}`);if(L)throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,`HTTP ${T.status}`);let Re=Number(T.headers.get("content-length")??0);if(Re>n)throw new R(k.RESPONSE_TOO_LARGE,`响应超限:${Re}B > ${n}B`);let Ge=T.body?.getReader(),X;if(Ge){let wt=[],At=0;for(;;){let{done:yr,value:bt}=await Ge.read();if(yr)break;if(At+=bt.byteLength,At>n)throw await Ge.cancel(),new R(k.RESPONSE_TOO_LARGE,`响应超限:>${n}B`);wt.push(new TextDecoder().decode(bt))}X=wt.join("")}else if(X=await T.text(),X.length>n)throw new R(k.RESPONSE_TOO_LARGE,`响应超限:${X.length}B > ${n}B`);f.failures=0;try{return JSON.parse(X)}catch{return X}}catch(T){throw T instanceof R?T:T instanceof DOMException&&T.name==="AbortError"?(ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,`超时 ${_}ms`)):(ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,`网络错误:${T.message}`))}finally{clearTimeout(mr)}}}}}}function ee(t,e,r,n){t.failures+=1,t.failures>=e&&(t.openedAt=n())}function Hn(t,e,r){let n=t.replace(/\/+$/,""),o=e.startsWith("/")?e:`/${e}`,s=r&&Object.keys(r).length>0?`?${Object.entries(r).map(([i,a])=>`${encodeURIComponent(i)}=${encodeURIComponent(a)}`).join("&")}`:"";return`${n}${o}${s}`}function Fn(t){let e=new URL(t);if(e.protocol!=="https:"&&!((e.hostname==="127.0.0.1"||e.hostname==="localhost")&&e.protocol==="http:"))throw new R(k.TRANSPORT_FAILURE,`强制 HTTPS:${e.protocol}`)}import{buildSupplyLookup as Gn,PROVIDER_ERROR_CODES as te,resolveEffectiveService as cr,stableSerializeScope as Vn}from"@tbox.cn/app-contracts";var Fe=new Map;function qn(t,e){process.env.NODE_ENV!=="production"&&Fe.set(t,e)}function jn(){Fe.clear()}function ir(t){return Fe.has(t)}function ar(t,e){let r=Fe.get(t);if(!r)throw new Error(`无 dev fixture:${t}`);return r(e)}function Bn(t){let e={async request(n){let o=r;if(!o)throw new Error("fixture transport 未绑定实例");return ar(o.providerTemplateId,n)}},r;return{create(n,o){return ir(o.providerTemplateId)?(r=n,e):t.create(n,o)}}}function Tt(){let t=new Map,e=[],r;return{async request(n){if(e.push({path:n.path,body:n.body}),r){let s=r;throw r=void 0,s}let o=t.get(n.path);if(!o)throw new Error(`未 mock 的路径:${n.path}`);return o(n.body)},mock(n,o){t.set(n,o)},requests:()=>[...e],failNext(n){r=n}}}var dr=(t,e)=>`${t}\0${e}`,zn={identity:{userId:"",source:"anonymous"},credentials:{provider:"anonymous",token:""},attributes:{}},Xn=Object.freeze({});function Wn(t){let e=new Map,r=new Map,n=t.transportFactory??Rt({strategies:t.authStrategies,secretProvider:t.secretProvider,logger:t.logger}),o=t.instanceIdOf??(c=>Vn(c)),s=Gn(t.catalog),i=Xn,a=c=>typeof c=="string"?c:`${c.provider}(inline)`,d=(c,u,p,l)=>{if(typeof c=="string"){let g=t.catalog.providers[c]?.[u];if(!g)throw new R(te.PROVIDER_NOT_FOUND,`provider 未命中 catalog:${c}/${u}(${p}@${l})`);return{provider:c,implementation:u,entry:g,inline:void 0}}return{provider:c.provider,implementation:"inline",entry:void 0,inline:c}};function f(c){let u=o(c.scope),p=cr(t.integrations,c.service,u,s,t.ownerOf);if(p.status==="service-not-configured")throw new R(te.SERVICE_NOT_CONFIGURED,`服务槽未配置:${c.service}(integrations.services 缺键)`);if(p.status==="instance-not-found")throw new R(te.INSTANCE_NOT_FOUND,`无匹配实例:${c.service}@${u}(instances 缺键)`);if(p.status==="instance-disabled")throw new R(te.INSTANCE_DISABLED,`实例已禁用:${c.service}@${u}`);if(p.status==="binding-unresolved")throw new R(te.BINDING_UNRESOLVED,p.message);let l=p.effective,g=d(l.provider,l.implementation,c.service,u),m=g.entry?.local===!0,h;if(m)h=Tt();else{let x=`${c.service}\0${u}\0${g.provider}\0${g.implementation}`;h=r.get(x)??(()=>{let S={providerInstanceId:`${c.service}:${u}:${g.provider}:${g.implementation}`,providerTemplateId:g.implementation,scope:c.scope,config:l.config,...l.credentialRef?{credentialRef:l.credentialRef}:{},enabled:!0},I={providerTemplateId:g.implementation,credentialType:g.entry?.credentialType??g.inline?.credentialType??"-"},E=n.create(S,I);return r.set(x,E),E})()}return{transport:h,local:m,config:l.config,credentialRef:l.credentialRef,provider:g.provider,implementation:g.implementation,providerDisplay:a(l.provider),instanceId:u}}return{registerAdapter(c,u,p){let l=dr(c,u);e.has(l)&&t.logger?.warn(`adapter 重复注册(后者覆盖):${c}/${u}`),e.set(l,p)},listAdapters(){return[...e.keys()]},declareProviderInstances(c,u){if(u.length!==0){for(let p of u)if(typeof p.id!="string"||!p.id||p.id==="*"||typeof p.name!="string"||!p.name)throw new Error(`declareProviderInstances 非法实例(provider=${c}):id 禁空与 '*'(通配保留字),name 须非空 string`);i[c]!==void 0&&t.logger?.warn(`provider instances 重复声明(后者覆盖):${c}`),i=Object.freeze({...i,[c]:Object.freeze(u.map(p=>Object.freeze({...p})))})}},providerInstanceDeclarations(){return i},async resolveService(c){let u=f(c),p=e.get(dr(u.provider,u.implementation));if(!p)throw new R(te.PROVIDER_NOT_IMPLEMENTED,`provider 未实施(无 adapter 注册):${u.providerDisplay}/${u.implementation}(${c.service}@${u.instanceId})`);return p({transport:Ee(u.local?void 0:t.logger,u.transport),config:u.config??{},...u.credentialRef?{credentialRef:u.credentialRef}:{},...u.credentialRef?{credential:()=>t.secretProvider.resolve(u.credentialRef,c.scope)}:{},scope:c.scope,instanceId:u.instanceId,request:c.request,service:c.service})},async resolveLoginExchange(c){let u=f({...c,request:zn});return{transport:Ee(u.local?void 0:t.logger,u.transport),config:u.config??{},providerId:u.implementation}},hasProviderBinding(c,u,p,l){let g=o(u),m=cr(t.integrations,c,g,s,t.ownerOf);if(m.status!=="ok")return!1;let h=m.effective;return typeof h.provider=="string"&&h.provider===p&&h.implementation===l},raw:{config:t.integrations,...t.source?{source:t.source}:{}}}}import{loadProviderCatalog as Yn,buildOwnershipMap as Jn}from"@tbox.cn/app-toolkit";import{EventType as ur}from"@ag-ui/core";import{TBOX_CARD_UPDATE_EVENT_NAME as eo,TBOX_NOTICE_EVENT_NAME as to}from"@tbox.cn/app-contracts";var Qn=y("CARD");function Zn(t){return{actionId:t.actionId,...t.label!==void 0?{label:t.label}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.value!==void 0?{value:t.value}:{},...t.visible!==void 0?{visible:t.visible}:{},...t.url!==void 0?{url:t.url}:{},...t.style!==void 0?{style:t.style}:{},...t.enabled!==void 0?{enabled:t.enabled}:{},...t.disabledReason!==void 0?{disabledReason:t.disabledReason}:{}}}async function qe(t){if(t.payload.actions&&t.payload.actions.length>0)return t.payload;let e=[];for(let n of t.actions.getAll().values())n.cardType===t.payload.cardType&&!("hidden"in n&&n.hidden)&&e.push({...Zn(n),...n.singleUse?{singleUse:!0}:{}});if(e.length===0)return t.payload;let r={};for(let n of e)if(!(n.kind&&n.kind!=="moduleAction"))try{r[n.actionId]=await t.grants.issue({moduleId:t.actions.get(n.actionId)?.moduleId??"",actionId:n.actionId,cardType:t.payload.cardType,cardId:t.payload.id,sessionId:t.sessionId,scope:t.scope,singleUse:n.singleUse??!1})}catch(o){Qn.warn(`动作 token 签发失败(跳过):${n.actionId}`,o.message)}return{...t.payload,actions:e.map(({singleUse:n,...o})=>o),...Object.keys(r).length>0?{actionTokens:r}:{}}}var ro=600*1e3;function no(t){return t.type==="payment"||t.type==="authorization.alipay-user-profile"}function oo(t,e){if(typeof t=="string"&&t!=="")return t;if(!e||typeof e!="object"||Array.isArray(e))return;let r=e.surfaceId;return typeof r=="string"&&r!==""?r:void 0}function so(t){let e=new Map;return{register(r){if((!r.kind||r.kind==="moduleAction")&&!r.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${r.moduleId}:${r.actionId}`);e.set(r.actionId,r)},get(r){return e.get(r)},async dispatch(r){let n=e.get(r.actionId);if(!n)throw new A("ACTION_NOT_FOUND",`未知模块动作:${r.actionId}`);let o=t.extractScopeKey(r.ctx),s=t.sessions.assertCurrent(r.sessionId,o),i=await t.grants.authorize(r.token,{actionId:r.actionId,sessionId:s.sessionId,scope:s.scopeFlat,cardId:r.surfaceId||void 0}),a,d=[];try{if(i.cardType!==n.cardType)throw new A("GRANT_INVALID","授权 cardType 与动作声明不一致");let c=r.formData&&typeof r.formData=="object"&&!Array.isArray(r.formData)?r.formData:{},u=i.input&&typeof i.input=="object"&&!Array.isArray(i.input)?{...c,...i.input}:c,p=u;if(n.inputSchema){let g=n.inputSchema.safeParse(u);if(!g.success)throw new A("INPUT_INVALID",`入参校验失败:${g.error.message}`);p=g.data}if(!n.execute)throw new A("GRANT_INVALID",`动作无服务端执行体(纯客户端 kind 不应进 dispatch):${r.actionId}`);if(a=await n.execute(p,r.ctx),!a||typeof a!="object")throw new A("RESULT_INVALID","动作结果形状非法");for(let g of a.effects??[]){let m=g;if(m&&no(m)){let h=e.get(m.resultActionId);if(!h)throw new A("CALLBACK_INVALID",`效果回调动作未注册:${m.resultActionId}`);if(h.moduleId!==i.moduleId)throw new A("CALLBACK_INVALID",`效果回调动作组件归属不一致:${m.resultActionId}`);if(h.cardType!==n.cardType)throw new A("CALLBACK_INVALID",`效果回调动作 cardType 与当前动作不一致:${m.resultActionId}`);if(h.singleUse!==!0)throw new A("CALLBACK_INVALID",`效果回调动作必须 singleUse:${m.resultActionId}`);m.callback={actionId:h.actionId,contextToken:await t.grants.issue({moduleId:i.moduleId,actionId:h.actionId,cardType:n.cardType,sessionId:s.sessionId,scope:s.scopeFlat,singleUse:!0,ttlMs:ro,input:{...m.type==="payment"?{paymentRef:m.paymentRef}:{},...r.surfaceId?{surfaceId:r.surfaceId}:{}}})}}}d=t.effects.project(a);let l=oo(r.surfaceId,i.input);if(a.update){if(a.card)throw new A("RESULT_INVALID","card 与 update 互斥");if(!l)throw new A("RESULT_INVALID","原地更新需要来源卡 surfaceId");let m=new J(t.cardRegistry).build({cardType:n.cardType,data:a.update.data,conversationId:"",id:l});if(!m||m.status==="error")throw new A("RESULT_INVALID",`更新数据未通过 ${n.cardType} dataSchema 校验`);let h=await qe({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat}),x={...h,meta:{...h.meta,updatedAt:Date.now()}};r.emit({type:ur.CUSTOM,name:eo,value:x})}else if(a.card){let g=new J(t.cardRegistry),m=g.build({cardType:a.card.cardType,data:a.card.data,conversationId:""});if(m){let h=await qe({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat});g.send(h,r.emit)}}}catch(c){throw n.singleUse&&await t.grants.restore(r.token),c}let f=typeof a.text=="string"?a.text.trim():"";f&&r.emit({type:ur.CUSTOM,name:to,value:{level:"info",text:He(f),surfaceId:r.surfaceId||void 0}});for(let c of d)r.emit(c);return a}}}import{TBOX_EFFECT_EVENT_NAME as io}from"@tbox.cn/app-contracts";var B=class extends Error{constructor(e){super(e),this.name="EffectError"}},ao=new Set(["navigation.open","payment","share","download","authorization.alipay-user-profile","session.credentials-refreshed"]);function co(t){if(t.type==="payment"){if(!t.paymentRef||!t.orderInfo||!t.resultActionId)throw new B("payment 效果缺少 paymentRef/orderInfo/resultActionId")}else if(t.type==="authorization.alipay-user-profile"&&(!t.resultActionId||t.scopes.length===0))throw new B("authorization 效果缺少 resultActionId/scopes")}function uo(t={}){return{project(e){let r=[];for(let n of e.effects??[]){let o=n;if(!o||typeof o.type!="string"||!ao.has(o.type))throw new B(`未知宿主效果类型:${String(o?.type)}`);if(o.type==="navigation.open"){if(t.routeWhitelist&&!t.routeWhitelist.has(o.routeId))throw new B(`导航路由不在白名单:${o.routeId}`)}else co(o);r.push({type:"CUSTOM",name:io,value:o})}return r}}}var he=class extends Error{constructor(r,n){super(n);this.code=r;this.name="KnowledgeError"}code};function po(t={}){let e=t.apiKey??process.env.TBOX_API_KEY;if(!e)throw new he("MISSING_CREDENTIAL","TBOX_API_KEY 未配置");let r=new me({apiKey:e,...t.appId?{appId:t.appId}:{},...t.datasetId?{datasetId:t.datasetId}:{},...t.topK?{topK:t.topK}:{}});return{async search(n){try{let o=await r.retrieve(n.query,{...n.datasetId?{datasetId:n.datasetId}:{},...n.topK!==void 0?{topK:n.topK}:{},...n.scoreThreshold!==void 0?{scoreThreshold:n.scoreThreshold}:{}});return!o.success||!o.data?[]:o.data.map(s=>({content:s.content,score:s.score,...s.originFileName?{originFileName:s.originFileName}:{},...s.documentId?{documentId:s.documentId}:{},...s.metadata?{metadata:s.metadata}:{}}))}catch(o){throw new he("API_ERROR",`知识库检索失败:${o.message}`)}}}}var K=class extends Error{constructor(r,n){super(n);this.code=r;this.name="PaymentError"}code};function lo(t={}){return{async createCashier(e){if(!t.createCashierHandler)throw new K("NOT_CONFIGURED","支付通道未装配(宿主注入 createCashierHandler)");try{return await t.createCashierHandler(e)}catch(r){throw r instanceof K?r:new K("API_ERROR",`收银台创建失败:${r.message}`)}},async queryResult(e){if(!t.queryResultHandler)return{status:"UNKNOWN"};try{return await t.queryResultHandler(e)}catch(r){throw r instanceof K?r:new K("API_ERROR",`支付结果查询失败:${r.message}`)}}}}import{parseIntegrationsConfig as Ad,assertNoInlineSecrets as bd}from"@tbox.cn/app-contracts";import{createSign as go,createVerify as fo}from"crypto";var mo="https://openapi.alipay.com/gateway.do";function yo(t=process.env,e=fetch){function r(){let i=t.ALIPAY_APP_ID?.trim(),a=t.ALIPAY_APP_PRIVATE_KEY?.trim(),d=t.ALIPAY_PUBLIC_KEY?.trim();if(!i||!a||!d)throw new Error("AUTH_NOT_CONFIGURED: Alipay user authorization is unavailable");return Object.freeze({appId:i,privateKey:a,publicKey:d})}async function n(i,a){let{appId:d,privateKey:f}=r(),c={app_id:d,method:i,charset:"utf-8",sign_type:"RSA2",timestamp:pr(new Date),version:"1.0",...a};c.sign=ho(c,f);let u=await e(mo,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"},body:new URLSearchParams(c).toString(),signal:AbortSignal.timeout(1e4)});if(!u.ok)throw new Error(`ALIPAY_API_ERROR: HTTP ${u.status}`);let p=await u.text();try{return JSON.parse(p)}catch{throw new Error("ALIPAY_API_ERROR: response is not valid JSON")}}function o(i){let a=i.error_response;if(!a||typeof a!="object"||Array.isArray(a))return;let d=a,f=P(d.sub_msg)??P(d.msg)??"unknown error";throw new Error(`INVALID_CODE: ${f}`)}async function s(i){if(!i.trim()||i.length>256)throw new Error("INVALID_CODE: invalid Alipay auth code");let a=await n("alipay.system.oauth.token",{grant_type:"authorization_code",code:i});o(a);let d=a.alipay_system_oauth_token_response;if(!d||typeof d!="object"||Array.isArray(d))throw new Error("INVALID_CODE: no token response");return d}return Object.freeze({async authorizeUserProfile(i){let{publicKey:a}=r(),d=await s(i),f=P(d.access_token);if(!f)throw new Error("INVALID_CODE: no access_token in response");let c=await n("alipay.user.info.share",{auth_token:f});o(c);let u=c.alipay_user_info_share_response,p=P(c.sign);if(!u||typeof u!="object"||Array.isArray(u)||!p)throw new Error("ALIPAY_API_ERROR: incomplete authorized profile response");let l=fo("RSA-SHA256");if(l.update(JSON.stringify(u),"utf8"),!l.verify(St(a,"PUBLIC"),p,"base64"))throw new Error("ALIPAY_API_ERROR: profile response signature is invalid");let g=u,m=P(g.user_id)??P(g.open_id)??P(d.user_id)??P(d.open_id);if(!m)throw new Error("ALIPAY_API_ERROR: authorized user id is missing");let h=P(g.mobile),x=P(g.nick_name)??P(g.nickName),S=P(g.avatar),I=S?.startsWith("https://")?S:void 0,E=xo(g.gender),z=P(g.birthday);return Object.freeze({userId:m,...h?{mobile:h}:{},...x?{displayName:x}:{},...I?{avatarUrl:I}:{},...E?{gender:E}:{},...z?{birthday:z}:{}})}})}function pr(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}function St(t,e){let r=t.replace(/\\n/gu,`
|
|
1
|
+
import{AsyncLocalStorage as hr}from"async_hooks";import{createCoreLogger as xr,detailForLog as Te,resolveLevel as Rr,setLogContextProvider as Tr}from"@tbox.cn/app-sdk-core";var D=new hr;Tr(()=>D.getStore());function Sr(t,e){return D.run(t,e)}var Ie=()=>{};function Ir(t){Ie=t}function Ve(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Se(){return new Date}function ze(t){let e=t;return{message:e?.message||String(t??"unknown"),...e?.name?{type:e.name}:{},...e?.stack?{stack:e.stack}:{}}}function y(t){return{...xr({tag:t,getLevel:()=>Rr(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>D.getStore()}),span(r,n){let o=D.getStore();Ie({spanId:Ve(`sp_${t.replace(/[^a-zA-Z0-9]/g,"")}`),traceId:o?.requestId??"no-req",name:r,startTime:Se(),endTime:Se(),...n?.metadata!==void 0?{metadata:n.metadata}:{},...n?.error!==void 0?{errorInfo:ze(n.error)}:{},requestId:o?.requestId??"no-req",...o?.conversationId?{conversationId:o.conversationId}:{},...o?.threadKey?{sessionId:o.threadKey}:{}})}}}var re=3e3;async function Er(t,e,r,n){let o=Date.now();try{let s=await r(),i=Date.now()-o;if(n?.onDone?.(i),n?.logger&&t==="tool"){let a=n.detail?.args!==void 0?` args=${Te(n.detail.args)}`:"",d=` result=${Te(s)}`;n.logger.info(`${e} ok durMs=${i}${a}${d}`)}else n?.logger&&t==="op"&&n.logger.info(`${e} ok durMs=${i}`);return n?.emitSpan&&Ct(t,e,{durMs:i}),s}catch(s){let i=Date.now()-o;if(n?.onDone?.(i),n?.logger){let a=t==="tool"?"error":"warn",d=` err=${s?.message??String(s)}`;n.logger[a](`${e} fail durMs=${i}${d}`)}throw n?.emitSpan&&Ct(t,e,{durMs:i,error:s}),s}}function Ct(t,e,r){let n=D.getStore();Ie({spanId:Ve("sp_call"),traceId:n?.requestId??"no-req",name:`${t}:${e}`,startTime:Se(),endTime:Se(),metadata:{durMs:r.durMs,kind:t},...r.error!==void 0?{errorInfo:ze(r.error)}:{},requestId:n?.requestId??"no-req",...n?.conversationId?{conversationId:n.conversationId}:{},...n?.threadKey?{sessionId:n.threadKey}:{}})}function Ee(t,e){return t?{async request(r){t.info(`→ ${r.path} body=${Te(r.body)}`);let n=Date.now(),o=D.getStore(),s=o?new Date(n):void 0;try{let i=await e.request(r),a=Date.now()-n,d=`← ${r.path} durMs=${a} body=${Te(i)}`;return a>re?t.warn(`SLOW ${d}`):t.info(d),_t(o,s,r.path,a),i}catch(i){let a=Date.now()-n;throw t.warn(`← ${r.path} durMs=${a} err=${i?.message??String(i)}`),_t(o,s,r.path,a,i),i}}}:e}function _t(t,e,r,n,o){!t||!e||Ie({spanId:Ve("sp_ext"),traceId:t.requestId??"no-req",name:"external-call",startTime:e,endTime:new Date(e.getTime()+n),metadata:{path:r,durMs:n,...n>re?{slow:!0}:{}},...o!==void 0?{errorInfo:ze(o)}:{},requestId:t.requestId??"no-req",...t.conversationId?{conversationId:t.conversationId}:{},...t.threadKey?{sessionId:t.threadKey}:{}})}var kt=y("HandlerRegistry");function vr(t){let e=[],r=t instanceof Map?[...t.values()]:Object.values(t);for(let o of r)for(let s of o.intents??[])e.push({id:`${o.id}:${s.patterns[0]??"intent"}`,keywords:s.patterns,handlerId:o.id,action:"intent",...s.match?{match:s.match}:{}});let n=e.filter(o=>o.match===void 0||o.match==="bm25");return n.length>0&&kt.warn(`顶层意图路由非确定性档(${n.map(o=>o.id).join(", ")}):语义分类职责归 skill 路由与 LLM 工具编排——建议声明 match:"exact"/"prefix"(详见 prompt-pipeline「declaration 与 intents」)`),e}var ne=class{handlers=new Map;register(e){this.handlers.has(e.id)&&kt.warn(`overwriting existing handler: ${e.id}`),this.handlers.set(e.id,e)}resolve(e){return this.handlers.get(e)}getAll(){return Object.fromEntries(this.handlers)}has(e){return this.handlers.has(e)}get size(){return this.handlers.size}async dispatch(e,r,n,o,s){let i=this.handlers.get(e);return i?i.handle(r,n,o,s):{cards:[],text:`未知的服务:${e}`}}};var Pt=y("ToolRegistry"),oe=class{tools=new Map;disabled=new Set;disable(e){e&&(this.disabled.add(e),this.tools.delete(e))}register(e){let r=e.id;if(!r){Pt.warn("tool without id skipped:",e.description);return}this.disabled.has(r)||(this.tools.has(r)&&Pt.warn(`overwriting existing tool: ${r}`),this.tools.set(r,e))}registerAll(e){for(let r of e)this.register(r)}resolve(e){return this.tools.get(e)}getAll(){return Object.fromEntries(this.tools)}has(e){return this.tools.has(e)}get size(){return this.tools.size}};var ve=y("CardRegistry"),se=class{cards=new Map;disabled=new Set;owners=new Map;disable(e){e&&(this.disabled.add(e),this.cards.delete(e))}register(e){if(!e.cardType){ve.warn("meta without cardType skipped");return}if(this.disabled.has(e.cardType)){ve.debug(`disabled cardType skipped: ${e.cardType}`);return}this.cards.has(e.cardType)&&ve.warn(`overwriting existing cardType: ${e.cardType}`),this.cards.set(e.cardType,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e))r!==n.cardType&&ve.warn(`registerMap key "${r}" !== meta.cardType "${n.cardType}", registered as meta.cardType`),this.register(n)}resolve(e){return this.cards.get(e)}recordOwner(e,r){!e||!r||this.owners.set(e,r)}ownerOf(e){return this.owners.get(e)}getAll(){return Object.fromEntries(this.cards)}has(e){return this.cards.has(e)}get size(){return this.cards.size}};import{Router as wr}from"express";var Ot=y("ApiRouteRegistry"),ie=class{root=wr();moduleIds=[];register(e,r){let n=e.replace(/^\/+|\/+$/g,"");if(!n){Ot.warn("register with empty moduleId skipped");return}this.moduleIds.includes(n)&&Ot.warn(`overwriting existing module: ${n}`),this.root.use(`/${n}`,r),this.moduleIds.includes(n)||this.moduleIds.push(n)}mount(){return this.root}getModuleIds(){return[...this.moduleIds]}};var Ar=y("ServiceRegistry"),W=class{services=new Map;register(e,r){this.services.has(e)&&Ar.warn(`overwriting existing service: ${e}`),this.services.set(e,r)}resolve(e){return this.services.get(e)}clear(){this.services.clear()}getAll(){return Object.fromEntries(this.services)}},Xe=new W;function br(t,e){Xe.register(t,e)}function Cr(t){return Xe.resolve(t)}function _r(){Xe.clear()}import{SCOPE_ASSEMBLY_KIND as kr}from"@tbox.cn/app-contracts";var Pr=y("DomainAssemblyRegistry"),ae=class{assemblies=new Map;register(e,r){this.assemblies.has(e)&&Pr.warn(`overwriting existing domain assembly: ${e}`),this.assemblies.set(e,r)}resolve(e){return this.assemblies.get(e)}scopeAssembly(){return this.resolve(kr)}get size(){return this.assemblies.size}};var Nt=y("EventBus");function We(){let t=new Map;return{on(e,r){t.has(e)||t.set(e,new Set);let n=t.get(e);return n.add(r),()=>n.delete(r)},emit(e,r){let n=t.get(e);if(n)for(let o of n)try{o(r)}catch(s){Nt.error(`handler error for "${String(e)}":`,s)}},off(e,r){let n=t.get(e);n&&n.delete(r)},clear(){t.clear()},async publish(e,r){let n=t.get(e);if(!n||n.size===0)return;let o=[];for(let s of n)try{let i=s(r);i&&typeof i.then=="function"&&o.push(i)}catch(i){Nt.error(`handler error for "${String(e)}":`,i)}o.length>0&&await Promise.allSettled(o)},subscribe(e,r){return this.on(e,r)}}}function Mt(t){let e=0;for(let r=0;r<t.length;r++)e=e*31+t.charCodeAt(r)|0;return String(e)}var ce=class{store=new Map;ttlMs;maxEntries;constructor(e){this.ttlMs=e?.ttlMs??1440*60*1e3,this.maxEntries=e?.maxEntries??1e4}async tryAcquire(e,r){let n=Date.now(),o=this.store.get(e);return o&&o.expiresAt>n?{acquired:!1,result:o.result}:(this.store.set(e,{payloadHash:r,result:void 0,expiresAt:n+this.ttlMs}),this.evict(n),{acquired:!0})}async commit(e,r){let n=this.store.get(e);this.store.set(e,{payloadHash:n?.payloadHash??"",result:r,expiresAt:n?.expiresAt??Date.now()+this.ttlMs})}getPayloadHash(e){let r=this.store.get(e);if(!(!r||r.expiresAt<=Date.now()))return r.payloadHash}release(e){this.store.delete(e)}evict(e){for(let[r,n]of this.store)n.expiresAt<=e&&this.store.delete(r);for(;this.store.size>this.maxEntries;){let r=this.store.keys().next().value;if(r===void 0)break;this.store.delete(r)}}clear(){this.store.clear()}};function Ye(t){try{return Mt(JSON.stringify(t??{}))}catch{return Mt(String(t))}}import{AUTH_ERROR_CODES as F,authCodeToStatus as Or}from"@tbox.cn/app-contracts";var w=class t extends Error{code;status;constructor(e,r){super(r||e),this.name="AuthError",this.code=e,this.status=Or(e)}static unauthorized(e){return new t(F.UNAUTHORIZED,e)}static tokenExpired(e){return new t(F.TOKEN_EXPIRED,e)}static forbidden(e){return new t(F.FORBIDDEN,e)}static methodRequired(e){return new t(F.METHOD_REQUIRED,e)}static browserLoginDisabled(e){return new t(F.BROWSER_LOGIN_DISABLED,e)}static externalError(e){return new t(F.EXTERNAL_ERROR,e)}static missingSecret(e){return new t(F.MISSING_SECRET,e)}};var Nr=y("AUTH");async function de(t,e,r){if(!e){if(r==="optional")return{identity:Je()};throw w.unauthorized("missing Bearer token")}let n=await t.verify(e);return{identity:{userId:n.sub,source:n.source},...n.external?{credentials:n.external}:{}}}var Lt=4096;function ue(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>Lt){Nr.warn("context envelope dropped (>4KB): treated as absent (fail-soft)");return}return t}catch{return}}import{AsyncLocalStorage as Mr}from"async_hooks";import{networkInterfaces as Lr}from"os";import{createCoreLogger as Dr,resolveLevel as Ur}from"@tbox.cn/app-sdk-core";var Ut="sofa-traceid",$t="sofa-rpcid",Kt="traceid",Ht="rpcid",Dt=/^[\w.-]{1,64}$/,$r=["tbox.cn"],be=new Mr,Kr=Dr({tag:"SOFA",getLevel:()=>Ur(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>{}});function Hr(t){let e=t.split(".");if(e.length!==4)return"ffffffff";let r="";for(let n of e){let o=Number(n);if(!Number.isInteger(o)||o<0||o>255)return"ffffffff";let s=o.toString(16);r+=s.length===1?`0${s}`:s}return r}function Fr(){try{for(let t of Object.values(Lr()))for(let e of t??[])if(e.family==="IPv4"&&!e.internal)return Hr(e.address)}catch{}return"ffffffff"}var qr=Fr(),we=1e3;function jr(){return we=we>9e3?1e3:we+1,String(we)}function Qe(){return qr+Date.now()+jr()+process.pid}function Br(){be.enterWith({traceId:Qe(),parentRpcId:"0",childSeq:0})}function Ae(t){return Array.isArray(t)?t[0]:t}function Ze(t){let e=Ae(t[Ut])??Ae(t[Kt]),r;if(e!==void 0&&Dt.test(e)){let n=Ae(t[$t])??Ae(t[Ht]);r={traceId:e,parentRpcId:n!==void 0&&Dt.test(n)?n:"0",childSeq:0}}else r={traceId:Qe(),parentRpcId:"0",childSeq:0};return be.enterWith(r),r.traceId}function Gr(){return be.getStore()?.traceId}function Vr(){let t=process.env.TBOX_SOFA_TRACE_HOSTS;return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[]}function zr(t){return[...$r,...Vr()].some(r=>t===r||t.endsWith(`.${r}`))}function et(t){if(process.env.TBOX_SOFA_TRACE==="off")return{};let e,r;try{let i=new URL(t);e=i.hostname.toLowerCase(),r=i.pathname}catch{return{}}if(!zr(e))return{};let n=be.getStore(),o=n?.traceId??Qe(),s=n?`${n.parentRpcId}.${++n.childSeq}`:"0.1";return Kr.debug(`out traceId=${o} rpcId=${s} host=${e} path=${r}`),{[Ut]:o,[Kt]:o,[$t]:s,[Ht]:s}}var Ft=y("HTTP");function Xr(t){if(typeof t!="string")return;let e=t.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:void 0}function Wr(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var qt="tboxAuthContext";function jt(t,e){Object.defineProperty(t,qt,{value:e,enumerable:!0,configurable:!0})}function Y(t){return t[qt]}function Je(t=Date.now()){return{userId:`anonymous_${t}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"}}function tt(t,e={}){let r=e.mode??"required",n=(e.publicPaths??[]).map(s=>s.replace(/\/+$/,""));function o(s){let i=(s.originalUrl||s.url||"").split("?")[0].replace(/\/+$/,"");return n.some(a=>i===a||i.startsWith(`${a}/`))}return async(s,i,a)=>{let d=Xr(s.headers["x-request-id"])??Wr();i.setHeader?.("X-Request-ID",d),D.enterWith({requestId:d});let f=Ze(s.headers),c=Date.now();if(i.on?.("finish",()=>{let u=Date.now()-c,p=`${s.method} ${s.originalUrl||s.url} ${i.statusCode} durMs=${u} sofa=${f}`,l=(s.originalUrl||s.url||"").split("?")[0];/\/health(z)?$/.test(l)?Ft.debug(p):Ft.info(p)}),o(s))return a();try{let u=s.headers.authorization,p=u?.startsWith("Bearer ")?u.slice(7).trim():void 0,l=await de(t,p,r),g=s.body?.context,m=s.method==="POST"&&g!==void 0?ue(g):void 0;if(m&&e.validateContext&&!e.validateContext(m)){i.status(403).json({error:"context validation failed",code:"AUTH_FORBIDDEN"});return}return jt(s,{identity:l.identity,...l.credentials?{credentials:l.credentials}:{},...m?{attributes:m}:{}}),a()}catch(u){if(u instanceof w){i.status(u.status).json({error:u.message,code:u.code});return}i.status(401).json({error:u.message,code:"AUTH_UNAUTHORIZED"})}}}var Bt=y("ActionGateway");function rt(t){let e=new Map,r=t?.idempotencyStore??new ce;function n(c){return{sessionId:(c?.body??{})?.sessionId??"",requestContext:c?Y(c):void 0,emit:()=>{}}}async function o(c,u){for(let p of u.checks??[]){let l=await p.check(c);if(!l.ok)return l}return null}async function s(c,u,p,l){let g=c.policy,m=g.write??!1,h=g.idempotent??!1;if(m&&h){if(!l)return{status:400,body:{success:!1,error:"Missing idempotencyKey (write action)"}};let S=Ye(u),I=await r.tryAcquire(l,S);if(!I.acquired){let E=r.getPayloadHash?.(l);return E&&E!==S?{status:409,body:{success:!1,error:"Idempotency key reused with different payload"}}:I.result!==void 0?{status:200,body:{...I.result,cached:!0}}:{status:200,body:{success:!0,pending:!0,cached:!0}}}try{let E=await c.handler(u,p);return await r.commit(l,E),{status:200,body:E}}catch(E){throw r.release?.(l),E}}return{status:200,body:await c.handler(u,p)}}async function i(c,u,p){if(!c||typeof c!="string")return{status:400,body:{success:!1,error:"Missing action"}};let l=e.get(c);if(!l)return{status:404,body:{success:!1,error:`Unknown action: ${c}`}};if(l.policy.write&&Y(p)?.identity?.source==="anonymous")return{status:403,body:{success:!1,error:"anonymous write is forbidden"}};let g=await o(p,l.policy);if(g)return{status:g.code??403,body:{success:!1,error:g.message}};let m=p.body??{};return s(l,u,n(p),m.idempotencyKey)}function a(){return async(c,u,p)=>{try{let l=c.body??{},g=await i(l.action,l.payload,c);u.status(g.status).json(g.body)}catch(l){Bt.error("handler error:",l),u.status(500).json({success:!1,error:l?.message||"Internal error"})}}}function d(c={}){return async(u,p,l)=>{try{let g=await o(u,c);if(g){p.status(g.code??403).json({success:!1,error:g.message});return}l()}catch(g){l(g)}}}async function f(c,u,p){let l=e.get(c);if(!l)return{success:!1,error:`Unknown action: ${c}`};let g=p?.requestContext?.identity??p?.identity;if(l.policy.write&&g?.source==="anonymous")return{success:!1,error:"anonymous write is forbidden"};let m=await o({},l.policy);return m?{success:!1,error:m.message}:(await s(l,u,{sessionId:p?.sessionId??"",requestContext:p?.requestContext?p.requestContext:p?.identity?{identity:p.identity}:void 0,emit:()=>{}},p?.idempotencyKey)).body}return{registerAction(c,u,p={}){e.has(c)&&Bt.warn(`overwriting existing action: ${c}`),e.set(c,{handler:u,policy:p})},middleware:a,validateAction:d,dispatch:f,getActions:()=>new Map(e)}}var pe=class{store=new Map;async save(e,r){let n=this.store.get(e)??[],o=n.findIndex(s=>s.id===r.id);o>=0?n[o]=r:n.push(r),this.store.set(e,n)}async load(e){return this.store.get(e)??[]}async clear(e){this.store.delete(e)}};import{EventType as Yr}from"@ag-ui/core";import{TBOX_CARD_EVENT_NAME as Jr}from"@tbox.cn/app-contracts";var Gt=y("CARD");function Vt(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var J=class{constructor(e){this.cardRegistry=e}cardRegistry;emit(e,r){let n=this.build(e);if(n)return this.send(n,r)}build(e){let r=this.cardRegistry[e.cardType];if(!r){Gt.warn(`unknown cardType: ${e.cardType}`);return}let n=r.dataSchema.safeParse(e.data);return n.success?{id:e.id||Vt("card"),messageId:e.messageId,cardType:e.cardType,data:n.data,status:"ready",schemaVersion:r.schemaVersion??1,meta:{createdAt:Date.now()},...r.project?.(n.data)??{}}:(Gt.warn(`data schema mismatch for ${e.cardType}:`,n.error.message),{id:e.id||Vt("card"),messageId:e.messageId,cardType:e.cardType,data:{},status:"error",error:"卡片数据不符合约定",schemaVersion:r.schemaVersion??1,meta:{createdAt:Date.now()}})}send(e,r){let n={type:Yr.CUSTOM,name:Jr,value:e};return r(n),e}};var nt=class{store=new Map;ttlMs;maxEntries;constructor(e){this.ttlMs=e?.ttlMs??300*1e3,this.maxEntries=e?.maxEntries??1e4}async checkAndSet(e,r){let n=Date.now(),o=this.store.get(e);return o&&o.expiresAt>n?!0:(this.store.set(e,{expiresAt:n+(r??this.ttlMs)}),this.evict(n),!1)}evict(e){for(let[r,n]of this.store)n.expiresAt<=e&&this.store.delete(r);for(;this.store.size>this.maxEntries;){let r=this.store.keys().next().value;if(r===void 0)break;this.store.delete(r)}}clear(){this.store.clear()}};import{SKILL_NAME_PATTERN as ot}from"@tbox.cn/app-contracts";var Qr={description:1024,instructions:32*1024,references:64,referenceSize:32*1024};var Ce=y("SkillRegistry"),le=class{skills=new Map;register(e){if(!ot.test(e.name)){Ce.warn(`非法 skill 名 "${e.name}" 跳过(须匹配 ^[a-z0-9-]{1,64}$)`);return}for(let r of Object.keys(e.references))r.endsWith(".md")||Ce.warn(`skill "${e.name}" reference key "${r}" 非 .md 结尾`);this.skills.has(e.name)&&Ce.warn(`覆盖已注册 skill: ${e.name}`),this.skills.set(e.name,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e))r!==n.name&&Ce.warn(`registerMap key "${r}" !== skill.name "${n.name}", registered as skill.name`),this.register(n)}getAll(){return[...this.skills.values()]}has(e){return this.skills.has(e)}get size(){return this.skills.size}};import{PRE_TOOL_NAME_PATTERN as Zr}from"@tbox.cn/app-contracts";var _e=y("PreToolRegistry"),ge=class{preTools=new Map;register(e){let r=e?.tool?.id;if(!r||!Zr.test(r)){_e.warn(`非法 toolId "${r}" 跳过(须匹配 ^[A-Za-z0-9_-]{1,64}$)`);return}if(e.routing.mode==="keywords"&&e.routing.terms.length===0){_e.warn(`keywords 路由空 terms 跳过: ${r}(恒不命中;如须每轮候选请用 always 模式)`);return}this.preTools.has(r)&&_e.warn(`覆盖已注册 pre-tool: ${r}`),this.preTools.set(r,e)}registerAll(e){for(let r of e)this.register(r)}registerMap(e){for(let[r,n]of Object.entries(e)){let o=n?.tool?.id;r!==o&&_e.warn(`registerMap key "${r}" !== tool.id "${o}", registered as tool.id`),this.register(n)}}getAll(){return[...this.preTools.values()]}has(e){return this.preTools.has(e)}get size(){return this.preTools.size}};import{createHash as en,randomUUID as Ks}from"crypto";var q=(t,e)=>`${t}\0${e}`;function st(t){if(t!==null&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))st(e)}return t}function it(t=()=>new Date){let e=new Map,r=(n,o)=>n.expiresAt===void 0||n.expiresAt>o;return{async get(n,o){let s=e.get(q(n,o));return s?r(s,t().getTime())?s.value:(e.delete(q(n,o)),null):null},async getEntry(n,o){let s=e.get(q(n,o));return s?r(s,t().getTime())?{value:s.value,revision:s.revision,expiresAt:s.expiresAt}:(e.delete(q(n,o)),null):null},async put(n,o,s,i){let a=q(n,o),d=(e.get(a)?.revision??0)+1;return e.set(a,{value:st(structuredClone(s)),revision:d,expiresAt:i>0?t().getTime()+i:void 0}),!0},async compareAndSet(n,o,s,i,a){let d=q(n,o),f=t().getTime(),c=e.get(d),u=c&&r(c,f)?c.revision:0;return u!==s?!1:(e.set(d,{value:st(structuredClone(i)),revision:u+1,expiresAt:a>0?f+a:void 0}),!0)},async consume(n,o){let s=q(n,o),i=e.get(s);return i?r(i,t().getTime())?(e.delete(s),i.value):(e.delete(s),null):null}}}function tn(t){return en("sha256").update(t).digest("hex").slice(0,32)}var rn=y("PROVIDER"),zt="static-headers-v1",Xt={credentialType:zt,apply(t){let e={};for(let[r,n]of Object.entries(t.credential.value))typeof n=="string"&&(e[r]=n);return e}};function at(t=[Xt]){let e=new Map;for(let r of t)e.set(r.credentialType,r);return{get:r=>e.get(r),register:r=>{e.get(r.credentialType)!==r&&(e.has(r.credentialType)&&rn.warn(`认证策略重复注册(后者覆盖):${r.credentialType}`),e.set(r.credentialType,r))},list:()=>[...e.values()]}}var ke=y("auth-exchanges");function j(t){let e=new Map;for(let[n,o]of Object.entries(t??{}))e.set(n,o);let r=[];return{register(n){if(n.matches){r.includes(n)||r.push(n);return}let o=r.findIndex(s=>!s.matches&&s.provider===n.provider);if(o>=0){r[o]=n;return}r.push(n)},get(n,o){let s=r.filter(d=>d.provider===n);for(let d of s){if(!d.matches)continue;let f=!1;try{f=d.matches(o)!==!1}catch(c){ke.warn(`matches threw for ${n}(谓词违约视为不命中):`,c.message)}if(f)return ke.debug("resolve",n,"source=scoped"),d}let i=s.find(d=>!d.matches);if(i)return ke.debug("resolve",n,"source=fallback"),i;let a=e.get(n);return ke.debug("resolve",n,a?"source=builtin":"source=none",`explicit=${s.length}`),a},list(){return[...r,...e.values()]}}}function nn(t){let e=new W,r=t?.snapshotStore??new pe,n=new Map,o=rt({idempotencyStore:t?.idempotencyStore}),s=new ae,i=t?.scopeDefaults,a=new Proxy({},{get:(x,S)=>{if(typeof S!="string")return;let I=s.scopeAssembly()?.scopeDefaults?.[S];return I!==void 0?I:i?.[S]},has:(x,S)=>typeof S!="string"?!1:s.scopeAssembly()?.scopeDefaults?.[S]!==void 0||i?.[S]!==void 0}),d=t?.state??it(),f=t?.authStrategies??at(),c=t?.authExchanges??j(),u=new Map,p={register:x=>{if((!x.kind||x.kind==="moduleAction")&&!x.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${x.moduleId}:${x.actionId}`);u.set(x.actionId,x)},get:x=>u.get(x),getAll:()=>new Map(u)},l=x=>e.resolve(x),g=(x,S)=>n.get(x)?.[S],m=(x,S,I)=>{let E=n.get(x)??{};E[S]=I,n.set(x,E)},h=x=>{n.delete(x)};return{handlers:new ne,tools:new oe,cards:new se,skills:new le,preTools:new ge,routes:new ie,services:e,bus:We(),snapshotStore:r,actions:o,resolveService:l,flowStates:{get:g,set:m,clear:h},state:d,...t?.memory?{memory:t.memory}:{},cardActions:p,authStrategies:f,authExchanges:c,domainAssemblies:s,...t?.integrations?{integrations:t.integrations}:{},scopeDefaults:a}}import ln from"path";import{readFileSync as sn}from"fs";import{join as an}from"path";import{z as U}from"zod";import{expandEnvVars as on}from"@tbox.cn/app-toolkit";function ct(t,e=process.env,r="<config>"){let n=on(t,e);if(n.missing.length>0){let o={file:r,missing:n.missing};throw new Error(`配置文件 ${o.file} 引用的环境变量缺失:${o.missing.join("、")}(先 source .real-env/env.sh <vendor>[-<variant>] 或由部署链注入后重试;缺变量集中报错而非静默空值,防带错配置启动)`)}return n.text}var dt=y("app-config"),Wt=U.object({topK:U.number().int().positive().optional(),scoreThreshold:U.number().optional()}).passthrough(),cn=U.object({datasetId:U.string().min(1),retrieve_config:Wt.optional()}).passthrough(),dn=U.object({defaults:Wt.optional(),knowledge_bases:U.record(U.string(),cn).optional()}).passthrough(),fe={bases:{},defaults:{}};function ut(t){let e=an(t,"knowledge.json"),r;try{r=JSON.parse(ct(sn(e,"utf8"),process.env,e))}catch(s){return s.code==="ENOENT"?(dt.warn(`knowledge.json 不存在(文件:${e})——ref 引用将降级缺失(台账锚 = integrations.json 同目录,检查壳 source 传参)`),fe):(dt.warn(`knowledge.json 解析失败(${s.message},文件:${e})——ref 引用将降级缺失`),fe)}let n=dn.safeParse(r);if(!n.success)return dt.warn(`knowledge.json 校验失败(${n.error.message},文件:${e})——ref 引用将降级缺失`),fe;let o={};for(let[s,i]of Object.entries(n.data.knowledge_bases??{}))o[s]={datasetId:i.datasetId,...i.retrieve_config?.topK!==void 0?{topK:i.retrieve_config.topK}:{},...i.retrieve_config?.scoreThreshold!==void 0?{scoreThreshold:i.retrieve_config.scoreThreshold}:{}};return{bases:o,defaults:{...n.data.defaults?.topK!==void 0?{topK:n.data.defaults.topK}:{},...n.data.defaults?.scoreThreshold!==void 0?{scoreThreshold:n.data.defaults.scoreThreshold}:{}}}}var pt=y("app-config"),un=["faq","mall-knowledge"],Yt={};function lt(t,e){if(!t)return()=>Yt;let n=Object.values(t).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))?ut(e):fe,o=new Map;for(let[s,i]of Object.entries(t)){let a={};for(let[d,f]of Object.entries(i.resources??{})){let c=pn(s,d,f,n,e);c&&(a[d]=c)}o.set(s,a)}return s=>o.get(s)??Yt}function pn(t,e,r,n,o){if(r.datasetId!==void 0)return r.ref!==void 0&&pt.warn(`模块 ${t} 资源 ${e} 同时声明 datasetId 与 ref——datasetId 优先,ref 忽略`),{type:"knowledge",datasetId:r.datasetId,...r.topK!==void 0?{topK:r.topK}:{},...r.scoreThreshold!==void 0?{scoreThreshold:r.scoreThreshold}:{}};if(r.ref!==void 0){let s=n.bases[r.ref];if(!s){pt.warn(`模块 ${t} 资源 ${e} ref="${r.ref}" 在 knowledge.json 注册表未命中(目录锚:${o})——资源缺失,走模块占位回退`);return}return{type:"knowledge",datasetId:s.datasetId,topK:r.topK??s.topK??n.defaults.topK,scoreThreshold:r.scoreThreshold??s.scoreThreshold??n.defaults.scoreThreshold}}pt.warn(`模块 ${t} 资源 ${e} 无 datasetId/ref(zod 已拦,防御分支)——资源缺失`)}var gn=y("app-config");async function fn(t,e){if(!t.services.resolve("app-config")){let r=t.integrations?.raw,n=r?.source?ln.dirname(r.source):"";Object.values(r?.config.modules??{}).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))&&!r?.source&&gn.warn("integrations.raw.source 未传——模块资源 ref 将按空目录锚解析(通常落空):请在 createIntegrationsRegistry({ source: <integrations.json 源路径> }) 传参"),t.services.register("app-config",lt(r?.config.modules,n))}for(let r of e){let n={...t,logger:y(`module:${r.declaration?.moduleId??"anonymous"}`)};if("skills"in r&&r.skills&&n.skills.registerMap(r.skills),"preTools"in r&&r.preTools&&n.preTools.registerMap(r.preTools),r.declaration?.moduleId)for(let o of Object.values(r.cards))t.cards.recordOwner(o.cardType,r.declaration.moduleId);await r.register(n)}}var M="https://o.tbox.cn",gt="1.0.0",ft="X-Tbox-SDK-Version";var Jt=null;function Qt(){if(Jt)return Jt;if(typeof fetch<"u")return fetch;throw new Error("[@tbox-dev-js/sdk] No fetcher available. In mini-program environments, call setFetcher() before using SDK clients.")}function Zt(t){let e=t.success!==!1,r=t.data??t.resultObj??t.result,n=t.errorCode??t.code??t.resultCode,o=t.errorMsg??t.msg??t.resultDesc,s=t.traceId;return e?{success:!0,data:r,traceId:s}:{success:!1,errorCode:n,errorMsg:o,traceId:s}}var b=class{_baseUrl;timeout;auth;constructor(e){this._baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,"auth"in e&&e.auth?this.auth=e.auth:this.auth={type:"apiKey",apiKey:e.apiKey??""}}get baseUrl(){return this._baseUrl}getAuthHeaders(){return this.buildAuthHeaders()}buildAuthHeaders(){return this.auth.type==="session"?{TBOXSESSIONID:this.auth.session.sessionId,"X-Tbox-Channel":this.auth.session.channel,"X-Tbox-AppId":this.auth.session.appId}:{Authorization:this.auth.apiKey}}buildHeaders(e){return{"Content-Type":"application/json;charset=UTF-8",[ft]:gt,...this.buildAuthHeaders(),...e}}buildHeadersForFormData(e){return{[ft]:gt,...this.buildAuthHeaders(),...e}}async fetchWithTimeout(e,r){let n=et(e);if(Object.keys(n).length>0){let a=new Headers(r?.headers);for(let[d,f]of Object.entries(n))a.has(d)||a.set(d,f);r={...r,headers:a}}let o=Qt();if(!this.timeout||typeof AbortController>"u")return o(e,r);let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeout);try{return await o(e,{...r,signal:s.signal})}finally{clearTimeout(i)}}async post(e,r,n){let o=this.buildUrl(e,n),s;try{s=await this.fetchWithTimeout(o,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(r)})}catch(i){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:i instanceof Error?i.message:String(i)}}return this.parseResponse(s)}async postFormData(e,r,n){let o=this.buildUrl(e,n),s;try{s=await this.fetchWithTimeout(o,{method:"POST",headers:this.buildHeadersForFormData(),body:r})}catch(i){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:i instanceof Error?i.message:String(i)}}return this.parseResponse(s)}async get(e,r){let n=this.buildUrl(e,r),o;try{o=await this.fetchWithTimeout(n,{method:"GET",headers:this.buildHeaders()})}catch(s){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:s instanceof Error?s.message:String(s)}}return this.parseResponse(o)}buildUrl(e,r){let n;if(e.startsWith("http://")||e.startsWith("https://")?n=e:n=`${this._baseUrl}${e}`,!r||Object.keys(r).length===0)return n;let o=new URLSearchParams(r).toString();return`${n}?${o}`}async parseResponse(e){let r;try{r=await e.text()}catch{try{let o=await e.arrayBuffer();r=new TextDecoder("utf-8").decode(o)}catch{return{success:!1,errorCode:`HTTP_${e.status}`,errorMsg:`HTTP error: ${e.status} ${e.statusText}`}}}if(!e.ok)try{let o=JSON.parse(r),s=o.errorCode??o.code??o.resultCode??`HTTP_${e.status}`,i=o.errorMsg??o.msg??o.resultDesc??`HTTP error: ${e.status} ${e.statusText}`;return{success:!1,errorCode:s,errorMsg:i,traceId:o.traceId}}catch{return{success:!1,errorCode:`HTTP_${e.status}`,errorMsg:`HTTP error: ${e.status} ${e.statusText}`}}let n;try{n=JSON.parse(r)}catch{return{success:!1,errorCode:"PARSE_ERROR",errorMsg:"Failed to parse response JSON"}}return Zt(n)}};var Q=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,apiKey:e.apiKey,timeout:e.timeout})}async generateSession(e){return this.http.post("/openapi/v1/app/generate_session",e)}};var Pe="/openapi/v1/conversation",Oe=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,apiKey:e.apiKey,timeout:e.timeout})}async createConversation(e){return this.http.post(`${Pe}/create`,e)}async listConversations(e){return this.http.post(`${Pe}/list`,e)}async listMessages(e){return this.http.post(`${Pe}/message/list`,e)}async saveMessage(e){return this.http.post(`${Pe}/message/save`,e)}};var mn={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","audio/webm":".webm","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","application/pdf":".pdf","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","text/plain":".txt"};function yn(t,e){if(/\.\w+$/.test(t))return t;let r=e?mn[e]:void 0;return r?`${t}${r}`:t}var Ne=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,auth:{type:"session",session:e.session},timeout:e.timeout})}async upload(e){let r=yn(e.fileName??"upload",e.file.type),n=new FormData;return n.append("file",e.file,r),n.append("fileType",e.fileType==="video"?"vedio":e.fileType),this.http.postFormData("/api/files/afts/upload",n)}};var hn="wss://mediafeature.alipay.com:443/tts_stream",mt={voiceCode:"lingyue",voiceType:"SYSTEM",sampleRate:24e3,volume:50,speechRate:0,pitchRate:0},Me=class t{appId;appkey;authUrl;sessionId;channel;upstreamUrl;timeout;constructor(e){this.appId=e.appId,this.appkey=e.appkey,this.authUrl=e.authUrl,this.sessionId=e.sessionId,this.channel=e.channel,this.upstreamUrl=e.upstreamUrl??hn,this.timeout=e.timeout}static async create(e){let n=await new Q({apiKey:e.apiKey,baseUrl:e.baseUrl,timeout:e.timeout}).generateSession({appId:e.appId,userId:e.userId});if(!n.success||!n.data?.sessionId||!n.data?.channel)throw new Error(`Failed to generate session: ${n.errorCode??"UNKNOWN"} - ${n.errorMsg??"No session data returned"}`);return new t({appId:e.appId,appkey:e.appkey,authUrl:e.authUrl,sessionId:n.data.sessionId,channel:n.data.channel??e.channel,upstreamUrl:e.upstreamUrl,baseUrl:e.baseUrl,timeout:e.timeout})}async fetchAuth(){if(!this.authUrl)return{success:!1,errorCode:"CONFIGURATION_ERROR",errorMsg:"TTS authUrl is required"};if(!this.appkey)return{success:!1,errorCode:"CONFIGURATION_ERROR",errorMsg:"TTS appkey is required"};let e={"Content-Type":"application/json;charset=UTF-8","X-Tbox-AppId":this.appId};this.channel&&(e["X-Tbox-Channel"]=this.channel),this.sessionId&&(e.TBOXSESSIONID=this.sessionId);let r;try{let d={method:"POST",headers:e,body:JSON.stringify({appkey:this.appkey})};if(this.timeout){let f=new AbortController,c=setTimeout(()=>f.abort(),this.timeout);try{r=await fetch(this.authUrl,{...d,signal:f.signal})}finally{clearTimeout(c)}}else r=await fetch(this.authUrl,d)}catch(d){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:d instanceof Error?d.message:String(d)}}let n;try{n=await r.text()}catch{return{success:!1,errorCode:`HTTP_${r.status}`,errorMsg:`Failed to read response body: ${r.status} ${r.statusText}`}}if(!r.ok)try{let d=JSON.parse(n);return{success:!1,errorCode:d.errorCode??d.code??`HTTP_${r.status}`,errorMsg:d.errorMsg??d.msg??`TTS auth failed: ${r.status} ${r.statusText}`}}catch{return{success:!1,errorCode:`HTTP_${r.status}`,errorMsg:`TTS auth failed: ${r.status} - ${n}`}}let o;try{o=JSON.parse(n)}catch{return{success:!1,errorCode:"PARSE_ERROR",errorMsg:"Failed to parse TTS auth response JSON"}}let s=o.result??o,i=s.timestamp,a=s.digest;return!i||!a?{success:!1,errorCode:"INVALID_RESPONSE",errorMsg:"TTS auth response missing timestamp or digest"}:{success:!0,data:{timestamp:i,digest:a}}}buildUpstreamUrl(e){let r=new URLSearchParams({"Alipay-Mf-Appkey":this.appkey,"Alipay-Mf-Timestamp":e.timestamp,"Alipay-Mf-Digest":e.digest});return`${this.upstreamUrl}?${r.toString()}`}static buildPayload(e){let r={...mt,...e};return{sdk_language:"javascript",sdk_version:"1.0",tts_voice:r.voiceCode,sample_rate:`RATE_${r.sampleRate}`,format:"pcm",task_id:t.generateTaskId(),tts_volume:r.volume,tts_speech_rate:r.speechRate,tts_pitch_rate:r.pitchRate,tts_enable_timelines:!1,is_upload_to_afts:!1,is_blank_space_break:!1,tts_voice_type:r.voiceType,tts_style_code:"",api:"STREAM_TTS",action:"start",ext_info:"{}"}}static buildTextPayload(e){return JSON.stringify({tts_text:`<speak>${e}</speak>`})}static buildStopPayload(){return JSON.stringify({action:"stop"})}static generateTaskId(){let e="0123456789ABCDEF",r="";for(let n=0;n<32;n++)r+=e[Math.floor(Math.random()*16)];return r}};var xn="https://api.tbox.cn",me=class{http;defaultDatasetId;defaultTopK;defaultScoreThreshold;constructor(e){this.http=new b({baseUrl:e.baseUrl??"https://o.tbox.cn",apiKey:e.apiKey,timeout:e.timeout}),this.defaultDatasetId=e.datasetId,this.defaultTopK=e.topK??5,this.defaultScoreThreshold=e.scoreThreshold}async retrieve(e,r){let n=r?.datasetId??this.defaultDatasetId;if(!n)return{success:!1,errorCode:"MISSING_DATASET_ID",errorMsg:"datasetId is required. Set it in constructor config or pass it in options."};let o={datasetId:n,query:e,topK:r?.topK??this.defaultTopK,scoreThreshold:r?.scoreThreshold??this.defaultScoreThreshold},s=await this.http.post(`${xn}/api/datasets/retrieve`,o,void 0);return s.success&&s.data?{success:!0,data:s.data}:{success:!1,errorCode:s.errorCode,errorMsg:s.errorMsg}}};var er="/openapi/v1/plugin",Le=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,apiKey:e.apiKey,timeout:e.timeout})}async run(e,r){return this.http.post(`${er}/run/${encodeURIComponent(e)}`,r)}async getPluginInfo(e){return this.http.get(`${er}/info/${encodeURIComponent(e)}`)}};var De=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,auth:{type:"session",session:e.session},timeout:e.timeout})}async recognize(e){let r={base64_audio:e.base64_audio,sample_rate:e.sample_rate??"16000",audio_format:e.audio_format??"webm",enable_inverse_text:!0};return this.http.post("/agent/v1/plugin/asrBase64",r)}};var Ue=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??M,auth:{type:"session",session:e.session},timeout:e.timeout})}async addTag(e){let r={apiName:"agtprod.agtProdMessageFacade.addTag",requestObj:{requestId:e.requestId,feedback:e.feedback}};return this.http.post("/agent/v1/plugin/proxy",r)}};import{createHmac as Tn,hkdfSync as tr,timingSafeEqual as Sn,randomUUID as In}from"crypto";import{stableSerializeScope as En}from"@tbox.cn/app-contracts";import{randomBytes as Rn}from"crypto";function $e(t=process.env,e={}){let r=e.firstKeyName?t[e.firstKeyName]?.trim():void 0,n=t.AUTH_TOKEN_SECRET?.trim(),o=t.TBOX_API_KEY?.trim();return r?{secret:r,source:"explicit"}:n?{secret:n,source:"platform"}:o&&o.length>=32?{secret:o,source:"apiKey"}:t.NODE_ENV!=="production"?{secret:Rn(32).toString("hex"),source:"dev-temp"}:null}var C=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ActionGrantError"}code},Ke=900*1e3,ye="action-grant",rr="action-grant";function nr(t){let e=Buffer.from(t);if(e.length<32){let r=Buffer.alloc(32);return e.copy(r),new Uint8Array(tr("sha256",r,Buffer.alloc(0),Buffer.from(rr),32))}return new Uint8Array(tr("sha256",e,Buffer.alloc(0),Buffer.from(rr),32))}function vn(){let t=$e(process.env,{firstKeyName:"ACTION_TOKEN_SECRET"});if(!t)throw new C("TOKEN_INVALID","密钥链缺失:ACTION_TOKEN_SECRET/AUTH_TOKEN_SECRET");return new TextEncoder().encode(t.secret)}function wn(t){let e=t.store,r=nr(t.secret??vn()),n=t.now??(()=>Date.now());function o(a){let d=[a.moduleId,a.actionId,a.cardType,a.cardId??"",a.sessionId,En(a.scope),String(a.singleUse),String(a.expiresAt)].join("\0");return Tn("sha256",r).update(d).digest("base64url")}function s(a,d){return`${d}.${Buffer.from(JSON.stringify(a),"utf8").toString("base64url")}`}async function i(a){let d=a.indexOf(".");if(d<=0)throw new C("TOKEN_INVALID","令牌格式非法");let f=a.slice(0,d),c;try{c=JSON.parse(Buffer.from(a.slice(d+1),"base64url").toString("utf8"))}catch{throw new C("TOKEN_INVALID","令牌载荷非法")}let u=o(c),p=Buffer.from(f),l=Buffer.from(u);if(p.length!==l.length||!Sn(p,l))throw new C("TOKEN_INVALID","签名校验失败");if(c.expiresAt<=n())throw new C("TOKEN_EXPIRED","令牌已过期");return{record:c,signature:f}}return{async issue(a){let d=Math.min(a.ttlMs??Ke,Ke),f=n(),c={grantId:In(),moduleId:a.moduleId,actionId:a.actionId,cardType:a.cardType,...a.cardId!==void 0?{cardId:a.cardId}:{},sessionId:a.sessionId,scope:{...a.scope},...a.input!==void 0?{input:a.input}:{},singleUse:a.singleUse??!1,expiresAt:f+d},u=s(c,o(c));return c.singleUse&&await e.put(ye,c.grantId,{consumed:!1},d),u},async authorize(a,d){let{record:f}=await i(a);if(f.actionId!==d.actionId||f.sessionId!==d.sessionId)throw new C("GRANT_MISMATCH","授权与期望不匹配");if((f.cardId??void 0)!==(d.cardId??void 0))throw new C("GRANT_MISMATCH","授权 cardId 不匹配");let c=Object.keys(d.scope).sort(),u=Object.keys(f.scope).sort();if(c.length!==u.length||!c.every((l,g)=>l===u[g]&&d.scope[l]===f.scope[l]))throw new C("GRANT_MISMATCH","授权 scope 不匹配");let p=f.grantId;if(f.singleUse){let l=await e.getEntry(ye,p);if(!l)throw new C("TOKEN_CONSUMED","令牌已消费");if(l.value.consumed)throw new C("TOKEN_CONSUMED","令牌已消费");if(!await e.compareAndSet(ye,p,l.revision,{consumed:!0},Ke))throw new C("TOKEN_CONSUMED","令牌已消费")}return Object.freeze({...f})},async restore(a){let{record:d}=await i(a);if(!d.singleUse)return;let f=await e.get(ye,d.grantId);!f||!f.consumed||await e.put(ye,d.grantId,{consumed:!1},Math.max(d.expiresAt-n(),1e3))}}}var A=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ModuleActionError"}code};var yt=200;function He(t){return t.length>yt?`${t.slice(0,yt)}…`:t}function An(t){if(t instanceof C)return{level:"error",text:{TOKEN_EXPIRED:"操作已过期,请重新查询后再试",TOKEN_CONSUMED:"该操作已执行,请刷新卡片后重试"}[t.code]??"卡片数据已过期,为保护用户安全,请您重新唤起最新卡片数据操作"};if(t instanceof A&&t.code==="INPUT_INVALID")return{level:"error",text:"输入格式不正确,请检查后重试"};let e=t?.message??"";return{level:"error",text:He(e)||"操作执行失败,请稍后重试"}}import{SignJWT as bn,jwtVerify as Cn}from"jose";var _n=7200*1e3,kn="agent",Pn=30,or=16*1024,On={local:"local_",external:void 0,guest:"guest_",anonymous:"anonymous_"},sr=720*60*60*1e3;function ht(t){let e=new TextEncoder().encode(t.secret),r=t.issuer??kn,n=t.ttlMs??_n,o=t.clockToleranceSec??Pn,s=t.embedExternalToken??!0,i=new Set(["local","external","guest","anonymous"]);async function a(u,p){if(u.source==="anonymous")throw w.forbidden("anonymous identity cannot be issued a token");if(p?.external){let S=Buffer.byteLength(p.external.token,"utf8");if(S>(t.maxExternalTokenBytes??or))throw w.externalError(`external token too large (${S} bytes > ${t.maxExternalTokenBytes??or}); 请精简外部 claims,或由外部返回 identity 而非透传 token`)}let l=p?.now??Date.now(),g=Math.floor(l/1e3),m=Math.floor((l+n)/1e3);return{token:await new bn({source:u.source,...s&&p?.external?{external:p.external}:{}}).setProtectedHeader({alg:"HS256"}).setSubject(u.userId).setIssuer(r).setIssuedAt(g).setExpirationTime(m).sign(e),expiresAt:m*1e3}}async function d(u,p){try{let{payload:l}=await Cn(u,e,{issuer:r,algorithms:["HS256"],clockTolerance:o,...p?{ignoreExpiration:!0}:{}}),g=l.sub,m=l.source;if(!g||typeof g!="string")throw w.unauthorized("token subject missing");if(!m||!i.has(m))throw w.unauthorized("token source missing");let h=On[m];if(h&&!g.startsWith(h))throw w.unauthorized("token subject/source mismatch");return{sub:g,iss:l.iss??r,iat:typeof l.iat=="number"?l.iat*1e3:0,exp:typeof l.exp=="number"?l.exp*1e3:0,source:m,...l.external?{external:l.external}:{}}}catch(l){throw l instanceof w?l:l.code==="ERR_JWT_EXPIRED"?w.tokenExpired("token expired"):w.unauthorized(`invalid token: ${l.message}`)}}async function f(u){return d(u,!1)}async function c(u){return d(u,!0)}return{issue:a,verify:f,verifyIgnoringExpiration:c}}function xt(t,e={}){let r=e.mode??"required";return{async authenticate(n){return de(t,n,r)}}}import{createLogger as cd}from"@tbox.cn/app-sdk-core";import{randomUUID as Nn}from"crypto";var Z=class extends Error{constructor(r,n){super(r);this.code=n;this.name="ScopeSessionError"}code};function Mn(t){let e=t.ttlMs??18e5,r=t.now??(()=>Date.now()),n=new Map;return{bootstrap(o){let s=o.attributes??{};if(!t.validateScope(s))throw new Z("Scope 形状校验未通过(v4:mallId 会话边界键非空——白名单判定已退役)","SCOPE_INVALID");let i=t.extractScopeKey(o),a=r(),d={sessionId:Nn(),scopeKey:i,scope:structuredClone(s),scopeFlat:t.buildScope(s),createdAt:a,expiresAt:a+e};return n.set(d.sessionId,d),d},get(o){let s=n.get(o);return s?s.expiresAt<=r()?(n.delete(o),null):s:null},assertCurrent(o,s){let i=this.get(o);if(!i)throw new Z("会话不存在或已过期","SESSION_NOT_FOUND");if(i.scopeKey!==s)throw new Z("会话 scope 不匹配(跨 mall 需新会话)","SESSION_SCOPE_MISMATCH");return i},sweep(){let o=r();for(let[s,i]of n)i.expiresAt<=o&&n.delete(s)}}}import{PROVIDER_ERROR_CODES as $}from"@tbox.cn/app-contracts";import{existsSync as Ln,readFileSync as Dn}from"fs";import Un from"path";var R=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ProviderError"}code};function $n(t){let e=new Set(t.allowedHeaderNames??[]),r=t.production??process.env.NODE_ENV==="production";return{resolve(n,o){if(!n)throw r?new R($.CREDENTIAL_REF_MISSING,"credentialRef 缺失(生产 fail-fast)"):new R($.CREDENTIAL_REF_MISSING,"credentialRef 缺失");if(!n.startsWith("secret://"))throw new R($.CREDENTIAL_REF_MISSING,`非法 credentialRef 前缀:${n.split("://")[0]}`);let s=n.slice(9),i;if(t.files){let p=Un.join(t.files,`${s.toLowerCase().replaceAll("_","-")}.json`);if(Ln(p))try{i=Dn(p,"utf8")}catch{i=void 0}}if(i??=t.source[s.replaceAll("-","_").toUpperCase()],i??=t.source[s],!i)throw new R($.CREDENTIAL_REF_MISSING,`机密环境键缺失:${s}`);let a;try{a=JSON.parse(i)}catch{throw new R($.CREDENTIAL_REF_MISSING,`机密环境键非法 JSON:${s}`)}let d=a;if(!d||typeof d!="object")throw new R($.CREDENTIAL_REF_MISSING,`机密形状非法:${s}`);let f={};for(let[p,l]of Object.entries(d.scope??{}))typeof l=="string"&&(f[p]=l);if(Object.keys(f).length>0){for(let[p,l]of Object.entries(o))if(f[p]!==l)throw new R($.CREDENTIAL_SCOPE_MISMATCH,`凭证 scope 与实例 scope 不匹配:${p}`)}let c=typeof d.type=="string"?d.type:"static-headers-v1",u=d.value&&typeof d.value=="object"?d.value:{};if(c==="static-headers-v1"){for(let p of Object.keys(u))if(!e.has(p.toLowerCase()))throw new R($.CREDENTIAL_REF_MISSING,`头名不在白名单:${p}`)}return{scope:f,type:c,value:u}}}}import{PROVIDER_ERROR_CODES as k}from"@tbox.cn/app-contracts";import{randomUUID as Kn}from"crypto";function Rt(t){let e=t.circuitBreaker?.failureThreshold??3,r=t.circuitBreaker?.openMs??3e4,n=t.maxResponseBytes??1024*1024,o=t.maxTimeoutMs??15e3,s=t.now??(()=>Date.now());return{create:(a,d)=>{let f={failures:0,openedAt:0},c=t.strategies.get(d.credentialType);if(!c)throw new R(k.TRANSPORT_FAILURE,`未知认证类型:${d.credentialType}`);let p=(a.config??{}).baseUrl??"",l=a.scope??{},g=c.placement??"header";return{async request(m){if(f.openedAt>0){if(s()-f.openedAt<r)throw new R(k.CIRCUIT_OPEN,"熔断开闸");f.openedAt=0,f.failures=e-1}let h=m.method??"POST",x;try{x=Hn(p,m.path,m.query)}catch{throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,"URL 构造失败")}Fn(x);let S;try{S=t.secretProvider.resolve(a.credentialRef??"",l)}catch(T){throw T instanceof R&&T.code===k.CREDENTIAL_REF_MISSING?T:new R(k.TRANSPORT_FAILURE,`凭证解析失败:${T.message}`)}let I;try{I=c.apply({method:h,url:x,body:m.body,credential:S,headers:m.extraHeaders})}catch{throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,"认证参数构造失败")}let E=g==="body"&&(h==="POST"||h==="PUT");if((g==="query"||g==="body"&&!E)&&Object.keys(I).length>0)try{let T=new URL(x);for(let[L,Re]of Object.entries(I))T.searchParams.set(L,Re);x=T.toString()}catch{throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,"认证 query 追加失败")}let v={"content-type":"application/json","x-trace-id":Kn(),...g==="header"?I:{},...m.extraHeaders},N=m.body;E&&Object.keys(I).length>0&&(N={...m.body&&typeof m.body=="object"&&!Array.isArray(m.body)?m.body:{},...I});let _=Math.min(m.timeoutMs??o,o),O=new AbortController,mr=setTimeout(()=>O.abort(),_),Be=h==="GET"||N===void 0?void 0:JSON.stringify(N);t.logger?.debug("[transport] 最终请求",JSON.stringify({method:h,url:x,body:Be?JSON.parse(Be):null,headers:Object.fromEntries(Object.entries(v).map(([T,L])=>T.toLowerCase()==="token"||T.toLowerCase()==="authorization"||T.toLowerCase()==="visitortoken"?[T,typeof L=="string"?`${L.slice(0,20)}...(len=${L.length})`:L]:[T,L]))}));try{let T=await fetch(x,{method:h,headers:v,body:Be,signal:O.signal}),L=T.status>=500||T.status===429;if(!T.ok&&!L)throw new R(k.TRANSPORT_FAILURE,`HTTP ${T.status}`);if(L)throw ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,`HTTP ${T.status}`);let Re=Number(T.headers.get("content-length")??0);if(Re>n)throw new R(k.RESPONSE_TOO_LARGE,`响应超限:${Re}B > ${n}B`);let Ge=T.body?.getReader(),X;if(Ge){let wt=[],At=0;for(;;){let{done:yr,value:bt}=await Ge.read();if(yr)break;if(At+=bt.byteLength,At>n)throw await Ge.cancel(),new R(k.RESPONSE_TOO_LARGE,`响应超限:>${n}B`);wt.push(new TextDecoder().decode(bt))}X=wt.join("")}else if(X=await T.text(),X.length>n)throw new R(k.RESPONSE_TOO_LARGE,`响应超限:${X.length}B > ${n}B`);f.failures=0;try{return JSON.parse(X)}catch{return X}}catch(T){throw T instanceof R?T:T instanceof DOMException&&T.name==="AbortError"?(ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,`超时 ${_}ms`)):(ee(f,e,r,s),new R(k.TRANSPORT_FAILURE,`网络错误:${T.message}`))}finally{clearTimeout(mr)}}}}}}function ee(t,e,r,n){t.failures+=1,t.failures>=e&&(t.openedAt=n())}function Hn(t,e,r){let n=t.replace(/\/+$/,""),o=e.startsWith("/")?e:`/${e}`,s=r&&Object.keys(r).length>0?`?${Object.entries(r).map(([i,a])=>`${encodeURIComponent(i)}=${encodeURIComponent(a)}`).join("&")}`:"";return`${n}${o}${s}`}function Fn(t){let e=new URL(t);if(e.protocol!=="https:"&&!((e.hostname==="127.0.0.1"||e.hostname==="localhost")&&e.protocol==="http:"))throw new R(k.TRANSPORT_FAILURE,`强制 HTTPS:${e.protocol}`)}import{buildSupplyLookup as Gn,PROVIDER_ERROR_CODES as te,resolveEffectiveService as cr,stableSerializeScope as Vn}from"@tbox.cn/app-contracts";var Fe=new Map;function qn(t,e){process.env.NODE_ENV!=="production"&&Fe.set(t,e)}function jn(){Fe.clear()}function ir(t){return Fe.has(t)}function ar(t,e){let r=Fe.get(t);if(!r)throw new Error(`无 dev fixture:${t}`);return r(e)}function Bn(t){let e={async request(n){let o=r;if(!o)throw new Error("fixture transport 未绑定实例");return ar(o.providerTemplateId,n)}},r;return{create(n,o){return ir(o.providerTemplateId)?(r=n,e):t.create(n,o)}}}function Tt(){let t=new Map,e=[],r;return{async request(n){if(e.push({path:n.path,body:n.body}),r){let s=r;throw r=void 0,s}let o=t.get(n.path);if(!o)throw new Error(`未 mock 的路径:${n.path}`);return o(n.body)},mock(n,o){t.set(n,o)},requests:()=>[...e],failNext(n){r=n}}}var dr=(t,e)=>`${t}\0${e}`,zn={identity:{userId:"",source:"anonymous"},credentials:{provider:"anonymous",token:""},attributes:{}},Xn=Object.freeze({});function Wn(t){let e=new Map,r=new Map,n=t.transportFactory??Rt({strategies:t.authStrategies,secretProvider:t.secretProvider,logger:t.logger}),o=t.instanceIdOf??(c=>Vn(c)),s=Gn(t.catalog),i=Xn,a=c=>typeof c=="string"?c:`${c.provider}(inline)`,d=(c,u,p,l)=>{if(typeof c=="string"){let g=t.catalog.providers[c]?.[u];if(!g)throw new R(te.PROVIDER_NOT_FOUND,`provider 未命中 catalog:${c}/${u}(${p}@${l})`);return{provider:c,implementation:u,entry:g,inline:void 0}}return{provider:c.provider,implementation:"inline",entry:void 0,inline:c}};function f(c){let u=o(c.scope),p=cr(t.integrations,c.service,u,s,t.ownerOf);if(p.status==="service-not-configured")throw new R(te.SERVICE_NOT_CONFIGURED,`服务槽未配置:${c.service}(integrations.services 缺键)`);if(p.status==="instance-not-found")throw new R(te.INSTANCE_NOT_FOUND,`无匹配实例:${c.service}@${u}(instances 缺键)`);if(p.status==="instance-disabled")throw new R(te.INSTANCE_DISABLED,`实例已禁用:${c.service}@${u}`);if(p.status==="binding-unresolved")throw new R(te.BINDING_UNRESOLVED,p.message);let l=p.effective,g=d(l.provider,l.implementation,c.service,u),m=g.entry?.local===!0,h;if(m)h=Tt();else{let x=`${c.service}\0${u}\0${g.provider}\0${g.implementation}`;h=r.get(x)??(()=>{let S={providerInstanceId:`${c.service}:${u}:${g.provider}:${g.implementation}`,providerTemplateId:g.implementation,scope:c.scope,config:l.config,...l.credentialRef?{credentialRef:l.credentialRef}:{},enabled:!0},I={providerTemplateId:g.implementation,credentialType:g.entry?.credentialType??g.inline?.credentialType??"-"},E=n.create(S,I);return r.set(x,E),E})()}return{transport:h,local:m,config:l.config,credentialRef:l.credentialRef,provider:g.provider,implementation:g.implementation,providerDisplay:a(l.provider),instanceId:u}}return{registerAdapter(c,u,p){let l=dr(c,u);e.has(l)&&t.logger?.warn(`adapter 重复注册(后者覆盖):${c}/${u}`),e.set(l,p)},listAdapters(){return[...e.keys()]},declareProviderInstances(c,u){if(u.length!==0){for(let p of u)if(typeof p.id!="string"||!p.id||p.id==="*"||typeof p.name!="string"||!p.name)throw new Error(`declareProviderInstances 非法实例(provider=${c}):id 禁空与 '*'(通配保留字),name 须非空 string`);i[c]!==void 0&&t.logger?.warn(`provider instances 重复声明(后者覆盖):${c}`),i=Object.freeze({...i,[c]:Object.freeze(u.map(p=>Object.freeze({...p})))})}},providerInstanceDeclarations(){return i},async resolveService(c){let u=f(c),p=e.get(dr(u.provider,u.implementation));if(!p)throw new R(te.PROVIDER_NOT_IMPLEMENTED,`provider 未实施(无 adapter 注册):${u.providerDisplay}/${u.implementation}(${c.service}@${u.instanceId});实施指引见 packages/provider-custom/INTEGRATION.md`);return p({transport:Ee(u.local?void 0:t.logger,u.transport),config:u.config??{},...u.credentialRef?{credentialRef:u.credentialRef}:{},...u.credentialRef?{credential:()=>t.secretProvider.resolve(u.credentialRef,c.scope)}:{},scope:c.scope,instanceId:u.instanceId,request:c.request,service:c.service})},async resolveLoginExchange(c){let u=f({...c,request:zn});return{transport:Ee(u.local?void 0:t.logger,u.transport),config:u.config??{},providerId:u.implementation}},hasProviderBinding(c,u,p,l){let g=o(u),m=cr(t.integrations,c,g,s,t.ownerOf);if(m.status!=="ok")return!1;let h=m.effective;return typeof h.provider=="string"&&h.provider===p&&h.implementation===l},raw:{config:t.integrations,...t.source?{source:t.source}:{}}}}import{loadProviderCatalog as Yn,buildOwnershipMap as Jn}from"@tbox.cn/app-toolkit";import{EventType as ur}from"@ag-ui/core";import{TBOX_CARD_UPDATE_EVENT_NAME as eo,TBOX_NOTICE_EVENT_NAME as to}from"@tbox.cn/app-contracts";var Qn=y("CARD");function Zn(t){return{actionId:t.actionId,...t.label!==void 0?{label:t.label}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.value!==void 0?{value:t.value}:{},...t.visible!==void 0?{visible:t.visible}:{},...t.url!==void 0?{url:t.url}:{},...t.style!==void 0?{style:t.style}:{},...t.enabled!==void 0?{enabled:t.enabled}:{},...t.disabledReason!==void 0?{disabledReason:t.disabledReason}:{}}}async function qe(t){if(t.payload.actions&&t.payload.actions.length>0)return t.payload;let e=[];for(let n of t.actions.getAll().values())n.cardType===t.payload.cardType&&!("hidden"in n&&n.hidden)&&e.push({...Zn(n),...n.singleUse?{singleUse:!0}:{}});if(e.length===0)return t.payload;let r={};for(let n of e)if(!(n.kind&&n.kind!=="moduleAction"))try{r[n.actionId]=await t.grants.issue({moduleId:t.actions.get(n.actionId)?.moduleId??"",actionId:n.actionId,cardType:t.payload.cardType,cardId:t.payload.id,sessionId:t.sessionId,scope:t.scope,singleUse:n.singleUse??!1})}catch(o){Qn.warn(`动作 token 签发失败(跳过):${n.actionId}`,o.message)}return{...t.payload,actions:e.map(({singleUse:n,...o})=>o),...Object.keys(r).length>0?{actionTokens:r}:{}}}var ro=600*1e3;function no(t){return t.type==="payment"||t.type==="authorization.alipay-user-profile"}function oo(t,e){if(typeof t=="string"&&t!=="")return t;if(!e||typeof e!="object"||Array.isArray(e))return;let r=e.surfaceId;return typeof r=="string"&&r!==""?r:void 0}function so(t){let e=new Map;return{register(r){if((!r.kind||r.kind==="moduleAction")&&!r.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${r.moduleId}:${r.actionId}`);e.set(r.actionId,r)},get(r){return e.get(r)},async dispatch(r){let n=e.get(r.actionId);if(!n)throw new A("ACTION_NOT_FOUND",`未知模块动作:${r.actionId}`);let o=t.extractScopeKey(r.ctx),s=t.sessions.assertCurrent(r.sessionId,o),i=await t.grants.authorize(r.token,{actionId:r.actionId,sessionId:s.sessionId,scope:s.scopeFlat,cardId:r.surfaceId||void 0}),a,d=[];try{if(i.cardType!==n.cardType)throw new A("GRANT_INVALID","授权 cardType 与动作声明不一致");let c=r.formData&&typeof r.formData=="object"&&!Array.isArray(r.formData)?r.formData:{},u=i.input&&typeof i.input=="object"&&!Array.isArray(i.input)?{...c,...i.input}:c,p=u;if(n.inputSchema){let g=n.inputSchema.safeParse(u);if(!g.success)throw new A("INPUT_INVALID",`入参校验失败:${g.error.message}`);p=g.data}if(!n.execute)throw new A("GRANT_INVALID",`动作无服务端执行体(纯客户端 kind 不应进 dispatch):${r.actionId}`);if(a=await n.execute(p,r.ctx),!a||typeof a!="object")throw new A("RESULT_INVALID","动作结果形状非法");for(let g of a.effects??[]){let m=g;if(m&&no(m)){let h=e.get(m.resultActionId);if(!h)throw new A("CALLBACK_INVALID",`效果回调动作未注册:${m.resultActionId}`);if(h.moduleId!==i.moduleId)throw new A("CALLBACK_INVALID",`效果回调动作组件归属不一致:${m.resultActionId}`);if(h.cardType!==n.cardType)throw new A("CALLBACK_INVALID",`效果回调动作 cardType 与当前动作不一致:${m.resultActionId}`);if(h.singleUse!==!0)throw new A("CALLBACK_INVALID",`效果回调动作必须 singleUse:${m.resultActionId}`);m.callback={actionId:h.actionId,contextToken:await t.grants.issue({moduleId:i.moduleId,actionId:h.actionId,cardType:n.cardType,sessionId:s.sessionId,scope:s.scopeFlat,singleUse:!0,ttlMs:ro,input:{...m.type==="payment"?{paymentRef:m.paymentRef}:{},...r.surfaceId?{surfaceId:r.surfaceId}:{}}})}}}d=t.effects.project(a);let l=oo(r.surfaceId,i.input);if(a.update){if(a.card)throw new A("RESULT_INVALID","card 与 update 互斥");if(!l)throw new A("RESULT_INVALID","原地更新需要来源卡 surfaceId");let m=new J(t.cardRegistry).build({cardType:n.cardType,data:a.update.data,conversationId:"",id:l});if(!m||m.status==="error")throw new A("RESULT_INVALID",`更新数据未通过 ${n.cardType} dataSchema 校验`);let h=await qe({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat}),x={...h,meta:{...h.meta,updatedAt:Date.now()}};r.emit({type:ur.CUSTOM,name:eo,value:x})}else if(a.card){let g=new J(t.cardRegistry),m=g.build({cardType:a.card.cardType,data:a.card.data,conversationId:""});if(m){let h=await qe({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat});g.send(h,r.emit)}}}catch(c){throw n.singleUse&&await t.grants.restore(r.token),c}let f=typeof a.text=="string"?a.text.trim():"";f&&r.emit({type:ur.CUSTOM,name:to,value:{level:"info",text:He(f),surfaceId:r.surfaceId||void 0}});for(let c of d)r.emit(c);return a}}}import{TBOX_EFFECT_EVENT_NAME as io}from"@tbox.cn/app-contracts";var B=class extends Error{constructor(e){super(e),this.name="EffectError"}},ao=new Set(["navigation.open","payment","share","download","authorization.alipay-user-profile","session.credentials-refreshed"]);function co(t){if(t.type==="payment"){if(!t.paymentRef||!t.orderInfo||!t.resultActionId)throw new B("payment 效果缺少 paymentRef/orderInfo/resultActionId")}else if(t.type==="authorization.alipay-user-profile"&&(!t.resultActionId||t.scopes.length===0))throw new B("authorization 效果缺少 resultActionId/scopes")}function uo(t={}){return{project(e){let r=[];for(let n of e.effects??[]){let o=n;if(!o||typeof o.type!="string"||!ao.has(o.type))throw new B(`未知宿主效果类型:${String(o?.type)}`);if(o.type==="navigation.open"){if(t.routeWhitelist&&!t.routeWhitelist.has(o.routeId))throw new B(`导航路由不在白名单:${o.routeId}`)}else co(o);r.push({type:"CUSTOM",name:io,value:o})}return r}}}var he=class extends Error{constructor(r,n){super(n);this.code=r;this.name="KnowledgeError"}code};function po(t={}){let e=t.apiKey??process.env.TBOX_API_KEY;if(!e)throw new he("MISSING_CREDENTIAL","TBOX_API_KEY 未配置");let r=new me({apiKey:e,...t.appId?{appId:t.appId}:{},...t.datasetId?{datasetId:t.datasetId}:{},...t.topK?{topK:t.topK}:{}});return{async search(n){try{let o=await r.retrieve(n.query,{...n.datasetId?{datasetId:n.datasetId}:{},...n.topK!==void 0?{topK:n.topK}:{},...n.scoreThreshold!==void 0?{scoreThreshold:n.scoreThreshold}:{}});return!o.success||!o.data?[]:o.data.map(s=>({content:s.content,score:s.score,...s.originFileName?{originFileName:s.originFileName}:{},...s.documentId?{documentId:s.documentId}:{},...s.metadata?{metadata:s.metadata}:{}}))}catch(o){throw new he("API_ERROR",`知识库检索失败:${o.message}`)}}}}var K=class extends Error{constructor(r,n){super(n);this.code=r;this.name="PaymentError"}code};function lo(t={}){return{async createCashier(e){if(!t.createCashierHandler)throw new K("NOT_CONFIGURED","支付通道未装配(宿主注入 createCashierHandler)");try{return await t.createCashierHandler(e)}catch(r){throw r instanceof K?r:new K("API_ERROR",`收银台创建失败:${r.message}`)}},async queryResult(e){if(!t.queryResultHandler)return{status:"UNKNOWN"};try{return await t.queryResultHandler(e)}catch(r){throw r instanceof K?r:new K("API_ERROR",`支付结果查询失败:${r.message}`)}}}}import{parseIntegrationsConfig as Ad,assertNoInlineSecrets as bd}from"@tbox.cn/app-contracts";import{createSign as go,createVerify as fo}from"crypto";var mo="https://openapi.alipay.com/gateway.do";function yo(t=process.env,e=fetch){function r(){let i=t.ALIPAY_APP_ID?.trim(),a=t.ALIPAY_APP_PRIVATE_KEY?.trim(),d=t.ALIPAY_PUBLIC_KEY?.trim();if(!i||!a||!d)throw new Error("AUTH_NOT_CONFIGURED: Alipay user authorization is unavailable");return Object.freeze({appId:i,privateKey:a,publicKey:d})}async function n(i,a){let{appId:d,privateKey:f}=r(),c={app_id:d,method:i,charset:"utf-8",sign_type:"RSA2",timestamp:pr(new Date),version:"1.0",...a};c.sign=ho(c,f);let u=await e(mo,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"},body:new URLSearchParams(c).toString(),signal:AbortSignal.timeout(1e4)});if(!u.ok)throw new Error(`ALIPAY_API_ERROR: HTTP ${u.status}`);let p=await u.text();try{return JSON.parse(p)}catch{throw new Error("ALIPAY_API_ERROR: response is not valid JSON")}}function o(i){let a=i.error_response;if(!a||typeof a!="object"||Array.isArray(a))return;let d=a,f=P(d.sub_msg)??P(d.msg)??"unknown error";throw new Error(`INVALID_CODE: ${f}`)}async function s(i){if(!i.trim()||i.length>256)throw new Error("INVALID_CODE: invalid Alipay auth code");let a=await n("alipay.system.oauth.token",{grant_type:"authorization_code",code:i});o(a);let d=a.alipay_system_oauth_token_response;if(!d||typeof d!="object"||Array.isArray(d))throw new Error("INVALID_CODE: no token response");return d}return Object.freeze({async authorizeUserProfile(i){let{publicKey:a}=r(),d=await s(i),f=P(d.access_token);if(!f)throw new Error("INVALID_CODE: no access_token in response");let c=await n("alipay.user.info.share",{auth_token:f});o(c);let u=c.alipay_user_info_share_response,p=P(c.sign);if(!u||typeof u!="object"||Array.isArray(u)||!p)throw new Error("ALIPAY_API_ERROR: incomplete authorized profile response");let l=fo("RSA-SHA256");if(l.update(JSON.stringify(u),"utf8"),!l.verify(St(a,"PUBLIC"),p,"base64"))throw new Error("ALIPAY_API_ERROR: profile response signature is invalid");let g=u,m=P(g.user_id)??P(g.open_id)??P(d.user_id)??P(d.open_id);if(!m)throw new Error("ALIPAY_API_ERROR: authorized user id is missing");let h=P(g.mobile),x=P(g.nick_name)??P(g.nickName),S=P(g.avatar),I=S?.startsWith("https://")?S:void 0,E=xo(g.gender),z=P(g.birthday);return Object.freeze({userId:m,...h?{mobile:h}:{},...x?{displayName:x}:{},...I?{avatarUrl:I}:{},...E?{gender:E}:{},...z?{birthday:z}:{}})}})}function pr(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}function St(t,e){let r=t.replace(/\\n/gu,`
|
|
2
2
|
`).trim();if(r.startsWith("-----BEGIN"))return r;let n=r.replace(/\s+/gu,"").match(/.{1,64}/gu)?.join(`
|
|
3
3
|
`);if(!n)throw new Error(`ALIPAY_${e}_KEY is invalid`);return`-----BEGIN ${e} KEY-----
|
|
4
4
|
${n}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-sdk-server",
|
|
3
|
-
"version": "0.24.
|
|
3
|
+
"version": "0.24.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"tbox-inspector-check": "bin/check-inspector.mjs"
|
|
@@ -34,12 +34,12 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@ag-ui/core": "0.0.47",
|
|
37
|
-
"@tbox.cn/app-contracts": "0.12.
|
|
38
|
-
"@tbox.cn/app-sdk-core": "0.20.
|
|
37
|
+
"@tbox.cn/app-contracts": "0.12.4",
|
|
38
|
+
"@tbox.cn/app-sdk-core": "0.20.3",
|
|
39
39
|
"express": "4.22.2",
|
|
40
40
|
"jose": "6.2.8",
|
|
41
41
|
"zod": "3.25.76",
|
|
42
|
-
"@tbox.cn/app-toolkit": "0.7.
|
|
42
|
+
"@tbox.cn/app-toolkit": "0.7.4"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@mastra/core": "1.59.0",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
"tsup": "8.5.1",
|
|
52
52
|
"typescript": "5.9.3",
|
|
53
53
|
"vitest": "4.1.10",
|
|
54
|
-
"@tbox.cn/app-sdk-client": "0.21.
|
|
55
|
-
"@tbox.cn/app-agent-sdk-server": "0.2.
|
|
54
|
+
"@tbox.cn/app-sdk-client": "0.21.2",
|
|
55
|
+
"@tbox.cn/app-agent-sdk-server": "0.2.2"
|
|
56
56
|
},
|
|
57
57
|
"license": "MIT",
|
|
58
58
|
"scripts": {
|