@prave/cli 1.3.0 → 1.4.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.
@@ -0,0 +1,32 @@
1
+ import chalk from 'chalk';
2
+ import open from 'open';
3
+ import { CONFIG } from '../lib/config.js';
4
+ /**
5
+ * `prave docs [slug]` — open the docs in the user's browser.
6
+ *
7
+ * No `slug` → opens https://prave.app/docs
8
+ * Slug given → opens https://prave.app/docs/<slug>
9
+ *
10
+ * No auth needed — the docs are public. The command exists purely so
11
+ * users don't have to alt-tab to a browser, type a URL, and hunt for
12
+ * the right section. From the terminal:
13
+ *
14
+ * prave docs # docs home
15
+ * prave docs cli/run # the Runs CLI reference
16
+ * prave docs web/runs # the Runs dashboard guide
17
+ * prave docs pricing # the plans page
18
+ */
19
+ export async function docsCommand(slug) {
20
+ const cleaned = (slug ?? '').replace(/^\/+|\/+$/g, '').trim();
21
+ // CONFIG.webUrl points at the SPA host (https://prave.app in prod,
22
+ // http://localhost:5173 in dev). Docs always live under /docs.
23
+ const base = CONFIG.webUrl?.replace(/\/$/, '') ?? 'https://prave.app';
24
+ const url = cleaned ? `${base}/docs/${cleaned}` : `${base}/docs`;
25
+ console.log(`${chalk.dim('Opening')} ${chalk.cyan(url)}`);
26
+ try {
27
+ await open(url);
28
+ }
29
+ catch {
30
+ console.log(chalk.dim('(your browser did not open — copy the URL above)'));
31
+ }
32
+ }
@@ -0,0 +1,301 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises';
2
+ import { resolve, relative, basename, sep } from 'node:path';
3
+ import { Buffer } from 'node:buffer';
4
+ import chalk from 'chalk';
5
+ import open from 'open';
6
+ import ora from 'ora';
7
+ import * as tar from 'tar';
8
+ import { request } from 'undici';
9
+ import { isLikelyTextPath, scanForSecrets, } from '@prave/shared';
10
+ import { api, ApiError } from '../lib/api.js';
11
+ import { CONFIG } from '../lib/config.js';
12
+ import { loadCredentials, requireAuth } from '../lib/credentials.js';
13
+ import { log } from '../utils/logger.js';
14
+ /**
15
+ * `prave run` — scheduled server-side skill executions on Prave's
16
+ * infrastructure.
17
+ *
18
+ * prave run deploy [path] # bundle dir → upload → open wizard
19
+ * prave run list # list my deployed runs
20
+ * prave run logs <slug> # tail the most recent execution logs
21
+ *
22
+ * `deploy` is the headline action — the rest just expose the same data
23
+ * the dashboard already shows. The wizard handles schedule + agent
24
+ * selection in the browser because picking from an agent dropdown
25
+ * filtered to "which API keys do I have" is way clearer in a UI than
26
+ * an interactive prompt.
27
+ */
28
+ // Sane-default ignore list for `tar.create` — none of these belong in
29
+ // a deployable bundle and dragging them up adds noise to the scan +
30
+ // bloats storage.
31
+ const TAR_IGNORE = new Set([
32
+ '.git',
33
+ '.github',
34
+ '.next',
35
+ '.turbo',
36
+ '.svelte-kit',
37
+ '.cache',
38
+ 'node_modules',
39
+ 'dist',
40
+ 'build',
41
+ 'coverage',
42
+ '.venv',
43
+ 'venv',
44
+ '__pycache__',
45
+ '.DS_Store',
46
+ ]);
47
+ const MAX_BUNDLE_BYTES = 20 * 1024 * 1024; // matches API + Supabase Storage cap
48
+ const MAX_FILES = 200;
49
+ export async function runDeployCommand(pathArg) {
50
+ const root = resolve(pathArg ?? process.cwd());
51
+ const rootStat = await stat(root).catch(() => null);
52
+ if (!rootStat?.isDirectory()) {
53
+ log.error(`Not a directory: ${root}`);
54
+ process.exit(1);
55
+ }
56
+ // Sanity check — the dir should *look* like a skill project. We don't
57
+ // hard-reject; we just warn if there's no SKILL.md anywhere.
58
+ const skillMd = await findSkillMd(root);
59
+ if (!skillMd) {
60
+ log.warn('No SKILL.md found in this directory. Deploys still work without it, but the runner will not have skill-shaped context for the agent.');
61
+ }
62
+ const creds0 = await requireAuth('prave run');
63
+ if (!creds0)
64
+ return;
65
+ // 1. Local secret-scan BEFORE we ship anything. Cheap defence in
66
+ // depth — even though the API scans again, surfacing the finding
67
+ // pre-upload saves the user a round-trip and avoids briefly storing
68
+ // a secret-bearing tarball in our bucket.
69
+ const localFindings = await preflightScan(root);
70
+ if (localFindings.length > 0) {
71
+ log.error('Bundle contains files that look like secrets:');
72
+ for (const f of localFindings.slice(0, 10)) {
73
+ console.error(` ${chalk.red('•')} ${f.rule} ${chalk.dim(f.path)}${f.line ? `:${f.line}` : ''}`);
74
+ }
75
+ console.error(chalk.dim('\nRemove these files (or scrub the values) and re-run.\n' +
76
+ 'For env vars, ship a .env.example template instead — Prave\n' +
77
+ 'will prompt you for the real values during the wizard.'));
78
+ process.exit(1);
79
+ }
80
+ // 2. Mint the deploy session
81
+ const initSpinner = ora('Opening deploy session…').start();
82
+ let session;
83
+ try {
84
+ const { data } = await api.post('/api/v1/deploy/init', {}, true);
85
+ session = data.session;
86
+ initSpinner.succeed('Session opened');
87
+ }
88
+ catch (err) {
89
+ initSpinner.fail(`Could not open deploy session: ${err.message}`);
90
+ process.exit(1);
91
+ }
92
+ // 3. Pack the directory into a gzipped tar in memory. tar.create's
93
+ // `cwd` option is critical — paths inside the archive must be
94
+ // RELATIVE to the project root, not absolute.
95
+ const packSpinner = ora('Bundling project…').start();
96
+ let tarball;
97
+ try {
98
+ tarball = await packDirectory(root);
99
+ packSpinner.succeed(`Bundled ${formatBytes(tarball.length)}`);
100
+ }
101
+ catch (err) {
102
+ packSpinner.fail(`Bundle failed: ${err.message}`);
103
+ process.exit(1);
104
+ }
105
+ if (tarball.length > MAX_BUNDLE_BYTES) {
106
+ log.error(`Bundle is ${formatBytes(tarball.length)}, cap is ${formatBytes(MAX_BUNDLE_BYTES)}. ` +
107
+ 'Add large files to .gitignore-style noise (or place them in node_modules / .git which we already skip).');
108
+ process.exit(1);
109
+ }
110
+ // 4. Stream the tarball to /deploy/upload. We use undici directly
111
+ // because api.ts only does JSON.
112
+ const uploadSpinner = ora('Uploading to Prave…').start();
113
+ const creds = await loadCredentials();
114
+ if (!creds) {
115
+ uploadSpinner.fail('Credentials expired mid-flight — please re-login.');
116
+ process.exit(1);
117
+ }
118
+ const uploadUrl = `${CONFIG.apiUrl}/api/v1/deploy/upload?session=${encodeURIComponent(session.session_id)}`;
119
+ try {
120
+ const { statusCode, body } = await request(uploadUrl, {
121
+ method: 'POST',
122
+ headers: {
123
+ 'Content-Type': 'application/gzip',
124
+ Authorization: `Bearer ${creds.access_token}`,
125
+ },
126
+ body: tarball,
127
+ });
128
+ const text = await body.text();
129
+ if (statusCode >= 400) {
130
+ const parsed = safeJson(text);
131
+ const msg = parsed?.error ?? `HTTP ${statusCode}`;
132
+ uploadSpinner.fail(`Upload rejected: ${msg}`);
133
+ process.exit(1);
134
+ }
135
+ uploadSpinner.succeed('Upload complete');
136
+ }
137
+ catch (err) {
138
+ uploadSpinner.fail(`Upload failed: ${err.message}`);
139
+ process.exit(1);
140
+ }
141
+ // 5. Open the browser at the wizard
142
+ console.log();
143
+ console.log(chalk.bold('Finish in the browser:'));
144
+ console.log(chalk.cyan(' ' + session.wizard_url));
145
+ try {
146
+ await open(session.wizard_url);
147
+ }
148
+ catch {
149
+ /* user can copy the URL manually */
150
+ }
151
+ }
152
+ export async function runListCommand() {
153
+ if (!(await requireAuth('prave run list')))
154
+ return;
155
+ const spinner = ora('Fetching runs…').start();
156
+ try {
157
+ const { data } = await api.get('/api/v1/runs', true);
158
+ spinner.stop();
159
+ if (!data.runs.length) {
160
+ console.log(chalk.dim('No runs yet. `prave run deploy` to schedule your first one.'));
161
+ return;
162
+ }
163
+ for (const r of data.runs) {
164
+ const nextRun = r.next_run_at
165
+ ? new Date(r.next_run_at).toLocaleString()
166
+ : chalk.dim('paused');
167
+ const status = r.status === 'active'
168
+ ? chalk.green('active')
169
+ : r.status === 'paused'
170
+ ? chalk.yellow('paused')
171
+ : chalk.red(r.status);
172
+ console.log(` ${chalk.bold(r.name)} ${chalk.dim(r.slug)}\n` +
173
+ ` ${chalk.dim(`agent=${r.agent} schedule=${r.schedule_kind} status=${status} next=${nextRun}`)}`);
174
+ }
175
+ }
176
+ catch (err) {
177
+ spinner.fail(err.message);
178
+ process.exit(err instanceof ApiError ? 1 : 1);
179
+ }
180
+ }
181
+ export async function runLogsCommand(slug) {
182
+ if (!(await requireAuth('prave run logs')))
183
+ return;
184
+ const spinner = ora(`Fetching logs for ${slug}…`).start();
185
+ try {
186
+ const { data } = await api.get(`/api/v1/runs/${encodeURIComponent(slug)}/executions?limit=10`, true);
187
+ spinner.stop();
188
+ if (!data.executions.length) {
189
+ console.log(chalk.dim('No executions yet. The first one will appear after the next scheduled fire.'));
190
+ return;
191
+ }
192
+ const latest = data.executions[0];
193
+ const status = latest.status === 'success'
194
+ ? chalk.green(latest.status)
195
+ : latest.status === 'running'
196
+ ? chalk.cyan(latest.status)
197
+ : chalk.red(latest.status);
198
+ console.log(`${chalk.bold(slug)} ${chalk.dim(latest.started_at)} ${status}` +
199
+ (latest.duration_ms !== null ? chalk.dim(` (${latest.duration_ms}ms)`) : ''));
200
+ console.log();
201
+ console.log(latest.log_text ?? chalk.dim('(no log captured)'));
202
+ if (latest.error_message) {
203
+ console.log();
204
+ console.log(chalk.red('Error: ') + latest.error_message);
205
+ }
206
+ }
207
+ catch (err) {
208
+ spinner.fail(err.message);
209
+ process.exit(1);
210
+ }
211
+ }
212
+ // ── helpers ──────────────────────────────────────────────────────────
213
+ async function findSkillMd(root) {
214
+ // Top-level only — most skill projects ship SKILL.md at the root.
215
+ // Deeper search would be wasted work for the warning we'd print.
216
+ try {
217
+ const entries = await readdir(root);
218
+ return entries.find((n) => n.toLowerCase() === 'skill.md') ?? null;
219
+ }
220
+ catch {
221
+ return null;
222
+ }
223
+ }
224
+ async function preflightScan(root) {
225
+ const inputs = [];
226
+ let files = 0;
227
+ let bytes = 0;
228
+ const visit = async (dir) => {
229
+ if (files >= MAX_FILES)
230
+ return;
231
+ if (bytes >= MAX_BUNDLE_BYTES)
232
+ return;
233
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
234
+ for (const entry of entries) {
235
+ if (TAR_IGNORE.has(entry.name))
236
+ continue;
237
+ if (entry.name.startsWith('._'))
238
+ continue;
239
+ const abs = `${dir}${sep}${entry.name}`;
240
+ if (entry.isDirectory()) {
241
+ await visit(abs);
242
+ continue;
243
+ }
244
+ if (!entry.isFile())
245
+ continue;
246
+ files++;
247
+ const rel = relative(root, abs).split(sep).join('/');
248
+ if (!isLikelyTextPath(rel)) {
249
+ inputs.push({ path: rel });
250
+ continue;
251
+ }
252
+ try {
253
+ const content = await readFile(abs, 'utf8');
254
+ bytes += content.length;
255
+ inputs.push({ path: rel, content });
256
+ }
257
+ catch {
258
+ inputs.push({ path: rel });
259
+ }
260
+ }
261
+ };
262
+ await visit(root);
263
+ return scanForSecrets(inputs).findings;
264
+ }
265
+ async function packDirectory(root) {
266
+ // Top-level entries only — tar.create resolves them against `cwd`.
267
+ const entries = (await readdir(root)).filter((n) => !TAR_IGNORE.has(n));
268
+ if (entries.length === 0) {
269
+ throw new Error('Project directory is empty.');
270
+ }
271
+ const stream = tar.create({
272
+ gzip: true,
273
+ cwd: root,
274
+ portable: true,
275
+ // Prefix all paths with the project's basename so the runner
276
+ // gets a `<project>/SKILL.md` shape, not a flat dump at the
277
+ // archive root.
278
+ prefix: basename(root),
279
+ filter: (_path) => true,
280
+ }, entries);
281
+ const chunks = [];
282
+ for await (const chunk of stream) {
283
+ chunks.push(Buffer.from(chunk));
284
+ }
285
+ return Buffer.concat(chunks);
286
+ }
287
+ function formatBytes(n) {
288
+ if (n < 1024)
289
+ return `${n}B`;
290
+ if (n < 1024 * 1024)
291
+ return `${(n / 1024).toFixed(1)}KB`;
292
+ return `${(n / 1024 / 1024).toFixed(2)}MB`;
293
+ }
294
+ function safeJson(text) {
295
+ try {
296
+ return JSON.parse(text);
297
+ }
298
+ catch {
299
+ return null;
300
+ }
301
+ }
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { Command } from 'commander';
6
6
  import { conflictsCommand } from './commands/conflicts.js';
