@muqian/xiangsu-mcp-plus 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,6 +8,7 @@
8
8
  - 官方素材库:浏览、搜索、看封面、应用(脸部变形、美型、AI 实时变脸、美妆、滤镜、贴纸、画面特效等),流程与素材库面板相同;包括「素材广场」(其他创作者分享的现成 AI 图片、AI 妆容、自定义实时变脸、贴纸和素材包,应用时不重新生成、不扣额度)和自己的「收藏」。
9
9
  - 「添加对象」菜单:工具栏美妆 / 美型 / AI 实时变脸里的全部官方功能项(美容、面部生成、表情生成、性别年龄、五官处理、身体换装等),可看示意图后按菜单项 ID 添加。
10
10
  - AI 组合效果(用户拍照后在云端按工作流出图或出视频):像 AI 效果窗口的「新建工作流」一样建工作流,交给官方工作流工具编辑,再像「应用」一样放进场景。
11
+ - 素材库「AI 3D」:图生 3D 模型(一张图 → 静态 GLB 网格)、3D 动画(视频里人的动作 → 套到带标准人形骨骼的 FBX 上)、高精度模型重建(实物环绕视频 → 3D 高斯点云),提交、等待、取消任务,把结果导入工程,请求和导入方式与面板相同。
11
12
  - 首页作品:浏览、搜索、看封面,下载完整工程到本地或直接在编辑器里打开(官方工程和已发布的作品),供 agent 读取场景、脚本和资源,学习别人的做法;下载的东西都有登记,用完即删,最长保留 24 小时。
12
13
  - 交付:设置并上传图标、特效检测(和编辑器里点「特效检测」一样,云端检测)、填好提交窗口(名称、触发提示、摄像头方向、灵感、任务,一直走到「提交审核」页并等检测跑完;最后的「提交审核」由你来点)、手机预览二维码、把已领取的任务或创作灵感绑定到工程。
13
14
  - 抖音音乐:按分类或关键词找歌,设为特效音乐。
@@ -74,6 +75,12 @@
74
75
  | `menu_list` / `menu_add` | 「添加对象」菜单项列表(`details=true` 时带说明和示意图,一次最多 8 项)、按菜单项添加(可撤销);云端 AI 生成项不暴露(AI 组合效果用下面两个工具) |
75
76
  | `ai_combine_new` | 新建一张「AI 组合效果」工作流,等同 AI 效果窗口的「新建工作流」:本地建 AI Graph,只有「输入图」「效果组合」两个节点且未连线,不联网、不扣额度、不建云端草稿;返回 `ai_graph_id` 和各节点的 `node_id`(与官方 `get_workflow_context` 的节点 ID 相同) |
76
77
  | `ai_combine_apply` | 把一张 AI 工作流放进场景,等同「应用」(可撤销):编辑器编译工作流、上传工作流文件,再添加「AI 组合效果」对象(没有 2D 前景时一并建「2D 前景」「2D 摄像机」);不扣额度、不建草稿,生成过预览视频时一并上传供审核;编辑器拒绝时返回它的提示原文(如「请先连接效果组合器」);返回新增对象和 `draft_id` |
78
+ | `ai3d_image_submit` | 素材库「AI 3D › 3D模型」:上传参考图(PNG/JPG/JPEG,不超过 10 MB、4000 像素),按精度(low / medium / high = 1000 / 10000 / 50000 面)提交图生 3D,返回 `task_id`;产物是静态网格,没有骨骼 |
79
+ | `ai3d_animation_submit` | 「AI 3D › 3D动画」:上传参考视频(MP4,不超过 30 秒、20 MB、1280 像素)和模型(内置 `whole` / `upper_body` / `lower_body` / `arm`,或本地 FBX),提交动作生成;本地 FBX 按面板的方式检查骨骼(缺标准人形骨骼只提醒,与编辑器一致)和导入上限 |
80
+ | `ai3d_gs_segment` / `ai3d_gs_submit` | 「AI 3D › 高精度模型重建」两步:上传环绕视频(MP4/MOV,不超过 120 秒、100 MB、4000 像素)识别主体,返回主体图 `subject_image_ref`;确认后按主体生成 3D 高斯点云 |
81
+ | `ai3d_tasks` | 按类型分页列出 AI 3D 历史任务(状态、时间、输入、失败原因、本机是否已下载和预览文件),每页最多 20 条;带 `task_id` 时只查一个,再给 `wait_s` 就等到它不再运行(最多 600 秒) |
82
+ | `ai3d_import` | 下载并解压一个已完成任务的结果(放在编辑器的 AI 3D 缓存目录,面板里同样能看到),导入工程并放进场景(可撤销),与面板的「导入素材」相同 |
83
+ | `ai3d_cancel` | 取消运行中的 AI 3D 任务 |
77
84
  | `face_warp_list` / `face_warp_set_intensity` | 列出塑型画笔、改强度(保留笔刷数据,可撤销) |
78
85
  | `object_remove` | 删除对象(可撤销),报告只被它使用的资源和它导入时带来的素材包文件夹;`delete_unused_resources=true` 时一并删除 |
79
86
  | `resource_delete_unused` | 删除 `object_remove` 报告的路径;场景仍在引用的一律拒绝 |
@@ -88,6 +95,7 @@
88
95
  - 看榜上特效的工程:`rank_list` → 把这页的 `effect_id` 和 `name` 交给 `works_by_effect` → `status=found` 的用返回的 `template_id` 走 `works_download` / `works_open`。
89
96
  - 查审核结果:`my_effects` 看哪些没过、`review.text` 是原因 → 要看整条时间线用 `my_effect_reviews`;`can_edit=true` 的在编辑器「拍摄特效管理」里点「编辑」改完重新提交。
90
97
  - 拆别人的妆:`works_download` → `makeup_layers` 看用了哪些部位、什么颜色、多浓;自己的工程 `save_project` 后同样用 `makeup_layers` 查缺了哪些部位。
98
+ - 做 3D 角色:官方 `generate_image`(正面全身、纯色背景)→ `ai3d_image_submit` → `ai3d_tasks`(`task_id` + `wait_s`)→ `ai3d_import` → `capture_preview` 调大小和位置 → `save_project`。图生 3D 的模型没有骨骼,动作用脚本驱动;要用视频里的动作,模型须带标准人形骨骼(如 Mixamo 绑过骨、去掉 `mixamorig_` 前缀),走 `ai3d_animation_submit`。
91
99
  - 做 AI 组合效果:`ai_combine_new` → 官方 `get_workflow_capabilities`(选生图基模)→ `apply_workflow_patch`(加生图节点、写 prompt、连「输入图 → 生图 → 效果组合」)→ 要看效果时官方 `generate_workflow`(扣额度)→ `ai_combine_apply` → `save_project`。别人的作品怎么搭的,用 `works_download` 下载「AI玩法」分类里的工程,看 `Assets/AI 组合效果/*.oAICombineTextureJSA` 里的 `workflow` 和 `Graph/graph.json` 里的 AI Graph。
92
100
 
93
101
  相近工具的分工(每个工具只做一件事,这些也写进了工具说明;和官方工具重叠的,在官方工具的说明末尾补了一句指向这里):
@@ -125,6 +133,15 @@
125
133
  - 每份下载(临时目录或 `dest`)登记在 `~/.xiangsu-mcp-ext/works-downloads.json`。`works_cleanup` 随时删除;没删的在 24 小时后由下一次下载自动清掉(这个时长是拍的:够一个工作日内学完,又不至于堆积,可按需调 `src/works.mjs` 的 `DOWNLOAD_TTL_MS`)。
126
134
  - 编辑器窗口正开着的下载不会被删;像塑关窗时不会自己删除这些目录,关窗后再调 `works_cleanup`。
127
135
  - AI 组合效果在工程里由三部分组成:场景里的「AI 组合效果」图片对象、它绑定的组合效果纹理(`Assets/AI 组合效果/*.oAICombineTextureJSA`,存编译好的 `workflow`、上传后的 `graphTosUri` 和云端草稿 `draftId`),以及 `Graph/graph.json` 里的 AI Graph。「添加对象」菜单里的 AI 组合效果只建对象和一张 `workflow` 为 `{}` 的空纹理,编辑器自己也是先建空壳、再由「应用」填参数,所以 `menu_add` 仍然拒绝它,改用 `ai_combine_new` / `ai_combine_apply`。哪些步骤会连到云端(2026-11-08 读编辑器代码;`ai_combine_new` 和 `ai_combine_apply` 不建草稿是实测,官方 Patch 建草稿、预览视频上传只读了代码,没有实测):`ai_combine_new` 和本地连线都不联网;官方 `apply_workflow_patch` 每次改完都会把工作流存成账号下的云端 AI 效果草稿(`releaseAIEffect`),此后 `ai_combine_apply` 返回的 `draft_id` 就是这个草稿;官方 `generate_workflow` 扣生图额度;`ai_combine_apply` 上传工作流文件,生成过预览视频时把视频一并上传供审核,自己不建草稿。场景里有变声组件时编辑器拒绝「应用」,工具报 `AI_COMBINE_APPLY_NO_EFFECT`。
