@stav-ai/cli 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +71 -2
- package/dist/adapters/adapters.json +16 -0
- package/dist/adapters/index.js +134 -0
- package/dist/auth/pkce.js +12 -0
- package/dist/auth/session.js +228 -0
- package/dist/cli.js +207 -0
- package/dist/config.js +20 -0
- package/dist/errors.js +52 -0
- package/dist/http.js +42 -0
- package/dist/launch.js +248 -0
- package/dist/prompt.js +18 -0
- package/dist/stav.js +60 -0
- package/dist/store/index.js +149 -0
- package/dist/version-compare.js +12 -0
- package/dist/version.js +2 -0
- package/dist/workspace.js +37 -0
- package/package.json +47 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
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 { Stav } from './stav.js';
|
|
20
|
+
import { forgetAppKeys, openStore, readSettings, writeSetting } from './store/index.js';
|
|
21
|
+
import { VERSION } from './version.js';
|
|
22
|
+
import { chooseWorkspace } from './workspace.js';
|
|
23
|
+
const HELP = `stav ${VERSION} — run your coding agent on Stav
|
|
24
|
+
|
|
25
|
+
Usage:
|
|
26
|
+
stav login Sign in through your browser
|
|
27
|
+
stav logout [--forget-keys] Remove the sign-in from this machine
|
|
28
|
+
stav whoami Who you are, and which workspace
|
|
29
|
+
stav workspace [<slug>] Show your workspaces, or choose one
|
|
30
|
+
stav apps The apps this CLI can launch
|
|
31
|
+
stav launch <app> [options] [-- <app arguments>]
|
|
32
|
+
|
|
33
|
+
Launch options:
|
|
34
|
+
--model <id> The model, e.g. zai-org/glm-5-2 (default: the app's Stav default)
|
|
35
|
+
--workspace <slug> The workspace to use for this run
|
|
36
|
+
--yes Do not ask before making the key
|
|
37
|
+
|
|
38
|
+
Environment:
|
|
39
|
+
STAV_API_KEY Use this key; no sign-in and no key is made
|
|
40
|
+
|
|
41
|
+
Examples:
|
|
42
|
+
stav launch claude
|
|
43
|
+
stav launch codex --model zai-org/glm-5-2
|
|
44
|
+
`;
|
|
45
|
+
const out = (line = '') => process.stdout.write(`${line}\n`);
|
|
46
|
+
const err = (line) => process.stderr.write(`${line}\n`);
|
|
47
|
+
async function main(argv) {
|
|
48
|
+
const dash = argv.indexOf('--');
|
|
49
|
+
const own = dash >= 0 ? argv.slice(0, dash) : argv;
|
|
50
|
+
const appArgs = dash >= 0 ? argv.slice(dash + 1) : [];
|
|
51
|
+
const { values, positionals } = parseArgs({
|
|
52
|
+
args: own,
|
|
53
|
+
allowPositionals: true,
|
|
54
|
+
options: {
|
|
55
|
+
model: { type: 'string' },
|
|
56
|
+
workspace: { type: 'string' },
|
|
57
|
+
yes: { type: 'boolean', short: 'y' },
|
|
58
|
+
'forget-keys': { type: 'boolean' },
|
|
59
|
+
help: { type: 'boolean', short: 'h' },
|
|
60
|
+
version: { type: 'boolean', short: 'v' },
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
const [command, ...rest] = positionals;
|
|
64
|
+
if (values.version) {
|
|
65
|
+
out(VERSION);
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
if (values.help || !command || command === 'help') {
|
|
69
|
+
out(HELP);
|
|
70
|
+
return command || values.help ? 0 : 1;
|
|
71
|
+
}
|
|
72
|
+
const cfg = loadConfig();
|
|
73
|
+
const store = await openStore();
|
|
74
|
+
const fetchFn = fetch;
|
|
75
|
+
const stav = new Stav(cfg, fetchFn);
|
|
76
|
+
const token = () => accessToken(fetchFn, cfg, store);
|
|
77
|
+
switch (command) {
|
|
78
|
+
case 'login': {
|
|
79
|
+
await login(fetchFn, cfg, store, defaultIO);
|
|
80
|
+
const t = await token();
|
|
81
|
+
if (t) {
|
|
82
|
+
const all = await stav.workspaces(t);
|
|
83
|
+
const settings = await readSettings();
|
|
84
|
+
if (all.length) {
|
|
85
|
+
let w;
|
|
86
|
+
try {
|
|
87
|
+
w = await chooseWorkspace(all, values.workspace, settings.workspace, terminal);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
// The sign-in itself worked and is saved; only the choice is left.
|
|
91
|
+
if (e instanceof StavError && e.code === 'workspace_required') {
|
|
92
|
+
out(`Signed in. ${e.message}`);
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
throw e;
|
|
96
|
+
}
|
|
97
|
+
await writeSetting('workspace', w.id);
|
|
98
|
+
out(`Signed in. Workspace: ${w.name}.`);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
out('Signed in. You are not in a workspace yet: create one at https://stav.ai/app.');
|
|
102
|
+
}
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
throw new StavError('Sign-in did not finish. Run stav login again.', 'not_signed_in');
|
|
106
|
+
}
|
|
107
|
+
case 'logout': {
|
|
108
|
+
const had = await logout(fetchFn, cfg, store);
|
|
109
|
+
const forgotten = values['forget-keys'] ? await forgetAppKeys(store) : 0;
|
|
110
|
+
await writeSetting('workspace', null);
|
|
111
|
+
out(had ? 'Signed out.' : 'You were not signed in.');
|
|
112
|
+
out(values['forget-keys']
|
|
113
|
+
? `Removed ${forgotten} saved app key${forgotten === 1 ? '' : 's'} from this machine. They still work until revoked in the portal.`
|
|
114
|
+
: 'Saved app keys stay on this machine for the next launch. Remove them with stav logout --forget-keys.');
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
case 'whoami': {
|
|
118
|
+
const envKey = process.env.STAV_API_KEY?.trim();
|
|
119
|
+
if (envKey) {
|
|
120
|
+
const check = await stav.checkKey(envKey);
|
|
121
|
+
if (!check?.valid)
|
|
122
|
+
throw new StavError('The key in STAV_API_KEY does not work.', 'bad_key');
|
|
123
|
+
out(`Using the key in STAV_API_KEY: "${check.api_key_name ?? check.api_key_id}" in workspace ${check.team_name ?? check.team_id}.`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
const t = await token();
|
|
127
|
+
if (!t) {
|
|
128
|
+
out('You are not signed in. Run stav login.');
|
|
129
|
+
return 1;
|
|
130
|
+
}
|
|
131
|
+
const settings = await readSettings();
|
|
132
|
+
const mine = await stav.workspaces(t);
|
|
133
|
+
const chosen = mine.find((w) => w.id === settings.workspace);
|
|
134
|
+
const me = await stav.me(t, chosen?.id);
|
|
135
|
+
const name = [me.first_name, me.last_name].filter(Boolean).join(' ');
|
|
136
|
+
out(`${name ? `${name} <${me.email}>` : me.email}`);
|
|
137
|
+
if (chosen)
|
|
138
|
+
out(`Workspace: ${chosen.name} (${chosen.role.toLowerCase()})`);
|
|
139
|
+
else
|
|
140
|
+
out(mine.length > 1 ? 'No workspace chosen: run stav workspace <slug>.' : mine.length ? `Workspace: ${mine[0].name}` : 'No workspace yet.');
|
|
141
|
+
out(`Keys are kept in: ${store.kind === 'keychain' ? 'your keychain' : 'a file only you can read'}`);
|
|
142
|
+
return 0;
|
|
143
|
+
}
|
|
144
|
+
case 'workspace': {
|
|
145
|
+
const t = await token();
|
|
146
|
+
if (!t)
|
|
147
|
+
throw new StavError('You are not signed in. Run stav login.', 'not_signed_in');
|
|
148
|
+
const all = await stav.workspaces(t);
|
|
149
|
+
const settings = await readSettings();
|
|
150
|
+
if (rest[0]) {
|
|
151
|
+
const w = await chooseWorkspace(all, rest[0], undefined, terminal);
|
|
152
|
+
await writeSetting('workspace', w.id);
|
|
153
|
+
out(`Workspace: ${w.name}.`);
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
for (const w of all)
|
|
157
|
+
out(`${w.id === settings.workspace ? '*' : ' '} ${w.name}${w.slug ? ` (${w.slug})` : ''}, ${w.role.toLowerCase()}`);
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
case 'apps': {
|
|
161
|
+
for (const a of ADAPTERS) {
|
|
162
|
+
for (const slug of a.apps) {
|
|
163
|
+
const app = await stav.app(slug).catch(() => null);
|
|
164
|
+
const state = app?.cli_available ? 'ready' : 'not launchable yet';
|
|
165
|
+
out(`${slug.padEnd(14)} ${a.displayName.padEnd(14)} ${state}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
case 'launch': {
|
|
171
|
+
const app = rest[0];
|
|
172
|
+
if (!app)
|
|
173
|
+
throw new StavError('Say which app: stav launch <app>. Run stav apps to see them.', 'usage');
|
|
174
|
+
const deps = {
|
|
175
|
+
cfg, fetchFn, store, prompter: terminal, env: process.env,
|
|
176
|
+
settings: await readSettings(),
|
|
177
|
+
saveSetting: (n, v) => writeSetting(n, v),
|
|
178
|
+
token,
|
|
179
|
+
signIn: async () => {
|
|
180
|
+
await login(fetchFn, cfg, store, defaultIO);
|
|
181
|
+
},
|
|
182
|
+
which: (p) => which(p),
|
|
183
|
+
spawn: runChild,
|
|
184
|
+
log: err,
|
|
185
|
+
platform: process.platform,
|
|
186
|
+
cwd: process.cwd(),
|
|
187
|
+
};
|
|
188
|
+
return launch({ app, model: values.model, workspace: values.workspace, yes: values.yes, appArgs }, deps);
|
|
189
|
+
}
|
|
190
|
+
default:
|
|
191
|
+
err(`Unknown command "${command}".\n`);
|
|
192
|
+
out(HELP);
|
|
193
|
+
return 1;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
|
|
197
|
+
if (e instanceof StavError) {
|
|
198
|
+
if (e.status === 401 && !['bad_key', 'sign_in_failed'].includes(e.code)) {
|
|
199
|
+
err('stav: Your sign-in has expired or was revoked. Run stav login.');
|
|
200
|
+
process.exit(3);
|
|
201
|
+
}
|
|
202
|
+
err(`stav: ${e.message}`);
|
|
203
|
+
process.exit(e.code === 'session_revoked' ? 3 : 2);
|
|
204
|
+
}
|
|
205
|
+
err(`stav: ${e instanceof Error ? e.message : String(e)}`);
|
|
206
|
+
process.exit(2);
|
|
207
|
+
});
|
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(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
|
+
}
|
package/dist/launch.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `stav launch <app>` (R-19): make or reuse a key for the app, ask once,
|
|
3
|
+
* then start the app pointed at Stav.
|
|
4
|
+
*
|
|
5
|
+
* Order matters: everything that can refuse runs before the question, and
|
|
6
|
+
* nothing changes (no key made, nothing stored) before the person says yes.
|
|
7
|
+
*/
|
|
8
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
9
|
+
import { accessSync, constants, statSync } from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { adapterForApp, MODEL_RE, resolveApp } from './adapters/index.js';
|
|
13
|
+
import { StavError } from './errors.js';
|
|
14
|
+
import { confirm } from './prompt.js';
|
|
15
|
+
import { Stav } from './stav.js';
|
|
16
|
+
import { appKeyName, saveAppKey } from './store/index.js';
|
|
17
|
+
import { compareVersions } from './version-compare.js';
|
|
18
|
+
import { VERSION } from './version.js';
|
|
19
|
+
import { chooseWorkspace } from './workspace.js';
|
|
20
|
+
export const INSTALL_HINT = {
|
|
21
|
+
claude: 'npm install -g @anthropic-ai/claude-code',
|
|
22
|
+
codex: 'npm install -g @openai/codex',
|
|
23
|
+
};
|
|
24
|
+
export async function planLaunch(opts, d) {
|
|
25
|
+
if (d.platform === 'win32') {
|
|
26
|
+
throw new StavError('The Stav CLI does not launch apps on Windows yet. Use WSL, or set the app up by hand: https://stav.ai/apps', 'unsupported_platform');
|
|
27
|
+
}
|
|
28
|
+
const slug = resolveApp(opts.app);
|
|
29
|
+
const adapter = adapterForApp(slug);
|
|
30
|
+
if (!adapter)
|
|
31
|
+
throw new StavError(`The Stav CLI cannot launch "${opts.app}". Run stav apps to see the apps it can.`, 'unknown_app');
|
|
32
|
+
const stav = new Stav(d.cfg, d.fetchFn);
|
|
33
|
+
const app = await stav.app(slug);
|
|
34
|
+
checkLaunchable(app, adapter, slug);
|
|
35
|
+
const model = opts.model ?? app.launch_recipe.default_model ?? null;
|
|
36
|
+
if (model !== null && !MODEL_RE.test(model)) {
|
|
37
|
+
throw new StavError(`"${model}" is not a model id. Use one like zai-org/glm-5-2.`, 'bad_model');
|
|
38
|
+
}
|
|
39
|
+
const programPath = d.which(adapter.program);
|
|
40
|
+
if (!programPath) {
|
|
41
|
+
throw new StavError(`${adapter.displayName} is not installed. Install it with: ${INSTALL_HINT[adapter.program] ?? adapter.program}`, 'not_installed');
|
|
42
|
+
}
|
|
43
|
+
const conflict = adapter.conflicts ? await adapter.conflicts(d.env.HOME, d.cwd) : null;
|
|
44
|
+
if (conflict)
|
|
45
|
+
throw new StavError(conflict, 'settings_conflict');
|
|
46
|
+
// A key in the environment: no sign-in, no key made (B.9).
|
|
47
|
+
const envKey = d.env.STAV_API_KEY?.trim();
|
|
48
|
+
if (envKey)
|
|
49
|
+
return { adapter, slug, model, programPath, key: { secret: envKey, source: 'env' } };
|
|
50
|
+
let token = await d.token();
|
|
51
|
+
if (!token) {
|
|
52
|
+
if (!d.prompter.interactive) {
|
|
53
|
+
throw new StavError('You are not signed in. Run stav login, or set STAV_API_KEY.', 'not_signed_in');
|
|
54
|
+
}
|
|
55
|
+
if (!(await confirm(d.prompter, 'You are not signed in to Stav. Sign in now in your browser?'))) {
|
|
56
|
+
throw new StavError('Not signed in.', 'not_signed_in');
|
|
57
|
+
}
|
|
58
|
+
await d.signIn();
|
|
59
|
+
token = await d.token();
|
|
60
|
+
if (!token)
|
|
61
|
+
throw new StavError('Sign-in did not finish.', 'not_signed_in');
|
|
62
|
+
}
|
|
63
|
+
const workspace = await chooseWorkspace(await stav.workspaces(token), opts.workspace, d.settings.workspace, d.prompter);
|
|
64
|
+
const rememberWorkspace = !opts.workspace && d.settings.workspace !== workspace.id;
|
|
65
|
+
const me = await stav.me(token, workspace.id);
|
|
66
|
+
const person = me.email;
|
|
67
|
+
const role = (me.team_role ?? workspace.role ?? '').toUpperCase();
|
|
68
|
+
const balance = await stav.walletBalance(token, workspace.id);
|
|
69
|
+
if (balance !== null && balance <= 0) {
|
|
70
|
+
throw new StavError(`The workspace ${workspace.name} has no credits, so ${adapter.displayName} would get no answers. Add credits at ${d.cfg.apiUrl}/app/billing, then run this again.`, 'wallet_empty');
|
|
71
|
+
}
|
|
72
|
+
// Saved per workspace, app AND person: another person signed in on the
|
|
73
|
+
// same account never gets this person's key.
|
|
74
|
+
const stored = await readStoredKey(d.store, appKeyName(workspace.id, slug, person));
|
|
75
|
+
if (stored) {
|
|
76
|
+
const check = await stav.checkKey(stored.secret);
|
|
77
|
+
if (check?.valid && check.team_id === workspace.id) {
|
|
78
|
+
return { adapter, slug, model, programPath, key: { secret: stored.secret, source: 'stored' }, workspace, rememberWorkspace, person, token };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const teamKey = role === 'OWNER' || role === 'ADMIN';
|
|
82
|
+
return {
|
|
83
|
+
adapter, slug, model, programPath, workspace, rememberWorkspace, person, token,
|
|
84
|
+
key: { create: true, teamKey, name: `${adapter.displayName} (${me.email})` },
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function checkLaunchable(app, adapter, slug) {
|
|
88
|
+
if (!app) {
|
|
89
|
+
throw new StavError(`${adapter.displayName} is not in the Stav app catalogue yet.`, 'not_launchable');
|
|
90
|
+
}
|
|
91
|
+
const r = app.launch_recipe;
|
|
92
|
+
if (!app.cli_available || !r) {
|
|
93
|
+
throw new StavError(`${adapter.displayName} cannot be launched with the Stav CLI yet. See https://stav.ai/apps/${slug} to set it up by hand.`, 'not_launchable');
|
|
94
|
+
}
|
|
95
|
+
if (r.adapter !== adapter.name) {
|
|
96
|
+
throw new StavError(`Stav launches ${adapter.displayName} in a way this CLI does not know. Update it: npx @stav-ai/cli@latest`, 'update_cli');
|
|
97
|
+
}
|
|
98
|
+
if (compareVersions(VERSION, r.min_cli) < 0) {
|
|
99
|
+
throw new StavError(`Launching ${adapter.displayName} needs Stav CLI ${r.min_cli} or newer (this is ${VERSION}). Update it: npx @stav-ai/cli@latest`, 'update_cli');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function readStoredKey(store, name) {
|
|
103
|
+
const raw = await store.get(name);
|
|
104
|
+
if (!raw)
|
|
105
|
+
return null;
|
|
106
|
+
try {
|
|
107
|
+
const k = JSON.parse(raw);
|
|
108
|
+
return typeof k.secret === 'string' ? k : null;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** The refusal of a key, said so the person knows who can fix it. */
|
|
115
|
+
async function explainRefusal(err, stav, token, teamId, workspaceName) {
|
|
116
|
+
const admins = await stav.admins(token, teamId);
|
|
117
|
+
const who = admins.length ? `An owner or admin (${admins.slice(0, 3).join(', ')}) can change this` : 'An owner or admin of the workspace can change this';
|
|
118
|
+
const policy = `${stav.cfg.apiUrl}/app/api-key-policies`;
|
|
119
|
+
const text = {
|
|
120
|
+
user_keys_not_enabled: `Personal keys are turned off in ${workspaceName}. ${who} under Govern → Key policies (${policy}).`,
|
|
121
|
+
self_service_disabled: `In ${workspaceName}, members cannot make their own personal keys. ${who} under Govern → Key policies (${policy}).`,
|
|
122
|
+
approval_required: `In ${workspaceName}, a personal key needs an admin's approval. Ask for one in the portal (${stav.cfg.apiUrl}/app/api-keys); ${who.toLowerCase()}.`,
|
|
123
|
+
max_user_keys_reached: `You have the most personal keys ${workspaceName} allows. Revoke one you do not use (${stav.cfg.apiUrl}/app/api-keys), or ${who.toLowerCase()}.`,
|
|
124
|
+
max_user_key_seats_reached: `${workspaceName} has used all its personal-key seats. ${who}.`,
|
|
125
|
+
ip_allowlist_required: `${workspaceName} requires an IP allowlist on every workspace key, and the CLI cannot know yours. Make the key in the portal (${stav.cfg.apiUrl}/app/api-keys) and run with STAV_API_KEY.`,
|
|
126
|
+
team_key_limit_reached: `${workspaceName} has the most workspace keys it allows. Revoke one you do not use (${stav.cfg.apiUrl}/app/api-keys).`,
|
|
127
|
+
};
|
|
128
|
+
return text[err.code] ? new StavError(text[err.code], err.code, err.status) : err;
|
|
129
|
+
}
|
|
130
|
+
/** Make the key if the plan says so, store it, and return the secret. */
|
|
131
|
+
export async function settleKey(plan, d) {
|
|
132
|
+
if (!('create' in plan.key))
|
|
133
|
+
return plan.key.secret;
|
|
134
|
+
const stav = new Stav(d.cfg, d.fetchFn);
|
|
135
|
+
const body = { name: plan.key.name, scopes: [...plan.adapter.scopes], client_app: plan.slug };
|
|
136
|
+
let made;
|
|
137
|
+
try {
|
|
138
|
+
made = plan.key.teamKey
|
|
139
|
+
? await stav.createTeamKey(plan.token, plan.workspace.id, body)
|
|
140
|
+
: await stav.createUserKey(plan.token, plan.workspace.id, body);
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
if (err instanceof StavError)
|
|
144
|
+
throw await explainRefusal(err, stav, plan.token, plan.workspace.id, plan.workspace.name);
|
|
145
|
+
throw err;
|
|
146
|
+
}
|
|
147
|
+
await saveAppKey(d.store, appKeyName(plan.workspace.id, plan.slug, plan.person), JSON.stringify({ id: made.id, secret: made.full_key }));
|
|
148
|
+
if (!plan.key.teamKey && !(made.scopes && made.scopes.length)) {
|
|
149
|
+
// A Stav that does not yet set scopes on personal keys makes a key with
|
|
150
|
+
// full access: say so rather than claim it is scoped.
|
|
151
|
+
d.log(`Note: this personal key has full access; your workspace's Stav does not limit personal keys to ${plan.adapter.scopes.join(', ')} yet.`);
|
|
152
|
+
}
|
|
153
|
+
return made.full_key;
|
|
154
|
+
}
|
|
155
|
+
export function describePlan(plan, launch, appArgs, storeKind = 'keychain') {
|
|
156
|
+
const lines = [];
|
|
157
|
+
if (plan.workspace)
|
|
158
|
+
lines.push(`Workspace: ${plan.workspace.name}`);
|
|
159
|
+
if ('create' in plan.key) {
|
|
160
|
+
lines.push(plan.key.teamKey
|
|
161
|
+
? `Make a workspace API key "${plan.key.name}" for ${plan.adapter.displayName}, with access to ${plan.adapter.scopes.join(', ')} only.`
|
|
162
|
+
// A Stav that does not yet limit personal keys makes this key with
|
|
163
|
+
// full access, so this is said before the question, not after.
|
|
164
|
+
: `Make a personal API key "${plan.key.name}" for ${plan.adapter.displayName}, asking for access to ${plan.adapter.scopes.join(', ')} only. If Stav cannot limit personal keys yet, the key has full access to your workspace.`, storeKind === 'keychain'
|
|
165
|
+
? 'Keep it in your keychain (never in this folder), and use it next time.'
|
|
166
|
+
: 'Keep it in a file only you can read (no keychain here; never in this folder), and use it next time.');
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
lines.push(plan.key.source === 'env' ? 'Use the key in STAV_API_KEY.' : `Use your saved ${plan.adapter.displayName} key.`);
|
|
170
|
+
}
|
|
171
|
+
lines.push(`Start ${plan.adapter.displayName} (${plan.programPath}) with:`);
|
|
172
|
+
for (const l of launch.describe)
|
|
173
|
+
lines.push(` ${l}`);
|
|
174
|
+
if (appArgs.length)
|
|
175
|
+
lines.push(` your arguments: ${appArgs.join(' ')}`);
|
|
176
|
+
return lines;
|
|
177
|
+
}
|
|
178
|
+
export async function launch(opts, d) {
|
|
179
|
+
const plan = await planLaunch(opts, d);
|
|
180
|
+
const preview = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: '<key>', model: plan.model });
|
|
181
|
+
for (const line of describePlan(plan, preview, opts.appArgs, d.store.kind))
|
|
182
|
+
d.log(line);
|
|
183
|
+
const changes = 'create' in plan.key;
|
|
184
|
+
if (!opts.yes) {
|
|
185
|
+
if (!d.prompter.interactive) {
|
|
186
|
+
if (changes)
|
|
187
|
+
throw new StavError('This makes an API key. Run it in a terminal, or add --yes.', 'confirm_required');
|
|
188
|
+
}
|
|
189
|
+
else if (!(await confirm(d.prompter, changes ? 'Go ahead?' : 'Start it?'))) {
|
|
190
|
+
d.log('Nothing was changed.');
|
|
191
|
+
return 1;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (plan.workspace && plan.rememberWorkspace)
|
|
195
|
+
await d.saveSetting('workspace', plan.workspace.id);
|
|
196
|
+
const secret = await settleKey(plan, d);
|
|
197
|
+
const run = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: secret, model: plan.model });
|
|
198
|
+
const env = { ...d.env };
|
|
199
|
+
for (const k of run.unset)
|
|
200
|
+
delete env[k];
|
|
201
|
+
Object.assign(env, run.env);
|
|
202
|
+
// An argv array and no shell: nothing in a value is ever run as a command.
|
|
203
|
+
return d.spawn(plan.programPath, [...run.args, ...opts.appArgs], { stdio: 'inherit', env, shell: false });
|
|
204
|
+
}
|
|
205
|
+
/** PATH lookup without a shell. */
|
|
206
|
+
export function which(program, env = process.env) {
|
|
207
|
+
for (const dir of (env.PATH ?? '').split(path.delimiter)) {
|
|
208
|
+
if (!dir)
|
|
209
|
+
continue;
|
|
210
|
+
const full = path.join(dir, program);
|
|
211
|
+
// Absolute PATH entries only: an empty or relative entry would run a
|
|
212
|
+
// program from the current folder.
|
|
213
|
+
if (!path.isAbsolute(dir))
|
|
214
|
+
continue;
|
|
215
|
+
try {
|
|
216
|
+
accessSync(full, constants.X_OK);
|
|
217
|
+
if (!statSync(full).isFile())
|
|
218
|
+
continue;
|
|
219
|
+
return full;
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
// Not here.
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
/** Run the app in the foreground; resolve with its exit code. */
|
|
228
|
+
export function runChild(command, args, options) {
|
|
229
|
+
return new Promise((resolve, reject) => {
|
|
230
|
+
const child = nodeSpawn(command, args, options);
|
|
231
|
+
// Ctrl-C reaches the app by itself (same foreground process group), so
|
|
232
|
+
// the CLI only ignores it; forwarding it too would be a second Ctrl-C,
|
|
233
|
+
// which both apps read as "force quit". TERM and HUP are forwarded.
|
|
234
|
+
const onInt = () => undefined;
|
|
235
|
+
const onTerm = () => child.kill('SIGTERM');
|
|
236
|
+
const onHup = () => child.kill('SIGHUP');
|
|
237
|
+
process.on('SIGINT', onInt);
|
|
238
|
+
process.on('SIGTERM', onTerm);
|
|
239
|
+
process.on('SIGHUP', onHup);
|
|
240
|
+
child.on('error', (err) => reject(new StavError(`Could not start ${command}: ${err.message}`, 'spawn_failed')));
|
|
241
|
+
child.on('exit', (code, signal) => {
|
|
242
|
+
process.off('SIGINT', onInt);
|
|
243
|
+
process.off('SIGTERM', onTerm);
|
|
244
|
+
process.off('SIGHUP', onHup);
|
|
245
|
+
resolve(code ?? (signal ? 128 + (os.constants.signals[signal] ?? 0) : 1));
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
}
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Questions in the terminal. Never asked when there is no terminal. */
|
|
2
|
+
import { createInterface } from 'node:readline/promises';
|
|
3
|
+
export const terminal = {
|
|
4
|
+
interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
5
|
+
async ask(question) {
|
|
6
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
7
|
+
try {
|
|
8
|
+
return (await rl.question(question)).trim();
|
|
9
|
+
}
|
|
10
|
+
finally {
|
|
11
|
+
rl.close();
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
export async function confirm(p, question) {
|
|
16
|
+
const answer = (await p.ask(`${question} [y/N] `)).toLowerCase();
|
|
17
|
+
return answer === 'y' || answer === 'yes';
|
|
18
|
+
}
|
package/dist/stav.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** The Stav calls the CLI makes, typed. */
|
|
2
|
+
import { StavError } from './errors.js';
|
|
3
|
+
import { request } from './http.js';
|
|
4
|
+
export class Stav {
|
|
5
|
+
cfg;
|
|
6
|
+
fetchFn;
|
|
7
|
+
constructor(cfg, fetchFn) {
|
|
8
|
+
this.cfg = cfg;
|
|
9
|
+
this.fetchFn = fetchFn;
|
|
10
|
+
}
|
|
11
|
+
workspaces(token) {
|
|
12
|
+
return request(this.fetchFn, `${this.cfg.apiUrl}/api/settings/me/teams`, { token }).then((w) => w ?? []);
|
|
13
|
+
}
|
|
14
|
+
async me(token, teamId) {
|
|
15
|
+
const me = await request(this.fetchFn, `${this.cfg.apiUrl}/api/auth/me`, { token, teamId });
|
|
16
|
+
if (!me)
|
|
17
|
+
throw new StavError('Stav did not answer who you are.', 'empty');
|
|
18
|
+
return me;
|
|
19
|
+
}
|
|
20
|
+
async walletBalance(token, teamId) {
|
|
21
|
+
const w = await request(this.fetchFn, `${this.cfg.apiUrl}/api/billing/wallet`, { token, teamId, nullOn: [403, 404] });
|
|
22
|
+
return w && typeof w.balance === 'number' ? w.balance : null;
|
|
23
|
+
}
|
|
24
|
+
/** Null while the catalogue is off or the app is unknown (404). */
|
|
25
|
+
app(slug) {
|
|
26
|
+
return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/public/apps/${encodeURIComponent(slug)}`, { nullOn: [404] });
|
|
27
|
+
}
|
|
28
|
+
/** Whether a key still works, and for which workspace. Null when it does not. */
|
|
29
|
+
checkKey(key) {
|
|
30
|
+
return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/auth/validate`, { token: key, nullOn: [401, 403] });
|
|
31
|
+
}
|
|
32
|
+
async createTeamKey(token, teamId, body) {
|
|
33
|
+
const k = await request(this.fetchFn, `${this.cfg.apiUrl}/api/api-keys/`, {
|
|
34
|
+
token, teamId, body: { ...body, environment: 'PRODUCTION' },
|
|
35
|
+
});
|
|
36
|
+
if (!k?.full_key)
|
|
37
|
+
throw new StavError('Stav made no key.', 'empty');
|
|
38
|
+
return k;
|
|
39
|
+
}
|
|
40
|
+
async createUserKey(token, teamId, body) {
|
|
41
|
+
const k = await request(this.fetchFn, `${this.cfg.apiUrl}/api/user-keys/`, {
|
|
42
|
+
token, teamId, body: { ...body, environment: 'PRODUCTION' },
|
|
43
|
+
});
|
|
44
|
+
if (!k?.full_key)
|
|
45
|
+
throw new StavError('Stav made no key.', 'empty');
|
|
46
|
+
return k;
|
|
47
|
+
}
|
|
48
|
+
/** The OWNER and ADMIN emails, to name who can change a policy. */
|
|
49
|
+
async admins(token, teamId) {
|
|
50
|
+
try {
|
|
51
|
+
const page = await request(this.fetchFn, `${this.cfg.apiUrl}/api/teams/current/members?limit=100`, { token, teamId, nullOn: [403, 404] });
|
|
52
|
+
return (page?.items ?? [])
|
|
53
|
+
.filter((m) => (m.role === 'OWNER' || m.role === 'ADMIN') && (m.status ?? 'ACTIVE') === 'ACTIVE')
|
|
54
|
+
.map((m) => m.email);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|