dsh-workrally 0.2.5 → 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/gallery.js CHANGED
@@ -40,6 +40,18 @@ export const isAllowedGalleryMediaUrl = (value) => {
40
40
  }
41
41
  };
42
42
 
43
+ /** 任务回执里的 /s/ 短链是分享页,会过期并返回 HTML,不能当作图片或视频地址。 */
44
+ export const isShareMediaUrl = (value) => {
45
+ try {
46
+ const url = new URL(value);
47
+ return url.pathname === '/s' || url.pathname.startsWith('/s/');
48
+ } catch {
49
+ return false;
50
+ }
51
+ };
52
+
53
+ export const isDirectMediaUrl = value => isAllowedGalleryMediaUrl(value) && !isShareMediaUrl(value);
54
+
43
55
  const safeFileName = value => typeof value === 'string' && /^[\w-][\w.-]*$/.test(value) ? value : '';
44
56
  const clone = value => JSON.parse(JSON.stringify(value));
45
57
  let storeMtime = 0;
@@ -111,10 +123,12 @@ export const reloadGalleryIfChanged = () => {
111
123
  }
112
124
  };
113
125
 
126
+ const fileSrc = item => `/workrally/file/${encodeURIComponent(item.id)}?session=${encodeURIComponent(item.sessionId || '')}`;
127
+
114
128
  const publicItem = item => ({
115
129
  id: item.id,
116
130
  url: item.url,
117
- src: item.file ? `/workrally/file/${encodeURIComponent(item.id)}?session=${encodeURIComponent(item.sessionId)}` : item.url,
131
+ src: fileSrc(item),
118
132
  local: Boolean(item.file),
119
133
  mediaType: item.mediaType || 'image',
120
134
  prompt: item.prompt || '',
@@ -313,23 +327,102 @@ export const readGalleryFile = (id, sessionId) => {
313
327
  }
314
328
  };
315
329
 
330
+ const findGalleryItem = (id, sessionId) => items.find(entry => entry.id === id && (!sessionId || entry.sessionId === sessionId));
331
+
332
+ /**
333
+ * 从 asset_detail 回执里取可下载地址。优先 download_url,跳过 /s/ 分享短链。
334
+ * 只采纳与 assetId 对应的那一条,避免把同页其他素材的地址拿来。
335
+ */
336
+ export const pickAssetDownloadUrl = (payloads, assetId) => {
337
+ const want = String(assetId || '');
338
+ const ranked = [];
339
+ const visit = (node, matched, depth) => {
340
+ if (!node || typeof node !== 'object' || depth > 12) return;
341
+ if (Array.isArray(node)) {
342
+ node.forEach(entry => visit(entry, matched, depth + 1));
343
+ return;
344
+ }
345
+ const id = String(node.asset_id || node.assetId || node.id || '');
346
+ const now = matched || Boolean(want && id === want);
347
+ const details = node.asset_details && typeof node.asset_details === 'object' ? node.asset_details : null;
348
+ if (now || !want) {
349
+ const bag = details || node;
350
+ const download = bag.download_url || bag.downloadUrl;
351
+ const page = bag.url || bag.cdn_url || bag.asset_url;
352
+ if (typeof download === 'string') ranked.push(download);
353
+ if (typeof page === 'string') ranked.push(page);
354
+ }
355
+ for (const [key, value] of Object.entries(node)) {
356
+ if (key === 'asset_details') continue;
357
+ if (value && typeof value === 'object') visit(value, now, depth + 1);
358
+ }
359
+ };
360
+ (Array.isArray(payloads) ? payloads : []).forEach(payload => visit(payload, false, 0));
361
+ return ranked.find(isDirectMediaUrl) || '';
362
+ };
363
+
364
+ const storeGalleryMedia = (item, media) => {
365
+ if (!filesDir) return false;
366
+ mkdirSync(filesDir, { recursive: true });
367
+ const name = safeFileName(`${item.id}.${media.ext}`);
368
+ if (!name) return false;
369
+ const path = join(filesDir, name);
370
+ const temporary = `${path}.${randomUUID()}.tmp`;
371
+ writeFileSync(temporary, media.bytes, { mode: 0o600 });
372
+ renameSync(temporary, path);
373
+ item.file = name;
374
+ return true;
375
+ };
376
+
316
377
  /** 用户主动打开媒体后保存本地副本;内容已通过签名校验,失败不影响展示。 */
317
378
  export const saveGalleryFile = (url, media) => {
318
379
  if (!filesDir) return;
319
380
  const pending = items.filter(item => item.url === url && !item.file);
320
381
  if (!pending.length) return;
321
382
  try {
322
- mkdirSync(filesDir, { recursive: true });
323
- for (const item of pending) {
324
- const name = safeFileName(`${item.id}.${media.ext}`);
325
- const path = join(filesDir, name);
326
- const temporary = `${path}.${randomUUID()}.tmp`;
327
- writeFileSync(temporary, media.bytes, { mode: 0o600 });
328
- renameSync(temporary, path);
329
- item.file = name;
330
- }
383
+ pending.forEach(item => storeGalleryMedia(item, media));
331
384
  saveGallery();
332
385
  } catch {
333
386
  pending.forEach((item) => { item.file = ''; });
334
387
  }
335
388
  };
389
+
390
+ const materializing = new Map();
391
+
392
+ /**
393
+ * 本地没有副本时补一份。已存的签名地址先试一次;失败或只剩分享短链时,
394
+ * 用调用方提供的解析(通常是 asset_detail)换一条新的下载地址再落盘。
395
+ */
396
+ export const materializeGalleryFile = async (id, sessionId, resolveUrl, signal) => {
397
+ const ready = readGalleryFile(id, sessionId);
398
+ if (ready) return ready;
399
+ const key = `${sessionId}\n${id}`;
400
+ const pending = materializing.get(key);
401
+ if (pending) return pending;
402
+ const job = (async () => {
403
+ const item = findGalleryItem(id, sessionId);
404
+ if (!item || signal?.aborted) return null;
405
+ let media = null;
406
+ if (isDirectMediaUrl(item.url)) {
407
+ try { media = await downloadGalleryMedia(item.url, signal); } catch { media = null; }
408
+ }
409
+ if (!media && item.assetId && typeof resolveUrl === 'function') {
410
+ let fresh = '';
411
+ try { fresh = await resolveUrl({ id: item.id, assetId: item.assetId, sessionId: item.sessionId, serverName: item.serverName || '' }); }
412
+ catch { fresh = ''; }
413
+ if (isDirectMediaUrl(fresh) && fresh !== item.url) {
414
+ try { media = await downloadGalleryMedia(fresh, signal); } catch { media = null; }
415
+ }
416
+ }
417
+ if (!media) return null;
418
+ try {
419
+ if (storeGalleryMedia(item, media)) saveGallery();
420
+ } catch {
421
+ item.file = '';
422
+ }
423
+ return { bytes: media.bytes, mime: media.mime };
424
+ })();
425
+ materializing.set(key, job);
426
+ try { return await job; }
427
+ finally { materializing.delete(key); }
428
+ };
package/lib/index.js CHANGED
@@ -14,13 +14,15 @@ import {
14
14
  listGallery,
15
15
  listLineage,
16
16
  loadGallery,
17
+ materializeGalleryFile,
18
+ pickAssetDownloadUrl,
17
19
  readGalleryFile,
18
20
  saveGalleryFile,
19
21
  stopGalleryDownloads,
20
22
  } from './gallery.js';
21
- import { listInspiration } from './inspiration.js';
22
- import { configureMcp, readNativeCanvases } from './mcp.js';
23
- import { listCollections } from './plaza.js';
23
+ import { listInspiration, resetInspiration } from './inspiration.js';
24
+ import { callNativeTool, configureMcp, downloadAssetFile, normalizeToolResult, readAssetDownloadTarget, readAssetPrompt, readNativeAssets, readNativeCanvases, resolveAssetPlaybackUrl } from './mcp.js';
25
+ import { listCollections, resetCollections } from './plaza.js';
24
26
  import { registerWorkrallySkills } from './skills.js';
25
27
 
26
28
  export const name = 'dsh-workrally';
@@ -111,19 +113,36 @@ const sessionParam = (value) => {
111
113
  return !id || SESSION_ID.test(id) ? id : null;
112
114
  };
113
115
 
116
+ /** 分享短链过期后,用素材 ID 向当前登录账号重取可下载地址。 */
117
+ const resolveAssetMediaUrl = async (ctx, record) => {
118
+ const serverName = /^[A-Za-z0-9_-]+$/.test(record?.serverName || '') ? record.serverName : 'workrally';
119
+ if (!record?.assetId) return '';
120
+ const result = await callNativeTool(ctx, {
121
+ serverName,
122
+ action: 'asset_detail',
123
+ args: { asset_ids: [record.assetId] },
124
+ sessionId: record.sessionId || '',
125
+ }, AbortSignal.timeout(20_000));
126
+ return pickAssetDownloadUrl(normalizeToolResult(result).payloads, record.assetId);
127
+ };
128
+
129
+ const sendMedia = (res, file, cache) => {
130
+ res.writeHead(200, {
131
+ 'content-type': file.mime,
132
+ 'content-length': file.bytes.length,
133
+ 'cache-control': cache,
134
+ 'x-content-type-options': 'nosniff',
135
+ });
136
+ res.end(file.bytes);
137
+ };
138
+
114
139
  const proxyMedia = async (res, target) => {
115
140
  const controller = new AbortController();
116
141
  res.on?.('close', () => controller.abort());
117
142
  try {
118
143
  const media = await downloadGalleryMedia(target, controller.signal);
119
144
  saveGalleryFile(target, media);
120
- res.writeHead(200, {
121
- 'content-type': media.mime,
122
- 'content-length': media.bytes.length,
123
- 'cache-control': 'private, max-age=300',
124
- 'x-content-type-options': 'nosniff',
125
- });
126
- res.end(media.bytes);
145
+ sendMedia(res, media, 'private, max-age=300');
127
146
  } catch (error) {
128
147
  if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '媒体读取失败,请稍后重试' });
129
148
  }