136
+ - AI 3D(2026-11-08 读编辑器 9.8.1 的 `AI3DManager` 和三个上传面板):提交、查询、取消走面板同一组云端接口(`submitAIGCRequest` / `queryAIGCResult` / `queryAITaskHistories` / `cancelAIGCRequest`),参数原样照抄;结果解压到编辑器的 `AIGen3D/<task_id>/` 缓存目录,导入方式、命名和缩放(GLB 外层放大 15 倍、点云缩小到 0.3)也与面板相同。几个限制的来源:
137
+ - 精度对应的面数、视频的时长 / 分辨率 / 大小上限、本地模型要有的 20 根骨骼,取自面板组件里没导出的常量(在编辑器里让组件自己跑一遍校验读出来的)。
138
+ - 面板拿视频探测函数量图片,图片读出来宽高大小都是 0,所以编辑器实际只检查了扩展名;工具按面板文案写的 10 MB、4000 像素真的检查。
139
+ - 本地 FBX 缺标准人形骨骼时编辑器只弹提醒、照样提交,工具也照样提交,在返回里给 `warning`;没有骨骼、骨骼超过 100 根或面数超过 12 万时编辑器拒绝,工具同样拒绝。
140
+ - 同一类型运行中的任务满 3 个时面板拒绝提交,工具先查历史里运行中的任务数,同样拒绝。
141
+ - 历史接口一页超过 20 条时返回 5062「超出最大条数限制」(实测,面板自己一页取 5 条),所以 `ai3d_tasks` 的 `count` 最多 20。
142
+ - 结果接口不带任务的输入,导入 3D 动画时到历史里按 `task_id` 找回所用的模型,按面板的方式给文件起名(如「全身.fbx」);最近 200 条里找不到就用 `task_id` 命名。
143
+ - 实测耗时(2026-11-08 各跑一次):图生 3D(medium)约 13 分钟,3D 动画(内置全身模型、约 3.5 秒的挥手视频)约 9 分钟。
144
+ - 编辑器代码里没有扣额度的逻辑或提示,是否收费以平台为准。
128
145
  - 预览重载有延迟,应用后用 `interact_by_dsl` 先 `wait` 2–3 秒再截图更稳。
129
146
  - 资源删除不可撤销;对象删除可以在编辑器里撤销,但已删除的资源不会回来。
130
147
  - 「孤儿资源」只按场景直接引用判断(资源的编辑器 guid 是否出现在场景序列化数据里)。只通过材质等间接引用的资源不会被判为孤儿。
@@ -192,6 +209,7 @@ node scripts/install.mjs
192
209
  - 导入:`@orion/orion-sdk/EditorFramework` 的 `Resource.AssetPackageManager.instance.import`、`UndoSystem`、`PreviewSyncer`
193
210
  - 菜单:`@orion/orion-sdk/orionui` 的 `ExtensionManager` / `I18n`,`DynamicMenuConfigInfo`,`SceneOpsService.createEntity`,`HoverTipsMap`
194
211
  - AI 组合效果:`AIEffectWindow/AICombinationToolPanel/Core/AIGraphProjectUtils.createAIGraph`(「新建工作流」按钮用的同一个),`.../Core/Manager/AIGraphManager` 的 `getInstance`、`addGraph`、`getGraphById`、`switchGraphbyGuid`、`editorPanelApply`(「应用」;失败时不抛异常,而是在 `BusinessEventManager` 上发 `AIEffectShowToast`,工具监听它并以场景里出现新对象为准)
212
+ - AI 3D:`AssetsLibrary/Core/Control/AI3DManager/{const,utils}`(场景名、模型 ID、缓存目录、结果文件路径)、`@orion/Business/API/ai_effect_api`(提交 / 查询 / 历史 / 取消)、`@orion/Business/API/upload_api`(`uploadFileCommon`、`uploadToSpace`)、`AIEffectWindow/controller/apiUtils.QueryTaskResult`(主体识别的轮询)、`Utils/LokiAsset/utils.downloadTemplateFile`、`ResItemExtraData/ResourceImportHandles`(`importExtAsset` + 加载回调)、`EditorFramework` 的 `APJS.FbxLoaderAPJSWrapper`(检查本地模型)和 `Extension.Scene.AssetSceneObjectCreationSystem`、`PreviewManager.checkIsValidVideoFile` / `getFirstNonBlackFrame`、`@orion/config/LegacyGlobalConfig.url`(内置模型的绝对路径;`orionui` 的 `url` 给的是相对路径)
195
213
  - 工程窗口:`OpenProjectFromEditCommand` + `EditSender`(与编辑器自己的 `launchProject` 同一请求,9.8.1 起首页进程只认它),`closeProjectAndBackToHome`
196
214
  - 首页作品:`@orion/Business/HomeWindow/TemplatesPanel/Request/{templatesPanel,templatesCategory}`、`.../Model/util.transformTemplate`、`.../Model/DownloadTemplateModel`;打开作品用 `OpenProjectFromEditCommand` 的 `openTemplate`
197
215
  - 交付:`IconCreationNew/controller/IconPreviewManager`、`IconCreationNew/UI/BottomPanel/DYEHIconUploadHelper.uploadIcon`(上传图标,写回 `iconUri`)、`Submission/SubmissionExtension/EffectSubmissionExtension`(提交接口 `submit()` 只做前置检查并打开提交窗口)、全局 `App._windows`(编辑器每次都新开提交窗口和特效检测窗口、不保存引用,按类名 `DYEHEffectSubmissionWindow` / `DYEHPerfTestWebWindow` 在这里找到它们;提交窗口和特效检测窗口都是网页窗口,网页里的脚本经 `webview.evaluateJavascript` 注入,结果经窗口的 JS bridge 以 `orionJSB://` 查询传回)、`PerfTest/PerfTestExtension`、`EditWindow/ToolBar/MobilePreview/backendHelper`、`effectExporter.exportEffectPackage`
@@ -211,6 +229,6 @@ node scripts/install.mjs
211
229
 
212
230
  ## English
213
231
 
214
- Unofficial MCP extension for Douyin AR (像塑) on macOS. One stdio MCP server proxies every tool of the editor's official MCP (with automatic reconnects) and adds what the official server cannot do: browse/search/preview/apply official library assets, browse/search/download or open the homepage works (official projects and published effects) as full projects an agent can read and learn from (rank-board effects are looked up there by effect id, though effects whose authors did not share them on the homepage have no downloadable project; every download is registered and deleted by works_cleanup or after 24 hours), add any item of the editor's "add object" menu (toolbar makeup / reshape / AI face effects), create AI combine workflows (the photo is sent to the cloud and generated from the workflow) and apply them to the scene the way the AI effect window does, leaving node editing and preview generation to the official workflow tools, list a project's makeup layers with the face part, colour and strength of each (from the layer's region and its texture's pixels when the name says nothing), set FaceWarpX brush intensity, prepare delivery (setting and uploading the icon, local and cloud effect checks, filling in the submit window — name, trigger hint, camera, inspiration, task — up to its final step, where pressing 提交审核 stays a user click, phone preview QR codes, binding received creator tasks or inspirations), read the signed-in account's inspirations and tasks (collect inspirations, receive tasks) and the mobile app's rank boards, list the account's submitted effects with their review status and, for rejected ones, the reviewer's reason and full review timeline, use Douyin music, open/create/close project windows, and remove objects together with resources only they used. It works through a small editor plugin that exposes a token-protected RPC on 127.0.0.1 inside each project window. Relies on editor internals (verified on 9.7.2); `ext_status` reports any missing internals. Install with `npm install -g @muqian/xiangsu-mcp-plus && xiangsu-mcp-ext-install` (a global install is required: the editor plugin loads this code by absolute path, so the npx cache is refused), or from source with `npm ci && node scripts/install.mjs`; then register `node <package>/src/server.mjs` as a stdio MCP server.
232
+ Unofficial MCP extension for Douyin AR (像塑) on macOS. One stdio MCP server proxies every tool of the editor's official MCP (with automatic reconnects) and adds what the official server cannot do: browse/search/preview/apply official library assets, browse/search/download or open the homepage works (official projects and published effects) as full projects an agent can read and learn from (rank-board effects are looked up there by effect id, though effects whose authors did not share them on the homepage have no downloadable project; every download is registered and deleted by works_cleanup or after 24 hours), add any item of the editor's "add object" menu (toolbar makeup / reshape / AI face effects), create AI combine workflows (the photo is sent to the cloud and generated from the workflow) and apply them to the scene the way the AI effect window does, leaving node editing and preview generation to the official workflow tools, run the asset library's AI 3D generation (image → static mesh, a video's human motion → an animated FBX with the standard humanoid skeleton, an orbit video → a 3D Gaussian splat) and import the results the way its panel does, list a project's makeup layers with the face part, colour and strength of each (from the layer's region and its texture's pixels when the name says nothing), set FaceWarpX brush intensity, prepare delivery (setting and uploading the icon, local and cloud effect checks, filling in the submit window — name, trigger hint, camera, inspiration, task — up to its final step, where pressing 提交审核 stays a user click, phone preview QR codes, binding received creator tasks or inspirations), read the signed-in account's inspirations and tasks (collect inspirations, receive tasks) and the mobile app's rank boards, list the account's submitted effects with their review status and, for rejected ones, the reviewer's reason and full review timeline, use Douyin music, open/create/close project windows, and remove objects together with resources only they used. It works through a small editor plugin that exposes a token-protected RPC on 127.0.0.1 inside each project window. Relies on editor internals (verified on 9.7.2); `ext_status` reports any missing internals. Install with `npm install -g @muqian/xiangsu-mcp-plus && xiangsu-mcp-ext-install` (a global install is required: the editor plugin loads this code by absolute path, so the npx cache is refused), or from source with `npm ci && node scripts/install.mjs`; then register `node <package>/src/server.mjs` as a stdio MCP server.
215
233
 
