@zenaigc/zenmcp 0.0.0-stage → 0.1.1

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.
Files changed (66) hide show
  1. package/INSTALL.md +77 -0
  2. package/README.md +53 -2
  3. package/dist/src/acquire/download.js +152 -0
  4. package/dist/src/acquire/errors.js +8 -0
  5. package/dist/src/acquire/share.js +67 -0
  6. package/dist/src/acquire/social.js +98 -0
  7. package/dist/src/acquire/trim.js +95 -0
  8. package/dist/src/assets/files.js +29 -0
  9. package/dist/src/assets/generator.js +141 -0
  10. package/dist/src/assets/images.js +90 -0
  11. package/dist/src/assets/index.js +3 -0
  12. package/dist/src/assets/model-library.js +87 -0
  13. package/dist/src/assets/upload-cache.js +36 -0
  14. package/dist/src/contract/cloud-v1.js +334 -0
  15. package/dist/src/core/hash.js +18 -0
  16. package/dist/src/core/index.js +4 -0
  17. package/dist/src/core/job-store.js +251 -0
  18. package/dist/src/core/safety.js +43 -0
  19. package/dist/src/core/schema.js +295 -0
  20. package/dist/src/doctor.js +22 -0
  21. package/dist/src/effects/check.js +19 -0
  22. package/dist/src/effects/font.js +78 -0
  23. package/dist/src/effects/index.js +188 -0
  24. package/dist/src/engine/card.js +50 -0
  25. package/dist/src/engine/direct.js +493 -0
  26. package/dist/src/engine/generate.js +234 -0
  27. package/dist/src/engine/index.js +3 -0
  28. package/dist/src/engine/media.js +24 -0
  29. package/dist/src/engine/steps.js +444 -0
  30. package/dist/src/engine/storage.js +90 -0
  31. package/dist/src/gateway/attempt-store.js +110 -0
  32. package/dist/src/gateway/budget.js +39 -0
  33. package/dist/src/gateway/cloud-gateway.js +141 -0
  34. package/dist/src/gateway/config.js +10 -0
  35. package/dist/src/gateway/device-auth.js +53 -0
  36. package/dist/src/gateway/errors.js +105 -0
  37. package/dist/src/gateway/http.js +124 -0
  38. package/dist/src/gateway/index.js +8 -0
  39. package/dist/src/gateway/paid-runner.js +376 -0
  40. package/dist/src/gateway/types.js +42 -0
  41. package/dist/src/inspect/index.js +276 -0
  42. package/dist/src/inspect/media.js +43 -0
  43. package/dist/src/mcp/server.js +177 -0
  44. package/dist/src/models/wan3/index.js +173 -0
  45. package/dist/src/models/wan3/limits.js +25 -0
  46. package/dist/src/timeline/conform.js +255 -0
  47. package/dist/src/timeline/cuts.js +225 -0
  48. package/dist/src/timeline/diff.js +82 -0
  49. package/dist/src/timeline/errors.js +8 -0
  50. package/dist/src/timeline/ffmpeg.js +164 -0
  51. package/dist/src/timeline/index.js +6 -0
  52. package/dist/src/timeline/params.js +46 -0
  53. package/dist/src/timeline/probe.js +98 -0
  54. package/dist/src/timeline/types.js +1 -0
  55. package/dist/templates/pop-title/README.md +18 -0
  56. package/dist/templates/pop-title/index.html +102 -0
  57. package/dist/templates/pop-title/pop-title.js +97 -0
  58. package/dist/templates/pop-title/render.js +42 -0
  59. package/dist/templates/pop-title/size-1080/index.html +102 -0
  60. package/dist/templates/pop-title/variables.example.json +9 -0
  61. package/dist/templates/pop-title/vendor/FONT.md +10 -0
  62. package/dist/templates/pop-title/vendor/NotoSansCJKsc-Bold.otf +0 -0
  63. package/dist/templates/pop-title/vendor/OFL.txt +92 -0
  64. package/dist/templates/pop-title/vendor/gsap.min.js +11 -0
  65. package/package.json +35 -4
  66. package/skills/zenmcp/SKILL.md +27 -0
