@stav-ai/cli 0.1.0 → 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/README.md CHANGED
@@ -31,14 +31,16 @@ The first release launches **Claude Code** (`claude`) and **Codex**
31
31
  1. Checks the app can be launched, and that your workspace has credits.
32
32
  2. Shows what it will do, and asks once.
33
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);
34
+ - a personal key, under your workspace's key policy; if that policy
35
+ refuses it and you are an owner or admin, a workspace key instead;
36
36
  - named for the app and you, marked with the app in your request log;
37
37
  - with only the scope the app needs (`inference:messages` for Claude Code,
38
38
  `inference:chat` for Codex).
39
39
  4. Starts the app with the Stav gateway and the key in its environment.
40
40
  **No file is written.** Your `~/.claude` and `~/.codex/config.toml` are not
41
- changed.
41
+ changed. For a model Claude Code does not know, the CLI also tells it the
42
+ model's context window (`CLAUDE_CODE_MAX_CONTEXT_TOKENS`, the largest
43
+ window Stav serves that model at for your workspace).
42
44
 
43
45
  The key is kept in your operating system's keychain, or in a file only you
44
46
  can read when there is no keychain. Never in your project folder.
@@ -16,6 +16,23 @@ import { promises as fs } from 'node:fs';
16
16
  import os from 'node:os';
17
17
  import path from 'node:path';
18
18
  import list from './adapters.json' with { type: 'json' };
19
+ /**
20
+ * A model Claude Code knows by name brings its own window, and for one of
21
+ * those CLAUDE_CODE_MAX_CONTEXT_TOKENS is ignored unless compaction is off.
22
+ * A bare claude-* id or an anthropic/claude-* id is left alone.
23
+ */
24
+ function claudeKnows(model) {
25
+ return /^(anthropic\/)?claude-/.test(model);
26
+ }
27
+ /**
28
+ * Whether Claude Code should be told this model's window: a model it does
29
+ * not know, and not "auto" or an @workspace/router (the endpoint list then
30
+ * spans every model the Router may pick, and the largest is not the one
31
+ * served).
32
+ */
33
+ function claudeNeedsWindow(model) {
34
+ return model !== null && model !== 'auto' && !model.startsWith('@') && !claudeKnows(model);
35
+ }
19
36
  /** A model id as the gateway takes it; mirrors launch_recipes.MODEL_RE. */
20
37
  export const MODEL_RE = /^[a-z0-9@][a-z0-9._/@:-]{0,127}$/;