216
234
  **For learning and personal creation only. Do not use it to copy other creators' works**: works you view, download or apply through this tool (homepage projects, ranked effects, assets other creators shared) must not be republished, submitted, used commercially or passed off as your own, as is or modified. Licensed under [MIT](LICENSE), which covers this project's own code only. Not affiliated with or endorsed by ByteDance / Douyin; all product names and trademarks belong to their owners. The repository contains no editor code or assets. Official assets and homepage works accessed through this tool belong to 像塑 or their creators and are subject to the platform's terms; use downloaded works for learning only, delete them with works_cleanup when done, and do not redistribute them.
@@ -0,0 +1,441 @@
1
+ 'use strict';
2
+ // AI 3D (素材库 › AI 3D): 图生3D (an image → a static GLB mesh), 3D 动画 (an FBX with the standard humanoid
3
+ // skeleton + a reference video → that FBX animated with the video's motion) and 高精度模型重建 (an orbit
4
+ // video of a real object → a 3D Gaussian splat). Requests are the ones AI3DManager makes; results are
5
+ // downloaded to and imported from the folder the panel uses, so the panel finds them as well.
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { execFileSync } = require('child_process');
9
+ const { M, editingScene, sceneObjectSet, addedObjectEditors, sceneObjectPath, projectResources, packageRootsAdded, recordImport } = require('./common.cjs');
10
+
11
+ // The panel's names for the three generation types (AI3DManager/type AIGenType).
12
+ const GEN_TYPE = { image: 'Image', animation: 'Animation', gs: 'Video' };
13
+ // The precision options of 图生3D (FaceNumSelection, 9.8.1).
14
+ const FACE_NUM = { low: 1000, medium: 10000, high: 50000 };
15
+ // The upload panels' own checks (9.8.1): extensions from the panels' texts, numbers from their code.
16
+ // The image panel measures images with the video probe, which reads 0 for pictures, so in the editor
17
+ // only the extension is really checked; the size and resolution here are the limits its text states.
18
+ const IMAGE_LIMIT = { exts: ['png', 'jpg', 'jpeg'], maxSide: 4000, maxMB: 10 };
19
+ const VIDEO_LIMIT = {
20
+ animation: { exts: ['mp4'], maxSide: 1280, maxMB: 20, maxSeconds: 30 },
21
+ gs: { exts: ['mp4', 'mov'], maxSide: 4000, maxMB: 100, maxSeconds: 120 },
22
+ };
23
+ // The panel refuses a fourth running task of the same type (3d_gen_max_limit).
24
+ const MAX_RUNNING = 3;
25
+ // Built-in reference models of 3D 动画 (BuiltinResource/AssetLibrary/<id>.fbx).
26
+ const PRESET_MODELS = {
27
+ whole: '3d_gen_preset_model_whole',
28
+ upper_body: '3d_gen_preset_model_upper_body',
29
+ lower_body: '3d_gen_preset_model_lower_body',
30
+ arm: '3d_gen_preset_model_arm',
31
+ };
32
+ // Bones the animation panel looks for in an uploaded model (case-insensitive, whole names). Missing ones
33
+ // only bring up a warning there; the model is still used.
34
+ const REQUIRED_BONES = [
35
+ 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',
36
+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'RightUpLeg', 'RightLeg', 'RightFoot',
37
+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand', 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',
38
+ ];
39
+ const STATUS = { 1: 'running', 2: 'finished', 3: 'failed', 4: 'discarded' };
40
+ // How the editor tags and sizes each kind of result when importing it (AI3DManager.import*Model).
41
+ const IMPORT = {
42
+ image: { file: 'modelPath', idPrefix: 'AIAsset_3DMesh_', type: 'AIAsset_ImageTo3D' },
43
+ gs: { file: 'plyPath', idPrefix: 'AIAsset_3DGS_', type: 'AIAsset_VideoTo3DGS' },
44
+ animation: { file: 'resultFbxPath', idPrefix: 'AIAsset_Animation_', type: 'AIDanceToAnimation' },
45
+ };
46
+ // Picked, not measured: often enough to notice a finished task soon, rare enough not to hammer the API.
47
+ const POLL_MS = 3000;
48
+ // Same as the panel's TaskSucceed download.
49
+ const DOWNLOAD_TIMEOUT_MS = 30000;
50
+ // Measured: the history API answers 5062 「超出最大条数限制」 for a page of more than 20 (the panel asks for 5).
51
+ const HISTORY_PAGE = 20;
52
+ // Picked: how far back an import looks for a task's own record (queryAIGCResult does not return the
53
+ // input); 10 pages of 20 reach well past what anyone keeps importing from.
54
+ const HISTORY_PAGES = 10;
55
+
56
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
57
+
58
+ function parseJson(s) {
59
+ if (typeof s !== 'string' || !s) return {};
60
+ try {
61
+ return JSON.parse(s);
62
+ } catch (_) {
63
+ return {};
64
+ }
65
+ }
66
+
67
+ function ext(file) {
68
+ return path.extname(file).slice(1).toLowerCase();
69
+ }
70
+
71
+ function checkFile(file, exts, what) {
72
+ if (typeof file !== 'string' || !path.isAbsolute(file)) throw Error(`${what}_PATH_NOT_ABSOLUTE: ${file}`);
73
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw Error(`${what}_NOT_FOUND: ${file}`);
74
+ if (!exts.includes(ext(file))) throw Error(`${what}_FORMAT: ${path.basename(file)}; supported: ${exts.join(', ')}`);
75
+ return file;
76
+ }
77
+
78
+ function checkKind(kind) {
79
+ if (!Object.prototype.hasOwnProperty.call(GEN_TYPE, kind)) throw Error(`INVALID_KIND: ${kind}; valid: ${Object.keys(GEN_TYPE).join(', ')}`);
80
+ return kind;
81
+ }
82
+
83
+ const iso = (sec) => (sec ? new Date(sec * 1000).toISOString() : null);
84
+
85
+ // What the record says about its own input, read the way the panel's 「重新编辑」 reads it.
86
+ function taskInput(kind, record) {
87
+ const params = parseJson(((record.inputNodeList || [])[0] || {}).params);
88
+ if (kind === 'animation') {
89
+ const req = params.req_json || {};
90
+ const preset = Object.keys(PRESET_MODELS).find((k) => PRESET_MODELS[k] === req.presetModel);
91
+ return preset ? { model: preset } : { model: req.localModel || null };
92
+ }
93
+ const req = (params.dyeh_custom_params && params.dyeh_custom_params.req_json) || {};
94
+ if (kind === 'image') {
95
+ const precision = Object.keys(FACE_NUM).find((k) => FACE_NUM[k] === req.faceNum);
96
+ return { precision: precision || null, face_num: req.faceNum ?? null };
97
+ }
98
+ return {};
99
+ }
100
+
101
+ function failureText(record) {
102
+ const out = (record.outputNodeList || [])[0] || {};
103
+ return (out.textList || [])[0] || null;
104
+ }
105
+
106
+ const methods = {
107
+ ai3dRun(cmd, args) {
108
+ return (this.ai3dExec || execFileSync)(cmd, args, { encoding: 'utf8' });
109
+ },
110
+
111
+ ai3dConst() {
112
+ return this.mod(M.ai3dConst);
113
+ },
114
+
115
+ ai3dCheckImage(file) {
116
+ checkFile(file, IMAGE_LIMIT.exts, 'IMAGE');
117
+ const mb = fs.statSync(file).size / (1024 * 1024);
118
+ if (mb > IMAGE_LIMIT.maxMB) throw Error(`IMAGE_TOO_LARGE: ${mb.toFixed(1)} MB; the limit is ${IMAGE_LIMIT.maxMB} MB`);
119
+ const out = this.ai3dRun('sips', ['-g', 'pixelWidth', '-g', 'pixelHeight', file]);
120
+ const width = Number((/pixelWidth:\s*(\d+)/.exec(out) || [])[1]);
121
+ const height = Number((/pixelHeight:\s*(\d+)/.exec(out) || [])[1]);
122
+ if (!(width > 0 && height > 0)) throw Error(`NOT_AN_IMAGE: ${file}`);
123
+ if (width > IMAGE_LIMIT.maxSide || height > IMAGE_LIMIT.maxSide) throw Error(`IMAGE_RESOLUTION: ${width}×${height}; the limit is ${IMAGE_LIMIT.maxSide}×${IMAGE_LIMIT.maxSide}`);
124
+ return { width, height };
125
+ },
126
+
127
+ ai3dCheckVideo(file, kind) {
128
+ const limit = VIDEO_LIMIT[kind];
129
+ checkFile(file, limit.exts, 'VIDEO');
130
+ const meta = this.mod(M.preview).PreviewManager.getInstance().checkIsValidVideoFile(file);
131
+ if (!meta || !meta.valid) throw Error(`VIDEO_UNREADABLE: ${file}`);
132
+ // The probe gives the duration in microseconds and the size in MB.
133
+ const seconds = meta.duration / 1e6;
134
+ if (seconds > limit.maxSeconds) throw Error(`VIDEO_TOO_LONG: ${seconds.toFixed(1)} s; the limit is ${limit.maxSeconds} s`);
135
+ if (meta.width > limit.maxSide || meta.height > limit.maxSide) throw Error(`VIDEO_RESOLUTION: ${meta.width}×${meta.height}; the limit is ${limit.maxSide}×${limit.maxSide}`);
136
+ if (meta.size > limit.maxMB) throw Error(`VIDEO_TOO_LARGE: ${meta.size.toFixed(1)} MB; the limit is ${limit.maxMB} MB`);
137
+ return { width: meta.width, height: meta.height, seconds: Number(seconds.toFixed(2)) };
138
+ },
139
+
140
+ // The animation panel's model check: no skeleton or over the import limits refuses; missing bones warn.
141
+ async ai3dCheckRig(file) {
142
+ const EF = this.mod(M.ef);
143
+ const fbx = await EF.APJS.FbxLoaderAPJSWrapper.createFromPathAsync(file, 'zh_CN.UTF-8');
144
+ const triangles = fbx.getTriangleCount();
145
+ const bones = fbx.getMaxBoneCount();
146
+ if (!(triangles >= 0 && fbx.getVertexCount() >= 0 && bones > 0)) throw Error(`MODEL_NOT_RIGGED: ${path.basename(file)} has no skeleton`);
147
+ const limits = EF.ImportLimitationNumber;
148
+ if (bones > limits.BONE_NUM_LIMIT) throw Error(`MODEL_TOO_MANY_BONES: ${bones}; the limit is ${limits.BONE_NUM_LIMIT}`);
149
+ if (triangles > limits.SKIN_MESH_TRIANGLE_HARD_NUM_LIMIT) throw Error(`MODEL_TOO_MANY_TRIANGLES: ${triangles}; the limit is ${limits.SKIN_MESH_TRIANGLE_HARD_NUM_LIMIT}`);
150
+ const names = new Set(fbx.getAllNodeNames().map((n) => String(n).toLowerCase()));
151
+ return { bones, triangles, missing_bones: REQUIRED_BONES.filter((b) => !names.has(b.toLowerCase())) };
152
+ },
153
+
154
+ async ai3dRunningCheck(kind) {
155
+ const res = await this.mod(M.aiEffectApi).queryAITaskHistories({ cursor: 0, size: MAX_RUNNING, scene: this.ai3dConst().AIGen3DModelScene[GEN_TYPE[kind]], statusList: [1] });
156
+ if (!res || res.code !== 0) throw Error(`AI3D_HISTORY_FAILED: code=${res && res.code} message=${(res && res.message) || ''}`);
157
+ const running = ((res.data && res.data.taskRecords) || []).length;
158
+ if (running >= MAX_RUNNING) throw Error(`AI3D_TOO_MANY_RUNNING: ${running} ${kind} tasks are running; the editor allows ${MAX_RUNNING} at a time, wait for one to finish`);
159
+ },
160
+
161
+ async ai3dUpload(file, type) {
162
+ const api = this.mod(M.uploadApi);
163
+ const res = await api.uploadFileCommon({ filePath: file, fileType: api.FileType[type] });
164
+ if (!res || res.code !== 0) throw Error(`UPLOAD_FAILED: ${path.basename(file)} code=${res && res.code} message=${(res && res.message) || ''}`);
165
+ return res.data;
166
+ },
167
+
168
+ async ai3dUploadVideo(file) {
169
+ const api = this.mod(M.uploadApi);
170
+ const res = await api.uploadToSpace({ filePath: file, fileType: api.FileType.Video });
171
+ if (!res || res.code !== 0 || !res.data || res.data.res === false) throw Error(`UPLOAD_FAILED: ${path.basename(file)} code=${res && res.code} message=${(res && res.message) || ''}`);
172
+ return res.data.videoInfo;
173
+ },
174
+
175
+ async ai3dSubmit(kind, node, needRecord) {
176
+ const c = this.ai3dConst();
177
+ const type = GEN_TYPE[kind];
178
+ const res = await this.mod(M.aiEffectApi).submitAIGCRequest({
179
+ inputNodeList: [{ source: `loki_material://${c.AIGenModelIdMap[type]}`, ...node, aigc_env: this.mod(M.aigcUtils).getAIGCEnv() }],
180
+ scene: c.AIGen3DModelScene[type],
181
+ needRecord,
182
+ });
183
+ const b = res && res.body;
184
+ if (!b || b.code !== 0 || !b.data || !b.data.taskId) throw Error(`AI3D_SUBMIT_FAILED: code=${b && b.code} message=${(b && b.message) || ''}`);
185
+ return String(b.data.taskId);
186
+ },
187
+
188
+ async ai3dImageSubmit({ image_path, precision = 'medium' }) {
189
+ this.ensureCompatible('ai3d');
190
+ if (!Object.prototype.hasOwnProperty.call(FACE_NUM, precision)) throw Error(`INVALID_PRECISION: ${precision}; valid: ${Object.keys(FACE_NUM).join(', ')}`);
191
+ const size = this.ai3dCheckImage(image_path);
192
+ await this.ai3dRunningCheck('image');
193
+ const up = await this.ai3dUpload(image_path, 'Picture');
194
+ const params = { business_type: 'dyeh', dyeh_custom_params: { req_json: { faceNum: FACE_NUM[precision] } } };
195
+ const task_id = await this.ai3dSubmit('image', { params: JSON.stringify(params), uriList: [up.decryptedUri] }, true);
196
+ return { task_id, kind: 'image', precision, face_num: FACE_NUM[precision], image: size };
197
+ },
198
+
199
+ async ai3dAnimationSubmit({ video_path, model = 'whole' }) {
200
+ this.ensureCompatible('ai3d');
201
+ const video = this.ai3dCheckVideo(video_path, 'animation');
202
+ let modelPath;
203
+ let reqModel;
204
+ let rig = null;
205
+ if (Object.prototype.hasOwnProperty.call(PRESET_MODELS, model)) {
206
+ // The url() the panel resolves built-in files with; orionui's url() returns a relative path.
207
+ modelPath = this.mod(M.globalConfig).url(`./BuiltinResource/AssetLibrary/${PRESET_MODELS[model]}.fbx`);
208
+ if (!fs.existsSync(modelPath)) throw Error(`PRESET_MODEL_MISSING: ${modelPath}`);
209
+ reqModel = { presetModel: PRESET_MODELS[model], localModel: '' };
210
+ } else {
211
+ if (typeof model === 'string' && !path.isAbsolute(model)) throw Error(`INVALID_MODEL: ${model}; pass one of ${Object.keys(PRESET_MODELS).join(', ')} or the absolute path of an .fbx`);
212
+ modelPath = checkFile(model, ['fbx'], 'MODEL');
213
+ rig = await this.ai3dCheckRig(modelPath);
214
+ reqModel = { presetModel: '', localModel: path.basename(modelPath) };
215
+ }
216
+ await this.ai3dRunningCheck('animation');
217
+ const root = this.ai3dConst().AIGen3DFolder;
218
+ fs.mkdirSync(root, { recursive: true });
219
+ const dir = fs.mkdtempSync(path.join(root, 'xiangsu-mcp-ext-upload-'));
220
+ try {
221
+ const cover = path.join(dir, 'cover.png');
222
+ this.mod(M.preview).PreviewManager.getInstance().getFirstNonBlackFrame(video_path, cover);
223
+ if (!fs.existsSync(cover)) throw Error(`VIDEO_COVER_FAILED: no frame could be read from ${video_path}`);
224
+ const coverUp = await this.ai3dUpload(cover, 'Picture');
225
+ // The panel zips the model with its file name at the root of the archive.
226
+ const zip = path.join(dir, 'model.zip');
227
+ this.ai3dRun('zip', ['-j', '-q', zip, modelPath]);
228
+ const modelUp = await this.ai3dUpload(zip, 'File');
229
+ const info = await this.ai3dUploadVideo(video_path);
230
+ const params = { model: `tos://${modelUp.decryptedUri}`, video: info.vid, req_json: { videoCoverUri: coverUp.url, ...reqModel } };
231
+ const task_id = await this.ai3dSubmit('animation', { params: JSON.stringify(params) }, true);
232
+ const out = { task_id, kind: 'animation', model: Object.prototype.hasOwnProperty.call(PRESET_MODELS, model) ? model : modelPath, video };
233
+ if (rig) {
234
+ out.model_check = rig;
235
+ if (rig.missing_bones.length) out.warning = `模型缺少标准人形骨骼 ${rig.missing_bones.join('、')}(名字要完全一致,不能带 mixamorig_ 之类的前缀);编辑器在这种情况下也只是提醒,照样提交,生成结果可能不对`;
236
+ }
237
+ return out;
238
+ } finally {
239
+ fs.rmSync(dir, { recursive: true, force: true });
240
+ }
241
+ },
242
+
243
+ // Step one of 高精度模型重建: the cloud finds the subject in the video; step two (ai3dGsSubmit) builds it.
244
+ async ai3dGsSegment({ video_path, wait_s = 120 }) {
245
+ this.ensureCompatible('ai3d');
246
+ this.ai3dCheckVideo(video_path, 'gs');
247
+ await this.ai3dRunningCheck('gs');
248
+ const info = await this.ai3dUploadVideo(video_path);
249
+ const req_json = { req_type: 1, vid: info.vid, prompt: '', duration: info.duration, width: info.width, height: info.height };
250
+ const params = { business_type: 'dyeh', dyeh_custom_params: { req_json } };
251
+ const seg_task_id = await this.ai3dSubmit('gs', { params: JSON.stringify(params), uriList: [''] }, false);
252
+ let res;
253
+ try {
254
+ // On timeout this cancels the task itself, as the panel's window does.
255
+ res = await this.mod(M.aiApiUtils).QueryTaskResult(seg_task_id, 1000, wait_s * 1000);
256
+ } catch (e) {
257
+ throw Error(`AI3D_SUBJECT_FAILED: ${e.message} (task ${seg_task_id})`);
258
+ }
259
+ const node = (((res && res.result) || {}).output_node_list || [])[0] || {};
260
+ const subject_image_url = (node.image_url_list || [])[0];
261
+ const subject_uri = ((node.image_info_list || [])[0] || {}).uri;
262
+ if (!subject_image_url || !subject_uri) throw Error(`AI3D_SUBJECT_NOT_FOUND: the cloud found no subject in the video (task ${seg_task_id})`);
263
+ return { seg_task_id, subject_image_url, subject_uri, req_json };
264
+ },
265
+
266
+ async ai3dGsSubmit({ subject_uri, req_json }) {
267
+ this.ensureCompatible('ai3d');
268
+ if (typeof subject_uri !== 'string' || !subject_uri || !req_json || !req_json.vid) throw Error('INVALID_SUBJECT: pass what ai3d_gs_segment returned');
269
+ await this.ai3dRunningCheck('gs');
270
+ const params = { business_type: 'dyeh', dyeh_custom_params: { req_json: { ...req_json, req_type: 0 } } };
271
+ const task_id = await this.ai3dSubmit('gs', { params: JSON.stringify(params), uriList: [subject_uri] }, true);
272
+ return { task_id, kind: 'gs' };
273
+ },
274
+
275
+ ai3dLocal(task_id) {
276
+ const info = this.mod(M.ai3dUtils).getGen3DModelLocalInfoByTaskId(task_id);
277
+ const has = (p) => fs.existsSync(p);
278
+ return {
279
+ downloaded: has(info.unzipLocalPath),
280
+ preview_image_file: has(info.previewVideoCoverPath) ? info.previewVideoCoverPath : null,
281
+ preview_video_file: has(info.previewVideoPath) ? info.previewVideoPath : null,
282
+ };
283
+ },
284
+
285
+ async ai3dHistory(kind, cursor, size) {
286
+ const c = this.ai3dConst();
287
+ const res = await this.mod(M.aiEffectApi).queryAITaskHistories({ cursor, size, scene: c.AIGen3DModelScene[GEN_TYPE[kind]], statusList: c.AIGen3DModelQueryStatus });
288
+ if (!res || res.code !== 0) throw Error(`AI3D_HISTORY_FAILED: code=${res && res.code} message=${(res && res.message) || ''}`);
289
+ return res.data || {};
290
+ },
291
+
292
+ // The history record of one task, or null when it is not among the latest HISTORY_PAGES pages.
293
+ async ai3dRecord(kind, task_id) {
294
+ let cursor = 0;
295
+ for (let page = 0; page < HISTORY_PAGES; page++) {
296
+ const data = await this.ai3dHistory(kind, cursor, HISTORY_PAGE);
297
+ const hit = (data.taskRecords || []).find((t) => String(t.taskId) === task_id);
298
+ if (hit) return hit;
299
+ if (!data.hasMore) return null;
300
+ cursor = data.nextCursor;
301
+ }
302
+ return null;
303
+ },
304
+
305
+ async ai3dTasks({ kind, cursor = 0, count = HISTORY_PAGE }) {
306
+ this.ensureCompatible('ai3d');
307
+ checkKind(kind);
308
+ const data = await this.ai3dHistory(kind, cursor, count);
309
+ const items = (data.taskRecords || []).map((t) => ({
310
+ task_id: String(t.taskId),
311
+ status: STATUS[t.status] || String(t.status),
312
+ created_at: iso(t.createTime),
313
+ finished_at: t.status === 1 ? null : iso(t.finishTime),
314
+ ...taskInput(kind, t),
315
+ ...(t.status === 3 ? { failure: failureText(t) } : {}),
316
+ ...this.ai3dLocal(String(t.taskId)),
317
+ }));
318
+ return { kind, items, next_cursor: data.nextCursor ?? null, has_more: !!data.hasMore };
319
+ },
320
+
321
+ async ai3dQuery(task_id) {
322
+ const res = await this.mod(M.aiEffectApi).queryAIGCResult({ taskId: task_id });
323
+ if (!res || res.code !== 0 || !res.data) throw Error(`AI3D_QUERY_FAILED: task ${task_id} code=${res && res.code} message=${(res && res.message) || ''}`);
324
+ return res.data;
325
+ },
326
+
327
+ // One task's state; with wait_s it keeps asking until the task stops running or the time is up.
328
+ async ai3dTask({ task_id, wait_s = 0 }) {
329
+ this.ensureCompatible('ai3d');
330
+ if (typeof task_id !== 'string' || !task_id) throw Error('INVALID_TASK_ID: task_id must be a non-empty string');
331
+ const poll = this.ai3dPollMs ?? POLL_MS;
332
+ const until = Date.now() + wait_s * 1000;
333
+ let data = await this.ai3dQuery(task_id);
334
+ while (data.status === 1 && Date.now() + poll <= until) {
335
+ await sleep(poll);
336
+ data = await this.ai3dQuery(task_id);
337
+ }
338
+ const out = { task_id, status: STATUS[data.status] || String(data.status) };
339
+ if (data.status === 3) out.failure = failureText(data);
340
+ if (data.status === 2) out.result_ready = !!((((data.outputNodeList || [])[0] || {}).objectInfoList || [])[0] || {}).url;
341
+ return { ...out, ...this.ai3dLocal(task_id) };
342
+ },
343
+
344
+ async ai3dImport({ task_id, kind }) {
345
+ this.ensureCompatible('ai3d');
346
+ checkKind(kind);
347
+ if (typeof task_id !== 'string' || !task_id) throw Error('INVALID_TASK_ID: task_id must be a non-empty string');
348
+ const EF = this.mod(M.ef);
349
+ const { sceneEditor, project } = editingScene(this);
350
+ const data = await this.ai3dQuery(task_id);
351
+ if (data.status !== 2) throw Error(`AI3D_NOT_FINISHED: task ${task_id} is ${STATUS[data.status] || data.status}`);
352
+ const url = ((((data.outputNodeList || [])[0] || {}).objectInfoList || [])[0] || {}).url;
353
+ if (!url) throw Error(`AI3D_NO_RESULT: task ${task_id} has no result file`);
354
+ const info = this.mod(M.ai3dUtils).getGen3DModelLocalInfoByTaskId(task_id);
355
+ // Absent until the account's first AI 3D result.
356
+ fs.mkdirSync(path.dirname(info.zipLocalPath), { recursive: true });
357
+ if (!fs.existsSync(info.zipLocalPath)) await this.mod(M.lokiUtils).downloadTemplateFile(url, info.zipLocalPath, DOWNLOAD_TIMEOUT_MS);
358
+ if (!fs.existsSync(info.unzipLocalPath)) this.ai3dRun('ditto', ['-x', '-k', info.zipLocalPath, info.unzipLocalPath]);
359
+ const spec = IMPORT[kind];
360
+ const result = info[spec.file];
361
+ if (!fs.existsSync(result)) throw Error(`AI3D_RESULT_MISSING: ${path.basename(result)} is not in task ${task_id}'s result; is it a ${kind} task?`);
362
+ const I18n = this.mod(M.orionui).I18n;
363
+ let file;
364
+ if (kind === 'image') file = path.join(info.unzipLocalPath, `${I18n.t('ai_3d_generation')}.glb`);
365
+ else if (kind === 'gs') file = path.join(info.unzipLocalPath, '视频生3DGS模型.ply');
366
+ else {
367
+ // The panel names the copy after the model the task was made with.
368
+ const record = await this.ai3dRecord('animation', task_id);
369
+ const { model } = taskInput('animation', record || {});
370
+ const name = Object.prototype.hasOwnProperty.call(PRESET_MODELS, model) ? `${I18n.t(PRESET_MODELS[model])}.fbx` : model || `${task_id}.fbx`;
371
+ file = path.join(info.unzipLocalPath, 'animationResult', name);
372
+ fs.mkdirSync(path.dirname(file), { recursive: true });
373
+ }
374
+ if (!fs.existsSync(file)) fs.copyFileSync(result, file);
375
+ const before = sceneObjectSet(sceneEditor);
376
+ const beforePaths = new Set(projectResources(project).map((r) => r.assetPath));
377
+ const RIH = this.mod(M.resImport).ResourceImportHandles;
378
+ let item;
379
+ try {
380
+ const pending = RIH.importExtAsset([file], false, undefined, true, { enablePopupWindow: false });
381
+ item = await new Promise((resolve) => RIH.registerLoadingCallbackByResItem(pending, (res, state) => resolve(state === 'loaded' ? res : null)));
382
+ } finally {
383
+ // The editor keeps the animation copy and removes the other two once imported.
384
+ if (kind !== 'animation') fs.rmSync(file, { force: true });
385
+ }
386
+ if (!item) throw Error(`AI3D_IMPORT_FAILED: the editor could not import ${path.basename(file)}`);
387
+ const tag = { id: `${spec.idPrefix}${task_id}`, styleTag: '', type: spec.type };
388
+ for (const r of [item, ...(item.subResourceItems || [])]) {
389
+ if (!r) continue;
390
+ r.assetPackageID = tag.id;
391
+ r.assetStudioData = { ...tag };
392
+ }
393
+ const created = EF.Extension.Scene.AssetSceneObjectCreationSystem.createSceneObjectFromAssetWithUndo({
394
+ sceneEditor,
395
+ resItems: [item],
396
+ onDoUndoRedo: () => EF.SceneView.SceneView.repaintAll(),
397
+ });
398
+ for (const so of created) {
399
+ if (kind === 'image') {
400
+ const scale = so.getChildren()[0];
401
+ scale.target.getComponent('Transform').localScale = new EF.APJS.Vector3f(15, 15, 15);
402
+ scale.name = I18n.t('ai_3d_generation_scale');
403
+ scale.getChildren()[0].name = I18n.t('ai_3d_generation_mesh');
404
+ } else if (kind === 'gs') {
405
+ so.target.getComponent('Transform').localScale = new EF.APJS.Vector3f(0.3, 0.3, 0.3);
406
+ }
407
+ }
408
+ const added = addedObjectEditors(before, sceneEditor);
409
+ if (!added.length) throw Error(`AI3D_IMPORT_NO_OBJECT: ${path.basename(file)} was imported but nothing was added to the scene`);
410
+ const packageFolders = packageRootsAdded(project, beforePaths);
411
+ recordImport(project, added, packageFolders);
412
+ return {
413
+ task_id,
414
+ kind,
415
+ added_objects: added.map((o) => ({ name: o.name, object_path: sceneObjectPath(o) })),
416
+ package_folders: packageFolders,
417
+ ...this.ai3dLocal(task_id),
418
+ };
419
+ },
420
+
421
+ async ai3dCancel({ task_id }) {
422
+ this.ensureCompatible('ai3d');
423
+ if (typeof task_id !== 'string' || !task_id) throw Error('INVALID_TASK_ID: task_id must be a non-empty string');
424
+ const res = await this.mod(M.aiEffectApi).cancelAIGCRequest({ taskId: task_id });
425
+ if (!res || res.code !== 0) throw Error(`AI3D_CANCEL_FAILED: task ${task_id} code=${res && res.code} message=${(res && res.message) || ''}`);
426
+ return { task_id, cancelled: true };
427
+ },
428
+ };
429
+
430
+ const METHODS = {
431
+ ai3d_image_submit: 'ai3dImageSubmit',
432
+ ai3d_animation_submit: 'ai3dAnimationSubmit',
433
+ ai3d_gs_segment: 'ai3dGsSegment',
434
+ ai3d_gs_submit: 'ai3dGsSubmit',
435
+ ai3d_tasks: 'ai3dTasks',
436
+ ai3d_task: 'ai3dTask',
437
+ ai3d_import: 'ai3dImport',
438
+ ai3d_cancel: 'ai3dCancel',
439
+ };
440
+
441
+ module.exports = { methods, METHODS, GEN_TYPE, FACE_NUM, IMAGE_LIMIT, VIDEO_LIMIT, MAX_RUNNING, PRESET_MODELS, REQUIRED_BONES, HISTORY_PAGE };
@@ -148,6 +148,39 @@ const REQUIRED = {
148
148
  [M.aiGraphManager, 'AIGraphManager.prototype.editorPanelApply'],
149
149
  [M.events, 'BusinessEventManager.TypeGuard'],
150
150
  ],
