@yolo-labs/yolo-cli 1.0.0 → 1.1.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.
@@ -336,6 +336,103 @@ function readWranglerConfig(cwd, read) {
336
336
  }
337
337
  return undefined;
338
338
  }
339
+ /**
340
+ * Read top-level `triggers.crons` from wrangler.jsonc / wrangler.json /
341
+ * wrangler.toml. YOLO Host used to DROP these silently; now they ship with the
342
+ * release (the server validates them and refuses while the platform flag is
343
+ * off). A malformed stanza is an error, never a silent skip. Env-scoped
344
+ * triggers (`env.<name>.triggers`) are not read — wrangler's env overrides are
345
+ * not a YOLO Host concept.
346
+ */
347
+ export function readWranglerCrons(cwd, readFileImpl) {
348
+ const read = readFileImpl ?? defaultReadFile;
349
+ for (const name of ['wrangler.jsonc', 'wrangler.json']) {
350
+ const text = read(path.join(cwd, name));
351
+ if (text === undefined)
352
+ continue;
353
+ const parsed = parseJsonc(text);
354
+ if (parsed === undefined)
355
+ return { ok: true, crons: undefined };
356
+ const triggers = parsed.triggers;
357
+ if (triggers === undefined || triggers === null) {
358
+ const envs = parsed.env;
359
+ const envCrons = envs !== null && typeof envs === 'object' && !Array.isArray(envs)
360
+ && Object.values(envs).some((e) => {
361
+ const t = e !== null && typeof e === 'object' ? e.triggers : undefined;
362
+ return t !== null && typeof t === 'object' && Array.isArray(t.crons)
363
+ && t.crons.length > 0;
364
+ });
365
+ if (envCrons) {
366
+ return {
367
+ ok: false,
368
+ message: `${name}: crons are declared only under \`env.<name>.triggers\` — YOLO Host reads the top-level \`triggers.crons\``,
369
+ };
370
+ }
371
+ return { ok: true, crons: undefined };
372
+ }
373
+ if (typeof triggers !== 'object' || Array.isArray(triggers)) {
374
+ return { ok: false, message: `${name}: \`triggers\` must be an object like { "crons": ["*/15 * * * *"] }` };
375
+ }
376
+ const crons = triggers.crons;
377
+ if (crons === undefined)
378
+ return { ok: true, crons: undefined };
379
+ if (!Array.isArray(crons) || crons.some((c) => typeof c !== 'string')) {
380
+ return { ok: false, message: `${name}: \`triggers.crons\` must be an array of cron strings` };
381
+ }
382
+ return { ok: true, crons: crons, sourceFile: name };
383
+ }
384
+ const toml = read(path.join(cwd, 'wrangler.toml'));
385
+ if (toml === undefined)
386
+ return { ok: true, crons: undefined };
387
+ return extractTomlCrons(toml);
388
+ }
389
+ /**
390
+ * `[triggers]` → `crons = ["…", '…']`, single- or multi-line. Line comments
391
+ * outside strings are dropped. Anything else in the value is an error.
392
+ */
393
+ function extractTomlCrons(text) {
394
+ const lines = text.split('\n');
395
+ let section = '';
396
+ for (let i = 0; i < lines.length; i++) {
397
+ const line = lines[i].trim();
398
+ const sectionMatch = /^\[([^\]]+)\]/.exec(line);
399
+ if (sectionMatch) {
400
+ section = sectionMatch[1].trim();
401
+ continue;
402
+ }
403
+ if (section !== 'triggers')
404
+ continue;
405
+ const m = /^crons\s*=\s*(.*)$/.exec(line);
406
+ if (!m)
407
+ continue;
408
+ let value = m[1];
409
+ while (!value.includes(']') && i + 1 < lines.length)
410
+ value += '\n' + lines[++i];
411
+ const body = /^\[([\s\S]*)\]\s*(#.*)?$/.exec(value.trim());
412
+ if (!body)
413
+ return { ok: false, message: 'wrangler.toml: `[triggers] crons` must be an array of cron strings' };
414
+ const crons = [];
415
+ const rest = body[1].replace(/#[^\n"']*$/gm, '').replace(/("[^"]*"|'[^']*')|\s+|,/g, (tok, str) => {
416
+ if (str)
417
+ crons.push(str.slice(1, -1));
418
+ return '';
419
+ });
420
+ if (rest.trim() !== '') {
421
+ return { ok: false, message: 'wrangler.toml: `[triggers] crons` must be an array of quoted cron strings' };
422
+ }
423
+ return { ok: true, crons, sourceFile: 'wrangler.toml' };
424
+ }
425
+ // A `crons` key we could not attribute to a top-level `[triggers]` table (an
426
+ // inline table, or `[env.<name>.triggers]`) must not be skipped quietly.
427
+ if (/^\s*(triggers\s*=.*crons|crons\s*=)/m.test(text)) {
428
+ return {
429
+ ok: false,
430
+ message: 'wrangler.toml declares `crons` outside a top-level `[triggers]` table — YOLO Host reads only\n' +
431
+ '[triggers]\ncrons = ["*/15 * * * *"]',
432
+ };
433
+ }
434
+ return { ok: true, crons: undefined };
435
+ }
339
436
  /**
340
437
  * Adapt an existing wrangler config into the canonical `.yolo/deploy.json`
341
438
  * shape — the migration `yolo deploy init` performs once when a project has a
@@ -22,7 +22,7 @@ import * as path from 'node:path';
22
22
  import * as fs from 'node:fs';
23
23
  import { spawn, execFileSync } from 'node:child_process';
24
24
  import { readDeployConfig } from './deploy-config.js';
25
- import { detectProjectShape } from './deploy-detect.js';
25
+ import { detectProjectShape, readWranglerCrons } from './deploy-detect.js';
26
26
  import { bundleProject } from './deploy-bundle.js';
27
27
  import { resolveDeployContext, startShip, uploadAssetBucket, finalizeShip, } from './deploy-client.js';
28
28
  import { defaultPendingStore, PENDING_MAX_AGE_MS, } from './deploy-pending.js';
@@ -144,6 +144,27 @@ export async function runDeployShip(options) {
144
144
  if (!detected.ok)
145
145
  return fail('detect-failed', detected.message);
146
146
  const shape = detected.shape;
147
+ // 2.5 Cron triggers — deploy.json `crons` wins (`[]` = explicitly none),
148
+ // else wrangler `triggers.crons`. Sent as declared; the server validates
149
+ // (syntax, ≤3, min interval) and refuses — never drops — when the platform
150
+ // flag is off. A malformed stanza fails here rather than shipping without it.
151
+ let crons = [];
152
+ let cronsSource = '.yolo/deploy.json';
153
+ if (config.crons !== undefined) {
154
+ crons = config.crons;
155
+ }
156
+ else {
157
+ const fromWrangler = (deps.readWranglerCronsImpl ?? readWranglerCrons)(cwd);
158
+ if (!fromWrangler.ok)
159
+ return fail('cron-invalid', fromWrangler.message);
160
+ if (fromWrangler.crons !== undefined) {
161
+ crons = fromWrangler.crons;
162
+ cronsSource = fromWrangler.sourceFile;
163
+ }
164
+ }
165
+ if (crons.length > 0) {
166
+ progress(`deploy: crons ${crons.length} declared in ${cronsSource} (UTC): ${crons.join(' | ')}`);
167
+ }
147
168
  // 3. Build (if the shape carries a build command).
148
169
  if (shape.buildCommand) {
149
170
  const startedAt = Date.now();
@@ -181,6 +202,7 @@ export async function runDeployShip(options) {
181
202
  fileCount,
182
203
  totalAssetBytes: bundled.totalAssetBytes,
183
204
  bundleDigest: bundled.bundleDigest,
205
+ ...(crons.length > 0 ? { crons } : {}),
184
206
  };
185
207
  // 5. Dry-run stops here — fully offline by construction (auth + network
186
208
  // resolution happen below this line).
@@ -208,6 +230,11 @@ export async function runDeployShip(options) {
208
230
  if (config.compatibilityFlags && config.compatibilityFlags.length > 0) {
209
231
  request.compatibilityFlags = config.compatibilityFlags;
210
232
  }
233
+ // A Worker ship always sends `crons`, `[]` included: the field's presence is how the server tells a
234
+ // cron-aware client from a pre-cron CLI, whose Worker ships with scheduled() it refuses
235
+ // (`cron-client-outdated`) rather than shipping without the crons that CLI could not read.
236
+ if (crons.length > 0 || shape.type === 'worker')
237
+ request.crons = crons;
211
238
  const gitSha = resolveGitSha(cwd);
212
239
  if (gitSha)
213
240
  request.gitSha = gitSha;
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * Exit codes: 0 success · 1 http · 64 usage/auth.
14
14
  */
