@yolo-labs/yolo-cli 0.45.1 → 0.46.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
@@ -43,13 +43,17 @@ yolo preview status
43
43
  yolo preview status <tile-id> --json
44
44
  yolo preview logs <tile-id> --tail 100
45
45
  yolo preview stop <tile-id>
46
+ yolo preview update <tile-id> --env API_MOCKS=1 --health-path /health
46
47
  ```
47
48
 
48
49
  Choose commands appropriate to your app; the example assumes its start script
49
50
  accepts `--hostname` and `--port`. Single-quote commands to preserve `$PORT` and
50
51
  `$HOST` for the service. It uses isolated checkouts, checks candidate health, and
51
52
  switches the tile's stable port only after a successful build and start. Failed
52
- updates keep the last working version. The required runtime must already be
53
+ updates keep the last working version, and `status` reports why a commit was
54
+ refused (health probe outcomes and the last output line). `update` changes the
55
+ command, env or health settings in place, keeping the tile and port, and rebuilds
56
+ the branch head once. The required runtime must already be
53
57
  installed; this service targets stateless HTTP apps, not database migrations.
54
58
 
55
59
  The session resolves the authoritative workspace. Preview operations use delegated
package/dist/cli.js CHANGED
@@ -64,6 +64,8 @@ function printHelp() {
64
64
  ' [--workspace <wsId>] Sanity-check the workspace bound to this session.',
65
65
  ' kanban models List the model ids a card can be pinned to, and whether each can run now.',
66
66
  ' [--json] [--workspace <wsId>] Raw JSON instead of the table; sanity-check the workspace.',
67
+ ' workspace set-repository <url> [opts] Point this workspace at a different repository: preview, then --confirm <snapshot>.',
68
+ ' [--default-branch B] [--auth https|ssh] [--keep-old-remote-as N | --drop-old-remote] [--json]',
67
69
  ' git doctor [opts] Diagnose why git (not gh) can\'t authenticate to github.com.',
68
70
  ' [--fix] Repair what is safe to (store file, helpers, remote URL), then re-check.',
69
71
  ' [--offline] [--remote <name>] [--json] Skip network checks; remote to probe (default: origin); JSON output.',
@@ -750,6 +752,10 @@ async function main(argv) {
750
752
  const { runKanbanCmd } = await import('./kanban-cli.js');
751
753
  return runKanbanCmd(args.slice(1));
752
754
  }
755
+ if (cmd === 'workspace') {
756
+ const { runWorkspaceCmd } = await import('./workspace-cli.js');
757
+ return runWorkspaceCmd(args.slice(1));
758
+ }
753
759
  if (cmd === 'mcp') {
754
760
  const sub = args[1];
755
761
  if (sub === 'scopes')
@@ -6,7 +6,10 @@
6
6
  * wrapper) re-reads ~/.yolo-env on every call, so it always holds the current
7
7
  * token. git asks its credential helpers: `store` (~/.git-credentials), then
8
8
  * the github.com-scoped `gh auth git-credential` fallback from setup-git.sh.
9
- * When the two disagree, `gh` works and `git push` fails with "could not read
9
+ * That fallback must name the wrapper by absolute path: the real /usr/bin/gh
10
+ * answers from its own GH_TOKEN, which is stale in a long-lived shell, and
11
+ * `gh auth setup-git` writes exactly that path, plus a '' reset that hides
12
+ * `store` for github.com. When the two disagree, `gh` works and `git push` fails with "could not read
10
13
  * Username" — which is what a root exec leaving ~/.git-credentials root-owned
11
14
  * 0600 looked like (the lane-gc probe, until #1181). This command looks at
12
15
  * every link in git's chain and says which one is broken.
@@ -20,7 +23,8 @@
20
23
  * - rewrites ~/.git-credentials from the current token by temp file + rename
21
24
  * (a rename replaces a file we cannot write through; we own the directory),
22
25
  * keeping readable non-github lines, or the forge line from the pod env
23
- * - sets `credential.helper store` / the github.com gh fallback if missing
26
+ * - sets `credential.helper store` if missing, and points the github.com gh
27
+ * fallback at the wrapper (dropping a '' reset and real-binary values)
24
28
  * - strips credentials embedded in a github.com remote URL
25
29
  * It only writes a token GitHub accepted in this run, and never while the
26
30
  * Auth V2 purge fence is up: that fence means GitHub access was withdrawn, and
@@ -43,8 +47,10 @@ Diagnose why git (not gh) can't authenticate to github.com over HTTPS.
43
47
  --remote <name> Remote to inspect and probe (default: origin).
44
48
  --json Print {checks, fixed} as JSON.
45
49
  `;
