@muqian/xiangsu-mcp-plus 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,318 @@
1
+ 'use strict';
2
+ // AR 视频贴片 (素材库 › AI 素材 › AR 视频): a subject image or video, optionally with a motion prompt and
3
+ // reference media, becomes a matted video of the subject (Seedance in the cloud, matting and packing on
4
+ // this machine) that is placed in the scene as an AR plane. Everything goes through the ARVideoManager the
5
+ // panel itself uses (AssetsLibrary.getInstance().arVideoManager), so its input checks and conversions,
6
+ // audits, local composition, history cache and the toolbar's background task list stay the editor's own.
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const crypto = require('crypto');
10
+ const { M, STATE_ROOT, editingScene, sceneObjectSet, addedObjectEditors, sceneObjectPath, projectResources, packageRootsAdded, recordImport } = require('./common.cjs');
11
+
12
+ const MODES = ['direct', 'motion'];
13
+ // Picked: often enough to return soon after the cloud accepts the task, cheap since it only reads memory.
14
+ const SUBMIT_POLL_MS = 500;
15
+ // Picked, not measured: input conversion, uploads (60 s each in the editor) and the submit call (60 s).
16
+ const ACCEPT_TIMEOUT_MS = 240000;
17
+ // Derived: the editor's own audit gives up after AR_VIDEO_VIDEO_AUDIT_TIMEOUT_MS; this only guards a hang.
18
+ const AUDIT_SLACK_MS = 60000;
19
+ // Picked, as for AI 3D: often enough to notice a finished task soon.
20
+ const POLL_MS = 3000;
21
+ // Same as the panel's history page.
22
+ const HISTORY_PAGE = 20;
23
+ // Picked: how far back a task_id is looked up; 10 pages of 20 reach well past what anyone imports from.
24
+ const HISTORY_PAGES = 10;
25
+ // Picked: six frames show a 4–15 s move well enough to judge it; 320 px high keeps the strip under 200 KB.
26
+ const STRIP_FRAMES = 6;
27
+ const STRIP_HEIGHT = 320;
28
+ const QUOTA_NOTE =
29
+ '会占用账号的 AI 模型使用次数:次数按特效师等级给,用完时报「模型使用次数达到上限,请提升特效师等级以获取更多次数」(错误码 2038)。编辑器里没有查询剩余次数或单次扣多少的接口,这里给不出具体数字。';
30
+
31
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
32
+ const iso = (ms) => (ms ? new Date(ms).toISOString() : null);
33
+ const exists = (p) => typeof p === 'string' && p !== '' && fs.existsSync(p);
34
+
35
+ function checkPath(file, what) {
36
+ if (typeof file !== 'string' || !path.isAbsolute(file)) throw Error(`${what}_PATH_NOT_ABSOLUTE: ${file}`);
37
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw Error(`${what}_NOT_FOUND: ${file}`);
38
+ return file;
39
+ }
40
+
41
+ // The panel's own reading of a request: a video subject with no prompt and no references is matted as it
42
+ // is; anything else has Seedance make the motion.
43
+ function modeOf(request) {
44
+ const r = request || {};
45
+ return r.subject && r.subject.type === 'video' && !String(r.prompt || '').trim() && !(r.references || []).length ? 'direct' : 'motion';
46
+ }
47
+
48
+ const methods = {
49
+ arVideo() {
50
+ return this.mod(M.assetsLibrary).AssetsLibrary.getInstance().arVideoManager;
51
+ },
52
+
53
+ arVideoLimits() {
54
+ const C = this.mod(M.arVideoContract);
55
+ return {
56
+ min_duration_s: C.AR_VIDEO_MIN_DURATION_SECONDS,
57
+ max_duration_s: C.getARVideoMaxOutputDurationSeconds(),
58
+ default_duration_s: C.AR_VIDEO_DEFAULT_DURATION_SECONDS,
59
+ max_total_input_video_s: C.getARVideoMaxTotalVideoDurationMs() / 1000,
60
+ max_images: C.AR_VIDEO_MAX_IMAGE_COUNT,
61
+ max_videos: C.AR_VIDEO_MAX_VIDEO_COUNT,
62
+ max_prompt_length: C.AR_VIDEO_MAX_PROMPT_LENGTH,
63
+ shadow_default: C.getARVideoWithShadowDefault(),
64
+ };
65
+ },
66
+
67
+ arVideoEnsureEnabled() {
68
+ this.ensureCompatible('arVideo');
69
+ if (!this.mod(M.nav).isARVideoEntryEnabled()) throw Error('AR_VIDEO_DISABLED: 素材库里没有「AR 视频」入口(编辑器开关 dyeh_enable_ar_video_entry 没有打开)');
70
+ },
71
+
72
+ // Waits until the editor's audit of an uploaded video has passed; the editor rejects it itself on timeout.
73
+ async arVideoAudited(mgr, media) {
74
+ const A = this.mod(M.arVideoAudit);
75
+ const until = Date.now() + this.mod(M.arVideoContract).AR_VIDEO_VIDEO_AUDIT_TIMEOUT_MS + AUDIT_SLACK_MS;
76
+ const poll = this.arVideoSubmitPollMs ?? SUBMIT_POLL_MS;
77
+ for (;;) {
78
+ const state = mgr.getAuditState(media);
79
+ if (state && state.status === A.ARVideoAuditStatus.Rejected) throw Error(`AR_VIDEO_AUDIT_REJECTED: ${path.basename(media.sourcePath || media.path)}: ${state.message || ''}`);
80
+ if (!A.isAuditPending(state)) return;
81
+ if (Date.now() + poll > until) throw Error(`AR_VIDEO_AUDIT_TIMEOUT: ${path.basename(media.sourcePath || media.path)} is still being audited`);
82
+ await sleep(poll);
83
+ }
84
+ },
85
+
86
+ async arVideoSubmit({ subject, mode, prompt = '', reference_images = [], reference_video, shadow, duration_s }) {
87
+ this.arVideoEnsureEnabled();
88
+ const C = this.mod(M.arVideoContract);
89
+ const limits = this.arVideoLimits();
90
+ if (!MODES.includes(mode)) throw Error(`INVALID_MODE: ${mode}; valid: ${MODES.join(', ')}`);
91
+ checkPath(subject, 'SUBJECT');
92
+ const subjectType = C.classifyARVideoMedia(subject);
93
+ if (!subjectType) throw Error(`SUBJECT_FORMAT: ${path.basename(subject)}; 素材仅支持 JPG、JPEG、PNG、MP4、MOV`);
94
+ const refs = [...reference_images.map((f) => [f, 'image']), ...(reference_video === undefined ? [] : [[reference_video, 'video']])];
95
+ for (const [f, type] of refs) {
96
+ checkPath(f, 'REFERENCE');
97
+ if (C.classifyARVideoMedia(f) !== type) throw Error(`REFERENCE_FORMAT: ${path.basename(f)} is not ${type === 'image' ? 'a JPG / JPEG / PNG image' : 'an MP4 / MOV video'}`);
98
+ }
99
+ const text = String(prompt).trim();
100
+ if (mode === 'direct') {
101
+ if (subjectType !== 'video') throw Error('INVALID_ARGUMENTS: mode=direct only mattes a subject video as it is; an image subject needs mode=motion and a prompt');
102
+ if (text || refs.length) throw Error('INVALID_ARGUMENTS: mode=direct takes no prompt and no references (with them the editor generates a new motion); use mode=motion');
103
+ } else if (!text) throw Error('INVALID_ARGUMENTS: mode=motion needs a prompt describing the motion');
104
+ if (text.length > limits.max_prompt_length) throw Error(`PROMPT_TOO_LONG: ${text.length} characters; the limit is ${limits.max_prompt_length}`);
105
+ const seconds = duration_s ?? limits.default_duration_s;
106
+ if (!Number.isInteger(seconds) || seconds < limits.min_duration_s || seconds > limits.max_duration_s) throw Error(`INVALID_DURATION: ${seconds}; 动作时长需要在 ${limits.min_duration_s}-${limits.max_duration_s} 秒之间(上限由编辑器开关 dyeh_ar_video_max_output_duration_s 决定)`);
107
+ try {
108
+ C.validateARVideoInputCounts([{ type: subjectType }, ...refs.map(([, type]) => ({ type }))]);
109
+ } catch (e) {
110
+ throw Error(`AR_VIDEO_TOO_MANY_INPUTS: ${e.message}`);
111
+ }
112
+
113
+ const mgr = this.arVideo();
114
+ const MC = this.mod(M.arVideoManager);
115
+ await mgr.refreshRecords();
116
+ if (mgr.activeTaskCount >= MC.AR_VIDEO_MAX_CONCURRENT_TASKS) throw Error(`AR_VIDEO_TOO_MANY_RUNNING: ${MC.AR_VIDEO_CONCURRENT_LIMIT_MESSAGE}`);
117
+
118
+ // The panel's own input step: copy, check against the Seedance limits, convert if needed, audit videos.
119
+ const abort = new AbortController();
120
+ const media = [];
121
+ try {
122
+ for (const [file, role] of [[subject, 'subject'], ...refs.map(([f]) => [f, 'reference'])]) {
123
+ let m;
124
+ try {
125
+ m = await mgr.captureInput(file, media.slice(), abort.signal, role);
126
+ } catch (e) {
127
+ throw Error(`AR_VIDEO_INPUT_INVALID: ${path.basename(file)}: ${e.message}`);
128
+ }
129
+ media.push(m);
130
+ }
131
+ for (const m of media) if (m.type === 'video') await this.arVideoAudited(mgr, m);
132
+ } catch (e) {
133
+ abort.abort();
134
+ for (const m of media) mgr.discardAudit(m);
135
+ throw e;
136
+ }
137
+
138
+ // One generation at a time belongs to the panel's editor; an earlier one moves to the background,
139
+ // as when the asset library is closed.
140
+ if (mgr.isGenerating) mgr.closeEditor();
141
+ mgr.clearError();
142
+ const request = { subject: media[0], references: media.slice(1), prompt: text, durationSeconds: seconds, withShadow: shadow ?? limits.shadow_default };
143
+ const run = mgr.generate(request);
144
+ const id = mgr.editorTaskId;
145
+ if (!id) throw Error(`AR_VIDEO_SUBMIT_REFUSED: ${mgr.operationError.getValue() || 'the editor did not start a generation'}`);
146
+ let settled = false;
147
+ run.then(
148
+ () => (settled = true),
149
+ () => (settled = true),
150
+ );
151
+ const poll = this.arVideoSubmitPollMs ?? SUBMIT_POLL_MS;
152
+ const until = Date.now() + (this.arVideoAcceptTimeoutMs ?? ACCEPT_TIMEOUT_MS);
153
+ for (;;) {
154
+ const t = mgr.tasks.getValue().find((x) => x.id === id);
155
+ if (t && t.recordTaskId) {
156
+ if (mgr.editorTaskId === id) mgr.closeEditor();
157
+ const named = mgr.tasks.getValue().find((x) => x.id === id) || t;
158
+ const out = { task_id: String(t.recordTaskId), name: named.name || null, mode, subject_type: subjectType, references: request.references.map((m) => m.type), prompt: text, duration_s: seconds, shadow: request.withShadow, quota: QUOTA_NOTE };
159
+ const trimmed = media.filter((m) => m.crop).map((m) => `${path.basename(m.sourcePath || m.path)} 超过可用时长,编辑器截取了 ${(m.crop.durationMs / 1000).toFixed(1)} 秒`);
160
+ if (trimmed.length) out.input_notes = trimmed;
161
+ return out;
162
+ }
163
+ if (t && (t.status === 'failed' || t.status === 'unconfirmed')) throw Error(`AR_VIDEO_SUBMIT_FAILED: ${t.errorMessage || t.status}${t.errorCode !== undefined ? ` (code ${t.errorCode})` : ''}`);
164
+ if (!t || settled) throw Error(`AR_VIDEO_SUBMIT_FAILED: ${mgr.operationError.getValue() || (t ? t.errorMessage : '') || 'the generation ended before the cloud accepted it'}`);
165
+ if (Date.now() + poll > until) throw Error(`AR_VIDEO_SUBMIT_TIMEOUT: not accepted by the cloud after ${Math.round((this.arVideoAcceptTimeoutMs ?? ACCEPT_TIMEOUT_MS) / 1000)} s (stage: ${t.stage}); it keeps running in the editor, check ar_video_tasks later`);
166
+ await sleep(poll);
167
+ }
168
+ },
169
+
170
+ // A strip of frames across the preview video, so the motion can be judged from one image.
171
+ async arVideoStrip(task_id, video, seconds) {
172
+ const file = path.join(STATE_ROOT, 'ar-video', `${task_id.replace(/[^\w-]/g, '_')}.jpg`);
173
+ if (fs.existsSync(file) && fs.statSync(file).mtimeMs >= fs.statSync(video).mtimeMs) return file;
174
+ fs.mkdirSync(path.dirname(file), { recursive: true });
175
+ await this.mod(M.ffmpeg).ffmpegExec(['-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-i', video, '-vf', `fps=${STRIP_FRAMES}/${seconds},scale=-2:${STRIP_HEIGHT},tile=${STRIP_FRAMES}x1`, '-frames:v', '1', '-q:v', '3', file]);
176
+ if (!fs.existsSync(file)) throw Error('ffmpeg wrote no image');
177
+ return file;
178
+ },
179
+
180
+ async arVideoView(t) {
181
+ const r = t.request || {};
182
+ const out = {
183
+ task_id: t.recordTaskId ? String(t.recordTaskId) : null,
184
+ name: t.name || null,
185
+ status: t.status,
186
+ stage: t.stage || null,
187
+ created_at: iso(t.createdAt),
188
+ mode: modeOf(r),
189
+ subject_type: r.subject ? r.subject.type : null,
190
+ references: (r.references || []).map((m) => m.type),
191
+ prompt: r.prompt ?? null,
192
+ duration_s: r.durationSeconds ?? null,
193
+ shadow: r.withShadow ?? null,
194
+ };
195
+ if (t.status === 'failed' || t.status === 'unconfirmed') out.failure = { message: t.errorMessage || null, code: t.errorCode ?? null };
196
+ const res = t.output && t.output.result;
197
+ if (t.status === 'succeeded' && res) {
198
+ const seconds = res.fps > 0 ? Number((res.frameCount / res.fps).toFixed(2)) : null;
199
+ Object.assign(out, {
200
+ seconds,
201
+ size: { width: res.sourceWidth, height: res.sourceHeight },
202
+ green_screen: !!res.greenScreen,
203
+ audio: res.audioStatus || null,
204
+ preview_video_file: exists(res.previewVideoPath) ? res.previewVideoPath : null,
205
+ video_file: exists(res.mixedVideoPath) ? res.mixedVideoPath : null,
206
+ });
207
+ if (out.preview_video_file && out.task_id && seconds) {
208
+ try {
209
+ out.preview_image_file = await this.arVideoStrip(out.task_id, out.preview_video_file, seconds);
210
+ } catch (e) {
211
+ out.preview_image_file = null;
212
+ out.preview_image_error = String(e.message || e);
213
+ }
214
+ }
215
+ }
216
+ return out;
217
+ },
218
+
219
+ // The manager's task for a cloud task id, loading older history pages when it is not among the loaded ones.
220
+ async arVideoFind(task_id) {
221
+ if (typeof task_id !== 'string' || !task_id) throw Error('INVALID_TASK_ID: task_id must be a non-empty string');
222
+ const mgr = this.arVideo();
223
+ const hit = () => mgr.tasks.getValue().find((t) => String(t.recordTaskId) === task_id);
224
+ if (hit()) return hit();
225
+ await mgr.refreshRecords();
226
+ for (let page = 1; !hit() && mgr.recordHasMore && page < HISTORY_PAGES; page++) await mgr.loadMoreRecords();
227
+ if (!hit()) throw Error(`AR_VIDEO_TASK_NOT_FOUND: ${task_id} is not in this account's latest ${HISTORY_PAGES * HISTORY_PAGE} AR 视频 tasks`);
228
+ return hit();
229
+ },
230
+
231
+ async arVideoTasks({ offset = 0, count = HISTORY_PAGE }) {
232
+ this.arVideoEnsureEnabled();
233
+ const mgr = this.arVideo();
234
+ await mgr.refreshRecords();
235
+ while (mgr.tasks.getValue().length < offset + count && mgr.recordHasMore) await mgr.loadMoreRecords();
236
+ const all = [...mgr.tasks.getValue()].sort((a, b) => b.createdAt - a.createdAt);
237
+ const items = [];
238
+ for (const t of all.slice(offset, offset + count)) items.push(await this.arVideoView(t));
239
+ const next = offset + count;
240
+ return { items, next_offset: next, has_more: next < all.length || !!mgr.recordHasMore, limits: this.arVideoLimits() };
241
+ },
242
+
243
+ // One task; with wait_s it waits until the result is composed on this machine, failed, or the time is up.
244
+ async arVideoTask({ task_id, wait_s = 0 }) {
245
+ this.arVideoEnsureEnabled();
246
+ const mgr = this.arVideo();
247
+ let t = await this.arVideoFind(task_id);
248
+ const poll = this.arVideoPollMs ?? POLL_MS;
249
+ const until = Date.now() + wait_s * 1000;
250
+ while (['running', 'restoring'].includes(t.status) && Date.now() + poll <= until) {
251
+ await sleep(poll);
252
+ t = mgr.tasks.getValue().find((x) => x.id === t.id) || (await this.arVideoFind(task_id));
253
+ }
254
+ return this.arVideoView(t);
255
+ },
256
+
257
+ // What the panel's 「导入 AR 视频贴片」 does for one task, without touching the other selected results.
258
+ async arVideoImport({ task_id }) {
259
+ this.arVideoEnsureEnabled();
260
+ const mgr = this.arVideo();
261
+ const t = await this.arVideoFind(task_id);
262
+ if (t.status !== 'succeeded' || !t.output) throw Error(`AR_VIDEO_NOT_READY: task ${task_id} is ${t.status}${t.stage ? `(${t.stage})` : ''}; wait with ar_video_tasks first`);
263
+ if (mgr.importing.getValue()) throw Error('AR_VIDEO_IMPORT_IN_PROGRESS: the panel is importing; try again when it is done');
264
+ const { sceneEditor, project } = editingScene(this);
265
+ const r = t.request;
266
+ const source = {
267
+ assetId: String(t.assetId ?? t.id),
268
+ originTaskId: String(t.acceptedTaskId ?? t.taskId ?? t.id),
269
+ originImportId: crypto.randomUUID(),
270
+ generationMode: String(t.output.usedSeedance ? this.mod(M.arVideoAnalytics).arVideoInputFields(r.subject, r.references, r.prompt).generation_mode : 'video_direct'),
271
+ };
272
+ const before = sceneObjectSet(sceneEditor);
273
+ const beforePaths = new Set(projectResources(project).map((x) => x.assetPath));
274
+ mgr.importing.next(true);
275
+ let res;
276
+ try {
277
+ res = await this.mod(M.arVideoProject).importARVideosToCurrentProject([{ result: t.output.result, source }]);
278
+ } catch (e) {
279
+ throw Error(`AR_VIDEO_IMPORT_FAILED: ${e.message}`);
280
+ } finally {
281
+ mgr.importing.next(false);
282
+ }
283
+ mgr.updateTask(t.id, { selected: false });
284
+ const added = addedObjectEditors(before, sceneEditor);
285
+ if (!added.length) throw Error(`AR_VIDEO_IMPORT_NO_OBJECT: task ${task_id} was imported but nothing was added to the scene`);
286
+ const packageFolders = packageRootsAdded(project, beforePaths);
287
+ recordImport(project, added, packageFolders);
288
+ return {
289
+ task_id,
290
+ added_objects: added.map((o) => ({ name: o.name, object_path: sceneObjectPath(o) })),
291
+ package_folders: packageFolders,
292
+ plane_guid: res.selectedPlaneGuid || null,
293
+ };
294
+ },
295
+
296
+ async arVideoCancel({ task_id }) {
297
+ this.arVideoEnsureEnabled();
298
+ const mgr = this.arVideo();
299
+ const t = await this.arVideoFind(task_id);
300
+ if (!['running', 'unconfirmed'].includes(t.status)) throw Error(`AR_VIDEO_NOT_RUNNING: task ${task_id} is ${t.status}`);
301
+ mgr.clearError();
302
+ await mgr.cancelTask(t.id);
303
+ const after = mgr.tasks.getValue().find((x) => x.id === t.id);
304
+ if (!after) return { task_id, cancelled: true };
305
+ if (mgr.operationError.getValue()) throw Error(`AR_VIDEO_CANCEL_FAILED: ${mgr.operationError.getValue()}`);
306
+ return { task_id, cancelled: false, status: after.status, note: '任务在取消前已经结束' };
307
+ },
308
+ };
309
+
310
+ const METHODS = {
311
+ ar_video_submit: 'arVideoSubmit',
312
+ ar_video_tasks: 'arVideoTasks',
313
+ ar_video_task: 'arVideoTask',
314
+ ar_video_import: 'arVideoImport',
315
+ ar_video_cancel: 'arVideoCancel',
316
+ };
317
+
318
+ module.exports = { methods, METHODS, MODES, HISTORY_PAGE };
@@ -4,7 +4,7 @@
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
  const crypto = require('crypto');