7
7
  import { deployCommand } from './commands/deploy.js';
8
8
  import { diffCommand } from './commands/diff.js';
9
+ import { docsCommand } from './commands/docs.js';
9
10
  import { exportCommand } from './commands/export.js';
10
11
  import { importCommand } from './commands/import.js';
11
12
  import { installCommand } from './commands/install.js';
@@ -16,6 +17,7 @@ import { mcpInstallCommand } from './commands/mcp-install.js';
16
17
  import { mcpServerCommand } from './commands/mcp-server.js';
17
18
  import { optimizeCommand } from './commands/optimize.js';
18
19
  import { overviewCommand } from './commands/overview.js';
20
+ import { runDeployCommand, runListCommand, runLogsCommand, } from './commands/run.js';
19
21
  import { searchCommand } from './commands/search.js';
20
22
  import { settingsCommand } from './commands/settings.js';
21
23
  import { syncCommand } from './commands/sync.js';
@@ -167,6 +169,26 @@ program
167
169
  .command('mcp-server')
168
170
  .description('Run the Prave MCP server over stdio. Wire into Claude Desktop / Cursor MCP / Continue.dev via { "command": "npx", "args": ["-y", "@prave/cli", "mcp-server"] }. Exposes search, install, audit, my-skills, whatdoes as MCP tools.')
