@stav-ai/cli 0.1.3 → 0.1.5

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
@@ -10,6 +10,7 @@ npx @stav-ai/cli launch codex --model zai-org/glm-5-2
10
10
  npx @stav-ai/cli launch dsh -- "run the tests"
11
11
  npx @stav-ai/cli launch kilo
12
12
  npx @stav-ai/cli launch copilot
13
+ npx @stav-ai/cli launch pi
13
14
  ```
14
15
 
15
16
  Always use the scoped name `@stav-ai/cli`. The unscoped `stav` package on npm
@@ -27,9 +28,11 @@ is not ours.
27
28
  | `stav launch <app> [--model <id>] [--workspace <slug>] [--yes] [-- <app arguments>]` | Start an app on Stav |
28
29
 
29
30
  It launches **Claude Code** (`claude`), **Codex** (`codex`),
30
- **DeepSeek Harness** (`dsh`), **Kilo Code** (`kilo`) and the
31
- **GitHub Copilot CLI** (`copilot`). The app must
32
- already be installed.
31
+ **DeepSeek Harness** (`dsh`), **Kilo Code** (`kilo`), the
32
+ **GitHub Copilot CLI** (`copilot`) and **pi** (`pi`). If the app is
33
+ not installed, it offers to install it with `npm install -g` and does so
34
+ only if you say yes. With `--yes`, or with no terminal, it installs
35
+ nothing and prints the command instead.
33
36
 
34
37
  ## What `stav launch` does
35
38
 
@@ -40,8 +43,8 @@ already be installed.
40
43
  refuses it and you are an owner or admin, a workspace key instead;
41
44
  - named for the app and you, marked with the app in your request log;
42
45
  - with only the scope the app needs (`inference:messages` for Claude Code,
43
- `inference:chat` for Codex, DeepSeek Harness, Kilo Code and the
44
- GitHub Copilot CLI).
46
+ `inference:chat` for Codex, DeepSeek Harness, Kilo Code, the
47
+ GitHub Copilot CLI and pi).
45
48
  4. Starts the app with the Stav gateway and the key in its environment.
46
49
  **No file is written.** Your `~/.claude` and `~/.codex/config.toml` are not
47
50
  changed. For a model Claude Code does not know, the CLI also tells it the
@@ -83,6 +86,15 @@ already be installed.
83
86
  edits and commands: add `--allow-tool` or `--allow-all-tools` after the
84
87
  task to allow them without asking.
85
88
 
89
+ pi reads a provider's address only from its own `models.json`, so the CLI
90
+ starts it with `--extension` and a provider file that ships with the CLI.
91
+ That file holds no key and no address: every value comes from the
92
+ environment, and the key is only in `STAV_PI_API_KEY`. No provider
93
+ settings are written to `~/.pi/agent`. The CLI also sets `PI_OFFLINE=1`, so pi does not refresh
94
+ its model catalogue or check for updates at pi.dev. pi runs the commands
95
+ the model writes without asking. For one task without the chat screen,
96
+ give `-p "<task>"` after `--`.
97
+
86
98
  The key is kept in your operating system's keychain, or in a file only you
87
99
  can read when there is no keychain. Never in your project folder.
88
100
 
@@ -26,6 +26,11 @@
26
26
  "apps": [
27
27
  "github-copilot"
28
28
  ]
29
+ },
30
+ "pi": {
31
+ "apps": [
32
+ "pi"
33
+ ]
29
34
  }
30
35
  }
31
36
  }
@@ -8,8 +8,10 @@
8
8
  * from the environment and the command line, DeepSeek Harness reads a
9
9
  * fixed overlay file shipped with the CLI (deepseek-harness.patch.yml) whose
10
10
  * values all come from the environment, Kilo Code takes its whole
11
- * provider from KILO_CONFIG_CONTENT, and the GitHub Copilot CLI from its
12
- * COPILOT_PROVIDER_* variables. The key goes only into the child's
11
+ * provider from KILO_CONFIG_CONTENT, the GitHub Copilot CLI from its
12
+ * COPILOT_PROVIDER_* variables, and pi from a fixed provider extension
13
+ * shipped with the CLI (pi-stav-provider.js) whose values all come from the
14
+ * environment. The key goes only into the child's
13
15
  * environment, never into its arguments or a file (R-20).
14
16
  *
15
17
  * adapters.json is byte-identical to the Stav API's
@@ -221,6 +223,53 @@ const deepseekHarness = {
221
223
  };
222
224
  },
223
225
  };
226
+ /**
227
+ * The most bytes the model list may take in the one environment variable
228
+ * that carries it. Linux refuses a single variable over 128 KiB
229
+ * (MAX_ARG_STRLEN) and the program would not start; this leaves room for
230
+ * the rest of the value. macOS has no per-variable limit below that. Windows
231
+ * (32,767 characters per variable) is not a concern: `stav launch` refuses
232
+ * win32 before any adapter runs (checkLaunch in launch.ts, code
233
+ * `unsupported_platform`). Lower this before launches on Windows are allowed.
234
+ */
235
+ export const MODEL_LIST_BUDGET = 96_000;
236
+ /**
237
+ * The models an app's picker offers: the launch's own model first, with its
238
+ * window, then every other one the key may use, in the order Stav gave them
239
+ * (auto, the Routers, the models). Models past ``budget`` bytes, as
240
+ * ``entryBytes`` counts them, are left out and counted in ``dropped``; the
241
+ * launch's model, ``auto`` and the Routers are always kept.
242
+ */
243
+ export function pickerModels(ctx, defaultContext, entryBytes, budget = MODEL_LIST_BUDGET) {
244
+ const id = ctx.model ?? 'auto';
245
+ const first = { id, contextWindow: ctx.contextWindow && namedModel(ctx.model) ? ctx.contextWindow : defaultContext };
246
+ const out = [first];
247
+ let used = entryBytes(first);
248
+ let dropped = 0;
249
+ for (const m of ctx.models ?? []) {
250
+ if (m.id === id)
251
+ continue;
252
+ const entry = { id: m.id, contextWindow: m.contextWindow ?? defaultContext };
253
+ const n = entryBytes(entry);
254
+ if (namedModel(m.id) && used + n > budget) {
255
+ dropped += 1;
256
+ continue;
257
+ }
258
+ used += n;
259
+ out.push(entry);
260
+ }
261
+ return { models: out, dropped };
262
+ }
263
+ /** The plan's line about the picker, for the preview and the run. */
264
+ function describePicker(models, dropped, ctx, picker) {
265
+ if (ctx.models === undefined)
266
+ return `every chat model and Router your key may use, read from Stav, to pick from with ${picker}`;
267
+ if (ctx.models === null)
268
+ return `only this model in ${picker}: the list of models could not be read from Stav`;
269
+ const more = models.length - 1;
270
+ const left = dropped ? ` (${dropped} more models left out: the list would not fit in one environment variable)` : '';
271
+ return `${more} more models and Routers your key may use, to pick from with ${picker}${left}`;
272
+ }
224
273
  /** The provider id the kilo-code adapter gives Stav; one only the CLI uses, so a "stav" block a person made from the guide never merges into it. */
225
274
  export const KILO_PROVIDER = 'stav-cli';
226
275
  /**
@@ -242,7 +291,9 @@ const kiloCode = {
242
291
  program: 'kilo',
243
292
  scopes: ['inference:chat'],
244
293
  wantsContextWindow: namedModel,
245
- plan({ gatewayUrl, key, model, contextWindow }) {
294
+ wantsModelList: true,
295
+ plan(ctx) {
296
+ const { gatewayUrl, key, model, contextWindow } = ctx;
246
297
  // Kilo Code merges KILO_CONFIG_CONTENT after the global and the project
247
298
  // config files, and resolves {env:} in it (checked with Kilo Code
248
299
  // 7.8.40), so the whole provider is given in the environment and no file
@@ -255,7 +306,6 @@ const kiloCode = {
255
306
  const base = `${gatewayUrl}/v1`;
256
307
  const id = model ?? 'auto';
257
308
  const ref = `${KILO_PROVIDER}/${id}`;
258
- const window = contextWindow && namedModel(model) ? contextWindow : KILO_DEFAULT_CONTEXT;
259
309
  // The config files merge deep, so a "stav-cli" block in the person's own
260
310
  // config keeps every key this one does not set. The SDK and the address
261
311
  // are therefore set at both levels Kilo Code reads them from (provider and
@@ -263,7 +313,12 @@ const kiloCode = {
263
313
  // reach Stav, never anywhere else. Only a Kilo organisation's console
264
314
  // config and MDM-managed config merge after KILO_CONFIG_CONTENT; those are
265
315
  // set by the person's administrator and are meant to win.
316
+ // Every chat model, Router and auto the key may use is listed, so
317
+ // Kilo's model picker (/models) offers them all; the launch's model is
318
+ // the one selected.
266
319
  const sdk = '@ai-sdk/openai-compatible';
320
+ const entry = (m) => ({ name: m.id, provider: { npm: sdk, api: base }, limit: { context: m.contextWindow ?? KILO_DEFAULT_CONTEXT, output: KILO_MAX_OUTPUT } });
321
+ const picker = pickerModels(ctx, KILO_DEFAULT_CONTEXT, (m) => JSON.stringify({ [m.id]: entry(m) }).length);
267
322
  const config = {
268
323
  model: ref,
269
324
  small_model: ref,
@@ -274,9 +329,7 @@ const kiloCode = {
274
329
  api: base,
275
330
  name: 'Stav',
276
331
  options: { apiKey: '{env:STAV_KILO_API_KEY}', baseURL: base },
277
- models: {
278
- [id]: { name: id, provider: { npm: sdk, api: base }, limit: { context: window, output: KILO_MAX_OUTPUT } },
279
- },
332
+ models: Object.fromEntries(picker.models.map((m) => [m.id, entry(m)])),
280
333
  },
281
334
  },
282
335
  };
@@ -303,6 +356,7 @@ const kiloCode = {
303
356
  'STAV_KILO_API_KEY=<the key, in the environment only>',
304
357
  model ? `model ${model}` : "model auto (your workspace's default Router)",
305
358
  describeWindow,
359
+ describePicker(picker.models, picker.dropped, ctx, '/models'),
306
360
  `at most ${KILO_MAX_OUTPUT} output tokens per call`,
307
361
  'KILO_TELEMETRY_LEVEL=off, KILO_DISABLE_SESSION_INGEST=1, KILO_DISABLE_SHARE=1 (no usage data or session uploads to Kilo)',
308
362
  'note: Kilo Code runs commands and edits files. It asks before most shell commands, unless your Kilo config allows them (Kilo writes bash: allow into a config file that existed before its first start)',
@@ -383,7 +437,105 @@ const githubCopilot = {
383
437
  };
384
438
  },
385
439
  };
386
- export const ADAPTERS = [claudeCode, codex, deepseekHarness, kiloCode, githubCopilot];
440
+ /** The provider extension pi loads; built next to this module (npm run build copies it). */
441
+ export const PI_EXTENSION_FILE = fileURLToPath(new URL('./pi-stav-provider.js', import.meta.url));
442
+ /** The provider id the pi adapter registers; one only the CLI uses. */
443
+ export const PI_PROVIDER = 'stav-cli';
444
+ /** The output cap pi sends as max_completion_tokens (the value the app test proved). */
445
+ export const PI_MAX_TOKENS = 16_384;
446
+ /** The context window given for auto, a Router, or a model Stav knows none for (pi's own default). */
447
+ export const PI_DEFAULT_CONTEXT = 128_000;
448
+ const pi = {
449
+ name: 'pi',
450
+ apps: ['pi'],
451
+ displayName: 'pi',
452
+ program: 'pi',
453
+ scopes: ['inference:chat'],
454
+ wantsContextWindow: namedModel,
455
+ wantsModelList: true,
456
+ plan(ctx) {
457
+ const { gatewayUrl, key, model, contextWindow } = ctx;
458
+ // pi reads a custom provider's base URL only from models.json, so the
459
+ // shipped extension registers a "stav-cli" provider from the STAV_PI_*
460
+ // variables (checked with pi 1.7.0). --provider is always given: Stav
461
+ // model ids contain "/", which pi reads as a provider otherwise. With no
462
+ // model, "auto" (the workspace's default Router), never pi's own default.
463
+ const base = `${gatewayUrl}/v1`;
464
+ const id = model ?? 'auto';
465
+ const window = contextWindow && namedModel(model) ? contextWindow : PI_DEFAULT_CONTEXT;
466
+ // Every chat model, Router and auto the key may use, for pi's model
467
+ // picker (/model), in STAV_PI_MODELS; the launch's model comes first.
468
+ const toEnv = (m) => ({ id: m.id, contextWindow: m.contextWindow ?? PI_DEFAULT_CONTEXT });
469
+ const picker = pickerModels(ctx, PI_DEFAULT_CONTEXT, (m) => JSON.stringify(toEnv(m)).length + 1);
470
+ // undefined: the preview, before the key exists; null: read, and Stav knows none.
471
+ const describeWindow = contextWindow && namedModel(model)
472
+ ? `a context window of ${contextWindow} tokens (the model's in your workspace)`
473
+ : contextWindow === undefined && namedModel(model)
474
+ ? "the model's largest context window in your workspace, read from Stav"
475
+ : `a context window of ${PI_DEFAULT_CONTEXT} tokens (pi compacts the chat by it)`;
476
+ return {
477
+ program: 'pi',
478
+ args: ['--extension', PI_EXTENSION_FILE, '--provider', PI_PROVIDER, '--model', id],
479
+ env: {
480
+ STAV_PI_API_KEY: key,
481
+ STAV_PI_BASE_URL: base,
482
+ STAV_PI_MODEL: id,
483
+ STAV_PI_CONTEXT_WINDOW: String(window),
484
+ STAV_PI_MAX_TOKENS: String(PI_MAX_TOKENS),
485
+ STAV_PI_MODELS: JSON.stringify(picker.models.map(toEnv)),
486
+ // No model catalogue refresh or update check at pi.dev.
487
+ PI_OFFLINE: '1',
488
+ },
489
+ unset: [],
490
+ describe: [
491
+ `pi with a "${PI_PROVIDER}" provider at ${base}, loaded from a file that ships with the Stav CLI, for this run only (no provider settings are written to ~/.pi/agent)`,
492
+ 'STAV_PI_API_KEY=<the key, in the environment only>',
493
+ model ? `model ${model}` : "model auto (your workspace's default Router)",
494
+ describeWindow,
495
+ describePicker(picker.models, picker.dropped, ctx, '/model'),
496
+ `at most ${PI_MAX_TOKENS} output tokens per call`,
497
+ 'PI_OFFLINE=1 (no model catalogue refresh or update check at pi.dev)',
498
+ 'note: pi runs the commands the model writes without asking, and those commands can read STAV_PI_API_KEY from their environment; run it in a folder or container where that is safe',
499
+ 'run one task without the chat screen after --, for example: stav launch pi -- -p "fix the failing test"',
500
+ ],
501
+ };
502
+ },
503
+ async conflicts(home = os.homedir(), cwd = process.cwd(), env = process.env, appArgs = []) {
504
+ // A "stav-cli" entry in pi's own models.json is merged over the
505
+ // extension and could send the key to another address; a stored
506
+ // credential for it would replace the key. The check reads the folder pi
507
+ // will read. pi accepts comments and a BOM in these files (pi 1.7.0,
508
+ // model-config.js), so the provider id written out anywhere in them
509
+ // counts, parsed or not; an id spelled with JSON escapes is not caught.
510
+ // Not checked: extensions pi loads from <agent-dir>/extensions, from a
511
+ // trusted project's .pi/ or from packages. Those run code in pi already,
512
+ // so they can read the key with or without this launch.
513
+ if (appArgs.some((a) => a === '--agent-dir' || a.startsWith('--agent-dir='))) {
514
+ return 'stav launch pi cannot check a folder given with --agent-dir. Set PI_CODING_AGENT_DIR instead, then run stav launch again.';
515
+ }
516
+ // Exactly the value pi reads: no trimming, so both read the same folder.
517
+ const configured = env.PI_CODING_AGENT_DIR;
518
+ const expanded = configured
519
+ ? configured === '~' || configured.startsWith('~/') ? path.join(home, configured.slice(1)) : configured
520
+ : path.join(home, '.pi', 'agent');
521
+ const dir = path.resolve(cwd, expanded);
522
+ for (const name of ['models.json', 'auth.json']) {
523
+ const file = path.join(dir, name);
524
+ let text;
525
+ try {
526
+ text = await fs.readFile(file, 'utf8');
527
+ }
528
+ catch {
529
+ continue; // No file: nothing overrides.
530
+ }
531
+ if (text.includes(`"${PI_PROVIDER}"`)) {
532
+ return `pi's ${name} (${file}) has an entry for "${PI_PROVIDER}", which would override the launch. Remove it, then run stav launch again.`;
533
+ }
534
+ }
535
+ return null;
536
+ },
537
+ };
538
+ export const ADAPTERS = [claudeCode, codex, deepseekHarness, kiloCode, githubCopilot, pi];
387
539
  /** Names a person may type for an app (DECIDE-APPS-P: `claude` → claude-code). */
