Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.
JavaScript 2d-animationai-agentsai-videoanimationclaude-codecodexmulti-agentstyle-transfervideo-generation
Convert the app to TypeScript; add tests, lint and CI
許元豪42f78b7f7de2
diff --git a/.gitattributes b/.gitattributesindex d4234f2..05355b1 100644--- a/.gitattributes+++ b/.gitattributes@@ -2,3 +2,30 @@*.sh text eol=lf*.bat text eol=crlf*.cmd text eol=crlf++# GitHub language stats: bundled upstream skills keep their own licenses (THIRD_PARTY_NOTICES.md) and are not our code+.claude/skills/hyperframes*/** linguist-vendored+.claude/skills/embedded-captions/** linguist-vendored+.claude/skills/faceless-explainer/** linguist-vendored+.claude/skills/figma/** linguist-vendored+.claude/skills/general-video/** linguist-vendored+.claude/skills/media-use/** linguist-vendored+.claude/skills/motion-graphics/** linguist-vendored+.claude/skills/music-to-video/** linguist-vendored+.claude/skills/pr-to-video/** linguist-vendored+.claude/skills/product-launch-video/** linguist-vendored+.claude/skills/remotion-to-hyperframes/** linguist-vendored+.claude/skills/slideshow/** linguist-vendored+.claude/skills/captions-overlay/** linguist-vendored+.claude/skills/cut-the-curve/** linguist-vendored+.claude/skills/motion-doctrine/** linguist-vendored+.claude/skills/oversized-cursor/** linguist-vendored+.claude/skills/seam-craft/** linguist-vendored+.claude/skills/talking-head-recut/** linguist-vendored+.claude/skills/frontend-design/** linguist-vendored+.claude/skills/ffmpeg/** linguist-vendored+.claude/skills/painted-animation/** linguist-vendored+.claude/skills/crayon-storybook/** linguist-vendored+.claude/skills/*/template/render.mjs linguist-vendored+.claude/skills/video-clone/assets/engine-kit/render.mjs linguist-vendored+**/package-lock.json linguist-generateddiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..83192ac--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,29 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:++jobs:+ app:+ name: App (Node ${{ matrix.node }})+ runs-on: ubuntu-latest+ strategy:+ matrix:+ node: ['22.18', '24']+ defaults:+ run:+ working-directory: app+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node }}+ cache: npm+ cache-dependency-path: app/package-lock.json+ - run: npm ci+ - run: npm run typecheck+ - run: npm run lint+ - run: npm test+ - run: npm run builddiff --git a/CLAUDE.md b/CLAUDE.mdindex 2542d12..90f21da 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@- 每次渲染後抽影格用 Read 看,有問題修完再出片。## 工具-- 需要的程式與安裝方式見 README(`npm run doctor` 會逐項檢查):Node 20+、Python 3.10+(requirements.txt)、FFmpeg、Chrome、Claude Code 或 Codex CLI。+- 需要的程式與安裝方式見 README(`npm run doctor` 會逐項檢查):Node 22.18+、Python 3.10+(requirements.txt)、FFmpeg、Chrome、Claude Code 或 Codex CLI。- 找不到 FFmpeg 時看環境變數 `FFMPEG_DIR`;Chrome 看 `CHROME_PATH`;Blender 看 `BLENDER`;API 金鑰在 `~/.reelmimic/secrets.json`(伺服器啟動時載入)。- yt-dlp:`python -m yt_dlp`;截圖一律用 `.claude/skills/video-clone/scripts/hf_frames.py`(HyperFrames 專案)或引擎自己的 render 指令。diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 666a4d5..5cac4d4 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -25,12 +25,14 @@ How it works is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), and how to extestyle file or the engine's `SKILL.md`.- **A new rendering engine**: an agent skill folder. For third-party skills, include the source and license and update`THIRD_PARTY_NOTICES.md`.-- **Pipeline and prompts**: if you change `app/server/prompts.mjs` or `jobs.mjs`, say which video you tested with and+- **Pipeline and prompts**: if you change `app/server/prompts.ts` or `jobs.ts`, say which video you tested with andinclude a before/after timing from `timeline.py`.## Before you open a PR-- `npm run build` passes, and `node --check` passes for `app/server/*.mjs`.+- In `app/`: `npm run check` (type check, lint, tests) and `npm run build` pass. CI runs the same on every PR.+- The app is TypeScript (strict). The server runs its `.ts` files directly on Node's type stripping, so there is no build step+ for it; use only erasable syntax (no `enum`, `namespace` or parameter properties).- Don't commit `projects/`, API keys (`~/.reelmimic/secrets.json`), reference videos, or any asset you don't have therights to.- Comments and docs can be in English or Traditional Chinese. Match what's around them.diff --git a/README.md b/README.mdindex becfa0a..06afa97 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@[](LICENSE)[](https://docs.anthropic.com/en/docs/claude-code)[](https://github.com/openai/codex)-+**English** · [繁體中文](README.zh-TW.md) · [简体中文](README.zh-CN.md)@@ -97,7 +97,7 @@ The whole thing runs on your own computer, with your own Claude Code or Codex.## Getting started-You'll need Node.js 20+, Python 3.10+, FFmpeg, Chrome, and either+You'll need Node.js 22.18+, Python 3.10+, FFmpeg, Chrome, and either[Claude Code](https://docs.anthropic.com/en/docs/claude-code) or [Codex CLI](https://github.com/openai/codex) (logged in).```bashdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 8dd76c7..a9ed7b8 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -9,7 +9,7 @@[](LICENSE)[](https://docs.anthropic.com/en/docs/claude-code)[](https://github.com/openai/codex)-+[English](README.md) · [繁體中文](README.zh-TW.md) · **简体中文**@@ -86,7 +86,7 @@ ReelMimic 学的是参考片的做法,不是把原本的画面、角色或素## 开始用-先装好这些:Node.js 20 以上、Python 3.10 以上、FFmpeg、Chrome,还有 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [Codex CLI](https://github.com/openai/codex) 其中一个(要先登录)。+先装好这些:Node.js 22.18 以上、Python 3.10 以上、FFmpeg、Chrome,还有 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [Codex CLI](https://github.com/openai/codex) 其中一个(要先登录)。```bashgit clone https://github.com/edenfunf/reelmimic.git && cd reelmimicdiff --git a/README.zh-TW.md b/README.zh-TW.mdindex 42e875a..9dea6f9 100644--- a/README.zh-TW.md+++ b/README.zh-TW.md@@ -9,7 +9,7 @@[](LICENSE)[](https://docs.anthropic.com/en/docs/claude-code)[](https://github.com/openai/codex)-+[English](README.md) · **繁體中文** · [简体中文](README.zh-CN.md)@@ -86,7 +86,7 @@ ReelMimic 學的是參考片的做法,不是把原本的畫面、角色或素## 開始用-先裝好這些:Node.js 20 以上、Python 3.10 以上、FFmpeg、Chrome,還有 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [Codex CLI](https://github.com/openai/codex) 其中一個(要先登入)。+先裝好這些:Node.js 22.18 以上、Python 3.10 以上、FFmpeg、Chrome,還有 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [Codex CLI](https://github.com/openai/codex) 其中一個(要先登入)。```bashgit clone https://github.com/edenfunf/reelmimic.git && cd reelmimicdiff --git a/app/README.md b/app/README.mdindex 90d1657..f186784 100644--- a/app/README.md+++ b/app/README.md@@ -3,7 +3,17 @@Install and start it as described in the root [README](../README.md); how it works is in [docs/ARCHITECTURE.md](../docs/ARCHITECTURE.md).```-server/ index.mjs (HTTP/SSE) · jobs.mjs (workflow and production line) · prompts.mjs (agent instructions) · agents/ (Claude Code / Codex adapters) · env.mjs (keys)-web/ React UI: App.jsx (home) · Project.jsx (project page) · Chat.jsx (chat and live agent steps) · ui.jsx (components) · i18n.js (languages) · styles.css-scripts/ doctor.mjs (environment check)+server/ index.ts (HTTP/SSE) · jobs.ts (workflow and production line) · prompts.ts (agent instructions) · agents/ (Claude Code / Codex adapters) · env.ts (keys)+web/ React UI: App.tsx (home) · Project.tsx (project page) · Chat.tsx (chat and live agent steps) · ui.tsx (components) · i18n.ts (languages) · styles.css+shared/ types.ts (job.json, the project snapshot and live events: the contract between server and web)+scripts/ doctor.mjs (environment check; plain JS so it can run on any Node and say what to upgrade)+```++TypeScript throughout (strict). The server runs its `.ts` files directly on Node's built-in type stripping (Node 22.18+),+so there is no build step for it; Vite builds the web UI.++```+npm run server start the server (http://localhost:4318)+npm run web UI dev server with hot reload (proxies /api to the server)+npm run check type check + lint + tests (what CI runs, plus npm run build)```diff --git a/app/eslint.config.js b/app/eslint.config.jsnew file mode 100644index 0000000..8efebed--- /dev/null+++ b/app/eslint.config.js@@ -0,0 +1,21 @@+// Correctness rules only; formatting is left to the existing (dense) house style.+import js from '@eslint/js';+import tseslint from 'typescript-eslint';+import reactHooks from 'eslint-plugin-react-hooks';+import globals from 'globals';++export default tseslint.config(+ { ignores: ['dist', 'node_modules'] },+ js.configs.recommended,+ tseslint.configs.recommended,+ {+ rules: {+ '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', caughtErrors: 'none' }],+ '@typescript-eslint/no-unused-expressions': ['error', { allowTernary: true, allowShortCircuit: true }], // `ok ? a() : b()` is house style+ 'no-empty': ['error', { allowEmptyCatch: true }],+ },+ },+ { files: ['server/**', 'scripts/**', 'shared/**', '*.js'], languageOptions: { globals: globals.node } },+ // Only the rules of hooks: memos here are keyed on lengths / last timestamps on purpose (logs grow to hundreds of entries)+ { files: ['web/**'], languageOptions: { globals: globals.browser }, plugins: { 'react-hooks': reactHooks }, rules: { 'react-hooks/rules-of-hooks': 'error' } },+);diff --git a/app/package-lock.json b/app/package-lock.jsonindex 0682c9e..0192f41 100644--- a/app/package-lock.json+++ b/app/package-lock.json@@ -11,9 +11,20 @@"opencc-js": "^1.4.2"},"devDependencies": {+ "@eslint/js": "^10.0.1",+ "@types/express": "^4.17.25",+ "@types/multer": "^2.3.0",+ "@types/node": "^22.20.4",+ "@types/react": "^18.3.31",+ "@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.3.4",+ "eslint": "^10.11.0",+ "eslint-plugin-react-hooks": "^7.1.1",+ "globals": "^17.12.0","react": "^18.3.1","react-dom": "^18.3.1",+ "typescript": "^6.0.3",+ "typescript-eslint": "^8.71.0","vite": "^6.0.7"},"engines": {@@ -302,6 +313,30 @@"node": ">=6.9.0"}},+ "node_modules/@cacheable/memory": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz",+ "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cacheable/utils": "^2.5.0",+ "@keyv/bigmap": "^1.3.1",+ "hookified": "^1.15.1",+ "keyv": "^5.6.0"+ }+ },+ "node_modules/@cacheable/utils": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz",+ "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hashery": "^1.5.1",+ "keyv": "^5.6.0"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.25.12","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",@@ -744,6 +779,200 @@"node": ">=18"}},+ "node_modules/@eslint-community/eslint-utils": {+ "version": "4.10.1",+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",+ "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eslint-visitor-keys": "^3.4.3"+ },+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ },+ "peerDependencies": {+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint-community/regexpp": {+ "version": "4.12.2",+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"+ }+ },+ "node_modules/@eslint/config-array": {+ "version": "0.23.5",+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",+ "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/object-schema": "^3.0.5",+ "debug": "^4.3.1",+ "minimatch": "^10.2.4"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ }+ },+ "node_modules/@eslint/config-helpers": {+ "version": "0.7.0",+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",+ "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^1.2.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ }+ },+ "node_modules/@eslint/core": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz",+ "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@types/json-schema": "^7.0.15"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ }+ },+ "node_modules/@eslint/js": {+ "version": "10.0.1",+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz",+ "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ },+ "peerDependencies": {+ "eslint": "^10.0.0"+ },+ "peerDependenciesMeta": {+ "eslint": {+ "optional": true+ }+ }+ },+ "node_modules/@eslint/object-schema": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz",+ "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ }+ },+ "node_modules/@eslint/plugin-kit": {+ "version": "0.7.3",+ "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz",+ "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^1.2.1",+ "levn": "^0.4.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ }+ },+ "node_modules/@humanfs/core": {+ "version": "0.19.2",+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",+ "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@humanfs/types": "^0.15.0"+ },+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanfs/node": {+ "version": "0.16.8",+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz",+ "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@humanfs/core": "^0.19.2",+ "@humanfs/types": "^0.15.0",+ "@humanwhocodes/retry": "^0.4.0"+ },+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanfs/types": {+ "version": "0.15.0",+ "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",+ "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanwhocodes/module-importer": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.22"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@humanwhocodes/retry": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },"node_modules/@jridgewell/gen-mapping": {"version": "0.3.13","resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",@@ -794,6 +1023,30 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@keyv/bigmap": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz",+ "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hashery": "^1.4.0",+ "hookified": "^1.15.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "peerDependencies": {+ "keyv": "^5.6.0"+ }+ },+ "node_modules/@keyv/serialize": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz",+ "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@napi-rs/lzma-linux-x64-gnu": {"version": "1.5.1","resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",@@ -1255,6 +1508,34 @@"@babel/types": "^7.28.2"}},+ "node_modules/@types/body-parser": {+ "version": "1.19.6",+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/connect": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/connect": {+ "version": "3.4.38",+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/esrecurse": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",+ "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/estree": {"version": "1.0.9","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",@@ -1262,136 +1543,584 @@"dev": true,"license": "MIT"},- "node_modules/@vitejs/plugin-react": {- "version": "4.7.0",- "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",- "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",+ "node_modules/@types/express": {+ "version": "4.17.25",+ "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz",+ "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==","dev": true,"license": "MIT","dependencies": {- "@babel/core": "^7.28.0",- "@babel/plugin-transform-react-jsx-self": "^7.27.1",- "@babel/plugin-transform-react-jsx-source": "^7.27.1",- "@rolldown/pluginutils": "1.0.0-beta.27",- "@types/babel__core": "^7.20.5",- "react-refresh": "^0.17.0"- },- "engines": {- "node": "^14.18.0 || >=16.0.0"- },- "peerDependencies": {- "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"+ "@types/body-parser": "*",+ "@types/express-serve-static-core": "^4.17.33",+ "@types/qs": "*",+ "@types/serve-static": "^1"}},- "node_modules/accepts": {- "version": "1.3.8",- "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",- "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",+ "node_modules/@types/express-serve-static-core": {+ "version": "4.19.9",+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.9.tgz",+ "integrity": "sha512-QP2ESEe/ImWY0HDwNAnK9PvEffUyhLTnWkk7KXzHfyeWAnlrDe1fN77bXl6ia8KT3wPlmA7t9/VPRpnf4Ex9sg==",+ "dev": true,"license": "MIT","dependencies": {- "mime-types": "~2.1.34",- "negotiator": "0.6.3"- },- "engines": {- "node": ">= 0.6"+ "@types/node": "*",+ "@types/qs": "*",+ "@types/range-parser": "*",+ "@types/send": "*"}},- "node_modules/append-field": {- "version": "1.0.0",- "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",- "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",+ "node_modules/@types/http-errors": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",+ "dev": true,"license": "MIT"},- "node_modules/array-flatten": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",- "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "dev": true,"license": "MIT"},- "node_modules/baseline-browser-mapping": {- "version": "2.11.26",- "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.26.tgz",- "integrity": "sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==",+ "node_modules/@types/mime": {+ "version": "1.3.5",+ "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",+ "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==","dev": true,- "license": "Apache-2.0",- "bin": {- "baseline-browser-mapping": "dist/cli.cjs"- },- "engines": {- "node": ">=6.0.0"- }+ "license": "MIT"},- "node_modules/body-parser": {- "version": "1.20.8",- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",- "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==",+ "node_modules/@types/multer": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.3.0.tgz",+ "integrity": "sha512-i7STIm9V4K2MPH4ZYMtrZAwNxs3kglk2LgleaTuB9pUXgADBcQYQuYMd7+6xgTIxfoggIkFA/DkkvycdZpIARA==",+ "dev": true,"license": "MIT","dependencies": {- "bytes": "~3.1.2",- "content-type": "~1.0.5",- "debug": "2.6.9",- "depd": "2.0.0",- "destroy": "~1.2.0",- "http-errors": "~2.0.1",- "iconv-lite": "~0.4.24",- "on-finished": "~2.4.1",- "qs": "~6.16.0",- "raw-body": "~2.5.3",- "type-is": "~1.6.18",- "unpipe": "~1.0.0"- },- "engines": {- "node": ">= 0.8",- "npm": "1.2.8000 || >= 1.4.16"+ "@types/express": "*"}},- "node_modules/body-parser/node_modules/debug": {- "version": "2.6.9",- "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",- "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "node_modules/@types/node": {+ "version": "22.20.4",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.4.tgz",+ "integrity": "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==",+ "dev": true,"license": "MIT","dependencies": {- "ms": "2.0.0"+ "undici-types": "~6.21.0"}},- "node_modules/body-parser/node_modules/ms": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",- "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "node_modules/@types/prop-types": {+ "version": "15.7.15",+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",+ "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",+ "dev": true,"license": "MIT"},- "node_modules/browserslist": {- "version": "4.29.1",- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.1.tgz",- "integrity": "sha512-AUdjuRyCNGUYtqpqfTmWyM4fXay8yIQhmLnvYe/THMGfT9B/34X7xQd3ifKxwyNPPpowVBjLb+64BN9Rn1mizw==",+ "node_modules/@types/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/range-parser": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/react": {+ "version": "18.3.31",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",+ "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==","dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/browserslist"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/browserslist"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],"license": "MIT","dependencies": {- "baseline-browser-mapping": "^2.11.25",- "caniuse-lite": "^1.0.30001810",- "electron-to-chromium": "^1.5.438",- "node-releases": "^2.0.57",- "update-browserslist-db": "^1.3.3"- },- "bin": {- "browserslist": "cli.js"- },- "engines": {- "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"+ "@types/prop-types": "*",+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "18.3.7",+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",+ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "^18.0.0"+ }+ },+ "node_modules/@types/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/serve-static": {+ "version": "1.15.10",+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz",+ "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/http-errors": "*",+ "@types/node": "*",+ "@types/send": "<1"+ }+ },+ "node_modules/@types/serve-static/node_modules/@types/send": {+ "version": "0.17.6",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz",+ "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/mime": "^1",+ "@types/node": "*"+ }+ },+ "node_modules/@typescript-eslint/eslint-plugin": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.0.tgz",+ "integrity": "sha512-pqcS9c1HxZTHt7End4nXqd0s5lJrrFzrgCkKFJrsbUnaL6M3+6oBFZaslg6Gjsl3argl2DDRFROnXARaZ2e4Nw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/regexpp": "^4.12.2",+ "@typescript-eslint/scope-manager": "8.71.0",+ "@typescript-eslint/type-utils": "8.71.0",+ "@typescript-eslint/utils": "8.71.0",+ "@typescript-eslint/visitor-keys": "8.71.0",+ "ignore": "^7.0.5",+ "natural-compare": "^1.4.0",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "@typescript-eslint/parser": "^8.71.0",+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {+ "version": "7.0.11",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.11.tgz",+ "integrity": "sha512-YChdK5txDjwGUvgR7oCJcLGkwi3LDh8Zx8tS7ndYciLEg/oOCL26VUBSUEtgS7EjiybcBqFxh5j0rAdDX7/bbg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/@typescript-eslint/parser": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.71.0.tgz",+ "integrity": "sha512-CG4nPk1f2zc8yw4pALqHsFYH2hdo+h1T9daSp21+Hnxi9LOE3GT9hAfTKJCBXVNM2GmYs1eMEP615wPoeOgk3A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/scope-manager": "8.71.0",+ "@typescript-eslint/types": "8.71.0",+ "@typescript-eslint/typescript-estree": "8.71.0",+ "@typescript-eslint/visitor-keys": "8.71.0",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/project-service": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.71.0.tgz",+ "integrity": "sha512-aABjw5rjBacYONVPaPiWOCjJu0vEF4a25iQuodlmQYL1trtLZ0X/y+2Vzl3BKI1odM4LnwLE1oUDXYp1wzx1TQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/tsconfig-utils": "^8.71.0",+ "@typescript-eslint/types": "^8.71.0",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/scope-manager": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.71.0.tgz",+ "integrity": "sha512-gWF0BhUcnjZxSpLE8ngS/59n2SB0J3YqRxvX1+2aoRJk9hNtHSLOV+TcarFiOr5ipXm3yc1QrI4c9YZc8zyCxw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.71.0",+ "@typescript-eslint/visitor-keys": "8.71.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/tsconfig-utils": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.71.0.tgz",+ "integrity": "sha512-Z1UlWHADEK2Mlb9NpWfDeSjqoZ5EyrOv4R3eQpbkzqn/EwaIdOpXXupEA1+0ZIOSJSZZDBHG0BrQyN8zUG6Pwg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/type-utils": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.71.0.tgz",+ "integrity": "sha512-i8uO1qbdxeKgRnS5sCRt6On3/nfo2d2DwQe3Yvjx543zLy7r8ySqRuPPiIIXAhS03U0v5NfAFx+rUgxFzKKwNw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.71.0",+ "@typescript-eslint/typescript-estree": "8.71.0",+ "@typescript-eslint/utils": "8.71.0",+ "debug": "^4.4.3",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/types": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.71.0.tgz",+ "integrity": "sha512-cJ4OoxPGWvFnBTnSZyaU+qJzGTqPTGJY+gDchj6cRyLRdmIdt4rcsE4twj+zPfrNiWuVi38wijHzShL++Z9atQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.71.0.tgz",+ "integrity": "sha512-PEEF4G5sLLWAS5BpPrUvms4ySZkiBQQZM4z+3ReI46axK5Vqr/vXBQatJQIZZOYdGyPUAKTtsrWzpqKuU+3DEw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/project-service": "8.71.0",+ "@typescript-eslint/tsconfig-utils": "8.71.0",+ "@typescript-eslint/types": "8.71.0",+ "@typescript-eslint/visitor-keys": "8.71.0",+ "debug": "^4.4.3",+ "minimatch": "^10.2.2",+ "semver": "^7.7.3",+ "tinyglobby": "^0.2.15",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@typescript-eslint/utils": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.71.0.tgz",+ "integrity": "sha512-pKR/tEMVrXZG23UFKUn5BQf3zfmfk7KQceI2cGzywZ5nxM5Eu3hEJU1utjWzydtzBbcJAQhHN8iPCxobHpPcZQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.9.1",+ "@typescript-eslint/scope-manager": "8.71.0",+ "@typescript-eslint/types": "8.71.0",+ "@typescript-eslint/typescript-estree": "8.71.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.71.0.tgz",+ "integrity": "sha512-8eQ9R218XORK+KLosnf4bu/QsUXvUyVwTbArg7/0NMB1Pu87OJKvj4nhFblkYE8gQV73mW1dx1ptlPCkwRGa7A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.71.0",+ "eslint-visitor-keys": "^5.0.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@vitejs/plugin-react": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",+ "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.28.0",+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",+ "@rolldown/pluginutils": "1.0.0-beta.27",+ "@types/babel__core": "^7.20.5",+ "react-refresh": "^0.17.0"+ },+ "engines": {+ "node": "^14.18.0 || >=16.0.0"+ },+ "peerDependencies": {+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"+ }+ },+ "node_modules/accepts": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "~2.1.34",+ "negotiator": "0.6.3"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/acorn": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",+ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-jsx": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/ajv": {+ "version": "6.15.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",+ "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.1",+ "fast-json-stable-stringify": "^2.0.0",+ "json-schema-traverse": "^0.4.1",+ "uri-js": "^4.2.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/append-field": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",+ "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",+ "license": "MIT"+ },+ "node_modules/array-flatten": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",+ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",+ "license": "MIT"+ },+ "node_modules/balanced-match": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/baseline-browser-mapping": {+ "version": "2.11.26",+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.26.tgz",+ "integrity": "sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "baseline-browser-mapping": "dist/cli.cjs"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/body-parser": {+ "version": "1.20.8",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",+ "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "content-type": "~1.0.5",+ "debug": "2.6.9",+ "depd": "2.0.0",+ "destroy": "~1.2.0",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.4.24",+ "on-finished": "~2.4.1",+ "qs": "~6.16.0",+ "raw-body": "~2.5.3",+ "type-is": "~1.6.18",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8",+ "npm": "1.2.8000 || >= 1.4.16"+ }+ },+ "node_modules/body-parser/node_modules/debug": {+ "version": "2.6.9",+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.0.0"+ }+ },+ "node_modules/body-parser/node_modules/ms": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "license": "MIT"+ },+ "node_modules/brace-expansion": {+ "version": "5.0.12",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",+ "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/browserslist": {+ "version": "4.29.1",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.1.tgz",+ "integrity": "sha512-AUdjuRyCNGUYtqpqfTmWyM4fXay8yIQhmLnvYe/THMGfT9B/34X7xQd3ifKxwyNPPpowVBjLb+64BN9Rn1mizw==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "baseline-browser-mapping": "^2.11.25",+ "caniuse-lite": "^1.0.30001810",+ "electron-to-chromium": "^1.5.438",+ "node-releases": "^2.0.57",+ "update-browserslist-db": "^1.3.3"+ },+ "bin": {+ "browserslist": "cli.js"+ },+ "engines": {+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"}},"node_modules/busboy": {@@ -1414,6 +2143,20 @@"node": ">= 0.8"}},+ "node_modules/cacheable": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz",+ "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cacheable/memory": "^2.2.0",+ "@cacheable/utils": "^2.5.0",+ "hookified": "^1.15.0",+ "keyv": "^5.6.0",+ "qified": "^0.10.1"+ }+ },"node_modules/call-bind-apply-helpers": {"version": "1.0.2","resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",@@ -1507,6 +2250,28 @@"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==","license": "MIT"},+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1525,6 +2290,13 @@}}},+ "node_modules/deep-is": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/depd": {"version": "2.0.0","resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",@@ -1668,6 +2440,194 @@"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==","license": "MIT"},+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/eslint": {+ "version": "10.11.0",+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.11.0.tgz",+ "integrity": "sha512-P7a6UEEqb9G95MYAtqkmsTbVXIYyzIfl6NGOIJk162PaahFxFyeGcrlXYFSiagECg4sEm8IseJdZBKR3rx6MsQ==",+ "dev": true,+ "license": "MIT",+ "workspaces": [+ "packages/*"+ ],+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.8.0",+ "@eslint-community/regexpp": "^4.12.2",+ "@eslint/config-array": "^0.23.5",+ "@eslint/config-helpers": "^0.7.0",+ "@eslint/core": "^1.2.1",+ "@eslint/plugin-kit": "^0.7.3",+ "@humanfs/node": "^0.16.6",+ "@humanwhocodes/module-importer": "^1.0.1",+ "@humanwhocodes/retry": "^0.4.2",+ "@types/estree": "^1.0.6",+ "ajv": "^6.14.0",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.2",+ "escape-string-regexp": "^4.0.0",+ "eslint-scope": "^9.1.2",+ "eslint-visitor-keys": "^5.0.1",+ "espree": "^11.2.0",+ "esquery": "^1.7.0",+ "esutils": "^2.0.2",+ "fast-deep-equal": "^3.1.3",+ "file-entry-cache": "11.1.5 || >11.1.6 <12",+ "find-up": "^5.0.0",+ "glob-parent": "^6.0.2",+ "ignore": "^5.2.0",+ "imurmurhash": "^0.1.4",+ "is-glob": "^4.0.0",+ "json-stable-stringify-without-jsonify": "^1.0.1",+ "minimatch": "^10.2.5",+ "natural-compare": "^1.4.0",+ "optionator": "^0.9.3"+ },+ "bin": {+ "eslint": "bin/eslint.js"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ },+ "peerDependencies": {+ "jiti": "*"+ },+ "peerDependenciesMeta": {+ "jiti": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-plugin-react-hooks": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz",+ "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.24.4",+ "@babel/parser": "^7.24.4",+ "hermes-parser": "^0.25.1",+ "zod": "^3.25.0 || ^4.0.0",+ "zod-validation-error": "^3.5.0 || ^4.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0"+ }+ },+ "node_modules/eslint-scope": {+ "version": "9.1.2",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz",+ "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "@types/esrecurse": "^4.3.1",+ "@types/estree": "^1.0.8",+ "esrecurse": "^4.3.0",+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/eslint-visitor-keys": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",+ "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/espree": {+ "version": "11.2.0",+ "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz",+ "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "acorn": "^8.16.0",+ "acorn-jsx": "^5.3.2",+ "eslint-visitor-keys": "^5.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/esquery": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",+ "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "estraverse": "^5.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/etag": {"version": "1.8.1","resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",@@ -1738,6 +2698,27 @@"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==","license": "MIT"},+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-json-stable-stringify": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-levenshtein": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/fdir": {"version": "6.5.0","resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",@@ -1756,6 +2737,16 @@}}},+ "node_modules/file-entry-cache": {+ "version": "11.1.5",+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz",+ "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flat-cache": "^6.1.23"+ }+ },"node_modules/finalhandler": {"version": "1.3.2","resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",@@ -1789,6 +2780,42 @@"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==","license": "MIT"},+ "node_modules/find-up": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "locate-path": "^6.0.0",+ "path-exists": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/flat-cache": {+ "version": "6.1.23",+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz",+ "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cacheable": "^2.5.0",+ "flatted": "^3.4.2",+ "hookified": "^1.15.0"+ }+ },+ "node_modules/flatted": {+ "version": "3.4.4",+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",+ "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",+ "dev": true,+ "license": "ISC"+ },"node_modules/forwarded": {"version": "0.2.0","resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",@@ -1875,7 +2902,33 @@"es-object-atoms": "^1.0.0"},"engines": {- "node": ">= 0.4"+ "node": ">= 0.4"+ }+ },+ "node_modules/glob-parent": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "is-glob": "^4.0.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/globals": {+ "version": "17.12.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-17.12.0.tgz",+ "integrity": "sha512-cezEd/DTyyht9cvSSURyygXPfy04GtWO/5e6ZPvH7fCtjKz9PYOmuawphw1Ctd1f6C+5JypXfGD7ahNMXvevBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"}},"node_modules/gopd": {@@ -1902,6 +2955,19 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/hashery": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz",+ "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hookified": "^1.15.0"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/hasown": {"version": "2.0.4","resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",@@ -1914,6 +2980,30 @@"node": ">= 0.4"}},+ "node_modules/hermes-estree": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",+ "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/hermes-parser": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz",+ "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hermes-estree": "0.25.1"+ }+ },+ "node_modules/hookified": {+ "version": "1.15.1",+ "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz",+ "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/http-errors": {"version": "2.0.1","resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",@@ -1946,6 +3036,26 @@"node": ">=0.10.0"}},+ "node_modules/ignore": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.8.19"+ }+ },"node_modules/inherits": {"version": "2.0.4","resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",@@ -1961,6 +3071,36 @@"node": ">= 0.10"}},+ "node_modules/is-extglob": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-glob": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-extglob": "^2.1.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "dev": true,+ "license": "ISC"+ },"node_modules/js-tokens": {"version": "4.0.0","resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",@@ -1981,6 +3121,20 @@"node": ">=6"}},+ "node_modules/json-schema-traverse": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-stable-stringify-without-jsonify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/json5": {"version": "2.2.3","resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",@@ -1994,6 +3148,46 @@"node": ">=6"}},+ "node_modules/keyv": {+ "version": "5.6.0",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",+ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@keyv/serialize": "^1.1.1"+ }+ },+ "node_modules/levn": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1",+ "type-check": "~0.4.0"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/locate-path": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-locate": "^5.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/loose-envify": {"version": "1.4.0","resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",@@ -2086,6 +3280,22 @@"node": ">= 0.6"}},+ "node_modules/minimatch": {+ "version": "10.2.6",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "brace-expansion": "^5.0.8"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",@@ -2129,6 +3339,13 @@"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"}},+ "node_modules/natural-compare": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/negotiator": {"version": "0.6.3","resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",@@ -2178,6 +3395,56 @@"integrity": "sha512-EdcspgdROiCCZDM+jZR6Pa670xW+EW2QhctPBQ8gRjg6lrx4IHEl+2s+kt5izk/TkxVRgdWuFgaGkaEdIUfdaw==","license": "MIT AND Apache-2.0"},+ "node_modules/optionator": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "deep-is": "^0.1.3",+ "fast-levenshtein": "^2.0.6",+ "levn": "^0.4.1",+ "prelude-ls": "^1.2.1",+ "type-check": "^0.4.0",+ "word-wrap": "^1.2.5"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-locate": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-limit": "^3.0.2"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",@@ -2187,6 +3454,26 @@"node": ">= 0.8"}},+ "node_modules/path-exists": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/path-to-regexp": {"version": "0.1.13","resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",@@ -2242,6 +3529,16 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/prelude-ls": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.8.0"+ }+ },"node_modules/proxy-addr": {"version": "2.0.8","resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",@@ -2259,6 +3556,36 @@"url": "https://opencollective.com/express"}},+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/qified": {+ "version": "0.10.1",+ "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz",+ "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hookified": "^2.1.1"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/qified/node_modules/hookified": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz",+ "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/qs": {"version": "6.16.0","resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",@@ -2488,6 +3815,29 @@"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==","license": "ISC"},+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/side-channel": {"version": "1.1.1","resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",@@ -2613,6 +3963,32 @@"node": ">=0.6"}},+ "node_modules/ts-api-utils": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",+ "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.12"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4"+ }+ },+ "node_modules/type-check": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },"node_modules/type-is": {"version": "1.6.18","resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",@@ -2626,6 +4002,51 @@"node": ">= 0.6"}},+ "node_modules/typescript": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",+ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/typescript-eslint": {+ "version": "8.71.0",+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.71.0.tgz",+ "integrity": "sha512-fBdHYiqQ14RW6mOMXD14Svn82ZsCYAoQSzGRzyEjR59S5A2Krh/l7fGTOQ7iCr8gGy/mHVXtEF7s5fgjEdV0Pw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/eslint-plugin": "8.71.0",+ "@typescript-eslint/parser": "8.71.0",+ "@typescript-eslint/typescript-estree": "8.71.0",+ "@typescript-eslint/utils": "8.71.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/unpipe": {"version": "1.0.0","resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",@@ -2666,6 +4087,16 @@"browserslist": ">= 4.21.0"}},+ "node_modules/uri-js": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "punycode": "^2.1.0"+ }+ },"node_modules/utils-merge": {"version": "1.0.1","resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",@@ -2759,12 +4190,74 @@}}},+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/word-wrap": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz","integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==","dev": true,"license": "ISC"+ },+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/zod": {+ "version": "4.6.5",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-validation-error": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz",+ "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ }}}}diff --git a/app/package.json b/app/package.jsonindex 0e14915..2fc65df 100644--- a/app/package.json+++ b/app/package.json@@ -3,10 +3,14 @@"private": true,"type": "module","scripts": {- "server": "node server/index.mjs",+ "server": "node server/index.ts","web": "vite web --port 5173","build": "vite build web --outDir ../dist --emptyOutDir",- "start": "npm run build && node server/index.mjs",+ "start": "npm run build && node server/index.ts",+ "typecheck": "tsc -p tsconfig.json && tsc -p web/tsconfig.json",+ "lint": "eslint .",+ "test": "node --test --experimental-test-module-mocks \"server/**/*.test.ts\"",+ "check": "npm run typecheck && npm run lint && npm test","doctor": "node scripts/doctor.mjs","setup": "npm install && node scripts/doctor.mjs"},@@ -16,12 +20,23 @@"opencc-js": "^1.4.2"},"devDependencies": {+ "@eslint/js": "^10.0.1",+ "@types/express": "^4.17.25",+ "@types/multer": "^2.3.0",+ "@types/node": "^22.20.4",+ "@types/react": "^18.3.31",+ "@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.3.4",+ "eslint": "^10.11.0",+ "eslint-plugin-react-hooks": "^7.1.1",+ "globals": "^17.12.0","react": "^18.3.1","react-dom": "^18.3.1",+ "typescript": "^6.0.3",+ "typescript-eslint": "^8.71.0","vite": "^6.0.7"},"engines": {- "node": ">=20"+ "node": ">=22.18"}}diff --git a/app/restart.sh b/app/restart.shindex 4b69d7c..5f4928d 100644--- a/app/restart.sh+++ b/app/restart.sh@@ -17,6 +17,6 @@ elsefuser -k $P/tcp 2>/dev/null || truefisleep 2-nohup node app/server/index.mjs > "$LOG" 2>&1 &+nohup node app/server/index.ts > "$LOG" 2>&1 &for i in $(seq 1 20); do curl -s -m 1 localhost:${PORT:-4318}/api/config >/dev/null && { echo "server up"; exit 0; }; sleep 0.5; doneecho "server did not start"; tail -20 "$LOG"; exit 1diff --git a/app/scripts/doctor.mjs b/app/scripts/doctor.mjsindex 5602d30..d726f1c 100644--- a/app/scripts/doctor.mjs+++ b/app/scripts/doctor.mjs@@ -1,30 +1,42 @@// Checks everything ReelMimic needs and says how to fix what's missing. npm run doctor-import '../server/env.mjs'; // same secrets and Python choice as the server+// Plain JavaScript on purpose: it must run (and say "upgrade Node") even on a Node too old to run the TypeScript server.+// @ts-checkimport { execFileSync } from 'node:child_process';import { existsSync, readFileSync } from 'node:fs';import { homedir, platform } from 'node:os';import { join } from 'node:path';+// The server runs its TypeScript directly (Node's built-in type stripping, on by default from 22.18).+const [major, minor] = process.versions.node.split('.').map(Number);+if (major < 22 || (major === 22 && minor < 18)) { console.log(`+ [31m✗[0m Node ${process.versions.node}: ReelMimic needs Node 22.18 or newer+ → https://nodejs.org+`); process.exit(1); }+await import('../server/env.ts'); // same secrets and Python choice as the server+const IS_WIN = platform() === 'win32';+/** @param {string} m */const ok = (m) => console.log(` \x1b[32m✓\x1b[0m ${m}`);+/** @param {string} m @param {string} [fix] */const bad = (m, fix) => { console.log(` \x1b[31m✗\x1b[0m ${m}${fix ? `\n → ${fix}` : ''}`); failed++; };+/** @param {string} m @param {string} [fix] */const opt = (m, fix) => console.log(` \x1b[33m○\x1b[0m ${m}${fix ? ` (${fix})` : ''}`);let failed = 0;// .cmd shims (claude, codex, npx) need a shell on Windows; real executables must not go through one (it would split `-c "import x"`)+/** @param {string} cmd @param {string[]} args */const run = (cmd, args, shell = IS_WIN && !/python|ffmpeg|blender/i.test(cmd)) => { try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], shell, timeout: 20000 }).trim(); } catch { return null; } };const PY = process.env.PYTHON || 'python';console.log('\nReelMimic — environment check\n');console.log('Core');-const nodeMajor = +process.versions.node.split('.')[0];-nodeMajor >= 20 ? ok(`Node ${process.versions.node}`) : bad(`Node ${process.versions.node} (need 20+)`, 'https://nodejs.org');+ok(`Node ${process.versions.node}`);const pyv = run(PY, ['--version']);pyv ? ok(pyv) : bad('Python 3.10+ not found', 'install Python, or set PYTHON=/path/to/python');const ff = run('ffmpeg', ['-version']);const ffDir = process.env.FFMPEG_DIR && existsSync(join(process.env.FFMPEG_DIR, IS_WIN ? 'ffmpeg.exe' : 'ffmpeg'));ff || ffDir ? ok(`FFmpeg ${(ff || '').split('\n')[0].split(' ')[2] || `(FFMPEG_DIR)`}`) : bad('FFmpeg not found', 'install FFmpeg and put it on PATH, or set FFMPEG_DIR');const chromes = [process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'].filter(Boolean);+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'].filter(/** @returns {p is string} */ (p) => !!p);const chrome = chromes.find((p) => existsSync(p));chrome ? ok(`Chrome ${chrome}`) : bad('Chrome/Chromium not found (renders frames headlessly)', 'install Chrome, or set CHROME_PATH');@@ -32,7 +44,7 @@ console.log('\nPython packages');const mods = [['numpy', 'numpy'], ['cv2', 'opencv-python'], ['scenedetect', 'scenedetect'], ['librosa', 'librosa'], ['PIL', 'Pillow'], ['yt_dlp', 'yt-dlp']];const optMods = [['faster_whisper', 'faster-whisper', 'lyrics auto-timing'], ['opencc', 'opencc-python-reimplemented', 'lyrics simplified→traditional']];if (pyv) {- const probe = (m) => run(PY, ['-c', `import ${m}`]) !== null;+ const probe = (/** @type {string} */ m) => run(PY, ['-c', `import ${m}`]) !== null;for (const [m, pkg] of mods) probe(m) ? ok(pkg) : bad(pkg, `${PY} -m pip install -r requirements.txt`);for (const [m, pkg, why] of optMods) probe(m) ? ok(pkg) : opt(`${pkg} not installed`, why);}@@ -47,9 +59,10 @@ if (!claude && !codex) bad('no agent CLI available', 'install Claude Code or Codconsole.log('\nOptional');const secretsPath = [join(homedir(), '.reelmimic', 'secrets.json'), join(homedir(), '.clone-studio', 'secrets.json')].find((p) => existsSync(p)) || join(homedir(), '.reelmimic', 'secrets.json');+/** @type {Record<string, unknown>} */let secrets = {};try { secrets = JSON.parse(readFileSync(secretsPath, 'utf8')); } catch {}-const has = (k) => process.env[k] || secrets[k];+const has = (/** @type {string} */ k) => process.env[k] || secrets[k];has('YATING_KEY') ? ok('YATING_KEY (Taiwan TTS voices)') : opt('YATING_KEY not set', `natural Taiwan Mandarin narration; put it in ${secretsPath}`);has('PIXABAY_KEY') ? ok('PIXABAY_KEY') : opt('PIXABAY_KEY not set', 'more stock images/music; Openverse works without a key');has('FREESOUND_KEY') ? ok('FREESOUND_KEY') : opt('FREESOUND_KEY not set', 'more sound effects');diff --git a/app/server/agents/index.test.ts b/app/server/agents/index.test.tsnew file mode 100644index 0000000..eb4aa4c--- /dev/null+++ b/app/server/agents/index.test.ts@@ -0,0 +1,67 @@+// Both CLIs' JSON streams must come out as the same normalised events.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import type { AgentEvent } from '../../shared/types.ts';+import { parseClaude, parseCodex } from './index.ts';++const run = (parse: typeof parseClaude, lines: object[]) => {+ const events: AgentEvent[] = [], st = { sessionId: null, text: '', ok: false, cost: null, lastError: '' };+ for (const l of lines) parse(l, (e) => events.push(e), st);+ return { events, st };+};++test('Claude Code stream', () => {+ const { events, st } = run(parseClaude, [+ { type: 'system', session_id: 's1' },+ { type: 'assistant', session_id: 's1', message: { content: [+ { type: 'thinking', thinking: 'plan the shots' },+ { type: 'tool_use', name: 'Bash', input: { command: 'python analyze.py ref.mp4' } },+ { type: 'text', text: 'Done.' },+ ] } },+ { type: 'result', subtype: 'success', is_error: false, result: 'All done.', total_cost_usd: 0.42 },+ ]);+ assert.deepEqual(events, [+ { type: 'session', id: 's1' },+ { type: 'thinking', text: 'plan the shots' },+ { type: 'tool', name: 'Bash', detail: 'python analyze.py ref.mp4' },+ { type: 'text', text: 'Done.' },+ ]);+ assert.equal(st.ok, true);+ assert.equal(st.text, 'All done.');+ assert.equal(st.cost, 0.42);+});++test('Claude Code error result is not ok', () => {+ const { st } = run(parseClaude, [{ type: 'result', subtype: 'error_max_turns', is_error: true }]);+ assert.equal(st.ok, false);+});++test('Codex stream', () => {+ const { events, st } = run(parseCodex, [+ { type: 'thread.started', thread_id: 't1' },+ { type: 'item.started', item: { type: 'command_execution', command: 'ls' } },+ { type: 'item.completed', item: { type: 'file_change', changes: [{ path: 'a.js' }, { path: 'b.js' }] } },+ { type: 'item.completed', item: { type: 'agent_message', text: 'Built it.' } },+ { type: 'turn.completed' },+ ]);+ assert.deepEqual(events, [+ { type: 'session', id: 't1' },+ { type: 'tool', name: 'shell', detail: 'ls' },+ { type: 'tool', name: 'edit', detail: 'a.js, b.js' },+ { type: 'text', text: 'Built it.' },+ ]);+ assert.equal(st.ok, true);+});++test('Codex failure emits an error', () => {+ const { events, st } = run(parseCodex, [{ type: 'turn.failed', error: { message: 'usage limit reached' } }]);+ assert.equal(st.ok, false);+ assert.deepEqual(events, [{ type: 'error', text: 'usage limit reached' }]);+});++test('long tool details are shortened', () => {+ const { events } = run(parseClaude, [{ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Write', input: { file_path: 'x'.repeat(300) } }] } }]);+ const e = events[0] as Extract<AgentEvent, { type: 'tool' }>;+ assert.equal(e.detail.length, 161);+ assert.ok(e.detail.endsWith('…'));+});diff --git a/app/server/agents/index.mjs b/app/server/agents/index.tssimilarity index 74%rename from app/server/agents/index.mjsrename to app/server/agents/index.tsindex 141e39c..156d1de 100644--- a/app/server/agents/index.mjs+++ b/app/server/agents/index.ts@@ -1,7 +1,7 @@// Agent adapters: run one turn of Claude Code or Codex headlessly, stream normalised events, return the session id so// the next turn continues the same conversation (the "discussion" with the user lives inside that session).//-// runAgent({ kind, cwd, prompt, sessionId, onEvent, signal }) → Promise<{ sessionId, text, ok }>+// runAgent({ kind, cwd, prompt, sessionId, onEvent, signal }) → Promise<AgentResult>//// Normalised events passed to onEvent:// { type: 'session', id } session/thread id known@@ -12,38 +12,55 @@//// The prompt always goes through stdin, so nothing user-typed is ever put on a command line.import { spawn, spawnSync } from 'node:child_process';--const IS_WIN = process.platform === 'win32';import { existsSync } from 'node:fs';import { join } from 'node:path';+import type { Readable } from 'node:stream';+import type { AgentEvent, AgentKind, AgentStatus } from '../../shared/types.ts';++const IS_WIN = process.platform === 'win32';// An old codex-cli can shadow a current one on PATH (e.g. a runtime manager's copy). Prefer CODEX_BIN, then npm's global shim.const NPM_CODEX = IS_WIN && process.env.APPDATA ? join(process.env.APPDATA, 'npm', 'codex.cmd') : null;const CODEX_BIN = process.env.CODEX_BIN || (NPM_CODEX && existsSync(NPM_CODEX) ? NPM_CODEX : 'codex');const CLAUDE_TOOLS = 'Bash,Read,Write,Edit,Glob,Grep,Skill,WebFetch,WebSearch,TodoWrite';-export function agentStatus() {- const probe = (cmd) => {+export interface AgentRun {+ kind: AgentKind;+ cwd: string;+ prompt: string;+ sessionId?: string | null;+ onEvent?: (e: AgentEvent) => void;+ signal?: AbortSignal;+}+export interface AgentResult { sessionId?: string | null; text: string; ok: boolean; code: number | null; stderr: string; lastError: string }+// Turn state while the CLI streams: filled in by the parsers, returned when the process closes+interface TurnState { sessionId?: string | null; text: string; ok: boolean; cost: number | null; lastError: string }+type Emit = (e: AgentEvent) => void;+// One line of the CLIs' JSON streams; only the fields read below+type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any++export function agentStatus(): AgentStatus {+ const probe = (cmd: string) => {const r = spawnSync(cmd, ['--version'], { shell: IS_WIN, encoding: 'utf8', timeout: 20000 });return r.status === 0 ? (r.stdout || '').trim().split('\n')[0] : null;};return { claude: probe('claude'), codex: probe(CODEX_BIN) };}-function lines(stream, onLine) {+function lines(stream: Readable, onLine: (l: string) => void) {let buf = '';stream.setEncoding('utf8');- stream.on('data', (d) => { buf += d; let i; while ((i = buf.indexOf('\n')) >= 0) { const l = buf.slice(0, i).trim(); buf = buf.slice(i + 1); if (l) onLine(l); } });+ stream.on('data', (d: string) => { buf += d; let i; while ((i = buf.indexOf('\n')) >= 0) { const l = buf.slice(0, i).trim(); buf = buf.slice(i + 1); if (l) onLine(l); } });stream.on('end', () => { if (buf.trim()) onLine(buf.trim()); });}-const short = (v, n = 160) => { const s = typeof v === 'string' ? v : JSON.stringify(v); return s.length > n ? s.slice(0, n) + '…' : s; };+const short = (v: unknown, n = 160) => { const s = typeof v === 'string' ? v : JSON.stringify(v); return s.length > n ? s.slice(0, n) + '…' : s; };-function claudeArgs(sessionId) {+function claudeArgs(sessionId?: string | null) {const a = ['-p', '--output-format', 'stream-json', '--verbose', '--permission-mode', 'acceptEdits', '--allowedTools', CLAUDE_TOOLS];if (sessionId) a.push('--resume', sessionId);return a;}-function parseClaude(obj, emit, st) {+export function parseClaude(obj: Json, emit: Emit, st: TurnState) {if (obj.session_id && obj.session_id !== st.sessionId) { st.sessionId = obj.session_id; emit({ type: 'session', id: obj.session_id }); }if (obj.type === 'assistant' && obj.message?.content) {for (const c of obj.message.content) {@@ -55,7 +72,7 @@ function parseClaude(obj, emit, st) {if (obj.type === 'result') { st.ok = obj.subtype === 'success' && !obj.is_error; if (obj.result) st.text = obj.result; st.cost = obj.total_cost_usd; }}-function codexArgs(sessionId, cwd) {+function codexArgs(sessionId: string | null | undefined, cwd: string) {// No approval prompts (headless). Codex's workspace-write sandbox can't start Chrome (spawn EPERM), and every render// needs it, so the default is full access — the same reach Claude Code gets with Bash allowed. Set CODEX_SANDBOX=// workspace-write to keep the sandbox (planning works; rendering won't). Set via -c: works for exec and resume.@@ -64,22 +81,22 @@ function codexArgs(sessionId, cwd) {...(mode === 'workspace-write' ? ['-c', 'sandbox_workspace_write.network_access=true'] : [])];return sessionId ? ['exec', 'resume', ...common, sessionId, '-'] : ['exec', ...common, '-C', cwd, '-'];}-function parseCodex(obj, emit, st) {+export function parseCodex(obj: Json, emit: Emit, st: TurnState) {const id = obj.thread_id || obj.session_id || obj.conversation_id;if (id && id !== st.sessionId) { st.sessionId = id; emit({ type: 'session', id }); }const it = obj.item;if (it && obj.type === 'item.completed' && it.type === 'agent_message' && it.text) { st.text = it.text; emit({ type: 'text', text: it.text }); }if (it && obj.type === 'item.started' && it.type === 'command_execution') emit({ type: 'tool', name: 'shell', detail: short(it.command) });if (it && obj.type === 'item.completed' && it.type === 'reasoning' && (it.text || '').trim()) emit({ type: 'thinking', text: short(it.text, 1200) });- if (it && obj.type === 'item.completed' && it.type === 'file_change') emit({ type: 'tool', name: 'edit', detail: short((it.changes || []).map((c) => c.path).join(', ')) });+ if (it && obj.type === 'item.completed' && it.type === 'file_change') emit({ type: 'tool', name: 'edit', detail: short((it.changes || []).map((c: { path: string }) => c.path).join(', ')) });if (obj.type === 'turn.completed') st.ok = true;if (obj.type === 'turn.failed' || obj.type === 'error') { st.ok = false; emit({ type: 'error', text: short(obj.error?.message || obj.message || obj, 400) }); }}-export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, signal }) {+export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, signal }: AgentRun): Promise<AgentResult> {return new Promise((resolve) => {- const st = { sessionId, text: '', ok: false, cost: null, lastError: '' };- const emit = (e) => { if (e.type === 'error') st.lastError = e.text; onEvent(e); }; // keep the last error for the job's error card+ const st: TurnState = { sessionId, text: '', ok: false, cost: null, lastError: '' };+ const emit: Emit = (e) => { if (e.type === 'error') st.lastError = e.text; onEvent(e); }; // keep the last error for the job's error cardconst isClaude = kind === 'claude';const cmd = isClaude ? 'claude' : CODEX_BIN;const args = isClaude ? claudeArgs(sessionId) : codexArgs(sessionId, cwd);@@ -87,7 +104,7 @@ export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, sigconst child = spawn(cmd, args, { cwd, shell: IS_WIN, env: { ...process.env, HYPERFRAMES_NO_TELEMETRY: '1', DO_NOT_TRACK: '1' } });if (signal) signal.addEventListener('abort', () => { try { IS_WIN ? spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F']) : child.kill('SIGTERM'); } catch {} });lines(child.stdout, (l) => {- let obj; try { obj = JSON.parse(l); } catch { return; }+ let obj: Json; try { obj = JSON.parse(l); } catch { return; }(isClaude ? parseClaude : parseCodex)(obj, emit, st);});let err = '';diff --git a/app/server/env.mjs b/app/server/env.tssimilarity index 100%rename from app/server/env.mjsrename to app/server/env.tsdiff --git a/app/server/index.mjs b/app/server/index.tssimilarity index 79%rename from app/server/index.mjsrename to app/server/index.tsindex 7d30267..6576ad2 100644--- a/app/server/index.mjs+++ b/app/server/index.ts@@ -1,12 +1,13 @@-// ReelMimic server: REST + SSE over the job machine in jobs.mjs, and static files (the built UI and project files).-// node server/index.mjs → http://localhost:4318-import './env.mjs'; // first: API keys / tool paths from ~/.reelmimic/secrets.json-import express from 'express';+// ReelMimic server: REST + SSE over the job machine in jobs.ts, and static files (the built UI and project files).+// node server/index.ts → http://localhost:4318+import './env.ts'; // first: API keys / tool paths from ~/.reelmimic/secrets.json+import express, { type Request, type Response } from 'express';import multer from 'multer';import { existsSync, mkdirSync, renameSync, unlinkSync } from 'node:fs';import { join, extname, resolve, sep } from 'node:path';-import { agentStatus } from './agents/index.mjs';-import * as J from './jobs.mjs';+import type { AgentStatus } from '../shared/types.ts';+import { agentStatus } from './agents/index.ts';+import * as J from './jobs.ts';// Ctrl+C / kill: stop the agents first (the next start marks their turns interrupted, and Retry resumes them)for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { J.stopAll(); setTimeout(() => process.exit(0), 800); });@@ -18,31 +19,32 @@ const upload = multer({ dest: join(J.PROJECTS, '.uploads'), limits: { fileSize:const slug = () => new Date().toISOString().slice(0, 10).replace(/-/g, '') + '-' + Math.random().toString(36).slice(2, 7);// multer hands over multipart filenames as latin1; browsers send UTF-8-const fileName = (f) => safeName(Buffer.from(f.originalname, 'latin1').toString('utf8'));-const safeName = (n) => n.replace(/[\\/:*?"<>|]+/g, '_').slice(0, 120);-const isUrl = (s) => /^https?:\/\/\S+$/i.test((s || '').trim());-const guard = (res, id) => { if (!/^[\w-]+$/.test(id) || !existsSync(join(J.dirOf(id), 'job.json'))) { res.status(404).json({ error: 'no such project' }); return false; } return true; };+type Upload = Express.Multer.File;+const fileName = (f: Upload) => safeName(Buffer.from(f.originalname, 'latin1').toString('utf8'));+const safeName = (n: string) => n.replace(/[\\/:*?"<>|]+/g, '_').slice(0, 120);+const isUrl = (s: string | undefined) => /^https?:\/\/\S+$/i.test((s || '').trim());+const guard = (res: Response, id: string) => { if (!/^[\w-]+$/.test(id) || !existsSync(join(J.dirOf(id), 'job.json'))) { res.status(404).json({ error: 'no such project' }); return false; } return true; };-let AGENTS = null;+let AGENTS: AgentStatus | null = null;app.get('/api/agents', (req, res) => { AGENTS = AGENTS || agentStatus(); res.json(AGENTS); });app.get('/api/projects', (req, res) => res.json(J.listJobs()));// New project: a reference (file upload or URL) + brief + agent, optional music / assets / lyrics files.app.post('/api/projects', upload.fields([{ name: 'reference', maxCount: 1 }, { name: 'inputs', maxCount: 20 }]), (req, res) => {const { url, brief = '', agent = 'claude', title } = req.body, lang = ['zh-TW', 'en', 'zh-CN'].includes(req.body.lang) ? req.body.lang : 'zh-TW';- const ref = req.files?.reference?.[0];+ const files = req.files as Record<string, Upload[]> | undefined, ref = files?.reference?.[0];if (!ref && !isUrl(url)) return res.status(400).json({ error: '請上傳參考影片或貼上影片連結' });if (!['claude', 'codex'].includes(agent)) return res.status(400).json({ error: 'agent 必須是 claude 或 codex' });if (/�/.test(brief + (title || ''))) return res.status(400).json({ error: '需求文字編碼錯誤(請用 UTF-8 送出)' });// optional review/fix round limits for this project (castRounds, chunkRounds, finalRounds: whole numbers 1–10)let settings;try { settings = Object.fromEntries(Object.entries(J.cleanRounds(req.body)).filter(([, v]) => v != null)); }- catch (e) { for (const f of Object.values(req.files || {}).flat()) try { unlinkSync(f.path); } catch {} return res.status(400).json({ error: e.message }); }+ catch (e) { for (const f of Object.values(files || {}).flat()) try { unlinkSync(f.path); } catch {} return res.status(400).json({ error: (e as Error).message }); }const id = slug();const job = J.createJob({ id, title: (title || brief.split('\n')[0] || '未命名').slice(0, 40), agent, brief, lang, settings,reference: ref ? { type: 'file', src: 'inputs/reference' + (extname(ref.originalname) || '.mp4') } : { type: 'url', src: url.trim() } });if (ref) renameSync(ref.path, join(J.dirOf(id), job.reference.src));- for (const f of req.files?.inputs || []) renameSync(f.path, join(J.dirOf(id), 'inputs', fileName(f)));+ for (const f of files?.inputs || []) renameSync(f.path, join(J.dirOf(id), 'inputs', fileName(f)));J.start(id).catch((e) => console.error(e));res.json({ id });});@@ -56,7 +58,7 @@ app.post('/api/projects/:id/inputs', upload.array('inputs', 20), async (req, resconst attach = req.query.to === 'attachments', sub = attach ? join('inputs', 'attachments') : 'inputs';mkdirSync(join(J.dirOf(req.params.id), sub), { recursive: true });const saved = [];- for (const f of req.files || []) {+ for (const f of (req.files as Upload[] | undefined) || []) {const name = (attach ? `${Date.now().toString(36)}_` : '') + fileName(f);renameSync(f.path, join(J.dirOf(req.params.id), sub, name)); saved.push(`${sub.split(sep).join('/')}/${name}`);}@@ -67,7 +69,7 @@ app.post('/api/projects/:id/inputs', upload.array('inputs', 20), async (req, resres.json({ ...J.snapshot(req.params.id), saved });});-const act = (fn) => (req, res) => {+const act = (fn: (id: string, text: string, meta: J.MessageMeta) => unknown) => (req: Request<{ id: string }>, res: Response) => {const { id } = req.params; if (!guard(res, id)) return;if (J.busy(id) && fn !== J.cancel && !(fn === J.message && J.PRE_PLAN.includes(J.load(id).stage))) return res.status(409).json({ error: 'agent 正在工作中,請等這一輪完成' });Promise.resolve(fn(id, req.body?.text, req.body?.meta || {})).catch((e) => console.error(e));@@ -95,7 +97,7 @@ app.post('/api/projects/:id/accept', act(J.accept));// Review/fix round limits for this project. Allowed any time (also while agents work): the next check uses the new value.app.post('/api/projects/:id/settings', (req, res) => {if (!guard(res, req.params.id)) return;- try { res.json(J.setRounds(req.params.id, req.body || {})); } catch (e) { res.status(400).json({ error: e.message }); }+ try { res.json(J.setRounds(req.params.id, req.body || {})); } catch (e) { res.status(400).json({ error: (e as Error).message }); }});app.get('/api/config', (req, res) => res.json(J.CONFIG));app.post('/api/projects/:id/retry', act(J.retry));@@ -106,14 +108,14 @@ app.post('/api/projects/:id/cancel', (req, res) => { if (guard(res, req.params.iapp.get('/api/projects/:id/events', (req, res) => {const { id } = req.params; if (!guard(res, id)) return;res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });- const send = (jid, ev) => { if (jid === id) res.write(`data: ${JSON.stringify(ev.type === 'job' ? { type: 'job', stage: ev.job.stage } : ev)}\n\n`); };+ const send = (jid: string, ev: J.BusEvent) => { if (jid === id) res.write(`data: ${JSON.stringify(ev.type === 'job' ? { type: 'job', stage: ev.job.stage } : ev)}\n\n`); };J.bus.on('job', send);const ping = setInterval(() => res.write(': ping\n\n'), 20000);req.on('close', () => { clearInterval(ping); J.bus.off('job', send); });});// Project files (images, video, markdown), confined to the project folder.-app.get('/files/:id/*', (req, res) => {+app.get<'/files/:id/*', { id: string; 0: string }>('/files/:id/*', (req, res) => {const { id } = req.params; if (!guard(res, id)) return;const base = resolve(J.dirOf(id)), p = resolve(base, req.params[0]);if (!p.startsWith(base + sep) || !existsSync(p)) return res.status(404).end();diff --git a/app/server/jobs.test.ts b/app/server/jobs.test.tsnew file mode 100644index 0000000..484f89f--- /dev/null+++ b/app/server/jobs.test.ts@@ -0,0 +1,112 @@+// The job machine's bookkeeping: round limits, required inputs, approval gate, restart recovery.+// Runs against a throwaway projects folder (REELMIMIC_PROJECTS), never the real one. No agent is started.+import { after, before, describe, test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const TMP = mkdtempSync(join(tmpdir(), 'reelmimic-test-'));+process.env.REELMIMIC_PROJECTS = TMP;+const J = await import('./jobs.ts');+after(() => rmSync(TMP, { recursive: true, force: true }));++let n = 0;+const newJob = (extra = {}) => J.createJob({ id: `t-${++n}`, title: 'test', agent: 'claude', brief: 'a brief', reference: { type: 'url', src: 'https://example.com/v' }, ...extra });+const writePlan = (id: string, plan: object) => writeFileSync(join(J.dirOf(id), 'plan.json'), JSON.stringify(plan));++describe('cleanRounds', () => {+ test('keeps whole numbers in range and only the keys given', () => {+ assert.deepEqual(J.cleanRounds({ castRounds: 2, finalRounds: '5', other: 9 }), { castRounds: 2, finalRounds: 5 });+ });+ test('empty or null means back to the default', () => {+ assert.deepEqual(J.cleanRounds({ chunkRounds: '', castRounds: null }), { chunkRounds: null, castRounds: null });+ });+ test('rejects out of range and fractions', () => {+ assert.throws(() => J.cleanRounds({ castRounds: 0 }), /1 to 10/);+ assert.throws(() => J.cleanRounds({ castRounds: 11 }), /1 to 10/);+ assert.throws(() => J.cleanRounds({ chunkRounds: 2.5 }), /whole number/);+ });+});++describe('project settings', () => {+ test('a new project uses the server defaults', () => {+ const { id } = newJob();+ assert.deepEqual(J.rounds(id), { castRounds: J.CONFIG.castRounds, chunkRounds: J.CONFIG.chunkRounds, finalRounds: J.CONFIG.finalRounds });+ });+ test('setRounds overrides one limit, and null resets it', () => {+ const { id } = newJob({ settings: { finalRounds: 4 } });+ assert.equal(J.rounds(id).finalRounds, 4);+ J.setRounds(id, { castRounds: 7 });+ assert.equal(J.rounds(id).castRounds, 7);+ assert.equal(J.rounds(id).finalRounds, 4);+ const snap = J.setRounds(id, { finalRounds: '' });+ assert.equal(snap.rounds.values.finalRounds, J.CONFIG.finalRounds);+ assert.equal(snap.rounds.defaults.castRounds, J.CONFIG.castRounds);+ });+});++describe('required inputs', () => {+ let id: string;+ before(() => {+ id = newJob().id;+ writePlan(id, { required_inputs: [{ id: 'lyrics', kind: 'lyrics', label: 'Lyrics' }, { id: 'logo', kind: 'image', label: 'Logo' }, { id: 'song', kind: 'audio', label: 'Song' }] });+ });+ const status = () => Object.fromEntries(J.snapshot(id).requiredInputs.map((r) => [r.id, r.status]));++ test('everything starts missing and approval is refused with 409', async () => {+ assert.deepEqual(status(), { lyrics: 'missing', logo: 'missing', song: 'missing' });+ await assert.rejects(J.approve(id), (e: Error & { code?: number }) => e.code === 409 && /Lyrics/.test(e.message));+ });+ test('waive and unwaive', () => {+ J.waive(id, 'song');+ assert.equal(status().song, 'waived');+ J.unwaive(id, 'song');+ assert.equal(status().song, 'missing');+ });+ test('a file uploaded for an item counts whatever its name', () => {+ mkdirSync(join(J.dirOf(id), 'inputs'), { recursive: true });+ writeFileSync(join(J.dirOf(id), 'inputs', 'IMG_0042.png'), '');+ assert.equal(J.provideInput(id, 'logo', ['inputs/IMG_0042.png']), true);+ assert.equal(status().logo, 'provided');+ assert.deepEqual(J.snapshot(id).requiredInputs.find((r) => r.id === 'logo')?.files, ['inputs/IMG_0042.png']);+ });+ test('an unknown item or no files is refused', () => {+ assert.equal(J.provideInput(id, 'nope', ['inputs/x.png']), false);+ assert.equal(J.provideInput(id, 'logo', []), false);+ });+ test('pasted lyrics satisfy the lyrics item', () => {+ writeFileSync(join(J.dirOf(id), 'inputs', 'lyrics.txt'), 'la la la\n');+ assert.equal(status().lyrics, 'provided');+ });+ test('a file named after the item id counts', () => {+ writeFileSync(join(J.dirOf(id), 'inputs', 'my-song.mp3'), '');+ assert.equal(status().song, 'provided');+ assert.deepEqual(J.openInputs(id), []);+ });+});++describe('restart recovery', () => {+ test('a job that was working is marked interrupted, a finished one is left alone', () => {+ const working = newJob().id, done = newJob().id;+ for (const [id, stage] of [[working, 'planning'], [done, 'done']] as const) {+ const f = join(J.dirOf(id), 'job.json');+ writeFileSync(f, JSON.stringify({ ...J.load(id), stage }));+ }+ J.recoverOrphans();+ const w = J.load(working);+ assert.equal(w.stage, 'error');+ assert.equal(w.failed, 'planning');+ assert.equal(w.chat.at(-1)?.role, 'system');+ assert.equal(J.load(done).stage, 'done');+ });+});++describe('project list', () => {+ test('lists every project, newest first', () => {+ const list = J.listJobs();+ assert.ok(list.length >= 5);+ const times = list.map((p) => p.updatedAt || '');+ assert.deepEqual(times, [...times].sort().reverse());+ });+});diff --git a/app/server/jobs.mjs b/app/server/jobs.tssimilarity index 68%rename from app/server/jobs.mjsrename to app/server/jobs.tsindex 5a1972c..2c4ea1d 100644--- a/app/server/jobs.mjs+++ b/app/server/jobs.ts@@ -9,28 +9,32 @@// → done (needs_user items never trigger a revise: they pause the job and ask the user)// Quality is checked where defects are born (each character, each chunk), not only at the end.import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync, cpSync } from 'node:fs';-import { join, relative } from 'node:path';+import { join, relative, resolve } from 'node:path';import { spawn } from 'node:child_process';import { EventEmitter } from 'node:events';-import { runAgent } from './agents/index.mjs';-import { prompts as bootPrompts } from './prompts.mjs';-// prompts.mjs is re-imported when it changes, so prompt fixes reach the next agent turn without restarting running jobs-let promptCache = { m: 0, p: bootPrompts };+import { runAgent, type AgentResult } from './agents/index.ts';+import { prompts as bootPrompts } from './prompts.ts';+import { ROUND_KEYS } from '../shared/types.ts';+import type { AgentKind, CastCharProgress, ChatMessage, ChunkProgress, Config, EngineSnapshot, Job, Lang, LogEntry, LogEvent, Need, NeedRequest, Pipeline, Plan, ProjectSummary, Reference, RequiredInput, Review, RoundKey, Rounds, Snapshot, Stage } from '../shared/types.ts';+import type { CastMember, Chunk, ChunkReview, Critique, Phase, Production, Prompts, SharedItem, ShotEntry, StepVars } from './types.ts';+export { ROUND_KEYS };+// prompts.ts is re-imported when it changes, so prompt fixes reach the next agent turn without restarting running jobs+let promptCache: { m: number; p: Prompts } = { m: 0, p: bootPrompts };async function livePrompts() {- const f = join(import.meta.dirname, 'prompts.mjs'), m = statSync(f).mtimeMs;- if (m !== promptCache.m) { try { promptCache = { m, p: (await import(`./prompts.mjs?v=${m}`)).prompts }; } catch (e) { console.error('prompts reload failed', e); } }+ const f = join(import.meta.dirname, 'prompts.ts'), m = statSync(f).mtimeMs;+ if (m !== promptCache.m) { try { promptCache = { m, p: (await import(`./prompts.ts?v=${m}`)).prompts }; } catch (e) { console.error('prompts reload failed', e); } }return promptCache.p;}export const ROOT = join(import.meta.dirname, '..', '..');-export const PROJECTS = join(ROOT, 'projects');+export const PROJECTS = process.env.REELMIMIC_PROJECTS ? resolve(process.env.REELMIMIC_PROJECTS) : join(ROOT, 'projects'); // override: tests, a second checkoutconst SCRIPTS = join(ROOT, '.claude', 'skills', 'video-clone', 'scripts');const PY = process.env.PYTHON || 'python';// A review passes when nothing it lists is a blocker (polish items are handed on, they never hold the line)-const passed = (rv) => { const L = rv.issues || []; return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!rv.pass; };-const shotPassed = (s) => { const L = s.issues || []; return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!s.pass; };+const passed = (rv: Review) => { const L = rv.issues || []; return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!rv.pass; };+const shotPassed = (s: ShotEntry) => { const L = s.issues || []; return L.length && L.every((x) => x.severity) ? !L.some((x) => x.severity !== 'polish') : !!s.pass; };-export const CONFIG = {+export const CONFIG: Config = {builders: +(process.env.BUILDERS || 6), // parallel shot builders per project (12 cores / 32 GB measured)castRounds: +(process.env.CAST_ROUNDS || 3), // cast gate: review/fix rounds before asking the userchunkRounds: +(process.env.CHUNK_ROUNDS || 3), // shot line: review/fix rounds per chunk@@ -40,12 +44,11 @@ export const CONFIG = {// Review/fix round limits: CONFIG holds the defaults; a project can set its own (job.settings), read at every check so a// change applies from the next round on. When a limit is reached the job pauses for the user instead of looping.-export const ROUND_KEYS = ['castRounds', 'chunkRounds', 'finalRounds'];export const ROUND_RANGE = { min: 1, max: 10 };-export function rounds(id) { const s = load(id).settings || {}; return Object.fromEntries(ROUND_KEYS.map((k) => [k, s[k] ?? CONFIG[k]])); }+export function rounds(id: string): Rounds { const s = load(id).settings || {}; return Object.fromEntries(ROUND_KEYS.map((k) => [k, s[k] ?? CONFIG[k]])) as Rounds; }// Validates { castRounds?, chunkRounds?, finalRounds? } (whole numbers 1–10; '' / null = back to the default). Throws on bad input.-export function cleanRounds(input = {}) {- const out = {};+export function cleanRounds(input: Record<string, unknown> = {}) {+ const out: Partial<Record<RoundKey, number | null>> = {};for (const k of ROUND_KEYS) {if (!(k in input)) continue;const raw = input[k];@@ -56,26 +59,27 @@ export function cleanRounds(input = {}) {}return out;}-export function setRounds(id, input) {+export function setRounds(id: string, input: Record<string, unknown>) {const clean = cleanRounds(input);- update(id, (x) => { const s = { ...(x.settings || {}) }; for (const [k, v] of Object.entries(clean)) { if (v == null) delete s[k]; else s[k] = v; } x.settings = s; });+ update(id, (x) => { const s = { ...(x.settings || {}) }; for (const [k, v] of Object.entries(clean) as [RoundKey, number | null][]) { if (v == null) delete s[k]; else s[k] = v; } x.settings = s; });return snapshot(id);}-export const bus = new EventEmitter(); bus.setMaxListeners(100);-const running = new Map(); // id → Set<AbortController>+export type BusEvent = { type: 'job'; job: Job } | { type: 'log'; ev: LogEvent };+export const bus = new EventEmitter<{ job: [id: string, ev: BusEvent] }>(); bus.setMaxListeners(100);+const running = new Map<string, Set<AbortController>>();// Stop every agent this server started (on shutdown), so none keeps working unseen after a restart.export function stopAll() { for (const set of running.values()) for (const ac of set) ac.abort(); }const now = () => new Date().toISOString();-export const dirOf = (id) => join(PROJECTS, id);-const jpath = (id) => join(dirOf(id), 'job.json');+export const dirOf = (id: string) => join(PROJECTS, id);+const jpath = (id: string) => join(dirOf(id), 'job.json');// System messages in the project's language (Simplified Chinese is converted from the Chinese text by the UI).-const L = (id, zh, en) => (load(id).lang === 'en' ? en : zh);-export function load(id) { return JSON.parse(readFileSync(jpath(id), 'utf8')); }-function save(job) { job.updatedAt = now(); writeFileSync(jpath(job.id), JSON.stringify(job, null, 1)); bus.emit('job', job.id, { type: 'job', job }); return job; }-function update(id, fn) { const j = load(id); fn(j); return save(j); }-function log(id, ev) {+const L = (id: string, zh: string, en: string) => (load(id).lang === 'en' ? en : zh);+export function load(id: string): Job { return JSON.parse(readFileSync(jpath(id), 'utf8')); }+function save(job: Job) { job.updatedAt = now(); writeFileSync(jpath(job.id), JSON.stringify(job, null, 1)); bus.emit('job', job.id, { type: 'job', job }); return job; }+function update(id: string, fn: (j: Job) => void) { const j = load(id); fn(j); return save(j); }+function log(id: string, ev: LogEntry) {const e = { ts: now(), ...ev }; bus.emit('job', id, { type: 'log', ev: e });try { update(id, (j) => { j.log = [...(j.log || []).slice(-600), e]; }); } catch {}// the full, uncapped record lives in logs/events.jsonl (job.json keeps only the latest 600 for the UI)@@ -92,68 +96,69 @@ export function recoverOrphans() {update(d, (x) => { x.failed = x.stage; x.stage = 'error'; x.error = L(d, '伺服器重新啟動,這一輪被中斷了(它可能已經改了部分檔案)。按「重試這一步」從目前的檔案繼續。', 'The server restarted and this turn was cut off (it may have changed some files). Click “Retry this step” to continue from the current files.'); x.chat.push({ role: 'system', text: L(d, '這一輪因為伺服器重新啟動而中斷。', 'This turn was cut off by a server restart.'), ts: now() }); });}}-const readJSON = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };-const readText = (p) => { try { return readFileSync(p, 'utf8'); } catch { return null; } };-const mtime = (p) => (existsSync(p) ? statSync(p).mtimeMs : 0);+const readJSON = <T>(p: string): T | null => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };+const readText = (p: string): string | null => { try { return readFileSync(p, 'utf8'); } catch { return null; } };+const oneOf = (v: string | null | undefined, ...L: string[]) => !!v && L.includes(v);+const mtime = (p: string) => (existsSync(p) ? statSync(p).mtimeMs : 0);// ---------- global agent slots (all projects share them) ----------// Reviews and fixes jump the queue: a defect is fixed while the builder still has it in mind, and nobody waits on a// review behind a fresh 30-minute build. New builds take whatever slots are left.-let active = 0; const waiters = [];+let active = 0; const waiters: { r: () => void; hi: boolean }[] = [];const URGENT = new Set(['cast_qa', 'cast_fix', 'shot_qa', 'fix_chunk', 'assemble', 'critique', 'revise', 'replan', 'plan', 'style']);-async function slot(phase) {+async function slot(phase: Phase) {if (active < CONFIG.maxAgentsGlobal) { active++; return; }- await new Promise((r) => { const w = { r, hi: URGENT.has(phase) }; if (w.hi) { const i = waiters.findIndex((x) => !x.hi); i < 0 ? waiters.push(w) : waiters.splice(i, 0, w); } else waiters.push(w); });+ await new Promise<void>((r) => { const w = { r, hi: URGENT.has(phase) }; if (w.hi) { const i = waiters.findIndex((x) => !x.hi); i < 0 ? waiters.push(w) : waiters.splice(i, 0, w); } else waiters.push(w); });active++;}function release() { active--; const w = waiters.shift(); if (w) w.r(); }-export function listJobs() {+export function listJobs(): ProjectSummary[] {if (!existsSync(PROJECTS)) return [];- return readdirSync(PROJECTS).filter((d) => existsSync(jpath(d))).map((d) => { const j = load(d); return { id: j.id, title: readJSON(join(dirOf(d), 'plan.json'))?.title || j.title, stage: j.stage, agent: j.agent, updatedAt: j.updatedAt, needs: (j.needs || []).length, thumb: existsSync(join(dirOf(d), 'out', 'check', 'style_1.jpg')) ? 'out/check/style_1.jpg' : existsSync(join(dirOf(d), 'analysis', 'sheet_1fps.jpg')) ? 'analysis/sheet_1fps.jpg' : null }; })+ return readdirSync(PROJECTS).filter((d) => existsSync(jpath(d))).map((d) => { const j = load(d); return { id: j.id, title: readJSON<Plan>(join(dirOf(d), 'plan.json'))?.title || j.title, stage: j.stage, agent: j.agent, updatedAt: j.updatedAt, needs: (j.needs || []).length, thumb: existsSync(join(dirOf(d), 'out', 'check', 'style_1.jpg')) ? 'out/check/style_1.jpg' : existsSync(join(dirOf(d), 'analysis', 'sheet_1fps.jpg')) ? 'analysis/sheet_1fps.jpg' : null }; }).sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));}// Everything the UI needs for one project, read straight from the contract files.-export function snapshot(id) {+export function snapshot(id: string): Snapshot {const d = dirOf(id), job = load(id);- const list = (sub, re) => { const p = join(d, sub); return existsSync(p) ? readdirSync(p).filter((f) => re.test(f)).map((f) => ({ f: `${sub}/${f}`, t: statSync(join(p, f)).mtimeMs })).sort((a, b) => b.t - a.t).map((x) => x.f) : []; };- const plan = readJSON(join(d, 'plan.json'));+ const list = (sub: string, re: RegExp) => { const p = join(d, sub); return existsSync(p) ? readdirSync(p).filter((f) => re.test(f)).map((f) => ({ f: `${sub}/${f}`, t: statSync(join(p, f)).mtimeMs })).sort((a, b) => b.t - a.t).map((x) => x.f) : []; };+ const plan = readJSON<Plan>(join(d, 'plan.json'));return {job, brief: readText(join(d, 'brief.md')),report: readJSON(join(d, 'analysis', 'report.json')), styleMd: readText(join(d, 'analysis', 'STYLE.md')), route: readJSON(join(d, 'analysis', 'route.json')),plan, storyboard: readText(join(d, 'STORYBOARD.md')), assetsMd: readText(join(d, 'assets', 'ASSETS.md')),checks: list('out/check', /\.(jpg|png)$/i).slice(0, 24), video: existsSync(join(d, 'out', 'video.mp4')) ? 'out/video.mp4' : null,critique: readJSON(join(d, 'out', 'check', 'critique.json')),- cast: { sheets: list('out/check/cast', /sheet[^/]*\.(jpg|png)$/i).slice(0, 8), review: readJSON(join(d, 'out', 'check', 'cast', 'review.json')) },+ cast: { sheets: list('out/check/cast', /sheet[^/]*\.(jpg|png)$/i).slice(0, 8), review: readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) },shots: list('out/check/shots', /_sheet\.(jpg|png)$/i).slice(0, 60),production: readJSON(join(d, 'build', 'production.json')),lyrics: readJSON(join(d, 'analysis', 'lyrics', 'subs.json')),requiredInputs: requiredInputs(id, plan, job),- rounds: { values: rounds(id), defaults: Object.fromEntries(ROUND_KEYS.map((k) => [k, CONFIG[k]])), ...ROUND_RANGE },+ rounds: { values: rounds(id), defaults: Object.fromEntries(ROUND_KEYS.map((k) => [k, CONFIG[k]])) as Rounds, ...ROUND_RANGE },inputs: list('inputs', /./),};}-export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW', settings = {} }) {+export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW', settings = {} }: { id: string; title: string; agent: AgentKind; brief: string; reference: Reference; lang?: Lang; settings?: Partial<Rounds> }) {const d = dirOf(id); mkdirSync(join(d, 'inputs'), { recursive: true }); mkdirSync(join(d, 'analysis'), { recursive: true });writeFileSync(join(d, 'brief.md'), brief || '');- const job = { id, title, agent, lang, reference, settings, stage: 'new', sessionId: null, sessions: {}, createdAt: now(), chat: [], log: [], needs: [], waived: [], pipeline: {} };+ const job: Job = { id, title, agent, lang, reference, settings, stage: 'new', sessionId: null, sessions: {}, createdAt: now(), chat: [], log: [], needs: [], waived: [], pipeline: {} };save(job);return job;}-const setStage = (id, stage, extra = {}) => update(id, (j) => Object.assign(j, { stage, ...extra }));-const chat = (id, role, text, extra = {}) => update(id, (j) => { j.chat.push({ role, text, ts: now(), ...extra }); });-const pipe = (id, fn) => update(id, (j) => { j.pipeline = j.pipeline || {}; fn(j.pipeline); });+const setStage = (id: string, stage: Stage, extra: Partial<Job> = {}) => update(id, (j) => Object.assign(j, { stage, ...extra }));+const chat = (id: string, role: ChatMessage['role'], text: string, extra: Partial<ChatMessage> = {}) => update(id, (j) => { j.chat.push({ role, text, ts: now(), ...extra }); });+const pipe = (id: string, fn: (p: Pipeline) => void) => update(id, (j) => { j.pipeline = j.pipeline || {}; fn(j.pipeline); });// ---------- required inputs (lyrics, product photos, logos…) ----------// plan.required_inputs: [{ id, kind: lyrics|audio|image|text|other, label, why }]. Satisfied by a file in inputs/ (or the// aligned lyrics), or waived by the user. Approval is blocked while any is open, so production never runs without them.-function requiredInputs(id, plan, job) {+function requiredInputs(id: string, plan: Plan | null, job: Job): RequiredInput[] {const d = dirOf(id), files = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')) : [];return (plan?.required_inputs || []).map((r) => {- let status = 'missing';+ let status: RequiredInput['status'] = 'missing';const given = (job.provided?.[r.id] || []).filter((f) => existsSync(join(d, f)));if ((job.waived || []).includes(r.id)) status = 'waived';else if (given.length) status = 'provided'; // uploaded for this item from the web app@@ -163,15 +168,15 @@ function requiredInputs(id, plan, job) {return { ...r, status, files: given };});}-export function openInputs(id) { const s = snapshot(id); return s.requiredInputs.filter((r) => r.status === 'missing'); }-export function waive(id, inputId) { update(id, (j) => { j.waived = [...new Set([...(j.waived || []), inputId])]; j.needs = (j.needs || []).filter((n) => n.input !== inputId); }); }-export function unwaive(id, inputId) { update(id, (j) => { j.waived = (j.waived || []).filter((x) => x !== inputId); }); }-export function touch(id) { update(id, () => {}); } // tell open pages to reload (e.g. after files were added)+export function openInputs(id: string) { const s = snapshot(id); return s.requiredInputs.filter((r) => r.status === 'missing'); }+export function waive(id: string, inputId: string) { update(id, (j) => { j.waived = [...new Set([...(j.waived || []), inputId])]; j.needs = (j.needs || []).filter((n) => n.input !== inputId); }); }+export function unwaive(id: string, inputId: string) { update(id, (j) => { j.waived = (j.waived || []).filter((x) => x !== inputId); }); }+export function touch(id: string) { update(id, () => {}); } // tell open pages to reload (e.g. after files were added)// Files uploaded for one required input (inputs/…): remember which item they answer, so any file name counts.// A .txt for a lyrics item is taken as the lyric text. Then time the lyrics if the music is there now.-export function provideInput(id, inputId, saved) { // records the answer now; lyric timing (≈1 min) runs in the background- const d = dirOf(id), r = (readJSON(join(d, 'plan.json'))?.required_inputs || []).find((x) => x.id === inputId);+export function provideInput(id: string, inputId: string, saved: string[]) { // records the answer now; lyric timing (≈1 min) runs in the background+ const d = dirOf(id), r = (readJSON<Plan>(join(d, 'plan.json'))?.required_inputs || []).find((x) => x.id === inputId);if (!r || !saved.length) return false;update(id, (j) => { j.provided = { ...(j.provided || {}), [inputId]: saved }; j.waived = (j.waived || []).filter((x) => x !== inputId); });const txt = r.kind === 'lyrics' && saved.find((f) => /\.txt$/i.test(f)), text = txt && !/(^|\/)lyrics\.txt$/i.test(txt) ? readText(join(d, txt)) : null;@@ -179,14 +184,14 @@ export function provideInput(id, inputId, saved) { // records the answer now;return true;}// Lyrics pasted before the music arrived are only text: time them as soon as there is audio (and again before production).-export async function alignIfReady(id) {+export async function alignIfReady(id: string): Promise<LyricsResult | null> {const d = dirOf(id);if (!existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || !musicFile(id)) return null;- return saveLyrics(id, readText(join(d, 'inputs', 'lyrics.txt')));+ return saveLyrics(id, readText(join(d, 'inputs', 'lyrics.txt')) ?? '');}// The song to time lyrics against: the plan's music file, else a file the user uploaded for an audio item, else any audio in inputs/.-function musicFile(id) {- const d = dirOf(id), plan = readJSON(join(d, 'plan.json')) || {}, job = load(id), AUD = /\.(mp3|m4a|wav|aac|flac|ogg|opus|mp4|mov|webm)$/i;+function musicFile(id: string): string | null {+ const d = dirOf(id), plan = readJSON<Plan>(join(d, 'plan.json')) || {}, job = load(id), AUD = /\.(mp3|m4a|wav|aac|flac|ogg|opus|mp4|mov|webm)$/i;if (plan.music?.file && existsSync(join(d, plan.music.file))) return plan.music.file;const audioIds = (plan.required_inputs || []).filter((r) => r.kind === 'audio').map((r) => r.id);for (const k of audioIds) for (const f of job.provided?.[k] || []) if (AUD.test(f) && existsSync(join(d, f))) return f;@@ -195,14 +200,15 @@ function musicFile(id) {}// The user pastes lyrics (their text) → inputs/lyrics.txt → timed against the plan's music section → analysis/lyrics/subs.lrc-export function saveLyrics(id, text) {+export interface LyricsResult { ok: boolean; aligned: boolean; report?: string }+export function saveLyrics(id: string, text: string): Promise<LyricsResult> {const d = dirOf(id); writeFileSync(join(d, 'inputs', 'lyrics.txt'), text.trim() + '\n');- const plan = readJSON(join(d, 'plan.json')) || {}, m = plan.music || {};+ const plan = readJSON<Plan>(join(d, 'plan.json')) || {}, m = plan.music || {};const song = musicFile(id), audio = song ? join(d, song) : null;const out = join(d, 'analysis', 'lyrics'); mkdirSync(out, { recursive: true });if (!audio) { log(id, { type: 'text', text: L(id, '歌詞已存,收到配樂後會自動對時', 'Lyrics saved; they will be timed as soon as the music arrives') }); return Promise.resolve({ ok: true, aligned: false }); }const args = [join(SCRIPTS, 'align_lyrics.py'), audio, join(d, 'inputs', 'lyrics.txt'), '--out', join(out, 'subs.lrc')];- if (m.section?.start_s != null && !/clip/i.test(song)) args.push('--start', String(m.section.start_s), '--end', String(m.section.end_s));+ if (m.section?.start_s != null && song && !/clip/i.test(song)) args.push('--start', String(m.section.start_s), '--end', String(m.section.end_s));log(id, { type: 'tool', name: 'align_lyrics.py', detail: `對時:${song}` });return new Promise((resolve) => {const p = spawn(PY, args, { cwd: ROOT, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } }); let o = '';@@ -217,7 +223,7 @@ export function saveLyrics(id, text) {}// ---------- analysis -----------function analyze(id) {+function analyze(id: string): Promise<boolean> {const j = load(id), d = dirOf(id), src = j.reference.type === 'url' ? j.reference.src : join(d, j.reference.src);setStage(id, 'analyzing');log(id, { type: 'tool', name: 'analyze.py', detail: j.reference.src });@@ -236,16 +242,18 @@ function analyze(id) {// ---------- one agent turn ----------// session: 'director' (the project's main conversation), 'fresh' (a reviewer with no stake), or any key (a builder that keeps// its own conversation across its fix rounds). Returns { ok, text } — never touches the stage; the orchestrator does.-async function turn(id, phase, vars, must, { session = 'director', who } = {}) {+interface TurnOpts { session?: string; who?: string }+interface TurnResult { ok: boolean; text?: string; missing?: string[]; stderr?: string; lastError?: string; aborted?: boolean }+async function turn<P extends Phase>(id: string, phase: P, vars: StepVars[P], must: string[], { session = 'director', who }: TurnOpts = {}): Promise<TurnResult> {const j = load(id), d = dirOf(id);- const ac = new AbortController(); if (!running.has(id)) running.set(id, new Set()); running.get(id).add(ac);+ const ac = new AbortController(); if (!running.has(id)) running.set(id, new Set()); running.get(id)!.add(ac);const p = { dir: relative(ROOT, d).replace(/\\/g, '/'), brief: readText(join(d, 'brief.md')) || '', inputs: snapshot(id).inputs, config: CONFIG, lang: j.lang || 'zh-TW', ...vars };const before = must.map((f) => mtime(join(d, f)));const sid = session === 'fresh' ? undefined : session === 'director' ? j.sessionId : (j.sessions || {})[session];const label = who || (session === 'fresh' ? 'reviewer' : session);await slot(phase);log(id, { type: 'turn', state: 'start', phase, who: label });- let r;+ let r: AgentResult;try {r = await runAgent({ kind: j.agent, cwd: ROOT, prompt: (await livePrompts())[phase](p), sessionId: sid, signal: ac.signal,onEvent: (e) => {@@ -263,7 +271,7 @@ async function turn(id, phase, vars, must, { session = 'director', who } = {}) {if (r.text) chat(id, session === 'fresh' ? 'critic' : session === 'director' ? 'agent' : 'builder', r.text, { phase, who: label });return { ok: r.ok && !missing.length, text: r.text, missing, stderr: r.stderr, lastError: r.lastError };}-function fail(id, stageName, res) {+function fail(id: string, stageName: Stage, res: TurnResult) {// an account limit is the real cause, even when it also left outputs missing: say so plainlyconst limit = [res.lastError, res.text, res.stderr].find((t) => t && /usage limit|rate limit|hit your limit|limit reached|quota|credit balance/i.test(t));if (limit && !res.aborted) {@@ -273,7 +281,7 @@ function fail(id, stageName, res) {setStage(id, 'error', { failed: stageName, error: res.aborted ? L(id, '已取消', 'Cancelled') : !res.missing?.length ? L(id, `agent 回合失敗 ${res.stderr ? ':' + res.stderr.slice(-300) : ''}`, `The agent turn failed${res.stderr ? ': ' + res.stderr.slice(-300) : ''}`) : L(id, `缺少輸出:${res.missing.join(', ')}`, `Missing output: ${res.missing.join(', ')}`) });return false;}-async function step(id, stageName, phase, vars, must, next, opts) {+async function step<P extends Phase>(id: string, stageName: Stage, phase: P, vars: StepVars[P], must: string[], next?: Stage | null, opts?: TurnOpts) {setStage(id, stageName, { error: null, failed: null });const r = await turn(id, phase, vars, must, opts);if (!r.ok) return fail(id, stageName, r);@@ -282,8 +290,8 @@ async function step(id, stageName, phase, vars, must, next, opts) {}// needs_user items (from any reviewer) pause instead of looping-function collectNeeds(id, items, from) {- const add = (items || []).filter(Boolean).map((n) => ({ ...n, from, at: now() }));+function collectNeeds(id: string, items: NeedRequest[] | undefined, from: string) {+ const add: Need[] = (items || []).filter(Boolean).map((n) => ({ ...n, from, at: now() }));if (!add.length) return 0;// a new batch from the same reviewer replaces its earlier one (the critic re-reports open items every round)update(id, (j) => { j.needs = [...(j.needs || []).filter((x) => x.from !== from && !add.some((a) => a.issue === x.issue)), ...add]; });@@ -292,7 +300,7 @@ function collectNeeds(id, items, from) {}// ---------- pre-production -----------export async function start(id) {+export async function start(id: string) {if (!(await analyze(id))) return;if (!(await step(id, 'styling', 'style', {}, ['analysis/STYLE.md', 'analysis/route.json'], 'styled'))) return;await preProduction(id);@@ -300,11 +308,11 @@ export async function start(id) {// Pre-production as a small DAG: the director writes the plan core, then every character (one agent each) and the assets// (one agent) are made at the same time, then the director merges them and paints the style frames with the real cast.-async function preProduction(id) {+async function preProduction(id: string) {const d = dirOf(id);if (!(await step(id, 'planning', 'plan', {}, ['plan.json', 'STORYBOARD.md']))) return false;- const plan = readJSON(join(d, 'plan.json')) || {};- const chars = (plan.characters || []).filter((c) => c && c.id && c.file && /^build\//.test(c.file));+ const plan = readJSON<Plan>(join(d, 'plan.json')) || {};+ const chars = (plan.characters || []).filter((c): c is typeof c & { file: string } => !!(c && c.id && c.file && /^build\//.test(c.file)));const needAssets = (plan.assets || []).some((a) => a && a.status === 'to_fetch');const work = [...chars.map((c) => turn(id, 'pre_cast', { character: c }, [c.file], { session: `cast-${c.id}`, who: `cast-${c.id}` }).then((r) => ({ what: `角色 ${c.name || c.id}`, ok: r.ok }))),@@ -318,7 +326,7 @@ async function preProduction(id) {}// Notes the user sent while the plan was being written: folded in with a replan as soon as the plan exists.-async function flushNotes(id) {+async function flushNotes(id: string): Promise<boolean> {const notes = load(id).pendingNotes || [];if (!notes.length) return true;update(id, (x) => { x.pendingNotes = []; });@@ -327,10 +335,11 @@ async function flushNotes(id) {return flushNotes(id);}-export function busy(id) { return (running.get(id)?.size || 0) > 0 || ['analyzing', 'styling', 'planning', 'replanning', 'producing', 'revising', 'critiquing'].includes(load(id).stage); }+export function busy(id: string) { return (running.get(id)?.size || 0) > 0 || ['analyzing', 'styling', 'planning', 'replanning', 'producing', 'revising', 'critiquing'].includes(load(id).stage); }-export const PRE_PLAN = ['new', 'analyzing', 'styling', 'styled', 'planning', 'replanning']; // notes allowed while busy here-export async function message(id, text, meta = {}) {+export const PRE_PLAN: Stage[] = ['new', 'analyzing', 'styling', 'styled', 'planning', 'replanning']; // notes allowed while busy here+export type MessageMeta = Pick<ChatMessage, 'shot' | 'time' | 'attachments' | 'notes'>;+export async function message(id: string, text: string, meta: MessageMeta = {}) {const j = load(id);let tagged = meta.shot ? `[鏡頭 ${meta.shot}]${text}` : meta.time != null ? `[${Number(meta.time).toFixed(1)} 秒]${text}` : text;chat(id, 'user', tagged, meta);@@ -343,24 +352,24 @@ export async function message(id, text, meta = {}) {if (['planning', 'replanning'].includes(j.stage)) update(id, (x) => { x.pendingNotes = [...(x.pendingNotes || []), tagged]; });return;}- if (j.stage === 'plan_review' || (j.stage === 'error' && ['planning', 'replanning', 'styling'].includes(j.failed))) {+ if (j.stage === 'plan_review' || (j.stage === 'error' && oneOf(j.failed, 'planning', 'replanning', 'styling'))) {if (!(await step(id, 'replanning', 'replan', { message: tagged }, ['plan.json'], 'plan_review'))) return false;return flushNotes(id);}// paused (or failed) before there is a film: the note goes back into the production line, not into "revise the film"- const prePhase = ['setup', 'cast', 'shots', 'assemble'].includes(j.pipeline?.phase);- if (prePhase && (j.stage === 'needs_input' || (j.stage === 'error' && ['producing', 'revising'].includes(j.failed)))) return productionNote(id, tagged);- if (['done', 'needs_input'].includes(j.stage) || (j.stage === 'error' && ['producing', 'revising', 'critiquing'].includes(j.failed))) {+ const prePhase = oneOf(j.pipeline?.phase, 'setup', 'cast', 'shots', 'assemble');+ if (prePhase && (j.stage === 'needs_input' || (j.stage === 'error' && oneOf(j.failed, 'producing', 'revising')))) return productionNote(id, tagged);+ if (['done', 'needs_input'].includes(j.stage) || (j.stage === 'error' && oneOf(j.failed, 'producing', 'revising', 'critiquing'))) {if (await step(id, 'revising', 'revise', { message: tagged, round: 'user' }, ['out/video.mp4', 'out/check/fixes.json'])) await finalPanel(id);}}-async function productionNote(id, msg) {+async function productionNote(id: string, msg: string) {const j = load(id), d = dirOf(id), ph = j.pipeline?.phase;update(id, (x) => { x.needs = []; x.error = null; x.failed = null; });if (ph === 'cast' || (j.pipeline?.cast && !j.pipeline.cast.pass)) {- const rv = readJSON(join(d, 'out', 'check', 'cast', 'review.json')) || {};- pipe(id, (p) => { p.cast = { ...(p.cast || {}), state: 'fixing' }; });+ const rv = readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};+ pipe(id, (p) => { p.cast = { round: 0, pass: false, ...p.cast, state: 'fixing' }; });if (!(await step(id, 'producing', 'cast_fix', { issues: rv.issues || [], round: 'user', message: msg }, ['out/check/cast/sheet.jpg', 'out/check/cast/fixes.json']))) return;pipe(id, (p) => { p.cast = { round: 0, pass: false }; }); // the gate starts over with fresh rounds} else if (ph === 'shots') {@@ -370,8 +379,8 @@ async function productionNote(id, msg) {}// Freeze the engine at approval: the render uses this snapshot, so improving a skill never changes a job mid-flight.-function snapshotEngine(id) {- const route = readJSON(join(dirOf(id), 'analysis', 'route.json')) || {}, eng = route.engine;+function snapshotEngine(id: string): EngineSnapshot | null {+ const route = readJSON<{ engine?: string }>(join(dirOf(id), 'analysis', 'route.json')) || {}, eng = route.engine;if (!eng) return null;const src = join(ROOT, '.claude', 'skills', eng), dst = join(dirOf(id), 'build', 'engine', eng);if (!existsSync(src)) return null;@@ -382,18 +391,18 @@ function snapshotEngine(id) {return info;}-export async function approve(id) {+export async function approve(id: string) {const open = openInputs(id);- if (open.length) { const e = new Error('還有需要你提供或略過的素材:' + open.map((r) => r.label || r.id).join('、')); e.code = 409; throw e; }+ if (open.length) throw Object.assign(new Error('還有需要你提供或略過的素材:' + open.map((r) => r.label || r.id).join('、')), { code: 409 });await alignIfReady(id).catch(() => null); // lyrics pasted before the music arrived: time them now, before anything is built- update(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; });+ update(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON<Plan>(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; });chat(id, 'system', L(id, `企劃已核准,開始生產:角色關 → 分段製作(每段做完立刻審)→ 組裝 → 最後評審`, 'Plan approved. Production: characters → parts built and reviewed as they finish → assembly → final review'));if (await production(id, { fresh: true })) await finalPanel(id);}// ---------- production: gates where defects are born -----------async function production(id, { fresh = false } = {}) {- const d = dirOf(id), prev = fresh ? {} : load(id).pipeline || {};+async function production(id: string, { fresh = false } = {}): Promise<boolean> {+ const d = dirOf(id), prev: Pipeline = fresh ? {} : load(id).pipeline || {};const hasSetup = !fresh && existsSync(join(d, 'build', 'production.json')) && existsSync(join(d, 'out', 'check', 'cast', 'sheet.jpg'));// 1) director: scaffold, shared assets, cast sheets, chunk plan (skipped when resuming)if (!hasSetup) {@@ -403,23 +412,23 @@ async function production(id, { fresh = false } = {}) {// 2) cast gate and 3) shot building run at the same time: shots only call the shared character definitions, so cast fixes// flow into them automatically. Shot REVIEWS wait until the cast has passed, and re-grab fresh frames first.const castP = castGate(id, prev);- const prod = readJSON(join(d, 'build', 'production.json')) || {};+ const prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};const chunks = prod.chunks || [];const old = prev.chunks || {};// a segment that stopped at its round limit already has a fresh review: resuming fixes those issues first instead of re-reviewing unchanged shots- pipe(id, (p) => { p.phase = 'shots'; p.chunks = Object.fromEntries(chunks.map((c) => [c.id, old[c.id]?.state === 'passed' ? old[c.id] : { shots: c.shots, state: 'queued', round: 0, fixFirst: !!old[c.id]?.fixFirst || old[c.id]?.state === 'failed' }])); });- const runChunk = async (c) => {- const key = `builder-${c.id}`, set = (s) => pipe(id, (p) => Object.assign(p.chunks[c.id], s));- if (load(id).pipeline.chunks[c.id].state === 'passed') return true;- const SH = join(d, 'out', 'check', 'shots'), shotFile = (sid, kind) => join(SH, `${sid}.${kind}.json`);+ pipe(id, (p) => { p.phase = 'shots'; p.chunks = Object.fromEntries(chunks.map((c): [string, ChunkProgress] => [c.id, old[c.id]?.state === 'passed' ? old[c.id] : { shots: c.shots, state: 'queued', round: 0, fixFirst: !!old[c.id]?.fixFirst || old[c.id]?.state === 'failed' }])); });+ const runChunk = async (c: Chunk): Promise<boolean> => {+ const key = `builder-${c.id}`, set = (s: Partial<ChunkProgress>) => pipe(id, (p) => Object.assign(p.chunks![c.id], s));+ if (load(id).pipeline.chunks?.[c.id]?.state === 'passed') return true;+ const SH = join(d, 'out', 'check', 'shots'), shotFile = (sid: string, kind: string) => join(SH, `${sid}.${kind}.json`);// Every shot gets its own fresh reviewer as soon as the builder marks it done (<shot>.done.json), while the builder// goes on with the next shot. Reviews still wait for the cast gate, and each one is a full review of that shot.- const reviews = {}, results = {};- const reviewShot = (sid, round) => (reviews[sid] = (async () => {+ const reviews: Record<string, Promise<boolean>> = {}, results: Record<string, { entry: ShotEntry; needs: NeedRequest[]; verified: unknown[] }> = {};+ const reviewShot = (sid: string, round: number) => (reviews[sid] = (async () => {if (!(await castP)) return false;const r = await turn(id, 'shot_qa', { chunk: c, shots: [sid], round, out: `out/check/shots/${sid}.review.json` }, [`out/check/shots/${sid}.review.json`], { session: 'fresh', who: `shot-qa-${sid}` });if (!r.ok) return false;- const rv = readJSON(shotFile(sid, 'review')) || {};+ const rv = readJSON<ChunkReview>(shotFile(sid, 'review')) || {};results[sid] = { entry: (rv.shots || []).find((x) => x.id === sid) || { id: sid, pass: !!rv.pass, issues: rv.issues || [] }, needs: rv.needs_user || [], verified: rv.verified_fixes || [] };return true;})());@@ -427,7 +436,7 @@ async function production(id, { fresh = false } = {}) {const all = c.shots.filter((x) => results[x]);writeFileSync(join(SH, `${c.id}.review.json`), JSON.stringify({ shots: all.map((x) => results[x].entry), verified_fixes: all.flatMap((x) => results[x].verified), needs_user: all.flatMap((x) => results[x].needs) }, null, 1));};- let reuse = load(id).pipeline.chunks[c.id].fixFirst && existsSync(join(SH, `${c.id}.review.json`));+ let reuse = load(id).pipeline.chunks?.[c.id]?.fixFirst && existsSync(join(SH, `${c.id}.review.json`));if (reuse) set({ fixFirst: false });if (fresh || !existsSync(join(SH, `${c.id}.done.json`))) {set({ state: 'building' });@@ -445,7 +454,7 @@ async function production(id, { fresh = false } = {}) {for (let round = 1; ; round++) {set({ state: 'reviewing', round });if (reuse) { // after a user note the latest review is still valid: fix first- const rv = readJSON(join(SH, `${c.id}.review.json`)) || {};+ const rv = readJSON<ChunkReview>(join(SH, `${c.id}.review.json`)) || {};for (const e of rv.shots || []) results[e.id] = { entry: e, needs: [], verified: [] };reuse = false;} else {@@ -456,7 +465,7 @@ async function production(id, { fresh = false } = {}) {}const needs = c.shots.flatMap((x) => results[x]?.needs || []);if (collectNeeds(id, needs, `shot-qa-${c.id}`)) { set({ state: 'needs_user' }); return false; }- const bad = c.shots.map((x) => results[x]?.entry).filter((e) => e && !shotPassed(e));+ const bad = c.shots.map((x) => results[x]?.entry).filter((e): e is ShotEntry => !!e && !shotPassed(e));if (!bad.length) { set({ state: 'passed' }); return true; }if (round >= rounds(id).chunkRounds) { set({ state: 'failed', open: bad.length }); return false; }set({ state: 'fixing' });@@ -464,7 +473,7 @@ async function production(id, { fresh = false } = {}) {if (!f.ok) { set({ state: 'error' }); return false; }// shared-file problems (rig, cast, common assets) can't be fixed by a builder: the director fixes them right now,// one at a time across segments, before this segment is reviewed again- const fx = readJSON(join(SH, `${c.id}.fixes.json`));+ const fx = readJSON<SharedItem[] | { fixes?: SharedItem[] }>(join(SH, `${c.id}.fixes.json`));const shared = (Array.isArray(fx) ? fx : fx?.fixes || []).filter((x) => x && x.status === 'shared');if (shared.length) {set({ state: 'shared_fix' });@@ -475,16 +484,16 @@ async function production(id, { fresh = false } = {}) {});if (ok) { // the builder applies the new shared feature in the same round, so the next review sees itset({ state: 'fixing' });- const g = await turn(id, 'fix_chunk', { chunk: c, bad: shared.map((x) => ({ id: x.shot, issues: [{ issue: x.issue, fix: '導演已改好共用檔,照 shared.json 的 api 套用' }] })), round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });+ const g = await turn(id, 'fix_chunk', { chunk: c, bad: shared.map((x) => ({ id: x.shot ?? '', issues: [{ issue: x.issue, fix: '導演已改好共用檔,照 shared.json 的 api 套用' }] })), round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });if (!g.ok) { set({ state: 'error' }); return false; }}}- todo = bad.map((e) => e.id).concat(shared.map((x) => x.shot)).filter((x, i, A) => x && A.indexOf(x) === i && c.shots.includes(x));+ todo = bad.map((e): string | undefined => e.id).concat(shared.map((x) => x.shot)).filter((x, i, A): x is string => !!x && A.indexOf(x) === i && c.shots.includes(x));}};- const queue = [...chunks], results = [];+ const queue = [...chunks], results: boolean[] = [];await Promise.all(Array.from({ length: Math.max(1, Math.min(CONFIG.builders, chunks.length)) }, async () => {- while (queue.length) { const c = queue.shift(); results.push(await runChunk(c)); }+ while (queue.length) { const c = queue.shift()!; results.push(await runChunk(c)); }}));if (!(await castP)) return false; // the cast gate paused for the user; built segments are keptconst j = load(id);@@ -498,19 +507,20 @@ async function production(id, { fresh = false } = {}) {// ---------- cast gate ----------// Several characters, each in its own file → one reviewer + fixer pair per character, all at once; then one line-up check.// One character, or everything in one file → the serial gate.-async function castGate(id, prev) {- const d = dirOf(id), prod = readJSON(join(d, 'build', 'production.json')) || {};+type CastResult = 'error' | 'needs' | 'passed' | 'failed' | 'shared';+async function castGate(id: string, prev: Pipeline): Promise<boolean> {+ const d = dirOf(id), prod = readJSON<Production>(join(d, 'build', 'production.json')) || {};const chars = (prod.characters || []).filter((c) => c && c.id && c.file && c.sheet);const files = new Set(chars.map((c) => c.file));const parallel = chars.length > 1 && files.size === chars.length && chars.every((c) => existsSync(join(d, c.sheet)));if (prev.cast?.pass) return true;if (!parallel) return castSerial(id, prev);- const setC = (cid, v) => pipe(id, (p) => { p.cast.chars = p.cast.chars || {}; p.cast.chars[cid] = { ...(p.cast.chars[cid] || {}), ...v }; });- const keep = prev.cast?.mode === 'parallel' ? prev.cast.chars || {} : {}; // resuming: characters that already passed stay passed- pipe(id, (p) => { p.cast = { round: 0, pass: false, state: 'reviewing', mode: 'parallel', chars: Object.fromEntries(chars.map((c) => [c.id, keep[c.id]?.state === 'passed' ? keep[c.id] : { state: 'queued', round: 0 }])) }; });+ const setC = (cid: string, v: Partial<CastCharProgress>) => pipe(id, (p) => { const cast = p.cast!; cast.chars = cast.chars || {}; cast.chars[cid] = { ...(cast.chars[cid] ?? { state: 'queued', round: 0 }), ...v }; });+ const keep: Record<string, CastCharProgress> = prev.cast?.mode === 'parallel' ? prev.cast.chars || {} : {}; // resuming: characters that already passed stay passed+ pipe(id, (p) => { p.cast = { round: 0, pass: false, state: 'reviewing', mode: 'parallel', chars: Object.fromEntries(chars.map((c): [string, CastCharProgress] => [c.id, keep[c.id]?.state === 'passed' ? keep[c.id] : { state: 'queued', round: 0 }])) }; });chat(id, 'system', L(id, `角色關:${chars.length} 個角色各自由一組審查+修正同時進行`, `Characters: reviewing and fixing ${chars.length} character${chars.length > 1 ? 's' : ''} in parallel`));- const shared = [];- const one = async (c) => {+ const shared: SharedItem[] = [];+ const one = async (c: CastMember): Promise<CastResult> => {// resuming a character that stopped at its round limit: its last review is still current, so fix those issues firstconst reuse = keep[c.id]?.state === 'failed' && existsSync(join(d, 'out', 'check', 'cast', `review_${c.id}.json`));for (let round = 1; ; round++) {@@ -519,73 +529,73 @@ async function castGate(id, prev) {const r = await turn(id, 'cast_qa', { round, character: c }, [`out/check/cast/review_${c.id}.json`], { session: 'fresh', who: `cast-qa-${c.id}` });if (!r.ok) { setC(c.id, { state: 'error' }); return 'error'; }}- const rv = readJSON(join(d, 'out', 'check', 'cast', `review_${c.id}.json`)) || {};+ const rv = readJSON<Review>(join(d, 'out', 'check', 'cast', `review_${c.id}.json`)) || {};if (collectNeeds(id, rv.needs_user, `cast-qa-${c.id}`)) { setC(c.id, { state: 'needs_user' }); return 'needs'; }if (passed(rv)) { setC(c.id, { state: 'passed' }); return 'passed'; }if (round >= rounds(id).castRounds) { setC(c.id, { state: 'failed', issues: (rv.issues || []).length }); return 'failed'; }setC(c.id, { state: 'fixing' });const f = await turn(id, 'cast_fix', { issues: rv.issues || [], round, character: c, rigFiles: prod.rig_files || [] }, [c.sheet, `out/check/cast/fixes_${c.id}.json`], { session: `cast-${c.id}`, who: `cast-${c.id}` });if (!f.ok) { setC(c.id, { state: 'error' }); return 'error'; }- const fx = readJSON(join(d, 'out', 'check', 'cast', `fixes_${c.id}.json`)) || [];+ const fx = readJSON<SharedItem[] | { fixes?: SharedItem[] }>(join(d, 'out', 'check', 'cast', `fixes_${c.id}.json`)) || [];const sh = (Array.isArray(fx) ? fx : fx.fixes || []).filter((x) => x && x.status === 'shared');if (sh.length) { shared.push(...sh.map((x) => ({ ...x, character: c.id }))); setC(c.id, { state: 'waiting_shared' }); return 'shared'; }}};- let res = await Promise.all(chars.map((c) => (keep[c.id]?.state === 'passed' ? 'passed' : one(c))));+ let res: CastResult[] = await Promise.all(chars.map((c) => (keep[c.id]?.state === 'passed' ? 'passed' : one(c))));if (res.includes('needs')) return pause(id);for (let k = 0; shared.length && k < rounds(id).castRounds; k++) { // skeleton changes: one director turn, then re-check who asked (and anyone it may affect)- pipe(id, (p) => { p.cast.state = 'fixing'; });+ pipe(id, (p) => { p.cast!.state = 'fixing'; });const f = await turn(id, 'cast_fix', { issues: [...shared], round: 'shared', shared: true }, ['out/check/cast/sheet.jpg'], { who: 'director' });if (!f.ok) return fail(id, 'producing', f);shared.length = 0;res = await Promise.all(chars.map((c, i) => (res[i] === 'passed' || res[i] === 'shared' ? one(c) : res[i])));if (res.includes('needs')) return pause(id);}- if (res.some((x) => x !== 'passed')) { pipe(id, (p) => { p.cast.state = 'failed'; p.cast.round = rounds(id).castRounds; }); chat(id, 'system', L(id, `角色關:${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join('、')} 審了 ${rounds(id).castRounds} 輪還沒通過,請你看設定圖決定`, `Characters: ${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join(', ')} still not passing after ${rounds(id).castRounds} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }+ if (res.some((x) => x !== 'passed')) { pipe(id, (p) => { p.cast!.state = 'failed'; p.cast!.round = rounds(id).castRounds; }); chat(id, 'system', L(id, `角色關:${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join('、')} 審了 ${rounds(id).castRounds} 輪還沒通過,請你看設定圖決定`, `Characters: ${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join(', ')} still not passing after ${rounds(id).castRounds} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }// every character passed on its own → one line-up check across them, then the serial gate handles anything it finds- pipe(id, (p) => { p.cast.state = 'reviewing'; p.cast.lineup = true; });+ pipe(id, (p) => { p.cast!.state = 'reviewing'; p.cast!.lineup = true; });const r = await turn(id, 'cast_qa', { round: 'lineup', lineup: true }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });if (!r.ok) return fail(id, 'producing', r);- const rv = readJSON(join(d, 'out', 'check', 'cast', 'review.json')) || {};+ const rv = readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};if (collectNeeds(id, rv.needs_user, 'cast-qa')) return pause(id);- if (passed(rv)) { pipe(id, (p) => { p.cast.pass = true; p.cast.state = 'passed'; }); chat(id, 'system', L(id, '角色關通過(每個角色各自通過+並排檢查)', 'Characters passed (each one on its own, then side by side)')); return true; }- return castSerial(id, { cast: { pass: false } }, rv);+ if (passed(rv)) { pipe(id, (p) => { p.cast!.pass = true; p.cast!.state = 'passed'; }); chat(id, 'system', L(id, '角色關通過(每個角色各自通過+並排檢查)', 'Characters passed (each one on its own, then side by side)')); return true; }+ return castSerial(id, { cast: { round: 0, pass: false } }, rv);}-async function castSerial(id, prev, firstReview) {+async function castSerial(id: string, prev: Pipeline, firstReview?: Review | null): Promise<boolean> {const d = dirOf(id);if (!prev.cast?.pass) pipe(id, (p) => { p.cast = { round: 0, pass: false }; });for (let round = 1; !load(id).pipeline.cast?.pass; round++) {- pipe(id, (p) => { p.cast.round = round; p.cast.state = 'reviewing'; });- let rv = firstReview; // the line-up check already reviewed: go straight to fixing+ pipe(id, (p) => { p.cast!.round = round; p.cast!.state = 'reviewing'; });+ let rv: Review | null | undefined = firstReview; // the line-up check already reviewed: go straight to fixingif (rv) firstReview = null;else {const r = await turn(id, 'cast_qa', { round }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });if (!r.ok) return fail(id, 'producing', r);- rv = readJSON(join(d, 'out', 'check', 'cast', 'review.json')) || {};+ rv = readJSON<Review>(join(d, 'out', 'check', 'cast', 'review.json')) || {};}if (collectNeeds(id, rv.needs_user, 'cast-qa')) return pause(id);- if (passed(rv)) { pipe(id, (p) => { p.cast.pass = true; p.cast.state = 'passed'; }); chat(id, 'system', L(id, `角色關通過(第 ${round} 輪)`, `Characters passed (round ${round})`)); break; }- if (round >= rounds(id).castRounds) { pipe(id, (p) => { p.cast.state = 'failed'; }); chat(id, 'system', L(id, `角色關 ${round} 輪仍未通過,請你看角色設定圖決定`, `Characters still not passing after ${round} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }- pipe(id, (p) => { p.cast.state = 'fixing'; });+ if (passed(rv)) { pipe(id, (p) => { p.cast!.pass = true; p.cast!.state = 'passed'; }); chat(id, 'system', L(id, `角色關通過(第 ${round} 輪)`, `Characters passed (round ${round})`)); break; }+ if (round >= rounds(id).castRounds) { pipe(id, (p) => { p.cast!.state = 'failed'; }); chat(id, 'system', L(id, `角色關 ${round} 輪仍未通過,請你看角色設定圖決定`, `Characters still not passing after ${round} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }+ pipe(id, (p) => { p.cast!.state = 'fixing'; });const f = await turn(id, 'cast_fix', { issues: rv.issues || [], round }, ['out/check/cast/sheet.jpg', 'out/check/cast/fixes.json'], { who: 'director' });if (!f.ok) return fail(id, 'producing', f);}return true;}-const sharedLocks = new Map(); // per project: one director edits shared files at a time-function sharedLock(key, fn) { const prev = sharedLocks.get(key) || Promise.resolve(); const next = prev.then(fn, fn); sharedLocks.set(key, next.catch(() => {})); return next; }+const sharedLocks = new Map<string, Promise<unknown>>(); // per project: one director edits shared files at a time+function sharedLock<T>(key: string, fn: () => Promise<T>): Promise<T> { const prev = sharedLocks.get(key) || Promise.resolve(); const next = prev.then(fn, fn); sharedLocks.set(key, next.catch(() => {})); return next; }-function pause(id) { setStage(id, 'needs_input'); return false; }+function pause(id: string) { setStage(id, 'needs_input'); return false; }// ---------- final panel: seams, continuity, pacing; verifies every earlier fix -----------async function finalPanel(id) {+async function finalPanel(id: string) {const d = dirOf(id);for (let round = 1; ; round++) {pipe(id, (p) => { p.phase = 'final'; p.final = { round }; });if (!(await step(id, 'critiquing', 'critique', { round }, ['out/check/critique.json'], null, { session: 'fresh', who: 'critic' }))) return;- const c = readJSON(join(d, 'out', 'check', 'critique.json')) || {};+ const c = readJSON<Critique>(join(d, 'out', 'check', 'critique.json')) || {};const must = (c.must_fix || []).filter(Boolean);update(id, (j) => { j.critiqueRounds = round; j.lastCritique = { pass: !must.length, must: must.length, at: now() }; });const needs = collectNeeds(id, c.needs_user, 'critic');@@ -597,7 +607,7 @@ async function finalPanel(id) {}}-export async function retry(id) {+export async function retry(id: string) {const j = load(id), f = j.failed;update(id, (x) => { x.retryPending = true; });if (f === 'analyzing') return start(id);@@ -609,18 +619,18 @@ export async function retry(id) {}// Resume after the user provided what was asked (or waived it)-export async function resume(id) { const j = load(id); update(id, (x) => { x.needs = []; }); if (existsSync(join(dirOf(id), 'out', 'video.mp4')) && j.pipeline?.phase === 'final') return finalPanel(id); if (await production(id)) await finalPanel(id); }+export async function resume(id: string) { const j = load(id); update(id, (x) => { x.needs = []; }); if (existsSync(join(dirOf(id), 'out', 'video.mp4')) && j.pipeline?.phase === 'final') return finalPanel(id); if (await production(id)) await finalPanel(id); }// The user looked at what the reviewers flagged and accepts it as is: mark the gate passed and keep going.-export async function accept(id) {+export async function accept(id: string) {const j = load(id), ph = j.pipeline?.cast && !j.pipeline.cast.pass ? 'cast' : j.pipeline?.phase;update(id, (x) => { x.needs = []; x.error = null; x.failed = null;- if (ph === 'cast') x.pipeline.cast = { ...(x.pipeline.cast || {}), pass: true, state: 'passed', acceptedByUser: true };+ if (ph === 'cast') x.pipeline.cast = { round: 0, ...x.pipeline.cast, pass: true, state: 'passed', acceptedByUser: true };if (ph === 'shots') for (const c of Object.values(x.pipeline.chunks || {})) if (c.state !== 'passed') Object.assign(c, { state: 'passed', acceptedByUser: true });x.chat.push({ role: 'system', text: ph === 'cast' ? '你接受了目前的角色設定,繼續製作鏡頭。' : '你接受了目前的鏡頭,繼續組裝。', ts: now() }); });if (ph === 'final' || (j.stage === 'done')) return;if (await production(id)) await finalPanel(id);}-export function cancel(id) { for (const ac of running.get(id) || []) ac.abort(); }-export async function critique(id) { return finalPanel(id); }+export function cancel(id: string) { for (const ac of running.get(id) || []) ac.abort(); }+export async function critique(id: string) { return finalPanel(id); }diff --git a/app/server/pipeline.test.ts b/app/server/pipeline.test.tsnew file mode 100644index 0000000..f7fe139--- /dev/null+++ b/app/server/pipeline.test.ts@@ -0,0 +1,261 @@+// The whole production line with a fake agent: every turn writes the files its step must produce (as a real agent+// would, per CONTRACT.md), and each scenario decides which reviews pass. Checks the order of steps and where it ends.+import { after, beforeEach, describe, mock, test } from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import type { AgentRun } from './agents/index.ts';++const TMP = mkdtempSync(join(tmpdir(), 'reelmimic-pipe-'));+process.env.REELMIMIC_PROJECTS = TMP;+after(() => rmSync(TMP, { recursive: true, force: true }));++// ---------- the fake agent ----------+interface Scenario {+ chars: string[]; // character ids+ chunks: { id: string; shots: string[] }[];+ castPass: (who: string, round: number) => boolean; // who: a character id, 'lineup' or 'serial'+ shotPass: (shot: string, round: number) => boolean;+ sharedFix?: (chunk: string, call: number) => boolean; // the builder reports a shared-file problem instead+ castShared?: (char: string, call: number) => boolean;+ critique: (round: number) => { must?: number; needs?: number };+ buildDelayMs?: number; // let the per-shot watcher (every 4 s) pick shots up+}+let S: Scenario;+let calls: string[] = [];+const count: Record<string, number> = {};+const bump = (k: string) => (count[k] = (count[k] || 0) + 1);++function outputs(prompt: string, dir: string): [string, Record<string, unknown>] {+ const m = (re: RegExp) => prompt.match(re);+ const json = (o: unknown) => o;+ let r: RegExpMatchArray | null;+ if (m(/## 步驟:風格拆解/)) return ['style', { 'analysis/STYLE.md': '# 2D', 'analysis/route.json': { engine: 'no-such-engine' } }];+ if (m(/## 步驟:前製企劃/)) return ['plan', { 'plan.json': { title: 'T', version: 1, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js` })) }, 'STORYBOARD.md': '# SB' }];+ if ((r = m(/## 步驟:做角色「[^」]+」[\s\S]*?只寫 (\S+?):/))) return [`pre_cast`, { [r[1]]: '// character' }];+ if (m(/## 步驟:整合前製結果/)) return ['plan_frames', { 'plan.json': { title: 'T', version: 2, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js` })) } }];+ if (m(/## 步驟:依使用者意見修改企劃/)) return ['replan', { 'plan.json': { title: 'T', version: 3 } }];+ if (m(/## 步驟:製作準備/)) return ['setup', {+ 'build/production.json': { chunks: S.chunks, characters: S.chars.map((id) => ({ id, name: id, file: `build/${id}.js`, sheet: `out/check/cast/sheet_${id}.jpg` })) },+ 'out/check/cast/sheet.jpg': 'jpg', ...Object.fromEntries(S.chars.map((id) => [`out/check/cast/sheet_${id}.jpg`, 'jpg'])) }];+ if (m(/## 步驟:角色關/)) {+ const round = +(m(/第 (\d+) 輪/)?.[1] || 1), ch = m(/結果寫到 out\/check\/cast\/review_(\S+?)\.json/)?.[1];+ const who = ch || (m(/只看並排圖/) ? 'lineup' : 'serial'), ok = S.castPass(who, round);+ return [`cast_qa:${who}`, { [ch ? `out/check/cast/review_${ch}.json` : 'out/check/cast/review.json']: json({ pass: ok, issues: ok ? [] : [{ issue: 'arm floats', severity: 'blocker' }] }) }];+ }+ if (m(/## 步驟:修角色/)) {+ const ch = m(/修正紀錄寫到 out\/check\/cast\/fixes_(\S+?)\.json/)?.[1];+ if (m(/只處理各角色 agent 回報需要改共用骨架/)) return ['cast_fix:shared', { 'out/check/cast/sheet.jpg': 'jpg' }];+ if (ch) {+ const shared = S.castShared?.(ch, bump(`cs-${ch}`));+ return [`cast_fix:${ch}`, { [`out/check/cast/sheet_${ch}.jpg`]: 'jpg', [`out/check/cast/fixes_${ch}.json`]: shared ? [{ status: 'shared', issue: 'rig neck' }] : [{ issue: 'arm', change: 'fixed' }] }];+ }+ return ['cast_fix:serial', { 'out/check/cast/sheet.jpg': 'jpg', 'out/check/cast/fixes.json': [{ issue: 'arm', change: 'fixed' }] }];+ }+ if ((r = m(/## 步驟:製作鏡頭段 (\S+?):(.+)/))) {+ const shots = r[2].trim().split('、');+ return [`build:${r[1]}`, { ...Object.fromEntries(shots.map((s) => [`out/check/shots/${s}.done.json`, { id: s }])), [`out/check/shots/${r[1]}.done.json`]: { shots: shots.map((id) => ({ id })) } }];+ }+ if ((r = m(/## 步驟:審查鏡頭 (\S+?)(屬於段落 (\S+?),第 (\d+) 輪)/))) {+ const [sid, round] = [r[1], +r[3]], ok = S.shotPass(sid, round), out = m(/寫 (out\/check\/shots\/\S+?\.review\.json)(JSON)/)![1];+ return [`shot_qa:${sid}:${round}`, { [out]: { shots: [{ id: sid, pass: ok, issues: ok ? [] : [{ issue: 'seam', severity: 'blocker' }] }] } }];+ }+ if ((r = m(/## 步驟:修鏡頭段 (\S+?)(/))) {+ const c = r[1], shared = S.sharedFix?.(c, bump(`sf-${c}`)), shot = S.chunks.find((x) => x.id === c)!.shots[0];+ return [`fix:${c}`, { [`out/check/shots/${c}.fixes.json`]: shared ? [{ status: 'shared', shot, issue: 'rig hand' }] : [{ shot, change: 'fixed' }] }];+ }+ if ((r = m(/## 步驟:修共用檔(鏡頭段 (\S+?) /))) return [`shared_fix:${r[1]}`, { [`out/check/shots/${r[1]}.shared.json`]: [{ api: 'handR' }] }];+ if (m(/## 步驟:組裝成片/)) return ['assemble', { 'out/video.mp4': 'mp4' }];+ if (m(/獨立評審/)) {+ const round = bump(`critique-${dir}`), c = S.critique(round);+ return [`critique`, { 'out/check/critique.json': { must_fix: Array.from({ length: c.must || 0 }, (_, i) => ({ shot: 'S1', issue: `must ${i}` })), needs_user: Array.from({ length: c.needs || 0 }, () => ({ kind: 'text', issue: 'confirm the lyric' })) } }];+ }+ if (m(/## 步驟:修改成片/)) return ['revise', { 'out/video.mp4': 'mp4', 'out/check/fixes.json': [{ status: 'fixed' }] }];+ throw new Error('fake agent: unknown step\n' + prompt.slice(0, 300));+}++async function fakeAgent({ cwd, prompt, onEvent }: AgentRun) {+ const dir = resolve(cwd, prompt.match(/專案資料夾:(\S+?)[(。]/)![1]);+ const [name, files] = outputs(prompt, dir);+ calls.push(name);+ if (name.startsWith('build:') && S.buildDelayMs) { // shot files first, the segment file after the delay+ const entries = Object.entries(files), last = entries.pop()!;+ for (const [f, v] of entries) put(dir, f, v);+ await new Promise((r) => setTimeout(r, S.buildDelayMs));+ put(dir, ...last);+ } else for (const [f, v] of Object.entries(files)) put(dir, f, v);+ onEvent?.({ type: 'session', id: `sess-${calls.length}` });+ return { sessionId: `sess-${calls.length}`, text: `did ${name}`, ok: true, code: 0, stderr: '', lastError: '' };+}+function put(dir: string, f: string, v: unknown) {+ const p = join(dir, f); mkdirSync(dirname(p), { recursive: true });+ writeFileSync(p, typeof v === 'string' ? v : JSON.stringify(v));+}++mock.module('./agents/index.ts', { namedExports: { runAgent: fakeAgent, agentStatus: () => ({ claude: 'fake', codex: null }) } });+const J = await import('./jobs.ts');++// ---------- helpers ----------+let n = 0;+function newProject(stage: 'plan_review' | 'error', extra: Record<string, unknown> = {}) {+ const id = `p-${++n}`;+ J.createJob({ id, title: 't', agent: 'claude', brief: 'make a video', reference: { type: 'url', src: 'https://example.com' } });+ const f = join(J.dirOf(id), 'job.json');+ writeFileSync(f, JSON.stringify({ ...J.load(id), stage, ...extra }));+ if (stage === 'plan_review') writeFileSync(join(J.dirOf(id), 'plan.json'), JSON.stringify({ title: 'T', version: 1 }));+ return id;+}+const base = (o: Partial<Scenario> = {}): Scenario => ({+ chars: ['hero'], chunks: [{ id: 'C1', shots: ['S1'] }, { id: 'C2', shots: ['S2'] }],+ castPass: () => true, shotPass: () => true, critique: () => ({}), ...o,+});+beforeEach(() => { calls = []; for (const k of Object.keys(count)) delete count[k]; });++describe('pre-production', () => {+ test('retrying a failed style step runs style → plan → characters → plan frames, then waits for approval', async () => {+ S = base({ chars: ['hero', 'cat'] });+ const id = newProject('error', { failed: 'styling' });+ await J.retry(id);+ assert.equal(J.load(id).stage, 'plan_review');+ assert.deepEqual(calls.slice(0, 2), ['style', 'plan']);+ assert.deepEqual(calls.slice(2, 4), ['pre_cast', 'pre_cast']);+ assert.equal(calls[4], 'plan_frames');+ assert.ok(existsSync(join(J.dirOf(id), 'build', 'hero.js')));+ });+});++describe('production', () => {+ test('happy path: one character, two segments, final review passes → done', async () => {+ S = base();+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'done', j.error || '');+ assert.equal(calls[0], 'setup');+ assert.ok(calls.includes('cast_qa:serial'));+ assert.deepEqual(calls.filter((c) => c.startsWith('build:')).sort(), ['build:C1', 'build:C2']);+ assert.deepEqual(calls.slice(-2), ['assemble', 'critique']);+ assert.deepEqual(Object.values(j.pipeline.chunks!).map((c) => c.state), ['passed', 'passed']);+ assert.equal(j.pipeline.cast?.pass, true);+ assert.ok(j.approvedAt);+ });++ test('failed reviews are fixed and re-reviewed: cast round 2, shot round 2, one revise', async () => {+ S = base({ castPass: (_w, r) => r >= 2, shotPass: (s, r) => s !== 'S2' || r >= 2, critique: (r) => ({ must: r === 1 ? 1 : 0 }) });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ assert.deepEqual(calls.filter((c) => c.startsWith('cast')), ['cast_qa:serial', 'cast_fix:serial', 'cast_qa:serial']);+ assert.ok(calls.indexOf('fix:C2') > calls.indexOf('shot_qa:S2:1'));+ assert.ok(calls.includes('shot_qa:S2:2'));+ assert.ok(!calls.includes('fix:C1'));+ assert.deepEqual(calls.slice(-3), ['critique', 'revise', 'critique']);+ assert.equal(J.load(id).critiqueRounds, 2);+ });++ test('shot reviews start while the builder is still working (per-shot watcher)', async () => {+ S = base({ chunks: [{ id: 'C1', shots: ['S1', 'S2'] }], buildDelayMs: 4600 });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done');+ // both shots were reviewed exactly once in round 1, not re-reviewed after the build finished+ assert.equal(calls.filter((c) => c.startsWith('shot_qa:S1:1')).length, 1);+ assert.equal(calls.filter((c) => c.startsWith('shot_qa:S2:1')).length, 1);+ });++ test('parallel cast gate: each character reviewed on its own, then one line-up check', async () => {+ S = base({ chars: ['hero', 'cat'], castPass: (w, r) => w !== 'cat' || r >= 2 });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'done', j.error || '');+ const cast = calls.filter((c) => c.startsWith('cast'));+ assert.deepEqual(cast.filter((c) => c.includes('hero')), ['cast_qa:hero']);+ assert.deepEqual(cast.filter((c) => c.includes('cat')), ['cast_qa:cat', 'cast_fix:cat', 'cast_qa:cat']);+ assert.equal(cast.at(-1), 'cast_qa:lineup');+ assert.equal(j.pipeline.cast?.mode, 'parallel');+ assert.deepEqual(Object.values(j.pipeline.cast!.chars!).map((c) => c.state), ['passed', 'passed']);+ });++ test('a character fix that needs the shared rig goes to the director, then that character is re-checked', async () => {+ S = base({ chars: ['hero', 'cat'], castPass: (w, r) => w !== 'cat' || r >= 2, castShared: (_c, call) => call === 1 });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ const i = calls.indexOf('cast_fix:shared');+ assert.ok(i > calls.indexOf('cast_fix:cat'));+ assert.ok(calls.slice(i).includes('cast_qa:cat'));+ });++ test('a shot problem in a shared file: director fixes it, builder applies it in the same round', async () => {+ S = base({ shotPass: (s, r) => s !== 'S1' || r >= 2, sharedFix: (_c, call) => call === 1 });+ const id = newProject('plan_review');+ await J.approve(id);+ assert.equal(J.load(id).stage, 'done', J.load(id).error || '');+ const seq = calls.filter((c) => /C1|S1/.test(c));+ assert.deepEqual(seq.slice(seq.indexOf('fix:C1')), ['fix:C1', 'shared_fix:C1', 'fix:C1', 'shot_qa:S1:2']);+ });+});++describe('pauses', () => {+ test('a segment that hits its round limit pauses for the user; accepting it finishes the film', async () => {+ S = base({ shotPass: (s) => s !== 'S2' });+ const id = newProject('plan_review');+ J.setRounds(id, { chunkRounds: 1 });+ await J.approve(id);+ let j = J.load(id);+ assert.equal(j.stage, 'needs_input');+ assert.equal(j.pipeline.chunks!.C2.state, 'failed');+ assert.ok(!calls.includes('assemble'));+ assert.match(j.chat.at(-1)!.text, /C2/);+ calls = [];+ await J.accept(id);+ j = J.load(id);+ assert.equal(j.stage, 'done', j.error || '');+ assert.equal(j.pipeline.chunks!.C2.acceptedByUser, true);+ assert.deepEqual(calls, ['assemble', 'critique']);+ });++ test('the cast gate stops at its round limit instead of looping', async () => {+ S = base({ castPass: () => false });+ const id = newProject('plan_review');+ J.setRounds(id, { castRounds: 2 });+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'needs_input');+ assert.equal(calls.filter((c) => c === 'cast_qa:serial').length, 2);+ assert.ok(!calls.includes('assemble'));+ });++ test('something only the user can give pauses the job and is listed as a need', async () => {+ S = base({ critique: () => ({ needs: 1 }) });+ const id = newProject('plan_review');+ await J.approve(id);+ const j = J.load(id);+ assert.equal(j.stage, 'needs_input');+ assert.equal(j.needs.length, 1);+ assert.equal(j.needs[0].from, 'critic');+ });++ test('a user note after the film is done triggers a revise and a fresh final review', async () => {+ S = base();+ const id = newProject('plan_review');+ await J.approve(id);+ calls = [];+ await J.message(id, 'make the title bigger', { time: 3.2 });+ const j = J.load(id);+ assert.equal(j.stage, 'done');+ assert.deepEqual(calls, ['revise', 'critique']);+ assert.ok(j.chat.some((c) => c.role === 'user' && c.text.startsWith('[3.2 秒]')));+ });++ test('a note during plan review replans', async () => {+ S = base();+ const id = newProject('plan_review');+ await J.message(id, 'shorter please');+ assert.deepEqual(calls, ['replan']);+ assert.equal(J.load(id).stage, 'plan_review');+ assert.equal(JSON.parse(readFileSync(join(J.dirOf(id), 'plan.json'), 'utf8')).version, 3);+ });+});diff --git a/app/server/prompts.mjs b/app/server/prompts.tssimilarity index 97%rename from app/server/prompts.mjsrename to app/server/prompts.tsindex c14c040..8ffb8a6 100644--- a/app/server/prompts.mjs+++ b/app/server/prompts.ts@@ -1,5 +1,8 @@// Phase prompts. Each agent turn does exactly one step and writes the files CONTRACT.md defines; the server advances only// when those files exist. Same prompts for Claude Code and Codex (skills are referenced by path, no Skill tool needed).+import type { Lang } from '../shared/types.ts';+import type { BaseVars, Prompts } from './types.ts';+const SKILL = '.claude/skills/video-clone';const RULES = `規則:使用者在 inputs/ 提供的自家角色可直接照著做;其他角色與畫面原創(不畫知名既有角色、他人吉祥物或品牌);@@ -7,7 +10,7 @@ const RULES = `規則:使用者在 inputs/ 提供的自家角色可直接照外部素材可以自己上網找(圖片、音效、配樂、字型、參考資料):先用 ${SKILL}/scripts/fetch_assets.py 的授權安全來源;不夠再用網路搜尋,每一個都把來源網址、作者、授權寫進 assets/ASSETS.md,授權不明的標「授權未確認」並在回報裡告訴使用者。不下載商業歌曲、不抓他人品牌 Logo 或知名角色圖。`;-const ENGINE = (p) => `企劃核准後,製作引擎已凍結成快照 ${p.dir}/build/engine/<engine>/(SNAPSHOT.json):製作一律用快照裡的 SKILL.md 與 scripts。+const ENGINE = (p: BaseVars) => `企劃核准後,製作引擎已凍結成快照 ${p.dir}/build/engine/<engine>/(SNAPSHOT.json):製作一律用快照裡的 SKILL.md 與 scripts。工具本體(.claude/skills/)是唯讀的;需要改引擎就複製到 build/ 裡改,並把「坑、修正、建議合回 skill」寫進 out/lessons.md。`;// Measured on real runs: ~60% of agent time went to screenshots (one Chrome launch per crop, retries under load) and to@@ -21,9 +24,9 @@ const SPEED = `效率規則(不能省略任何檢查,只是不浪費時間絕不可以留著背景渲染就結束回合,必須寫的輸出檔(例如 out/video.mp4)在回合結束前一定要已經存在。- 先把要看的時間點想好再一次截,不要一張一張截;改完一批問題再一次重截驗證。`;-const LANG_NAME = { 'zh-TW': '繁體中文', en: 'English', 'zh-CN': '简体中文' };+const LANG_NAME: Record<Lang, string> = { 'zh-TW': '繁體中文', en: 'English', 'zh-CN': '简体中文' };-const HEADER = (p, role = '導演') => `你是「風格克隆影片工作室」的${role} agent,工作目錄是 repo 根目錄。+const HEADER = (p: BaseVars, role = '導演') => `你是「風格克隆影片工作室」的${role} agent,工作目錄是 repo 根目錄。本專案資料夾:${p.dir}(以下路徑都相對於它,除非寫明 repo 根目錄)先讀:${SKILL}/SKILL.md(流程與規則)與 ${SKILL}/CONTRACT.md(檔案格式,必須照寫)。${process.env.PYTHON && process.env.PYTHON !== 'python' ? `這台電腦的 Python 指令是 \`${process.env.PYTHON}\`:下面(和 skill 文件)寫 python 的地方都用它執行。@@ -41,7 +44,7 @@ const EYE = `用人眼逐處檢查(一定要看全解析度的放大截圖,字不壓主體;字幕要把整張圖縮到手機寬度(約 390px 寬)也讀得出來:字高至少畫面高度 4.5%、有描邊或半透明底;沒有色帶、髒污、破圖、閃格、跳格;轉場每個接縫都有。- 動作:有預備動作與餘韻、不機械;同一鏡內造型不跳動(例如眼鏡突然變墨鏡)。`;-const QA_OUT = (file, extra = '') => `寫 ${file}(JSON):${extra}+const QA_OUT = (file: string, extra = '') => `寫 ${file}(JSON):${extra}"needs_user": [ { "kind": "lyrics|audio|image|text|other", "issue": "缺什麼、為什麼導演自己做不到" } ] ← 只有必須由使用者提供的東西才放這裡,這類不算缺陷、不要放進問題清單每個問題都要寫:鏡頭、秒數或畫面位置、看到什麼(具體)、建議怎麼改(engine 參數或畫法)。不要放「做不到的事」當問題。每個問題都要標 "severity":@@ -51,7 +54,7 @@ const QA_OUT = (file, extra = '') => `寫 ${file}(JSON):${extra}**pass = 沒有任何 blocker**(polish 照寫,會交給後面的製作 agent 順手處理,不會擋住進度)。第 2 輪以後:先核對上一輪的修正;新發現的問題只有 blocker 才能讓這一輪不通過,不要每一輪都用放大鏡找新的小毛病。`;-export const prompts = {+export const prompts: Prompts = {// ---------- pre-production ----------style: (p) => `${HEADER(p)}diff --git a/app/server/types.ts b/app/server/types.tsnew file mode 100644index 0000000..5a3c266--- /dev/null+++ b/app/server/types.ts@@ -0,0 +1,44 @@+// Server-only shapes: build/production.json (written by the director at setup) and the variables each agent step gets.+import type { Config, Issue, Lang, NeedRequest, PlanCharacter } from '../shared/types.ts';++export interface Chunk { id: string; shots: string[] }+export interface CastMember { id: string; name?: string; file: string; sheet: string }++export interface Production {+ chunks?: Chunk[];+ characters?: CastMember[];+ rig_files?: string[];+ [k: string]: unknown;+}++// A problem a builder or character agent can't fix alone because it lives in a shared file (rig, cast, common assets).+export interface SharedItem { status: 'shared'; issue: string; shot?: string; character?: string; [k: string]: unknown }+export interface ShotEntry { id: string; pass?: boolean; issues?: Issue[] }+export interface ChunkReview { shots?: ShotEntry[]; verified_fixes?: unknown[]; needs_user?: NeedRequest[]; pass?: boolean; issues?: Issue[] }+export interface Critique { must_fix?: { shot?: string; time?: number; issue: string; fix?: string }[]; needs_user?: NeedRequest[] }++type NoVars = Record<never, never>;++// Every prompt gets these…+export interface BaseVars { dir: string; brief: string; inputs: string[]; config: Config; lang: Lang }+// …plus the variables of its own step.+export interface StepVars {+ style: NoVars;+ plan: NoVars;+ pre_cast: { character: PlanCharacter };+ pre_assets: NoVars;+ plan_frames: { results: { what: string; ok: boolean }[] };+ replan: { message: string };+ setup: NoVars;+ cast_qa: { round: number | 'lineup'; character?: CastMember; lineup?: boolean };+ cast_fix: { issues: unknown[]; round: number | 'user' | 'shared'; character?: CastMember; rigFiles?: string[]; shared?: boolean; message?: string };+ build_chunk: { chunk: Chunk };+ shot_qa: { chunk: Chunk; shots: string[]; round: number; out: string };+ fix_chunk: { chunk: Chunk; bad: ShotEntry[]; round: number; message?: string | null };+ shared_fix: { chunk: Chunk; items: SharedItem[] };+ assemble: NoVars;+ critique: { round: number };+ revise: { message: string; round: number | 'user' };+}+export type Phase = keyof StepVars;+export type Prompts = { [P in Phase]: (p: BaseVars & StepVars[P]) => string };diff --git a/app/shared/types.ts b/app/shared/types.tsnew file mode 100644index 0000000..37566b6--- /dev/null+++ b/app/shared/types.ts@@ -0,0 +1,189 @@+// Shapes shared by the server and the web app: job.json, the project snapshot, live events.+// Files written by agents (plan.json, reviews, critique…) follow CONTRACT.md; only the fields the app reads are typed here.++export type AgentKind = 'claude' | 'codex';+export type Lang = 'zh-TW' | 'en' | 'zh-CN';++export type Stage =+ | 'new' | 'analyzing' | 'styling' | 'styled' | 'planning' | 'replanning' | 'plan_review'+ | 'producing' | 'critiquing' | 'revising' | 'needs_input' | 'done' | 'error';++export const ROUND_KEYS = ['castRounds', 'chunkRounds', 'finalRounds'] as const;+export type RoundKey = (typeof ROUND_KEYS)[number];+export type Rounds = Record<RoundKey, number>;++export interface Config extends Rounds {+ builders: number;+ maxAgentsGlobal: number;+}++export interface Reference { type: 'file' | 'url'; src: string }++export interface ChatMessage {+ role: 'user' | 'agent' | 'builder' | 'critic' | 'system';+ text: string;+ ts: string;+ phase?: string;+ who?: string;+ shot?: string;+ time?: number;+ attachments?: string[];+ notes?: { t: number; text: string }[]; // timed notes on the video, sent with a message+}++// Normalised agent events (agents/index.ts) plus the server's own turn and tool markers.+export type AgentEvent =+ | { type: 'session'; id: string }+ | { type: 'text'; text: string }+ | { type: 'thinking'; text: string }+ | { type: 'tool'; name: string; detail: string }+ | { type: 'error'; text: string }+ | { type: 'done'; ok: boolean; text: string; cost?: number | null };++export type TurnMarker = { type: 'turn'; state: 'start' | 'end'; phase: string; ok?: boolean };+export type LogEntry = (AgentEvent | TurnMarker) & { who?: string };+export type LogEvent = LogEntry & { ts: string };++// Something only the user can give (a file, a decision). Reviewers write these as needs_user.+export interface NeedRequest { issue: string; kind?: string; why?: string; input?: string; [k: string]: unknown }+export interface Need extends NeedRequest { from: string; at: string }++export type ChunkState =+ | 'queued' | 'building' | 'waiting_cast' | 'built' | 'reviewing' | 'fixing' | 'shared_fix'+ | 'needs_user' | 'passed' | 'failed' | 'error';++export interface ChunkProgress {+ shots?: string[];+ state: ChunkState;+ round: number;+ fixFirst?: boolean;+ open?: number;+ acceptedByUser?: boolean;+}++export type CastCharState = 'queued' | 'reviewing' | 'fixing' | 'waiting_shared' | 'needs_user' | 'passed' | 'failed' | 'error';+export interface CastCharProgress { state: CastCharState; round: number; issues?: number }++export interface CastProgress {+ round: number;+ pass: boolean;+ state?: 'reviewing' | 'fixing' | 'passed' | 'failed';+ mode?: 'parallel';+ lineup?: boolean;+ chars?: Record<string, CastCharProgress>;+ acceptedByUser?: boolean;+}++export interface Pipeline {+ phase?: 'setup' | 'cast' | 'shots' | 'assemble' | 'final';+ cast?: CastProgress;+ chunks?: Record<string, ChunkProgress>;+ final?: { round: number };+}++export interface EngineSnapshot { engine: string; frozenAt: string; path: string }++export interface Job {+ id: string;+ title: string;+ agent: AgentKind;+ lang: Lang;+ reference: Reference;+ settings: Partial<Rounds>;+ stage: Stage;+ failed?: Stage | null;+ error?: string | null;+ sessionId: string | null;+ sessions: Record<string, string>;+ createdAt: string;+ updatedAt?: string;+ chat: ChatMessage[];+ log: LogEvent[];+ needs: Need[];+ waived: string[];+ provided?: Record<string, string[]>; // required input id → files uploaded for it+ pipeline: Pipeline;+ pendingNotes?: string[];+ retryPending?: boolean;+ approvedAt?: string;+ approvedAtPrev?: boolean;+ approvedPlanVersion?: number | string;+ engineSnapshot?: EngineSnapshot | null;+ userNote?: string | null;+ critiqueRounds?: number;+ lastCritique?: { pass: boolean; must: number; at: string };+}++export type InputKind = 'lyrics' | 'audio' | 'image' | 'text' | 'other';++export interface RequiredInputSpec {+ id: string;+ kind: InputKind;+ label?: string;+ why?: string;+ file?: string;+ match?: string;+}++export interface RequiredInput extends RequiredInputSpec {+ status: 'missing' | 'provided' | 'waived';+ files: string[];+}++export interface PlanCharacter { id: string; name?: string; file?: string; [k: string]: unknown }++export interface Plan {+ title?: string;+ version?: number | string;+ required_inputs?: RequiredInputSpec[];+ music?: { file?: string; section?: { start_s?: number; end_s?: number } };+ characters?: PlanCharacter[];+ assets?: { status?: string; [k: string]: unknown }[];+ [k: string]: unknown;+}++export interface Issue { issue: string; severity?: 'blocker' | 'polish' | string; fix?: string; character?: string; what?: string; [k: string]: unknown }++export interface Review {+ pass?: boolean;+ issues?: Issue[];+ needs_user?: NeedRequest[];+ [k: string]: unknown;+}++export interface ProjectSummary {+ id: string;+ title: string;+ stage: Stage;+ agent: AgentKind;+ updatedAt?: string;+ needs: number;+ thumb: string | null;+}++// GET /api/projects/:id: everything the project page shows, read straight from the contract files.+export interface Snapshot {+ job: Job;+ brief: string | null;+ report: Record<string, unknown> | null;+ styleMd: string | null;+ route: { engine?: string; [k: string]: unknown } | null;+ plan: Plan | null;+ storyboard: string | null;+ assetsMd: string | null;+ checks: string[];+ video: string | null;+ critique: Record<string, unknown> | null;+ cast: { sheets: string[]; review: Review | null };+ shots: string[];+ production: Record<string, unknown> | null;+ lyrics: unknown;+ requiredInputs: RequiredInput[];+ rounds: { values: Rounds; defaults: Rounds; min: number; max: number };+ inputs: string[];+}++// Server-Sent Events on /api/projects/:id/events+export type ServerEvent = { type: 'job'; stage: Stage } | { type: 'log'; ev: LogEvent };++export type AgentStatus = Record<AgentKind, string | null>;diff --git a/app/tsconfig.base.json b/app/tsconfig.base.jsonnew file mode 100644index 0000000..3df07e8--- /dev/null+++ b/app/tsconfig.base.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2023",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "strict": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "erasableSyntaxOnly": true,+ "isolatedModules": true,+ "noFallthroughCasesInSwitch": true,+ "noImplicitOverride": true,+ "forceConsistentCasingInFileNames": true,+ "skipLibCheck": true+ }+}diff --git a/app/tsconfig.json b/app/tsconfig.jsonnew file mode 100644index 0000000..ae579f1--- /dev/null+++ b/app/tsconfig.json@@ -0,0 +1,10 @@+{+ // Server, scripts and shared types. Runs on Node's built-in type stripping (no build step); `tsc` only checks.+ "extends": "./tsconfig.base.json",+ "compilerOptions": {+ "lib": ["ES2023"],+ "types": ["node"],+ "allowJs": true+ },+ "include": ["server", "scripts", "shared"]+}diff --git a/app/web/index.html b/app/web/index.htmlindex de0f25c..f2832ec 100644--- a/app/web/index.html+++ b/app/web/index.html@@ -10,6 +10,6 @@</head><body><div id="root"></div>-<script type="module" src="/src/main.jsx"></script>+<script type="module" src="/src/main.tsx"></script></body></html>diff --git a/app/web/src/App.jsx b/app/web/src/App.tsxsimilarity index 77%rename from app/web/src/App.jsxrename to app/web/src/App.tsxindex 11807d6..6611a44 100644--- a/app/web/src/App.jsx+++ b/app/web/src/App.tsx@@ -1,18 +1,20 @@import React, { useEffect, useMemo, useRef, useState } from 'react';-import { api } from './api.js';-import { I, BrandMark, Orb, Seg, AutoText, ago, RoundsEditor } from './ui.jsx';-import { Project, Status } from './Project.jsx';-import { LANGS, lang as initialLang, setLang } from './i18n.js';+import type { AgentKind, AgentStatus, ProjectSummary, Rounds } from '../../shared/types.ts';+import { api } from './api.ts';+import { I, BrandMark, Orb, Seg, AutoText, ago, RoundsEditor } from './ui.tsx';+import type { IconName, RoundValues } from './ui.tsx';+import { Project, Status } from './Project.tsx';+import { LANGS, lang as initialLang, setLang } from './i18n.ts';// ---------- router & theme -----------const useRoute = () => {+const useRoute = (): { page: 'project'; id: string } | { page: 'home'; id?: undefined } => {const [h, setH] = useState(location.hash);useEffect(() => { const f = () => { setH(location.hash); scrollTo(0, 0); }; addEventListener('hashchange', f); return () => removeEventListener('hashchange', f); }, []);const m = h.match(/^#\/p\/([\w-]+)/);return m ? { page: 'project', id: m[1] } : { page: 'home' };};-const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } }, set: (k, v) => { try { localStorage.setItem(k, v); } catch {} } };-function useTheme() {+const store = { get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } }, set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch {} } };+function useTheme(): [string, () => void] {const sys = () => (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');const [t, setT] = useState(() => store.get('theme') || sys());useEffect(() => { document.documentElement.dataset.theme = t; }, [t]);@@ -21,7 +23,7 @@ function useTheme() {export default function App() {const r = useRoute(), [theme, toggle] = useTheme();- const [agents, setAgents] = useState(undefined);+ const [agents, setAgents] = useState<Partial<AgentStatus> | undefined>(undefined);useEffect(() => { api.agents().then(setAgents).catch(() => setAgents({})); }, []);return (<>@@ -42,9 +44,9 @@ export default function App() {// ---------- language menu (top right) ----------function LangMenu() {- const [cur, setCur] = useState(initialLang), [open, setOpen] = useState(false), ref = useRef();- useEffect(() => { const f = (e) => ref.current && !ref.current.contains(e.target) && setOpen(false); addEventListener('mousedown', f); return () => removeEventListener('mousedown', f); }, []);- const L = LANGS.find((l) => l.id === cur);+ const [cur, setCur] = useState(initialLang), [open, setOpen] = useState(false), ref = useRef<HTMLDivElement>(null);+ useEffect(() => { const f = (e: MouseEvent) => ref.current && !ref.current.contains(e.target as Node) && setOpen(false); addEventListener('mousedown', f); return () => removeEventListener('mousedown', f); }, []);+ const L = LANGS.find((l) => l.id === cur)!;return (<div className="lang" ref={ref} data-no-i18n><button className="lang-btn" onClick={() => setOpen(!open)} aria-haspopup="listbox" aria-expanded={open} title="Language / 介面語言"><I n="globe" /><span>{L.short}</span></button>@@ -57,10 +59,10 @@ function LangMenu() {// ---------- home ----------const SUGGEST = ['做一支類似風格的 30 秒影片,主軸是愛情,要有好笑的反轉', '同樣的剪法,改成介紹我們的新 App', '保留節奏和轉場,主題換成親情,直式 9:16', '把我的小故事畫成 Q 版漫畫,第一人稱旁白'];-const HOW = [['scan', '拆解風格', '剪法、節奏、轉場、畫面語言逐鏡量測'], ['wand', '選製作技能', '判斷畫風,交給對應的製作 skill'], ['film', '前製企劃', '分鏡、運鏡、素材、定調畫面,和你來回對焦'], ['check', '關卡審查', '角色、每一段都即時檢查,過關才往下做']];+const HOW: [IconName, string, string][] = [['scan', '拆解風格', '剪法、節奏、轉場、畫面語言逐鏡量測'], ['wand', '選製作技能', '判斷畫風,交給對應的製作 skill'], ['film', '前製企劃', '分鏡、運鏡、素材、定調畫面,和你來回對焦'], ['check', '關卡審查', '角色、每一段都即時檢查,過關才往下做']];-function Home({ agents }) {- const [list, setList] = useState(null);+function Home({ agents }: { agents?: Partial<AgentStatus> }) {+ const [list, setList] = useState<ProjectSummary[] | null>(null);useEffect(() => { api.projects().then((l) => setList(l.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || '')))).catch(() => setList([])); }, []);return (<main className="home">@@ -75,7 +77,7 @@ function Home({ agents }) {<div className="section-title"><h2>專案</h2><span className="small faint">{list.length}</span></div><div className="plist">{list.map((p, i) => (<a key={p.id} className="pcard fade-in" onMouseEnter={(e) => { const v = e.currentTarget.querySelector('video'); if (v) { v.currentTime = 3; v.play().catch(() => {}); } }} onMouseLeave={(e) => e.currentTarget.querySelector('video')?.pause()} style={{ animationDelay: `${Math.min(i, 8) * 40}ms` }} href={`#/p/${p.id}`}>- <div className="th" style={{ backgroundImage: p.thumb ? `url(${api.file(p.id, p.thumb)})` : undefined }}>{p.stage === 'done' && <video muted loop playsInline preload="none" src={api.file(p.id, 'out/video.mp4')} onError={(e) => e.target.remove()} />}<Status stage={p.stage} /></div>+ <div className="th" style={{ backgroundImage: p.thumb ? `url(${api.file(p.id, p.thumb)})` : undefined }}>{p.stage === 'done' && <video muted loop playsInline preload="none" src={api.file(p.id, 'out/video.mp4')} onError={(e) => e.currentTarget.remove()} />}<Status stage={p.stage} /></div><div className="meta"><b>{p.title}</b><div className="small faint" style={{ marginTop: 2 }}>{p.agent === 'codex' ? 'Codex' : 'Claude Code'} · {ago(p.updatedAt)}{p.needs ? ` · ${p.needs} 項待你提供` : ''}</div></div></a>))}</div></section>}@@ -83,21 +85,21 @@ function Home({ agents }) {);}-const ytId = (u) => (u.match(/(?:v=|youtu\.be\/|shorts\/|embed\/)([\w-]{11})/) || [])[1];-function Composer({ agents }) {- const [file, setFile] = useState(null), [url, setUrl] = useState(''), [linkMode, setLinkMode] = useState(false);- const [brief, setBrief] = useState(''), [agent, setAgent] = useState('claude'), [inputs, setInputs] = useState([]);+const ytId = (u: string) => (u.match(/(?:v=|youtu\.be\/|shorts\/|embed\/)([\w-]{11})/) || [])[1];+function Composer({ agents }: { agents?: Partial<AgentStatus> }) {+ const [file, setFile] = useState<File | null>(null), [url, setUrl] = useState(''), [linkMode, setLinkMode] = useState(false);+ const [brief, setBrief] = useState(''), [agent, setAgent] = useState<AgentKind>('claude'), [inputs, setInputs] = useState<File[]>([]);const [drag, setDrag] = useState(false), [busy, setBusy] = useState(false), [err, setErr] = useState('');- const [rounds, setRounds] = useState({}), [roundsOpen, setRoundsOpen] = useState(false), [defaults, setDefaults] = useState(null);+ const [rounds, setRounds] = useState<RoundValues>({}), [roundsOpen, setRoundsOpen] = useState(false), [defaults, setDefaults] = useState<Rounds | null>(null);useEffect(() => { api.config().then((c) => setDefaults({ castRounds: c.castRounds, chunkRounds: c.chunkRounds, finalRounds: c.finalRounds })).catch(() => {}); }, []);const customRounds = Object.entries(rounds).filter(([, v]) => v != null);- const pick = useRef(), assets = useRef();+ const pick = useRef<HTMLInputElement>(null), assets = useRef<HTMLInputElement>(null);const preview = useMemo(() => (file ? URL.createObjectURL(file) : null), [file]);- useEffect(() => () => preview && URL.revokeObjectURL(preview), [preview]);+ useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]);useEffect(() => { if (agents && !agents.claude && agents.codex) setAgent('codex'); }, [agents]);const validUrl = /^https?:\/\//.test(url.trim());const ok = (file || validUrl) && brief.trim() && !busy;- const setVideo = (f) => { if (f && f.type.startsWith('video/')) { setFile(f); setUrl(''); setLinkMode(false); setErr(''); } else if (f) setErr('請選擇影片檔(mp4 / mov / webm)'); };+ const setVideo = (f: File | null | undefined) => { if (f && f.type.startsWith('video/')) { setFile(f); setUrl(''); setLinkMode(false); setErr(''); } else if (f) setErr('請選擇影片檔(mp4 / mov / webm)'); };const submit = async () => {if (!ok) return; setBusy(true); setErr('');const f = new FormData();@@ -105,13 +107,13 @@ function Composer({ agents }) {f.append('brief', brief); f.append('agent', agent); f.append('lang', document.documentElement.lang || 'zh-TW');inputs.forEach((x) => f.append('inputs', x));customRounds.forEach(([k, v]) => f.append(k, String(v)));- try { const { id } = await api.create(f); location.hash = `#/p/${id}`; } catch (e) { setErr(e.message); setBusy(false); }+ try { const { id } = await api.create(f); location.hash = `#/p/${id}`; } catch (e) { setErr((e as Error).message); setBusy(false); }};const yt = ytId(url);return (<><div className={`composer fade-in ${drag ? 'drag' : ''}`} style={{ animationDelay: '80ms' }}- onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget)) setDrag(false); }}+ onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDrag(false); }}onDrop={(e) => { e.preventDefault(); setDrag(false); setVideo(e.dataTransfer.files[0]); }}>{file ? (<div className="ref-slot">@@ -124,21 +126,21 @@ function Composer({ agents }) {{validUrl && <div className="ref-slot fade-in"><div className="ref-thumb">{yt ? <img src={`https://i.ytimg.com/vi/${yt}/hqdefault.jpg`} alt="" /> : <I n="globe" />}</div><div className="ref-meta"><span className="eyebrow">參考影片連結</span><b>{yt ? `YouTube · ${yt}` : url}</b><span className="small faint">建立專案時自動下載</span></div></div>}</>) : (- <div className="ref-empty" onClick={() => pick.current.click()}>+ <div className="ref-empty" onClick={() => pick.current!.click()}><div className="big-ico"><I n="film" /></div><div className="grow"><b>拖入參考影片,或點擊選擇</b><span className="small">mp4 / mov / webm,手機螢幕錄影也可以(會自動裁掉介面)</span></div><button className="btn sm" onClick={(e) => { e.stopPropagation(); setLinkMode(true); }}><I n="link" />貼連結</button></div>)}- <input ref={pick} type="file" accept="video/*" hidden onChange={(e) => setVideo(e.target.files[0])} />+ <input ref={pick} type="file" accept="video/*" hidden onChange={(e) => setVideo(e.target.files![0])} /><AutoText minRows={3} placeholder="你想做什麼樣的影片?主題、長度、角色、想保留參考片的哪些地方…" value={brief} onChange={(e) => setBrief(e.target.value)}onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submit(); }} /><div className="comp-bar">- {file && <button className="tool-chip" onClick={() => pick.current.click()}><I n="retry" />換影片</button>}+ {file && <button className="tool-chip" onClick={() => pick.current!.click()}><I n="retry" />換影片</button>}{file && <button className="tool-chip" onClick={() => setFile(null)}><I n="x" />移除</button>}- <button className={`tool-chip ${inputs.length ? 'on' : ''}`} onClick={() => assets.current.click()} title="配樂、歌詞、圖片、Logo、自家角色設計圖">+ <button className={`tool-chip ${inputs.length ? 'on' : ''}`} onClick={() => assets.current!.click()} title="配樂、歌詞、圖片、Logo、自家角色設計圖"><I n="clip" />素材{inputs.length > 0 && <span className="n">{inputs.length}</span>}</button>- <input ref={assets} type="file" multiple hidden onChange={(e) => setInputs([...e.target.files])} />+ <input ref={assets} type="file" multiple hidden onChange={(e) => setInputs([...e.target.files!])} />{defaults && <button className={`tool-chip ${customRounds.length ? 'on' : ''}`} onClick={() => setRoundsOpen(!roundsOpen)} aria-expanded={roundsOpen} title="每一關最多審查、修改幾輪"><I n="sliders" />審查輪數{customRounds.length > 0 && <span className="n">{customRounds.length}</span>}</button>}<span className="grow" />diff --git a/app/web/src/Chat.jsx b/app/web/src/Chat.tsxsimilarity index 72%rename from app/web/src/Chat.jsxrename to app/web/src/Chat.tsxindex 18f576f..78d6370 100644--- a/app/web/src/Chat.jsx+++ b/app/web/src/Chat.tsx@@ -1,9 +1,12 @@import React, { useEffect, useMemo, useRef, useState } from 'react';-import { api } from './api.js';-import { I, Orb, Md, AutoText, Seg, useNow, dur, clock } from './ui.jsx';+import type { ChatMessage, Job, LogEvent, Stage } from '../../shared/types.ts';+import { api } from './api.ts';+import { I, Orb, Md, AutoText, Seg, useNow, dur, clock } from './ui.tsx';+import type { IconName } from './ui.tsx';+import type { MessageMeta, SnapshotView, Tag } from './types.ts';// ---------- who is talking -----------export const whoName = (w) => {+export const whoName = (w?: string) => {if (!w || w === '_') return '系統';if (w === 'director') return 'AI 導演';if (w === 'critic') return '獨立評審';@@ -16,16 +19,20 @@ export const whoName = (w) => {m = w.match(/^shot-qa-(.+)/); if (m) return `鏡頭審查 ${m[1]}`;return w;};-const whoKind = (w, role) => (role === 'builder' || /^builder|^cast-(?!qa)/.test(w || '') ? 'builder' : role === 'critic' || /qa|critic|reviewer/.test(w || '') ? 'critic' : 'director');-const PHASE_DO = { pre_cast: '設計角色', pre_assets: '抓素材', plan_frames: '整合素材、畫定調畫面', style: '判斷風格與製作技能', plan: '寫企劃核心(分鏡、旁白、素材清單)', replan: '修改企劃', setup: '建置角色與共用素材', cast_qa: '檢查角色設定圖', cast_fix: '修正角色', build_chunk: '製作鏡頭', shot_qa: '逐格檢查鏡頭', fix_chunk: '修正鏡頭', assemble: '組裝成片', critique: '審片', revise: '修改成片' };-export const STAGE_DO = { analyzing: '拆解參考片', styling: '判斷風格與製作技能', planning: '寫前製企劃', replanning: '修改企劃', producing: '生產中', revising: '修改成片', critiquing: '審片' };+type Kind = 'builder' | 'critic' | 'director';+const whoKind = (w: string | undefined, role: ChatMessage['role']): Kind => (role === 'builder' || /^builder|^cast-(?!qa)/.test(w || '') ? 'builder' : role === 'critic' || /qa|critic|reviewer/.test(w || '') ? 'critic' : 'director');+const PHASE_DO: Record<string, string> = { pre_cast: '設計角色', pre_assets: '抓素材', plan_frames: '整合素材、畫定調畫面', style: '判斷風格與製作技能', plan: '寫企劃核心(分鏡、旁白、素材清單)', replan: '修改企劃', setup: '建置角色與共用素材', cast_qa: '檢查角色設定圖', cast_fix: '修正角色', build_chunk: '製作鏡頭', shot_qa: '逐格檢查鏡頭', fix_chunk: '修正鏡頭', assemble: '組裝成片', critique: '審片', revise: '修改成片' };+export const STAGE_DO: Partial<Record<Stage, string>> = { analyzing: '拆解參考片', styling: '判斷風格與製作技能', planning: '寫前製企劃', replanning: '修改企劃', producing: '生產中', revising: '修改成片', critiquing: '審片' };// ---------- merge chat + activity log: each AI message gets the steps that led to it; unfinished work becomes live cards -----------export function buildThread(job) {+// one agent's turn: the steps it took, open until the turn ends or it replies+export type Turn = { start: string; steps: LogEvent[]; phase?: string; who: string; ended?: string; ok?: boolean; last?: string };+export type Think = Turn & { end: string };+export function buildThread(job: Job) {const chat = job.chat || [], log = job.log || [];- const items = [...chat.map((m) => ({ k: 'm', ts: m.ts || '', m })), ...log.map((e) => ({ k: 'e', ts: e.ts || '', e }))]+ const items = [...chat.map((m) => ({ k: 'm' as const, ts: m.ts || '', m })), ...log.map((e) => ({ k: 'e' as const, ts: e.ts || '', e }))].sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.k === 'e' ? -1 : 1));- const buf = {}, out = [];+ const buf: Record<string, Turn> = {}, out: { m: ChatMessage; think?: Think | null }[] = [];for (const it of items) {if (it.k === 'e') {const e = it.e, w = e.who || '_';@@ -55,30 +62,33 @@ export function buildThread(job) {}// ---------- steps -----------const TOOL = {+const TOOL: Record<string, [IconName, string]> = {Bash: ['term', '執行'], shell: ['term', '執行'], PowerShell: ['term', '執行'], Read: ['doc', '閱讀'], Write: ['pencil', '寫入'], Edit: ['pencil', '修改'],MultiEdit: ['pencil', '修改'], edit: ['pencil', '修改'], Glob: ['search', '尋找檔案'], Grep: ['search', '搜尋'], Skill: ['wand', '載入技能'],WebFetch: ['globe', '讀取網頁'], WebSearch: ['globe', '搜尋網路'], TodoWrite: ['check', '整理待辦'], Task: ['layers', '派出子任務'], Agent: ['layers', '派出子任務'],};const IMG = /\.(jpe?g|png|webp)$/i;-const CMD = [+const CMD: [RegExp, string][] = [[/render\.mjs[^\n]*--frames/, '渲染全部影格'], [/render\.mjs[^\n]*(--sheet|--strip)/, '輸出審查影格'], [/render\.mjs[^\n]*(--encode|--clip)/, '編碼成影片'],[/hyperframes[^\n]*render/, '渲染影片'], [/hyperframes[^\n]*(lint|check)/, '檢查動畫檔'], [/compare\.py/, '和參考片並排比較'], [/analyze\.py/, '分析影片'],[/align_lyrics/, '歌詞對時'], [/fetch_assets/, '搜尋授權素材'], [/ffprobe/, '讀取影片資訊'], [/ffmpeg/, 'FFmpeg 處理影音'],[/shot\.mjs|puppeteer|screenshot/, '截圖檢查'], [/npm (i|install|ci)\b/, '安裝套件'], [/pip install/, '安裝套件'], [/yt_dlp|yt-dlp/, '下載影片'],[/\b(ls|dir|find|Get-ChildItem)\b/, '查看檔案'], [/\bpython\b/, '執行 Python'], [/\bnode\b/, '執行 Node'],];-const cmdLabel = (c) => (CMD.find(([re]) => re.test(c)) || [null, '執行指令'])[1];-function relPath(id, d) {+const cmdLabel = (c: string) => (CMD.find(([re]) => re.test(c)) || [null, '執行指令'])[1];+function relPath(id: string, d: unknown) {const s = String(d || '').replace(/\\/g, '/');const m = s.match(new RegExp(`projects/${id}/(.+)$`)); if (m) return { rel: m[1], inProject: true };const r = s.match(/\/((?:\.claude|app|docs|projects)\/.+)$/); return { rel: r ? r[1] : s, inProject: false };}-function toSteps(id, raw) {- const out = [];+type Step = { kind: 'frames'; ico: IconName; verb: string; det: string; n: number; thumbs: string[]; ts: string }+ | { kind: 'tool'; ico: IconName; verb: string; det: string; ts: string; n?: undefined; thumbs?: undefined }+ | { kind: 'thought'; text: string; ts: string } | { kind: 'err'; text: string; ts: string };+function toSteps(id: string, raw: LogEvent[]) {+ const out: Step[] = [];for (const e of raw) {if (e.type === 'tool') {- const [ico, verb] = TOOL[e.name] || ['term', e.name];+ const [ico, verb]: [IconName, string] = TOOL[e.name] || ['term', e.name];const p = relPath(id, e.detail);if (e.name === 'Read' && IMG.test(p.rel)) {const prev = out[out.length - 1];@@ -94,7 +104,8 @@ function toSteps(id, raw) {}return out;}-function Steps({ id, raw, live, limit, onZoom }) {+type Zoom = (src: string) => void;+function Steps({ id, raw, live, limit, onZoom }: { id: string; raw: LogEvent[]; live?: boolean; limit?: number; onZoom?: Zoom }) {const now = useNow(!!live);const all = useMemo(() => toSteps(id, raw), [id, raw.length, raw[raw.length - 1]?.ts]);const [more, setMore] = useState(false);@@ -108,9 +119,9 @@ function Steps({ id, raw, live, limit, onZoom }) {if (s.kind === 'err') return <div key={i} className="step err"><span className="verb">錯誤</span><span className="det">{s.text}</span></div>;return (<div key={i} className={`step ${isLive ? 'live' : ''}`}>- <span className="verb"><I n={s.ico} style={{ marginRight: 5, color: 'var(--label-3)' }} />{s.verb}{s.n > 1 ? ` ${s.n} 張` : ''}</span>{isLive && s.ts && <span className="step-t">{clock(now - new Date(s.ts).getTime())}</span>}+ <span className="verb"><I n={s.ico} style={{ marginRight: 5, color: 'var(--label-3)' }} />{s.verb}{s.n && s.n > 1 ? ` ${s.n} 張` : ''}</span>{isLive && s.ts && <span className="step-t">{clock(now - new Date(s.ts).getTime())}</span>}<span className="det" title={s.det}>{s.det}</span>- {s.thumbs?.length > 0 && <div className="thumbs">{s.thumbs.map((t) => <img key={t} src={t} loading="lazy" onClick={() => onZoom?.(t)} onError={(e) => (e.target.style.display = 'none')} />)}</div>}+ {s.thumbs && s.thumbs.length > 0 && <div className="thumbs">{s.thumbs.map((t) => <img key={t} src={t} loading="lazy" onClick={() => onZoom?.(t)} onError={(e) => (e.currentTarget.style.display = 'none')} />)}</div>}</div>);})}@@ -118,9 +129,9 @@ function Steps({ id, raw, live, limit, onZoom }) {);}-function Thinking({ id, t, onZoom }) {+function Thinking({ id, t, onZoom }: { id: string; t: Think; onZoom?: Zoom }) {const [open, setOpen] = useState(false);- const ms = new Date(t.end || t.ended || t.last).getTime() - new Date(t.start).getTime();+ const ms = new Date((t.end || t.ended || t.last)!).getTime() - new Date(t.start).getTime();const n = toSteps(id, t.steps).length;return (<div className="think">@@ -132,10 +143,10 @@ function Thinking({ id, t, onZoom }) {);}-function LiveCard({ id, b, stage, onZoom }) {+function LiveCard({ id, b, stage, onZoom }: { id: string; b: Turn; stage: Stage; onZoom?: Zoom }) {const now = useNow(true);const [open, setOpen] = useState(true);- const doing = PHASE_DO[b.phase] || STAGE_DO[stage] || '工作中';+ const doing = PHASE_DO[b.phase ?? ''] || STAGE_DO[stage] || '工作中';return (<div className="livecard"><div className="lc-h">@@ -150,28 +161,28 @@ function LiveCard({ id, b, stage, onZoom }) {);}-const Avatar = ({ kind }) => kind === 'director' ? <Orb size={26} idle /> : <div className={`avatar-ai ${kind}`}><I n={kind === 'critic' ? 'mag' : 'film'} /></div>;+const Avatar = ({ kind }: { kind: Kind }) => kind === 'director' ? <Orb size={26} idle /> : <div className={`avatar-ai ${kind}`}><I n={kind === 'critic' ? 'mag' : 'film'} /></div>;// ---------- the conversation panel -----------export function Conversation({ id, s, tag, setTag, onZoom }) {+export function Conversation({ id, s, tag, setTag, onZoom }: { id: string; s: SnapshotView; tag: Tag | null; setTag: (t: Tag | null) => void; onZoom?: Zoom }) {const job = s.job, [text, setText] = useState(''), [err, setErr] = useState(''), [sending, setSending] = useState(false);- const [files, setFiles] = useState([]), [drag, setDrag] = useState(false), pick = useRef();- const addFiles = (list) => { const L = [...(list || [])].filter((f) => f.size < 200 * 1024 ** 2); if (L.length) setFiles((x) => [...x, ...L.map((f) => ({ f, url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null }))].slice(0, 10)); };- const onPaste = (e) => { const L = [...(e.clipboardData?.files || [])]; if (L.length) { e.preventDefault(); addFiles(L); } };- const box = useRef(), stick = useRef(true), [tab, setTab] = useState('chat');+ const [files, setFiles] = useState<{ f: File; url: string | null }[]>([]), [drag, setDrag] = useState(false), pick = useRef<HTMLInputElement>(null);+ const addFiles = (list: FileList | File[] | null) => { const L = [...(list || [])].filter((f) => f.size < 200 * 1024 ** 2); if (L.length) setFiles((x) => [...x, ...L.map((f) => ({ f, url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null }))].slice(0, 10)); };+ const onPaste = (e: React.ClipboardEvent) => { const L = [...(e.clipboardData?.files || [])]; if (L.length) { e.preventDefault(); addFiles(L); } };+ const box = useRef<HTMLDivElement>(null), stick = useRef(true), [tab, setTab] = useState<'chat' | 'log'>('chat');const { out, live } = useMemo(() => buildThread(job), [job.chat?.length, job.log?.length, job.stage, job.log?.[job.log.length - 1]?.ts]);const canTalk = ['plan_review', 'done', 'error', 'needs_input', 'new', 'analyzing', 'styling', 'styled', 'planning', 'replanning'].includes(job.stage);const working = !!STAGE_DO[job.stage];useEffect(() => { const b = box.current; if (b && stick.current) b.scrollTop = b.scrollHeight; }, [out.length, live.length, job.log?.length]);- const onScroll = () => { const b = box.current; stick.current = b.scrollHeight - b.scrollTop - b.clientHeight < 80; };+ const onScroll = () => { const b = box.current!; stick.current = b.scrollHeight - b.scrollTop - b.clientHeight < 80; };const send = async () => {if ((!text.trim() && !files.length) || !canTalk) return; setErr(''); setSending(true);- const meta = tag ? { ...(tag.shot && { shot: tag.shot }), ...(tag.time != null && { time: tag.time }) } : {};+ const meta: MessageMeta = tag ? { ...(tag.shot && { shot: tag.shot }), ...(tag.time != null && { time: tag.time }) } : {};const t = tag?.q ? `關於「${tag.q}」:${text}` : text || '(見附件)';try {if (files.length) { const fd = new FormData(); files.forEach((x) => fd.append('inputs', x.f)); meta.attachments = (await api.addInputs(id, fd, 'attachments')).saved; }await api.message(id, t, meta); setText(''); setTag(null); files.forEach((x) => x.url && URL.revokeObjectURL(x.url)); setFiles([]); stick.current = true;- } catch (e) { setErr(e.message); }+ } catch (e) { setErr((e as Error).message); }setSending(false);};const hint = job.stage === 'plan_review' ? '對企劃提意見,例如:S3 的轉場想更誇張…' : job.stage === 'done' ? '對成片提意見,例如:12 秒那裡太快看不懂…' : job.stage === 'needs_input' ? '告訴導演怎麼處理,或補充說明…' : job.stage === 'error' ? '說明要怎麼處理這個問題…' : ['new', 'analyzing', 'styling', 'styled', 'planning', 'replanning'].includes(job.stage) ? '企劃還在寫,可以先補充想法,導演會一併放進企劃…' : 'AI 工作中,這一輪完成後就可以說話';@@ -187,9 +198,9 @@ export function Conversation({ id, s, tag, setTag, onZoom }) {<div className="m-brief m"><div className="eyebrow">你的需求</div>{s.brief}</div>{out.map(({ m, think }, i) => {if (m.role === 'user') return <div key={i} className="m m-user">{(m.shot || m.time != null) && <div className="meta">{m.shot ? `針對 ${m.shot}` : `針對 ${Number(m.time).toFixed(1)} 秒`}</div>}- {(m.attachments || []).length > 0 && <div className="m-att">{m.attachments.map((a) => /\.(png|jpe?g|webp|gif)$/i.test(a)+ {(m.attachments || []).length > 0 && <div className="m-att">{m.attachments?.map((a) => /\.(png|jpe?g|webp|gif)$/i.test(a)? <img key={a} src={api.file(id, a)} onClick={() => onZoom?.(api.file(id, a))} />- : <a key={a} className="att-file" href={api.file(id, a)} target="_blank" rel="noreferrer"><I n="doc" />{a.split('/').pop().replace(/^[a-z0-9]+_/, '')}</a>)}</div>}+ : <a key={a} className="att-file" href={api.file(id, a)} target="_blank" rel="noreferrer"><I n="doc" />{a.split('/').pop()!.replace(/^[a-z0-9]+_/, '')}</a>)}</div>}{m.text === '(見附件)' && (m.attachments || []).length ? null : m.text.replace(/^[[^]]+]/, '')}</div>;if (m.role === 'system') return <div key={i} className="m m-sys"><I n="spark" style={{ color: 'var(--accent-ink)' }} />{m.text}</div>;const kind = whoKind(m.who, m.role);@@ -215,7 +226,7 @@ export function Conversation({ id, s, tag, setTag, onZoom }) {<div className={`compose-box ${drag ? 'drag' : ''}`}onDragOver={(e) => { if (canTalk) { e.preventDefault(); setDrag(true); } }} onDragLeave={() => setDrag(false)}onDrop={(e) => { e.preventDefault(); setDrag(false); if (canTalk) addFiles(e.dataTransfer.files); }}>- <button className="icon-btn att-btn" disabled={!canTalk} onClick={() => pick.current.click()} aria-label="附加檔案" title="附加圖片或檔案(也可以直接貼上或拖進來)"><I n="clip" /></button>+ <button className="icon-btn att-btn" disabled={!canTalk} onClick={() => pick.current!.click()} aria-label="附加檔案" title="附加圖片或檔案(也可以直接貼上或拖進來)"><I n="clip" /></button><input ref={pick} type="file" multiple hidden onChange={(e) => { addFiles(e.target.files); e.target.value = ''; }} /><AutoText placeholder={hint} value={text} disabled={!canTalk} onPaste={onPaste} onChange={(e) => setText(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); send(); } }} /><button className="send" disabled={!canTalk || (!text.trim() && !files.length) || sending} onClick={send} aria-label="送出">{sending ? <span className="spin-ring" /> : <I n="up" s={2.2} />}</button>@@ -228,23 +239,23 @@ export function Conversation({ id, s, tag, setTag, onZoom }) {}// ---------- raw activity log -----------const hms = (iso) => { const d = new Date(iso); return isNaN(d) ? '' : d.toLocaleTimeString('zh-TW', { hour12: false }); };-function LogView({ id, job }) {- const log = job.log || [], box = useRef(), stick = useRef(true);+const hms = (iso: string) => { const d = new Date(iso); return isNaN(+d) ? '' : d.toLocaleTimeString('zh-TW', { hour12: false }); };+function LogView({ id, job }: { id: string; job: Job }) {+ const log = job.log || [], box = useRef<HTMLDivElement>(null), stick = useRef(true);const [who, setWho] = useState('all'), [q, setQ] = useState('');const whos = useMemo(() => [...new Set(log.map((e) => e.who || '_'))], [log.length]);const rows = log.filter((e) => e.type !== 'session' && (who === 'all' || (e.who || '_') === who) && (!q || JSON.stringify(e).toLowerCase().includes(q.toLowerCase())));useEffect(() => { const b = box.current; if (b && stick.current) b.scrollTop = b.scrollHeight; }, [rows.length]);const download = () => {- const txt = log.map((e) => `${e.ts}\t${e.who || '-'}\t${e.type}\t${e.name || e.state || ''}\t${(e.text || e.detail || e.phase || '').replace(/\n/g, ' ')}`).join('\n');+ const txt = log.map((x) => { const e = x as LogEvent & { name?: string; state?: string; text?: string; detail?: string; phase?: string }; return `${e.ts}\t${e.who || '-'}\t${e.type}\t${e.name || e.state || ''}\t${(e.text || e.detail || e.phase || '').replace(/\n/g, ' ')}`; }).join('\n');const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([txt], { type: 'text/plain;charset=utf-8' })); a.download = `${id}-log.txt`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);};- const line = (e) => {+ const line = (e: LogEvent) => {if (e.type === 'turn') return <span className="lg-turn">{e.state === 'start' ? '▶ 開始' : e.ok ? '■ 完成' : '■ 失敗'} {e.phase}</span>;if (e.type === 'tool') return <><span className="lg-tool">{e.name}</span> {e.detail}</>;if (e.type === 'error') return <span className="lg-err">{e.text}</span>;if (e.type === 'thinking') return <span className="lg-think">{e.text}</span>;- return <span>{e.text}</span>;+ return <span>{'text' in e && e.text}</span>;};return (<div className="logview">@@ -253,7 +264,7 @@ function LogView({ id, job }) {<input placeholder="搜尋紀錄" value={q} onChange={(e) => setQ(e.target.value)} /><button className="icon-btn" title="下載紀錄" onClick={download}><I n="download" /></button></div>- <div className="lg-body" ref={box} onScroll={() => { const b = box.current; stick.current = b.scrollHeight - b.scrollTop - b.clientHeight < 60; }}>+ <div className="lg-body" ref={box} onScroll={() => { const b = box.current!; stick.current = b.scrollHeight - b.scrollTop - b.clientHeight < 60; }}>{rows.length === 0 && <div className="small faint" style={{ padding: 16 }}>沒有紀錄</div>}{rows.map((e, i) => <div key={i} className={`lg-row ${e.type}`}><span className="lg-ts">{hms(e.ts)}</span><span className="lg-who">{whoName(e.who)}</span><span className="lg-msg">{line(e)}</span></div>)}</div>diff --git a/app/web/src/Project.jsx b/app/web/src/Project.tsxsimilarity index 71%rename from app/web/src/Project.jsxrename to app/web/src/Project.tsxindex 8411031..4c1d65d 100644--- a/app/web/src/Project.jsx+++ b/app/web/src/Project.tsx@@ -1,50 +1,56 @@import React, { useEffect, useMemo, useRef, useState } from 'react';-import { api } from './api.js';-import { I, Orb, Md, Ring, AutoText, useNow, clock, fmt, RoundsEditor } from './ui.jsx';-import { Conversation, buildThread, STAGE_DO } from './Chat.jsx';+import type { ReactNode } from 'react';+import type { InputKind, Job, Pipeline as PipelineState, RequiredInput, RoundKey, Rounds, Stage } from '../../shared/types.ts';+import { api } from './api.ts';+import { I, Orb, Md, Ring, AutoText, useNow, clock, fmt, RoundsEditor } from './ui.tsx';+import type { IconName, RoundValues } from './ui.tsx';+import { Conversation, buildThread, STAGE_DO } from './Chat.tsx';+import type { Critique as CritiqueData, MustFix, PlanAsset, Shot as ShotData, SnapshotView, Tag } from './types.ts';-export const STATUS = {+export const STATUS: Record<Stage, [string, string]> = {new: ['排隊中', ''], analyzing: ['拆解中', 'live'], styling: ['判斷風格', 'live'], styled: ['風格完成', ''], planning: ['企劃中', 'live'],plan_review: ['等你確認企劃', 'warn'], replanning: ['修改企劃', 'live'], producing: ['生產中', 'live'], needs_input: ['等你提供', 'warn'],critiquing: ['評審中', 'live'], revising: ['修改中', 'live'], done: ['完成', 'ok'], error: ['需要處理', 'bad'],};-export const Status = ({ stage }) => { const [t, c] = STATUS[stage] || [stage, '']; return <span className={`cap ${c}`}>{c === 'live' ? <span className="dot live" /> : c === 'ok' ? <I n="check" s={2.4} /> : c === 'warn' ? <I n="pause" s={2.4} /> : c === 'bad' ? <I n="alert" s={2.2} /> : null}{t}</span>; };+export const Status = ({ stage }: { stage: Stage }) => { const [t, c] = STATUS[stage] || [stage, '']; return <span className={`cap ${c}`}>{c === 'live' ? <span className="dot live" /> : c === 'ok' ? <I n="check" s={2.4} /> : c === 'warn' ? <I n="pause" s={2.4} /> : c === 'bad' ? <I n="alert" s={2.2} /> : null}{t}</span>; };-const STEPS = [+const STEPS: { label: string; st: Stage[] }[] = [{ label: '參考片', st: ['new', 'analyzing'] },{ label: '風格拆解', st: ['styling', 'styled'] },{ label: '前製企劃', st: ['planning', 'plan_review', 'replanning'] },{ label: '生產', st: ['producing', 'needs_input'] },{ label: '成品', st: ['done', 'revising', 'critiquing'] },];-const stepIdx = (job) => { const s = job.stage === 'error' ? job.failed : job.stage; return Math.max(0, STEPS.findIndex((x) => x.st.includes(s))); };-const PRE_PROD = ['planning', 'replanning', 'plan_review']; // required inputs sit at the top of the page in these stages-const PIPE_DO = { setup: '導演建置角色與共用素材', cast: '角色關:審查角色設定圖', shots: '分段製作,每段做完立刻審查', assemble: '組裝成片', final: '最後評審:接縫、連戲、節奏' };+const stepIdx = (job: Job) => { const s = job.stage === 'error' ? job.failed : job.stage; return Math.max(0, STEPS.findIndex((x) => x.st.includes(s as Stage))); };+const PRE_PROD: Stage[] = ['planning', 'replanning', 'plan_review']; // required inputs sit at the top of the page in these stages+const PIPE_DO: Record<string, string> = { setup: '導演建置角色與共用素材', cast: '角色關:審查角色設定圖', shots: '分段製作,每段做完立刻審查', assemble: '組裝成片', final: '最後評審:接縫、連戲、節奏' };-export function Project({ id }) {- const [s, setS] = useState(null), [v, setV] = useState(0), [tag, setTag] = useState(null), [zoom, setZoom] = useState(null), [tab, setTab] = useState(null);- const lastStage = useRef(null);+type FileUrl = (p: string) => string;+type Zoom = (src: string) => void;+export function Project({ id }: { id: string }) {+ const [s, setS] = useState<SnapshotView | null>(null), [v, setV] = useState(0), [tag, setTag] = useState<Tag | null>(null), [zoom, setZoom] = useState<string | null>(null), [tab, setTab] = useState<string | null>(null);+ const lastStage = useRef<Stage | null>(null);useEffect(() => {- let t, alive = true;- const load = () => api.project(id).then((d) => { if (alive) { setS(d); setV((x) => x + 1); } }).catch(() => {});+ let t: ReturnType<typeof setTimeout> | undefined, alive = true;+ const load = () => api.project(id).then((d) => { if (alive) { setS(d as SnapshotView); setV((x) => x + 1); } }).catch(() => {});load();const off = api.events(id, () => { clearTimeout(t); t = setTimeout(load, 350); });return () => { alive = false; off(); clearTimeout(t); };}, [id]);- useEffect(() => { const k = (e) => e.key === 'Escape' && setZoom(null); addEventListener('keydown', k); return () => removeEventListener('keydown', k); }, []);+ useEffect(() => { const k = (e: KeyboardEvent) => e.key === 'Escape' && setZoom(null); addEventListener('keydown', k); return () => removeEventListener('keydown', k); }, []);useEffect(() => { if (s && lastStage.current && lastStage.current !== s.job.stage) setTab(null); if (s) lastStage.current = s.job.stage; }, [s?.job.stage]);if (!s) return <main className="page"><div className="skeleton" style={{ height: 44, width: 320, marginBottom: 24 }} /><div className="proj"><div className="skeleton" style={{ height: 420 }} /><div className="skeleton" style={{ height: 560 }} /></div></main>;const { job } = s, idx = stepIdx(job), working = !!STAGE_DO[job.stage];- const file = (p) => api.file(id, p, v);- const onZoom = (src) => setZoom(src);- const P = job.pipeline || {}, chunks = Object.values(P.chunks || {});- const preProd = PRE_PROD.includes(job.stage) || (job.stage === 'error' && PRE_PROD.includes(job.failed));+ const file = (p: string) => api.file(id, p, v);+ const onZoom = (src: string) => setZoom(src);+ const P: PipelineState = job.pipeline || {}, chunks = Object.values(P.chunks || {});+ const preProd = PRE_PROD.includes(job.stage) || (job.stage === 'error' && PRE_PROD.includes(job.failed as Stage));const tabs = [s.video && { k: 'result', label: '成品', ico: 'play', badge: s.critique && !s.critique.pass ? [`${(s.critique.must_fix || []).length} 項必修`, 'warn'] : null },P.phase && { k: 'pipe', label: '生產線', ico: 'layers', badge: chunks.length ? [`${chunks.filter((c) => c.state === 'passed').length}/${chunks.length}`, ''] : null },s.plan && { k: 'plan', label: '企劃', ico: 'doc', badge: job.stage === 'plan_review' ? ['待確認', 'warn'] : null },s.report && { k: 'ref', label: '參考片拆解', ico: 'scan' },- ].filter(Boolean);+ ].filter((t): t is { k: string; label: string; ico: IconName; badge?: [string, string] | null } => !!t);const auto = ['producing', 'needs_input'].includes(job.stage) && P.phase && P.phase !== 'final' ? 'pipe' : s.video ? 'result' : P.phase ? 'pipe' : s.plan ? 'plan' : 'ref';const cur = tabs.some((t) => t.k === tab) ? tab : tabs.some((t) => t.k === auto) ? auto : tabs[0]?.k;return (@@ -83,11 +89,11 @@ export function Project({ id }) {);}-function LiveBanner({ id, job }) {+function LiveBanner({ id, job }: { id: string; job: Job }) {const now = useNow(true);const { live } = useMemo(() => buildThread(job), [job.log?.length, job.stage]);- const since = live.length ? Math.min(...live.map((b) => new Date(b.start).getTime())) : new Date(job.updatedAt).getTime();- const detail = job.stage === 'producing' || job.stage === 'critiquing' || job.stage === 'revising' ? PIPE_DO[job.pipeline?.phase] : null;+ const since = live.length ? Math.min(...live.map((b) => new Date(b.start).getTime())) : new Date(job.updatedAt!).getTime();+ const detail = job.stage === 'producing' || job.stage === 'critiquing' || job.stage === 'revising' ? PIPE_DO[job.pipeline?.phase ?? ''] : null;return (<div className="livebar fade-in"><Orb size={36} live />@@ -99,8 +105,8 @@ function LiveBanner({ id, job }) {}// ---------- analysis -----------function Analysis({ s, file, onZoom }) {- const r = s.report, a = r.audio || {}, p = r.pacing || {};+function Analysis({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom: Zoom }) {+ const r = s.report!, a = r.audio || {}, p = r.pacing || {};const [open, setOpen] = useState(true);return (<section className="card">@@ -120,27 +126,27 @@ function Analysis({ s, file, onZoom }) {</div><div className="sheets" style={{ marginTop: 14 }}><div><div className="sub-h" style={{ marginTop: 0 }}>每秒一格</div><img className="shot-img" src={file('analysis/sheet_1fps.jpg')} onClick={() => onZoom(file('analysis/sheet_1fps.jpg'))} /></div>- <div><div className="sub-h" style={{ marginTop: 0 }}>每個鏡頭</div><img className="shot-img" src={file('analysis/sheet_scenes.jpg')} onError={(e) => (e.target.parentNode.style.display = 'none')} onClick={() => onZoom(file('analysis/sheet_scenes.jpg'))} /></div>+ <div><div className="sub-h" style={{ marginTop: 0 }}>每個鏡頭</div><img className="shot-img" src={file('analysis/sheet_scenes.jpg')} onError={(e) => (e.currentTarget.parentElement!.style.display = 'none')} onClick={() => onZoom(file('analysis/sheet_scenes.jpg'))} /></div></div>{s.styleMd && <details style={{ marginTop: 14 }}><summary className="small muted" style={{ cursor: 'pointer' }}>完整風格拆解 STYLE.md</summary><div style={{ marginTop: 10 }}><Md src={s.styleMd} /></div></details>}</>}</section>);}-const W = ({ v, k, warn }) => <div className={`widget ${warn ? 'warn' : ''}`}><div className="v">{v}</div><div className="k">{k}</div></div>;+const W = ({ v, k, warn }: { v: ReactNode; k: ReactNode; warn?: boolean }) => <div className={`widget ${warn ? 'warn' : ''}`}><div className="v">{v}</div><div className="k">{k}</div></div>;// ---------- plan ----------const SOFT = ['#C9C4FF', '#FFC8E6', '#FFD6B5', '#BDEBD9', '#BFE3FF', '#FFE7A3', '#E3CCFF', '#C8F0C0'];-const MOVES = { static: '固定', dolly_in: '推近', dolly_out: '拉遠', orbit: '環繞', crane_up: '升鏡', crane_down: '降鏡', macro_slide: '微距平移', push_reveal: '推進揭露', rack_focus: '移焦', pan: '橫搖', tilt: '直搖', zoom_in: '變焦推近', zoom_out: '變焦拉遠', shake: '晃動' };-function camText(x) {+const MOVES: Record<string, string> = { static: '固定', dolly_in: '推近', dolly_out: '拉遠', orbit: '環繞', crane_up: '升鏡', crane_down: '降鏡', macro_slide: '微距平移', push_reveal: '推進揭露', rack_focus: '移焦', pan: '橫搖', tilt: '直搖', zoom_in: '變焦推近', zoom_out: '變焦拉遠', shake: '晃動' };+function camText(x: ShotData) {const c = x.camera;if (!c || typeof c === 'string') return c || x.camera_note;- const f = (k) => (c[k] && c[k].fill != null ? Math.round(c[k].fill * 100) + '%' : null);+ const f = (k: 'from' | 'to') => (c[k] && c[k].fill != null ? Math.round(c[k].fill! * 100) + '%' : null);const parts = [MOVES[c.move] || c.move, c.lens && `${c.lens}mm`, f('from') && `主體 ${f('from')}${f('to') && f('to') !== f('from') ? '→' + f('to') : ''}`, c.pace && `速度 ${c.pace}`].filter(Boolean);return (x.camera_note ? x.camera_note + ' ' : '') + (parts.length ? `〔${parts.join(' · ')}〕` : '');}-function Plan({ s, file, job, onTag, onZoom }) {- const P = s.plan, [sel, setSel] = useState(null), [allAssets, setAllAssets] = useState(false);+function Plan({ s, file, job, onTag, onZoom }: { s: SnapshotView; file: FileUrl; job: Job; onTag: (t: Tag) => void; onZoom: Zoom }) {+ const P = s.plan!, [sel, setSel] = useState<string | null>(null), [allAssets, setAllAssets] = useState(false);const shots = P.shots || [];const total = P.format?.duration_s || Math.max(...shots.map((x) => x.end_s || 0), 1);const review = job.stage === 'plan_review';@@ -162,11 +168,11 @@ function Plan({ s, file, job, onTag, onZoom }) {{P.music && P.music.source !== 'none' && <div className="list" style={{ marginTop: 18 }}><div className="li"><div className="li-ico accent"><I n="music" /></div><div className="grow"><div className="t">{P.music.file || P.music.source}</div><div className="d">{[P.music.bpm && `${Math.round(P.music.bpm)} BPM`, P.music.section && `${P.music.section.start_s}s – ${P.music.section.end_s}s`, P.music.license].filter(Boolean).join(' · ')}</div></div></div></div>}</section>- {(P.style_frames || []).length > 0 && <section className="card"><div className="card-h"><h2>定調畫面</h2><span className="sp" /><span className="small faint">{P.style_frames.length} 張</span></div>- <div className="scroller">{P.style_frames.map((f) => <img key={f} className="shot-img" src={file(f)} onClick={() => onZoom(file(f))} />)}</div></section>}+ {(P.style_frames || []).length > 0 && <section className="card"><div className="card-h"><h2>定調畫面</h2><span className="sp" /><span className="small faint">{P.style_frames!.length} 張</span></div>+ <div className="scroller">{P.style_frames!.map((f) => <img key={f} className="shot-img" src={file(f)} onClick={() => onZoom(file(f))} />)}</div></section>}{(P.characters || []).length > 0 && <section className="card"><div className="card-h"><h2>角色</h2></div>- <div className="cast">{P.characters.map((c, i) => <div key={c.id || c.name}><div className="avatar" style={{ background: palette[(i + 1) % Math.max(1, palette.length)] || SOFT[i % 8], color: 'rgba(0,0,0,.6)' }}>{(c.name || '?').slice(0, 1)}</div><div className="grow"><b>{c.name}</b><div className="small muted" style={{ marginTop: 2 }}>{c.design}</div>{c.arc && <div className="small faint" style={{ marginTop: 4 }}>{c.arc}</div>}</div></div>)}</div></section>}+ <div className="cast">{P.characters!.map((c, i) => <div key={c.id || c.name}><div className="avatar" style={{ background: palette[(i + 1) % Math.max(1, palette.length)] || SOFT[i % 8], color: 'rgba(0,0,0,.6)' }}>{(c.name || '?').slice(0, 1)}</div><div className="grow"><b>{c.name}</b><div className="small muted" style={{ marginTop: 2 }}>{c.design}</div>{c.arc && <div className="small faint" style={{ marginTop: 4 }}>{c.arc}</div>}</div></div>)}</div></section>}<section className="card"><div className="card-h"><h2>分鏡與運鏡</h2><span className="sp" />{sel && <button className="btn sm plain" onClick={() => setSel(null)}>顯示全部</button>}</div>@@ -175,23 +181,23 @@ function Plan({ s, file, job, onTag, onZoom }) {<div className="list">{shots.map((x, i) => <Shot key={x.id} x={x} i={i} open={sel === x.id} onToggle={() => setSel(sel === x.id ? null : x.id)} review={review} onTag={onTag} />)}</div></section>- {(P.assets || []).length > 0 && <section className="card"><div className="card-h"><h2>素材</h2><span className="sp" /><span className="small faint">{P.assets.length} 項</span></div>- <div className="assets">{(allAssets ? P.assets : P.assets.slice(0, 8)).map((a) => <Asset key={a.id} a={a} file={file} />)}</div>- {P.assets.length > 8 && <button className="btn sm plain" style={{ marginTop: 10, marginLeft: -10 }} onClick={() => setAllAssets(!allAssets)}>{allAssets ? '收起' : `顯示全部 ${P.assets.length} 項`}</button>}+ {(P.assets || []).length > 0 && <section className="card"><div className="card-h"><h2>素材</h2><span className="sp" /><span className="small faint">{P.assets!.length} 項</span></div>+ <div className="assets">{(allAssets ? P.assets! : P.assets!.slice(0, 8)).map((a) => <Asset key={a.id} a={a} file={file} />)}</div>+ {P.assets!.length > 8 && <button className="btn sm plain" style={{ marginTop: 10, marginLeft: -10 }} onClick={() => setAllAssets(!allAssets)}>{allAssets ? '收起' : `顯示全部 ${P.assets!.length} 項`}</button>}{s.assetsMd && <details style={{ marginTop: 12 }}><summary className="small muted" style={{ cursor: 'pointer' }}>授權紀錄</summary><div style={{ marginTop: 8 }}><Md src={s.assetsMd} /></div></details>}</section>}{!PRE_PROD.includes(job.stage) && ((s.requiredInputs || []).length > 0 || s.lyrics) && <RequiredInputs id={job.id} s={s} editable={false} />}{PRE_PROD.includes(job.stage) && !(s.requiredInputs || []).length && s.lyrics && <RequiredInputs id={job.id} s={s} editable={review} />}{(P.open_questions || []).length > 0 && <section className="card"><div className="card-h"><h2>需要你決定</h2></div>- <div className="list">{P.open_questions.map((q, i) => <div key={i} className="li"><div className="li-ico accent"><I n="bubble" /></div><div className="grow">{q}</div>{review && <button className="btn sm plain" onClick={() => onTag({ q })}>回答</button>}</div>)}</div></section>}+ <div className="list">{P.open_questions!.map((q, i) => <div key={i} className="li"><div className="li-ico accent"><I n="bubble" /></div><div className="grow">{q}</div>{review && <button className="btn sm plain" onClick={() => onTag({ q })}>回答</button>}</div>)}</div></section>}- {(P.changelog || []).length > 1 && <div className="small faint" style={{ margin: '14px 4px 0' }}>修改紀錄:{P.changelog.join(' → ')}</div>}+ {(P.changelog || []).length > 1 && <div className="small faint" style={{ margin: '14px 4px 0' }}>修改紀錄:{P.changelog!.join(' → ')}</div>}{review && <Approve id={job.id} open={(s.requiredInputs || []).filter((r) => r.status === 'missing')} />}</div>);}-function Shot({ x, i, open, onToggle, review, onTag }) {+function Shot({ x, i, open, onToggle, review, onTag }: { x: ShotData; i: number; open: boolean; onToggle: () => void; review: boolean; onTag: (t: Tag) => void }) {return (<><div className="li click shot-li" onClick={onToggle}>@@ -205,22 +211,22 @@ function Shot({ x, i, open, onToggle, review, onTag }) {{(x.camera || x.camera_note) && <><span>運鏡</span><span>{camText(x)}</span></>}{x.ref_shot != null && <><span>對照參考</span><span>#{x.ref_shot}{x.ref_what ? ` · ${x.ref_what}` : ''}</span></>}{(x.transition_in || x.transition_out) && <><span>轉場</span><span>{x.transition_in && `進:${x.transition_in}`}{x.transition_in && x.transition_out && ' '}{x.transition_out && `出:${x.transition_out}`}</span></>}- {(x.reads || []).length > 0 && <><span>觀眾讀到</span><span>{x.reads.join(';')}</span></>}- {(x.text_overlay || []).length > 0 && <><span>字幕/字卡</span><span>{x.text_overlay.map((t) => t.text).join(';')}</span></>}- {(x.assets || []).length > 0 && <><span>素材</span><span>{x.assets.join('、')}</span></>}+ {(x.reads || []).length > 0 && <><span>觀眾讀到</span><span>{x.reads!.join(';')}</span></>}+ {(x.text_overlay || []).length > 0 && <><span>字幕/字卡</span><span>{x.text_overlay!.map((t) => t.text).join(';')}</span></>}+ {(x.assets || []).length > 0 && <><span>素材</span><span>{x.assets!.join('、')}</span></>}</div>{review && <button className="btn sm plain" style={{ marginTop: 10, marginLeft: -10 }} onClick={() => onTag({ shot: x.id })}><I n="bubble" />對 {x.id} 提意見</button>}</div>}</>);}-const ASTATUS = { user: '你提供的', to_fetch: '待抓取', fetched: '網路取得', drawn_in_code: '程式繪製', to_generate: '待生成' };-function Asset({ a, file }) {- const src = a.file ? file(a.file) : null, isImg = src && /\.(jpe?g|png|webp|gif|svg)$/i.test(a.file), isAud = src && /\.(mp3|m4a|wav|ogg)$/i.test(a.file);+const ASTATUS: Record<string, string> = { user: '你提供的', to_fetch: '待抓取', fetched: '網路取得', drawn_in_code: '程式繪製', to_generate: '待生成' };+function Asset({ a, file }: { a: PlanAsset; file: FileUrl }) {+ const src = a.file ? file(a.file) : undefined, isImg = src && /\.(jpe?g|png|webp|gif|svg)$/i.test(a.file!), isAud = src && /\.(mp3|m4a|wav|ogg)$/i.test(a.file!);return (<div className="asset"><div className="pv" style={isImg ? { backgroundImage: `url(${src})` } : undefined}>{isAud ? <audio controls src={src} /> : !isImg && <I n={a.kind === 'music' || a.kind === 'sfx' ? 'music' : a.kind === 'font' ? 'doc' : 'image'} />}</div>- <div className="b"><b>{a.id} · {a.purpose}</b><span className="faint">{ASTATUS[a.status] || a.status}{a.source && ` · ${a.source}`}</span>+ <div className="b"><b>{a.id} · {a.purpose}</b><span className="faint">{ASTATUS[a.status ?? ''] || a.status}{a.source && ` · ${a.source}`}</span><span className={`cap ${a.license ? 'ok' : a.status === 'drawn_in_code' ? '' : 'warn'}`} style={{ justifySelf: 'start', height: 20, fontSize: 11 }}>{a.license || (a.status === 'drawn_in_code' ? '原創' : '授權未填')}</span></div></div>);@@ -229,13 +235,13 @@ function Asset({ a, file }) {// ---------- required inputs & lyrics ----------// Things only the user can give (a song, lyrics, their own character art…). Shown at the top of the page while the plan is// being written or reviewed, so they are found before "approve" is blocked by them.-const KIND = { lyrics: '歌詞', audio: '音檔', image: '圖片', text: '文字', other: '檔案' };-const ACCEPT = { audio: 'audio/*,video/*,.mp3,.m4a,.wav,.aac,.flac,.ogg', image: 'image/*', lyrics: '.txt,.lrc,text/plain', text: '.txt,.md,text/plain' };-function RequiredInputs({ id, s, editable, top }) {+const KIND: Record<InputKind, string> = { lyrics: '歌詞', audio: '音檔', image: '圖片', text: '文字', other: '檔案' };+const ACCEPT: Partial<Record<InputKind, string>> = { audio: 'audio/*,video/*,.mp3,.m4a,.wav,.aac,.flac,.ogg', image: 'image/*', lyrics: '.txt,.lrc,text/plain', text: '.txt,.md,text/plain' };+function RequiredInputs({ id, s, editable, top }: { id: string; s: SnapshotView; editable: boolean; top?: boolean }) {const req = s.requiredInputs || [], missing = req.filter((r) => r.status === 'missing');const hasLyrics = req.some((r) => r.kind === 'lyrics') || s.lyrics;const [err, setErr] = useState(''), [busy, setBusy] = useState('');- const act = (k, fn) => async () => { setErr(''); setBusy(k); try { await fn(); } catch (e) { setErr(e.message); } setBusy(''); };+ const act = (k: string, fn: () => Promise<unknown>) => async () => { setErr(''); setBusy(k); try { await fn(); } catch (e) { setErr((e as Error).message); } setBusy(''); };return (<section id="required-inputs" className={`card req ${top && missing.length ? 'req-top' : ''}`}><div className="card-h"><div>@@ -264,28 +270,28 @@ function RequiredInputs({ id, s, editable, top }) {</section>);}-export function Upload({ id, label = '上傳檔案', forInput, accept, multiple = true, primary }) {- const [busy, setBusy] = useState(false), [msg, setMsg] = useState({}), ref = useRef();- const up = async (files) => {+export function Upload({ id, label = '上傳檔案', forInput, accept, multiple = true, primary }: { id: string; label?: string; forInput?: string; accept?: string; multiple?: boolean; primary?: boolean }) {+ const [busy, setBusy] = useState(false), [msg, setMsg] = useState<{ names?: string; err?: string }>({}), ref = useRef<HTMLInputElement>(null);+ const up = async (files: FileList) => {if (!files.length) return; setBusy(true); setMsg({});const f = new FormData(); [...files].forEach((x) => f.append('inputs', x));try { const r = await api.addInputs(id, f, null, forInput); setMsg({ names: (r.saved || []).map((p) => p.split('/').pop()).join('、') }); }- catch (e) { setMsg({ err: e.message }); } finally { setBusy(false); if (ref.current) ref.current.value = ''; }+ catch (e) { setMsg({ err: (e as Error).message }); } finally { setBusy(false); if (ref.current) ref.current.value = ''; }};return (<span className="upload"><label className={`btn sm ${primary ? 'primary' : ''}`}>{busy ? <span className="spin-ring" /> : <I n="clip" />}{busy ? '上傳中' : label}- <input ref={ref} type="file" multiple={multiple} accept={accept} hidden onChange={(e) => up(e.target.files)} /></label>+ <input ref={ref} type="file" multiple={multiple} accept={accept} hidden onChange={(e) => up(e.target.files!)} /></label>{msg.names && <span className="tiny faint up-msg"><span>已上傳</span> <span data-no-i18n>{msg.names}</span></span>}{msg.err && <span className="tiny up-msg" style={{ color: 'var(--red)' }}>{msg.err}</span>}</span>);}-function Lyrics({ id, s, editable }) {+function Lyrics({ id, s, editable }: { id: string; s: SnapshotView; editable: boolean }) {const [text, setText] = useState(''), [busy, setBusy] = useState(false), [msg, setMsg] = useState('');const L = s.lyrics?.lines || [];const mean = L.length ? L.reduce((a, l) => a + (l.match || 0), 0) / L.length : 0;- const go = async () => { setBusy(true); setMsg(''); try { const r = await api.lyrics(id, text); setMsg(r.aligned ? '對時完成' : r.ok ? '歌詞已存,收到配樂後會自動對時' : '對時失敗,請看右側紀錄'); if (r.ok) setText(''); } catch (e) { setMsg(e.message); } setBusy(false); };+ const go = async () => { setBusy(true); setMsg(''); try { const r = await api.lyrics(id, text); setMsg(r.aligned ? '對時完成' : r.ok ? '歌詞已存,收到配樂後會自動對時' : '對時失敗,請看右側紀錄'); if (r.ok) setText(''); } catch (e) { setMsg((e as Error).message); } setBusy(false); };return (<div style={{ marginTop: 18 }}><div className="row" style={{ marginBottom: 8 }}><div className="sub-h" style={{ margin: 0 }}>歌詞字幕</div><span className="sp grow" />{L.length > 0 && <span className="cap ok"><I n="check" s={2.4} />{L.length} 句 · 平均匹配 {Math.round(mean * 100)}%</span>}</div>@@ -297,9 +303,9 @@ function Lyrics({ id, s, editable }) {</div>);}-function Approve({ id, open }) {+function Approve({ id, open }: { id: string; open: RequiredInput[] }) {const [err, setErr] = useState(''), [busy, setBusy] = useState(false);- const go = async () => { setErr(''); setBusy(true); try { await api.approve(id); } catch (e) { setErr(e.message); } setBusy(false); };+ const go = async () => { setErr(''); setBusy(true); try { await api.approve(id); } catch (e) { setErr((e as Error).message); } setBusy(false); };return (<div className="approve-bar"><div className="grow"><b>{open.length ? `還差 ${open.length} 項素材` : '企劃看起來 OK 嗎?'}</b>@@ -311,13 +317,13 @@ function Approve({ id, open }) {}// ---------- error: say what happened in plain words, offer the next move -----------const STEP_NAME = { analyzing: '拆解參考片', styling: '判斷風格', planning: '寫企劃', replanning: '修改企劃', producing: '生產', revising: '修改成片', critiquing: '評審' };-function ErrorCard({ id, job }) {+const STEP_NAME: Record<string, string> = { analyzing: '拆解參考片', styling: '判斷風格', planning: '寫企劃', replanning: '修改企劃', producing: '生產', revising: '修改成片', critiquing: '評審' };+function ErrorCard({ id, job }: { id: string; job: Job }) {const [busy, setBusy] = useState(false), [open, setOpen] = useState(false);// the server writes errors in the project's language: match bothconst e = job.error || '', cancelled = /取消|^Cancelled/.test(e), restarted = /重新啟動|server restarted/i.test(e), limited = /用量到上限|usage limit/i.test(e);const missing = e.match(/(?:缺少輸出:|Missing output: )(.+)/)?.[1];- const title = cancelled ? `你停止了「${STEP_NAME[job.failed] || job.failed}」` : restarted ? `「${STEP_NAME[job.failed] || job.failed}」被伺服器重啟打斷` : limited ? 'AI 帳號的用量到上限了' : `「${STEP_NAME[job.failed] || job.failed}」沒有完成`;+ const title = cancelled ? `你停止了「${STEP_NAME[job.failed ?? ''] || job.failed}」` : restarted ? `「${STEP_NAME[job.failed ?? ''] || job.failed}」被伺服器重啟打斷` : limited ? 'AI 帳號的用量到上限了' : `「${STEP_NAME[job.failed ?? ''] || job.failed}」沒有完成`;const why = cancelled ? '檔案保留在停下來的地方,可以從這裡繼續。' : restarted ? '做到一半的檔案都還在,繼續會從目前的檔案接著做。' : limited ? '等額度恢復,或換另一個 AI 導演,再從這裡繼續;做到一半的檔案都還在。' : missing ? `AI 這一輪結束了,但沒有產出應有的檔案(${missing})。通常再跑一次就會好;也可以在右邊說明要怎麼處理。` : 'AI 這一輪出錯了。可以再跑一次,或在右邊說明要怎麼處理。';const go = async () => { setBusy(true); try { await api.retry(id); } finally { setBusy(false); } };return (@@ -337,23 +343,23 @@ function ErrorCard({ id, job }) {}// ---------- paused: show exactly what to decide, with the evidence and one-click answers -----------function Needs({ id, s, file, onZoom }) {- const job = s.job, needs = job.needs || [], p = job.pipeline || {}, [err, setErr] = useState(''), [busy, setBusy] = useState('');+function Needs({ id, s, file, onZoom }: { id: string; s: SnapshotView; file: FileUrl; onZoom: Zoom }) {+ const job = s.job, needs = job.needs || [], p: PipelineState = job.pipeline || {}, [err, setErr] = useState(''), [busy, setBusy] = useState('');const lyricsNeeded = needs.some((n) => n.kind === 'lyrics' || /歌詞|lyric|LRC/i.test(n.issue || ''));const castStuck = !needs.length && p.cast?.state === 'failed' && !p.cast?.pass;const failedChunks = Object.entries(p.chunks || {}).filter(([, v]) => ['failed', 'error'].includes(v.state));const shotsStuck = !needs.length && p.phase === 'shots' && failedChunks.length > 0;const rv = s.cast?.review;- const act = (k, fn) => async () => { setErr(''); setBusy(k); try { await fn(); } catch (e) { setErr(e.message); } setBusy(''); };+ const act = (k: string, fn: () => Promise<unknown>) => async () => { setErr(''); setBusy(k); try { await fn(); } catch (e) { setErr((e as Error).message); } setBusy(''); };const fixAll = act('fix', () => api.message(id, castStuck ? '照審查意見全部修,修完重新過角色關' : '照審查意見把沒通過的鏡頭全部修好'));- const Btn = ({ k, onClick, children, primary }) => <button className={`btn sm ${primary ? 'primary' : ''}`} disabled={!!busy} onClick={onClick}>{busy === k ? <span className="spin-ring" /> : null}{children}</button>;- let title = '暫停中:需要你決定', body = null, actions;+ const Btn = ({ k, onClick, children, primary }: { k: string; onClick: () => void; children: ReactNode; primary?: boolean }) => <button className={`btn sm ${primary ? 'primary' : ''}`} disabled={!!busy} onClick={onClick}>{busy === k ? <span className="spin-ring" /> : null}{children}</button>;+ let title = '暫停中:需要你決定', body: ReactNode, actions: ReactNode;if (castStuck) {- title = `角色關審了 ${p.cast.round} 輪還沒通過`;+ title = `角色關審了 ${p.cast!.round} 輪還沒通過`;body = <><div className="small muted">審查員還看到下面這些問題。你可以讓導演照著全部修,或覺得已經夠好就直接開始做鏡頭。</div>{(s.cast?.sheets || []).length > 0 && <div className="needs-thumbs">{s.cast.sheets.slice(0, 4).map((f) => <img key={f} src={file(f)} onClick={() => onZoom(file(f))} />)}</div>}- {(rv?.issues || []).length > 0 && <ul className="issues" onClick={(e) => e.target.closest('li')?.classList.toggle('open')}>{rv.issues.slice(0, 6).map((x, i) => <li key={i}><span className="tagc">{x.character || '角色'}</span><span>{x.what && <b>{x.what}:</b>}{x.issue}</span></li>)}{rv.issues.length > 6 && <li className="small faint">還有 {rv.issues.length - 6} 項,在「生產線」分頁</li>}</ul>}+ {(rv?.issues || []).length > 0 && <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>{rv!.issues!.slice(0, 6).map((x, i) => <li key={i}><span className="tagc">{x.character || '角色'}</span><span>{x.what && <b>{x.what}:</b>}{x.issue}</span></li>)}{rv!.issues!.length > 6 && <li className="small faint">還有 {rv!.issues!.length - 6} 項,在「生產線」分頁</li>}</ul>}</>;actions = <><Btn k="fix" primary onClick={fixAll}><I n="wand" />照審查全部修</Btn><Btn k="ok" onClick={act('ok', () => api.accept(id))}><I n="check" s={2.4} />角色可以了,開始做鏡頭</Btn></>;} else if (shotsStuck) {@@ -361,7 +367,7 @@ function Needs({ id, s, file, onZoom }) {body = <><div className="small muted">沒過的段落:{failedChunks.map(([k, v]) => `${k}(${(v.shots || []).join('、')})`).join(',')}。詳細審查意見在「生產線」分頁。</div></>;actions = <><Btn k="fix" primary onClick={fixAll}><I n="wand" />照審查全部修</Btn><Btn k="ok" onClick={act('ok', () => api.accept(id))}><I n="check" s={2.4} />可以了,直接組裝</Btn></>;} else {- body = needs.length > 0 ? <ul className="issues" onClick={(e) => e.target.closest('li')?.classList.toggle('open')}>{needs.map((n, i) => <li key={i}><span className="tagc">{n.from}</span><span>{n.issue}{n.why && <span className="faint"> · {n.why}</span>}</span></li>)}</ul>+ body = needs.length > 0 ? <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>{needs.map((n, i) => <li key={i}><span className="tagc">{n.from}</span><span>{n.issue}{typeof n.why === 'string' && n.why && <span className="faint"> · {n.why}</span>}</span></li>)}</ul>: <div className="small muted">在右邊告訴導演要怎麼處理,或直接繼續。</div>;actions = <><Upload id={id} /><Btn k="go" primary onClick={act('go', () => api.resume(id))}><I n="play" />{needs.length ? '已處理,繼續生產' : '繼續生產'}</Btn></>;}@@ -379,17 +385,17 @@ function Needs({ id, s, file, onZoom }) {}// ---------- review/fix round limits (header button + panel) -----------function RoundsButton({ id, r }) {- const [open, setOpen] = useState(false), [saving, setSaving] = useState(false), [err, setErr] = useState(''), ref = useRef();+function RoundsButton({ id, r }: { id: string; r: SnapshotView['rounds'] }) {+ const [open, setOpen] = useState(false), [saving, setSaving] = useState(false), [err, setErr] = useState(''), ref = useRef<HTMLDivElement>(null);const [local, setLocal] = useState(r.values);useEffect(() => { if (!saving) setLocal(r.values); }, [r.values.castRounds, r.values.chunkRounds, r.values.finalRounds]);- useEffect(() => { if (!open) return; const k = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); }; addEventListener('pointerdown', k); return () => removeEventListener('pointerdown', k); }, [open]);- const custom = Object.keys(r.defaults).filter((k) => r.values[k] !== r.defaults[k]).length;- const change = async (next) => {- const diff = Object.fromEntries(Object.keys(next).filter((k) => next[k] !== local[k]).map((k) => [k, next[k] == null ? '' : next[k]]));- setLocal({ ...local, ...Object.fromEntries(Object.entries(next).map(([k, v]) => [k, v ?? r.defaults[k]])) });+ useEffect(() => { if (!open) return; const k = (e: PointerEvent) => { if (!ref.current?.contains(e.target as Node)) setOpen(false); }; addEventListener('pointerdown', k); return () => removeEventListener('pointerdown', k); }, [open]);+ const custom = (Object.keys(r.defaults) as RoundKey[]).filter((k) => r.values[k] !== r.defaults[k]).length;+ const change = async (next: RoundValues) => {+ const diff = Object.fromEntries((Object.keys(next) as RoundKey[]).filter((k) => next[k] !== local[k]).map((k) => [k, next[k] == null ? '' : next[k]]));+ setLocal({ ...local, ...Object.fromEntries(Object.entries(next).map(([k, v]) => [k, v ?? r.defaults[k as RoundKey]])) });setSaving(true); setErr('');- try { await api.settings(id, diff); } catch (e) { setErr(e.message); setLocal(r.values); } finally { setSaving(false); }+ try { await api.settings(id, diff); } catch (e) { setErr((e as Error).message); setLocal(r.values); } finally { setSaving(false); }};return (<div className="rd-wrap" ref={ref}>@@ -397,7 +403,7 @@ function RoundsButton({ id, r }) {{open && <div className="rd-pop"><div className="row" style={{ marginBottom: 4 }}><b style={{ fontSize: 15 }}>審查輪數</b><span className="grow" />{saving ? <span className="spin-ring" style={{ width: 12, height: 12 }} /> : <span className="tiny faint">已自動儲存</span>}</div><div className="tiny muted" style={{ marginBottom: 6 }}>做到一半也可以改,從下一次檢查開始生效。</div>- <RoundsEditor value={Object.fromEntries(Object.entries(local).map(([k, v]) => [k, v === r.defaults[k] ? null : v]))} defaults={r.defaults} min={r.min} max={r.max} onChange={change} />+ <RoundsEditor value={Object.fromEntries(Object.entries(local).map(([k, v]) => [k, v === r.defaults[k as RoundKey] ? null : v]))} defaults={r.defaults} min={r.min} max={r.max} onChange={change} />{err && <div className="small" style={{ color: 'var(--red)', marginTop: 6 }}>{err}</div>}</div>}</div>@@ -405,26 +411,26 @@ function RoundsButton({ id, r }) {}// ---------- production line -----------const CHUNK = { queued: ['排隊中', ''], building: ['製作中', 'live'], reviewing: ['審查中', 'live'], fixing: ['修正中', 'warn'], passed: ['通過', 'ok'], failed: ['未通過', 'bad'], error: ['錯誤', 'bad'], needs_user: ['等你提供', 'warn'], shared_fix: ['導演改共用檔', 'live'], waiting_cast: ['做好了,等角色關', ''], built: ['做好了,等角色關', ''] };-const PHASES = [['setup', '建置', 'layers'], ['cast', '角色關', 'user'], ['shots', '分段製作', 'film'], ['assemble', '組裝', 'play'], ['final', '最後評審', 'mag']];-function Pipeline({ s, file, onZoom }) {- const p = s.job.pipeline || {}, rv = s.cast?.review, chunks = Object.entries(p.chunks || {}), R = s.rounds?.values || {};+const CHUNK: Record<string, [string, string]> = { queued: ['排隊中', ''], building: ['製作中', 'live'], reviewing: ['審查中', 'live'], fixing: ['修正中', 'warn'], passed: ['通過', 'ok'], failed: ['未通過', 'bad'], error: ['錯誤', 'bad'], needs_user: ['等你提供', 'warn'], shared_fix: ['導演改共用檔', 'live'], waiting_cast: ['做好了,等角色關', ''], built: ['做好了,等角色關', ''] };+const PHASES: [NonNullable<PipelineState['phase']>, string, IconName][] = [['setup', '建置', 'layers'], ['cast', '角色關', 'user'], ['shots', '分段製作', 'film'], ['assemble', '組裝', 'play'], ['final', '最後評審', 'mag']];+function Pipeline({ s, file, onZoom }: { s: SnapshotView; file: FileUrl; onZoom: Zoom }) {+ const p: PipelineState = s.job.pipeline || {}, rv = s.cast?.review, chunks = Object.entries(p.chunks || {}), R: Partial<Rounds> = s.rounds?.values || {};const cur = PHASES.findIndex(([k]) => k === p.phase), allDone = s.job.stage === 'done';const passed = chunks.filter(([, v]) => v.state === 'passed').length;return (<section className="card">- <div className="card-h"><div><div className="eyebrow">生產線</div><h2>{PIPE_DO[p.phase] || '生產中'}</h2></div></div>+ <div className="card-h"><div><div className="eyebrow">生產線</div><h2>{PIPE_DO[p.phase ?? ''] || '生產中'}</h2></div></div><div className="phases">{PHASES.map(([k, label, ico], i) => {const st = i < cur || allDone ? 'done' : i === cur ? 'cur' : '';- return <React.Fragment key={k}>{i > 0 && <span className={`phase-line ${i <= cur || allDone ? 'done' : ''}`} />}<span className={`phase ${st}`}><span className="pi">{st === 'done' ? <I n="check" s={2.6} /> : <I n={ico} />}</span>{label}{k === 'cast' && p.cast?.round > 1 ? ` · ${p.cast.round}` : ''}{k === 'final' && p.final?.round ? ` · 第 ${p.final.round} 輪` : ''}</span></React.Fragment>;+ return <React.Fragment key={k}>{i > 0 && <span className={`phase-line ${i <= cur || allDone ? 'done' : ''}`} />}<span className={`phase ${st}`}><span className="pi">{st === 'done' ? <I n="check" s={2.6} /> : <I n={ico} />}</span>{label}{k === 'cast' && p.cast && p.cast.round > 1 ? ` · ${p.cast.round}` : ''}{k === 'final' && p.final?.round ? ` · 第 ${p.final.round} 輪` : ''}</span></React.Fragment>;})}</div>{(s.cast?.sheets || []).length > 0 && <><div className="row" style={{ marginTop: 22, marginBottom: 10 }}><div className="sub-h" style={{ margin: 0 }}>角色設定圖</div><span className="grow" />- {p.cast?.state && <span className={`cap ${p.cast.pass ? 'ok' : p.cast.state === 'failed' ? 'bad' : p.cast.state === 'fixing' ? 'warn' : 'live'}`}>{p.cast.pass ? <><I n="check" s={2.4} />已通過</> : { reviewing: '審查中', fixing: '導演修正中', failed: '未通過' }[p.cast.state] || p.cast.state}{p.cast.round > 1 ? ` · 第 ${p.cast.round} / ${R.castRounds} 輪` : ''}</span>}</div>- <div className="scroller">{(s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop())).length ? s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop())) : s.cast.sheets).map((f) => <img key={f} className="shot-img" src={file(f)} onClick={() => onZoom(file(f))} />)}</div>+ {p.cast?.state && <span className={`cap ${p.cast.pass ? 'ok' : p.cast.state === 'failed' ? 'bad' : p.cast.state === 'fixing' ? 'warn' : 'live'}`}>{p.cast.pass ? <><I n="check" s={2.4} />已通過</> : ({ reviewing: '審查中', fixing: '導演修正中', failed: '未通過' } as Record<string, string>)[p.cast.state] || p.cast.state}{p.cast.round > 1 ? ` · 第 ${p.cast.round} / ${R.castRounds} 輪` : ''}</span>}</div>+ <div className="scroller">{(s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop()!)).length ? s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop()!)) : s.cast.sheets).map((f) => <img key={f} className="shot-img" src={file(f)} onClick={() => onZoom(file(f))} />)}</div>{p.cast?.chars && <div className="chunks" style={{ marginTop: 12 }}>{Object.entries(p.cast.chars).map(([k, c]) => { const [t, cl] = CHUNK[c.state] || (c.state === 'waiting_shared' ? ['等導演改骨架', 'warn'] : [c.state, '']); return <div key={k} className={`chunk ${c.state}`}><div className="ch-h"><b style={{ fontSize: 15 }}>{(s.production?.characters || []).find((x) => x.id === k)?.name || k}</b><span className="grow" /><span className={`cap ${cl}`} style={{ height: 22, fontSize: 11.5 }}>{cl === 'live' && <span className="dot live" />}{t}</span></div>{c.round > 1 && <div className="tiny faint">第 {c.round} / {R.castRounds} 輪</div>}</div>; })}</div>}- {rv && !rv.pass && (rv.issues || []).length > 0 && <ul className="issues" onClick={(e) => e.target.closest('li')?.classList.toggle('open')}>{rv.issues.map((x, i) => <li key={i}><span className="tagc">{x.character || '角色'}</span><span>{x.what && <b>{x.what}:</b>}{x.issue}{x.fix && <span className="faint"> → {x.fix}</span>}</span></li>)}</ul>}+ {rv && !rv.pass && (rv.issues || []).length > 0 && <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>{rv.issues!.map((x, i) => <li key={i}><span className="tagc">{x.character || '角色'}</span><span>{x.what && <b>{x.what}:</b>}{x.issue}{x.fix && <span className="faint"> → {x.fix}</span>}</span></li>)}</ul>}</>}{chunks.length > 0 && <>@@ -444,17 +450,18 @@ function Pipeline({ s, file, onZoom }) {}// ---------- result: review the video like an editor — pause anywhere, type the note right there, send them all at once -----------const tc = (x) => { const m = Math.floor(x / 60), s = x - m * 60; return `${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`; };-function Result({ s, file }) {- const id = s.job.id, key = `notes:${id}`, v = useRef(), input = useRef();- const [t, setT] = useState(0), [d, setD] = useState(0), [text, setText] = useState(''), [pin, setPin] = useState(null);- const [notes, setNotes] = useState(() => { try { return JSON.parse(localStorage.getItem(key)) || []; } catch { return []; } });+const tc = (x: number) => { const m = Math.floor(x / 60), s = x - m * 60; return `${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`; };+type Note = { id: number; t: number; text: string; thumb: string | null };+function Result({ s, file }: { s: SnapshotView; file: FileUrl }) {+ const id = s.job.id, key = `notes:${id}`, v = useRef<HTMLVideoElement>(null), input = useRef<HTMLTextAreaElement>(null);+ const [t, setT] = useState(0), [d, setD] = useState(0), [text, setText] = useState(''), [pin, setPin] = useState<number | null>(null);+ const [notes, setNotes] = useState<Note[]>(() => { try { return JSON.parse(localStorage.getItem(key) ?? 'null') || []; } catch { return []; } });const [sending, setSending] = useState(false), [err, setErr] = useState('');useEffect(() => { try { localStorage.setItem(key, JSON.stringify(notes)); } catch {} }, [notes]);const canSend = ['done', 'needs_input', 'error'].includes(s.job.stage);- const seek = (x) => { if (v.current) { v.current.currentTime = x; v.current.pause(); } };- const grab = () => { try { const c = document.createElement('canvas'); c.width = 192; c.height = 108; c.getContext('2d').drawImage(v.current, 0, 0, 192, 108); return c.toDataURL('image/jpeg', 0.72); } catch { return null; } };- const typing = (val) => { setText(val); if (pin == null && val.trim()) { v.current?.pause(); setPin(v.current?.currentTime || 0); } if (!val.trim()) setPin(null); };+ const seek = (x: number) => { if (v.current) { v.current.currentTime = x; v.current.pause(); } };+ const grab = () => { try { const c = document.createElement('canvas'); c.width = 192; c.height = 108; c.getContext('2d')!.drawImage(v.current!, 0, 0, 192, 108); return c.toDataURL('image/jpeg', 0.72); } catch { return null; } };+ const typing = (val: string) => { setText(val); if (pin == null && val.trim()) { v.current?.pause(); setPin(v.current?.currentTime || 0); } if (!val.trim()) setPin(null); };const add = () => {if (!text.trim()) return;const at = pin ?? v.current?.currentTime ?? 0;@@ -464,15 +471,15 @@ function Result({ s, file }) {const send = async () => {if (!notes.length || !canSend) return; setSending(true); setErr('');const body = `請依以下時間點修改(共 ${notes.length} 項):\n` + notes.map((n, i) => `${i + 1}. [${tc(n.t)}] ${n.text}`).join('\n');- try { await api.message(id, body, { notes: notes.map(({ t, text }) => ({ t: +t.toFixed(2), text })) }); setNotes([]); } catch (e) { setErr(e.message); }+ try { await api.message(id, body, { notes: notes.map(({ t, text }) => ({ t: +t.toFixed(2), text })) }); setNotes([]); } catch (e) { setErr((e as Error).message); }setSending(false);};- const must = (s.critique?.must_fix || []).filter((m) => m && typeof m.time === 'number');- const near = (x) => Math.abs(x - t) < 0.35;+ const must = (s.critique?.must_fix || []).filter((m): m is MustFix & { time: number } => !!m && typeof m.time === 'number');+ const near = (x: number) => Math.abs(x - t) < 0.35;return (<section className="card">- <div className="card-h"><div><div className="eyebrow">成品</div><h2>影片</h2></div><span className="sp" /><a className="btn sm" href={file(s.video)} download><I n="download" />下載 MP4</a></div>- <div className="player"><video ref={v} src={file(s.video)} poster={s.plan?.style_frames?.[0] ? file(s.plan.style_frames[0]) : undefined} preload="metadata" controls playsInline onTimeUpdate={(e) => setT(e.target.currentTime)} onLoadedMetadata={(e) => setD(e.target.duration)} onSeeked={(e) => setT(e.target.currentTime)} /></div>+ <div className="card-h"><div><div className="eyebrow">成品</div><h2>影片</h2></div><span className="sp" /><a className="btn sm" href={file(s.video!)} download><I n="download" />下載 MP4</a></div>+ <div className="player"><video ref={v} src={file(s.video!)} poster={s.plan?.style_frames?.[0] ? file(s.plan.style_frames[0]) : undefined} preload="metadata" controls playsInline onTimeUpdate={(e) => setT(e.currentTarget.currentTime)} onLoadedMetadata={(e) => setD(e.currentTarget.duration)} onSeeked={(e) => setT(e.currentTarget.currentTime)} /></div><div className="scrub" onClick={(e) => { const r = e.currentTarget.getBoundingClientRect(); seek(((e.clientX - r.left) / r.width) * d); }}><div className="scrub-fill" style={{ width: d ? `${(t / d) * 100}%` : 0 }} />@@ -505,15 +512,15 @@ function Result({ s, file }) {</section>);}-function Critique({ c, onSeek, id, stage }) {- const sc = Object.entries(c.scores || {}), must = (c.must_fix || []).filter(Boolean), [busy, setBusy] = useState(false);+function Critique({ c, onSeek, id, stage }: { c: CritiqueData; onSeek?: (t: number) => void; id: string; stage: Stage }) {+ const sc = Object.entries(c.scores || {}), must = (c.must_fix || []).filter((m): m is MustFix => !!m), [busy, setBusy] = useState(false);const fix = async () => { setBusy(true); try { await api.message(id, `照獨立評審列的 ${must.length} 項必修全部修改:\n` + must.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}`).join('\n')); } finally { setBusy(false); } };return (<div className="critique"><div className="row"><div className="avatar-ai critic"><I n="mag" /></div><b>獨立評審</b><span className="grow" /><span className={`cap ${c.pass ? 'ok' : 'bad'}`}>{c.pass ? <><I n="check" s={2.4} />通過</> : `${must.length} 項必修`}</span></div>{c.summary && <p className="small muted" style={{ margin: '10px 0 0' }}>{c.summary}</p>}{sc.length > 0 && <div className="scores">{sc.map(([k, v]) => <div key={k} className={`score ${v < 4 ? 'low' : ''}`}><div className="row"><span>{k}</span><b>{v}</b></div><div className="pips">{[1, 2, 3, 4, 5].map((n) => <i key={n} className={n <= v ? 'on' : ''} />)}</div></div>)}</div>}- {must.length > 0 && <ul className="issues" onClick={(e) => e.target.closest('li')?.classList.toggle('open')}>{must.map((m, i) => <li key={i} className={typeof m.time === 'number' ? 'seekable' : ''} onClick={() => typeof m.time === 'number' && onSeek?.(m.time)}><span className="tagc">{m.shot || '全片'}{typeof m.time === 'number' ? ` · ${m.time}s` : ''}</span><span>{m.issue}{m.fix && <span className="faint"> → {m.fix}</span>}</span></li>)}</ul>}+ {must.length > 0 && <ul className="issues" onClick={(e) => (e.target as Element).closest('li')?.classList.toggle('open')}>{must.map((m, i) => <li key={i} className={typeof m.time === 'number' ? 'seekable' : ''} onClick={() => typeof m.time === 'number' && onSeek?.(m.time)}><span className="tagc">{m.shot || '全片'}{typeof m.time === 'number' ? ` · ${m.time}s` : ''}</span><span>{m.issue}{m.fix && <span className="faint"> → {m.fix}</span>}</span></li>)}</ul>}{!c.pass && must.length > 0 && ['done', 'error'].includes(stage) && <div className="row" style={{ marginTop: 12 }}><button className="btn sm primary" disabled={busy} onClick={fix}>{busy ? <span className="spin-ring" /> : <I n="wand" />}照評審的 {must.length} 項全部修</button><span className="small faint">或在上方影片時間軸自己標要改的地方</span></div>}</div>);diff --git a/app/web/src/api.js b/app/web/src/api.jsdeleted file mode 100644index 606c070..0000000--- a/app/web/src/api.js+++ /dev/null@@ -1,22 +0,0 @@-// Thin client for the ReelMimic server.-const j = async (r) => { const d = await r.json().catch(() => ({})); if (!r.ok) throw new Error(d.error || r.statusText); return d; };-export const api = {- agents: () => fetch('/api/agents').then(j),- projects: () => fetch('/api/projects').then(j),- project: (id) => fetch(`/api/projects/${id}`).then(j),- create: (form) => fetch('/api/projects', { method: 'POST', body: form }).then(j),- addInputs: (id, form, to, forInput) => fetch(`/api/projects/${id}/inputs?${new URLSearchParams({ ...(to ? { to } : {}), ...(forInput ? { for: forInput } : {}) })}`, { method: 'POST', body: form }).then(j),- message: (id, text, meta) => fetch(`/api/projects/${id}/message`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, meta }) }).then(j),- approve: (id) => fetch(`/api/projects/${id}/approve`, { method: 'POST' }).then(j),- retry: (id) => fetch(`/api/projects/${id}/retry`, { method: 'POST' }).then(j),- lyrics: (id, text) => fetch(`/api/projects/${id}/lyrics`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }).then(j),- unwaive: (id, input) => fetch(`/api/projects/${id}/unwaive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j),- waive: (id, input) => fetch(`/api/projects/${id}/waive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j),- config: () => fetch('/api/config').then(j),- settings: (id, body) => fetch(`/api/projects/${id}/settings`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(j),- accept: (id) => fetch(`/api/projects/${id}/accept`, { method: 'POST' }).then(j),- resume: (id) => fetch(`/api/projects/${id}/resume`, { method: 'POST' }).then(j),- cancel: (id) => fetch(`/api/projects/${id}/cancel`, { method: 'POST' }).then(j),- events: (id, fn) => { const es = new EventSource(`/api/projects/${id}/events`); es.onmessage = (m) => fn(JSON.parse(m.data)); return () => es.close(); },- file: (id, p, bust) => `/files/${id}/${p}${bust ? `?v=${bust}` : ''}`,-};diff --git a/app/web/src/api.ts b/app/web/src/api.tsnew file mode 100644index 0000000..7bcf0b0--- /dev/null+++ b/app/web/src/api.ts@@ -0,0 +1,25 @@+// Thin client for the ReelMimic server.+import type { AgentStatus, Config, ProjectSummary, RoundKey, ServerEvent, Snapshot } from '../../shared/types.ts';+import type { MessageMeta } from './types.ts';+type Ok = { ok: true };+const j = async <T>(r: Response): Promise<T> => { const d: unknown = await r.json().catch(() => ({})); if (!r.ok) throw new Error((d as { error?: string }).error || r.statusText); return d as T; };+export const api = {+ agents: () => fetch('/api/agents').then(j<AgentStatus>),+ projects: () => fetch('/api/projects').then(j<ProjectSummary[]>),+ project: (id: string) => fetch(`/api/projects/${id}`).then(j<Snapshot>),+ create: (form: FormData) => fetch('/api/projects', { method: 'POST', body: form }).then(j<{ id: string }>),+ addInputs: (id: string, form: FormData, to?: string | null, forInput?: string) => fetch(`/api/projects/${id}/inputs?${new URLSearchParams({ ...(to ? { to } : {}), ...(forInput ? { for: forInput } : {}) })}`, { method: 'POST', body: form }).then(j<Snapshot & { saved: string[] }>),+ message: (id: string, text: string, meta?: MessageMeta) => fetch(`/api/projects/${id}/message`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, meta }) }).then(j<Ok>),+ approve: (id: string) => fetch(`/api/projects/${id}/approve`, { method: 'POST' }).then(j<Ok>),+ retry: (id: string) => fetch(`/api/projects/${id}/retry`, { method: 'POST' }).then(j<Ok>),+ lyrics: (id: string, text: string) => fetch(`/api/projects/${id}/lyrics`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }).then(j<{ ok: boolean; aligned: boolean; report?: unknown }>),+ unwaive: (id: string, input: string) => fetch(`/api/projects/${id}/unwaive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j<Snapshot>),+ waive: (id: string, input: string) => fetch(`/api/projects/${id}/waive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j<Snapshot>),+ config: () => fetch('/api/config').then(j<Config>),+ settings: (id: string, body: Partial<Record<RoundKey, number | ''>>) => fetch(`/api/projects/${id}/settings`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(j<Snapshot>),+ accept: (id: string) => fetch(`/api/projects/${id}/accept`, { method: 'POST' }).then(j<Ok>),+ resume: (id: string) => fetch(`/api/projects/${id}/resume`, { method: 'POST' }).then(j<Ok>),+ cancel: (id: string) => fetch(`/api/projects/${id}/cancel`, { method: 'POST' }).then(j<Ok>),+ events: (id: string, fn: (ev: ServerEvent) => void) => { const es = new EventSource(`/api/projects/${id}/events`); es.onmessage = (m: MessageEvent<string>) => fn(JSON.parse(m.data) as ServerEvent); return () => es.close(); },+ file: (id: string, p: string, bust?: number) => `/files/${id}/${p}${bust ? `?v=${bust}` : ''}`,+};diff --git a/app/web/src/i18n.js b/app/web/src/i18n.tssimilarity index 90%rename from app/web/src/i18n.jsrename to app/web/src/i18n.tsindex 9eecc69..c2c3f77 100644--- a/app/web/src/i18n.js+++ b/app/web/src/i18n.ts@@ -3,16 +3,19 @@// renders: English through the table below (exact strings + templates for text with numbers), Simplified Chinese through// OpenCC (Taiwan → Mainland phrasing), which also converts the AI's own messages. Text the user types is never touched.-export const LANGS = [+import type { Lang } from '../../shared/types.ts';+import type { ConverterFunction } from 'opencc-js/t2cn';++export const LANGS: { id: Lang; label: string; short: string }[] = [{ id: 'en', label: 'English', short: 'EN' },{ id: 'zh-TW', label: '繁體中文', short: '繁' },{ id: 'zh-CN', label: '简体中文', short: '简' },];-const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } }, set: (k, v) => { try { localStorage.setItem(k, v); } catch {} } };-export let lang = LANGS.some((l) => l.id === store.get('lang')) ? store.get('lang') : 'en'; // default for first-time visitors; the menu (top right) remembers a choice+const store = { get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } }, set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch {} } };+export let lang: Lang = LANGS.some((l) => l.id === store.get('lang')) ? store.get('lang') as Lang : 'en'; // default for first-time visitors; the menu (top right) remembers a choice// ---------- English -----------const EN = {+const EN: Record<string, string> = {// shell & home'已連線的 AI 導演': 'Connected AI directors', '切換外觀': 'Toggle appearance', '介面語言': 'Language','丟一支喜歡的影片,': 'Drop in a video you love,', '做出同樣風格的新作品。': 'get a new one in the same style.',@@ -85,7 +88,7 @@ const EN = {'開場': 'Opening', '畫面質感': 'Look & texture', '構圖': 'Composition', '瑕疵': 'Defects', '字幕標題': 'Captions & titles', '節奏連戲': 'Pacing & continuity', '光線材質': 'Light & material', '標題': 'Titles', '節奏': 'Pacing',// conversation'AI 導演': 'AI director', '對話': 'Chat', '紀錄': 'Log', '你的需求': 'Your brief', '工作中': 'Working', '獨立審查': 'Independent review', '系統': 'System', '審查員': 'Reviewer',- '角色審查': 'Cast review', '素材': 'Assets', '思考了': 'Thought for', '個步驟': 'steps', '顯示前面': 'Show earlier', '(見附件)': '(see attachments)',+ '角色審查': 'Cast review', '思考了': 'Thought for', '個步驟': 'steps', '顯示前面': 'Show earlier', '(見附件)': '(see attachments)','對企劃提意見,例如:S3 的轉場想更誇張…': 'Comment on the plan, e.g. make the S3 transition bigger…','對成片提意見,例如:12 秒那裡太快看不懂…': 'Comment on the film, e.g. too fast to follow at 12 s…','告訴導演怎麼處理,或補充說明…': 'Tell the director what to do, or add details…', '說明要怎麼處理這個問題…': 'Explain how to handle this…',@@ -93,7 +96,7 @@ const EN = {'Enter 送出 · Shift+Enter 換行 · 圖片可以直接貼上或拖進來': 'Enter to send · Shift+Enter for a new line · paste or drop images','附加檔案': 'Attach files', '附加圖片或檔案(也可以直接貼上或拖進來)': 'Attach images or files (you can also paste or drop them)', '送出': 'Send','全部 agent': 'All agents', '搜尋紀錄': 'Search log', '下載紀錄': 'Download log', '沒有紀錄': 'No log entries', '完整紀錄在': 'full log in',- '錯誤': 'Error', '查看影格': 'Viewing frames', '閱讀': 'Reading', '寫入': 'Writing', '修改': 'Editing', '尋找檔案': 'Finding files', '搜尋': 'Searching',+ '查看影格': 'Viewing frames', '閱讀': 'Reading', '寫入': 'Writing', '修改': 'Editing', '尋找檔案': 'Finding files', '搜尋': 'Searching','載入技能': 'Loading skill', '讀取網頁': 'Reading web page', '搜尋網路': 'Web search', '整理待辦': 'Updating todos', '派出子任務': 'Starting subtask','執行指令': 'Running command', '執行': 'Running', '渲染全部影格': 'Rendering all frames', '輸出審查影格': 'Rendering review frames', '編碼成影片': 'Encoding video','渲染影片': 'Rendering video', '檢查動畫檔': 'Checking composition', '和參考片並排比較': 'Comparing with the reference', '分析影片': 'Analyzing video',@@ -101,12 +104,12 @@ const EN = {'截圖檢查': 'Taking screenshots', '安裝套件': 'Installing packages', '下載影片': 'Downloading video', '查看檔案': 'Listing files', '執行 Python': 'Running Python', '執行 Node': 'Running Node','設計角色': 'Designing a character', '抓素材': 'Fetching assets', '整合素材、畫定調畫面': 'Merging assets, painting style frames', '寫企劃核心(分鏡、旁白、素材清單)': 'Writing the plan core (storyboard, narration, asset list)','建置角色與共用素材': 'Setting up characters and shared assets', '檢查角色設定圖': 'Checking character sheets', '修正角色': 'Fixing a character', '製作鏡頭': 'Building shots',- '逐格檢查鏡頭': 'Checking shots frame by frame', '修正鏡頭': 'Fixing shots', '組裝成片': 'Assembling the film',+ '逐格檢查鏡頭': 'Checking shots frame by frame', '修正鏡頭': 'Fixing shots','這一輪因為伺服器重新啟動而中斷。': 'This turn was cut off by a server restart.','▶ 開始': '▶ start', '■ 完成': '■ done', '■ 失敗': '■ failed',};// text with numbers / names in it-const EN_RE = [+const EN_RE: [RegExp, string][] = [[/^(\d+) 秒$/, '$1 s'], [/^(\d+) 分 (\d+) 秒$/, '$1 min $2 s'], [/^(\d+) 小時 (\d+) 分$/, '$1 h $2 min'],[/^(\d+) 分鐘前$/, '$1 min ago'], [/^(\d+) 小時前$/, '$1 h ago'], [/^(\d+) 天前$/, '$1 d ago'],[/^(\d+) 項必修$/, '$1 must-fix'], [/^· (\d+) 項待你提供$/, '· $1 need your input'], [/^(\d+) 張$/, '$1 frames'], [/^張$/, 'frames'],@@ -131,14 +134,14 @@ const EN_RE = [// ---------- Simplified Chinese ----------// the Traditional→Simplified dictionary (~0.3 MB) is loaded only when someone picks 简体中文-let toCN = null, loadingCN = null;+let toCN: ConverterFunction | null = null, loadingCN: Promise<void> | null = null;const loadCN = () => loadingCN || (loadingCN = import('opencc-js/t2cn').then((m) => { toCN = m.Converter({ from: 'tw', to: 'cn' }); }));-const cn = (s) => (toCN ? toCN(s) : s);+const cn = (s: string) => (toCN ? toCN(s) : s);-function translate(text) {+function translate(text: string) {if (lang === 'zh-TW' || !/[㐀-鿿]/.test(text)) return text;if (lang === 'zh-CN') return cn(text);- const m = text.match(/^(\s*)([\s\S]*?)(\s*)$/), core = m[2];+ const m = text.match(/^(\s*)([\s\S]*?)(\s*)$/)!, core = m[2];if (EN[core] != null) return m[1] + EN[core] + m[3];for (const [re, rep] of EN_RE) if (re.test(core)) return m[1] + core.replace(re, rep) + m[3];return text; // AI-written content and anything unlisted stays as written@@ -147,14 +150,16 @@ function translate(text) {// ---------- DOM pass ----------const ATTRS = ['placeholder', 'title', 'aria-label'];const SKIP = 'textarea, input, code, pre, script, style, [data-no-i18n]';-function fixText(n) {+type TrText = Text & { __tr?: string; __orig?: string };+type TrEl = Element & { __o?: Record<string, string>; __t?: Record<string, string> };+function fixText(n: TrText) {if (!n.data || !n.parentElement || n.parentElement.closest(SKIP)) return;if (n.__tr !== n.data) n.__orig = n.data; // React (or anything) wrote new source text- const out = translate(n.__orig);+ const out = translate(n.__orig!);if (n.data !== out) n.data = out;n.__tr = out;}-function fixAttrs(el) {+function fixAttrs(el: TrEl) {if (el.closest && el.closest('[data-no-i18n]')) return;el.__o = el.__o || {}; el.__t = el.__t || {};for (const a of ATTRS) {@@ -165,30 +170,31 @@ function fixAttrs(el) {el.__t[a] = out;}}-function walk(root) {- if (root.nodeType === 3) return fixText(root);- if (root.nodeType !== 1) return;+function walk(node: Node) {+ if (node.nodeType === 3) return fixText(node as TrText);+ if (node.nodeType !== 1) return;+ const root = node as Element;if (root.hasAttribute && ATTRS.some((a) => root.hasAttribute(a))) fixAttrs(root);const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);- for (let n; (n = w.nextNode());) n.nodeType === 3 ? fixText(n) : ATTRS.some((a) => n.hasAttribute(a)) && fixAttrs(n);+ for (let n: Node | null; (n = w.nextNode());) n.nodeType === 3 ? fixText(n as TrText) : ATTRS.some((a) => (n as Element).hasAttribute(a)) && fixAttrs(n as Element);}-let obs;+let obs: MutationObserver;export async function startI18n() {document.documentElement.lang = lang;if (lang === 'zh-CN') await loadCN();walk(document.body);obs = new MutationObserver((list) => {for (const m of list) {- if (m.type === 'characterData') fixText(m.target);- else if (m.type === 'attributes') fixAttrs(m.target);+ if (m.type === 'characterData') fixText(m.target as TrText);+ else if (m.type === 'attributes') fixAttrs(m.target as Element);else m.addedNodes.forEach(walk);}});obs.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRS });}-const listeners = new Set();-export const onLang = (fn) => { listeners.add(fn); return () => listeners.delete(fn); };-export async function setLang(id) {+const listeners = new Set<(id: Lang) => void>();+export const onLang = (fn: (id: Lang) => void) => { listeners.add(fn); return () => listeners.delete(fn); };+export async function setLang(id: Lang) {if (id === 'zh-CN') await loadCN();lang = id; store.set('lang', id); document.documentElement.lang = id;walk(document.body); listeners.forEach((fn) => fn(id));diff --git a/app/web/src/main.jsx b/app/web/src/main.tsxsimilarity index 88%rename from app/web/src/main.jsxrename to app/web/src/main.tsxindex 6dae989..ddfe639 100644--- a/app/web/src/main.jsx+++ b/app/web/src/main.tsx@@ -1,9 +1,9 @@import React from 'react';import { createRoot } from 'react-dom/client';-import App from './App.jsx';+import App from './App.tsx';import './styles.css';-import { startI18n } from './i18n.js';-createRoot(document.getElementById('root')).render(<App />);+import { startI18n } from './i18n.ts';+createRoot(document.getElementById('root')!).render(<App />);startI18n();// A tab left open across a rebuild keeps running the old bundle: check once a minute and offer a refresh.diff --git a/app/web/src/types.ts b/app/web/src/types.tsnew file mode 100644index 0000000..aeda823--- /dev/null+++ b/app/web/src/types.ts@@ -0,0 +1,45 @@+// Web-only views of the agent-written JSON that shared/types.ts leaves open (plan shots, report, critique, lyrics…).+// Only the fields the UI reads; everything is optional unless the page can't render without it.+import type { Snapshot, Plan, PlanCharacter, ChatMessage } from '../../shared/types.ts';++export type Camera = { move: string; lens?: number | string; from?: { fill?: number | null }; to?: { fill?: number | null }; pace?: string };+export type Shot = {+ id: string; start_s?: number; end_s?: number; summary?: string; action?: string; camera?: string | Camera; camera_note?: string;+ ref_shot?: number | string | null; ref_what?: string; transition_in?: string; transition_out?: string; reads?: string[]; text_overlay?: { text: string }[]; assets?: string[];+};+export type PlanAsset = { id: string; file?: string; kind?: string; purpose?: string; status?: string; source?: string; license?: string };+export interface PlanView extends Plan {+ logline?: string; style?: string; engine?: string;+ format?: { width?: number; height?: number; duration_s?: number };+ look?: { palette?: string[]; medium?: string; color_arc?: string };+ borrowed_from_reference?: string[];+ music?: { file?: string; source?: string; bpm?: number; license?: string; section?: { start_s?: number; end_s?: number } };+ style_frames?: string[];+ characters?: (PlanCharacter & { design?: string; arc?: string })[];+ shots?: Shot[];+ assets?: PlanAsset[];+ open_questions?: string[];+ changelog?: string[];+}++export type Report = {+ video: { duration: number; width: number; height: number; fps: number };+ crop?: { w: number; h: number } | null;+ audio?: { bpm?: number; present?: boolean; silent?: boolean };+ pacing?: { count?: number; mean_shot_s?: number; mean_shot_beats?: number };+};+export type Route = { engine?: string; style?: string; medium?: string; confidence?: number; why?: string[] };+export type MustFix = { shot?: string; time?: number | null; issue: string; fix?: string };+export type Critique = { pass?: boolean; summary?: string; scores?: Record<string, number>; must_fix?: (MustFix | null)[] };+export type Production = { characters?: { id: string; name?: string }[] };+export type LyricLine = { start?: number; end?: number; text: string; match: number };+export type Lyrics = { lines?: LyricLine[] };++// the project snapshot with those files narrowed (cast once where it is loaded)+export type SnapshotView = Omit<Snapshot, 'report' | 'route' | 'plan' | 'critique' | 'production' | 'lyrics'> & {+ report: Report | null; route: Route | null; plan: PlanView | null; critique: Critique | null; production: Production | null; lyrics: Lyrics | null;+};++// what a chat message is about (a shot, a moment in the film, or an open question from the plan)+export type Tag = { shot?: string; time?: number; q?: string };+export type MessageMeta = Pick<ChatMessage, 'shot' | 'time' | 'attachments' | 'notes'>;diff --git a/app/web/src/ui.jsx b/app/web/src/ui.tsxsimilarity index 70%rename from app/web/src/ui.jsxrename to app/web/src/ui.tsxindex 7065440..774ca80 100644--- a/app/web/src/ui.jsx+++ b/app/web/src/ui.tsx@@ -1,4 +1,6 @@import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import type { CSSProperties, ReactNode, TextareaHTMLAttributes } from 'react';+import type { RoundKey, Rounds } from '../../shared/types.ts';// ---------- icons (SF-Symbols-like strokes) ----------const P = {@@ -37,7 +39,8 @@ const P = {mag: 'M10.5 4.5a6 6 0 1 1 0 12 6 6 0 0 1 0-12ZM15 15l5 5M8 10.5h5',stop: 'M7 7h10v10H7z',};-export const I = ({ n, s, style, className = '' }) => (+export type IconName = keyof typeof P;+export const I = ({ n, s, style, className = '' }: { n: IconName; s?: number; style?: CSSProperties; className?: string }) => (<svg className={`ico ${className}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={s || 1.8} strokeLinecap="round" strokeLinejoin="round" style={style} aria-hidden="true"><path d={P[n]} /></svg>);@@ -51,13 +54,14 @@ export const BrandMark = () => (</svg>);-export const Orb = ({ size = 56, live, idle, className = '' }) => <div className={`orb ${live ? 'live' : ''} ${idle ? 'idle' : ''} ${className}`} style={{ '--s': `${size}px` }}><i /></div>;+export const Orb = ({ size = 56, live, idle, className = '' }: { size?: number; live?: boolean; idle?: boolean; className?: string }) => <div className={`orb ${live ? 'live' : ''} ${idle ? 'idle' : ''} ${className}`} style={{ '--s': `${size}px` } as CSSProperties}><i /></div>;// ---------- segmented control with a sliding thumb -----------export function Seg({ value, options, onChange }) {- const ref = useRef(), [th, setTh] = useState(null);+export type SegOption<T extends string> = { value: T; label: ReactNode; disabled?: boolean; title?: string };+export function Seg<T extends string>({ value, options, onChange }: { value: T; options: SegOption<T>[]; onChange: (v: T) => void }) {+ const ref = useRef<HTMLDivElement>(null), [th, setTh] = useState<{ w: number; x: number } | null>(null);useLayoutEffect(() => {- const m = () => { const b = ref.current?.querySelector(`[data-v="${value}"]`); if (b) setTh({ w: b.offsetWidth, x: b.offsetLeft }); };+ const m = () => { const b = ref.current?.querySelector<HTMLElement>(`[data-v="${value}"]`); if (b) setTh({ w: b.offsetWidth, x: b.offsetLeft }); };m(); addEventListener('resize', m); return () => removeEventListener('resize', m);}, [value, options.map((o) => o.value).join()]);return (@@ -68,7 +72,7 @@ export function Seg({ value, options, onChange }) {);}-export const Ring = ({ value = 0, size = 64, stroke = 6 }) => {+export const Ring = ({ value = 0, size = 64, stroke = 6 }: { value?: number; size?: number; stroke?: number }) => {const r = (size - stroke) / 2, c = 2 * Math.PI * r;return (<div className="ring" style={{ width: size, height: size }}>@@ -86,37 +90,37 @@ export function useNow(active = true, ms = 1000) {useEffect(() => { if (!active) return; const t = setInterval(() => setN(Date.now()), ms); return () => clearInterval(t); }, [active, ms]);return n;}-export const dur = (ms) => {+export const dur = (ms: number) => {const s = Math.max(0, Math.round(ms / 1000));if (s < 60) return `${s} 秒`;const m = Math.floor(s / 60);if (m < 60) return `${m} 分 ${s % 60} 秒`;return `${Math.floor(m / 60)} 小時 ${m % 60} 分`;};-export const clock = (ms) => { const s = Math.max(0, Math.floor(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };-export const ago = (iso) => {+export const clock = (ms: number) => { const s = Math.max(0, Math.floor(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };+export const ago = (iso?: string) => {if (!iso) return '';const s = (Date.now() - new Date(iso).getTime()) / 1000;if (s < 60) return '剛剛'; if (s < 3600) return `${Math.floor(s / 60)} 分鐘前`; if (s < 86400) return `${Math.floor(s / 3600)} 小時前`;return `${Math.floor(s / 86400)} 天前`;};-export const fmt = (x) => (x == null ? '' : `${Number(x).toFixed(1)}s`);+export const fmt = (x?: number | null) => (x == null ? '' : `${Number(x).toFixed(1)}s`);// ---------- minimal markdown -----------export function Md({ src }) {+export function Md({ src }: { src?: string | null }) {const html = useMemo(() => {- const esc = (t) => t.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');- const inl = (t) => esc(t).replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>');- const out = [], L = (src || '').split('\n');+ const esc = (t: string) => t.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ const inl = (t: string) => esc(t).replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>');+ const out: string[] = [], L = (src || '').split('\n');for (let i = 0; i < L.length; i++) {const l = L[i];if (/^\s*\|/.test(l)) {- const rows = []; while (i < L.length && /^\s*\|/.test(L[i])) { if (!/^\s*\|[\s:|-]+\|\s*$/.test(L[i])) rows.push(L[i].trim().replace(/^\||\|$/g, '').split('|')); i++; } i--;+ const rows: string[][] = []; while (i < L.length && /^\s*\|/.test(L[i])) { if (!/^\s*\|[\s:|-]+\|\s*$/.test(L[i])) rows.push(L[i].trim().replace(/^\||\|$/g, '').split('|')); i++; } i--;out.push('<table>' + rows.map((r, k) => '<tr>' + r.map((c) => `<${k ? 'td' : 'th'}>${inl(c.trim())}</${k ? 'td' : 'th'}>`).join('') + '</tr>').join('') + '</table>');- } else if (/^#{1,4} /.test(l)) { const n = l.match(/^#+/)[0].length; out.push(`<h${Math.min(n + 1, 4)}>${inl(l.replace(/^#+ /, ''))}</h${Math.min(n + 1, 4)}>`); }+ } else if (/^#{1,4} /.test(l)) { const n = l.match(/^#+/)![0].length; out.push(`<h${Math.min(n + 1, 4)}>${inl(l.replace(/^#+ /, ''))}</h${Math.min(n + 1, 4)}>`); }else if (/^>\s?/.test(l)) out.push(`<blockquote>${inl(l.replace(/^>\s?/, ''))}</blockquote>`);- else if (/^\s*\d+\. /.test(l)) { const items = []; while (i < L.length && /^\s*\d+\. /.test(L[i])) { items.push(`<li>${inl(L[i].replace(/^\s*\d+\. /, ''))}</li>`); i++; } i--; out.push(`<ol>${items.join('')}</ol>`); }- else if (/^\s*[-*] /.test(l)) { const items = []; while (i < L.length && /^\s*[-*] /.test(L[i])) { items.push(`<li>${inl(L[i].replace(/^\s*[-*] /, ''))}</li>`); i++; } i--; out.push(`<ul>${items.join('')}</ul>`); }+ else if (/^\s*\d+\. /.test(l)) { const items: string[] = []; while (i < L.length && /^\s*\d+\. /.test(L[i])) { items.push(`<li>${inl(L[i].replace(/^\s*\d+\. /, ''))}</li>`); i++; } i--; out.push(`<ol>${items.join('')}</ol>`); }+ else if (/^\s*[-*] /.test(l)) { const items: string[] = []; while (i < L.length && /^\s*[-*] /.test(L[i])) { items.push(`<li>${inl(L[i].replace(/^\s*[-*] /, ''))}</li>`); i++; } i--; out.push(`<ul>${items.join('')}</ul>`); }else if (l.trim()) out.push(`<p>${inl(l)}</p>`);}return out.join('');@@ -125,9 +129,9 @@ export function Md({ src }) {}// textarea that grows with its content-export const AutoText = React.forwardRef(function AutoText({ value, onChange, minRows = 1, ...rest }, outer) {- const ref = useRef();- React.useImperativeHandle(outer, () => ref.current);+export const AutoText = React.forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement> & { minRows?: number }>(function AutoText({ value, onChange, minRows = 1, ...rest }, outer) {+ const ref = useRef<HTMLTextAreaElement>(null);+ React.useImperativeHandle(outer, () => ref.current as HTMLTextAreaElement);useLayoutEffect(() => { const t = ref.current; if (!t) return; t.style.height = 'auto'; t.style.height = t.scrollHeight + 'px'; }, [value]);return <textarea ref={ref} rows={minRows} value={value} onChange={onChange} {...rest} />;});@@ -135,13 +139,14 @@ export const AutoText = React.forwardRef(function AutoText({ value, onChange, mi// ---------- review/fix round limits (per project) ----------// value: the project's own settings (may be partial); defaults: server defaults. Changing a number calls onChange with// the full next value; a number equal to its default is sent as null (= follow the default).-export const ROUND_FIELDS = [+export const ROUND_FIELDS: [RoundKey, string, string][] = [['castRounds', '角色關', '每個角色最多審幾輪'],['chunkRounds', '每段鏡頭', '每段最多審幾輪'],['finalRounds', '最後評審', '自動修改最多幾輪'],];-export function RoundsEditor({ value = {}, defaults = {}, min = 1, max = 10, onChange, disabled }) {- const set = (k, v) => onChange({ ...value, [k]: v === defaults[k] ? null : v });+export type RoundValues = Partial<Record<RoundKey, number | null>>;+export function RoundsEditor({ value = {}, defaults, min = 1, max = 10, onChange, disabled }: { value?: RoundValues; defaults: Rounds; min?: number; max?: number; onChange: (next: RoundValues) => void; disabled?: boolean }) {+ const set = (k: RoundKey, v: number) => onChange({ ...value, [k]: v === defaults[k] ? null : v });return (<div className="rounds">{ROUND_FIELDS.map(([k, label, hint]) => {diff --git a/app/web/tsconfig.json b/app/web/tsconfig.jsonnew file mode 100644index 0000000..813508e--- /dev/null+++ b/app/web/tsconfig.json@@ -0,0 +1,12 @@+{+ // The React UI. Vite compiles it; `tsc` only checks.+ "extends": "../tsconfig.base.json",+ "compilerOptions": {+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "jsx": "react-jsx",+ "types": ["vite/client"]+ },+ "include": ["src", "vite.config.ts", "../shared"]+}diff --git a/app/web/vite.config.js b/app/web/vite.config.tssimilarity index 100%rename from app/web/vite.config.jsrename to app/web/vite.config.tsdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 747619b..ba0d749 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -3,7 +3,7 @@# ArchitectureReelMimic has three layers: the **web app** (React), the **server** (Node — runs the workflow and dispatches-agents) and the **agent workspace** (the repo root, where Claude Code or Codex read skills, write files and render).+agents; both are TypeScript and share their API types in `app/shared/types.ts`) and the **agent workspace** (the repo root, where Claude Code or Codex read skills, write files and render).The layers talk only through **files**: agents write files as specified in `CONTRACT.md`, the server decides whether astep is done by checking whether the files it must produce were updated, and the web app renders those files directly.So you can swap the agent, add an engine or change the UI without touching the other layers.@@ -13,11 +13,11 @@ Browser (app/web, React + Vite)│ REST + Server-Sent Events▼Server (app/server)- ├─ index.mjs HTTP API, uploads, SSE, project files (/files/:id/*)- ├─ env.mjs loads ~/.reelmimic/secrets.json at startup- ├─ jobs.mjs workflow state machine + production scheduling (order, parallelism, pausing)- ├─ prompts.mjs the instructions each step gives its agent (edits apply on the next turn, no restart)- └─ agents/index.mjs agent adapters: Claude Code / Codex → one event stream+ ├─ index.ts HTTP API, uploads, SSE, project files (/files/:id/*)+ ├─ env.ts loads ~/.reelmimic/secrets.json at startup+ ├─ jobs.ts workflow state machine + production scheduling (order, parallelism, pausing)+ ├─ prompts.ts the instructions each step gives its agent (edits apply on the next turn, no restart)+ └─ agents/index.ts agent adapters: Claude Code / Codex → one event stream│ spawn (prompt on stdin, events streamed on stdout)▼Agent workspace (repo root)@@ -110,7 +110,7 @@ projects/<id>/## 4. Agent adapters-`agents/index.mjs` turns both CLIs into the same events: `session`, `text`, `thinking`, `tool`, `error`, `done`.+`agents/index.ts` turns both CLIs into the same events: `session`, `text`, `thinking`, `tool`, `error`, `done`.| | Claude Code | Codex ||---|---|---|@@ -123,13 +123,13 @@ builder (kept across fix rounds); reviewers always start fresh.## 5. Web app-- `App.jsx`: home (composer card, project list), routing, language menu.-- `Project.jsx`: project page with tabs Final / Production line / Plan / Reference analysis; pause and error cards,+- `App.tsx`: home (composer card, project list), routing, language menu.+- `Project.tsx`: project page with tabs Final / Production line / Plan / Reference analysis; pause and error cards,required inputs and lyric timing, time-stamped notes on the video.-- `Chat.jsx`: conversation and "thinking": merges `job.chat` with the event log; working agents show as live cards+- `Chat.tsx`: conversation and "thinking": merges `job.chat` with the event log; working agents show as live cards(plain-language steps, timers, thumbnails of frames they looked at); finished replies collapse into"Thought for N s · M steps"; plus a raw log tab.-- `i18n.js`: interface language (繁體中文 source, English table, 简体中文 via OpenCC).+- `i18n.ts`: interface language (繁體中文 source, English table, 简体中文 via OpenCC).- Live updates: `GET /api/projects/:id/events` (SSE).## 6. HTTP APIdiff --git a/docs/EXTENDING.md b/docs/EXTENDING.mdindex 47510a3..5a6fe3b 100644--- a/docs/EXTENDING.md+++ b/docs/EXTENDING.md@@ -8,10 +8,10 @@ Extension points, from shallow to deep:|---|---|---|| Add a video style | `.claude/skills/video-clone/styles/<name>.md` | No || Add a production engine (a new drawing / rendering method) | `.claude/skills/<engine>/` (an ordinary agent skill) | No |-| Change how an agent handles a step | `app/server/prompts.mjs` | Text only, applies on the next turn |+| Change how an agent handles a step | `app/server/prompts.ts` | Text only, applies on the next turn || Give agents a new tool | `.claude/skills/video-clone/scripts/` | Write the script, then mention it in a prompt / SKILL.md |-| Plug in another AI director (a new agent CLI) | `app/server/agents/index.mjs` | Yes |-| Change the steps or order of the production line | `app/server/jobs.mjs` + `prompts.mjs` + `CONTRACT.md` | Yes |+| Plug in another AI director (a new agent CLI) | `app/server/agents/index.ts` | Yes |+| Change the steps or order of the production line | `app/server/jobs.ts` + `prompts.ts` + `CONTRACT.md` | Yes |---@@ -88,9 +88,9 @@ free.If a new engine has its own way of making characters, keep the same rule — "characters defined in shared files, onefile per character, shots only pass pose parameters" — so the cast gate can review and fix them in parallel.-## 3. Tune agent behaviour (prompts.mjs)+## 3. Tune agent behaviour (prompts.ts)-Each key in `app/server/prompts.mjs` is one step of the pipeline:+Each key in `app/server/prompts.ts` is one step of the pipeline:| Key | Who | Does ||---|---|---|@@ -112,20 +112,20 @@ forward into the setup or build specs is the most effective speed-up.## 4. Plug in another AI director-In `app/server/agents/index.mjs`:+In `app/server/agents/index.ts`:1. Write `xxxArgs(sessionId, cwd)`: command-line arguments for a non-interactive run that auto-approves file editsand can resume a session.2. Write `parseXxx(obj, emit, st)`: turn the CLI's JSON stream into the common events:`session {id}`, `text {text}`, `thinking {text}`, `tool {name, detail}`, `error {text}`, and finally `done {ok, text}`.-3. Add the new `kind` to `runAgent` and `agentStatus`, and an option to the picker in the web app's `App.jsx`.+3. Add the new `kind` to `runAgent` and `agentStatus`, and an option to the picker in the web app's `App.tsx`.The agent must be able to: read and write files in the repo, run a shell (python, node, ffmpeg), look at images(review depends on it) and resume a conversation.## 5. Change the production line-Main functions in `app/server/jobs.mjs`:+Main functions in `app/server/jobs.ts`:- `production()`: setup → `castGate()` (runs alongside segment building) → `runChunk()` × N → assemble.- `castGate()` / `castSerial()`: per-character parallel review and fixing; the serial version is used for a single@@ -133,13 +133,13 @@ Main functions in `app/server/jobs.mjs`:- `finalPanel()`: final critic ⇄ revise.- `turn()`: dispatches one agent turn (session handling, global slots, required-file check).-When changing a step, change three places together: `jobs.mjs` (flow), `prompts.mjs` (instructions) and `CONTRACT.md`-(format of any new file); plus `Project.jsx` if the web app should show it.+When changing a step, change three places together: `jobs.ts` (flow), `prompts.ts` (instructions) and `CONTRACT.md`+(format of any new file); plus `Project.tsx` if the web app should show it.Parameters (parallelism, rounds per gate) are in `CONFIG` and can also be set through environment variables.## 6. Adding UI text / translations-Interface strings are written in Traditional Chinese in the components. `app/web/src/i18n.js` translates the page at+Interface strings are written in Traditional Chinese in the components. `app/web/src/i18n.ts` translates the page atruntime: English comes from the `EN` table (plus `EN_RE` patterns for strings with numbers), Simplified Chinese isconverted automatically with OpenCC. When you add a new string, add its English entry to `EN`; mark elements that mustnever be translated (user content, file names) with `data-no-i18n`.diff --git a/docs/zh-CN/ARCHITECTURE.md b/docs/zh-CN/ARCHITECTURE.mdindex 12b79e5..556ebff 100644--- a/docs/zh-CN/ARCHITECTURE.md+++ b/docs/zh-CN/ARCHITECTURE.md@@ -11,11 +11,11 @@ ReelMimic 由三层组成:**网站**(React)、**服务器**(Node,负│ REST + Server-Sent Events▼服务器(app/server)- ├─ index.mjs HTTP API、上传、SSE、提供项目文件(/files/:id/*)- ├─ env.mjs 启动时加载 ~/.reelmimic/secrets.json- ├─ jobs.mjs 流程状态机 + 生产线调度(谁先谁后、平行几个、何时暂停)- ├─ prompts.mjs 每个步骤给 agent 的指令(改档后下一轮就生效,不用重启)- └─ agents/index.mjs agent 转接层:Claude Code / Codex → 统一事件+ ├─ index.ts HTTP API、上传、SSE、提供项目文件(/files/:id/*)+ ├─ env.ts 启动时加载 ~/.reelmimic/secrets.json+ ├─ jobs.ts 流程状态机 + 生产线调度(谁先谁后、平行几个、何时暂停)+ ├─ prompts.ts 每个步骤给 agent 的指令(改档后下一轮就生效,不用重启)+ └─ agents/index.ts agent 转接层:Claude Code / Codex → 统一事件│ spawn(stdin 给指令,stdout 串流事件)▼agent 工作区(repo 根目录)@@ -97,7 +97,7 @@ projects/<id>/## 4. Agent 转接层-`agents/index.mjs` 把两种 CLI 统一成同一组事件:`session`、`text`、`thinking`、`tool`、`error`、`done`。+`agents/index.ts` 把两种 CLI 统一成同一组事件:`session`、`text`、`thinking`、`tool`、`error`、`done`。| | Claude Code | Codex ||---|---|---|@@ -109,10 +109,10 @@ projects/<id>/## 5. 网站-- `App.jsx`:首页(输入卡片、项目列表)、路由、语言菜单。-- `Project.jsx`:项目页,分页为成品/生产线/企划/参考片拆解;暂停卡、错误卡、必要素材与歌词对时、视频时间点留言。-- `Chat.jsx`:对话与「思考」:把 `job.chat` 与事件纪录合并,工作中的 agent 显示成即时卡片(白话步骤、计时、看过的影格缩略图),完成的回复收成「思考了 N 秒 · M 个步骤」;另有原始纪录分页。-- `i18n.js`:界面语言(繁體中文为原文、English 对照表、简体中文由 OpenCC 转换)。+- `App.tsx`:首页(输入卡片、项目列表)、路由、语言菜单。+- `Project.tsx`:项目页,分页为成品/生产线/企划/参考片拆解;暂停卡、错误卡、必要素材与歌词对时、视频时间点留言。+- `Chat.tsx`:对话与「思考」:把 `job.chat` 与事件纪录合并,工作中的 agent 显示成即时卡片(白话步骤、计时、看过的影格缩略图),完成的回复收成「思考了 N 秒 · M 个步骤」;另有原始纪录分页。+- `i18n.ts`:界面语言(繁體中文为原文、English 对照表、简体中文由 OpenCC 转换)。- 即时更新:`GET /api/projects/:id/events`(SSE)。## 6. HTTP APIdiff --git a/docs/zh-CN/EXTENDING.md b/docs/zh-CN/EXTENDING.mdindex 8aff7ce..65e5acf 100644--- a/docs/zh-CN/EXTENDING.md+++ b/docs/zh-CN/EXTENDING.md@@ -8,10 +8,10 @@ ReelMimic 的扩充点由浅到深:|---|---|---|| 加一种视频风格 | `.claude/skills/video-clone/styles/<name>.md` | 不用 || 加一个制作引擎(新的画法/渲染方式) | `.claude/skills/<engine>/`(一般 agent skill) | 不用 |-| 调整 agent 在某一步怎么做 | `app/server/prompts.mjs` | 只改文本,下一轮就生效 |+| 调整 agent 在某一步怎么做 | `app/server/prompts.ts` | 只改文本,下一轮就生效 || 加新工具给 agent 用 | `.claude/skills/video-clone/scripts/` | 写脚本,再在 prompt/SKILL.md 提到它 |-| 接另一种 AI 导演(新的 agent CLI) | `app/server/agents/index.mjs` | 要 |-| 改生产线的步骤或顺序 | `app/server/jobs.mjs` + `prompts.mjs` + `CONTRACT.md` | 要 |+| 接另一种 AI 导演(新的 agent CLI) | `app/server/agents/index.ts` | 要 |+| 改生产线的步骤或顺序 | `app/server/jobs.ts` + `prompts.ts` + `CONTRACT.md` | 要 |---@@ -73,7 +73,7 @@ ReelMimic 的扩充点由浅到深:## 3. 调整 agent 的做法(prompts.mjs)-`app/server/prompts.mjs` 每个键对应生产线的一步:+`app/server/prompts.ts` 每个键对应生产线的一步:| 键 | 谁 | 做什么 ||---|---|---|@@ -93,30 +93,30 @@ ReelMimic 的扩充点由浅到深:## 4. 接另一种 AI 导演-在 `app/server/agents/index.mjs`:+在 `app/server/agents/index.ts`:1. 写一个 `xxxArgs(sessionId, cwd)`:无交互、自动核准文件修改、可接续 session 的命令行参数。2. 写一个 `parseXxx(obj, emit, st)`:把 CLI 的 JSON 串流转成统一事件:`session {id}`、`text {text}`、`thinking {text}`、`tool {name, detail}`、`error {text}`,最后 `done {ok, text}`。-3. 在 `runAgent` 与 `agentStatus` 加上新的 `kind`,前端 `App.jsx` 的选择器加一个选项。+3. 在 `runAgent` 与 `agentStatus` 加上新的 `kind`,前端 `App.tsx` 的选择器加一个选项。agent 需要能:读写 repo 内文件、运行 shell(python、node、ffmpeg)、看图片(审查靠它)、接续对话。## 5. 改生产线-`app/server/jobs.mjs` 的主要函数:+`app/server/jobs.ts` 的主要函数:- `production()`:setup → `castGate()`(与分段制作同时跑)→ `runChunk()` × N → assemble。- `castGate()` / `castSerial()`:每个角色平行审查修正;一个角色或共用档时走串行版。- `finalPanel()`:最后评审 ⇄ 修改。- `turn()`:派一次 agent 回合(session 管理、全域名额、必须文件检查)。-改步骤时三个地方要一起改:`jobs.mjs`(流程)、`prompts.mjs`(指令)、`CONTRACT.md`(新文件的格式),前端要显示的话再改 `Project.jsx`。+改步骤时三个地方要一起改:`jobs.ts`(流程)、`prompts.ts`(指令)、`CONTRACT.md`(新文件的格式),前端要显示的话再改 `Project.tsx`。参数(平行数、每关轮数)在 `CONFIG`,也可以用环境变量调整。## 6. 界面文本与翻译-组件里的界面文本一律写繁體中文。`app/web/src/i18n.js` 在运行时翻译整个页面:英文来自 `EN` 对照表(含数字的字符串用 `EN_RE` 样式),简体中文由 OpenCC 自动转换。+组件里的界面文本一律写繁體中文。`app/web/src/i18n.ts` 在运行时翻译整个页面:英文来自 `EN` 对照表(含数字的字符串用 `EN_RE` 样式),简体中文由 OpenCC 自动转换。添加文本时请在 `EN` 补上英文;不该被翻译的元素(用户内容、文件名)加 `data-no-i18n`。## 7. 开发diff --git a/docs/zh-TW/ARCHITECTURE.md b/docs/zh-TW/ARCHITECTURE.mdindex 794ee6a..fb0619b 100644--- a/docs/zh-TW/ARCHITECTURE.md+++ b/docs/zh-TW/ARCHITECTURE.md@@ -11,11 +11,11 @@ ReelMimic 由三層組成:**網站**(React)、**伺服器**(Node,負│ REST + Server-Sent Events▼伺服器(app/server)- ├─ index.mjs HTTP API、上傳、SSE、提供專案檔案(/files/:id/*)- ├─ env.mjs 啟動時載入 ~/.reelmimic/secrets.json- ├─ jobs.mjs 流程狀態機 + 生產線排程(誰先誰後、平行幾個、何時暫停)- ├─ prompts.mjs 每個步驟給 agent 的指令(改檔後下一輪就生效,不用重啟)- └─ agents/index.mjs agent 轉接層:Claude Code / Codex → 統一事件+ ├─ index.ts HTTP API、上傳、SSE、提供專案檔案(/files/:id/*)+ ├─ env.ts 啟動時載入 ~/.reelmimic/secrets.json+ ├─ jobs.ts 流程狀態機 + 生產線排程(誰先誰後、平行幾個、何時暫停)+ ├─ prompts.ts 每個步驟給 agent 的指令(改檔後下一輪就生效,不用重啟)+ └─ agents/index.ts agent 轉接層:Claude Code / Codex → 統一事件│ spawn(stdin 給指令,stdout 串流事件)▼agent 工作區(repo 根目錄)@@ -97,7 +97,7 @@ projects/<id>/## 4. Agent 轉接層-`agents/index.mjs` 把兩種 CLI 統一成同一組事件:`session`、`text`、`thinking`、`tool`、`error`、`done`。+`agents/index.ts` 把兩種 CLI 統一成同一組事件:`session`、`text`、`thinking`、`tool`、`error`、`done`。| | Claude Code | Codex ||---|---|---|@@ -109,10 +109,10 @@ projects/<id>/## 5. 網站-- `App.jsx`:首頁(輸入卡片、專案列表)、路由、語言選單。-- `Project.jsx`:專案頁,分頁為成品/生產線/企劃/參考片拆解;暫停卡、錯誤卡、必要素材與歌詞對時、影片時間點留言。-- `Chat.jsx`:對話與「思考」:把 `job.chat` 與事件紀錄合併,工作中的 agent 顯示成即時卡片(白話步驟、計時、看過的影格縮圖),完成的回覆收成「思考了 N 秒 · M 個步驟」;另有原始紀錄分頁。-- `i18n.js`:介面語言(繁體中文為原文、English 對照表、简体中文由 OpenCC 轉換)。+- `App.tsx`:首頁(輸入卡片、專案列表)、路由、語言選單。+- `Project.tsx`:專案頁,分頁為成品/生產線/企劃/參考片拆解;暫停卡、錯誤卡、必要素材與歌詞對時、影片時間點留言。+- `Chat.tsx`:對話與「思考」:把 `job.chat` 與事件紀錄合併,工作中的 agent 顯示成即時卡片(白話步驟、計時、看過的影格縮圖),完成的回覆收成「思考了 N 秒 · M 個步驟」;另有原始紀錄分頁。+- `i18n.ts`:介面語言(繁體中文為原文、English 對照表、简体中文由 OpenCC 轉換)。- 即時更新:`GET /api/projects/:id/events`(SSE)。## 6. HTTP APIdiff --git a/docs/zh-TW/CONTRIBUTING.md b/docs/zh-TW/CONTRIBUTING.mdindex 8a95bc9..84382e1 100644--- a/docs/zh-TW/CONTRIBUTING.md+++ b/docs/zh-TW/CONTRIBUTING.md@@ -20,9 +20,10 @@ npm run doctor # 環境檢查- **新風格**:`.claude/skills/video-clone/styles/<name>.md`,附一段你用來測試的參考片描述(不要附上受版權保護的影片檔)。- **「已知的坑」**:做片時踩到的問題與解法,補進對應風格檔或引擎的 SKILL.md。- **新製作引擎**:一個 agent skill 資料夾;第三方 skill 請附上來源與授權,並更新 `THIRD_PARTY_NOTICES.md`。-- **流程與指令**:改 `app/server/prompts.mjs` 或 `jobs.mjs` 時,請說明用哪支片驗證、`timeline.py` 的前後時間比較。+- **流程與指令**:改 `app/server/prompts.ts` 或 `jobs.ts` 時,請說明用哪支片驗證、`timeline.py` 的前後時間比較。## 提交前-- `npm run build` 能過,`node --check` 過 `app/server/*.mjs`。+- 在 `app/` 裡 `npm run check`(型別檢查、lint、測試)和 `npm run build` 都要過;每個 PR 的 CI 會跑同樣的檢查。+- app 是 TypeScript(strict)。server 的 `.ts` 由 Node 內建的型別剝除直接執行,不需要建置;只能用可剝除的語法(不要用 `enum`、`namespace`、建構子參數屬性)。- 不要提交 `projects/`、金鑰(`~/.reelmimic/secrets.json`)、參考影片或任何你沒有授權的素材。- 程式碼註解與文件用繁體中文或英文皆可,保持和周圍一致。diff --git a/docs/zh-TW/EXTENDING.md b/docs/zh-TW/EXTENDING.mdindex f38b859..ab30dff 100644--- a/docs/zh-TW/EXTENDING.md+++ b/docs/zh-TW/EXTENDING.md@@ -8,10 +8,10 @@ ReelMimic 的擴充點由淺到深:|---|---|---|| 加一種影片風格 | `.claude/skills/video-clone/styles/<name>.md` | 不用 || 加一個製作引擎(新的畫法/渲染方式) | `.claude/skills/<engine>/`(一般 agent skill) | 不用 |-| 調整 agent 在某一步怎麼做 | `app/server/prompts.mjs` | 只改文字,下一輪就生效 |+| 調整 agent 在某一步怎麼做 | `app/server/prompts.ts` | 只改文字,下一輪就生效 || 加新工具給 agent 用 | `.claude/skills/video-clone/scripts/` | 寫腳本,再在 prompt/SKILL.md 提到它 |-| 接另一種 AI 導演(新的 agent CLI) | `app/server/agents/index.mjs` | 要 |-| 改生產線的步驟或順序 | `app/server/jobs.mjs` + `prompts.mjs` + `CONTRACT.md` | 要 |+| 接另一種 AI 導演(新的 agent CLI) | `app/server/agents/index.ts` | 要 |+| 改生產線的步驟或順序 | `app/server/jobs.ts` + `prompts.ts` + `CONTRACT.md` | 要 |---@@ -73,7 +73,7 @@ ReelMimic 的擴充點由淺到深:## 3. 調整 agent 的做法(prompts.mjs)-`app/server/prompts.mjs` 每個鍵對應生產線的一步:+`app/server/prompts.ts` 每個鍵對應生產線的一步:| 鍵 | 誰 | 做什麼 ||---|---|---|@@ -93,30 +93,30 @@ ReelMimic 的擴充點由淺到深:## 4. 接另一種 AI 導演-在 `app/server/agents/index.mjs`:+在 `app/server/agents/index.ts`:1. 寫一個 `xxxArgs(sessionId, cwd)`:無互動、自動核准檔案修改、可接續 session 的命令列參數。2. 寫一個 `parseXxx(obj, emit, st)`:把 CLI 的 JSON 串流轉成統一事件:`session {id}`、`text {text}`、`thinking {text}`、`tool {name, detail}`、`error {text}`,最後 `done {ok, text}`。-3. 在 `runAgent` 與 `agentStatus` 加上新的 `kind`,前端 `App.jsx` 的選擇器加一個選項。+3. 在 `runAgent` 與 `agentStatus` 加上新的 `kind`,前端 `App.tsx` 的選擇器加一個選項。agent 需要能:讀寫 repo 內檔案、執行 shell(python、node、ffmpeg)、看圖片(審查靠它)、接續對話。## 5. 改生產線-`app/server/jobs.mjs` 的主要函式:+`app/server/jobs.ts` 的主要函式:- `production()`:setup → `castGate()`(與分段製作同時跑)→ `runChunk()` × N → assemble。- `castGate()` / `castSerial()`:每個角色平行審查修正;一個角色或共用檔時走序列版。- `finalPanel()`:最後評審 ⇄ 修改。- `turn()`:派一次 agent 回合(session 管理、全域名額、必須檔案檢查)。-改步驟時三個地方要一起改:`jobs.mjs`(流程)、`prompts.mjs`(指令)、`CONTRACT.md`(新檔案的格式),前端要顯示的話再改 `Project.jsx`。+改步驟時三個地方要一起改:`jobs.ts`(流程)、`prompts.ts`(指令)、`CONTRACT.md`(新檔案的格式),前端要顯示的話再改 `Project.tsx`。參數(平行數、每關輪數)在 `CONFIG`,也可以用環境變數調整。## 6. 介面文字與翻譯-元件裡的介面文字一律寫繁體中文。`app/web/src/i18n.js` 在執行時翻譯整個頁面:英文來自 `EN` 對照表(含數字的字串用 `EN_RE` 樣式),簡體中文由 OpenCC 自動轉換。+元件裡的介面文字一律寫繁體中文。`app/web/src/i18n.ts` 在執行時翻譯整個頁面:英文來自 `EN` 對照表(含數字的字串用 `EN_RE` 樣式),簡體中文由 OpenCC 自動轉換。新增文字時請在 `EN` 補上英文;不該被翻譯的元素(使用者內容、檔名)加 `data-no-i18n`。## 7. 開發diff --git a/start.bat b/start.batindex 0c39dd4..006ddfa 100644--- a/start.bat+++ b/start.bat@@ -4,4 +4,4 @@ cd /d "%~dp0app"if not exist node_modules call npm installif not exist dist call npm run buildstart "" http://localhost:4318-node server\index.mjs+node server\index.tsdiff --git a/start.sh b/start.shindex 9c71348..bf064b7 100644--- a/start.sh+++ b/start.sh@@ -5,4 +5,4 @@ cd "$(dirname "$0")/app"[ -d node_modules ] || npm install[ -d dist ] || npm run build( sleep 2; (command -v xdg-open >/dev/null && xdg-open http://localhost:4318) || (command -v open >/dev/null && open http://localhost:4318) || true ) &-exec node server/index.mjs+exec node server/index.ts