151
+ ai3d: [
152
+ [M.ai3dConst, 'AIGen3DModelScene.Image'],
153
+ [M.ai3dConst, 'AIGen3DModelScene.Animation'],
154
+ [M.ai3dConst, 'AIGen3DModelScene.Video'],
155
+ [M.ai3dConst, 'AIGenModelIdMap.Image'],
156
+ [M.ai3dConst, 'AIGenModelIdMap.Animation'],
157
+ [M.ai3dConst, 'AIGenModelIdMap.Video'],
158
+ [M.ai3dConst, 'AIGen3DModelQueryStatus'],
159
+ [M.ai3dConst, 'AIGen3DFolder'],
160
+ [M.ai3dUtils, 'getGen3DModelLocalInfoByTaskId'],
161
+ [M.aiEffectApi, 'submitAIGCRequest'],
162
+ [M.aiEffectApi, 'queryAIGCResult'],
163
+ [M.aiEffectApi, 'queryAITaskHistories'],
164
+ [M.aiEffectApi, 'cancelAIGCRequest'],
165
+ [M.uploadApi, 'uploadFileCommon'],
166
+ [M.uploadApi, 'uploadToSpace'],
167
+ [M.uploadApi, 'FileType.Picture'],
168
+ [M.aigcUtils, 'getAIGCEnv'],
169
+ [M.lokiUtils, 'downloadTemplateFile'],
170
+ [M.aiApiUtils, 'QueryTaskResult'],
171
+ [M.resImport, 'ResourceImportHandles.importExtAsset'],
172
+ [M.resImport, 'ResourceImportHandles.registerLoadingCallbackByResItem'],
173
+ [M.preview, 'PreviewManager.getInstance'],
174
+ [M.preview, 'PreviewManager.prototype.checkIsValidVideoFile'],
175
+ [M.preview, 'PreviewManager.prototype.getFirstNonBlackFrame'],
176
+ [M.ef, 'APJS.FbxLoaderAPJSWrapper.createFromPathAsync'],
177
+ [M.ef, 'ImportLimitationNumber.BONE_NUM_LIMIT'],
178
+ [M.ef, 'ImportLimitationNumber.SKIN_MESH_TRIANGLE_HARD_NUM_LIMIT'],
179
+ [M.ef, 'Extension.Scene.AssetSceneObjectCreationSystem.createSceneObjectFromAssetWithUndo'],
180
+ [M.ef, 'SceneView.SceneView.repaintAll'],
181
+ [M.orionui, 'I18n.t'],
182
+ [M.globalConfig, 'url'],
183
+ ],
151
184
  };