388
540
  export const ALIASES = {
389
541
  claude: 'claude-code',
@@ -0,0 +1,48 @@
1
+ // The Stav provider for pi, given to `pi --extension` by the pi adapter in
2
+ // index.ts. Shipped with the CLI and never written at run time: every value
3
+ // comes from the environment the CLI sets for the child, so the key is never
4
+ // in this file or in an argument (R-20).
5
+ //
6
+ // pi reads a custom provider from models.json, where only apiKey and headers
7
+ // take environment variables; the base URL does not. A provider extension
8
+ // registered at startup is ready for --provider/--model on the same run, and
9
+ // ~/.pi/agent is not changed. Checked with pi 1.7.0.
10
+
11
+ // STAV_PI_MODELS is the list for pi's model picker (/model): every chat
12
+ // model, Router and auto the key may use, the launch's model first, each as
13
+ // {id, contextWindow}. Without it, or when it does not read, only
14
+ // STAV_PI_MODEL is offered.
15
+ function pickerModels(env) {
16
+ const one = [{ id: env.STAV_PI_MODEL, contextWindow: Number(env.STAV_PI_CONTEXT_WINDOW) }];
17
+ let list;
18
+ try {
19
+ list = JSON.parse(env.STAV_PI_MODELS ?? "");
20
+ } catch {
21
+ return one;
22
+ }
23
+ if (!Array.isArray(list)) return one;
24
+ const ok = list.filter(
25
+ (m) => m && typeof m.id === "string" && m.id && Number.isInteger(m.contextWindow) && m.contextWindow > 0,
26
+ );
27
+ return ok.length ? ok : one;
28
+ }
29
+
30
+ export default function stavProvider(pi) {
31
+ const env = process.env;
32
+ pi.registerProvider("stav-cli", {
33
+ name: "Stav",
34
+ baseUrl: env.STAV_PI_BASE_URL,
35
+ apiKey: "$STAV_PI_API_KEY",
36
+ api: "openai-completions",
37
+ models: pickerModels(env).map((m) => ({
38
+ type: "chat",
39
+ id: m.id,
40
+ name: m.id,
41
+ reasoning: false,
42
+ input: ["text"],
43
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
44
+ contextWindow: m.contextWindow,
45
+ maxTokens: Number(env.STAV_PI_MAX_TOKENS),
46
+ })),
47
+ });
48
+ }
package/dist/cli.js CHANGED
@@ -45,6 +45,7 @@ Examples:
45
45
  stav launch dsh -- "run the tests"
46
46
  stav launch kilo
47
47
  stav launch copilot -- -p "fix the failing test"
48
+ stav launch pi
48
49
  `;
49
50
  // Every line goes through terminalText: much of it is text from the Stav API.
50
51
  const out = (line = '') => process.stdout.write(`${terminalText(line)}\n`);
package/dist/launch.js CHANGED
@@ -17,14 +17,26 @@ import { appKeyName, saveAppKey } from './store/index.js';
17
17
  import { compareVersions } from './version-compare.js';
18
18
  import { VERSION } from './version.js';
19
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
- dsh: 'npm install -g @deepseek-ai/dsh',
24
- kilo: 'npm install -g @kilocode/cli',
25
- copilot: 'npm install -g @github/copilot',
20
+ /** The npm package that installs each app's program. */
21
+ export const INSTALL_PACKAGE = {
22
+ claude: '@anthropic-ai/claude-code',
23
+ codex: '@openai/codex',
24
+ dsh: '@deepseek-ai/dsh',
25
+ kilo: '@kilocode/cli',
26
+ copilot: '@github/copilot',
27
+ pi: '@earendil-works/pi-coding-agent',
26
28
  };
29
+ export const INSTALL_HINT = Object.fromEntries(Object.entries(INSTALL_PACKAGE).map(([program, pkg]) => [program, `npm install -g ${pkg}`]));
30
+ /**
31
+ * Everything that can refuse runs first; only then, if the app is missing,
32
+ * is the install offered, so a yes never installs an app for a launch that
33
+ * would be refused anyway.
34
+ */
27
35
  export async function planLaunch(opts, d) {
36
+ const plan = await checkLaunch(opts, d);
37
+ return plan.programPath ? plan : { ...plan, programPath: await offerInstall(plan.adapter, opts, d), installed: true };
38
+ }
39
+ async function checkLaunch(opts, d) {
28
40
  if (d.platform === 'win32') {
29
41
  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');
30
42
  }
@@ -40,10 +52,7 @@ export async function planLaunch(opts, d) {
40
52
  throw new StavError(`"${model}" is not a model id. Use one like zai-org/glm-5-2.`, 'bad_model');
41
53
  }
42
54
  const programPath = d.which(adapter.program);
43
- if (!programPath) {
44
- throw new StavError(`${adapter.displayName} is not installed. Install it with: ${INSTALL_HINT[adapter.program] ?? adapter.program}`, 'not_installed');
45
- }
46
- const conflict = adapter.conflicts ? await adapter.conflicts(d.env.HOME, d.cwd) : null;
55
+ const conflict = adapter.conflicts ? await adapter.conflicts(d.env.HOME, d.cwd, d.env, opts.appArgs ?? []) : null;
47
56
  if (conflict)
48
57
  throw new StavError(conflict, 'settings_conflict');
49
58
  // A key in the environment: no sign-in, no key made (B.9).
@@ -87,6 +96,36 @@ export async function planLaunch(opts, d) {
87
96
  key: { create: true, orWorkspaceKey, name: `${adapter.displayName} (${me.email})` },
88
97
  };
89
98
  }
99
+ /**
100
+ * The app is not on PATH. In a terminal, offer to install it with npm and
101
+ * do so only on a yes; otherwise refuse and say the command. --yes never
102
+ * installs: it answers the key question, and a global install is a
103
+ * different thing to agree to. Returns the program's path once installed.
104
+ */
105
+ async function offerInstall(adapter, opts, d) {
106
+ const pkg = INSTALL_PACKAGE[adapter.program];
107
+ const hint = INSTALL_HINT[adapter.program] ?? adapter.program;
108
+ const refuse = (text = `${adapter.displayName} is not installed. Install it with: ${hint}`) => new StavError(text, 'not_installed');
109
+ const npm = pkg ? d.which('npm') : null;
110
+ if (!pkg || !npm || !d.prompter.interactive || opts.yes)
111
+ throw refuse();
112
+ if (!(await confirm(d.prompter, `${adapter.displayName} is not installed. Install it now with ${hint}?`)))
113
+ throw refuse();
114
+ // An argv array and no shell, like the app itself.
115
+ // npm runs the package's install scripts: they get no STAV_* variable,
116
+ // so a key in STAV_API_KEY never reaches them.
117
+ const env = Object.fromEntries(Object.entries(d.env).filter(([k]) => !k.toUpperCase().startsWith('STAV_')));
118
+ const code = await d.spawn(npm, ['install', '-g', pkg], { stdio: 'inherit', env, shell: false });
119
+ if (code !== 0) {
120
+ throw new StavError(`npm could not install ${adapter.displayName} (exit code ${code}). Install it yourself with: ${hint}`, 'install_failed');
121
+ }
122
+ const installed = d.which(adapter.program);
123
+ if (!installed) {
124
+ throw refuse(`${adapter.displayName} was installed, but "${adapter.program}" is not on your PATH. Open a new terminal, or add npm's global bin folder (npm prefix -g) to PATH, then run this again.`);
125
+ }
126
+ d.log(`Installed ${adapter.displayName}.`);
127
+ return installed;
128
+ }
90
129
  function checkLaunchable(app, adapter, slug) {
91
130
  if (!app) {
92
131
  throw new StavError(`${adapter.displayName} is not in the Stav app catalogue yet.`, 'not_launchable');
@@ -211,15 +250,16 @@ export async function launch(opts, d) {
211
250
  throw new StavError('This makes an API key. Run it in a terminal, or add --yes.', 'confirm_required');
212
251
  }
213
252
  else if (!(await confirm(d.prompter, changes ? 'Go ahead?' : 'Start it?'))) {
214
- d.log('Nothing was changed.');
253
+ d.log(plan.installed ? `No key was made, and ${plan.adapter.displayName} was not started. It stays installed.` : 'Nothing was changed.');
215
254
  return 1;
216
255
  }
217
256
  }
218
257
  if (plan.workspace && plan.rememberWorkspace)
219
258
  await d.saveSetting('workspace', plan.workspace.id);
220
259
  const secret = await settleKey(plan, d);
221
- const contextWindow = await readContextWindow(plan, secret, d);
222
- const run = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: secret, model: plan.model, contextWindow });
260
+ // Both reads at once: each gives up after its own timeout.
261
+ const [contextWindow, models] = await Promise.all([readContextWindow(plan, secret, d), readModelList(plan, secret, d)]);
262
+ const run = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: secret, model: plan.model, contextWindow, models });
223
263
  const env = { ...d.env };
