Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Keep fal video prompts within each model's length limit

Claudee5f0b74f636d
diff --git a/server/lib/README.md b/server/lib/README.md
index 1ac30d91de..b79fe5c42f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -323,7 +323,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback; `cleanup({ throwOnError: true })` reports cleanup failure to an owning lifecycle). |
| `filmStyleGrammars.js` | Curated film style grammar catalog (`FILM_STYLE_GRAMMARS`, eight code-rendered media with rendering, colour, type, motion, camera, sound and native-move guidance), `getFilmStyleGrammar`, `summarizeFilmStyleGrammar` (picker projection) and `knownFilmStyleIdSchema` (request-field id check) and `renderFilmStyleGrammarPrompt(id, { parts })` — one prompt section capped at `FILM_STYLE_PROMPT_MAX_CHARS`; unknown id or bad parts is a 400. |
-| `falVideoModels.js` | Curated fal.ai VIDEO model catalog — `FAL_VIDEO_MODELS` (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, OmniHuman v1.5 audio-to-video (`FAL_AUDIO_VIDEO_MODELS`, kind `a2v`: the supplied audio drives the figure's whole motion; LTX audio-to-video runs locally, never on fal), Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on `FAL_VIDEO_PRICING_VERIFIED_AT`; `getFalVideoModel()`, `coerceFalVideoSeconds()` (round UP to a covering length), `resolveFalVideoResolution()`, `buildFalVideoRequest()` (the exact queue body per model; null for an uncurated id, which keeps the legacy body), `estimateFalVideoCostUsd()` (null = unknown), `describeFalVideoRate()`. Dependency-free; the client re-exports it. |
+| `falVideoModels.js` | Curated fal.ai VIDEO model catalog — `FAL_VIDEO_MODELS` (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, OmniHuman v1.5 audio-to-video (`FAL_AUDIO_VIDEO_MODELS`, kind `a2v`: the supplied audio drives the figure's whole motion; LTX audio-to-video runs locally, never on fal), Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on `FAL_VIDEO_PRICING_VERIFIED_AT`; `getFalVideoModel()`, `coerceFalVideoSeconds()` (round UP to a covering length), `resolveFalVideoResolution()`, `buildFalVideoRequest()` (the exact queue body per model; null for an uncurated id, which keeps the legacy body) (a prompt over the model's `promptMaxChars` is cut at a clause boundary and reported as `promptClipped`), `estimateFalVideoCostUsd()` (null = unknown), `describeFalVideoRate()`. Dependency-free; the client re-exports it. |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10, 15]`; 6/10 measured in #3022, where a 2s/3s request returned the same 6.04s clip; 15 from xAI's 1–15 s API limit, confirmed per clip by the probe in `videoGen/grok.js`), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
| `fontMetadata.js` | `fontContainer(buf)` (sfnt / woff2 / null) and `fontFamilyName(buf)` — a font file's family name read from its `name` table (TrueType, OpenType, and WOFF2's brotli stream) with no font library; null for anything unreadable (#10345). |
| `musicVideoCoverOverlay.js` | Music Video cover lettering (#10345): `COVER_DESIGN_OPTIONS` / `DEFAULT_COVER_DESIGN`, `normalizeCoverDesign(design, { fonts })` (accepts every stored design; a `font:<id>` typeface only when that uploaded font is listed), `coverOverlaySvg({ title, tag, design, widths, fonts })` and the `coverFontSpec` / `fontAttrs` / `titleLinesFor` / `tagTextFor` helpers the width probe reads. Pure; the server render (`coverArtCompose.js`) and the client's live Lettering preview run this one layout. |
diff --git a/server/lib/falVideoModels.js b/server/lib/falVideoModels.js
index 1cc91dad34..f310838ea7 100644
--- a/server/lib/falVideoModels.js
+++ b/server/lib/falVideoModels.js
@@ -71,6 +71,8 @@ const seedance = (id, kind, label, extra) => ({
const h3 = (id, label, rates, extra = {}) => ({
id, kind: 'i2v', label, family: 'minimax-h3',
prompt: 'required',
+ // MiniMax's own prompt cap, the same as Hailuo-02's.
+ promptMaxChars: 2000,
image: { param: 'image_url', required: false },
endImage: { param: 'end_image_url' },
duration: { kind: 'range', min: 5, max: 15, wire: 'integer', defaultSec: 5 },
@@ -90,6 +92,8 @@ export const FAL_VIDEO_MODELS = Object.freeze([
{
id: FAL_DEFAULT_IMAGE_VIDEO_MODEL, kind: 'i2v', label: 'MiniMax Hailuo-02 Standard (image)', family: 'hailuo-02',
prompt: 'required',
+ // fal refuses a longer prompt with a 422 after the job is queued.
+ promptMaxChars: 2000,
image: { param: 'image_url', required: true },
endImage: { param: 'end_image_url' },
duration: { kind: 'enum', values: [6, 10], wire: 'string', defaultSec: 6 },
@@ -101,6 +105,7 @@ export const FAL_VIDEO_MODELS = Object.freeze([
{
id: FAL_DEFAULT_TEXT_VIDEO_MODEL, kind: 't2v', label: 'MiniMax Hailuo-02 Standard (text)', family: 'hailuo-02',
prompt: 'required',
+ promptMaxChars: 2000,
duration: { kind: 'enum', values: [6, 10], wire: 'string', defaultSec: 6 },
// Fixed 768P output; the text route takes neither resolution nor aspect ratio.
resolution: null,
@@ -113,6 +118,7 @@ export const FAL_VIDEO_MODELS = Object.freeze([
{
id: 'minimax/h3-max/reference-to-video', kind: 'ref2v', label: 'MiniMax H3 Max (reference)', family: 'minimax-h3',
prompt: 'required',
+ promptMaxChars: 2000,
// Referenced in the prompt as "Image 1", "Audio 1", … in list order.
referenceImages: { param: 'reference_image_urls', max: 9 },
referenceAudio: { param: 'reference_audio_urls', max: 3, minSec: 2, maxSec: 15 },
@@ -176,6 +182,7 @@ export const FAL_VIDEO_MODELS = Object.freeze([
{
id: 'fal-ai/kling-video/v3/pro/image-to-video', kind: 'i2v', label: 'Kling v3 Pro (image)', family: 'kling-v3',
prompt: 'required',
+ promptMaxChars: 2500,
image: { param: 'start_image_url', required: true },
endImage: { param: 'end_image_url' },
duration: { kind: 'range', min: 3, max: 15, wire: 'string', defaultSec: 5 },
@@ -396,6 +403,27 @@ export function describeFalVideoRate(modelId, resolution) {
* master soundtrack (Music Video) or silent-by-default clips; a caller asks for
* provider audio explicitly.
*/
+// The last clause, sentence or line boundary at or before `max`, else a hard cut.
+const clipAtBoundary = (text, max) => {
+ if (text.length <= max) return text;
+ const head = text.slice(0, max);
+ const cut = Math.max(head.lastIndexOf('\n'), head.lastIndexOf(', '), head.lastIndexOf('. '), head.lastIndexOf('; '));
+ return (cut > max / 2 ? head.slice(0, cut) : head).trimEnd();
+};
+
+/**
+ * `text` plus its folded `Avoid:` clause within `max` characters. The Avoid
+ * clause keeps up to a quarter of the budget; the authored text is cut at a
+ * clause boundary. Unchanged when it already fits.
+ */
+function fitFalPrompt(text, avoid, max) {
+ const whole = avoid ? `${text}\nAvoid: ${avoid}` : text;
+ if (whole.length <= max) return whole;
+ const avoidPart = avoid ? `\nAvoid: ${clipAtBoundary(avoid, Math.max(0, Math.floor(max / 4) - 8))}` : '';
+ const keptAvoid = avoidPart.trim() === 'Avoid:' ? '' : avoidPart;
+ return `${clipAtBoundary(text, max - keptAvoid.length)}${keptAvoid}`;
+}
+
export function buildFalVideoRequest({
modelId, prompt = '', negativePrompt = '', seconds, audioSec, aspectRatio, width, height, resolution,
imageUrl = null, endImageUrl = null, referenceImageUrls = [], audioUrl = null, referenceAudioUrls = [],
@@ -408,12 +436,17 @@ export function buildFalVideoRequest({
const text = typeof prompt === 'string' ? prompt.trim() : '';
const avoid = typeof negativePrompt === 'string' ? negativePrompt.trim() : '';
+ let promptClipped = null;
if (model.prompt !== 'none') {
if (model.prompt === 'required' && !text) throw refuse(`${model.label} needs a prompt`);
// No native field: fold the negative prompt into the prompt as an "Avoid:"
// clause — the same fallback grok.js uses for a provider without one.
const folded = model.negativePrompt === 'fold' && avoid ? `${text}\nAvoid: ${avoid}` : text;
- if (folded) body.prompt = folded;
+ // A prompt over the model's cap is refused by fal only after the job is
+ // queued, so it is shortened here: the authored text first, then the Avoid clause.
+ const fitted = model.promptMaxChars ? fitFalPrompt(text, model.negativePrompt === 'fold' ? avoid : '', model.promptMaxChars) : folded;
+ if (fitted.length < folded.length) promptClipped = { from: folded.length, to: fitted.length, max: model.promptMaxChars };
+ if (fitted) body.prompt = fitted;
if (model.negativePrompt === 'native' && avoid) body.negative_prompt = avoid;
}
@@ -460,6 +493,7 @@ export function buildFalVideoRequest({
return {
body,
model,
+ promptClipped,
seconds: coercedSec,
resolution: res,
generateAudio: wantsAudio,
diff --git a/server/lib/falVideoModels.test.js b/server/lib/falVideoModels.test.js
index 76caa829e1..46e9975935 100644
--- a/server/lib/falVideoModels.test.js
+++ b/server/lib/falVideoModels.test.js
@@ -161,3 +161,21 @@ describe('per-clip quotes — what a shot actually bills', () => {
expect(endFrame.map((q) => q.modelId)).not.toContain('fal-ai/veo3.1/fast/image-to-video');
});
});
+
+// Regression: a 2,000+ character prompt reached Hailuo-02, which fal refused with a 422 only after the job was queued.
+describe('buildFalVideoRequest — prompt length caps', () => {
+ it('cuts a prompt over the model limit at a clause boundary and keeps a short Avoid clause', () => {
+ const prompt = Array.from({ length: 300 }, (_, i) => `clause ${i}`).join(', ');
+ const { body, promptClipped } = build('fal-ai/minimax/hailuo-02/standard/image-to-video', { prompt, negativePrompt: 'blur' });
+ expect(body.prompt.length).toBeLessThanOrEqual(2000);
+ expect(body.prompt).toMatch(/clause \d+\nAvoid: blur$/);
+ expect(body.prompt.startsWith('clause 0, clause 1,')).toBe(true);
+ expect(promptClipped).toEqual({ from: prompt.length + '\nAvoid: blur'.length, to: body.prompt.length, max: 2000 });
+ });
+
+ it('leaves a prompt within the limit, and a model without a known limit, untouched', () => {
+ expect(build('fal-ai/minimax/hailuo-02/standard/image-to-video').promptClipped).toBeNull();
+ const long = 'x '.repeat(1500).trim();
+ expect(build('fal-ai/veo3.1/fast/image-to-video', { prompt: long }).body.prompt).toBe(long);
+ });
+});
diff --git a/server/lib/musicVideoMotion.js b/server/lib/musicVideoMotion.js
index b720b4835b..785dbdc561 100644
--- a/server/lib/musicVideoMotion.js
+++ b/server/lib/musicVideoMotion.js
@@ -26,6 +26,23 @@ const SONG_INTENT_LINE = /^(?:Lyric|Word) \d+(?:\.\d+)?s–\d+(?:\.\d+)?s: .*$|^
// Generated shot-intent and camera lines, kept as written.
const CONTRACT_LINE = /^(?:(?:Action|Reaction) \d+(?:\.\d+)?s–|(?:Purpose|Starting emotion|Ending emotion|Active speaker|Camera|Camera movement|Must preserve|Acceptance|Speed|Framing|End):)/;
+// The opening of each block musicVideoCreativeContext() writes. A shot prompt the
+// board composed from an older copy of the project still carries its bible, which
+// the verbatim strip cannot match; the block runs to the clause that follows it.
+const CREATIVE_CONTEXT_START = /Character style \(fixed identity|Universe style: |Look \(palette, light and texture only\): |Mood board look \(palette, lighting and texture only|Production bible \(use the subjects/;
+const CREATIVE_CONTEXT_END = /\n(?=Camera|Shot intent \(clip-relative seconds\):|(?:Action|Reaction) \d)/;
+
+function withoutCreativeContext(text, ends) {
+ let out = text;
+ for (let start = out.search(CREATIVE_CONTEXT_START); start >= 0; start = out.search(CREATIVE_CONTEXT_START)) {
+ const rest = out.slice(start);
+ const stops = [...ends.map((end) => rest.indexOf(end)), rest.search(CREATIVE_CONTEXT_END)].filter((i) => i > 0);
+ const length = stops.length ? Math.min(...stops) : rest.length;
+ out = `${out.slice(0, start)}${out.slice(start + length)}`;
+ }
+ return out;
+}
+
const tidy = (text) => text.replace(/\s+([,.;:])/g, '$1').replace(/([,;])\s*(?=[,;.])/g, '').replace(/[ \t]{2,}/g, ' ').replace(/^[,;\s]+|[,;\s]+$/gm, '');
/**
@@ -36,16 +53,19 @@ const tidy = (text) => text.replace(/\s+([,.;:])/g, '$1').replace(/([,;])\s*(?=[
* then any short subjectless clause naming film stock, grain, lens or grade),
* since the frame already carries the look and these models act style words
* out literally. The shot-intent block keeps its clip-relative actions but
- * drops its lyric, word and onset lines. An audio-driven or lip-sync take keeps
- * its prompt as authored.
+ * drops its lyric, word and onset lines. A creative-context block left over
+ * (the bible from an older copy of the project) is cut up to the first of
+ * `keep`, the continuity clause or the camera and shot-intent lines. An
+ * audio-driven or lip-sync take keeps its prompt as authored.
*/
-export function silentMotionPrompt(prompt, { styleParts = [] } = {}) {
+export function silentMotionPrompt(prompt, { styleParts = [], keep = [] } = {}) {
let text = String(prompt || '');
for (const part of styleParts) {
const trimmed = typeof part === 'string' ? part.trim() : '';
if (trimmed) text = text.split(trimmed).join('');
}
- return text.split('\n')
+ const ends = [MOTION_CONTINUITY_CLAUSE, ...keep].map((part) => (typeof part === 'string' ? part.trim() : '')).filter(Boolean);
+ return withoutCreativeContext(text, ends).split('\n')
.filter((line) => !SONG_INTENT_LINE.test(line.trim()))
.map((line) => {
if (CONTRACT_LINE.test(line.trim())) return line.replace(/; land the move exactly on the downbeat/, '');
diff --git a/server/lib/musicVideoMotion.test.js b/server/lib/musicVideoMotion.test.js
index 880f7a0272..3440fafda9 100644
--- a/server/lib/musicVideoMotion.test.js
+++ b/server/lib/musicVideoMotion.test.js
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { silentMotionPrompt } from './musicVideoMotion.js';
+import { MOTION_CONTINUITY_CLAUSE, silentMotionPrompt } from './musicVideoMotion.js';
+import { musicVideoCreativeContext } from './musicVideoCreativeContext.js';
// Regression: a silent i2v model acted out song cues and look words, and stripping must never erase the action itself.
describe('silentMotionPrompt', () => {
@@ -23,4 +24,15 @@ describe('silentMotionPrompt', () => {
expect(silentMotionPrompt(prompt, { styleParts: ['grainy 35mm look'] })).toBe(
'She runs\nCamera movement: Push in — slow push\nSpeed: Slow.\nAction 0.000s–1.000s: Singer — Offers a hand');
});
+
+ // Regression: a board holding an older copy of the project sent its whole bible to Hailuo-02, which refused the 2,000+ character prompt.
+ it('cuts a creative-context block the verbatim strip cannot match, up to the motion clause', () => {
+ const subjects = (description) => [{ kind: 'character', role: 'lead', name: 'Example Lead', description },
+ { kind: 'location', name: 'Example Diner', description: 'a chrome diner at night, neon in the window' }];
+ const stale = musicVideoCreativeContext({ universeStyle: 'Example universe look', subjects: subjects('red jacket, short hair') }, { moodBoard: false });
+ const current = musicVideoCreativeContext({ universeStyle: 'Example universe look', subjects: subjects('black sweater, short hair') }, { moodBoard: false });
+ const prompt = [`She shakes her head, ${stale}; warm practical light, one slow beat, ${MOTION_CONTINUITY_CLAUSE}`, 'Camera: static'].join('\n');
+ expect(silentMotionPrompt(prompt, { styleParts: [current], keep: ['one slow beat'] }))
+ .toBe(`She shakes her head, one slow beat, ${MOTION_CONTINUITY_CLAUSE}\nCamera: static`);
+ });
});
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
index 47b1d5f7ad..a1a78aaa18 100644
--- a/server/services/videoGen/fal.js
+++ b/server/services/videoGen/fal.js
@@ -210,6 +210,11 @@ export async function generateVideo({
throw new ServerError(err.message, { status: 400, code: 'VALIDATION_ERROR' });
}
+ if (planned?.promptClipped) {
+ const { from, to, max } = planned.promptClipped;
+ console.warn(`✂️ fal prompt for ${modelId} shortened ${from} → ${to} chars (model limit ${max})`);
+ }
+
if (lastImagePath && !planned) {
throw new ServerError('End frames require a fal.ai model with catalogued end-frame support', { status: 400, code: 'VALIDATION_ERROR' });
}
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index 62eee838cd..6425264ce4 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -43,12 +43,12 @@ const musicVideoProjectAspect = async (projectId) => {
return musicVideoAspect(await getProject(projectId));
};
/** A Music Video motion prompt for a take that hears no audio, with the project's look clauses removed. */
-async function silentMusicVideoMotionPrompt(prompt, project) {
+async function silentMusicVideoMotionPrompt(prompt, project, scene) {
const [{ silentMotionPrompt }, { musicVideoCreativeContext }, { visualDirection }] = await Promise.all([
import('../../lib/musicVideoMotion.js'), import('../../lib/musicVideoCreativeContext.js'), import('../musicVideo/handoff.js'),
]);
return silentMotionPrompt(prompt, { styleParts: [project?.concept?.style, musicVideoCreativeContext(project?.concept, { moodBoard: false }),
- visualDirection(project?.visualSpec)].filter(Boolean) });
+ visualDirection(project?.visualSpec)].filter(Boolean), keep: [scene?.direction?.motionClause] });
}
const submitValidatedVideoGenJob = async (body, uploads) => {
@@ -314,7 +314,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
// motion: the model would act out song cues and look words instead of reading them.
const hearsAudio = !!(performance || prepared.audio || params.audioConditioning || params.audioFilePath);
params.prompt = withShotActionPrompt(params.prompt, project, scene, { offsetSec: performance?.shotInstruction?.edit?.inSec || 0 });
- if (!hearsAudio) params.prompt = await silentMusicVideoMotionPrompt(params.prompt, project);
+ if (!hearsAudio) params.prompt = await silentMusicVideoMotionPrompt(params.prompt, project, scene);
const interval = performance?.shotInstruction?.songInterval || prepared.audio?.songInterval;
if (params.audioConditioning && Math.round(scene?.startSec * 48000) !== params.audioConditioning.startSample) {
throw new ServerError('Scene timing changed while source audio was prepared', { status: 409, code: 'MUSIC_VIDEO_SHOT_TIMING_CHANGED' });