genflow-connect 0.0.0-stage → 0.1.2

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,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # genflow-connect
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
+ 내 AI 앱(Claude Code·Claude 데스크톱·Codex)이 GenFlow 스튜디오를 조종하게 해 주는 연결 도우미입니다.
4
+ 이 컴퓨터 안(127.0.0.1)에서만 동작하며, 영상과 글은 어디로도 보내지 않습니다.
5
+
6
+ ```
7
+ npx -y genflow-connect install # 설치된 AI 앱을 찾아 등록 (--dry-run, --target 지원)
8
+ npx -y genflow-connect status
9
+ ```
10
+
11
+ 등록 후 AI 앱을 껐다 켜고, GenFlow 스튜디오 탭을 연 상태에서 "GenFlow 편집기 상태 알려줘"라고 말해 보세요.
package/cli.mjs ADDED
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ // GenFlow 연결 도우미: 내 AI 앱(Claude Code·Claude Desktop·Codex)이 GenFlow 스튜디오를 조종하도록 한 번에 등록한다.
3
+ // 이 도구는 이 컴퓨터 안에서만 동작한다(127.0.0.1). 영상·글은 어디로도 보내지 않는다.
4
+ // npx genflow-connect install [--target claude-code|claude-desktop|codex|all] [--dry-run]
5
+ // npx genflow-connect status
6
+ // npx genflow-connect serve (AI 앱이 자동으로 실행한다 — 직접 실행할 필요 없음)
7
+ import { spawnSync } from "node:child_process";
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { homedir, platform } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ const HERE = dirname(fileURLToPath(import.meta.url));
14
+ const SERVER = join(HERE, "server.mjs");
15
+ const NAME = "genflow-editor";
16
+ // npx 임시 캐시는 정리될 수 있어서, 패키지로 실행 중이면 경로 대신 npx로 서버를 띄우게 등록한다(개발 중 저장소 실행은 파일 경로 그대로)
17
+ const viaPackage = /[\\/](_npx|node_modules)[\\/]/.test(HERE);
18
+ const win = platform() === "win32";
19
+ const SERVE = viaPackage
20
+ ? win
21
+ ? { command: "cmd", args: ["/c", "npx", "-y", "genflow-connect@0", "serve"] }
22
+ : { command: "npx", args: ["-y", "genflow-connect@0", "serve"] }
23
+ : { command: process.execPath, args: [SERVER] };
24
+ const args = process.argv.slice(2);
25
+ const cmd = args[0] && !args[0].startsWith("--") ? args[0] : "install";
26
+ const flag = (n) => args.includes(`--${n}`);
27
+ const opt = (n, d) => {
28
+ const i = args.indexOf(`--${n}`);
29
+ return i >= 0 && args[i + 1] ? args[i + 1] : d;
30
+ };
31
+ const dry = flag("dry-run");
32
+ const home = process.env.GENFLOW_HOME_OVERRIDE || homedir();
33
+
34
+ const has = (bin) => spawnSync(platform() === "win32" ? "where" : "which", [bin], { encoding: "utf8" }).status === 0;
35
+ const log = (...a) => console.log(...a);
36
+
37
+ function desktopConfigPath() {
38
+ if (platform() === "darwin") return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
39
+ if (platform() === "win32") return join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
40
+ return join(home, ".config", "Claude", "claude_desktop_config.json");
41
+ }
42
+
43
+ const targets = {
44
+ "claude-code": {
45
+ label: "Claude Code",
46
+ available: () => has("claude"),
47
+ install() {
48
+ const a = ["mcp", "add", NAME, "--scope", "user", "--", SERVE.command, ...SERVE.args];
49
+ if (dry) return log(` [미리보기] claude ${a.join(" ")}`);
50
+ spawnSync("claude", ["mcp", "remove", NAME, "--scope", "user"], { encoding: "utf8" }); // 다시 설치해도 "이미 있음" 오류가 나지 않게
51
+ const r = spawnSync("claude", a, { encoding: "utf8" });
52
+ if (r.status !== 0) throw new Error((r.stderr || r.stdout || "claude mcp add 실패").trim());
53
+ },
54
+ },
55
+ codex: {
56
+ label: "Codex",
57
+ available: () => has("codex"),
58
+ install() {
59
+ const a = ["mcp", "add", NAME, "--", SERVE.command, ...SERVE.args];
60
+ if (dry) return log(` [미리보기] codex ${a.join(" ")}`);
61
+ spawnSync("codex", ["mcp", "remove", NAME], { encoding: "utf8" });
62
+ const r = spawnSync("codex", a, { encoding: "utf8" });
63
+ if (r.status !== 0) throw new Error((r.stderr || r.stdout || "codex mcp add 실패").trim());
64
+ },
65
+ },
66
+ "claude-desktop": {
67
+ label: "Claude 데스크톱",
68
+ available: () => existsSync(dirname(desktopConfigPath())) || dry,
69
+ install() {
70
+ const file = desktopConfigPath();
71
+ let cfg = {};
72
+ if (existsSync(file)) {
73
+ try {
74
+ cfg = JSON.parse(readFileSync(file, "utf8"));
75
+ } catch {
76
+ throw new Error(`${file} 을(를) 읽을 수 없어요. 파일이 깨져 있으면 직접 고쳐 주세요`);
77
+ }
78
+ }
79
+ cfg.mcpServers = { ...(cfg.mcpServers ?? {}), [NAME]: { command: SERVE.command, args: SERVE.args } };
80
+ if (dry) return log(` [미리보기] ${file} 에 mcpServers.${NAME} 추가`);
81
+ mkdirSync(dirname(file), { recursive: true });
82
+ if (existsSync(file)) writeFileSync(`${file}.genflow-backup`, readFileSync(file));
83
+ writeFileSync(file, JSON.stringify(cfg, null, 2));
84
+ },
85
+ },
86
+ };
87
+
88
+ if (cmd === "serve") {
89
+ await import("./server.mjs");
90
+ } else if (cmd === "status") {
91
+ log("GenFlow 연결 도우미 상태");
92
+ for (const [k, t] of Object.entries(targets)) log(`- ${t.label}: ${t.available() ? "찾았어요" : "설치돼 있지 않아요"}`);
93
+ log(`연결 서버 파일: ${SERVER}`);
94
+ } else if (cmd === "install") {
95
+ const want = opt("target", "all");
96
+ const list = want === "all" ? Object.keys(targets) : [want];
97
+ if (list.some((k) => !targets[k])) {
98
+ console.error(`알 수 없는 대상: ${want} (claude-code | claude-desktop | codex | all)`);
99
+ process.exit(2);
100
+ }
101
+ let done = 0;
102
+ for (const k of list) {
103
+ const t = targets[k];
104
+ if (!t.available()) {
105
+ if (want !== "all") console.error(`✗ ${t.label}: 설치돼 있지 않아요`);
106
+ continue;
107
+ }
108
+ try {
109
+ t.install();
110
+ log(`✓ ${t.label}에 연결했어요${dry ? " (미리보기)" : ""}`);
111
+ done++;
112
+ } catch (e) {
113
+ console.error(`✗ ${t.label}: ${e.message}`);
114
+ }
115
+ }
116
+ if (!done) {
117
+ console.error("연결할 AI 앱을 찾지 못했어요. Claude Code, Claude 데스크톱, Codex 중 하나가 필요해요.");
118
+ process.exit(1);
119
+ }
120
+ log("\n다음 순서:\n1) AI 앱을 껐다 켜세요(이미 켜져 있었다면 새로 시작해야 연결 도구를 불러와요)\n2) GenFlow 스튜디오 탭을 열어 두세요\n3) AI 앱에서 \"GenFlow 편집기 상태 알려줘\"라고 말해 보세요");
121
+ } else {
122
+ console.error("사용법: genflow-connect install | status | serve");
123
+ process.exit(2);
124
+ }
@@ -0,0 +1,66 @@
1
+ // 허브(로컬 웹소켓)의 연결 허용 규칙. 규약 문서: entry-mockup/PROTOCOL.md §5.
2
+ // - 브라우저(에디터 탭)는 Origin 헤더로 확인한다. 브라우저는 Origin을 속일 수 없어서 임의 웹페이지의 접속이 막힌다.
3
+ // - Origin이 없는 연결(앱·익스텐션 밖의 로컬 프로그램, 롤콜 등)은 사용자 전용 파일의 토큰이 있어야 한다.
4
+ import { randomBytes, timingSafeEqual } from "node:crypto";
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ export const DEFAULT_ALLOWED_ORIGINS = [
10
+ "http://localhost:3200",
11
+ "http://127.0.0.1:3200",
12
+ "https://genflow.work",
13
+ "https://editor.genflow.work",
14
+ ];
15
+
16
+ /** 환경 변수 GENFLOW_ALLOWED_ORIGINS(쉼표 구분)로 허용 목록을 더할 수 있다. */
17
+ export function allowedOrigins(env = process.env) {
18
+ const extra = (env.GENFLOW_ALLOWED_ORIGINS ?? "")
19
+ .split(",")
20
+ .map((s) => s.trim())
21
+ .filter(Boolean);
22
+ return [...DEFAULT_ALLOWED_ORIGINS, ...extra];
23
+ }
24
+
25
+ /** 토큰 파일 경로(사용자 전용). */
26
+ export function tokenFilePath(home = homedir()) {
27
+ return join(home, ".genflow", "hub-token");
28
+ }
29
+
30
+ /** 토큰 파일이 없으면 만들고(권한 0600), 토큰을 돌려준다. 있으면 그대로 읽는다. */
31
+ export function ensureToken(home = homedir()) {
32
+ const file = tokenFilePath(home);
33
+ if (existsSync(file)) return readFileSync(file, "utf8").trim();
34
+ mkdirSync(join(home, ".genflow"), { recursive: true, mode: 0o700 });
35
+ const token = randomBytes(24).toString("hex");
36
+ writeFileSync(file, token + "\n", { mode: 0o600 });
37
+ try {
38
+ chmodSync(file, 0o600);
39
+ } catch {}
40
+ return token;
41
+ }
42
+
43
+ function sameToken(a, b) {
44
+ const x = Buffer.from(String(a ?? ""));
45
+ const y = Buffer.from(String(b ?? ""));
46
+ return x.length === y.length && x.length > 0 && timingSafeEqual(x, y);
47
+ }
48
+
49
+ /**
50
+ * 연결을 허용할지 결정한다.
51
+ * @param {{ origin?: string, url?: string }} req origin = 핸드셰이크 Origin 헤더, url = 요청 경로(쿼리 포함)
52
+ * @param {{ origins: string[], token: string }} cfg
53
+ * @returns {{ ok: boolean, reason?: string }}
54
+ */
55
+ export function checkConnection({ origin, url }, { origins, token }) {
56
+ if (origin) {
57
+ // 브라우저에서 온 연결: 허용 목록에 있는 출처만
58
+ return origins.includes(origin) ? { ok: true } : { ok: false, reason: `허용되지 않은 출처: ${origin}` };
59
+ }
60
+ // 브라우저가 아닌 로컬 프로그램: 토큰 필수
61
+ let given = null;
62
+ try {
63
+ given = new URL(url ?? "/", "ws://127.0.0.1").searchParams.get("token");
64
+ } catch {}
65
+ return sameToken(given, token) ? { ok: true } : { ok: false, reason: "토큰이 필요해요" };
66
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "genflow-connect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "description": "GenFlow 스튜디오를 내 AI 앱(Claude·Codex)에서 조종하게 해 주는 연결 도우미 (이 컴퓨터 안에서만 동작)",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "node --test hub-security.test.mjs relay.test.mjs"
8
+ },
9
+ "keywords": [],
10
+ "author": "",
11
+ "license": "UNLICENSED",
12
+ "type": "commonjs",
13
+ "dependencies": {
14
+ "@modelcontextprotocol/sdk": "^1.32.1",
15
+ "ws": "^8.22.0",
16
+ "zod": "^4.6.7"
17
+ },
18
+ "bin": {
19
+ "genflow-connect": "./cli.mjs"
20
+ },
21
+ "files": [
22
+ "README.md",
23
+ "cli.mjs",
24
+ "server.mjs",
25
+ "hub-security.mjs"
26
+ ],
27
+ "engines": {
28
+ "node": ">=18"
29
+ }
6
30
  }
