@tbox.cn/app-template-agent 0.10.29 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.gitignore +6 -0
  2. package/.tbox/app.json +3 -19
  3. package/.tbox/default-modules.json +4 -1
  4. package/.tbox/miniapp-containers.json +1 -1
  5. package/AGENTS.md +52 -147
  6. package/README.md +11 -9
  7. package/apps/AGENTS.md +13 -0
  8. package/apps/client/.tbox-gen/app-kind.ts +1 -0
  9. package/apps/client/.tbox-gen/documents/_tbox/card-preview.html +38 -0
  10. package/apps/client/.tbox-gen/documents/index.html +39 -0
  11. package/apps/client/.tbox-gen/entries/card-preview.tsx +18 -0
  12. package/apps/client/.tbox-gen/entries/index.tsx +18 -0
  13. package/apps/client/.tbox-gen/manifest.json +17 -0
  14. package/apps/client/.tbox-gen/registry.client.ts +6 -0
  15. package/apps/client/.tbox-gen/registry.server.ts +15 -0
  16. package/apps/client/index.html +1 -1
  17. package/apps/client/package.json +3 -2
  18. package/apps/client/src/cards/registry.ts +6 -19
  19. package/apps/client/src/pages/page.tsx +11 -0
  20. package/apps/client/src/platform/AgentChatApp.tsx +2 -40
  21. package/apps/client/src/platform/AppShell.tsx +42 -0
  22. package/apps/client/src/platform/bootstrap.ts +55 -0
  23. package/apps/client/src/platform/card-preview-page.tsx +10 -0
  24. package/apps/client/src/platform/mount-page.tsx +20 -0
  25. package/apps/client/src/vite-env.d.ts +0 -3
  26. package/apps/client/tsconfig.json +10 -2
  27. package/apps/client/vite.config.ts +6 -10
  28. package/apps/server/package.json +1 -1
  29. package/apps/server/src/app.ts +18 -18
  30. package/apps/server/src/cli/collect-registry.ts +7 -11
  31. package/apps/server/src/dev.ts +47 -49
  32. package/apps/server/src/index.ts +28 -22
  33. package/apps/server/src/pre-tools.ts +1 -1
  34. package/apps/server/src/tools/{clock.ts → clock.tool.ts} +1 -1
  35. package/apps/server/src/tools/{translate.ts → translate.tool.ts} +1 -1
  36. package/apps/server/tests/cards-registry.test.ts +1 -1
  37. package/apps/server/tests/helpers/register.ts +10 -0
  38. package/apps/server/tests/tool-runtime.test.ts +2 -2
  39. package/apps/server/tsconfig.json +1 -1
  40. package/apps/server/tsup.config.ts +6 -3
  41. package/{packages → modules}/provider-custom/AGENTS.md +1 -1
  42. package/modules/provider-custom/INTEGRATION.md +10 -0
  43. package/{packages → modules}/provider-custom/package.json +1 -0
  44. package/package.json +11 -6
  45. package/packages/agent-ui-kit/package.json +1 -1
  46. package/packages/shared/AGENTS.md +11 -0
  47. package/packages/shared/package.json +13 -0
  48. package/packages/shared/src/index.ts +8 -0
  49. package/packages/shared/tsconfig.json +7 -0
  50. package/pnpm-lock.template.yaml +181 -179
  51. package/pnpm-workspace.template.yaml +10 -8
  52. package/scripts/generate.mjs +3 -0
  53. package/scripts/verify-generated.mjs +22 -127
  54. package/apps/client/src/app.tsx +0 -35
  55. package/apps/client/src/business/App.tsx +0 -11
  56. package/apps/client/src/business/README.md +0 -76
  57. package/apps/client/src/main.tsx +0 -54
  58. package/apps/client/src/modules.ts +0 -33
  59. package/apps/server/src/app-tools.ts +0 -14
  60. package/apps/server/src/modules.ts +0 -38
  61. /package/{packages → modules}/provider-custom/LICENSE +0 -0
  62. /package/{packages → modules}/provider-custom/README.md +0 -0
  63. /package/{packages → modules}/provider-custom/src/index.ts +0 -0
  64. /package/{packages → modules}/provider-custom/src/server/example-adapter.ts +0 -0
  65. /package/{packages → modules}/provider-custom/src/server/index.ts +0 -0
  66. /package/{packages → modules}/provider-custom/tbox.module.json +0 -0
  67. /package/{packages → modules}/provider-custom/tests/provider-custom.test.ts +0 -0
  68. /package/{packages → modules}/provider-custom/tsconfig.json +0 -0
  69. /package/{packages → modules}/provider-custom/tsup.config.ts +0 -0
@@ -1,44 +1,6 @@
1
- import { createLogger } from '@tbox.cn/app-agent-sdk-client';
2
-
3
- const appLogger = createLogger('AgentChatApp');
4
-
5
- import { useCallback, useEffect, useMemo, useState } from 'react';
6
- import { AdapterProvider, createPlatformAdapters, type AdapterContextValue } from '@tbox.cn/app-agent-sdk-client';
7
- import type { TboxSessionData } from '@tbox.cn/app-contracts';
8
1
  import IndexPage from '@/pages/index/index';
