@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.
@@ -27,24 +27,24 @@
27
27
  * `readFileImpl` for the token file) so unit tests never touch real network
28
28
  * or the real FS — the work-client.test.ts convention.
29
29
  */
30
- import { resolveUserToken } from './auth-context.js';
30
+ import { missingUserTokenMessage, podSessionTelemetryHeaders, resolveUserToken } from './auth-context.js';
31
31
  import { userRouteRequest } from './work-client.js';
32
+ import { ownerApprovalRequestedOf } from './pod-owner-approval.js';
33
+ import { resolveCommonApiUrl } from './api-url.js';
32
34
  /**
33
35
  * Resolve the deploy transport context. Checks the env trio once up front
34
36
  * (fail fast with a single auth message); the token itself is still
35
37
  * re-resolved per leg by every client function.
36
38
  */
37
39
  export function resolveDeployContext(env = process.env, readFileImpl, fetchImpl) {
38
- const commonApiUrl = env.YOLO_COMMON_API_URL || env.YOLO_API_URL;
39
- if (!commonApiUrl) {
40
- return { ok: false, kind: 'auth', message: 'YOLO_COMMON_API_URL (or YOLO_API_URL) env var is required' };
41
- }
40
+ // Defaults to production when neither URL env var is set (api-url.ts).
41
+ const commonApiUrl = resolveCommonApiUrl(env);
42
42
  const token = currentTokenFrom(env, readFileImpl);
43
43
  if (!token) {
44
44
  return {
45
45
  ok: false,
46
46
  kind: 'auth',
47
- message: 'no user token available: expected a user access JWT in ~/.config/yolo/token or the YOLO_API_TOKEN env var',
47
+ message: missingUserTokenMessage(env),
48
48
  };
49
49
  }
50
50
  return { ok: true, context: { commonApiUrl, env, readFileImpl, fetchImpl } };
@@ -112,13 +112,13 @@ export async function finalizeShip(ctx, projectId, shipId, modules = [], sourceM
112
112
  // status` before rerunning rather than auto-looping into a misleading error.
113
113
  const token = currentToken(ctx);
114
114
  if (!token)
115
- return missingTokenFailure();
115
+ return missingTokenFailure({ ...ctx.env, YOLO_COMMON_API_URL: ctx.commonApiUrl });
116
116
  const fetchImpl = resolveFetch(ctx);
117
117
  if (!fetchImpl)
118
118
  return noFetchFailure();
119
119
  const url = `${stripTrailingSlash(ctx.commonApiUrl)}/v1/deploy/projects/${enc(projectId)}/ship/${enc(shipId)}/finalize`;
120
120
  // Optional session provenance for the hosting audit record.
121
- const requestHeaders = sessionContextHeaders(ctx.env);
121
+ const requestHeaders = { ...sessionContextHeaders(ctx.env), ...podSessionTelemetryHeaders(ctx.env) };
122
122
  // Resume-after-grant: the pending-store rerun redeems the operator's grant
123
123
  // explicitly (x-approval-id → approvalNonce server-side), which yields crisp
124
124
  // approval-pending/-denied/-expired outcomes instead of the nonce-less
@@ -414,7 +414,9 @@ async function withRetry(ctx, leg, fn) {
414
414
  * rotation must not expire a multi-leg ship mid-flight).
415
415
  */
416
416
  function currentToken(ctx) {
417
- return currentTokenFrom(ctx.env, ctx.readFileImpl);
417
+ // Decide which credential is allowed against the URL this context actually calls (api-env.ts), not
418
+ // whatever the env says: a context built for staging must never pick up the production token.
419
+ return currentTokenFrom({ ...ctx.env, YOLO_COMMON_API_URL: ctx.commonApiUrl }, ctx.readFileImpl);
418
420
  }
419
421
  function currentTokenFrom(env, readFileImpl) {
420
422
  return readFileImpl ? resolveUserToken(env, readFileImpl) : resolveUserToken(env);
@@ -426,7 +428,7 @@ function resolveFetch(ctx) {
426
428
  async function jsonLeg(ctx, routePath, init) {
427
429
  const token = currentToken(ctx);
428
430
  if (!token)
429
- return missingTokenFailure();
431
+ return missingTokenFailure({ ...ctx.env, YOLO_COMMON_API_URL: ctx.commonApiUrl });
430
432
  let response;
431
433
  try {
432
434
  response = await userRouteRequest({ commonApiUrl: ctx.commonApiUrl, userToken: token, fetchImpl: ctx.fetchImpl }, routePath, init);
@@ -435,12 +437,28 @@ async function jsonLeg(ctx, routePath, init) {
435
437
  return networkFailure(err);
436
438
  }
437
439
  if (response.ok) {
440
+ let value;
438
441
  try {
439
- return { ok: true, value: await response.json() };
442
+ value = await response.json();
440
443
  }
441
444
  catch {
442
445
  return { ok: true, value: {} };
443
446
  }
447
+ // MOGUL-D040 P2: from a pod, an account-wide step is STAGED for the owner
448
+ // (202), not performed. Not a success, and never resent: the approval runs it.
449
+ const staged = ownerApprovalRequestedOf(response.status, value);
450
+ if (staged) {
451
+ return {
452
+ ok: false,
453
+ kind: 'awaiting-approval',
454
+ message: staged.message,
455
+ status: response.status,
456
+ detail: { approvalId: staged.approvalId, ...(staged.statement ? { statement: staged.statement } : {}), ...(staged.expiresAt ? { expiresAt: staged.expiresAt } : {}) },
457
+ ...(staged.hint ? { hint: staged.hint } : {}),
458
+ body: value,
459
+ };
460
+ }
461
+ return { ok: true, value };
444
462
  }
445
463
  return mapErrorResponse(response);
446
464
  }
@@ -489,11 +507,11 @@ async function mapErrorResponse(response) {
489
507
  body,
490
508
  };
491
509
  }
492
- function missingTokenFailure() {
510
+ function missingTokenFailure(env) {
493
511
  return {
494
512
  ok: false,
495
513
  kind: 'auth',
496
- message: 'no user token available: expected a user access JWT in ~/.config/yolo/token or the YOLO_API_TOKEN env var',
514
+ message: missingUserTokenMessage(env),
497
515
  };
498
516
  }
499
517
  function noFetchFailure() {
@@ -247,6 +247,18 @@ export function validateDeployConfig(value) {
247
247
  });
248
248
  }
249
249
  }
250
+ if (obj.crons !== undefined) {
251
+ if (!Array.isArray(obj.crons)) {
252
+ errors.push({ path: 'crons', message: `must be an array of cron strings, got ${describe(obj.crons)}` });
253
+ }
254
+ else {
255
+ obj.crons.forEach((cron, i) => {
256
+ if (typeof cron !== 'string' || cron.trim() === '') {
257
+ errors.push({ path: `crons[${i}]`, message: `must be a non-empty cron string, got ${describe(cron)}` });
258
+ }
259
+ });
260
+ }
261
+ }
250
262
  if (obj.bindings !== undefined) {
251
263
  if (!Array.isArray(obj.bindings)) {
252
264
  errors.push({ path: 'bindings', message: `must be an array, got ${describe(obj.bindings)}` });
@@ -274,7 +286,7 @@ export function validateDeployConfig(value) {
274
286
  // surfaced as warnings so a silently-ignored field doesn't mislead the author.
275
287
  // `bindings[]` entries intentionally allow extra keys (provisioning hints), so
276
288
  // they're excluded here.
277
- const KNOWN_TOP_KEYS = new Set(['$version', 'projectId', 'slug', 'type', 'build', 'worker', 'compatibilityFlags', 'bindings']);
289
+ const KNOWN_TOP_KEYS = new Set(['$version', 'projectId', 'slug', 'type', 'build', 'worker', 'compatibilityFlags', 'crons', 'bindings']);
278
290
  const KNOWN_BUILD_KEYS = new Set(['command', 'outputDir']);
279
291
  const KNOWN_WORKER_KEYS = new Set(['entry', 'prebuilt', 'assetsDir']);
280
292
  function collectUnknownKeyWarnings(obj) {
@@ -335,6 +347,8 @@ function canonicalize(config) {
335
347
  }
336
348
  if (config.compatibilityFlags !== undefined)
337
349
  out.compatibilityFlags = [...config.compatibilityFlags];
350
+ if (config.crons !== undefined)
351
+ out.crons = [...config.crons];
338
352
  if (config.bindings !== undefined) {
339
353
  out.bindings = config.bindings.map((b) => {
340
354
  const entry = { kind: b.kind, binding: b.binding };
@@ -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 { isRuntimeManifest, isPersonalManifest, lintManifest } 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';
@@ -110,12 +110,9 @@ export function runTileAppValidate(opts) {
110
110
  const read = readManifestFile(opts.manifestPath);
111
111
  if (!read.ok)
112
112
  return { ok: false, kind: 'io', message: read.message };
113
- // A runtime personal app publishes an OCI archive and gets no R2 bundle, so
114
- // only a PURE-UI personal manifest may use the `media/<file>` ref form.
115
- const v = validateManifest(read.manifest, {
116
- allowPlatformHostedScreenshots: !!opts.personal && !isRuntimeManifest(read.manifest),
117
- });
118
- const errors = [...v.errors, ...publishGateErrors(read.manifest)];
113
+ const inferred = opts.personal === undefined;
114
+ const personal = opts.personal ?? isPersonalManifest(read.manifest);
115
+ const errors = lintManifest(read.manifest, { personal });
119
116
  // A non-object manifest is fully reported by validateManifest; bail before the
120
117
  // bundle/runtime checks (which deref manifest fields) so we never crash on it.
121
118
  const manifestIsObject = typeof read.manifest === 'object' && read.manifest !== null && !Array.isArray(read.manifest);
@@ -136,13 +133,17 @@ export function runTileAppValidate(opts) {
136
133
  bundleNote = '\n runtime app — surface served from its container image (no local bundle checked)';
137
134
  }
138
135
  if (errors.length > 0) {
139
- return { ok: false, kind: 'validation', message: `manifest invalid (${errors.length} issue${errors.length === 1 ? '' : 's'}):\n - ${errors.join('\n - ')}` };
136
+ const rules = personal ? 'personal-app rules' : 'marketplace rules';
137
+ return { ok: false, kind: 'validation', message: `manifest invalid under the ${rules} (${errors.length} issue${errors.length === 1 ? '' : 's'}):\n - ${errors.join('\n - ')}` };
140
138
  }
141
139
  const id = String(read.manifest.id);
142
140
  const version = String(read.manifest.version);
141
+ const modeNote = personal
142
+ ? `\n rules: personal app${inferred ? ' (no marketplace `publisher`; pass --marketplace for the marketplace rules)' : ''} — publish with: yolo tileapp publish ${opts.manifestPath} --personal`
143
+ : `\n rules: marketplace${inferred ? ` (publisher '${String(read.manifest.publisher)}'; pass --personal for a personal app)` : ''}`;
143
144
  return {
144
145
  ok: true,
145
- output: `OK: ${id}@${version} is valid.${bundleNote}\n note: mcp-scope + secret-key NAMES are confirmed server-side at publish.`,
146
+ output: `OK: ${id}@${version} is valid.${bundleNote}${modeNote}\n note: mcp-scope + secret-key NAMES are confirmed server-side at publish.`,
146
147
  };
147
148
  }
148
149
  /**
@@ -194,7 +195,7 @@ export async function runTileAppDev(opts) {
194
195
  // Block on schema AND publish-gate errors before serving — `dev` claims to
195
196
  // validate before serving, so it must reject anything publish would (e.g. an
196
197
  // image-only manifest missing its pinned digest).
197
- const gateErrors = [...validateManifest(read.manifest).errors, ...publishGateErrors(read.manifest)];
198
+ const gateErrors = lintManifest(read.manifest, { personal: isPersonalManifest(read.manifest) });
198
199
  if (gateErrors.length) {
199
200
  process.stderr.write(`FAIL [validation]: manifest invalid:\n - ${gateErrors.join('\n - ')}\n`);
200
201
  return devExitCode('validation');