152
185
 
153
186
  // Plain asset lists, 素材广场 and 收藏 can be applied; AI generation panels (妆容/图片/视频/实时变脸 UGC)
@@ -57,6 +57,14 @@ const M = {
57
57
  editWindow: '@orion/Business/EditWindow/EditWindowController',
58
58
  aiGraphManager: '@orion/Business/AIEffectWindow/AICombinationToolPanel/Core/Manager/AIGraphManager',
59
59
  aiGraphProject: '@orion/Business/AIEffectWindow/AICombinationToolPanel/Core/AIGraphProjectUtils',
60
+ ai3dConst: '@orion/Business/AssetsLibrary/Core/Control/AI3DManager/const',
61
+ ai3dUtils: '@orion/Business/AssetsLibrary/Core/Control/AI3DManager/utils',
62
+ uploadApi: '@orion/Business/API/upload_api',
63
+ aigcUtils: '@orion/Business/Utils/utils',
64
+ lokiUtils: '@orion/Business/Utils/LokiAsset/utils',
65
+ aiApiUtils: '@orion/Business/AIEffectWindow/controller/apiUtils',
66
+ resImport: '@orion/Business/ResItemExtraData/ResourceImportHandles',
67
+ globalConfig: '@orion/config/LegacyGlobalConfig',
60
68
  };