7
- const { M, body, editingScene, sceneObjectSet, addedObjectEditors, sceneObjectPath, projectResources, packageRootsAdded, recordImport } = require('./common.cjs');
7
+ const { M, body, editingScene, sceneObjectSet, addedObjectEditors, describeAdded, projectResources, packageRootsAdded, recordImport } = require('./common.cjs');
8
8
  const { SQUARE_PANEL } = require('./square.cjs');
9
9
 
10
10
  // Editor internals each feature relies on; checked up front so an editor upgrade fails with a precise list.
@@ -139,6 +139,13 @@ const REQUIRED = {
139
139
  [M.orionui, 'WindowState.Minimized'],
140
140
  [M.editWindow, 'EditWindowController.getInstance'],
141
141
  ],
142
+ makeup: [
143
+ [M.scene, 'SceneModule.getEditingSceneService'],
144
+ [M.ef, 'UndoSystem.instance.start'],
145
+ [M.ef, 'UndoSystem.instance.end'],
146
+ [M.ef, 'Resource.ResourceUndoManager.createImportUndoID'],
147
+ [M.events, 'BusinessEventManager.TypeGuard'],
148
+ ],
142
149
  aiCombine: [
143
150
  [M.aiGraphProject, 'createAIGraph'],
144
151
  [M.aiGraphManager, 'AIGraphManager.getInstance'],
@@ -181,6 +188,31 @@ const REQUIRED = {
181
188
  [M.orionui, 'I18n.t'],
182
189
  [M.globalConfig, 'url'],
183
190
  ],
191
+ arVideo: [
192
+ [M.assetsLibrary, 'AssetsLibrary.getInstance'],
193
+ [M.arVideoManager, 'AR_VIDEO_MAX_CONCURRENT_TASKS'],
194
+ [M.arVideoManager, 'AR_VIDEO_CONCURRENT_LIMIT_MESSAGE'],
195
+ ...['refreshRecords', 'loadMoreRecords', 'captureInput', 'discardAudit', 'getAuditState', 'generate', 'closeEditor', 'clearError', 'cancelTask', 'updateTask'].map((p) => [M.arVideoManager, `default.prototype.${p}`]),
196
+ ...[
197
+ 'AR_VIDEO_MIN_DURATION_SECONDS',
198
+ 'AR_VIDEO_DEFAULT_DURATION_SECONDS',
199
+ 'AR_VIDEO_MAX_IMAGE_COUNT',
200
+ 'AR_VIDEO_MAX_VIDEO_COUNT',
201
+ 'AR_VIDEO_MAX_PROMPT_LENGTH',
202
+ 'AR_VIDEO_VIDEO_AUDIT_TIMEOUT_MS',
203
+ 'getARVideoMaxOutputDurationSeconds',
204
+ 'getARVideoMaxTotalVideoDurationMs',
205
+ 'getARVideoWithShadowDefault',
206
+ 'classifyARVideoMedia',
207
+ 'validateARVideoInputCounts',
208
+ ].map((p) => [M.arVideoContract, p]),
209
+ [M.arVideoAudit, 'ARVideoAuditStatus.Rejected'],
210
+ [M.arVideoAudit, 'isAuditPending'],
211
+ [M.arVideoAnalytics, 'arVideoInputFields'],
212
+ [M.arVideoProject, 'importARVideosToCurrentProject'],
213
+ [M.nav, 'isARVideoEntryEnabled'],
214
+ [M.ffmpeg, 'ffmpegExec'],
215
+ ],
184
216
  };
