@yolo-labs/yolo-cli 1.0.0 → 1.2.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.
@@ -13,13 +13,21 @@
13
13
  * → POST /v1/tileapps/personal (register the manifest, returns the namespaced
14
14
  * appId) then PUT /v1/tileapps/personal/<appId>/bundle (upload the static
15
15
  * files). Prints the appId. Auth: user JWT (no SESSION_ID needed).
16
+ * A `runtime.kind: 'worker'` app takes this same bundle path: its backend
17
+ * ships in the bundle under `_worker/` (entry `_worker/index.js`) — no
18
+ * image build. `--live` uploads it as still being edited, so the backend
19
+ * runs owner-only on Dynamic Workers when the deployment has them on.
16
20
  */
17
21
  import fs from 'node:fs';
18
22
  import os from 'node:os';
19
23
  import path from 'node:path';
20
24
  import { spawn } from 'node:child_process';
21
- import { resolveUserToken } from './auth-context.js';
22
- import { validateManifest, isRuntimeManifest } from './tileapp-validator.js';
25
+ import { defaultReadFile, podSessionTelemetryHeaders, resolveUserToken } from './auth-context.js';
26
+ import { isProductionTarget, podProvisionedApiUrl, sameApiOrigin, targetApiUrl } from './api-env.js';
27
+ import { resolveCommonApiUrl } from './api-url.js';
28
+ import { formatOwnerApprovalPending, ownerApprovalRequestedOf } from './pod-owner-approval.js';
29
+ import { missingUserTokenMessage } from './api-env.js';
30
+ import { validateManifest, isRuntimeManifest, isWorkerRuntimeManifest, workerBundleErrors } from './tileapp-validator.js';
23
31
  import { readImageDimensions } from './image-dimensions.js';
24
32
  import { resolveBundleDir } from './tileapp-developer.js';
25
33
  import { parseDockerfile, assembleOciArchive } from './tileapp-oci-assembler.js';
@@ -39,6 +47,9 @@ function defaultExec(file, args) {
39
47
  });
40
48
  }
