@dawnwood/cli 0.3.0 → 0.5.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/README.md CHANGED
@@ -1,40 +1,54 @@
1
1
  # @dawnwood/cli — Dawnwood for agents
2
2
 
3
- CLI + MCP server,让本地 Agent(Claude Code / Cursor / Codex)直连 dawnwood
4
- harness 跑全管线:圣经 → 剧本链 → 设定包 → 美术/渲染。人工审核走 console
5
- 深链(`get_review_url`)。
3
+ A CLI and MCP server that lets your local agent (Claude Code, Cursor, Codex) drive
4
+ the full [Dawnwood](https://dawnwood.ai) short-drama pipeline: series bible →
5
+ episode scripts → asset pack → art and renders. Visual review and approvals stay
6
+ with you in the console — the agent hands you a deep link (`get_review_url`).
6
7
 
7
- 设计与裁决台账:`docs/designs/agent-access-mcp-cli-2026-08.md`。
8
-
9
- ## 快速开始
8
+ ## Quick start
10
9
 
11
10
  ```bash
12
- # 1. console(Settings → API tokens)铸一枚 PAT(只显示一次,默认 90 天)
13
- # 2. 登录(token 落 ~/.config/dawnwood/config.json,0600)
11
+ # 1. Mint a personal access token in the console
12
+ # (avatar menu → API tokens; shown only once, valid 90 days by default)
13
+
14
+ # 2. Sign in (the token is saved to ~/.config/dawnwood/config.json, mode 0600)
14
15
  npx @dawnwood/cli auth login --token dw_pat_v1_...
15
16
 
16
- # 3a. 挂进 Claude Code
17
+ # 3a. Add it to Claude Code
17
18
  claude mcp add dawnwood -- npx -y @dawnwood/cli mcp
18
19
 
19
- # 3b. 或直接用 CLI 验身份
20
+ # 3b. Or check your identity from the CLI
20
21
  npx @dawnwood/cli whoami
21
22
  ```
22
23
 
23
- ## 工具面(v1,冻结于 test/mcp.test.ts)
24
-
25
- /runs PORTAL 族 1:1 + `credits_balance` + `get_review_url`。交付包/发布是
26
- 二期(评审 D8);轮询纪律:`get_run`/`art_status`,间隔 ≥10s,`list_runs`
27
- 禁止轮询(D7)。
28
-
29
- ## 环境变量
30
-
31
- - `DAWNWOOD_TOKEN` — 覆盖本地配置的 token(CI 用)
32
- - `DAWNWOOD_API_BASE` — 默认 `https://console.dawnwood.ai/api`
33
- - `DAWNWOOD_AGENT` — 遥测归因名(`x-tfund-agent` 头)
34
- - `DAWNWOOD_CONFIG_DIR` — 配置目录(默认 `~/.config/dawnwood`)
35
-
36
- ## 发布
37
-
38
- `git tag cli-v<version> && git push origin cli-v<version>` →
39
- `.github/workflows/npm-publish.yml`(需 NPM_TOKEN secret;tag 与
40
- package.json 版本一致性有闸)。
24
+ ## Tools
25
+
26
+ | Stage | Tools |
27
+ |---|---|
28
+ | Runs | `list_runs`, `get_run`, `create_run`, `delete_run` |
29
+ | Bible | `generate_bible`, `get_bible`, `update_bible`, `sync_bible`, `approve_bible` |
30
+ | Scripts | `generate_scripts`, `get_script`, `update_script`, `approve_script` |
31
+ | Asset pack | `generate_pack`, `update_pack`, `commit_pack` |
32
+ | Art and render | `art_estimate`, `generate_art`, `art_status`, `upload_character_ref` |
33
+ | Covers | `covers_estimate`, `generate_covers`, `regen_cover`, `set_cover_theme` |
34
+ | Storyboard tools | `flashback_montage`, `reclone_voice`, `likeness_reroll`, `import_clip`, `job_status` |
35
+ | Sign-off and delivery | `signoff_episode`, `build_delivery_pack` |
36
+ | Account | `credits_balance`, `get_review_url` |
37
+ | Clips | `upload_video`, `clips_create`, `clips_get_job`, `clips_edit_clip`, `clips_send_to_matrix`, `clips_list_jobs`, `clips_series_episodes`, `clips_retry` |
38
+ | Matrix (posting) | `matrix_status`, `matrix_accounts`, `matrix_update_account`, `matrix_lanes`, `matrix_update_lane`, `matrix_media`, `matrix_add_media`, `matrix_plan_posts`, `matrix_schedule_posts`, `matrix_posts`, `matrix_cancel_post`, `matrix_comments`, `matrix_report` |
39
+
40
+ Poll with `get_run`, `art_status` or `job_status`, no more than every 10 seconds.
41
+ `list_runs` is for browsing, not polling. Approvals are gate actions: give the
42
+ user `get_review_url` first. Spending actions are billed in credits to the
43
+ account that owns the token.
44
+
45
+ ## Environment variables
46
+
47
+ - `DAWNWOOD_TOKEN` — overrides the saved token (useful in CI)
48
+ - `DAWNWOOD_API_BASE` — defaults to `https://console.dawnwood.ai/api`
49
+ - `DAWNWOOD_AGENT` — agent name reported for usage attribution
50
+ - `DAWNWOOD_CONFIG_DIR` — config directory (default `~/.config/dawnwood`)
51
+
52
+ ## Support
53
+
54
+ Questions and issues: [dawnwood.ai/docs](https://dawnwood.ai/docs).
package/dist/api.js CHANGED
@@ -22,13 +22,13 @@ function explain(status, body) {
22
22
  const err = typeof body?.error === "string" ? body.error : JSON.stringify(body);
23
23
  switch (status) {
24
24
  case 401:
25
- return `${err} — token 无效/过期/已撤销。到 console 头像菜单 → API tokens 重铸一枚,然后 \`dawnwood auth login --token <新token>\`。`;
25
+ return `${err} — the token is invalid, expired or revoked. Mint a new one in the console (avatar menu → API tokens), then run \`dawnwood auth login --token <new token>\`.`;
26
26
  case 402:
27
- return `${err} — credits 不足。到 ${getApiBase().replace(/\/api$/, "")}/#billing 充值或升级订阅后重试。`;
27
+ return `${err} — not enough credits. Top up or upgrade at ${getApiBase().replace(/\/api$/, "")}/#billing, then retry.`;
28
28
  case 403:
29
- return `${err} — 这个 token 的权限面不含该操作(customer PAT 只有自助面;交付/发布是二期)。`;
29
+ return `${err} — this token is not allowed to perform this action (customer tokens only cover the self-serve surface).`;
30
30
  case 503:
31
- return `${err} — 服务端暂时无法校验 token(fail-closed),稍等重试即可,token 本身没坏。`;
31
+ return `${err} — the server can't verify tokens right now (fail-closed); retry shortly — your token is fine.`;
32
32
  default:
33
33
  return err;
34
34
  }
@@ -36,7 +36,7 @@ function explain(status, body) {
36
36
  export async function apiCall(path, opts = {}) {
37
37
  const token = opts.token ?? getToken();
38
38
  if (!token) {
39
- throw new ApiError(0, "未登录 — 先跑 `dawnwood auth login --token <dw_pat_v1_...>`(token 在 console 头像菜单 → API tokens 铸)。", null);
39
+ throw new ApiError(0, "Not signed in — run `dawnwood auth login --token <dw_pat_v1_...>` first (mint a token in the console: avatar menu → API tokens).", null);
40
40
  }
41
41
  const base = opts.base ?? getApiBase();
42
42
  const f = opts.fetchImpl ?? fetch;
package/dist/index.js CHANGED
@@ -28,33 +28,33 @@ async function main() {
28
28
  const i = rest.indexOf("--token");
29
29
  const token = i >= 0 ? rest[i + 1] : undefined;
30
30
  if (!token) {
31
- die("用法: dawnwood auth login --token <dw_pat_v1_...>\n" +
32
- "token 在 console(头像菜单 → API tokens)铸造,只显示一次。");
31
+ die("Usage: dawnwood auth login --token <dw_pat_v1_...>\n" +
32
+ "Mint a token in the console (avatar menu → API tokens); it is shown only once.");
33
33
  }
34
34
  if (!token.startsWith("dw_pat_v1_")) {
35
- die("这不像一枚 dawnwood PAT(应以 dw_pat_v1_ 开头)。");
35
+ die("That doesn't look like a dawnwood token (it should start with dw_pat_v1_).");
36
36
  }
37
37
  // 铸造响应里的占位/截断很常见 —— 落盘前先用一次只读调用验真伪。
38
38
  try {
39
39
  const me = (await apiCall("/me", { token, tool: "auth_login" }));
40
40
  const p = saveConfig({ ...loadConfig(), token });
41
- out(`已登录 ${me.email ?? "?"}(token ${maskToken(token)})→ ${p}(0600)`);
41
+ out(`Signed in as ${me.email ?? "?"} (token ${maskToken(token)}) → ${p} (0600)`);
42
42
  }
43
43
  catch (e) {
44
- die(`token 验证失败:${e instanceof Error ? e.message : e}`);
44
+ die(`Token check failed: ${e instanceof Error ? e.message : e}`);
45
45
  }
46
46
  return;
47
47
  }
48
48
  if (cmd === "auth" && sub === "status") {
49
49
  const t = getToken();
50
- out(t ? `已登录(token ${maskToken(t)},api ${getApiBase()})` : "未登录");
50
+ out(t ? `Signed in (token ${maskToken(t)}, api ${getApiBase()})` : "Not signed in");
51
51
  return;
52
52
  }
53
53
  if (cmd === "auth" && sub === "logout") {
54
54
  const cfg = loadConfig();
55
55
  delete cfg.token;
56
56
  saveConfig(cfg);
57
- out("已退出(本地 token 已删;要彻底作废去 console 撤销那枚 token)。");
57
+ out("Signed out (local token deleted; revoke the token in the console to invalidate it completely).");
58
58
  return;
59
59
  }
60
60
  if (cmd === "whoami") {
@@ -64,15 +64,15 @@ async function main() {
64
64
  }
65
65
  out(`dawnwood — agent access CLI
66
66
 
67
- 用法:
68
- dawnwood auth login --token <dw_pat_v1_...> 登录(token 在 console 头像菜单 → API tokens 铸)
69
- dawnwood auth status 查看登录状态
70
- dawnwood auth logout 退出(本地删 token)
71
- dawnwood whoami 验 token / 看身份与权限
72
- dawnwood mcp 启动 stdio MCP server(给 Claude Code / Cursor 等)
67
+ Usage:
68
+ dawnwood auth login --token <dw_pat_v1_...> sign in (mint a token in the console: avatar menu → API tokens)
69
+ dawnwood auth status show sign-in status
70
+ dawnwood auth logout sign out (deletes the local token)
71
+ dawnwood whoami check the token / show identity and permissions
72
+ dawnwood mcp start the stdio MCP server (for Claude Code, Cursor, etc.)
73
73
 
74
- MCP 接入(Claude Code):
74
+ Connect to Claude Code:
75
75
  claude mcp add dawnwood -- npx -y @dawnwood/cli mcp
76
- 环境变量:DAWNWOOD_TOKEN / DAWNWOOD_API_BASE / DAWNWOOD_AGENT 可覆盖本地配置。`);
76
+ Environment: DAWNWOOD_TOKEN / DAWNWOOD_API_BASE / DAWNWOOD_AGENT override the local config.`);
77
77
  }
78
78
  main().catch((e) => die(e instanceof Error ? e.message : String(e)));
package/dist/mcp.js CHANGED
@@ -13,6 +13,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
13
13
  import { z } from "zod";
14
14
  import { apiCall } from "./api.js";
15
15
  import { CONSOLE_BASE_DEFAULT, getApiBase } from "./config.js";
16
+ import { registerOpsTools } from "./ops.js";
16
17
  const AGENT = process.env.DAWNWOOD_AGENT || "mcp";
17
18
  function consoleBase() {
18
19
  return process.env.DAWNWOOD_CONSOLE_BASE ||
@@ -34,114 +35,127 @@ async function call(path, tool, method, body) {
34
35
  }
35
36
  }
36
37
  export function buildServer() {
37
- const server = new McpServer({ name: "dawnwood", version: "0.3.0" });
38
+ const server = new McpServer({ name: "dawnwood", version: "0.5.0" });
38
39
  // ---- runs 生命周期 ---------------------------------------------------------
39
- server.tool("list_runs", "列出你的 runs(草稿与进行中)。浏览用——**禁止用它轮询状态**,查单个 run 用 get_run。", async () => call("/runs", "list_runs"));
40
- server.tool("get_run", "读单个 run 的完整状态(向导步骤/圣经/剧本/pack/art 进度)。这是轮询状态的正确工具(O(1) 直取);轮询间隔 ≥10 秒。", { run_id: z.string().describe("run id(snake_case)") }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}`, "get_run"));
41
- server.tool("create_run", "创建一个新剧 run(向导 Step 1:brief)。premise 100-6000 字符;titles 必须含 primary_locale 一项;必须显式 compliance_ack=true(无真人肖像/无第三方 IP)。集数默认 10(改集数是运营特权)。", {
42
- run_id: z.string().describe("snake_case ascii id,全局唯一"),
43
- titles: z.record(z.string(), z.string()).describe('各语言标题,如 {"en": "..."}'),
40
+ server.tool("list_runs", "List your runs (drafts and in progress). For browsing only — **never poll status with it**; use get_run for a single run.", async () => call("/runs", "list_runs"));
41
+ server.tool("get_run", "Read one run's full state (wizard step, bible, scripts, pack, art progress). This is the right tool for polling (O(1) lookup); poll at most every 10 seconds (10s).", { run_id: z.string().describe("run id (snake_case)") }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}`, "get_run"));
42
+ server.tool("create_run", "Create a new series run (wizard step 1: brief). premise is 100–6000 characters; titles must include the primary_locale; compliance_ack=true is required (no real-person likeness, no third-party IP). Episode count defaults to 10 (changing it is an operator privilege).", {
43
+ run_id: z.string().describe("snake_case ASCII id, globally unique"),
44
+ titles: z.record(z.string(), z.string()).describe('title per locale, e.g. {"en": "..."}'),
44
45
  primary_locale: z.string().default("en"),
45
- premise: z.string().describe("剧情前提,100-6000 字符"),
46
- lang: z.string().default("en").describe("产出语言(BCP-47)"),
46
+ premise: z.string().describe("story premise, 100–6000 characters"),
47
+ lang: z.string().default("en").describe("output language (BCP-47)"),
47
48
  render_style: z.enum(["real", "comic"]).default("real"),
48
- compliance_ack: z.boolean().describe("确认无真人肖像/无第三方 IP,必须 true"),
49
+ compliance_ack: z.boolean().describe("confirms no real-person likeness and no third-party IP; must be true"),
49
50
  episodes: z.number().int().optional()
50
- .describe("集数(运营特权:服务端要求 OPS 权限且限 6-120;不填 = 10)"),
51
+ .describe("episode count (operator privilege: the server requires OPS permission and 6–120; omit = 10)"),
52
+ lead_actor_id: z.string().optional()
53
+ .describe("optional: id of a reusable actor (your roster or the shared library) who must play the lead"),
54
+ lead_name: z.string().optional().describe("optional: the lead's name, used to match the role"),
55
+ parent: z.object({
56
+ wid: z.string().describe("id of one of your existing shows"),
57
+ inherit: z.object({
58
+ world: z.boolean().optional(), scenes: z.boolean().optional(), props: z.boolean().optional(),
59
+ characters: z.array(z.string()).optional().describe("character ids that return (same face, voice, looks)"),
60
+ }).optional(),
61
+ exclude_note: z.string().optional().describe("what must NOT carry over"),
62
+ }).optional().describe("optional: make a spinoff in the same universe as one of your shows"),
51
63
  }, async (a) => call("/runs", "create_run", "POST", {
52
64
  id: a.run_id, titles: a.titles, primary_locale: a.primary_locale,
53
65
  premise: a.premise, lang: a.lang, render_style: a.render_style,
54
66
  compliance_ack: a.compliance_ack,
55
67
  ...(a.episodes != null ? { episodes: a.episodes } : {}),
68
+ ...(a.parent ? { parent: a.parent } : {}),
69
+ ...(a.lead_actor_id ? { cast_pins: [{ actor_id: a.lead_actor_id, ...(a.lead_name ? { name: a.lead_name } : {}) }] } : {}),
56
70
  }));
57
- server.tool("delete_run", "放弃一个向导草稿 run(不可逆;只能删自助 run)。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}`, "delete_run", "DELETE"));
71
+ server.tool("delete_run", "Discard a draft run (irreversible; self-serve runs only).", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}`, "delete_run", "DELETE"));
58
72
  // ---- 圣经(Step 2) ---------------------------------------------------------
59
- server.tool("generate_bible", "生成剧集圣经(世界观/人物/弧线/情绪框架/中点/逐集 beat)。异步倾向的长操作,完成后用 get_bible 读。可带 feedback 重生成。圣经字段:emotion_frame(revenge|sweet_healing|angst|benevolence|career|light_mystery|family_ethics 之一,含四段弧)、midpoint(ally_flip|hidden_truth|major_failure,落在全季 40-60%)、reveal_ladder、beats[]{hook_0_5s,turn,cliffhanger,payoff_next(下集必须先兑现的爽点),phase(1-4 单调不降)}。", { run_id: z.string(), feedback: z.string().optional().describe("对上一版的修改意见") }, async ({ run_id, feedback }) => call(`/runs/${encodeURIComponent(run_id)}/bible/generate`, "generate_bible", "POST", feedback ? { feedback } : {}));
60
- server.tool("get_bible", "读当前圣经(含版本轨)。返回里的 stale_eps = 这些集的 beat 落后于现行剧本(以 get_script 为准,别信 beat);pending_deltas = 回流判出的圣经级改动(新世界规则/cast/ladder),等人确认,勿自动写。content.writing_rules = 本剧写法约束(谁何时可被怀疑/披露时间表/颜色口径/禁句),改剧本前必读、当硬约束。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/bible`, "get_bible"));
61
- server.tool("sync_bible", "按现行剧本重出圣经 beat(后台异步)。给 ep 只回流一集;不给 = 整季从 EP1 串行回填。正常不必调:每次剧本写版本都自动回流;get_bible 报了 stale_eps 又急用时才手动。", { run_id: z.string(), ep: z.string().optional().describe("集号,如 '5';不填 = 整季") }, async ({ run_id, ep }) => call(`/runs/${encodeURIComponent(run_id)}/bible/sync`, "sync_bible", "POST", ep ? { ep: String(parseInt(ep, 10)) } : {}));
62
- server.tool("update_bible", "直接改写圣经内容(整体 PUT;细粒度改动优先走 generate_bible 的 feedback)。校验:emotion_frame.type/midpoint.type 必须取自固定枚举,midpoint.ep 落在 40-60% 区间,beats[].phase 1-4 且跨集不降;writing_rules 可选,≤12 条字符串(本剧写法约束,通用写法规则系统自带不用写)。", { run_id: z.string(), bible: z.record(z.string(), z.unknown()).describe("圣经 JSON 全量") }, async ({ run_id, bible }) => call(`/runs/${encodeURIComponent(run_id)}/bible`, "update_bible", "PUT", bible));
63
- server.tool("approve_bible", "批准圣经,解锁剧本链。批准是闸门动作——建议先用 get_review_url 让人在 console 里过目。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/bible/approve`, "approve_bible", "POST"));
73
+ server.tool("generate_bible", "Generate the series bible (world, characters, arcs, emotion frame, midpoint, per-episode beats). A long operation; read the result with get_bible. Pass feedback to regenerate. Bible fields: emotion_frame (one of revenge|sweet_healing|angst|benevolence|career|light_mystery|family_ethics, with a four-part arc), midpoint (ally_flip|hidden_truth|major_failure, placed at 40–60% of the season), reveal_ladder, beats[]{hook_0_5s, turn, cliffhanger, payoff_next (the payoff the next episode must deliver first), phase (1–4, never decreasing)}.", { run_id: z.string(), feedback: z.string().optional().describe("notes on the previous version") }, async ({ run_id, feedback }) => call(`/runs/${encodeURIComponent(run_id)}/bible/generate`, "generate_bible", "POST", feedback ? { feedback } : {}));
74
+ server.tool("get_bible", "Read the current bible (with version history). stale_eps = episodes whose beats lag behind the current scripts (trust get_script, not the beat); pending_deltas = bible-level changes detected from script edits (new world rules / cast / reveal ladder) awaiting human confirmation — never write them automatically. content.writing_rules = this series' writing constraints (who may be suspected when, disclosure schedule, colour conventions, banned lines): read them before editing a script and treat them as hard constraints.", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/bible`, "get_bible"));
75
+ server.tool("sync_bible", "Rebuild the bible's beats from the current scripts (async, in the background). With ep, only that episode; without, the whole season from EP1. Normally unnecessary — every script version syncs back automatically; call it only when get_bible reports stale_eps and you need them now.", { run_id: z.string(), ep: z.string().optional().describe("episode number, e.g. '5'; omit = whole season") }, async ({ run_id, ep }) => call(`/runs/${encodeURIComponent(run_id)}/bible/sync`, "sync_bible", "POST", ep ? { ep: String(parseInt(ep, 10)) } : {}));
76
+ server.tool("update_bible", "Overwrite the bible content (full PUT; prefer generate_bible feedback for small changes). Validation: emotion_frame.type / midpoint.type must come from the fixed enums, midpoint.ep must sit at 40–60% of the season, beats[].phase 1–4 and never decreasing across episodes; writing_rules optional, ≤12 strings (series-specific constraints — the general craft rules are built in).", { run_id: z.string(), bible: z.record(z.string(), z.unknown()).describe("the full bible JSON") }, async ({ run_id, bible }) => call(`/runs/${encodeURIComponent(run_id)}/bible`, "update_bible", "PUT", bible));
77
+ server.tool("approve_bible", "Approve the bible and unlock the script chain. A gate action — hand the user get_review_url to look it over in the console first.", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/bible/approve`, "approve_bible", "POST"));
64
78
  // ---- 剧本链(Step 3) -------------------------------------------------------
65
- server.tool("generate_scripts", "跑剧本链(逐集生成,带前情摘要)。长操作;进度用 get_run 轮询(≥10s)。" +
66
- "缺省**续跑**:已 ready/已批准的集跳过 —— 链被杀/卡死后重调是安全的。" +
67
- "force=true 才全量重生成(如 bible 反馈后整链重写;会把每集顶成新 LLM 版)。", { run_id: z.string(), force: z.boolean().optional().describe("全量重生成(慎用)") }, async ({ run_id, force }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/generate`, "generate_scripts", "POST", force ? { force: true } : {}));
68
- server.tool("get_script", "读某一集剧本。ep 形如 '0001'。响应带 render_lock:{locked, reason} —— locked=true 时这一集不能起草/渲染:" +
69
- "reason=proposal_pending 是有一份改写提案等用户确认(Apply/Reject),reason=unapproved 是新版本还没批准。" +
70
- "遇到 locked 必须原话告诉用户去 console 的 Script 页处理(或经用户明确同意后调 approve_script),不要绕开。", { run_id: z.string(), ep: z.string().describe("集号,如 0001") }, async ({ run_id, ep }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/${encodeURIComponent(ep)}`, "get_script"));
71
- server.tool("update_script", "改写某一集剧本(PUT;approve 后的改动会计费,approve 前的 feedback 重生免费)。写入后圣经该集 beat 自动回流。" +
72
- "**写入即清掉批准**:响应 render_lock.locked=true,该集在用户重新批准前不能起草/渲染 —— 必须提醒用户去批准(或得到明确同意后调 approve_script)。改已有剧本前先读前后两集(get_script),保留用户没点名要改的 beat/道具/人物;用户要你「核查」某集是否支持一个前提时,先原文引用说明成不成立,不许补台词让前提成立。", { run_id: z.string(), ep: z.string(), body: z.record(z.string(), z.unknown()) }, async ({ run_id, ep, body }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/${encodeURIComponent(ep)}`, "update_script", "PUT", body));
73
- server.tool("approve_script", "批准某一集剧本(闸门动作;建议先 get_review_url 人工过目)。", { run_id: z.string(), ep: z.string() }, async ({ run_id, ep }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/${encodeURIComponent(ep)}/approve`, "approve_script", "POST"));
79
+ server.tool("generate_scripts", "Run the script chain (episode by episode, each with a recap of what came before). Long operation; poll progress with get_run (≥10s). " +
80
+ "By default it **resumes**: episodes already ready or approved are skipped, so re-calling after a killed or stuck chain is safe. " +
81
+ "force=true regenerates everything (e.g. rewriting the whole chain after bible feedback; every episode becomes a new version).", { run_id: z.string(), force: z.boolean().optional().describe("regenerate every episode (use with care)") }, async ({ run_id, force }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/generate`, "generate_scripts", "POST", force ? { force: true } : {}));
82
+ server.tool("get_script", "Read one episode's script. ep looks like '0001'. The response carries render_lock: {locked, reason} — while locked=true the episode cannot be storyboarded or rendered: " +
83
+ "reason=proposal_pending means a rewrite proposal is waiting for the user (Apply/Reject); reason=unapproved means the new version has not been approved yet. " +
84
+ "When locked, tell the user plainly to resolve it on the console's Script page (or call approve_script only with their explicit consent); never work around it.", { run_id: z.string(), ep: z.string().describe("episode number, e.g. 0001") }, async ({ run_id, ep }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/${encodeURIComponent(ep)}`, "get_script"));
85
+ server.tool("update_script", "Rewrite one episode's script (PUT; edits after approval are billed, feedback regenerations before approval are free). The bible's beat for that episode syncs back automatically. " +
86
+ "**Writing clears the approval**: the response has render_lock.locked=true and the episode cannot be storyboarded or rendered until the user re-approves — remind them to approve (or call approve_script only with explicit consent). Before editing an existing script, read the episodes before and after it (get_script) and keep every beat, prop and character the user did not ask to change. When the user asks you to CHECK whether an episode supports a premise, quote the text and say whether it holds — never add lines to make it true.", { run_id: z.string(), ep: z.string(), body: z.record(z.string(), z.unknown()) }, async ({ run_id, ep, body }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/${encodeURIComponent(ep)}`, "update_script", "PUT", body));
87
+ server.tool("approve_script", "Approve one episode's script (a gate action; hand the user get_review_url to look it over first).", { run_id: z.string(), ep: z.string() }, async ({ run_id, ep }) => call(`/runs/${encodeURIComponent(run_id)}/scripts/${encodeURIComponent(ep)}/approve`, "approve_script", "POST"));
74
88
  // ---- 设定包(Step 4) -------------------------------------------------------
75
- server.tool("generate_pack", "生成设定包草稿(角色/场景/道具的视觉设定)。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/pack/generate`, "generate_pack", "POST"));
76
- server.tool("update_pack", "改设定包草稿(PUT 全量)。", { run_id: z.string(), pack: z.record(z.string(), z.unknown()) }, async ({ run_id, pack }) => call(`/runs/${encodeURIComponent(run_id)}/pack`, "update_pack", "PUT", pack));
77
- server.tool("commit_pack", "锁定设定包,进入美术/渲染阶段(闸门动作)。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/pack/commit`, "commit_pack", "POST"));
89
+ server.tool("generate_pack", "Generate the asset-pack draft (visual design of characters, scenes and props).", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/pack/generate`, "generate_pack", "POST"));
90
+ server.tool("update_pack", "Edit the asset-pack draft (full PUT).", { run_id: z.string(), pack: z.record(z.string(), z.unknown()) }, async ({ run_id, pack }) => call(`/runs/${encodeURIComponent(run_id)}/pack`, "update_pack", "PUT", pack));
91
+ server.tool("commit_pack", "Lock the asset pack and move on to art/rendering (a gate action).", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/pack/commit`, "commit_pack", "POST"));
78
92
  // ---- 美术/渲染(Step 5) ----------------------------------------------------
79
- server.tool("art_estimate", "美术/渲染的 credits 报价(动手前先看账)。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/art/estimate`, "art_estimate"));
80
- server.tool("generate_art", "启动美术/渲染(烧 credits 的一步;先跑 art_estimate 确认)。进度用 art_status 轮询(≥10s)。" +
81
- "409 code=script_proposal_pending / script_unapproved = 某集剧本等用户确认(提案未 Apply/Reject 或新版本未批准):转述原因让用户去 Script 页处理,不要重试。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/art/generate`, "generate_art", "POST"));
82
- server.tool("art_status", "美术/渲染进度(单 run 直取,轮询用这个,间隔 ≥10 秒)。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/art/status`, "art_status"));
83
- server.tool("covers_estimate", "渲前生成式剧集封面的报量:哪些集还缺封面 + credits 价 + 闸门 blockers(需全剧本" +
84
- "批准 + 立绘锚齐)。调 generate_covers **之前**先读这个,把张数/价钱告知用户确认。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/covers/estimate`, "covers_estimate"));
85
- server.tool("generate_covers", "批量生成缺封面的集(剧本 → 封面场景+钩子 → 脸锁 9:16 出图 → 按封面主题 typeset)。" +
86
- "异步批;进度在 covers_estimate / get_run 的 covers 字段(轮询 ≥10s)。幂等:已有" +
87
- "封面的集跳过;之后成片抽帧/手修的封面会自然覆盖生成版(发布取最新)。", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/covers/generate`, "generate_covers", "POST", {}));
88
- server.tool("set_cover_theme", "设置本剧的封面主题(同频道多剧混排时,个人页网格靠它一眼分剧)。全部字段可选:" +
89
- "accent/text/dim 为 #RRGGBB(缺省金/白/暗白),wordmark 为烧在每张封面上的系列字标" +
90
- "(≤24 字符,如 'BOUGHT BRIDE'),ep_badge 为章行格式串(可用 {n}/{title})。" +
91
- "省略的字段保持缺省;校验在服务端。", {
92
- run_id: z.string().describe("run/work id(snake_case)"),
93
- accent: z.string().optional().describe("#RRGGBB 主色(书名/分隔线/字标)"),
94
- text: z.string().optional().describe("#RRGGBB 正文色(钩子)"),
95
- dim: z.string().optional().describe("#RRGGBB 次级色(章行)"),
96
- wordmark: z.string().optional().describe("系列字标,≤24 字符"),
97
- ep_badge: z.string().optional().describe("章行格式串,如 'EP {n}'"),
93
+ server.tool("art_estimate", "Credits quote for art/rendering (check it before starting).", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/art/estimate`, "art_estimate"));
94
+ server.tool("generate_art", "Start art/rendering (this step spends credits; run art_estimate first). Poll progress with art_status (≥10s). " +
95
+ "409 with code=script_proposal_pending / script_unapproved = an episode's script is waiting on the user (a proposal not applied/rejected, or a new version not approved): relay the reason and send them to the Script page; do not retry.", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/art/generate`, "generate_art", "POST"));
96
+ server.tool("art_status", "Art/rendering progress (single-run lookup — use this to poll, at most every 10 seconds).", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/art/status`, "art_status"));
97
+ server.tool("covers_estimate", "Quote for generated episode covers before rendering: which episodes still lack a cover, the credits price, and gate blockers " +
98
+ "(all scripts approved + character anchors ready). Read this **before** generate_covers and confirm the count and price with the user.", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/covers/estimate`, "covers_estimate"));
99
+ server.tool("generate_covers", "Generate covers for every episode that lacks one (script → cover scene + hook → face-locked 9:16 image → typeset in the cover theme). " +
100
+ "Async batch; progress in covers_estimate / the covers field of get_run (poll ≥10s). Idempotent: episodes with a cover are skipped; " +
101
+ "covers later taken from the finished footage or fixed by hand naturally replace the generated one (publishing uses the newest).", { run_id: z.string() }, async ({ run_id }) => call(`/runs/${encodeURIComponent(run_id)}/covers/generate`, "generate_covers", "POST", {}));
102
+ server.tool("set_cover_theme", "Set this series' cover theme (when several series share a channel, the profile grid tells them apart by it). All fields optional: " +
103
+ "accent/text/dim are #RRGGBB (defaults gold/white/dim white), wordmark is the series wordmark burned onto every cover " +
104
+ "(≤24 characters, e.g. 'BOUGHT BRIDE'), ep_badge is the episode-line format string ({n}/{title} available). " +
105
+ "Omitted fields keep their defaults; validated on the server.", {
106
+ run_id: z.string().describe("run/work id (snake_case)"),
107
+ accent: z.string().optional().describe("#RRGGBB accent colour (title / divider / wordmark)"),
108
+ text: z.string().optional().describe("#RRGGBB body colour (hook)"),
109
+ dim: z.string().optional().describe("#RRGGBB secondary colour (episode line)"),
110
+ wordmark: z.string().optional().describe("series wordmark, ≤24 characters"),
111
+ ep_badge: z.string().optional().describe("episode-line format string, e.g. 'EP {n}'"),
98
112
  }, async ({ run_id, ...t }) => call(`/works/${encodeURIComponent(run_id)}`, "set_cover_theme", "PUT", { cover_theme: Object.fromEntries(Object.entries(t).filter(([, v]) => v != null)) }));
99
- server.tool("import_clip", "从前作成片剪一段进本剧(直接复用或闪回):source_asset_id 为源作品的视频资产" +
100
- "(segment_cut/母带),按 [start_ms, end_ms] 剪出落为本剧 archival_clip 资产(带出处)。" +
101
- "treatment='flashback' 提取期烧死往事感滤镜。可选 splice={chapter, seg_id, position} " +
102
- "剪好即插进该 segment 的拼接序(不渲染)。异步——轮询返回 asset_id 的 import_status。" +
103
- "staff-only(服务端把门);跨账户旧母带需运维先拷进本桶。", {
104
- run_id: z.string().describe("目标 run/work id"),
105
- source_work_id: z.string().describe("源作品 id(出处校验)"),
106
- source_asset_id: z.string().describe("源视频资产 id"),
107
- start_ms: z.number().int().describe("起点毫秒"),
108
- end_ms: z.number().int().describe("终点毫秒(≤起点+120000)"),
113
+ server.tool("import_clip", "Cut a clip from an earlier finished work into this series (straight reuse or a flashback): source_asset_id is the source work's video asset " +
114
+ "(segment cut / master); [start_ms, end_ms] is cut out and stored as this series' archival_clip asset (with provenance). " +
115
+ "treatment='flashback' burns in a memory grade at extraction. Optional splice={chapter, seg_id, position} " +
116
+ "inserts it straight into that segment's stitch order (no render). Async — poll import_status on the returned asset_id. " +
117
+ "Staff-only (enforced on the server).", {
118
+ run_id: z.string().describe("target run/work id"),
119
+ source_work_id: z.string().describe("source work id (provenance check)"),
120
+ source_asset_id: z.string().describe("source video asset id"),
121
+ start_ms: z.number().int().describe("start, milliseconds"),
122
+ end_ms: z.number().int().describe("end, milliseconds (≤ start + 120000)"),
109
123
  treatment: z.enum(["none", "flashback"]).optional(),
110
- note: z.string().optional().describe("备注(如「EP7 退婚戏」)"),
124
+ note: z.string().optional().describe("note, e.g. 'EP7 broken engagement'"),
111
125
  splice: z.object({ chapter: z.number().int(), seg_id: z.string(),
112
126
  position: z.number().int().optional() }).optional()
113
- .describe("剪好即插组:目标章/段/1-based 组位(缺省段尾)"),
127
+ .describe("insert as a group right away: target chapter / segment / 1-based group slot (default: end of segment)"),
114
128
  }, async ({ run_id, ...body }) => call(`/works/${encodeURIComponent(run_id)}/clips/import`, "import_clip", "POST", body));
115
129
  // ---- EP21 感情戏兑现沉淀(TQ 2026-09-25):回忆蒙太奇 / 片中声线重克隆 / KYC 撞脸重抽 ------------
116
- server.tool("flashback_montage", "用观众**看过的**前几集成片拼回忆(分镜指南 B24):每段 3–6 个短切片,统一往事调色、原声静音(默片)," +
117
- "每片配一句 ≤16 词的内心旁白(说话人自己的克隆声线),拼成一个 archival 组插进目标段(position 1-based,缺省段尾)," +
118
- "带字幕拍,段自动重拼。绝不重渲往事——新渲的过去对不上老脸老造型。clips 的 seg_no/group_no 是**源集**的 1-based 序号;" +
119
- "单片 ≤12s、合计 ≤30s。旁白声线不像本人先调 reclone_voice。异步——返回 job_id,用 job_status 轮询(≥10 秒)。", {
130
+ server.tool("flashback_montage", "Build a flashback from footage the viewer has ALREADY SEEN in earlier episodes: 3–6 short slices, one memory grade, original audio muted (silent footage), " +
131
+ "one inner V.O. line of ≤16 words per slice in the speaker's own cloned voice, assembled into one archival group inside the target segment (position 1-based, default the end) " +
132
+ "with subtitle beats; the segment restitches automatically. Never re-render the past — new renders never match the old faces and costumes. clips' seg_no/group_no are the SOURCE episode's 1-based numbers; " +
133
+ "each slice ≤12s, ≤30s total. If the V.O. doesn't sound like the character, run reclone_voice first. Async — returns job_id; poll job_status (≥10s).", {
120
134
  run_id: z.string(),
121
- episode: z.number().int().describe("插入回忆的集"),
122
- seg_id: z.string().describe("插入的段 id"),
135
+ episode: z.number().int().describe("episode that receives the flashback"),
136
+ seg_id: z.string().describe("segment id it goes into"),
123
137
  clips: z.array(z.object({
124
138
  ep: z.number().int(), seg_no: z.number().int(), group_no: z.number().int(),
125
139
  t0: z.number(), t1: z.number(), vo: z.string().optional(),
126
140
  })).min(1).max(8),
127
- speaker: z.string().optional().describe("这段回忆是谁的(角色名或 id);有 vo 时必填"),
141
+ speaker: z.string().optional().describe("whose memory it is (character name or id); required when any clip has vo"),
128
142
  position: z.number().int().optional(),
129
- silent: z.boolean().optional().describe("默认 true:原声静音只留旁白"),
143
+ silent: z.boolean().optional().describe("default true: mute the original audio, keep only the V.O."),
130
144
  }, async ({ run_id, episode, seg_id, ...body }) => call(`/works/${encodeURIComponent(run_id)}/chapters/${episode}/storyboard/segments/${encodeURIComponent(seg_id)}/flashback`, "flashback_montage", "POST", body));
131
- server.tool("reclone_voice", "用角色在某集成片里的**真实表演**重克隆声线(写回默认声线):各段人声分离→只留这个角色的台词→即时克隆。" +
132
- "旁白/新台词听着不像片里的他/她时用;选他/她台词多的已拼好集。干净语音 <4s 或原声线是共享库声线时保留原声线。" +
133
- "按 voice_recast 计费。异步——job_id → job_status。", { character_id: z.string(), run_id: z.string().optional(), episode: z.number().int() }, async ({ character_id, run_id, episode }) => call(`/characters/${encodeURIComponent(character_id)}/voice/reclone`, "reclone_voice", "POST", { chapter: episode, ...(run_id ? { work_id: run_id } : {}) }));
134
- server.tool("likeness_reroll", "某组被引擎按「像真人」连拒(改过镜头仍拒)时,给惹审核的那位演员临时开 KYC 资产库(参考图以可信素材送审)并重渲该组;" +
135
- "组出片后自动删库。character 缺省=本集撞脸组里出现最多的那位。仅内部账户的剧(服务端把门,客户剧 403——改机位/加动作)。", { run_id: z.string(), episode: z.number().int(), seg_id: z.string(), group_id: z.string(),
145
+ server.tool("reclone_voice", "Re-clone a character's voice from their own performance in a finished episode (written back as their default voice): vocals are separated per segment, only this character's lines are kept, then instantly cloned. " +
146
+ "Use it when a V.O. or new line doesn't sound like them on screen; pick a finished episode where they talk a lot. With <4s of clean speech the current voice is kept. " +
147
+ "Costs one voice recast. Async — job_id → job_status.", { character_id: z.string(), run_id: z.string().optional(), episode: z.number().int() }, async ({ character_id, run_id, episode }) => call(`/characters/${encodeURIComponent(character_id)}/voice/reclone`, "reclone_voice", "POST", { chapter: episode, ...(run_id ? { work_id: run_id } : {}) }));
148
+ server.tool("likeness_reroll", "When the engine keeps rejecting a group as 'looks like a real person' (even after the shot was changed), temporarily register the flagged actor in the verified asset library (references sent as trusted assets) and re-render the group; " +
149
+ "the library is removed once the group renders. character defaults to whoever appears most in this episode's likeness-rejected groups. Internal shows only (enforced on the server; customer shows get 403 — change the angle or add motion instead).", { run_id: z.string(), episode: z.number().int(), seg_id: z.string(), group_id: z.string(),
136
150
  character: z.string().optional(), engine: z.string().optional() }, async ({ run_id, episode, seg_id, group_id, ...body }) => call(`/works/${encodeURIComponent(run_id)}/chapters/${episode}/storyboard/segments/${encodeURIComponent(seg_id)}` +
137
151
  `/groups/${encodeURIComponent(group_id)}/likeness-reroll`, "likeness_reroll", "POST", body));
138
- server.tool("job_status", "查异步任务(flashback_montage / reclone_voice 等返回的 job_id):status PENDING/RUNNING/DONE/FAILED + result/error。轮询间隔 ≥10 秒。", { job_id: z.string() }, async ({ job_id }) => call(`/jobs/${encodeURIComponent(job_id)}`, "job_status"));
139
- server.tool("upload_character_ref", "上传角色外部参考图(如 face-blend 脸模):登记 variant='ref' 资产并把本地文件传上去。" +
140
- "之后该角色的立绘锚生成会把最新参考图作为脸部参考(脸随参考图)。" +
141
- "char: subject 服务端限内部员工(staff-only)。", {
142
- character_id: z.string().describe("角色 id(snake_case)"),
143
- file_path: z.string().describe("本地图片路径(png/jpg/webp)"),
144
- note: z.string().optional().describe("备注(存 label_en,如来源/用途)"),
152
+ server.tool("job_status", "Check an async job (the job_id returned by flashback_montage, reclone_voice, etc.): status PENDING/RUNNING/DONE/FAILED plus result/error. Poll at most every 10 seconds.", { job_id: z.string() }, async ({ job_id }) => call(`/jobs/${encodeURIComponent(job_id)}`, "job_status"));
153
+ server.tool("upload_character_ref", "Upload an external reference image for a character (e.g. a face-blend face model): registers a variant='ref' asset and uploads the local file. " +
154
+ "From then on the character's anchor portraits use the newest reference as the face reference. " +
155
+ "Staff-only on the server.", {
156
+ character_id: z.string().describe("character id (snake_case)"),
157
+ file_path: z.string().describe("local image path (png/jpg/webp)"),
158
+ note: z.string().optional().describe("note (stored as label_en, e.g. source/purpose)"),
145
159
  }, async ({ character_id, file_path, note }) => {
146
160
  try {
147
161
  const { readFile } = await import("node:fs/promises");
@@ -169,20 +183,33 @@ export function buildServer() {
169
183
  }
170
184
  });
171
185
  // ---- 签收与交付(TQ 2026-08-31:Review 不自动绿,人签字才算) ----------------
172
- server.tool("signoff_episode", "签收一集(闸门动作:看过成片才签;发布与交付都以签收为前提)。响应带全剧进度" +
173
- "(signed/total/all_signed)——all_signed=true 时**问用户**是否生成整剧交付包," +
174
- "用户确认后再调 build_delivery_pack;不确认就停,绝不擅自打包。传 revoke=true 撤签。", { run_id: z.string(), episode: z.number().int(), revoke: z.boolean().optional() }, async ({ run_id, episode, revoke }) => call(`/works/${encodeURIComponent(run_id)}/chapters/${episode}/signoff`, "signoff_episode", "POST", revoke ? { revoke: true } : {}));
175
- server.tool("regen_cover", "重出**一集**封面(封面是签收时的默认产物,用户对那张不满意才调;强制重出,不看已有," +
176
- "新图发布时自动取最新一张;按价卡扣一张 art_reroll)。", { run_id: z.string(), episode: z.number().int() }, async ({ run_id, episode }) => call(`/works/${encodeURIComponent(run_id)}/chapters/${episode}/cover/regen`, "regen_cover", "POST", {}));
177
- server.tool("build_delivery_pack", "生成整剧交付包(母带/干净母版/SRT/封面,按章异步打包,分钟级)。只在用户明确" +
178
- "确认后调用——通常是 signoff_episode 返回 all_signed 后询问的下一步。", { run_id: z.string() }, async ({ run_id }) => call(`/works/${encodeURIComponent(run_id)}/delivery-package`, "build_delivery_pack", "POST", {}));
186
+ server.tool("signoff_episode", "Sign off one episode (a gate action: sign only after watching the finished episode; publishing and delivery both require sign-off). The response carries series progress " +
187
+ "(signed/total/all_signed) — when all_signed=true, **ask the user** whether to build the full delivery package, " +
188
+ "and call build_delivery_pack only after they confirm; otherwise stop, never package on your own. Pass revoke=true to withdraw a sign-off.", { run_id: z.string(), episode: z.number().int(), revoke: z.boolean().optional() }, async ({ run_id, episode, revoke }) => call(`/works/${encodeURIComponent(run_id)}/chapters/${episode}/signoff`, "signoff_episode", "POST", revoke ? { revoke: true } : {}));
189
+ server.tool("regen_cover", "Regenerate **one** episode's cover (a cover is produced by default at sign-off; call this only when the user dislikes it). Always regenerates; " +
190
+ "publishing picks the newest image automatically. Costs one art reroll.", { run_id: z.string(), episode: z.number().int() }, async ({ run_id, episode }) => call(`/works/${encodeURIComponent(run_id)}/chapters/${episode}/cover/regen`, "regen_cover", "POST", {}));
191
+ server.tool("build_delivery_pack", "Build the full-series delivery package (masters / clean masters / SRT / covers, packaged per episode asynchronously, takes minutes). Call only after the user " +
192
+ "explicitly confirms — usually the follow-up question after signoff_episode returns all_signed.", { run_id: z.string() }, async ({ run_id }) => call(`/works/${encodeURIComponent(run_id)}/delivery-package`, "build_delivery_pack", "POST", {}));
193
+ // ---- 整剧版本(2026-10-03 版本模型第一版)----------------------------------
194
+ // 版本 = 用已出镜头重排 / 重新分集 / 压缩 / 字卡 / 补拍出来的整剧剪辑;原版(v0)和旧版本永远不动,改 = 另存新版本。
195
+ server.tool("list_versions", "List this series' versions: v0 is the original episodes; v1, v2… are re-edits built from already-rendered footage. Each has notes (what changed and why), per-episode build status/duration and a timeline showing which original episode/group every piece comes from. Read before creating a new one.", { run_id: z.string() }, async ({ run_id }) => call(`/works/${encodeURIComponent(run_id)}/versions`, "list_versions"));
196
+ server.tool("version_inventory", "The parts list for a new version: every rendered group of the given episodes — ep, seg, gid, start/end inside the segment cut, position in the original episode, beats and spoken lines. eps like '1-5' or '1,3,901' (901+ are patch-shot episodes). Build version specs only from these ids.", { run_id: z.string(), eps: z.string().default("1-5") }, async ({ run_id, eps }) => call(`/works/${encodeURIComponent(run_id)}/versions/inventory?eps=${encodeURIComponent(eps)}`, "version_inventory"));
197
+ server.tool("create_version", "Create a NEW version from existing footage and queue its cloud build (free; minutes per episode). spec = {title, notes, episodes:[{title, hook, notes, items:[{kind:'clip', ep, gid, trim_head?, trim_tail?} | {kind:'clip', ep, seg, from, to} | {kind:'card', text, secs 0.5–6}]}], then_original_from? (continue with original episode N after these)}. Keep episodes 60–110 s, end each on a hook, keep continuity. The original and older versions are never changed.", { run_id: z.string(), spec: z.record(z.string(), z.unknown()), based_on: z.string().optional() }, async ({ run_id, spec, based_on }) => call(`/works/${encodeURIComponent(run_id)}/versions`, "create_version", "POST", { spec, based_on: based_on || "", build: true }));
198
+ server.tool("build_version", "Re-run the cloud build of a version (all episodes or eps:[n…]) — after a failed build, or once a patch shot it uses is ready. Poll with list_versions at most every 30 s.", { run_id: z.string(), version_id: z.string(), eps: z.array(z.number().int()).optional() }, async ({ run_id, version_id, eps }) => call(`/works/${encodeURIComponent(run_id)}/versions/${encodeURIComponent(version_id)}/build`, "build_version", "POST", { eps: eps || null }));
199
+ server.tool("patch_shot", "Shoot a NEW group a version needs but the footage lacks (a character entrance, a bridge, a key reaction). Renders in a hidden patch episode (901+) next to an anchor group of the original, inheriting its scene/outfits/staging — the original episode is not changed. shots = [{desc, blocking, dialogue?, cast[] (ids from version_inventory), duration ≤8}], ≤15 s total; for a shot with no dialogue add 'AUDIO: quiet room tone only — no music' to blocking. Costs render credits. When ready, reference it as {kind:'clip', ep:<patch_ep>, gid:<group_id>}.", {
200
+ run_id: z.string(), ep: z.number().int(), gid: z.string(),
201
+ position: z.enum(["after", "before"]).default("after"),
202
+ shots: z.array(z.record(z.string(), z.unknown())), note: z.string().optional(),
203
+ }, async (a) => call(`/works/${encodeURIComponent(a.run_id)}/versions/patch`, "patch_shot", "POST", { ep: a.ep, gid: a.gid, position: a.position, shots: a.shots, note: a.note || "" }));
179
204
  // ---- 账面 ------------------------------------------------------------------
180
- server.tool("credits_balance", "查 credits 余额与免费额度;附 usage.by_source(console vs 各 agent 名的扣费净额/笔数)与 usage.by_token(每枚 PAT),entries 逐笔带 source/token_id/tool。", async () => call("/credits", "credits_balance"));
205
+ server.tool("credits_balance", "Credits balance and free allowance, plus usage.by_source (net spend / count per console vs each agent name) and usage.by_token (per PAT); entries list each charge with source/token_id/tool.", async () => call("/credits", "credits_balance"));
181
206
  // ---- 人工审核动线(前提 5:console = 审核/裁决面) ---------------------------
182
- server.tool("get_review_url", "返回 console 深链,交给人类在浏览器里做视觉审核/裁决(选图、审片、批准)。不发任何 API 请求。在 approve_* 之前把这个链接给用户是推荐动线。", { run_id: z.string() }, async ({ run_id }) => ok({
207
+ server.tool("get_review_url", "Return a console deep link for a human to do the visual review and decisions in the browser (pick images, review footage, approve). Makes no API request. Giving the user this link before any approve_* is the recommended flow.", { run_id: z.string() }, async ({ run_id }) => ok({
183
208
  url: `${consoleBase()}/#run-wizard/${encodeURIComponent(run_id)}`,
184
- note: "在浏览器打开(需要 console 登录);agent 不应该也不能替人做视觉裁决。",
209
+ note: "Open it in a browser (console sign-in required); an agent should not and cannot make visual decisions on the user's behalf.",
185
210
  }));
211
+ // ---- Operations(Clips + Matrix,TQ 2026-10-11:本地 agent 也能做运营)----------------
212
+ registerOpsTools(server, call, ok, fail, AGENT);
186
213
  return server;
187
214
  }
188
215
  export async function runMcp() {
package/dist/ops.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Operations 面的 MCP 工具(TQ 2026-10-11:「Operation 这边也要有 API、Agent 和 MCP,这样本地 agent 能操作」)。
3
+ *
4
+ * Clips(切片任务)+ Matrix(号 / lane / 素材库 / 排期 / 读数)+ 本地视频上传。和 runs 那组一样是薄代理:
5
+ * 业务、校验、计费全在服务端(/v1/clips/*、/v1/matrix/*),这里只拼请求。
6
+ *
7
+ * 轮询纪律:clips_get_job 是查单个任务的正确工具,间隔 ≥10 秒;不要拿 list 类工具轮询。
8
+ */
9
+ import { readFileSync, statSync } from "node:fs";
10
+ import { basename, extname } from "node:path";
11
+ import { z } from "zod";
12
+ import { apiCall } from "./api.js";
13
+ const enc = encodeURIComponent;
14
+ const MAX_UPLOAD_BYTES = 1024 * 1024 * 1024;
15
+ function qs(params) {
16
+ const p = Object.entries(params).filter(([, v]) => v !== undefined && v !== "").map(([k, v]) => `${k}=${enc(String(v))}`);
17
+ return p.length ? `?${p.join("&")}` : "";
18
+ }
19
+ /** 本地 mp4/mov → POST /assets 拿预签名 → PUT 上传 → asset_id(给 clips_create 或 matrix_add_media 用)。 */
20
+ export async function uploadVideo(path, agent, fetchImpl = fetch) {
21
+ const ext = extname(path).toLowerCase();
22
+ const ct = ext === ".mp4" ? "video/mp4" : ext === ".mov" ? "video/quicktime" : "";
23
+ if (!ct)
24
+ throw new Error("only .mp4 or .mov files can be uploaded");
25
+ const size = statSync(path).size;
26
+ if (!size)
27
+ throw new Error("the file is empty");
28
+ if (size > MAX_UPLOAD_BYTES)
29
+ throw new Error(`the file is ${(size / 1e6).toFixed(0)} MB — the limit is 1 GB`);
30
+ const reg = await apiCall("/assets", { method: "POST", tool: "upload_video", agent, fetchImpl,
31
+ body: { type: "video", subject_ref: "tool:video", content_type: ct, label_en: basename(path) } });
32
+ if (!reg?.upload_url || !reg.asset_id)
33
+ throw new Error("the server did not return an upload URL");
34
+ const put = await fetchImpl(reg.upload_url, { method: "PUT", headers: { "content-type": ct }, body: readFileSync(path) });
35
+ if (!put.ok)
36
+ throw new Error(`upload failed (HTTP ${put.status}) — retry`);
37
+ return { asset_id: reg.asset_id, bytes: size, name: basename(path) };
38
+ }
39
+ export function registerOpsTools(server, call, ok, fail, agent) {
40
+ // ---- 上传 -----------------------------------------------------------------
41
+ server.tool("upload_video", "Upload a local .mp4/.mov (≤1 GB) to your workspace and return its asset_id. Use it as the source of clips_create ({kind:'upload', asset_id}) or register it in the Matrix library with matrix_add_media.", { path: z.string().describe("absolute path of a local video file") }, async ({ path }) => { try {
42
+ return ok(await uploadVideo(path, agent));
43
+ }
44
+ catch (e) {
45
+ return fail(e);
46
+ } });
47
+ // ---- Clips ----------------------------------------------------------------
48
+ server.tool("clips_list_jobs", "List your clip jobs (newest first, summary only) and the price: per_min cr per started source minute, min cr per job, max upload minutes.", async () => call("/v1/clips/jobs", "clips_list_jobs"));
49
+ server.tool("clips_series_episodes", "For a series you own: the finished episodes you can clip, with each episode's length in seconds (to estimate cost: 1 cr per started minute, 3 cr minimum).", { work_id: z.string() }, async ({ work_id }) => call(`/v1/clips/series/${enc(work_id)}`, "clips_series_episodes"));
50
+ server.tool("clips_create", "Start a clip job: vertical clips with pop captions and an end card, picked for conflict/reveal/hook moments, no spoilers. Source is either {kind:'series', work_id, chapters:[…≤12]} (your own Dawnwood series) or {kind:'upload', asset_id, name} (any video people talk in, ≤60 min; landscape becomes vertical). Charged once the source is ready: 1 cr per started source minute, 3 cr minimum; refunded in full if no clip comes out. Poll with clips_get_job every ≥10 s.", {
51
+ source: z.object({
52
+ kind: z.enum(["series", "upload"]),
53
+ work_id: z.string().optional(), chapters: z.array(z.number().int()).optional(),
54
+ asset_id: z.string().optional(), name: z.string().optional(),
55
+ }),
56
+ durations: z.array(z.tuple([z.number(), z.number()])).optional().describe("clip length range in seconds, e.g. [[20, 50]] (default)"),
57
+ captions: z.enum(["pop", "plain", "none"]).default("pop"),
58
+ end_card: z.object({
59
+ text: z.string().optional().describe("end card headline, default 'Watch the full series'"),
60
+ link: z.string().optional().describe("readable URL burned into the end card; empty = no end card"),
61
+ lane_id: z.string().optional().describe("Matrix lane the clips are meant for (default target of clips_send_to_matrix)"),
62
+ }).optional(),
63
+ }, async (a) => call("/v1/clips/jobs", "clips_create", "POST", a));
64
+ server.tool("clips_get_job", "One clip job with every clip: start/end (source seconds), title, opening hook line, why it was picked, score, spoiler flag, kept, status, and 1-hour playback URLs. The right tool for polling (every ≥10 s).", { job_id: z.string() }, async ({ job_id }) => call(`/v1/clips/jobs/${enc(job_id)}`, "clips_get_job"));
65
+ server.tool("clips_edit_clip", "Edit one clip: kept (keep or drop), title, captions ('pop'|'plain'|'none'), nudge_start / nudge_end (move the cut by whole lines, e.g. -1 or 1). Changing the cut or captions re-renders the clip for free.", {
66
+ job_id: z.string(), clip_id: z.string(),
67
+ kept: z.boolean().optional(), title: z.string().optional(),
68
+ captions: z.enum(["pop", "plain", "none"]).optional(),
69
+ nudge_start: z.number().int().optional(), nudge_end: z.number().int().optional(),
70
+ }, async ({ job_id, clip_id, ...body }) => call(`/v1/clips/jobs/${enc(job_id)}/clips/${enc(clip_id)}`, "clips_edit_clip", "PATCH", body));
71
+ server.tool("clips_retry", "Retry a failed clip job from where it stopped (a job that produced nothing was already refunded and is charged again on retry).", { job_id: z.string() }, async ({ job_id }) => call(`/v1/clips/jobs/${enc(job_id)}/retry`, "clips_retry", "POST", {}));
72
+ server.tool("clips_send_to_matrix", "Put every kept, finished clip of a job into the Matrix library (optionally under lane_id); sending twice does not duplicate. Then schedule them with matrix_plan_posts / matrix_schedule_posts.", { job_id: z.string(), lane_id: z.string().optional() }, async ({ job_id, lane_id }) => call(`/v1/clips/jobs/${enc(job_id)}/send`, "clips_send_to_matrix", "POST", lane_id ? { lane_id } : {}));
73
+ // ---- Matrix:号与 lane -----------------------------------------------------
74
+ server.tool("matrix_status", "Whether Matrix is enabled for your workspace, platforms, default caps and posting windows.", async () => call("/v1/matrix", "matrix_status"));
75
+ server.tool("matrix_accounts", "Your connected social accounts with their Matrix settings: key '<platform>:<account_id>', lane, group, stage (warming/testing/scaling/retired), paused, per-account permissions (publish/insights/comments) and Instagram token expiry.", async () => call("/v1/matrix/accounts", "matrix_accounts"));
76
+ server.tool("matrix_update_account", "Change one account's Matrix settings: lane_id, group_id, stage, paused (pausing stops its scheduled posts from going out and stops Autopilot from scheduling it).", {
77
+ key: z.string().describe("'<platform>:<account_id>' from matrix_accounts"),
78
+ lane_id: z.string().nullable().optional(), group_id: z.string().nullable().optional(),
79
+ stage: z.enum(["warming", "testing", "scaling", "retired"]).optional(), paused: z.boolean().optional(),
80
+ }, async ({ key, ...body }) => call(`/v1/matrix/accounts/${enc(key)}`, "matrix_update_account", "PATCH", body));
81
+ server.tool("matrix_lanes", "Your lanes (one niche + one tracked link + posting policy + Autopilot settings each).", async () => call("/v1/matrix/lanes", "matrix_lanes"));
82
+ server.tool("matrix_update_lane", "Edit a lane: name, link, lang, work_id, policy {daily_cap{platform:n}, windows['HH:MM'], tz, jitter_min, dedupe_days, caption_template, first_comment} (merged field by field), autopilot {on, show_link, slots{platform:'HH:MM'}, per_day}.", {
83
+ lane_id: z.string(),
84
+ name: z.string().optional(), link: z.string().optional(), lang: z.string().optional(), work_id: z.string().nullable().optional(),
85
+ policy: z.record(z.string(), z.unknown()).optional(), autopilot: z.record(z.string(), z.unknown()).optional(),
86
+ }, async ({ lane_id, ...body }) => call(`/v1/matrix/lanes/${enc(lane_id)}`, "matrix_update_lane", "PATCH", body));
87
+ // ---- Matrix:素材与排期 ----------------------------------------------------
88
+ server.tool("matrix_media", "Your Matrix library (uploads, imported episodes, clips sent from Clips), newest first.", async () => call("/v1/matrix/media", "matrix_media"));
89
+ server.tool("matrix_add_media", "Register a video in the Matrix library: {asset_id, title?, hook?, lane_id?} after upload_video, or {work_id, chapter} to import one of your own finished episodes.", {
90
+ asset_id: z.string().optional(), title: z.string().optional(), hook: z.string().optional(), lane_id: z.string().optional(),
91
+ work_id: z.string().optional(), chapter: z.number().int().optional(),
92
+ }, async (a) => call("/v1/matrix/media", "matrix_add_media", "POST", a));
93
+ const scheduleShape = {
94
+ items: z.array(z.object({
95
+ media_id: z.string(), account: z.string().optional().describe("'<platform>:<account_id>'"),
96
+ group: z.string().optional().describe("account group id instead of account: posts to every member"),
97
+ at: z.string().optional().describe("ISO UTC time; omitted = next free window"), caption: z.string().optional(),
98
+ })),
99
+ auto_resolve: z.boolean().default(true).describe("swap duplicate footage for an unused clip and move over-cap posts to the next free window"),
100
+ tiktok: z.object({
101
+ privacy_level: z.string(), disable_comment: z.boolean().optional(), disable_duet: z.boolean().optional(),
102
+ disable_stitch: z.boolean().optional(), consent: z.boolean().describe("the account owner agreed to TikTok's music/branded-content terms"),
103
+ }).optional().describe("required when any item posts to TikTok"),
104
+ };
105
+ server.tool("matrix_plan_posts", "Dry-run a batch of posts (nothing is saved): each item comes back ok / shifted / swapped / blocked with a reason, plus a summary and warnings (comment permission, token expiry, TikTok consent). Always plan before matrix_schedule_posts.", scheduleShape, async (a) => call("/v1/matrix/posts/plan", "matrix_plan_posts", "POST", a));
106
+ server.tool("matrix_schedule_posts", "Save a batch of posts (same body as matrix_plan_posts plus client_token for safe retries and skip_blocked). Fails with 409 and the plan when anything is blocked unless skip_blocked=true. Posts go out from the accounts themselves at their times.", { ...scheduleShape, client_token: z.string().describe("any unique string; replaying it never double-schedules"), skip_blocked: z.boolean().default(false) }, async (a) => call("/v1/matrix/posts", "matrix_schedule_posts", "POST", a));
107
+ server.tool("matrix_posts", "Your posts in a time window (ISO since/until), optionally filtered by status, lane or account. Includes posts scheduled by Autopilot and the publishing pipeline.", {
108
+ since: z.string().optional(), until: z.string().optional(),
109
+ status: z.string().optional(), lane: z.string().optional(), account: z.string().optional(),
110
+ }, async (a) => call(`/v1/matrix/posts${qs(a)}`, "matrix_posts"));
111
+ server.tool("matrix_cancel_post", "Cancel a post that hasn't started going out (a scheduled YouTube video is deleted). Already published posts must be removed on the platform.", { post_id: z.string() }, async ({ post_id }) => call(`/v1/matrix/posts/${enc(post_id)}`, "matrix_cancel_post", "DELETE"));
112
+ server.tool("matrix_comments", "Latest comments (≤25) on one published Facebook/Instagram post plus the first-comment status.", { post_id: z.string() }, async ({ post_id }) => call(`/v1/matrix/posts/${enc(post_id)}/comments`, "matrix_comments"));
113
+ // ---- Matrix:读数 ----------------------------------------------------------
114
+ server.tool("matrix_report", "Performance over the last `days` (default 7) vs the prior period: views, link taps, visits, purchases, revenue, per-account verdicts (scale/keep/kill/warming/check) against each account's own baseline and its lane, and the lane × platform grid.", { days: z.number().int().min(1).max(30).default(7) }, async ({ days }) => call(`/v1/matrix/report${qs({ days })}`, "matrix_report"));
115
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dawnwood/cli",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Dawnwood for agents — CLI + MCP server. Your agent drives the full short-drama pipeline (bible → scripts → pack → renders) against console.dawnwood.ai.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",