224
264
  for (const k of run.unset)
225
265
  delete env[k];
@@ -250,6 +290,29 @@ async function readContextWindow(plan, key, d) {
250
290
  d.log(`Stav does not know the context window of ${plan.model} for your workspace; ${plan.adapter.displayName} starts without the window from Stav (see the plan above for what it uses).`);
251
291
  return n;
252
292
  }
293
+ /**
294
+ * Every chat model, Router and auto the key may use, when the adapter wants
295
+ * them for the app's model picker. Never stops the launch: without the list
296
+ * the app offers only the launch's model, and the person is told.
297
+ * ``undefined`` when the adapter does not want it.
298
+ */
299
+ async function readModelList(plan, key, d) {
300
+ if (!plan.adapter.wantsModelList)
301
+ return undefined;
302
+ d.log('Reading the models and Routers your key may use from Stav...');
303
+ try {
304
+ const list = await new Stav(d.cfg, d.fetchFn).chatModels(key);
305
+ if (list === null)
306
+ d.log(`Stav did not list the models for this key; ${plan.adapter.displayName} offers only ${plan.model ?? 'auto'}.`);
307
+ else
308
+ d.log(`Stav listed ${list.length} models and Routers for this key.`);
309
+ return list;
310
+ }
311
+ catch (err) {
312
+ d.log(`Could not read the models your key may use (${err instanceof Error ? err.message : String(err)}); ${plan.adapter.displayName} offers only ${plan.model ?? 'auto'}.`);
313
+ return null;
314
+ }
315
+ }
253
316
  /** PATH lookup without a shell. */