15
- import { resolveSubstrateContext } from './auth-context.js';
15
+ import { podSessionTelemetryHeaders, resolveSubstrateContext } from './auth-context.js';
16
16
  import { SUBSTRATE_CLI_AGENT_ID } from './work-client.js';
17
17
  export async function runMcpScopes(options) {
18
18
  const env = options.env ?? process.env;
@@ -29,7 +29,7 @@ export async function runMcpScopes(options) {
29
29
  try {
30
30
  const response = await fetchImpl(url, {
31
31
  method: 'GET',
32
- headers: { Authorization: `Bearer ${userToken}` },
32
+ headers: { Authorization: `Bearer ${userToken}`, ...podSessionTelemetryHeaders() },
33
33
  });
34
34
  if (!response.ok) {
35
35
  const text = await safeReadText(response);
@@ -0,0 +1,47 @@
1
+ /**
2
+ * MOGUL-D040 P2 / OD-5 — "the owner has to approve this" from a workspace pod.
3
+ *
4
+ * When common-api enforces the pod-token boundary, an account-wide request made
5
+ * from a pod (re-linking a deploy project, a domain change, registering or
6
+ * uploading a personal app, a prod ship with the hosting gate off) is not run:
7
+ * it is staged as an owner approval and answered with
8
+ *
9
+ * 202 { ok:false, reason:'approval-required', code:'POD_OWNER_APPROVAL_REQUESTED',
10
+ * approvalId, statement, expiresAt, pollPath, hint }
11
+ *
12
+ * The owner approves it in Studio (the deploy approval card) and it then runs AS
13
+ * THE OWNER. So the CLI must NOT treat the 202 as success (nothing happened yet)
14
+ * and must NOT resend the request (the approval runs it).
15
+ */
16
+ export const POD_OWNER_APPROVAL_CODE = 'POD_OWNER_APPROVAL_REQUESTED';
17
+ function str(v) {
18
+ return typeof v === 'string' && v.length > 0 ? v : undefined;
19
+ }
20
+ /** The staged-approval answer, or null for any other response. */
21
+ export function ownerApprovalRequestedOf(status, body) {
22
+ if (status !== 202 || !body || typeof body !== 'object')
23
+ return null;
24
+ const b = body;
25
+ if (b.code !== POD_OWNER_APPROVAL_CODE)
26
+ return null;
27
+ const approvalId = str(b.approvalId);
28
+ if (!approvalId)
29
+ return null;
30
+ return {
31
+ approvalId,
32
+ ...(str(b.statement) ? { statement: str(b.statement) } : {}),
33
+ ...(str(b.expiresAt) ? { expiresAt: str(b.expiresAt) } : {}),
34
+ message: str(b.message) ?? 'Owner approval requested in Studio.',
35
+ ...(str(b.hint) ? { hint: str(b.hint) } : {}),
36
+ };
37
+ }
38
+ /** The PENDING block the CLI prints (exit 3, like a prod-ship approval). */
39
+ export function formatOwnerApprovalPending(a, what = 'this request') {
40
+ return [
41
+ `PENDING [awaiting-approval]: ${what} needs the workspace owner's approval (approval ${a.approvalId}).`,
42
+ ...(a.statement ? [` asks: ${a.statement}`] : []),
43
+ ` approve: the owner approves it in Studio (notification / Approvals panel)${a.expiresAt ? ` before ${a.expiresAt}` : ''}.`,
44
+ ' then: it runs AS THE OWNER on approval. Do not rerun the command for this step;',
45
+ ' MCP callers can poll deploy.approval_status with the approval id.',
46
+ ].join('\n');
47
+ }
@@ -21,7 +21,7 @@ import * as fs from 'node:fs';
21
21
  import * as path from 'node:path';
22
22
  import * as http from 'node:http';
23
23
  import { createServeHandler } from './serve.js';
24
- import { validateManifest, isRuntimeManifest, publishGateErrors } from './tileapp-validator.js';
24
+ import { validateManifest, isRuntimeManifest, isWorkerRuntimeManifest, publishGateErrors } from './tileapp-validator.js';
25
25
  /** The mock-broker + helper routes the dev server mounts (under a reserved
26
26
  * prefix so they can't collide with a real bundle asset path). */
27
27
  export const DEV_BROKER_PATH = '/__yolo/broker';
@@ -115,7 +115,10 @@ export function runTileAppValidate(opts) {
115
115
  const v = validateManifest(read.manifest, {
116
116
  allowPlatformHostedScreenshots: !!opts.personal && !isRuntimeManifest(read.manifest),
117
117
  });
118
- const errors = [...v.errors, ...publishGateErrors(read.manifest)];
118
+ // The image-digest gate is the marketplace publish rule; a PERSONAL worker app
119
+ // ships its backend in the bundle and has no image to pin.
120
+ const skipGate = !!opts.personal && isWorkerRuntimeManifest(read.manifest);
121
+ const errors = [...v.errors, ...(skipGate ? [] : publishGateErrors(read.manifest))];
119
122
  // A non-object manifest is fully reported by validateManifest; bail before the
120
123
  // bundle/runtime checks (which deref manifest fields) so we never crash on it.
121
124
  const manifestIsObject = typeof read.manifest === 'object' && read.manifest !== null && !Array.isArray(read.manifest);
@@ -13,13 +13,20 @@
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 { podSessionTelemetryHeaders, resolveUserToken } from './auth-context.js';
26
+ import { resolveCommonApiUrl } from './api-url.js';
27
+ import { formatOwnerApprovalPending, ownerApprovalRequestedOf } from './pod-owner-approval.js';
28
+ import { missingUserTokenMessage } from './api-env.js';
29
+ import { validateManifest, isRuntimeManifest, isWorkerRuntimeManifest, workerBundleErrors } from './tileapp-validator.js';
23
30
  import { readImageDimensions } from './image-dimensions.js';
24
31
  import { resolveBundleDir } from './tileapp-developer.js';
25
32
  import { parseDockerfile, assembleOciArchive } from './tileapp-oci-assembler.js';
@@ -39,6 +46,9 @@ function defaultExec(file, args) {
39
46
  });
40
47
  }
41
48
  export function exitCodeForFailure(kind) {
49
+ // MOGUL-D040 P2: staged for the workspace owner — NOT an error (same exit as a pending prod ship).
50
+ if (kind === 'awaiting-approval')
51
+ return 3;
42
52
  if (kind === 'http')
43
53
  return 1;
44
54
  if (kind === 'validation')
@@ -55,14 +65,16 @@ function apiBase(commonApiUrl) {
55
65
  return base.endsWith('/v1') ? base : `${base}/v1`;
56
66
  }
57
67
  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' };
68
+ const commonApiUrl = resolveCommonApiUrl(env);
61
69
  const userToken = resolveUserToken(env);
62
70
  if (!userToken)
63
- return { ok: false, message: 'no user token: set YOLO_API_TOKEN or sign in (~/.config/yolo/token)' };
71
+ return { ok: false, message: missingUserTokenMessage(env) };
64
72
  return { ok: true, commonApiUrl, userToken };
65
73
  }
74
+ /** A workspace pod (container-api sets SESSION_ID; the deploy CLI reads the same marker). */
75
+ function inWorkspacePod(env) {
76
+ return typeof env.SESSION_ID === 'string' && env.SESSION_ID.length > 0;
77
+ }
66
78
  async function safeText(res) {
67
79
  try {
68
80
  return await res.text();
@@ -71,6 +83,23 @@ async function safeText(res) {
71
83
  return '<no body>';
72
84
  }
73
85
  }
86
+ /**
87
+ * MOGUL-D040 P2: a 202 staged-approval answer (the step was NOT performed; the
88
+ * owner approves it in Studio and it then runs as the owner). Null otherwise.
89
+ */
90
+ async function stagedForOwner(res, what) {
91
+ if (res.status !== 202)
92
+ return null;
93
+ let body;
94
+ try {
95
+ body = await (res.clone ? res.clone() : res).json();
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ const staged = ownerApprovalRequestedOf(res.status, body);
101
+ return staged ? { ok: false, kind: 'awaiting-approval', message: formatOwnerApprovalPending(staged, what) } : null;
102
+ }
74
103
  function readManifest(p) {
75
104
  let raw;
76
105
  try {
@@ -121,12 +150,10 @@ export function runTileAppInit(opts) {
121
150
  a real tokenizer/parser in app.js; you cannot shortcut with eval.
122
151
  • NO network — no CDN scripts, remote fonts, or fetch() to other origins.
123
152
  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.
153
+ CSS: inline <style> and style="…" work, but keep it in style.css (linked
154
+ below) so the page is easy to review.
125
155
  -->
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>
156
+ <link rel="stylesheet" href="style.css" />
130
157
  </head>
131
158
  <body>
132
159
  <main>
@@ -140,6 +167,10 @@ export function runTileAppInit(opts) {
140
167
  <script src="app.js" type="module"></script>
141
168
  </body>
142
169
  </html>
170
+ `;
171
+ const styleCss = `/* ${title} — the app's CSS. */
172
+ body { font: 15px/1.5 system-ui, sans-serif; margin: 0; display: grid; place-items: center;
173
+ height: 100vh; color: #e5e7eb; background: #111827; }
143
174
  `;
144
175
  const appJs = `// ${title} — personal tile-app logic.
145
176
  //
@@ -194,6 +225,7 @@ Check refs before publishing: yolo tileapp validate tileapp.json --personal
194
225
  fs.writeFileSync(path.join(dir, 'tileapp.json'), `${JSON.stringify(manifest, null, 2)}\n`);
195
226
  fs.writeFileSync(path.join(dir, 'index.html'), indexHtml);
196
227
  fs.writeFileSync(path.join(dir, 'app.js'), appJs);
228
+ fs.writeFileSync(path.join(dir, 'style.css'), styleCss);
197
229
  fs.mkdirSync(path.join(dir, 'media'), { recursive: false });
198
230
  fs.writeFileSync(path.join(dir, 'media', 'README.md'), mediaReadme);
199
231
  }
@@ -202,7 +234,7 @@ Check refs before publishing: yolo tileapp validate tileapp.json --personal
202
234
  }
203
235
  return {
204
236
  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`,
237
+ 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: 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`,
206
238
  };
207
239
  }
208
240
  /**
@@ -294,7 +326,7 @@ export async function runTileAppMediaPush(opts) {
294
326
  }
295
327
  const fetchImpl = opts.fetchImpl ?? fetch;
296
328
  const base = apiBase(auth.commonApiUrl);
297
- const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}` };
329
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}`, ...podSessionTelemetryHeaders() };
298
330
  // Resolve the namespaced appId (pa-<ownerId>-<localId>) — the caller only
299
331
  // knows the local slug; the owner half is server-side.
300
332
  let appId;
@@ -362,6 +394,9 @@ export async function runTileAppMediaPush(opts) {
362
394
  headers,
363
395
  body: JSON.stringify({ files: batch }),
364
396
  });
397
+ const staged = await stagedForOwner(res, `uploading media for ${appId}`);
398
+ if (staged)
399
+ return staged;
365
400
  if (!res.ok) {
366
401
  const sofar = uploaded.length > 0 ? ` (${uploaded.length} image(s) already uploaded)` : '';
367
402
  return { ok: false, kind: 'http', message: `media upload failed: HTTP ${res.status} — ${await safeText(res)}${sofar}` };
@@ -459,7 +494,13 @@ export async function runTileAppPublishPersonal(opts) {
459
494
  if (!LOCAL_ID_RE.test(localId)) {
460
495
  return { ok: false, kind: 'validation', message: `manifest "id" must be a lowercase kebab-case slug, 2-32 chars (got '${localId}')` };
461
496
  }
497
+ const isWorker = isWorkerRuntimeManifest(read.manifest);
498
+ if (opts.live && !isWorker) {
499
+ return { ok: false, kind: 'usage', message: "--live applies only to a runtime.kind 'worker' app (its backend is what runs live); publish without --live" };
500
+ }
462
501
  // Runtime app (has `runtime`/`image`): build the image in-pod + mediated push.
502
+ // A worker app is NOT one (isRuntimeManifest excludes it): it falls through to
503
+ // the bundle path below, backend included.
463
504
  // Branch BEFORE the strict pure-UI lint, since a runtime manifest legitimately
464
505
  // omits `image` (the server fills it from the actual pushed digest).
465
506
  if (isRuntimeManifest(read.manifest)) {
@@ -484,6 +525,14 @@ export async function runTileAppPublishPersonal(opts) {
484
525
  const collected = collectBundleFiles(resolved.dir, opts.manifestPath);
485
526
  if (!collected.ok)
486
527
  return { ok: false, kind: 'io', message: collected.message };
528
+ // The server refuses a worker bundle without its backend (INVALID_WORKER_BUNDLE)
529
+ // — but only at upload, after the manifest is registered. Check it first.
530
+ if (isWorker) {
531
+ const bundleErrors = workerBundleErrors(collected.files.map((f) => f.path));
532
+ if (bundleErrors.length > 0) {
533
+ return { ok: false, kind: 'validation', message: `worker bundle invalid (${resolved.dir}):\n - ${bundleErrors.join('\n - ')}` };
534
+ }
535
+ }
487
536
  // Screenshots ride along in the bundle, and the server rejects a bad one
488
537
  // during the UPLOAD — which happens after the manifest is already registered.
489
538
  // Check them here, before the first mutating call, so a wrong-aspect image
@@ -500,43 +549,127 @@ export async function runTileAppPublishPersonal(opts) {
500
549
  }
501
550
  const fetchImpl = opts.fetchImpl ?? fetch;
502
551
  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}` };
521
- }
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)}` };
552
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${auth.userToken}`, ...podSessionTelemetryHeaders() };
553
+ // MOGUL-D040 P2 ruling (2026-11-07): inside a workspace pod, register + upload
554
+ // go in ONE request, so the owner approves the publish once. Falls back to the
555
+ // two-step path below on a server that predates the batch route.
556
+ let uploadJson = {};
557
+ let appId = '';
558
+ let batched = false;
559
+ if (inWorkspacePod(env)) {
560
+ try {
561
+ const res = await fetchImpl(`${base}/tileapps/personal/publish-batch`, {
562
+ method: 'POST',
563
+ headers,
564
+ body: JSON.stringify({ id: localId, manifest: read.manifest, files: collected.files, ...(opts.live ? { live: true } : {}) }),
565
+ });
566
+ const staged = await stagedForOwner(res, `publishing personal app '${localId}'`);
567
+ if (staged)
568
+ return staged;
569
+ const text = await safeText(res);
570
+ let json = {};
571
+ try {
572
+ json = JSON.parse(text);
573
+ }
574
+ catch { /* not JSON */ }
575
+ const missingRoute = res.status === 404 && json.code !== 'feature-disabled';
576
+ if (!missingRoute) {
577
+ if (!res.ok) {
578
+ if (res.status === 409 && text.includes(DYNAMIC_WORKERS_DISABLED)) {
579
+ return { ok: false, kind: 'http', message: DYNAMIC_WORKERS_DISABLED_MESSAGE };
580
+ }
581
+ const step = json.failedStep === 'bundle' ? 'bundle upload' : 'register';
582
+ return { ok: false, kind: 'http', message: `${step} failed: HTTP ${res.status} — ${text}` };
583
+ }
584
+ if (!json.appId)
585
+ return { ok: false, kind: 'http', message: 'publish response missing appId' };
586
+ appId = json.appId;
587
+ uploadJson = json.bundle ?? {};
588
+ batched = true;
589
+ }
590
+ }
591
+ catch (e) {
592
+ return { ok: false, kind: 'http', message: `publish request failed: ${e.message}` };
593
+ }
531
594
  }
532
- catch (e) {
533
- return { ok: false, kind: 'http', message: `bundle upload request failed: ${e.message}` };
595
+ if (!batched) {
596
+ // 1) Register the manifest (id + publisher are stamped server-side).
597
+ try {
598
+ const res = await fetchImpl(`${base}/tileapps/personal`, {
599
+ method: 'POST',
600
+ headers,
601
+ body: JSON.stringify({ id: localId, manifest: read.manifest }),
602
+ });
603
+ const staged = await stagedForOwner(res, `registering personal app '${localId}'`);
604
+ if (staged)
605
+ return staged;
606
+ if (!res.ok)
607
+ return { ok: false, kind: 'http', message: `register failed: HTTP ${res.status} — ${await safeText(res)}` };
608
+ const json = (await res.json());
609
+ if (!json.appId)
610
+ return { ok: false, kind: 'http', message: 'register response missing appId' };
611
+ appId = json.appId;
612
+ }
613
+ catch (e) {
614
+ return { ok: false, kind: 'http', message: `register request failed: ${e.message}` };
615
+ }
616
+ // 2) Upload the bundle.
617
+ try {
618
+ const res = await fetchImpl(`${base}/tileapps/personal/${encodeURIComponent(appId)}/bundle`, {
619
+ method: 'PUT',
620
+ headers,
621
+ body: JSON.stringify({ files: collected.files, ...(opts.live ? { live: true } : {}) }),
622
+ });
623
+ const staged = await stagedForOwner(res, `uploading the bundle of ${appId}`);
624
+ if (staged)
625
+ return staged;
626
+ if (!res.ok) {
627
+ const body = await safeText(res);
628
+ if (res.status === 409 && body.includes(DYNAMIC_WORKERS_DISABLED)) {
629
+ return { ok: false, kind: 'http', message: DYNAMIC_WORKERS_DISABLED_MESSAGE };
630
+ }
631
+ return { ok: false, kind: 'http', message: `bundle upload failed: HTTP ${res.status} — ${body}` };
632
+ }
633
+ try {
634
+ uploadJson = ((await res.json()) ?? {});
635
+ }
636
+ catch { /* older servers: no report */ }
637
+ }
638
+ catch (e) {
639
+ return { ok: false, kind: 'http', message: `bundle upload request failed: ${e.message}` };
640
+ }
534
641
  }
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
- };
642
+ const summary = `Published ${appId} (${collected.files.length} file${collected.files.length === 1 ? '' : 's'}, ${collected.totalBytes} bytes)`;
643
+ const next = ' next: install it + add a tile from the workspace (or via the studio.install_app / studio.create_app_tile MCP tools).';
644
+ if (!isWorker)
645
+ return { ok: true, output: `${summary}\n${next}` };
646
+ // A worker app's bundle is stored either way; `publish` says whether its
647
+ // backend made it, and `live` whether that backend runs on Dynamic Workers.
648
+ // A version with no backend serves a UI whose /api/* is dead, so it is a failure.
649
+ const publish = uploadJson.publish;
650
+ if (publish?.status === 'failed') {
651
+ return { ok: false, kind: 'http', message: `${appId}: the bundle was stored but the worker backend was not published: ${publish.error ?? 'unknown error'}` };
652
+ }
653
+ const lines = [summary, ` live: ${uploadJson.live === true}`];
654
+ if (publish)
655
+ lines.push(` publish: ${publish.status}${publish.backend !== undefined ? ` (backend: ${publish.backend})` : ''}`);
656
+ if (uploadJson.live === true) {
657
+ lines.push(' backend: running live on Dynamic Workers — owner only, as an in-progress edit. Publish without --live to ship a version.');
658
+ }
659
+ else if (publish?.status === 'published') {
660
+ lines.push(opts.live
661
+ ? ' backend: published as a version (Workers for Platforms) — Dynamic Workers is off on this deployment, so --live had no effect.'
662
+ : ' backend: published as a version (Workers for Platforms).');
663
+ }
664
+ else {
665
+ lines.push(' backend: no worker placement report — the worker placement may be off on this deployment, so the backend was not published.');
666
+ }
667
+ lines.push(next);
668
+ return { ok: true, output: lines.join('\n') };
539
669
  }
670
+ /** The refusal code (HTTP 409) for a live worker tile when Dynamic Workers is off on the deployment. */
671
+ const DYNAMIC_WORKERS_DISABLED = 'dynamic-workers-disabled';
672
+ export const DYNAMIC_WORKERS_DISABLED_MESSAGE = 'live worker tiles are not enabled on this deployment; publish without --live';
540
673
  /**
541
674
  * Build the app image in-pod with podman, `save` it to an OCI archive in the
542
675
  * workspace, and hand it to common-api's MEDIATED push endpoint — common-api
@@ -658,6 +791,7 @@ async function publishRuntime(p) {
658
791
  headers: {
659
792
  'content-type': 'application/octet-stream',
660
793
  authorization: `Bearer ${p.auth.userToken}`,
794
+ ...podSessionTelemetryHeaders(),
661
795
  'x-tileapp-manifest': manifestHeader,
662
796
  },
663
797
  body: fs.createReadStream(archiveTmp),