@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.
package/README.md CHANGED
@@ -10,8 +10,9 @@ yolo tileapp init my-app
10
10
  yolo deploy --dry-run
11
11
  ```
12
12
 
13
- Authenticated commands require `SESSION_ID`, `YOLO_COMMON_API_URL` (or
14
- `YOLO_API_URL`), and a user access JWT. The CLI reads the rotated token at
13
+ Authenticated commands require `SESSION_ID` and a user access JWT. The API
14
+ origin comes from `YOLO_COMMON_API_URL`, then `YOLO_API_URL`; with neither set
15
+ it defaults to production (`https://api.yolo.studio`). The CLI reads the rotated token at
15
16
  `~/.config/yolo/token`, falling back to `YOLO_API_TOKEN`. The session record
16
17
  supplies the workspace identity.
17
18
 
@@ -20,6 +21,20 @@ Artifact commands mint a scoped delegated token through
20
21
  Offline commands such as app scaffolding, validation, and local serving do not
21
22
  require authentication.
22
23
 
24
+ **Non-production APIs.** The token file and `YOLO_API_TOKEN` are the sandbox's
25
+ own credential, so when the API URL is not production (`https://api.yolo.studio`)
26
+ the CLI does not use them by default. Set `YOLO_API_TOKEN_NONPROD` to a token for
27
+ that API, or `YOLO_API_TOKEN_FILE` to a file holding one. Without either, commands
28
+ fail and say so. A sandbox provisioned for that same API (its `/run/yolo/env`
29
+ names it) still uses its rotated token file. On a non-production API,
30
+ `yolo deploy init` and `yolo deploy link` also do not use `$WORKSPACE_ID`, so a
31
+ server-side workspace association needs an explicit `--workspace-id`.
32
+
33
+ Worker ships always send `crons` (`[]` when none are declared). The server
34
+ refuses a Worker that defines `scheduled()` from a client that omits the field
35
+ (`cron-client-outdated`). CLIs older than 1.1.0 cannot read wrangler
36
+ `triggers.crons` and would ship without them.
37
+
23
38
  Build and test locally:
24
39
 
