@yolo-labs/yolo-cli 0.42.0 → 0.43.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.
@@ -1,420 +0,0 @@
1
- /**
2
- * `yolo plan import <file>` orchestration (Phase 8c.3).
3
- *
4
- * Composes everything from earlier slices:
5
- * - `plan-validate` (8c.1) — parse + schema + canonical + no-coercion
6
- * - `revision` (8c.2) — sha256 over canonical bytes
7
- * - `lockfile` (8c.2) — `(workspaceId, planId) → entry` storage
8
- * - `work-client` (8c.2) — `mintSubstrateToken` + `authenticatedRequest`
9
- * - `plan-diff` (8c.3) — DB plan vs file plan → mutation list
10
- *
11
- * High-level flow:
12
- *
13
- * 1. Validate file (offline: parse + schema + canonical + no-coercion).
14
- * 2. Enforce planId equals the file stem (semantic check, design F8.1).
15
- * 3. Resolve substrate context (env trio); error otherwise.
16
- * 4. Mint a session-bound delegated token; the response carries the
17
- * authoritative `workspaceId` (Phase 8 design: workspace binding
18
- * is derived from session, not env/args).
19
- * 5. If `--workspace` was passed, assert it matches the minted
20
- * workspaceId — otherwise the user's mental model and the
21
- * session's binding diverge silently.
22
- * 6. Read the lockfile (gitignored default unless `--env` is set).
23
- * 7. Decide the action:
24
- * - **NO_CHANGE** — file revision == lockfile.lastImportedRevision.
25
- * Refresh the timestamp on the lockfile entry,
26
- * do not touch the DB.
27
- * - **CREATE** — no lockfile entry. Call `work.create_plan`.
28
- * On 409 (plan already exists in DB), refuse
29
- * unless `--force`.
30
- * - **UPDATE** — lockfile entry exists, file revision differs.
31
- * GET the DB plan, check `version` against
32
- * `lastImportedVersion` to detect drift, then
33
- * `work.update_plan` with computed mutations.
34
- * - **DIVERGED** — lockfile entry exists but DB version >
35
- * lastImportedVersion. Refuse unless `--force`.
36
- * 8. On success, write the new lockfile entry
37
- * (`{ revision, version, importedAt }`).
38
- *
39
- * Errors map to exit codes via the CLI wrapper:
40
- * - 0 = success (CREATE / UPDATE / NO_CHANGE all success)
41
- * - 1 = validation failure / refused divergence / DB error
42
- * - 64 = usage error (missing file, planId/stem mismatch, --workspace
43
- * mismatch, missing env trio)
44
- *
45
- * Out of scope (deferred to a later slice if real demand emerges):
46
- * - Step REORDER detection. Substrate executor reads
47
- * `gate.config.requires`, not array order; reordering is a
48
- * semantic no-op. New steps land at the end via `add-step`.
49
- * - Outside-container login flow. v1 errors out without `SESSION_ID`
50
- * (substrate CLI is container-only — design Round 5).
51
- * - Concurrent import safety. The lockfile read-modify-write is not
52
- * atomic across processes; multi-developer concurrent imports to
53
- * the same workspace are rare enough to defer.
54
- */
55
- import { readFileSync } from 'node:fs';
56
- import path from 'node:path';
57
- import { canonicalizePlanFile } from './canonicalizer.js';
58
- import { computeMutations } from './plan-diff.js';
59
- import { validatePlanText, formatErrors } from './plan-validate.js';
60
- import { computeRevisionHash } from './revision.js';
61
- import { LockfileError, getEntry, readLockfile, resolveLockfilePath, setEntry, writeLockfile, } from './lockfile.js';
62
- import { SUBSTRATE_CLI_PLAN_SCOPES, WorkClientError, authenticatedRequest, mintSubstrateToken, } from './work-client.js';
63
- import { resolveSubstrateContext } from './auth-context.js';
64
- import yaml from 'js-yaml';
65
- import { planDagUrl } from './webapp-url.js';
66
- // ─── Public entry ─────────────────────────────────────────────────────────
67
- export async function runPlanImport(options) {
68
- const env = options.env ?? process.env;
69
- const now = options.now ?? (() => new Date().toISOString());
70
- // 1) Validate file
71
- let fileText;
72
- try {
73
- fileText = readFileSync(options.filePath, 'utf8');
74
- }
75
- catch (err) {
76
- return fail('usage', `cannot read plan file '${options.filePath}': ${describeError(err)}`);
77
- }
78
- const validation = validatePlanText(fileText);
79
- if (!validation.ok) {
80
- return fail('validation', `plan-file validation failed:\n${formatErrors(validation.errors)}`);
81
- }
82
- // Parse the file once we know it's valid+canonical so we can hand
83
- // both the frontmatter and body to the diff.
84
- let frontmatter;
85
- let body;
86
- try {
87
- const parsed = parsePlanFile(fileText);
88
- frontmatter = parsed.frontmatter;
89
- body = parsed.body;
90
- }
91
- catch (err) {
92
- // validatePlanText already ruled this path out; defense-in-depth.
93
- return fail('validation', `plan-file parse failed: ${describeError(err)}`);
94
- }
95
- const filePlan = makeFilePlan(frontmatter, body);
96
- // 2) planId vs file stem (design F8.1)
97
- const stem = path.basename(options.filePath, path.extname(options.filePath));
98
- if (filePlan.planId !== stem) {
99
- return fail('planid_stem_mismatch', `frontmatter planId '${filePlan.planId}' must equal the file stem '${stem}' (file '${options.filePath}')`);
100
- }
101
- // 3) Substrate context
102
- const auth = resolveSubstrateContext(env);
103
- if (!auth.ok)
104
- return fail('auth', auth.message);
105
- const { sessionId, commonApiUrl, userToken } = auth.context;
106
- // 4) Mint token
107
- let mint;
108
- try {
109
- mint = await mintSubstrateToken({
110
- commonApiUrl,
111
- userToken,
112
- sessionId,
113
- scopes: SUBSTRATE_CLI_PLAN_SCOPES,
114
- fetchImpl: options.fetchImpl,
115
- });
116
- }
117
- catch (err) {
118
- if (err instanceof WorkClientError) {
119
- return fail('auth', `failed to mint substrate token: ${err.message}`, { status: err.status, code: err.code });
120
- }
121
- return fail('auth', `failed to mint substrate token: ${describeError(err)}`);
122
- }
123
- // 5) --workspace assertion
124
- if (options.workspaceFlag && options.workspaceFlag !== mint.workspaceId) {
125
- return fail('workspace_mismatch', `--workspace ${options.workspaceFlag} does not match the workspace bound to this session (${mint.workspaceId}). ` +
126
- `Either omit the flag (it's optional in containers) or open a session for the right workspace.`);
127
- }
128
- // 6) Lockfile
129
- const plansDir = options.plansDir ?? path.dirname(options.filePath);
130
- let lockfilePath;
131
- let lockfile;
132
- try {
133
- lockfilePath = resolveLockfilePath(plansDir, options.lockfileFlag);
134
- lockfile = readLockfile(lockfilePath);
135
- }
136
- catch (err) {
137
- if (err instanceof LockfileError) {
138
- return fail('lockfile', err.message, { code: err.code });
139
- }
140
- return fail('lockfile', describeError(err));
141
- }
142
- // 7) Decide action
143
- const canonicalBytes = canonicalizePlanFile(frontmatter, body);
144
- const fileRevision = computeRevisionHash(canonicalBytes);
145
- const existingEntry = getEntry(lockfile, mint.workspaceId, filePlan.planId);
146
- const requestCtx = {
147
- commonApiUrl,
148
- delegatedToken: mint.token,
149
- fetchImpl: options.fetchImpl,
150
- };
151
- let resultAction;
152
- let resultVersion;
153
- if (!existingEntry) {
154
- // CREATE path
155
- const created = await tryCreate(requestCtx, mint.workspaceId, filePlan);
156
- if (created.ok) {
157
- resultAction = 'created';
158
- resultVersion = created.version;
159
- }
160
- else if (created.conflict409) {
161
- if (!options.force) {
162
- return fail('conflict_no_force', `plan '${filePlan.planId}' already exists in workspace ${mint.workspaceId} but the lockfile has no entry. ` +
163
- `Run with --force to fast-forward import (will rewrite the DB plan with the file's contents), or ` +
164
- `run \`yolo plan export ${filePlan.planId}\` first to capture the DB shape.`);
165
- }
166
- // --force on 409: pull the DB plan, run the UPDATE path with whatever's there as the base.
167
- const fetched = await tryGet(requestCtx, mint.workspaceId, filePlan.planId);
168
- if (!fetched.ok)
169
- return fetched.error;
170
- const updated = await tryUpdate(requestCtx, mint.workspaceId, filePlan, fetched.plan);
171
- if (!updated.ok)
172
- return updated.error;
173
- resultAction = 'updated';
174
- resultVersion = updated.version;
175
- }
176
- else {
177
- return created.error;
178
- }
179
- }
180
- else if (existingEntry.lastImportedRevision === fileRevision) {
181
- // NO_CHANGE path: refresh timestamp, write lockfile, exit.
182
- resultAction = 'no-change';
183
- resultVersion = existingEntry.lastImportedVersion;
184
- }
185
- else {
186
- // UPDATE path: GET DB, check drift, compute mutations, PATCH.
187
- const fetched = await tryGet(requestCtx, mint.workspaceId, filePlan.planId);
188
- if (!fetched.ok)
189
- return fetched.error;
190
- if (fetched.plan.version !== existingEntry.lastImportedVersion) {
191
- if (!options.force) {
192
- return fail('diverged', `DB has plan '${filePlan.planId}' at version ${fetched.plan.version}, but lockfile expected version ${existingEntry.lastImportedVersion}. ` +
193
- `Run with --force to fast-forward (overwrites DB changes), or \`yolo plan export\` first to capture the DB shape.`, { dbVersion: fetched.plan.version, expectedVersion: existingEntry.lastImportedVersion });
194
- }
195
- }
196
- const updated = await tryUpdate(requestCtx, mint.workspaceId, filePlan, fetched.plan);
197
- if (!updated.ok)
198
- return updated.error;
199
- resultAction = updated.action;
200
- resultVersion = updated.version;
201
- }
202
- // 8) Update lockfile (idempotent — same input → same bytes).
203
- const importedAt = now();
204
- const newEntry = {
205
- lastImportedRevision: fileRevision,
206
- lastImportedVersion: resultVersion,
207
- lastImportedAt: importedAt,
208
- };
209
- setEntry(lockfile, mint.workspaceId, filePlan.planId, newEntry);
210
- try {
211
- writeLockfile(lockfilePath, lockfile);
212
- }
213
- catch (err) {
214
- if (err instanceof LockfileError) {
215
- return fail('lockfile', err.message, { code: err.code });
216
- }
217
- return fail('lockfile', describeError(err));
218
- }
219
- return {
220
- ok: true,
221
- action: resultAction,
222
- planId: filePlan.planId,
223
- workspaceId: mint.workspaceId,
224
- version: resultVersion,
225
- revision: fileRevision,
226
- importedAt,
227
- lockfilePath,
228
- };
229
- }
230
- async function tryCreate(ctx, workspaceId, filePlan) {
231
- // `filePlan.description` is the SEPARATOR-NORMALIZED body
232
- // (`makeFilePlan` strips the leading `\n` that the regex captures
233
- // along with the body). Sending it raw was the Codex 8c.3 R1 bug —
234
- // canonical files emit `---\n\n<body>` so the captured `body`
235
- // starts with `\n`, which would make imported descriptions begin
236
- // with a phantom blank line and break round-trips.
237
- const body = {
238
- planId: filePlan.planId,
239
- name: filePlan.name,
240
- description: filePlan.description,
241
- inputs: filePlan.inputs ?? [],
242
- failurePolicy: filePlan.failurePolicy ?? 'pause-and-wait',
243
- autoRetryCap: filePlan.autoRetryCap,
244
- autoRetryFallback: filePlan.autoRetryFallback,
245
- integrationPolicy: filePlan.integrationPolicy,
246
- steps: filePlan.steps,
247
- // Send the file's state so a Plan authored as 'active' lands at
248
- // 'active' instead of silently downgrading to 'draft'. Surfaced
249
- // in Phase 8d.2 verification: the substrate's create_plan didn't
250
- // accept the field until this slice (validatePlanCreateFields now
251
- // normalizes it via PLAN_STATES). Omitting the field keeps the
252
- // substrate's draft-first default for hand-authored callers that
253
- // don't supply one.
254
- //
255
- // Renamed from `authoringState` 2026-05-09 (item 17 of
256
- // `docs/SUBSTRATE_IMPROVEMENTS.md`).
257
- state: filePlan.state,
258
- };
259
- const response = await authenticatedRequest(ctx, `/workspaces/${workspaceId}/plans`, {
260
- method: 'POST',
261
- jsonBody: body,
262
- });
263
- if (response.ok) {
264
- const json = (await response.json());
265
- if (typeof json.version !== 'number') {
266
- return { ok: false, error: fail('http', 'create_plan response missing version field') };
267
- }
268
- return { ok: true, version: json.version };
269
- }
270
- if (response.status === 409) {
271
- return { ok: false, conflict409: true };
272
- }
273
- const text = await safeReadText(response);
274
- return {
275
- ok: false,
276
- error: fail('http', `work.create_plan failed: HTTP ${response.status} — ${text}`, {
277
- status: response.status,
278
- }),
279
- };
280
- }
281
- async function tryGet(ctx, workspaceId, planId) {
282
- const response = await authenticatedRequest(ctx, `/workspaces/${workspaceId}/plans/${planId}`, {
283
- method: 'GET',
284
- });
285
- if (!response.ok) {
286
- const text = await safeReadText(response);
287
- return {
288
- ok: false,
289
- error: fail('http', `work.get_plan failed: HTTP ${response.status} — ${text}`, { status: response.status }),
290
- };
291
- }
292
- const json = (await response.json());
293
- if (!json.plan) {
294
- return { ok: false, error: fail('http', 'work.get_plan response missing `plan` field') };
295
- }
296
- return { ok: true, plan: json.plan };
297
- }
298
- async function tryUpdate(ctx, workspaceId, filePlan, dbPlan) {
299
- const mutations = computeMutations(dbPlan, filePlan);
300
- if (mutations.length === 0) {
301
- // Lockfile knew the file was different (otherwise we'd be on the
302
- // NO_CHANGE path), but the diff says nothing to change. Likely:
303
- // the file's revision changed cosmetically (e.g., the
304
- // canonicalizer's output changed across versions). Treat as
305
- // no-change, and the caller will refresh the lockfile entry.
306
- return { ok: true, action: 'no-change', version: dbPlan.version };
307
- }
308
- const response = await authenticatedRequest(ctx, `/workspaces/${workspaceId}/plans/${filePlan.planId}`, {
309
- method: 'PATCH',
310
- jsonBody: { baseVersion: dbPlan.version, mutations: mutations },
311
- });
312
- if (!response.ok) {
313
- const text = await safeReadText(response);
314
- return {
315
- ok: false,
316
- error: fail('http', `work.update_plan failed: HTTP ${response.status} — ${text}`, { status: response.status }),
317
- };
318
- }
319
- const json = (await response.json());
320
- if (typeof json.version !== 'number') {
321
- return { ok: false, error: fail('http', 'work.update_plan response missing version field') };
322
- }
323
- return { ok: true, action: 'updated', version: json.version };
324
- }
325
- // ─── Helpers ──────────────────────────────────────────────────────────────
326
- const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
327
- /**
328
- * Re-split the file into frontmatter object + body string. Mirrors
329
- * the regex used by validatePlanText so that a successful validate
330
- * implies a successful parse here. Throws on failure (defense-in-depth
331
- * against future drift between the two parsers).
332
- */
333
- function parsePlanFile(text) {
334
- const match = text.match(FRONTMATTER_RE);
335
- if (!match)
336
- throw new Error('frontmatter delimiters missing');
337
- const fm = yaml.load(match[1]);
338
- return { frontmatter: fm, body: match[2] };
339
- }
340
- function makeFilePlan(frontmatter, body) {
341
- // Body is Plan.description (Phase 8b design). The frontmatter→body
342
- // separator (the blank line after the closing `---`) is OWNED by
343
- // the canonicalizer (`canonicalizePlanFile` builds `---\n\n<body>`
344
- // and strips leading `\n+` from the captured body before re-emit).
345
- // Mirror that normalization here so `description` we send to
346
- // `work.create_plan` / `work.update_plan` is exactly what
347
- // round-tripping back through the canonicalizer would produce —
348
- // otherwise an imported description gets a phantom leading blank
349
- // line, and 8c.4 export round-trips churn (Codex 8c.3 R1 Medium).
350
- const description = body
351
- .replace(/\r\n/g, '\n') // CRLF → LF (validate already rejects CRLF; defense in depth)
352
- .replace(/^\n+/, '') // strip separator-owned leading newline(s)
353
- .replace(/\s+$/, '') + // collapse trailing whitespace…
354
- '\n'; // …and ensure exactly one trailing newline.
355
- return {
356
- planId: String(frontmatter.planId ?? ''),
357
- name: String(frontmatter.name ?? ''),
358
- description,
359
- state: frontmatter.state ?? 'draft',
360
- failurePolicy: frontmatter.failurePolicy,
361
- autoRetryCap: frontmatter.autoRetryCap,
362
- autoRetryFallback: frontmatter.autoRetryFallback,
363
- inputs: frontmatter.inputs ?? [],
364
- integrationPolicy: frontmatter.integrationPolicy,
365
- steps: (frontmatter.steps ?? []),
366
- };
367
- }
368
- function fail(kind, message, detail) {
369
- return { ok: false, kind, message, detail };
370
- }
371
- function describeError(err) {
372
- return err instanceof Error ? err.message : String(err);
373
- }
374
- async function safeReadText(response) {
375
- try {
376
- return await response.text();
377
- }
378
- catch {
379
- return '<no body>';
380
- }
381
- }
382
- /**
383
- * Map an `ImportFailure.kind` to a CLI exit code. Used by cli.ts and
384
- * exported for tests.
385
- */
386
- export function exitCodeForFailure(kind) {
387
- switch (kind) {
388
- case 'usage':
389
- case 'auth':
390
- case 'planid_stem_mismatch':
391
- case 'workspace_mismatch':
392
- return 64; // EX_USAGE
393
- case 'validation':
394
- case 'lockfile':
395
- case 'diverged':
396
- case 'conflict_no_force':
397
- case 'http':
398
- return 1;
399
- }
400
- }
401
- /**
402
- * Render an `ImportSuccess` as a CLI summary. The first line is the
403
- * existing one-liner; if a webapp URL can be derived from the env, a
404
- * second line prints the Plan-DAG link so operators can click straight
405
- * through to the visual topology view. Caller appends `\n` if needed.
406
- */
407
- export function formatSuccess(result, env = process.env) {
408
- const headline = (() => {
409
- switch (result.action) {
410
- case 'created':
411
- return `OK: created plan '${result.planId}' in workspace ${result.workspaceId} at version ${result.version} (revision ${result.revision.slice(0, 14)}…)`;
412
- case 'updated':
413
- return `OK: updated plan '${result.planId}' in workspace ${result.workspaceId} to version ${result.version} (revision ${result.revision.slice(0, 14)}…)`;
414
- case 'no-change':
415
- return `OK: plan '${result.planId}' already at file revision (workspace ${result.workspaceId}, version ${result.version})`;
416
- }
417
- })();
418
- const dagUrl = planDagUrl(env, result.workspaceId, result.planId);
419
- return dagUrl ? `${headline}\n view: ${dagUrl}` : headline;
420
- }
package/dist/plan-list.js DELETED
@@ -1,153 +0,0 @@
1
- /**
2
- * `yolo plan list` — list Plans in the current workspace.
3
- *
4
- * The third read-path verb after `plan get` and `plan validate`.
5
- * Closes the "what's even in this workspace?" gap that operators
6
- * hit immediately after `yolo context` (no in-CLI way to discover
7
- * planIds without a curl detour). Maps directly to the substrate's
8
- * `work.list_plans` route, which is already in
9
- * `SUBSTRATE_CLI_PLAN_SCOPES`.
10
- *
11
- * Two output modes:
12
- * - default (`--summary`): one-line table per plan with planId,
13
- * state, version, latestRunId (or `—`), updatedAt (relative ISO
14
- * date for at-a-glance recency).
15
- * - `--json`: pretty-printed raw `plans[]` array. For jq /
16
- * scripted operator pipelines.
17
- *
18
- * Filter: `--state <draft|active|archived>` server-side filter
19
- * (passed as `?state=` query param; renamed from `authoringState`
20
- * 2026-05-09, item 17). Avoids client-side filtering on workspaces
21
- * with many plans.
22
- *
23
- * Exit codes:
24
- * - 0 = success (zero plans is also success — empty list, not an error)
25
- * - 1 = http (e.g., 401 from a token that's been revoked mid-session)
26
- * - 64 = usage (bad --state, missing env, --workspace mismatch)
27
- */
28
- import { SUBSTRATE_CLI_PLAN_SCOPES, WorkClientError, authenticatedRequest, mintSubstrateToken, } from './work-client.js';
29
- import { resolveSubstrateContext } from './auth-context.js';
30
- const ALLOWED_STATES = ['draft', 'active', 'archived'];
31
- // ─── Public entry ─────────────────────────────────────────────────────────
32
- export async function runPlanList(options) {
33
- const env = options.env ?? process.env;
34
- const format = options.outputFormat ?? 'summary';
35
- // 1) --state value (validated even though the server also validates,
36
- // so we can fail fast without a network round-trip).
37
- if (options.stateFilter !== undefined && !ALLOWED_STATES.includes(options.stateFilter)) {
38
- return fail('usage', `invalid --state '${options.stateFilter}': must be one of ${ALLOWED_STATES.join(', ')}`);
39
- }
40
- // 2) Substrate context
41
- const auth = resolveSubstrateContext(env);
42
- if (!auth.ok)
43
- return fail('auth', auth.message);
44
- const { sessionId, commonApiUrl, userToken } = auth.context;
45
- // 3) Mint token
46
- let mint;
47
- try {
48
- mint = await mintSubstrateToken({
49
- commonApiUrl,
50
- userToken,
51
- sessionId,
52
- scopes: SUBSTRATE_CLI_PLAN_SCOPES,
53
- fetchImpl: options.fetchImpl,
54
- });
55
- }
56
- catch (err) {
57
- if (err instanceof WorkClientError) {
58
- return fail('auth', `failed to mint substrate token: ${err.message}`, { status: err.status, code: err.code });
59
- }
60
- return fail('auth', `failed to mint substrate token: ${describeError(err)}`);
61
- }
62
- // 4) --workspace assertion
63
- if (options.workspaceFlag && options.workspaceFlag !== mint.workspaceId) {
64
- return fail('workspace_mismatch', `--workspace ${options.workspaceFlag} does not match the workspace bound to this session (${mint.workspaceId}).`);
65
- }
66
- // 5) GET /workspaces/<wsId>/plans (with optional ?state=)
67
- const ctx = {
68
- commonApiUrl,
69
- delegatedToken: mint.token,
70
- fetchImpl: options.fetchImpl,
71
- };
72
- const path = options.stateFilter
73
- ? `/workspaces/${mint.workspaceId}/plans?state=${options.stateFilter}`
74
- : `/workspaces/${mint.workspaceId}/plans`;
75
- const response = await authenticatedRequest(ctx, path, { method: 'GET' });
76
- if (!response.ok) {
77
- const text = await safeReadText(response);
78
- return fail('http', `work.list_plans failed: HTTP ${response.status} — ${text}`, {
79
- status: response.status,
80
- });
81
- }
82
- const json = (await response.json());
83
- if (!Array.isArray(json.plans)) {
84
- return fail('http', 'work.list_plans response missing `plans` array');
85
- }
86
- return {
87
- ok: true,
88
- output: format === 'json'
89
- ? formatJson(json.plans)
90
- : formatSummary(json.plans, mint.workspaceId, options.stateFilter),
91
- plans: json.plans,
92
- workspaceId: mint.workspaceId,
93
- };
94
- }
95
- // ─── Output formatting ────────────────────────────────────────────────────
96
- /**
97
- * One-line header + one row per plan, columns:
98
- * `planId state v# latestRun updatedAt`. Right-padded so
99
- * planIds align even when they vary in length. When the list is
100
- * empty, prints a clear "(no plans)" hint instead of just a header.
101
- */
102
- export function formatSummary(plans, workspaceId, stateFilter) {
103
- const lines = [];
104
- const filterTag = stateFilter ? ` (filter: ${stateFilter})` : '';
105
- lines.push(`Plans in workspace ${workspaceId}${filterTag}: ${plans.length}`);
106
- if (plans.length === 0) {
107
- lines.push(' (no plans)');
108
- return lines.join('\n');
109
- }
110
- // Column widths from data — keeps short workspaces compact, won't
111
- // visually break at scale.
112
- const planIdCol = Math.max(8, ...plans.map((p) => p.planId.length));
113
- const nameCol = Math.max(4, ...plans.map((p) => p.name.length));
114
- const header = ` ${'planId'.padEnd(planIdCol)} ${'name'.padEnd(nameCol)} state version latestRun updatedAt`;
115
- lines.push(header);
116
- for (const p of plans) {
117
- const planId = p.planId.padEnd(planIdCol);
118
- const name = p.name.padEnd(nameCol);
119
- const state = p.state.padEnd(8);
120
- const version = `v${p.version}`.padEnd(7);
121
- const latestRun = (p.latestRunId ?? '—').padEnd(9);
122
- lines.push(` ${planId} ${name} ${state} ${version} ${latestRun} ${p.updatedAt}`);
123
- }
124
- return lines.join('\n');
125
- }
126
- function formatJson(plans) {
127
- return JSON.stringify(plans, null, 2);
128
- }
129
- // ─── Helpers ──────────────────────────────────────────────────────────────
130
- function fail(kind, message, detail) {
131
- return { ok: false, kind, message, detail };
132
- }
133
- function describeError(err) {
134
- return err instanceof Error ? err.message : String(err);
135
- }
136
- async function safeReadText(response) {
137
- try {
138
- return await response.text();
139
- }
140
- catch {
141
- return '<no body>';
142
- }
143
- }
144
- export function exitCodeForFailure(kind) {
145
- switch (kind) {
146
- case 'usage':
147
- case 'auth':
148
- case 'workspace_mismatch':
149
- return 64;
150
- case 'http':
151
- return 1;
152
- }
153
- }
package/dist/plan-open.js DELETED
@@ -1,100 +0,0 @@
1
- /**
2
- * `yolo plan open <planId>` — print the webapp Plan-DAG URL for the
3
- * given Plan in the calling session's workspace.
4
- *
5
- * Mints a substrate token to get the workspaceId, calls work.get_plan
6
- * just to confirm the Plan exists (so a typo'd planId surfaces an
7
- * `http` error instead of printing a URL that 404s in the browser),
8
- * then prints the URL. No file I/O, no canonicalization, no Run.
9
- *
10
- * Output modes:
11
- * - default: prints the URL on a single line — handy for piping
12
- * into clipboard tools or `open`.
13
- * - `--json`: emits `{ ok, planId, workspaceId, url }`.
14
- *
15
- * Exit codes (via the CLI wrapper):
16
- * - 0 = success
17
- * - 1 = http (plan not found, etc.)
18
- * - 64 = usage error (bad planId, missing env trio, --workspace
19
- * mismatch, derivation failed)
20
- */
21
- import { SUBSTRATE_CLI_PLAN_SCOPES, WorkClientError, authenticatedRequest, mintSubstrateToken, } from './work-client.js';
22
- import { resolveSubstrateContext } from './auth-context.js';
23
- import { planDagUrl } from './webapp-url.js';
24
- const PLAN_ID_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;
25
- export async function runPlanOpen(options) {
26
- const env = options.env ?? process.env;
27
- if (!PLAN_ID_REGEX.test(options.planId)) {
28
- return fail('usage', `invalid planId '${options.planId}': must match /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/`);
29
- }
30
- const auth = resolveSubstrateContext(env);
31
- if (!auth.ok)
32
- return fail('auth', auth.message);
33
- const { sessionId, commonApiUrl, userToken } = auth.context;
34
- let mint;
35
- try {
36
- mint = await mintSubstrateToken({
37
- commonApiUrl,
38
- userToken,
39
- sessionId,
40
- scopes: SUBSTRATE_CLI_PLAN_SCOPES,
41
- fetchImpl: options.fetchImpl,
42
- });
43
- }
44
- catch (err) {
45
- if (err instanceof WorkClientError) {
46
- return fail('auth', `failed to mint substrate token: ${err.message}`, { status: err.status, code: err.code });
47
- }
48
- return fail('auth', `failed to mint substrate token: ${describeError(err)}`);
49
- }
50
- if (options.workspaceFlag && options.workspaceFlag !== mint.workspaceId) {
51
- return fail('workspace_mismatch', `--workspace ${options.workspaceFlag} does not match the workspace bound to this session (${mint.workspaceId}).`);
52
- }
53
- // Existence check — keeps the CLI honest about typo'd planIds.
54
- // Cheaper than fetching the full plan: just rely on the HTTP status.
55
- const ctx = {
56
- commonApiUrl,
57
- delegatedToken: mint.token,
58
- fetchImpl: options.fetchImpl,
59
- };
60
- const response = await authenticatedRequest(ctx, `/workspaces/${mint.workspaceId}/plans/${options.planId}`, { method: 'GET' });
61
- if (!response.ok) {
62
- const text = await safeReadText(response);
63
- return fail('http', `work.get_plan failed: HTTP ${response.status} — ${text}`, { status: response.status });
64
- }
65
- const url = planDagUrl(env, mint.workspaceId, options.planId);
66
- if (!url) {
67
- return fail('usage', 'could not derive webapp URL from YOLO_COMMON_API_URL — set YOLO_WEBAPP_URL to override.');
68
- }
69
- return {
70
- ok: true,
71
- planId: options.planId,
72
- workspaceId: mint.workspaceId,
73
- url,
74
- output: url,
75
- };
76
- }
77
- function fail(kind, message, detail) {
78
- return { ok: false, kind, message, detail };
79
- }
80
- function describeError(err) {
81
- return err instanceof Error ? err.message : String(err);
82
- }
83
- async function safeReadText(response) {
84
- try {
85
- return await response.text();
86
- }
87
- catch {
88
- return '<no body>';
89
- }
90
- }
91
- export function exitCodeForFailure(kind) {
92
- switch (kind) {
93
- case 'usage':
94
- case 'auth':
95
- case 'workspace_mismatch':
96
- return 64;
97
- case 'http':
98
- return 1;
99
- }
100
- }