185
217
 
186
218
  // Plain asset lists, 素材广场 and 收藏 can be applied; AI generation panels (妆容/图片/视频/实时变脸 UGC)
@@ -200,7 +232,8 @@ function slim(item, kind) {
200
232
  kind,
201
233
  desc: item.desc || '',
202
234
  material_type: extra.originalMaterialType || null,
203
- file_size: file.fileSize ?? null,
235
+ // Square cards all carry 3409 here (2026-11-09), the size of no file the apply downloads.
236
+ file_size: item.panelKey === SQUARE_PANEL ? null : file.fileSize ?? null,
204
237
  cover_url: cover.url || null,
205
238
  };
206
239
  }
@@ -356,7 +389,7 @@ class Library {
356
389
  package_cached: cached,
357
390
  kind: 'package',
358
391
  auto_instantiated: !!auto_instantiate,
359
- added_objects: added.map((o) => ({ name: o.name, object_path: sceneObjectPath(o) })),
392
+ added_objects: describeAdded(added, before, sceneEditor),
360
393
  package_folders: packageFolders,
361
394
  resources,
362
395
  };
@@ -65,8 +65,17 @@ const M = {
65
65
  aiApiUtils: '@orion/Business/AIEffectWindow/controller/apiUtils',
66
66
  resImport: '@orion/Business/ResItemExtraData/ResourceImportHandles',
67
67
  globalConfig: '@orion/config/LegacyGlobalConfig',
68
+ arVideoManager: '@orion/Business/AssetsLibrary/Core/Control/ARVideoManager/ARVideoManager',
69
+ arVideoContract: '@orion/Business/VideoMatting/ARVideoGenerationContract',
70
+ arVideoAudit: '@orion/Business/VideoMatting/ARVideoAudit',
71
+ arVideoAnalytics: '@orion/Business/VideoMatting/ARVideoAnalytics',
72
+ arVideoProject: '@orion/Business/VideoMatting/ARVideoProject',
73
+ ffmpeg: '@orion/Business/Utils/Ffmpeg',
68
74
  };
