@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/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright {yyyy} {name of copyright owner}
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Stav CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Run your coding agent on [Stav](https://stav.ai), the EU-sovereign AI gateway.
|
|
4
|
+
The CLI signs you in, makes an API key for the app with only the access it
|
|
5
|
+
needs, and starts the app pointed at Stav.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx @stav-ai/cli launch claude
|
|
9
|
+
npx @stav-ai/cli launch codex --model zai-org/glm-5-2
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Always use the scoped name `@stav-ai/cli`. The unscoped `stav` package on npm
|
|
13
|
+
is not ours.
|
|
14
|
+
|
|
15
|
+
## Commands
|
|
16
|
+
|
|
17
|
+
| Command | What it does |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `stav login` | Sign in through your browser |
|
|
20
|
+
| `stav logout` | Remove the sign-in from this machine |
|
|
21
|
+
| `stav whoami` | Who you are, and which workspace |
|
|
22
|
+
| `stav workspace [<slug>]` | Show your workspaces, or choose one |
|
|
23
|
+
| `stav apps` | The apps this CLI can launch |
|
|
24
|
+
| `stav launch <app> [--model <id>] [--workspace <slug>] [--yes] [-- <app arguments>]` | Start an app on Stav |
|
|
25
|
+
|
|
26
|
+
The first release launches **Claude Code** (`claude`) and **Codex**
|
|
27
|
+
(`codex`). The app must already be installed.
|
|
28
|
+
|
|
29
|
+
## What `stav launch` does
|
|
30
|
+
|
|
31
|
+
1. Checks the app can be launched, and that your workspace has credits.
|
|
32
|
+
2. Shows what it will do, and asks once.
|
|
33
|
+
3. Makes an API key for the app, or uses the one it saved last time:
|
|
34
|
+
- a workspace key if you are an owner or admin, a personal key if you are
|
|
35
|
+
a member (under your workspace's key policy);
|
|
36
|
+
- named for the app and you, marked with the app in your request log;
|
|
37
|
+
- with only the scope the app needs (`inference:messages` for Claude Code,
|
|
38
|
+
`inference:chat` for Codex).
|
|
39
|
+
4. Starts the app with the Stav gateway and the key in its environment.
|
|
40
|
+
**No file is written.** Your `~/.claude` and `~/.codex/config.toml` are not
|
|
41
|
+
changed.
|
|
42
|
+
|
|
43
|
+
The key is kept in your operating system's keychain, or in a file only you
|
|
44
|
+
can read when there is no keychain. Never in your project folder.
|
|
45
|
+
|
|
46
|
+
## Without signing in
|
|
47
|
+
|
|
48
|
+
Set `STAV_API_KEY` to a key you made in the portal. The CLI then makes no key
|
|
49
|
+
and does not sign you in.
|
|
50
|
+
|
|
51
|
+
## Platforms
|
|
52
|
+
|
|
53
|
+
macOS and Linux. Windows is not supported yet: use WSL.
|
|
54
|
+
|
|
55
|
+
## Privacy
|
|
56
|
+
|
|
57
|
+
The CLI sends no telemetry. It talks only to `stav.ai`, `api.stav.ai` and
|
|
58
|
+
`auth.stav.ai`.
|
|
59
|
+
|
|
60
|
+
## Source and releases
|
|
61
|
+
|
|
62
|
+
This repository is a mirror: the CLI is developed in Stav's own repository
|
|
63
|
+
and copied here for each release. Issues are welcome here; changes to the
|
|
64
|
+
code are made upstream, so a pull request here is read but not merged as is.
|
|
65
|
+
|
|
66
|
+
From 0.1.1 on, releases are built by this repository's `Release` workflow
|
|
67
|
+
with npm trusted publishing (no npm token), and a maintainer approves each
|
|
68
|
+
one with two-factor authentication before it is public.
|
|
69
|
+
|
|
70
|
+
## Licence
|
|
71
|
+
|
|
72
|
+
Apache-2.0.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_comment": "The launch adapters the Stav CLI has compiled in. A catalogue recipe may only pick one of these, for the apps listed. Kept byte-identical between the CLI and the Stav API.",
|
|
3
|
+
"version": 1,
|
|
4
|
+
"adapters": {
|
|
5
|
+
"claude-code": {
|
|
6
|
+
"apps": [
|
|
7
|
+
"claude-code"
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
"codex": {
|
|
11
|
+
"apps": [
|
|
12
|
+
"codex"
|
|
13
|
+
]
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The launch adapters compiled into this CLI (C-6, DECIDE-APPS-M).
|
|
3
|
+
*
|
|
4
|
+
* A catalogue row's recipe only picks one of these by name and may give a
|
|
5
|
+
* default model. Everything that runs on the person's machine — the program,
|
|
6
|
+
* its environment and its arguments — is here, reviewed and released with
|
|
7
|
+
* the CLI. No adapter writes a file (both apps take everything from the
|
|
8
|
+
* environment and the command line), and the key goes only into the child's
|
|
9
|
+
* environment, never into its arguments or a file (R-20).
|
|
10
|
+
*
|
|
11
|
+
* adapters.json is byte-identical to the Stav API's
|
|
12
|
+
* app/services/launch_recipes/adapters.json (the admin endpoint checks
|
|
13
|
+
* recipes against it; a lockstep test pins the copy).
|
|
14
|
+
*/
|
|
15
|
+
import { promises as fs } from 'node:fs';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import list from './adapters.json' with { type: 'json' };
|
|
19
|
+
/** A model id as the gateway takes it; mirrors launch_recipes.MODEL_RE. */
|
|
20
|
+
export const MODEL_RE = /^[a-z0-9@][a-z0-9._/@:-]{0,127}$/;
|
|
21
|
+
const claudeCode = {
|
|
22
|
+
name: 'claude-code',
|
|
23
|
+
apps: ['claude-code'],
|
|
24
|
+
displayName: 'Claude Code',
|
|
25
|
+
program: 'claude',
|
|
26
|
+
scopes: ['inference:messages'],
|
|
27
|
+
plan({ gatewayUrl, key, model }) {
|
|
28
|
+
// Claude Code adds /v1 itself: the base URL is the origin. AUTH_TOKEN is
|
|
29
|
+
// sent as a Bearer with no approval prompt; API_KEY would ask once, and
|
|
30
|
+
// both together are ambiguous, so API_KEY is removed.
|
|
31
|
+
const env = {
|
|
32
|
+
ANTHROPIC_BASE_URL: gatewayUrl,
|
|
33
|
+
ANTHROPIC_AUTH_TOKEN: key,
|
|
34
|
+
};
|
|
35
|
+
if (model) {
|
|
36
|
+
env.ANTHROPIC_MODEL = model;
|
|
37
|
+
env.ANTHROPIC_SMALL_FAST_MODEL = model;
|
|
38
|
+
env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
program: 'claude',
|
|
42
|
+
args: [],
|
|
43
|
+
env,
|
|
44
|
+
// Settings that would send Claude Code to another provider for this run.
|
|
45
|
+
unset: [
|
|
46
|
+
'ANTHROPIC_API_KEY',
|
|
47
|
+
'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',
|
|
48
|
+
'ANTHROPIC_BEDROCK_BASE_URL', 'ANTHROPIC_VERTEX_BASE_URL', 'ANTHROPIC_FOUNDRY_BASE_URL',
|
|
49
|
+
],
|
|
50
|
+
describe: [
|
|
51
|
+
`ANTHROPIC_BASE_URL=${gatewayUrl}`,
|
|
52
|
+
'ANTHROPIC_AUTH_TOKEN=<the key, in the environment only>',
|
|
53
|
+
model ? `model ${model}` : "Claude Code's own default model",
|
|
54
|
+
],
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
async conflicts(home = os.homedir(), cwd = process.cwd()) {
|
|
58
|
+
// An env block in a Claude Code settings file beats the shell's
|
|
59
|
+
// environment, so the launch (and the key) would go elsewhere: the
|
|
60
|
+
// user's own file, and the project's files in the folder it starts in.
|
|
61
|
+
const files = [
|
|
62
|
+
[path.join(home, '.claude', 'settings.json'), '~/.claude/settings.json'],
|
|
63
|
+
[path.join(cwd, '.claude', 'settings.json'), '.claude/settings.json in this folder'],
|
|
64
|
+
[path.join(cwd, '.claude', 'settings.local.json'), '.claude/settings.local.json in this folder'],
|
|
65
|
+
];
|
|
66
|
+
const watched = [
|
|
67
|
+
'ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'ANTHROPIC_MODEL',
|
|
68
|
+
'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',
|
|
69
|
+
];
|
|
70
|
+
for (const [file, label] of files) {
|
|
71
|
+
try {
|
|
72
|
+
const raw = await fs.readFile(file, 'utf8');
|
|
73
|
+
const env = JSON.parse(raw).env ?? {};
|
|
74
|
+
const hits = watched.filter((k) => k in env);
|
|
75
|
+
if (hits.length) {
|
|
76
|
+
return `${label} sets ${hits.join(', ')} in its "env" block, which overrides the launch and would send your Stav key there. Remove ${hits.length > 1 ? 'them' : 'it'}, then run stav launch again.`;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// No file, or not JSON: nothing overrides.
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
const codex = {
|
|
87
|
+
name: 'codex',
|
|
88
|
+
apps: ['codex'],
|
|
89
|
+
displayName: 'Codex',
|
|
90
|
+
program: 'codex',
|
|
91
|
+
scopes: ['inference:chat'],
|
|
92
|
+
plan({ gatewayUrl, key, model }) {
|
|
93
|
+
// Codex takes the whole provider from -c overrides (checked with codex
|
|
94
|
+
// 0.151), so ~/.codex/config.toml is never touched. The key is read
|
|
95
|
+
// from STAV_API_KEY through env_key.
|
|
96
|
+
const base = `${gatewayUrl}/v1`;
|
|
97
|
+
const args = [
|
|
98
|
+
'-c', 'model_provider="stav"',
|
|
99
|
+
'-c', 'model_providers.stav.name="Stav"',
|
|
100
|
+
'-c', `model_providers.stav.base_url=${JSON.stringify(base)}`,
|
|
101
|
+
'-c', 'model_providers.stav.env_key="STAV_API_KEY"',
|
|
102
|
+
'-c', 'model_providers.stav.wire_api="responses"',
|
|
103
|
+
'-c', 'web_search="disabled"',
|
|
104
|
+
];
|
|
105
|
+
if (model)
|
|
106
|
+
args.push('-m', model);
|
|
107
|
+
return {
|
|
108
|
+
program: 'codex',
|
|
109
|
+
args,
|
|
110
|
+
env: { STAV_API_KEY: key },
|
|
111
|
+
unset: [],
|
|
112
|
+
describe: [
|
|
113
|
+
`a "stav" model provider at ${base}, for this run only (your ~/.codex/config.toml is not changed)`,
|
|
114
|
+
'STAV_API_KEY=<the key, in the environment only>',
|
|
115
|
+
model ? `model ${model}` : "Codex's own default model",
|
|
116
|
+
],
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
export const ADAPTERS = [claudeCode, codex];
|
|
121
|
+
/** Names a person may type for an app (DECIDE-APPS-P: `claude` → claude-code). */
|
|
122
|
+
export const ALIASES = { claude: 'claude-code' };
|
|
123
|
+
export function resolveApp(name) {
|
|
124
|
+
const n = name.trim().toLowerCase();
|
|
125
|
+
return ALIASES[n] ?? n;
|
|
126
|
+
}
|
|
127
|
+
export function adapterFor(adapterName) {
|
|
128
|
+
return ADAPTERS.find((a) => a.name === adapterName);
|
|
129
|
+
}
|
|
130
|
+
export function adapterForApp(slug) {
|
|
131
|
+
return ADAPTERS.find((a) => a.apps.includes(slug));
|
|
132
|
+
}
|
|
133
|
+
/** The list the server shares with this build. */
|
|
134
|
+
export const ADAPTER_LIST = list;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** PKCE (RFC 7636) and the state value, from node:crypto only. */
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
const b64url = (buf) => buf.toString('base64url');
|
|
4
|
+
export function newVerifier() {
|
|
5
|
+
return b64url(randomBytes(32));
|
|
6
|
+
}
|
|
7
|
+
export function challengeOf(verifier) {
|
|
8
|
+
return b64url(createHash('sha256').update(verifier).digest());
|
|
9
|
+
}
|
|
10
|
+
export function newState() {
|
|
11
|
+
return b64url(randomBytes(16));
|
|
12
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in through the browser (R-17, C-4): Auth0 authorization code with
|
|
3
|
+
* PKCE on a loopback redirect, on a native application with no secret.
|
|
4
|
+
*
|
|
5
|
+
* - The listener binds 127.0.0.1 only, on one of three fixed ports (the
|
|
6
|
+
* callback URLs registered on the Auth0 application).
|
|
7
|
+
* - The answer must carry the state we sent; the code is exchanged with the
|
|
8
|
+
* PKCE verifier.
|
|
9
|
+
* - offline_access gives a refresh token, so the browser opens once; a
|
|
10
|
+
* refresh also skips the human check on first login (it ran already).
|
|
11
|
+
*/
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { StavError } from '../errors.js';
|
|
15
|
+
import { USER_AGENT } from '../http.js';
|
|
16
|
+
import { challengeOf, newState, newVerifier } from './pkce.js';
|
|
17
|
+
export const CALLBACK_PORTS = [53682, 53683, 53684];
|
|
18
|
+
const SESSION_KEY = 'session';
|
|
19
|
+
const SCOPE = 'openid profile email offline_access';
|
|
20
|
+
function needClientId(cfg) {
|
|
21
|
+
if (!cfg.auth0ClientId) {
|
|
22
|
+
throw new StavError('This build of the Stav CLI has no sign-in application yet. Set STAV_API_KEY to use a key, or STAV_AUTH0_CLIENT_ID.', 'no_client_id');
|
|
23
|
+
}
|
|
24
|
+
return cfg.auth0ClientId;
|
|
25
|
+
}
|
|
26
|
+
async function tokenCall(fetchFn, cfg, body) {
|
|
27
|
+
let res;
|
|
28
|
+
try {
|
|
29
|
+
res = await fetchFn(`https://${cfg.auth0Domain}/oauth/token`, {
|
|
30
|
+
method: 'POST',
|
|
31
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': USER_AGENT },
|
|
32
|
+
body: new URLSearchParams(body).toString(),
|
|
33
|
+
signal: AbortSignal.timeout(30_000),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new StavError(`Could not reach ${cfg.auth0Domain}.`, 'network');
|
|
38
|
+
}
|
|
39
|
+
const data = (await res.json().catch(() => ({})));
|
|
40
|
+
if (!res.ok || typeof data.access_token !== 'string') {
|
|
41
|
+
const reason = typeof data.error_description === 'string' ? printable(data.error_description) : `HTTP ${res.status}`;
|
|
42
|
+
throw new StavError(`Sign-in failed: ${reason}`, 'sign_in_failed', res.status);
|
|
43
|
+
}
|
|
44
|
+
return data;
|
|
45
|
+
}
|
|
46
|
+
function toSession(t, previous) {
|
|
47
|
+
return {
|
|
48
|
+
access_token: t.access_token,
|
|
49
|
+
// A rotated refresh token replaces the old one; keep the old one when none came back.
|
|
50
|
+
refresh_token: t.refresh_token ?? previous?.refresh_token,
|
|
51
|
+
expires_at: Math.floor(Date.now() / 1000) + Math.max(0, (t.expires_in ?? 0) - 60),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export async function readSession(store) {
|
|
55
|
+
const raw = await store.get(SESSION_KEY);
|
|
56
|
+
if (!raw)
|
|
57
|
+
return null;
|
|
58
|
+
try {
|
|
59
|
+
const s = JSON.parse(raw);
|
|
60
|
+
return typeof s.access_token === 'string' ? s : null;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** A valid access token, refreshed when it is old; null when not signed in. */
|
|
67
|
+
export async function accessToken(fetchFn, cfg, store) {
|
|
68
|
+
const s = await readSession(store);
|
|
69
|
+
if (!s)
|
|
70
|
+
return null;
|
|
71
|
+
if (s.expires_at > Math.floor(Date.now() / 1000))
|
|
72
|
+
return s.access_token;
|
|
73
|
+
if (!s.refresh_token)
|
|
74
|
+
return null;
|
|
75
|
+
try {
|
|
76
|
+
const t = await tokenCall(fetchFn, cfg, {
|
|
77
|
+
grant_type: 'refresh_token',
|
|
78
|
+
client_id: needClientId(cfg),
|
|
79
|
+
refresh_token: s.refresh_token,
|
|
80
|
+
});
|
|
81
|
+
const next = toSession(t, s);
|
|
82
|
+
await store.set(SESSION_KEY, JSON.stringify(next));
|
|
83
|
+
return next.access_token;
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
// A refused refresh token (expired, revoked) means "sign in again". A
|
|
87
|
+
// network failure or an Auth0 outage is said as what it is.
|
|
88
|
+
if (err instanceof StavError && (err.status === 400 || err.status === 401 || err.status === 403))
|
|
89
|
+
return null;
|
|
90
|
+
throw err instanceof StavError ? err : new StavError(`Could not reach ${cfg.auth0Domain} to renew the sign-in.`, 'network');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export const defaultIO = {
|
|
94
|
+
open(url) {
|
|
95
|
+
const [cmd, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
96
|
+
: process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
97
|
+
: ['xdg-open', [url]];
|
|
98
|
+
try {
|
|
99
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
100
|
+
child.on('error', () => undefined);
|
|
101
|
+
child.unref();
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// The URL is printed too.
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
log: (line) => process.stderr.write(`${line}\n`),
|
|
108
|
+
};
|
|
109
|
+
/** Text from a web page, safe to print: no control characters, bounded. */
|
|
110
|
+
export function printable(text) {
|
|
111
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').slice(0, 300);
|
|
112
|
+
}
|
|
113
|
+
/** Listen on the first free callback port; resolve with the code or reject. */
|
|
114
|
+
function listen(expectedState, timeoutMs) {
|
|
115
|
+
return new Promise((resolveListen, rejectListen) => {
|
|
116
|
+
let resolveCode;
|
|
117
|
+
let rejectCode;
|
|
118
|
+
const code = new Promise((res, rej) => {
|
|
119
|
+
resolveCode = res;
|
|
120
|
+
rejectCode = rej;
|
|
121
|
+
});
|
|
122
|
+
const server = http.createServer((req, res) => {
|
|
123
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
124
|
+
if (url.pathname !== '/callback') {
|
|
125
|
+
res.writeHead(404).end();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
// Only an answer with our state counts. Anything else (a stray tab, a
|
|
129
|
+
// page that knows the port) is ignored, and the CLI keeps waiting.
|
|
130
|
+
if (url.searchParams.get('state') !== expectedState) {
|
|
131
|
+
res.writeHead(400, { 'Content-Type': 'text/plain' }).end('This is not the sign-in the Stav CLI started.');
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const page = (title) => `<!doctype html><meta charset="utf-8"><title>Stav CLI</title><body style="font-family:system-ui;margin:4rem"><h1>${title}</h1><p>You can close this tab and go back to the terminal.</p></body>`;
|
|
135
|
+
const err = url.searchParams.get('error');
|
|
136
|
+
if (err) {
|
|
137
|
+
res.writeHead(400, { 'Content-Type': 'text/html' }).end(page('Sign-in was not completed'));
|
|
138
|
+
rejectCode(new StavError(`Sign-in was not completed: ${printable(url.searchParams.get('error_description') ?? err)}`, 'sign_in_failed'));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const got = url.searchParams.get('code');
|
|
142
|
+
if (!got) {
|
|
143
|
+
res.writeHead(400).end();
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
res.writeHead(200, { 'Content-Type': 'text/html' }).end(page('You are signed in to Stav'));
|
|
147
|
+
resolveCode(got);
|
|
148
|
+
});
|
|
149
|
+
const timer = setTimeout(() => rejectCode(new StavError('Sign-in timed out. Run stav login again.', 'timeout')), timeoutMs);
|
|
150
|
+
timer.unref();
|
|
151
|
+
const close = () => {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
server.close();
|
|
154
|
+
};
|
|
155
|
+
const tryPort = (i) => {
|
|
156
|
+
if (i >= CALLBACK_PORTS.length) {
|
|
157
|
+
rejectListen(new StavError(`Ports ${CALLBACK_PORTS.join(', ')} on 127.0.0.1 are all in use.`, 'ports_busy'));
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const port = CALLBACK_PORTS[i];
|
|
161
|
+
const onListening = () => {
|
|
162
|
+
server.off('error', onError);
|
|
163
|
+
resolveListen({ port, code, close });
|
|
164
|
+
};
|
|
165
|
+
const onError = () => {
|
|
166
|
+
// A busy port: drop this attempt's listener, or a later success
|
|
167
|
+
// would report this port to Auth0.
|
|
168
|
+
server.off('listening', onListening);
|
|
169
|
+
tryPort(i + 1);
|
|
170
|
+
};
|
|
171
|
+
server.once('error', onError);
|
|
172
|
+
server.once('listening', onListening);
|
|
173
|
+
server.listen(port, '127.0.0.1');
|
|
174
|
+
};
|
|
175
|
+
tryPort(0);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
export async function login(fetchFn, cfg, store, io = defaultIO, timeoutMs = 5 * 60_000) {
|
|
179
|
+
const clientId = needClientId(cfg);
|
|
180
|
+
const verifier = newVerifier();
|
|
181
|
+
const state = newState();
|
|
182
|
+
const listener = await listen(state, timeoutMs);
|
|
183
|
+
try {
|
|
184
|
+
const redirectUri = `http://127.0.0.1:${listener.port}/callback`;
|
|
185
|
+
const url = new URL(`https://${cfg.auth0Domain}/authorize`);
|
|
186
|
+
url.search = new URLSearchParams({
|
|
187
|
+
response_type: 'code',
|
|
188
|
+
client_id: clientId,
|
|
189
|
+
redirect_uri: redirectUri,
|
|
190
|
+
audience: cfg.auth0Audience,
|
|
191
|
+
scope: SCOPE,
|
|
192
|
+
code_challenge: challengeOf(verifier),
|
|
193
|
+
code_challenge_method: 'S256',
|
|
194
|
+
state,
|
|
195
|
+
}).toString();
|
|
196
|
+
io.log('Opening your browser to sign in to Stav. If it does not open, visit:');
|
|
197
|
+
io.log(url.toString());
|
|
198
|
+
io.open(url.toString());
|
|
199
|
+
const code = await listener.code;
|
|
200
|
+
const t = await tokenCall(fetchFn, cfg, {
|
|
201
|
+
grant_type: 'authorization_code',
|
|
202
|
+
client_id: clientId,
|
|
203
|
+
code,
|
|
204
|
+
code_verifier: verifier,
|
|
205
|
+
redirect_uri: redirectUri,
|
|
206
|
+
});
|
|
207
|
+
const session = toSession(t);
|
|
208
|
+
await store.set(SESSION_KEY, JSON.stringify(session));
|
|
209
|
+
return session;
|
|
210
|
+
}
|
|
211
|
+
finally {
|
|
212
|
+
listener.close();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/** Remove the sign-in here and revoke its refresh token at Auth0. */
|
|
216
|
+
export async function logout(fetchFn, cfg, store) {
|
|
217
|
+
const s = await readSession(store);
|
|
218
|
+
await store.delete(SESSION_KEY);
|
|
219
|
+
if (s?.refresh_token && cfg.auth0ClientId) {
|
|
220
|
+
await fetchFn(`https://${cfg.auth0Domain}/oauth/revoke`, {
|
|
221
|
+
method: 'POST',
|
|
222
|
+
headers: { 'Content-Type': 'application/json', 'User-Agent': USER_AGENT },
|
|
223
|
+
body: JSON.stringify({ client_id: cfg.auth0ClientId, token: s.refresh_token }),
|
|
224
|
+
signal: AbortSignal.timeout(15_000),
|
|
225
|
+
}).catch(() => undefined);
|
|
226
|
+
}
|
|
227
|
+
return s !== null;
|
|
228
|
+
}
|