dsh-workrally 0.2.1 → 0.3.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/lib/mcp.js CHANGED
@@ -71,6 +71,27 @@ export const readNativeTask = async (ctx, { serverName, taskId, sessionId, actio
71
71
  return result;
72
72
  };
73
73
 
74
+ /** 执行任意已登记的只读 WorkRally 工具,返回 DSH 原始结果。 */
75
+ export const callNativeTool = async (ctx, { serverName, action, args = {}, sessionId }, signal) => {
76
+ if (!serverNames.has(serverName) || typeof action !== 'string' || !action) throw new Error('没有可用的 WorkRally 工具');
77
+ const agent = ctx?.agents?.get?.(sessionId);
78
+ const definitions = await ctx?.tools?.definitions?.();
79
+ const name = `mcp__${serverName}__${action}`;
80
+ if (!Array.isArray(definitions) || !definitions.some(tool => tool?.name === name)) {
81
+ throw new Error('当前没有可用的 WorkRally 工具,请先在工作台登录 WorkRally');
82
+ }
83
+ if (typeof ctx?.tools?.execute !== 'function') throw new Error('DSH 原生工具执行服务不可用');
84
+ const id = randomUUID();
85
+ const response = await ctx.tools.execute({
86
+ calls: [{ type: 'tool-call', id, name, arguments: JSON.stringify(args) }],
87
+ signal,
88
+ ...(agent ? { agent } : {}),
89
+ });
90
+ const result = response?.results?.find(entry => entry.callId === id)?.result;
91
+ if (!result) throw new Error('DSH 原生工具没有返回结果');
92
+ return result;
93
+ };
94
+
74
95
  /** 账号状态由本插件的登录连接给出;toolCount 说明 DSH 已发现多少个 WorkRally 工具。 */
75
96
  export const getConnection = async (ctx) => {
76
97
  const account = ctx?.account?.status?.() ?? { status: 'unavailable', message: '暂时无法读取 WorkRally 连接状态。' };
@@ -84,3 +105,500 @@ export const getConnection = async (ctx) => {
84
105
  return { ...account, serverNames: [], toolCount: 0 };
85
106
  }
86
107
  };
108
+
109
+ /** 通过已挂载的 WorkRally MCP 实时读取当前登录账号身份、项目分组与全量无限画布列表。 */
110
+ export const readNativeCanvases = async (ctx, signal) => {
111
+ const definitions = await ctx?.tools?.definitions?.();
112
+ const defs = Array.isArray(definitions) ? definitions : [];
113
+ const manageDef = defs.map(tool => workrallyTool(tool?.name)).find(item => item?.action === 'canvas_manage');
114
+ if (!manageDef) throw new Error('尚未连接 WorkRally 账号,请先点击登录绑定你的账号');
115
+ if (typeof ctx?.tools?.execute !== 'function') throw new Error('DSH 原生工具执行服务不可用');
116
+
117
+ const server = manageDef.serverName;
118
+ const hasTool = action => defs.some(tool => tool?.name === `mcp__${server}__${action}`);
119
+ const timeoutSig = () => (signal ? AbortSignal.any([signal, AbortSignal.timeout(20_000)]) : AbortSignal.timeout(20_000));
120
+
121
+ const listCallId = randomUUID();
122
+ const urlCallId = randomUUID();
123
+ const whoCallId = randomUUID();
124
+ const projCallId = randomUUID();
125
+
126
+ const calls = [
127
+ {
128
+ type: 'tool-call',
129
+ id: listCallId,
130
+ name: `mcp__${server}__canvas_manage`,
131
+ arguments: JSON.stringify({ action: 'list', page: 1, page_size: 100 }),
132
+ },
133
+ ];
134
+ if (hasTool('workrally_url')) {
135
+ calls.push({
136
+ type: 'tool-call',
137
+ id: urlCallId,
138
+ name: `mcp__${server}__workrally_url`,
139
+ arguments: JSON.stringify({ action: 'build', query: '无限画布管理' }),
140
+ });
141
+ }
142
+ if (hasTool('who_am_i')) {
143
+ calls.push({
144
+ type: 'tool-call',
145
+ id: whoCallId,
146
+ name: `mcp__${server}__who_am_i`,
147
+ arguments: '{}',
148
+ });
149
+ }
150
+ if (hasTool('project_list')) {
151
+ calls.push({
152
+ type: 'tool-call',
153
+ id: projCallId,
154
+ name: `mcp__${server}__project_list`,
155
+ arguments: JSON.stringify({ page: 1, page_size: 100 }),
156
+ });
157
+ }
158
+
159
+ const response = await ctx.tools.execute({ calls, signal: timeoutSig() });
160
+ const getPayloads = (callId) => {
161
+ const res = response?.results?.find(entry => entry.callId === callId)?.result;
162
+ return res ? normalizeToolResult(res) : { payloads: [], error: 'missing' };
163
+ };
164
+
165
+ const normalized = getPayloads(listCallId);
166
+ if (normalized.error) throw new Error(normalized.error);
167
+
168
+ let manager = 'https://workrally.qq.com/toolbox/canvas-manager';
169
+ if (hasTool('workrally_url')) {
170
+ const urlNorm = getPayloads(urlCallId);
171
+ const built = urlNorm.payloads.find(p => typeof p?.url === 'string' && p.url.startsWith('https://'))?.url;
172
+ if (built) manager = built;
173
+ }
174
+ const editorPrefix = manager.replace(/\/canvas-manager\/?$/, '/canvas/');
175
+
176
+ let account = null;
177
+ if (hasTool('who_am_i')) {
178
+ const whoNorm = getPayloads(whoCallId);
179
+ const info = whoNorm.payloads[0]?.userInfo || whoNorm.payloads[0];
180
+ if (info) {
181
+ const uid = info.profile?.uid || info.corp?.self?.id || '';
182
+ const nickname = info.profile?.nickname || info.corp?.self?.name || '';
183
+ const corpName = info.corp?.name || '';
184
+ if (uid || nickname) account = { uid, nickname, corpName, isEnterprise: Boolean(whoNorm.payloads[0]?.isEnterprise || corpName) };
185
+ }
186
+ }
187
+
188
+ let quota = null;
189
+ if (account?.uid && account.isEnterprise && hasTool('corp_member_quota_list')) {
190
+ try {
191
+ const qId = randomUUID();
192
+ const qRes = await ctx.tools.execute({
193
+ calls: [{
194
+ type: 'tool-call',
195
+ id: qId,
196
+ name: `mcp__${server}__corp_member_quota_list`,
197
+ arguments: JSON.stringify({ page: 1, page_size: 100 }),
198
+ }],
199
+ signal: timeoutSig(),
200
+ });
201
+ const qNorm = normalizeToolResult(qRes?.results?.[0]?.result);
202
+ const members = qNorm.payloads.find(p => Array.isArray(p?.members))?.members || [];
203
+ const me = members.find(m => m.user_id === account.uid);
204
+ if (me) quota = { spent: Number(me.usage) || 0, remaining: Number(me.remaining) ?? 0, quota: Number(me.quota) || 0, unlimited: Boolean(me.unlimited) };
205
+ } catch {
206
+ // ignore optional quota lookup error
207
+ }
208
+ }
209
+
210
+ const projectGroups = [];
211
+ if (hasTool('project_list')) {
212
+ const projNorm = getPayloads(projCallId);
213
+ const pList = projNorm.payloads.find(p => Array.isArray(p?.project_list))?.project_list || [];
214
+ for (const gp of pList) {
215
+ if (gp?.project_id && gp?.project_name) {
216
+ projectGroups.push({ id: String(gp.project_id), name: String(gp.project_name) });
217
+ }
218
+ }
219
+ }
220
+ const groupNameMap = new Map(projectGroups.map(g => [g.id, g.name]));
221
+
222
+ const payload = normalized.payloads.find(p => Array.isArray(p?.list)) || normalized.payloads[0] || {};
223
+ const rawItems = [...(Array.isArray(payload.list) ? payload.list : [])];
224
+ const totalCount = Number(payload?.page_info?.total) || rawItems.length;
225
+
226
+ // 若总画布数超过 100,继续翻页拉齐该账号下的全部画布
227
+ for (let page = 2; rawItems.length < totalCount && page <= 5; page++) {
228
+ const nextId = randomUUID();
229
+ const nextRes = await ctx.tools.execute({
230
+ calls: [{
231
+ type: 'tool-call',
232
+ id: nextId,
233
+ name: `mcp__${server}__canvas_manage`,
234
+ arguments: JSON.stringify({ action: 'list', page, page_size: 100 }),
235
+ }],
236
+ signal: timeoutSig(),
237
+ });
238
+ const nextNorm = normalizeToolResult(nextRes?.results?.[0]?.result);
239
+ const more = nextNorm.payloads.find(p => Array.isArray(p?.list))?.list || [];
240
+ if (!more.length) break;
241
+ rawItems.push(...more);
242
+ }
243
+
244
+ const projects = rawItems
245
+ .map((entry) => {
246
+ const p = entry?.project || entry;
247
+ const id = typeof p?.id === 'string' ? p.id.trim() : '';
248
+ const title = typeof p?.title === 'string' ? p.title.trim() : '';
249
+ if (!id || !title) return null;
250
+ const updatedRaw = typeof p.updated_at === 'string' ? p.updated_at : (typeof p.created_at === 'string' ? p.created_at : '');
251
+ const groupId = typeof p.project_id === 'string' ? p.project_id.trim() : '';
252
+ return {
253
+ id,
254
+ title,
255
+ url: `${editorPrefix}${encodeURIComponent(id)}`,
256
+ updated: updatedRaw.slice(0, 10),
257
+ updatedAt: updatedRaw,
258
+ images: Number(p.image_count) || 0,
259
+ videos: Number(p.video_count) || 0,
260
+ texts: Number(p.text_count) || 0,
261
+ thumb: typeof p.thumbnail_url === 'string' ? p.thumbnail_url.trim() : '',
262
+ mine: Boolean(p.is_author),
263
+ groupId,
264
+ groupName: groupNameMap.get(groupId) || '',
265
+ };
266
+ })
267
+ .filter(Boolean);
268
+
269
+ return {
270
+ manager,
271
+ account,
272
+ quota,
273
+ groups: projectGroups,
274
+ total: projects.length,
275
+ projects,
276
+ };
277
+ };
278
+
279
+ const ASSET_TYPES = new Set(['image', 'video', 'audio', '3d']);
280
+
281
+ const clipPrompt = (value) => (typeof value === 'string' ? value.trim().slice(0, 4000) : '');
282
+
283
+ const promptText = (node) => {
284
+ if (!node || typeof node !== 'object') return '';
285
+ const params = node.data?.params && typeof node.data.params === 'object'
286
+ ? node.data.params
287
+ : (node.params && typeof node.params === 'object' ? node.params : {});
288
+ return clipPrompt(params.prompt)
289
+ || clipPrompt(params.positive_prompt)
290
+ || clipPrompt(params.positivePrompt)
291
+ || clipPrompt(params.user_prompt)
292
+ || clipPrompt(params.text)
293
+ || clipPrompt(node.data?.prompt)
294
+ || clipPrompt(node.prompt);
295
+ };
296
+
297
+ const taskIdOf = (node) => String(node?.data?.task?.taskId || node?.data?.task?.task_id || node?.task?.taskId || node?.taskId || '');
298
+
299
+ /** 在画布草稿里按素材编号取出对应节点的提示词。节点本身没有时,再用同一个任务编号上的提示词。 */
300
+ export const promptForAsset = (root, assetId) => {
301
+ const want = String(assetId || '');
302
+ if (!want || !root || typeof root !== 'object') return '';
303
+ let found = '';
304
+ let taskId = '';
305
+ const byTask = new Map();
306
+ const visit = (node, depth) => {
307
+ if (!node || typeof node !== 'object' || depth > 12) return;
308
+ if (Array.isArray(node)) {
309
+ node.forEach(entry => visit(entry, depth + 1));
310
+ return;
311
+ }
312
+ const prompt = promptText(node);
313
+ const tid = taskIdOf(node);
314
+ if (prompt && tid && !byTask.has(tid)) byTask.set(tid, prompt);
315
+ const asset = node.data?.asset && typeof node.data.asset === 'object' ? node.data.asset : node.asset;
316
+ const id = String(asset?.id || asset?.asset_id || node.asset_id || '');
317
+ if (id === want) {
318
+ if (!found) found = prompt;
319
+ if (!taskId) taskId = tid;
320
+ }
321
+ Object.values(node).forEach(value => { if (value && typeof value === 'object') visit(value, depth + 1); });
322
+ };
323
+ visit(root, 0);
324
+ return found || (taskId ? byTask.get(taskId) || '' : '');
325
+ };
326
+
327
+ const parseDraftTree = (value) => {
328
+ if (!value || typeof value !== 'object') return null;
329
+ const raw = typeof value.draft === 'string' ? value.draft : '';
330
+ if (!raw || raw.length > 2_000_000) return null;
331
+ try {
332
+ const outer = JSON.parse(raw);
333
+ const content = typeof outer?.content === 'string' ? JSON.parse(outer.content) : outer?.content;
334
+ return content && typeof content === 'object' ? content : (outer && typeof outer === 'object' ? outer : null);
335
+ } catch {
336
+ return null;
337
+ }
338
+ };
339
+ const CANVAS_ASSET_ID = /^[\w-]{1,80}$/;
340
+ const ASSET_FILE_HOSTS = new Set(['workrally.qq.com', 'cdn.workrally.qq.com', 'zenvideo.gtimg.com', 'zenvideo-pro.gtimg.com']);
341
+ const ASSET_FILE_LIMIT = 200 * 1024 * 1024;
342
+ let assetFetcher = globalThis.fetch;
343
+
344
+ export const configureAssetFetcher = (fetchImpl) => { assetFetcher = fetchImpl || globalThis.fetch; };
345
+
346
+ export const isAssetFileUrl = (value) => {
347
+ try {
348
+ const url = new URL(value);
349
+ return url.protocol === 'https:' && ASSET_FILE_HOSTS.has(url.hostname) && !url.username && !url.password
350
+ && (!url.port || url.port === '443');
351
+ } catch {
352
+ return false;
353
+ }
354
+ };
355
+
356
+ /** 下载地址优先。短链可以做第一跳,最终文件必须落在 WorkRally 或腾讯视频 CDN。 */
357
+ export const pickAssetFileUrl = (payloads, assetId) => {
358
+ const want = String(assetId || '');
359
+ const ranked = [];
360
+ const visit = (node, matched, depth) => {
361
+ if (!node || typeof node !== 'object' || depth > 12) return;
362
+ if (Array.isArray(node)) {
363
+ node.forEach(entry => visit(entry, matched, depth + 1));
364
+ return;
365
+ }
366
+ const id = String(node.asset_id || node.assetId || node.id || '');
367
+ const now = matched || Boolean(want && id === want);
368
+ const details = node.asset_details && typeof node.asset_details === 'object' ? node.asset_details : null;
369
+ if (now || !want) {
370
+ const bag = details || node;
371
+ if (typeof bag.download_url === 'string') ranked.push(bag.download_url);
372
+ if (typeof bag.downloadUrl === 'string') ranked.push(bag.downloadUrl);
373
+ if (typeof bag.url === 'string') ranked.push(bag.url);
374
+ }
375
+ for (const [key, value] of Object.entries(node)) {
376
+ if (key === 'asset_details') continue;
377
+ if (value && typeof value === 'object') visit(value, now, depth + 1);
378
+ }
379
+ };
380
+ (Array.isArray(payloads) ? payloads : []).forEach(payload => visit(payload, false, 0));
381
+ return ranked.find(isAssetFileUrl) || '';
382
+ };
383
+
384
+ /** 把 asset_search 回执收成画布媒资卡片。封面优先用海报,图片才回退到会跳转的短链。 */
385
+ export const normalizeCanvasAssets = (payloads) => {
386
+ const payload = (Array.isArray(payloads) ? payloads : []).find(item => Array.isArray(item?.assets)) || {};
387
+ const assets = [];
388
+ for (const asset of payload.assets) {
389
+ if (!asset || typeof asset.id !== 'string' || !asset.id) continue;
390
+ const details = asset.asset_details && typeof asset.asset_details === 'object' ? asset.asset_details : {};
391
+ const type = ASSET_TYPES.has(asset.type) ? asset.type : 'image';
392
+ const poster = typeof details.poster === 'string' && details.poster.startsWith('https://') ? details.poster : '';
393
+ const pageUrl = typeof details.url === 'string' && details.url.startsWith('https://') ? details.url : '';
394
+ const count = (value) => {
395
+ const n = Number(value);
396
+ return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
397
+ };
398
+ assets.push({
399
+ id: asset.id,
400
+ title: typeof asset.title === 'string' ? asset.title : '',
401
+ type,
402
+ canvasId: typeof details.material_canvas_project === 'string' ? details.material_canvas_project : '',
403
+ poster,
404
+ src: poster || (type === 'image' ? pageUrl : ''),
405
+ width: count(details.width),
406
+ height: count(details.height),
407
+ bytes: count(details.size),
408
+ prompt: clipPrompt(asset.prompt) || clipPrompt(details.prompt) || clipPrompt(details.positive_prompt),
409
+ created: typeof asset.created_at === 'string' ? asset.created_at.slice(0, 10) : '',
410
+ createdAt: typeof asset.created_at === 'string' ? asset.created_at : '',
411
+ });
412
+ }
413
+ return {
414
+ assets,
415
+ total: Number(payload.page_info?.total) || assets.length,
416
+ page: Number(payload.page_info?.page) || 1,
417
+ };
418
+ };
419
+
420
+ /** 只读当前账号在无限画布里生成并入库的媒资,可按画布收窄。 */
421
+ export const readNativeAssets = async (ctx, { page = 1, materialType = '', canvasId = '', keyword = '' } = {}, signal) => {
422
+ const definitions = await ctx?.tools?.definitions?.();
423
+ const defs = Array.isArray(definitions) ? definitions : [];
424
+ const searchDef = defs.map(tool => workrallyTool(tool?.name)).find(item => item?.action === 'asset_search');
425
+ if (!searchDef) throw new Error('尚未连接 WorkRally 账号,请先点击登录绑定你的账号');
426
+ if (typeof ctx?.tools?.execute !== 'function') throw new Error('DSH 原生工具执行服务不可用');
427
+ const args = {
428
+ channel: ['toolbox_canvas'],
429
+ artifact_type: [0],
430
+ sort_field: 1,
431
+ sort_order: 1,
432
+ page: Math.min(500, Math.max(1, Number(page) || 1)),
433
+ page_size: 24,
434
+ };
435
+ if (ASSET_TYPES.has(materialType)) args.material_type = [materialType];
436
+ if (CANVAS_ASSET_ID.test(canvasId)) args.canvas_project_id = [canvasId];
437
+ const query = String(keyword || '').trim().slice(0, 80);
438
+ if (query) args.keyword = query;
439
+ const id = randomUUID();
440
+ const response = await ctx.tools.execute({
441
+ calls: [{
442
+ type: 'tool-call',
443
+ id,
444
+ name: `mcp__${searchDef.serverName}__asset_search`,
445
+ arguments: JSON.stringify(args),
446
+ }],
447
+ signal: signal || AbortSignal.timeout(20_000),
448
+ });
449
+ const result = response?.results?.find(entry => entry.callId === id)?.result;
450
+ if (!result) throw new Error('媒资读取失败');
451
+ const normalized = normalizeToolResult(result);
452
+ if (normalized.error) throw new Error(normalized.error);
453
+ return normalizeCanvasAssets(normalized.payloads);
454
+ };
455
+
456
+ /** 打开详情时补提示词:先看素材本身,再按画布草稿里同一素材编号查找。 */
457
+ export const readAssetPrompt = async (ctx, assetId, canvasId, signal) => {
458
+ if (!CANVAS_ASSET_ID.test(assetId)) return '';
459
+ const definitions = await ctx?.tools?.definitions?.();
460
+ const defs = Array.isArray(definitions) ? definitions : [];
461
+ const detailDef = defs.map(tool => workrallyTool(tool?.name)).find(item => item?.action === 'asset_detail');
462
+ const manageDef = defs.map(tool => workrallyTool(tool?.name)).find(item => item?.action === 'canvas_manage');
463
+ if (typeof ctx?.tools?.execute !== 'function') return '';
464
+ const detailId = randomUUID();
465
+ const canvasCallId = randomUUID();
466
+ const calls = [];
467
+ if (detailDef) {
468
+ calls.push({
469
+ type: 'tool-call',
470
+ id: detailId,
471
+ name: `mcp__${detailDef.serverName}__asset_detail`,
472
+ arguments: JSON.stringify({ asset_ids: [assetId] }),
473
+ });
474
+ }
475
+ if (manageDef && CANVAS_ASSET_ID.test(canvasId)) {
476
+ calls.push({
477
+ type: 'tool-call',
478
+ id: canvasCallId,
479
+ name: `mcp__${manageDef.serverName}__canvas_manage`,
480
+ arguments: JSON.stringify({ action: 'get', canvas_id: canvasId }),
481
+ });
482
+ }
483
+ if (!calls.length) return '';
484
+ const response = await ctx.tools.execute({ calls, signal: signal || AbortSignal.timeout(20_000) });
485
+ const payloadsOf = (callId) => {
486
+ const result = response?.results?.find(entry => entry.callId === callId)?.result;
487
+ return result ? normalizeToolResult(result).payloads : [];
488
+ };
489
+ const fromAsset = payloadsOf(detailId).flatMap((payload) => {
490
+ const assets = Array.isArray(payload?.assets) ? payload.assets : [payload];
491
+ return assets
492
+ .filter(asset => String(asset?.id || asset?.asset_id || '') === assetId)
493
+ .map(asset => clipPrompt(asset?.prompt) || clipPrompt(asset?.asset_details?.prompt) || clipPrompt(asset?.asset_details?.positive_prompt));
494
+ }).find(Boolean);
495
+ if (fromAsset) return fromAsset;
496
+ const drafts = [];
497
+ const collect = (node, depth) => {
498
+ if (!node || typeof node !== 'object' || depth > 6) return;
499
+ if (typeof node.draft === 'string') drafts.push(node);
500
+ Object.values(node).forEach(value => { if (value && typeof value === 'object') collect(value, depth + 1); });
501
+ };
502
+ payloadsOf(canvasCallId).forEach(payload => collect(payload, 0));
503
+ for (const draft of drafts) {
504
+ const prompt = promptForAsset(parseDraftTree(draft), assetId);
505
+ if (prompt) return prompt;
506
+ }
507
+ return '';
508
+ };
509
+
510
+ const assetTitle = (payloads, assetId) => {
511
+ const found = [];
512
+ const visit = (node, depth) => {
513
+ if (!node || typeof node !== 'object' || depth > 12) return;
514
+ if (Array.isArray(node)) { node.forEach(entry => visit(entry, depth + 1)); return; }
515
+ if (String(node.id || node.asset_id || '') === assetId && typeof node.title === 'string') found.push(node.title);
516
+ Object.values(node).forEach(value => { if (value && typeof value === 'object') visit(value, depth + 1); });
517
+ };
518
+ payloads.forEach(payload => visit(payload, 0));
519
+ return found.find(title => title.trim()) || '';
520
+ };
521
+
522
+ /** 按素材 ID 向当前账号取下载地址和文件名,不接收调用方传入的任意网址。 */
523
+ export const readAssetDownloadTarget = async (ctx, assetId, signal) => {
524
+ if (!CANVAS_ASSET_ID.test(assetId)) throw Object.assign(new Error('素材编号无效'), { status: 400 });
525
+ const definitions = await ctx?.tools?.definitions?.();
526
+ const defs = Array.isArray(definitions) ? definitions : [];
527
+ const detailDef = defs.map(tool => workrallyTool(tool?.name)).find(item => item?.action === 'asset_detail');
528
+ if (!detailDef) throw new Error('尚未连接 WorkRally 账号,请先点击登录绑定你的账号');
529
+ if (typeof ctx?.tools?.execute !== 'function') throw new Error('DSH 原生工具执行服务不可用');
530
+ const id = randomUUID();
531
+ const response = await ctx.tools.execute({
532
+ calls: [{
533
+ type: 'tool-call',
534
+ id,
535
+ name: `mcp__${detailDef.serverName}__asset_detail`,
536
+ arguments: JSON.stringify({ asset_ids: [assetId] }),
537
+ }],
538
+ signal: signal || AbortSignal.timeout(20_000),
539
+ });
540
+ const result = response?.results?.find(entry => entry.callId === id)?.result;
541
+ if (!result) throw new Error('媒资读取失败');
542
+ const normalized = normalizeToolResult(result);
543
+ if (normalized.error) throw new Error(normalized.error);
544
+ const url = pickAssetFileUrl(normalized.payloads, assetId);
545
+ if (!url) throw Object.assign(new Error('没有可下载的文件'), { status: 404 });
546
+ return { url, title: assetTitle(normalized.payloads, assetId) };
547
+ };
548
+
549
+ /** 跟随短链,每跳都必须落在允许的域名上。最终响应留给调用方读取或取消。 */
550
+ const followAssetUrl = async (startUrl, signal) => {
551
+ if (!isAssetFileUrl(startUrl)) throw Object.assign(new Error('下载地址不在允许范围内'), { status: 400 });
552
+ if (typeof assetFetcher !== 'function') throw new Error('下载不可用');
553
+ let url = startUrl;
554
+ let response;
555
+ for (let hop = 0; hop <= 4; hop += 1) {
556
+ if (!isAssetFileUrl(url)) throw Object.assign(new Error('下载地址不在允许范围内'), { status: 400 });
557
+ response = await assetFetcher(url, { redirect: 'manual', signal });
558
+ if (![301, 302, 303, 307, 308].includes(response.status)) break;
559
+ const location = response.headers.get('location');
560
+ await response.body?.cancel();
561
+ if (!location || hop === 4) throw new Error('下载重定向次数过多');
562
+ url = new URL(location, url).href;
563
+ }
564
+ return { url, response };
565
+ };
566
+
567
+ /** 解析出可直接播放的音视频地址,不把文件读进内存。 */
568
+ export const resolveAssetPlaybackUrl = async (startUrl, signal) => {
569
+ const { url, response } = await followAssetUrl(startUrl, signal);
570
+ const mime = String(response?.headers?.get('content-type') || '').split(';')[0].trim().toLowerCase();
571
+ await response?.body?.cancel?.();
572
+ if (!response?.ok || !/^(video|audio)\//.test(mime)) throw new Error('响应不是可播放的音视频');
573
+ return { url, mime };
574
+ };
575
+
576
+ /** 跟随短链跳转,只接受图片、视频、音频,并限制 200 MB。 */
577
+ export const downloadAssetFile = async (startUrl, signal) => {
578
+ const { response } = await followAssetUrl(startUrl, signal);
579
+ const mime = String(response?.headers?.get('content-type') || '').split(';')[0].trim().toLowerCase();
580
+ if (!response?.ok || !/^(image|video|audio)\//.test(mime) || !response.body?.getReader) {
581
+ await response?.body?.cancel?.();
582
+ throw new Error('响应不是可下载的媒体文件');
583
+ }
584
+ const declared = Number(response.headers.get('content-length'));
585
+ if (declared > ASSET_FILE_LIMIT) {
586
+ await response.body.cancel();
587
+ throw Object.assign(new Error('文件超过 200 MB'), { status: 413 });
588
+ }
589
+ const reader = response.body.getReader();
590
+ const chunks = [];
591
+ let size = 0;
592
+ try {
593
+ while (true) {
594
+ const { done, value } = await reader.read();
595
+ if (done) break;
596
+ size += value.byteLength;
597
+ if (size > ASSET_FILE_LIMIT) throw Object.assign(new Error('文件超过 200 MB'), { status: 413 });
598
+ chunks.push(Buffer.from(value));
599
+ }
600
+ } finally {
601
+ await reader.cancel().catch(() => {});
602
+ }
603
+ return { bytes: Buffer.concat(chunks, size), mime };
604
+ };
package/lib/plaza.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * 模版库:与 WorkRally 首页「作品广场 / 模板合集」同一张无极表(正式环境),
3
+ * 解析出每个合集的模板列表与可直接推入对话输入框的提示词。
4
+ */
5
+ const COLLECTION_SOURCE = 'https://api.wuji.qq.com/x/api/wuji_cache/object?appid=grail_zenanimate'
6
+ + '&schemaid=template_collection_prod&schemakey=ba178851cc6142d590308199c6de395a&size=total';
7
+ const ALLOWED_ORIGINS = new Set(['https://zenvideo.gtimg.com', 'https://zenvideo-pro.gtimg.com']);
8
+ const TTL_MS = 10 * 60_000;
9
+ const TIMEOUT_MS = 10_000;
10
+
11
+ let cache = null;
12
+ let loading = null;
13
+
14
+ const readText = value => (typeof value === 'string' ? value.trim() : '');
15
+
16
+ const parseJson = (value) => {
17
+ if (!value) return null;
18
+ if (typeof value === 'object') return value;
19
+ if (typeof value === 'string' && value.trim()) {
20
+ try { return JSON.parse(value); } catch { return null; }
21
+ }
22
+ return null;
23
+ };
24
+
25
+ const readMediaUrl = (value) => {
26
+ if (value && typeof value === 'object') return readMediaUrl(value.url || value.path || value.src);
27
+ const text = readText(value);
28
+ if (!text) return '';
29
+ let href = text;
30
+ if (text.startsWith('//')) href = `https:${text}`;
31
+ else if (!/^https?:\/\//i.test(text)) href = `https://zenvideo.gtimg.com/${text.replace(/^\/+/, '')}`;
32
+ try {
33
+ const url = new URL(href);
34
+ return ALLOWED_ORIGINS.has(url.origin) && !url.username && !url.password ? url.href : '';
35
+ } catch {
36
+ return '';
37
+ }
38
+ };
39
+
40
+ const buildPrompt = (item, collectionTitle) => {
41
+ const title = readText(item.title);
42
+ const desc = readText(item.description);
43
+ if (item.type === 'code2video') {
44
+ const prefill = parseJson(item.input_prefill) || {};
45
+ const promptObj = prefill.prompt;
46
+ const promptText = readText(typeof promptObj === 'object' ? promptObj?.text : promptObj)
47
+ || readText(item.prompt)
48
+ || desc;
49
+ const meta = [];
50
+ const duration = prefill.duration || item.duration;
51
+ const aspect = readText(prefill.aspect_ratio || item.aspect_ratio);
52
+ if (duration) meta.push(`时长 ${duration}s`);
53
+ if (aspect) meta.push(`画幅 ${aspect}`);
54
+ const head = `请使用 WorkRally 代码搓片生成:${title}${meta.length ? `(${meta.join(' · ')})` : ''}`;
55
+ return [head, promptText].filter(Boolean).join('\n\n');
56
+ }
57
+ const ref = parseJson(item.reference_materials);
58
+ const materials = Array.isArray(ref?.materials) ? ref.materials : [];
59
+ const parts = [];
60
+ for (const m of materials) {
61
+ if (!m || typeof m !== 'object') continue;
62
+ const text = readText(m.text);
63
+ if (text && text !== '即可获取同款提示词') parts.push(text);
64
+ }
65
+ const category = readText(item.category);
66
+ if (collectionTitle === 'BGM 精选' || category === 'BGM') {
67
+ const body = parts.join('\n\n') || desc;
68
+ return [ `请使用 WorkRally 生成音乐:${title}`, body ].filter(Boolean).join('\n\n');
69
+ }
70
+ if (collectionTitle === '角色库精选' || category === '角色') {
71
+ const cover = readMediaUrl(item.cover_url);
72
+ return [
73
+ `请使用 WorkRally 生成角色设定图:${title}`,
74
+ desc,
75
+ cover ? `参考图:${cover}` : '',
76
+ ].filter(Boolean).join('\n\n');
77
+ }
78
+ if (parts.length) return `请使用 WorkRally 按「${title}」模板生成:\n\n${parts.join('\n\n')}`;
79
+ if (desc) return `请使用 WorkRally 按「${title}」模板生成:\n\n${desc}`;
80
+ return `请使用 WorkRally 生成:${title}`;
81
+ };
82
+
83
+ export const parseCollections = (rows) => {
84
+ if (!Array.isArray(rows)) return [];
85
+ const out = [];
86
+ for (const raw of rows) {
87
+ if (!raw || typeof raw !== 'object') continue;
88
+ const id = readText(raw.id || raw._id);
89
+ const title = readText(raw.title);
90
+ // This collection is intentionally excluded from the DSH plugin.
91
+ if (id === '3zsszfod4t' || title === '代码搓片') continue;
92
+ const desc = readText(raw.desc);
93
+ const rawItems = parseJson(raw.items);
94
+ const list = Array.isArray(rawItems) ? rawItems : [];
95
+ if (!id || !title || !list.length) continue;
96
+ const items = [];
97
+ list.forEach((entry, index) => {
98
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return;
99
+ const itemTitle = readText(entry.title);
100
+ if (!itemTitle) return;
101
+ const itemId = readText(entry.template_id || entry.id || entry.style) || `${id}-${index}`;
102
+ const cover = readMediaUrl(entry.cover_url);
103
+ const video = readMediaUrl(entry.video_url);
104
+ const itemDesc = readText(entry.description);
105
+ const category = readText(entry.category) || (entry.type === 'code2video' ? '代码搓片' : title);
106
+ items.push({
107
+ id: itemId,
108
+ title: itemTitle,
109
+ category,
110
+ description: itemDesc,
111
+ cover,
112
+ video,
113
+ prompt: buildPrompt(entry, title),
114
+ });
115
+ });
116
+ if (!items.length) continue;
117
+ out.push({
118
+ id,
119
+ title,
120
+ desc,
121
+ count: items.length,
122
+ covers: items.map(item => item.cover).filter(Boolean).slice(0, 3),
123
+ items,
124
+ });
125
+ }
126
+ return out;
127
+ };
128
+
129
+ const fetchCollections = async (fetchImpl) => {
130
+ const response = await fetchImpl(COLLECTION_SOURCE, { redirect: 'error', signal: AbortSignal.timeout(TIMEOUT_MS) });
131
+ if (!response.ok) throw new Error(`模版库读取失败(${response.status})`);
132
+ const data = await response.json();
133
+ if (data?.code !== 200) throw new Error('模版库读取失败');
134
+ return parseCollections(data.data);
135
+ };
136
+
137
+ export const listCollections = async (fetchImpl = fetch) => {
138
+ if (cache && Date.now() - cache.at < TTL_MS) return cache.collections;
139
+ loading ??= fetchCollections(fetchImpl)
140
+ .then((collections) => {
141
+ cache = { collections, at: Date.now() };
142
+ return collections;
143
+ })
144
+ .catch((error) => {
145
+ if (cache) return cache.collections;
146
+ throw error;
147
+ })
148
+ .finally(() => { loading = null; });
149
+ return loading;
150
+ };
151
+
152
+ export const resetCollections = () => {
153
+ cache = null;
154
+ loading = null;
155
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-workrally",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "WorkRally 创作工作台:原生 MCP、按需创作技能、任务追踪与会话素材。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",