@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
package/dist/launch.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
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 orWorkspaceKey = role === 'OWNER' || role === 'ADMIN';
|
|
82
|
+
return {
|
|
83
|
+
adapter, slug, model, programPath, workspace, rememberWorkspace, person, token,
|
|
84
|
+
key: { create: true, orWorkspaceKey, 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
|
+
/**
|
|
131
|
+
* The refusals of a personal key that come from the workspace's key policy.
|
|
132
|
+
* Each is a 403 that makes nothing, so trying a workspace key after it
|
|
133
|
+
* leaves no half-made key behind.
|
|
134
|
+
*/
|
|
135
|
+
export const POLICY_REFUSALS = new Map([
|
|
136
|
+
['user_keys_not_enabled', 'personal keys are turned off'],
|
|
137
|
+
['self_service_disabled', 'members cannot make their own personal keys'],
|
|
138
|
+
['approval_required', 'a personal key needs an approval'],
|
|
139
|
+
['max_user_keys_reached', 'you have the most personal keys it allows'],
|
|
140
|
+
['max_user_key_seats_reached', 'all its personal-key seats are used'],
|
|
141
|
+
]);
|
|
142
|
+
/** Make the key if the plan says so, store it, and return the secret. */
|
|
143
|
+
export async function settleKey(plan, d) {
|
|
144
|
+
if (!('create' in plan.key))
|
|
145
|
+
return plan.key.secret;
|
|
146
|
+
const stav = new Stav(d.cfg, d.fetchFn);
|
|
147
|
+
const body = { name: plan.key.name, scopes: [...plan.adapter.scopes], client_app: plan.slug };
|
|
148
|
+
const refused = async (err) => err instanceof StavError ? explainRefusal(err, stav, plan.token, plan.workspace.id, plan.workspace.name) : err;
|
|
149
|
+
let made;
|
|
150
|
+
let personal = true;
|
|
151
|
+
try {
|
|
152
|
+
made = await stav.createUserKey(plan.token, plan.workspace.id, body);
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
if (!plan.key.orWorkspaceKey || !(err instanceof StavError) || !POLICY_REFUSALS.has(err.code))
|
|
156
|
+
throw await refused(err);
|
|
157
|
+
d.log(`In ${plan.workspace.name}, ${POLICY_REFUSALS.get(err.code)}, so a workspace key is made instead.`);
|
|
158
|
+
personal = false;
|
|
159
|
+
try {
|
|
160
|
+
made = await stav.createTeamKey(plan.token, plan.workspace.id, body);
|
|
161
|
+
}
|
|
162
|
+
catch (err2) {
|
|
163
|
+
throw await refused(err2);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
await saveAppKey(d.store, appKeyName(plan.workspace.id, plan.slug, plan.person), JSON.stringify({ id: made.id, secret: made.full_key }));
|
|
167
|
+
if (personal && !(made.scopes && made.scopes.length)) {
|
|
168
|
+
// A Stav that does not yet set scopes on personal keys makes a key with
|
|
169
|
+
// full access: say so rather than claim it is scoped.
|
|
170
|
+
d.log(`Note: this personal key has full access; your workspace's Stav does not limit personal keys to ${plan.adapter.scopes.join(', ')} yet.`);
|
|
171
|
+
}
|
|
172
|
+
return made.full_key;
|
|
173
|
+
}
|
|
174
|
+
export function describePlan(plan, launch, appArgs, storeKind = 'keychain') {
|
|
175
|
+
const lines = [];
|
|
176
|
+
if (plan.workspace)
|
|
177
|
+
lines.push(`Workspace: ${plan.workspace.name}`);
|
|
178
|
+
if ('create' in plan.key) {
|
|
179
|
+
// A Stav that does not yet limit personal keys makes this key with
|
|
180
|
+
// full access, so this is said before the question, not after.
|
|
181
|
+
lines.push(`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.`);
|
|
182
|
+
if (plan.key.orWorkspaceKey) {
|
|
183
|
+
lines.push(`If ${plan.workspace.name} does not allow personal keys, make a workspace API key with the same name and access instead.`);
|
|
184
|
+
}
|
|
185
|
+
lines.push(storeKind === 'keychain'
|
|
186
|
+
? 'Keep it in your keychain (never in this folder), and use it next time.'
|
|
187
|
+
: 'Keep it in a file only you can read (no keychain here; never in this folder), and use it next time.');
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
lines.push(plan.key.source === 'env' ? 'Use the key in STAV_API_KEY.' : `Use your saved ${plan.adapter.displayName} key.`);
|
|
191
|
+
}
|
|
192
|
+
lines.push(`Start ${plan.adapter.displayName} (${plan.programPath}) with:`);
|
|
193
|
+
for (const l of launch.describe)
|
|
194
|
+
lines.push(` ${l}`);
|
|
195
|
+
if (appArgs.length)
|
|
196
|
+
lines.push(` your arguments: ${appArgs.join(' ')}`);
|
|
197
|
+
return lines;
|
|
198
|
+
}
|
|
199
|
+
export async function launch(opts, d) {
|
|
200
|
+
const plan = await planLaunch(opts, d);
|
|
201
|
+
const preview = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: '<key>', model: plan.model });
|
|
202
|
+
for (const line of describePlan(plan, preview, opts.appArgs, d.store.kind))
|
|
203
|
+
d.log(line);
|
|
204
|
+
const changes = 'create' in plan.key;
|
|
205
|
+
if (!opts.yes) {
|
|
206
|
+
if (!d.prompter.interactive) {
|
|
207
|
+
if (changes)
|
|
208
|
+
throw new StavError('This makes an API key. Run it in a terminal, or add --yes.', 'confirm_required');
|
|
209
|
+
}
|
|
210
|
+
else if (!(await confirm(d.prompter, changes ? 'Go ahead?' : 'Start it?'))) {
|
|
211
|
+
d.log('Nothing was changed.');
|
|
212
|
+
return 1;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (plan.workspace && plan.rememberWorkspace)
|
|
216
|
+
await d.saveSetting('workspace', plan.workspace.id);
|
|
217
|
+
const secret = await settleKey(plan, d);
|
|
218
|
+
const contextWindow = await readContextWindow(plan, secret, d);
|
|
219
|
+
const run = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: secret, model: plan.model, contextWindow });
|
|
220
|
+
const env = { ...d.env };
|
|
221
|
+
for (const k of run.unset)
|
|
222
|
+
delete env[k];
|
|
223
|
+
Object.assign(env, run.env);
|
|
224
|
+
// An argv array and no shell: nothing in a value is ever run as a command.
|
|
225
|
+
return d.spawn(plan.programPath, [...run.args, ...opts.appArgs], { stdio: 'inherit', env, shell: false });
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The model's context window for this workspace, when the adapter wants it.
|
|
229
|
+
* Never stops the launch: without it the app keeps its own assumption, and
|
|
230
|
+
* the person is told.
|
|
231
|
+
*/
|
|
232
|
+
async function readContextWindow(plan, key, d) {
|
|
233
|
+
if (!plan.model || !plan.adapter.wantsContextWindow?.(plan.model))
|
|
234
|
+
return null;
|
|
235
|
+
let n = null;
|
|
236
|
+
d.log(`Reading the context window of ${plan.model} from Stav...`);
|
|
237
|
+
try {
|
|
238
|
+
const stav = new Stav(d.cfg, d.fetchFn);
|
|
239
|
+
stav.onNote = d.log;
|
|
240
|
+
n = await stav.modelContext(key, plan.model);
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
d.log(`Could not read the context window of ${plan.model} (${err instanceof Error ? err.message : String(err)}); ${plan.adapter.displayName} uses its own guess.`);
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
if (n === null)
|
|
247
|
+
d.log(`Stav does not know the context window of ${plan.model} for your workspace; ${plan.adapter.displayName} uses its own guess.`);
|
|
248
|
+
return n;
|
|
249
|
+
}
|
|
250
|
+
/** PATH lookup without a shell. */
|
|
251
|
+
export function which(program, env = process.env) {
|
|
252
|
+
for (const dir of (env.PATH ?? '').split(path.delimiter)) {
|
|
253
|
+
if (!dir)
|
|
254
|
+
continue;
|
|
255
|
+
const full = path.join(dir, program);
|
|
256
|
+
// Absolute PATH entries only: an empty or relative entry would run a
|
|
257
|
+
// program from the current folder.
|
|
258
|
+
if (!path.isAbsolute(dir))
|
|
259
|
+
continue;
|
|
260
|
+
try {
|
|
261
|
+
accessSync(full, constants.X_OK);
|
|
262
|
+
if (!statSync(full).isFile())
|
|
263
|
+
continue;
|
|
264
|
+
return full;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// Not here.
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
/** Run the app in the foreground; resolve with its exit code. */
|
|
273
|
+
export function runChild(command, args, options) {
|
|
274
|
+
return new Promise((resolve, reject) => {
|
|
275
|
+
const child = nodeSpawn(command, args, options);
|
|
276
|
+
// Ctrl-C reaches the app by itself (same foreground process group), so
|
|
277
|
+
// the CLI only ignores it; forwarding it too would be a second Ctrl-C,
|
|
278
|
+
// which both apps read as "force quit". TERM and HUP are forwarded.
|
|
279
|
+
const onInt = () => undefined;
|
|
280
|
+
const onTerm = () => child.kill('SIGTERM');
|
|
281
|
+
const onHup = () => child.kill('SIGHUP');
|
|
282
|
+
process.on('SIGINT', onInt);
|
|
283
|
+
process.on('SIGTERM', onTerm);
|
|
284
|
+
process.on('SIGHUP', onHup);
|
|
285
|
+
child.on('error', (err) => reject(new StavError(`Could not start ${command}: ${err.message}`, 'spawn_failed')));
|
|
286
|
+
child.on('exit', (code, signal) => {
|
|
287
|
+
process.off('SIGINT', onInt);
|
|
288
|
+
process.off('SIGTERM', onTerm);
|
|
289
|
+
process.off('SIGHUP', onHup);
|
|
290
|
+
resolve(code ?? (signal ? 128 + (os.constants.signals[signal] ?? 0) : 1));
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
}
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Questions in the terminal. Never asked when there is no terminal. */
|
|
2
|
+
import { createInterface } from 'node:readline/promises';
|
|
3
|
+
import { terminalText } from './terminal-text.js';
|
|
4
|
+
export const terminal = {
|
|
5
|
+
interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
6
|
+
async ask(question) {
|
|
7
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
8
|
+
try {
|
|
9
|
+
return (await rl.question(terminalText(question))).trim();
|
|
10
|
+
}
|
|
11
|
+
finally {
|
|
12
|
+
rl.close();
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
export async function confirm(p, question) {
|
|
17
|
+
const answer = (await p.ask(`${question} [y/N] `)).toLowerCase();
|
|
18
|
+
return answer === 'y' || answer === 'yes';
|
|
19
|
+
}
|
package/dist/stav.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** The Stav calls the CLI makes, typed. */
|
|
2
|
+
import { StavError } from './errors.js';
|
|
3
|
+
import { request } from './http.js';
|
|
4
|
+
/**
|
|
5
|
+
* The window is a nicety: each read gives up after this. The second read runs
|
|
6
|
+
* only when no endpoint states a window, so a slow gateway delays the start by
|
|
7
|
+
* at most twice this (10 s).
|
|
8
|
+
*/
|
|
9
|
+
const WINDOW_TIMEOUT_MS = 5_000;
|
|
10
|
+
export class Stav {
|
|
11
|
+
cfg;
|
|
12
|
+
fetchFn;
|
|
13
|
+
/** Where a note for the person goes (the launch sets it). */
|
|
14
|
+
onNote;
|
|
15
|
+
constructor(cfg, fetchFn) {
|
|
16
|
+
this.cfg = cfg;
|
|
17
|
+
this.fetchFn = fetchFn;
|
|
18
|
+
}
|
|
19
|
+
workspaces(token) {
|
|
20
|
+
return request(this.fetchFn, `${this.cfg.apiUrl}/api/settings/me/teams`, { token }).then((w) => w ?? []);
|
|
21
|
+
}
|
|
22
|
+
async me(token, teamId) {
|
|
23
|
+
const me = await request(this.fetchFn, `${this.cfg.apiUrl}/api/auth/me`, { token, teamId });
|
|
24
|
+
if (!me)
|
|
25
|
+
throw new StavError('Stav did not answer who you are.', 'empty');
|
|
26
|
+
return me;
|
|
27
|
+
}
|
|
28
|
+
async walletBalance(token, teamId) {
|
|
29
|
+
const w = await request(this.fetchFn, `${this.cfg.apiUrl}/api/billing/wallet`, { token, teamId, nullOn: [403, 404] });
|
|
30
|
+
return w && typeof w.balance === 'number' ? w.balance : null;
|
|
31
|
+
}
|
|
32
|
+
/** Null while the catalogue is off or the app is unknown (404). */
|
|
33
|
+
app(slug) {
|
|
34
|
+
return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/public/apps/${encodeURIComponent(slug)}`, { nullOn: [404] });
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The model's context window for the key's workspace: the LARGEST window
|
|
38
|
+
* any endpoint the workspace may use states, from the gateway's endpoint
|
|
39
|
+
* list (Roland 2026-11-27: the largest, not the smallest, so Claude Code
|
|
40
|
+
* is not held to one small endpoint). When no endpoint states one, the
|
|
41
|
+
* model's own figure (``context_length`` on the model answer). Null when
|
|
42
|
+
* the gateway knows neither or does not list the model.
|
|
43
|
+
*/
|
|
44
|
+
async modelContext(key, model) {
|
|
45
|
+
const path = model.split('/').map(encodeURIComponent).join('/');
|
|
46
|
+
const ok = (n) => typeof n === 'number' && Number.isInteger(n) && n > 0;
|
|
47
|
+
const list = await request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/models/${path}/endpoints`, { token: key, nullOn: [401, 403, 404], timeoutMs: WINDOW_TIMEOUT_MS });
|
|
48
|
+
const known = (list?.data?.endpoints ?? []).map((e) => e.context_length).filter(ok);
|
|
49
|
+
if (known.length) {
|
|
50
|
+
const largest = Math.max(...known);
|
|
51
|
+
const smallest = Math.min(...known);
|
|
52
|
+
if (smallest < largest)
|
|
53
|
+
this.onNote?.(`${model} is served at ${largest} tokens of context, but at ${smallest} on one endpoint your workspace may use; a very long chat that lands there is refused.`);
|
|
54
|
+
return largest;
|
|
55
|
+
}
|
|
56
|
+
const m = await request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/models/${path}`, { token: key, nullOn: [401, 403, 404], timeoutMs: WINDOW_TIMEOUT_MS });
|
|
57
|
+
return ok(m?.context_length) ? m.context_length : null;
|
|
58
|
+
}
|
|
59
|
+
/** Whether a key still works, and for which workspace. Null when it does not. */
|
|
60
|
+
checkKey(key) {
|
|
61
|
+
return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/auth/validate`, { token: key, nullOn: [401, 403] });
|
|
62
|
+
}
|
|
63
|
+
async createTeamKey(token, teamId, body) {
|
|
64
|
+
const k = await request(this.fetchFn, `${this.cfg.apiUrl}/api/api-keys/`, {
|
|
65
|
+
token, teamId, body: { ...body, environment: 'PRODUCTION' },
|
|
66
|
+
});
|
|
67
|
+
if (!k?.full_key)
|
|
68
|
+
throw new StavError('Stav made no key.', 'empty');
|
|
69
|
+
return k;
|
|
70
|
+
}
|
|
71
|
+
async createUserKey(token, teamId, body) {
|
|
72
|
+
const k = await request(this.fetchFn, `${this.cfg.apiUrl}/api/user-keys/`, {
|
|
73
|
+
token, teamId, body: { ...body, environment: 'PRODUCTION' },
|
|
74
|
+
});
|
|
75
|
+
if (!k?.full_key)
|
|
76
|
+
throw new StavError('Stav made no key.', 'empty');
|
|
77
|
+
return k;
|
|
78
|
+
}
|
|
79
|
+
/** The OWNER and ADMIN emails, to name who can change a policy. */
|
|
80
|
+
async admins(token, teamId) {
|
|
81
|
+
try {
|
|
82
|
+
const page = await request(this.fetchFn, `${this.cfg.apiUrl}/api/teams/current/members?limit=100`, { token, teamId, nullOn: [403, 404] });
|
|
83
|
+
return (page?.items ?? [])
|
|
84
|
+
.filter((m) => (m.role === 'OWNER' || m.role === 'ADMIN') && (m.status ?? 'ACTIVE') === 'ACTIVE')
|
|
85
|
+
.map((m) => m.email);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the CLI keeps the sign-in and the app keys (DECIDE-APPS-K): the
|
|
3
|
+
* operating system's keychain, with a file only the user can read as the
|
|
4
|
+
* fallback (a Linux server with no secret service). Never in a project
|
|
5
|
+
* folder (R-20).
|
|
6
|
+
*
|
|
7
|
+
* Secrets are stored one entry each. Settings that are not secret (the
|
|
8
|
+
* chosen workspace) live in config.json beside the fallback file.
|
|
9
|
+
*/
|
|
10
|
+
import { promises as fs } from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
export const SERVICE = 'stav-cli';
|
|
14
|
+
export function configDir(env = process.env, platform = process.platform) {
|
|
15
|
+
if (env.STAV_CONFIG_DIR)
|
|
16
|
+
return env.STAV_CONFIG_DIR;
|
|
17
|
+
if (platform === 'win32' && env.APPDATA)
|
|
18
|
+
return path.join(env.APPDATA, 'stav');
|
|
19
|
+
const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
20
|
+
return path.join(base, 'stav');
|
|
21
|
+
}
|
|
22
|
+
/** A JSON file of name → value, mode 0600, in a 0700 directory. */
|
|
23
|
+
export class FileStore {
|
|
24
|
+
file;
|
|
25
|
+
kind = 'file';
|
|
26
|
+
constructor(file) {
|
|
27
|
+
this.file = file;
|
|
28
|
+
}
|
|
29
|
+
async readAll() {
|
|
30
|
+
try {
|
|
31
|
+
const raw = await fs.readFile(this.file, 'utf8');
|
|
32
|
+
const parsed = JSON.parse(raw);
|
|
33
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async write(data) {
|
|
40
|
+
await fs.mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
|
41
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
42
|
+
await fs.writeFile(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
43
|
+
await fs.rename(tmp, this.file);
|
|
44
|
+
await fs.chmod(this.file, 0o600).catch(() => undefined);
|
|
45
|
+
}
|
|
46
|
+
async get(name) {
|
|
47
|
+
return (await this.readAll())[name] ?? null;
|
|
48
|
+
}
|
|
49
|
+
async set(name, value) {
|
|
50
|
+
const data = await this.readAll();
|
|
51
|
+
data[name] = value;
|
|
52
|
+
await this.write(data);
|
|
53
|
+
}
|
|
54
|
+
async delete(name) {
|
|
55
|
+
const data = await this.readAll();
|
|
56
|
+
if (name in data) {
|
|
57
|
+
delete data[name];
|
|
58
|
+
await this.write(data);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** The OS keychain through @napi-rs/keyring (an optional dependency). */
|
|
63
|
+
export class KeychainStore {
|
|
64
|
+
mod;
|
|
65
|
+
kind = 'keychain';
|
|
66
|
+
constructor(mod) {
|
|
67
|
+
this.mod = mod;
|
|
68
|
+
}
|
|
69
|
+
async get(name) {
|
|
70
|
+
return new this.mod.Entry(SERVICE, name).getPassword() ?? null;
|
|
71
|
+
}
|
|
72
|
+
async set(name, value) {
|
|
73
|
+
new this.mod.Entry(SERVICE, name).setPassword(value);
|
|
74
|
+
}
|
|
75
|
+
async delete(name) {
|
|
76
|
+
await new this.mod.Entry(SERVICE, name).deletePassword();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export class MemoryStore {
|
|
80
|
+
kind = 'memory';
|
|
81
|
+
data = new Map();
|
|
82
|
+
async get(name) {
|
|
83
|
+
return this.data.get(name) ?? null;
|
|
84
|
+
}
|
|
85
|
+
async set(name, value) {
|
|
86
|
+
this.data.set(name, value);
|
|
87
|
+
}
|
|
88
|
+
async delete(name) {
|
|
89
|
+
this.data.delete(name);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The keychain when it loads and answers, else the file. STAV_STORE=file
|
|
94
|
+
* forces the file (CI, containers).
|
|
95
|
+
*/
|
|
96
|
+
export async function openStore(env = process.env) {
|
|
97
|
+
const file = new FileStore(path.join(configDir(env), 'credentials.json'));
|
|
98
|
+
if (env.STAV_STORE === 'file')
|
|
99
|
+
return file;
|
|
100
|
+
try {
|
|
101
|
+
const mod = await import('@napi-rs/keyring');
|
|
102
|
+
const store = new KeychainStore(mod);
|
|
103
|
+
await store.get('probe');
|
|
104
|
+
return store;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return file;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** The app keys saved on this machine, one entry each, and an index of their names. */
|
|
111
|
+
const KEY_INDEX = 'keys';
|
|
112
|
+
export function appKeyName(team, slug, person) {
|
|
113
|
+
return `key:${team}:${slug}:${person.toLowerCase()}`;
|
|
114
|
+
}
|
|
115
|
+
async function keyIndex(store) {
|
|
116
|
+
try {
|
|
117
|
+
const raw = await store.get(KEY_INDEX);
|
|
118
|
+
const list = raw ? JSON.parse(raw) : [];
|
|
119
|
+
return Array.isArray(list) ? list.filter((x) => typeof x === 'string') : [];
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export async function saveAppKey(store, name, value) {
|
|
126
|
+
await store.set(name, value);
|
|
127
|
+
const names = await keyIndex(store);
|
|
128
|
+
if (!names.includes(name))
|
|
129
|
+
await store.set(KEY_INDEX, JSON.stringify([...names, name]));
|
|
130
|
+
}
|
|
131
|
+
/** Remove every saved app key (all workspaces, all people on this account). */
|
|
132
|
+
export async function forgetAppKeys(store) {
|
|
133
|
+
const names = await keyIndex(store);
|
|
134
|
+
for (const n of names)
|
|
135
|
+
await store.delete(n);
|
|
136
|
+
await store.delete(KEY_INDEX);
|
|
137
|
+
return names.length;
|
|
138
|
+
}
|
|
139
|
+
/** Settings that are not secret. */
|
|
140
|
+
export async function readSettings(env = process.env) {
|
|
141
|
+
return new FileStore(path.join(configDir(env), 'config.json')).readAll();
|
|
142
|
+
}
|
|
143
|
+
export async function writeSetting(name, value, env = process.env) {
|
|
144
|
+
const s = new FileStore(path.join(configDir(env), 'config.json'));
|
|
145
|
+
if (value === null)
|
|
146
|
+
await s.delete(name);
|
|
147
|
+
else
|
|
148
|
+
await s.set(name, value);
|
|
149
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text safe to write to a terminal.
|
|
3
|
+
*
|
|
4
|
+
* Much of what the CLI prints comes from the Stav API: error messages, key
|
|
5
|
+
* names, workspace names, emails. An escape sequence in any of them would be
|
|
6
|
+
* run by the terminal: it could hide or rewrite lines of the plan shown
|
|
7
|
+
* before "Go ahead?", set the window title or write the clipboard. So every
|
|
8
|
+
* line passes through here on its way out.
|
|
9
|
+
*
|
|
10
|
+
* Kept: line feed and tab (the CLI's own help and lists use them).
|
|
11
|
+
* Replaced with a space: every other C0 and C1 control character (ESC, CR,
|
|
12
|
+
* BEL, NEL, CSI …), DEL, the Unicode line and paragraph separators, and the
|
|
13
|
+
* bidirectional marks, overrides and isolates, which can reorder what the
|
|
14
|
+
* reader sees.
|
|
15
|
+
*/
|
|
16
|
+
const UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
|
|
17
|
+
export function terminalText(text) {
|
|
18
|
+
return text.replace(UNSAFE, ' ');
|
|
19
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** x.y.z compare: negative when a < b. Anything unparseable sorts last. */
|
|
2
|
+
export function compareVersions(a, b) {
|
|
3
|
+
const parse = (v) => (/^[0-9]+\.[0-9]+\.[0-9]+$/.test(v) ? v.split('.').map(Number) : null);
|
|
4
|
+
const pa = parse(a);
|
|
5
|
+
const pb = parse(b);
|
|
6
|
+
if (!pa || !pb)
|
|
7
|
+
return pa ? -1 : pb ? 1 : 0;
|
|
8
|
+
for (let i = 0; i < 3; i++)
|
|
9
|
+
if (pa[i] !== pb[i])
|
|
10
|
+
return pa[i] - pb[i];
|
|
11
|
+
return 0;
|
|
12
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which workspace (R-21): a person in more than one picks one, and the CLI
|
|
3
|
+
* never picks for them. Every /api call then sends X-Team-Id, because with
|
|
4
|
+
* no header Stav silently uses the oldest membership.
|
|
5
|
+
*/
|
|
6
|
+
import { StavError } from './errors.js';
|
|
7
|
+
import { terminalText } from './terminal-text.js';
|
|
8
|
+
/**
|
|
9
|
+
* The chosen workspace: the one named (by id or slug), else the stored
|
|
10
|
+
* choice if still a membership, else the only one, else ask. Without a
|
|
11
|
+
* terminal and with more than one, it refuses and says how to choose.
|
|
12
|
+
*/
|
|
13
|
+
export async function chooseWorkspace(all, named, stored, prompter) {
|
|
14
|
+
if (all.length === 0) {
|
|
15
|
+
throw new StavError('You are not in a Stav workspace yet. Create one at https://stav.ai/app, then run this again.', 'no_workspace');
|
|
16
|
+
}
|
|
17
|
+
if (named) {
|
|
18
|
+
const hit = all.find((w) => w.id === named || (w.slug && w.slug === named));
|
|
19
|
+
if (!hit)
|
|
20
|
+
throw new StavError(`You are not a member of a workspace "${named}". Run stav workspace to see yours.`, 'unknown_workspace');
|
|
21
|
+
return hit;
|
|
22
|
+
}
|
|
23
|
+
const kept = stored ? all.find((w) => w.id === stored) : undefined;
|
|
24
|
+
if (kept)
|
|
25
|
+
return kept;
|
|
26
|
+
if (all.length === 1)
|
|
27
|
+
return all[0];
|
|
28
|
+
if (!prompter.interactive) {
|
|
29
|
+
throw new StavError(`You are in ${all.length} workspaces. Choose one with --workspace <slug> or stav workspace <slug>.`, 'workspace_required');
|
|
30
|
+
}
|
|
31
|
+
all.forEach((w, i) => process.stderr.write(`${terminalText(` ${i + 1}. ${w.name}${w.slug ? ` (${w.slug})` : ''}, ${w.role.toLowerCase()}`)}\n`));
|
|
32
|
+
for (;;) {
|
|
33
|
+
const answer = await prompter.ask(`Which workspace? 1-${all.length}: `);
|
|
34
|
+
const n = Number.parseInt(answer, 10);
|
|
35
|
+
if (n >= 1 && n <= all.length && String(n) === answer)
|
|
36
|
+
return all[n - 1];
|
|
37
|
+
}
|
|
38
|
+
}
|