50
+ export const GH_WRAPPER = '/usr/local/bin/gh';
46
51
  const GH_FALLBACK_KEY = 'credential.https://github.com.helper';
47
- const GH_FALLBACK_VALUE = '!gh auth git-credential';
52
+ const BARE_GH_VALUE = '!gh auth git-credential';
53
+ const GH_HELPER = /^!(\S+) auth git-credential$/;
48
54
  const GITHUB_LINE = /^https:\/\/[^:@/\s]+:([^@\s]+)@github\.com\/?$/;
49
55
  /** prefix…last4, so two tokens can be told apart without either being shown. */
50
56
  export function maskToken(token) {
@@ -96,16 +102,26 @@ function defaultGit(cwd, env) {
96
102
  return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? (r.error ? String(r.error.message) : '') };
97
103
  };
98
104
  }
99
- function defaultHasCommand(env) {
100
- return (name) => (env.PATH ?? '').split(':').some((dir) => {
101
- try {
102
- fs.accessSync(path.join(dir, name), fs.constants.X_OK);
103
- return true;
104
- }
105
- catch {
106
- return false;
107
- }
108
- });
105
+ function isExecutable(file) {
106
+ try {
107
+ fs.accessSync(file, fs.constants.X_OK);
108
+ return fs.statSync(file).isFile();
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
114
+ function defaultWhich(env) {
115
+ return (name) => (env.PATH ?? '').split(':').filter(Boolean)
116
+ .map((dir) => path.join(dir, name)).find(isExecutable);
117
+ }
118
+ function sameFile(a, b) {
119
+ try {
120
+ return fs.realpathSync(a) === fs.realpathSync(b);
121
+ }
122
+ catch {
123
+ return a === b;
124
+ }
109
125
  }
110
126
  function getAll(git, args) {
111
127
  const r = git(['config', ...args]);
@@ -218,16 +234,56 @@ function checkHelpers(ctx, d) {
218
234
  if (status === 'ok')
219
235
  status = 'warn';
220
236
  }
221
- if (!fallback.includes(GH_FALLBACK_VALUE)) {
222
- if (ctx.hasCommand('gh')) {
223
- problems.push(`no github.com gh fallback (${GH_FALLBACK_KEY})`);
224
- d.needFallback = true;
237
+ // The wrapper by absolute path; a bare `gh` only where no wrapper is installed.
238
+ const wrapperInstalled = isExecutable(ctx.ghWrapper);
239
+ const want = wrapperInstalled ? `!${ctx.ghWrapper} auth git-credential` : ctx.which('gh') ? BARE_GH_VALUE : undefined;
240
+ const ghValues = fallback.filter((v) => v === '' || GH_HELPER.test(v));
241
+ const fallbackProblems = [];
242
+ let fallbackStatus = 'ok';
243
+ if (!want) {
244
+ if (!ghValues.some((v) => v !== ''))
245
+ fallbackProblems.push('no github.com gh fallback, and gh is not on PATH');
246
+ }
247
+ else if (ghValues.length === 0) {
248
+ fallbackProblems.push(`no github.com gh fallback (${GH_FALLBACK_KEY})`);
249
+ }
250
+ for (const v of new Set(ghValues)) {
251
+ if (v === '') {
252
+ fallbackProblems.push(`${GH_FALLBACK_KEY} has a '' reset (left by \`gh auth setup-git\`): git skips the store helper for github.com`);
253
+ fallbackStatus = 'fail';
254
+ continue;
255
+ }
256
+ if (!want || v === want)
257
+ continue;
258
+ const bin = GH_HELPER.exec(v)[1];
259
+ if (bin.includes('/')) {
260
+ fallbackProblems.push(`'${v}' bypasses the token-refreshing wrapper ${ctx.ghWrapper}: it answers from a stale GH_TOKEN`);
261
+ fallbackStatus = 'fail';
225
262
  }
226
263
  else {
227
- problems.push('no github.com gh fallback, and gh is not on PATH');
264
+ const resolved = ctx.which(bin);
265
+ if (resolved && sameFile(resolved, ctx.ghWrapper)) {
266
+ fallbackProblems.push(`'${v}' depends on PATH (the wrapper here, the real gh where git's PATH differs)`);
267
+ if (fallbackStatus === 'ok')
268
+ fallbackStatus = 'warn';
269
+ }
270
+ else {
271
+ fallbackProblems.push(`'${v}' resolves to ${resolved ?? 'nothing'}, not the token-refreshing wrapper ${ctx.ghWrapper}`);
272
+ fallbackStatus = 'fail';
273
+ }
228
274
  }
229
- if (status === 'ok')
230
- status = 'warn';
275
+ }
276
+ if (want && ghValues.filter((v) => v === want).length > 1) {
277
+ fallbackProblems.push(`${GH_FALLBACK_KEY} lists '${want}' more than once`);
278
+ }
279
+ if (fallbackProblems.length) {
280
+ problems.push(...fallbackProblems);
281
+ if (fallbackStatus === 'ok')
282
+ fallbackStatus = 'warn';
283
+ if (status !== 'fail')
284
+ status = fallbackStatus;
285
+ if (want)
286
+ d.needFallback = want;
231
287
  }
232
288
  if (d.inRepo) {
233
289
  const local = getAll(ctx.git, ['--local', '--get-all', 'credential.helper']);
@@ -238,7 +294,7 @@ function checkHelpers(ctx, d) {
238
294
  }
239
295
  }
240
296
  d.checks.push({ id: 'helper', status, detail: problems.length ? problems.join('; ')
241
- : `store, then ${GH_FALLBACK_VALUE} for github.com` });
297
+ : `store, then ${want ?? 'no gh fallback'} for github.com` });
242
298
  }
243
299
  function checkRemote(ctx, d) {
244
300
  if (!d.inRepo) {
@@ -287,7 +343,7 @@ function checkLsRemote(ctx, d) {
287
343
  }
288
344
  async function diagnose(ctx) {
289
345
  const inRepo = ctx.git(['rev-parse', '--is-inside-work-tree']).stdout.trim() === 'true';
290
- const d = { checks: [], inRepo, credsNeedRewrite: false, needStoreHelper: false, needFallback: false };
346
+ const d = { checks: [], inRepo, credsNeedRewrite: false, needStoreHelper: false };
291
347
  const token = await checkToken(ctx, d);
292
348
  checkCredentialsFile(ctx, d, token);
293
349
  checkHelpers(ctx, d);
@@ -356,8 +412,13 @@ function applyFixes(ctx, d) {
356
412
  : `credential.helper: git config failed (${r.stderr.trim()})`);
357
413
  }
358
414
  if (d.needFallback) {
359
- const r = ctx.git(['config', '--global', GH_FALLBACK_KEY, GH_FALLBACK_VALUE]);
360
- (r.status === 0 ? fixed : refused).push(r.status === 0 ? `set ${GH_FALLBACK_KEY} '${GH_FALLBACK_VALUE}'`
415
+ // Drop every gh-shaped value and '' reset, then add exactly one; a helper the
416
+ // user put on this key for something else stays. Exit 5 = nothing to unset.
417
+ const unset = ctx.git(['config', '--global', '--unset-all', GH_FALLBACK_KEY, '^$|auth git-credential$']);
418
+ const r = unset.status === 0 || unset.status === 5
419
+ ? ctx.git(['config', '--global', '--add', GH_FALLBACK_KEY, d.needFallback])
420
+ : unset;
421
+ (r.status === 0 ? fixed : refused).push(r.status === 0 ? `set ${GH_FALLBACK_KEY} '${d.needFallback}'`
361
422
  : `${GH_FALLBACK_KEY}: git config failed (${r.stderr.trim()})`);
362
423
  }
363
424
  if (d.embeddedUrl) {
@@ -402,7 +463,8 @@ export async function runGitDoctor(opts, deps = {}) {
402
463
  git: deps.git ?? defaultGit(cwd, { ...env, HOME: home }),
403
464
  fetchImpl: deps.fetchImpl ?? globalThis.fetch,
404
465
  getuid: deps.getuid ?? (() => process.getuid?.() ?? -1),
405
- hasCommand: deps.hasCommand ?? defaultHasCommand(env),
466
+ which: deps.which ?? defaultWhich(env),
467
+ ghWrapper: deps.ghWrapper ?? GH_WRAPPER,
406
468
  opts,
407
469
  };
408
470
  let d = await diagnose(ctx);
package/dist/preview.js CHANGED
@@ -6,6 +6,7 @@ export const PREVIEW_HELP = `Usage:
6
6
  yolo preview status [tile-id] [--json]
7
7
  yolo preview logs <tile-id> [--tail 50] [--json]
8
8
  yolo preview stop <tile-id> [--json]
9
+ yolo preview update <tile-id> [--env KEY=VALUE ...] [--unset-env KEY ...] [options]
9
10
 
10
11
  Create options:
11
12
  --cwd <dir> Repository-relative app directory (default: .)
@@ -22,16 +23,30 @@ Create options:
22
23
  --desktop <id> Destination desktop
23
24
  --json Print structured output
24
25
 
26
+ Update options (same tile and port; rebuilds the branch head once and
27
+ forgets the failed commit):
28
+ --env KEY=VALUE Set an environment variable (repeatable)
29
+ --unset-env KEY Remove an environment variable (repeatable)
30
+ --command <command> Server start command
31
+ --setup <command> Setup command
32
+ --build <command> Build command
33
+ --health-path <path> Readiness endpoint
34
+ --ready-seconds <n> Server readiness timeout, 1..300
35
+ --timeout-seconds <n> Setup/build timeout, 1..1800
36
+
25
37
  Run inside a Studio workspace. Quote commands so $PORT and $HOST reach the
26
38
  managed server unchanged. Stop keeps the tile and prevents automatic restart.
27
39
  `;
28
40
  function parse(args) {
29
41
  const action = args[0];
30
- if (!['create', 'status', 'logs', 'stop'].includes(action || ''))
31
- throw new Error('Choose create, status, logs, or stop');
42
+ if (!['create', 'status', 'logs', 'stop', 'update'].includes(action || ''))
43
+ throw new Error('Choose create, status, logs, stop, or update');
32
44
  const values = {};
45
+ const env = {};
46
+ const unsetEnv = [];
33
47
  let id, json = false;
34
- const allowed = action === 'create' ? ['name', 'branch', 'command', 'cwd', 'setup', 'build', 'health-path', 'port', 'poll-seconds', 'timeout-seconds', 'ready-seconds', 'wait-for', 'request-id', 'desktop'] : action === 'logs' ? ['tail'] : [];
48
+ const allowed = action === 'create' ? ['name', 'branch', 'command', 'cwd', 'setup', 'build', 'health-path', 'port', 'poll-seconds', 'timeout-seconds', 'ready-seconds', 'wait-for', 'request-id', 'desktop'] : action === 'logs' ? ['tail']
49
+ : action === 'update' ? ['env', 'unset-env', 'command', 'setup', 'build', 'health-path', 'ready-seconds', 'timeout-seconds'] : [];
35
50
  for (let i = 1; i < args.length; i++) {
36
51
  const arg = args[i];
37
52
  if (arg === '--json') {
@@ -51,13 +66,27 @@ function parse(args) {
51
66
  if (values[key] !== undefined)
52
67
  throw new Error(`Repeated option: --${key}`);
53
68
  const value = match[2] ?? args[++i];
69
+ if (key === 'env') {
70
+ // `--env KEY=` sets an empty value; the name is checked here, the rest by the service.
71
+ const pair = value === undefined ? null : /^([A-Za-z_][A-Za-z0-9_]{0,127})=(.*)$/s.exec(value);
72
+ if (!pair)
73
+ throw new Error('--env requires KEY=VALUE');
74
+ env[pair[1]] = pair[2];
75
+ continue;
76
+ }
54
77
  if (!value || (match[2] === undefined && value.startsWith('--')))
55
78
  throw new Error(`--${key} requires a value`);
79
+ if (key === 'unset-env') {
80
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(value))
81
+ throw new Error('--unset-env requires a variable name');
82
+ unsetEnv.push(value);
83
+ continue;
84
+ }
56
85
  values[key] = value;
57
86
  }
58
87
  if (id && !/^[a-zA-Z0-9_-]{1,128}$/.test(id))
59
88
  throw new Error('Invalid preview tile ID');
60
- if ((action === 'logs' || action === 'stop') && !id)
89
+ if ((action === 'logs' || action === 'stop' || action === 'update') && !id)
61
90
  throw new Error(`${action} requires a preview tile ID`);
62
91
  const number = (key, min, max, fallback) => {
63
92
  const raw = values[key];
@@ -87,6 +116,21 @@ function parse(args) {
87
116
  timeoutSeconds: number('timeout-seconds', 1, 1800, 300), readySeconds: number('ready-seconds', 1, 300, 60),
88
117
  ...(waitFor && { waitFor }) } };
89
118
  }
119
+ if (action === 'update') {
120
+ const healthPath = values['health-path'];
121
+ if (healthPath !== undefined && (!healthPath.startsWith('/') || healthPath.startsWith('//')))
122
+ throw new Error('--health-path must start with a single /');
123
+ const body = {
124
+ ...(Object.keys(env).length && { env }), ...(unsetEnv.length && { unsetEnv }),
125
+ ...(values.command !== undefined && { command: values.command }), ...(values.setup !== undefined && { setup: values.setup }),
126
+ ...(values.build !== undefined && { build: values.build }), ...(healthPath !== undefined && { healthPath }),
127
+ ...(values['ready-seconds'] !== undefined && { readySeconds: number('ready-seconds', 1, 300, 60) }),
128
+ ...(values['timeout-seconds'] !== undefined && { timeoutSeconds: number('timeout-seconds', 1, 1800, 300) }),
129
+ };
130
+ if (!Object.keys(body).length)
131
+ throw new Error('update needs at least one change (e.g. --env KEY=VALUE)');
132
+ result.body = body;
133
+ }
90
134
  return result;
91
135
  }
92
136
  export async function runPreviewCmd(args, deps = {}) {
@@ -110,14 +154,14 @@ export async function runPreviewCmd(args, deps = {}) {
110
154
  return 78;
111
155
  }
112
156
  try {
113
- const scope = input.action === 'create' ? 'studio.create_preview' : input.action === 'stop' ? 'studio.stop_preview' : 'studio.read_preview';
157
+ const scope = input.action === 'create' || input.action === 'update' ? 'studio.create_preview' : input.action === 'stop' ? 'studio.stop_preview' : 'studio.read_preview';
114
158
  const token = await mintSubstrateToken({ ...auth.context, scopes: [scope], fetchImpl: deps.fetchImpl });
115
159
  const base = `${auth.context.commonApiUrl.replace(/\/+$/, '')}/internal/mcp/workspaces/${encodeURIComponent(token.workspaceId)}`;
116
160
  const route = input.action === 'create' ? '/tiles/preview' : input.action === 'status'
117
161
  ? `/previews${input.id ? `/${encodeURIComponent(input.id)}` : ''}`
118
162
  : `/previews/${encodeURIComponent(input.id)}/${input.action}${input.action === 'logs' ? `?tail=${input.tail}` : ''}`;
119
163
  const response = await (deps.fetchImpl ?? globalThis.fetch)(base + route, {
120
- method: input.action === 'create' || input.action === 'stop' ? 'POST' : 'GET',
164
+ method: input.action === 'status' || input.action === 'logs' ? 'GET' : 'POST',
121
165
  headers: { Authorization: `Bearer ${token.token}`, 'Content-Type': 'application/json' },
122
166
  ...(input.body && { body: JSON.stringify(input.body) }),
123
167
  });
@@ -130,11 +174,15 @@ export async function runPreviewCmd(args, deps = {}) {
130
174
  out(`Preview ${body.tile?.id || body.previewId} follows ${input.body.followBranch && input.body.followBranch.branch} on port ${body.preview?.port}.\nUse yolo preview status to check build progress.\n`);
131
175
  else if (input.action === 'stop')
132
176
  out(`Stopped preview ${input.id}. The tile is retained.\n`);
177
+ else if (input.action === 'update')
178
+ out(`Updated preview ${input.id} on port ${body.port}${body.version ? ` (config v${body.version})` : ''}; ${body.confirmed === false
179
+ ? 'saved; the workspace has not confirmed it yet and will be sent it again on the next status check.'
180
+ : 'rebuilding the branch head with the new configuration.'}\nUse yolo preview status ${input.id} to follow it.\n`);
133
181
  else if (input.action === 'logs')
134
182
  out((body.lines?.map((line) => line.text).join('') || '(no logs)') + '\n');
135
183
  else {
136
184
  const previews = body.previews || [body.preview];
137
- out(previews.length ? previews.map((p) => `${p.tileId}\t${p.name}\t${p.status}\t${p.branchStatus?.phase || '-'}\t${p.branch}\t:${p.port}\t${p.branchStatus?.servedCommit?.slice(0, 12) || '-'}${p.branchStatus?.error ? `\n ${p.branchStatus.error}` : ''}`).join('\n') + '\n' : 'No managed branch previews.\n');
185
+ out(previews.length ? previews.map((p) => `${p.tileId}\t${p.name}\t${p.status}\t${p.branchStatus?.phase || '-'}\t${p.branch}\t:${p.port}\t${p.branchStatus?.servedCommit?.slice(0, 12) || '-'}${p.update && p.update.state !== 'applied' ? `\n Config v${p.update.version} update ${p.update.state}${p.update.error ? `: ${p.update.error}` : ''}` : ''}${p.branchStatus?.error ? `\n ${p.branchStatus.error}\n See: yolo preview logs ${p.tileId}` : ''}`).join('\n') + '\n' : 'No managed branch previews.\n');
138
186
  }
139
187
  return 0;
140
188
  }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * `yolo workspace set-repository <url>` — point this workspace at a different
3
+ * repository. A thin client over `POST /v1/workspaces/:id/repository`
4
+ * (docs/plans/workspace-set-repository.md §7.2), the operator's own
5
+ * user-token route, so it mints no delegated token and needs no MCP scope.
6
+ *
7
+ * Two steps, like the MCP tool:
8
+ * - without `--confirm` it prints the preview and its snapshot; nothing changes;
9
+ * - `--confirm <snapshot>` applies, and is refused if anything moved since.
10
+ *
11
+ * Exit codes: 0 success (a preview with blockers included) · 1 http/refused · 64 usage/auth.
12
+ */
13
+ import { userRouteRequest } from './work-client.js';
14
+ import { resolveSubstrateContext } from './auth-context.js';
15
+ export const SET_REPOSITORY_USAGE = [
16
+ 'Usage: yolo workspace set-repository <url> [options]',
17
+ '',
18
+ ' --default-branch <b> Branch to check out (default: the new remote\'s HEAD). Alias: --branch',
19
+ ' --auth <https|ssh> Transport (default: keep the current one when the host supports it)',
20
+ ' --keep-old-remote-as <n> Name for the old origin remote (default: yolo-studio). Alias: --keep-old-as',
21
+ ' --drop-old-remote Remove the old origin instead of keeping it',
22
+ ' --confirm <snapshot> Apply the preview that returned this snapshot',
23
+ ' --json Print the raw response',
24
+ ' --workspace <wsId> Defaults to this session\'s workspace',
25
+ '',
26
+ 'Without --confirm nothing changes: the command prints what would happen and the snapshot to confirm.',
27
+ '',
28
+ ].join('\n');
29
+ const WORKSPACE_USAGE = [
30
+ 'Usage: yolo workspace <subcommand>',
31
+ '',
32
+ 'Subcommands:',
33
+ ' set-repository <url> Point this workspace at a different repository (preview, then --confirm)',
34
+ '',
35
+ ].join('\n');
36
+ export function parseSetRepositoryArgs(args) {
37
+ let url;
38
+ const out = { json: false };
39
+ let keep;
40
+ let drop = false;
41
+ for (let i = 0; i < args.length; i++) {
42
+ const raw = args[i];
43
+ const eq = raw.startsWith('--') ? raw.indexOf('=') : -1;
44
+ const flag = eq > 0 ? raw.slice(0, eq) : raw;
45
+ const value = () => {
46
+ const v = eq > 0 ? raw.slice(eq + 1) : args[++i];
47
+ if (!v || (eq < 0 && v.startsWith('--')))
48
+ throw new Error(`${flag} requires a value`);
49
+ return v;
50
+ };
51
+ try {
52
+ if (flag === '--default-branch' || flag === '--branch')
53
+ out.defaultBranch = value();
54
+ else if (flag === '--auth') {
55
+ const v = value();
56
+ if (v !== 'https' && v !== 'ssh')
57
+ return { ok: false, message: '--auth must be https or ssh' };
58
+ out.authMethod = v;
59
+ }
60
+ else if (flag === '--keep-old-remote-as' || flag === '--keep-old-as')
61
+ keep = value();
62
+ else if (flag === '--drop-old-remote')
63
+ drop = true;
64
+ else if (flag === '--confirm') {
65
+ const v = value();
66
+ if (!/^[a-f0-9]{64}$/.test(v))
67
+ return { ok: false, message: '--confirm takes the 64-character snapshot a preview printed' };
68
+ out.confirm = v;
69
+ }
70
+ else if (flag === '--json')
71
+ out.json = true;
72
+ else if (flag === '--workspace')
73
+ out.workspaceFlag = value();
74
+ else if (raw.startsWith('-'))
75
+ return { ok: false, message: `unknown option: ${raw}` };
76
+ else if (url === undefined)
77
+ url = raw;
78
+ else
79
+ return { ok: false, message: `unexpected positional argument: ${raw}` };
80
+ }
81
+ catch (error) {
82
+ return { ok: false, message: error.message };
83
+ }
84
+ }
85
+ if (!url)
86
+ return { ok: false, message: 'a repository <url> is required' };
87
+ if (keep !== undefined && drop)
88
+ return { ok: false, message: '--keep-old-remote-as and --drop-old-remote are mutually exclusive' };
89
+ return { ok: true, url, ...out, ...(drop ? { keepOldRemoteAs: null } : keep !== undefined ? { keepOldRemoteAs: keep } : {}) };
90
+ }
91
+ /** What an operator reads before confirming; `--json` prints the response as-is. */
92
+ export function formatSetRepository(body, url) {
93
+ if (body.error) {
94
+ const lines = [`Refused (${body.code ?? 'error'}): ${body.error}`];
95
+ for (const blocker of body.preview?.blockers ?? [])
96
+ lines.push(` ✗ ${blocker.code}: ${blocker.message}`);
97
+ return lines.join('\n');
98
+ }
99
+ const oldRemote = body.oldRemote?.dropped ? 'dropped' : `kept as '${body.oldRemote?.keptAs ?? 'yolo-studio'}'`;
100
+ const lines = [
101
+ `${body.applied ? 'Switched' : 'Would switch'}: ${body.from?.url ?? '(none)'} → ${body.to?.url ?? url}`,
102
+ ` default branch: ${body.to?.defaultBranch ?? '(unknown)'} transport: ${body.to?.authMethod ?? '?'} old remote: ${oldRemote}`,
103
+ ];
104
+ if (body.credential)
105
+ lines.push(` access: ${body.credential.method ?? 'none'} (${body.credential.probe ?? 'unchecked'})`);
106
+ const lanes = body.applied ? body.lanesFlagged ?? [] : (body.lanes ?? []).map((lane) => lane.name);
107
+ if (lanes.length)
108
+ lines.push(` lanes staying on the previous repository: ${lanes.join(', ')}`);
109
+ for (const blocker of body.blockers ?? [])
110
+ lines.push(` ✗ ${blocker.code}: ${blocker.message}`);
111
+ for (const warning of body.warnings ?? [])
112
+ lines.push(` ! ${warning}`);
113
+ if (body.restart?.required)
114
+ lines.push(` ↻ restart required (${body.restart.reason ?? 'credentials'})${body.restart.message ? `: ${body.restart.message}` : ''}`);
115
+ if (!body.applied) {
116
+ lines.push(body.blockers?.length
117
+ ? 'Blocked: resolve the items marked ✗, then preview again.'
118
+ : `To apply: yolo workspace set-repository ${url} --confirm ${body.snapshot}`);
119
+ }
120
+ return lines.join('\n');
121
+ }
122
+ export async function runSetRepository(args, deps = {}) {
123
+ const env = deps.env ?? process.env;
124
+ const auth = resolveSubstrateContext(env);
125
+ if (!auth.ok)
126
+ return { code: 64, stderr: `FAIL [auth]: ${auth.message}` };
127
+ const sessionWorkspace = env.WORKSPACE_ID?.trim() || undefined;
128
+ if (args.workspaceFlag && sessionWorkspace && args.workspaceFlag !== sessionWorkspace) {
129
+ return { code: 64, stderr: `FAIL [workspace_mismatch]: --workspace ${args.workspaceFlag} does not match this session's workspace (${sessionWorkspace}).` };
130
+ }
131
+ const workspaceId = args.workspaceFlag ?? sessionWorkspace;
132
+ if (!workspaceId)
133
+ return { code: 64, stderr: 'FAIL [usage]: no workspace: WORKSPACE_ID is unset — pass --workspace <workspaceId>' };
134
+ const body = {
135
+ url: args.url,
136
+ ...(args.defaultBranch ? { defaultBranch: args.defaultBranch } : {}),
137
+ ...(args.authMethod ? { authMethod: args.authMethod } : {}),
138
+ ...(args.keepOldRemoteAs !== undefined ? { keepOldRemoteAs: args.keepOldRemoteAs } : {}),
139
+ ...(args.confirm ? { expectedSnapshot: args.confirm } : {}),
140
+ };
141
+ let response;
142
+ try {
143
+ response = await userRouteRequest({ commonApiUrl: auth.context.commonApiUrl, userToken: auth.context.userToken, fetchImpl: deps.fetchImpl }, `/workspaces/${encodeURIComponent(workspaceId)}/repository`, { method: 'POST', jsonBody: body });
144
+ }
145
+ catch (err) {
146
+ return { code: 1, stderr: `FAIL [http]: workspace.set_repository failed: ${err instanceof Error ? err.message : String(err)}` };
147
+ }
148
+ const text = await response.text().catch(() => '');
149
+ let parsed = null;
150
+ try {
151
+ parsed = JSON.parse(text);
152
+ }
153
+ catch { /* reported raw below */ }
154
+ if (args.json)
155
+ return { code: response.ok ? 0 : 1, stdout: text };
156
+ if (!parsed)
157
+ return { code: 1, stderr: `FAIL [http]: HTTP ${response.status} — ${text}` };
158
+ return response.ok ? { code: 0, stdout: formatSetRepository(parsed, args.url) } : { code: 1, stderr: formatSetRepository(parsed, args.url) };
159
+ }
160
+ /** `args` is everything after `workspace`. */
161
+ export async function runWorkspaceCmd(args, deps = {}) {
162
+ const sub = args[0];
163
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') {
164
+ process.stdout.write(WORKSPACE_USAGE);
165
+ return sub ? 0 : 64;
166
+ }
167
+ if (sub !== 'set-repository') {
168
+ process.stderr.write(`yolo: unknown workspace subcommand '${sub}'\n${WORKSPACE_USAGE}`);
169
+ return 64;
170
+ }
171
+ if (args.slice(1).some((a) => a === '--help' || a === '-h')) {
172
+ process.stdout.write(SET_REPOSITORY_USAGE);
173
+ return 0;
174
+ }
175
+ const parsed = parseSetRepositoryArgs(args.slice(1));
176
+ if (!parsed.ok) {
177
+ process.stderr.write(`yolo: workspace set-repository: ${parsed.message}\n${SET_REPOSITORY_USAGE}`);
178
+ return 64;
179
+ }
180
+ const result = await runSetRepository(parsed, deps);
181
+ if (result.stdout)
182
+ process.stdout.write(`${result.stdout}\n`);
183
+ if (result.stderr)
184
+ process.stderr.write(`${result.stderr}\n`);
185
+ return result.code;
186
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolo-labs/yolo-cli",
3
- "version": "0.45.1",
3
+ "version": "0.46.0",
4
4
  "description": "YOLO Studio CLI for workspace context, artifacts, personal apps and hosting.",
5
5
  "license": "MIT",
6
6
  "repository": {