69
75
 
76
+ // Where this plugin keeps its own files (import records, preview strips) outside any project.
77
+ const STATE_ROOT = process.env.XIANGSU_MCP_EXT_STATE || path.join(os.homedir(), '.xiangsu-mcp-ext');
78
+
70
79
  // Scratch folder under the editor instance for exports this plugin makes and removes itself.
71
80
  function scratchDir(lib, kind) {
72
81
  const base = lib.mod(M.ef).Resource.EditorFoundation.env.getInstancePath();
@@ -141,6 +150,17 @@ function addedObjectEditors(before, sceneEditor) {
141
150
  return added.filter((o) => !fresh.has(o.parent));
142
151
  }
143
152
 
153
+ // A new object as library_apply reports it. Applying to a scene without the render group a material
154
+ // needs creates the group too, so the new object is the group (「面部面具」, 「2D 前景」); what the
155
+ // material itself added sits under it and is listed as contents.
156
+ function describeAdded(roots, before, sceneEditor) {
157
+ const fresh = sceneEditor.getAllSceneObjectEditors().filter((o) => !before.has(o));
158
+ return roots.map((o) => {
159
+ const contents = fresh.filter((c) => c.parent === o).map((c) => ({ name: c.name, object_path: sceneObjectPath(c) }));
160
+ return { name: o.name, object_path: sceneObjectPath(o), ...(contents.length ? { contents } : {}) };
161
+ });
162
+ }
163
+
144
164
  function addedObjects(before, sceneEditor) {
145
165
  return addedObjectEditors(before, sceneEditor).map((o) => ({ name: o.name, object_path: sceneObjectPath(o) }));
146
166
  }
@@ -163,7 +183,7 @@ function packageRoot(projectPath, assetPath) {
163
183
 
164
184
  // Package folders an import created, recorded against the scene objects it added, so removing those
165
185
  // objects later can also remove folders the scene never references (e.g. prefab templates).
166
- const IMPORTS_DIR = path.join(process.env.XIANGSU_MCP_EXT_STATE || path.join(os.homedir(), '.xiangsu-mcp-ext'), 'imports');
186
+ const IMPORTS_DIR = path.join(STATE_ROOT, 'imports');
167
187
 
168
188
  function importsFile(projectPath) {
169
189
  return path.join(IMPORTS_DIR, `${crypto.createHash('sha1').update(projectPath).digest('hex')}.json`);
@@ -214,6 +234,7 @@ function resolveByPath(candidates, objectPath, what) {
214
234
 
215
235
  module.exports = {
216
236
  M,
237
+ STATE_ROOT,
217
238
  scratchDir,
218
239
  exportEffectPackage,
219
240
  nextEvent,
@@ -223,6 +244,7 @@ module.exports = {
223
244
  sceneObjectSet,
224
245
  addedObjectEditors,
225
246
  addedObjects,
247
+ describeAdded,
226
248
  resolveByPath,
227
249
  projectResources,
228
250
  packageRoot,