package/server.mjs ADDED
@@ -0,0 +1,306 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { WebSocket, WebSocketServer } from "ws";
4
+ import { z } from "zod";
5
+ import { allowedOrigins, checkConnection, ensureToken } from "./hub-security.mjs";
6
+
7
+ // 에디터 탭(브라우저)이 접속하는 로컬 WebSocket. 127.0.0.1 전용.
8
+ // 3777이 다른 프로그램에 쓰이고 있으면 3778~3781로 넘어간다(에디터가 같은 순서로 찾는다)
9
+ const PORTS = (process.env.GENFLOW_HUB_PORTS || process.env.GENFLOW_HUB_PORT || "3777,3778,3779,3780,3781").split(",").map(Number);
10
+ let relay = null; // 이미 켜진 다른 GenFlow 허브가 있으면 거기에 붙어 명령만 중계한다
11
+ let editor = null;
12
+ // 접속을 전부 기억한다: 가장 최근 접속이 닫혀도(시험 접속·옛 탭 등) 아직 살아 있는 에디터 탭으로 이어지게 한다
13
+ const editors = new Set();
14
+ let seq = 0;
15
+ const pending = new Map();
16
+
17
+ // 연결 규칙(규약 §5): 브라우저는 허용된 Origin만, 그 외 로컬 프로그램은 ~/.genflow/hub-token 토큰 필요
18
+ const hubConfig = { origins: allowedOrigins(), token: ensureToken() };
19
+ const HELLO = JSON.stringify({ hello: "genflow-hub", v: 1 });
20
+
21
+ function attach(wss) {
22
+ wss.on("connection", (ws, req) => {
23
+ const verdict = checkConnection({ origin: req.headers.origin, url: req.url }, hubConfig);
24
+ if (!verdict.ok) {
25
+ console.error(`[hub] 연결 거부: ${verdict.reason}`);
26
+ ws.close(1008, "unauthorized");
27
+ return;
28
+ }
29
+ ws.send(HELLO); // 이 포트가 GenFlow 허브가 맞다는 표시(에디터·다른 서버가 포트를 고를 때 쓴다)
30
+ if (!req.headers.origin && new URL(req.url ?? "/", "ws://x").searchParams.get("role") === "mcp") {
31
+ // 다른 AI 앱이 띄운 서버: 명령을 받아 에디터 탭으로 전달하고 결과를 돌려준다
32
+ ws.on("message", async (raw) => {
33
+ const { id, method, params } = JSON.parse(raw.toString());
34
+ try {
35
+ ws.send(JSON.stringify({ id, result: await call(method, params, tooLong) }));
36
+ } catch (e) {
37
+ ws.send(JSON.stringify({ id, error: String(e.message) }));
38
+ }
39
+ });
40
+ return;
41
+ }
42
+ editors.add(ws);
43
+ editor = ws;
44
+ ws.on("message", (raw) => {
45
+ const msg = JSON.parse(raw.toString());
46
+ const p = pending.get(msg.id);
47
+ if (!p) return;
48
+ pending.delete(msg.id);
49
+ msg.error ? p.reject(new Error(msg.error)) : p.resolve(msg.result);
50
+ });
51
+ ws.on("close", () => {
52
+ editors.delete(ws);
53
+ if (editor === ws) editor = [...editors].filter((w) => w.readyState === 1).pop() ?? null;
54
+ });
55
+ });
56
+ }
57
+
58
+ const bindPort = (port) =>
59
+ new Promise((resolve, reject) => {
60
+ const wss = new WebSocketServer({ host: "127.0.0.1", port });
61
+ wss.once("listening", () => resolve(wss));
62
+ wss.once("error", reject);
63
+ });
64
+
65
+ // 포트가 이미 쓰이고 있을 때: GenFlow 허브(인사를 보냄)인지 확인하고, 맞으면 거기에 붙는다
66
+ const probeHub = (port) =>
67
+ new Promise((resolve) => {
68
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/?role=mcp&token=${encodeURIComponent(hubConfig.token)}`);
69
+ const fail = () => (clearTimeout(t), ws.terminate(), resolve(null));
70
+ const t = setTimeout(fail, 1500);
71
+ ws.on("error", fail);
72
+ ws.on("close", fail);
73
+ ws.on("message", (raw) => {
74
+ let m;
75
+ try {
76
+ m = JSON.parse(raw.toString());
77
+ } catch {
78
+ return;
79
+ }
80
+ if (m.hello !== "genflow-hub") return;
81
+ clearTimeout(t);
82
+ ws.removeAllListeners("message");
83
+ ws.removeAllListeners("close");
84
+ ws.on("message", (r) => {
85
+ const msg = JSON.parse(r.toString());
86
+ const p = pending.get(msg.id);
87
+ if (!p) return;
88
+ pending.delete(msg.id);
89
+ msg.error ? p.reject(new Error(msg.error)) : p.resolve(msg.result);
90
+ });
91
+ ws.on("close", () => (relay = null));
92
+ resolve(ws);
93
+ });
94
+ });
95
+
96
+ let hubUp = false;
97
+ for (const port of PORTS) {
98
+ try {
99
+ attach(await bindPort(port));
100
+ hubUp = true;
101
+ console.error(`[hub] 포트 ${port}에서 대기`);
102
+ break;
103
+ } catch (e) {
104
+ if (e.code !== "EADDRINUSE") throw e;
105
+ relay = await probeHub(port);
106
+ if (relay) {
107
+ console.error(`[hub] 포트 ${port}의 GenFlow 허브에 연결`);
108
+ break;
109
+ }
110
+ // 다른 프로그램이 쓰는 포트: 다음 포트로
111
+ }
112
+ }
113
+ if (!hubUp && !relay) console.error(`[hub] 쓸 수 있는 포트가 없어요(${PORTS.join(", ")}). 다른 프로그램이 모두 쓰고 있어요`);
114
+
115
+ function call(method, params = {}, timeoutMs = 15000) {
116
+ return new Promise((resolve, reject) => {
117
+ if (relay) {
118
+ if (relay.readyState !== 1) return reject(new Error("먼저 켜진 GenFlow 연결 서버에 붙는 중이에요. 잠시 뒤 다시 시도하세요."));
119
+ const id = ++seq;
120
+ const t = setTimeout(() => (pending.delete(id), reject(new Error("에디터 응답 시간 초과"))), timeoutMs);
121
+ pending.set(id, { resolve: (v) => (clearTimeout(t), resolve(v)), reject: (e) => (clearTimeout(t), reject(e)) });
122
+ return relay.send(JSON.stringify({ id, method, params }));
123
+ }
124
+ if (!editor || editor.readyState !== 1)
125
+ return reject(new Error("에디터 탭이 연결되지 않았습니다. localhost:3200에서 프로젝트를 열어두세요."));
126
+ const id = ++seq;
127
+ const t = setTimeout(() => {
128
+ pending.delete(id);
129
+ reject(new Error("에디터 응답 시간 초과"));
130
+ }, timeoutMs);
131
+ pending.set(id, {
132
+ resolve: (v) => (clearTimeout(t), resolve(v)),
133
+ reject: (e) => (clearTimeout(t), reject(e)),
134
+ });
135
+ editor.send(JSON.stringify({ id, method, params }));
136
+ });
137
+ }
138
+
139
+ const server = new McpServer({ name: "genflow-editor", version: "0.1.2" });
140
+ const out = (v) => ({ content: [{ type: "text", text: JSON.stringify(v, null, 2) }] });
141
+ const tool = (name, description, shape, method) =>
142
+ server.tool(name, description, shape, async (args) => {
143
+ try {
144
+ return out(await call(method, args));
145
+ } catch (e) {
146
+ return { isError: true, content: [{ type: "text", text: String(e.message) }] };
147
+ }
148
+ });
149
+
150
+ tool("editor_get_state", "현재 프로젝트의 재생헤드, 전체 길이, 트랙/요소, 미디어 에셋 목록을 조회", {}, "get_state");
151
+ tool("editor_list_actions", "run_action으로 실행 가능한 에디터 액션 목록", {}, "list_actions");
152
+ tool(
153
+ "editor_run_action",
154
+ "에디터 액션 실행 (toggle-play, split-left, delete-selected, select-all 등)",
155
+ { action: z.string(), args: z.record(z.any()).optional() },
156
+ "run_action",
157
+ );
158
+ tool("editor_seek", "재생헤드를 초 단위 위치로 이동", { seconds: z.number() }, "seek");
159
+ tool(
160
+ "editor_add_text",
161
+ "텍스트 요소를 타임라인에 추가",
162
+ { text: z.string(), start: z.number().optional(), duration: z.number().optional() },
163
+ "add_text",
164
+ );
165
+ tool(
166
+ "editor_place_media",
167
+ "미디어 에셋(editor_get_state의 assets)을 타임라인에 배치",
168
+ { assetId: z.string(), start: z.number().optional(), duration: z.number().optional() },
169
+ "place_media",
170
+ );
171
+ tool(
172
+ "editor_split_at",
173
+ "지정한 초 위치에서 요소를 분할 (elementId 생략 시 그 시각에 걸친 모든 요소)",
174
+ { seconds: z.number().optional(), elementId: z.string().optional() },
175
+ "split_at",
176
+ );
177
+ tool("editor_delete_elements", "요소 삭제 (elementIds 생략 시 현재 선택된 요소)", { elementIds: z.array(z.string()).optional() }, "delete_elements");
178
+
179
+ tool("editor_undo", "방금 작업 되돌리기", {}, "undo");
180
+ tool("editor_redo", "되돌린 작업 다시 실행", {}, "redo");
181
+ tool(
182
+ "editor_select_by_name",
183
+ "이름/종류(text,video,audio)로 요소 선택. which=first|last (예: 마지막 자막)",
184
+ { query: z.string().optional(), which: z.enum(["first", "last", "all"]).optional() },
185
+ "select_by_name",
186
+ );
187
+
188
+ tool(
189
+ "editor_catalog",
190
+ "에디터 기능 사전 조회. search='글씨 크게' 같은 한국어 표현으로 기능 id 검색, elementType(text/video/image/audio...)으로 지금 조정 가능한 항목 목록. 인자 없으면 전체",
191
+ { search: z.string().optional(), elementType: z.string().optional() },
192
+ "catalog",
193
+ );
194
+ tool(
195
+ "editor_adjust",
196
+ "선택된 요소(또는 elementIds)의 파라미터를 조정. param은 카탈로그의 param id에서 'param:' 뒤 부분(예: fontSize, opacity). value로 절대값, 또는 direction=up|down(+factor 배율, 생략 시 범위의 10%)으로 상대 조정",
197
+ {
198
+ param: z.string(),
199
+ value: z.union([z.number(), z.string(), z.boolean()]).optional(),
200
+ direction: z.enum(["up", "down"]).optional(),
201
+ factor: z.number().optional(),
202
+ elementIds: z.array(z.string()).optional(),
203
+ },
204
+ "adjust",
205
+ );
206
+ tool(
207
+ "editor_apply_effect",
208
+ "선택된 요소(또는 elementIds)에 효과 추가. effect는 카탈로그의 effect id 뒤 부분(예: blur, grayscale, vignette)",
209
+ { effect: z.string(), elementIds: z.array(z.string()).optional() },
210
+ "apply_effect",
211
+ );
212
+ tool(
213
+ "editor_apply_transition",
214
+ "선택된 클립과 다음 클립 사이에 전환 추가. transition은 카탈로그의 transition id 뒤 부분(예: dissolve, zoom-in, glitch-cut)",
215
+ { transition: z.string(), elementIds: z.array(z.string()).optional() },
216
+ "apply_transition",
217
+ );
218
+
219
+ tool(
220
+ "editor_analyze_speech",
221
+ "말하기 영상 정리 1단계(분석만, 타임라인 변경 없음): 선택된(없으면 첫) 영상/오디오 클립에서 빈 구간·군더더기·반복을 찾아 컷 목록과 줄어드는 길이를 반환. withTranscript=true면 음성 인식(느림)으로 군더더기/반복까지 탐지. options: minSilenceSec(기본0.6), keepPadSec(0.15), silenceThresholdDb(-42), removeFillers, removeRepeats",
222
+ {
223
+ elementId: z.string().optional(),
224
+ withTranscript: z.boolean().optional(),
225
+ language: z.string().optional(),
226
+ modelId: z.enum(["whisper-small-timestamped", "whisper-large-v3-turbo-timestamped"]).optional(),
227
+ options: z
228
+ .object({
229
+ minSilenceSec: z.number().optional(),
230
+ keepPadSec: z.number().optional(),
231
+ silenceThresholdDb: z.number().optional(),
232
+ removeFillers: z.boolean().optional(),
233
+ removeRepeats: z.boolean().optional(),
234
+ })
235
+ .optional(),
236
+ },
237
+ "analyze_speech",
238
+ );
239
+ tool(
240
+ "editor_apply_speech_cleanup",
241
+ "말하기 영상 정리 2단계: editor_analyze_speech 결과의 cuts(start/end 초)를 타임라인에 적용. 사용자에게 줄어드는 길이를 먼저 알려 확인받은 뒤 호출. 한 번의 undo로 전체 복구",
242
+ { cuts: z.array(z.object({ start: z.number(), end: z.number() })) },
243
+ "apply_speech_cleanup",
244
+ );
245
+
246
+ tool(
247
+ "editor_analyze_beats",
248
+ "박자 맞춤 1단계(분석만): 선택된(없으면 첫) 음악/영상 클립에서 BPM과 비트 시각(timelineBeats, 타임라인 초)을 반환. 타임라인 변경 없음",
249
+ { elementId: z.string().optional() },
250
+ "analyze_beats",
251
+ );
252
+ tool(
253
+ "editor_apply_beat_cuts",
254
+ "박자 맞춤 2단계: editor_analyze_beats 의 timelineBeats 에서 every(N박마다)로 영상/이미지를 자른다. 한 번의 undo로 복구",
255
+ { beats: z.array(z.number()), every: z.number().optional(), offsetSec: z.number().optional() },
256
+ "apply_beat_cuts",
257
+ );
258
+
259
+ // ───────── 스튜디오 명령(에디터 안 executeEditorCommand와 같은 실행기) ─────────
260
+ // AI가 문장마다 정해진 규칙 없이, 에디터의 모든 명령을 직접 골라 부를 수 있게 하는 통로.
261
+ const tooLong = 10 * 60 * 1000; // 자막 만들기는 모델 내려받기 때문에 오래 걸릴 수 있다
262
+ const timed = (name, description, shape, method, timeoutMs) =>
263
+ server.tool(name, description, shape, async (args) => {
264
+ try {
265
+ return out(await call(method, args, timeoutMs));
266
+ } catch (e) {
267
+ return { isError: true, content: [{ type: "text", text: String(e.message) }] };
268
+ }
269
+ });
270
+
271
+ tool(
272
+ "editor_get_captions",
273
+ "자막 목록과 상태 조회: 각 자막의 글자 내용·시작·길이·줄 수, 그리고 두 줄 이상인 자막 개수 요약. 자막을 손보기 전에 먼저 호출해 현재 모습을 확인",
274
+ {},
275
+ "get_captions",
276
+ );
277
+ timed(
278
+ "editor_generate_captions",
279
+ "영상 소리를 브라우저 안에서 받아 적어 자막 트랙을 만든다(이미 있으면 새 자막으로 교체). 처음에는 모델을 내려받아 수 분 걸릴 수 있다",
280
+ { language: z.string().optional() },
281
+ "generate_captions",
282
+ tooLong,
283
+ );
284
+ tool("editor_fit_shorts", "세로 9:16 화면 + 흐린 배경으로 전체 보이게 바꾸고, 이미 있는 자막은 새 화면에 맞게 다시 배치", {}, "fit_shorts");
285
+ tool(
286
+ "editor_fit_caption_lines",
287
+ "묶음 명령: 모든 자막이 lines줄(기본 1) 안에 들어오도록 글자 크기를 한 번에 맞춘다(글자 폭을 실제로 재서 계산). '자막 한 줄로' 요청에 사용",
288
+ { lines: z.number().optional() },
289
+ "fit_caption_lines",
290
+ );
291
+ tool("editor_shift_captions", "자막 전체를 seconds초만큼 옮긴다(음수=앞당김, 양수=늦춤)", { seconds: z.number() }, "shift_captions");
292
+ tool("editor_delete_captions", "스튜디오가 만든 자막(Caption N)을 모두 지운다. undo로 복구 가능", {}, "delete_captions");
293
+ server.tool(
294
+ "editor_command",
295
+ "에디터 실행기에 직접 명령 전달(고급): method와 params. 위 전용 도구에 없는 새 명령이 생겼을 때 사용",
296
+ { method: z.string(), params: z.record(z.any()).optional() },
297
+ async ({ method, params }) => {
298
+ try {
299
+ return out(await call(method, params ?? {}, tooLong));
300
+ } catch (e) {
301
+ return { isError: true, content: [{ type: "text", text: String(e.message) }] };
302
+ }
303
+ },
304
+ );
305
+
306
+ await server.connect(new StdioServerTransport());