package/INSTALL.md ADDED
@@ -0,0 +1,77 @@
1
+ # ZenMCP Agent 自助安装指南
2
+
3
+ 请按以下七步执行。涉及安装缺失依赖时先征得用户同意;平台 Key 不得在对话或日志中回显明文。
4
+
5
+ ## 1. 检查本机环境
6
+
7
+ 运行 `node -v`,确认 Node.js 版本 ≥ 22;运行 `ffmpeg -version`、`ffprobe -version`,并检查 Google Chrome 已安装且可启动。
8
+
9
+ 有缺失时,先告知用户需要安装的组件并征得同意,再按系统安装:
10
+
11
+ - macOS:使用 `brew`,例如 `brew install node@22 ffmpeg`、`brew install --cask google-chrome`。确保 Node.js 的 bin 目录在 PATH 中。
12
+ - Windows:使用 `winget`,例如 `winget install OpenJS.NodeJS.LTS`、`winget install Gyan.FFmpeg`、`winget install Google.Chrome`。
13
+ - Linux:使用 `apt` 安装 Node.js、FFmpeg 和 Google Chrome(Chrome 使用官方 deb 包交给 `apt` 安装)。先检查 apt 软件源提供的 Node.js 是否 ≥ 22;不满足时先说明需要配置兼容的软件源,获得用户同意后再处理。
14
+
15
+ 安装后重新打开终端并重复检查;Node.js 必须 ≥ 22,FFmpeg 安装应同时提供 ffprobe。
16
+
17
+ ## 2. 安装 ZenMCP
18
+
19
+ ```bash
20
+ npm install -g @zenaigc/zenmcp
21
+ ```
22
+
23
+ ## 3. 运行本机自检
24
+
25
+ ```bash
26
+ zenmcp-doctor
27
+ ```
28
+
29
+ 确认输出 `"ok": true`,否则按检查结果修复环境再运行。此时在终端直接运行,`config` 中 `ZENMCP_BASE_URL` 与 `ZENMCP_TOKEN` 两项显示为 `false` 是正常的;这两项只表示当前进程是否配置环境变量,不影响本机自检结果,也不验证平台 Key 或服务器连通性。
30
+
31
+ ## 4. 获取平台 Key
32
+
33
+ 引导用户登录 ZenAIGC 官网 https://zenaigc.com 获取平台 Key。**官网域名切换前请使用 https://api.zenaigc.com 登录获取**。
34
+
35
+ Key 不得在对话中回显明文。由用户自行粘贴进配置,或由 Agent 写入配置文件但不回显;不要把真实 Key 放入命令记录或日志。
36
+
37
+ ## 5. 配置 MCP 客户端
38
+
39
+ 通用配置块如下,将 `<平台Key>` 替换为用户的平台 Key:
40
+
41
+ ```json
42
+ {
43
+ "mcpServers": {
44
+ "zenmcp": {
45
+ "command": "zenmcp",
46
+ "env": {
47
+ "ZENMCP_TOKEN": "<平台Key>"
48
+ }
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ 无需配置 `ZENMCP_BASE_URL`,已内置默认地址 `https://api.zenaigc.com/api/v1`。编辑已有配置时合并 `zenmcp` 项,保留其他 MCP 服务。
55
+
56
+ - **WorkBuddy**:写入 `~/.workbuddy/mcp.json`,或在客户端 MCP 设置中添加上述配置块。
57
+ - **豆包电脑版**:左侧「技能·连接器」→ 添加 MCP,填入上述配置块,或命令填 `zenmcp`、环境变量填 `ZENMCP_TOKEN`。
58
+ - **SuperOne**:在其 MCP 设置中添加上述配置块。
59
+ - **Claude Code**:命令格式为 `claude mcp add zenmcp -s user -e ZENMCP_TOKEN=<Key> -- zenmcp`;不要在对话中回显真实 Key,避免将含真实 Key 的命令保存在历史或日志中。
60
+ - **Claude Desktop**:在 `claude_desktop_config.json` 中添加上述配置块。
61
+ - **OpenClaw**:在其 MCP 配置中添加上述配置块。
62
+
63
+ 命令查找失败时按以下顺序处理:
64
+
65
+ - Windows 上 `command` 用 `zenmcp.cmd`。
66
+ - GUI 客户端找不到命令时,`command` 改用 `command -v zenmcp`(Windows 用 `where zenmcp`)得到的绝对路径。
67
+ - 如果仍然报 `node` 找不到,`command` 填 `node` 的绝对路径,`args` 填 `["<npm root -g>/@zenaigc/zenmcp/dist/src/mcp/server.js"]`;将 `<npm root -g>` 替换为运行 `npm root -g` 得到的真实目录。
68
+
69
+ ## 6. 安装 Skill
70
+
71
+ 从 `$(npm root -g)/@zenaigc/zenmcp/skills/zenmcp/SKILL.md` 复制到客户端的 skills 目录,例如 `~/.agents/skills/zenmcp/SKILL.md`;Claude Code 为 `~/.claude/skills/zenmcp/SKILL.md`。先创建目标目录。Windows 上使用 `npm root -g` 的输出定位源文件,再复制到对应目录。
72
+
73
+ 客户端不支持 skills 时跳过这一步。
74
+
75
+ ## 7. 验证连通性
76
+
77
+ 重启客户端或重载 MCP,调用只读工具 `account_status`;返回积分信息即为连通。若提示 Key 未配置,检查客户端 MCP 环境变量后重载,排查时不要回显 Key。
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # Zenmcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > 状态(2026-11-07 UTC 核实):Z0–Z8、L1-01 至 L1-08、L1-10 至 L1-12、T6a/b/c 已合入;本分支代码基线 `82b9ba4`。Engine、MCP 与真实本地云代码的联调已完成,上游为 mock,S3 为本地 fake;真实供应商生成与付费案例未验收。云契约 v1.1 已冻结。
4
+ > 新会话先读 [当前进度与验收证据](docs/09-current-status.md) 和 [协作接续记录](docs/07-coordination.md),再按任务阅读模块与历史方案。本文状态是核对快照,接续时须重新检查代码和最新会话。
5
+
6
+ ## 一句话
7
+
8
+ 在 Super-1(多 harness 桌面 Agent 壳)之上,用 MCP 原子工具 + 对话式 Agent,为非专业用户提供短视频复刻能力:第一批以电商带货为业务方向,覆盖**穿搭展示、手持展示、场景展示、人物讲述**四类视频(可叠加口播、画面特效等属性),核心操作是换人、换产品(含换衣服)、或人品双换,并保持原片的结构、节奏和卡点。
9
+
10
+ ## 项目关系
11
+
12
+ - ZenAIGC:总项目名称。注意 `~/code/zenaigc` 是原网站主站仓库,不等于总项目本身。
13
+ - `zenmcp`(本项目):ZenAIGC 下通过 agentic 协作方式推出的第一个产品,承载于 Super-1,技术路线 MCP-first。
14
+ - 旧主站:保持不动,按需要参考已验证参数、协议与测试;客户端已改为对接云契约(`CloudGateway`)。
15
+ - 新云与薄网站:线路2负责注册、订阅、积分、平台 Key 和渠道;线路1负责 MCP 与本地视频闭环。云契约 v1.1 已冻结,云实现位于 `cloud/`;代码完成不代表生产上线或全部商业规则已确定。
16
+ - `Zenmini`:只读参考,不是继承基线,见 `docs/05-zenmini-reference.md`。
17
+ - 历史“两个项目再合并”的设想不作为当前实施依据;D-06 已定新账户与积分独立,不迁移旧账。最新远端及后续决定见当前进度页。
18
+
19
+ ## 文档索引
20
+
21
+ | 文件 | 内容 |
22
+ |---|---|
23
+ | `docs/00-briefing.md` | 综合简报:背景、已定方向、第一批内容的解决方案、技术架构、增长设想。给其他模型/新成员快速过目用 |
24
+ | `docs/01-research-competitors.md` | 竞品与开源生态深度调研全文(Hypit 深挖、平台 API/CLI/MCP 核查表、开源积木、许可证雷区) |
25
+ | `docs/research-notes/` | 调研过程笔记(Hypit 一手核查、生态笔记) |
26
+ | `docs/02-discussion-log.md` | 全部讨论的整理:每轮聊了什么、定了什么、哪些早期说法已被后续澄清作废 |
27
+ | `docs/03-open-questions.md` | 待确定问题清单(Muse 拟定,待用户逐项拍板) |
28
+ | `docs/04-blueprint-v1-draft-historical.md` | 历史草稿:早期「视频蓝图 Blueprint v1」,其品类收窄(桌前科技口播)已被后续讨论取代,仅作演进参考,不要直接据此开发 |
29
+ | `docs/05-zenmini-reference.md` | Zenmini 只读参考清单:裁决规则、证据教训、待重审决策、主站能力快照 |
30
+ | `docs/06-roadmap.md` | 路线与节奏草案、协作约定(待异模型审核) |
31
+ | `docs/07-coordination.md` | 正确指挥会话、两线责任、派单机制与接续核查入口 |
32
+ | `docs/08-quality-consistency-plan-draft.md` | Z0–Z8 的历史基础建设方案 v3;实现状态与后续方向以当前进度页为入口 |
33
+ | `docs/09-current-status.md` | 收尾基线、验收来源、已接受限制与 T10 前置条件 |
34
+ | `docs/10-cloud-contract.md` | 已冻结的云契约 v1.1 |
35
+ | `docs/history/docs-handoff-20261106/PRESERVATION.md` | 用户早先五份文档原文、校验值与逐项取舍记录 |
36
+
37
+ ## 产品方向(详见简报与讨论整理)
38
+
39
+ 以下是既有产品方向,不代表功能均已实现;历史范围与新云建议冲突时,先查当前进度页及最新明确决定,不从旧文档推导开工授权。
40
+
41
+ - 形态:Super-1 内的能力(小程序 `.s1app` + MCP 工具 + Skill),对话为主、UI 为辅(UI 只做语言难描述的对齐与可视化确认)。
42
+ - 用户:非专业用户(非 AIGC 专业、非行业专业),看到好视频就想复刻。
43
+ - 动作:靠参考视频本身或白模(姿态/骨骼信号)驱动,不做动作词表;语义识别只是可选加强。
44
+ - 人物:不提供人物库;模特由用户提供参考图,版权由用户自行确认并承担。用户选择保留原片模特时不做授权确认。
45
+ - 素材外发:不做授权审核,也不单独告知,相关说明写入服务条款。
46
+ - 分类:用户层按「视频在展示什么」分四类,并叠加口播、画面特效属性,由系统识别、用户无需选择;后台层按段标注制作维度,用于组合制作能力。
47
+ - 第一批承诺:四类都能识别和尝试;穿搭展示、手持展示做质量验收。
48
+ - 流程:引擎主控;Agent 负责对话和创作;原子工具保留给例外情况和高级用户。
49
+ - 视频判断:用户确认整条,后台按切点分段执行;不确定时用默认值,不逐段提问。
50
+ - 首批用户:现有学员(有货商家运营、无货达人、代运营人员)。
51
+ - 时长:有人声时默认按原时长,也可按台词音频时长。音频可由用户录制或音频原子能力生成,来源不决定时长模式;差距大时先告知,再调整音频或切换模式。无人声时不出现该选项。
52
+ - 模型:按视频类型定首选 + 备选顺序,不贪多;不自建模型。
53
+ - 工作原则:不做 Over-engineering,不过度审查。只做当前需求需要的最小方案;不为假想需求提前抽象;审查和测试按风险投入,计费、凭据、付费调用和删除用户素材才做严格审查。
54
+ - 已删除/搁置的概念不要再引入:泛化分级(深度/弱/强/结构泛化)、中期批量泛化规划、蓝图库/案例库/「什么结构能卖货」数据资产、动作词表。
@@ -0,0 +1,152 @@
1
+ import { lookup } from 'node:dns/promises';
2
+ import { isIP } from 'node:net';
3
+ import { request } from 'node:https';
4
+ import { Readable } from 'node:stream';
5
+ import { open, rename, rm } from 'node:fs/promises';
6
+ import { AcquireError } from './errors.js';
7
+ export const VIDEO_LIMIT = 500 * 1024 * 1024;
8
+ export const IMAGE_LIMIT = 30 * 1024 * 1024;
9
+ /** Accept global unicast only. Mapped IPv4 is checked by the IPv4 policy. */
10
+ export function isPublicAddress(address) {
11
+ if (isIP(address) === 4) {
12
+ const [a = 0, b = 0, c = 0, d = 0] = address.split('.').map(Number);
13
+ return !(a === 0 || a === 10 || a === 127 || a >= 224 ||
14
+ (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
15
+ (a === 172 && b >= 16 && b <= 31) || (a === 192 && (b === 168 || b === 0)) ||
16
+ (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||
17
+ (a === 192 && ((b === 0 && c === 2) || (b === 88 && c === 99))) ||
18
+ (a === 203 && b === 0 && c === 113) || (a === 168 && b === 63 && c === 129 && d === 16));
19
+ }
20
+ if (isIP(address) !== 6 || address.includes('%'))
21
+ return false;
22
+ // URL canonicalization expands embedded dotted IPv4 into hexadecimal words.
23
+ const normalized = new URL(`http://[${address}]/`).hostname.slice(1, -1);
24
+ if (normalized.startsWith('::ffff:')) {
25
+ const words = normalized.slice(7).split(':');
26
+ if (words.length !== 2)
27
+ return false;
28
+ const value = words.map(word => parseInt(word, 16));
29
+ return isPublicAddress(`${value[0] >> 8}.${value[0] & 255}.${value[1] >> 8}.${value[1] & 255}`);
30
+ }
31
+ const words = normalized.split(':');
32
+ const first = parseInt(words[0], 16), second = parseInt(words[1] || '0', 16);
33
+ // Exclude non-global space, transition mechanisms and documentation space.
34
+ return first >= 0x2000 && first <= 0x3fff &&
35
+ !(first === 0x2001 && (second <= 0x1ff || second === 0xdb8)) && first !== 0x2002 && first !== 0x3fff;
36
+ }
37
+ async function pinnedFetch(url, address, headers, signal) {
38
+ return new Promise((resolve, reject) => {
39
+ const req = request(url, {
40
+ hostname: address, servername: url.hostname.replace(/^\[|\]$/g, ''),
41
+ headers: { ...headers, Host: url.host }, agent: false, signal,
42
+ }, res => {
43
+ try {
44
+ const headers = new Headers();
45
+ for (const [key, value] of Object.entries(res.headers)) {
46
+ if (value !== undefined)
47
+ headers.set(key, Array.isArray(value) ? value.join(', ') : value);
48
+ }
49
+ const status = res.statusCode ?? 500;
50
+ if ([204, 205, 304].includes(status)) {
51
+ res.destroy();
52
+ resolve(new Response(null, { status, headers }));
53
+ }
54
+ else
55
+ resolve(new Response(Readable.toWeb(res), { status, headers }));
56
+ }
57
+ catch (error) {
58
+ res.destroy();
59
+ reject(error);
60
+ }
61
+ });
62
+ req.on('error', reject);
63
+ req.end();
64
+ });
65
+ }
66
+ /** Security failures are distinguished from transport failures for share-link guidance. */
67
+ export class UnsafeUrlError extends Error {
68
+ }
69
+ export async function validatePublicUrl(url, signal, options = {}) {
70
+ if (url.protocol !== 'https:' || url.username || url.password)
71
+ throw new UnsafeUrlError();
72
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
73
+ const resolution = isIP(hostname) ? Promise.resolve([{ address: hostname, family: isIP(hostname) }])
74
+ : (options.resolve ?? (host => lookup(host, { all: true, verbatim: true })))(hostname);
75
+ const addresses = await new Promise((resolve, reject) => {
76
+ const abort = () => reject(new Error('timeout'));
77
+ signal.addEventListener('abort', abort, { once: true });
78
+ resolution.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
79
+ if (signal.aborted)
80
+ abort();
81
+ });
82
+ if (!addresses.length || addresses.some(item => !isPublicAddress(item.address)))
83
+ throw new UnsafeUrlError();
84
+ signal.throwIfAborted();
85
+ return addresses[0].address;
86
+ }
87
+ export async function requestPublicUrl(url, headers, signal, options = {}) {
88
+ const address = await validatePublicUrl(url, signal, options);
89
+ return options.fetch
90
+ ? options.fetch(url.href, { method: 'GET', headers, redirect: 'manual', signal })
91
+ : pinnedFetch(url, address, headers, signal);
92
+ }
93
+ /** Every redirect is checked before opening a socket; DNS answers cannot be rebound. */
94
+ export async function downloadFile(input, destination, limit, allowedHeaders = {}, options = {}) {
95
+ const controller = new AbortController();
96
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 300_000);
97
+ const signal = controller.signal;
98
+ const part = `${destination}.part`;
99
+ let file;
100
+ let body = null;
101
+ try {
102
+ let url = new URL(input);
103
+ const headers = {};
104
+ if (allowedHeaders.referer)
105
+ headers.Referer = allowedHeaders.referer;
106
+ if (allowedHeaders.user_agent)
107
+ headers['User-Agent'] = allowedHeaders.user_agent;
108
+ for (let redirects = 0;; redirects++) {
109
+ const res = await requestPublicUrl(url, headers, signal, options);
110
+ body = res.body;
111
+ if ([301, 302, 303, 307, 308].includes(res.status)) {
112
+ await body?.cancel();
113
+ body = null;
114
+ if (redirects >= 5 || !res.headers.get('location'))
115
+ throw new Error();
116
+ url = new URL(res.headers.get('location'), url);
117
+ continue;
118
+ }
119
+ if (!res.ok || !body)
120
+ throw new Error();
121
+ const length = res.headers.get('content-length');
122
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > limit))
123
+ throw new Error();
124
+ file = await open(part, 'wx');
125
+ let bytes = 0;
126
+ for await (const chunk of body) {
127
+ bytes += chunk.byteLength;
128
+ if (bytes > limit) {
129
+ controller.abort();
130
+ throw new Error();
131
+ }
132
+ signal.throwIfAborted();
133
+ await file.writeFile(chunk);
134
+ }
135
+ signal.throwIfAborted();
136
+ await file.close();
137
+ file = undefined;
138
+ await rename(part, destination);
139
+ return;
140
+ }
141
+ }
142
+ catch {
143
+ controller.abort();
144
+ await body?.cancel().catch(() => undefined);
145
+ await file?.close().catch(() => undefined);
146
+ await rm(part, { force: true });
147
+ throw new AcquireError('download_failed');
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ }
152
+ }
@@ -0,0 +1,8 @@
1
+ export class AcquireError extends Error {
2
+ code;
3
+ constructor(code, message = code) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = 'AcquireError';
7
+ }
8
+ }
@@ -0,0 +1,67 @@
1
+ import { AcquireError } from './errors.js';
2
+ import { requestPublicUrl, validatePublicUrl, UnsafeUrlError } from './download.js';
3
+ export { AcquireError } from './errors.js';
4
+ export const PLATFORM_DOMAINS = {
5
+ douyin: ['douyin.com', 'iesdouyin.com'],
6
+ xiaohongshu: ['xiaohongshu.com', 'xhslink.com'],
7
+ bilibili: ['bilibili.com', 'b23.tv'],
8
+ tiktok: ['tiktok.com'],
9
+ instagram: ['instagram.com', 'instagr.am'],
10
+ x: ['x.com', 'twitter.com', 't.co'],
11
+ };
12
+ export function extractShareUrl(text) {
13
+ const raw = text.match(/https?:\/\/[^\s<>]+/i)?.[0]?.replace(/[,。!?、;:”’)】》,.;:!?)>\]}\x27"`]+$/u, '');
14
+ try {
15
+ if (!raw)
16
+ throw new Error();
17
+ const url = new URL(raw);
18
+ const host = url.hostname.toLowerCase();
19
+ if (url.username || url.password || !Object.values(PLATFORM_DOMAINS).some(domains => domains.some(domain => host === domain || host.endsWith(`.${domain}`))))
20
+ throw new Error();
21
+ return url.href;
22
+ }
23
+ catch {
24
+ throw new AcquireError('unsupported_platform');
25
+ }
26
+ }
27
+ export const SHORT_LINK_DOMAINS = ['v.douyin.com', 'xhslink.com', 'b23.tv', 'vm.tiktok.com', 'vt.tiktok.com', 't.co'];
28
+ const FULL_POST_DOMAINS = ['douyin.com', 'iesdouyin.com', 'xiaohongshu.com', 'bilibili.com', 'tiktok.com', 'instagram.com', 'instagr.am', 'x.com', 'twitter.com'];
29
+ const isTikTokShort = (url) => (url.hostname === 'tiktok.com' || url.hostname.endsWith('.tiktok.com')) && /^\/t\/[^/]+/.test(url.pathname);
30
+ const isShort = (url) => SHORT_LINK_DOMAINS.some(host => url.hostname === host) || isTikTokShort(url);
31
+ const isFullPost = (url) => !isShort(url) && FULL_POST_DOMAINS.some(host => url.hostname === host || url.hostname.endsWith(`.${host}`));
32
+ /** Follow only allowlisted short links locally. Never consume a response body. */
33
+ export async function expandShareUrl(input, options = {}) {
34
+ let url = new URL(input);
35
+ if (!isShort(url)) {
36
+ if (!isFullPost(url))
37
+ throw new AcquireError('unsupported_platform');
38
+ return url.href;
39
+ }
40
+ const signal = AbortSignal.timeout(options.timeoutMs ?? 15_000);
41
+ try {
42
+ for (let hops = 0;; hops++) {
43
+ // Share text often uses http on short domains only. Full post URLs stay unchanged.
44
+ if (isShort(url) && url.protocol === 'http:')
45
+ url.protocol = 'https:';
46
+ if (url.protocol !== 'https:' || url.username || url.password || (!isShort(url) && !isFullPost(url)))
47
+ throw new UnsafeUrlError();
48
+ if (!isShort(url)) {
49
+ await validatePublicUrl(url, signal, options);
50
+ return url.href;
51
+ }
52
+ if (hops >= 3)
53
+ throw new Error('redirect_limit');
54
+ const res = await requestPublicUrl(url, {}, signal, options);
55
+ const location = res.headers.get('location');
56
+ await res.body?.cancel();
57
+ if (![301, 302, 303, 307, 308].includes(res.status) || !location)
58
+ throw new Error('missing_redirect');
59
+ url = new URL(location, url);
60
+ }
61
+ }
62
+ catch (error) {
63
+ if (error instanceof UnsafeUrlError)
64
+ throw new AcquireError('unsupported_platform');
65
+ throw new AcquireError('share_link_unresolved', 'share_link_unresolved:请复制完整链接');
66
+ }
67
+ }
@@ -0,0 +1,98 @@
1
+ import { mkdir, readdir, writeFile, rename, rm, stat } from 'node:fs/promises';
2
+ import { resolve, join, extname } from 'node:path';
3
+ import { socialPostSchema } from '../contract/cloud-v1.js';
4
+ import { sha256File } from '../core/index.js';
5
+ import { runExec } from '../timeline/ffmpeg.js';
6
+ import { probe } from '../timeline/probe.js';
7
+ import { downloadFile, IMAGE_LIMIT, VIDEO_LIMIT } from './download.js';
8
+ import { extractShareUrl, expandShareUrl, AcquireError } from './share.js';
9
+ function imageExtension(url) {
10
+ const ext = extname(new URL(url).pathname).toLowerCase();
11
+ return ['.jpg', '.jpeg', '.png', '.webp', '.avif', '.gif'].includes(ext) ? ext : '.jpg';
12
+ }
13
+ // Only the explicit metadata allowlist reaches disk; remote media URLs and headers never do.
14
+ export async function fetchSocialPost(gateway, input, options = {}) {
15
+ const extractedUrl = extractShareUrl(input.text);
16
+ const directory = resolve(input.directory);
17
+ await mkdir(directory, { recursive: true });
18
+ if ((await readdir(directory)).length)
19
+ throw new AcquireError('directory_not_empty');
20
+ if (!gateway.resolveSocial)
21
+ throw new AcquireError('upstream_unavailable');
22
+ const shareUrl = await expandShareUrl(extractedUrl, options);
23
+ const post = socialPostSchema.parse(await gateway.resolveSocial(shareUrl));
24
+ const result = {
25
+ platform: post.platform, post_id: post.post_id, canonical_url: post.canonical_url,
26
+ kind: post.kind, title: post.title, text: post.text, hashtags: post.hashtags,
27
+ author: post.author, published_at: post.published_at,
28
+ video: null, images: [], cover: null, manifest: join(directory, 'post.json'), warnings: [], markdown: '',
29
+ };
30
+ const image = async (remote, name) => {
31
+ const path = join(directory, `${name}${imageExtension(remote.url)}`);
32
+ await downloadFile(remote.url, path, IMAGE_LIMIT, post.download_headers, options);
33
+ return { path, sha256: await sha256File(path), width: remote.width, height: remote.height };
34
+ };
35
+ if (input.download !== false) {
36
+ if (post.kind === 'video') {
37
+ const path = join(directory, 'video.mp4');
38
+ const parts = [join(directory, 'video-stream.mp4'), join(directory, 'audio-stream.m4a')];
39
+ const merged = `${path}.part`;
40
+ try {
41
+ const video = post.video;
42
+ if (video.streams.length === 1) {
43
+ await downloadFile(video.streams[0].url, path, VIDEO_LIMIT, post.download_headers, options);
44
+ }
45
+ else {
46
+ let remaining = VIDEO_LIMIT;
47
+ for (const [i, type] of ['video', 'audio'].entries()) {
48
+ await downloadFile(video.streams.find(s => s.type === type).url, parts[i], remaining, post.download_headers, options);
49
+ remaining -= (await stat(parts[i])).size;
50
+ }
51
+ await runExec('ffmpeg', ['-v', 'error', '-nostdin', '-y', '-i', parts[0], '-i', parts[1], '-map', '0:v:0', '-map', '1:a:0', '-c', 'copy', '-f', 'mp4', merged]);
52
+ if ((await stat(merged)).size > VIDEO_LIMIT)
53
+ throw new AcquireError('download_failed');
54
+ await rename(merged, path);
55
+ }
56
+ const actual = await probe(path);
57
+ const timing = JSON.parse(await runExec('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=duration:format=duration', '-of', 'json', path]));
58
+ const duration = Number(timing.streams?.[0]?.duration ?? timing.format?.duration);
59
+ if (!Number.isFinite(duration) || duration < 0)
60
+ throw new AcquireError('download_failed');
61
+ result.video = { path, sha256: await sha256File(path), duration_seconds: duration,
62
+ width: actual.width, height: actual.height, watermark_free: video.watermark_free };
63
+ }
64
+ catch {
65
+ await rm(path, { force: true });
66
+ throw new AcquireError('download_failed');
67
+ }
68
+ finally {
69
+ await Promise.all([...parts, merged].map(p => rm(p, { force: true })));
70
+ }
71
+ }
72
+ else {
73
+ for (const [index, remote] of post.images.entries()) {
74
+ try {
75
+ result.images.push(await image(remote, `image-${String(index + 1).padStart(2, '0')}`));
76
+ }
77
+ catch {
78
+ result.warnings.push(`image_download_failed:${index + 1}`);
79
+ }
80
+ }
81
+ if (!result.images.length)
82
+ throw new AcquireError('download_failed');
83
+ }
84
+ if (post.cover) {
85
+ try {
86
+ result.cover = await image(post.cover, 'cover');
87
+ }
88
+ catch {
89
+ result.warnings.push('cover_download_failed');
90
+ }
91
+ }
92
+ }
93
+ const files = [result.video?.path, ...result.images.map(i => i.path), result.cover?.path, result.manifest].filter(Boolean);
94
+ result.markdown = `平台:${result.platform}\n\n标题:${result.title}\n\n${result.text.slice(0, 500)}\n\n话题:${result.hashtags.map(t => `#${t}`).join(' ')}\n\n文件:\n${files.map(p => `- ${p}`).join('\n')}\n\n${post.kind === 'video' ? '可直接调用 analyze_reference 分析切点并生成任务草案' : '请用户选择需要作为商品/模特的素材后调用 import_assets'}`;
95
+ await writeFile(`${result.manifest}.part`, JSON.stringify(result, null, 2), { flag: 'wx' });
96
+ await rename(`${result.manifest}.part`, result.manifest);
97
+ return result;
98
+ }
@@ -0,0 +1,95 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, stat } from "node:fs/promises";
3
+ import { dirname, extname, resolve } from "node:path";
4
+ import { sha256File } from "../core/index.js";
5
+ import { runExec } from "../timeline/ffmpeg.js";
6
+ import { probe } from "../timeline/probe.js";
7
+ export async function trimMedia(input) {
8
+ const { path, start_seconds, end_seconds, output } = input;
9
+ if (!Number.isFinite(start_seconds) || start_seconds < 0) {
10
+ throw new Error("start_seconds 必须大于等于 0");
11
+ }
12
+ if (!Number.isFinite(end_seconds) || !(end_seconds > start_seconds)) {
13
+ throw new Error("end_seconds 必须大于 start_seconds");
14
+ }
15
+ if (extname(output).toLowerCase() !== ".mp4") {
16
+ throw new Error("output 扩展名必须为 .mp4");
17
+ }
18
+ await refuseExisting(output);
19
+ const source = await probe(path);
20
+ const sourceDuration = source.frames * source.fps.den / source.fps.num;
21
+ if (end_seconds > sourceDuration + 1e-3) {
22
+ throw new Error(`end_seconds 超过源视频时长 ${sourceDuration}`);
23
+ }
24
+ await mkdir(dirname(output), { recursive: true });
25
+ const temp = `${output}.${randomUUID()}.part.mp4`;
26
+ let committed = false;
27
+ try {
28
+ // -ss sits after -i so ffmpeg decodes up to the cut instead of keyframe seeking.
29
+ const args = [
30
+ "-nostdin",
31
+ "-v",
32
+ "error",
33
+ "-y",
34
+ "-i",
35
+ path,
36
+ "-ss",
37
+ String(start_seconds),
38
+ "-t",
39
+ String(end_seconds - start_seconds),
40
+ "-map",
41
+ "0:v:0",
42
+ "-c:v",
43
+ "libx264",
44
+ "-pix_fmt",
45
+ "yuv420p",
46
+ ];
47
+ if (source.has_audio) {
48
+ args.push("-map", "0:a", "-c:a", "aac");
49
+ }
50
+ else {
51
+ args.push("-an");
52
+ }
53
+ args.push("-movflags", "+faststart", temp);
54
+ await runExec("ffmpeg", args);
55
+ await rename(temp, output);
56
+ committed = true;
57
+ }
58
+ finally {
59
+ if (!committed) {
60
+ await rm(temp, { force: true });
61
+ }
62
+ }
63
+ const probed = await probe(output);
64
+ const duration_seconds = probed.frames * probed.fps.den / probed.fps.num;
65
+ const sha256 = await sha256File(output);
66
+ const resolved = resolve(output);
67
+ const markdown = [
68
+ "已截取视频片段。",
69
+ "",
70
+ `- 路径:${resolved}`,
71
+ `- sha256:${sha256}`,
72
+ `- 时长(秒):${duration_seconds}`,
73
+ `- 帧数:${probed.frames}`,
74
+ `- 音轨:${probed.has_audio ? "保留" : "无"}`,
75
+ ].join("\n");
76
+ return {
77
+ path: resolved,
78
+ sha256,
79
+ duration_seconds,
80
+ frames: probed.frames,
81
+ markdown,
82
+ };
83
+ }
84
+ async function refuseExisting(path) {
85
+ try {
86
+ await stat(path);
87
+ }
88
+ catch (error) {
89
+ if (error.code === "ENOENT") {
90
+ return;
91
+ }
92
+ throw error;
93
+ }
94
+ throw new Error(`拒绝覆盖已存在的输出文件:${path}`);
95
+ }
@@ -0,0 +1,29 @@
1
+ import { lstat, mkdir, realpath } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { isSafeId } from "../core/schema.js";
4
+ export function safeId(id) {
5
+ if (!isSafeId(id))
6
+ throw new Error("id must be a single safe path segment");
7
+ }
8
+ /** Like JobStore, static containment checks do not close a later replacement race. */
9
+ export async function child(root, ...parts) {
10
+ let path = await realpath(root);
11
+ for (const part of parts) {
12
+ safeId(part);
13
+ path = join(path, part);
14
+ try {
15
+ if ((await lstat(path)).isSymbolicLink())
16
+ throw new Error("symlink is not allowed");
17
+ }
18
+ catch (error) {
19
+ if (error.code !== "ENOENT")
20
+ throw error;
21
+ }
22
+ }
23
+ return path;
24
+ }
25
+ export async function directory(root, ...parts) {
26
+ const path = await child(root, ...parts);
27
+ await mkdir(path, { recursive: true });
28
+ return path;
29
+ }