@stav-ai/cli 0.1.7 → 0.1.10
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/README.md +20 -6
- package/dist/adapters/index.js +61 -20
- package/dist/adapters/pi-stav-provider.js +2 -1
- package/dist/agent/index.js +626 -0
- package/dist/agent/pairings.js +83 -0
- package/dist/agent/passkey.js +86 -0
- package/dist/agent/questions.js +232 -0
- package/dist/agent/relay.js +224 -0
- package/dist/agent/steps.js +131 -0
- package/dist/agent/wire.js +41 -0
- package/dist/app-names.js +54 -0
- package/dist/cli.js +41 -7
- package/dist/config.js +1 -0
- package/dist/http.js +2 -1
- package/dist/launch.js +27 -8
- package/dist/noise.js +225 -0
- package/dist/prompt.js +119 -0
- package/dist/stav.js +3 -3
- package/dist/store/index.js +10 -0
- package/dist/update-check.js +67 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The steps of a task as lines in the terminal.
|
|
3
|
+
*
|
|
4
|
+
* The text of a step comes from an agent that reads other people's text, so
|
|
5
|
+
* none of it may look like a line of ours. Every line of it starts with
|
|
6
|
+
* `MARK`: control characters are gone (terminalText), a line feed starts a new
|
|
7
|
+
* marked line, and a long line is broken here, because a line the terminal
|
|
8
|
+
* breaks itself would go on at the left edge. Only our own fixed words start
|
|
9
|
+
* a line without the mark.
|
|
10
|
+
*/
|
|
11
|
+
import { terminalText } from '../terminal-text.js';
|
|
12
|
+
export const MARK = '│ ';
|
|
13
|
+
/** At most this many columns: only ASCII is sure to take one, a terminal may show § or ø in two. */
|
|
14
|
+
const width = (char) => (char.codePointAt(0) < 0x7f ? 1 : 2);
|
|
15
|
+
const isNumber = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
16
|
+
const isText = (v) => typeof v === 'string';
|
|
17
|
+
/** A code the connector or the relay sent, or `unknown`. It goes on lines of ours. */
|
|
18
|
+
export const word = (v) => (isText(v) && /^[a-z0-9_]{1,64}$/.test(v) ? v : 'unknown');
|
|
19
|
+
const QUESTIONS = {
|
|
20
|
+
needs_approval: '● The agent asks for your approval',
|
|
21
|
+
needs_login: '● The agent asks you to sign in where its data is',
|
|
22
|
+
needs_access: '● The agent asks for access',
|
|
23
|
+
};
|
|
24
|
+
const END_STATES = { done: 'done', cannot: 'the agent could not do it', failed: 'failed' };
|
|
25
|
+
export class StepPrinter {
|
|
26
|
+
columns;
|
|
27
|
+
/** The text that goes on: which one, and how many columns its last line has. Null at the start of a line. */
|
|
28
|
+
open = null;
|
|
29
|
+
constructor(columns) {
|
|
30
|
+
this.columns = columns;
|
|
31
|
+
}
|
|
32
|
+
/** What to write before a line of ours. */
|
|
33
|
+
close() {
|
|
34
|
+
const out = this.open?.column ? '\n' : '';
|
|
35
|
+
this.open = null;
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
line(text) {
|
|
39
|
+
return `${this.close()}${text}\n`;
|
|
40
|
+
}
|
|
41
|
+
/** `first` and then `rest` start the lines. */
|
|
42
|
+
marked(text, first = MARK, rest = MARK) {
|
|
43
|
+
const limit = Math.max(8, this.columns() - 1);
|
|
44
|
+
let mark = first;
|
|
45
|
+
let out = '';
|
|
46
|
+
for (const char of terminalText(text.replace(/\r\n/g, '\n')).replace(/\t/g, ' ')) {
|
|
47
|
+
if (char === '\n') {
|
|
48
|
+
out += this.open.column ? '\n' : `${MARK}\n`;
|
|
49
|
+
this.open.column = 0;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (this.open.column + width(char) > limit && this.open.column > mark.length) {
|
|
53
|
+
out += '\n';
|
|
54
|
+
this.open.column = 0;
|
|
55
|
+
}
|
|
56
|
+
if (!this.open.column) {
|
|
57
|
+
out += mark;
|
|
58
|
+
this.open.column = mark.length;
|
|
59
|
+
mark = rest;
|
|
60
|
+
}
|
|
61
|
+
out += char;
|
|
62
|
+
this.open.column += width(char);
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
/** A text under a heading of ours. With `more` the next step of the same text goes on where it ended. */
|
|
67
|
+
text(key, heading, text, more) {
|
|
68
|
+
let out = '';
|
|
69
|
+
if (this.open?.key !== key) {
|
|
70
|
+
out = this.line(heading);
|
|
71
|
+
this.open = { key, column: 0 };
|
|
72
|
+
}
|
|
73
|
+
out += this.marked(text);
|
|
74
|
+
return more ? out : out + this.close();
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A question. A choice's number stands left of the mark, where no text of
|
|
78
|
+
* the agent can come: not from the question, not from a long choice.
|
|
79
|
+
*/
|
|
80
|
+
question(reason, text, choices) {
|
|
81
|
+
let out = this.text('question', QUESTIONS[reason] ?? '● The agent has a question', text, false);
|
|
82
|
+
if (choices.length)
|
|
83
|
+
out += this.line('● You can answer');
|
|
84
|
+
for (const [i, choice] of choices.entries()) {
|
|
85
|
+
this.open = { key: 'choice', column: 0 };
|
|
86
|
+
out += this.marked(terminalText(choice).replace(/\s+/g, ' ').trim() || ' ', `${i + 1} ${MARK}`, ` ${MARK}`) + this.close();
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** The step as it goes to the terminal. Empty for a kind this version does not know. */
|
|
91
|
+
step(f) {
|
|
92
|
+
const key = [f.task, f.call, f.kind, f.id, f.reasoning].join(' ');
|
|
93
|
+
const text = isText(f.text) ? f.text : '';
|
|
94
|
+
const more = f.more === true;
|
|
95
|
+
switch (f.kind) {
|
|
96
|
+
case 'start':
|
|
97
|
+
return this.line(`● A task started at ${isNumber(f.at) ? clock(f.at) : 'an unknown time'}.`);
|
|
98
|
+
case 'prompt':
|
|
99
|
+
return this.text(key, '● To the model', text, more);
|
|
100
|
+
case 'text':
|
|
101
|
+
return this.text(key, f.reasoning === true ? '● The model thinks' : '● The model', text, more);
|
|
102
|
+
case 'tool_call':
|
|
103
|
+
// The name comes from the agent too: it gets a marked line of its own.
|
|
104
|
+
return this.text(key, '● The model calls a tool', this.open?.key === key ? text : `${isText(f.name) ? f.name : ''}\n${text}`, more);
|
|
105
|
+
case 'tool_result':
|
|
106
|
+
return this.text(key, f.error === true ? '● The tool gave an error' : '● The tool gave', text, more);
|
|
107
|
+
case 'refused':
|
|
108
|
+
return this.text(key, '● A model call was refused', text, more);
|
|
109
|
+
case 'usage': {
|
|
110
|
+
const parts = [];
|
|
111
|
+
if (isNumber(f.input_tokens))
|
|
112
|
+
parts.push(`${f.input_tokens} tokens in`);
|
|
113
|
+
if (isNumber(f.output_tokens))
|
|
114
|
+
parts.push(`${f.output_tokens} tokens out`);
|
|
115
|
+
if (isText(f.cost) && /^\d{1,12}(\.\d{1,12})?$/.test(f.cost))
|
|
116
|
+
parts.push(`cost ${f.cost}${isText(f.currency) && /^[A-Z]{3}$/.test(f.currency) ? ` ${f.currency}` : ''}`);
|
|
117
|
+
return parts.length ? this.line(`● Used: ${parts.join(', ')}.`) : '';
|
|
118
|
+
}
|
|
119
|
+
case 'end':
|
|
120
|
+
return this.line(`● The task ended: ${END_STATES[word(f.state)] ?? word(f.state)}${f.reason ? ` (${word(f.reason)})` : ''}.`);
|
|
121
|
+
case 'gap':
|
|
122
|
+
return this.line(`● ${isNumber(f.lines) ? f.lines : 'Some'} steps were left out here: they came faster than this terminal could show them.`);
|
|
123
|
+
default:
|
|
124
|
+
return '';
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Epoch seconds as a local time. */
|
|
129
|
+
export function clock(at) {
|
|
130
|
+
return new Date(at * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
|
|
131
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The small parts of WATCH.md that the CLI, the connector and the page must all make the same way. */
|
|
2
|
+
import { createHash, hkdfSync } from 'node:crypto';
|
|
3
|
+
const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
4
|
+
const CODE_LENGTH = 26;
|
|
5
|
+
const FINGERPRINT_LENGTH = 10;
|
|
6
|
+
/** What a person typed, in the alphabet of § 3: case, spaces and dashes do not matter. */
|
|
7
|
+
function readTyped(typed, length) {
|
|
8
|
+
const text = typed.replace(/[\s-]/g, '').replace(/[a-z]/g, (c) => c.toUpperCase()).replace(/[IL]/g, '1').replace(/O/g, '0');
|
|
9
|
+
return text.length === length && [...text].every((c) => ALPHABET.includes(c)) ? text : null;
|
|
10
|
+
}
|
|
11
|
+
/** The pairing code, or null when it is not one. */
|
|
12
|
+
export const readCode = (typed) => readTyped(typed, CODE_LENGTH);
|
|
13
|
+
/** A typed passkey fingerprint, or null when it is not one. */
|
|
14
|
+
export const readFingerprint = (typed) => readTyped(typed, FINGERPRINT_LENGTH);
|
|
15
|
+
export function pskOf(code) {
|
|
16
|
+
return Buffer.from(hkdfSync('sha256', Buffer.from(code), Buffer.alloc(0), 'stav-agent-watch-v1 pair', 32));
|
|
17
|
+
}
|
|
18
|
+
export function prologue(kind, n) {
|
|
19
|
+
return Buffer.concat(['stav-agent-watch', '1', kind, n.agent_id, n.team_id, n.user_id, n.device_id].flatMap((s) => {
|
|
20
|
+
const bytes = Buffer.from(s);
|
|
21
|
+
const length = Buffer.alloc(2);
|
|
22
|
+
length.writeUInt16BE(bytes.length);
|
|
23
|
+
return [length, bytes];
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
/** The bytes the passkey signs. `number` is for `watch` only. */
|
|
27
|
+
export function challenge(mode, h, number = '') {
|
|
28
|
+
return createHash('sha256').update(`stav-agent-passkey-${mode}-v1\0`).update(h).update(mode === 'watch' ? number : '').digest();
|
|
29
|
+
}
|
|
30
|
+
/** The first 10 characters of the SHA-256 of the passkey's public key (SPKI DER). */
|
|
31
|
+
export function fingerprint(spki) {
|
|
32
|
+
const bits = [...createHash('sha256').update(spki).digest()].map((b) => b.toString(2).padStart(8, '0')).join('');
|
|
33
|
+
return Array.from({ length: FINGERPRINT_LENGTH }, (_, i) => ALPHABET[parseInt(bits.slice(i * 5, i * 5 + 5), 2)]).join('');
|
|
34
|
+
}
|
|
35
|
+
/** The bytes, or null when the text is not in the one canonical form. */
|
|
36
|
+
export function decode(text, encoding, length) {
|
|
37
|
+
if (typeof text !== 'string' || text === '')
|
|
38
|
+
return null;
|
|
39
|
+
const bytes = Buffer.from(text, encoding);
|
|
40
|
+
return bytes.toString(encoding) === text && (length === undefined || bytes.length === length) ? bytes : null;
|
|
41
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The names a person may type after `stav launch`, the `stav apps` list, and
|
|
3
|
+
* the hint for a name that is nearly right.
|
|
4
|
+
*/
|
|
5
|
+
import { ADAPTERS, ALIASES } from './adapters/index.js';
|
|
6
|
+
/** The short name of an app ("claude" for claude-code), or null when it has none. */
|
|
7
|
+
export function shortName(slug) {
|
|
8
|
+
return Object.keys(ALIASES).find((a) => ALIASES[a] === slug) ?? null;
|
|
9
|
+
}
|
|
10
|
+
/** The lines of `stav apps`: the name to type first, then the long name, which works too. */
|
|
11
|
+
export function appsTable(rows) {
|
|
12
|
+
const cells = [
|
|
13
|
+
['NAME', 'LONG NAME', 'APP', 'STATE'],
|
|
14
|
+
...rows.map((r) => {
|
|
15
|
+
const short = shortName(r.slug);
|
|
16
|
+
return [short ?? r.slug, short ? r.slug : '', r.displayName, r.ready ? 'ready' : 'not launchable yet'];
|
|
17
|
+
}),
|
|
18
|
+
];
|
|
19
|
+
const widths = [0, 1, 2].map((i) => Math.max(...cells.map((c) => c[i].length)));
|
|
20
|
+
return cells.map((c) => c.map((x, i) => (i < 3 ? x.padEnd(widths[i]) : x)).join(' '));
|
|
21
|
+
}
|
|
22
|
+
/** Edits (add, remove, change or swap two letters) between two words. */
|
|
23
|
+
function distance(a, b) {
|
|
24
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
|
|
25
|
+
for (let i = 1; i <= a.length; i++) {
|
|
26
|
+
for (let j = 1; j <= b.length; j++) {
|
|
27
|
+
const change = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
28
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + change);
|
|
29
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
|
|
30
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return d[a.length][b.length];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The name the person most likely meant, or null. Only ever shown as a
|
|
37
|
+
* question: the CLI never starts an app on a guess. One edit for a short
|
|
38
|
+
* word, two for a longer one, or the start of exactly one app's name.
|
|
39
|
+
*/
|
|
40
|
+
export function suggestApp(typed) {
|
|
41
|
+
const t = typed.trim().toLowerCase();
|
|
42
|
+
// Two letters are one edit from too much; a very long word is not a typo.
|
|
43
|
+
if (t.length < 3 || t.length > 40)
|
|
44
|
+
return null;
|
|
45
|
+
const names = [...Object.keys(ALIASES), ...ADAPTERS.flatMap((a) => a.apps)];
|
|
46
|
+
const near = names
|
|
47
|
+
.map((name) => ({ name, d: distance(t, name) }))
|
|
48
|
+
.filter((x) => x.d <= (t.length < 6 ? 1 : 2))
|
|
49
|
+
.sort((a, b) => a.d - b.d)[0];
|
|
50
|
+
if (near)
|
|
51
|
+
return near.name;
|
|
52
|
+
const starts = names.filter((n) => n.startsWith(t));
|
|
53
|
+
return starts.length === 1 ? starts[0] : null;
|
|
54
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -7,18 +7,22 @@
|
|
|
7
7
|
* stav apps
|
|
8
8
|
* stav launch <app> [--model <id>] [--workspace <slug>] [--yes] [--verbose] [-- <app arguments>]
|
|
9
9
|
*
|
|
10
|
-
* No telemetry (spec B.9).
|
|
10
|
+
* No telemetry (spec B.9). Once a day it asks npm for the newest version
|
|
11
|
+
* (update-check.ts).
|
|
11
12
|
*/
|
|
12
13
|
import { parseArgs } from 'node:util';
|
|
13
14
|
import { ADAPTERS } from './adapters/index.js';
|
|
15
|
+
import { appsTable } from './app-names.js';
|
|
16
|
+
import { agentCommand, TIMES } from './agent/index.js';
|
|
14
17
|
import { accessToken, defaultIO, login, logout } from './auth/session.js';
|
|
15
18
|
import { loadConfig } from './config.js';
|
|
16
19
|
import { StavError } from './errors.js';
|
|
17
20
|
import { launch, runChild, which } from './launch.js';
|
|
18
|
-
import { terminal } from './prompt.js';
|
|
21
|
+
import { askHere, terminal } from './prompt.js';
|
|
19
22
|
import { terminalText } from './terminal-text.js';
|
|
20
23
|
import { Stav } from './stav.js';
|
|
21
24
|
import { forgetAppKeys, openStore, readSettings, writeSetting } from './store/index.js';
|
|
25
|
+
import { updateNotice } from './update-check.js';
|
|
22
26
|
import { VERSION } from './version.js';
|
|
23
27
|
import { chooseWorkspace } from './workspace.js';
|
|
24
28
|
const HELP = `stav ${VERSION} — run your coding agent on Stav
|
|
@@ -28,17 +32,18 @@ Usage:
|
|
|
28
32
|
stav logout [--forget-keys] Remove the sign-in from this machine
|
|
29
33
|
stav whoami Who you are, and which workspace
|
|
30
34
|
stav workspace [<slug>] Show your workspaces, or choose one
|
|
31
|
-
stav apps The apps this CLI can launch
|
|
35
|
+
stav apps The apps this CLI can launch, and their names
|
|
32
36
|
stav launch <app> [options] [-- <app arguments>]
|
|
33
37
|
|
|
34
38
|
Launch options:
|
|
35
39
|
--model <id> The model, e.g. zai-org/glm-5-2 (default: the app's Stav default)
|
|
36
40
|
--workspace <slug> The workspace to use for this run
|
|
37
41
|
--yes Do not ask before making the key
|
|
38
|
-
--verbose Show every setting
|
|
42
|
+
--verbose Show the key's access, every setting and the app's warnings
|
|
39
43
|
|
|
40
44
|
Environment:
|
|
41
45
|
STAV_API_KEY Use this key; no sign-in and no key is made
|
|
46
|
+
STAV_NO_UPDATE_CHECK=1 Do not ask npm for a newer version
|
|
42
47
|
|
|
43
48
|
Examples:
|
|
44
49
|
stav launch claude
|
|
@@ -79,8 +84,34 @@ async function main(argv) {
|
|
|
79
84
|
return command || values.help ? 0 : 1;
|
|
80
85
|
}
|
|
81
86
|
const cfg = loadConfig();
|
|
82
|
-
const store = await openStore();
|
|
83
87
|
const fetchFn = fetch;
|
|
88
|
+
if (command === 'agent') {
|
|
89
|
+
// Before the store is opened: pair and watch refuse first.
|
|
90
|
+
return agentCommand([...rest, ...appArgs], {
|
|
91
|
+
cfg, fetchFn, openStore, env: process.env, times: TIMES,
|
|
92
|
+
isTerminal: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
93
|
+
token: (s) => accessToken(fetchFn, cfg, s),
|
|
94
|
+
workspace: async (s) => {
|
|
95
|
+
const stored = (await readSettings()).workspace;
|
|
96
|
+
if (!values.workspace)
|
|
97
|
+
return stored;
|
|
98
|
+
const t = await accessToken(fetchFn, cfg, s);
|
|
99
|
+
return t ? (await chooseWorkspace(await new Stav(cfg, fetchFn).workspaces(t), values.workspace, stored, terminal)).id : stored;
|
|
100
|
+
},
|
|
101
|
+
ask: askHere,
|
|
102
|
+
openBrowser: defaultIO.open,
|
|
103
|
+
write: (text) => new Promise((resolve, reject) => process.stdout.write(text, (e) => (e ? reject(e) : resolve()))),
|
|
104
|
+
columns: () => process.stdout.columns || 80,
|
|
105
|
+
onInterrupt: (fn) => {
|
|
106
|
+
process.on('SIGINT', fn);
|
|
107
|
+
return () => process.off('SIGINT', fn);
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
// Before the command: an app that is started takes over the terminal.
|
|
112
|
+
for (const line of await updateNotice({ fetchFn, env: process.env, isTerminal: Boolean(process.stderr.isTTY) }))
|
|
113
|
+
err(line);
|
|
114
|
+
const store = await openStore();
|
|
84
115
|
const stav = new Stav(cfg, fetchFn);
|
|
85
116
|
const token = () => accessToken(fetchFn, cfg, store);
|
|
86
117
|
switch (command) {
|
|
@@ -167,13 +198,16 @@ async function main(argv) {
|
|
|
167
198
|
return 0;
|
|
168
199
|
}
|
|
169
200
|
case 'apps': {
|
|
201
|
+
const rows = [];
|
|
170
202
|
for (const a of ADAPTERS) {
|
|
171
203
|
for (const slug of a.apps) {
|
|
172
204
|
const app = await stav.app(slug).catch(() => null);
|
|
173
|
-
|
|
174
|
-
out(`${slug.padEnd(14)} ${a.displayName.padEnd(14)} ${state}`);
|
|
205
|
+
rows.push({ slug, displayName: a.displayName, ready: Boolean(app?.cli_available) });
|
|
175
206
|
}
|
|
176
207
|
}
|
|
208
|
+
for (const line of appsTable(rows))
|
|
209
|
+
out(line);
|
|
210
|
+
out('\nStart one with its name or its long name, for example: stav launch claude');
|
|
177
211
|
return 0;
|
|
178
212
|
}
|
|
179
213
|
case 'launch': {
|
package/dist/config.js
CHANGED
|
@@ -13,6 +13,7 @@ export function loadConfig(env = process.env) {
|
|
|
13
13
|
return {
|
|
14
14
|
apiUrl: trim(env.STAV_API_URL, 'https://stav.ai'),
|
|
15
15
|
gatewayUrl: trim(env.STAV_GATEWAY_URL, 'https://api.stav.ai'),
|
|
16
|
+
relayUrl: trim(env.STAV_RELAY_URL, 'wss://relay.stav.ai'),
|
|
16
17
|
auth0Domain: trim(env.STAV_AUTH0_DOMAIN, 'auth.stav.ai'),
|
|
17
18
|
auth0ClientId: trim(env.STAV_AUTH0_CLIENT_ID, PROD_AUTH0_CLIENT_ID),
|
|
18
19
|
auth0Audience: trim(env.STAV_AUTH0_AUDIENCE, 'https://api.stav.ai') + '/',
|
package/dist/http.js
CHANGED
|
@@ -15,6 +15,7 @@ export async function request(fetchFn, url, opts = {}) {
|
|
|
15
15
|
if (opts.body !== undefined)
|
|
16
16
|
headers['Content-Type'] = 'application/json';
|
|
17
17
|
let res;
|
|
18
|
+
let text;
|
|
18
19
|
try {
|
|
19
20
|
res = await fetchFn(url, {
|
|
20
21
|
method: opts.method ?? (opts.body !== undefined ? 'POST' : 'GET'),
|
|
@@ -22,11 +23,11 @@ export async function request(fetchFn, url, opts = {}) {
|
|
|
22
23
|
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
23
24
|
signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
|
|
24
25
|
});
|
|
26
|
+
text = await res.text();
|
|
25
27
|
}
|
|
26
28
|
catch (err) {
|
|
27
29
|
throw new StavError(`Could not reach ${new URL(url).host}: ${err instanceof Error ? err.message : String(err)}`, 'network');
|
|
28
30
|
}
|
|
29
|
-
const text = await res.text();
|
|
30
31
|
let body = text;
|
|
31
32
|
try {
|
|
32
33
|
body = text ? JSON.parse(text) : null;
|
package/dist/launch.js
CHANGED
|
@@ -9,11 +9,13 @@ import { spawn as nodeSpawn } from 'node:child_process';
|
|
|
9
9
|
import { accessSync, constants, statSync } from 'node:fs';
|
|
10
10
|
import os from 'node:os';
|
|
11
11
|
import path from 'node:path';
|
|
12
|
+
import { suggestApp } from './app-names.js';
|
|
12
13
|
import { adapterForApp, MODEL_RE, resolveApp } from './adapters/index.js';
|
|
13
14
|
import { StavError } from './errors.js';
|
|
14
15
|
import { confirm } from './prompt.js';
|
|
15
16
|
import { Stav } from './stav.js';
|
|
16
17
|
import { appKeyName, saveAppKey } from './store/index.js';
|
|
18
|
+
import { updateCommand } from './update-check.js';
|
|
17
19
|
import { compareVersions } from './version-compare.js';
|
|
18
20
|
import { VERSION } from './version.js';
|
|
19
21
|
import { chooseWorkspace } from './workspace.js';
|
|
@@ -46,14 +48,15 @@ async function checkLaunch(opts, d) {
|
|
|
46
48
|
}
|
|
47
49
|
const slug = resolveApp(opts.app);
|
|
48
50
|
const adapter = adapterForApp(slug);
|
|
51
|
+
const hint = adapter ? null : suggestApp(opts.app);
|
|
49
52
|
if (!adapter)
|
|
50
|
-
throw new StavError(`The Stav CLI cannot launch "${opts.app}"
|
|
53
|
+
throw new StavError(`The Stav CLI cannot launch "${opts.app}".${hint ? ` Did you mean "${hint}"?` : ''} Run stav apps to see the apps it can.`, 'unknown_app');
|
|
51
54
|
const stav = new Stav(d.cfg, d.fetchFn);
|
|
52
55
|
const app = await stav.app(slug);
|
|
53
56
|
checkLaunchable(app, adapter, slug);
|
|
54
57
|
const model = opts.model ?? app.launch_recipe.default_model ?? null;
|
|
55
58
|
if (model !== null && !MODEL_RE.test(model)) {
|
|
56
|
-
throw new StavError(`"${model}" is not a model id. Use one like zai-org/glm-5-2.`, 'bad_model');
|
|
59
|
+
throw new StavError(`"${model}" is not a model id. Use one like zai-org/glm-5-2 or auto:eu.`, 'bad_model');
|
|
57
60
|
}
|
|
58
61
|
const programPath = d.which(adapter.program);
|
|
59
62
|
const conflict = adapter.conflicts ? await adapter.conflicts(d.env.HOME, d.cwd, d.env, opts.appArgs ?? []) : null;
|
|
@@ -139,10 +142,10 @@ function checkLaunchable(app, adapter, slug) {
|
|
|
139
142
|
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');
|
|
140
143
|
}
|
|
141
144
|
if (r.adapter !== adapter.name) {
|
|
142
|
-
throw new StavError(`Stav launches ${adapter.displayName} in a way this CLI does not know. Update it:
|
|
145
|
+
throw new StavError(`Stav launches ${adapter.displayName} in a way this CLI does not know. Update it: ${updateCommand()}`, 'update_cli');
|
|
143
146
|
}
|
|
144
147
|
if (compareVersions(VERSION, r.min_cli) < 0) {
|
|
145
|
-
throw new StavError(`Launching ${adapter.displayName} needs Stav CLI ${r.min_cli} or newer (this is ${VERSION}). Update it:
|
|
148
|
+
throw new StavError(`Launching ${adapter.displayName} needs Stav CLI ${r.min_cli} or newer (this is ${VERSION}). Update it: ${updateCommand()}`, 'update_cli');
|
|
146
149
|
}
|
|
147
150
|
}
|
|
148
151
|
async function readStoredKey(store, name) {
|
|
@@ -221,12 +224,30 @@ export function describePlan(plan, launch, appArgs, storeKind = 'keychain', verb
|
|
|
221
224
|
const lines = [];
|
|
222
225
|
if (plan.workspace)
|
|
223
226
|
lines.push(`Workspace: ${plan.workspace.name}`);
|
|
227
|
+
if (!verbose) {
|
|
228
|
+
const name = plan.adapter.displayName;
|
|
229
|
+
if ('create' in plan.key) {
|
|
230
|
+
// The key's access, and the workspace key an owner or admin may get
|
|
231
|
+
// instead, are said before the question; the rest is --verbose.
|
|
232
|
+
const fallback = plan.key.orWorkspaceKey ? '; a workspace key if personal keys are off' : '';
|
|
233
|
+
lines.push(`Make an API key for ${name} (${plan.adapter.scopes.join(', ')}${fallback}) and start it with ${launch.summary}.`);
|
|
234
|
+
}
|
|
235
|
+
else
|
|
236
|
+
lines.push(`Start ${name} with ${launch.summary}, using ${plan.key.source === 'env' ? 'the key in STAV_API_KEY' : 'your saved key'}.`);
|
|
237
|
+
if (launch.warning)
|
|
238
|
+
lines.push(launch.warning);
|
|
239
|
+
if (appArgs.length)
|
|
240
|
+
lines.push(`Your arguments: ${appArgs.join(' ')}`);
|
|
241
|
+
lines.push('Add --verbose to see the details.');
|
|
242
|
+
return lines;
|
|
243
|
+
}
|
|
224
244
|
const keep = storeKind === 'keychain'
|
|
225
245
|
? 'keep it in your keychain (never in this folder)'
|
|
226
246
|
: 'keep it in a file only you can read (no keychain here; never in this folder)';
|
|
227
247
|
if ('create' in plan.key) {
|
|
228
248
|
// A Stav that does not yet limit personal keys makes this key with
|
|
229
|
-
// full access
|
|
249
|
+
// full access. The short plan leaves that out; settleKey says so once
|
|
250
|
+
// the key is made.
|
|
230
251
|
lines.push(`Make a personal API key "${plan.key.name}" with access to ${plan.adapter.scopes.join(', ')} only, and ${keep} for next time. If Stav cannot limit personal keys yet, the key has full access to your workspace.`);
|
|
231
252
|
if (plan.key.orWorkspaceKey) {
|
|
232
253
|
lines.push(`If ${plan.workspace.name} does not allow personal keys, make a workspace API key with the same name and access instead.`);
|
|
@@ -236,12 +257,10 @@ export function describePlan(plan, launch, appArgs, storeKind = 'keychain', verb
|
|
|
236
257
|
lines.push(plan.key.source === 'env' ? 'Use the key in STAV_API_KEY.' : `Use your saved ${plan.adapter.displayName} key.`);
|
|
237
258
|
}
|
|
238
259
|
lines.push(`Start ${plan.adapter.displayName} (${plan.programPath}) with:`);
|
|
239
|
-
for (const l of
|
|
260
|
+
for (const l of launch.describe)
|
|
240
261
|
lines.push(` ${l}`);
|
|
241
262
|
if (appArgs.length)
|
|
242
263
|
lines.push(` your arguments: ${appArgs.join(' ')}`);
|
|
243
|
-
if (!verbose)
|
|
244
|
-
lines.push('Add --verbose to see every setting.');
|
|
245
264
|
return lines;
|
|
246
265
|
}
|
|
247
266
|
export async function launch(opts, d) {
|
package/dist/noise.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two Noise handshakes of WATCH.md § 2 (revision 34) on node:crypto:
|
|
3
|
+
* Noise_XXpsk0_25519_AESGCM_SHA256 and Noise_KK_25519_AESGCM_SHA256.
|
|
4
|
+
*
|
|
5
|
+
* Both roles are here: the CLI is always the initiator, the tests answer as
|
|
6
|
+
* the connector. Every handshake message has an empty payload.
|
|
7
|
+
*/
|
|
8
|
+
import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey, diffieHellman, randomBytes } from 'node:crypto';
|
|
9
|
+
const DH_LEN = 32;
|
|
10
|
+
const TAG_LEN = 16;
|
|
11
|
+
export const MAX_MESSAGE = 65_535;
|
|
12
|
+
const EMPTY = Buffer.alloc(0);
|
|
13
|
+
// The DER heads in front of a raw X25519 private and public key.
|
|
14
|
+
const PKCS8 = Buffer.from('302e020100300506032b656e04220420', 'hex');
|
|
15
|
+
const SPKI = Buffer.from('302a300506032b656e032100', 'hex');
|
|
16
|
+
export class NoiseError extends Error {
|
|
17
|
+
}
|
|
18
|
+
function privateKey(raw) {
|
|
19
|
+
return createPrivateKey({ key: Buffer.concat([PKCS8, raw]), format: 'der', type: 'pkcs8' });
|
|
20
|
+
}
|
|
21
|
+
export function keyPair(raw = randomBytes(DH_LEN)) {
|
|
22
|
+
if (raw.length !== DH_LEN)
|
|
23
|
+
throw new NoiseError('wrong key length');
|
|
24
|
+
return { private: raw, public: createPublicKey(privateKey(raw)).export({ format: 'der', type: 'spki' }).subarray(SPKI.length) };
|
|
25
|
+
}
|
|
26
|
+
/** X25519. A public key that gives the all-zero result is refused. */
|
|
27
|
+
export function dh(priv, pub) {
|
|
28
|
+
let out;
|
|
29
|
+
try {
|
|
30
|
+
out = diffieHellman({
|
|
31
|
+
privateKey: privateKey(priv),
|
|
32
|
+
publicKey: createPublicKey({ key: Buffer.concat([SPKI, pub]), format: 'der', type: 'spki' }),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new NoiseError('bad public key');
|
|
37
|
+
}
|
|
38
|
+
if (out.length !== DH_LEN || out.every((b) => b === 0))
|
|
39
|
+
throw new NoiseError('bad public key');
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
const sha256 = (...parts) => createHash('sha256').update(Buffer.concat(parts)).digest();
|
|
43
|
+
const hmac = (key, ...parts) => createHmac('sha256', key).update(Buffer.concat(parts)).digest();
|
|
44
|
+
function hkdf(ck, input, n) {
|
|
45
|
+
const temp = hmac(ck, input);
|
|
46
|
+
const out = [];
|
|
47
|
+
let last = EMPTY;
|
|
48
|
+
for (let i = 1; i <= n; i++) {
|
|
49
|
+
last = hmac(temp, last, Buffer.from([i]));
|
|
50
|
+
out.push(last);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
/** One key and its counter. */
|
|
55
|
+
export class CipherState {
|
|
56
|
+
key;
|
|
57
|
+
n = 0;
|
|
58
|
+
constructor(key) {
|
|
59
|
+
this.key = key;
|
|
60
|
+
}
|
|
61
|
+
nonce() {
|
|
62
|
+
const b = Buffer.alloc(12);
|
|
63
|
+
b.writeBigUInt64BE(BigInt(this.n), 4);
|
|
64
|
+
return b;
|
|
65
|
+
}
|
|
66
|
+
encrypt(plain, ad = EMPTY) {
|
|
67
|
+
if (plain.length + TAG_LEN > MAX_MESSAGE)
|
|
68
|
+
throw new NoiseError('message too long');
|
|
69
|
+
const c = createCipheriv('aes-256-gcm', this.key, this.nonce(), { authTagLength: TAG_LEN });
|
|
70
|
+
c.setAAD(ad);
|
|
71
|
+
const out = Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]);
|
|
72
|
+
this.n++;
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
decrypt(message, ad = EMPTY) {
|
|
76
|
+
if (message.length < TAG_LEN || message.length > MAX_MESSAGE)
|
|
77
|
+
throw new NoiseError('wrong message length');
|
|
78
|
+
const d = createDecipheriv('aes-256-gcm', this.key, this.nonce(), { authTagLength: TAG_LEN });
|
|
79
|
+
d.setAAD(ad);
|
|
80
|
+
d.setAuthTag(message.subarray(message.length - TAG_LEN));
|
|
81
|
+
try {
|
|
82
|
+
const out = Buffer.concat([d.update(message.subarray(0, message.length - TAG_LEN)), d.final()]);
|
|
83
|
+
this.n++;
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new NoiseError('message does not decrypt');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const PATTERNS = {
|
|
92
|
+
pair: { name: 'Noise_XXpsk0_25519_AESGCM_SHA256', known: false, messages: [['psk', 'e'], ['e', 'ee', 's', 'es'], ['s', 'se']] },
|
|
93
|
+
watch: { name: 'Noise_KK_25519_AESGCM_SHA256', known: true, messages: [['e', 'es', 'ss'], ['e', 'ee', 'se']] },
|
|
94
|
+
};
|
|
95
|
+
export class Handshake {
|
|
96
|
+
o;
|
|
97
|
+
ck;
|
|
98
|
+
h;
|
|
99
|
+
cipher = null;
|
|
100
|
+
step = 0;
|
|
101
|
+
e;
|
|
102
|
+
re = null;
|
|
103
|
+
rs;
|
|
104
|
+
constructor(o) {
|
|
105
|
+
this.o = o;
|
|
106
|
+
const p = PATTERNS[o.kind];
|
|
107
|
+
this.e = o.ephemeral ?? keyPair();
|
|
108
|
+
this.rs = o.remoteStatic ?? null;
|
|
109
|
+
if (p.known !== (this.rs !== null) || (o.kind === 'pair') !== (o.psk?.length === 32))
|
|
110
|
+
throw new NoiseError('wrong keys for this handshake');
|
|
111
|
+
// A name of at most 32 bytes is padded with zeros, a longer one is hashed.
|
|
112
|
+
const name = Buffer.from(p.name);
|
|
113
|
+
this.h = name.length <= 32 ? Buffer.concat([name, Buffer.alloc(32 - name.length)]) : sha256(name);
|
|
114
|
+
this.ck = this.h;
|
|
115
|
+
this.mixHash(o.prologue);
|
|
116
|
+
if (p.known) {
|
|
117
|
+
this.mixHash(o.initiator ? o.static.public : this.rs);
|
|
118
|
+
this.mixHash(o.initiator ? this.rs : o.static.public);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
get done() {
|
|
122
|
+
return this.step === PATTERNS[this.o.kind].messages.length;
|
|
123
|
+
}
|
|
124
|
+
/** The handshake hash, after the last message. */
|
|
125
|
+
get hash() {
|
|
126
|
+
if (!this.done)
|
|
127
|
+
throw new NoiseError('the handshake is not finished');
|
|
128
|
+
return this.h;
|
|
129
|
+
}
|
|
130
|
+
get remoteStatic() {
|
|
131
|
+
if (!this.done || !this.rs)
|
|
132
|
+
throw new NoiseError('the handshake is not finished');
|
|
133
|
+
return this.rs;
|
|
134
|
+
}
|
|
135
|
+
mixHash(data) {
|
|
136
|
+
this.h = sha256(this.h, data);
|
|
137
|
+
}
|
|
138
|
+
mixKey(input) {
|
|
139
|
+
const [ck, k] = hkdf(this.ck, input, 2);
|
|
140
|
+
this.ck = ck;
|
|
141
|
+
this.cipher = new CipherState(k);
|
|
142
|
+
}
|
|
143
|
+
mixPsk() {
|
|
144
|
+
const [ck, h, k] = hkdf(this.ck, this.o.psk, 3);
|
|
145
|
+
this.ck = ck;
|
|
146
|
+
this.mixHash(h);
|
|
147
|
+
this.cipher = new CipherState(k);
|
|
148
|
+
}
|
|
149
|
+
seal(plain) {
|
|
150
|
+
const out = this.cipher ? this.cipher.encrypt(plain, this.h) : plain;
|
|
151
|
+
this.mixHash(out);
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
unseal(data) {
|
|
155
|
+
const out = this.cipher ? this.cipher.decrypt(data, this.h) : data;
|
|
156
|
+
this.mixHash(data);
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
/** The DH of a two-letter token: the first letter is the initiator's key. */
|
|
160
|
+
mixDh(token) {
|
|
161
|
+
const [mine, theirs] = this.o.initiator ? [token[0], token[1]] : [token[1], token[0]];
|
|
162
|
+
this.mixKey(dh((mine === 'e' ? this.e : this.o.static).private, (theirs === 'e' ? this.re : this.rs)));
|
|
163
|
+
}
|
|
164
|
+
tokens(writing) {
|
|
165
|
+
if (this.done || (this.step % 2 === 0) !== (writing === this.o.initiator))
|
|
166
|
+
throw new NoiseError('not this side\'s turn');
|
|
167
|
+
return PATTERNS[this.o.kind].messages[this.step];
|
|
168
|
+
}
|
|
169
|
+
write() {
|
|
170
|
+
const out = [];
|
|
171
|
+
for (const t of this.tokens(true)) {
|
|
172
|
+
if (t === 'psk')
|
|
173
|
+
this.mixPsk();
|
|
174
|
+
else if (t === 'e') {
|
|
175
|
+
out.push(this.e.public);
|
|
176
|
+
this.mixHash(this.e.public);
|
|
177
|
+
if (this.o.psk)
|
|
178
|
+
this.mixKey(this.e.public);
|
|
179
|
+
}
|
|
180
|
+
else if (t === 's')
|
|
181
|
+
out.push(this.seal(this.o.static.public));
|
|
182
|
+
else
|
|
183
|
+
this.mixDh(t);
|
|
184
|
+
}
|
|
185
|
+
out.push(this.seal(EMPTY));
|
|
186
|
+
this.step++;
|
|
187
|
+
return Buffer.concat(out);
|
|
188
|
+
}
|
|
189
|
+
/** A message that fails leaves the handshake useless: drop it. */
|
|
190
|
+
read(message) {
|
|
191
|
+
let rest = message;
|
|
192
|
+
const take = (n) => {
|
|
193
|
+
if (rest.length < n)
|
|
194
|
+
throw new NoiseError('message too short');
|
|
195
|
+
const part = rest.subarray(0, n);
|
|
196
|
+
rest = rest.subarray(n);
|
|
197
|
+
return part;
|
|
198
|
+
};
|
|
199
|
+
for (const t of this.tokens(false)) {
|
|
200
|
+
if (t === 'psk')
|
|
201
|
+
this.mixPsk();
|
|
202
|
+
else if (t === 'e') {
|
|
203
|
+
this.re = Buffer.from(take(DH_LEN));
|
|
204
|
+
this.mixHash(this.re);
|
|
205
|
+
if (this.o.psk)
|
|
206
|
+
this.mixKey(this.re);
|
|
207
|
+
}
|
|
208
|
+
else if (t === 's')
|
|
209
|
+
this.rs = this.unseal(take(DH_LEN + TAG_LEN));
|
|
210
|
+
else
|
|
211
|
+
this.mixDh(t);
|
|
212
|
+
}
|
|
213
|
+
if (rest.length !== TAG_LEN)
|
|
214
|
+
throw new NoiseError('wrong message length');
|
|
215
|
+
this.unseal(rest);
|
|
216
|
+
this.step++;
|
|
217
|
+
}
|
|
218
|
+
/** The two keys after the handshake, for this side. */
|
|
219
|
+
split() {
|
|
220
|
+
if (!this.done)
|
|
221
|
+
throw new NoiseError('the handshake is not finished');
|
|
222
|
+
const [first, second] = hkdf(this.ck, EMPTY, 2).map((k) => new CipherState(k));
|
|
223
|
+
return this.o.initiator ? { send: first, receive: second } : { send: second, receive: first };
|
|
224
|
+
}
|
|
225
|
+
}
|