61
69
 
62
70
  // Scratch folder under the editor instance for exports this plugin makes and removes itself.
@@ -25,10 +25,11 @@ const music = require('./features/music.cjs');
25
25
  const preview = require('./features/preview.cjs');
26
26
  const search = require('./features/search.cjs');
27
27
  const aicombine = require('./features/aicombine.cjs');
28
+ const ai3d = require('./features/ai3d.cjs');
28
29
  const dev = require('./features/dev.cjs');
29
30
 
30
31
  const { Library } = assets;
31
- const features = [menu, facewarp, project, cleanup, works, square, delivery, community, music, preview, search, aicombine, dev];
32
+ const features = [menu, facewarp, project, cleanup, works, square, delivery, community, music, preview, search, aicombine, ai3d, dev];
32
33
  for (const f of features) Object.assign(Library.prototype, f.methods);
33
34
 
34
35
  // RPC method name -> Library method; the runtime dispatches through this table.
@@ -50,4 +51,10 @@ module.exports = {
50
51
  RANK_TYPES: community.RANK_TYPES,
51
52
  RANK_FILTERS: community.RANK_FILTERS,
52
53
  CONFIG_PATH: dev.CONFIG_PATH,
54
+ AI3D_FACE_NUM: ai3d.FACE_NUM,
55
+ AI3D_IMAGE_LIMIT: ai3d.IMAGE_LIMIT,
56
+ AI3D_VIDEO_LIMIT: ai3d.VIDEO_LIMIT,
57
+ AI3D_MAX_RUNNING: ai3d.MAX_RUNNING,
58
+ AI3D_PRESET_MODELS: ai3d.PRESET_MODELS,
59
+ AI3D_HISTORY_PAGE: ai3d.HISTORY_PAGE,
53
60
  };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@muqian/xiangsu-mcp-plus",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "mcpName": "io.github.Muqian-Sun/xiangsu-mcp-plus",