@@ -252,6 +271,14 @@ export const createStudioHandler = ctx => async (req, res) => {
252
271
  sendJson(res, 200, await ctx.account.relogin());
253
272
  return;
254
273
  }
274
+ if (method === 'POST' && url.pathname === '/workrally/refresh') {
275
+ // Workbench 的「刷新全部」:先丢掉宿主端模板/灵感缓存,客户端随后
276
+ // 重新读取任务、画布与合集,避免拿到 10 分钟内的旧数据。
277
+ resetCollections();
278
+ resetInspiration();
279
+ sendJson(res, 200, { ok: true, at: Date.now() });
280
+ return;
281
+ }
255
282
  if (method === 'POST' && url.pathname === '/workrally/studio/refresh') {
256
283
  if (!isJson) {
257
284
  sendJson(res, 415, { error: 'json required' });
@@ -299,6 +326,63 @@ export const createStudioHandler = ctx => async (req, res) => {
299
326
  }
300
327
  return;
301
328
  }
329
+ if (url.pathname === '/workrally/assets') {
330
+ try {
331
+ sendJson(res, 200, await readNativeAssets(ctx, {
332
+ page: url.searchParams.get('page') || 1,
333
+ materialType: url.searchParams.get('type') || '',
334
+ canvasId: url.searchParams.get('canvas') || '',
335
+ keyword: url.searchParams.get('q') || '',
336
+ }));
337
+ } catch (error) {
338
+ sendJson(res, 502, { error: error?.message || '媒资暂时读取不到,请稍后重试' });
339
+ }
340
+ return;
341
+ }
342
+ if (url.pathname === '/workrally/assets/prompt') {
343
+ try {
344
+ const prompt = await readAssetPrompt(ctx, url.searchParams.get('id') || '', url.searchParams.get('canvas') || '');
345
+ sendJson(res, 200, { prompt });
346
+ } catch {
347
+ sendJson(res, 200, { prompt: '' });
348
+ }
349
+ return;
350
+ }
351
+ if (url.pathname === '/workrally/assets/play') {
352
+ try {
353
+ const target = await readAssetDownloadTarget(ctx, url.searchParams.get('id') || '');
354
+ const media = await resolveAssetPlaybackUrl(target.url);
355
+ res.writeHead(302, {
356
+ location: media.url,
357
+ 'cache-control': 'private, no-store',
358
+ 'referrer-policy': 'no-referrer',
359
+ });
360
+ res.end();
361
+ } catch (error) {
362
+ if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '视频暂时播放不了,请稍后重试' });
363
+ }
364
+ return;
365
+ }
366
+ if (url.pathname === '/workrally/assets/file') {
367
+ try {
368
+ const target = await readAssetDownloadTarget(ctx, url.searchParams.get('id') || '');
369
+ const file = await downloadAssetFile(target.url);
370
+ const ext = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'audio/wav': 'wav', 'audio/wave': 'wav', 'audio/mpeg': 'mp3', 'audio/mp4': 'm4a' }[file.mime] || 'bin';
371
+ const base = String(target.title || url.searchParams.get('id') || 'workrally').replace(/[\\/:*?"<>|\r\n]+/g, ' ').trim().slice(0, 80) || 'workrally';
372
+ const filename = `${base}.${ext}`;
373
+ res.writeHead(200, {
374
+ 'content-type': file.mime,
375
+ 'content-length': file.bytes.length,
376
+ 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
377
+ 'cache-control': 'private, no-store',
378
+ 'x-content-type-options': 'nosniff',
379
+ });
380
+ res.end(file.bytes);
381
+ } catch (error) {
382
+ if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '下载失败,请稍后重试' });
383
+ }
384
+ return;
385
+ }
302
386
  if (url.pathname === '/workrally/draft/Consume') {
303
387
  const item = queuedDraft && Date.now() - queuedDraft.at < 30_000 ? queuedDraft : null;
304
388
  queuedDraft = null;
@@ -312,18 +396,22 @@ export const createStudioHandler = ctx => async (req, res) => {
312
396
  } catch {
313
397
  // 按不存在处理
314
398
  }
315
- const file = readGalleryFile(id, url.searchParams.get('session') || '');
316
- if (!file) {
317
- sendJson(res, 404, { error: 'not found' });
399
+ const session = url.searchParams.get('session') || '';
400
+ const cached = readGalleryFile(id, session);
401
+ if (cached) {
402
+ sendMedia(res, cached, 'private, max-age=86400');
318
403
  return;
319
404
  }
320
- res.writeHead(200, {
321
- 'content-type': file.mime,
322
- 'content-length': file.bytes.length,
323
- 'cache-control': 'private, max-age=86400',
324
- 'x-content-type-options': 'nosniff',
325
- });
326
- res.end(file.bytes);
405
+ try {
406
+ const file = await materializeGalleryFile(id, session, record => resolveAssetMediaUrl(ctx, record));
407
+ if (!file) {
408
+ sendJson(res, 404, { error: 'not found' });
409
+ return;
410
+ }
411
+ sendMedia(res, file, 'private, max-age=86400');
412
+ } catch (error) {
413
+ if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '媒体读取失败,请稍后重试' });
414
+ }
327
415
  return;
328
416
  }
329
417
  const session = sessionParam(url.searchParams.get('session') || '');
package/lib/mcp.js CHANGED
@@ -275,3 +275,330 @@ export const readNativeCanvases = async (ctx, signal) => {
275
275
  projects,
276
276
  };
277
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 CHANGED
@@ -87,6 +87,8 @@ export const parseCollections = (rows) => {
87
87
  if (!raw || typeof raw !== 'object') continue;
88
88
  const id = readText(raw.id || raw._id);
89
89
  const title = readText(raw.title);
90
+ // This collection is intentionally excluded from the DSH plugin.
91
+ if (id === '3zsszfod4t' || title === '代码搓片') continue;
90
92
  const desc = readText(raw.desc);
91
93
  const rawItems = parseJson(raw.items);
92
94
  const list = Array.isArray(rawItems) ? rawItems : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-workrally",
3
- "version": "0.2.5",
3
+ "version": "0.3.0",
4
4
  "description": "WorkRally 创作工作台:原生 MCP、按需创作技能、任务追踪与会话素材。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",