254
317
  export function which(program, env = process.env) {
255
318
  for (const dir of (env.PATH ?? '').split(path.delimiter)) {
package/dist/stav.js CHANGED
@@ -1,4 +1,5 @@
1
1
  /** The Stav calls the CLI makes, typed. */
2
+ import { MODEL_RE } from './adapters/index.js';
2
3
  import { StavError } from './errors.js';
3
4
  import { request } from './http.js';
4
5
  /**
@@ -56,6 +57,35 @@ export class Stav {
56
57
  const m = await request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/models/${path}`, { token: key, nullOn: [401, 403, 404], timeoutMs: WINDOW_TIMEOUT_MS });
57
58
  return ok(m?.context_length) ? m.context_length : null;
58
59
  }
60
+ /**
61
+ * Every chat model the key's workspace may use, with ``auto`` and the
62
+ * workspace's Routers, from the gateway's model list (the key's own
63
+ * policy). Order: ``auto``, then the Routers, then the models in the
64
+ * gateway's order. ``contextWindow`` is the list's ``context_length``:
65
+ * the smallest window any serving endpoint states, so it holds wherever
66
+ * a call lands; null for ``auto``, a Router, or a model with none stated.
67
+ * Null when the gateway refuses the key.
68
+ */
69
+ async chatModels(key) {
70
+ const list = await request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/models`, { token: key, nullOn: [401, 403, 404], timeoutMs: WINDOW_TIMEOUT_MS });
71
+ if (!list)
72
+ return null;
73
+ const out = [];
74
+ const seen = new Set();
75
+ for (const m of list.data ?? []) {
76
+ if (typeof m.id !== 'string' || !MODEL_RE.test(m.id) || seen.has(m.id))
77
+ continue;
78
+ if (!Array.isArray(m.stav_surfaces) || !m.stav_surfaces.includes('chat'))
79
+ continue;
80
+ seen.add(m.id);
81
+ const router = m.id === 'auto' || m.id.startsWith('@');
82
+ const n = m.context_length;
83
+ out.push({ id: m.id, contextWindow: !router && typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null });
84
+ }
85
+ const rank = (id) => (id === 'auto' ? 0 : id.startsWith('@') ? 1 : 2);
86
+ // Array.prototype.sort is stable: the gateway's order holds inside each group.
87
+ return out.sort((a, b) => rank(a.id) - rank(b.id));
88
+ }
59
89
  /** Whether a key still works, and for which workspace. Null when it does not. */
60
90
  checkKey(key) {
61
91
  return request(this.fetchFn, `${this.cfg.gatewayUrl}/v1/auth/validate`, { token: key, nullOn: [401, 403] });
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The CLI's own version. Kept equal to package.json by units.test.ts ("VERSION matches package.json"). */
2
- export const VERSION = '0.1.3';
2
+ export const VERSION = '0.1.5';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stav-ai/cli",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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": {
@@ -15,7 +15,7 @@
15
15
  "node": ">=22"
16
16
  },
17
17
  "scripts": {
18
- "build": "tsc -p tsconfig.build.json && node --input-type=module -e \"import { copyFileSync } from 'node:fs'; copyFileSync('src/adapters/deepseek-harness.patch.yml', 'dist/adapters/deepseek-harness.patch.yml')\"",
18
+ "build": "tsc -p tsconfig.build.json && node --input-type=module -e \"import { copyFileSync } from 'node:fs'; copyFileSync('src/adapters/deepseek-harness.patch.yml', 'dist/adapters/deepseek-harness.patch.yml'); copyFileSync('src/adapters/pi-stav-provider.js', 'dist/adapters/pi-stav-provider.js')\"",
19
19
  "prepack": "npm run build",
20
20
  "typecheck": "tsc --noEmit",
21
21
  "test": "tsx --test 'src/**/*.test.ts'",