41
49
  export function exitCodeForFailure(kind) {
50
+ // MOGUL-D040 P2: staged for the workspace owner — NOT an error (same exit as a pending prod ship).
51
+ if (kind === 'awaiting-approval')
52
+ return 3;
42
53
  if (kind === 'http')
43
54
  return 1;
44
55
  if (kind === 'validation')
@@ -55,14 +66,16 @@ function apiBase(commonApiUrl) {
55
66
  return base.endsWith('/v1') ? base : `${base}/v1`;
56
67
  }
57
68
  function resolveAuth(env) {
58
- const commonApiUrl = env.YOLO_COMMON_API_URL || env.YOLO_API_URL;
59
- if (!commonApiUrl)
60
- return { ok: false, message: 'YOLO_COMMON_API_URL (or YOLO_API_URL) env var is required' };
69
+ const commonApiUrl = resolveCommonApiUrl(env);
61
70
  const userToken = resolveUserToken(env);
62
71
  if (!userToken)
63
- return { ok: false, message: 'no user token: set YOLO_API_TOKEN or sign in (~/.config/yolo/token)' };
72
+ return { ok: false, message: missingUserTokenMessage(env) };
64
73
  return { ok: true, commonApiUrl, userToken };
65
74
  }
75
+ /** A workspace pod (container-api sets SESSION_ID; the deploy CLI reads the same marker). */
76
+ function inWorkspacePod(env) {
77
+ return typeof env.SESSION_ID === 'string' && env.SESSION_ID.length > 0;
78
+ }
66
79
  async function safeText(res) {
67
80
  try {
68
81
  return await res.text();
@@ -71,6 +84,23 @@ async function safeText(res) {
71
84
  return '<no body>';
72
85
  }
73
86
  }
87
+ /**
88
+ * MOGUL-D040 P2: a 202 staged-approval answer (the step was NOT performed; the
89
+ * owner approves it in Studio and it then runs as the owner). Null otherwise.
90
+ */
91
+ async function stagedForOwner(res, what) {
92
+ if (res.status !== 202)
93
+ return null;
94
+ let body;
95
+ try {
96
+ body = await (res.clone ? res.clone() : res).json();
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ const staged = ownerApprovalRequestedOf(res.status, body);
102
+ return staged ? { ok: false, kind: 'awaiting-approval', message: formatOwnerApprovalPending(staged, what) } : null;
103
+ }
74
104
  function readManifest(p) {
75
105
  let raw;
76
106
  try {
@@ -100,7 +130,9 @@ export function runTileAppInit(opts) {
100
130
  id: name,
101
131
  version: '1.0.0',
102
132
  displayName: title,
103
- publisher: 'personal',
133
+ // No `publisher`: a personal app omits it and the server stamps
134
+ // `personal:<ownerId>`. `id` is the app's LOCAL name; the server namespaces
135
+ // it to `pa-<ownerId>-<id>` (see isPersonalManifest).
104
136
  description: `${title} — a personal tile-app.`,
105
137
  ui: { icon: '🧩', color: '#4f46e5', label: title },
106
138
  surface: { kind: 'iframe', entry: 'index.html', tilePrefersSize: { rowSpan: 2, colSpan: 2 } },
@@ -121,12 +153,10 @@ export function runTileAppInit(opts) {
121
153
  a real tokenizer/parser in app.js; you cannot shortcut with eval.
122
154
  • NO network — no CDN scripts, remote fonts, or fetch() to other origins.
123
155
  Keep the app fully self-contained (only the files in this folder).
124
- Inline <style> is fine; CSS may also live in a bundled .css file.
156
+ CSS: inline <style> and style="…" work, but keep it in style.css (linked
157
+ below) so the page is easy to review.
125
158
  -->
126
- <style>
127
- body { font: 15px/1.5 system-ui, sans-serif; margin: 0; display: grid; place-items: center;
128
- height: 100vh; color: #e5e7eb; background: #111827; }
129
- </style>
159
+ <link rel="stylesheet" href="style.css" />
130
160
  </head>
131
161
  <body>
132
162
  <main>
@@ -140,6 +170,10 @@ export function runTileAppInit(opts) {
140
170
  <script src="app.js" type="module"></script>
141
171
  </body>
142
172
  </html>
173
+ `;
174
+ const styleCss = `/* ${title} — the app's CSS. */
175
+ body { font: 15px/1.5 system-ui, sans-serif; margin: 0; display: grid; place-items: center;
176
+ height: 100vh; color: #e5e7eb; background: #111827; }
143
177
  `;
144
178
  const appJs = `// ${title} — personal tile-app logic.
145
179
  //
@@ -159,50 +193,24 @@ export function runTileAppInit(opts) {
159
193
  const status = document.getElementById('status');
160
194
  if (status) status.textContent = 'Ready — edit app.js to build your app.';
161
195
  `;
162
- // Store screenshots live in `media/`. Scaffolding the directory (with a
163
- // README, since an empty dir wouldn't survive and a dotfile is skipped by
164
- // both the collector and the server) is what makes the feature discoverable
165
- // — an author who never learns the folder exists ships a listing with no
166
- // preview and no idea one was possible.
167
- const mediaReadme = `# Store screenshots
168
-
169
- Drop screenshots here, then reference them from tileapp.json:
170
-
171
- "screenshots": ["media/01-main.webp"]
172
-
173
- \`yolo tileapp publish tileapp.json --personal\` walks this directory and
174
- uploads whatever is in it; the platform serves each file at
175
- /v1/tileapps/<appId>/media/<file>.
176
-
177
- format 1280x800 (16:10) webp, <= 400 KB each, 1-6 images, first is the hero
178
- capture render at 2x and downscale — the store card crops to ~320px wide
179
- content show the app doing its job on realistic data; an empty state or a
180
- permission prompt is a wasted slot
181
- budget bundles cap at 100 files / 3 MB total
182
-
183
- An absolute https:// URL works too, and is the ONLY option for a runtime app
184
- (it publishes an image, not a bundle, so it has nowhere to put these).
185
-
186
- Upload (additive — leaves the rest of your bundle alone):
187
-
188
- yolo tileapp media push tileapp.json
189
-
190
- Check refs before publishing: yolo tileapp validate tileapp.json --personal
191
- `;
196
+ // Store screenshots live in `media/`. The directory is created EMPTY: a
197
+ // README there would be uploaded with the bundle and served publicly (and
198
+ // `publish` now skips README/*.md files anyway). The guidance is in the
199
+ // output below instead.
192
200
  try {
193
201
  fs.mkdirSync(dir, { recursive: false });
194
202
  fs.writeFileSync(path.join(dir, 'tileapp.json'), `${JSON.stringify(manifest, null, 2)}\n`);
195
203
  fs.writeFileSync(path.join(dir, 'index.html'), indexHtml);
196
204
  fs.writeFileSync(path.join(dir, 'app.js'), appJs);
205
+ fs.writeFileSync(path.join(dir, 'style.css'), styleCss);
197
206
  fs.mkdirSync(path.join(dir, 'media'), { recursive: false });
198
- fs.writeFileSync(path.join(dir, 'media', 'README.md'), mediaReadme);
199
207
  }
200
208
  catch (e) {
201
209
  return { ok: false, kind: 'io', message: `scaffold failed: ${e.message}` };
202
210
  }
203
211
  return {
204
212
  ok: true,
205
- 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`,
213
+ output: `Created ${name}/ (tileapp.json + index.html + app.js + style.css + media/)\n note: bundle CSP is \`script-src 'self'\` — keep JS in app.js (no inline <script>, no eval, no network); CSS goes in style.css\n note: store preview: drop a 1280x800 (16:10) webp, <= 400 KB, in media/ and add \`"screenshots": ["media/01-main.webp"]\` (1-6 images, the first is the hero; \`yolo tileapp media push tileapp.json\` uploads them without a full publish)\n note: tileapp.json has no \`publisher\` on purpose: the server stamps it; \`id\` is your app's local name\n next: cd ${name} && yolo tileapp publish tileapp.json --personal`,
206
214
  };
207
215
  }
208
216
  /**
@@ -273,7 +281,7 @@ export async function runTileAppMediaPush(opts) {
273
281
  entries = fs.readdirSync(dir);
274
282
  }
275
283
  catch {
276
- 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\`)` };
284
+ return { ok: false, kind: 'io', message: `no media directory at ${dir} — create it and add your screenshots (1280x800 webp, referenced as \"screenshots\": [\"media/<file>\"])` };
277
285
  }
278
286
  const files = [];
279
287
  for (const name of entries.sort()) {
@@ -294,7 +302,7 @@ export async function runTileAppMediaPush(opts) {
294
302
  }
295
303
  const fetchImpl = opts.fetchImpl ?? fetch;
296
304
  const base = apiBase(auth.commonApiUrl);
297
- const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}` };
305
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}`, ...podSessionTelemetryHeaders() };
298
306
  // Resolve the namespaced appId (pa-<ownerId>-<localId>) — the caller only
299
307
  // knows the local slug; the owner half is server-side.
300
308
  let appId;
@@ -362,6 +370,9 @@ export async function runTileAppMediaPush(opts) {
362
370
  headers,
363
371
  body: JSON.stringify({ files: batch }),
364
372
  });
373
+ const staged = await stagedForOwner(res, `uploading media for ${appId}`);
374
+ if (staged)
375
+ return staged;
365
376
  if (!res.ok) {
366
377
  const sofar = uploaded.length > 0 ? ` (${uploaded.length} image(s) already uploaded)` : '';
367
378
  return { ok: false, kind: 'http', message: `media upload failed: HTTP ${res.status} — ${await safeText(res)}${sofar}` };
@@ -386,18 +397,53 @@ export async function runTileAppMediaPush(opts) {
386
397
  + `Keep ${opts.manifestPath} in sync by adding the same array, so your next publish doesn't drop them.`,
387
398
  };
388
399
  }
389
- /** Recursively collect a bundle dir's files as upload entries. Skips VCS/dep
390
- * dirs and the manifest itself; classifies text vs binary by extension. */
391
- function collectBundleFiles(rootDir, manifestPath) {
400
+ /**
401
+ * Documentation files the bundle does NOT upload by default: `README*` (any
402
+ * extension, any case) and `*.md` / `*.markdown`, at any depth. A bundle is
403
+ * served PUBLICLY at the app's origin, and these are almost always notes for
404
+ * the author (e.g. the old `init`'s media/README.md), not app content.
405
+ */
406
+ export function isBundleDocFile(relPath) {
407
+ const base = relPath.slice(relPath.lastIndexOf('/') + 1).toLowerCase();
408
+ return /^readme(\..*)?$/.test(base) || base.endsWith('.md') || base.endsWith('.markdown');
409
+ }
410
+ /**
411
+ * Recursively collect a bundle dir's files as upload entries.
412
+ *
413
+ * What is NOT uploaded (the bundle is public):
414
+ * - dotfiles / dot-directories, and the `node_modules`, VCS and `.yolo` dirs
415
+ * - the manifest itself
416
+ * - documentation files (`isBundleDocFile`), UNLESS the file is
417
+ * · `surface.entry`, or
418
+ * · named in `include` (`--include <path>`, relative to the bundle dir), or
419
+ * · referenced from an uploaded text file (html/js/css/json/svg/…) by its
420
+ * bundle path or its file name — the app fetches or links it.
421
+ * Skipped doc files are returned in `skipped` so publish can say so.
422
+ */
423
+ export function collectBundleFiles(rootDir, manifestPath, opts = {}) {
392
424
  const out = [];
425
+ const docs = [];
393
426
  const manifestAbs = path.resolve(manifestPath);
394
427
  const root = path.resolve(rootDir);
395
428
  let total = 0;
396
429
  const SKIP_DIRS = new Set(['node_modules', '.git', '.yolo']);
430
+ const add = (rel, buf) => {
431
+ total += buf.byteLength;
432
+ if (out.length + 1 > MAX_FILES)
433
+ return `too many files (max ${MAX_FILES})`;
434
+ if (total > MAX_TOTAL_BYTES)
435
+ return `bundle exceeds ${MAX_TOTAL_BYTES} bytes — use a smaller bundle`;
436
+ const ext = path.extname(rel).toLowerCase();
437
+ if (TEXT_EXTS.has(ext))
438
+ out.push({ path: rel, content: buf.toString('utf8'), encoding: 'utf8' });
439
+ else
440
+ out.push({ path: rel, content: buf.toString('base64'), encoding: 'base64' });
441
+ return null;
442
+ };
397
443
  const walk = (abs) => {
398
444
  for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
399
445
  // Skip dotfiles/dotdirs entirely — the bundle is served PUBLICLY, so a
400
- // stray .env/.npmrc/.git from the project dir must never be uploaded (the
446
+ // stray .env/.npmrc from the project dir must never be uploaded (the
401
447
  // server's sanitizeBundlePath also rejects dot-leading paths). codex Round-3 P1.
402
448
  if (entry.name.startsWith('.'))
403
449
  continue;
@@ -415,17 +461,13 @@ function collectBundleFiles(rootDir, manifestPath) {
415
461
  if (path.resolve(childAbs) === manifestAbs)
416
462
  continue; // never upload the manifest
417
463
  const rel = path.relative(root, childAbs).split(path.sep).join('/');
418
- const buf = fs.readFileSync(childAbs);
419
- total += buf.byteLength;
420
- if (out.length + 1 > MAX_FILES)
421
- return `too many files (max ${MAX_FILES})`;
422
- if (total > MAX_TOTAL_BYTES)
423
- return `bundle exceeds ${MAX_TOTAL_BYTES} bytes — use a smaller bundle`;
424
- const ext = path.extname(rel).toLowerCase();
425
- if (TEXT_EXTS.has(ext))
426
- out.push({ path: rel, content: buf.toString('utf8'), encoding: 'utf8' });
427
- else
428
- out.push({ path: rel, content: buf.toString('base64'), encoding: 'base64' });
464
+ if (isBundleDocFile(rel)) {
465
+ docs.push({ rel, abs: childAbs });
466
+ continue;
467
+ } // decided below
468
+ const err = add(rel, fs.readFileSync(childAbs));
469
+ if (err)
470
+ return err;
429
471
  }
430
472
  return null;
431
473
  };
@@ -437,9 +479,39 @@ function collectBundleFiles(rootDir, manifestPath) {
437
479
  catch (e) {
438
480
  return { ok: false, message: `reading bundle failed: ${e.message}` };
439
481
  }
482
+ const norm = (p) => p.split('\\').join('/').replace(/^(\.\/)+/, '').replace(/^\/+/, '');
483
+ const include = new Set((opts.include ?? []).map(norm));
484
+ const docPaths = new Set(docs.map((d) => d.rel));
485
+ for (const inc of include) {
486
+ if (!docPaths.has(inc) && !out.some((f) => f.path === inc)) {
487
+ return { ok: false, message: `--include ${inc}: no such file in the bundle dir ${rootDir} (dotfiles are never uploaded)` };
488
+ }
489
+ }
490
+ const entry = norm(opts.entry || 'index.html');
491
+ const texts = out.filter((f) => f.encoding === 'utf8').map((f) => f.content);
492
+ const referenced = (rel) => {
493
+ const base = rel.slice(rel.lastIndexOf('/') + 1);
494
+ return texts.some((t) => t.includes(rel) || t.includes(base));
495
+ };
496
+ const skipped = [];
497
+ for (const d of docs.sort((x, y) => (x.rel < y.rel ? -1 : x.rel > y.rel ? 1 : 0))) {
498
+ if (d.rel === entry || include.has(d.rel) || referenced(d.rel)) {
499
+ try {
500
+ const err = add(d.rel, fs.readFileSync(d.abs));
501
+ if (err)
502
+ return { ok: false, message: err };
503
+ }
504
+ catch (e) {
505
+ return { ok: false, message: `reading bundle failed: ${e.message}` };
506
+ }
507
+ }
508
+ else {
509
+ skipped.push(d.rel);
510
+ }
511
+ }
440
512
  if (out.length === 0)
441
513
  return { ok: false, message: `no files found in bundle dir: ${rootDir}` };
442
- return { ok: true, files: out, totalBytes: total };
514
+ return { ok: true, files: out, totalBytes: total, skipped };
443
515
  }
444
516
  export async function runTileAppPublishPersonal(opts) {
445
517
  const env = opts.env ?? process.env;
@@ -459,7 +531,13 @@ export async function runTileAppPublishPersonal(opts) {
459
531
  if (!LOCAL_ID_RE.test(localId)) {
460
532
  return { ok: false, kind: 'validation', message: `manifest "id" must be a lowercase kebab-case slug, 2-32 chars (got '${localId}')` };
461
533
  }
534
+ const isWorker = isWorkerRuntimeManifest(read.manifest);
535
+ if (opts.live && !isWorker) {
536
+ return { ok: false, kind: 'usage', message: "--live applies only to a runtime.kind 'worker' app (its backend is what runs live); publish without --live" };
537
+ }
462
538
  // Runtime app (has `runtime`/`image`): build the image in-pod + mediated push.
539
+ // A worker app is NOT one (isRuntimeManifest excludes it): it falls through to
540
+ // the bundle path below, backend included.
463
541
  // Branch BEFORE the strict pure-UI lint, since a runtime manifest legitimately
464
542
  // omits `image` (the server fills it from the actual pushed digest).
465
543
  if (isRuntimeManifest(read.manifest)) {
@@ -472,7 +550,7 @@ export async function runTileAppPublishPersonal(opts) {
472
550
  // Pure-UI path: strict schema lint (the server re-validates authoritatively).
473
551
  // This IS the path that gets an R2 bundle, so the `media/<file>` screenshot
474
552
  // form is available to it — see ScreenshotRefOptions.
475
- const v = validateManifest(read.manifest, { allowPlatformHostedScreenshots: true });
553
+ const v = validateManifest(read.manifest, { personal: true, allowPlatformHostedScreenshots: true });
476
554
  if (v.errors.length > 0) {
477
555
  return { ok: false, kind: 'validation', message: `manifest invalid:\n - ${v.errors.join('\n - ')}` };
478
556
  }
@@ -481,9 +559,20 @@ export async function runTileAppPublishPersonal(opts) {
481
559
  const resolved = resolveBundleDir(opts.manifestPath, read.manifest, opts.bundleDir);
482
560
  if (!resolved.ok)
483
561
  return { ok: false, kind: 'io', message: `bundle: ${resolved.message}` };
484
- const collected = collectBundleFiles(resolved.dir, opts.manifestPath);
562
+ const collected = collectBundleFiles(resolved.dir, opts.manifestPath, {
563
+ entry: read.manifest.surface?.entry,
564
+ include: opts.include,
565
+ });
485
566
  if (!collected.ok)
486
567
  return { ok: false, kind: 'io', message: collected.message };
568
+ // The server refuses a worker bundle without its backend (INVALID_WORKER_BUNDLE)
569
+ // — but only at upload, after the manifest is registered. Check it first.
570
+ if (isWorker) {
571
+ const bundleErrors = workerBundleErrors(collected.files.map((f) => f.path));
572
+ if (bundleErrors.length > 0) {
573
+ return { ok: false, kind: 'validation', message: `worker bundle invalid (${resolved.dir}):\n - ${bundleErrors.join('\n - ')}` };
574
+ }
575
+ }
487
576
  // Screenshots ride along in the bundle, and the server rejects a bad one
488
577
  // during the UPLOAD — which happens after the manifest is already registered.
489
578
  // Check them here, before the first mutating call, so a wrong-aspect image
@@ -500,42 +589,179 @@ export async function runTileAppPublishPersonal(opts) {
500
589
  }
501
590
  const fetchImpl = opts.fetchImpl ?? fetch;
502
591
  const base = apiBase(auth.commonApiUrl);
503
- const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}` };
504
- // 1) Register the manifest (id + publisher are stamped server-side).
505
- let appId;
506
- try {
507
- const res = await fetchImpl(`${base}/tileapps/personal`, {
508
- method: 'POST',
509
- headers,
510
- body: JSON.stringify({ id: localId, manifest: read.manifest }),
511
- });
512
- if (!res.ok)
513
- return { ok: false, kind: 'http', message: `register failed: HTTP ${res.status} — ${await safeText(res)}` };
514
- const json = (await res.json());
515
- if (!json.appId)
516
- return { ok: false, kind: 'http', message: 'register response missing appId' };
517
- appId = json.appId;
518
- }
519
- catch (e) {
520
- return { ok: false, kind: 'http', message: `register request failed: ${e.message}` };
592
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}`, ...podSessionTelemetryHeaders() };
593
+ // MOGUL-D040 P2 ruling (2026-11-07): inside a workspace pod, register + upload
594
+ // go in ONE request, so the owner approves the publish once. Falls back to the
595
+ // two-step path below on a server that predates the batch route.
596
+ let uploadJson = {};
597
+ let installReport;
598
+ const workspaceId = workspaceIdOf(env);
599
+ let appId = '';
600
+ let batched = false;
601
+ if (inWorkspacePod(env)) {
602
+ try {
603
+ const res = await fetchImpl(`${base}/tileapps/personal/publish-batch`, {
604
+ method: 'POST',
605
+ headers,
606
+ // `workspaceId`: this pod's workspace, so the server can move an existing
607
+ // install there to the new version (the install route's own checks apply).
608
+ body: JSON.stringify({
609
+ id: localId, manifest: read.manifest, files: collected.files,
610
+ ...(opts.live ? { live: true } : {}),
611
+ ...(workspaceId ? { workspaceId } : {}),
612
+ }),
613
+ });
614
+ const staged = await stagedForOwner(res, `publishing personal app '${localId}'`);
615
+ if (staged)
616
+ return staged;
617
+ const text = await safeText(res);
618
+ let json = {};
619
+ try {
620
+ json = JSON.parse(text);
621
+ }
622
+ catch { /* not JSON */ }
623
+ const missingRoute = res.status === 404 && json.code !== 'feature-disabled';
624
+ if (!missingRoute) {
625
+ if (!res.ok) {
626
+ if (res.status === 409 && text.includes(DYNAMIC_WORKERS_DISABLED)) {
627
+ return { ok: false, kind: 'http', message: DYNAMIC_WORKERS_DISABLED_MESSAGE };
628
+ }
629
+ const step = json.failedStep === 'bundle' ? 'bundle upload' : 'register';
630
+ return { ok: false, kind: 'http', message: `${step} failed: HTTP ${res.status} — ${text}` };
631
+ }
632
+ if (!json.appId)
633
+ return { ok: false, kind: 'http', message: 'publish response missing appId' };
634
+ appId = json.appId;
635
+ uploadJson = json.bundle ?? {};
636
+ installReport = json.install;
637
+ batched = true;
638
+ }
639
+ }
640
+ catch (e) {
641
+ return { ok: false, kind: 'http', message: `publish request failed: ${e.message}` };
642
+ }
521
643
  }
522
- // 2) Upload the bundle.
523
- try {
524
- const res = await fetchImpl(`${base}/tileapps/personal/${encodeURIComponent(appId)}/bundle`, {
525
- method: 'PUT',
526
- headers,
527
- body: JSON.stringify({ files: collected.files }),
528
- });
529
- if (!res.ok)
530
- return { ok: false, kind: 'http', message: `bundle upload failed: HTTP ${res.status} — ${await safeText(res)}` };
644
+ if (!batched) {
645
+ // 1) Register the manifest (id + publisher are stamped server-side).
646
+ try {
647
+ const res = await fetchImpl(`${base}/tileapps/personal`, {
648
+ method: 'POST',
649
+ headers,
650
+ body: JSON.stringify({ id: localId, manifest: read.manifest }),
651
+ });
652
+ const staged = await stagedForOwner(res, `registering personal app '${localId}'`);
653
+ if (staged)
654
+ return staged;
655
+ if (!res.ok)
656
+ return { ok: false, kind: 'http', message: `register failed: HTTP ${res.status} — ${await safeText(res)}` };
657
+ const json = (await res.json());
658
+ if (!json.appId)
659
+ return { ok: false, kind: 'http', message: 'register response missing appId' };
660
+ appId = json.appId;
661
+ }
662
+ catch (e) {
663
+ return { ok: false, kind: 'http', message: `register request failed: ${e.message}` };
664
+ }
665
+ // 2) Upload the bundle.
666
+ try {
667
+ const res = await fetchImpl(`${base}/tileapps/personal/${encodeURIComponent(appId)}/bundle`, {
668
+ method: 'PUT',
669
+ headers,
670
+ body: JSON.stringify({ files: collected.files, ...(opts.live ? { live: true } : {}) }),
671
+ });
672
+ const staged = await stagedForOwner(res, `uploading the bundle of ${appId}`);
673
+ if (staged)
674
+ return staged;
675
+ if (!res.ok) {
676
+ const body = await safeText(res);
677
+ if (res.status === 409 && body.includes(DYNAMIC_WORKERS_DISABLED)) {
678
+ return { ok: false, kind: 'http', message: DYNAMIC_WORKERS_DISABLED_MESSAGE };
679
+ }
680
+ return { ok: false, kind: 'http', message: `bundle upload failed: HTTP ${res.status} — ${body}` };
681
+ }
682
+ try {
683
+ uploadJson = ((await res.json()) ?? {});
684
+ }
685
+ catch { /* older servers: no report */ }
686
+ }
687
+ catch (e) {
688
+ return { ok: false, kind: 'http', message: `bundle upload request failed: ${e.message}` };
689
+ }
531
690
  }
532
- catch (e) {
533
- return { ok: false, kind: 'http', message: `bundle upload request failed: ${e.message}` };
691
+ const summary = `Published ${appId} (${collected.files.length} file${collected.files.length === 1 ? '' : 's'}, ${collected.totalBytes} bytes)`
692
+ + (collected.skipped.length > 0 ? `\n skipped (docs are not uploaded; --include <path> to upload one): ${collected.skipped.join(', ')}` : '');
693
+ const next = installNextLines(appId, workspaceId, installReport);
694
+ if (!isWorker)
695
+ return { ok: true, output: [summary, ...next].join('\n') };
696
+ // A worker app's bundle is stored either way; `publish` says whether its
697
+ // backend made it, and `live` whether that backend runs on Dynamic Workers.
698
+ // A version with no backend serves a UI whose /api/* is dead, so it is a failure.
699
+ const publish = uploadJson.publish;
700
+ if (publish?.status === 'failed') {
701
+ return { ok: false, kind: 'http', message: `${appId}: the bundle was stored but the worker backend was not published: ${publish.error ?? 'unknown error'}` };
702
+ }
703
+ const lines = [summary, ` live: ${uploadJson.live === true}`];
704
+ if (publish)
705
+ lines.push(` publish: ${publish.status}${publish.backend !== undefined ? ` (backend: ${publish.backend})` : ''}`);
706
+ if (uploadJson.live === true) {
707
+ lines.push(' backend: running live on Dynamic Workers — owner only, as an in-progress edit. Publish without --live to ship a version.');
708
+ }
709
+ else if (publish?.status === 'published') {
710
+ lines.push(opts.live
711
+ ? ' backend: published as a version (Workers for Platforms) — Dynamic Workers is off on this deployment, so --live had no effect.'
712
+ : ' backend: published as a version (Workers for Platforms).');
713
+ }
714
+ else {
715
+ lines.push(' backend: no worker placement report — the worker placement may be off on this deployment, so the backend was not published.');
716
+ }
717
+ lines.push(...next);
718
+ return { ok: true, output: lines.join('\n') };
719
+ }
720
+ /** The refusal code (HTTP 409) for a live worker tile when Dynamic Workers is off on the deployment. */
721
+ const DYNAMIC_WORKERS_DISABLED = 'dynamic-workers-disabled';
722
+ export const DYNAMIC_WORKERS_DISABLED_MESSAGE = 'live worker tiles are not enabled on this deployment; publish without --live';
723
+ /**
724
+ * This pod's workspace id (`WORKSPACE_ID`, set in every session pod), or
725
+ * undefined. Only when the API is the one the pod belongs to (production, or the
726
+ * API the pod was provisioned for): `$WORKSPACE_ID` names a workspace there,
727
+ * not on another API — the same rule `yolo deploy` follows.
728
+ */
729
+ export function workspaceIdOf(env, readFileImpl = defaultReadFile) {
730
+ const ws = (env.WORKSPACE_ID ?? '').trim().toLowerCase();
731
+ if (!inWorkspacePod(env) || !/^[a-f0-9]{24}$/.test(ws))
732
+ return undefined;
733
+ if (isProductionTarget(env))
734
+ return ws;
735
+ const provisioned = podProvisionedApiUrl(env, readFileImpl);
736
+ return provisioned && sameApiOrigin(provisioned, targetApiUrl(env)) ? ws : undefined;
737
+ }
738
+ /**
739
+ * The publish output's install line(s): what happened to the workspace install,
740
+ * and exactly ONE next command when one is needed.
741
+ */
742
+ export function installNextLines(appId, workspaceId, report) {
743
+ const ws = workspaceId ?? '<workspaceId>';
744
+ const install = `yolo tileapp install ${appId} --workspace ${ws}`;
745
+ const addTile = `yolo tileapp add-tile ${appId} --workspace ${ws}`;
746
+ switch (report?.status) {
747
+ case 'upgraded': {
748
+ const n = report.refreshedTileIds?.length ?? 0;
749
+ return [` install: this workspace's install moved to ${report.version ?? 'the new version'}${n > 0 ? ` (${n} open tile${n === 1 ? '' : 's'} reloading)` : ''} — nothing else to run.`];
750
+ }
751
+ case 'current':
752
+ return [' install: this workspace already runs this version — nothing else to run.'];
753
+ case 'not-installed':
754
+ return [` next: ${install} && ${addTile}`];
755
+ case 'reconsent-required': {
756
+ const perms = [...(report.newRequiredPermissions ?? []), ...(report.stalePermissions ?? []).map((p) => `-${p}`)];
757
+ return [` next: ${install} (this version changes the app's permissions${perms.length ? `: ${perms.join(', ')}` : ''}, so it needs your consent again)`];
758
+ }
759
+ case 'failed':
760
+ return [` install: not moved to the new version (${report.error ?? 'the install step failed'})`, ` next: ${install}`];
761
+ default:
762
+ // No report: published outside a workspace pod, or a server that predates it.
763
+ return [` next: if it's already installed, ${install} moves the install to this version; if not, also run ${addTile}`];
534
764
  }
535
- return {
536
- ok: true,
537
- output: `Published ${appId} (${collected.files.length} file${collected.files.length === 1 ? '' : 's'}, ${collected.totalBytes} bytes)\n next: install it + add a tile from the workspace (or via the studio.install_app / studio.create_app_tile MCP tools).`,
538
- };
539
765
  }
540
766
  /**
541
767
  * Build the app image in-pod with podman, `save` it to an OCI archive in the
@@ -658,6 +884,7 @@ async function publishRuntime(p) {
658
884
  headers: {
659
885
  'content-type': 'application/octet-stream',
660
886
  authorization: `Bearer ${p.auth.userToken}`,
887
+ ...podSessionTelemetryHeaders(),
661
888
  'x-tileapp-manifest': manifestHeader,
662
889
  },
663
890
  body: fs.createReadStream(archiveTmp),
@@ -671,7 +898,7 @@ async function publishRuntime(p) {
671
898
  return { ok: false, kind: 'http', message: 'publish-image response missing appId' };
672
899
  return {
673
900
  ok: true,
674
- output: `Published runtime app ${json.appId}\n image: ${json.ref}:${json.tag}@${json.digest}\n next: install it + add a tile (studio.install_app / studio.create_app_tile).`,
901
+ output: [`Published runtime app ${json.appId}`, ` image: ${json.ref}:${json.tag}@${json.digest}`, ...installNextLines(json.appId, workspaceIdOf(p.env), undefined)].join('\n'),
675
902
  };
676
903
  }
677
904
  catch (e) {