@tbox.cn/app-sdk-server 0.26.2 → 0.26.4
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/chunk-U2YZGGOR.js +1 -0
- package/dist/config.d.ts +151 -0
- package/dist/config.js +1 -0
- package/dist/platform/index.d.ts +205 -1
- package/dist/platform/index.js +15 -9
- package/dist/server/index.js +3 -3
- package/package.json +8 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod";var o=e.object({topK:e.number().int().positive().optional(),scoreThreshold:e.number().optional()}).passthrough(),t=e.object({datasetId:e.string().min(1).describe("平台知识库数据集 ID;knowledge_bases 的键是本地引用名"),retrieve_config:o.optional()}).passthrough(),r=e.object({defaults:o.optional(),knowledge_bases:e.record(e.string(),t).optional()}).passthrough();export{r as a};
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/** Pure configuration contracts: shared by runtime loaders and authoring tools. */
|
|
4
|
+
|
|
5
|
+
declare const knowledgeRegistrySchema: z.ZodObject<{
|
|
6
|
+
defaults: z.ZodOptional<z.ZodObject<{
|
|
7
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
8
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
9
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
10
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
11
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
12
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
13
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
14
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
15
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
16
|
+
knowledge_bases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
17
|
+
datasetId: z.ZodString;
|
|
18
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
19
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
20
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
21
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
22
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
24
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
25
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
26
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
27
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
28
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
29
|
+
datasetId: z.ZodString;
|
|
30
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
31
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
32
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
33
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
34
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
35
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
36
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
37
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
38
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
39
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
40
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
41
|
+
datasetId: z.ZodString;
|
|
42
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
43
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
44
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
45
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
46
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
47
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
48
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
49
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
50
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
51
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
52
|
+
}, z.ZodTypeAny, "passthrough">>>>;
|
|
53
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
54
|
+
defaults: z.ZodOptional<z.ZodObject<{
|
|
55
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
56
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
57
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
58
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
59
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
60
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
61
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
62
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
63
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
64
|
+
knowledge_bases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
65
|
+
datasetId: z.ZodString;
|
|
66
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
67
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
68
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
69
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
70
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
71
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
72
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
73
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
74
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
75
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
76
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
77
|
+
datasetId: z.ZodString;
|
|
78
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
79
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
80
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
81
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
82
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
83
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
84
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
85
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
86
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
87
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
88
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
89
|
+
datasetId: z.ZodString;
|
|
90
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
91
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
92
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
93
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
94
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
95
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
96
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
97
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
98
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
99
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
100
|
+
}, z.ZodTypeAny, "passthrough">>>>;
|
|
101
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
102
|
+
defaults: z.ZodOptional<z.ZodObject<{
|
|
103
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
104
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
105
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
106
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
107
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
108
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
109
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
110
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
111
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
112
|
+
knowledge_bases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
113
|
+
datasetId: z.ZodString;
|
|
114
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
115
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
116
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
117
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
118
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
119
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
120
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
121
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
122
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
123
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
124
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
125
|
+
datasetId: z.ZodString;
|
|
126
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
127
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
128
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
129
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
130
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
131
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
132
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
133
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
134
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
135
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
136
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
137
|
+
datasetId: z.ZodString;
|
|
138
|
+
retrieve_config: z.ZodOptional<z.ZodObject<{
|
|
139
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
140
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
141
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
142
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
143
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
144
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
145
|
+
topK: z.ZodOptional<z.ZodNumber>;
|
|
146
|
+
scoreThreshold: z.ZodOptional<z.ZodNumber>;
|
|
147
|
+
}, z.ZodTypeAny, "passthrough">>>;
|
|
148
|
+
}, z.ZodTypeAny, "passthrough">>>>;
|
|
149
|
+
}, z.ZodTypeAny, "passthrough">>;
|
|
150
|
+
|
|
151
|
+
export { knowledgeRegistrySchema };
|
package/dist/config.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-U2YZGGOR.js";export{a as knowledgeRegistrySchema};
|
package/dist/platform/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import * as express from 'express';
|
|
1
2
|
import { Express, RequestHandler } from 'express';
|
|
2
3
|
import { IncomingMessage, Server } from 'node:http';
|
|
3
4
|
import { Duplex } from 'node:stream';
|
|
@@ -9,6 +10,44 @@ declare function injectScript(html: string): string;
|
|
|
9
10
|
declare function isReady(): boolean;
|
|
10
11
|
declare function installInspector(app: Express): void;
|
|
11
12
|
|
|
13
|
+
/** 平台文档(精确 path → dist 内文档文件;如卡片预览页) */
|
|
14
|
+
interface PlatformDocument {
|
|
15
|
+
/** 精确 URL 路径(如 /_tbox/card-preview) */
|
|
16
|
+
path: string;
|
|
17
|
+
/** dist 内文档文件相对路径(如 _tbox/card-preview.html) */
|
|
18
|
+
document: string;
|
|
19
|
+
/** 生成 entry 名(= mpa 插件 ExtraDocumentSpec.inputName;dev 面服务 .tbox-gen/<inputName>.ts) */
|
|
20
|
+
inputName: string;
|
|
21
|
+
}
|
|
22
|
+
interface StrictStaticOptions {
|
|
23
|
+
/** client dist 根(文档与资产的 fs 真源) */
|
|
24
|
+
distDir: string;
|
|
25
|
+
/** 平台文档表(精确 path 服务;文件不在场 = 能力关 = 404) */
|
|
26
|
+
platformPages?: readonly PlatformDocument[];
|
|
27
|
+
/** 文档响应装饰(static 面 = SSE client 注入;生产缺省裸服务) */
|
|
28
|
+
decorateHtml?: (html: string) => string | Promise<string>;
|
|
29
|
+
/** 构建进行中(watch BUNDLE_START→END 窗口;miss 时 503 而非 404) */
|
|
30
|
+
isBuildActive?: () => boolean;
|
|
31
|
+
/** 503 等待页 body 覆盖(dev runtime 传 SSE 感知版;生产缺省 meta-refresh 版) */
|
|
32
|
+
html503?: string;
|
|
33
|
+
logger?: DevRuntimeLogger;
|
|
34
|
+
}
|
|
35
|
+
declare const STRICT_HTML_404 = "<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>404</title></head><body style=\"font-family:system-ui;padding:40px;color:#333\"><h1>404</h1><p>\u9875\u9762\u4E0D\u5B58\u5728</p></body></html>";
|
|
36
|
+
declare const STRICT_HTML_503 = "<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>503</title><meta http-equiv=\"refresh\" content=\"3\"></head><body style=\"font-family:system-ui;padding:40px;color:#333\"><h1>503</h1><p>\u6784\u5EFA\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u5237\u65B0</p></body></html>";
|
|
37
|
+
/** 严格面统一 HTML 响应(no-store + Content-Length;HEAD 无 body;dev-runtime strict 树共用) */
|
|
38
|
+
declare function sendStrictHtml(req: express.Request, res: express.Response, statusCode: number, body: string, extra?: Record<string, string>): void;
|
|
39
|
+
/** 路径最后一段是否含扩展名(资源判定;空段=无扩展名;dev-runtime strict 树共用) */
|
|
40
|
+
declare function lastSegmentHasExtension(pathname: string): boolean;
|
|
41
|
+
/** 根目录内安全绝对路径(防穿越;越界返回 null;dev-runtime publicDir 解析共用) */
|
|
42
|
+
declare function safeJoin(distDir: string, pathname: string): string | null;
|
|
43
|
+
declare function isFile(target: string): boolean;
|
|
44
|
+
declare function isDirectory(target: string): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* 严格静态处理器:assets + 平台文档 + 文档管线 + 301 + 404/503。
|
|
47
|
+
* 非 GET/HEAD → 404(对齐既有 static 面行为)。
|
|
48
|
+
*/
|
|
49
|
+
declare function createStrictStaticHandler(options: StrictStaticOptions): RequestHandler;
|
|
50
|
+
|
|
12
51
|
/** dev 凭据 env 名(box 注入;本地缺省 = classic 模式) */
|
|
13
52
|
declare const DEV_TOKEN_ENV = "TBOX_DEV_TOKEN";
|
|
14
53
|
/** query/cookie 凭据参数名(box 302 盖戳与应用侧判定共用常量) */
|
|
@@ -58,6 +97,27 @@ interface DevRuntimeOptions {
|
|
|
58
97
|
fsAllowNarrowed?: boolean;
|
|
59
98
|
/** SSE 心跳间隔 ms(默认 15000;smoke 经 TBOX_DEV_SSE_KEEPALIVE_MS 覆盖) */
|
|
60
99
|
sseKeepaliveMs?: number;
|
|
100
|
+
/**
|
|
101
|
+
* 严格文档模式(v3.2 MPA):routes.json 在场时由模板传入(G8 模式开关)。
|
|
102
|
+
* dev/classic 面 = 平台文档表 + routes 集合 + entry src 替换 + public 目录索引;
|
|
103
|
+
* static 面 = dist 文件存在性真源(平台文档表 + 统一文档管线 + 404/503)。
|
|
104
|
+
* 缺席 = legacy SPA fallback(与历史行为等价,存量消费者零变化)。
|
|
105
|
+
*/
|
|
106
|
+
pagePolicy?: {
|
|
107
|
+
/** routes.json 绝对路径(存在性由本层探测;文件损坏 = 503 fail-visible) */
|
|
108
|
+
routesModule: string;
|
|
109
|
+
/** 根 entry script src(默认 /src/main.tsx;per-template 契约) */
|
|
110
|
+
clientEntrySrc?: string;
|
|
111
|
+
/** 生成 entry 目录名(默认 .tbox-gen;与构建插件同参) */
|
|
112
|
+
genDirName?: string;
|
|
113
|
+
/** public 目录(dev 面目录索引解析;默认 <clientRoot>/public) */
|
|
114
|
+
publicDir?: string;
|
|
115
|
+
/**
|
|
116
|
+
* 平台文档表(static/生产面 = dist 文档精确服务;dev/classic 面 = `.tbox-gen/<inputName>.ts`
|
|
117
|
+
* entry 替换 shell;能力关 = 文件不在 = 404。`inputName` 须与插件 `ExtraDocumentSpec.inputName` 一致)
|
|
118
|
+
*/
|
|
119
|
+
platformPages?: readonly PlatformDocument[];
|
|
120
|
+
};
|
|
61
121
|
}
|
|
62
122
|
interface DevRuntime {
|
|
63
123
|
/** pathless 挂载:app.use(runtime.gate())——SSE 端点 + 面裁决 */
|
|
@@ -68,6 +128,8 @@ interface DevRuntime {
|
|
|
68
128
|
handleUpgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
69
129
|
/** watch 构建完成回调(模板 BUNDLE_END 时调用 → SSE 广播 → static 面刷新) */
|
|
70
130
|
notifyBuildEnd: () => void;
|
|
131
|
+
/** watch 构建开始回调(BUNDLE_START → 构建窗口标记 → static 面 miss 时 503 而非 404) */
|
|
132
|
+
notifyBuildStart: () => void;
|
|
71
133
|
}
|
|
72
134
|
/** env 三态解析:缺席/空串 → classic;形状合规 → protected+token;在场不合规 → protected 无 token(fail-closed) */
|
|
73
135
|
declare function resolveDevTokenFromEnv(env: NodeJS.ProcessEnv): DevTokenResolution;
|
|
@@ -81,4 +143,146 @@ interface PreviewErrorReporterOptions {
|
|
|
81
143
|
/** Dev-only browser exception transport over the application's existing Vite HMR socket. */
|
|
82
144
|
declare function previewErrorReporter(options?: PreviewErrorReporterOptions): Plugin;
|
|
83
145
|
|
|
84
|
-
|
|
146
|
+
/**
|
|
147
|
+
* ============================================================================
|
|
148
|
+
* 🔒 平台基础设施 — MPA 路由清单契约(route-validator)
|
|
149
|
+
* ============================================================================
|
|
150
|
+
* routes.json 是应用页面清单的唯一真源(v3.2 方案):在场 ⇔ 端到端文档模式。
|
|
151
|
+
* 本模块是纯函数校验器(零 fs / 零 vite 依赖,双端可复用):
|
|
152
|
+
* - E 规则族:结构 / id / 纯静态段 / 保留命名空间 / 数量上限 / 解码归一;
|
|
153
|
+
* - 派生工具:文档输出路径(`/orders` → `orders/index.html`)、
|
|
154
|
+
* 请求路径单次解码归一(`/%75sers` ≡ `/users`,双编码保持字面区分)。
|
|
155
|
+
*
|
|
156
|
+
* fs 侧冲突族(public 树 × 生成文档 × 平台文档)在 mpa-build-plugin 内
|
|
157
|
+
* (构建期有 fs 访问);本文件只负责数据自身的一致性。
|
|
158
|
+
* ============================================================================
|
|
159
|
+
*/
|
|
160
|
+
/** 保留首段(服务端真实挂载前缀 + Vite 默认 chunk 目录;模板可追加) */
|
|
161
|
+
declare const RESERVED_ROUTE_SEGMENTS: readonly string[];
|
|
162
|
+
/** routes.json 单条目的宽松输入形状(校验前的未知字段面) */
|
|
163
|
+
interface RouteEntryInput {
|
|
164
|
+
id?: unknown;
|
|
165
|
+
path?: unknown;
|
|
166
|
+
title?: unknown;
|
|
167
|
+
meta?: unknown;
|
|
168
|
+
page?: unknown;
|
|
169
|
+
}
|
|
170
|
+
/** 校验通过后的规范条目 */
|
|
171
|
+
interface NormalizedRouteEntry {
|
|
172
|
+
id: string;
|
|
173
|
+
path: string;
|
|
174
|
+
title?: string;
|
|
175
|
+
meta?: Record<string, string>;
|
|
176
|
+
page?: string;
|
|
177
|
+
}
|
|
178
|
+
interface ValidateRoutesOptions {
|
|
179
|
+
/** 追加的保留首段(与内置集合并) */
|
|
180
|
+
reservedSegments?: readonly string[];
|
|
181
|
+
/** 路由总数上限(默认 100) */
|
|
182
|
+
maxRoutes?: number;
|
|
183
|
+
}
|
|
184
|
+
interface RouteValidationResult {
|
|
185
|
+
ok: boolean;
|
|
186
|
+
errors: string[];
|
|
187
|
+
warnings: string[];
|
|
188
|
+
/** 仅 ok 时非空 */
|
|
189
|
+
entries: NormalizedRouteEntry[];
|
|
190
|
+
}
|
|
191
|
+
/** 请求路径单次解码(失败返回 null——调用方按未命中处理;双编码保持字面) */
|
|
192
|
+
declare function decodeRoutePathname(pathname: string): string | null;
|
|
193
|
+
/** 冲突检测键:NFC 归一 + 小写(大小写不敏感文件系统上的同键判定) */
|
|
194
|
+
declare function canonicalRouteKey(pathname: string): string;
|
|
195
|
+
/**
|
|
196
|
+
* 静态路由 → 物理文档输出路径(目录索引形态)。
|
|
197
|
+
* `/` 返回 undefined(根入口恒用应用根 index.html,不生成文档)。
|
|
198
|
+
*/
|
|
199
|
+
declare function routeDocumentOutput(pathname: string): string | undefined;
|
|
200
|
+
/**
|
|
201
|
+
* 校验 routes.json 数据(E 规则族)。
|
|
202
|
+
* 错误 = 阻断(构建/启动 fail-fast);警告 = 提示(不阻断)。
|
|
203
|
+
*/
|
|
204
|
+
declare function validateRoutes(data: unknown, options?: ValidateRoutesOptions): RouteValidationResult;
|
|
205
|
+
/** 读取 + 解析 + 校验 routes.json(供 dev-runtime / 插件共用;fs 侧由调用方) */
|
|
206
|
+
declare function parseRoutesJson(text: string): RouteValidationResult;
|
|
207
|
+
|
|
208
|
+
/** 平台文档规格(能力开时由模板传入;如卡片预览页) */
|
|
209
|
+
interface ExtraDocumentSpec {
|
|
210
|
+
/** 生成 input 名(filesystem-safe:^[a-z0-9][a-z0-9-]*$) */
|
|
211
|
+
inputName: string;
|
|
212
|
+
/** dist 内文档输出相对路径(如 _tbox/card-preview.html) */
|
|
213
|
+
document: string;
|
|
214
|
+
/** mountPage 动态 import 的页面模块 id(如 @/platform/card-preview-page) */
|
|
215
|
+
entry: string;
|
|
216
|
+
/** 文档标题(缺省沿用根骨架) */
|
|
217
|
+
title?: string;
|
|
218
|
+
}
|
|
219
|
+
interface TboxMpaPluginOptions {
|
|
220
|
+
/** routes.json 绝对路径(默认 <root>/src/business/routes.json) */
|
|
221
|
+
routesModule?: string;
|
|
222
|
+
/** public 目录(默认 <root>/public;传 false 跳过冲突族检查) */
|
|
223
|
+
publicDir?: string | false;
|
|
224
|
+
/** 生成目录名(默认 .tbox-gen;位于 clientRoot 下、src 之外——typecheck/eslint 零扫描) */
|
|
225
|
+
genDirName?: string;
|
|
226
|
+
/** 应用根 entry script src(默认 /src/main.tsx;HTML 骨架替换目标,per-template 契约) */
|
|
227
|
+
clientEntrySrc?: string;
|
|
228
|
+
/** mountPage helper 模块 id(默认 @/platform/mount-page,per-template 契约) */
|
|
229
|
+
mountHelperId?: string;
|
|
230
|
+
/** 平台文档(能力开时传入;如卡片预览) */
|
|
231
|
+
extraDocuments?: readonly ExtraDocumentSpec[];
|
|
232
|
+
}
|
|
233
|
+
declare const DEFAULT_CLIENT_ENTRY_SRC = "/src/main.tsx";
|
|
234
|
+
declare const DEFAULT_GEN_DIR_NAME = ".tbox-gen";
|
|
235
|
+
declare const DEFAULT_MOUNT_HELPER_ID = "@/platform/mount-page";
|
|
236
|
+
/** 递归列出 public 目录内全部文件(posix 相对路径;含 dotfiles) */
|
|
237
|
+
declare function listPublicFiles(publicDir: string): string[];
|
|
238
|
+
/**
|
|
239
|
+
* 冲突族校验(E11):public 树 × 生成文档 × 平台文档。
|
|
240
|
+
* 理由 = Vite 构建序 emptyDir → bundle 写出 → copyDir(publicDir)——public 同名文件
|
|
241
|
+
* 会静默覆盖生成文档;canonical key(NFC + 小写)拦截大小写不敏感 fs 上的跨面 clobber;
|
|
242
|
+
* 祖先段被 public 文件占据 = fs 无法同时存在文件与目录。
|
|
243
|
+
*/
|
|
244
|
+
declare function validateRouteConflicts(entries: readonly NormalizedRouteEntry[], publicFiles: readonly string[], extraDocuments: readonly ExtraDocumentSpec[]): string[];
|
|
245
|
+
/** 生成 entry 模块源码(dev/build 双态共用的页面装配唯一实现) */
|
|
246
|
+
declare function buildEntryModule(entry: {
|
|
247
|
+
id: string;
|
|
248
|
+
page?: string;
|
|
249
|
+
}, extraImport: string | undefined, mountHelperId: string): string;
|
|
250
|
+
interface DocumentHtmlOptions {
|
|
251
|
+
/** 根 entry script src(替换目标) */
|
|
252
|
+
clientEntrySrc: string;
|
|
253
|
+
/** 本文档 entry src(root-absolute,指向 gen 目录) */
|
|
254
|
+
entrySrc: string;
|
|
255
|
+
title?: string;
|
|
256
|
+
meta?: Record<string, string>;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* 根 entry script src 替换(dev 面经 dev-runtime 消费同一实现——I1 不变式的服务端半边)。
|
|
260
|
+
* 未匹配返回 null(调用方按契约破坏处理:build throw / dev warn 降级)。
|
|
261
|
+
*/
|
|
262
|
+
declare function replaceClientEntrySrc(html: string, clientEntrySrc: string, entrySrc: string): string | null;
|
|
263
|
+
/** 生成文档 HTML:复制根骨架 + entry src 替换 + title/meta 注入 */
|
|
264
|
+
declare function buildDocumentHtml(rootHtml: string, options: DocumentHtmlOptions): string;
|
|
265
|
+
interface GenerateFilesOptions {
|
|
266
|
+
root: string;
|
|
267
|
+
entries: readonly NormalizedRouteEntry[];
|
|
268
|
+
extraDocuments: readonly ExtraDocumentSpec[];
|
|
269
|
+
genDirName: string;
|
|
270
|
+
mountHelperId: string;
|
|
271
|
+
clientEntrySrc: string;
|
|
272
|
+
/** build = 生成 .html 文档骨架 + inputs;serve = 仅 .ts entry */
|
|
273
|
+
withHtml: boolean;
|
|
274
|
+
}
|
|
275
|
+
interface GeneratedFiles {
|
|
276
|
+
/** rollup input 键 → gen html 绝对路径(build 用;serve 为空) */
|
|
277
|
+
inputs: Record<string, string>;
|
|
278
|
+
/** gen html 文件名(root 相对 posix)→ 最终文档输出路径(generateBundle 重命名用) */
|
|
279
|
+
renames: Record<string, string>;
|
|
280
|
+
}
|
|
281
|
+
/** 清空重写 gen 目录并生成全部文件(幂等:先 rm 再全量写,结果确定) */
|
|
282
|
+
declare function generateRouteFiles(options: GenerateFilesOptions): GeneratedFiles;
|
|
283
|
+
declare function resolveStagingDir(distDir: string): string;
|
|
284
|
+
/** 原子发布:staging 就绪校验 → dist → backup → staging → dist → 清 backup;失败回滚 */
|
|
285
|
+
declare function publishStagedDist(stagingDir: string, distDir: string): void;
|
|
286
|
+
declare function tboxMpaPlugin(options?: TboxMpaPluginOptions): Plugin;
|
|
287
|
+
|
|
288
|
+
export { DEFAULT_CLIENT_ENTRY_SRC, DEFAULT_GEN_DIR_NAME, DEFAULT_MOUNT_HELPER_ID, DEV_SSE_PATH, DEV_TOKEN_ENV, DEV_TOKEN_NAME, type DevFace, type DevRuntime, type DevRuntimeLogger, type DevRuntimeOptions, type DevTokenResolution, type DocumentHtmlOptions, type ExtraDocumentSpec, type GenerateFilesOptions, type GeneratedFiles, type NormalizedRouteEntry, type PlatformDocument, type PreviewErrorReporterOptions, RESERVED_ROUTE_SEGMENTS, RUNTIME_PATH, type RouteEntryInput, type RouteValidationResult, SCRIPT_TAG, STRICT_HTML_404, STRICT_HTML_503, type StrictStaticOptions, type TboxMpaPluginOptions, type ValidateRoutesOptions, buildDocumentHtml, buildEntryModule, canonicalRouteKey, createStrictStaticHandler, createTboxDevRuntime, decodeRoutePathname, generateRouteFiles, injectScript, installInspector, isDirectory, isFile, isReady, lastSegmentHasExtension, listPublicFiles, parseRoutesJson, previewErrorReporter, publishStagedDist, replaceClientEntrySrc, resolveDevTokenFromEnv, resolveStagingDir, routeDocumentOutput, safeJoin, sendStrictHtml, tboxMpaPlugin, validateRouteConflicts, validateRoutes };
|
package/dist/platform/index.js
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
|
-
var
|
|
1
|
+
var st="https://env-00jx4e7pq1un-static.normal.cloudstatic.cn/asset/codingbox/inspector.umd.js",Y="/__vs_inspector__.js",ue=`<script src="${Y}" defer></script>`,Z="",de=!1;async function at(e=3){for(let t=0;t<e;t++)try{let n=await fetch(st);if(!n.ok)throw new Error(`HTTP ${n.status}`);Z=await n.text(),de=!0,console.log(`[inspector] runtime loaded (${Z.length} bytes)`);return}catch(n){console.warn(`[inspector] fetch failed (attempt ${t+1}/${e}):`,n.message),t<e-1&&await new Promise(s=>setTimeout(s,1e3*(t+1)))}console.error("[inspector] runtime unavailable; inspector script will be skipped")}function Pe(e){if(e.includes(Y))return e;let t=e.search(/<\/head\s*>/i);if(t!==-1)return e.slice(0,t)+ue+e.slice(t);let n=e.search(/<body[\s>]/i);return n!==-1?e.slice(0,n)+ue+e.slice(n):e}function ct(){return de}function lt(e){at(),e.get(Y,(t,n)=>{if(!Z){n.status(503).type("application/javascript").send("// inspector runtime not ready");return}n.type("application/javascript").set("Cache-Control","no-cache").send(Z)}),e.use((t,n,s)=>{if(!de)return s();let c=[],a=n.write.bind(n),f=n.end.bind(n),h=!1,p=()=>{let g=String(n.getHeader("content-type")||""),u=String(n.getHeader("content-encoding")||"");return g.includes("text/html")&&!u};n.write=((g,...u)=>(!h&&!c.length&&(h=p()),h&&g?(c.push(Buffer.isBuffer(g)?g:Buffer.from(g)),!0):a(g,...u))),n.end=((g,...u)=>{if(!h&&!c.length&&(h=p()),h){g&&c.push(Buffer.isBuffer(g)?g:Buffer.from(g));try{let o=Buffer.concat(c).toString("utf8"),v=Pe(o);return n.setHeader("Content-Length",Buffer.byteLength(v)),f(v,...u)}catch(o){return console.warn("[inspector] inject failed, fallback to original:",o.message),f(Buffer.concat(c),...u)}}return f(g,...u)}),s()})}import{createHash as Ge,randomUUID as Et,timingSafeEqual as xt}from"crypto";import{existsSync as St,readFileSync as _t,statSync as Rt}from"fs";import{readFile as X}from"fs/promises";import Dt from"express";import H from"path";var He=["api","ws","assets"],ut=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu,dt=/^[a-z][a-z0-9-]*$/,ft=/^[a-z0-9][a-z0-9-]*$/,pt=/^[a-zA-Z][a-zA-Z0-9-]*$/;function V(e){if(!e.includes("%"))return e;try{return decodeURI(e)}catch{return null}}function B(e){return e.normalize("NFC").toLowerCase()}function Q(e){if(e==="/")return;let t=e.slice(1).split("/");if(!t.some(n=>n.length===0))return`${t.join("/")}/index.html`}function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t={}){let n=[],s=[],c=new Set([...He,...t.reservedSegments??[]]),a=t.maxRoutes??100;if(!Array.isArray(e))return{ok:!1,errors:["E01: routes.json 顶层必须是数组"],warnings:s,entries:[]};e.length>a&&n.push(`E09: 路由总数 ${e.length} 超过上限 ${a}`);for(let[u,o]of e.entries())Ne(o)||n.push(`E01: 第 ${u} 项必须是对象`);if(n.length>0)return{ok:!1,errors:n,warnings:s,entries:[]};let f=[],h=new Set,p=new Map,g=0;for(let[u,o]of e.entries()){let v=`第 ${u} 项`,m=o.id;if(typeof m!="string"||m.length===0){n.push(`E02: ${v} 缺少 id`);continue}if(m.length>64||!dt.test(m)){n.push(`E03: ${v} id "${m}" 不符合 ^[a-z][a-z0-9-]*$(≤64 字符)`);continue}if(ut.test(m)){n.push(`E03: ${v} id "${m}" 是 Windows 保留名`);continue}if(h.has(m)){n.push(`E02: id "${m}" 重复`);continue}h.add(m);let i=o.path;if(typeof i!="string"||i.length===0||i[0]!=="/"){n.push(`E04: ${v}(id=${m})path 必须以 / 开头的字符串`);continue}let y=V(i);if(y===null){n.push(`E12: ${v}(id=${m})path 含非法百分号编码`);continue}if(y!=="/"){let M=y.slice(1).split("/").find(j=>!ft.test(j));if(M!==void 0){n.push(`E04: ${v}(id=${m})path 段 "${M}" 不合法——每段必须匹配 ^[a-z0-9][a-z0-9-]*$(禁点号/冒号/通配/下划线;动态路由已按方案裁决放弃)`);continue}}let d=B(y),R=p.get(d);if(R!==void 0){n.push(`E12: path "${i}"(id=${m})与 "${R}" 解码归一后冲突`);continue}if(p.set(d,i),y!=="/"){let I=y.slice(1).split("/")[0];if(c.has(B(`/${I}`).slice(1))){n.push(`E08: ${v}(id=${m})首段 "${I}" 落在保留命名空间(${[...c].join("/")})`);continue}}y==="/"&&(g+=1,o.page!==void 0&&n.push(`E05: 根路由(id=${m})禁用 page 字段——根入口恒为应用根 main 链`),(o.title!==void 0||o.meta!==void 0)&&s.push(`根路由(id=${m})的 title/meta 不生效——根文档标题维持应用 index.html 静态值(租户主题运行时覆写)`));let b;if(o.title!==void 0){if(typeof o.title!="string"||o.title.length===0){n.push(`E04: ${v}(id=${m})title 必须是非空字符串`);continue}if(o.title.length>200){n.push(`E04: ${v}(id=${m})title 超过 200 字符`);continue}b=o.title}let S;if(o.meta!==void 0){if(!Ne(o.meta)){n.push(`E04: ${v}(id=${m})meta 必须是 Record<string, string>`);continue}let I=Object.keys(o.meta);if(I.length>20){n.push(`E04: ${v}(id=${m})meta 条目超过 20`);continue}let M=I.find(U=>!pt.test(U));if(M!==void 0){n.push(`E04: ${v}(id=${m})meta 键 "${M}" 不符合 ^[a-zA-Z][a-zA-Z0-9-]*$`);continue}let j=I.find(U=>typeof o.meta[U]!="string");if(j!==void 0){n.push(`E04: ${v}(id=${m})meta["${j}"] 必须是字符串`);continue}let q=I.find(U=>o.meta[U].length>500);if(q!==void 0){n.push(`E04: ${v}(id=${m})meta["${q}"] 超过 500 字符`);continue}S=o.meta}let P;if(o.page!==void 0){if(typeof o.page!="string"||!o.page.startsWith("@/")){n.push(`E04: ${v}(id=${m})page 必须以 @/ 开头的模块路径`);continue}P=o.page}f.push({id:m,path:y,...b!==void 0?{title:b}:{},...S?{meta:S}:{},...P?{page:P}:{}})}return g===0?n.push('E05: 必须恰有一个 path 为 "/" 的根路由'):g>1&&n.push(`E05: 根路由数量 ${g} > 1`),{ok:n.length===0,errors:n,warnings:s,entries:f}}function W(e){let t;try{t=JSON.parse(e)}catch(n){return{ok:!1,errors:[`E01: routes.json JSON 解析失败:${n.message}`],warnings:[],entries:[]}}return Ce(t)}import{randomUUID as Ae}from"crypto";import{existsSync as te,mkdirSync as mt,readFileSync as Oe,readdirSync as gt,renameSync as fe,rmSync as ve,writeFileSync as ee}from"fs";import _ from"path";var Le="/src/main.tsx",je=".tbox-gen",Ue="@/platform/mount-page",ht=/^[a-z0-9][a-z0-9-]*$/;function Fe(e){let t=[],n=(s,c)=>{for(let a of gt(s,{withFileTypes:!0})){let f=c?`${c}/${a.name}`:a.name;a.isDirectory()?n(_.join(s,a.name),f):t.push(f)}};return n(e,""),t}function Be(e,t,n){let s=[],c=new Set(t.map(p=>B(`/${p}`)));t.includes("index.html")&&s.push("E11: public/index.html 会覆盖构建产物入口 HTML(copyDir 后置 clobber)");let a=new Map,f=(p,g)=>{let u=B(`/${p}`),o=a.get(u);o!==void 0?s.push(`E11: 文档输出 "${p}"(${g})与 "${o}" 归一化后冲突`):a.set(u,g),c.has(u)&&s.push(`E11: public 文件与生成文档同路径 "${p}"(${g})——构建后拷贝将覆盖产物`);let v=p.split("/");for(let m=1;m<v.length;m++){let i=v.slice(0,m).join("/");c.has(B(`/${i}`))&&s.push(`E11: public 文件 "${i}" 占据了 "${p}"(${g})所需的目录路径`)}};for(let p of e){let g=Q(p.path);g&&f(g,`路由 ${p.id}`)}for(let p of n)f(p.document,`平台文档 ${p.inputName}`);let h=new Set;for(let p of n)h.has(p.inputName)?s.push(`E11: 平台文档 inputName "${p.inputName}" 重复——.tbox-gen/ 生成文件互相覆写`):h.add(p.inputName);for(let p of e)h.has(p.id)&&s.push(`E11: 路由 id "${p.id}" 与平台文档 inputName 同名——共享 .tbox-gen/ 命名空间将静默覆写(改写 route id 或平台 inputName)`);return s}function pe(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function me(e,t,n){let s=t??e.page??`@/pages/${e.id}`;return`import { mountPage } from '${n}';
|
|
2
|
+
mountPage(() => import('${s}'));
|
|
3
|
+
`}function G(e,t,n){let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(<script\\b[^>]*\\bsrc=")${s}(")`,"g"),a=e.match(c);return!a||a.length===0?null:e.replace(c,`$1${n}$2`)}function ge(e,t){let n=G(e,t.clientEntrySrc,t.entrySrc);if(n===null)throw new Error(`[tbox-mpa] 根 index.html 中未找到 entry script(src="${t.clientEntrySrc}")——per-template 契约被破坏`);let s=n;if(t.title!==void 0){let c=pe(t.title);if(/<title>[^<]*<\/title>/i.test(s))s=s.replace(/<title>[^<]*<\/title>/i,`<title>${c}</title>`);else if(/<\/head>/i.test(s))s=s.replace(/<\/head>/i,`<title>${c}</title></head>`);else throw new Error("[tbox-mpa] 根 index.html 缺少 <title>/<head>——无法注入文档标题")}if(t.meta&&Object.keys(t.meta).length>0){if(!/<\/head>/i.test(s))throw new Error("[tbox-mpa] 根 index.html 缺少 </head>——无法注入 meta");let c=Object.entries(t.meta).map(([a,f])=>`<meta name="${pe(a)}" content="${pe(f)}">`).join("");s=s.replace(/<\/head>/i,`${c}</head>`)}return s}function he(e){let t=_.join(e.root,e.genDirName);ve(t,{recursive:!0,force:!0}),mt(t,{recursive:!0});let n={},s={},c=e.withHtml?Oe(_.join(e.root,"index.html"),"utf-8"):void 0;for(let a of e.entries){let f=Q(a.path);if(f&&(ee(_.join(t,`${a.id}.ts`),me(a,void 0,e.mountHelperId)),c!==void 0)){let h=ge(c,{clientEntrySrc:e.clientEntrySrc,entrySrc:`/${e.genDirName}/${a.id}.ts`,...a.title!==void 0?{title:a.title}:{},...a.meta?{meta:a.meta}:{}});ee(_.join(t,`${a.id}.html`),h),n[`tbox_${a.id}`]=_.join(t,`${a.id}.html`),s[`${e.genDirName}/${a.id}.html`]=f}}for(let a of e.extraDocuments){if(!ht.test(a.inputName))throw new Error(`[tbox-mpa] 平台文档 inputName "${a.inputName}" 不符合 ^[a-z0-9][a-z0-9-]*$`);if(ee(_.join(t,`${a.inputName}.ts`),me({id:a.inputName},a.entry,e.mountHelperId)),c!==void 0){let f=ge(c,{clientEntrySrc:e.clientEntrySrc,entrySrc:`/${e.genDirName}/${a.inputName}.ts`,...a.title!==void 0?{title:a.title}:{}});ee(_.join(t,`${a.inputName}.html`),f),n[`tbox_extra_${a.inputName}`]=_.join(t,`${a.inputName}.html`),s[`${e.genDirName}/${a.inputName}.html`]=a.document}}return{inputs:n,renames:s}}function Ve(e){return _.join(_.dirname(e),`.tbox-dist-staging-${Ae().slice(0,8)}`)}function ze(e,t){if(!te(_.join(e,"index.html")))throw new Error(`[tbox-mpa] staging 产物不完整(缺 index.html):${e}——拒绝发布`);let n=_.join(_.dirname(t),`.tbox-dist-backup-${Ae().slice(0,8)}`),s=te(t);s&&fe(t,n);try{fe(e,t)}catch(c){throw s&&fe(n,t),c}s&&ve(n,{recursive:!0,force:!0})}function Me(e,t,n,s){if(!te(e))return null;let c=W(Oe(e,"utf-8"));if(!c.ok)throw new Error(`[tbox-mpa] routes.json 校验失败(${_.relative(s,e)}):
|
|
4
|
+
- ${c.errors.join(`
|
|
5
|
+
- `)}`);let a=t!==!1&&te(t)?Fe(t):[],f=Be(c.entries,a,n);if(f.length>0)throw new Error(`[tbox-mpa] 路由 × public 冲突族校验失败:
|
|
6
|
+
- ${f.join(`
|
|
7
|
+
- `)}`);return{entries:c.entries,warnings:c.warnings}}function vt(e={}){let t=e.genDirName??je,n=e.clientEntrySrc??Le,s=e.mountHelperId??Ue,c=e.extraDocuments??[],a={root:"",renames:{},inputPaths:[],transaction:!1,wrote:!1};return{name:"tbox-mpa-pages",config(f,h){if(h.command!=="build"||process.env.VITEST)return;let p=_.resolve(f.root??process.cwd());a.root=p;let g=e.routesModule??_.join(p,"src/business/routes.json"),u=e.publicDir===!1?!1:e.publicDir??_.join(p,"public"),o=Me(g,u,c,p);if(!o)return;for(let b of o.warnings)console.warn(`[tbox-mpa] ${b}`);let v=he({root:p,entries:o.entries,extraDocuments:c,genDirName:t,mountHelperId:s,clientEntrySrc:n,withHtml:!0});a.renames=v.renames,a.inputPaths=Object.values(v.inputs);let m=f.build?.watch,i=typeof m=="object"&&m!==null,y=f.build?.outDir??"dist",d=_.resolve(p,y),R={build:{rollupOptions:{input:v.inputs}}};if(!i&&Object.keys(v.inputs).length+1>1){let b=Ve(d),S=_.relative(p,b);S.startsWith("..")||_.isAbsolute(S)?console.warn(`[tbox-mpa] outDir ${y} 位于 root 外——跳过输出事务(直写 dist)`):(a.stagingDir=b,a.distDir=d,a.transaction=!0,R.build.outDir=S)}return R},configResolved(f){if(f.command!=="build"||process.env.VITEST||a.inputPaths.length===0)return;if(f.base!=="/")throw new Error(`[tbox-mpa] MPA 文档模式要求 vite base === '/'(当前 "${f.base}")——生成文档的资产引用会随路径深度断链`);let h=f.build.rollupOptions.input,p=h===void 0?[]:typeof h=="string"||Array.isArray(h)?Array.isArray(h)?h:[h]:Object.values(h),g=new Set(p.map(u=>_.resolve(f.root,u)));for(let u of a.inputPaths)if(!g.has(u))throw new Error(`[tbox-mpa] 生成输入 ${u} 未出现在最终 rollupOptions.input——被其他配置移除(框架产物不可覆盖)`)},configureServer(f){if(process.env.VITEST)return;let h=f.config.root,p=e.routesModule??_.join(h,"src/business/routes.json"),g=e.publicDir===!1?!1:e.publicDir??_.join(h,"public"),u=Me(p,g,c,h);if(u){for(let o of u.warnings)console.warn(`[tbox-mpa] ${o}`);he({root:h,entries:u.entries,extraDocuments:c,genDirName:t,mountHelperId:s,clientEntrySrc:n,withHtml:!1})}},generateBundle:{order:"post",handler(f,h){for(let[p,g]of Object.entries(h)){if(g.type!=="asset")continue;let u=a.renames[p];u!==void 0&&(g.fileName=u)}}},writeBundle(){a.wrote=!0},closeBundle(){a.transaction&&(a.transaction=!1,a.stagingDir&&a.distDir&&(a.wrote?ze(a.stagingDir,a.distDir):ve(a.stagingDir,{recursive:!0,force:!0})))}}}import{statSync as We}from"fs";import{readFile as yt}from"fs/promises";import J from"path";import bt from"express";function ye(e){let t=new Map;for(let n of e){let s=V(n.path);s&&t.set(s,n)}return t}var C='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404</title></head><body style="font-family:system-ui;padding:40px;color:#333"><h1>404</h1><p>页面不存在</p></body></html>',be='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>503</title><meta http-equiv="refresh" content="3">',L=`${be}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,请稍后刷新</p></body></html>`;function T(e,t,n,s,c){if(t.statusCode=n,t.setHeader("Content-Type","text/html; charset=utf-8"),t.setHeader("Cache-Control","no-store"),t.setHeader("Content-Length",Buffer.byteLength(s)),c)for(let[a,f]of Object.entries(c))t.setHeader(a,f);e.method!=="HEAD"&&t.write(s),t.end()}function wt(e){let t;try{t=new URL(e,"http://tbox.local")}catch{return null}let n=V(t.pathname);return n===null?null:{decoded:n,rawPathname:t.pathname,search:t.search}}function ne(e){let t=e.split("/"),n=t[t.length-1]??"";return n.length>0&&n.includes(".")}function O(e,t){let n=J.resolve(e,`.${t}`);return n!==e&&!n.startsWith(e+J.sep)?null:n}function N(e){try{return We(e).isFile()}catch{return!1}}function re(e){try{return We(e).isDirectory()}catch{return!1}}function we(e){let{distDir:t,decorateHtml:n,logger:s}=e,c=e.html503??L,a=e.platformPages??[],f=e.isBuildActive??(()=>!1),h=bt.static(t,{index:!1,redirect:!1,fallthrough:!0}),p=ye(a);async function g(u,o,v){let m;try{m=await yt(v,"utf-8")}catch{T(u,o,f()?503:404,f()?c:C);return}let i=n?await n(m):m;o.statusCode=200,o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.setHeader("Content-Length",Buffer.byteLength(i)),u.method!=="HEAD"&&o.write(i),o.end()}return(u,o,v)=>{(async()=>{if(u.method!=="GET"&&u.method!=="HEAD"){o.statusCode=404,o.setHeader("Cache-Control","no-store"),o.setHeader("Content-Type","text/plain; charset=utf-8"),o.end("Not Found");return}if(!N(J.join(t,"index.html"))){s?.debug("strict_static_unready",{pathname:u.path}),T(u,o,503,c);return}let m=wt(u.url??"/");if(!m){T(u,o,404,C);return}let{decoded:i,search:y}=m,d=p.get(i);if(d){let b=O(t,`/${d.document}`);b&&N(b)?await g(u,o,b):(s?.debug("strict_static_platform_off",{pathname:i}),T(u,o,404,C));return}if(i.endsWith(".html")||i.endsWith(".htm")){let b=O(t,i);if(b&&N(b)){await g(u,o,b);return}T(u,o,f()?503:404,f()?c:C);return}if(await new Promise(b=>{h(u,o,()=>b())}),o.writableEnded)return;if(i.endsWith("/")){let b=O(t,i),S=b===null?null:J.join(b,"index.html");if(S&&N(S)){await g(u,o,S);return}}else{let b=O(t,i);if(b&&re(b)&&N(J.join(b,"index.html"))){let S=`${m.rawPathname}/${y}`,P=S.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),I=`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${P}">${P}</a></body></html>`;T(u,o,301,I,{Location:S});return}}let R=f()?503:404;if(ne(i)){s?.debug("strict_static_miss_asset",{pathname:i,buildActive:f()}),o.statusCode=R,o.setHeader("Content-Type","text/plain; charset=utf-8"),o.setHeader("Cache-Control","no-store"),u.method!=="HEAD"&&o.write(f()?"Service Unavailable":"Not Found"),o.end();return}s?.debug("strict_static_miss",{pathname:i,buildActive:f()}),T(u,o,R,f()?c:C)})().catch(v)}}var Ke="TBOX_DEV_TOKEN",K="tbox_dev_token",oe="/__tbox_dev_hot_reload",Ee=/^[A-Za-z0-9_-]{20,128}$/,qe="tbox_hmr_protocol",$t={debug(){},info(){},warn(){}};function It(e){let t=e[Ke];return t===void 0||t===""?{mode:"classic"}:Ee.test(t)?{mode:"protected",token:t}:{mode:"protected",token:void 0}}function xe(e,t){if(!e||!t||!Ee.test(e)||!Ee.test(t))return!1;let n=Ge("sha256").update(e).digest(),s=Ge("sha256").update(t).digest();return xt(n,s)}function Ze(e){try{return new URL(e,"http://tbox.local").searchParams.get(K)??void 0}catch{return}}function Tt(e){if(e)for(let t of e.split(";")){let n=t.trim();if(n.startsWith(`${K}=`))return n.slice(K.length+1)}}function kt(e,t){if(t===void 0)return{face:"static",credSource:"none",reason:"no-cred"};let n=Ze(e.url??"/"),s=Tt(e.headers.cookie),c="none";if(n!==void 0&&xe(n,t)?c="query":s!==void 0&&xe(s,t)?c="cookie":(n!==void 0||s!==void 0)&&(c="invalid"),c!=="query"&&c!=="cookie")return{face:"static",credSource:c,reason:"no-cred"};let a=e.headers["sec-fetch-site"],f=e.headers["sec-fetch-mode"];return f==="navigate"?{face:"dev",credSource:c,reason:"navigate"}:a==="same-origin"||a==="none"?{face:"dev",credSource:c,reason:"same-origin"}:a===void 0&&f===void 0?{face:"dev",credSource:c,reason:"no-sec-fetch-header"}:{face:"static",credSource:c,reason:"cross-site-subresource"}}function z(e,t){let n=/<head[^>]*>/i.exec(e);if(!n)return e;let s=n.index+n[0].length;return e.slice(0,s)+t+e.slice(s)}function Pt(e,t){return t.some(n=>e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))}function Je(e,t,n){return`<script>window.__TBOX_DEV_TOKEN__='${e}';(function(){var OW=window.WebSocket;function PW(url,protocols){if((typeof url==='string'||url instanceof URL)&&new URL(url,'http://tbox.local').pathname===${JSON.stringify(t)}){var u=new URL(url,window.location?.href||'http://tbox.local');u.searchParams.set('${K}',window.__TBOX_DEV_TOKEN__);`+(n?`var p=Array.isArray(protocols)&&protocols.length===1?protocols[0]:protocols;if(p==='vite-hmr'||p==='vite-ping'){u.searchParams.set('${qe}',p);protocols=undefined;}`:"")+"url=u.href;}return protocols===undefined?new OW(url):new OW(url,protocols);}PW.prototype=OW.prototype;Object.setPrototypeOf(PW,OW);window.WebSocket=PW;})();</script>"}var Ye="__tbox_build__",Xe=`<script>(function(){var es=new EventSource('${oe}');var last=null;var meta=null;try{var m=document.getElementById('${Ye}');if(m){meta=JSON.parse(m.textContent);}}catch(e){}var G='__tbox_sse_reload__';function gr(){try{var t=Number(sessionStorage.getItem(G)||0);if(t&&Date.now()-t<10000){return;}sessionStorage.setItem(G,String(Date.now()));}catch(e){}location.reload();}es.onmessage=function(e){try{var d=JSON.parse(e.data);if(last===null){last=d;if(meta){if(d.serverSessionId&&meta.serverSessionId&&d.serverSessionId!==meta.serverSessionId){gr();return;}if(typeof d.buildId==='number'&&typeof meta.buildId==='number'&&d.buildId>meta.buildId){gr();return;}}try{sessionStorage.removeItem(G);sessionStorage.removeItem('__tbox_wait_count__');}catch(e2){}return;}if(d.buildId!==last.buildId){location.reload();}last=d;}catch(err){}};})();</script>`;function Nt(){return`<script>(function(){var es=new EventSource('${oe}');var last=null;es.onmessage=function(e){try{var d=JSON.parse(e.data).buildId;if(last===null){last=d;return;}if(d!==last){location.reload();}last=d;}catch(err){}};var C='__tbox_wait_count__';try{var n=Number(sessionStorage.getItem(C)||0)+1;if(n>20){var m=document.querySelector('meta[http-equiv=refresh]');if(m){m.remove();}var b=document.querySelector('body');if(b){b.innerHTML='<h1>503</h1><p>构建时间较长,请稍后手动刷新页面。</p>';}return;}sessionStorage.setItem(C,String(n));}catch(e){}})();</script>`}function Ht(e){let t=e.logger??$t,n=Symbol("tboxDevFace"),s=e.tokenState.mode==="classic",c=e.tokenState.mode==="protected"?e.tokenState.token:void 0,a=!s&&c!==void 0&&e.vite.ws!==void 0,f=new WeakSet;e.vite.ws?.on("headers",(r,l)=>{if(f.has(l))for(let E=r.length-1;E>=0;E--)/^sec-websocket-protocol\s*:/i.test(r[E])&&r.splice(E,1)});let h=0,p=!1,g=Et(),u=new Set,o=e.sseKeepaliveMs??15e3,v=Dt.static(e.clientDist,{index:!1,fallthrough:!0}),m=new Set,i=e.pagePolicy,y=i!==void 0&&St(i.routesModule),d=i?.clientEntrySrc??"/src/main.tsx",R=i?.genDirName??".tbox-gen",b=i?.publicDir??H.join(e.clientRoot,"public"),S=ye(i?.platformPages??[]),P=(()=>{if(!y)return null;let r=null;return{load:()=>{try{let E=Rt(i.routesModule);if(r&&r.mtimeMs===E.mtimeMs)return r.byPath;let x=W(_t(i.routesModule,"utf-8"));if(!x.ok)return t.warn("strict_routes_invalid",{errors:x.errors.slice(0,3)}),null;let w=new Map;for(let D of x.entries)w.set(D.path,D.id);return r={mtimeMs:E.mtimeMs,byPath:w},w}catch{return null}}}})(),I=y?we({distDir:e.clientDist,...i?.platformPages?{platformPages:i.platformPages}:{},decorateHtml:r=>z(z(r,Xe),j()),isBuildActive:()=>p,html503:`${be}${Nt()}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,页面将在就绪后自动刷新</p></body></html>`,logger:t}):null;if(y){let r=P?.load()??null;t.info("dev_guard_mode",{strictPages:!0,routesCount:r?r.size:0})}t.info("dev_guard_mode",{hmrNoSubprotocol:a,mode:e.tokenState.mode,tokenShapeOk:e.tokenState.mode==="protected"&&c!==void 0,fsAllowNarrowed:e.fsAllowNarrowed===!0});function M(){return JSON.stringify({buildId:h,serverSessionId:g})}function j(){return`<script type="application/json" id="${Ye}">${JSON.stringify({serverSessionId:g,buildId:h})}</script>`}function q(r){r.setHeader("Content-Type","text/event-stream; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.setHeader("X-Accel-Buffering","no"),r.flushHeaders(),r.write(`data: ${M()}
|
|
2
8
|
|
|
3
|
-
`),
|
|
9
|
+
`),u.add(r);let l=setInterval(()=>{r.destroyed||r.write(`: keepalive
|
|
4
10
|
|
|
5
|
-
`)},
|
|
11
|
+
`)},o);r.on("close",()=>{clearInterval(l),u.delete(r),t.debug("dev_sse_close",{subscriberCount:u.size})}),t.debug("dev_sse_conn",{subscriberCount:u.size})}let U=(r,l,E)=>{if(s){e.vite.middlewares(r,l,E);return}if(r.method==="GET"&&r.path===oe){q(l);return}let x=kt(r,c);r[n]=x.face,t.debug("dev_face_decision",{face:x.face,credSource:x.credSource,reason:x.reason,method:r.method,pathname:r.path,secFetchSite:r.headers["sec-fetch-site"]??null,secFetchMode:r.headers["sec-fetch-mode"]??null,requestId:r.headers["x-request-id"]??null,reqIdSource:"header"}),x.face==="dev"?e.vite.middlewares(r,l,E):E()},rt=(r,l,E)=>{ot(r,l,E)};async function ot(r,l,E){if(Pt(r.path??"/",e.spaExcludePrefixes)){E();return}let x=s?"classic":r[n]??"static";if(x==="static"&&I){I(r,l,E);return}if(x!=="static"){if(y){try{await it(r,l,E)}catch(w){E(w)}return}try{let w=await X(H.join(e.clientRoot,"index.html"),"utf-8");w=await e.vite.transformIndexHtml(r.originalUrl??"/",w),x==="dev"&&(w=z(w,Je(c,e.hmrPath,a))),w=e.decorateHtml?e.decorateHtml(w,"dev"):w,l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),x==="dev"&&l.setHeader("Cache-Control","no-store"),l.end(w),m.has("dev")||(m.add("dev"),t.info("dev_html_face",{face:"dev",pathname:r.path,source:"clientRoot"}))}catch(w){E(w)}return}v(r,l,()=>{if(r.method!=="GET"&&r.method!=="HEAD"){l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.end("Not Found");return}X(H.join(e.clientDist,"index.html"),"utf-8").then(w=>{let D=z(z(w,Xe),j()),$=e.decorateHtml?e.decorateHtml(D,"static"):D;l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),l.setHeader("Cache-Control","no-store"),l.end($),t.debug("dev_spa_fallback_hit",{face:"static",pathname:r.path,method:r.method,distReady:!0})}).catch(()=>{l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.end("Not Found"),t.debug("dev_spa_fallback_hit",{face:"static",pathname:r.path,method:r.method,distReady:!1})})})}async function it(r,l,E){if(r.method!=="GET"&&r.method!=="HEAD"){l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.setHeader("Content-Type","text/plain; charset=utf-8"),l.end("Not Found");return}let x=null,w="",D=r.path??"/";try{let k=new URL(r.url??"/","http://tbox.local");D=k.pathname,w=k.search,x=V(k.pathname)}catch{x=null}if(x===null){T(r,l,404,C);return}let $=x,ce=S.get($);if(ce!==void 0){t.debug("strict_dev_platform_hit",{pathname:$});let k=H.join(e.clientRoot,R,`${ce.inputName}.ts`);if(!N(k)){t.warn("strict_dev_platform_entry_missing",{pathname:$,expected:H.relative(e.clientRoot,k)}),T(r,l,503,L);return}let A=await X(H.join(e.clientRoot,"index.html"),"utf-8"),F=G(A,d,`/${R}/${ce.inputName}.ts`);if(F===null){t.warn("strict_dev_platform_entry_replace_failed",{pathname:$,clientEntrySrc:d}),T(r,l,503,L);return}await ae(r,l,E,F,se(r));return}if(ne($)){l.statusCode=404,l.setHeader("Content-Type","text/plain; charset=utf-8"),l.setHeader("Cache-Control","no-store"),r.method!=="HEAD"&&l.write("Not Found"),l.end();return}let De=P?.load()??null;if(De===null){T(r,l,503,L);return}let $e=await X(H.join(e.clientRoot,"index.html"),"utf-8");if($!=="/"&&!$.endsWith("/")){let k=O(b,$);if(k&&re(k)&&N(H.join(k,"index.html"))){let A=`${D}/${w}`,F=A.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");T(r,l,301,`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${F}">${F}</a></body></html>`,{Location:A});return}}if($!=="/"&&$.endsWith("/")){let k=O(b,$),A=k===null?null:H.join(k,"index.html");if(A&&N(A)){let F=await X(A,"utf-8");l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),l.setHeader("Cache-Control","no-store"),r.method!=="HEAD"&&l.write(F),l.end();return}}let Ie=$.endsWith("/")&&$!=="/"?$.slice(0,-1):$,le=De.get(Ie);if(le===void 0){T(r,l,404,C);return}if(Ie==="/"){await ae(r,l,E,$e,se(r));return}let Te=H.join(e.clientRoot,R,`${le}.ts`);if(!N(Te)){t.warn("strict_dev_entry_missing",{pathname:$,expected:H.relative(e.clientRoot,Te)}),T(r,l,503,L);return}let ke=G($e,d,`/${R}/${le}.ts`);if(ke===null){t.warn("strict_dev_entry_replace_failed",{pathname:$,clientEntrySrc:d}),T(r,l,503,L);return}await ae(r,l,E,ke,se(r))}function se(r){return r[n]??"classic"}async function ae(r,l,E,x,w){try{let D=await e.vite.transformIndexHtml(r.originalUrl??"/",x);w==="dev"&&(D=z(D,Je(c,e.hmrPath,a))),D=e.decorateHtml?e.decorateHtml(D,"dev"):D,l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),w==="dev"&&l.setHeader("Cache-Control","no-store"),l.end(D)}catch(D){E(D)}}return{gate:U,final:rt,handleUpgrade:(r,l,E)=>{let x;try{x=new URL(r.url||"/","http://localhost").pathname}catch{return!1}if(x!==e.hmrPath)return!1;let w=r.headers["sec-websocket-protocol"],D=a?new URL(r.url||"/","http://localhost").searchParams.get(qe):void 0;if(!w)r.headers["sec-websocket-protocol"]=D==="vite-ping"?"vite-ping":"vite-hmr";else if(w!=="vite-hmr"&&w!=="vite-ping")return!1;if(!s){let $=Ze(r.url??"/");if(c===void 0||!xe($,c))return l.write(`HTTP/1.1 401 Unauthorized\r
|
|
6
12
|
Connection: close\r
|
|
7
13
|
Content-Length: 0\r
|
|
8
14
|
\r
|
|
9
|
-
`),
|
|
15
|
+
`),l.end(()=>{l.destroyed||l.destroy()}),t.info("dev_hmr_upgrade",{outcome:"rejected-401",pathname:x,protocol:r.headers["sec-websocket-protocol"]}),!0}return!w&&(D==="vite-hmr"||D==="vite-ping")&&f.add(r),e.hmrHub.emit("upgrade",r,l,E),t.info("dev_hmr_upgrade",{outcome:"claimed",pathname:x,protocol:r.headers["sec-websocket-protocol"]}),!0},notifyBuildEnd:()=>{p=!1,h+=1;for(let r of u)r.destroyed||r.write(`data: ${M()}
|
|
10
16
|
|
|
11
|
-
`);
|
|
17
|
+
`);t.info("dev_build_end",{buildId:h})},notifyBuildStart:()=>{p=!0,t.info("dev_build_start",{})}}}import{randomUUID as Se}from"crypto";var Qe=String.raw`function installPreviewCapture(ticket) {
|
|
12
18
|
const root = window;
|
|
13
19
|
if (root.__tboxPreviewErrors)
|
|
14
20
|
return;
|
|
@@ -88,7 +94,7 @@ Content-Length: 0\r
|
|
|
88
94
|
}
|
|
89
95
|
}, true);
|
|
90
96
|
window.addEventListener('unhandledrejection', (event) => report('promise', event.reason));
|
|
91
|
-
}`,
|
|
97
|
+
}`,et=String.raw`function connectPreviewCapture(hot) {
|
|
92
98
|
const state = window.__tboxPreviewErrors;
|
|
93
99
|
if (!state || !hot)
|
|
94
100
|
return;
|
|
@@ -153,7 +159,7 @@ Content-Length: 0\r
|
|
|
153
159
|
document.addEventListener('DOMContentLoaded', () => { ready = true; observe(); }, { once: true });
|
|
154
160
|
bind();
|
|
155
161
|
hot.dispose(() => { clearTimeout(timer); state.connected = false; state.flush = () => { }; });
|
|
156
|
-
}`;var
|
|
157
|
-
`;for(;Buffer.byteLength(
|
|
162
|
+
}`;var tt="tbox:preview-report",nt="[TBOX_PREVIEW_REPORT] ",_e="\0tbox-preview-errors",Re=e=>typeof e=="string"&&/^[\w:-]{1,160}$/.test(e),Ct=(e,t)=>typeof e=="string"?e.slice(0,t).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,""):"",ie=(e,t)=>Ct(e,t).replace(/https?:\/\/[^\s)]+/g,n=>{try{let s=new URL(n);return s.origin+s.pathname}catch{return"[URL]"}});function Mt(e={}){let t=Math.max(5e3,Math.min(6e4,Math.trunc(e.observationMs||5e3))),n=Se(),s=new Map,c=new Map,a=new Map,f=0,h="/",p=!1,g=()=>{},u=(o,v,m={})=>{let i={v:1,type:v,serverSessionId:n,scopeId:o.scopeId,pageId:o.pageId,documentEpoch:o.epoch,seq:++o.seq,errorRevision:o.revision,...m},y=nt+JSON.stringify(i)+`
|
|
163
|
+
`;for(;Buffer.byteLength(y)>16384;){let d=["stack","message","filename"].sort((b,S)=>String(i[S]??"").length-String(i[b]??"").length)[0],R=String(i[d]??"");if(R.length<2)return;i[d]=R.slice(0,Math.floor(R.length/2)),y=nt+JSON.stringify(i)+`
|
|
158
164
|
`}process.stdout.write(`
|
|
159
|
-
`+
|
|
165
|
+
`+y)};return{name:"tbox-preview-error-reporter",apply:"serve",configResolved(o){p=e.enabled!==!1&&!process.env.VITEST&&o.command==="serve",h=o.base},resolveId(o){if(p&&o===_e)return _e},load(o){if(p&&o===_e)return`(${et})(import.meta.hot);`},transformIndexHtml:{order:"pre",handler(){if(!p)return;let o=Date.now();for(let[m,i]of s)o-i.at>6e5&&s.delete(m);s.size>=256&&s.delete(s.keys().next().value);let v=Se();return s.set(v,{epoch:++f,at:o}),[{tag:"script",children:`(${Qe})(${JSON.stringify(v)});`,injectTo:"head-prepend"},{tag:"script",attrs:{type:"module",src:`${h}@id/__x00__tbox-preview-errors`},injectTo:"head-prepend"}]}},configureServer(o){if(!p)return;let v=(i,y)=>{try{if(!i||!Re(i.ticket)||!Re(i.pageId)||!Re(i.scopeId))return;let d=c.get(i.pageId),R=s.get(i.ticket)??(d&&d.ticket===i.ticket?{epoch:d.epoch,at:d.startedAt}:void 0);if(!R)return;if(i.type==="page-start"){if(d){if(d.ticket!==i.ticket||d.client!==y&&d.client.socket.readyState===1)return;d.client!==y&&(d.available=!1),d.client=y}else{for(let[P,I]of c)I.client.socket.readyState!==1&&Date.now()-I.startedAt>6e5&&(c.delete(P),a.get(I.scopeId)===I&&a.delete(I.scopeId));if(c.size>=128)return;let b=i.scopeId,S=a.get(b);if(S&&R.epoch<=S.epoch)return;S?.client.socket.readyState===1?b=Se():S&&c.delete(S.pageId),d={ticket:i.ticket,scopeId:b,pageId:i.pageId,epoch:R.epoch,client:y,seq:0,clientSeq:0,revision:0,startedAt:Date.now(),available:!0,windowAt:Date.now(),count:0},c.set(i.pageId,d),a.set(b,d),u(d,"page-start")}y.send("tbox:preview-bound",{pageId:d.pageId,scopeId:d.scopeId,observationMs:t});return}if(!d||d.ticket!==i.ticket||d.client!==y||a.get(d.scopeId)!==d||!Number.isSafeInteger(i.clientSeq)||i.clientSeq<1)return;if(i.clientSeq<=d.clientSeq){y.send("tbox:preview-ack",{pageId:d.pageId,clientSeq:i.clientSeq});return}if(i.clientSeq!==d.clientSeq+1&&(d.available=!1),d.clientSeq=i.clientSeq,Date.now()-d.windowAt>=1e3&&(d.windowAt=Date.now(),d.count=0),++d.count>10){d.available&&(d.available=!1,u(d,"unavailable"));return}if(i.type==="error"){if(!["javascript","promise","script"].includes(i.kind))return;d.revision++,u(d,"error",{kind:i.kind,name:ie(i.name,120),message:ie(i.message,3e3),stack:ie(i.stack,5e3),filename:ie(i.filename,1e3).split(/[?#]/)[0],line:Number.isSafeInteger(i.line)&&i.line>=0?i.line:0,column:Number.isSafeInteger(i.column)&&i.column>=0?i.column:0})}else i.type==="observed"&&d.available&&!d.revision&&Date.now()-d.startedAt>=t?u(d,"observed",{observedMs:t}):i.type==="unavailable"&&(d.available=!1,u(d,"unavailable"));y.send("tbox:preview-ack",{pageId:d.pageId,clientSeq:i.clientSeq})}catch{}},m=i=>{i.once("close",()=>{for(let y of c.values())y.client.socket===i&&(y.available=!1,u(y,"unavailable"))})};o.ws.on(tt,v),o.ws.on("connection",m),g=()=>{o.ws.off(tt,v),o.ws.off("connection",m),c.clear(),a.clear(),s.clear()}},closeBundle(){g()}}}export{Le as DEFAULT_CLIENT_ENTRY_SRC,je as DEFAULT_GEN_DIR_NAME,Ue as DEFAULT_MOUNT_HELPER_ID,oe as DEV_SSE_PATH,Ke as DEV_TOKEN_ENV,K as DEV_TOKEN_NAME,He as RESERVED_ROUTE_SEGMENTS,Y as RUNTIME_PATH,ue as SCRIPT_TAG,C as STRICT_HTML_404,L as STRICT_HTML_503,ge as buildDocumentHtml,me as buildEntryModule,B as canonicalRouteKey,we as createStrictStaticHandler,Ht as createTboxDevRuntime,V as decodeRoutePathname,he as generateRouteFiles,Pe as injectScript,lt as installInspector,re as isDirectory,N as isFile,ct as isReady,ne as lastSegmentHasExtension,Fe as listPublicFiles,W as parseRoutesJson,Mt as previewErrorReporter,ze as publishStagedDist,G as replaceClientEntrySrc,It as resolveDevTokenFromEnv,Ve as resolveStagingDir,Q as routeDocumentOutput,O as safeJoin,T as sendStrictHtml,vt as tboxMpaPlugin,Be as validateRouteConflicts,Ce as validateRoutes};
|
package/dist/server/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{AsyncLocalStorage as yr}from"async_hooks";import{createCoreLogger as hr,detailForLog as xe,resolveLevel as Rr,setLogContextProvider as xr}from"@tbox.cn/app-sdk-core";var L=new yr;xr(()=>L.getStore());function Tr(t,e){return L.run(t,e)}var Se=()=>{};function Sr(t){Se=t}function Ge(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Te(){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 h(t){return{...hr({tag:t,getLevel:()=>Rr(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>L.getStore()}),span(r,n){let o=L.getStore();Se({spanId:Ge(`sp_${t.replace(/[^a-zA-Z0-9]/g,"")}`),traceId:o?.requestId??"no-req",name:r,startTime:Te(),endTime:Te(),...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 Ir(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=${xe(n.detail.args)}`:"",u=` result=${xe(s)}`;n.logger.info(`${e} ok durMs=${i}${a}${u}`)}else n?.logger&&t==="op"&&n.logger.info(`${e} ok durMs=${i}`);return n?.emitSpan&&bt(t,e,{durMs:i}),s}catch(s){let i=Date.now()-o;if(n?.onDone?.(i),n?.logger){let a=t==="tool"?"error":"warn",u=` err=${s?.message??String(s)}`;n.logger[a](`${e} fail durMs=${i}${u}`)}throw n?.emitSpan&&bt(t,e,{durMs:i,error:s}),s}}function bt(t,e,r){let n=L.getStore();Se({spanId:Ge("sp_call"),traceId:n?.requestId??"no-req",name:`${t}:${e}`,startTime:Te(),endTime:Te(),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 Ie(t,e){return t?{async request(r){t.info(`→ ${r.path} body=${xe(r.body)}`);let n=Date.now(),o=L.getStore(),s=o?new Date(n):void 0;try{let i=await e.request(r),a=Date.now()-n,u=`← ${r.path} durMs=${a} body=${xe(i)}`;return a>re?t.warn(`SLOW ${u}`):t.info(u),Ct(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)}`),Ct(o,s,r.path,a,i),i}}}:e}function Ct(t,e,r,n,o){!t||!e||Se({spanId:Ge("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 _t=h("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&&_t.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)&&_t.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 kt=h("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){kt.warn("tool without id skipped:",e.description);return}this.disabled.has(r)||(this.tools.has(r)&&kt.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=h("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 Ar}from"express";var Pt=h("ApiRouteRegistry"),ie=class{root=Ar();moduleIds=[];register(e,r){let n=e.replace(/^\/+|\/+$/g,"");if(!n){Pt.warn("register with empty moduleId skipped");return}this.moduleIds.includes(n)&&Pt.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 wr=h("ServiceRegistry"),X=class{services=new Map;register(e,r){this.services.has(e)&&wr.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)}},Ve=new X;function Er(t,e){Ve.register(t,e)}function br(t){return Ve.resolve(t)}function Cr(){Ve.clear()}import{SCOPE_ASSEMBLY_KIND as _r}from"@tbox.cn/app-contracts";var kr=h("DomainAssemblyRegistry"),ae=class{assemblies=new Map;register(e,r){this.assemblies.has(e)&&kr.warn(`overwriting existing domain assembly: ${e}`),this.assemblies.set(e,r)}resolve(e){return this.assemblies.get(e)}scopeAssembly(){return this.resolve(_r)}get size(){return this.assemblies.size}};var Ot=h("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){Ot.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){Ot.error(`handler error for "${String(e)}":`,i)}o.length>0&&await Promise.allSettled(o)},subscribe(e,r){return this.on(e,r)}}}function Nt(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 Xe(t){try{return Nt(JSON.stringify(t??{}))}catch{return Nt(String(t))}}import{AUTH_ERROR_CODES as F,authCodeToStatus as Pr}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=Pr(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 Or=h("AUTH");async function de(t,e,r){if(!e){if(r==="optional")return{identity:Ye()};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 Mt=4096;function ue(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>Mt){Or.warn("context envelope dropped (>4KB): treated as absent (fail-soft)");return}return t}catch{return}}import{AsyncLocalStorage as Nr}from"async_hooks";import{networkInterfaces as Mr}from"os";import{createCoreLogger as Dr,resolveLevel as Lr}from"@tbox.cn/app-sdk-core";var Lt="sofa-traceid",$t="sofa-rpcid",Ut="traceid",Kt="rpcid",Dt=/^[\w.-]{1,64}$/,$r=["tbox.cn"],Ee=new Nr,Ur=Dr({tag:"SOFA",getLevel:()=>Lr(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>{}});function Kr(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 Hr(){try{for(let t of Object.values(Mr()))for(let e of t??[])if(e.family==="IPv4"&&!e.internal)return Kr(e.address)}catch{}return"ffffffff"}var Fr=Hr(),Ae=1e3;function qr(){return Ae=Ae>9e3?1e3:Ae+1,String(Ae)}function Je(){return Fr+Date.now()+qr()+process.pid}function jr(){Ee.enterWith({traceId:Je(),parentRpcId:"0",childSeq:0})}function we(t){return Array.isArray(t)?t[0]:t}function Qe(t){let e=we(t[Lt])??we(t[Ut]),r;if(e!==void 0&&Dt.test(e)){let n=we(t[$t])??we(t[Kt]);r={traceId:e,parentRpcId:n!==void 0&&Dt.test(n)?n:"0",childSeq:0}}else r={traceId:Je(),parentRpcId:"0",childSeq:0};return Ee.enterWith(r),r.traceId}function Br(){return Ee.getStore()?.traceId}function Gr(){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,...Gr()].some(r=>t===r||t.endsWith(`.${r}`))}function Ze(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=Ee.getStore(),o=n?.traceId??Je(),s=n?`${n.parentRpcId}.${++n.childSeq}`:"0.1";return Ur.debug(`out traceId=${o} rpcId=${s} host=${e} path=${r}`),{[Lt]:o,[Ut]:o,[$t]:s,[Kt]:s}}var Ht=h("HTTP");function Vr(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 Ft="tboxAuthContext";function qt(t,e){Object.defineProperty(t,Ft,{value:e,enumerable:!0,configurable:!0})}function Y(t){return t[Ft]}function Ye(t=Date.now()){return{userId:`anonymous_${t}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"}}function et(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 u=Vr(s.headers["x-request-id"])??Wr();i.setHeader?.("X-Request-ID",u),L.enterWith({requestId:u});let f=Qe(s.headers),d=Date.now();if(i.on?.("finish",()=>{let c=Date.now()-d,l=`${s.method} ${s.originalUrl||s.url} ${i.statusCode} durMs=${c} sofa=${f}`,p=(s.originalUrl||s.url||"").split("?")[0];/\/health(z)?$/.test(p)?Ht.debug(l):Ht.info(l)}),o(s))return a();try{let c=s.headers.authorization,l=c?.startsWith("Bearer ")?c.slice(7).trim():void 0,p=await de(t,l,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 qt(s,{identity:p.identity,...p.credentials?{credentials:p.credentials}:{},...m?{attributes:m}:{}}),a()}catch(c){if(c instanceof w){i.status(c.status).json({error:c.message,code:c.code});return}i.status(401).json({error:c.message,code:"AUTH_UNAUTHORIZED"})}}}var jt=h("ActionGateway");function tt(t){let e=new Map,r=t?.idempotencyStore??new ce;function n(d){return{sessionId:(d?.body??{})?.sessionId??"",requestContext:d?Y(d):void 0,emit:()=>{}}}async function o(d,c){for(let l of c.checks??[]){let p=await l.check(d);if(!p.ok)return p}return null}async function s(d,c,l,p){let g=d.policy,m=g.write??!1,y=g.idempotent??!1;if(m&&y){if(!p)return{status:400,body:{success:!1,error:"Missing idempotencyKey (write action)"}};let T=Xe(c),I=await r.tryAcquire(p,T);if(!I.acquired){let A=r.getPayloadHash?.(p);return A&&A!==T?{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 A=await d.handler(c,l);return await r.commit(p,A),{status:200,body:A}}catch(A){throw r.release?.(p),A}}return{status:200,body:await d.handler(c,l)}}async function i(d,c,l){if(!d||typeof d!="string")return{status:400,body:{success:!1,error:"Missing action"}};let p=e.get(d);if(!p)return{status:404,body:{success:!1,error:`Unknown action: ${d}`}};if(p.policy.write&&Y(l)?.identity?.source==="anonymous")return{status:403,body:{success:!1,error:"anonymous write is forbidden"}};let g=await o(l,p.policy);if(g)return{status:g.code??403,body:{success:!1,error:g.message}};let m=l.body??{};return s(p,c,n(l),m.idempotencyKey)}function a(){return async(d,c,l)=>{try{let p=d.body??{},g=await i(p.action,p.payload,d);c.status(g.status).json(g.body)}catch(p){jt.error("handler error:",p),c.status(500).json({success:!1,error:p?.message||"Internal error"})}}}function u(d={}){return async(c,l,p)=>{try{let g=await o(c,d);if(g){l.status(g.code??403).json({success:!1,error:g.message});return}p()}catch(g){p(g)}}}async function f(d,c,l){let p=e.get(d);if(!p)return{success:!1,error:`Unknown action: ${d}`};let g=l?.requestContext?.identity??l?.identity;if(p.policy.write&&g?.source==="anonymous")return{success:!1,error:"anonymous write is forbidden"};let m=await o({},p.policy);return m?{success:!1,error:m.message}:(await s(p,c,{sessionId:l?.sessionId??"",requestContext:l?.requestContext?l.requestContext:l?.identity?{identity:l.identity}:void 0,emit:()=>{}},l?.idempotencyKey)).body}return{registerAction(d,c,l={}){e.has(d)&&jt.warn(`overwriting existing action: ${d}`),e.set(d,{handler:c,policy:l})},middleware:a,validateAction:u,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 Xr}from"@ag-ui/core";import{TBOX_CARD_EVENT_NAME as Yr}from"@tbox.cn/app-contracts";var Bt=h("CARD");function Gt(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){Bt.warn(`unknown cardType: ${e.cardType}`);return}let n=r.dataSchema.safeParse(e.data);return n.success?{id:e.id||Gt("card"),messageId:e.messageId,cardType:e.cardType,data:n.data,status:"ready",schemaVersion:r.schemaVersion??1,meta:{createdAt:Date.now()},...r.project?.(n.data)??{}}:(Bt.warn(`data schema mismatch for ${e.cardType}:`,n.error.message),{id:e.id||Gt("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:Xr.CUSTOM,name:Yr,value:e};return r(n),e}};var rt=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 nt}from"@tbox.cn/app-contracts";var Jr={description:1024,instructions:32*1024,references:64,referenceSize:32*1024};var be=h("SkillRegistry"),le=class{skills=new Map;register(e){if(!nt.test(e.name)){be.warn(`非法 skill 名 "${e.name}" 跳过(须匹配 ^[a-z0-9-]{1,64}$)`);return}for(let r of Object.keys(e.references))r.endsWith(".md")||be.warn(`skill "${e.name}" reference key "${r}" 非 .md 结尾`);this.skills.has(e.name)&&be.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&&be.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 Qr}from"@tbox.cn/app-contracts";var Ce=h("PreToolRegistry"),ge=class{preTools=new Map;register(e){let r=e?.tool?.id;if(!r||!Qr.test(r)){Ce.warn(`非法 toolId "${r}" 跳过(须匹配 ^[A-Za-z0-9_-]{1,64}$)`);return}if(e.routing.mode==="keywords"&&e.routing.terms.length===0){Ce.warn(`keywords 路由空 terms 跳过: ${r}(恒不命中;如须每轮候选请用 always 模式)`);return}this.preTools.has(r)&&Ce.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&&Ce.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 Zr,randomUUID as Ps}from"crypto";var q=(t,e)=>`${t}\0${e}`;function ot(t){if(t!==null&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))ot(e)}return t}function st(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),u=(e.get(a)?.revision??0)+1;return e.set(a,{value:ot(structuredClone(s)),revision:u,expiresAt:i>0?t().getTime()+i:void 0}),!0},async compareAndSet(n,o,s,i,a){let u=q(n,o),f=t().getTime(),d=e.get(u),c=d&&r(d,f)?d.revision:0;return c!==s?!1:(e.set(u,{value:ot(structuredClone(i)),revision:c+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 en(t){return Zr("sha256").update(t).digest("hex").slice(0,32)}var tn=h("PROVIDER"),zt="static-headers-v1",it="-",Vt={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=[Vt]){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)&&tn.warn(`认证策略重复注册(后者覆盖):${r.credentialType}`),e.set(r.credentialType,r))},list:()=>[...e.values()]}}var _e=h("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(u=>u.provider===n);for(let u of s){if(!u.matches)continue;let f=!1;try{f=u.matches(o)!==!1}catch(d){_e.warn(`matches threw for ${n}(谓词违约视为不命中):`,d.message)}if(f)return _e.debug("resolve",n,"source=scoped"),u}let i=s.find(u=>!u.matches);if(i)return _e.debug("resolve",n,"source=fallback"),i;let a=e.get(n);return _e.debug("resolve",n,a?"source=builtin":"source=none",`explicit=${s.length}`),a},list(){return[...r,...e.values()]}}}function rn(t){let e=new X,r=t?.snapshotStore??new pe,n=new Map,o=tt({idempotencyStore:t?.idempotencyStore}),s=new ae,i=t?.scopeDefaults,a=new Proxy({},{get:(R,T)=>{if(typeof T!="string")return;let I=s.scopeAssembly()?.scopeDefaults?.[T];return I!==void 0?I:i?.[T]},has:(R,T)=>typeof T!="string"?!1:s.scopeAssembly()?.scopeDefaults?.[T]!==void 0||i?.[T]!==void 0}),u=t?.state??st(),f=t?.authStrategies??at(),d=t?.authExchanges??j(),c=new Map,l={register:R=>{if((!R.kind||R.kind==="moduleAction")&&!R.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${R.moduleId}:${R.actionId}`);c.set(R.actionId,R)},get:R=>c.get(R),getAll:()=>new Map(c)},p=R=>e.resolve(R),g=(R,T)=>n.get(R)?.[T],m=(R,T,I)=>{let A=n.get(R)??{};A[T]=I,n.set(R,A)},y=R=>{n.delete(R)};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:p,flowStates:{get:g,set:m,clear:y},state:u,...t?.memory?{memory:t.memory}:{},cardActions:l,authStrategies:f,authExchanges:d,domainAssemblies:s,...t?.integrations?{integrations:t.integrations}:{},scopeDefaults:a}}import pn from"path";import{readFileSync as on}from"fs";import{join as sn}from"path";import{z as U}from"zod";import{expandEnvVars as nn}from"@tbox.cn/app-toolkit";function ct(t,e=process.env,r="<config>"){let n=nn(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=h("app-config"),Wt=U.object({topK:U.number().int().positive().optional(),scoreThreshold:U.number().optional()}).passthrough(),an=U.object({datasetId:U.string().min(1),retrieve_config:Wt.optional()}).passthrough(),cn=U.object({defaults:Wt.optional(),knowledge_bases:U.record(U.string(),an).optional()}).passthrough(),fe={bases:{},defaults:{}};function ut(t){let e=sn(t,"knowledge.json"),r;try{r=JSON.parse(ct(on(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=cn.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=h("app-config"),dn=["faq","mall-knowledge"],Xt={};function lt(t,e){if(!t)return()=>Xt;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[u,f]of Object.entries(i.resources??{})){let d=un(s,u,f,n,e);d&&(a[u]=d)}o.set(s,a)}return s=>o.get(s)??Xt}function un(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 ln=h("app-config");async function gn(t,e){if(!t.services.resolve("app-config")){let r=t.integrations?.raw,n=r?.source?pn.dirname(r.source):"";Object.values(r?.config.modules??{}).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))&&!r?.source&&ln.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:h(`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 D="https://o.tbox.cn",gt="1.0.0",ft="X-Tbox-SDK-Version";var Yt=null;function Jt(){if(Yt)return Yt;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 Qt(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=Ze(e);if(Object.keys(n).length>0){let a=new Headers(r?.headers);for(let[u,f]of Object.entries(n))a.has(u)||a.set(u,f);r={...r,headers:a}}let o=Jt();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 Qt(n)}};var Q=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,apiKey:e.apiKey,timeout:e.timeout})}async generateSession(e){return this.http.post("/openapi/v1/app/generate_session",e)}};var ke="/openapi/v1/conversation",Pe=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,apiKey:e.apiKey,timeout:e.timeout})}async createConversation(e){return this.http.post(`${ke}/create`,e)}async listConversations(e){return this.http.post(`${ke}/list`,e)}async listMessages(e){return this.http.post(`${ke}/message/list`,e)}async saveMessage(e){return this.http.post(`${ke}/message/save`,e)}};var fn={"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 mn(t,e){if(/\.\w+$/.test(t))return t;let r=e?fn[e]:void 0;return r?`${t}${r}`:t}var Oe=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,auth:{type:"session",session:e.session},timeout:e.timeout})}async upload(e){let r=mn(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 yn="wss://mediafeature.alipay.com:443/tts_stream",mt={voiceCode:"lingyue",voiceType:"SYSTEM",sampleRate:24e3,volume:50,speechRate:0,pitchRate:0},Ne=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??yn,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 u={method:"POST",headers:e,body:JSON.stringify({appkey:this.appkey})};if(this.timeout){let f=new AbortController,d=setTimeout(()=>f.abort(),this.timeout);try{r=await fetch(this.authUrl,{...u,signal:f.signal})}finally{clearTimeout(d)}}else r=await fetch(this.authUrl,u)}catch(u){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:u instanceof Error?u.message:String(u)}}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 u=JSON.parse(n);return{success:!1,errorCode:u.errorCode??u.code??`HTTP_${r.status}`,errorMsg:u.errorMsg??u.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 hn="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(`${hn}/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 Zt="/openapi/v1/plugin",Me=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,apiKey:e.apiKey,timeout:e.timeout})}async run(e,r){return this.http.post(`${Zt}/run/${encodeURIComponent(e)}`,r)}async getPluginInfo(e){return this.http.get(`${Zt}/info/${encodeURIComponent(e)}`)}};var De=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,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 Le=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,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 xn,hkdfSync as er,timingSafeEqual as Tn,randomUUID as Sn}from"crypto";import{stableSerializeScope as In}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 k=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ActionGrantError"}code},Ue=900*1e3,ye="action-grant",tr="action-grant";function rr(t){let e=Buffer.from(t);if(e.length<32){let r=Buffer.alloc(32);return e.copy(r),new Uint8Array(er("sha256",r,Buffer.alloc(0),Buffer.from(tr),32))}return new Uint8Array(er("sha256",e,Buffer.alloc(0),Buffer.from(tr),32))}function vn(){let t=$e(process.env,{firstKeyName:"ACTION_TOKEN_SECRET"});if(!t)throw new k("TOKEN_INVALID","密钥链缺失:ACTION_TOKEN_SECRET/AUTH_TOKEN_SECRET");return new TextEncoder().encode(t.secret)}function An(t){let e=t.store,r=rr(t.secret??vn()),n=t.now??(()=>Date.now());function o(a){let u=[a.moduleId,a.actionId,a.cardType,a.cardId??"",a.sessionId,In(a.scope),String(a.singleUse),String(a.expiresAt)].join("\0");return xn("sha256",r).update(u).digest("base64url")}function s(a,u){return`${u}.${Buffer.from(JSON.stringify(a),"utf8").toString("base64url")}`}async function i(a){let u=a.indexOf(".");if(u<=0)throw new k("TOKEN_INVALID","令牌格式非法");let f=a.slice(0,u),d;try{d=JSON.parse(Buffer.from(a.slice(u+1),"base64url").toString("utf8"))}catch{throw new k("TOKEN_INVALID","令牌载荷非法")}let c=o(d),l=Buffer.from(f),p=Buffer.from(c);if(l.length!==p.length||!Tn(l,p))throw new k("TOKEN_INVALID","签名校验失败");if(d.expiresAt<=n())throw new k("TOKEN_EXPIRED","令牌已过期");return{record:d,signature:f}}return{async issue(a){let u=Math.min(a.ttlMs??Ue,Ue),f=n(),d={grantId:Sn(),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+u},c=s(d,o(d));return d.singleUse&&await e.put(ye,d.grantId,{consumed:!1},u),c},async authorize(a,u){let{record:f}=await i(a);if(f.actionId!==u.actionId||f.sessionId!==u.sessionId)throw new k("GRANT_MISMATCH","授权与期望不匹配");if((f.cardId??void 0)!==(u.cardId??void 0))throw new k("GRANT_MISMATCH","授权 cardId 不匹配");let d=Object.keys(u.scope).sort(),c=Object.keys(f.scope).sort();if(d.length!==c.length||!d.every((p,g)=>p===c[g]&&u.scope[p]===f.scope[p]))throw new k("GRANT_MISMATCH","授权 scope 不匹配");let l=f.grantId;if(f.singleUse){let p=await e.getEntry(ye,l);if(!p)throw new k("TOKEN_CONSUMED","令牌已消费");if(p.value.consumed)throw new k("TOKEN_CONSUMED","令牌已消费");if(!await e.compareAndSet(ye,l,p.revision,{consumed:!0},Ue))throw new k("TOKEN_CONSUMED","令牌已消费")}return Object.freeze({...f})},async restore(a){let{record:u}=await i(a);if(!u.singleUse)return;let f=await e.get(ye,u.grantId);!f||!f.consumed||await e.put(ye,u.grantId,{consumed:!1},Math.max(u.expiresAt-n(),1e3))}}}var E=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ModuleActionError"}code};var yt=200;function Ke(t){return t.length>yt?`${t.slice(0,yt)}…`:t}function wn(t){if(t instanceof k)return{level:"error",text:{TOKEN_EXPIRED:"操作已过期,请重新查询后再试",TOKEN_CONSUMED:"该操作已执行,请刷新卡片后重试"}[t.code]??"卡片数据已过期,为保护用户安全,请您重新唤起最新卡片数据操作"};if(t instanceof E&&t.code==="INPUT_INVALID")return{level:"error",text:"输入格式不正确,请检查后重试"};let e=t?.message??"";return{level:"error",text:Ke(e)||"操作执行失败,请稍后重试"}}import{SignJWT as En,jwtVerify as bn}from"jose";var Cn=7200*1e3,_n="agent",kn=30,nr=16*1024,Pn={local:"local_",external:void 0,guest:"guest_",anonymous:"anonymous_"},or=720*60*60*1e3;function ht(t){let e=new TextEncoder().encode(t.secret),r=t.issuer??_n,n=t.ttlMs??Cn,o=t.clockToleranceSec??kn,s=t.embedExternalToken??!0,i=new Set(["local","external","guest","anonymous"]);async function a(c,l){if(c.source==="anonymous")throw w.forbidden("anonymous identity cannot be issued a token");if(l?.external){let T=Buffer.byteLength(l.external.token,"utf8");if(T>(t.maxExternalTokenBytes??nr))throw w.externalError(`external token too large (${T} bytes > ${t.maxExternalTokenBytes??nr}); 请精简外部 claims,或由外部返回 identity 而非透传 token`)}let p=l?.now??Date.now(),g=Math.floor(p/1e3),m=Math.floor((p+n)/1e3);return{token:await new En({source:c.source,...s&&l?.external?{external:l.external}:{}}).setProtectedHeader({alg:"HS256"}).setSubject(c.userId).setIssuer(r).setIssuedAt(g).setExpirationTime(m).sign(e),expiresAt:m*1e3}}async function u(c,l){try{let{payload:p}=await bn(c,e,{issuer:r,algorithms:["HS256"],clockTolerance:o,...l?{ignoreExpiration:!0}:{}}),g=p.sub,m=p.source;if(!g||typeof g!="string")throw w.unauthorized("token subject missing");if(!m||!i.has(m))throw w.unauthorized("token source missing");let y=Pn[m];if(y&&!g.startsWith(y))throw w.unauthorized("token subject/source mismatch");return{sub:g,iss:p.iss??r,iat:typeof p.iat=="number"?p.iat*1e3:0,exp:typeof p.exp=="number"?p.exp*1e3:0,source:m,...p.external?{external:p.external}:{}}}catch(p){throw p instanceof w?p:p.code==="ERR_JWT_EXPIRED"?w.tokenExpired("token expired"):w.unauthorized(`invalid token: ${p.message}`)}}async function f(c){return u(c,!1)}async function d(c){return u(c,!0)}return{issue:a,verify:f,verifyIgnoringExpiration:d}}function Rt(t,e={}){let r=e.mode??"required";return{async authenticate(n){return de(t,n,r)}}}import{createLogger as Wc}from"@tbox.cn/app-sdk-core";import{randomUUID as On}from"crypto";var Z=class extends Error{constructor(r,n){super(r);this.code=n;this.name="ScopeSessionError"}code};function Nn(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(),u={sessionId:On(),scopeKey:i,scope:structuredClone(s),scopeFlat:t.buildScope(s),createdAt:a,expiresAt:a+e};return n.set(u.sessionId,u),u},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 K}from"@tbox.cn/app-contracts";import{existsSync as Mn,readFileSync as Dn}from"fs";import Ln from"path";var x=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 x(K.CREDENTIAL_REF_MISSING,"credentialRef 缺失(生产 fail-fast)"):new x(K.CREDENTIAL_REF_MISSING,"credentialRef 缺失");if(!n.startsWith("secret://"))throw new x(K.CREDENTIAL_REF_MISSING,`非法 credentialRef 前缀:${n.split("://")[0]}`);let s=n.slice(9),i;if(t.files){let l=Ln.join(t.files,`${s.toLowerCase().replaceAll("_","-")}.json`);if(Mn(l))try{i=Dn(l,"utf8")}catch{i=void 0}}if(i??=t.source[s.replaceAll("-","_").toUpperCase()],i??=t.source[s],!i)throw new x(K.CREDENTIAL_REF_MISSING,`机密环境键缺失:${s}`);let a;try{a=JSON.parse(i)}catch{throw new x(K.CREDENTIAL_REF_MISSING,`机密环境键非法 JSON:${s}`)}let u=a;if(!u||typeof u!="object")throw new x(K.CREDENTIAL_REF_MISSING,`机密形状非法:${s}`);let f={};for(let[l,p]of Object.entries(u.scope??{}))typeof p=="string"&&(f[l]=p);if(Object.keys(f).length>0){for(let[l,p]of Object.entries(o))if(f[l]!==p)throw new x(K.CREDENTIAL_SCOPE_MISMATCH,`凭证 scope 与实例 scope 不匹配:${l}`)}let d=typeof u.type=="string"?u.type:"static-headers-v1",c=u.value&&typeof u.value=="object"?u.value:{};if(d==="static-headers-v1"){for(let l of Object.keys(c))if(!e.has(l.toLowerCase()))throw new x(K.CREDENTIAL_REF_MISSING,`头名不在白名单:${l}`)}return{scope:f,type:d,value:c}}}}import{PROVIDER_ERROR_CODES as O}from"@tbox.cn/app-contracts";import{randomUUID as Un}from"crypto";function xt(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,u)=>{let f={failures:0,openedAt:0},d=u.credentialType===it,c=d?void 0:t.strategies.get(u.credentialType);if(!c&&!d)throw new x(O.TRANSPORT_FAILURE,`未知认证类型:${u.credentialType}`);let p=(a.config??{}).baseUrl??"",g=a.scope??{},m=c?.placement??"header";return{async request(y){if(f.openedAt>0){if(s()-f.openedAt<r)throw new x(O.CIRCUIT_OPEN,"熔断开闸");f.openedAt=0,f.failures=e-1}let R=y.method??"POST",T;try{T=Kn(p,y.path,y.query)}catch{throw ee(f,e,r,s),new x(O.TRANSPORT_FAILURE,"URL 构造失败")}Hn(T);let I;if(!c)I={};else{let S;try{S=t.secretProvider.resolve(a.credentialRef??"",g)}catch(P){throw P instanceof x&&P.code===O.CREDENTIAL_REF_MISSING?P:new x(O.TRANSPORT_FAILURE,`凭证解析失败:${P.message}`)}try{I=c.apply({method:R,url:T,body:y.body,credential:S,headers:y.extraHeaders})}catch{throw ee(f,e,r,s),new x(O.TRANSPORT_FAILURE,"认证参数构造失败")}}let A=m==="body"&&(R==="POST"||R==="PUT");if((m==="query"||m==="body"&&!A)&&Object.keys(I).length>0)try{let S=new URL(T);for(let[P,Re]of Object.entries(I))S.searchParams.set(P,Re);T=S.toString()}catch{throw ee(f,e,r,s),new x(O.TRANSPORT_FAILURE,"认证 query 追加失败")}let M={"content-type":"application/json","x-trace-id":Un(),...m==="header"?I:{},...y.extraHeaders},C=y.body;A&&Object.keys(I).length>0&&(C={...y.body&&typeof y.body=="object"&&!Array.isArray(y.body)?y.body:{},...I});let _=Math.min(y.timeoutMs??o,o),V=new AbortController,fr=setTimeout(()=>V.abort(),_),je=R==="GET"||C===void 0?void 0:JSON.stringify(C);t.logger?.debug("[transport] 最终请求",JSON.stringify({method:R,url:T,body:je?JSON.parse(je):null,headers:Object.fromEntries(Object.entries(M).map(([S,P])=>S.toLowerCase()==="token"||S.toLowerCase()==="authorization"||S.toLowerCase()==="visitortoken"?[S,typeof P=="string"?`${P.slice(0,20)}...(len=${P.length})`:P]:[S,P]))}));try{let S=await fetch(T,{method:R,headers:M,body:je,signal:V.signal}),P=S.status>=500||S.status===429;if(!S.ok&&!P)throw new x(O.TRANSPORT_FAILURE,`HTTP ${S.status}`);if(P)throw ee(f,e,r,s),new x(O.TRANSPORT_FAILURE,`HTTP ${S.status}`);let Re=Number(S.headers.get("content-length")??0);if(Re>n)throw new x(O.RESPONSE_TOO_LARGE,`响应超限:${Re}B > ${n}B`);let Be=S.body?.getReader(),W;if(Be){let At=[],wt=0;for(;;){let{done:mr,value:Et}=await Be.read();if(mr)break;if(wt+=Et.byteLength,wt>n)throw await Be.cancel(),new x(O.RESPONSE_TOO_LARGE,`响应超限:>${n}B`);At.push(new TextDecoder().decode(Et))}W=At.join("")}else if(W=await S.text(),W.length>n)throw new x(O.RESPONSE_TOO_LARGE,`响应超限:${W.length}B > ${n}B`);f.failures=0;try{return JSON.parse(W)}catch{return W}}catch(S){throw S instanceof x?S:S instanceof DOMException&&S.name==="AbortError"?(ee(f,e,r,s),new x(O.TRANSPORT_FAILURE,`超时 ${_}ms`)):(ee(f,e,r,s),new x(O.TRANSPORT_FAILURE,`网络错误:${S.message}`))}finally{clearTimeout(fr)}}}}}}function ee(t,e,r,n){t.failures+=1,t.failures>=e&&(t.openedAt=n())}function Kn(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 Hn(t){let e=new URL(t);if(e.protocol!=="https:"&&!((e.hostname==="127.0.0.1"||e.hostname==="localhost")&&e.protocol==="http:"))throw new x(O.TRANSPORT_FAILURE,`强制 HTTPS:${e.protocol}`)}import{buildSupplyLookup as Bn,PROVIDER_ERROR_CODES as te,resolveEffectiveService as ar,stableSerializeScope as Gn}from"@tbox.cn/app-contracts";var He=new Map;function Fn(t,e){process.env.NODE_ENV!=="production"&&He.set(t,e)}function qn(){He.clear()}function sr(t){return He.has(t)}function ir(t,e){let r=He.get(t);if(!r)throw new Error(`无 dev fixture:${t}`);return r(e)}function jn(t){let e={async request(n){let o=r;if(!o)throw new Error("fixture transport 未绑定实例");return ir(o.providerTemplateId,n)}},r;return{create(n,o){return sr(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 cr=(t,e)=>`${t}\0${e}`,zn={identity:{userId:"",source:"anonymous"},credentials:{provider:"anonymous",token:""},attributes:{}},Vn=Object.freeze({});function Wn(t){let e=new Map,r=new Map,n=t.transportFactory??xt({strategies:t.authStrategies,secretProvider:t.secretProvider,logger:t.logger}),o=t.instanceIdOf??(d=>Gn(d)),s=Bn(t.catalog),i=Vn,a=d=>typeof d=="string"?d:`${d.provider}(inline)`,u=(d,c,l,p)=>{if(typeof d=="string"){let g=t.catalog.providers[d]?.[c];if(!g)throw new x(te.PROVIDER_NOT_FOUND,`provider 未命中 catalog:${d}/${c}(${l}@${p})`);return{provider:d,implementation:c,entry:g,inline:void 0}}return{provider:d.provider,implementation:"inline",entry:void 0,inline:d}};function f(d){let c=o(d.scope),l=ar(t.integrations,d.service,c,s,t.ownerOf);if(l.status==="service-not-configured")throw new x(te.SERVICE_NOT_CONFIGURED,`服务槽未配置:${d.service}(integrations.services 缺键)`);if(l.status==="instance-not-found")throw new x(te.INSTANCE_NOT_FOUND,`无匹配实例:${d.service}@${c}(instances 缺键)`);if(l.status==="instance-disabled")throw new x(te.INSTANCE_DISABLED,`实例已禁用:${d.service}@${c}`);if(l.status==="binding-unresolved")throw new x(te.BINDING_UNRESOLVED,l.message);let p=l.effective,g=u(p.provider,p.implementation,d.service,c),m=g.entry?.local===!0,y;if(m)y=Tt();else{let R=`${d.service}\0${c}\0${g.provider}\0${g.implementation}`;y=r.get(R)??(()=>{let T={providerInstanceId:`${d.service}:${c}:${g.provider}:${g.implementation}`,providerTemplateId:g.implementation,scope:d.scope,config:p.config,...p.credentialRef?{credentialRef:p.credentialRef}:{},enabled:!0},I={providerTemplateId:g.implementation,credentialType:g.entry?.credentialType??g.inline?.credentialType??"-"},A=n.create(T,I);return r.set(R,A),A})()}return{transport:y,local:m,config:p.config,credentialRef:p.credentialRef,provider:g.provider,implementation:g.implementation,providerDisplay:a(p.provider),instanceId:c}}return{registerAdapter(d,c,l){let p=cr(d,c);e.has(p)&&t.logger?.warn(`adapter 重复注册(后者覆盖):${d}/${c}`),e.set(p,l)},listAdapters(){return[...e.keys()]},declareProviderInstances(d,c){if(c.length!==0){for(let l of c)if(typeof l.id!="string"||!l.id||l.id==="*"||typeof l.name!="string"||!l.name)throw new Error(`declareProviderInstances 非法实例(provider=${d}):id 禁空与 '*'(通配保留字),name 须非空 string`);i[d]!==void 0&&t.logger?.warn(`provider instances 重复声明(后者覆盖):${d}`),i=Object.freeze({...i,[d]:Object.freeze(c.map(l=>Object.freeze({...l})))})}},providerInstanceDeclarations(){return i},async resolveService(d){let c=f(d),l=e.get(cr(c.provider,c.implementation));if(!l)throw new x(te.PROVIDER_NOT_IMPLEMENTED,`provider 未实施(无 adapter 注册):${c.providerDisplay}/${c.implementation}(${d.service}@${c.instanceId});实施指引见 packages/provider-custom/INTEGRATION.md`);return l({transport:Ie(c.local?void 0:t.logger,c.transport),config:c.config??{},...c.credentialRef?{credentialRef:c.credentialRef}:{},...c.credentialRef?{credential:()=>t.secretProvider.resolve(c.credentialRef,d.scope)}:{},scope:d.scope,instanceId:c.instanceId,request:d.request,service:d.service})},async resolveLoginExchange(d){let c=f({...d,request:zn});return{transport:Ie(c.local?void 0:t.logger,c.transport),config:c.config??{},providerId:c.implementation}},hasProviderBinding(d,c,l,p){let g=o(c),m=ar(t.integrations,d,g,s,t.ownerOf);if(m.status!=="ok")return!1;let y=m.effective;return typeof y.provider=="string"&&y.provider===l&&y.implementation===p},raw:{config:t.integrations,...t.source?{source:t.source}:{}}}}import{loadProviderCatalog as Xn,buildOwnershipMap as Yn}from"@tbox.cn/app-toolkit";import{EventType as dr}from"@ag-ui/core";import{TBOX_CARD_UPDATE_EVENT_NAME as Zn,TBOX_NOTICE_EVENT_NAME as eo}from"@tbox.cn/app-contracts";var Jn=h("CARD");function Qn(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 Fe(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({...Qn(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){Jn.warn(`动作 token 签发失败(跳过):${n.actionId}`,o.message)}return{...t.payload,actions:e.map(({singleUse:n,...o})=>o),...Object.keys(r).length>0?{actionTokens:r}:{}}}var to=600*1e3;function ro(t){return t.type==="payment"||t.type==="authorization.alipay-user-profile"}function no(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 oo(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 E("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,u=[];try{if(i.cardType!==n.cardType)throw new E("GRANT_INVALID","授权 cardType 与动作声明不一致");let d=r.formData&&typeof r.formData=="object"&&!Array.isArray(r.formData)?r.formData:{},c=i.input&&typeof i.input=="object"&&!Array.isArray(i.input)?{...d,...i.input}:d,l=c;if(n.inputSchema){let g=n.inputSchema.safeParse(c);if(!g.success)throw new E("INPUT_INVALID",`入参校验失败:${g.error.message}`);l=g.data}if(!n.execute)throw new E("GRANT_INVALID",`动作无服务端执行体(纯客户端 kind 不应进 dispatch):${r.actionId}`);if(a=await n.execute(l,r.ctx),!a||typeof a!="object")throw new E("RESULT_INVALID","动作结果形状非法");for(let g of a.effects??[]){let m=g;if(m&&ro(m)){let y=e.get(m.resultActionId);if(!y)throw new E("CALLBACK_INVALID",`效果回调动作未注册:${m.resultActionId}`);if(y.moduleId!==i.moduleId)throw new E("CALLBACK_INVALID",`效果回调动作组件归属不一致:${m.resultActionId}`);if(y.cardType!==n.cardType)throw new E("CALLBACK_INVALID",`效果回调动作 cardType 与当前动作不一致:${m.resultActionId}`);if(y.singleUse!==!0)throw new E("CALLBACK_INVALID",`效果回调动作必须 singleUse:${m.resultActionId}`);m.callback={actionId:y.actionId,contextToken:await t.grants.issue({moduleId:i.moduleId,actionId:y.actionId,cardType:n.cardType,sessionId:s.sessionId,scope:s.scopeFlat,singleUse:!0,ttlMs:to,input:{...m.type==="payment"?{paymentRef:m.paymentRef}:{},...r.surfaceId?{surfaceId:r.surfaceId}:{}}})}}}u=t.effects.project(a);let p=no(r.surfaceId,i.input);if(a.update){if(a.card)throw new E("RESULT_INVALID","card 与 update 互斥");if(!p)throw new E("RESULT_INVALID","原地更新需要来源卡 surfaceId");let m=new J(t.cardRegistry).build({cardType:n.cardType,data:a.update.data,conversationId:"",id:p});if(!m||m.status==="error")throw new E("RESULT_INVALID",`更新数据未通过 ${n.cardType} dataSchema 校验`);let y=await Fe({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat}),R={...y,meta:{...y.meta,updatedAt:Date.now()}};r.emit({type:dr.CUSTOM,name:Zn,value:R})}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 y=await Fe({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat});g.send(y,r.emit)}}}catch(d){throw n.singleUse&&await t.grants.restore(r.token),d}let f=typeof a.text=="string"?a.text.trim():"";f&&r.emit({type:dr.CUSTOM,name:eo,value:{level:"info",text:Ke(f),surfaceId:r.surfaceId||void 0}});for(let d of u)r.emit(d);return a}}}import{TBOX_EFFECT_EVENT_NAME as so}from"@tbox.cn/app-contracts";var B=class extends Error{constructor(e){super(e),this.name="EffectError"}},io=new Set(["navigation.open","payment","share","download","authorization.alipay-user-profile","session.credentials-refreshed"]);function ao(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 co(t={}){return{project(e){let r=[];for(let n of e.effects??[]){let o=n;if(!o||typeof o.type!="string"||!io.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 ao(o);r.push({type:"CUSTOM",name:so,value:o})}return r}}}var he=class extends Error{constructor(r,n){super(n);this.code=r;this.name="KnowledgeError"}code};function uo(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 H=class extends Error{constructor(r,n){super(n);this.code=r;this.name="PaymentError"}code};function po(t={}){return{async createCashier(e){if(!t.createCashierHandler)throw new H("NOT_CONFIGURED","支付通道未装配(宿主注入 createCashierHandler)");try{return await t.createCashierHandler(e)}catch(r){throw r instanceof H?r:new H("API_ERROR",`收银台创建失败:${r.message}`)}},async queryResult(e){if(!t.queryResultHandler)return{status:"UNKNOWN"};try{return await t.queryResultHandler(e)}catch(r){throw r instanceof H?r:new H("API_ERROR",`支付结果查询失败:${r.message}`)}}}}import{parseIntegrationsConfig as ld,assertNoInlineSecrets as gd}from"@tbox.cn/app-contracts";import{createSign as lo,createVerify as go}from"crypto";var fo="https://openapi.alipay.com/gateway.do";function mo(t=process.env,e=fetch){function r(){let i=t.ALIPAY_APP_ID?.trim(),a=t.ALIPAY_APP_PRIVATE_KEY?.trim(),u=t.ALIPAY_PUBLIC_KEY?.trim();if(!i||!a||!u)throw new Error("AUTH_NOT_CONFIGURED: Alipay user authorization is unavailable");return Object.freeze({appId:i,privateKey:a,publicKey:u})}async function n(i,a){let{appId:u,privateKey:f}=r(),d={app_id:u,method:i,charset:"utf-8",sign_type:"RSA2",timestamp:ur(new Date),version:"1.0",...a};d.sign=yo(d,f);let c=await e(fo,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"},body:new URLSearchParams(d).toString(),signal:AbortSignal.timeout(1e4)});if(!c.ok)throw new Error(`ALIPAY_API_ERROR: HTTP ${c.status}`);let l=await c.text();try{return JSON.parse(l)}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 u=a,f=N(u.sub_msg)??N(u.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 u=a.alipay_system_oauth_token_response;if(!u||typeof u!="object"||Array.isArray(u))throw new Error("INVALID_CODE: no token response");return u}return Object.freeze({async authorizeUserProfile(i){let{publicKey:a}=r(),u=await s(i),f=N(u.access_token);if(!f)throw new Error("INVALID_CODE: no access_token in response");let d=await n("alipay.user.info.share",{auth_token:f});o(d);let c=d.alipay_user_info_share_response,l=N(d.sign);if(!c||typeof c!="object"||Array.isArray(c)||!l)throw new Error("ALIPAY_API_ERROR: incomplete authorized profile response");let p=go("RSA-SHA256");if(p.update(JSON.stringify(c),"utf8"),!p.verify(St(a,"PUBLIC"),l,"base64"))throw new Error("ALIPAY_API_ERROR: profile response signature is invalid");let g=c,m=N(g.user_id)??N(g.open_id)??N(u.user_id)??N(u.open_id);if(!m)throw new Error("ALIPAY_API_ERROR: authorized user id is missing");let y=N(g.mobile),R=N(g.nick_name)??N(g.nickName),T=N(g.avatar),I=T?.startsWith("https://")?T:void 0,A=ho(g.gender),v=N(g.birthday);return Object.freeze({userId:m,...y?{mobile:y}:{},...R?{displayName:R}:{},...I?{avatarUrl:I}:{},...A?{gender:A}:{},...v?{birthday:v}:{}})}})}function ur(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{a as Be}from"../chunk-U2YZGGOR.js";import{AsyncLocalStorage as mr}from"async_hooks";import{createCoreLogger as yr,detailForLog as Re,resolveLevel as hr,setLogContextProvider as Rr}from"@tbox.cn/app-sdk-core";var L=new mr;Rr(()=>L.getStore());function xr(t,e){return L.run(t,e)}var Te=()=>{};function Tr(t){Te=t}function Ge(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function xe(){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 h(t){return{...yr({tag:t,getLevel:()=>hr(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>L.getStore()}),span(r,n){let o=L.getStore();Te({spanId:Ge(`sp_${t.replace(/[^a-zA-Z0-9]/g,"")}`),traceId:o?.requestId??"no-req",name:r,startTime:xe(),endTime:xe(),...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 te=3e3;async function Sr(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=${Re(n.detail.args)}`:"",u=` result=${Re(s)}`;n.logger.info(`${e} ok durMs=${i}${a}${u}`)}else n?.logger&&t==="op"&&n.logger.info(`${e} ok durMs=${i}`);return n?.emitSpan&&bt(t,e,{durMs:i}),s}catch(s){let i=Date.now()-o;if(n?.onDone?.(i),n?.logger){let a=t==="tool"?"error":"warn",u=` err=${s?.message??String(s)}`;n.logger[a](`${e} fail durMs=${i}${u}`)}throw n?.emitSpan&&bt(t,e,{durMs:i,error:s}),s}}function bt(t,e,r){let n=L.getStore();Te({spanId:Ge("sp_call"),traceId:n?.requestId??"no-req",name:`${t}:${e}`,startTime:xe(),endTime:xe(),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 Se(t,e){return t?{async request(r){t.info(`→ ${r.path} body=${Re(r.body)}`);let n=Date.now(),o=L.getStore(),s=o?new Date(n):void 0;try{let i=await e.request(r),a=Date.now()-n,u=`← ${r.path} durMs=${a} body=${Re(i)}`;return a>te?t.warn(`SLOW ${u}`):t.info(u),Ct(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)}`),Ct(o,s,r.path,a,i),i}}}:e}function Ct(t,e,r,n,o){!t||!e||Te({spanId:Ge("sp_ext"),traceId:t.requestId??"no-req",name:"external-call",startTime:e,endTime:new Date(e.getTime()+n),metadata:{path:r,durMs:n,...n>te?{slow:!0}:{}},...o!==void 0?{errorInfo:ze(o)}:{},requestId:t.requestId??"no-req",...t.conversationId?{conversationId:t.conversationId}:{},...t.threadKey?{sessionId:t.threadKey}:{}})}var _t=h("HandlerRegistry");function Ir(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&&_t.warn(`顶层意图路由非确定性档(${n.map(o=>o.id).join(", ")}):语义分类职责归 skill 路由与 LLM 工具编排——建议声明 match:"exact"/"prefix"(详见 prompt-pipeline「declaration 与 intents」)`),e}var re=class{handlers=new Map;register(e){this.handlers.has(e.id)&&_t.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 kt=h("ToolRegistry"),ne=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){kt.warn("tool without id skipped:",e.description);return}this.disabled.has(r)||(this.tools.has(r)&&kt.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 Ie=h("CardRegistry"),oe=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){Ie.warn("meta without cardType skipped");return}if(this.disabled.has(e.cardType)){Ie.debug(`disabled cardType skipped: ${e.cardType}`);return}this.cards.has(e.cardType)&&Ie.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&&Ie.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 vr}from"express";var Pt=h("ApiRouteRegistry"),se=class{root=vr();moduleIds=[];register(e,r){let n=e.replace(/^\/+|\/+$/g,"");if(!n){Pt.warn("register with empty moduleId skipped");return}this.moduleIds.includes(n)&&Pt.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=h("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)}},Ve=new W;function wr(t,e){Ve.register(t,e)}function Er(t){return Ve.resolve(t)}function br(){Ve.clear()}import{SCOPE_ASSEMBLY_KIND as Cr}from"@tbox.cn/app-contracts";var _r=h("DomainAssemblyRegistry"),ie=class{assemblies=new Map;register(e,r){this.assemblies.has(e)&&_r.warn(`overwriting existing domain assembly: ${e}`),this.assemblies.set(e,r)}resolve(e){return this.assemblies.get(e)}scopeAssembly(){return this.resolve(Cr)}get size(){return this.assemblies.size}};var Ot=h("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){Ot.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){Ot.error(`handler error for "${String(e)}":`,i)}o.length>0&&await Promise.allSettled(o)},subscribe(e,r){return this.on(e,r)}}}function Nt(t){let e=0;for(let r=0;r<t.length;r++)e=e*31+t.charCodeAt(r)|0;return String(e)}var ae=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 Xe(t){try{return Nt(JSON.stringify(t??{}))}catch{return Nt(String(t))}}import{AUTH_ERROR_CODES as H,authCodeToStatus as kr}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=kr(e)}static unauthorized(e){return new t(H.UNAUTHORIZED,e)}static tokenExpired(e){return new t(H.TOKEN_EXPIRED,e)}static forbidden(e){return new t(H.FORBIDDEN,e)}static methodRequired(e){return new t(H.METHOD_REQUIRED,e)}static browserLoginDisabled(e){return new t(H.BROWSER_LOGIN_DISABLED,e)}static externalError(e){return new t(H.EXTERNAL_ERROR,e)}static missingSecret(e){return new t(H.MISSING_SECRET,e)}};var Pr=h("AUTH");async function ce(t,e,r){if(!e){if(r==="optional")return{identity:Ye()};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 Mt=4096;function de(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>Mt){Pr.warn("context envelope dropped (>4KB): treated as absent (fail-soft)");return}return t}catch{return}}import{AsyncLocalStorage as Or}from"async_hooks";import{networkInterfaces as Nr}from"os";import{createCoreLogger as Mr,resolveLevel as Dr}from"@tbox.cn/app-sdk-core";var Lt="sofa-traceid",$t="sofa-rpcid",Ut="traceid",Kt="rpcid",Dt=/^[\w.-]{1,64}$/,Lr=["tbox.cn"],we=new Or,$r=Mr({tag:"SOFA",getLevel:()=>Dr(process.env.TBOX_LOG_LEVEL,"info"),getContext:()=>{}});function Ur(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 Kr(){try{for(let t of Object.values(Nr()))for(let e of t??[])if(e.family==="IPv4"&&!e.internal)return Ur(e.address)}catch{}return"ffffffff"}var Hr=Kr(),ve=1e3;function Fr(){return ve=ve>9e3?1e3:ve+1,String(ve)}function Je(){return Hr+Date.now()+Fr()+process.pid}function qr(){we.enterWith({traceId:Je(),parentRpcId:"0",childSeq:0})}function Ae(t){return Array.isArray(t)?t[0]:t}function Qe(t){let e=Ae(t[Lt])??Ae(t[Ut]),r;if(e!==void 0&&Dt.test(e)){let n=Ae(t[$t])??Ae(t[Kt]);r={traceId:e,parentRpcId:n!==void 0&&Dt.test(n)?n:"0",childSeq:0}}else r={traceId:Je(),parentRpcId:"0",childSeq:0};return we.enterWith(r),r.traceId}function jr(){return we.getStore()?.traceId}function Br(){let t=process.env.TBOX_SOFA_TRACE_HOSTS;return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0):[]}function Gr(t){return[...Lr,...Br()].some(r=>t===r||t.endsWith(`.${r}`))}function Ze(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(!Gr(e))return{};let n=we.getStore(),o=n?.traceId??Je(),s=n?`${n.parentRpcId}.${++n.childSeq}`:"0.1";return $r.debug(`out traceId=${o} rpcId=${s} host=${e} path=${r}`),{[Lt]:o,[Ut]:o,[$t]:s,[Kt]:s}}var Ht=h("HTTP");function zr(t){if(typeof t!="string")return;let e=t.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:void 0}function Vr(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var Ft="tboxAuthContext";function qt(t,e){Object.defineProperty(t,Ft,{value:e,enumerable:!0,configurable:!0})}function X(t){return t[Ft]}function Ye(t=Date.now()){return{userId:`anonymous_${t}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"}}function et(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 u=zr(s.headers["x-request-id"])??Vr();i.setHeader?.("X-Request-ID",u),L.enterWith({requestId:u});let f=Qe(s.headers),d=Date.now();if(i.on?.("finish",()=>{let c=Date.now()-d,l=`${s.method} ${s.originalUrl||s.url} ${i.statusCode} durMs=${c} sofa=${f}`,p=(s.originalUrl||s.url||"").split("?")[0];/\/health(z)?$/.test(p)?Ht.debug(l):Ht.info(l)}),o(s))return a();try{let c=s.headers.authorization,l=c?.startsWith("Bearer ")?c.slice(7).trim():void 0,p=await ce(t,l,r),g=s.body?.context,m=s.method==="POST"&&g!==void 0?de(g):void 0;if(m&&e.validateContext&&!e.validateContext(m)){i.status(403).json({error:"context validation failed",code:"AUTH_FORBIDDEN"});return}return qt(s,{identity:p.identity,...p.credentials?{credentials:p.credentials}:{},...m?{attributes:m}:{}}),a()}catch(c){if(c instanceof w){i.status(c.status).json({error:c.message,code:c.code});return}i.status(401).json({error:c.message,code:"AUTH_UNAUTHORIZED"})}}}var jt=h("ActionGateway");function tt(t){let e=new Map,r=t?.idempotencyStore??new ae;function n(d){return{sessionId:(d?.body??{})?.sessionId??"",requestContext:d?X(d):void 0,emit:()=>{}}}async function o(d,c){for(let l of c.checks??[]){let p=await l.check(d);if(!p.ok)return p}return null}async function s(d,c,l,p){let g=d.policy,m=g.write??!1,y=g.idempotent??!1;if(m&&y){if(!p)return{status:400,body:{success:!1,error:"Missing idempotencyKey (write action)"}};let T=Xe(c),I=await r.tryAcquire(p,T);if(!I.acquired){let A=r.getPayloadHash?.(p);return A&&A!==T?{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 A=await d.handler(c,l);return await r.commit(p,A),{status:200,body:A}}catch(A){throw r.release?.(p),A}}return{status:200,body:await d.handler(c,l)}}async function i(d,c,l){if(!d||typeof d!="string")return{status:400,body:{success:!1,error:"Missing action"}};let p=e.get(d);if(!p)return{status:404,body:{success:!1,error:`Unknown action: ${d}`}};if(p.policy.write&&X(l)?.identity?.source==="anonymous")return{status:403,body:{success:!1,error:"anonymous write is forbidden"}};let g=await o(l,p.policy);if(g)return{status:g.code??403,body:{success:!1,error:g.message}};let m=l.body??{};return s(p,c,n(l),m.idempotencyKey)}function a(){return async(d,c,l)=>{try{let p=d.body??{},g=await i(p.action,p.payload,d);c.status(g.status).json(g.body)}catch(p){jt.error("handler error:",p),c.status(500).json({success:!1,error:p?.message||"Internal error"})}}}function u(d={}){return async(c,l,p)=>{try{let g=await o(c,d);if(g){l.status(g.code??403).json({success:!1,error:g.message});return}p()}catch(g){p(g)}}}async function f(d,c,l){let p=e.get(d);if(!p)return{success:!1,error:`Unknown action: ${d}`};let g=l?.requestContext?.identity??l?.identity;if(p.policy.write&&g?.source==="anonymous")return{success:!1,error:"anonymous write is forbidden"};let m=await o({},p.policy);return m?{success:!1,error:m.message}:(await s(p,c,{sessionId:l?.sessionId??"",requestContext:l?.requestContext?l.requestContext:l?.identity?{identity:l.identity}:void 0,emit:()=>{}},l?.idempotencyKey)).body}return{registerAction(d,c,l={}){e.has(d)&&jt.warn(`overwriting existing action: ${d}`),e.set(d,{handler:c,policy:l})},middleware:a,validateAction:u,dispatch:f,getActions:()=>new Map(e)}}var ue=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 Wr}from"@ag-ui/core";import{TBOX_CARD_EVENT_NAME as Xr}from"@tbox.cn/app-contracts";var Bt=h("CARD");function Gt(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var Y=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){Bt.warn(`unknown cardType: ${e.cardType}`);return}let n=r.dataSchema.safeParse(e.data);return n.success?{id:e.id||Gt("card"),messageId:e.messageId,cardType:e.cardType,data:n.data,status:"ready",schemaVersion:r.schemaVersion??1,meta:{createdAt:Date.now()},...r.project?.(n.data)??{}}:(Bt.warn(`data schema mismatch for ${e.cardType}:`,n.error.message),{id:e.id||Gt("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:Wr.CUSTOM,name:Xr,value:e};return r(n),e}};var rt=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 nt}from"@tbox.cn/app-contracts";var Yr={description:1024,instructions:32*1024,references:64,referenceSize:32*1024};var Ee=h("SkillRegistry"),pe=class{skills=new Map;register(e){if(!nt.test(e.name)){Ee.warn(`非法 skill 名 "${e.name}" 跳过(须匹配 ^[a-z0-9-]{1,64}$)`);return}for(let r of Object.keys(e.references))r.endsWith(".md")||Ee.warn(`skill "${e.name}" reference key "${r}" 非 .md 结尾`);this.skills.has(e.name)&&Ee.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&&Ee.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 Jr}from"@tbox.cn/app-contracts";var be=h("PreToolRegistry"),le=class{preTools=new Map;register(e){let r=e?.tool?.id;if(!r||!Jr.test(r)){be.warn(`非法 toolId "${r}" 跳过(须匹配 ^[A-Za-z0-9_-]{1,64}$)`);return}if(e.routing.mode==="keywords"&&e.routing.terms.length===0){be.warn(`keywords 路由空 terms 跳过: ${r}(恒不命中;如须每轮候选请用 always 模式)`);return}this.preTools.has(r)&&be.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&&be.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 Qr,randomUUID as Cs}from"crypto";var F=(t,e)=>`${t}\0${e}`;function ot(t){if(t!==null&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))ot(e)}return t}function st(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(F(n,o));return s?r(s,t().getTime())?s.value:(e.delete(F(n,o)),null):null},async getEntry(n,o){let s=e.get(F(n,o));return s?r(s,t().getTime())?{value:s.value,revision:s.revision,expiresAt:s.expiresAt}:(e.delete(F(n,o)),null):null},async put(n,o,s,i){let a=F(n,o),u=(e.get(a)?.revision??0)+1;return e.set(a,{value:ot(structuredClone(s)),revision:u,expiresAt:i>0?t().getTime()+i:void 0}),!0},async compareAndSet(n,o,s,i,a){let u=F(n,o),f=t().getTime(),d=e.get(u),c=d&&r(d,f)?d.revision:0;return c!==s?!1:(e.set(u,{value:ot(structuredClone(i)),revision:c+1,expiresAt:a>0?f+a:void 0}),!0)},async consume(n,o){let s=F(n,o),i=e.get(s);return i?r(i,t().getTime())?(e.delete(s),i.value):(e.delete(s),null):null}}}function Zr(t){return Qr("sha256").update(t).digest("hex").slice(0,32)}var en=h("PROVIDER"),zt="static-headers-v1",it="-",Vt={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=[Vt]){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)&&en.warn(`认证策略重复注册(后者覆盖):${r.credentialType}`),e.set(r.credentialType,r))},list:()=>[...e.values()]}}var Ce=h("auth-exchanges");function q(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(u=>u.provider===n);for(let u of s){if(!u.matches)continue;let f=!1;try{f=u.matches(o)!==!1}catch(d){Ce.warn(`matches threw for ${n}(谓词违约视为不命中):`,d.message)}if(f)return Ce.debug("resolve",n,"source=scoped"),u}let i=s.find(u=>!u.matches);if(i)return Ce.debug("resolve",n,"source=fallback"),i;let a=e.get(n);return Ce.debug("resolve",n,a?"source=builtin":"source=none",`explicit=${s.length}`),a},list(){return[...r,...e.values()]}}}function tn(t){let e=new W,r=t?.snapshotStore??new ue,n=new Map,o=tt({idempotencyStore:t?.idempotencyStore}),s=new ie,i=t?.scopeDefaults,a=new Proxy({},{get:(R,T)=>{if(typeof T!="string")return;let I=s.scopeAssembly()?.scopeDefaults?.[T];return I!==void 0?I:i?.[T]},has:(R,T)=>typeof T!="string"?!1:s.scopeAssembly()?.scopeDefaults?.[T]!==void 0||i?.[T]!==void 0}),u=t?.state??st(),f=t?.authStrategies??at(),d=t?.authExchanges??q(),c=new Map,l={register:R=>{if((!R.kind||R.kind==="moduleAction")&&!R.execute)throw new Error(`moduleAction 动作缺少 execute 回调:${R.moduleId}:${R.actionId}`);c.set(R.actionId,R)},get:R=>c.get(R),getAll:()=>new Map(c)},p=R=>e.resolve(R),g=(R,T)=>n.get(R)?.[T],m=(R,T,I)=>{let A=n.get(R)??{};A[T]=I,n.set(R,A)},y=R=>{n.delete(R)};return{handlers:new re,tools:new ne,cards:new oe,skills:new pe,preTools:new le,routes:new se,services:e,bus:We(),snapshotStore:r,actions:o,resolveService:p,flowStates:{get:g,set:m,clear:y},state:u,...t?.memory?{memory:t.memory}:{},cardActions:l,authStrategies:f,authExchanges:d,domainAssemblies:s,...t?.integrations?{integrations:t.integrations}:{},scopeDefaults:a}}import cn from"path";import{readFileSync as nn}from"fs";import{join as on}from"path";import{expandEnvVars as rn}from"@tbox.cn/app-toolkit";function ct(t,e=process.env,r="<config>"){let n=rn(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=h("app-config"),ge={bases:{},defaults:{}};function ut(t){let e=on(t,"knowledge.json"),r;try{r=JSON.parse(ct(nn(e,"utf8"),process.env,e))}catch(s){return s.code==="ENOENT"?(dt.warn(`knowledge.json 不存在(文件:${e})——ref 引用将降级缺失(台账锚 = integrations.json 同目录,检查壳 source 传参)`),ge):(dt.warn(`knowledge.json 解析失败(${s.message},文件:${e})——ref 引用将降级缺失`),ge)}let n=Be.safeParse(r);if(!n.success)return dt.warn(`knowledge.json 校验失败(${n.error.message},文件:${e})——ref 引用将降级缺失`),ge;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=h("app-config"),sn=["faq","mall-knowledge"],Wt={};function lt(t,e){if(!t)return()=>Wt;let n=Object.values(t).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))?ut(e):ge,o=new Map;for(let[s,i]of Object.entries(t)){let a={};for(let[u,f]of Object.entries(i.resources??{})){let d=an(s,u,f,n,e);d&&(a[u]=d)}o.set(s,a)}return s=>o.get(s)??Wt}function an(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 dn=h("app-config");async function un(t,e){if(!t.services.resolve("app-config")){let r=t.integrations?.raw,n=r?.source?cn.dirname(r.source):"";Object.values(r?.config.modules??{}).some(s=>Object.values(s.resources??{}).some(i=>i.ref!==void 0))&&!r?.source&&dn.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:h(`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 D="https://o.tbox.cn",gt="1.0.0",ft="X-Tbox-SDK-Version";var Xt=null;function Yt(){if(Xt)return Xt;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 Jt(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=Ze(e);if(Object.keys(n).length>0){let a=new Headers(r?.headers);for(let[u,f]of Object.entries(n))a.has(u)||a.set(u,f);r={...r,headers:a}}let o=Yt();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 Jt(n)}};var J=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,apiKey:e.apiKey,timeout:e.timeout})}async generateSession(e){return this.http.post("/openapi/v1/app/generate_session",e)}};var _e="/openapi/v1/conversation",ke=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,apiKey:e.apiKey,timeout:e.timeout})}async createConversation(e){return this.http.post(`${_e}/create`,e)}async listConversations(e){return this.http.post(`${_e}/list`,e)}async listMessages(e){return this.http.post(`${_e}/message/list`,e)}async saveMessage(e){return this.http.post(`${_e}/message/save`,e)}};var pn={"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 ln(t,e){if(/\.\w+$/.test(t))return t;let r=e?pn[e]:void 0;return r?`${t}${r}`:t}var Pe=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,auth:{type:"session",session:e.session},timeout:e.timeout})}async upload(e){let r=ln(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 gn="wss://mediafeature.alipay.com:443/tts_stream",mt={voiceCode:"lingyue",voiceType:"SYSTEM",sampleRate:24e3,volume:50,speechRate:0,pitchRate:0},Oe=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??gn,this.timeout=e.timeout}static async create(e){let n=await new J({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 u={method:"POST",headers:e,body:JSON.stringify({appkey:this.appkey})};if(this.timeout){let f=new AbortController,d=setTimeout(()=>f.abort(),this.timeout);try{r=await fetch(this.authUrl,{...u,signal:f.signal})}finally{clearTimeout(d)}}else r=await fetch(this.authUrl,u)}catch(u){return{success:!1,errorCode:"NETWORK_ERROR",errorMsg:u instanceof Error?u.message:String(u)}}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 u=JSON.parse(n);return{success:!1,errorCode:u.errorCode??u.code??`HTTP_${r.status}`,errorMsg:u.errorMsg??u.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 fn="https://api.tbox.cn",fe=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(`${fn}/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 Qt="/openapi/v1/plugin",Ne=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,apiKey:e.apiKey,timeout:e.timeout})}async run(e,r){return this.http.post(`${Qt}/run/${encodeURIComponent(e)}`,r)}async getPluginInfo(e){return this.http.get(`${Qt}/info/${encodeURIComponent(e)}`)}};var Me=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,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 De=class{http;constructor(e){this.http=new b({baseUrl:e.baseUrl??D,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 yn,hkdfSync as Zt,timingSafeEqual as hn,randomUUID as Rn}from"crypto";import{stableSerializeScope as xn}from"@tbox.cn/app-contracts";import{randomBytes as mn}from"crypto";function Le(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:mn(32).toString("hex"),source:"dev-temp"}:null}var k=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ActionGrantError"}code},$e=900*1e3,me="action-grant",er="action-grant";function tr(t){let e=Buffer.from(t);if(e.length<32){let r=Buffer.alloc(32);return e.copy(r),new Uint8Array(Zt("sha256",r,Buffer.alloc(0),Buffer.from(er),32))}return new Uint8Array(Zt("sha256",e,Buffer.alloc(0),Buffer.from(er),32))}function Tn(){let t=Le(process.env,{firstKeyName:"ACTION_TOKEN_SECRET"});if(!t)throw new k("TOKEN_INVALID","密钥链缺失:ACTION_TOKEN_SECRET/AUTH_TOKEN_SECRET");return new TextEncoder().encode(t.secret)}function Sn(t){let e=t.store,r=tr(t.secret??Tn()),n=t.now??(()=>Date.now());function o(a){let u=[a.moduleId,a.actionId,a.cardType,a.cardId??"",a.sessionId,xn(a.scope),String(a.singleUse),String(a.expiresAt)].join("\0");return yn("sha256",r).update(u).digest("base64url")}function s(a,u){return`${u}.${Buffer.from(JSON.stringify(a),"utf8").toString("base64url")}`}async function i(a){let u=a.indexOf(".");if(u<=0)throw new k("TOKEN_INVALID","令牌格式非法");let f=a.slice(0,u),d;try{d=JSON.parse(Buffer.from(a.slice(u+1),"base64url").toString("utf8"))}catch{throw new k("TOKEN_INVALID","令牌载荷非法")}let c=o(d),l=Buffer.from(f),p=Buffer.from(c);if(l.length!==p.length||!hn(l,p))throw new k("TOKEN_INVALID","签名校验失败");if(d.expiresAt<=n())throw new k("TOKEN_EXPIRED","令牌已过期");return{record:d,signature:f}}return{async issue(a){let u=Math.min(a.ttlMs??$e,$e),f=n(),d={grantId:Rn(),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+u},c=s(d,o(d));return d.singleUse&&await e.put(me,d.grantId,{consumed:!1},u),c},async authorize(a,u){let{record:f}=await i(a);if(f.actionId!==u.actionId||f.sessionId!==u.sessionId)throw new k("GRANT_MISMATCH","授权与期望不匹配");if((f.cardId??void 0)!==(u.cardId??void 0))throw new k("GRANT_MISMATCH","授权 cardId 不匹配");let d=Object.keys(u.scope).sort(),c=Object.keys(f.scope).sort();if(d.length!==c.length||!d.every((p,g)=>p===c[g]&&u.scope[p]===f.scope[p]))throw new k("GRANT_MISMATCH","授权 scope 不匹配");let l=f.grantId;if(f.singleUse){let p=await e.getEntry(me,l);if(!p)throw new k("TOKEN_CONSUMED","令牌已消费");if(p.value.consumed)throw new k("TOKEN_CONSUMED","令牌已消费");if(!await e.compareAndSet(me,l,p.revision,{consumed:!0},$e))throw new k("TOKEN_CONSUMED","令牌已消费")}return Object.freeze({...f})},async restore(a){let{record:u}=await i(a);if(!u.singleUse)return;let f=await e.get(me,u.grantId);!f||!f.consumed||await e.put(me,u.grantId,{consumed:!1},Math.max(u.expiresAt-n(),1e3))}}}var E=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ModuleActionError"}code};var yt=200;function Ue(t){return t.length>yt?`${t.slice(0,yt)}…`:t}function In(t){if(t instanceof k)return{level:"error",text:{TOKEN_EXPIRED:"操作已过期,请重新查询后再试",TOKEN_CONSUMED:"该操作已执行,请刷新卡片后重试"}[t.code]??"卡片数据已过期,为保护用户安全,请您重新唤起最新卡片数据操作"};if(t instanceof E&&t.code==="INPUT_INVALID")return{level:"error",text:"输入格式不正确,请检查后重试"};let e=t?.message??"";return{level:"error",text:Ue(e)||"操作执行失败,请稍后重试"}}import{SignJWT as vn,jwtVerify as An}from"jose";var wn=7200*1e3,En="agent",bn=30,rr=16*1024,Cn={local:"local_",external:void 0,guest:"guest_",anonymous:"anonymous_"},nr=720*60*60*1e3;function ht(t){let e=new TextEncoder().encode(t.secret),r=t.issuer??En,n=t.ttlMs??wn,o=t.clockToleranceSec??bn,s=t.embedExternalToken??!0,i=new Set(["local","external","guest","anonymous"]);async function a(c,l){if(c.source==="anonymous")throw w.forbidden("anonymous identity cannot be issued a token");if(l?.external){let T=Buffer.byteLength(l.external.token,"utf8");if(T>(t.maxExternalTokenBytes??rr))throw w.externalError(`external token too large (${T} bytes > ${t.maxExternalTokenBytes??rr}); 请精简外部 claims,或由外部返回 identity 而非透传 token`)}let p=l?.now??Date.now(),g=Math.floor(p/1e3),m=Math.floor((p+n)/1e3);return{token:await new vn({source:c.source,...s&&l?.external?{external:l.external}:{}}).setProtectedHeader({alg:"HS256"}).setSubject(c.userId).setIssuer(r).setIssuedAt(g).setExpirationTime(m).sign(e),expiresAt:m*1e3}}async function u(c,l){try{let{payload:p}=await An(c,e,{issuer:r,algorithms:["HS256"],clockTolerance:o,...l?{ignoreExpiration:!0}:{}}),g=p.sub,m=p.source;if(!g||typeof g!="string")throw w.unauthorized("token subject missing");if(!m||!i.has(m))throw w.unauthorized("token source missing");let y=Cn[m];if(y&&!g.startsWith(y))throw w.unauthorized("token subject/source mismatch");return{sub:g,iss:p.iss??r,iat:typeof p.iat=="number"?p.iat*1e3:0,exp:typeof p.exp=="number"?p.exp*1e3:0,source:m,...p.external?{external:p.external}:{}}}catch(p){throw p instanceof w?p:p.code==="ERR_JWT_EXPIRED"?w.tokenExpired("token expired"):w.unauthorized(`invalid token: ${p.message}`)}}async function f(c){return u(c,!1)}async function d(c){return u(c,!0)}return{issue:a,verify:f,verifyIgnoringExpiration:d}}function Rt(t,e={}){let r=e.mode??"required";return{async authenticate(n){return ce(t,n,r)}}}import{createLogger as zc}from"@tbox.cn/app-sdk-core";import{randomUUID as _n}from"crypto";var Q=class extends Error{constructor(r,n){super(r);this.code=n;this.name="ScopeSessionError"}code};function kn(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 Q("Scope 形状校验未通过(v4:mallId 会话边界键非空——白名单判定已退役)","SCOPE_INVALID");let i=t.extractScopeKey(o),a=r(),u={sessionId:_n(),scopeKey:i,scope:structuredClone(s),scopeFlat:t.buildScope(s),createdAt:a,expiresAt:a+e};return n.set(u.sessionId,u),u},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 Q("会话不存在或已过期","SESSION_NOT_FOUND");if(i.scopeKey!==s)throw new Q("会话 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 U}from"@tbox.cn/app-contracts";import{existsSync as Pn,readFileSync as On}from"fs";import Nn from"path";var x=class extends Error{constructor(r,n){super(n);this.code=r;this.name="ProviderError"}code};function Mn(t){let e=new Set(t.allowedHeaderNames??[]),r=t.production??process.env.NODE_ENV==="production";return{resolve(n,o){if(!n)throw r?new x(U.CREDENTIAL_REF_MISSING,"credentialRef 缺失(生产 fail-fast)"):new x(U.CREDENTIAL_REF_MISSING,"credentialRef 缺失");if(!n.startsWith("secret://"))throw new x(U.CREDENTIAL_REF_MISSING,`非法 credentialRef 前缀:${n.split("://")[0]}`);let s=n.slice(9),i;if(t.files){let l=Nn.join(t.files,`${s.toLowerCase().replaceAll("_","-")}.json`);if(Pn(l))try{i=On(l,"utf8")}catch{i=void 0}}if(i??=t.source[s.replaceAll("-","_").toUpperCase()],i??=t.source[s],!i)throw new x(U.CREDENTIAL_REF_MISSING,`机密环境键缺失:${s}`);let a;try{a=JSON.parse(i)}catch{throw new x(U.CREDENTIAL_REF_MISSING,`机密环境键非法 JSON:${s}`)}let u=a;if(!u||typeof u!="object")throw new x(U.CREDENTIAL_REF_MISSING,`机密形状非法:${s}`);let f={};for(let[l,p]of Object.entries(u.scope??{}))typeof p=="string"&&(f[l]=p);if(Object.keys(f).length>0){for(let[l,p]of Object.entries(o))if(f[l]!==p)throw new x(U.CREDENTIAL_SCOPE_MISMATCH,`凭证 scope 与实例 scope 不匹配:${l}`)}let d=typeof u.type=="string"?u.type:"static-headers-v1",c=u.value&&typeof u.value=="object"?u.value:{};if(d==="static-headers-v1"){for(let l of Object.keys(c))if(!e.has(l.toLowerCase()))throw new x(U.CREDENTIAL_REF_MISSING,`头名不在白名单:${l}`)}return{scope:f,type:d,value:c}}}}import{PROVIDER_ERROR_CODES as O}from"@tbox.cn/app-contracts";import{randomUUID as Dn}from"crypto";function xt(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,u)=>{let f={failures:0,openedAt:0},d=u.credentialType===it,c=d?void 0:t.strategies.get(u.credentialType);if(!c&&!d)throw new x(O.TRANSPORT_FAILURE,`未知认证类型:${u.credentialType}`);let p=(a.config??{}).baseUrl??"",g=a.scope??{},m=c?.placement??"header";return{async request(y){if(f.openedAt>0){if(s()-f.openedAt<r)throw new x(O.CIRCUIT_OPEN,"熔断开闸");f.openedAt=0,f.failures=e-1}let R=y.method??"POST",T;try{T=Ln(p,y.path,y.query)}catch{throw Z(f,e,r,s),new x(O.TRANSPORT_FAILURE,"URL 构造失败")}$n(T);let I;if(!c)I={};else{let S;try{S=t.secretProvider.resolve(a.credentialRef??"",g)}catch(P){throw P instanceof x&&P.code===O.CREDENTIAL_REF_MISSING?P:new x(O.TRANSPORT_FAILURE,`凭证解析失败:${P.message}`)}try{I=c.apply({method:R,url:T,body:y.body,credential:S,headers:y.extraHeaders})}catch{throw Z(f,e,r,s),new x(O.TRANSPORT_FAILURE,"认证参数构造失败")}}let A=m==="body"&&(R==="POST"||R==="PUT");if((m==="query"||m==="body"&&!A)&&Object.keys(I).length>0)try{let S=new URL(T);for(let[P,he]of Object.entries(I))S.searchParams.set(P,he);T=S.toString()}catch{throw Z(f,e,r,s),new x(O.TRANSPORT_FAILURE,"认证 query 追加失败")}let M={"content-type":"application/json","x-trace-id":Dn(),...m==="header"?I:{},...y.extraHeaders},C=y.body;A&&Object.keys(I).length>0&&(C={...y.body&&typeof y.body=="object"&&!Array.isArray(y.body)?y.body:{},...I});let _=Math.min(y.timeoutMs??o,o),z=new AbortController,gr=setTimeout(()=>z.abort(),_),qe=R==="GET"||C===void 0?void 0:JSON.stringify(C);t.logger?.debug("[transport] 最终请求",JSON.stringify({method:R,url:T,body:qe?JSON.parse(qe):null,headers:Object.fromEntries(Object.entries(M).map(([S,P])=>S.toLowerCase()==="token"||S.toLowerCase()==="authorization"||S.toLowerCase()==="visitortoken"?[S,typeof P=="string"?`${P.slice(0,20)}...(len=${P.length})`:P]:[S,P]))}));try{let S=await fetch(T,{method:R,headers:M,body:qe,signal:z.signal}),P=S.status>=500||S.status===429;if(!S.ok&&!P)throw new x(O.TRANSPORT_FAILURE,`HTTP ${S.status}`);if(P)throw Z(f,e,r,s),new x(O.TRANSPORT_FAILURE,`HTTP ${S.status}`);let he=Number(S.headers.get("content-length")??0);if(he>n)throw new x(O.RESPONSE_TOO_LARGE,`响应超限:${he}B > ${n}B`);let je=S.body?.getReader(),V;if(je){let At=[],wt=0;for(;;){let{done:fr,value:Et}=await je.read();if(fr)break;if(wt+=Et.byteLength,wt>n)throw await je.cancel(),new x(O.RESPONSE_TOO_LARGE,`响应超限:>${n}B`);At.push(new TextDecoder().decode(Et))}V=At.join("")}else if(V=await S.text(),V.length>n)throw new x(O.RESPONSE_TOO_LARGE,`响应超限:${V.length}B > ${n}B`);f.failures=0;try{return JSON.parse(V)}catch{return V}}catch(S){throw S instanceof x?S:S instanceof DOMException&&S.name==="AbortError"?(Z(f,e,r,s),new x(O.TRANSPORT_FAILURE,`超时 ${_}ms`)):(Z(f,e,r,s),new x(O.TRANSPORT_FAILURE,`网络错误:${S.message}`))}finally{clearTimeout(gr)}}}}}}function Z(t,e,r,n){t.failures+=1,t.failures>=e&&(t.openedAt=n())}function Ln(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 $n(t){let e=new URL(t);if(e.protocol!=="https:"&&!((e.hostname==="127.0.0.1"||e.hostname==="localhost")&&e.protocol==="http:"))throw new x(O.TRANSPORT_FAILURE,`强制 HTTPS:${e.protocol}`)}import{buildSupplyLookup as Fn,PROVIDER_ERROR_CODES as ee,resolveEffectiveService as ir,stableSerializeScope as qn}from"@tbox.cn/app-contracts";var Ke=new Map;function Un(t,e){process.env.NODE_ENV!=="production"&&Ke.set(t,e)}function Kn(){Ke.clear()}function or(t){return Ke.has(t)}function sr(t,e){let r=Ke.get(t);if(!r)throw new Error(`无 dev fixture:${t}`);return r(e)}function Hn(t){let e={async request(n){let o=r;if(!o)throw new Error("fixture transport 未绑定实例");return sr(o.providerTemplateId,n)}},r;return{create(n,o){return or(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 ar=(t,e)=>`${t}\0${e}`,jn={identity:{userId:"",source:"anonymous"},credentials:{provider:"anonymous",token:""},attributes:{}},Bn=Object.freeze({});function Gn(t){let e=new Map,r=new Map,n=t.transportFactory??xt({strategies:t.authStrategies,secretProvider:t.secretProvider,logger:t.logger}),o=t.instanceIdOf??(d=>qn(d)),s=Fn(t.catalog),i=Bn,a=d=>typeof d=="string"?d:`${d.provider}(inline)`,u=(d,c,l,p)=>{if(typeof d=="string"){let g=t.catalog.providers[d]?.[c];if(!g)throw new x(ee.PROVIDER_NOT_FOUND,`provider 未命中 catalog:${d}/${c}(${l}@${p})`);return{provider:d,implementation:c,entry:g,inline:void 0}}return{provider:d.provider,implementation:"inline",entry:void 0,inline:d}};function f(d){let c=o(d.scope),l=ir(t.integrations,d.service,c,s,t.ownerOf);if(l.status==="service-not-configured")throw new x(ee.SERVICE_NOT_CONFIGURED,`服务槽未配置:${d.service}(integrations.services 缺键)`);if(l.status==="instance-not-found")throw new x(ee.INSTANCE_NOT_FOUND,`无匹配实例:${d.service}@${c}(instances 缺键)`);if(l.status==="instance-disabled")throw new x(ee.INSTANCE_DISABLED,`实例已禁用:${d.service}@${c}`);if(l.status==="binding-unresolved")throw new x(ee.BINDING_UNRESOLVED,l.message);let p=l.effective,g=u(p.provider,p.implementation,d.service,c),m=g.entry?.local===!0,y;if(m)y=Tt();else{let R=`${d.service}\0${c}\0${g.provider}\0${g.implementation}`;y=r.get(R)??(()=>{let T={providerInstanceId:`${d.service}:${c}:${g.provider}:${g.implementation}`,providerTemplateId:g.implementation,scope:d.scope,config:p.config,...p.credentialRef?{credentialRef:p.credentialRef}:{},enabled:!0},I={providerTemplateId:g.implementation,credentialType:g.entry?.credentialType??g.inline?.credentialType??"-"},A=n.create(T,I);return r.set(R,A),A})()}return{transport:y,local:m,config:p.config,credentialRef:p.credentialRef,provider:g.provider,implementation:g.implementation,providerDisplay:a(p.provider),instanceId:c}}return{registerAdapter(d,c,l){let p=ar(d,c);e.has(p)&&t.logger?.warn(`adapter 重复注册(后者覆盖):${d}/${c}`),e.set(p,l)},listAdapters(){return[...e.keys()]},declareProviderInstances(d,c){if(c.length!==0){for(let l of c)if(typeof l.id!="string"||!l.id||l.id==="*"||typeof l.name!="string"||!l.name)throw new Error(`declareProviderInstances 非法实例(provider=${d}):id 禁空与 '*'(通配保留字),name 须非空 string`);i[d]!==void 0&&t.logger?.warn(`provider instances 重复声明(后者覆盖):${d}`),i=Object.freeze({...i,[d]:Object.freeze(c.map(l=>Object.freeze({...l})))})}},providerInstanceDeclarations(){return i},async resolveService(d){let c=f(d),l=e.get(ar(c.provider,c.implementation));if(!l)throw new x(ee.PROVIDER_NOT_IMPLEMENTED,`provider 未实施(无 adapter 注册):${c.providerDisplay}/${c.implementation}(${d.service}@${c.instanceId});实施指引见 packages/provider-custom/INTEGRATION.md`);return l({transport:Se(c.local?void 0:t.logger,c.transport),config:c.config??{},...c.credentialRef?{credentialRef:c.credentialRef}:{},...c.credentialRef?{credential:()=>t.secretProvider.resolve(c.credentialRef,d.scope)}:{},scope:d.scope,instanceId:c.instanceId,request:d.request,service:d.service})},async resolveLoginExchange(d){let c=f({...d,request:jn});return{transport:Se(c.local?void 0:t.logger,c.transport),config:c.config??{},providerId:c.implementation}},hasProviderBinding(d,c,l,p){let g=o(c),m=ir(t.integrations,d,g,s,t.ownerOf);if(m.status!=="ok")return!1;let y=m.effective;return typeof y.provider=="string"&&y.provider===l&&y.implementation===p},raw:{config:t.integrations,...t.source?{source:t.source}:{}}}}import{loadProviderCatalog as zn,buildOwnershipMap as Vn}from"@tbox.cn/app-toolkit";import{EventType as cr}from"@ag-ui/core";import{TBOX_CARD_UPDATE_EVENT_NAME as Yn,TBOX_NOTICE_EVENT_NAME as Jn}from"@tbox.cn/app-contracts";var Wn=h("CARD");function Xn(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 He(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({...Xn(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){Wn.warn(`动作 token 签发失败(跳过):${n.actionId}`,o.message)}return{...t.payload,actions:e.map(({singleUse:n,...o})=>o),...Object.keys(r).length>0?{actionTokens:r}:{}}}var Qn=600*1e3;function Zn(t){return t.type==="payment"||t.type==="authorization.alipay-user-profile"}function eo(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 to(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 E("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,u=[];try{if(i.cardType!==n.cardType)throw new E("GRANT_INVALID","授权 cardType 与动作声明不一致");let d=r.formData&&typeof r.formData=="object"&&!Array.isArray(r.formData)?r.formData:{},c=i.input&&typeof i.input=="object"&&!Array.isArray(i.input)?{...d,...i.input}:d,l=c;if(n.inputSchema){let g=n.inputSchema.safeParse(c);if(!g.success)throw new E("INPUT_INVALID",`入参校验失败:${g.error.message}`);l=g.data}if(!n.execute)throw new E("GRANT_INVALID",`动作无服务端执行体(纯客户端 kind 不应进 dispatch):${r.actionId}`);if(a=await n.execute(l,r.ctx),!a||typeof a!="object")throw new E("RESULT_INVALID","动作结果形状非法");for(let g of a.effects??[]){let m=g;if(m&&Zn(m)){let y=e.get(m.resultActionId);if(!y)throw new E("CALLBACK_INVALID",`效果回调动作未注册:${m.resultActionId}`);if(y.moduleId!==i.moduleId)throw new E("CALLBACK_INVALID",`效果回调动作组件归属不一致:${m.resultActionId}`);if(y.cardType!==n.cardType)throw new E("CALLBACK_INVALID",`效果回调动作 cardType 与当前动作不一致:${m.resultActionId}`);if(y.singleUse!==!0)throw new E("CALLBACK_INVALID",`效果回调动作必须 singleUse:${m.resultActionId}`);m.callback={actionId:y.actionId,contextToken:await t.grants.issue({moduleId:i.moduleId,actionId:y.actionId,cardType:n.cardType,sessionId:s.sessionId,scope:s.scopeFlat,singleUse:!0,ttlMs:Qn,input:{...m.type==="payment"?{paymentRef:m.paymentRef}:{},...r.surfaceId?{surfaceId:r.surfaceId}:{}}})}}}u=t.effects.project(a);let p=eo(r.surfaceId,i.input);if(a.update){if(a.card)throw new E("RESULT_INVALID","card 与 update 互斥");if(!p)throw new E("RESULT_INVALID","原地更新需要来源卡 surfaceId");let m=new Y(t.cardRegistry).build({cardType:n.cardType,data:a.update.data,conversationId:"",id:p});if(!m||m.status==="error")throw new E("RESULT_INVALID",`更新数据未通过 ${n.cardType} dataSchema 校验`);let y=await He({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat}),R={...y,meta:{...y.meta,updatedAt:Date.now()}};r.emit({type:cr.CUSTOM,name:Yn,value:R})}else if(a.card){let g=new Y(t.cardRegistry),m=g.build({cardType:a.card.cardType,data:a.card.data,conversationId:""});if(m){let y=await He({payload:m,actions:t.actions,grants:t.grants,sessionId:s.sessionId,scope:s.scopeFlat});g.send(y,r.emit)}}}catch(d){throw n.singleUse&&await t.grants.restore(r.token),d}let f=typeof a.text=="string"?a.text.trim():"";f&&r.emit({type:cr.CUSTOM,name:Jn,value:{level:"info",text:Ue(f),surfaceId:r.surfaceId||void 0}});for(let d of u)r.emit(d);return a}}}import{TBOX_EFFECT_EVENT_NAME as ro}from"@tbox.cn/app-contracts";var j=class extends Error{constructor(e){super(e),this.name="EffectError"}},no=new Set(["navigation.open","payment","share","download","authorization.alipay-user-profile","session.credentials-refreshed"]);function oo(t){if(t.type==="payment"){if(!t.paymentRef||!t.orderInfo||!t.resultActionId)throw new j("payment 效果缺少 paymentRef/orderInfo/resultActionId")}else if(t.type==="authorization.alipay-user-profile"&&(!t.resultActionId||t.scopes.length===0))throw new j("authorization 效果缺少 resultActionId/scopes")}function so(t={}){return{project(e){let r=[];for(let n of e.effects??[]){let o=n;if(!o||typeof o.type!="string"||!no.has(o.type))throw new j(`未知宿主效果类型:${String(o?.type)}`);if(o.type==="navigation.open"){if(t.routeWhitelist&&!t.routeWhitelist.has(o.routeId))throw new j(`导航路由不在白名单:${o.routeId}`)}else oo(o);r.push({type:"CUSTOM",name:ro,value:o})}return r}}}var ye=class extends Error{constructor(r,n){super(n);this.code=r;this.name="KnowledgeError"}code};function io(t={}){let e=t.apiKey??process.env.TBOX_API_KEY;if(!e)throw new ye("MISSING_CREDENTIAL","TBOX_API_KEY 未配置");let r=new fe({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 ye("API_ERROR",`知识库检索失败:${o.message}`)}}}}var K=class extends Error{constructor(r,n){super(n);this.code=r;this.name="PaymentError"}code};function ao(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 ud,assertNoInlineSecrets as pd}from"@tbox.cn/app-contracts";import{createSign as co,createVerify as uo}from"crypto";var po="https://openapi.alipay.com/gateway.do";function lo(t=process.env,e=fetch){function r(){let i=t.ALIPAY_APP_ID?.trim(),a=t.ALIPAY_APP_PRIVATE_KEY?.trim(),u=t.ALIPAY_PUBLIC_KEY?.trim();if(!i||!a||!u)throw new Error("AUTH_NOT_CONFIGURED: Alipay user authorization is unavailable");return Object.freeze({appId:i,privateKey:a,publicKey:u})}async function n(i,a){let{appId:u,privateKey:f}=r(),d={app_id:u,method:i,charset:"utf-8",sign_type:"RSA2",timestamp:dr(new Date),version:"1.0",...a};d.sign=go(d,f);let c=await e(po,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"},body:new URLSearchParams(d).toString(),signal:AbortSignal.timeout(1e4)});if(!c.ok)throw new Error(`ALIPAY_API_ERROR: HTTP ${c.status}`);let l=await c.text();try{return JSON.parse(l)}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 u=a,f=N(u.sub_msg)??N(u.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 u=a.alipay_system_oauth_token_response;if(!u||typeof u!="object"||Array.isArray(u))throw new Error("INVALID_CODE: no token response");return u}return Object.freeze({async authorizeUserProfile(i){let{publicKey:a}=r(),u=await s(i),f=N(u.access_token);if(!f)throw new Error("INVALID_CODE: no access_token in response");let d=await n("alipay.user.info.share",{auth_token:f});o(d);let c=d.alipay_user_info_share_response,l=N(d.sign);if(!c||typeof c!="object"||Array.isArray(c)||!l)throw new Error("ALIPAY_API_ERROR: incomplete authorized profile response");let p=uo("RSA-SHA256");if(p.update(JSON.stringify(c),"utf8"),!p.verify(St(a,"PUBLIC"),l,"base64"))throw new Error("ALIPAY_API_ERROR: profile response signature is invalid");let g=c,m=N(g.user_id)??N(g.open_id)??N(u.user_id)??N(u.open_id);if(!m)throw new Error("ALIPAY_API_ERROR: authorized user id is missing");let y=N(g.mobile),R=N(g.nick_name)??N(g.nickName),T=N(g.avatar),I=T?.startsWith("https://")?T:void 0,A=fo(g.gender),v=N(g.birthday);return Object.freeze({userId:m,...y?{mobile:y}:{},...R?{displayName:R}:{},...I?{avatarUrl:I}:{},...A?{gender:A}:{},...v?{birthday:v}:{}})}})}function dr(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}
|
|
5
|
-
-----END ${e} KEY-----`}function
|
|
5
|
+
-----END ${e} KEY-----`}function ur(t,e){let r=Object.keys(t).filter(o=>o!=="sign").sort().map(o=>`${o}=${t[o]}`).join("&"),n=co("RSA-SHA256");return n.update(r,"utf8"),n.sign(St(e,"PRIVATE"),"base64")}function go(t,e){return ur(t,e)}function N(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function fo(t){let e=N(t)?.toLowerCase();if(e)return e==="m"||e==="1"||e==="male"?"male":e==="f"||e==="2"||e==="female"?"female":"unknown"}var mo=h("AUTH");function It(t=process.env){let e=Le(t),r,n;if(!e)throw w.missingSecret("AUTH_TOKEN_SECRET 未配置(prod 禁用回退)。请由平台注入 AUTH_TOKEN_SECRET(≥32 字节随机串)。");r=e.secret,n=e.source==="explicit"?"platform":e.source,n!=="platform"&&mo.warn(`JWT 密钥回退至 ${n}(${n==="apiKey"?"TBOX_API_KEY":"dev 临时随机"})。生产请配置平台托管 AUTH_TOKEN_SECRET;回退模式下平台运维可伪 token。`);let o=t.AUTH_MODE==="optional"?"optional":"required";return{secret:r,secretSource:n,mode:o,issuer:t.AUTH_TOKEN_ISSUER||void 0,ttlMs:t.AUTH_TOKEN_TTL_MS?Number(t.AUTH_TOKEN_TTL_MS):void 0,embedExternalToken:t.AUTH_EMBED_EXTERNAL_TOKEN!=="false",externalTokenMaxBytes:t.AUTH_EXTERNAL_TOKEN_MAX_BYTES?Number(t.AUTH_EXTERNAL_TOKEN_MAX_BYTES):void 0}}function vt(t){return ht({secret:t.secret,issuer:t.issuer,ttlMs:t.ttlMs,embedExternalToken:t.embedExternalToken,...t.externalTokenMaxBytes?{maxExternalTokenBytes:t.externalTokenMaxBytes}:{}})}import{createHash as So,randomBytes as Io}from"crypto";import{Router as vo}from"express";import{createSign as yo}from"crypto";var Fe=h("AUTH:EXT"),ho=h("AUTH");async function pr(t,e,r){Fe.info(`→ ${t}`);let n=Date.now();try{let o=await fetch(e,r),s=await o.json(),i=Date.now()-n,a=`← ${t} durMs=${i} status=${o.status}`;return i>te?Fe.warn(`SLOW ${a}`):Fe.info(a),s}catch(o){let s=Date.now()-n;throw Fe.warn(`← ${t} durMs=${s} err=${o?.message??String(o)}`),o}}var B=class{provider="weapp";allowsGuestLogin(){return!0}async exchangeByCode({code:e}){let r=process.env.WX_APP_ID,n=process.env.WX_APP_SECRET;if(!r||!n)throw new Error("AUTH_NOT_CONFIGURED: WX_APP_ID or WX_APP_SECRET missing");let o=`https://api.weixin.qq.com/sns/jscode2session?appid=${encodeURIComponent(r)}&secret=${encodeURIComponent(n)}&js_code=${encodeURIComponent(e)}&grant_type=authorization_code`,s=await pr("weapp:jscode2session",o);if(s.errcode)throw new Error(`INVALID_CODE: ${s.errmsg||"unknown error"}`);if(!s.openid)throw new Error("INVALID_CODE: no openid in response");return{identity:{userId:`local_${s.openid}`,source:"local"}}}},G=class{provider="alipay";allowsGuestLogin(){return!0}async exchangeByCode({code:e}){let r=process.env.ALIPAY_APP_ID,n=process.env.ALIPAY_APP_PRIVATE_KEY;if(!r||!n)throw new Error("AUTH_NOT_CONFIGURED: ALIPAY_APP_ID or ALIPAY_APP_PRIVATE_KEY missing");let o={app_id:r,method:"alipay.system.oauth.token",charset:"utf-8",sign_type:"RSA2",timestamp:Ro(new Date),version:"1.0",grant_type:"authorization_code",code:e};o.sign=To(o,n);let s=Object.entries(o).map(([c,l])=>`${encodeURIComponent(c)}=${encodeURIComponent(l)}`).join("&"),i=await pr("alipay:oauth-token","https://openapi.alipay.com/gateway.do",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"},body:s}),a=i.error_response;if(a){ho.info("Alipay API error:",a.code,a.msg,a.sub_msg);let c=a.sub_msg||a.msg;throw new Error(`INVALID_CODE: ${c}`)}let u=i.alipay_system_oauth_token_response,f=u?.user_id||u?.open_id;if(!f)throw new Error("INVALID_CODE: no user_id in response");return{identity:{userId:`local_${f}`,source:"local"}}}};function Ro(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 xo(t){let e=t.replace(/\s+/g,"");return e.startsWith("-----")?t.replace(/\\n/g,`
|
|
6
6
|
`):`-----BEGIN RSA PRIVATE KEY-----
|
|
7
7
|
${e.match(/.{1,64}/g).join(`
|
|
8
8
|
`)}
|
|
9
|
-
-----END RSA PRIVATE KEY-----`}function
|
|
9
|
+
-----END RSA PRIVATE KEY-----`}function To(t,e){let r=Object.keys(t).filter(o=>o!=="sign").sort().map(o=>`${o}=${t[o]}`).join("&"),n=yo("RSA-SHA256");return n.update(r,"utf-8"),n.sign(xo(e),"base64")}var $=h("AUTH");function Ao(){return`guest_${Io(16).toString("hex")}`}function wo(t){return{userId:`mock_${So("sha256").update(`${t.provider}:${t.token}`).digest("hex").slice(0,24)}`,source:"external"}}function lr(t){let e=vo(),r=t.exchanges??q({alipay:new G,weapp:new B,...t.localExchanges});if(t.exchanges&&t.localExchanges)for(let o of Object.values(t.localExchanges))r.register(o);let n=async o=>{if(!(!o||typeof o!="string"))try{let s=await t.tokenService.verifyIgnoringExpiration(o);if(s.iat<=0){$.warn("previousToken 缺 iat,拒绝续签(fail-closed)");return}if(Date.now()-s.iat>nr){$.warn("previousToken 超出重签窗(30d),按缺席处理");return}return{userId:s.sub,source:s.source}}catch(s){$.warn("previousToken 解析失败(fail-soft 按缺席处理):",s.message);return}};return e.post("/login",async(o,s)=>{let{method:i,code:a,platform:u,context:f,previousToken:d}=o.body??{};if(i!=="code"&&i!=="browser"){s.status(400).json({error:"method is required and must be 'code' or 'browser'",code:"AUTH_METHOD_REQUIRED"});return}let c=de(f),l=await n(d),p=async()=>{let M={userId:l?.source==="guest"?l.userId:Ao(),source:"guest"},C=await t.tokenService.issue(M);s.json({token:C.token,identity:M,expiresAt:C.expiresAt})};if(i==="code"){if(!a||typeof a!="string"){s.status(400).json({error:"code is required"});return}let v=typeof u=="string"&&u?u:"alipay",M=r.get(v,c);if(!M){s.status(400).json({error:`unsupported platform: ${u}`});return}try{let C=await M.exchangeByCode({code:a,...typeof u=="string"&&u?{platform:u}:{},context:c,...l?{previousIdentity:l}:{}}),_=await t.tokenService.issue(C.identity,{...C.credentials?{external:C.credentials}:{}});s.json({token:_.token,identity:C.identity,expiresAt:_.expiresAt})}catch(C){let _=C.message??"unknown";if($.warn("login failed:",u,_),_.startsWith("INVALID_CODE")||_.startsWith("EXTERNAL_RESPONSE_INVALID")){s.status(401).json({error:_,code:"AUTH_UNAUTHORIZED"});return}if(_.startsWith("AUTH_SCOPE_REQUIRED")){s.status(503).json({error:_,code:"AUTH_SCOPE_REQUIRED"});return}if(_.startsWith("AUTH_NOT_CONFIGURED")){let z=!1;if(typeof M?.allowsGuestLogin=="function")try{z=M.allowsGuestLogin(c)===!0}catch{z=!1}if(z){$.warn(`login failed (downgraded to guest): ${_}`),await p();return}s.status(503).json({error:_,code:"AUTH_NOT_CONFIGURED"});return}$.error("login error:",_),s.status(502).json({error:"platform exchange error",code:"AUTH_EXTERNAL_ERROR"})}return}let g=r.get("alipay",c),m=process.env.NODE_ENV==="production",y="auto";if(typeof g?.browserLoginMode=="function")try{let v=g.browserLoginMode(c);(v==="guest"||v==="mock"||v==="off")&&(y=v)}catch(v){$.warn(`browserLoginMode 能力口违约(provider=${g?.provider??"none"},视为 auto):`,v.message)}if(y==="off"){s.status(403).json({error:"browser login disabled",code:"AUTH_BROWSER_LOGIN_DISABLED"});return}let R=async()=>{if(typeof g?.mockCredentials=="function")try{return await g.mockCredentials(c)}catch(v){$.warn(`mockCredentials 能力口违约抛异常(provider=${g.provider},视为无物料):`,v.message);return}},T=async v=>{if(m){s.status(403).json({error:"mock login disabled in production",code:"AUTH_BROWSER_LOGIN_DISABLED"});return}let M=wo(v),C=await t.tokenService.issue(M,{external:v});s.json({token:C.token,identity:M,expiresAt:C.expiresAt})};if(y==="guest"){await p();return}if(y==="mock"){let v=await R();if(!v){s.status(503).json({error:"AUTH_NOT_CONFIGURED: 显式 mock 档未配置登录物料(查登录槽 config mockCredentials 能力口)",code:"AUTH_NOT_CONFIGURED"});return}await T(v);return}let I=!1;if(typeof g?.allowsGuestLogin=="function")try{I=g.allowsGuestLogin(c)===!0}catch(v){$.warn(`allowsGuestLogin 能力口违约(provider=${g.provider},视为 false):`,v.message)}if(I){await p();return}let A=await R();if(A&&!m){await T(A);return}s.status(403).json({error:"browser login disabled",code:"AUTH_BROWSER_LOGIN_DISABLED"})}),e.get("/me",(o,s)=>{let i=X(o);if(!i){s.status(401).json({error:"unauthorized",code:"AUTH_UNAUTHORIZED"});return}s.json({identity:i.identity})}),e}function Eo(t,e){let r=t&&"secret"in t&&"mode"in t?t:It(t),n=vt(r),o=et(n,{mode:r.mode,publicPaths:["/api/auth/login","/api/health"],...e?.validateContext?{validateContext:e.validateContext}:{}}),s=q({alipay:new G,weapp:new B,...e?.exchanges}),i=lr({tokenService:n,exchanges:s}),a=Rt(n,{mode:r.mode});return{config:r,tokenService:n,middleware:o,router:i,wsAuth:a,exchanges:s}}export{$e as ACTION_GRANT_MAX_TTL_MS,k as ActionGrantError,se as ApiRouteRegistry,w as AuthError,Mt as CONTEXT_ENVELOPE_MAX_BYTES,Y as CardEmitter,oe as CardRegistry,ie as DomainAssemblyRegistry,te as EXTERNAL_SLOW_MS,j as EffectError,re as HandlerRegistry,ue as InMemoryCardSnapshotStore,ae as InMemoryIdempotencyStore,rt as InMemoryLruReplayStore,sn as KNOWLEDGE_PLACEHOLDER_DATASET_IDS,ye as KnowledgeError,G as LocalAlipayExchange,B as LocalWeappExchange,E as ModuleActionError,yt as NOTICE_TEXT_MAX_LEN,it as NO_CREDENTIAL_TYPE,K as PaymentError,le as PreToolRegistry,x as ProviderError,Yr as SKILL_LIMITS,nt as SKILL_NAME_PATTERN,zt as STATIC_HEADERS_CREDENTIAL_TYPE,Q as ScopeSessionError,W as ServiceRegistry,pe as SkillRegistry,mt as TTS_DEFAULTS,J as TboxAppClient,Me as TboxAsrClient,ke as TboxConversationClient,De as TboxFeedbackClient,Ne as TboxPluginClient,Oe as TboxTtsClient,Pe as TboxUploadClient,ne as ToolRegistry,pd as assertNoInlineSecrets,He as attachCardActionTokens,Vn as buildOwnershipMap,Kn as clearDevProviderFixtures,br as clearServices,Ir as collectIntentRoutes,tt as createActionGateway,Sn as createActionGrantService,lo as createAlipayUserAuthorization,Ye as createAnonymousIdentity,q as createAuthExchangeRegistry,et as createAuthMiddleware,Eo as createAuthRuntime,at as createAuthStrategyRegistry,xt as createAuthenticatedTransportFactory,so as createEffectRuntime,Mn as createEnvironmentSecretProvider,Hn as createFixtureTransportFactory,st as createInMemoryStateStore,Tt as createInMemoryTransport,Gn as createIntegrationsRegistry,io as createKnowledgeClient,zc as createLogger,to as createModuleActionDispatcher,lt as createModuleResourceResolver,ao as createPaymentClient,kn as createScopeSessionRegistry,tn as createServerContext,h as createServerLogger,ht as createTokenService,vt as createTokenServiceFromConfig,We as createTypedBus,Rt as createWsAuthenticator,jr as currentSofaTraceId,tr as deriveActionGrantKey,qr as enterSofaTraceRootScope,ct as expandEnvVars,dr as formatAlipayTimestamp,X as getRequestContext,or as hasDevProviderFixture,Xe as hashPayload,Zr as hashStateRef,Qe as inheritSofaTraceScope,ut as loadKnowledgeRegistry,zn as loadProviderCatalog,Ze as nextSofaTraceHeaders,de as normalizeContextEnvelope,ud as parseIntegrationsConfig,It as readAuthConfig,Sr as recordCall,Un as registerDevProviderFixture,un as registerServerModules,wr as registerService,ce as resolveBearerAuth,Er as resolveService,sr as runDevProviderFixture,L as runLogScope,xr as runWithLogContext,qt as setRequestContext,Tr as setServerSpanSink,ur as signAlipayParams,Vt as staticHeadersStrategy,In as toNoticeText,St as toPem,Ue as truncateNoticeText,Se as withCallLog};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-sdk-server",
|
|
3
|
-
"version": "0.26.
|
|
3
|
+
"version": "0.26.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"tbox-inspector-check": "bin/check-inspector.mjs"
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
"./platform": {
|
|
19
19
|
"types": "./dist/platform/index.d.ts",
|
|
20
20
|
"import": "./dist/platform/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./config": {
|
|
23
|
+
"types": "./dist/config.d.ts",
|
|
24
|
+
"import": "./dist/config.js"
|
|
21
25
|
}
|
|
22
26
|
},
|
|
23
27
|
"files": [
|
|
@@ -39,7 +43,7 @@
|
|
|
39
43
|
"express": "4.22.2",
|
|
40
44
|
"jose": "6.2.8",
|
|
41
45
|
"zod": "3.25.76",
|
|
42
|
-
"@tbox.cn/app-toolkit": "0.8.
|
|
46
|
+
"@tbox.cn/app-toolkit": "0.8.5"
|
|
43
47
|
},
|
|
44
48
|
"devDependencies": {
|
|
45
49
|
"@mastra/core": "1.59.0",
|
|
@@ -52,8 +56,8 @@
|
|
|
52
56
|
"typescript": "5.9.3",
|
|
53
57
|
"vite": "6.4.3",
|
|
54
58
|
"vitest": "4.1.10",
|
|
55
|
-
"@tbox.cn/app-agent-sdk-server": "0.3.
|
|
56
|
-
"@tbox.cn/app-sdk-client": "0.21.
|
|
59
|
+
"@tbox.cn/app-agent-sdk-server": "0.3.4",
|
|
60
|
+
"@tbox.cn/app-sdk-client": "0.21.4"
|
|
57
61
|
},
|
|
58
62
|
"license": "MIT",
|
|
59
63
|
"scripts": {
|