169
171
  .action(mcpServerCommand);
172
+ program
173
+ .command('docs [slug]')
174
+ .description('Open the docs in your browser. Bare `prave docs` lands on the home page; `prave docs cli/run` or `prave docs web/runs` jumps straight to a section.')
175
+ .action((slug) => docsCommand(slug));
176
+ // ─── prave run — scheduled server-side executions (Runs) ──────────
177
+ const run = program
178
+ .command('run')
179
+ .description('Schedule a skill to fire on a cron, executed by your chosen AI agent on Prave\'s sandbox. Bring the whole project — SKILL.md, scripts, .env.');
180
+ run
181
+ .command('deploy [path]')
182
+ .description('Bundle the current directory (or `path`), upload it to Prave, and open the browser wizard to pick the schedule + agent.')
183
+ .action((path) => runDeployCommand(path));
184
+ run
185
+ .command('list')
186
+ .description('List your scheduled runs with next-fire time + last status.')
187
+ .action(runListCommand);
188
+ run
189
+ .command('logs <slug>')
190
+ .description('Print the latest execution log for a scheduled run.')
191
+ .action(runLogsCommand);
170
192
  program
171
193
  .command('mcp install')
172
194
  .alias('mcp-install')
@@ -215,6 +237,15 @@ program
215
237
  'Settings',