21
38
  const claudeCode = {
@@ -24,7 +41,8 @@ const claudeCode = {
24
41
  displayName: 'Claude Code',
25
42
  program: 'claude',
26
43
  scopes: ['inference:messages'],
27
- plan({ gatewayUrl, key, model }) {
44
+ wantsContextWindow: claudeNeedsWindow,
45
+ plan({ gatewayUrl, key, model, contextWindow }) {
28
46
  // Claude Code adds /v1 itself: the base URL is the origin. AUTH_TOKEN is
29
47
  // sent as a Bearer with no approval prompt; API_KEY would ask once, and
30
48
  // both together are ambiguous, so API_KEY is removed.
@@ -36,7 +54,22 @@ const claudeCode = {
36
54
  env.ANTHROPIC_MODEL = model;
37
55
  env.ANTHROPIC_SMALL_FAST_MODEL = model;
38
56
  env.ANTHROPIC_DEFAULT_HAIKU_MODEL = model;
57
+ // Claude Code does not know a non-Claude model's window and assumes
58
+ // 200k. The real one lets it compact at the right point.
59
+ if (contextWindow && claudeNeedsWindow(model))
60
+ env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = String(contextWindow);
39
61
  }
62
+ // A window from the person's own shell (another gateway, another model)
63
+ // must never reach a Stav launch: with none from Stav, whatever the
64
+ // model, Claude Code uses its own figure.
65
+ const unsetWindow = !env.CLAUDE_CODE_MAX_CONTEXT_TOKENS ? ['CLAUDE_CODE_MAX_CONTEXT_TOKENS'] : [];
66
+ // The preview runs before the key exists, so the window is not known
67
+ // yet (contextWindow undefined): it is named, not given.
68
+ const describeWindow = env.CLAUDE_CODE_MAX_CONTEXT_TOKENS
69
+ ? [`CLAUDE_CODE_MAX_CONTEXT_TOKENS=${env.CLAUDE_CODE_MAX_CONTEXT_TOKENS} (the model's context window in your workspace)`]
70
+ : contextWindow === undefined && claudeNeedsWindow(model)
71
+ ? ["CLAUDE_CODE_MAX_CONTEXT_TOKENS=<the model's largest context window in your workspace, read from Stav; a long chat then sends more tokens per turn before it is compacted>"]
72
+ : [];
40
73
  return {
41
74
  program: 'claude',
42
75
  args: [],
@@ -46,11 +79,13 @@ const claudeCode = {
46
79
  'ANTHROPIC_API_KEY',
47
80
  'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',
48
81
  'ANTHROPIC_BEDROCK_BASE_URL', 'ANTHROPIC_VERTEX_BASE_URL', 'ANTHROPIC_FOUNDRY_BASE_URL',
82
+ ...unsetWindow,
49
83
  ],
50
84
  describe: [
51
85
  `ANTHROPIC_BASE_URL=${gatewayUrl}`,
52
86
  'ANTHROPIC_AUTH_TOKEN=<the key, in the environment only>',
53
87
  model ? `model ${model}` : "Claude Code's own default model",
88
+ ...describeWindow,
54
89
  ],
55
90
  };
56
91
  },
@@ -13,6 +13,7 @@ import http from 'node:http';
13
13
  import { spawn } from 'node:child_process';
14
14
  import { StavError } from '../errors.js';
15
15
  import { USER_AGENT } from '../http.js';
16
+ import { terminalText } from '../terminal-text.js';
16
17
  import { challengeOf, newState, newVerifier } from './pkce.js';
17
18
  export const CALLBACK_PORTS = [53682, 53683, 53684];
18
19
  const SESSION_KEY = 'session';
@@ -104,7 +105,7 @@ export const defaultIO = {
104
105
  // The URL is printed too.
105
106
  }
106
107
  },
107
- log: (line) => process.stderr.write(`${line}\n`),
108
+ log: (line) => process.stderr.write(`${terminalText(line)}\n`),
108
109
  };
109
110
  /** Text from a web page, safe to print: no control characters, bounded. */
110
111
  export function printable(text) {
package/dist/cli.js CHANGED
@@ -16,6 +16,7 @@ import { loadConfig } from './config.js';
16
16
  import { StavError } from './errors.js';
17
17
  import { launch, runChild, which } from './launch.js';
18
18
  import { terminal } from './prompt.js';
19
+ import { terminalText } from './terminal-text.js';
19
20
  import { Stav } from './stav.js';
20
21
  import { forgetAppKeys, openStore, readSettings, writeSetting } from './store/index.js';
21
22
  import { VERSION } from './version.js';
@@ -42,8 +43,9 @@ Examples:
42
43
  stav launch claude
43
44
  stav launch codex --model zai-org/glm-5-2
44
45
  `;
45
- const out = (line = '') => process.stdout.write(`${line}\n`);
46
- const err = (line) => process.stderr.write(`${line}\n`);
46
+ // Every line goes through terminalText: much of it is text from the Stav API.
47
+ const out = (line = '') => process.stdout.write(`${terminalText(line)}\n`);
48
+ const err = (line) => process.stderr.write(`${terminalText(line)}\n`);
47
49
  async function main(argv) {
48
50
  const dash = argv.indexOf('--');
49
51
  const own = dash >= 0 ? argv.slice(0, dash) : argv;
package/dist/http.js CHANGED
@@ -20,7 +20,7 @@ export async function request(fetchFn, url, opts = {}) {
20
20
  method: opts.method ?? (opts.body !== undefined ? 'POST' : 'GET'),
21
21
  headers,
22
22
  body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
23
- signal: AbortSignal.timeout(30_000),
23
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
24
24
  });
25
25
  }
26
26
  catch (err) {
package/dist/launch.js CHANGED
@@ -78,10 +78,10 @@ export async function planLaunch(opts, d) {
78
78
  return { adapter, slug, model, programPath, key: { secret: stored.secret, source: 'stored' }, workspace, rememberWorkspace, person, token };
79
79
  }
80
80
  }
81
- const teamKey = role === 'OWNER' || role === 'ADMIN';
81
+ const orWorkspaceKey = role === 'OWNER' || role === 'ADMIN';
82
82
  return {
83
83
  adapter, slug, model, programPath, workspace, rememberWorkspace, person, token,
84
- key: { create: true, teamKey, name: `${adapter.displayName} (${me.email})` },
84
+ key: { create: true, orWorkspaceKey, name: `${adapter.displayName} (${me.email})` },
85
85
  };
86
86
  }
87
87
  function checkLaunchable(app, adapter, slug) {
@@ -127,25 +127,44 @@ async function explainRefusal(err, stav, token, teamId, workspaceName) {
127
127
  };
128
128
  return text[err.code] ? new StavError(text[err.code], err.code, err.status) : err;
129
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
+ ]);
130
142
  /** Make the key if the plan says so, store it, and return the secret. */
131
143
  export async function settleKey(plan, d) {
132
144
  if (!('create' in plan.key))
133
145
  return plan.key.secret;
134
146
  const stav = new Stav(d.cfg, d.fetchFn);
135
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;
136
149
  let made;
150
+ let personal = true;
137
151
  try {
138
- made = plan.key.teamKey
139
- ? await stav.createTeamKey(plan.token, plan.workspace.id, body)
140
- : await stav.createUserKey(plan.token, plan.workspace.id, body);
152
+ made = await stav.createUserKey(plan.token, plan.workspace.id, body);
141
153
  }
142
154
  catch (err) {
143
- if (err instanceof StavError)
144
- throw await explainRefusal(err, stav, plan.token, plan.workspace.id, plan.workspace.name);
145
- throw 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
+ }
146
165
  }
147
166
  await saveAppKey(d.store, appKeyName(plan.workspace.id, plan.slug, plan.person), JSON.stringify({ id: made.id, secret: made.full_key }));
148
- if (!plan.key.teamKey && !(made.scopes && made.scopes.length)) {
167
+ if (personal && !(made.scopes && made.scopes.length)) {
149
168
  // A Stav that does not yet set scopes on personal keys makes a key with
150
169
  // full access: say so rather than claim it is scoped.
151
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.`);
@@ -157,11 +176,13 @@ export function describePlan(plan, launch, appArgs, storeKind = 'keychain') {
157
176
  if (plan.workspace)
158
177
  lines.push(`Workspace: ${plan.workspace.name}`);
159
178
  if ('create' in plan.key) {
160
- lines.push(plan.key.teamKey
161
- ? `Make a workspace API key "${plan.key.name}" for ${plan.adapter.displayName}, with access to ${plan.adapter.scopes.join(', ')} only.`
162
- // A Stav that does not yet limit personal keys makes this key with
163
- // full access, so this is said before the question, not after.
164
- : `Make a personal API key "${plan.key.name}" for ${plan.adapter.displayName}, asking for access to ${plan.adapter.scopes.join(', ')} only. If Stav cannot limit personal keys yet, the key has full access to your workspace.`, storeKind === 'keychain'
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'
165
186
  ? 'Keep it in your keychain (never in this folder), and use it next time.'
166
187
  : 'Keep it in a file only you can read (no keychain here; never in this folder), and use it next time.');
167
188
  }
@@ -194,7 +215,8 @@ export async function launch(opts, d) {
194
215
  if (plan.workspace && plan.rememberWorkspace)
195
216
  await d.saveSetting('workspace', plan.workspace.id);
196
217
  const secret = await settleKey(plan, d);
197
- const run = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: secret, model: plan.model });
218
+ const contextWindow = await readContextWindow(plan, secret, d);
219
+ const run = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: secret, model: plan.model, contextWindow });
198
220
  const env = { ...d.env };
