-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode2mp4-cli.ts
More file actions
236 lines (213 loc) · 6.84 KB
/
code2mp4-cli.ts
File metadata and controls
236 lines (213 loc) · 6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env node
/**
* Code2MP4 CLI — the agent-facing dispatcher.
*
* Agents call `code2mp4 media generate ...` to request media
* generation (HyperFrames render) from the daemon. The daemon runs
* the unsandboxed render and streams progress back.
*
* Also handles: media wait, health
*/
const DAEMON_URL = process.env.C2M_DAEMON_URL ?? 'http://localhost:7456';
async function main(): Promise<void> {
const args = process.argv.slice(2);
const cmd = args[0];
if (!cmd) {
console.error('Usage: od <command> [options]');
console.error('Commands: media generate, media wait, health');
process.exit(1);
}
if (cmd === 'health') {
await handleHealth();
} else if (cmd === 'media') {
const sub = args[1];
if (sub === 'generate') {
await handleMediaGenerate(args.slice(2));
} else if (sub === 'wait') {
await handleMediaWait(args.slice(2));
} else {
console.error('code2mp4 media: expected generate or wait');
process.exit(1);
}
} else {
console.error(`Unknown command: ${cmd}`);
process.exit(1);
}
}
async function handleHealth(): Promise<void> {
try {
const res = await fetch(`${DAEMON_URL}/api/health`);
const body = await res.json();
console.log(JSON.stringify(body));
process.exit(res.ok ? 0 : 1);
} catch (err) {
console.error(`WARN: failed to reach daemon at ${DAEMON_URL}: ${(err as Error).message}`);
process.exit(5);
}
}
async function handleMediaGenerate(args: string[]): Promise<void> {
const params = parseNamedArgs(args, {
project: 'string',
surface: 'string',
model: 'string',
output: 'string',
'composition-dir': 'string',
aspect: 'string',
length: 'number',
fps: 'number',
quality: 'string',
prompt: 'string',
voice: 'string',
speed: 'number',
'audio-kind': 'string',
'sfx-kind': 'string',
'sfx-duration': 'number',
'sfx-frequency': 'number',
'sfx-volume': 'number',
});
const project = params.project;
if (!project) {
console.error('Error: --project <project-id> is required');
process.exit(1);
}
const surface = params.surface ?? 'video';
const model = params.model ?? 'hyperframes-html';
// Build the request body
const body: Record<string, unknown> = {
projectId: project,
surface,
model,
output: params.output ?? 'output.mp4',
compositionDir: params['composition-dir'],
aspect: params.aspect,
length: params.length,
fps: params.fps,
quality: params.quality ?? 'standard',
prompt: params.prompt,
voice: params.voice,
speed: params.speed,
audioKind: params['audio-kind'],
sfxKind: params['sfx-kind'],
sfxDuration: params['sfx-duration'],
sfxFrequency: params['sfx-frequency'],
sfxVolume: params['sfx-volume'],
};
try {
const res = await fetch(`${DAEMON_URL}/api/media/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
const errBody = await res.text();
console.error(`WARN: daemon returned ${res.status}: ${errBody.slice(0, 500)}`);
process.exit(5);
}
const result = await res.json() as { taskId?: string; file?: { name: string; size: number; kind: string } };
// If the task is async (long-running), return taskId for wait loop
if (result.taskId) {
console.log(JSON.stringify({
taskId: result.taskId,
status: 'running',
nextSince: 0,
}));
process.exit(2); // exit 2 = still running, caller should poll
} else if (result.file) {
// Completed synchronously
console.log(JSON.stringify({ file: result.file }));
process.exit(0);
} else {
console.log(JSON.stringify(result));
process.exit(0);
}
} catch (err) {
console.error(`WARN: failed to reach daemon at ${DAEMON_URL}: ${(err as Error).message}`);
process.exit(5);
}
}
async function handleMediaWait(args: string[]): Promise<void> {
const taskId = args[0];
const sinceIdx = args.indexOf('--since');
const since = sinceIdx >= 0 ? parseInt(args[sinceIdx + 1], 10) : 0;
if (!taskId) {
console.error('Usage: code2mp4 media wait <taskId> [--since N]');
process.exit(1);
}
try {
const res = await fetch(`${DAEMON_URL}/api/media/wait/${taskId}?since=${since}`, {
headers: { Accept: 'text/event-stream' },
// Long poll: 25s timeout
signal: AbortSignal.timeout(25_000),
});
if (!res.ok) {
console.error(`WARN: daemon returned ${res.status}`);
process.exit(5);
}
const text = await res.text();
// Parse SSE to extract progress and final result
const lines = text.split('\n');
let lastData = '';
for (const line of lines) {
if (line.startsWith('data: ')) {
lastData = line.slice(6);
// Stream progress to stderr for agent visibility
const parsed = JSON.parse(lastData);
if (parsed.type === 'progress') {
console.error(`Capturing frame ${parsed.frame}/${parsed.totalFrames}`);
}
}
}
if (!lastData) {
console.log(JSON.stringify({ taskId, status: 'running', nextSince: since }));
process.exit(2);
}
const final = JSON.parse(lastData);
if (final.type === 'complete') {
console.log(JSON.stringify({ file: { name: final.outputPath, size: final.fileSize, kind: 'video' } }));
process.exit(0);
} else if (final.type === 'error') {
console.error(`WARN: ${final.message}`);
process.exit(5);
} else {
// Still running
console.log(JSON.stringify({ taskId, status: 'running', nextSince: since + 1 }));
process.exit(2);
}
} catch (err) {
if ((err as Error).name === 'TimeoutError') {
// Long poll timed out — still running
console.log(JSON.stringify({ taskId, status: 'running', nextSince: since }));
process.exit(2);
}
console.error(`WARN: ${(err as Error).message}`);
process.exit(5);
}
}
// ── Arg parser ────────────────────────────────────────────────────────
function parseNamedArgs(
args: string[],
spec: Record<string, 'string' | 'number'>,
): Record<string, string | number | undefined> {
const result: Record<string, string | number | undefined> = {};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg.startsWith('--')) {
const key = arg.slice(2);
const type = spec[key];
if (type) {
const val = args[i + 1];
if (val && !val.startsWith('--')) {
result[key] = type === 'number' ? Number(val) : val;
i++;
} else {
result[key] = type === 'number' ? undefined : '';
}
}
}
}
return result;
}
main().catch((err) => {
console.error(`od: fatal error: ${err.message}`);
process.exit(1);
});