5
5
  "type": "module",
6
- "description": "Unofficial MCP server for Douyin AR (像塑) on macOS: proxies the official MCP and adds the official asset library, add-object menu, AI combine workflows, delivery (icon, effect checks, submit window, phone preview), Douyin music, inspirations, tasks and rank boards, review status, FaceWarpX intensity and project windows. For learning and personal creation only; do not use it to copy other creators' works.",
6
+ "description": "Unofficial MCP server for Douyin AR (像塑) on macOS: proxies the official MCP and adds the official asset library, add-object menu, AI combine workflows, AI 3D generation, delivery (icon, effect checks, submit window, phone preview), Douyin music, inspirations, tasks and rank boards, review status, FaceWarpX intensity and project windows. For learning and personal creation only; do not use it to copy other creators' works.",
7
7
  "keywords": [
8
8
  "mcp",
9
9
  "model-context-protocol",
package/src/server.mjs CHANGED
@@ -25,10 +25,12 @@ import { QrCodes } from './qrcodes.mjs';
25
25
  import { CallLog } from './calllog.mjs';
26
26
  import { MediaRefs, REF_PATTERN, Spill, withRefs } from './outputs.mjs';
27
27
 
28
- const { INNOVATION_KINDS, MAX_MENU_PREVIEW, RANK_TYPES, RANK_FILTERS } = createRequire(import.meta.url)('../editor-plugin/library.cjs');
28
+ const { INNOVATION_KINDS, MAX_MENU_PREVIEW, RANK_TYPES, RANK_FILTERS, AI3D_FACE_NUM, AI3D_IMAGE_LIMIT, AI3D_VIDEO_LIMIT, AI3D_MAX_RUNNING, AI3D_PRESET_MODELS, AI3D_HISTORY_PAGE } = createRequire(
29
+ import.meta.url,
30
+ )('../editor-plugin/library.cjs');
29
31
  const rankFilter = (key) => z.array(z.enum(Object.keys(RANK_FILTERS[key].options))).optional();
30
32
  const LIBRARY_PANELS_TEXT =
31
- 'general 为普通面板(如 3d_distortion=脸部变形/3D 变形、distortion=美型、gaoguai_gan/makeup_gan=AI 实时变脸、3d_makeup=美妆、3d_filter=滤镜、sticker=跟脸贴纸);square 为 aigc_material=素材广场(其他创作者分享的素材,含现成的 AI 图片、AI 妆容、自定义实时变脸,应用时不重新生成、不扣额度);collection 为 collection=收藏(当前账号收藏的素材)。需要扣额度现生成的 AI 面板不在其中。';
33
+ 'general 为普通面板(如 3d_distortion=脸部变形/3D 变形、distortion=美型、gaoguai_gan/makeup_gan=AI 实时变脸、3d_makeup=美妆、3d_filter=滤镜、sticker=跟脸贴纸);square 为 aigc_material=素材广场(其他创作者分享的素材,含现成的 AI 图片、AI 妆容、自定义实时变脸,应用时不重新生成、不扣额度);collection 为 collection=收藏(当前账号收藏的素材)。现生成的 AI 面板不在其中;其中「AI 3D」(图生 3D 模型、3D 动画、高精度模型重建)用 ai3d_* 工具。';
32
34
  const RANK_TYPE_TEXT = Object.entries(RANK_TYPES).map(([k, name]) => `${k} ${name}`).join('、');
33
35
 
34
36
  const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
@@ -54,6 +56,14 @@ const OFFICIAL_SHOT_SIDE = 569;
54
56
  const QR_TTL_SEC = 604800;
55
57
  // Picked: the expiry timer fires this long after the code expires, so the clock has surely passed it.
56
58
  const QR_PRUNE_SLACK_MS = 1000;
59
+ // Picked, not measured: the subject step usually takes about 20 s (the editor's own estimate); six times that.
60
+ const AI3D_SEGMENT_WAIT_S = 120;
61
+ // Picked, not measured: long enough for one wait to cover a typical generation, short of the client's patience.
62
+ const AI3D_MAX_WAIT_S = 600;
63
+ // Derived: uploads (60 s each in the editor's upload API) plus the submit call, with room to spare.
64
+ const AI3D_SUBMIT_TIMEOUT_MS = 300000;
65
+ // Picked, not measured: the result download (30 s in the editor) plus the import.
66
+ const AI3D_IMPORT_TIMEOUT_MS = 180000;
57
67
  // Picked, not measured: as many images per image_view call as the old preview tools showed.
58
68
  const IMAGE_VIEW_MAX = 8;
59
69
  // Derived: the SDK's stdio transport drops a message over 10 MiB and with it the connection, and six
@@ -158,6 +168,8 @@ export function createServer(deps = {}) {
158
168
  const seenWorks = new Seen('UNKNOWN_WORK', 'works_list, works_search or works_by_effect');
159
169
  const seenTasks = new Seen('UNKNOWN_TASK', 'tasks_list', 'task_id');
160
170
  const seenMusic = new Seen('UNKNOWN_MUSIC', 'music_list', 'music_id');
171
+ // Subjects found by ai3d_gs_segment, kept here so ai3d_gs_submit only needs the segment task id.
172
+ const segments = new Map();
161
173
 
162
174
  // Background windows draw at 6 fps; the plugin holds full rate until released, or by itself until
163
175
  // hold_ms runs out if the release never arrives.
@@ -970,6 +982,101 @@ export function createServer(deps = {}) {
970
982
  shape: { ...target, graph_id: z.string().min(1).describe('ai_combine_new 或官方 get_workflow_context 返回的 ai_graph_id。') },
971
983
  run: plugin('ai_combine_apply', 180000),
972
984
  },
985
+ {
986
+ name: 'ai3d_image_submit',
987
+ description: `素材库「AI 3D › 3D模型」(图生 3D):上传一张参考图,在云端生成 3D 模型(静态网格,没有骨骼和动画),返回 task_id。参考图须是 ${AI3D_IMAGE_LIMIT.exts.join(' / ').toUpperCase()}、不超过 ${AI3D_IMAGE_LIMIT.maxMB} MB、长宽不超过 ${AI3D_IMAGE_LIMIT.maxSide} 像素;主体完整清晰、无遮挡,背景尽量纯色(编辑器的建议)。卡通角色可以先用官方 generate_image 出一张正面全身、纯色背景的图再交给本工具。同一类型最多同时跑 ${AI3D_MAX_RUNNING} 个任务。之后用 ai3d_tasks(带 task_id 和 wait_s)等它完成,再用 ai3d_import 放进工程。是否扣账号额度以编辑器为准,编辑器代码里没有相关提示。`,
988
+ shape: {
989
+ ...target,
990
+ image_path: z.string().min(1).describe('参考图的绝对路径。'),
991
+ precision: z
992
+ .enum(Object.keys(AI3D_FACE_NUM))
993
+ .optional()
994
+ .describe(`精度(面数):${Object.entries(AI3D_FACE_NUM).map(([k, v]) => `${k}=${v}`).join('、')},对应编辑器的低 / 中 / 高面数;默认 medium。`),
995
+ },
996
+ run: async (a) => {
997
+ const { project_path, instance_id, ...params } = a;
998
+ return text(await d.callPlugin('ai3d_image_submit', params, { ...(await homeWindow({ project_path, instance_id })), timeoutMs: AI3D_SUBMIT_TIMEOUT_MS }));
999
+ },
1000
+ },
1001
+ {
1002
+ name: 'ai3d_animation_submit',
1003
+ description: `素材库「AI 3D › 3D动画」:把参考视频里人的动作做成动画,套到一个带标准人形骨骼的 FBX 上,返回 task_id。model 可选内置的 ${Object.keys(AI3D_PRESET_MODELS).join(' / ')}(全身 / 上半身 / 下半身 / 手臂,编辑器自带的人形模型),或一个本地 .fbx 的绝对路径:须有骨骼(Hips、Spine、LeftUpLeg 等 20 根标准人形骨骼,名字完全一致、不带 mixamorig_ 前缀,缺了编辑器也只提醒,返回里会有 warning),骨骼和面数不超过编辑器的导入上限。参考视频须是 ${AI3D_VIDEO_LIMIT.animation.exts.join(' / ').toUpperCase()}、不超过 ${AI3D_VIDEO_LIMIT.animation.maxSeconds} 秒、${AI3D_VIDEO_LIMIT.animation.maxMB} MB、长宽不超过 ${AI3D_VIDEO_LIMIT.animation.maxSide},建议单人、全身出镜。图生 3D(ai3d_image_submit)出来的模型没有骨骼,不能直接用作 model。之后 ai3d_tasks 等完成、ai3d_import 导入(导入的是带动画的 FBX)。`,
1004
+ shape: {
1005
+ ...target,
1006
+ video_path: z.string().min(1).describe('参考视频的绝对路径。'),
1007
+ model: z.string().min(1).optional().describe(`${Object.keys(AI3D_PRESET_MODELS).join(' / ')} 之一,或本地 .fbx 的绝对路径;默认 whole。`),
1008
+ },
1009
+ run: async (a) => {
1010
+ const { project_path, instance_id, ...params } = a;
1011
+ return text(await d.callPlugin('ai3d_animation_submit', params, { ...(await homeWindow({ project_path, instance_id })), timeoutMs: AI3D_SUBMIT_TIMEOUT_MS }));
1012
+ },
1013
+ },
1014
+ {
1015
+ name: 'ai3d_gs_segment',
1016
+ refs: true,
1017
+ description: `素材库「AI 3D › 高精度模型重建」第一步:上传一段实物 360 度环绕视频,云端识别出要重建的主体,返回 seg_task_id 和主体图 subject_image_ref(交给 image_view 看)。确认主体没问题后用 ai3d_gs_submit 正式生成 3D 高斯点云(.ply);主体不对就换视频或重拍。视频须是 ${AI3D_VIDEO_LIMIT.gs.exts.join(' / ').toUpperCase()}、不超过 ${AI3D_VIDEO_LIMIT.gs.maxSeconds} 秒、${AI3D_VIDEO_LIMIT.gs.maxMB} MB、长宽不超过 ${AI3D_VIDEO_LIMIT.gs.maxSide},主体清晰、光线充足、各角度都拍到。识别一般约 20 秒,最多等 wait_s 秒,超时编辑器会取消这次识别。`,
1018
+ shape: {
1019
+ ...target,
1020
+ video_path: z.string().min(1).describe('环绕视频的绝对路径。'),
1021
+ wait_s: z.number().int().min(10).max(AI3D_MAX_WAIT_S).optional().describe(`最多等待识别的秒数,默认 ${AI3D_SEGMENT_WAIT_S}。`),
1022
+ },
1023
+ run: async (a) => {
1024
+ const { project_path, instance_id, wait_s = AI3D_SEGMENT_WAIT_S, ...params } = a;
1025
+ const got = await d.callPlugin('ai3d_gs_segment', { ...params, wait_s }, { ...(await homeWindow({ project_path, instance_id })), timeoutMs: AI3D_SUBMIT_TIMEOUT_MS + wait_s * 1000 });
1026
+ segments.set(got.seg_task_id, { subject_uri: got.subject_uri, req_json: got.req_json });
1027
+ return text({ seg_task_id: got.seg_task_id, subject_image_url: got.subject_image_url });
1028
+ },
1029
+ },
1030
+ {
1031
+ name: 'ai3d_gs_submit',
1032
+ description: '素材库「AI 3D › 高精度模型重建」第二步:按 ai3d_gs_segment 识别出的主体正式生成 3D 高斯点云,等同识别窗口里的「确认主体」,返回 task_id。之后 ai3d_tasks(kind=gs)等完成、ai3d_import 导入。',
1033
+ shape: { ...target, seg_task_id: z.string().min(1).describe('ai3d_gs_segment 返回的 seg_task_id。') },
1034
+ run: async (a) => {
1035
+ const { project_path, instance_id, seg_task_id } = a;
1036
+ const seg = segments.get(seg_task_id);
1037
+ if (!seg) throw Error(`UNKNOWN_SEGMENT: ${seg_task_id}; call ai3d_gs_segment first`);
1038
+ return text(await d.callPlugin('ai3d_gs_submit', seg, { ...(await homeWindow({ project_path, instance_id })), timeoutMs: AI3D_SUBMIT_TIMEOUT_MS }));
1039
+ },
1040
+ },
1041
+ {
1042
+ name: 'ai3d_tasks',
1043
+ description: `素材库「AI 3D」的生成任务(当前账号)。不传 task_id 时按 kind 分页列出历史任务:状态(running / finished / failed)、创建和完成时间、输入(图生 3D 的精度、3D 动画的模型)、失败原因,以及结果是否已下载到本机和本机的预览图 / 预览视频(preview_image_file 交给 image_view 看)。传 task_id 时只查这一个;再给 wait_s 就一直等到它不再是 running 或时间到(最多 ${AI3D_MAX_WAIT_S} 秒),status=finished 后用 ai3d_import 导入。`,
1044
+ shape: {
1045
+ ...target,
1046
+ kind: z.enum(['image', 'animation', 'gs']).describe('image=3D模型(图生 3D)、animation=3D动画、gs=高精度模型重建。'),
1047
+ task_id: z.string().min(1).optional().describe('只查这个任务。'),
1048
+ wait_s: z.number().int().min(0).max(AI3D_MAX_WAIT_S).optional().describe('配合 task_id:最多等多少秒,默认 0(只查一次)。'),
1049
+ cursor: z.number().int().min(0).optional().describe('翻页游标,原样取上一页的 next_cursor。'),
1050
+ count: z.number().int().min(1).max(AI3D_HISTORY_PAGE).optional().describe(`每页数量,默认 ${AI3D_HISTORY_PAGE}(服务端上限)。`),
1051
+ },
1052
+ run: async (a) => {
1053
+ const { project_path, instance_id, kind, task_id, wait_s = 0, cursor, count } = a;
1054
+ const win = await homeWindow({ project_path, instance_id });
1055
+ if (task_id !== undefined) return text({ kind, ...(await d.callPlugin('ai3d_task', { task_id, wait_s }, { ...win, timeoutMs: wait_s * 1000 + 30000 })) });
1056
+ if (a.wait_s !== undefined) throw Error('INVALID_ARGUMENTS: wait_s only applies together with task_id');
1057
+ return text(await d.callPlugin('ai3d_tasks', { kind, cursor, count }, win));
1058
+ },
1059
+ },
1060
+ {
1061
+ name: 'ai3d_import',
1062
+ description:
1063
+ '把一个已完成的 AI 3D 任务结果下载到编辑器的 AI 3D 缓存目录(面板里同样能看到),导入工程并放进场景(可撤销),与面板里勾选后点「导入素材」相同:图生 3D 导入 GLB(外层对象「模型大小控制」放大 15 倍)、3D 动画导入带动画的 FBX、高精度模型重建导入 PLY 点云(缩小到 0.3)。返回 added_objects(新对象名和 object_path)、package_folders 和本机预览文件。之后用 capture_preview 看大小和位置,save_project。',
1064
+ shape: {
1065
+ ...target,
1066
+ task_id: z.string().min(1).describe('ai3d_*_submit 或 ai3d_tasks 返回的 task_id。'),
1067
+ kind: z.enum(['image', 'animation', 'gs']).describe('任务类型,与提交时一致。'),
1068
+ },
1069
+ run: plugin('ai3d_import', AI3D_IMPORT_TIMEOUT_MS),
1070
+ },
1071
+ {
1072
+ name: 'ai3d_cancel',
1073
+ description: '取消一个还在 running 的 AI 3D 生成任务(等同面板里的「取消生成」)。',
1074
+ shape: { ...target, task_id: z.string().min(1).describe('要取消的 task_id。') },
1075
+ run: async (a) => {
1076
+ const { project_path, instance_id, task_id } = a;
1077
+ return text(await d.callPlugin('ai3d_cancel', { task_id }, await homeWindow({ project_path, instance_id })));
1078
+ },
1079
+ },
973
1080
  {
974
1081
  name: 'face_warp_list',
975
1082
  description: '列出场景里所有「塑型画笔」组件(FaceWarpX,含猫脸/狗脸),返回 object_path、是否启用、每项画笔的序号与强度。官方 set_component 改不了画笔强度,用 face_warp_set_intensity。',