vibedgames 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/commands/completions.js +3 -0
- package/dist/commands/deploy.js +21 -2
- package/dist/commands/factory.d.ts +3 -0
- package/dist/commands/factory.js +70 -0
- package/dist/commands/generate.js +77 -7
- package/dist/commands/init.js +1 -9
- package/dist/commands/login.js +1 -5
- package/dist/commands/new.js +61 -3
- package/dist/commands/update.d.ts +13 -0
- package/dist/commands/update.js +68 -0
- package/dist/commands/whoami.js +18 -14
- package/dist/index.js +18 -1
- package/dist/lib/codex.d.ts +84 -0
- package/dist/lib/codex.js +347 -0
- package/dist/lib/config.d.ts +1 -0
- package/dist/lib/config.js +1 -1
- package/dist/lib/media-args.js +8 -1
- package/dist/lib/media-download.d.ts +1 -0
- package/dist/lib/media-download.js +24 -4
- package/dist/lib/media-poll.d.ts +1 -1
- package/dist/lib/media-poll.js +3 -3
- package/dist/lib/media-upload.d.ts +1 -1
- package/dist/lib/media-upload.js +2 -2
- package/dist/lib/run.d.ts +5 -0
- package/dist/lib/run.js +9 -0
- package/dist/lib/update.d.ts +10 -0
- package/dist/lib/update.js +98 -0
- package/package.json +8 -8
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
5
|
+
import spawn from "cross-spawn";
|
|
6
|
+
import { readExplicitLocalFile } from "./media-args.js";
|
|
7
|
+
import { disambiguateTargets } from "./media-download.js";
|
|
8
|
+
/**
|
|
9
|
+
* Expected, user-facing failure of the codex provider. Carries a clean
|
|
10
|
+
* message plus any output Codex itself emitted, so the caller can present
|
|
11
|
+
* it directly instead of dumping a stack trace. `notInstalled` flags the
|
|
12
|
+
* "`codex` binary missing" case so callers can suggest a fallback.
|
|
13
|
+
*/
|
|
14
|
+
export class CodexError extends Error {
|
|
15
|
+
notInstalled;
|
|
16
|
+
output;
|
|
17
|
+
constructor(message, opts = {}) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "CodexError";
|
|
20
|
+
this.notInstalled = opts.notInstalled ?? false;
|
|
21
|
+
this.output = opts.output ?? "";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Resolve the effective provider from the `--provider` flag, falling back
|
|
26
|
+
* to the `VG_GENERATE_PROVIDER` env var and finally the vibedgames
|
|
27
|
+
* default. Unknown values throw so a typo (`--provider coddex`) fails
|
|
28
|
+
* loudly instead of silently hitting the paid backend.
|
|
29
|
+
*/
|
|
30
|
+
export function resolveProvider(flag) {
|
|
31
|
+
const raw = (flag ?? process.env.VG_GENERATE_PROVIDER ?? "").trim().toLowerCase();
|
|
32
|
+
if (raw === "codex")
|
|
33
|
+
return "codex";
|
|
34
|
+
if (raw === "" || raw === "vibedgames" || raw === "fal" || raw === "default") {
|
|
35
|
+
return "vibedgames";
|
|
36
|
+
}
|
|
37
|
+
throw new Error(`Unknown --provider "${raw}". Supported: vibedgames (default), codex.`);
|
|
38
|
+
}
|
|
39
|
+
// Input keys we map onto Codex's natural-language image request. Codex
|
|
40
|
+
// only exposes a single built-in image model, so most fal-style params
|
|
41
|
+
// don't apply — we fold the few that have a meaning (prompt, count,
|
|
42
|
+
// size, reference images) into the prompt / CLI flags and ignore the
|
|
43
|
+
// rest rather than erroring.
|
|
44
|
+
const PROMPT_KEYS = ["prompt", "text"];
|
|
45
|
+
const COUNT_KEYS = ["num_images", "num_outputs", "n", "count"];
|
|
46
|
+
const REF_KEYS = [
|
|
47
|
+
"image_url",
|
|
48
|
+
"image_urls",
|
|
49
|
+
"image",
|
|
50
|
+
"images",
|
|
51
|
+
"input_image",
|
|
52
|
+
"reference_image_url",
|
|
53
|
+
"reference_image_urls",
|
|
54
|
+
];
|
|
55
|
+
const MAX_IMAGES = 8;
|
|
56
|
+
const IMAGE_EXT = new Set(["png", "jpg", "jpeg", "webp", "gif"]);
|
|
57
|
+
/**
|
|
58
|
+
* Pull the fields Codex can act on out of the parsed `run` input. Pure:
|
|
59
|
+
* no filesystem access, so the reference values are returned verbatim and
|
|
60
|
+
* resolved to local files later.
|
|
61
|
+
*/
|
|
62
|
+
export function parseCodexInput(input) {
|
|
63
|
+
let prompt = "";
|
|
64
|
+
for (const key of PROMPT_KEYS) {
|
|
65
|
+
const v = input[key];
|
|
66
|
+
if (typeof v === "string" && v.trim().length > 0) {
|
|
67
|
+
prompt = v.trim();
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
let count = 1;
|
|
72
|
+
for (const key of COUNT_KEYS) {
|
|
73
|
+
const v = input[key];
|
|
74
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
75
|
+
count = Math.max(1, Math.min(MAX_IMAGES, Math.floor(v)));
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const referenceCandidates = [];
|
|
80
|
+
for (const key of REF_KEYS) {
|
|
81
|
+
const v = input[key];
|
|
82
|
+
if (typeof v === "string")
|
|
83
|
+
referenceCandidates.push(v);
|
|
84
|
+
else if (Array.isArray(v)) {
|
|
85
|
+
for (const item of v)
|
|
86
|
+
if (typeof item === "string")
|
|
87
|
+
referenceCandidates.push(item);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { prompt, count, sizeHint: buildSizeHint(input), referenceCandidates };
|
|
91
|
+
}
|
|
92
|
+
function buildSizeHint(input) {
|
|
93
|
+
const parts = [];
|
|
94
|
+
const size = input.image_size ?? input.size;
|
|
95
|
+
if (typeof size === "string" && size.trim().length > 0)
|
|
96
|
+
parts.push(size.trim());
|
|
97
|
+
const aspect = input.aspect_ratio;
|
|
98
|
+
if (typeof aspect === "string" && aspect.trim().length > 0) {
|
|
99
|
+
parts.push(`aspect ratio ${aspect.trim()}`);
|
|
100
|
+
}
|
|
101
|
+
const w = input.width;
|
|
102
|
+
const h = input.height;
|
|
103
|
+
if (typeof w === "number" && typeof h === "number")
|
|
104
|
+
parts.push(`${w}x${h}px`);
|
|
105
|
+
return parts.length > 0 ? parts.join(", ") : undefined;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Build the natural-language instruction handed to `codex exec`. We pin
|
|
109
|
+
* exact output filenames and the working directory so the generated
|
|
110
|
+
* files land somewhere we can deterministically collect them.
|
|
111
|
+
*/
|
|
112
|
+
export function buildCodexPrompt(input, filenames, hasReferences) {
|
|
113
|
+
const n = filenames.length;
|
|
114
|
+
const noun = n === 1 ? "image" : `${n} images`;
|
|
115
|
+
const lines = [
|
|
116
|
+
hasReferences
|
|
117
|
+
? `Edit the attached reference image to produce ${noun} using your built-in image generation.`
|
|
118
|
+
: `Generate ${noun} using your built-in image generation.`,
|
|
119
|
+
`Prompt: ${input.prompt}`,
|
|
120
|
+
];
|
|
121
|
+
if (input.sizeHint)
|
|
122
|
+
lines.push(`Size: ${input.sizeHint}.`);
|
|
123
|
+
lines.push(`Save the output as PNG into the current working directory using exactly ` +
|
|
124
|
+
`these filenames: ${filenames.join(", ")}.`, `Do not read, create, or modify any other files, and do not write or run code. $imagegen`);
|
|
125
|
+
return lines.join("\n");
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Choose the on-disk destination for a collected Codex output, mirroring
|
|
129
|
+
* the `--download` template semantics used for the vibedgames path
|
|
130
|
+
* ({index}, {ext}, {request_id} placeholders; bare path treated as a
|
|
131
|
+
* directory or a literal file by extension).
|
|
132
|
+
*/
|
|
133
|
+
export function renderLocalTarget(template, index, ext, requestId, count) {
|
|
134
|
+
if (!template) {
|
|
135
|
+
return resolve(process.cwd(), `codex-image-${requestId}-${index}.${ext}`);
|
|
136
|
+
}
|
|
137
|
+
if (template.includes("{")) {
|
|
138
|
+
const rendered = template
|
|
139
|
+
.replaceAll("{index}", String(index))
|
|
140
|
+
.replaceAll("{ext}", ext)
|
|
141
|
+
.replaceAll("{request_id}", requestId)
|
|
142
|
+
.replaceAll("{name}", "output");
|
|
143
|
+
return resolve(rendered);
|
|
144
|
+
}
|
|
145
|
+
if (extname(template)) {
|
|
146
|
+
if (count <= 1)
|
|
147
|
+
return resolve(template);
|
|
148
|
+
const e = extname(template);
|
|
149
|
+
const stem = template.slice(0, template.length - e.length);
|
|
150
|
+
return resolve(index === 0 ? template : `${stem}_${index}${e}`);
|
|
151
|
+
}
|
|
152
|
+
return resolve(template, `codex-image-${index}.${ext}`);
|
|
153
|
+
}
|
|
154
|
+
function codexHome() {
|
|
155
|
+
return process.env.CODEX_HOME ?? join(homedir(), ".codex");
|
|
156
|
+
}
|
|
157
|
+
function listImages(dir) {
|
|
158
|
+
let names;
|
|
159
|
+
try {
|
|
160
|
+
names = readdirSync(dir);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
const out = [];
|
|
166
|
+
for (const name of names) {
|
|
167
|
+
const ext = extname(name).slice(1).toLowerCase();
|
|
168
|
+
if (!IMAGE_EXT.has(ext))
|
|
169
|
+
continue;
|
|
170
|
+
const full = join(dir, name);
|
|
171
|
+
try {
|
|
172
|
+
if (statSync(full).isFile())
|
|
173
|
+
out.push(full);
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
// Raced away between readdir and stat; skip.
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return out.toSorted();
|
|
180
|
+
}
|
|
181
|
+
// Keep the `limit` most-recently-modified paths (by mtime), returned in
|
|
182
|
+
// stable name order. Used to bound the shared-store fallback.
|
|
183
|
+
function pickNewest(paths, limit) {
|
|
184
|
+
if (paths.length <= limit)
|
|
185
|
+
return paths;
|
|
186
|
+
const withTime = paths.map((p) => {
|
|
187
|
+
let mtimeMs = 0;
|
|
188
|
+
try {
|
|
189
|
+
mtimeMs = statSync(p).mtimeMs;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// Gone between listing and stat; sort it oldest.
|
|
193
|
+
}
|
|
194
|
+
return { p, mtimeMs };
|
|
195
|
+
});
|
|
196
|
+
return withTime
|
|
197
|
+
.toSorted((a, b) => b.mtimeMs - a.mtimeMs)
|
|
198
|
+
.slice(0, limit)
|
|
199
|
+
.map((x) => x.p)
|
|
200
|
+
.toSorted();
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Delegate image generation to the local `codex` CLI. Runs
|
|
204
|
+
* `codex exec` in an isolated temp workspace, then collects the produced
|
|
205
|
+
* images from that workspace (and, as a fallback, from Codex's default
|
|
206
|
+
* `generated_images` store). Throws with actionable guidance when Codex
|
|
207
|
+
* is missing, fails, or produces nothing.
|
|
208
|
+
*/
|
|
209
|
+
export async function generateImagesWithCodex(opts) {
|
|
210
|
+
const parsed = parseCodexInput(opts.input);
|
|
211
|
+
if (!parsed.prompt) {
|
|
212
|
+
throw new CodexError("codex image generation requires a prompt (--prompt).");
|
|
213
|
+
}
|
|
214
|
+
// Codex can only attach on-disk references. Record any non-local ones
|
|
215
|
+
// (e.g. uploaded URLs) so the caller can surface them even under --json,
|
|
216
|
+
// rather than silently generating plain text-to-image.
|
|
217
|
+
const references = [];
|
|
218
|
+
const ignoredReferences = [];
|
|
219
|
+
for (const candidate of parsed.referenceCandidates) {
|
|
220
|
+
const local = readExplicitLocalFile(candidate);
|
|
221
|
+
if (local)
|
|
222
|
+
references.push(local.path);
|
|
223
|
+
else
|
|
224
|
+
ignoredReferences.push(candidate);
|
|
225
|
+
}
|
|
226
|
+
const requestId = randomBytes(4).toString("hex");
|
|
227
|
+
const workDir = mkdtempSync(join(tmpdir(), "vg-codex-"));
|
|
228
|
+
const filenames = Array.from({ length: parsed.count }, (_, i) => `output-${i}.png`);
|
|
229
|
+
const prompt = buildCodexPrompt(parsed, filenames, references.length > 0);
|
|
230
|
+
const bin = process.env.VG_CODEX_BIN ?? "codex";
|
|
231
|
+
const args = [
|
|
232
|
+
"exec",
|
|
233
|
+
"--skip-git-repo-check",
|
|
234
|
+
"-s",
|
|
235
|
+
"workspace-write",
|
|
236
|
+
"-C",
|
|
237
|
+
workDir,
|
|
238
|
+
...references.flatMap((r) => ["-i", r]),
|
|
239
|
+
prompt,
|
|
240
|
+
];
|
|
241
|
+
// Snapshot Codex's default image store so we can tell which files this
|
|
242
|
+
// run produced if the model saves there instead of the workspace.
|
|
243
|
+
const storeDir = join(codexHome(), "generated_images");
|
|
244
|
+
const before = new Set(listImages(storeDir));
|
|
245
|
+
const outcome = await spawnCodex(bin, args, workDir);
|
|
246
|
+
if (outcome.notFound) {
|
|
247
|
+
throw new CodexError(`The \`codex\` CLI was not found on PATH. Install it (npm install -g @openai/codex) ` +
|
|
248
|
+
`and sign in with \`codex login\`, or drop --provider codex to use vibedgames. ` +
|
|
249
|
+
`Set VG_CODEX_BIN to point at a specific binary.`, { notInstalled: true });
|
|
250
|
+
}
|
|
251
|
+
if (outcome.code !== 0) {
|
|
252
|
+
throw new CodexError(`codex exec exited with code ${outcome.code}.`, {
|
|
253
|
+
output: outcome.output,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
// Prefer the exact filenames we pinned in the prompt — those are the
|
|
257
|
+
// images Codex produced for this run. A stray/incidental PNG in the
|
|
258
|
+
// workspace must NOT count as output nor suppress the store fallback.
|
|
259
|
+
const pinned = new Set(filenames);
|
|
260
|
+
const fromWork = listImages(workDir);
|
|
261
|
+
const pinnedWork = fromWork.filter((p) => pinned.has(basename(p)));
|
|
262
|
+
// Fallback for when Codex ignored the workspace and wrote to its shared
|
|
263
|
+
// store instead. That store is not scoped to this invocation, so cap to
|
|
264
|
+
// the newest `count` new files to limit picking up a concurrent run's
|
|
265
|
+
// outputs (best-effort — Codex names store files itself, so there's no
|
|
266
|
+
// requestId to match on).
|
|
267
|
+
const fromStore = pickNewest(listImages(storeDir).filter((p) => !before.has(p)), parsed.count);
|
|
268
|
+
// Pinned workspace files win; then the store; then, as a last resort,
|
|
269
|
+
// any workspace PNG (Codex saved images but chose different names) —
|
|
270
|
+
// capped to `count` like the store branch so an unexpected extra file
|
|
271
|
+
// can't inflate the output set.
|
|
272
|
+
const rawFiles = pinnedWork.length > 0
|
|
273
|
+
? pinnedWork
|
|
274
|
+
: fromStore.length > 0
|
|
275
|
+
? fromStore
|
|
276
|
+
: pickNewest(fromWork, parsed.count);
|
|
277
|
+
if (rawFiles.length === 0) {
|
|
278
|
+
throw new CodexError(`codex produced no image files. It may have declined the request or lack ` +
|
|
279
|
+
`image-generation access on the signed-in plan.`, { output: outcome.output });
|
|
280
|
+
}
|
|
281
|
+
return { requestId, prompt, rawFiles, ignoredReferences };
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Copy Codex's raw outputs to their final destinations per the
|
|
285
|
+
* `--download` template (or default cwd naming). Returns the written
|
|
286
|
+
* paths and any per-file failures.
|
|
287
|
+
*/
|
|
288
|
+
export function placeCodexOutputs(rawFiles, template, requestId) {
|
|
289
|
+
const downloaded = [];
|
|
290
|
+
// Keyed `url` (holding the source path) to match the shape the
|
|
291
|
+
// vibedgames run/status paths use for `download_failures`, so agents
|
|
292
|
+
// reading `download_failures[].url` on the shared --json surface work
|
|
293
|
+
// uniformly across providers.
|
|
294
|
+
const failed = [];
|
|
295
|
+
// Render every target first, then disambiguate colliding paths the same
|
|
296
|
+
// way downloadMedia does — a multi-image run with a template that lacks
|
|
297
|
+
// {index} (e.g. `{request_id}.{ext}` or a fixed filename) would
|
|
298
|
+
// otherwise overwrite earlier outputs while still reporting each path.
|
|
299
|
+
const rendered = rawFiles.map((source, index) => {
|
|
300
|
+
const ext = extname(source).slice(1).toLowerCase() || "png";
|
|
301
|
+
return renderLocalTarget(template, index, ext, requestId, rawFiles.length);
|
|
302
|
+
});
|
|
303
|
+
const targets = disambiguateTargets(rendered);
|
|
304
|
+
rawFiles.forEach((source, index) => {
|
|
305
|
+
const target = targets[index];
|
|
306
|
+
try {
|
|
307
|
+
if (resolve(source) !== target) {
|
|
308
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
309
|
+
copyFileSync(source, target);
|
|
310
|
+
}
|
|
311
|
+
downloaded.push(target);
|
|
312
|
+
}
|
|
313
|
+
catch (err) {
|
|
314
|
+
failed.push({ url: source, error: err instanceof Error ? err.message : String(err) });
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
return { downloaded, failed };
|
|
318
|
+
}
|
|
319
|
+
function spawnCodex(bin, args, cwd) {
|
|
320
|
+
return new Promise((resolvePromise) => {
|
|
321
|
+
const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
322
|
+
let output = "";
|
|
323
|
+
// Forward Codex's own stdout/stderr straight to our stderr so the user
|
|
324
|
+
// sees its progress and messages directly. It goes to stderr (never
|
|
325
|
+
// stdout) so it can't corrupt our `--json` payload. We also buffer it
|
|
326
|
+
// so a failure can surface the tail even for a caller that isn't
|
|
327
|
+
// watching the live stream.
|
|
328
|
+
child.stdout?.on("data", (c) => {
|
|
329
|
+
output += c.toString("utf8");
|
|
330
|
+
process.stderr.write(c);
|
|
331
|
+
});
|
|
332
|
+
child.stderr?.on("data", (c) => {
|
|
333
|
+
output += c.toString("utf8");
|
|
334
|
+
process.stderr.write(c);
|
|
335
|
+
});
|
|
336
|
+
child.on("error", (err) => {
|
|
337
|
+
resolvePromise({
|
|
338
|
+
code: 1,
|
|
339
|
+
output: output + err.message,
|
|
340
|
+
notFound: err.code === "ENOENT",
|
|
341
|
+
});
|
|
342
|
+
});
|
|
343
|
+
child.on("close", (code) => {
|
|
344
|
+
resolvePromise({ code: code ?? 1, output, notFound: false });
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
}
|
package/dist/lib/config.d.ts
CHANGED
package/dist/lib/config.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
function getConfigDir() {
|
|
4
|
+
export function getConfigDir() {
|
|
5
5
|
const xdg = process.env.XDG_CONFIG_HOME;
|
|
6
6
|
const base = xdg ?? join(homedir(), ".config");
|
|
7
7
|
return join(base, "vg");
|
package/dist/lib/media-args.js
CHANGED
|
@@ -7,7 +7,14 @@ import { basename, extname, isAbsolute, join, resolve } from "node:path";
|
|
|
7
7
|
// here: it's a `vg generate status` flag, not a `run` flag, so swallowing it
|
|
8
8
|
// would block users from passing a legitimate `logs` parameter to a
|
|
9
9
|
// model endpoint.
|
|
10
|
-
const RUN_RESERVED_FLAGS = new Set([
|
|
10
|
+
const RUN_RESERVED_FLAGS = new Set([
|
|
11
|
+
"--json",
|
|
12
|
+
"--help",
|
|
13
|
+
"--quiet",
|
|
14
|
+
"--async",
|
|
15
|
+
"--download",
|
|
16
|
+
"--provider",
|
|
17
|
+
]);
|
|
11
18
|
/**
|
|
12
19
|
* Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
|
|
13
20
|
* values that look like JSON (true/false/null/numbers/objects/arrays) and
|
|
@@ -5,8 +5,23 @@ import { isRecord } from "./types.js";
|
|
|
5
5
|
// response payloads where `content_type` is missing (some endpoints
|
|
6
6
|
// omit it).
|
|
7
7
|
const MEDIA_EXT = new Set([
|
|
8
|
-
"png",
|
|
9
|
-
"
|
|
8
|
+
"png",
|
|
9
|
+
"jpg",
|
|
10
|
+
"jpeg",
|
|
11
|
+
"webp",
|
|
12
|
+
"gif",
|
|
13
|
+
"bmp",
|
|
14
|
+
"tif",
|
|
15
|
+
"tiff",
|
|
16
|
+
"avif",
|
|
17
|
+
"mp4",
|
|
18
|
+
"mov",
|
|
19
|
+
"webm",
|
|
20
|
+
"mp3",
|
|
21
|
+
"wav",
|
|
22
|
+
"ogg",
|
|
23
|
+
"flac",
|
|
24
|
+
"m4a",
|
|
10
25
|
]);
|
|
11
26
|
/**
|
|
12
27
|
* Walk a fal result payload and pull out anything that looks like a media
|
|
@@ -131,12 +146,17 @@ export async function downloadMedia(opts) {
|
|
|
131
146
|
// Handle both POSIX and Windows separators regardless of host OS so a
|
|
132
147
|
// `..\\..\\evil` payload sent to a Linux client is still flattened.
|
|
133
148
|
function sanitizeFilename(name) {
|
|
134
|
-
const base = name
|
|
149
|
+
const base = name
|
|
150
|
+
.replace(/[\\/]+/g, "/")
|
|
151
|
+
.split("/")
|
|
152
|
+
.pop() ?? "";
|
|
135
153
|
if (!base || base === "." || base === "..")
|
|
136
154
|
return null;
|
|
137
155
|
return base;
|
|
138
156
|
}
|
|
139
|
-
|
|
157
|
+
// Exported so the codex provider (lib/codex.ts) reuses identical
|
|
158
|
+
// `_1`/`_2` collision-suffix behavior when placing its local outputs.
|
|
159
|
+
export function disambiguateTargets(paths) {
|
|
140
160
|
const counts = new Map();
|
|
141
161
|
for (const p of paths)
|
|
142
162
|
counts.set(p, (counts.get(p) ?? 0) + 1);
|
package/dist/lib/media-poll.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ type CompletedResult = {
|
|
|
9
9
|
/**
|
|
10
10
|
* Poll fal's queue from the client side until the job reaches a
|
|
11
11
|
* terminal status, then fetch the result. The Worker isn't in the
|
|
12
|
-
* loop — it's only along for each individual `
|
|
12
|
+
* loop — it's only along for each individual `generate.forward` hop.
|
|
13
13
|
*/
|
|
14
14
|
export declare function waitForCompletion(client: Client, endpoint_id: string, request_id: string, opts: {
|
|
15
15
|
quiet: boolean;
|
package/dist/lib/media-poll.js
CHANGED
|
@@ -25,7 +25,7 @@ const POLL_TIMEOUT_MS = 30 * 60 * 1000;
|
|
|
25
25
|
/**
|
|
26
26
|
* Poll fal's queue from the client side until the job reaches a
|
|
27
27
|
* terminal status, then fetch the result. The Worker isn't in the
|
|
28
|
-
* loop — it's only along for each individual `
|
|
28
|
+
* loop — it's only along for each individual `generate.forward` hop.
|
|
29
29
|
*/
|
|
30
30
|
export async function waitForCompletion(client, endpoint_id, request_id, opts) {
|
|
31
31
|
const ep = queueAppId(endpoint_id);
|
|
@@ -37,7 +37,7 @@ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
|
|
|
37
37
|
`(endpoint=${endpoint_id} request_id=${request_id}). ` +
|
|
38
38
|
`Use \`vg generate status ${endpoint_id} ${request_id} --result\` to check later.`);
|
|
39
39
|
}
|
|
40
|
-
const raw = await client.
|
|
40
|
+
const raw = await client.generate.forward.mutate({
|
|
41
41
|
target: "queue",
|
|
42
42
|
method: "GET",
|
|
43
43
|
path: `/${ep}/requests/${request_id}/status`,
|
|
@@ -58,7 +58,7 @@ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
|
|
|
58
58
|
}
|
|
59
59
|
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
|
|
60
60
|
}
|
|
61
|
-
const result = await client.
|
|
61
|
+
const result = await client.generate.forward.mutate({
|
|
62
62
|
target: "queue",
|
|
63
63
|
method: "GET",
|
|
64
64
|
path: `/${ep}/requests/${request_id}`,
|
|
@@ -3,7 +3,7 @@ import type { LocalFile } from "./media-args.js";
|
|
|
3
3
|
type Client = ReturnType<typeof createClient>;
|
|
4
4
|
/**
|
|
5
5
|
* Upload one local file directly to fal's CDN. The proxy hands us a
|
|
6
|
-
* presigned upload slot (upload_url + file_url) via the `
|
|
6
|
+
* presigned upload slot (upload_url + file_url) via the `generate.forward`
|
|
7
7
|
* storage target; bytes go straight from the client to fal, never
|
|
8
8
|
* through the worker. The returned file_url is a stable fal CDN URL
|
|
9
9
|
* that can be reused across runs without re-uploading.
|
package/dist/lib/media-upload.js
CHANGED
|
@@ -2,13 +2,13 @@ import { openAsBlob } from "node:fs";
|
|
|
2
2
|
import { isRecord } from "./types.js";
|
|
3
3
|
/**
|
|
4
4
|
* Upload one local file directly to fal's CDN. The proxy hands us a
|
|
5
|
-
* presigned upload slot (upload_url + file_url) via the `
|
|
5
|
+
* presigned upload slot (upload_url + file_url) via the `generate.forward`
|
|
6
6
|
* storage target; bytes go straight from the client to fal, never
|
|
7
7
|
* through the worker. The returned file_url is a stable fal CDN URL
|
|
8
8
|
* that can be reused across runs without re-uploading.
|
|
9
9
|
*/
|
|
10
10
|
export async function uploadFile(client, file) {
|
|
11
|
-
const slot = await client.
|
|
11
|
+
const slot = await client.generate.forward.mutate({
|
|
12
12
|
target: "storage",
|
|
13
13
|
method: "POST",
|
|
14
14
|
path: "/storage/upload/initiate",
|
package/dist/lib/run.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import spawn from "cross-spawn";
|
|
2
|
+
export const run = (cmd, args) => new Promise((resolve) => {
|
|
3
|
+
const chunks = [];
|
|
4
|
+
const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
5
|
+
child.stdout?.on("data", (c) => chunks.push(c));
|
|
6
|
+
child.stderr?.on("data", (c) => chunks.push(c));
|
|
7
|
+
child.on("error", (err) => resolve({ code: 1, output: `${err.message}\n` }));
|
|
8
|
+
child.on("close", (code) => resolve({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
|
|
9
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare function markUpdateChecked(): void;
|
|
2
|
+
export declare function isNewerVersion(latest: string, current: string): boolean;
|
|
3
|
+
export declare function fetchLatestVersion(): Promise<string | null>;
|
|
4
|
+
/**
|
|
5
|
+
* Fire-and-forget background update: at most once per day (and never in CI
|
|
6
|
+
* or with VG_NO_AUTO_UPDATE set), re-invoke this CLI as a detached
|
|
7
|
+
* `vg update --auto`, which only applies anything when npm has a newer
|
|
8
|
+
* version. The foreground command pays no latency and prints nothing.
|
|
9
|
+
*/
|
|
10
|
+
export declare function maybeScheduleAutoUpdate(): void;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { getConfigDir } from "./config.js";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
6
|
+
const VERSION_RE = /^\d+\.\d+\.\d+$/;
|
|
7
|
+
function getCachePath() {
|
|
8
|
+
return join(getConfigDir(), "update-check.json");
|
|
9
|
+
}
|
|
10
|
+
function getLastCheckedAt() {
|
|
11
|
+
const path = getCachePath();
|
|
12
|
+
if (!existsSync(path))
|
|
13
|
+
return 0;
|
|
14
|
+
try {
|
|
15
|
+
const data = JSON.parse(readFileSync(path, "utf-8"));
|
|
16
|
+
if (typeof data === "object" && data !== null && "lastCheckedAt" in data) {
|
|
17
|
+
const ts = data.lastCheckedAt;
|
|
18
|
+
if (typeof ts === "number")
|
|
19
|
+
return ts;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// corrupt cache — treat as never checked
|
|
24
|
+
}
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
|
27
|
+
export function markUpdateChecked() {
|
|
28
|
+
const dir = getConfigDir();
|
|
29
|
+
try {
|
|
30
|
+
if (!existsSync(dir))
|
|
31
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
32
|
+
writeFileSync(getCachePath(), JSON.stringify({ lastCheckedAt: Date.now() }, null, 2));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// best-effort; worst case we check again next run
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export function isNewerVersion(latest, current) {
|
|
39
|
+
if (!VERSION_RE.test(latest) || !VERSION_RE.test(current))
|
|
40
|
+
return false;
|
|
41
|
+
const a = latest.split(".").map(Number);
|
|
42
|
+
const b = current.split(".").map(Number);
|
|
43
|
+
for (let i = 0; i < 3; i++) {
|
|
44
|
+
const left = a[i] ?? 0;
|
|
45
|
+
const right = b[i] ?? 0;
|
|
46
|
+
if (left > right)
|
|
47
|
+
return true;
|
|
48
|
+
if (left < right)
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
export async function fetchLatestVersion() {
|
|
54
|
+
const registry = process.env.VG_REGISTRY_URL ?? "https://registry.npmjs.org";
|
|
55
|
+
try {
|
|
56
|
+
const res = await fetch(`${registry}/vibedgames/latest`, {
|
|
57
|
+
signal: AbortSignal.timeout(5000),
|
|
58
|
+
});
|
|
59
|
+
if (!res.ok)
|
|
60
|
+
return null;
|
|
61
|
+
const data = await res.json();
|
|
62
|
+
if (typeof data === "object" && data !== null && "version" in data) {
|
|
63
|
+
const version = data.version;
|
|
64
|
+
if (typeof version === "string")
|
|
65
|
+
return version;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// offline or registry down — skip this round
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Fire-and-forget background update: at most once per day (and never in CI
|
|
75
|
+
* or with VG_NO_AUTO_UPDATE set), re-invoke this CLI as a detached
|
|
76
|
+
* `vg update --auto`, which only applies anything when npm has a newer
|
|
77
|
+
* version. The foreground command pays no latency and prints nothing.
|
|
78
|
+
*/
|
|
79
|
+
export function maybeScheduleAutoUpdate() {
|
|
80
|
+
if (process.env.VG_NO_AUTO_UPDATE || process.env.CI)
|
|
81
|
+
return;
|
|
82
|
+
const script = process.argv[1];
|
|
83
|
+
if (!script)
|
|
84
|
+
return;
|
|
85
|
+
if (Date.now() - getLastCheckedAt() < CHECK_INTERVAL_MS)
|
|
86
|
+
return;
|
|
87
|
+
markUpdateChecked();
|
|
88
|
+
try {
|
|
89
|
+
const child = spawn(process.execPath, [script, "update", "--auto"], {
|
|
90
|
+
detached: true,
|
|
91
|
+
stdio: "ignore",
|
|
92
|
+
});
|
|
93
|
+
child.unref();
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// best-effort; worst case we try again next run
|
|
97
|
+
}
|
|
98
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vibedgames",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"bin": {
|
|
6
6
|
"vg": "./dist/index.js"
|
|
@@ -10,29 +10,29 @@
|
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@trpc/client": "^11.
|
|
13
|
+
"@trpc/client": "^11.18.0",
|
|
14
14
|
"citty": "^0.2.2",
|
|
15
15
|
"consola": "^3.4.2",
|
|
16
16
|
"cross-spawn": "^7.0.6",
|
|
17
17
|
"ignore": "^7.0.5",
|
|
18
18
|
"superjson": "^2.2.6",
|
|
19
|
-
"tar": "^7.
|
|
19
|
+
"tar": "^7.5.19",
|
|
20
20
|
"tiged": "^2.12.8"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
-
"@cloudflare/workers-types": "^
|
|
23
|
+
"@cloudflare/workers-types": "^5.20260708.1",
|
|
24
24
|
"@kyh/tsconfig": "^1.1.14",
|
|
25
|
-
"@trpc/server": "^11.
|
|
25
|
+
"@trpc/server": "^11.18.0",
|
|
26
26
|
"@types/cross-spawn": "^6.0.6",
|
|
27
|
-
"@types/node": "^
|
|
28
|
-
"typescript": "^
|
|
27
|
+
"@types/node": "^26.1.1",
|
|
28
|
+
"typescript": "^7.0.2",
|
|
29
29
|
"@repo/api": "^0.1.0"
|
|
30
30
|
},
|
|
31
31
|
"scripts": {
|
|
32
32
|
"build": "tsc",
|
|
33
33
|
"dev": "tsc --watch",
|
|
34
34
|
"clean": "rm -rf .turbo dist node_modules",
|
|
35
|
-
"test:media": "node --import tsx --test test/media-args.test.ts test/media-download.test.ts test/media-poll.test.ts",
|
|
35
|
+
"test:media": "node --import tsx --test test/media-args.test.ts test/media-download.test.ts test/media-poll.test.ts test/codex.test.ts",
|
|
36
36
|
"typecheck": "tsc --noEmit"
|
|
37
37
|
}
|
|
38
38
|
}
|