@stav-ai/cli 0.0.0-stage → 0.1.1
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/LICENSE +201 -0
- package/README.md +73 -2
- package/dist/adapters/adapters.json +16 -0
- package/dist/adapters/index.js +169 -0
- package/dist/auth/pkce.js +12 -0
- package/dist/auth/session.js +229 -0
- package/dist/cli.js +209 -0
- package/dist/config.js +20 -0
- package/dist/errors.js +52 -0
- package/dist/http.js +42 -0
- package/dist/launch.js +293 -0
- package/dist/prompt.js +19 -0
- package/dist/stav.js +91 -0
- package/dist/store/index.js +149 -0
- package/dist/terminal-text.js +19 -0
- package/dist/version-compare.js +12 -0
- package/dist/version.js +2 -0
- package/dist/workspace.js +38 -0
- package/package.json +47 -4
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in through the browser (R-17, C-4): Auth0 authorization code with
|
|
3
|
+
* PKCE on a loopback redirect, on a native application with no secret.
|
|
4
|
+
*
|
|
5
|
+
* - The listener binds 127.0.0.1 only, on one of three fixed ports (the
|
|
6
|
+
* callback URLs registered on the Auth0 application).
|
|
7
|
+
* - The answer must carry the state we sent; the code is exchanged with the
|
|
8
|
+
* PKCE verifier.
|
|
9
|
+
* - offline_access gives a refresh token, so the browser opens once; a
|
|
10
|
+
* refresh also skips the human check on first login (it ran already).
|
|
11
|
+
*/
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { StavError } from '../errors.js';
|
|
15
|
+
import { USER_AGENT } from '../http.js';
|
|
16
|
+
import { terminalText } from '../terminal-text.js';
|
|
17
|
+
import { challengeOf, newState, newVerifier } from './pkce.js';
|
|
18
|
+
export const CALLBACK_PORTS = [53682, 53683, 53684];
|
|
19
|
+
const SESSION_KEY = 'session';
|
|
20
|
+
const SCOPE = 'openid profile email offline_access';
|
|
21
|
+
function needClientId(cfg) {
|
|
22
|
+
if (!cfg.auth0ClientId) {
|
|
23
|
+
throw new StavError('This build of the Stav CLI has no sign-in application yet. Set STAV_API_KEY to use a key, or STAV_AUTH0_CLIENT_ID.', 'no_client_id');
|
|
24
|
+
}
|
|
25
|
+
return cfg.auth0ClientId;
|
|
26
|
+
}
|
|
27
|
+
async function tokenCall(fetchFn, cfg, body) {
|
|
28
|
+
let res;
|
|
29
|
+
try {
|
|
30
|
+
res = await fetchFn(`https://${cfg.auth0Domain}/oauth/token`, {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': USER_AGENT },
|
|
33
|
+
body: new URLSearchParams(body).toString(),
|
|
34
|
+
signal: AbortSignal.timeout(30_000),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new StavError(`Could not reach ${cfg.auth0Domain}.`, 'network');
|
|
39
|
+
}
|
|
40
|
+
const data = (await res.json().catch(() => ({})));
|
|
41
|
+
if (!res.ok || typeof data.access_token !== 'string') {
|
|
42
|
+
const reason = typeof data.error_description === 'string' ? printable(data.error_description) : `HTTP ${res.status}`;
|
|
43
|
+
throw new StavError(`Sign-in failed: ${reason}`, 'sign_in_failed', res.status);
|
|
44
|
+
}
|
|
45
|
+
return data;
|
|
46
|
+
}
|
|
47
|
+
function toSession(t, previous) {
|
|
48
|
+
return {
|
|
49
|
+
access_token: t.access_token,
|
|
50
|
+
// A rotated refresh token replaces the old one; keep the old one when none came back.
|
|
51
|
+
refresh_token: t.refresh_token ?? previous?.refresh_token,
|
|
52
|
+
expires_at: Math.floor(Date.now() / 1000) + Math.max(0, (t.expires_in ?? 0) - 60),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export async function readSession(store) {
|
|
56
|
+
const raw = await store.get(SESSION_KEY);
|
|
57
|
+
if (!raw)
|
|
58
|
+
return null;
|
|
59
|
+
try {
|
|
60
|
+
const s = JSON.parse(raw);
|
|
61
|
+
return typeof s.access_token === 'string' ? s : null;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** A valid access token, refreshed when it is old; null when not signed in. */
|
|
68
|
+
export async function accessToken(fetchFn, cfg, store) {
|
|
69
|
+
const s = await readSession(store);
|
|
70
|
+
if (!s)
|
|
71
|
+
return null;
|
|
72
|
+
if (s.expires_at > Math.floor(Date.now() / 1000))
|
|
73
|
+
return s.access_token;
|
|
74
|
+
if (!s.refresh_token)
|
|
75
|
+
return null;
|
|
76
|
+
try {
|
|
77
|
+
const t = await tokenCall(fetchFn, cfg, {
|
|
78
|
+
grant_type: 'refresh_token',
|
|
79
|
+
client_id: needClientId(cfg),
|
|
80
|
+
refresh_token: s.refresh_token,
|
|
81
|
+
});
|
|
82
|
+
const next = toSession(t, s);
|
|
83
|
+
await store.set(SESSION_KEY, JSON.stringify(next));
|
|
84
|
+
return next.access_token;
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
// A refused refresh token (expired, revoked) means "sign in again". A
|
|
88
|
+
// network failure or an Auth0 outage is said as what it is.
|
|
89
|
+
if (err instanceof StavError && (err.status === 400 || err.status === 401 || err.status === 403))
|
|
90
|
+
return null;
|
|
91
|
+
throw err instanceof StavError ? err : new StavError(`Could not reach ${cfg.auth0Domain} to renew the sign-in.`, 'network');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export const defaultIO = {
|
|
95
|
+
open(url) {
|
|
96
|
+
const [cmd, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
97
|
+
: process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
98
|
+
: ['xdg-open', [url]];
|
|
99
|
+
try {
|
|
100
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
101
|
+
child.on('error', () => undefined);
|
|
102
|
+
child.unref();
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// The URL is printed too.
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
log: (line) => process.stderr.write(`${terminalText(line)}\n`),
|
|
109
|
+
};
|
|
110
|
+
/** Text from a web page, safe to print: no control characters, bounded. */
|
|
111
|
+
export function printable(text) {
|
|
112
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').slice(0, 300);
|
|
113
|
+
}
|
|
114
|
+
/** Listen on the first free callback port; resolve with the code or reject. */
|
|
115
|
+
function listen(expectedState, timeoutMs) {
|
|
116
|
+
return new Promise((resolveListen, rejectListen) => {
|
|
117
|
+
let resolveCode;
|
|
118
|
+
let rejectCode;
|
|
119
|
+
const code = new Promise((res, rej) => {
|
|
120
|
+
resolveCode = res;
|
|
121
|
+
rejectCode = rej;
|
|
122
|
+
});
|
|
123
|
+
const server = http.createServer((req, res) => {
|
|
124
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
125
|
+
if (url.pathname !== '/callback') {
|
|
126
|
+
res.writeHead(404).end();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
// Only an answer with our state counts. Anything else (a stray tab, a
|
|
130
|
+
// page that knows the port) is ignored, and the CLI keeps waiting.
|
|
131
|
+
if (url.searchParams.get('state') !== expectedState) {
|
|
132
|
+
res.writeHead(400, { 'Content-Type': 'text/plain' }).end('This is not the sign-in the Stav CLI started.');
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const page = (title) => `<!doctype html><meta charset="utf-8"><title>Stav CLI</title><body style="font-family:system-ui;margin:4rem"><h1>${title}</h1><p>You can close this tab and go back to the terminal.</p></body>`;
|
|
136
|
+
const err = url.searchParams.get('error');
|
|
137
|
+
if (err) {
|
|
138
|
+
res.writeHead(400, { 'Content-Type': 'text/html' }).end(page('Sign-in was not completed'));
|
|
139
|
+
rejectCode(new StavError(`Sign-in was not completed: ${printable(url.searchParams.get('error_description') ?? err)}`, 'sign_in_failed'));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const got = url.searchParams.get('code');
|
|
143
|
+
if (!got) {
|
|
144
|
+
res.writeHead(400).end();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
res.writeHead(200, { 'Content-Type': 'text/html' }).end(page('You are signed in to Stav'));
|
|
148
|
+
resolveCode(got);
|
|
149
|
+
});
|
|
150
|
+
const timer = setTimeout(() => rejectCode(new StavError('Sign-in timed out. Run stav login again.', 'timeout')), timeoutMs);
|
|
151
|
+
timer.unref();
|
|
152
|
+
const close = () => {
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
server.close();
|
|
155
|
+
};
|
|
156
|
+
const tryPort = (i) => {
|
|
157
|
+
if (i >= CALLBACK_PORTS.length) {
|
|
158
|
+
rejectListen(new StavError(`Ports ${CALLBACK_PORTS.join(', ')} on 127.0.0.1 are all in use.`, 'ports_busy'));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const port = CALLBACK_PORTS[i];
|
|
162
|
+
const onListening = () => {
|
|
163
|
+
server.off('error', onError);
|
|
164
|
+
resolveListen({ port, code, close });
|
|
165
|
+
};
|
|
166
|
+
const onError = () => {
|
|
167
|
+
// A busy port: drop this attempt's listener, or a later success
|
|
168
|
+
// would report this port to Auth0.
|
|
169
|
+
server.off('listening', onListening);
|
|
170
|
+
tryPort(i + 1);
|
|
171
|
+
};
|
|
172
|
+
server.once('error', onError);
|
|
173
|
+
server.once('listening', onListening);
|
|
174
|
+
server.listen(port, '127.0.0.1');
|
|
175
|
+
};
|
|
176
|
+
tryPort(0);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
export async function login(fetchFn, cfg, store, io = defaultIO, timeoutMs = 5 * 60_000) {
|
|
180
|
+
const clientId = needClientId(cfg);
|
|
181
|
+
const verifier = newVerifier();
|
|
182
|
+
const state = newState();
|
|
183
|
+
const listener = await listen(state, timeoutMs);
|
|
184
|
+
try {
|
|
185
|
+
const redirectUri = `http://127.0.0.1:${listener.port}/callback`;
|
|
186
|
+
const url = new URL(`https://${cfg.auth0Domain}/authorize`);
|
|
187
|
+
url.search = new URLSearchParams({
|
|
188
|
+
response_type: 'code',
|
|
189
|
+
client_id: clientId,
|
|
190
|
+
redirect_uri: redirectUri,
|
|
191
|
+
audience: cfg.auth0Audience,
|
|
192
|
+
scope: SCOPE,
|
|
193
|
+
code_challenge: challengeOf(verifier),
|
|
194
|
+
code_challenge_method: 'S256',
|
|
195
|
+
state,
|
|
196
|
+
}).toString();
|
|
197
|
+
io.log('Opening your browser to sign in to Stav. If it does not open, visit:');
|
|
198
|
+
io.log(url.toString());
|
|
199
|
+
io.open(url.toString());
|
|
200
|
+
const code = await listener.code;
|
|
201
|
+
const t = await tokenCall(fetchFn, cfg, {
|
|
202
|
+
grant_type: 'authorization_code',
|
|
203
|
+
client_id: clientId,
|
|
204
|
+
code,
|
|
205
|
+
code_verifier: verifier,
|
|
206
|
+
redirect_uri: redirectUri,
|
|
207
|
+
});
|
|
208
|
+
const session = toSession(t);
|
|
209
|
+
await store.set(SESSION_KEY, JSON.stringify(session));
|
|
210
|
+
return session;
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
listener.close();
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** Remove the sign-in here and revoke its refresh token at Auth0. */
|
|
217
|
+
export async function logout(fetchFn, cfg, store) {
|
|
218
|
+
const s = await readSession(store);
|
|
219
|
+
await store.delete(SESSION_KEY);
|
|
220
|
+
if (s?.refresh_token && cfg.auth0ClientId) {
|
|
221
|
+
await fetchFn(`https://${cfg.auth0Domain}/oauth/revoke`, {
|
|
222
|
+
method: 'POST',
|
|
223
|
+
headers: { 'Content-Type': 'application/json', 'User-Agent': USER_AGENT },
|
|
224
|
+
body: JSON.stringify({ client_id: cfg.auth0ClientId, token: s.refresh_token }),
|
|
225
|
+
signal: AbortSignal.timeout(15_000),
|
|
226
|
+
}).catch(() => undefined);
|
|
227
|
+
}
|
|
228
|
+
return s !== null;
|
|
229
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* stav — run your coding agent on Stav (apps run on Stav P3, R-17..R-22).
|
|
4
|
+
*
|
|
5
|
+
* stav login | logout | whoami
|
|
6
|
+
* stav workspace [<slug>]
|
|
7
|
+
* stav apps
|
|
8
|
+
* stav launch <app> [--model <id>] [--workspace <slug>] [--yes] [-- <app arguments>]
|
|
9
|
+
*
|
|
10
|
+
* No telemetry (spec B.9).
|
|
11
|
+
*/
|
|
12
|
+
import { parseArgs } from 'node:util';
|
|
13
|
+
import { ADAPTERS } from './adapters/index.js';
|
|
14
|
+
import { accessToken, defaultIO, login, logout } from './auth/session.js';
|
|
15
|
+
import { loadConfig } from './config.js';
|
|
16
|
+
import { StavError } from './errors.js';
|
|
17
|
+
import { launch, runChild, which } from './launch.js';
|
|
18
|
+
import { terminal } from './prompt.js';
|
|
19
|
+
import { terminalText } from './terminal-text.js';
|
|
20
|
+
import { Stav } from './stav.js';
|
|
21
|
+
import { forgetAppKeys, openStore, readSettings, writeSetting } from './store/index.js';
|
|
22
|
+
import { VERSION } from './version.js';
|
|
23
|
+
import { chooseWorkspace } from './workspace.js';
|
|
24
|
+
const HELP = `stav ${VERSION} — run your coding agent on Stav
|
|
25
|
+
|
|
26
|
+
Usage:
|
|
27
|
+
stav login Sign in through your browser
|
|
28
|
+
stav logout [--forget-keys] Remove the sign-in from this machine
|
|
29
|
+
stav whoami Who you are, and which workspace
|
|
30
|
+
stav workspace [<slug>] Show your workspaces, or choose one
|
|
31
|
+
stav apps The apps this CLI can launch
|
|
32
|
+
stav launch <app> [options] [-- <app arguments>]
|
|
33
|
+
|
|
34
|
+
Launch options:
|
|
35
|
+
--model <id> The model, e.g. zai-org/glm-5-2 (default: the app's Stav default)
|
|
36
|
+
--workspace <slug> The workspace to use for this run
|
|
37
|
+
--yes Do not ask before making the key
|
|
38
|
+
|
|
39
|
+
Environment:
|
|
40
|
+
STAV_API_KEY Use this key; no sign-in and no key is made
|
|
41
|
+
|
|
42
|
+
Examples:
|
|
43
|
+
stav launch claude
|
|
44
|
+
stav launch codex --model zai-org/glm-5-2
|
|
45
|
+
`;
|
|
46
|
+
// Every line goes through terminalText: much of it is text from the Stav API.
|
|
47
|
+
const out = (line = '') => process.stdout.write(`${terminalText(line)}\n`);
|
|
48
|
+
const err = (line) => process.stderr.write(`${terminalText(line)}\n`);
|
|
49
|
+
async function main(argv) {
|
|
50
|
+
const dash = argv.indexOf('--');
|
|
51
|
+
const own = dash >= 0 ? argv.slice(0, dash) : argv;
|
|
52
|
+
const appArgs = dash >= 0 ? argv.slice(dash + 1) : [];
|
|
53
|
+
const { values, positionals } = parseArgs({
|
|
54
|
+
args: own,
|
|
55
|
+
allowPositionals: true,
|
|
56
|
+
options: {
|
|
57
|
+
model: { type: 'string' },
|
|
58
|
+
workspace: { type: 'string' },
|
|
59
|
+
yes: { type: 'boolean', short: 'y' },
|
|
60
|
+
'forget-keys': { type: 'boolean' },
|
|
61
|
+
help: { type: 'boolean', short: 'h' },
|
|
62
|
+
version: { type: 'boolean', short: 'v' },
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
const [command, ...rest] = positionals;
|
|
66
|
+
if (values.version) {
|
|
67
|
+
out(VERSION);
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
if (values.help || !command || command === 'help') {
|
|
71
|
+
out(HELP);
|
|
72
|
+
return command || values.help ? 0 : 1;
|
|
73
|
+
}
|
|
74
|
+
const cfg = loadConfig();
|
|
75
|
+
const store = await openStore();
|
|
76
|
+
const fetchFn = fetch;
|
|
77
|
+
const stav = new Stav(cfg, fetchFn);
|
|
78
|
+
const token = () => accessToken(fetchFn, cfg, store);
|
|
79
|
+
switch (command) {
|
|
80
|
+
case 'login': {
|
|
81
|
+
await login(fetchFn, cfg, store, defaultIO);
|
|
82
|
+
const t = await token();
|
|
83
|
+
if (t) {
|
|
84
|
+
const all = await stav.workspaces(t);
|
|
85
|
+
const settings = await readSettings();
|
|
86
|
+
if (all.length) {
|
|
87
|
+
let w;
|
|
88
|
+
try {
|
|
89
|
+
w = await chooseWorkspace(all, values.workspace, settings.workspace, terminal);
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
// The sign-in itself worked and is saved; only the choice is left.
|
|
93
|
+
if (e instanceof StavError && e.code === 'workspace_required') {
|
|
94
|
+
out(`Signed in. ${e.message}`);
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
throw e;
|
|
98
|
+
}
|
|
99
|
+
await writeSetting('workspace', w.id);
|
|
100
|
+
out(`Signed in. Workspace: ${w.name}.`);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
out('Signed in. You are not in a workspace yet: create one at https://stav.ai/app.');
|
|
104
|
+
}
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
throw new StavError('Sign-in did not finish. Run stav login again.', 'not_signed_in');
|
|
108
|
+
}
|
|
109
|
+
case 'logout': {
|
|
110
|
+
const had = await logout(fetchFn, cfg, store);
|
|
111
|
+
const forgotten = values['forget-keys'] ? await forgetAppKeys(store) : 0;
|
|
112
|
+
await writeSetting('workspace', null);
|
|
113
|
+
out(had ? 'Signed out.' : 'You were not signed in.');
|
|
114
|
+
out(values['forget-keys']
|
|
115
|
+
? `Removed ${forgotten} saved app key${forgotten === 1 ? '' : 's'} from this machine. They still work until revoked in the portal.`
|
|
116
|
+
: 'Saved app keys stay on this machine for the next launch. Remove them with stav logout --forget-keys.');
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
case 'whoami': {
|
|
120
|
+
const envKey = process.env.STAV_API_KEY?.trim();
|
|
121
|
+
if (envKey) {
|
|
122
|
+
const check = await stav.checkKey(envKey);
|
|
123
|
+
if (!check?.valid)
|
|
124
|
+
throw new StavError('The key in STAV_API_KEY does not work.', 'bad_key');
|
|
125
|
+
out(`Using the key in STAV_API_KEY: "${check.api_key_name ?? check.api_key_id}" in workspace ${check.team_name ?? check.team_id}.`);
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
const t = await token();
|
|
129
|
+
if (!t) {
|
|
130
|
+
out('You are not signed in. Run stav login.');
|
|
131
|
+
return 1;
|
|
132
|
+
}
|
|
133
|
+
const settings = await readSettings();
|
|
134
|
+
const mine = await stav.workspaces(t);
|
|
135
|
+
const chosen = mine.find((w) => w.id === settings.workspace);
|
|
136
|
+
const me = await stav.me(t, chosen?.id);
|
|
137
|
+
const name = [me.first_name, me.last_name].filter(Boolean).join(' ');
|
|
138
|
+
out(`${name ? `${name} <${me.email}>` : me.email}`);
|
|
139
|
+
if (chosen)
|
|
140
|
+
out(`Workspace: ${chosen.name} (${chosen.role.toLowerCase()})`);
|
|
141
|
+
else
|
|
142
|
+
out(mine.length > 1 ? 'No workspace chosen: run stav workspace <slug>.' : mine.length ? `Workspace: ${mine[0].name}` : 'No workspace yet.');
|
|
143
|
+
out(`Keys are kept in: ${store.kind === 'keychain' ? 'your keychain' : 'a file only you can read'}`);
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
case 'workspace': {
|
|
147
|
+
const t = await token();
|
|
148
|
+
if (!t)
|
|
149
|
+
throw new StavError('You are not signed in. Run stav login.', 'not_signed_in');
|
|
150
|
+
const all = await stav.workspaces(t);
|
|
151
|
+
const settings = await readSettings();
|
|
152
|
+
if (rest[0]) {
|
|
153
|
+
const w = await chooseWorkspace(all, rest[0], undefined, terminal);
|
|
154
|
+
await writeSetting('workspace', w.id);
|
|
155
|
+
out(`Workspace: ${w.name}.`);
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
|
158
|
+
for (const w of all)
|
|
159
|
+
out(`${w.id === settings.workspace ? '*' : ' '} ${w.name}${w.slug ? ` (${w.slug})` : ''}, ${w.role.toLowerCase()}`);
|
|
160
|
+
return 0;
|
|
161
|
+
}
|
|
162
|
+
case 'apps': {
|
|
163
|
+
for (const a of ADAPTERS) {
|
|
164
|
+
for (const slug of a.apps) {
|
|
165
|
+
const app = await stav.app(slug).catch(() => null);
|
|
166
|
+
const state = app?.cli_available ? 'ready' : 'not launchable yet';
|
|
167
|
+
out(`${slug.padEnd(14)} ${a.displayName.padEnd(14)} ${state}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
172
|
+
case 'launch': {
|
|
173
|
+
const app = rest[0];
|
|
174
|
+
if (!app)
|
|
175
|
+
throw new StavError('Say which app: stav launch <app>. Run stav apps to see them.', 'usage');
|
|
176
|
+
const deps = {
|
|
177
|
+
cfg, fetchFn, store, prompter: terminal, env: process.env,
|
|
178
|
+
settings: await readSettings(),
|
|
179
|
+
saveSetting: (n, v) => writeSetting(n, v),
|
|
180
|
+
token,
|
|
181
|
+
signIn: async () => {
|
|
182
|
+
await login(fetchFn, cfg, store, defaultIO);
|
|
183
|
+
},
|
|
184
|
+
which: (p) => which(p),
|
|
185
|
+
spawn: runChild,
|
|
186
|
+
log: err,
|
|
187
|
+
platform: process.platform,
|
|
188
|
+
cwd: process.cwd(),
|
|
189
|
+
};
|
|
190
|
+
return launch({ app, model: values.model, workspace: values.workspace, yes: values.yes, appArgs }, deps);
|
|
191
|
+
}
|
|
192
|
+
default:
|
|
193
|
+
err(`Unknown command "${command}".\n`);
|
|
194
|
+
out(HELP);
|
|
195
|
+
return 1;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
|
|
199
|
+
if (e instanceof StavError) {
|
|
200
|
+
if (e.status === 401 && !['bad_key', 'sign_in_failed'].includes(e.code)) {
|
|
201
|
+
err('stav: Your sign-in has expired or was revoked. Run stav login.');
|
|
202
|
+
process.exit(3);
|
|
203
|
+
}
|
|
204
|
+
err(`stav: ${e.message}`);
|
|
205
|
+
process.exit(e.code === 'session_revoked' ? 3 : 2);
|
|
206
|
+
}
|
|
207
|
+
err(`stav: ${e instanceof Error ? e.message : String(e)}`);
|
|
208
|
+
process.exit(2);
|
|
209
|
+
});
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the CLI talks to. Production is compiled in; every value can be
|
|
3
|
+
* overridden from the environment (staging, a local stack). No internal or
|
|
4
|
+
* staging host is written in this public package.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* The Auth0 native application "Stav CLI" (tenant stav-eu, no secret,
|
|
8
|
+
* PKCE, 127.0.0.1 callbacks). A client id is public by design.
|
|
9
|
+
*/
|
|
10
|
+
export const PROD_AUTH0_CLIENT_ID = 'AFfwAgHuE4yxYJzDW24lxzwfnV746UY6';
|
|
11
|
+
export function loadConfig(env = process.env) {
|
|
12
|
+
const trim = (v, fallback) => (v && v.trim() ? v.trim().replace(/\/+$/, '') : fallback);
|
|
13
|
+
return {
|
|
14
|
+
apiUrl: trim(env.STAV_API_URL, 'https://stav.ai'),
|
|
15
|
+
gatewayUrl: trim(env.STAV_GATEWAY_URL, 'https://api.stav.ai'),
|
|
16
|
+
auth0Domain: trim(env.STAV_AUTH0_DOMAIN, 'auth.stav.ai'),
|
|
17
|
+
auth0ClientId: trim(env.STAV_AUTH0_CLIENT_ID, PROD_AUTH0_CLIENT_ID),
|
|
18
|
+
auth0Audience: trim(env.STAV_AUTH0_AUDIENCE, 'https://api.stav.ai') + '/',
|
|
19
|
+
};
|
|
20
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** An error the CLI shows as one plain message, with a code for scripts. */
|
|
2
|
+
export class StavError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
constructor(message, code = 'error', status) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.name = 'StavError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The three error shapes the Stav API answers with:
|
|
14
|
+
* {"detail": "text"}
|
|
15
|
+
* {"detail": {"code": "...", "message": "..."}}
|
|
16
|
+
* {"detail": {"error": {"code": "...", "message": "...", "type": "..."}}}
|
|
17
|
+
* The gateway answers {"error": {"code", "message"}}.
|
|
18
|
+
*/
|
|
19
|
+
export function readError(status, body) {
|
|
20
|
+
const pick = (o) => {
|
|
21
|
+
if (!o || typeof o !== 'object')
|
|
22
|
+
return null;
|
|
23
|
+
const r = o;
|
|
24
|
+
if (typeof r.code === 'string' || typeof r.message === 'string') {
|
|
25
|
+
return { code: typeof r.code === 'string' ? r.code : undefined, message: typeof r.message === 'string' ? r.message : undefined };
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
};
|
|
29
|
+
let code;
|
|
30
|
+
let message;
|
|
31
|
+
if (body && typeof body === 'object') {
|
|
32
|
+
const b = body;
|
|
33
|
+
const detail = b.detail;
|
|
34
|
+
if (typeof detail === 'string')
|
|
35
|
+
message = detail;
|
|
36
|
+
else if (detail && typeof detail === 'object') {
|
|
37
|
+
const d = detail;
|
|
38
|
+
const inner = pick(d.error) ?? pick(d);
|
|
39
|
+
code = inner?.code;
|
|
40
|
+
message = inner?.message;
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
const inner = pick(b.error);
|
|
44
|
+
code = inner?.code;
|
|
45
|
+
message = inner?.message;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
else if (typeof body === 'string' && body.trim()) {
|
|
49
|
+
message = body.trim().slice(0, 300);
|
|
50
|
+
}
|
|
51
|
+
return new StavError(message || `Stav answered HTTP ${status}`, code || `http_${status}`, status);
|
|
52
|
+
}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one HTTP client. Global fetch (Node 22+), a User-Agent that names the
|
|
3
|
+
* CLI (audited as origin "api" in Stav), and every Stav error shape turned
|
|
4
|
+
* into a StavError.
|
|
5
|
+
*/
|
|
6
|
+
import { readError, StavError } from './errors.js';
|
|
7
|
+
import { VERSION } from './version.js';
|
|
8
|
+
export const USER_AGENT = `stav-cli/${VERSION} (${process.platform}; node ${process.versions.node})`;
|
|
9
|
+
export async function request(fetchFn, url, opts = {}) {
|
|
10
|
+
const headers = { 'User-Agent': USER_AGENT, Accept: 'application/json' };
|
|
11
|
+
if (opts.token)
|
|
12
|
+
headers.Authorization = `Bearer ${opts.token}`;
|
|
13
|
+
if (opts.teamId)
|
|
14
|
+
headers['X-Team-Id'] = opts.teamId;
|
|
15
|
+
if (opts.body !== undefined)
|
|
16
|
+
headers['Content-Type'] = 'application/json';
|
|
17
|
+
let res;
|
|
18
|
+
try {
|
|
19
|
+
res = await fetchFn(url, {
|
|
20
|
+
method: opts.method ?? (opts.body !== undefined ? 'POST' : 'GET'),
|
|
21
|
+
headers,
|
|
22
|
+
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
23
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
throw new StavError(`Could not reach ${new URL(url).host}: ${err instanceof Error ? err.message : String(err)}`, 'network');
|
|
28
|
+
}
|
|
29
|
+
const text = await res.text();
|
|
30
|
+
let body = text;
|
|
31
|
+
try {
|
|
32
|
+
body = text ? JSON.parse(text) : null;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// Not JSON: keep the text for the error message.
|
|
36
|
+
}
|
|
37
|
+
if (res.ok)
|
|
38
|
+
return body;
|
|
39
|
+
if (opts.nullOn?.includes(res.status))
|
|
40
|
+
return null;
|
|
41
|
+
throw readError(res.status, body);
|
|
42
|
+
}
|