@yolo-labs/yolo-cli 0.36.0 → 0.39.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/dist/cli.js CHANGED
@@ -126,6 +126,7 @@ function printHelp() {
126
126
  ' [--json] Pretty-print raw JSON instead of the table.',
127
127
  ' tileapp init <name> Scaffold a personal app (./<name>/tileapp.json + index.html).',
128
128
  ' tileapp validate <manifest> [opts] Offline lint: manifest schema + bundle layout (no auth).',
129
+ ' tileapp media push <manifest> [--dir d] Upload store screenshots (additive — leaves the rest of the bundle alone).',
129
130
  ' [--bundle-dir <dir>] Override the static-bundle directory to check.',
130
131
  ' tileapp dev <manifest> [opts] Serve the bundle locally + a mock broker (offline iterate).',
131
132
  ' [--port N] [--host H] Bind (default: 127.0.0.1:$PORT|3000).',
@@ -758,6 +759,7 @@ function tileAppUsage(sub, message) {
758
759
  dev: 'Usage: yolo tileapp dev <manifest.json> [--port N] [--host H] [--bundle-dir <dir>] [--deny]\n',
759
760
  install: 'Usage: yolo tileapp install <appId> --workspace <workspaceId> [--accept-optional <perm>]...\n',
760
761
  'add-tile': 'Usage: yolo tileapp add-tile <appId> --workspace <workspaceId> [--name <name>] [--version <v>]\n',
762
+ media: 'Usage: yolo tileapp media push <manifest.json> [--dir <dir>] (uploads store screenshots; additive, never touches the rest of the bundle)\n',
761
763
  };
762
764
  process.stderr.write(usage[sub]);
763
765
  return 64;
@@ -1040,6 +1042,38 @@ async function runTileAppInitCmd(args) {
1040
1042
  process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
1041
1043
  return exitCodeForFailure(result.kind);
1042
1044
  }
1045
+ async function runTileAppMediaCmd(args) {
1046
+ // `exitCodeForFailure` (not devExitCode) — this command can fail with
1047
+ // auth/http kinds that the offline dev helper's narrower union doesn't cover.
1048
+ const { runTileAppMediaPush, exitCodeForFailure } = await import('./tileapp-personal.js');
1049
+ const action = args[0];
1050
+ if (action !== 'push') {
1051
+ return tileAppUsage('media', action ? `unknown action '${action}' (expected: push)` : 'an action is required (push)');
1052
+ }
1053
+ let manifestPath;
1054
+ let dir;
1055
+ for (let i = 1; i < args.length; i++) {
1056
+ const a = args[i];
1057
+ if (a === '--dir') {
1058
+ dir = args[++i];
1059
+ if (dir === undefined)
1060
+ return tileAppUsage('media', '--dir requires a value');
1061
+ }
1062
+ else if (!a.startsWith('-') && !manifestPath)
1063
+ manifestPath = a;
1064
+ else
1065
+ return tileAppUsage('media', `unexpected argument '${a}'`);
1066
+ }
1067
+ if (!manifestPath)
1068
+ return tileAppUsage('media', 'a manifest path is required');
1069
+ const result = await runTileAppMediaPush({ manifestPath, dir });
1070
+ if (result.ok) {
1071
+ process.stdout.write(`${result.output}\n`);
1072
+ return 0;
1073
+ }
1074
+ process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
1075
+ return exitCodeForFailure(result.kind);
1076
+ }
1043
1077
  async function runTileAppValidateCmd(args) {
1044
1078
  const { runTileAppValidate, devExitCode } = await import('./tileapp-developer.js');
1045
1079
  let manifestPath;
@@ -1544,12 +1578,14 @@ async function main(argv) {
1544
1578
  return runTileAppInstallCmd(args.slice(2));
1545
1579
  if (sub === 'add-tile')
1546
1580
  return runTileAppAddTileCmd(args.slice(2));
1581
+ if (sub === 'media')
1582
+ return runTileAppMediaCmd(args.slice(2));
1547
1583
  if (!sub) {
1548
- process.stderr.write('yolo: tileapp requires a subcommand (init, validate, dev, sign, publish, install, add-tile)\n');
1584
+ process.stderr.write('yolo: tileapp requires a subcommand (init, validate, dev, sign, publish, media, install, add-tile)\n');
1549
1585
  return 64;
1550
1586
  }
1551
1587
  process.stderr.write(`yolo: unknown tileapp subcommand '${sub}'\n`);
1552
- process.stderr.write('Subcommands: init, validate, dev, sign, publish, install, add-tile\n');
1588
+ process.stderr.write('Subcommands: init, validate, dev, sign, publish, media, install, add-tile\n');
1553
1589
  return 64;
1554
1590
  }
1555
1591
  if (cmd === 'mcp') {
@@ -3,7 +3,7 @@
3
3
  * (docs/MANAGED_HOSTING_CLI_SPEC.md §1).
4
4
  *
5
5
  * yolo deploy [--env <staging|prod>] [--dry-run] [--json] ← bare = ship
6
- * yolo deploy init [--slug <slug>] [--type <static|worker>] [--json]
6
+ * yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug>] [--json]
7
7
  * yolo deploy status [--json]
8
8
  * yolo deploy logs [--tail] [--since <dur>] [--json]
9
9
  * yolo deploy rollback [releaseId] [--json]
@@ -41,7 +41,7 @@ import { runDeployDev } from './deploy-dev.js';
41
41
  import { defaultReadFile } from './auth-context.js';
42
42
  const USAGE = [
43
43
  'Usage: yolo deploy [--env <staging|prod>] [--dry-run] [--json]',
44
- ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--json]',
44
+ ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug>] [--json]',
45
45
  ' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>]',
46
46
  ' yolo deploy validate [--json]',
47
47
  ' yolo deploy doctor [--json]',
@@ -193,6 +193,7 @@ async function runShipCmd(args, deps, io) {
193
193
  export function parseInitArgs(args) {
194
194
  let slug;
195
195
  let type;
196
+ let parentProjectId;
196
197
  let jsonOutput = false;
197
198
  for (let i = 0; i < args.length; i++) {
198
199
  const a = args[i];
@@ -216,6 +217,15 @@ export function parseInitArgs(args) {
216
217
  return { ok: false, message: `--type must be 'static' or 'worker' (got '${v}')` };
217
218
  type = v;
218
219
  }
220
+ else if (a === '--parent') {
221
+ const v = args[++i];
222
+ if (!v || v.startsWith('--'))
223
+ return { ok: false, message: '--parent requires a project id' };
224
+ parentProjectId = v;
225
+ }
226
+ else if (a.startsWith('--parent=')) {
227
+ parentProjectId = a.slice('--parent='.length);
228
+ }
219
229
  else if (a.startsWith('--type=')) {
220
230
  const v = a.slice('--type='.length);
221
231
  if (v !== 'static' && v !== 'worker')
@@ -229,7 +239,10 @@ export function parseInitArgs(args) {
229
239
  return { ok: false, message: `unexpected positional argument: ${a}` };
230
240
  }
231
241
  }
232
- return { ok: true, slug, type, jsonOutput };
242
+ if (parentProjectId !== undefined && parentProjectId.length === 0) {
243
+ return { ok: false, message: '--parent requires a project id or slug' };
244
+ }
245
+ return { ok: true, slug, type, parentProjectId, jsonOutput };
233
246
  }
234
247
  async function runInitCmd(args, deps, io) {
235
248
  const parsed = parseInitArgs(args);
@@ -260,6 +273,27 @@ async function runInitCmd(args, deps, io) {
260
273
  return exitCodeForFailure(readResult.kind);
261
274
  }
262
275
  const existing = readResult.config;
276
+ if (existing?.projectId && parsed.parentProjectId) {
277
+ // 🚨 `--parent` on an ALREADY-LINKED directory would otherwise report
278
+ // `already-linked` and exit 0, having silently ignored the flag — the same
279
+ // false-success the slug-reconciliation guard below exists to prevent.
280
+ // Parent links are create-only, so there is nothing `init` can do here.
281
+ const message = 'this directory is already linked to a project; --parent only applies when creating one';
282
+ // JSON mode keeps stderr EMPTY — automation treats it as diagnostics, and
283
+ // the init contract is a clean stream split.
284
+ if (parsed.jsonOutput) {
285
+ io.out(`${formatJsonResult({ status: 'failed', message })}\n`);
286
+ }
287
+ else {
288
+ io.err(`FAIL: ${message}.\n`
289
+ // Only advice that actually works: parent links are create-only and
290
+ // there is no re-parent route or console control, so the recovery is
291
+ // to create the child as a NEW project.
292
+ + ' Nesting is set at creation. Create the child in its own directory with\n'
293
+ + ' `yolo deploy init --parent <id|slug>`, or from the Hosting console\'s New project dialog.\n');
294
+ }
295
+ return 1;
296
+ }
263
297
  if (existing?.projectId) {
264
298
  // Idempotent: a committed link means future sessions ship to the SAME
265
299
  // project instead of forking a new slug — never silently re-create.
@@ -282,6 +316,42 @@ async function runInitCmd(args, deps, io) {
282
316
  io.err(`${formatFail({ kind: 'auth', message: auth.message })}\n`);
283
317
  return 78;
284
318
  }
319
+ // Resolve `--parent` when given as a SLUG rather than an id. A CLI-only user
320
+ // has no way to discover an opaque 24-hex id (there is no `deploy list`
321
+ // subcommand), but slugs are the handle they already use everywhere else —
322
+ // so accept either and look the slug up through the same owned-projects
323
+ // helper `link` uses (codex P2).
324
+ let resolvedParentId = parsed.parentProjectId;
325
+ if (resolvedParentId) {
326
+ // SLUG FIRST, then id. A slug may legally be 24 hex characters, so a
327
+ // shape test alone is ambiguous; looking the slug up first resolves both
328
+ // forms with one call and gives slugs precedence — which is the form a
329
+ // human typed on purpose.
330
+ const parentLookup = await findOwnedProjectBySlug(deps, auth.context, resolvedParentId);
331
+ if (!parentLookup.ok) {
332
+ // A list failure (auth/network) is NOT "not found" — surface the real
333
+ // error and its exit code, matching how `link` treats the same helper.
334
+ if (parsed.jsonOutput)
335
+ io.out(`${formatJsonResult(parentLookup)}\n`);
336
+ else
337
+ io.err(`${formatFail(parentLookup)}\n`);
338
+ return exitCodeForFailure(parentLookup.kind);
339
+ }
340
+ const bySlug = parentLookup.project ? resolveProjectId(parentLookup.project) : undefined;
341
+ if (bySlug) {
342
+ resolvedParentId = bySlug;
343
+ }
344
+ else if (!/^[a-f0-9]{24}$/i.test(resolvedParentId)) {
345
+ const message = `no project of yours matches parent '${resolvedParentId}' — pass its slug or 24-hex id`;
346
+ if (parsed.jsonOutput)
347
+ io.out(`${formatJsonResult({ status: 'failed', message })}\n`);
348
+ else
349
+ io.err(`FAIL: ${message}\n`);
350
+ return 1;
351
+ }
352
+ // Else: not a slug of ours, but id-shaped — pass through and let the
353
+ // server's ownership-asserted read be the authority.
354
+ }
285
355
  const create = deps.createProjectImpl ?? createProject;
286
356
  const created = await create(auth.context, {
287
357
  name: parsed.slug ?? path.basename(cwd),
@@ -291,6 +361,9 @@ async function runInitCmd(args, deps, io) {
291
361
  // (and therefore to VibeAssist event watchers). Local CLI use remains
292
362
  // unchanged because the field is optional.
293
363
  ...(deps.env?.WORKSPACE_ID ? { workspaceId: deps.env.WORKSPACE_ID } : {}),
364
+ // Nesting S4 — passed straight through; the server verifies ownership,
365
+ // depth and parent state. Not written to `.yolo/deploy.json`.
366
+ ...(resolvedParentId ? { parentProjectId: resolvedParentId } : {}),
294
367
  });
295
368
  if (!created.ok) {
296
369
  // create-or-LINK: a `slug-taken` on a slug the caller ALREADY OWNS means a
@@ -308,7 +381,18 @@ async function runInitCmd(args, deps, io) {
308
381
  const lookup = await findOwnedProjectBySlug(deps, auth.context, takenSlug);
309
382
  const owned = lookup.ok ? lookup.project : undefined;
310
383
  const projectId = owned ? resolveProjectId(owned) : undefined;
311
- if (projectId) {
384
+ // 🚨 Do NOT reconcile into a project that is not already under the
385
+ // requested parent (codex P2). Parent links are CREATE-ONLY server
386
+ // side, so linking here would report a successful nesting that never
387
+ // happened — the caller believes the family exists and it does not.
388
+ // Fall through to the plain slug-taken refusal instead.
389
+ // Case-normalized: `--parent` accepts either case (the regex is /i) but
390
+ // the API serializes an ObjectId lowercase, so a raw compare would
391
+ // report a mismatch for the very same parent (codex P2).
392
+ const parentMismatch = parsed.parentProjectId !== undefined
393
+ && str(owned?.parentProjectId)?.toLowerCase()
394
+ !== resolvedParentId?.toLowerCase();
395
+ if (projectId && !parentMismatch) {
312
396
  return writeLinkFile(cwd, writeConfig, io, {
313
397
  projectId,
314
398
  slug: str(owned.slug) ?? takenSlug,
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Dependency-free PNG/WebP dimension reader.
3
+ *
4
+ * The yolo-cli ships no image library (and shouldn't — it's a single-binary CLI),
5
+ * but `publish --personal` needs to know an image's shape BEFORE it mutates
6
+ * anything server-side. The publish flow is two calls: register the manifest,
7
+ * then upload the bundle. If the server rejects a screenshot during the upload,
8
+ * the manifest is already registered — a first publish is left with no bundle,
9
+ * or a republish leaves a new manifest over the old bundle, while the command
10
+ * reports failure. Catching a bad screenshot locally, before the first call,
11
+ * keeps that state consistent for the realistic case (wrong aspect ratio).
12
+ *
13
+ * The server remains authoritative — `services/tileapp/screenshot-image.ts`
14
+ * fully decodes the pixel stream, which this deliberately does not attempt.
15
+ * This reads headers only: enough to reject the common mistakes offline, cheap
16
+ * enough to have no dependencies. Same "faithful mirror, narrower scope" stance
17
+ * as `tileapp-validator.ts`.
18
+ */
19
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
20
+ /**
21
+ * Read an image's dimensions from its header, or null if the bytes aren't a
22
+ * PNG/WebP we can parse. Null means "don't know" — callers must treat it as
23
+ * "let the server decide", never as a failure.
24
+ */
25
+ export function readImageDimensions(buf) {
26
+ // ── PNG: 8-byte signature, then a 25-byte IHDR whose width/height are
27
+ // big-endian u32 at offsets 16 and 20.
28
+ if (buf.length >= 24 && buf.subarray(0, 8).equals(PNG_SIG)) {
29
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20), format: 'png' };
30
+ }
31
+ // ── WebP: 'RIFF' <u32 size> 'WEBP' <chunk fourcc> …
32
+ if (buf.length >= 30 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') {
33
+ const chunk = buf.toString('ascii', 12, 16);
34
+ // VP8X (extended): 24-bit little-endian (width-1, height-1) at offset 24.
35
+ if (chunk === 'VP8X') {
36
+ const w = buf.readUIntLE(24, 3) + 1;
37
+ const h = buf.readUIntLE(27, 3) + 1;
38
+ return { width: w, height: h, format: 'webp' };
39
+ }
40
+ // VP8 (lossy): keyframe start code 9d 01 2a at offset 23, then two
41
+ // little-endian u16 whose low 14 bits are the dimensions.
42
+ if (chunk === 'VP8 ' && buf[23] === 0x9d && buf[24] === 0x01 && buf[25] === 0x2a) {
43
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff, format: 'webp' };
44
+ }
45
+ // VP8L (lossless): signature 0x2f at offset 20, then 14 bits of (width-1)
46
+ // and 14 bits of (height-1) packed across the following 4 bytes.
47
+ if (chunk === 'VP8L' && buf[20] === 0x2f) {
48
+ const bits = buf.readUInt32LE(21);
49
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1, format: 'webp' };
50
+ }
51
+ }
52
+ return null;
53
+ }
@@ -20,6 +20,7 @@ import path from 'node:path';
20
20
  import { spawn } from 'node:child_process';
21
21
  import { resolveUserToken } from './auth-context.js';
22
22
  import { validateManifest, isRuntimeManifest } from './tileapp-validator.js';
23
+ import { readImageDimensions } from './image-dimensions.js';
23
24
  import { resolveBundleDir } from './tileapp-developer.js';
24
25
  import { parseDockerfile, assembleOciArchive } from './tileapp-oci-assembler.js';
25
26
  function defaultExec(file, args) {
@@ -181,6 +182,10 @@ uploads whatever is in it; the platform serves each file at
181
182
  An absolute https:// URL works too, and is the ONLY option for a runtime app
182
183
  (it publishes an image, not a bundle, so it has nowhere to put these).
183
184
 
185
+ Upload (additive — leaves the rest of your bundle alone):
186
+
187
+ yolo tileapp media push tileapp.json
188
+
184
189
  Check refs before publishing: yolo tileapp validate tileapp.json --personal
185
190
  `;
186
191
  try {
@@ -199,6 +204,187 @@ Check refs before publishing: yolo tileapp validate tileapp.json --personal
199
204
  output: `Created ${name}/ (tileapp.json + index.html + app.js + media/)\n note: bundle CSP is \`script-src 'self'\` — keep JS in app.js (no inline <script>, no eval, no network)\n note: drop a 1280x800 webp in media/ and add \`"screenshots": ["media/01-main.webp"]\` to get a store preview (see media/README.md)\n next: cd ${name} && yolo tileapp publish tileapp.json --personal`,
200
205
  };
201
206
  }
207
+ /**
208
+ * Offline screenshot pre-check, applied to `media/<file>` images.
209
+ *
210
+ * Runs BEFORE any server call so `publish --personal` can't register a manifest
211
+ * and then fail on the bundle upload, which would leave the app registered with
212
+ * no bundle (or a new manifest over an old bundle) while reporting failure.
213
+ * Header-only — the server still fully decodes; this just catches the mistake
214
+ * people actually make offline. Unparseable bytes return null and are deferred
215
+ * to the server rather than rejected here.
216
+ */
217
+ function screenshotPreCheckError(name, body) {
218
+ // Size first — it needs no parsing and the server rejects on it too.
219
+ if (body.length > 1024 * 1024) {
220
+ return `${name}: image is ${Math.round(body.length / 1024)} KB — the limit is 1024 KB`;
221
+ }
222
+ const dims = readImageDimensions(body);
223
+ if (!dims)
224
+ return null; // not a shape we can read — the server is authoritative
225
+ // The media route sets Content-Type from the EXTENSION, so bytes that
226
+ // disagree with the name would be served as a lie. The server rejects this;
227
+ // catching it here keeps the rejection ahead of the manifest registration.
228
+ const ext = name.slice(name.lastIndexOf('.') + 1).toLowerCase();
229
+ if (ext !== dims.format) {
230
+ return `${name}: file is named .${ext} but the bytes are ${dims.format}`;
231
+ }
232
+ if (dims.width < 640 || dims.width > 2560) {
233
+ return `${name}: image is ${dims.width}px wide — screenshots must be 640-2560px (1280x800 is the target)`;
234
+ }
235
+ const aspect = dims.width / dims.height;
236
+ if (Math.abs(aspect - 1.6) / 1.6 > 0.04) {
237
+ return `${name}: image is ${dims.width}x${dims.height} (${aspect.toFixed(2)}:1) — screenshots must be 16:10, e.g. 1280x800`;
238
+ }
239
+ return null;
240
+ }
241
+ // ── media (store screenshots) ───────────────────────────────────────────────
242
+ const MEDIA_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;
243
+ const MEDIA_EXTS = new Set(['.webp', '.png']);
244
+ /**
245
+ * Upload store screenshots for an already-published personal app.
246
+ *
247
+ * ADDITIVE — it posts to `/tileapps/personal/:appId/media`, which writes one
248
+ * file at a time and never reaps. This is deliberately NOT `publish`: the
249
+ * bundle PUT is a full replace, so using it to add a screenshot would delete
250
+ * the app's index.html. This command exists so adding a preview never requires
251
+ * re-uploading (or still having) the whole bundle.
252
+ */
253
+ export async function runTileAppMediaPush(opts) {
254
+ const auth = resolveAuth(opts.env ?? process.env);
255
+ if (!auth.ok)
256
+ return { ok: false, kind: 'usage', message: auth.message };
257
+ const read = readManifest(opts.manifestPath);
258
+ if (!read.ok)
259
+ return { ok: false, kind: 'io', message: read.message };
260
+ // `null` and arrays are valid JSON but not manifests — deref would throw a
261
+ // TypeError past the CLI's exit handling instead of reporting a failure.
262
+ if (typeof read.manifest !== 'object' || read.manifest === null || Array.isArray(read.manifest)) {
263
+ return { ok: false, kind: 'validation', message: `manifest '${opts.manifestPath}' must be a JSON object` };
264
+ }
265
+ const localId = typeof read.manifest.id === 'string' ? read.manifest.id : '';
266
+ if (!LOCAL_ID_RE.test(localId)) {
267
+ return { ok: false, kind: 'validation', message: `manifest.id must be a lowercase kebab-case slug (got '${localId}')` };
268
+ }
269
+ const dir = path.resolve(opts.dir ?? path.join(path.dirname(path.resolve(opts.manifestPath)), 'media'));
270
+ let entries;
271
+ try {
272
+ entries = fs.readdirSync(dir);
273
+ }
274
+ catch {
275
+ return { ok: false, kind: 'io', message: `no media directory at ${dir} — create it and add your screenshots (see media/README.md from \`yolo tileapp init\`)` };
276
+ }
277
+ const files = [];
278
+ for (const name of entries.sort()) {
279
+ const ext = path.extname(name).toLowerCase();
280
+ if (!MEDIA_EXTS.has(ext))
281
+ continue; // README.md and friends are not screenshots
282
+ if (!MEDIA_NAME_RE.test(name)) {
283
+ return { ok: false, kind: 'validation', message: `invalid media filename '${name}' — lowercase, one segment, e.g. 01-main.webp` };
284
+ }
285
+ const bytes = fs.readFileSync(path.join(dir, name));
286
+ const preCheck = screenshotPreCheckError(name, bytes);
287
+ if (preCheck)
288
+ return { ok: false, kind: 'validation', message: preCheck };
289
+ files.push({ name, content: bytes.toString('base64') });
290
+ }
291
+ if (files.length === 0) {
292
+ return { ok: false, kind: 'io', message: `no .webp/.png files in ${dir}` };
293
+ }
294
+ const fetchImpl = opts.fetchImpl ?? fetch;
295
+ const base = apiBase(auth.commonApiUrl);
296
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}` };
297
+ // Resolve the namespaced appId (pa-<ownerId>-<localId>) — the caller only
298
+ // knows the local slug; the owner half is server-side.
299
+ let appId;
300
+ let storedManifest;
301
+ try {
302
+ const res = await fetchImpl(`${base}/tileapps/personal`, { headers });
303
+ if (!res.ok)
304
+ return { ok: false, kind: 'http', message: `could not list personal apps: HTTP ${res.status} — ${await safeText(res)}` };
305
+ // Shape is { appId, localId, manifest, … } — match on localId exactly.
306
+ const json = (await res.json());
307
+ const match = (json.apps ?? []).find((a) => a.localId === localId);
308
+ if (!match?.appId) {
309
+ return { ok: false, kind: 'validation', message: `no published personal app with id '${localId}' — publish it first: yolo tileapp publish ${opts.manifestPath} --personal` };
310
+ }
311
+ appId = match.appId;
312
+ storedManifest = match.manifest ?? {};
313
+ }
314
+ catch (e) {
315
+ return { ok: false, kind: 'http', message: `list request failed: ${e.message}` };
316
+ }
317
+ // Chunk by encoded size. The server accepts 6 images of up to 1 MiB each, but
318
+ // the route sits behind a global 5 MiB `express.json` parser and base64
319
+ // inflates by ~4/3 — so a batch that is legal by every documented limit can
320
+ // still be rejected by the body parser before the handler runs, with an
321
+ // unhelpful error. Splitting keeps each request well inside that budget; the
322
+ // per-app cap is enforced atomically server-side, so multiple requests are
323
+ // safe and the total limit still holds.
324
+ //
325
+ // Check the TOTAL against what's already stored first: split across requests,
326
+ // an early batch can succeed and a later one hit the cap, leaving the command
327
+ // partially applied. The server's per-request guard can't see the whole set.
328
+ const priorRefs = Array.isArray(storedManifest.screenshots)
329
+ ? storedManifest.screenshots.filter((r) => typeof r === 'string')
330
+ : [];
331
+ const wouldBe = new Set([...priorRefs, ...files.map((f) => `media/${f.name}`)]);
332
+ if (wouldBe.size > 6) {
333
+ return {
334
+ ok: false,
335
+ kind: 'validation',
336
+ message: `that would leave ${wouldBe.size} screenshots and the limit is 6 — `
337
+ + `${priorRefs.length} already referenced, ${files.length} in ${dir}. Remove some first.`,
338
+ };
339
+ }
340
+ const MAX_REQUEST_BYTES = 3 * 1024 * 1024; // encoded, comfortably under 5 MiB
341
+ const batches = [];
342
+ let current = [];
343
+ let currentBytes = 0;
344
+ for (const f of files) {
345
+ if (current.length > 0 && currentBytes + f.content.length > MAX_REQUEST_BYTES) {
346
+ batches.push(current);
347
+ current = [];
348
+ currentBytes = 0;
349
+ }
350
+ current.push(f);
351
+ currentBytes += f.content.length;
352
+ }
353
+ if (current.length > 0)
354
+ batches.push(current);
355
+ const uploaded = [];
356
+ let screenshots = [];
357
+ for (const batch of batches) {
358
+ try {
359
+ const res = await fetchImpl(`${base}/tileapps/personal/${encodeURIComponent(appId)}/media`, {
360
+ method: 'POST',
361
+ headers,
362
+ body: JSON.stringify({ files: batch }),
363
+ });
364
+ if (!res.ok) {
365
+ const sofar = uploaded.length > 0 ? ` (${uploaded.length} image(s) already uploaded)` : '';
366
+ return { ok: false, kind: 'http', message: `media upload failed: HTTP ${res.status} — ${await safeText(res)}${sofar}` };
367
+ }
368
+ const json = (await res.json());
369
+ uploaded.push(...(json.files ?? []));
370
+ screenshots = json.screenshots ?? uploaded.map((f) => f.ref);
371
+ }
372
+ catch (e) {
373
+ return { ok: false, kind: 'http', message: `media upload request failed: ${e.message}` };
374
+ }
375
+ }
376
+ // No manifest round-trip here on purpose. The upload route merges the refs
377
+ // into the stored manifest in-request; doing it client-side would mean POSTing
378
+ // a whole stale snapshot and silently rolling back anything that landed in
379
+ // between.
380
+ const lines = uploaded.map((f) => ` ${f.ref}${f.width ? ` ${f.width}x${f.height}` : ''}`);
381
+ return {
382
+ ok: true,
383
+ output: `Uploaded ${uploaded.length} screenshot(s) to ${appId}:\n${lines.join('\n')}\n\n`
384
+ + `Manifest updated — "screenshots": ${JSON.stringify(screenshots)}\n`
385
+ + `Keep ${opts.manifestPath} in sync by adding the same array, so your next publish doesn't drop them.`,
386
+ };
387
+ }
202
388
  /** Recursively collect a bundle dir's files as upload entries. Skips VCS/dep
203
389
  * dirs and the manifest itself; classifies text vs binary by extension. */
204
390
  function collectBundleFiles(rootDir, manifestPath) {
@@ -297,6 +483,20 @@ export async function runTileAppPublishPersonal(opts) {
297
483
  const collected = collectBundleFiles(resolved.dir, opts.manifestPath);
298
484
  if (!collected.ok)
299
485
  return { ok: false, kind: 'io', message: collected.message };
486
+ // Screenshots ride along in the bundle, and the server rejects a bad one
487
+ // during the UPLOAD — which happens after the manifest is already registered.
488
+ // Check them here, before the first mutating call, so a wrong-aspect image
489
+ // can't leave a half-published app behind.
490
+ for (const f of collected.files) {
491
+ if (!f.path.startsWith('media/') || f.path.slice(6).includes('/'))
492
+ continue;
493
+ const ext = path.extname(f.path).toLowerCase();
494
+ if (ext !== '.webp' && ext !== '.png')
495
+ continue;
496
+ const err = screenshotPreCheckError(f.path, Buffer.from(f.content, f.encoding));
497
+ if (err)
498
+ return { ok: false, kind: 'validation', message: err };
499
+ }
300
500
  const fetchImpl = opts.fetchImpl ?? fetch;
301
501
  const base = apiBase(auth.commonApiUrl);
302
502
  const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}` };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolo-labs/yolo-cli",
3
- "version": "0.36.0",
3
+ "version": "0.39.0",
4
4
  "description": "YOLO Studio substrate CLI \u2014 owns yolo plan/workspace/artifact substrate-tooling commands. Distinct from yolo-code (the agent CLI) and yolo-router (the LLM gateway client).",
5
5
  "license": "MIT",
6
6
  "type": "module",