@zenaigc/zenmcp 0.1.4 → 0.1.6

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/INSTALL.md CHANGED
@@ -72,7 +72,6 @@ Key 不得在对话中回显明文。由用户自行粘贴进配置,或由 Age
72
72
  - **SuperOne**:在其 MCP 设置中添加上述配置块。
73
73
  - **Claude Code**:命令格式为 `claude mcp add zenmcp -s user -e ZENMCP_TOKEN=<Key> -- zenmcp`;不要在对话中回显真实 Key,避免将含真实 Key 的命令保存在历史或日志中。
74
74
  - **Claude Desktop**:在 `claude_desktop_config.json` 中添加上述配置块。
75
- - **OpenClaw**:在其 MCP 配置中添加上述配置块。
76
75
 
77
76
  命令查找失败时按以下顺序处理:
78
77
 
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  ## 一句话
7
7
 
8
- 在 Super-1(多 harness 桌面 Agent 壳)之上,用 MCP 原子工具 + 对话式 Agent,为非专业用户提供短视频复刻能力:第一批以电商带货为业务方向,覆盖**穿搭展示、手持展示、场景展示、人物讲述**四类视频(可叠加口播、画面特效等属性),核心操作是换人、换产品(含换衣服)、或人品双换,并保持原片的结构、节奏和卡点。
8
+ 在 Super-1(多 harness 桌面 Agent 壳)之上,用 MCP 原子工具 + 对话式 Agent,为非专业用户提供短视频拆解二创能力:第一批以电商带货为业务方向,覆盖**穿搭展示、手持展示、场景展示、人物讲述**四类视频(可叠加口播、画面特效等属性),核心操作是换人、换产品(含换衣服)、或人品双换,并保持原片的结构、节奏和卡点。
9
9
 
10
10
  ## 项目关系
11
11
 
@@ -39,7 +39,7 @@
39
39
  以下是既有产品方向,不代表功能均已实现;历史范围与新云建议冲突时,先查当前进度页及最新明确决定,不从旧文档推导开工授权。
40
40
 
41
41
  - 形态:Super-1 内的能力(小程序 `.s1app` + MCP 工具 + Skill),对话为主、UI 为辅(UI 只做语言难描述的对齐与可视化确认)。
42
- - 用户:非专业用户(非 AIGC 专业、非行业专业),看到好视频就想复刻。
42
+ - 用户:非专业用户(非 AIGC 专业、非行业专业),看到好视频就想拆解二创。
43
43
  - 动作:靠参考视频本身或白模(姿态/骨骼信号)驱动,不做动作词表;语义识别只是可选加强。
44
44
  - 人物:不提供人物库;模特由用户提供参考图,版权由用户自行确认并承担。用户选择保留原片模特时不做授权确认。
45
45
  - 素材外发:不做授权审核,也不单独告知,相关说明写入服务条款。
@@ -86,6 +86,8 @@ async function exists(path) {
86
86
  }
87
87
  }
