dsh-workrally 0.2.0 → 0.2.5

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/desk.js CHANGED
@@ -6,7 +6,7 @@ import { randomUUID } from 'node:crypto';
6
6
  import { existsSync, readFileSync } from 'node:fs';
7
7
  import { homedir } from 'node:os';
8
8
  import { join } from 'node:path';
9
- import { assetsForTask, gallerySessions, listGallery, rememberGeneration, sessionIdFromExec, sourceList, writeStore } from './gallery.js';
9
+ import { assetsForTask, gallerySessions, listGallery, reloadGalleryIfChanged, rememberGeneration, sessionIdFromExec, sourceList, writeStore } from './gallery.js';
10
10
  import { getConnection, isGenerationTool, isResultTool, normalizeToolResult, readNativeTask, workrallyTool } from './mcp.js';
11
11
 
12
12
  const TERMINAL = new Set(['success', 'failed', 'cancelled']);
@@ -300,9 +300,12 @@ const listSessions = async (ctx) => {
300
300
  };
301
301
 
302
302
  /** GET 与 POST refresh 共用的快照;这里不发起任何远端请求。 */
303
- export const getStudio = async (ctx, sessionId = '') => ({
304
- items: listGallery(sessionId),
305
- tasks: listTasks(sessionId),
306
- connection: await getConnection(ctx),
307
- sessions: await listSessions(ctx),
308
- });
303
+ export const getStudio = async (ctx, sessionId = '') => {
304
+ reloadGalleryIfChanged();
305
+ return {
306
+ items: listGallery(sessionId),
307
+ tasks: listTasks(sessionId),
308
+ connection: await getConnection(ctx),
309
+ sessions: await listSessions(ctx),
310
+ };
311
+ };
package/lib/gallery.js CHANGED
@@ -42,9 +42,14 @@ export const isAllowedGalleryMediaUrl = (value) => {
42
42
 
43
43
  const safeFileName = value => typeof value === 'string' && /^[\w-][\w.-]*$/.test(value) ? value : '';
44
44
  const clone = value => JSON.parse(JSON.stringify(value));
45
+ let storeMtime = 0;
45
46
  export const configureGalleryStore = (file) => { storeFile = file; writable = true; };
46
47
  export const resetGallery = () => { items.length = 0; };
47
- const saveGallery = () => { if (writable) writeStore(storeFile, { version: 2, items }); };
48
+ const saveGallery = () => {
49
+ if (!writable) return;
50
+ writeStore(storeFile, { version: 2, items });
51
+ try { storeMtime = statSync(storeFile).mtimeMs; } catch { /* 读不到时间时下次再判 */ }
52
+ };
48
53
 
49
54
  /**
50
55
  * 读取 v2 清单;旧数组清单只读迁移到另一个新文件,原文件永不改写。
@@ -78,6 +83,32 @@ export const loadGallery = (file, legacyFile) => {
78
83
  if (source === storeFile) writable = false;
79
84
  throw error;
80
85
  }
86
+ try { storeMtime = statSync(storeFile).mtimeMs; } catch { storeMtime = 0; }
87
+ };
88
+
89
+ /**
90
+ * 清单文件被外部写入(例如 Agent 用独立 MCP 客户端生成)后热加载。
91
+ * 解析失败时保留当前内存清单,不影响正在展示的片库。
92
+ */
93
+ export const reloadGalleryIfChanged = () => {
94
+ if (!storeFile || !existsSync(storeFile)) return false;
95
+ try {
96
+ const mtime = statSync(storeFile).mtimeMs;
97
+ if (mtime === storeMtime) return false;
98
+ const backup = items.slice();
99
+ const previousWritable = writable;
100
+ try {
101
+ loadGallery(storeFile);
102
+ } catch {
103
+ items.length = 0;
104
+ items.push(...backup);
105
+ writable = previousWritable;
106
+ return false;
107
+ }
108
+ return true;
109
+ } catch {
110
+ return false;
111
+ }
81
112
  };
82
113
 
83
114
  const publicItem = item => ({
@@ -161,8 +192,15 @@ export const rememberGeneration = (toolName, args, result, sessionId = '', metad
161
192
  for (const asset of collectAssets(normalized.payloads)) {
162
193
  const taskId = asset.taskId || metadata.taskId || '';
163
194
  const known = typeof metadata.lookup === 'function' ? metadata.lookup(tool.serverName, taskId) || {} : {};
164
- let item = items.find(entry => entry.sessionId === sessionId && entry.serverName === tool.serverName
165
- && (entry.taskId || '') === taskId && (asset.assetId ? entry.assetId === asset.assetId : entry.url === asset.url));
195
+ // 同一素材先按 assetId/URL 认领:提交回执与后续查询回执的 taskId 可能一个为空,
196
+ // 只按 taskId 比对会把同一次生成记成两条(一条带提示词、一条只剩素材标题)。
197
+ const sameScope = entry => entry.sessionId === sessionId
198
+ && (!entry.serverName || entry.serverName === tool.serverName);
199
+ let item = items.find(entry => sameScope(entry)
200
+ && (asset.assetId ? entry.assetId === asset.assetId : entry.url === asset.url));
201
+ if (!item && taskId) {
202
+ item = items.find(entry => sameScope(entry) && (entry.taskId || '') === taskId && !entry.assetId);
203
+ }
166
204
  if (!item) {
167
205
  item = { id: randomUUID(), at: new Date().toISOString(), file: '', prompt: '', model: '', sources: [], params: {} };
168
206
  items.unshift(item);
@@ -171,7 +209,8 @@ export const rememberGeneration = (toolName, args, result, sessionId = '', metad
171
209
  const pick = key => (own[key] && (!Array.isArray(own[key]) || own[key].length) ? own[key] : null)
172
210
  ?? (known[key] && (!Array.isArray(known[key]) || known[key].length) ? known[key] : null);
173
211
  Object.assign(item, {
174
- url: asset.url, mediaType: asset.mediaType, assetId: asset.assetId || item.assetId || '', taskId,
212
+ url: asset.url, mediaType: asset.mediaType, assetId: asset.assetId || item.assetId || '',
213
+ taskId: taskId || item.taskId || '',
175
214
  sessionId, serverName: tool.serverName,
176
215
  toolName: fromSubmit ? toolName : known.toolName || item.toolName || toolName,
177
216
  prompt: pick('prompt') || item.prompt || asset.title || '',
package/lib/index.js CHANGED
@@ -19,7 +19,8 @@ import {
19
19
  stopGalleryDownloads,
20
20
  } from './gallery.js';
21
21
  import { listInspiration } from './inspiration.js';
22
- import { configureMcp } from './mcp.js';
22
+ import { configureMcp, readNativeCanvases } from './mcp.js';
23
+ import { listCollections } from './plaza.js';
23
24
  import { registerWorkrallySkills } from './skills.js';
24
25
 
25
26
  export const name = 'dsh-workrally';
@@ -128,6 +129,95 @@ const proxyMedia = async (res, target) => {
128
129
  }
129
130
  };
130
131
 
132
+ const MAX_BRIDGE_BODY = 32_768;
133
+ const bridgeHeaders = (req) => {
134
+ const origin = String(req?.headers?.origin || '');
135
+ const allowed = /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/i.test(origin) ? origin : 'http://127.0.0.1:8765';
136
+ return {
137
+ 'access-control-allow-origin': allowed,
138
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
139
+ 'access-control-allow-headers': 'content-type',
140
+ vary: 'Origin',
141
+ };
142
+ };
143
+ let queuedDraft = null;
144
+ let bridgeServer = null;
145
+ let bridgeView = null;
146
+
147
+ const readBridgeBody = req => new Promise((resolve, reject) => {
148
+ const chunks = [];
149
+ let size = 0;
150
+ req.on('data', (chunk) => {
151
+ size += chunk.length;
152
+ if (size > MAX_BRIDGE_BODY) {
153
+ reject(Object.assign(new Error('草稿过长'), { status: 413 }));
154
+ req.destroy();
155
+ return;
156
+ }
157
+ chunks.push(chunk);
158
+ });
159
+ req.on('end', () => {
160
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); }
161
+ catch { reject(Object.assign(new Error('请求不是 JSON'), { status: 400 })); }
162
+ });
163
+ req.on('error', reject);
164
+ });
165
+
166
+ const startDraftBridge = async (log) => {
167
+ if (bridgeServer) return bridgeServer;
168
+ const { createServer } = await import('node:http');
169
+ const server = createServer(async (req, res) => {
170
+ const cors = bridgeHeaders(req);
171
+ const method = (req.method || 'GET').toUpperCase();
172
+ if (method === 'OPTIONS') {
173
+ res.writeHead(204, cors);
174
+ res.end();
175
+ return;
176
+ }
177
+ const url = new URL(req.url || '/', 'http://127.0.0.1:47829');
178
+ if (method === 'GET' && url.pathname === '/canvases') {
179
+ try {
180
+ const data = await readNativeCanvases(bridgeView);
181
+ res.writeHead(200, { ...cors, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
182
+ res.end(JSON.stringify(data));
183
+ } catch (error) {
184
+ res.writeHead(502, { ...cors, 'content-type': 'application/json; charset=utf-8' });
185
+ res.end(JSON.stringify({ error: error?.message || '画布读取失败' }));
186
+ }
187
+ return;
188
+ }
189
+ if (method !== 'POST' || url.pathname !== '/draft') {
190
+ res.writeHead(404, { ...cors, 'content-type': 'application/json; charset=utf-8' });
191
+ res.end('{"error":"not found"}');
192
+ return;
193
+ }
194
+ try {
195
+ const body = await readBridgeBody(req);
196
+ const text = typeof body?.text === 'string' ? body.text.trim() : '';
197
+ if (!text) {
198
+ res.writeHead(400, { ...cors, 'content-type': 'application/json; charset=utf-8' });
199
+ res.end('{"error":"empty"}');
200
+ return;
201
+ }
202
+ queuedDraft = { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, text, at: Date.now() };
203
+ res.writeHead(200, { ...cors, 'content-type': 'application/json; charset=utf-8' });
204
+ res.end(JSON.stringify({ ok: true, id: queuedDraft.id }));
205
+ } catch (error) {
206
+ res.writeHead(error?.status || 500, { ...cors, 'content-type': 'application/json; charset=utf-8' });
207
+ res.end(JSON.stringify({ error: error?.message || 'failed' }));
208
+ }
209
+ });
210
+ server.on('error', err => log?.('本地草稿桥端口占用', err));
211
+ server.listen(47829, '127.0.0.1');
212
+ bridgeServer = server;
213
+ return server;
214
+ };
215
+
216
+ const stopDraftBridge = () => {
217
+ try { bridgeServer?.close(); } catch { /* ignore */ }
218
+ bridgeServer = null;
219
+ };
220
+
131
221
  /** 路由处理器。所有路由先过宿主准入,再按会话过滤数据。 */
132
222
  export const createStudioHandler = ctx => async (req, res) => {
133
223
  const url = new URL(req.url || '/', 'http://127.0.0.1');
@@ -150,6 +240,18 @@ export const createStudioHandler = ctx => async (req, res) => {
150
240
  sendJson(res, 200, ctx.account.login());
151
241
  return;
152
242
  }
243
+ if (method === 'POST' && url.pathname === '/workrally/account/relogin') {
244
+ if (!isJson) {
245
+ sendJson(res, 415, { error: 'json required' });
246
+ return;
247
+ }
248
+ if (!ctx.account) {
249
+ sendJson(res, 503, { error: 'account unavailable' });
250
+ return;
251
+ }
252
+ sendJson(res, 200, await ctx.account.relogin());
253
+ return;
254
+ }
153
255
  if (method === 'POST' && url.pathname === '/workrally/studio/refresh') {
154
256
  if (!isJson) {
155
257
  sendJson(res, 415, { error: 'json required' });
@@ -181,6 +283,28 @@ export const createStudioHandler = ctx => async (req, res) => {
181
283
  }
182
284
  return;
183
285
  }
286
+ if (url.pathname === '/workrally/plaza') {
287
+ try {
288
+ sendJson(res, 200, { collections: await listCollections() });
289
+ } catch {
290
+ sendJson(res, 502, { error: '模版库暂时读取不到,请稍后重试' });
291
+ }
292
+ return;
293
+ }
294
+ if (url.pathname === '/workrally/canvases') {
295
+ try {
296
+ sendJson(res, 200, await readNativeCanvases(ctx));
297
+ } catch (error) {
298
+ sendJson(res, 502, { error: error?.message || '画布列表暂时读取不到,请稍后重试' });
299
+ }
300
+ return;
301
+ }
302
+ if (url.pathname === '/workrally/draft/Consume') {
303
+ const item = queuedDraft && Date.now() - queuedDraft.at < 30_000 ? queuedDraft : null;
304
+ queuedDraft = null;
305
+ sendJson(res, 200, { draft: item });
306
+ return;
307
+ }
184
308
  if (url.pathname.startsWith('/workrally/file/')) {
185
309
  let id = '';
186
310
  try {
@@ -242,14 +366,19 @@ export const apply = (ctx, config = {}) => {
242
366
  configureGalleryFiles(join(home, 'workrally-gallery-files'));
243
367
 
244
368
  const account = createAccount({ warn: log });
369
+ const view = hostView(ctx, account);
370
+ bridgeView = view;
371
+ startDraftBridge(log).catch(() => {});
245
372
  ctx.effect(() => () => {
246
373
  account.stop();
247
374
  stopDesk();
248
375
  stopGalleryDownloads();
376
+ stopDraftBridge();
377
+ bridgeView = null;
249
378
  }, 'dsh-workrally.stop');
250
379
  ctx.effect(() => ctx.on('tools/result', observeToolResult), 'dsh-workrally.observe');
251
380
  ctx.effect(
252
- () => ctx.webServer.register({ kind: 'prefix', path: '/workrally', handler: guarded(hostView(ctx, account), log) }),
381
+ () => ctx.webServer.register({ kind: 'prefix', path: '/workrally', handler: guarded(view, log) }),
253
382
  'dsh-workrally.route',
254
383
  );
255
384
 
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,173 @@ 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
+ };
package/lib/plaza.js ADDED
@@ -0,0 +1,153 @@
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
+ const desc = readText(raw.desc);
91
+ const rawItems = parseJson(raw.items);
92
+ const list = Array.isArray(rawItems) ? rawItems : [];
93
+ if (!id || !title || !list.length) continue;
94
+ const items = [];
95
+ list.forEach((entry, index) => {
96
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return;
97
+ const itemTitle = readText(entry.title);
98
+ if (!itemTitle) return;
99
+ const itemId = readText(entry.template_id || entry.id || entry.style) || `${id}-${index}`;
100
+ const cover = readMediaUrl(entry.cover_url);
101
+ const video = readMediaUrl(entry.video_url);
102
+ const itemDesc = readText(entry.description);
103
+ const category = readText(entry.category) || (entry.type === 'code2video' ? '代码搓片' : title);
104
+ items.push({
105
+ id: itemId,
106
+ title: itemTitle,
107
+ category,
108
+ description: itemDesc,
109
+ cover,
110
+ video,
111
+ prompt: buildPrompt(entry, title),
112
+ });
113
+ });
114
+ if (!items.length) continue;
115
+ out.push({
116
+ id,
117
+ title,
118
+ desc,
119
+ count: items.length,
120
+ covers: items.map(item => item.cover).filter(Boolean).slice(0, 3),
121
+ items,
122
+ });
123
+ }
124
+ return out;
125
+ };
126
+
127
+ const fetchCollections = async (fetchImpl) => {
128
+ const response = await fetchImpl(COLLECTION_SOURCE, { redirect: 'error', signal: AbortSignal.timeout(TIMEOUT_MS) });
129
+ if (!response.ok) throw new Error(`模版库读取失败(${response.status})`);
130
+ const data = await response.json();
131
+ if (data?.code !== 200) throw new Error('模版库读取失败');
132
+ return parseCollections(data.data);
133
+ };
134
+
135
+ export const listCollections = async (fetchImpl = fetch) => {
136
+ if (cache && Date.now() - cache.at < TTL_MS) return cache.collections;
137
+ loading ??= fetchCollections(fetchImpl)
138
+ .then((collections) => {
139
+ cache = { collections, at: Date.now() };
140
+ return collections;
141
+ })
142
+ .catch((error) => {
143
+ if (cache) return cache.collections;
144
+ throw error;
145
+ })
146
+ .finally(() => { loading = null; });
147
+ return loading;
148
+ };
149
+
150
+ export const resetCollections = () => {
151
+ cache = null;
152
+ loading = null;
153
+ };