216
238
  ' prave settings # configure agents + paths',
217
239
  '',
240
+ 'Runs (scheduled cron on Prave)',
241
+ ' prave run deploy # bundle cwd, upload, open wizard',
242
+ ' prave run list # your scheduled runs',
243
+ ' prave run logs <slug> # tail latest execution log',
244
+ '',
245
+ 'Docs',
246
+ ' prave docs # open the docs in your browser',
247
+ ' prave docs <slug> # jump to a section, e.g. cli/run',
248
+ '',
218
249
  'Telemetry',
219
250
  ' PRAVE_TELEMETRY=0 # opt out of CLI usage analytics',
220
251
  '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prave/cli",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Prave CLI — discover, install, version, test, and ship Claude Skills. The developer platform for the complete Skill lifecycle.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -51,11 +51,13 @@
51
51
  "commander": "^12.1.0",
52
52
  "open": "^10.1.0",
53
53
  "ora": "^8.0.1",
54
+ "tar": "^7.4.3",
54
55
  "undici": "^6.18.0",
55
- "@prave/shared": "1.3.0"
56
+ "@prave/shared": "1.4.0"
56
57
  },
57
58
  "devDependencies": {
58
59
  "@types/node": "^20.12.7",
60
+ "@types/tar": "^6.1.13",
59
61
  "tsx": "^4.11.0",
60
62
  "typescript": "^5.4.5"
61
63
  },