88
88
  async function syncDirectory(dir) {
89
+ if (process.platform === "win32")
90
+ return;
89
91
  const handle = await open(dir, "r");
90
92
  try {
91
93
  await handle.sync();
@@ -207,7 +207,9 @@ export class DirectGeneration {
207
207
  }
208
208
  return assets;
209
209
  }
210
- async quote(input) {
210
+ async quote(input) { return (await this.quoteDetailed(input)).quote; }
211
+ /** quote() plus the request and catalog entry it was built from, so presentation needs no second catalog fetch or re-read. */
212
+ async quoteDetailed(input) {
211
213
  const secret = await this.options.tokens.token();
212
214
  const raw = { capability: input.capability, prompt: input.prompt, params: input.params, voice_id: input.voice_id };
213
215
  if (JSON.stringify(scrub(raw, secret)) !== JSON.stringify(raw) || [input.prompt, ...Object.values(input.params ?? {})].some(v => typeof v === 'string' && /zk_(?:live|test)_[A-Za-z0-9_-]+|Bearer\s+\S+/i.test(v)))
@@ -319,7 +321,7 @@ export class DirectGeneration {
319
321
  await writeJson(dir, 'request.json', req);
320
322
  if (!attempts.length)
321
323
  await writeJson(dir, 'state.json', { request_digest: digest, status: 'quoted' });
322
- return { ...req.quote, requestDigest: digest, markdown: `报价 ${quote.price_credits} 积分。请获得用户明确批准后,携带 requestDigest 调用 run_generation。` };
324
+ return { quote: { ...req.quote, requestDigest: digest, markdown: `报价 ${quote.price_credits} 积分。请获得用户明确批准后,携带 requestDigest 调用 run_generation。` }, request: req.request, capability: cap };
323
325
  }
324
326
  finally {
325
327
  await release();
@@ -21,8 +21,11 @@ const EFFECT_RENDERER_UNAVAILABLE = 'effect_renderer_unavailable:任务有特
21
21
  export function safeError(error, secret) {
22
22
  // External exception messages may contain credentials or signed output URLs.
23
23
  const fileError = error;
24
- if (fileError && typeof fileError.code === 'string' && typeof fileError.syscall === 'string')
25
- return `file_error:${fileError.code}`;
24
+ if (fileError && typeof fileError.code === 'string' && typeof fileError.syscall === 'string') {
25
+ const code = /^[A-Z0-9_]+$/i.test(fileError.code) ? fileError.code : 'UNKNOWN';
26
+ const syscall = /^[a-z0-9_]+$/i.test(fileError.syscall) ? ` (${fileError.syscall})` : '';
27
+ return `file_error:${code}${syscall}`;
28
+ }
26
29
  const message = error instanceof Error ? error.message : 'step_failed';
27
30
  return containsSensitiveText(message) ? 'step_failed:外部错误详情未持久化,避免泄露敏感信息' : scrub(message, secret);
28
31
  }
@@ -293,7 +296,8 @@ export class Engine {
293
296
  return out({ path: result.path, checks: await inspectComposited(job, path('conform'), result.path, { effectRanges: result.ranges }) }, [result.path]);
294
297
  }
295
298
  case 'mix': {
296
- const audio = input.audio ?? ((await probe(input.reference)).has_audio ? input.reference : undefined);
299
+ // The analyze step already proved storyboard.source equals a fresh probe of this reference.
300
+ const audio = input.audio ?? (job.storyboard.source.has_audio ? input.reference : undefined);
297
301
  const result = await mixAudio(path('effects'), audio, await file('mixed.mp4'));
298
302
  return out({ ...result, note: result.silent ? '没有音源,静音输出。' : '音源裁至成片时长,短音源补静音、尾部淡出,目标 -14 LUFS;实测见导出检查。' }, [result.path]);
299
303
  }
@@ -25,6 +25,8 @@ export class MemoryAttemptStore {
25
25
  }
26
26
  }
27
27
  async function syncDirectory(dir) {
28
+ if (process.platform === "win32")
29
+ return;
28
30
  const handle = await open(dir, "r");
29
31
  try {
30
32
  await handle.sync();
@@ -143,7 +143,7 @@ export class CloudGateway {
143
143
  const response = await this.fetchImpl(putUrl, {
144
144
  method: "PUT",
145
145
  headers: { "Content-Type": contentType },
146
- body: new Uint8Array(bytes),
146
+ body: bytes,
147
147
  redirect: "error",
148
148
  signal: AbortSignal.timeout(this.uploadTimeoutMs),
149
149
  });
@@ -1,5 +1,6 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
+ import { ByteQueue } from "../timeline/ffmpeg.js";
3
4
  const exec = promisify(execFile);
4
5
  export async function command(bin, args) {
5
6
  return exec(bin, args, { maxBuffer: 16 * 1024 * 1024 });
@@ -22,17 +23,16 @@ export async function* frames(path, bytes) {
22
23
  child.on("close", code => code === 0 ? resolve() : reject(new Error(`decode failed: ${stderr}`)));
23
24
  });
24
25
  void done.catch(() => undefined);
25
- let pending = Buffer.alloc(0);
26
+ // Re-concatenating the pending bytes per pipe chunk copied each frame dozens of times.
27
+ const queue = new ByteQueue();
26
28
  try {
27
29
  for await (const chunk of child.stdout) {
28
- pending = Buffer.concat([pending, chunk]);
29
- while (pending.length >= bytes) {
30
- yield pending.subarray(0, bytes);
31
- pending = pending.subarray(bytes);
32
- }
30
+ queue.push(chunk);
31
+ for (let frame = queue.take(bytes); frame !== null; frame = queue.take(bytes))
32
+ yield frame;
33
33
  }
34
34
  await done;
35
- if (pending.length)
35
+ if (queue.length)
36
36
  throw new Error("partial frame");
37
37
  }
38
38
  finally {
@@ -15,7 +15,7 @@ import { SpeechTools, transcribeInputSchema, cloneInputSchema } from '../speech/
15
15
  import { trimMedia } from '../acquire/trim.js';
16
16
  import { ACCOUNT_URL, ERROR_GUIDANCE, POLL_AFTER_SECONDS, LARGE_AMOUNT_CREDITS, LARGE_BALANCE_RATIO, errorGuidance } from './guidance.js';
17
17
  export const DEFAULT_BASE_URL = 'https://api.zenaigc.com/api/v1';
18
- export const CLIENT_VERSION = '0.1.4';
18
+ export const CLIENT_VERSION = '0.1.6';
19
19
  const inputSchema = z.object({
20
20
  job: jobSchema, reference: z.string().min(1),
21
21
  output: z.object({ duration_seconds: z.number().int(), resolution: z.enum(['480P', '720P', '1080P']), ratio: z.string(), seed: z.number().int().optional() }),
@@ -30,7 +30,7 @@ function effectiveAvailableCredits(me) {
30
30
  return Math.min(me.credits_available, ...(me.daily_credit_limit === null ? [] : [Math.max(0, me.daily_credit_limit - me.used_today)]), ...(me.total_credit_limit === null ? [] : [Math.max(0, me.total_credit_limit - me.used_total)]));
31
31
  }
32
32
  const GETTING_STARTED = {
33
- examples: ['生成一张雨后街头的图片', '用这个链接复刻一段短视频', '把这段录音转成文字'],
33
+ examples: ['生成一张雨后街头的图片', '用这个链接拆解二创一段短视频', '把这段录音转成文字'],
34
34
  billing_rule: '报价免费,确认后才扣积分;失败退款以任务查询结果为准。',
35
35
  };
36
36
  function refundText(state) {
@@ -229,16 +229,11 @@ export function createServer(engine, socialOptions = {}, speechOptions = {}) {
229
229
  return { ...result, markdown: ['| 能力 id | 媒介 | 模型 | 必填素材 | 必填参数 |', '| --- | --- | --- | --- | --- |', ...rows.map(row => `| ${row} |`), '', '下一步:选择能力并调用 quote_generation 免费报价;本地文件上传前须取得用户同意。'].join('\n') };
230
230
  }));
231
231
  server.registerTool('quote_generation', { description: '免费报价,不提交生成;会上传本地素材,须先取得上传同意。报价后一次性展示模型、关键参数、上传文件数和积分,取得明确批准后携带 requestDigest 调用 run_generation。', inputSchema: { directory: z.string(), capability: z.string(), prompt: z.string().optional(), voice_id: z.string().min(1).optional(), voice_authorized: z.boolean().optional(), params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(), inputs: z.record(z.string(), z.string()).optional(), consent_confirmed: z.boolean().optional() } }, guarded(async (i) => {
232
- const result = await direct.quote(i);
233
- // Only read presentation metadata here; the engine remains the execution authority.
234
- const [{ request }, catalog, me] = await Promise.all([
235
- direct.get({ directory: i.directory }),
236
- engine.options.gateway.catalog().catch(() => null),
237
- engine.options.gateway.me().catch(() => null),
238
- ]);
239
- const model = catalog?.modified ? catalog.catalog.capabilities.find(c => c.id === request.capability) : undefined;
232
+ // The engine remains the execution authority; its request and catalog entry are reused for presentation only.
233
+ const { quote: result, request, capability: model } = await direct.quoteDetailed(i);
234
+ const me = await engine.options.gateway.me().catch(() => null);
240
235
  const params = Object.entries(request.params).filter(([key]) => key !== 'prompt').map(([key, value]) => {
241
- const spec = model?.params.find(p => p.key === key);
236
+ const spec = model.params.find(p => p.key === key);
242
237
  return { key, label: spec?.label ?? key, value: spec?.options?.find(o => o.value === value)?.label ?? (typeof value === 'boolean' ? value ? '开启' : '关闭' : value) };
243
238
  });
244
239
  const prompt = String(request.params.prompt ?? '');
@@ -250,7 +245,7 @@ export function createServer(engine, socialOptions = {}, speechOptions = {}) {
250
245
  const large = credits >= LARGE_AMOUNT_CREDITS || (balance !== null && credits > balance * LARGE_BALANCE_RATIO);
251
246
  const confirmation = { kind: 'spend', credits, balance_before: balance, balance_after: balance === null ? null : balance - credits, sufficient, large, params, uploads, prompt_preview: preview };
252
247
  const markdown = [
253
- '### 生成确认', `- 模型:${model?.name ?? request.capability}(${request.capability})`,
248
+ '### 生成确认', `- 模型:${model.name ?? request.capability}(${request.capability})`,
254
249
  `- 参数:${params.length ? params.map(p => `${p.label}=${p.value}`).join(' · ') : '无额外参数'}`,
255
250
  ...(preview ? [`- 提示词:${preview}`] : []),
256
251
  ...(uploads.length ? [`- 上传:本次报价已上传 ${uploads.length} 个本地文件(${uploads.join('、')})`] : []),
@@ -285,10 +280,14 @@ export function createServer(engine, socialOptions = {}, speechOptions = {}) {
285
280
  }
286
281
  if (result.status === 'failed') {
287
282
  const detail = (await failure(new Error(attempt?.rejected_code ?? result.error ?? 'step_failed'), engine.tokens)).structuredContent;
283
+ const fileHint = detail.code === 'file_error' && result.error?.startsWith('file_error:') ? `(${result.error.slice('file_error:'.length)})` : '';
284
+ const reason = `${detail.message}${fileHint}`;
288
285
  const status = attempt?.status === 'cancelled' ? 'cancelled' : 'failed';
289
- const refund = refundText(attempt?.refund_state);
290
- return { ...result, result_summary: { status, reason: detail.message, refund_state: attempt?.refund_state ?? 'unknown', refund_message: refund },
291
- markdown: `${status === 'cancelled' ? '生成已取消' : '生成未完成'}:${detail.message}\n\n${refund}${result.charge_notice ? `\n\n${result.charge_notice}:预算已保留。${errorGuidance('outcome_unknown').next}` : ''}`,
286
+ const uncharged = (!attempt && !result.charge_notice) || attempt?.state === 'rejected';
287
+ const refund_state = uncharged ? 'uncharged' : (attempt?.refund_state ?? 'unknown');
288
+ const refund = uncharged ? '本次未产生扣费,无需等待退款。' : refundText(attempt?.refund_state);
289
+ return { ...result, result_summary: { status, reason, refund_state, refund_message: refund },
290
+ markdown: `${status === 'cancelled' ? '生成已取消' : '生成未完成'}:${reason}\n\n${refund}${result.charge_notice ? `\n\n${result.charge_notice}:预算已保留。${errorGuidance('outcome_unknown').next}` : ''}`,
292
291
  next_action: result.charge_notice ? errorGuidance('outcome_unknown').next : detail.next_action,
293
292
  };
294
293
  }
@@ -302,13 +301,13 @@ export function createServer(engine, socialOptions = {}, speechOptions = {}) {
302
301
  inputSchema: transcribeInputSchema.shape,
303
302
  }, guarded(input => speech.transcribe(input)));
304
303
  server.registerTool('clone_voice', {
305
- description: '使用用户明确同意的本地音频样本训练复刻音色。必须显式传入 consent_confirmed:true;≤10MB,建议14–30秒。训练不启用音色,付费启用另需报价和批准。相同参数重试可续查。',
304
+ description: '使用用户明确同意的本地音频样本训练定制音色。必须显式传入 consent_confirmed:true;≤10MB,建议14–30秒。训练不启用音色,付费启用另需报价和批准。相同参数重试可续查。',
306
305
  inputSchema: cloneInputSchema.shape,
307
306
  }, guarded(input => speech.clone(input)));
308
- server.registerTool('list_voices', { description: '查询当前账户复刻音色及 training、ready、active、failed、expired 状态;不启用、不收费。', inputSchema: {} }, guarded(() => speech.list()));
307
+ server.registerTool('list_voices', { description: '查询当前账户定制音色及 training、ready、active、failed、expired 状态;不启用、不收费。', inputSchema: {} }, guarded(() => speech.list()));
309
308
  const prompts = [
310
309
  { name: 'generate_media', title: '生成图片或视频', text: '请帮我生成图片或视频:先 list_models,再 quote_generation 免费报价。本地素材上传前取得同意;一次性确认模型、关键参数、上传文件数及积分后,携带 requestDigest 调用 run_generation;按 poll_after_seconds 等待后在同一目录 get_generation,并展示输出。' },
311
- { name: 'replicate_video', title: '复刻短视频', text: '请复刻我提供的短视频:链接先 fetch_social_post,本地文件直接 analyze_reference;必要时选段并 trim_media。展示素材并确认最终属性后 import_assets,再 plan_job;一次合并确认模型、关键参数、上传文件数及积分后 execute_job,按 poll_after_seconds 在同一目录 get_job,展示输出。' },
310
+ { name: 'replicate_video', title: '拆解二创短视频', text: '请拆解二创我提供的短视频:链接先 fetch_social_post,本地文件直接 analyze_reference;必要时选段并 trim_media。展示素材并确认最终属性后 import_assets,再 plan_job;一次合并确认模型、关键参数、上传文件数及积分后 execute_job,按 poll_after_seconds 在同一目录 get_job,展示输出。' },
312
311
  { name: 'check_setup', title: '检查安装与账户', text: `请检查 Zenmcp 安装和账户:环境异常时运行 zenmcp-doctor,随后 account_status 查询积分与客户端版本。缺少或无效的 Key 请引导用户前往 ${ACCOUNT_URL} 创建,写入 MCP 客户端配置 env.ZENMCP_TOKEN 后重新加载;绝不在聊天中索取 Key。` },
313
312
  ];
314
313
  for (const prompt of prompts)
@@ -8,6 +8,7 @@ import { sha256File } from '../core/index.js';
8
8
  import { hash } from '../engine/steps.js';
9
9
  import { lockJob, readJson, writeJson } from '../engine/storage.js';
10
10
  import { directory } from '../assets/files.js';
11
+ import { GatewayError } from '../gateway/index.js';
11
12
  import { transcriptionCreateSchema, voiceCreateSchema } from '../contract/cloud-v1.js';
12
13
  import { extractAudio, mediaCommand, probeAudio } from './audio.js';
13
14
  export const transcribeInputSchema = z.object({ path: z.string().min(1), language: z.string().min(1).max(32).optional(), speaker_info: z.boolean().optional(), output: z.string().min(1).optional() });
@@ -102,6 +103,37 @@ export class SpeechTools {
102
103
  await rm(temp, { recursive: true, force: true });
103
104
  }
104
105
  }
106
+ /**
107
+ * Create the cloud task once per receipt, or re-read it by ID. A stored receipt whose upload has
108
+ * since expired answers `asset_not_found`: the server looks the key up before the asset, so that
109
+ * answer proves it holds no task for this key, and the upload is replaced once under a fresh key.
110
+ */
111
+ async submit(dir, body, get, post) {
112
+ const fresh = async () => {
113
+ const next = { key: randomUUID(), body: await body() };
114
+ await writeJson(dir, 'request.json', next);
115
+ return next;
116
+ };
117
+ const stored = await this.load(dir);
118
+ let receipt = stored ?? await fresh();
119
+ let created;
120
+ if (receipt.id)
121
+ created = await get(receipt.id);
122
+ else {
123
+ try {
124
+ created = await post(receipt);
125
+ }
126
+ catch (error) {
127
+ if (!stored || !(error instanceof GatewayError) || error.code !== 'asset_not_found')
128
+ throw error;
129
+ receipt = await fresh();
130
+ created = await post(receipt);
131
+ }
132
+ }
133
+ receipt.id = created.id;
134
+ await writeJson(dir, 'request.json', receipt);
135
+ return { receipt, created };
136
+ }
105
137
  async poll(initial, pending, get, timeoutMs) {
106
138
  const deadline = this.now() + timeoutMs;
107
139
  let current = initial;
@@ -124,15 +156,7 @@ export class SpeechTools {
124
156
  const dir = await this.receiptDir(source, dirname(output), 'transcription', params);
125
157
  const release = await lockJob(dir);
126
158
  try {
127
- let receipt = await this.load(dir);
128
- if (!receipt) {
129
- const asset_id = await this.upload(source, TRANSCRIPTION_MAX_BYTES, 1800);
130
- receipt = { key: randomUUID(), body: { asset_id, ...params } };
131
- await writeJson(dir, 'request.json', receipt);
132
- }
133
- const created = receipt.id ? await this.gateway.getTranscription(receipt.id) : await this.gateway.createTranscription(transcriptionCreateSchema.parse(receipt.body), receipt.key);
134
- receipt.id = created.id;
135
- await writeJson(dir, 'request.json', receipt);
159
+ const { receipt, created } = await this.submit(dir, async () => ({ asset_id: await this.upload(source, TRANSCRIPTION_MAX_BYTES, 1800), ...params }), id => this.gateway.getTranscription(id), r => this.gateway.createTranscription(transcriptionCreateSchema.parse(r.body), r.key));
136
160
  const result = await this.poll(created, t => t.status === 'queued' || t.status === 'running', () => this.gateway.getTranscription(created.id), this.options.transcriptionTimeoutMs ?? 300_000);
137
161
  if (result.status === 'failed')
138
162
  throw new Error(`transcription_failed:${result.error};任务 ${result.id}。`);
@@ -158,16 +182,7 @@ export class SpeechTools {
158
182
  const dir = await this.receiptDir(source, dirname(source), 'voice', { name: input.name, consent_confirmed: input.consent_confirmed });
159
183
  const release = await lockJob(dir);
160
184
  try {
161
- let receipt = await this.load(dir);
162
- if (!receipt) {
163
- const sample_asset_id = await this.upload(source, VOICE_MAX_BYTES, Number.POSITIVE_INFINITY);
164
- const body = { name: input.name, sample_asset_id, consent_confirmed: input.consent_confirmed };
165
- receipt = { key: randomUUID(), body };
166
- await writeJson(dir, 'request.json', receipt);
167
- }
168
- const created = receipt.id ? await this.gateway.getVoice(receipt.id) : await this.gateway.createVoice(voiceCreateSchema.parse(receipt.body), receipt.key);
169
- receipt.id = created.id;
170
- await writeJson(dir, 'request.json', receipt);
185
+ const { receipt, created } = await this.submit(dir, async () => ({ name: input.name, sample_asset_id: await this.upload(source, VOICE_MAX_BYTES, Number.POSITIVE_INFINITY), consent_confirmed: input.consent_confirmed }), id => this.gateway.getVoice(id), r => this.gateway.createVoice(voiceCreateSchema.parse(r.body), r.key));
171
186
  const voice = await this.poll(created, v => v.status === 'training', () => this.gateway.getVoice(created.id), this.options.voiceTimeoutMs ?? 60_000);
172
187
  // Keep provider error text out of tool responses; Voice.error is an open wire string.
173
188
  const safe = safeVoice(voice);
@@ -179,6 +194,6 @@ export class SpeechTools {
179
194
  }
180
195
  async list() {
181
196
  const list = { voices: (await this.gateway.listVoices()).voices.map(safeVoice) };
182
- return { ...list, markdown: list.voices.length ? list.voices.map(v => `- ${v.name}(${v.id}):${v.status}`).join('\n') : '当前账户暂无复刻音色。' };
197
+ return { ...list, markdown: list.voices.length ? list.voices.map(v => `- ${v.name}(${v.id}):${v.status}`).join('\n') : '当前账户暂无定制音色。' };
183
198
  }
184
199
  }
@@ -125,10 +125,15 @@ export async function readRawFrames(stream, frameBytes, onFrame) {
125
125
  }
126
126
  return index;
127
127
  }
128
- class ByteQueue {
128
+ /** FIFO of decoder chunks: each frame is copied once, however the pipe splits it. */
129
+ export class ByteQueue {
129
130
  chunks = [];
130
131
  head = 0;
131
132
  available = 0;
133
+ /** Bytes buffered and not yet taken. */
134
+ get length() {
135
+ return this.available;
136
+ }
132
137
  push(chunk) {
133
138
  if (chunk.length === 0) {
134
139
  return;
@@ -1,6 +1,56 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { resolve } from "node:path";
1
3
  import { TimelineError } from "./errors.js";
2
4
  import { runExec } from "./ffmpeg.js";
5
+ const PROBE_CACHE_LIMIT = 32;
6
+ const probeCache = new Map();
7
+ /**
8
+ * Identity of the bytes currently at `path`. Any rewrite changes mtime/ctime, and a
9
+ * replacement changes the inode, so an equal key means the same content was probed.
10
+ */
11
+ async function fileIdentity(path) {
12
+ try {
13
+ const info = await stat(path, { bigint: true });
14
+ if (!info.isFile()) {
15
+ return null;
16
+ }
17
+ return [resolve(path), info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join("\0");
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ /**
24
+ * Counting frames decodes the whole stream, and one pipeline run asks about the same
25
+ * file from several modules. Results are remembered per file identity for this process;
26
+ * failures are never remembered.
27
+ */
3
28
  export async function probe(path) {
29
+ const key = await fileIdentity(path);
30
+ if (key === null) {
31
+ return probeFile(path);
32
+ }
33
+ let pending = probeCache.get(key);
34
+ if (pending === undefined) {
35
+ pending = probeFile(path).then(async (result) => {
36
+ // A file rewritten while ffprobe ran must not be remembered under its old identity.
37
+ if ((await fileIdentity(path)) !== key) {
38
+ probeCache.delete(key);
39
+ }
40
+ return result;
41
+ });
42
+ pending.catch(() => {
43
+ probeCache.delete(key);
44
+ });
45
+ probeCache.set(key, pending);
46
+ if (probeCache.size > PROBE_CACHE_LIMIT) {
47
+ probeCache.delete(probeCache.keys().next().value);
48
+ }
49
+ }
50
+ const result = await pending;
51
+ return { ...result, fps: { ...result.fps } };
52
+ }
53
+ async function probeFile(path) {
4
54
  // v:0 is ffprobe's specifier for the first video stream, the same stream
5
55
  // ffmpeg selects with -map 0:v:0. Audio is a separate selection so a
6
56
  // later video stream cannot replace the first one or hide the audio.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenaigc/zenmcp",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "zenmcp": "dist/src/mcp/server.js",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: zenmcp
3
- description: 用户需要生图、生视频、复刻短视频、录音识别、标准语音合成或进行 ZenMCP 环境配置自检时使用。
3
+ description: 用户需要生图、生视频、拆解二创短视频、录音识别、标准语音合成或进行 ZenMCP 环境配置自检时使用。
4
4
  ---
5
5
 
6
6
  # ZenMCP
@@ -11,12 +11,12 @@ description: 用户需要生图、生视频、复刻短视频、录音识别、
11
11
 
12
12
  - 直出生成:`list_models` → `quote_generation` → 展示报价并获得用户明确批准的积分 → `run_generation` → `get_generation`。
13
13
  - 每次生成使用新的空目录。本地素材上传前须获得用户同意,并传 `consent_confirmed: true`;提交时携带报价的 `requestDigest`。
14
- - 视频复刻:`fetch_social_post` 或用户提供的本地视频 → `analyze_reference` → 用户确认最终素材及属性后 `import_assets(confirmed: true)` → `plan_job` 报价 → 获批后 `execute_job` → `get_job`;修改走 `revise_job`。
14
+ - 视频拆解二创:`fetch_social_post` 或用户提供的本地视频 → `analyze_reference` → 用户确认最终素材及属性后 `import_assets(confirmed: true)` → `plan_job` 报价 → 获批后 `execute_job` → `get_job`;修改走 `revise_job`。
15
15
  - 分享链接先调用 `fetch_social_post`,每帖使用新的空目录,同一任务不重复抓取同一链接。本地视频跳过抓取,直接分析;抓取与分析无需用户确认。
16
16
  - 视频超过约 30 秒或报价提示时长限制时,先征求用户同意保留的片段,再用 `trim_media` 截取并分析截取后的文件。
17
17
  - 图集先展示图片,由用户确认哪些是产品或模特素材。最终素材及属性确认前不得调用 `import_assets`。
18
18
  - 录音识别:先取得本地音视频上传同意,再调用 `transcribe_media`(单次最长 30 分钟,当前服务端使用每日次数限额)。输出 `transcript.json`,相同参数可恢复未完成任务。
19
- - 标准语音合成:`list_models` → 选择 `doubao-seed-tts-2.0` → `quote_generation` → 用户批准积分 → `run_generation` → `get_generation`。音色训练与复刻暂不开放。
19
+ - 标准语音合成:`list_models` → 选择 `doubao-seed-tts-2.0` → `quote_generation` → 用户批准积分 → `run_generation` → `get_generation`。定制音色暂不开放。
20
20
  - 额度查询:用只读工具 `account_status` 查询。
21
21
 
22
22
  ## 展示与确认
@@ -35,8 +35,8 @@ description: 用户需要生图、生视频、复刻短视频、录音识别、
35
35
  - `plan_job` 后先原样展示返回的完整 `markdown`(分段、素材角色与属性、输出规格、预算明细及警告),随后用 `zenmcp-budget-confirm`,data 为 `{ confirmation, planDigest, directory, account_url }`。两者合为一次确认,不额外再问;当前 `confirmation` 只有总预算与重试预留,不得从设计示例编造分段、素材或余额。
36
36
  - `list_models` 用 `zenmcp-model-picker`,data 为 `{ medium, models: [{ capability, label, medium, price_hint, highlights }] }`;`account_status` 用 `zenmcp-account`,data 为其结果加 `account_url`;安装与配置引导用 `zenmcp-install-checklist`,Key 不进卡片。
37
37
  - **取用方式**:每个会话先调用一次 `widget_list_templates`。列表里有以上 id(用户手动保存的可能带后缀,按 `zenmcp-` 前缀匹配)就用 `widget_show({ template, data })`。没有时,征得用户同意后把 `widgets/<id>/` 整个目录一次性复制到 SuperOne 用户模板目录(stable 为 `~/.superone/widget/`,alpha 为 `~/.superone/alpha/widget/`),再查一次列表。仍然没有(Agent 与 SuperOne 桌面不在同一台机器)时,读取 `widgets/<id>/widget.html` 原文作为 `widget_code` 并照样传 `data`,不得改写 HTML。
38
- - **按钮消息即用户答复**:卡片按钮以用户身份发送固定文字。收到“确认付费生成:…批准 N 积分。requestDigest=…,directory=…”或“确认执行复刻任务,批准 N 积分。planDigest=…,directory=…”才算批准,按其中的积分和摘要调用付费工具。“把参数修改为…然后重新报价”:重新 `quote_generation` 并展示新卡。“取消这次付费,不要扣费。”:结束,不调用付费工具。“本次任务 N 积分内不用再逐次确认…”:按上文免再问预算处理。未收到确认前不得调用付费工具。
39
- - **结果展示**:生成图片用 `@native/image-gallery`,视频用 `@native/video-gallery`,data 为 `{ images | videos: [{ path }], prompt, params: { 模型, 关键参数, 实扣积分 }, warnings }`;实扣积分取 `result_summary.charged_credits`。复刻视频在 `warnings` 中加入“服装与身份需人工验收”。报告和多份文件用 `@native/files-previewer`。失败时不展示图集,按 `result_summary.reason` 与 `refund_message` 说明。
38
+ - **按钮消息即用户答复**:卡片按钮以用户身份发送固定文字。收到“确认付费生成:…批准 N 积分。requestDigest=…,directory=…”或“确认执行拆解二创任务,批准 N 积分。planDigest=…,directory=…”才算批准,按其中的积分和摘要调用付费工具。“把参数修改为…然后重新报价”:重新 `quote_generation` 并展示新卡。“取消这次付费,不要扣费。”:结束,不调用付费工具。“本次任务 N 积分内不用再逐次确认…”:按上文免再问预算处理。未收到确认前不得调用付费工具。
39
+ - **结果展示**:生成图片用 `@native/image-gallery`,视频用 `@native/video-gallery`,data 为 `{ images | videos: [{ path }], prompt, params: { 模型, 关键参数, 实扣积分 }, warnings }`;实扣积分取 `result_summary.charged_credits`。拆解二创视频在 `warnings` 中加入“服装与身份需人工验收”。报告和多份文件用 `@native/files-previewer`。失败时不展示图集,按 `result_summary.reason` 与 `refund_message` 说明。
40
40
  - **远程会话**:若展示时报“文件不存在”(Agent 在服务器上),把输出文件复制到 `$SUPERONE_SESSION_DIR/agent/<生成目录名>/`,用新路径展示;原生成目录保留不动,续查依赖它。
41
41
  - 有客户端提供的选项式提问工具时,用它呈现模型、参数和片段等选择。
42
42
  - 工具不存在时,按通用方式展示 Markdown 图片或文件路径,不调用不存在的工具。
@@ -25,6 +25,6 @@
25
25
  ]
26
26
  },
27
27
  "planDigest": "plan-example-001",
28
- "directory": "/tmp/复刻任务",
28
+ "directory": "/tmp/拆解二创任务",
29
29
  "account_url": "https://example.com/account"
30
30
  }
@@ -25,6 +25,6 @@
25
25
  ]
26
26
  },
27
27
  "planDigest": "plan-example-001",
28
- "directory": "/tmp/复刻任务",
28
+ "directory": "/tmp/拆解二创任务",
29
29
  "account_url": "https://example.com/account"
30
30
  }
@@ -5,5 +5,5 @@
5
5
  "retry_reserve_credits": 12
6
6
  },
7
7
  "planDigest": "plan-minimal-001",
8
- "directory": "/tmp/复刻任务"
8
+ "directory": "/tmp/拆解二创任务"
9
9
  }
@@ -25,6 +25,6 @@
25
25
  ]
26
26
  },
27
27
  "planDigest": "plan-example-001",
28
- "directory": "/tmp/复刻任务",
28
+ "directory": "/tmp/拆解二创任务",
29
29
  "account_url": "https://example.com/account"
30
30
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "zenmcp-budget-confirm",
3
- "title": "复刻预算确认",
4
- "description": "复刻任务总预算、分段及重试预留",
3
+ "title": "拆解二创预算确认",
4
+ "description": "拆解二创任务总预算、分段及重试预留",
5
5
  "inputSchema": {
6
6
  "type": "object",
7
7
  "properties": {
@@ -26,7 +26,7 @@ pair($('reserve'),'重试预留',`${display(view.reserve)} 积分(已含在总
26
26
  (view.segments ?? []).forEach(s => pair($('segments'),s.label,`${display(s.credits)} 积分`));
27
27
  if (view.assets?.length) $('assets').append(node('label','素材'),node('p',view.assets.join('、')));
28
28
  if (view.sufficient === false) { $('confirm').textContent = '充值'; $('confirm').disabled = !view.accountUrl; $('confirm').onclick = () => account(view.accountUrl); }
29
- else { $('confirm').textContent = `确认执行 ${display(view.total)} 积分 \u2197`; $('confirm').onclick = () => prompt(`确认执行复刻任务,批准 ${display(view.total)} 积分。planDigest=${view.digest},directory=${view.directory}`); }
29
+ else { $('confirm').textContent = `确认执行 ${display(view.total)} 积分 \u2197`; $('confirm').onclick = () => prompt(`确认执行拆解二创任务,批准 ${display(view.total)} 积分。planDigest=${view.digest},directory=${view.directory}`); }
30
30
  $('cancel').onclick = () => prompt('取消这次付费,不要扣费。');
31
31
 
32
32
  </script>