9
- import { authClient, platformApi } from './agent-runtime';
10
2
 
11
- /** 平台默认的全栈对话运行时。普通本地应用无需读取或修改。 */
3
+ /** 平台默认对话运行时;AppShell 由 mount-page 统一包裹。 */
12
4
  export default function AgentChatApp() {
13
- const [session, setSession] = useState<TboxSessionData | null>(null);
14
- // TTS 不依赖 session,恒可用且保持同一实例(播放状态不因会话刷新丢失)
15
- const tts = useMemo(() => createPlatformAdapters().tts, []);
16
-
17
- useEffect(() => {
18
- authClient
19
- .ensureAuth()
20
- // 会话 β 收口:身份恒取 token(服务端 401/403),userId 不再上行
21
- .then(() => platformApi.getTboxSession())
22
- .then(setSession)
23
- .catch((err) => appLogger.error('tbox session init failed:', err));
24
- }, []);
25
-
26
- const refreshSession = useCallback(async (): Promise<AdapterContextValue> => {
27
- platformApi.clearTboxSession();
28
- await authClient.refreshAuth();
29
- const data = await platformApi.getTboxSession(true);
30
- setSession(data);
31
- return { tts, ...createPlatformAdapters(data, { tts }), refreshSession };
32
- }, [tts]);
33
-
34
- const adapters = useMemo<AdapterContextValue>(() => {
35
- if (!session) return { tts, refreshSession };
36
- return { tts, ...createPlatformAdapters(session, { tts }), refreshSession };
37
- }, [session, tts, refreshSession]);
38
-
39
- return (
40
- <AdapterProvider value={adapters}>
41
- <IndexPage />
42
- </AdapterProvider>
43
- );
5
+ return <IndexPage />;
44
6
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 应用外壳(平台运行时供给层):session 引导 + 平台适配器(TTS 等)。
3
+ * 从 AgentChatApp 抽出的共享外壳——MPA 生成 entry(mount-page)与根 entry
4
+ * (AgentChatApp → BusinessApp)共用,保证任何页面的平台能力面一致。
5
+ */
6
+ import { useCallback, useEffect, useMemo, useState } from 'react';
7
+ import { AdapterProvider, createPlatformAdapters, type AdapterContextValue } from '@tbox.cn/app-agent-sdk-client';
8
+ import type { TboxSessionData } from '@tbox.cn/app-contracts';
9
+ import { authClient, platformApi } from './agent-runtime';
10
+ import { createLogger } from '@tbox.cn/app-agent-sdk-client';
11
+
12
+ const appLogger = createLogger('AppShell');
13
+
14
+ export function AppShell({ children }: { children: React.ReactNode }) {
15
+ const [session, setSession] = useState<TboxSessionData | null>(null);
16
+ // TTS 不依赖 session,恒可用且保持同一实例(播放状态不因会话刷新丢失)
17
+ const tts = useMemo(() => createPlatformAdapters().tts, []);
18
+
19
+ useEffect(() => {
20
+ authClient
21
+ .ensureAuth()
22
+ // 会话 β 收口:身份恒取 token(服务端 401/403),userId 不再上行
23
+ .then(() => platformApi.getTboxSession())
24
+ .then(setSession)
25
+ .catch((err: unknown) => appLogger.error('tbox session init failed:', err));
26
+ }, []);
27
+
28
+ const refreshSession = useCallback(async (): Promise<AdapterContextValue> => {
29
+ platformApi.clearTboxSession();
30
+ await authClient.refreshAuth();
31
+ const data = await platformApi.getTboxSession(true);
32
+ setSession(data);
33
+ return { tts, ...createPlatformAdapters(data, { tts }), refreshSession };
34
+ }, [tts]);
35
+
36
+ const adapters = useMemo<AdapterContextValue>(() => {
37
+ if (!session) return { tts, refreshSession };
38
+ return { tts, ...createPlatformAdapters(session, { tts }), refreshSession };
39
+ }, [session, tts, refreshSession]);
40
+
41
+ return <AdapterProvider value={adapters}>{children}</AdapterProvider>;
42
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 客户端启动层(单一职责:一次进程级初始化,幂等)。
3
+ * 消费方 = 根 entry(main.tsx)与全部生成 entry(.tbox-gen/<id>.ts 经 mount-page)——
4
+ * 两侧共享同一实现,保证任何文档入口的启动语义一致(主题/运行时/错误兜底/chat 配置快照)。
5
+ * 约束:只做同步可完成的初始化;@config 别名根除相对深度耦合(vite.config + tsconfig 同步接线)。
6
+ */
7
+ import { configureRuntime, createLogger, installGlobalErrorReporting } from '@tbox.cn/app-agent-sdk-client';
8
+ import { configureChatConfigDefaults } from '@app/agent-ui-kit';
9
+ import '@app/agent-ui-kit/theme/global.less';
10
+ // 品牌主题(出厂接线——theme-tbox 平台品牌资产包:素材/标题经本包承载,模块零品牌资产)。
11
+ // 换主题 = 替换三行(index.css + brand.js + applyTheme;叠加会致旧主题残留死重);
12
+ // 部署者轨迹见 cookbook·build-app-image「主题接线」。CLI 自由区,module sync 永不触碰。
13
+ import '@tbox.cn/app-theme-tbox/index.css';
14
+ import '@tbox.cn/app-theme-tbox/brand.js';
15
+ import { applyTheme } from '@app/agent-ui-kit/theme';
16
+ import chatConfigJson from '@config/chat.json';
17
+
18
+ const bootLogger = createLogger('BOOT');
19
+
20
+ let bootstrapped = false;
21
+
22
+ export function bootstrap(): void {
23
+ if (bootstrapped) return;
24
+ bootstrapped = true;
25
+
26
+ applyTheme('tbox');
27
+
28
+ // 壳→H5 接入契约观测:落页即打印 URL 参数(search + hash 双读源,全量加载仅一次)。
29
+ // 壳侧若把参数移进 hash,mall-scope-url 的 search-only 读源会静默失效——这里第一时间暴露。
30
+ // code/token 类值部分脱敏(前缀 + 长度,对齐 provider log-redact 惯例)。
31
+ const SENSITIVE_PARAM = /^(code|token|auth_code|visitortoken|session)$/i;
32
+ const collectParams = (source: string): Record<string, string> => {
33
+ const out: Record<string, string> = {};
34
+ new URLSearchParams(source).forEach((value, key) => {
35
+ out[key] = SENSITIVE_PARAM.test(key) ? `${value.slice(0, 6)}…(len=${value.length})` : value;
36
+ });
37
+ return out;
38
+ };
39
+ const hashQuery = window.location.hash.includes('?')
40
+ ? window.location.hash.slice(window.location.hash.indexOf('?') + 1)
41
+ : '';
42
+ bootLogger.info(
43
+ `url params: ${JSON.stringify({ search: collectParams(window.location.search), hash: collectParams(hashQuery) })}`,
44
+ );
45
+
46
+ // H1:环境值注入点(SDK 零 Vite 依赖)——VITE_API_URL 空串 = 同源相对路径
47
+ configureRuntime({ apiBaseUrl: import.meta.env.VITE_API_URL as string | undefined });
48
+
49
+ // 全局错误兜底:未捕获异常/rejection → 统一日志行(本地落地;上报扩展点见 SDK client logger)
50
+ installGlobalErrorReporting();
51
+
52
+ // chat.json 构建期快照 → kit 静态配置 store(render 前注入,首帧即快照值;
53
+ // HELLO_ACK settings 达后经 ChatPage 内水合覆盖)
54
+ configureChatConfigDefaults(chatConfigJson as Record<string, unknown>);
55
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * 卡片预览平台页:生成 entry 已注册模块/卡片,这里只读取同一 ClientContext。
3
+ */
4
+ import { CardPreviewPage } from '@tbox.cn/app-agent-sdk-client/client/card-preview';
5
+ import { getRegisteredClientCards } from '@tbox.cn/app-agent-sdk-client';
6
+ import { authClient } from '@/platform/agent-runtime';
7
+
8
+ export default function CardPreviewRoute() {
9
+ return <CardPreviewPage registry={getRegisteredClientCards()} authClient={authClient} />;
10
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 生成 entry 的页面挂载点(与生产 documents 同一入口)。
3
+ * bootstrap(幂等)+ AppShell(平台能力面)+ 页面组件;卡片预览传 shell:false。
4
+ */
5
+ import { StrictMode, type ComponentType } from 'react';
6
+ import { createRoot } from 'react-dom/client';
7
+ import { bootstrap } from './bootstrap';
8
+ import { AppShell } from './AppShell';
9
+
10
+ export function mountPage(Page: ComponentType, options: { shell?: boolean } = {}): void {
11
+ bootstrap();
12
+ const el = document.getElementById('root');
13
+ if (!el) return;
14
+ const content = options.shell === false ? <Page /> : (
15
+ <AppShell>
16
+ <Page />
17
+ </AppShell>
18
+ );
19
+ createRoot(el).render(<StrictMode>{content}</StrictMode>);
20
+ }
@@ -1,6 +1,3 @@
1
1
  /// <reference types="vite/client" />
2
2
 
3
3
  declare module 'postcss-pxtorem';
4
-
5
- // 卡片预览面三态编译常量(vite.config.ts define 注入;guard-dev-probe 断言声明在场)
6
- declare const __TBOX_CARD_PREVIEW__: boolean;
@@ -4,8 +4,16 @@
4
4
  "baseUrl": ".",
5
5
  "jsx": "react-jsx",
6
6
  "paths": {
7
- "@/*": ["src/*"]
7
+ "@/*": [
8
+ "src/*"
9
+ ],
10
+ "@config/*": [
11
+ "../../config/*"
12
+ ]
8
13
  }
9
14
  },
10
- "include": ["src", "vite.config.ts"]
15
+ "include": [
16
+ "src",
17
+ "vite.config.ts"
18
+ ]
11
19
  }
@@ -8,6 +8,7 @@ import { pathToFileURL } from 'node:url';
8
8
  // 平台微调配套 babel plugin(随 @tbox.cn/app-sdk 分发):给每个 JSX 注入 data-code-inspect-*
9
9
  // 源码位置属性,供 inspector runtime(/__vs_inspector__.js) 点选元素→定位源码。仅 dev 启用(见下)。
10
10
  import codeInspectPlugin from '@tbox.cn/app-agent-sdk-client/platform/code-inspect';
11
+ import { tboxAppPlugin } from '@tbox.cn/app-build';
11
12
 
12
13
  const pxToRemPlugin = pxToRem({
13
14
  rootValue: 100,
@@ -45,20 +46,18 @@ export default defineConfig(async ({ command }) => {
45
46
  }
46
47
  return {
47
48
  plugins: [
49
+ tboxAppPlugin({ root: resolve(__dirname, '../..') }),
48
50
  react({
49
51
  babel: { plugins: command === 'serve' ? [codeInspectPlugin] : [] },
50
52
  }),
51
53
  ...devPlugins,
52
54
  ],
53
- // 卡片预览面三态(方案 W):serve 恒 false(dev 面由 import.meta.env.DEV 放行);
54
- // build 无 TBOX_DEV_TOKEN → false(chunk 可摇除,生产零残留);build 有(沙箱 protected
55
- // watch 构建)→ true(static 面 /_tbox/card-preview 可达)。guard-dev-probe 断言本标记。
56
- define: {
57
- __TBOX_CARD_PREVIEW__: command === 'build' && !!process.env.TBOX_DEV_TOKEN ? 'true' : 'false',
58
- },
55
+ // 卡片预览面守卫已随 v6 统一文档形态退役(能力开关 = 平台文档/entry 生成与否)
59
56
  resolve: {
60
57
  alias: {
61
58
  '@': resolve(__dirname, 'src'),
59
+ // 应用配置面锚(chat.json 等):根除 src 层级相对路径深度耦合(bootstrap 消费)
60
+ '@config': resolve(__dirname, '../../config'),
62
61
  },
63
62
  // dev 域 React 单实例(G1/G2 防线):双 dev 入口经本文件合并生效(middleware
64
63
  // dev 加载本文件且 command==='serve');build 恒不继承——产物位稳定性。
@@ -76,9 +75,6 @@ export default defineConfig(async ({ command }) => {
76
75
  css: {
77
76
  postcss: { plugins: [pxToRemPlugin] },
78
77
  },
79
- build: {
80
- rollupOptions: { input: { index: resolve(__dirname, 'index.html') } },
81
- },
82
- // middlewareMode 下不需要 server 配置(由 server 端 vite middleware 托管)
78
+ // 构建输入由 tboxAppPlugin 按 .tbox-gen/manifest.json 注入(文档模式唯一真源)
83
79
  };
84
80
  });
@@ -11,13 +11,13 @@
11
11
  "typecheck": "tsc --noEmit"
12
12
  },
13
13
  "dependencies": {
14
+ "@app/shared": "file:../../packages/shared",
14
15
  "@tbox.cn/agent-plugin": "catalog:",
15
16
  "@tbox.cn/app-contracts": "catalog:",
16
17
  "@app/contracts-mall": "workspace:*",
17
18
  "@tbox-dev-js/sdk": "catalog:",
18
19
  "express": "catalog:",
19
20
  "zod": "catalog:",
20
- "@app/provider-custom": "workspace:*",
21
21
  "@tbox.cn/app-agent-sdk-server": "catalog:"
22
22
  },
23
23
  "devDependencies": {
@@ -3,13 +3,13 @@
3
3
  * 客户端供给由入口决定——静态产物见 index.ts(唯一 tsup entry),vite dev 见 dev.ts(仅 tsx)。
4
4
  * import 本模块即完成装配(与旧单文件入口时序等价:listen 仍在 start() 内最后发生)。
5
5
  */
6
- import express from 'express';
6
+ import express, { type Express } from 'express';
7
7
  import { createServer, type IncomingMessage } from 'http';
8
8
  import type { Duplex } from 'node:stream';
9
9
  import path from 'path';
10
10
  import { existsSync } from 'node:fs';
11
11
  import { fileURLToPath } from 'url';
12
- import { registerAll } from './modules.js';
12
+
13
13
  // ===== 模板日志(@tbox.cn/app-agent-sdk-server createLogger:本地时间 + LEVEL + [tag] + req/conv 尾缀) =====
14
14
  import { createLogger } from '@tbox.cn/app-agent-sdk-server';
15
15
  const serverLogger = createLogger('server');
@@ -48,7 +48,7 @@ import {
48
48
  installTboxDev,
49
49
  } from '@tbox.cn/app-agent-sdk-server';
50
50
  import { installInspector } from '@tbox.cn/app-agent-sdk-server/platform';
51
- import { registerAppTools } from './app-tools.js';
51
+
52
52
  import { APP_PRE_TOOLS } from './pre-tools.js';
53
53
  import { INTENT_ROUTES, createAppIntentDispatcher } from './intent-routes.js';
54
54
  import { loadIntegrations } from './config/integration.js';
@@ -264,7 +264,7 @@ if (!isProduction) {
264
264
  // authExchanges 同引用传递(provider 包 register 期自注册换码器)+ scopeDefaults 中立注入
265
265
  // scopeDefaults 静态注入退役——域装配(含 defaultMallId)经 registry 读取视图供给
266
266
  // (SDK ctx.scopeDefaults 惰性优先注册表 → provider getter 登录期求值)
267
- const ctx = createServerContext({
267
+ export const ctx = createServerContext({
268
268
  authStrategies,
269
269
  authExchanges: auth.exchanges,
270
270
  ...(memory.store ? { memory: memory.store } : {}),
@@ -305,8 +305,17 @@ app.get('/assets/deploy/:file', (req, res) => {
305
305
  // 017:装配记忆时挂载 /api/memory 管理面(与引擎同源 store)
306
306
  app.use('/api', createPlatformApiRouter({ ctx, auth, ...(memory.store ? { memory: memory.store } : {}) }));
307
307
 
308
- // tbox dev 工具族(/_tbox:卡片预览 API + 页面族;dev-only 自门控——NODE_ENV=production
309
- // 零挂载;import 期注册先于 dev.ts 运行期 vite middleware,路由序恒胜)
308
+ // tbox dev 工具族(/_tbox:卡片预览 API + 页面族)——dev 入口显式装配(幂等闭包):
309
+ // dev.ts 在 gate/final 挂载前调用 setupTboxDev()(/_tbox/api 路由序恒胜);静态入口
310
+ // (index.ts → dist/index.js)永不调用——生产零挂载不依赖 NODE_ENV 自觉(SDK 侧
311
+ // production 守卫保留为双保险)。
312
+ let tboxDevInstalled = false;
313
+ export function setupTboxDev(): void {
314
+ if (tboxDevInstalled) return;
315
+ tboxDevInstalled = true;
316
+ installTboxDev(app, { ctx, auth });
317
+ }
318
+
310
319
  // iframe 嵌入收紧(AI 构建面板 card-preview 预览):现状无该头 = 隐式全允许 → 显式三元组
311
320
  // (用户裁决 2026-09-13:不存在其他 origin 嵌入既有 demo,行为收紧确认;'self' + 生产域 + 本地面板 dev 端口)
312
321
  app.use((_req, res, next) => {
@@ -317,8 +326,6 @@ app.use((_req, res, next) => {
317
326
  next();
318
327
  });
319
328
 
320
- installTboxDev(app, { ctx, auth });
321
-
322
329
  // 从 ServerContext 构造 ChatEngine(自注册闭环组装端)
323
330
  async function createEngine(
324
331
  extra?: { cardActionAttacher: (payload: import('@tbox.cn/app-contracts').TboxCardPayload, sessionId: string) => Promise<import('@tbox.cn/app-contracts').TboxCardPayload> },
@@ -412,8 +419,6 @@ async function createEngine(
412
419
  return engine;
413
420
  }
414
421
 
415
- const httpServer = createServer(app);
416
-
417
422
  /** dev 态升级扩展点(dev.ts 注册):返回 true = 已认领,app 路由跳过。生产 bundle 恒空。 */
418
423
  export type UpgradeDelegate = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
419
424
  let upgradeDelegate: UpgradeDelegate | undefined;
@@ -421,15 +426,10 @@ export function registerUpgradeDelegate(delegate: UpgradeDelegate): void {
421
426
  upgradeDelegate = delegate;
422
427
  }
423
428
 
424
- export async function start() {
425
- // 注册业务模块(自注册闭环)——mall-directory 服务由 module-mall-core register 期注入
426
- await registerAll(ctx);
427
-
428
- // 模板演示工具(apps 级工具, 建议迁入模块):不参与模块体系,经统一注册面注册
429
- // (010:start() 与 cli/collect-registry.ts 双处同调,防注册面失同步)
430
- registerAppTools(ctx);
429
+ export async function start(serverApp: Express = app) {
430
+ const httpServer = createServer(serverApp);
431
431
 
432
- // 时序契约:域装配解析必须晚于 registerAll——module-mall-core 在 register 期经
432
+ // 时序契约:域装配解析必须晚于模块注册——module-mall-core 在 register 期经
433
433
  // ctx.domainAssemblies 注册装配;解析点置于 start() 头部会查空表(引入回归:
434
434
  // 默认商圈兜底/卡片动作授权/enhanceContext 全断——见 Agent Note 2026-09-17-mall-assembly-resolution-order)
435
435
  const assembly = mallAssembly();
@@ -1,7 +1,6 @@
1
- import { createServerContext } from '@tbox.cn/app-agent-sdk-server';
1
+ import { createServerContext, registerServerModules } from '@tbox.cn/app-agent-sdk-server';
2
2
  import type { ToolCardBinding } from '@tbox.cn/agent-plugin/cards';
3
- import { registerAll } from '../modules.js';
4
- import { registerAppTools } from '../app-tools.js';
3
+ import { registry } from '../../../client/.tbox-gen/registry.server';
5
4
 
6
5
  export interface RegistryState {
7
6
  staticToolIds: string[];
@@ -10,16 +9,13 @@ export interface RegistryState {
10
9
  bindings: ToolCardBinding[];
11
10
  }
12
11
 
13
- /**
14
- * 从自注册闭环收集当前注册状态(静态工具 id / cardType)。
15
- * 供 plugin-doctor / plugin-inspect 复用——替代已删除的手写 tools/registry.ts + cards/registry.ts。
16
- * 与运行时(apps/server/src/index.ts start())保持一致的注册面:registerAll + registerAppTools
17
- * (010:apps 级演示工具统一注册面,双处同调防失同步)。
18
- */
12
+ /** 从生成 registry 收集当前注册状态(与 createApp 同源)。 */
19
13
  export async function collectRegistryState(): Promise<RegistryState> {
20
14
  const ctx = createServerContext();
21
- await registerAll(ctx);
22
- registerAppTools(ctx); // 与运行时一致(translate + clock 为 apps 级演示工具)
15
+ for (const tool of registry.tools) ctx.tools.register(tool);
16
+ for (const skill of registry.skills) ctx.skills.register(skill);
17
+ for (const card of Object.values(registry.cards)) ctx.cards.register(card as never);
18
+ await registerServerModules(ctx, registry.modules);
23
19
  return {
24
20
  staticToolIds: Object.keys(ctx.tools.getAll()),
25
21
  cardTypes: Object.keys(ctx.cards.getAll()),
@@ -1,17 +1,11 @@
1
1
  /**
2
- * vite dev 入口(仅 tsx 运行:pnpm dev;物理不进 tsup bundle——forbid-vite 插件拦截)。
3
- * middlewareMode + 单端口:HTTP 与 HMR WS 全走应用端口(沙箱仅暴露一个端口亦可开发)。
4
- * 部署形态一律走 dist/index.js(静态产物,零 HMR WS)。
5
- *
6
- * 方案 W(沙箱 dev server 鉴权保护):TBOX_DEV_TOKEN 在场 → protected 双面裁决
7
- * (dev 面 = 凭据 + 导航/同源信号放行 vite;static 面 = 纯 dist + SSE 刷新,零源码泄漏);
8
- * 缺席 → classic,与历史行为字节级等价。裁决机制真源 = SDK platform/dev-runtime
9
- * (createTboxDevRuntime),本文件只做装配:vite 实例 + fs.allow 收窄 + 面无关自由区。
2
+ * vite dev 入口(仅 tsx 运行):import 即启动。
3
+ * 单端口:HTTP + HMR;页面由 dev-runtime 的 manifest 页集合交给 Vite/生成 entry。
10
4
  */
11
- import { createServer } from 'http';
12
- import path from 'path';
5
+ import { createServer } from 'node:http';
6
+ import path from 'node:path';
13
7
  import { existsSync } from 'node:fs';
14
- import { fileURLToPath } from 'url';
8
+ import { fileURLToPath } from 'node:url';
15
9
  import { build as viteBuild, createServer as createViteServer, searchForWorkspaceRoot } from 'vite';
16
10
  import {
17
11
  createTboxDevRuntime,
@@ -19,38 +13,39 @@ import {
19
13
  isReady,
20
14
  resolveDevTokenFromEnv,
21
15
  } from '@tbox.cn/app-agent-sdk-server/platform';
22
- import { createLogger } from '@tbox.cn/app-agent-sdk-server';
23
- import { app, registerUpgradeDelegate, start } from './app.js';
16
+ import { createApp, createLogger, getRequestContext } from '@tbox.cn/app-agent-sdk-server';
17
+ import { generateApp } from '@tbox.cn/app-build';
18
+ import { app as legacyApp, ctx, registerUpgradeDelegate, setupTboxDev, start } from './app.js';
24
19
 
25
20
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
21
  const serverLogger = createLogger('server');
22
+ const root = path.resolve(__dirname, '../../..');
27
23
  const clientRoot = path.resolve(__dirname, '../../client');
28
- const appRoot = path.resolve(__dirname, '../..');
29
24
 
30
- // HMR WS 独立路径:dev 基础设施命名空间(双下划线呼应 /@vite/*),与业务命名空间(/ws*)
31
- // 解耦——upgrade 认领只针对此路径,根路径归还业务路由。协议常量(vite-hmr/vite-ping)、
32
- // 认领路径 posix.join(base, hmr.path) 与 Spanner 子协议补写均内聚于 SDK handleUpgrade
33
- // (smoke-dev-hmr.sh 守护该契约面)。
34
- const HMR_WS_PATH = '/__vite_hmr';
25
+ if (process.env.NODE_ENV === 'production') {
26
+ serverLogger.error('dev 入口禁止 NODE_ENV=production——生产请使用 dist/index.js(pnpm start)');
27
+ process.exit(1);
28
+ }
35
29
 
36
- // HMR WS hub:永不 listen 的纯事件载体。hmr.server 在场 → vite 不自建独立端口,
37
- // 客户端按页面同源端口连接。vite 对 hub 仅 on/off('upgrade')(6.4.3 源码实证)。
38
- const hmrHub = createServer();
30
+ const generated = await generateApp({ root });
31
+ const [{ registry }, { appKind }] = await Promise.all([
32
+ import('../../client/.tbox-gen/registry.server.ts'),
33
+ import('../../client/.tbox-gen/app-kind.ts'),
34
+ ]);
39
35
 
36
+ const HMR_WS_PATH = '/__vite_hmr';
37
+ const hmrHub = createServer();
40
38
  const tokenState = resolveDevTokenFromEnv(process.env);
41
39
  const protectedMode = tokenState.mode === 'protected';
42
-
43
- // protected 面 fs.allow 收窄(classic 恒默认不传——红线):client 源 + 工作区依赖真源。
44
- // 模板原地装配(pnpm dev)时模块图经 workspace 链接解析到仓库 packages/,故并入
45
- // workspace 两目录(filter(existsSync):生成应用无此目录时自动滤除,不影响沙箱半径)。
46
40
  const workspaceRoot = searchForWorkspaceRoot(clientRoot);
47
41
  const fsAllowNarrowed = protectedMode
48
42
  ? [
49
43
  ...new Set(
50
44
  [
51
45
  clientRoot,
52
- path.join(appRoot, 'packages'),
53
- path.join(appRoot, 'node_modules'),
46
+ path.join(root, 'packages'),
47
+ path.join(root, 'modules'),
48
+ path.join(root, 'node_modules'),
54
49
  path.join(workspaceRoot, 'packages'),
55
50
  path.join(workspaceRoot, 'node_modules'),
56
51
  ].filter((p) => existsSync(p)),
@@ -62,24 +57,19 @@ const vite = await createViteServer({
62
57
  root: clientRoot,
63
58
  server: {
64
59
  middlewareMode: true,
65
- // 沙箱域名 Host 透传放行(dev-only;dist 物理不含 vite)。安全边界见 Agent Note
66
- // 2026-09-09 与方案 W Note(protected 面 /@fs 另有 allow 收窄 + deny 现值保留)
67
60
  allowedHosts: true,
68
61
  fs: {
69
62
  ...(fsAllowNarrowed ? { allow: fsAllowNarrowed } : {}),
70
- // /@fs 加固:默认 deny 不含服务端凭证目录(client 永不需要经 /@fs 读它)
71
63
  deny: ['.env', '.env.*', '*.{crt,pem}', '**/.git/**', '**/config/credentials/**'],
72
64
  },
73
65
  hmr: { server: hmrHub, path: HMR_WS_PATH },
74
66
  },
75
- // custom:不加 Vite 自己的 SPA fallback,HTML 路由由 runtime.final() 统一处理
76
67
  appType: 'custom',
77
68
  });
78
69
 
79
70
  const runtime = createTboxDevRuntime({
80
71
  vite: { middlewares: vite.middlewares, transformIndexHtml: vite.transformIndexHtml, ws: vite.ws },
81
72
  hmrHub,
82
- // 与 vite 同一 resolved config 同式 posix.join 派生——恒等无漂移
83
73
  hmrPath: path.posix.join(vite.config.base, HMR_WS_PATH),
84
74
  tokenState,
85
75
  clientRoot,
@@ -89,40 +79,48 @@ const runtime = createTboxDevRuntime({
89
79
  logger: serverLogger,
90
80
  fsAllowNarrowed: protectedMode,
91
81
  sseKeepaliveMs: process.env.TBOX_DEV_SSE_KEEPALIVE_MS ? Number(process.env.TBOX_DEV_SSE_KEEPALIVE_MS) : undefined,
82
+ pagePolicy: {
83
+ mode: 'manifest',
84
+ manifest: path.join(clientRoot, '.tbox-gen', 'manifest.json'),
85
+ },
92
86
  });
93
87
 
94
- // 面裁决:dev 面 → vite middlewares;static 面 → next()(落 final 的 dist 静态)
95
- app.use(runtime.gate);
96
-
97
- // ── 自由区(模板差异 + 应用自定义 middleware;dev/static 两面恒可见)──
98
- // 探针路由:smoke-dev-protected.sh ⑩ 断言两面可见性(dev 基础设施,dist 物理不含)
99
- app.get('/__tbox_dev_freezone_probe', (_req, res) => {
88
+ setupTboxDev();
89
+ legacyApp.use(runtime.gate);
90
+ legacyApp.get('/__tbox_dev_freezone_probe', (_req, res) => {
100
91
  res.type('text/plain').send('freezone-ok');
101
92
  });
102
- // ── 自由区结束 ──
103
-
104
- app.use(runtime.final);
105
-
106
- // 升级委托:唯一 WS 入口 = runtime.handleUpgrade(路径认领 + 子协议补写 + protected
107
- // token 校验,失败 401;未认领回落 app 路由——业务 /ws、根路径、fail-fast 语义不变)
93
+ legacyApp.use(runtime.final);
108
94
  registerUpgradeDelegate(runtime.handleUpgrade);
109
95
 
110
- // protected 面构建通知:watch 增量构建 → BUNDLE_END → SSE 广播 → static 面 reload。
111
- // fire-and-forget(不 await、无显式 close——dev 会话生命周期即进程生命周期);
112
- // watch 启动 emptyOutDir 清空 dist 为已定价行为(首建完成前 static 面纯 404)。
113
96
  if (protectedMode) {
114
97
  viteBuild({ root: clientRoot, build: { watch: {}, sourcemap: false } })
115
98
  .then((result) => {
116
99
  const watcher = Array.isArray(result) ? result[0] : result;
117
100
  if (!watcher || !('on' in watcher)) return;
118
101
  watcher.on('event', (e) => {
102
+ if (e.code === 'BUNDLE_START') runtime.notifyBuildStart();
119
103
  if (e.code === 'BUNDLE_END') runtime.notifyBuildEnd();
120
104
  });
121
105
  })
122
106
  .catch((err) => serverLogger.error('[dev] watch build failed:', err));
123
107
  }
124
108
 
125
- start().catch((err) => {
109
+ const app = await createApp({
110
+ ctx,
111
+ manifest: generated.manifest,
112
+ getManifest: () => generated.manifest,
113
+ appKind,
114
+ registry,
115
+ mode: 'dev',
116
+ resolveUser: (req) => getRequestContext(req)?.identity ?? null,
117
+ // CORS / JSON / auth 必须先于 createApp 的 /api/fn RPC。
118
+ beforeRoutes: (base) => {
119
+ base.use(legacyApp);
120
+ },
121
+ });
122
+
123
+ start(app).catch((err) => {
126
124
  serverLogger.error('Failed to start:', err);
127
125
  process.exit(1);
128
126
  });
@@ -1,35 +1,41 @@
1
1
  /**
2
- * 静态入口(唯一 tsup entry → dist/index.js):express.static 供给 client/dist。
3
- * dist 形态恒静态——vite dev 仅存在于 src/dev.ts(tsx 运行,禁入 tsup entry,
4
- * tsup.config.ts forbid-vite 插件拦截)。NODE_ENV 只影响 SDK 安全姿态(dev-login/密钥链)。
2
+ * 静态生产入口:createApp 装配 manifest/registry/页面运行时,业务路由仍由 app.ts 供给。
3
+ * dist 形态恒静态;vite dev 仅存在于 src/dev.ts。
5
4
  */
6
- import path from 'path';
5
+ import path from 'node:path';
7
6
  import { existsSync } from 'node:fs';
8
- import { fileURLToPath } from 'url';
9
- import express from 'express';
10
- import { createLogger } from '@tbox.cn/app-agent-sdk-server';
11
- import { app, start } from './app.js';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { createLogger, createApp, getRequestContext, type AppManifest } from '@tbox.cn/app-agent-sdk-server';
9
+ import { injectScript } from '@tbox.cn/app-agent-sdk-server/platform';
10
+ import manifest from '../../client/.tbox-gen/manifest.json';
11
+ import { appKind } from '../../client/.tbox-gen/app-kind';
12
+ import { registry } from '../../client/.tbox-gen/registry.server';
13
+ import { app as legacyApp, ctx, start } from './app.js';
12
14
 
13
15
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
16
  const serverLogger = createLogger('server');
17
+ const clientDir = path.join(__dirname, '../../client/dist');
15
18
 
16
- const clientDistPath = path.join(__dirname, '../../client/dist');
17
- if (!existsSync(path.join(clientDistPath, 'index.html'))) {
18
- serverLogger.warn(
19
- `client/dist 缺失(${clientDistPath})——页面将不可用(API/WS 不受影响);请先执行 pnpm build:client`,
20
- );
19
+ if (!existsSync(path.join(clientDir, 'index.html'))) {
20
+ serverLogger.warn(`client/dist 缺失(${clientDir})——页面将不可用(API/WS 不受影响);请先执行 pnpm build:client`);
21
21
  }
22
22
 
23
- app.use(express.static(clientDistPath));
24
- app.get('*', (req, res) => {
25
- if (!req.path.startsWith('/api')) {
26
- res.sendFile(path.join(clientDistPath, 'index.html'));
27
- } else {
28
- res.status(404).json({ error: 'Not Found' });
29
- }
23
+ const app = await createApp({
24
+ ctx,
25
+ manifest: manifest as AppManifest,
26
+ appKind,
27
+ registry,
28
+ mode: 'prod',
29
+ clientDir,
30
+ resolveUser: (req) => getRequestContext(req)?.identity ?? null,
31
+ decorateHtml: (html) => injectScript(html),
32
+ // CORS / JSON / auth 必须先于 createApp 的 /api/fn RPC;否则应用级函数可被匿名调用。
33
+ beforeRoutes: (base) => {
34
+ base.use(legacyApp);
35
+ },
30
36
  });
31
37
 
32
- start().catch((err) => {
38
+ start(app).catch((err) => {
33
39
  serverLogger.error('Failed to start:', err);
34
40
  process.exit(1);
35
- });
41
+ });
@@ -1,6 +1,6 @@
1
1
  // 铁律:不直接 import @mastra/core,经 @tbox.cn/app-agent-sdk-server 的 definePreTool 入口(单例铁律)
2
2
  import { definePreTool } from '@tbox.cn/app-agent-sdk-server';
3
- import { clockTool } from './tools/clock.js';
3
+ import { tool as clockTool } from './tools/clock.tool.js';
4
4
 
5
5
  /**
6
6
  * 应用级前置工具声明(010):BuildEngineOptions.preTools 通道(与模块声明合并、应用覆盖模块)。
@@ -6,7 +6,7 @@ import { z } from 'zod';
6
6
  * 当前时间工具 — 前置工具(pre-tool)演示:零参工具,参数无需模型抽取,
7
7
  * 词表命中即可工程化预执行(见 apps/server/src/pre-tools.ts)。
8
8
  */
9
- export const clockTool = createTool({
9
+ export const tool = createTool({
10
10
  id: 'getCurrentTime',
11
11
  description: '查询当前日期和时间',
12
12
  inputSchema: z.object({}),