25
40
  ```sh
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Which YOLO environment the CLI is talking to, and which credential it may
3
+ * use there.
4
+ *
5
+ * A Studio sandbox carries ONE credential: the pod's own user JWT, in
6
+ * `~/.config/yolo/token` (rotated) and `$YOLO_API_TOKEN`. In a production pod
7
+ * that is a production token. Pointing the CLI at another API
8
+ * (`YOLO_API_URL=https://api-staging.yolo.studio yolo deploy ...`) used to send
9
+ * that production token to the other host, and `yolo deploy link`/`init` used
10
+ * to stamp the production `$WORKSPACE_ID` onto a project there.
11
+ *
12
+ * The rule, for any API that is not production:
13
+ * - `$YOLO_API_TOKEN` is never used.
14
+ * - The token comes from `$YOLO_API_TOKEN_NONPROD`, or from the file named by
15
+ * `$YOLO_API_TOKEN_FILE`.
16
+ * - The default token file `~/.config/yolo/token` is used only when the pod
17
+ * itself was provisioned for that same API (its env file `$YOLO_ENV_FILE`,
18
+ * default `/run/yolo/env`, records that `YOLO_API_URL`). That is the case
19
+ * in a staging sandbox, whose rotated token IS a staging token. A prod pod
20
+ * pointed at staging falls through to a clear failure instead.
21
+ * - `$WORKSPACE_ID` is never defaulted onto a server-side project.
22
+ *
23
+ * Production behaviour is unchanged.
24
+ */
25
+ import { DEFAULT_YOLO_API_URL, resolveCommonApiUrl } from './api-url.js';
26
+ export const PRODUCTION_API_URL = DEFAULT_YOLO_API_URL;
27
+ /** The env var holding an explicit token for a non-production API. */
28
+ export const NONPROD_TOKEN_ENV = 'YOLO_API_TOKEN_NONPROD';
29
+ /** The env var naming a token file to use for a non-production API. */
30
+ export const NONPROD_TOKEN_FILE_ENV = 'YOLO_API_TOKEN_FILE';
31
+ /** The pod's env-profile file, which records the API it was provisioned for. */
32
+ export const DEFAULT_POD_ENV_FILE = '/run/yolo/env';
33
+ /**
34
+ * The API the CLI will call: `YOLO_COMMON_API_URL`, then `YOLO_API_URL`, then
35
+ * production when neither is set (api-url.ts, the CLI's single URL resolver).
36
+ */
37
+ export function targetApiUrl(env) {
38
+ return resolveCommonApiUrl(env);
39
+ }
40
+ function originOf(url) {
41
+ try {
42
+ return new URL(url.trim()).origin.toLowerCase();
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ /** True only for the production API origin. Anything unparseable is NOT production. */
49
+ export function isProductionApiUrl(url) {
50
+ return originOf(url) === PRODUCTION_API_URL;
51
+ }
52
+ export function isProductionTarget(env) {
53
+ return isProductionApiUrl(targetApiUrl(env));
54
+ }
55
+ /** Same origin, both parseable. */
56
+ export function sameApiOrigin(a, b) {
57
+ const oa = originOf(a);
58
+ return oa !== undefined && oa === originOf(b);
59
+ }
60
+ /**
61
+ * The `YOLO_API_URL` the pod was provisioned with, read from its env-profile
62
+ * file (lines like `export YOLO_API_URL='https://...'`). Undefined outside a
63
+ * pod or when the file does not say.
64
+ */
65
+ export function podProvisionedApiUrl(env, readFileImpl) {
66
+ const text = readFileImpl(env.YOLO_ENV_FILE || DEFAULT_POD_ENV_FILE);
67
+ if (!text)
68
+ return undefined;
69
+ let found;
70
+ for (const line of text.split('\n')) {
71
+ const m = /^\s*(?:export\s+)?(YOLO_COMMON_API_URL|YOLO_API_URL)=(.*)$/.exec(line);
72
+ if (!m)
73
+ continue;
74
+ const value = m[2].trim().replace(/^(['"])(.*)\1$/, '$2').trim();
75
+ // YOLO_COMMON_API_URL outranks YOLO_API_URL, as it does in targetApiUrl.
76
+ if (value && (m[1] === 'YOLO_COMMON_API_URL' || found === undefined))
77
+ found = value;
78
+ if (value && m[1] === 'YOLO_COMMON_API_URL')
79
+ break;
80
+ }
81
+ return found;
82
+ }
83
+ /** The failure message when no usable token exists for a non-production API. */
84
+ export function nonProdTokenMessage(env) {
85
+ const url = targetApiUrl(env);
86
+ return (`no token for the non-production API ${url}: the sandbox credential (~/.config/yolo/token, $YOLO_API_TOKEN) ` +
87
+ `belongs to this pod's own environment and is never sent to another API. ` +
88
+ `Set ${NONPROD_TOKEN_ENV}=<token for ${url}> or ${NONPROD_TOKEN_FILE_ENV}=<path to a file holding it>, ` +
89
+ `or unset YOLO_API_URL / YOLO_COMMON_API_URL to use production.`);
90
+ }
91
+ /**
92
+ * Why the user token came back empty, in one sentence every command can print. For a non-production API
93
+ * it names the explicit token variables, since the sandbox credential is deliberately withheld there.
94
+ */
95
+ export function missingUserTokenMessage(env) {
96
+ if (!isProductionTarget(env))
97
+ return nonProdTokenMessage(env);
98
+ return 'no user token available: expected a user access JWT in ~/.config/yolo/token or the YOLO_API_TOKEN env var';
99
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The YOLO API origin every CLI command talks to.
3
+ *
4
+ * `YOLO_COMMON_API_URL` wins, then `YOLO_API_URL` (both set in a Studio session
5
+ * pod, staging or prod). When neither is set, the CLI talks to production
6
+ * instead of failing with "env var is required": a fresh shell outside a pod
7
+ * (or one whose env was not inherited) otherwise could not run anything.
8
+ *
9
+ * Only the URL defaults. The token and workspace are still resolved as before
10
+ * and are never guessed, so an unset URL cannot pair a staging credential with
11
+ * prod by itself. Which token a non-production URL may use is api-env.ts.
12
+ */
13
+ export const DEFAULT_YOLO_API_URL = 'https://api.yolo.studio';
14
+ export function resolveCommonApiUrl(env) {
15
+ return env.YOLO_COMMON_API_URL || env.YOLO_API_URL || DEFAULT_YOLO_API_URL;
16
+ }
@@ -14,34 +14,87 @@
14
14
  * problem: a long-lived shell holds whatever token was in scope at
15
15
  * its own launch, but the file is always fresh.
16
16
  * 2. `YOLO_API_TOKEN` env — the pod-injected user JWT (≤24h TTL).
17
+ * Both are the sandbox's own credential, so for a NON-production API neither is
18
+ * used by default (api-env.ts): `YOLO_API_TOKEN_NONPROD` or `YOLO_API_TOKEN_FILE`
19
+ * is required instead, unless the pod was provisioned for that API.
17
20
  *
18
21
  * Auth requires SESSION_ID + a common-api URL + a user access JWT.
19
22
  */
23
+ import { NONPROD_TOKEN_ENV, NONPROD_TOKEN_FILE_ENV, isProductionApiUrl, missingUserTokenMessage, podProvisionedApiUrl, sameApiOrigin, targetApiUrl, } from './api-env.js';
20
24
  import * as fs from 'node:fs';
21
25
  import * as os from 'node:os';
22
26
  import * as path from 'node:path';
23
- export function resolveSubstrateContext(env, readFileImpl = defaultReadFile) {
27
+ import { resolveCommonApiUrl } from './api-url.js';
28
+ /**
29
+ * Set by the worker-domain launcher (container-api `execution-domain-launcher.js`) to the execution's
30
+ * broker socket. Its presence can only take authority away from the CLI; its absence grants nothing.
31
+ */
32
+ export const EXECUTION_BROKER_SOCKET_ENV = 'YOLO_EXECUTION_BROKER_SOCKET';
33
+ /** The launcher also names the execution and its lane; either alone marks one as plainly as the socket does. */
34
+ export const EXECUTION_MARKER_ENVS = [EXECUTION_BROKER_SOCKET_ENV, 'YOLO_EXECUTION_ID', 'YOLO_EXECUTION_LANE'];
35
+ /**
36
+ * The uid every restricted worker container runs as (common-api `execution-domain-template.ts`,
37
+ * `EXECUTION_WORKER_UID`). It is fixed by the pod template, not by anything a process in that container can
38
+ * set or unset, and no interactive session or ordinary lane ever runs under it.
39
+ */
40
+ export const EXECUTION_WORKER_UID = 20001;
41
+ const processProbe = { uid: () => (typeof process.getuid === 'function' ? process.getuid() : undefined) };
42
+ /**
43
+ * Is this CLI running inside a restricted Runner execution?
44
+ *
45
+ * Yes when ANY marker the launcher sets is present — and also when none is, if the process runs as the
46
+ * worker container's uid. So an execution whose environment was scrubbed, or that starts the CLI with its
47
+ * own environment, is still an execution: dropping the markers does not turn it into an ordinary session.
48
+ * Every answer here can only take authority away; nothing about it grants any.
49
+ */
50
+ export function inRestrictedExecution(env, probe = processProbe) {
51
+ if (EXECUTION_MARKER_ENVS.some((name) => Boolean(env[name])))
52
+ return true;
53
+ return probe.uid() === EXECUTION_WORKER_UID;
54
+ }
55
+ /** Why the CLI holds no credential inside an execution. One message, so every command says the same thing. */
56
+ export const RESTRICTED_EXECUTION_MESSAGE = 'this is a restricted Runner execution: the substrate CLI has no credential here and does not use the workspace ' +
57
+ 'owner\'s. Studio tools are reached through the execution\'s own broker.';
58
+ export function resolveSubstrateContext(env, readFileImpl = defaultReadFile, probe = processProbe) {
24
59
  const sessionId = env.SESSION_ID;
25
- const commonApiUrl = env.YOLO_COMMON_API_URL || env.YOLO_API_URL;
60
+ // Defaults to production when neither URL env var is set (api-url.ts).
61
+ const commonApiUrl = resolveCommonApiUrl(env);
26
62
  if (!sessionId) {
27
63
  return { ok: false, message: 'SESSION_ID env var is required (substrate CLI is container-only in v1)' };
28
64
  }
29
- if (!commonApiUrl) {
30
- return { ok: false, message: 'YOLO_COMMON_API_URL (or YOLO_API_URL) env var is required' };
65
+ // Inside a restricted Runner execution (docs/RUNNER_EXECUTION_BOOTSTRAP_PROTOCOL.md) the CLI has no
66
+ // credential to offer and must not go looking for one: the workspace owner's token is not the
67
+ // execution's identity, wherever a copy of it might be found. Checked BEFORE the token file and the
68
+ // environment are read. This is not what keeps the token away from an execution — the worker domain
69
+ // holds no copy of it, with or without a marker — it only makes the CLI say so plainly instead of
70
+ // presenting whatever it finds.
71
+ if (inRestrictedExecution(env, probe)) {
72
+ return { ok: false, message: RESTRICTED_EXECUTION_MESSAGE };
31
73
  }
32
- const userToken = resolveUserToken(env, readFileImpl);
74
+ const userToken = resolveUserToken(env, readFileImpl, probe);
33
75
  if (!userToken) {
34
76
  return {
35
77
  ok: false,
36
- message: 'no user token available: expected a user access JWT in ~/.config/yolo/token or the YOLO_API_TOKEN env var. ' +
78
+ message: `${missingUserTokenMessage(env).replace(/\.$/, '')}. ` +
37
79
  'The substrate CLI is user-JWT-only — the INTERNAL_API_KEY fallback was removed.',
38
80
  };
39
81
  }
40
82
  return { ok: true, context: { sessionId, commonApiUrl, userToken } };
41
83
  }
42
- export function resolveUserToken(env, readFileImpl = defaultReadFile) {
84
+ /**
85
+ * The user token, or undefined. EVERY client that needs the owner's token comes through here — the
86
+ * substrate context above, `yolo context`, deploy, the tile-app publisher and workspace commands — so the
87
+ * execution check lives here as well: inside a restricted execution this returns undefined without reading
88
+ * the token file or `YOLO_API_TOKEN`, whichever command asked.
89
+ */
90
+ export function resolveUserToken(env, readFileImpl = defaultReadFile, probe = processProbe) {
91
+ if (inRestrictedExecution(env, probe))
92
+ return undefined;
43
93
  const home = env.HOME || os.homedir();
44
94
  const tokenFile = path.join(home, '.config', 'yolo', 'token');
95
+ const target = targetApiUrl(env);
96
+ if (!isProductionApiUrl(target))
97
+ return resolveNonProdToken(env, target, tokenFile, readFileImpl);
45
98
  const fromFile = readFileImpl(tokenFile);
46
99
  if (fromFile && fromFile.trim())
47
100
  return fromFile.trim();
@@ -50,6 +103,41 @@ export function resolveUserToken(env, readFileImpl = defaultReadFile) {
50
103
  return fromEnv.trim();
51
104
  return undefined;
52
105
  }
106
+ /**
107
+ * A non-production API never gets the sandbox credential by default (see api-env.ts): an explicit
108
+ * `YOLO_API_TOKEN_NONPROD`, then the file named by `YOLO_API_TOKEN_FILE`, then the rotated token file
109
+ * ONLY when this pod was provisioned for that same API. `$YOLO_API_TOKEN` is never read here.
110
+ */
111
+ function resolveNonProdToken(env, target, defaultTokenFile, readFileImpl) {
112
+ const explicit = env[NONPROD_TOKEN_ENV];
113
+ if (explicit && explicit.trim())
114
+ return explicit.trim();
115
+ const explicitFile = env[NONPROD_TOKEN_FILE_ENV];
116
+ if (explicitFile && explicitFile.trim()) {
117
+ const fromExplicitFile = readFileImpl(explicitFile.trim());
118
+ return fromExplicitFile && fromExplicitFile.trim() ? fromExplicitFile.trim() : undefined;
119
+ }
120
+ const podUrl = podProvisionedApiUrl(env, readFileImpl);
121
+ if (podUrl && !isProductionApiUrl(podUrl) && sameApiOrigin(podUrl, target)) {
122
+ const fromFile = readFileImpl(defaultTokenFile);
123
+ if (fromFile && fromFile.trim())
124
+ return fromFile.trim();
125
+ }
126
+ return undefined;
127
+ }
128
+ /**
129
+ * MOGUL-D040 P1 (docs/plans/d040-pod-scoped-token.md §4.2): `X-Yolo-Pod-Session`
130
+ * names this pod's workspace session so common-api can COUNT legacy (unclaimed)
131
+ * pod tokens per route. Telemetry only: the server never authorizes on it. Sent
132
+ * with the user token, and only when SESSION_ID is a 24-hex session id (the
133
+ * same header container-api's `user-token.js` sends).
134
+ */
135
+ export function podSessionTelemetryHeaders(env = process.env) {
136
+ const sid = typeof env.SESSION_ID === 'string' ? env.SESSION_ID.trim().toLowerCase() : '';
137
+ return /^[a-f0-9]{24}$/.test(sid) ? { 'X-Yolo-Pod-Session': sid } : {};
138
+ }
139
+ /** Re-exported so every token consumer can import the failure message alongside `resolveUserToken`. */
140
+ export { missingUserTokenMessage };
53
141
  export function defaultReadFile(filePath) {
54
142
  try {
55
143
  return fs.readFileSync(filePath, 'utf-8');
package/dist/cli.js CHANGED
@@ -88,7 +88,9 @@ function printHelp() {
88
88
  ' [--stdout] Print the signed manifest instead of rewriting the file.',
89
89
  ' tileapp publish <manifest> --personal Register a PERSONAL app (no signing/review). Pure-UI: uploads the',
90
90
  ' bundle. Runtime (manifest has `runtime`): builds the image in-pod',
91
- ' + mediated-push to your registry namespace.',
91
+ ' + mediated-push to your registry namespace. Worker (`runtime.kind:',
92
+ " 'worker'`): uploads the bundle incl. its _worker/ backend, no build.",
93
+ ' [--live] Worker: run the backend live on Dynamic Workers (owner only, in-progress).',
92
94
  ' [--bundle-dir <dir>] Pure-UI: override the static-bundle directory to upload.',
93
95
  ' [--context <dir>] [--dockerfile <f>] Runtime: build context + Dockerfile (default: the manifest dir).',
94
96
  ' [--builder auto|podman|skopeo] Runtime build engine. auto (default): skopeo assembler for RUN-less',
@@ -133,7 +135,7 @@ function tileAppUsage(sub, message) {
133
135
  const usage = {
134
136
  init: 'Usage: yolo tileapp init <name> (scaffolds ./<name>/tileapp.json + index.html)\n',
135
137
  sign: 'Usage: yolo tileapp sign <manifest.json> --publisher <id> [--key <keyId>] [--stdout]\n',
136
- publish: 'Usage: yolo tileapp publish <manifest.json> --personal [--bundle-dir <dir>] [--context <dir>] [--dockerfile <f>] [--builder auto|podman|skopeo] (personal app)\n'
138
+ publish: 'Usage: yolo tileapp publish <manifest.json> --personal [--bundle-dir <dir>] [--context <dir>] [--dockerfile <f>] [--builder auto|podman|skopeo] [--live] (personal app)\n'
137
139
  + ' or: yolo tileapp publish <manifest.json> [--channel beta|stable] [--image-digest <d>] (marketplace)\n',
138
140
  validate: 'Usage: yolo tileapp validate <manifest.json> [--bundle-dir <dir>] [--personal]\n',
139
141
  dev: 'Usage: yolo tileapp dev <manifest.json> [--port N] [--host H] [--bundle-dir <dir>] [--deny]\n',
@@ -336,11 +338,15 @@ async function runTileAppPublishCmd(args) {
336
338
  let dockerfile;
337
339
  let builder;
338
340
  let personal = false;
341
+ let live = false;
339
342
  for (let i = 0; i < args.length; i++) {
340
343
  const a = args[i];
341
344
  if (a === '--personal' || a === '--private') {
342
345
  personal = true;
343
346
  }
347
+ else if (a === '--live') {
348
+ live = true;
349
+ }
344
350
  else if (a === '--bundle-dir') {
345
351
  bundleDir = args[++i];
346
352
  if (bundleDir === undefined)
@@ -384,16 +390,21 @@ async function runTileAppPublishCmd(args) {
384
390
  // bundle (no signing/review). Distinct from the marketplace publish below.
385
391
  if (personal) {
386
392
  const { runTileAppPublishPersonal, exitCodeForFailure } = await import('./tileapp-personal.js');
387
- const result = await runTileAppPublishPersonal({ manifestPath, bundleDir, context, dockerfile, builder });
393
+ const result = await runTileAppPublishPersonal({ manifestPath, bundleDir, context, dockerfile, builder, live });
388
394
  if (result.ok) {
389
395
  process.stdout.write(`${result.output}\n`);
390
396
  return 0;
391
397
  }
398
+ // D040 P2: staged for the owner — PENDING on stdout, not a FAIL.
399
+ if (result.kind === 'awaiting-approval') {
400
+ process.stdout.write(`${result.message}\n`);
401
+ return exitCodeForFailure(result.kind);
402
+ }
392
403
  process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
393
404
  return exitCodeForFailure(result.kind);
394
405
  }
395
- if (bundleDir || context || dockerfile || builder)
396
- return tileAppUsage('publish', '--bundle-dir/--context/--dockerfile/--builder are only valid with --personal');
406
+ if (bundleDir || context || dockerfile || builder || live)
407
+ return tileAppUsage('publish', '--bundle-dir/--context/--dockerfile/--builder/--live are only valid with --personal');
397
408
  const result = await runTileAppPublish({ manifestPath, channel, imageDigest });
398
409
  if (result.ok) {
399
410
  process.stdout.write(`${result.output}\n`);
@@ -451,6 +462,10 @@ async function runTileAppMediaCmd(args) {
451
462
  process.stdout.write(`${result.output}\n`);
452
463
  return 0;
453
464
  }
465
+ if (result.kind === 'awaiting-approval') {
466
+ process.stdout.write(`${result.message}\n`);
467
+ return exitCodeForFailure(result.kind);
468
+ }
454
469
  process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
455
470
  return exitCodeForFailure(result.kind);
456
471
  }
package/dist/context.js CHANGED
@@ -16,6 +16,7 @@
16
16
  * consistently from the same source.
17
17
  */
18
18
  import { resolveUserToken } from './auth-context.js';
19
+ import { resolveCommonApiUrl } from './api-url.js';
19
20
  export class ContextResolutionError extends Error {
20
21
  exitCode;
21
22
  constructor(message, exitCode) {
@@ -29,10 +30,8 @@ export function readSessionContext() {
29
30
  if (!sessionId || sessionId.length === 0) {
30
31
  throw new ContextResolutionError('session-required: SESSION_ID env var is empty or missing. The substrate CLI requires a Studio container session; outside-container invocation is out of scope for v1.', 78);
31
32
  }
32
- const commonApiUrl = process.env.YOLO_COMMON_API_URL || process.env.YOLO_API_URL;
33
- if (!commonApiUrl || commonApiUrl.length === 0) {
34
- throw new ContextResolutionError('session-required: YOLO_COMMON_API_URL env var is empty or missing.', 78);
35
- }
33
+ // Defaults to production when neither URL env var is set (api-url.ts).
34
+ const commonApiUrl = resolveCommonApiUrl(process.env);
36
35
  const userToken = resolveUserToken(process.env);
37
36
  return {
38
37
  sessionId,
@@ -24,6 +24,7 @@
24
24
  * 0 ok / 64 usage / 78 env / 1 local / 2 backend-rejected / 3 pending / 4 network.
25
25
  */
26
26
  import * as path from 'node:path';
27
+ import { formatOwnerApprovalPending, ownerApprovalRequestedOf } from './pod-owner-approval.js';
27
28
  import { statSync } from 'node:fs';
28
29
  function defaultStatPath(p) {
29
30
  try {
@@ -41,6 +42,7 @@ import { adaptWrangler, detectProjectShape } from './deploy-detect.js';
41
42
  import { collectNodeBuiltinsFromText } from './deploy-bundle.js';
42
43
  import { runDeployDev } from './deploy-dev.js';
43
44
  import { defaultReadFile } from './auth-context.js';
45
+ import { isProductionTarget, targetApiUrl } from './api-env.js';
44
46
  const USAGE = [
45
47
  'Usage: yolo deploy [--env <staging|prod>] [--dry-run] [--json]',
46
48
  ' yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug> | --no-parent] [--json]',
@@ -431,7 +433,9 @@ async function runInitCmd(args, deps, io) {
431
433
  // lets server-side deploy lifecycle events route back to the workspace
432
434
  // (and therefore to VibeAssist event watchers). Local CLI use remains
433
435
  // unchanged because the field is optional.
434
- ...(env.WORKSPACE_ID ? { workspaceId: env.WORKSPACE_ID } : {}),
436
+ // Never on a non-production API: `$WORKSPACE_ID` names this pod's own
437
+ // (production) workspace, which means nothing on another server (api-env.ts).
438
+ ...(env.WORKSPACE_ID && isProductionTarget(env) ? { workspaceId: env.WORKSPACE_ID } : {}),
435
439
  // Nesting S4 — passed straight through; the server verifies ownership,
436
440
  // depth and parent state. Not written to `.yolo/deploy.json`.
437
441
  ...(resolvedParentId ? { parentProjectId: resolvedParentId } : {}),
@@ -679,7 +683,16 @@ async function runLinkCmd(args, deps, io) {
679
683
  })}\n`);
680
684
  return exitCodeForFailure('already-linked');
681
685
  }
682
- const workspaceId = parsed.unlinkWorkspace ? null : parsed.localOnly ? undefined : parsed.workspaceId ?? (deps.env ?? process.env).WORKSPACE_ID;
686
+ // `$WORKSPACE_ID` is this pod's own workspace, so it is the default only on the production API. On any
687
+ // other API (api-env.ts) the server association needs an explicit --workspace-id; without one, nothing
688
+ // is linked server-side.
689
+ const linkEnv = deps.env ?? process.env;
690
+ const defaultWorkspaceId = isProductionTarget(linkEnv) ? linkEnv.WORKSPACE_ID : undefined;
691
+ if (!defaultWorkspaceId && linkEnv.WORKSPACE_ID && !parsed.workspaceId && !parsed.localOnly && !parsed.unlinkWorkspace) {
692
+ io.err(`yolo deploy link: ${targetApiUrl(linkEnv)} is not the production API, so this pod's WORKSPACE_ID is not linked; ` +
693
+ 'pass --workspace-id <id> to associate a workspace on that server.\n');
694
+ }
695
+ const workspaceId = parsed.unlinkWorkspace ? null : parsed.localOnly ? undefined : parsed.workspaceId ?? defaultWorkspaceId;
683
696
  if (workspaceId !== undefined) {
684
697
  // Always read project.workspaceId, never the release-derived workspace.
685
698
  const read = deps.getProjectStatusImpl ?? getProjectStatus;
@@ -697,6 +710,12 @@ async function runLinkCmd(args, deps, io) {
697
710
  workspaceId, expectedWorkspaceId: snapshot.project.workspaceId ?? null,
698
711
  });
699
712
  if (!linked.ok) {
713
+ // D040 P2: from a pod, the re-link is staged for the owner (202), not performed.
714
+ const staged = linked.kind === 'awaiting-approval' && linked.body ? ownerApprovalRequestedOf(linked.status ?? 0, linked.body) : null;
715
+ if (staged) {
716
+ io.out(`${formatOwnerApprovalPending(staged, `linking project ${projectId} to workspace ${workspaceId ?? 'none'}`)}\n`);
717
+ return 3;
718
+ }
700
719
  io.err(`${formatFail(linked)}\n`);
701
720
  return exitCodeForFailure(linked.kind);
702
721
  }
@@ -833,7 +852,7 @@ async function runValidateCmd(args, deps, io) {
833
852
  // canonical format. Surface a NOTE so a present-but-unread toml isn't
834
853
  // silent (the retro gotcha: "wrangler.toml silently ignored").
835
854
  if ((readFileImpl ?? defaultReadFile)(path.join(cwd, 'wrangler.toml')) !== undefined) {
836
- notes.push('wrangler.toml found — YOLO Host reads only top-level `main` + `[assets].directory` from toml; ' +
855
+ notes.push('wrangler.toml found — YOLO Host reads only top-level `main` + `[assets].directory` (and `[triggers] crons` at ship time) from toml; ' +
837
856
  'run `yolo deploy init` to adapt it into `.yolo/deploy.json` (the canonical format)');
838
857
  }
839
858
  const ok = issues.length === 0;
@@ -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 };