199
221
  for (const k of run.unset)
200
222
  delete env[k];
@@ -202,6 +224,29 @@ export async function launch(opts, d) {
202
224
  // An argv array and no shell: nothing in a value is ever run as a command.
203
225
  return d.spawn(plan.programPath, [...run.args, ...opts.appArgs], { stdio: 'inherit', env, shell: false });
204
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
+ }
205
250
  /** PATH lookup without a shell. */
206
251
  export function which(program, env = process.env) {
207
252
  for (const dir of (env.PATH ?? '').split(path.delimiter)) {
package/dist/prompt.js CHANGED
@@ -1,11 +1,12 @@
1
1
  /** Questions in the terminal. Never asked when there is no terminal. */
2
2
  import { createInterface } from 'node:readline/promises';
3
+ import { terminalText } from './terminal-text.js';
3
4
  export const terminal = {
4
5
  interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
5
6
  async ask(question) {
6
7
  const rl = createInterface({ input: process.stdin, output: process.stderr });
7
8
  try {
8
- return (await rl.question(question)).trim();
9
+ return (await rl.question(terminalText(question))).trim();
9
10
  }
10
11
  finally {
11
12
  rl.close();
package/dist/stav.js CHANGED
@@ -1,9 +1,17 @@
1
1
  /** The Stav calls the CLI makes, typed. */
2
2
  import { StavError } from './errors.js';
3
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;
4
10
  export class Stav {
5
11
  cfg;
6
12
  fetchFn;
13
+ /** Where a note for the person goes (the launch sets it). */
14
+ onNote;
7
15
  constructor(cfg, fetchFn) {
8
16
  this.cfg = cfg;
9
17
  this.fetchFn = fetchFn;
@@ -25,6 +33,29 @@ export class Stav {
25
33
  app(slug) {
26
34
  return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/public/apps/${encodeURIComponent(slug)}`, { nullOn: [404] });
27
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
+ }
28
59
  /** Whether a key still works, and for which workspace. Null when it does not. */
29
60
  checkKey(key) {
30
61
  return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/auth/validate`, { token: key, nullOn: [401, 403] });
@@ -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
+ }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The CLI's own version. Kept equal to package.json by version.test.ts. */
2
- export const VERSION = '0.1.0';
2
+ export const VERSION = '0.1.1';
package/dist/workspace.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * no header Stav silently uses the oldest membership.
5
5
  */
6
6
  import { StavError } from './errors.js';
7
+ import { terminalText } from './terminal-text.js';
7
8
  /**
8
9
  * The chosen workspace: the one named (by id or slug), else the stored
9
10
  * choice if still a membership, else the only one, else ask. Without a
@@ -27,7 +28,7 @@ export async function chooseWorkspace(all, named, stored, prompter) {
27
28
  if (!prompter.interactive) {
28
29
  throw new StavError(`You are in ${all.length} workspaces. Choose one with --workspace <slug> or stav workspace <slug>.`, 'workspace_required');
29
30
  }
30
- all.forEach((w, i) => process.stderr.write(` ${i + 1}. ${w.name}${w.slug ? ` (${w.slug})` : ''}, ${w.role.toLowerCase()}\n`));
31
+ all.forEach((w, i) => process.stderr.write(`${terminalText(` ${i + 1}. ${w.name}${w.slug ? ` (${w.slug})` : ''}, ${w.role.toLowerCase()}`)}\n`));
31
32
  for (;;) {
32
33
  const answer = await prompter.ask(`Which workspace? 1-${all.length}: `);
33
34
  const n = Number.parseInt(answer, 10);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stav-ai/cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Run your coding agent on Stav: sign in, get a key for the app, and start it pointed at the Stav gateway.",
5
5
  "type": "module",
6
6
  "bin": {