@yolo-labs/yolo-cli 0.46.0 → 0.47.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/dist/cli.js +11 -0
- package/dist/deploy-cli.js +64 -4
- package/dist/deploy-client.js +4 -0
- package/dist/kanban-cli.js +4 -4
- package/dist/preview.js +24 -5
- package/dist/routing-cli.js +302 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -64,6 +64,13 @@ 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
|
+
' routing status Background Runner routing: on/off, Jev\'s state and why, policies.',
|
|
68
|
+
' routing on | off Turn routing on or off for cards admitted from now on.',
|
|
69
|
+
' routing decisions [--card <id>] Recorded routing decisions for a card, or the latest.',
|
|
70
|
+
' [--limit <n>] How many (1-200).',
|
|
71
|
+
' routing preview <cardId> Where routing would send a card now (read-only).',
|
|
72
|
+
' routing policy get|set|delete [opts] Runner/board policies; `yolo routing --help` for options.',
|
|
73
|
+
' [--json] [--workspace <wsId>] The API response as-is; sanity-check the workspace.',
|
|
67
74
|
' workspace set-repository <url> [opts] Point this workspace at a different repository: preview, then --confirm <snapshot>.',
|
|
68
75
|
' [--default-branch B] [--auth https|ssh] [--keep-old-remote-as N | --drop-old-remote] [--json]',
|
|
69
76
|
' git doctor [opts] Diagnose why git (not gh) can\'t authenticate to github.com.',
|
|
@@ -752,6 +759,10 @@ async function main(argv) {
|
|
|
752
759
|
const { runKanbanCmd } = await import('./kanban-cli.js');
|
|
753
760
|
return runKanbanCmd(args.slice(1));
|
|
754
761
|
}
|
|
762
|
+
if (cmd === 'routing') {
|
|
763
|
+
const { runRoutingCmd } = await import('./routing-cli.js');
|
|
764
|
+
return runRoutingCmd(args.slice(1));
|
|
765
|
+
}
|
|
755
766
|
if (cmd === 'workspace') {
|
|
756
767
|
const { runWorkspaceCmd } = await import('./workspace-cli.js');
|
|
757
768
|
return runWorkspaceCmd(args.slice(1));
|
package/dist/deploy-cli.js
CHANGED
|
@@ -35,7 +35,7 @@ function defaultStatPath(p) {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
import { runDeployShip, exitCodeForFailure, formatShipSuccess, formatPending, formatFail, } from './deploy-ship.js';
|
|
38
|
-
import { resolveDeployContext, createProject, getProjectStatus, listProjects, rollbackProject, unpublishProject, republishProject, renameProject, setProjectParent, addAlias, removeAlias, setRedirect, deleteProject, cloneProject, getLogs, pollTail, queryD1, } from './deploy-client.js';
|
|
38
|
+
import { resolveDeployContext, createProject, getProjectStatus, listProjects, rollbackProject, unpublishProject, republishProject, renameProject, setProjectParent, setProjectWorkspace, addAlias, removeAlias, setRedirect, deleteProject, cloneProject, getLogs, pollTail, queryD1, } from './deploy-client.js';
|
|
39
39
|
import { readDeployConfig, writeDeployConfig, findAncestorDeployLink as findAncestorLink, } from './deploy-config.js';
|
|
40
40
|
import { adaptWrangler, detectProjectShape } from './deploy-detect.js';
|
|
41
41
|
import { collectNodeBuiltinsFromText } from './deploy-bundle.js';
|
|
@@ -44,7 +44,7 @@ import { defaultReadFile } from './auth-context.js';
|
|
|
44
44
|
const USAGE = [
|
|
45
45
|
'Usage: yolo deploy [--env <staging|prod>] [--dry-run] [--json]',
|
|
46
46
|
' yolo deploy init [--slug <slug>] [--type <static|worker>] [--parent <id|slug> | --no-parent] [--json]',
|
|
47
|
-
' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>]',
|
|
47
|
+
' yolo deploy link (--project-id <id> | --slug <slug>) [--type <static|worker>] [--workspace-id <id> | --unlink-workspace | --local-only]',
|
|
48
48
|
' yolo deploy validate [--json]',
|
|
49
49
|
' yolo deploy doctor [--json]',
|
|
50
50
|
' yolo deploy dev [--port <n>] [--host <h>] [--var KEY=VALUE ...]',
|
|
@@ -331,6 +331,8 @@ async function runInitCmd(args, deps, io) {
|
|
|
331
331
|
io.out(parsed.jsonOutput
|
|
332
332
|
? `${formatJsonResult({ status: 'already-linked', projectId: existing.projectId, ...(existing.slug ? { slug: existing.slug } : {}) })}\n`
|
|
333
333
|
: `OK: already linked to project ${existing.projectId}${existing.slug ? ` (slug ${existing.slug})` : ''} — .yolo/deploy.json left unchanged\n`);
|
|
334
|
+
if (!parsed.jsonOutput)
|
|
335
|
+
io.out(`Local repository configuration only. To save the server workspace association, run 'yolo deploy link --project-id ${existing.projectId} --workspace-id <workspace-id>'.\n`);
|
|
334
336
|
return 0;
|
|
335
337
|
}
|
|
336
338
|
// Fresh init in a project that has a wrangler config but no .yolo/deploy.json:
|
|
@@ -535,12 +537,31 @@ async function runInitCmd(args, deps, io) {
|
|
|
535
537
|
}, `OK: linked project ${projectId}${slug ? ` (slug ${slug})` : ''} — wrote .yolo/deploy.json`);
|
|
536
538
|
}
|
|
537
539
|
export function parseLinkArgs(args) {
|
|
540
|
+
let workspaceId;
|
|
541
|
+
let localOnly = false;
|
|
542
|
+
let unlinkWorkspace = false;
|
|
538
543
|
let projectId;
|
|
539
544
|
let slug;
|
|
540
545
|
let type;
|
|
541
546
|
for (let i = 0; i < args.length; i++) {
|
|
542
547
|
const a = args[i];
|
|
543
|
-
if (a === '--
|
|
548
|
+
if (a === '--workspace-id') {
|
|
549
|
+
workspaceId = args[++i];
|
|
550
|
+
if (!workspaceId || !/^[a-f0-9]{24}$/i.test(workspaceId))
|
|
551
|
+
return { ok: false, message: '--workspace-id requires a 24-hex workspace id' };
|
|
552
|
+
}
|
|
553
|
+
else if (a.startsWith('--workspace-id=')) {
|
|
554
|
+
workspaceId = a.slice('--workspace-id='.length);
|
|
555
|
+
if (!/^[a-f0-9]{24}$/i.test(workspaceId))
|
|
556
|
+
return { ok: false, message: '--workspace-id requires a 24-hex workspace id' };
|
|
557
|
+
}
|
|
558
|
+
else if (a === '--unlink-workspace') {
|
|
559
|
+
unlinkWorkspace = true;
|
|
560
|
+
}
|
|
561
|
+
else if (a === '--local-only') {
|
|
562
|
+
localOnly = true;
|
|
563
|
+
}
|
|
564
|
+
else if (a === '--project-id') {
|
|
544
565
|
const v = args[++i];
|
|
545
566
|
if (!v || v.startsWith('--'))
|
|
546
567
|
return { ok: false, message: '--project-id requires a value' };
|
|
@@ -587,7 +608,11 @@ export function parseLinkArgs(args) {
|
|
|
587
608
|
// link metadata that disagrees with the project the id resolves to.
|
|
588
609
|
return { ok: false, message: 'pass either --project-id or --slug, not both (the project\'s slug is resolved server-side)' };
|
|
589
610
|
}
|
|
590
|
-
|
|
611
|
+
if ((workspaceId && unlinkWorkspace) || (localOnly && unlinkWorkspace))
|
|
612
|
+
return { ok: false, message: 'choose only one workspace association option' };
|
|
613
|
+
if (workspaceId && localOnly)
|
|
614
|
+
return { ok: false, message: '--workspace-id and --local-only cannot be combined' };
|
|
615
|
+
return { ok: true, projectId, slug, type, ...(workspaceId ? { workspaceId } : {}), ...(localOnly ? { localOnly } : {}), ...(unlinkWorkspace ? { unlinkWorkspace } : {}) };
|
|
591
616
|
}
|
|
592
617
|
async function runLinkCmd(args, deps, io) {
|
|
593
618
|
const parsed = parseLinkArgs(args);
|
|
@@ -654,6 +679,41 @@ async function runLinkCmd(args, deps, io) {
|
|
|
654
679
|
})}\n`);
|
|
655
680
|
return exitCodeForFailure('already-linked');
|
|
656
681
|
}
|
|
682
|
+
const workspaceId = parsed.unlinkWorkspace ? null : parsed.localOnly ? undefined : parsed.workspaceId ?? (deps.env ?? process.env).WORKSPACE_ID;
|
|
683
|
+
if (workspaceId !== undefined) {
|
|
684
|
+
// Always read project.workspaceId, never the release-derived workspace.
|
|
685
|
+
const read = deps.getProjectStatusImpl ?? getProjectStatus;
|
|
686
|
+
const before = await read(auth.context, projectId);
|
|
687
|
+
if (!before.ok) {
|
|
688
|
+
io.err(`${formatFail(before)}\n`);
|
|
689
|
+
return exitCodeForFailure(before.kind);
|
|
690
|
+
}
|
|
691
|
+
const snapshot = before.value;
|
|
692
|
+
if (!snapshot?.project || (snapshot.project.workspaceId !== null && typeof snapshot.project.workspaceId !== 'string')) {
|
|
693
|
+
io.err('FAIL [invalid-response]: server did not return a persisted workspace association\n');
|
|
694
|
+
return 2;
|
|
695
|
+
}
|
|
696
|
+
const linked = await (deps.setProjectWorkspaceImpl ?? setProjectWorkspace)(auth.context, projectId, {
|
|
697
|
+
workspaceId, expectedWorkspaceId: snapshot.project.workspaceId ?? null,
|
|
698
|
+
});
|
|
699
|
+
if (!linked.ok) {
|
|
700
|
+
io.err(`${formatFail(linked)}\n`);
|
|
701
|
+
return exitCodeForFailure(linked.kind);
|
|
702
|
+
}
|
|
703
|
+
const after = await read(auth.context, projectId);
|
|
704
|
+
if (!after.ok) {
|
|
705
|
+
io.err(`${formatFail(after)}\n`);
|
|
706
|
+
return exitCodeForFailure(after.kind);
|
|
707
|
+
}
|
|
708
|
+
if (after.value?.project?.workspaceId !== (workspaceId?.toLowerCase() ?? null)) {
|
|
709
|
+
io.err('FAIL [workspace-link-conflict]: server association could not be verified; refresh and retry\n');
|
|
710
|
+
return 2;
|
|
711
|
+
}
|
|
712
|
+
io.out(`OK: verified server workspace association ${workspaceId ?? 'none'}. Old standing grants are revoked on change; review new grants separately.\n`);
|
|
713
|
+
}
|
|
714
|
+
else {
|
|
715
|
+
io.out('Local repository configuration only; server workspace association unchanged. Use --workspace-id <id> to associate this project.\n');
|
|
716
|
+
}
|
|
657
717
|
if (existing?.projectId === projectId) {
|
|
658
718
|
// Already linked to this project. Still honor a requested --type that isn't
|
|
659
719
|
// already set (the deploy_create_project link block has no `type`, so the
|
package/dist/deploy-client.js
CHANGED
|
@@ -511,3 +511,7 @@ function enc(value) {
|
|
|
511
511
|
function stripTrailingSlash(url) {
|
|
512
512
|
return url.endsWith('/') ? url.slice(0, -1) : url;
|
|
513
513
|
}
|
|
514
|
+
/** Explicit persisted association, separate from .yolo/deploy.json. */
|
|
515
|
+
export async function setProjectWorkspace(ctx, projectId, request) {
|
|
516
|
+
return jsonLeg(ctx, `/deploy/projects/${enc(projectId)}/workspace`, { method: 'PUT', jsonBody: request });
|
|
517
|
+
}
|
package/dist/kanban-cli.js
CHANGED
|
@@ -41,7 +41,7 @@ export async function runKanbanExport(options) {
|
|
|
41
41
|
const env = options.env ?? process.env;
|
|
42
42
|
if (!options.tileId)
|
|
43
43
|
return fail('usage', 'a tileId is required');
|
|
44
|
-
const resolved =
|
|
44
|
+
const resolved = resolveKanbanContext(env, options.workspaceFlag);
|
|
45
45
|
if (!resolved.ok)
|
|
46
46
|
return resolved.failure;
|
|
47
47
|
const { commonApiUrl, userToken, workspaceId } = resolved;
|
|
@@ -101,7 +101,7 @@ export async function runKanbanImport(options) {
|
|
|
101
101
|
return fail('usage', 'a boardId is required');
|
|
102
102
|
if (!options.file)
|
|
103
103
|
return fail('usage', 'a seed document path is required');
|
|
104
|
-
const resolved =
|
|
104
|
+
const resolved = resolveKanbanContext(env, options.workspaceFlag);
|
|
105
105
|
if (!resolved.ok)
|
|
106
106
|
return resolved.failure;
|
|
107
107
|
const { commonApiUrl, userToken, workspaceId } = resolved;
|
|
@@ -155,7 +155,7 @@ export async function runKanbanImport(options) {
|
|
|
155
155
|
}
|
|
156
156
|
export async function runKanbanModels(options = {}) {
|
|
157
157
|
const env = options.env ?? process.env;
|
|
158
|
-
const resolved =
|
|
158
|
+
const resolved = resolveKanbanContext(env, options.workspaceFlag);
|
|
159
159
|
if (!resolved.ok)
|
|
160
160
|
return resolved.failure;
|
|
161
161
|
const { commonApiUrl, userToken, workspaceId } = resolved;
|
|
@@ -220,7 +220,7 @@ export function formatImportSummary(body, boardId) {
|
|
|
220
220
|
* already writes (which names both places a token can live) rather than a
|
|
221
221
|
* workspace complaint that would send an operator looking in the wrong place.
|
|
222
222
|
*/
|
|
223
|
-
function
|
|
223
|
+
export function resolveKanbanContext(env, workspaceFlag) {
|
|
224
224
|
const auth = resolveSubstrateContext(env);
|
|
225
225
|
if (!auth.ok)
|
|
226
226
|
return { ok: false, failure: fail('auth', auth.message) };
|
package/dist/preview.js
CHANGED
|
@@ -12,6 +12,11 @@ Create options:
|
|
|
12
12
|
--cwd <dir> Repository-relative app directory (default: .)
|
|
13
13
|
--setup <command> Install dependencies in each candidate checkout
|
|
14
14
|
--build <command> Build each candidate
|
|
15
|
+
--mode <production|dev> production: build each landed commit once (--build
|
|
16
|
+
required), then serve it with a production --command;
|
|
17
|
+
the start command gets NODE_ENV=production. Default:
|
|
18
|
+
run --command as given (dev servers compile on request
|
|
19
|
+
and can time out under load)
|
|
15
20
|
--health-path <path> Readiness endpoint (default: /)
|
|
16
21
|
--port <auto|number> Public preview port (default: auto)
|
|
17
22
|
--poll-seconds <n> Branch polling interval, 5..3600 (default: 30)
|
|
@@ -30,10 +35,19 @@ forgets the failed commit):
|
|
|
30
35
|
--command <command> Server start command
|
|
31
36
|
--setup <command> Setup command
|
|
32
37
|
--build <command> Build command
|
|
38
|
+
--mode <production|dev> Switch serving mode (production needs a build command)
|
|
33
39
|
--health-path <path> Readiness endpoint
|
|
34
40
|
--ready-seconds <n> Server readiness timeout, 1..300
|
|
35
41
|
--timeout-seconds <n> Setup/build timeout, 1..1800
|
|
36
42
|
|
|
43
|
+
Production starts (with --mode production; run setup such as npm ci first):
|
|
44
|
+
Next.js: --build 'npx next build' --command 'npx next start -p "$PORT" -H "$HOST"'
|
|
45
|
+
OpenNext: --build 'npx next build' --command 'npx next start -p "$PORT" -H "$HOST"'
|
|
46
|
+
(opennextjs-cloudflare targets Workers; preview the Next server)
|
|
47
|
+
vinext: --build 'npx vinext build' --command 'npx vinext start --port "$PORT" --hostname "$HOST"'
|
|
48
|
+
Vite SPA: --build 'npx vite build' --command 'npx vite preview --port "$PORT" --host "$HOST" --strictPort'
|
|
49
|
+
Static: --build 'npm run build' --command 'python3 -m http.server "$PORT" --bind "$HOST" -d dist'
|
|
50
|
+
|
|
37
51
|
Run inside a Studio workspace. Quote commands so $PORT and $HOST reach the
|
|
38
52
|
managed server unchanged. Stop keeps the tile and prevents automatic restart.
|
|
39
53
|
`;
|
|
@@ -45,8 +59,8 @@ function parse(args) {
|
|
|
45
59
|
const env = {};
|
|
46
60
|
const unsetEnv = [];
|
|
47
61
|
let id, json = false;
|
|
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'] : [];
|
|
62
|
+
const allowed = action === 'create' ? ['name', 'branch', 'command', 'cwd', 'setup', 'build', 'health-path', 'port', 'poll-seconds', 'timeout-seconds', 'ready-seconds', 'wait-for', 'request-id', 'desktop', 'mode'] : action === 'logs' ? ['tail']
|
|
63
|
+
: action === 'update' ? ['env', 'unset-env', 'command', 'setup', 'build', 'mode', 'health-path', 'ready-seconds', 'timeout-seconds'] : [];
|
|
50
64
|
for (let i = 1; i < args.length; i++) {
|
|
51
65
|
const arg = args[i];
|
|
52
66
|
if (arg === '--json') {
|
|
@@ -97,6 +111,9 @@ function parse(args) {
|
|
|
97
111
|
throw new Error(`--${key} must be an integer in ${min}..${max}`);
|
|
98
112
|
return n;
|
|
99
113
|
};
|
|
114
|
+
const mode = values.mode;
|
|
115
|
+
if (mode !== undefined && mode !== 'production' && mode !== 'dev')
|
|
116
|
+
throw new Error('--mode must be production or dev');
|
|
100
117
|
const result = { action: action, id, json, tail: number('tail', 1, 200, 50) };
|
|
101
118
|
if (action === 'create') {
|
|
102
119
|
for (const key of ['name', 'branch', 'command'])
|
|
@@ -105,6 +122,8 @@ function parse(args) {
|
|
|
105
122
|
const cwd = values.cwd || '.';
|
|
106
123
|
if (cwd.startsWith('/') || cwd.split(/[\\/]/).includes('..'))
|
|
107
124
|
throw new Error('--cwd must stay inside the repository');
|
|
125
|
+
if (mode === 'production' && !values.build?.trim())
|
|
126
|
+
throw new Error('--mode production requires --build');
|
|
108
127
|
const waitFor = values['wait-for'];
|
|
109
128
|
if (waitFor !== undefined && (waitFor.length > 1024 || waitFor.startsWith('/') || waitFor.split(/[\\/]/).includes('..') || /[\r\n]/.test(waitFor)))
|
|
110
129
|
throw new Error('--wait-for must be a repository-relative path');
|
|
@@ -114,7 +133,7 @@ function parse(args) {
|
|
|
114
133
|
followBranch: { branch: values.branch, ...(values.setup && { setup: values.setup }), ...(values.build && { build: values.build }),
|
|
115
134
|
healthPath: values['health-path'] || '/', pollSeconds: number('poll-seconds', 5, 3600, 30),
|
|
116
135
|
timeoutSeconds: number('timeout-seconds', 1, 1800, 300), readySeconds: number('ready-seconds', 1, 300, 60),
|
|
117
|
-
...(waitFor && { waitFor }) } };
|
|
136
|
+
...(waitFor && { waitFor }), ...(mode && { mode }) } };
|
|
118
137
|
}
|
|
119
138
|
if (action === 'update') {
|
|
120
139
|
const healthPath = values['health-path'];
|
|
@@ -123,7 +142,7 @@ function parse(args) {
|
|
|
123
142
|
const body = {
|
|
124
143
|
...(Object.keys(env).length && { env }), ...(unsetEnv.length && { unsetEnv }),
|
|
125
144
|
...(values.command !== undefined && { command: values.command }), ...(values.setup !== undefined && { setup: values.setup }),
|
|
126
|
-
...(values.build !== undefined && { build: values.build }), ...(healthPath !== undefined && { healthPath }),
|
|
145
|
+
...(values.build !== undefined && { build: values.build }), ...(mode !== undefined && { mode }), ...(healthPath !== undefined && { healthPath }),
|
|
127
146
|
...(values['ready-seconds'] !== undefined && { readySeconds: number('ready-seconds', 1, 300, 60) }),
|
|
128
147
|
...(values['timeout-seconds'] !== undefined && { timeoutSeconds: number('timeout-seconds', 1, 1800, 300) }),
|
|
129
148
|
};
|
|
@@ -182,7 +201,7 @@ export async function runPreviewCmd(args, deps = {}) {
|
|
|
182
201
|
out((body.lines?.map((line) => line.text).join('') || '(no logs)') + '\n');
|
|
183
202
|
else {
|
|
184
203
|
const previews = body.previews || [body.preview];
|
|
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');
|
|
204
|
+
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?.mode || p.branchStatus?.lastBuild ? `\n ${p.branchStatus.mode || 'unset'} mode${p.branchStatus.lastBuild ? `, last build ${(p.branchStatus.lastBuild.durationMs / 1000).toFixed(1)}s (${p.branchStatus.lastBuild.commit.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');
|
|
186
205
|
}
|
|
187
206
|
return 0;
|
|
188
207
|
}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `yolo routing …` — Background Runner routing (which model runs each card)
|
|
3
|
+
* and Jev from a shell: status, on/off, decisions, a route preview, and the
|
|
4
|
+
* runner/board policy.
|
|
5
|
+
*
|
|
6
|
+
* Every verb is one of the owner REST routes in
|
|
7
|
+
* `common-api/src/routes/yolo-background-routing.ts`, reached with the USER
|
|
8
|
+
* token through `userRouteRequest`, like `yolo kanban models`. Nothing is
|
|
9
|
+
* decided here: `--json` prints the response body as-is, and the default
|
|
10
|
+
* output is a short reading of the same body.
|
|
11
|
+
*
|
|
12
|
+
* Exit codes as `kanban-cli.ts`: 0 success, 1 http, 64 usage/auth/workspace.
|
|
13
|
+
*/
|
|
14
|
+
import * as fs from 'node:fs';
|
|
15
|
+
import { userRouteRequest } from './work-client.js';
|
|
16
|
+
import { exitCodeForFailure, resolveKanbanContext } from './kanban-cli.js';
|
|
17
|
+
const OBJECT_ID = /^[a-f0-9]{24}$/;
|
|
18
|
+
/** `args` is everything after `routing`. */
|
|
19
|
+
export function parseRoutingArgs(args) {
|
|
20
|
+
const positional = [];
|
|
21
|
+
const flags = {};
|
|
22
|
+
const VALUED = new Set(['--workspace', '--card', '--board', '--limit', '--file', '--policy', '--expected-revision']);
|
|
23
|
+
for (let i = 0; i < args.length; i++) {
|
|
24
|
+
const a = args[i];
|
|
25
|
+
const eq = a.indexOf('=');
|
|
26
|
+
const name = a.startsWith('--') && eq > 0 ? a.slice(0, eq) : a;
|
|
27
|
+
if (VALUED.has(name)) {
|
|
28
|
+
const v = eq > 0 && a.startsWith('--') ? a.slice(eq + 1) : args[++i];
|
|
29
|
+
if (!v || (eq < 0 && v.startsWith('--')))
|
|
30
|
+
return { ok: false, message: `${name} requires a value` };
|
|
31
|
+
flags[name] = v;
|
|
32
|
+
}
|
|
33
|
+
else if (a === '--json' || a === '--runner') {
|
|
34
|
+
flags[a] = true;
|
|
35
|
+
}
|
|
36
|
+
else if (a.startsWith('-')) {
|
|
37
|
+
return { ok: false, message: `unknown option: ${a}` };
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
positional.push(a);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const json = flags['--json'] === true;
|
|
44
|
+
const workspaceFlag = flags['--workspace'];
|
|
45
|
+
const allow = (...names) => {
|
|
46
|
+
const extra = Object.keys(flags).find(f => f !== '--json' && f !== '--workspace' && !names.includes(f));
|
|
47
|
+
return extra ? `${extra} does not apply here` : null;
|
|
48
|
+
};
|
|
49
|
+
const card = flags['--card'];
|
|
50
|
+
if (card !== undefined && !OBJECT_ID.test(card))
|
|
51
|
+
return { ok: false, message: '--card takes a card id (24 hex characters)' };
|
|
52
|
+
const board = flags['--board'];
|
|
53
|
+
if (board !== undefined && !OBJECT_ID.test(board))
|
|
54
|
+
return { ok: false, message: '--board takes a board id (24 hex characters)' };
|
|
55
|
+
const revision = flags['--expected-revision'] === undefined ? undefined : Number(flags['--expected-revision']);
|
|
56
|
+
if (revision !== undefined && (!Number.isInteger(revision) || revision < 0)) {
|
|
57
|
+
return { ok: false, message: '--expected-revision takes a non-negative integer' };
|
|
58
|
+
}
|
|
59
|
+
const [verb, sub, ...rest] = positional;
|
|
60
|
+
const done = (command, ...names) => {
|
|
61
|
+
const problem = allow(...names);
|
|
62
|
+
return problem ? { ok: false, message: problem } : { ok: true, command, json, workspaceFlag };
|
|
63
|
+
};
|
|
64
|
+
const noMore = (list) => list.find(v => v !== undefined);
|
|
65
|
+
switch (verb) {
|
|
66
|
+
case 'status':
|
|
67
|
+
case 'on':
|
|
68
|
+
case 'off': {
|
|
69
|
+
const extra = noMore([sub, ...rest]);
|
|
70
|
+
if (extra)
|
|
71
|
+
return { ok: false, message: `unexpected positional argument: ${extra}` };
|
|
72
|
+
return done(verb === 'status' ? { verb } : { verb });
|
|
73
|
+
}
|
|
74
|
+
case 'decisions': {
|
|
75
|
+
const extra = noMore([sub, ...rest]);
|
|
76
|
+
if (extra)
|
|
77
|
+
return { ok: false, message: `unexpected positional argument: ${extra}` };
|
|
78
|
+
const limit = flags['--limit'] === undefined ? undefined : Number(flags['--limit']);
|
|
79
|
+
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 200)) {
|
|
80
|
+
return { ok: false, message: '--limit takes an integer from 1 to 200' };
|
|
81
|
+
}
|
|
82
|
+
return done({ verb, ...(card ? { cardId: card } : {}), ...(limit !== undefined ? { limit } : {}) }, '--card', '--limit');
|
|
83
|
+
}
|
|
84
|
+
case 'preview': {
|
|
85
|
+
if (!sub)
|
|
86
|
+
return { ok: false, message: 'a <cardId> is required' };
|
|
87
|
+
if (!OBJECT_ID.test(sub))
|
|
88
|
+
return { ok: false, message: '<cardId> must be a card id (24 hex characters)' };
|
|
89
|
+
const extra = noMore(rest);
|
|
90
|
+
if (extra)
|
|
91
|
+
return { ok: false, message: `unexpected positional argument: ${extra}` };
|
|
92
|
+
return done({ verb, cardId: sub });
|
|
93
|
+
}
|
|
94
|
+
case 'policy': {
|
|
95
|
+
const extra = noMore(rest);
|
|
96
|
+
if (extra)
|
|
97
|
+
return { ok: false, message: `unexpected positional argument: ${extra}` };
|
|
98
|
+
if (sub === 'get')
|
|
99
|
+
return done({ verb: 'policy-get', ...(card ? { cardId: card } : {}) }, '--card');
|
|
100
|
+
const targets = [flags['--runner'] === true, board !== undefined, card !== undefined].filter(Boolean).length;
|
|
101
|
+
if (sub === 'set') {
|
|
102
|
+
if (card !== undefined)
|
|
103
|
+
return { ok: false, message: 'a card\'s model pin is set on the card, not with `routing policy set`' };
|
|
104
|
+
if (targets !== 1)
|
|
105
|
+
return { ok: false, message: 'choose one of --runner or --board <id>' };
|
|
106
|
+
const file = flags['--file'];
|
|
107
|
+
const inline = flags['--policy'];
|
|
108
|
+
if ((file === undefined) === (inline === undefined))
|
|
109
|
+
return { ok: false, message: 'give the policy with exactly one of --file <path> or --policy <json>' };
|
|
110
|
+
const target = board ? { scope: 'board', scopeId: board } : { scope: 'runner' };
|
|
111
|
+
return done({ verb: 'policy-set', target, ...(file ? { policyFile: file } : { policyJson: inline }),
|
|
112
|
+
...(revision !== undefined ? { expectedRevision: revision } : {}) }, '--runner', '--board', '--file', '--policy', '--expected-revision');
|
|
113
|
+
}
|
|
114
|
+
if (sub === 'delete') {
|
|
115
|
+
if (targets !== 1)
|
|
116
|
+
return { ok: false, message: 'choose one of --runner, --board <id> or --card <id>' };
|
|
117
|
+
if (revision === 0)
|
|
118
|
+
return { ok: false, message: '--expected-revision for a delete is 1 or more' };
|
|
119
|
+
const target = board ? { scope: 'board', scopeId: board } : card ? { scope: 'card', scopeId: card } : { scope: 'runner' };
|
|
120
|
+
return done({ verb: 'policy-delete', target, ...(revision !== undefined ? { expectedRevision: revision } : {}) }, '--runner', '--board', '--card', '--expected-revision');
|
|
121
|
+
}
|
|
122
|
+
return { ok: false, message: sub ? `unknown policy subcommand '${sub}'` : 'policy requires get, set or delete' };
|
|
123
|
+
}
|
|
124
|
+
default:
|
|
125
|
+
return { ok: false, message: verb ? `unknown routing subcommand '${verb}'` : 'routing requires a subcommand' };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export async function runRouting(parsed, deps = {}) {
|
|
129
|
+
const env = deps.env ?? process.env;
|
|
130
|
+
const resolved = resolveKanbanContext(env, parsed.workspaceFlag);
|
|
131
|
+
if (!resolved.ok)
|
|
132
|
+
return resolved.failure;
|
|
133
|
+
const { commonApiUrl, userToken, workspaceId } = resolved;
|
|
134
|
+
const base = `/workspaces/${encodeURIComponent(workspaceId)}/yolo-background/routing`;
|
|
135
|
+
const send = async ({ method, path, body, label }) => {
|
|
136
|
+
let response;
|
|
137
|
+
try {
|
|
138
|
+
response = await userRouteRequest({ commonApiUrl, userToken, fetchImpl: deps.fetchImpl }, `${base}/${path}`, { method, ...(body !== undefined ? { jsonBody: body } : {}) });
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
return fail('http', `${label} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
142
|
+
}
|
|
143
|
+
const text = await response.text().catch(() => '<no body>');
|
|
144
|
+
if (!response.ok)
|
|
145
|
+
return fail('http', `${label} failed: HTTP ${response.status} — ${text}`, { status: response.status });
|
|
146
|
+
return { ok: true, text };
|
|
147
|
+
};
|
|
148
|
+
const finish = (text, human) => {
|
|
149
|
+
if (parsed.json)
|
|
150
|
+
return { ok: true, output: text, raw: true, workspaceId };
|
|
151
|
+
let body;
|
|
152
|
+
try {
|
|
153
|
+
body = JSON.parse(text);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return { ok: true, output: text, raw: false, workspaceId };
|
|
157
|
+
}
|
|
158
|
+
return { ok: true, output: human(body), raw: false, workspaceId };
|
|
159
|
+
};
|
|
160
|
+
const { command } = parsed;
|
|
161
|
+
switch (command.verb) {
|
|
162
|
+
case 'status': {
|
|
163
|
+
const r = await send({ method: 'GET', path: 'config', label: 'routing.config' });
|
|
164
|
+
return r.ok ? finish(r.text, formatStatus) : r;
|
|
165
|
+
}
|
|
166
|
+
case 'on':
|
|
167
|
+
case 'off': {
|
|
168
|
+
const r = await send({ method: 'PUT', path: 'enabled', body: { enabled: command.verb === 'on' }, label: 'routing.enabled' });
|
|
169
|
+
return r.ok ? finish(r.text, (body) => `Routing is ${body.enabled ? 'on: Jev assesses cards admitted from now on' : 'off: cards admitted from now on run on the background agent\'s default model'}. Running work is untouched.`) : r;
|
|
170
|
+
}
|
|
171
|
+
case 'decisions': {
|
|
172
|
+
const qs = new URLSearchParams();
|
|
173
|
+
if (command.cardId)
|
|
174
|
+
qs.set('cardIds', command.cardId);
|
|
175
|
+
if (command.limit !== undefined)
|
|
176
|
+
qs.set('limit', String(command.limit));
|
|
177
|
+
const q = qs.toString();
|
|
178
|
+
const r = await send({ method: 'GET', path: `decisions${q ? `?${q}` : ''}`, label: 'routing.decisions' });
|
|
179
|
+
return r.ok ? finish(r.text, formatDecisions) : r;
|
|
180
|
+
}
|
|
181
|
+
case 'preview': {
|
|
182
|
+
const r = await send({ method: 'POST', path: 'preview', body: { cardId: command.cardId }, label: 'routing.preview' });
|
|
183
|
+
// A preview's shape is the router's; the summary is its decision, the rest is `--json`.
|
|
184
|
+
return r.ok ? finish(r.text, (body) => JSON.stringify(body.decision ?? body, null, 2)) : r;
|
|
185
|
+
}
|
|
186
|
+
case 'policy-get': {
|
|
187
|
+
const r = await send({ method: 'GET', path: `config${command.cardId ? `?cardId=${command.cardId}` : ''}`, label: 'routing.config' });
|
|
188
|
+
if (!r.ok)
|
|
189
|
+
return r;
|
|
190
|
+
if (parsed.json) {
|
|
191
|
+
const body = JSON.parse(r.text);
|
|
192
|
+
return { ok: true, output: JSON.stringify({ policies: body.policies ?? [], cardPolicies: body.cardPolicies ?? null }, null, 2), raw: false, workspaceId };
|
|
193
|
+
}
|
|
194
|
+
return finish(r.text, formatPolicies);
|
|
195
|
+
}
|
|
196
|
+
case 'policy-set': {
|
|
197
|
+
let policy;
|
|
198
|
+
try {
|
|
199
|
+
const source = command.policyFile !== undefined ? (deps.readFileImpl ?? defaultReadFile)(command.policyFile) : command.policyJson;
|
|
200
|
+
policy = JSON.parse(source);
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
return fail('usage', `the policy is not readable JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
204
|
+
}
|
|
205
|
+
if (!policy || typeof policy !== 'object' || Array.isArray(policy))
|
|
206
|
+
return fail('usage', 'the policy must be a JSON object');
|
|
207
|
+
const scopeId = command.target.scope === 'board' ? command.target.scopeId : null;
|
|
208
|
+
let expectedRevision = command.expectedRevision;
|
|
209
|
+
if (expectedRevision === undefined) {
|
|
210
|
+
// Unfenced: overwrite what is stored now (revision 0: nothing is).
|
|
211
|
+
const r = await send({ method: 'GET', path: 'config', label: 'routing.config' });
|
|
212
|
+
if (!r.ok)
|
|
213
|
+
return r;
|
|
214
|
+
const policies = JSON.parse(r.text).policies ?? [];
|
|
215
|
+
expectedRevision = policies.find(doc => doc.scope === command.target.scope && (doc.scopeId ?? null) === scopeId)?.revision ?? 0;
|
|
216
|
+
}
|
|
217
|
+
const r = await send({ method: 'PUT', path: 'policy', body: { scope: command.target.scope, scopeId, policy, expectedRevision }, label: 'routing.policy' });
|
|
218
|
+
return r.ok ? finish(r.text, (body) => `Saved the ${describeScope(command.target)} policy (revision ${body.revision}).`) : r;
|
|
219
|
+
}
|
|
220
|
+
case 'policy-delete': {
|
|
221
|
+
const t = command.target;
|
|
222
|
+
const path = `policy/${t.scope}${t.scope === 'runner' ? '' : `/${t.scopeId}`}${command.expectedRevision !== undefined ? `?expectedRevision=${command.expectedRevision}` : ''}`;
|
|
223
|
+
const r = await send({ method: 'DELETE', path, label: 'routing.policy.delete' });
|
|
224
|
+
return r.ok ? finish(r.text, () => `Deleted the ${describeScope(t)} policy; it inherits again.`) : r;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// ─── Human output ─────────────────────────────────────────────────────────
|
|
229
|
+
const describeScope = (t) => t.scope === 'runner' ? 'runner' : `${t.scope} ${t.scopeId}`;
|
|
230
|
+
export function formatStatus(body) {
|
|
231
|
+
const jev = body.jev;
|
|
232
|
+
const usage = jev?.usage ?? [];
|
|
233
|
+
const calls = usage.reduce((n, d) => n + (d.calls ?? 0), 0);
|
|
234
|
+
const cost = usage.every(d => typeof d.costUsd === 'number') ? usage.reduce((n, d) => n + d.costUsd, 0) : null;
|
|
235
|
+
return [
|
|
236
|
+
`Routing: ${body.enabled ? 'on' : 'off'}`,
|
|
237
|
+
`Jev: ${jev?.state ?? 'unknown'}${jev?.reason ? ` (${jev.reason})` : ''}${jev?.model ? ` — ${jev.model}` : ''}`,
|
|
238
|
+
` ${calls} call${calls === 1 ? '' : 's'} in the last ${usage.length} day${usage.length === 1 ? '' : 's'}${cost === null ? '' : `, $${cost.toFixed(4)}`}`,
|
|
239
|
+
formatPolicies(body),
|
|
240
|
+
].join('\n');
|
|
241
|
+
}
|
|
242
|
+
export function formatPolicies(body) {
|
|
243
|
+
const lines = (body.policies ?? []).map(p => ` ${p.scope === 'runner' ? 'runner' : `${p.scope} ${p.scopeId}`} revision ${p.revision}`);
|
|
244
|
+
return [
|
|
245
|
+
`Policies:${lines.length ? '' : ' none (built-in defaults)'}`,
|
|
246
|
+
...lines,
|
|
247
|
+
`Card policies (model pins): ${body.cardPolicies?.count ?? 0}`,
|
|
248
|
+
].join('\n');
|
|
249
|
+
}
|
|
250
|
+
export function formatDecisions(body) {
|
|
251
|
+
const decisions = body.decisions ?? [];
|
|
252
|
+
if (decisions.length === 0)
|
|
253
|
+
return 'No routing decisions recorded.';
|
|
254
|
+
return decisions.map(d => {
|
|
255
|
+
const detail = d.decision?.selected?.configurationId ?? d.decision?.waiting?.code;
|
|
256
|
+
return `${d.createdAt} ${d.cardId} ${d.kind} ${d.decision?.status ?? '?'}${detail ? ` ${detail}` : ''}`;
|
|
257
|
+
}).join('\n');
|
|
258
|
+
}
|
|
259
|
+
// ─── CLI surface ──────────────────────────────────────────────────────────
|
|
260
|
+
export const ROUTING_USAGE = [
|
|
261
|
+
'Usage: yolo routing <subcommand> [--json] [--workspace <wsId>]',
|
|
262
|
+
'',
|
|
263
|
+
'Subcommands:',
|
|
264
|
+
' status Routing on/off, Jev\'s state and why it is unavailable, policies',
|
|
265
|
+
' on | off Turn routing on or off (cards admitted from now on)',
|
|
266
|
+
' decisions [--card <id>] [--limit <n>] Recorded decisions for one card, or the latest (1-200)',
|
|
267
|
+
' preview <cardId> Where routing would send a card now (read-only)',
|
|
268
|
+
' policy get [--card <id>] Runner and board policies with their revisions',
|
|
269
|
+
' policy set (--runner | --board <id>) Replace a policy: --file <path> or --policy <json>',
|
|
270
|
+
' [--expected-revision <n>] Refuse if the policy changed since revision <n>',
|
|
271
|
+
' policy delete (--runner | --board <id> | --card <id>) [--expected-revision <n>]',
|
|
272
|
+
' Delete a policy so it inherits again',
|
|
273
|
+
'',
|
|
274
|
+
'--json prints the API response as-is.',
|
|
275
|
+
'',
|
|
276
|
+
].join('\n');
|
|
277
|
+
/** `args` is everything after `routing`. */
|
|
278
|
+
export async function runRoutingCmd(args, deps = {}) {
|
|
279
|
+
if (args.length === 0 || args.some(a => a === '--help' || a === '-h') || args[0] === 'help') {
|
|
280
|
+
(args.length === 0 ? process.stderr : process.stdout).write(ROUTING_USAGE);
|
|
281
|
+
return args.length === 0 ? 64 : 0;
|
|
282
|
+
}
|
|
283
|
+
const parsed = parseRoutingArgs(args);
|
|
284
|
+
if (!parsed.ok) {
|
|
285
|
+
process.stderr.write(`yolo: routing: ${parsed.message}\n`);
|
|
286
|
+
process.stderr.write(ROUTING_USAGE);
|
|
287
|
+
return 64;
|
|
288
|
+
}
|
|
289
|
+
const result = await runRouting(parsed, deps);
|
|
290
|
+
if (result.ok) {
|
|
291
|
+
process.stdout.write(result.raw ? result.output : `${result.output}\n`);
|
|
292
|
+
return 0;
|
|
293
|
+
}
|
|
294
|
+
process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
|
|
295
|
+
return exitCodeForFailure(result.kind);
|
|
296
|
+
}
|
|
297
|
+
function fail(kind, message, detail) {
|
|
298
|
+
return { ok: false, kind, message, detail };
|
|
299
|
+
}
|
|
300
|
+
function defaultReadFile(filePath) {
|
|
301
|
+
return fs.readFileSync(filePath, 'utf-8');
|
|
302
|
+
}
|