yats-toolkit 0.5.1 → 0.6.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/bin/setup.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Usage:
6
6
  * yats setup # One-time setup wizard
7
- * yats index <path> # Index a repo (--skip-docs, --no-config)
7
+ * yats index <path> # Index a repo (--skip-docs, --no-config, --force)
8
8
  * yats search <query> # Search indexed code
9
9
  * yats list # List indexed repositories
10
10
  * yats summary <repo> # Show repository summary
@@ -31,12 +31,15 @@ function parseFlags(arr) {
31
31
  const a = arr[i];
32
32
  if (a === "--provider" && arr[i + 1]) flags.provider = arr[++i];
33
33
  else if (a === "--api-key" && arr[i + 1]) flags.apiKey = arr[++i];
34
+ else if (a === "--endpoint" && arr[i + 1]) flags.endpoint = arr[++i];
35
+ else if (a === "--model" && arr[i + 1]) flags.model = arr[++i];
34
36
  else if (a === "--port" && arr[i + 1]) flags.port = arr[++i];
35
37
  else if (a === "--batch" && arr[i + 1]) flags.batch = arr[++i];
36
38
  else if (a === "--no-docs") flags.noDocs = true;
37
39
  else if (a === "--yes") flags.skipConfirm = true;
38
40
  }
39
- flags.nonInteractive = !!(flags.provider && flags.apiKey);
41
+ // Azure additionally requires an endpoint URL to run unattended.
42
+ flags.nonInteractive = !!(flags.provider && flags.apiKey && (flags.provider !== "azure" || flags.endpoint));
40
43
  return flags;
41
44
  }
42
45
 
@@ -48,8 +51,13 @@ switch (cmd) {
48
51
  case "add": {
49
52
  const skipDocs = args.includes("--skip-docs");
50
53
  const noConfig = args.includes("--no-config");
51
- const cleanArgs = args.filter((a) => a !== "--skip-docs" && a !== "--no-config");
52
- import("../src/indexer.js").then(m => m.default(cleanArgs, { skipDocs, noConfig }));
54
+ const force = args.includes("--force");
55
+ const cleanArgs = args.filter(
56
+ (a) => a !== "--skip-docs" && a !== "--no-config" && a !== "--force",
57
+ );
58
+ import("../src/indexer.js").then((m) =>
59
+ m.default(cleanArgs, { skipDocs, noConfig, force }),
60
+ );
53
61
  break;
54
62
  }
55
63
  case "reindex":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yats-toolkit",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "description": "YATS — Yet Another Token Saver. One-command MCP server that indexes your codebase into a knowledge graph so AI agents (Claude, Cursor, Copilot) can search and navigate it without burning tokens.",
5
5
  "author": "Franco Vinciarelli <vinciarellifranco@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",
package/src/indexer.js CHANGED
@@ -21,6 +21,7 @@ import { readFileSync, statSync, readdirSync, readSync } from "node:fs";
21
21
  import { join, relative } from "node:path";
22
22
  import { homedir } from "node:os";
23
23
  import { spawnSync } from "node:child_process";
24
+ import { createHash } from "node:crypto";
24
25
 
25
26
  const YATS_URL = process.env.YATS_URL || "http://localhost:5555";
26
27
 
@@ -39,6 +40,45 @@ export const IGNORED = new Set([
39
40
 
40
41
  export const DEFAULT_DOC_EXTENSIONS = ".md,.mdx,.rst,.txt,.adoc,.org,.wiki,.readme";
41
42
 
43
+ /**
44
+ * Diff plan for one index run.
45
+ *
46
+ * @param walkedFiles [{path, hash}] — files found on disk with their content hash
47
+ * @param state server state from GET /index/state: {files, reanalyzeAll}
48
+ * @param options.force re-analyze everything (skips the state diff)
49
+ *
50
+ * send: files to POST /index/file (changed, new, or forced)
51
+ * remove: paths present in the server state but gone from disk
52
+ * unchanged: files skipped because hash + analyzer version match
53
+ */
54
+ export function planIndex(walkedFiles, state, { force = false } = {}) {
55
+ const files = state?.files ?? {};
56
+ const reanalyzeAll = !!state?.reanalyzeAll;
57
+ const send = [];
58
+ const remove = [];
59
+ let unchanged = 0;
60
+ const seen = new Set();
61
+
62
+ for (const f of walkedFiles) {
63
+ seen.add(f.path);
64
+ if (force || reanalyzeAll || files[f.path] !== f.hash) {
65
+ send.push(f.path);
66
+ } else {
67
+ unchanged++;
68
+ }
69
+ }
70
+
71
+ // Deletion detection: state entries not on disk anymore. Skipped on forced
72
+ // runs (state is not fetched) — the next normal run cleans them up.
73
+ if (!force) {
74
+ for (const p of Object.keys(files)) {
75
+ if (!seen.has(p)) remove.push(p);
76
+ }
77
+ }
78
+
79
+ return { send, remove, unchanged };
80
+ }
81
+
42
82
  /**
43
83
  * Read the YATS config written by `yats setup` (~/.yats/.env), so the CLI
44
84
  * filters files consistently with the server (DOC_EXTENSIONS, SKIP_EXTENSIONS,
@@ -247,6 +287,7 @@ async function walk(dir, ignored) {
247
287
  export default async function indexRepo(args, options = {}) {
248
288
  const skipDocsFlag = options.skipDocs || false;
249
289
  const noConfig = options.noConfig || false;
290
+ const force = options.force === true;
250
291
  const repoPath = args[0];
251
292
  if (!repoPath) {
252
293
  console.error("Usage: npx yats index <path> [--skip-docs] [--no-config]");
@@ -288,14 +329,11 @@ export default async function indexRepo(args, options = {}) {
288
329
  process.exit(1);
289
330
  }
290
331
 
291
- // Walk and send files
332
+ // Walk the tree and hash every file up front — reading + sha256 is cheap;
333
+ // it lets us diff against the server state instead of re-sending everything.
292
334
  console.log(`Indexing ${repoPath}...`);
293
- const files = await walk(repoPath, ignoredDirs);
294
- // Send files concurrently in batches
295
- const CONCURRENCY = 10;
296
- const batch = [];
297
-
298
- for (const file of files) {
335
+ const walked = [];
336
+ for (const file of await walk(repoPath, ignoredDirs)) {
299
337
  const relPath = relative(repoPath, file);
300
338
  if (shouldSkipFile(relPath, {
301
339
  skipDocs,
@@ -303,38 +341,107 @@ export default async function indexRepo(args, options = {}) {
303
341
  skipExtensions: effective.skipExtensions,
304
342
  docPatterns: effective.docPatterns,
305
343
  })) continue;
306
- batch.push(file);
344
+ try {
345
+ const content = readFileSync(file, "utf-8");
346
+ if (content.includes("\0") || content.length > 1_000_000) continue;
347
+ walked.push({
348
+ file,
349
+ relPath,
350
+ content,
351
+ hash: createHash("sha256").update(content).digest("hex"),
352
+ });
353
+ } catch {
354
+ // Unreadable file — skip it.
355
+ }
356
+ }
357
+
358
+ // Server state: which files were analyzed with which content hash, and
359
+ // whether the analyzer version forces a full re-analysis pass.
360
+ let state = { files: {}, reanalyzeAll: true };
361
+ if (!force) {
362
+ try {
363
+ const res = await fetch(
364
+ `${YATS_URL}/index/state?repository=${encodeURIComponent(repoName)}`,
365
+ );
366
+ if (res.ok) state = await res.json();
367
+ } catch {
368
+ // Server unreachable or endpoint missing — full pass.
369
+ }
370
+ }
371
+
372
+ const plan = planIndex(
373
+ walked.map((w) => ({ path: w.relPath, hash: w.hash })),
374
+ state,
375
+ { force },
376
+ );
377
+ const byPath = new Map(walked.map((w) => [w.relPath, w]));
378
+
379
+ // Remove files that disappeared since the last index
380
+ let removed = 0;
381
+ for (const relPath of plan.remove) {
382
+ try {
383
+ const res = await fetch(`${YATS_URL}/index/remove`, {
384
+ method: "POST",
385
+ headers: { "Content-Type": "application/json" },
386
+ body: JSON.stringify({ repository: repoName, path: relPath }),
387
+ });
388
+ if (res.ok) removed++;
389
+ } catch {
390
+ // Non-fatal — the next run retries.
391
+ }
307
392
  }
308
393
 
309
394
  let sent = 0;
310
395
  let errors = 0;
396
+ let serverSkipped = 0;
397
+ const failedPaths = [];
398
+ const CONCURRENCY = 10;
399
+ const batch = plan.send.map((p) => byPath.get(p));
311
400
  const total = batch.length;
312
401
 
313
402
  for (let i = 0; i < batch.length; i += CONCURRENCY) {
314
403
  const chunk = batch.slice(i, i + CONCURRENCY);
315
- const results = await Promise.all(chunk.map(async (file) => {
316
- const relPath = relative(repoPath, file);
404
+ const results = await Promise.all(chunk.map(async (entry) => {
405
+ const relPath = entry.relPath;
317
406
  try {
318
- const content = readFileSync(file, "utf-8");
319
- if (content.includes("\0") || content.length > 1_000_000) return { ok: true, skipped: true };
320
407
  const res = await fetch(`${YATS_URL}/index/file`, {
321
408
  method: "POST",
322
409
  headers: { "Content-Type": "application/json" },
323
- body: JSON.stringify({ repoName, filePath: relPath, content }),
410
+ body: JSON.stringify({
411
+ repoName,
412
+ filePath: relPath,
413
+ content: entry.content,
414
+ contentHash: entry.hash,
415
+ }),
324
416
  });
325
- return { ok: res.ok, skipped: false };
417
+ const data = await res.json().catch(() => ({}));
418
+ return { ok: res.ok, serverSkipped: data.skipped === true };
326
419
  } catch {
327
- return { ok: false, skipped: false };
420
+ return { ok: false, serverSkipped: false };
328
421
  }
329
422
  }));
330
-
423
+
331
424
  for (const r of results) {
332
- if (r.ok) sent++;
333
- else if (!r.skipped) errors++;
425
+ if (r.ok && !r.serverSkipped) sent++;
426
+ else if (r.ok) serverSkipped++;
427
+ else errors++;
428
+ }
429
+ for (const entry of chunk) {
430
+ const r = results[chunk.indexOf(entry)];
431
+ if (r && !r.ok) failedPaths.push(entry.relPath);
334
432
  }
335
433
  process.stdout.write(`\r ${sent + errors}/${total} files`);
336
434
  }
337
- console.log(`\r ✓ ${sent} files indexed${errors > 0 ? `, ${errors} skipped` : ""}`);
435
+ console.log(
436
+ `\r ✓ ${sent} files indexed` +
437
+ `${serverSkipped > 0 ? `, ${serverSkipped} skipped by server` : ""}` +
438
+ `${plan.unchanged > 0 ? `, ${plan.unchanged} unchanged` : ""}` +
439
+ `${removed > 0 ? `, ${removed} removed` : ""}` +
440
+ `${errors > 0 ? `, ${errors} failed` : ""}`,
441
+ );
442
+ if (failedPaths.length > 0) {
443
+ console.log(` ! failed: ${failedPaths.slice(0, 5).join(", ")}${failedPaths.length > 5 ? ` (+${failedPaths.length - 5} more)` : ""}`);
444
+ }
338
445
 
339
446
  // Finalize: resolve cross-file references and store relationships.
340
447
  // The server also flushes automatically after a quiet period, but an
@@ -17,6 +17,7 @@ import {
17
17
  validateRepoConfig,
18
18
  mergeRepoConfig,
19
19
  configErrorText,
20
+ planIndex,
20
21
  DEFAULT_DOC_EXTENSIONS,
21
22
  } from "./indexer.js";
22
23
 
@@ -272,3 +273,57 @@ describe("indexRepo — malformed config stops the run (P6)", () => {
272
273
  }
273
274
  });
274
275
  });
276
+
277
+ describe("planIndex", () => {
278
+ const walked = [
279
+ { path: "src/a.ts", hash: "h1" },
280
+ { path: "src/b.ts", hash: "h2-new" },
281
+ { path: "src/c.ts", hash: "h3" },
282
+ ];
283
+
284
+ it("sends only changed/new files against matching state", () => {
285
+ const state = {
286
+ files: { "src/a.ts": "h1", "src/b.ts": "h2-old", "src/d.ts": "h4" },
287
+ reanalyzeAll: false,
288
+ };
289
+ const plan = planIndex(walked, state);
290
+ assert.deepEqual(plan.send, ["src/b.ts", "src/c.ts"]); // b changed, c is new
291
+ assert.deepEqual(plan.remove, ["src/d.ts"]);
292
+ assert.equal(plan.unchanged, 1);
293
+ });
294
+
295
+ it("sends everything when the analyzer version changed (reanalyzeAll)", () => {
296
+ const state = {
297
+ files: { "src/a.ts": "h1", "src/b.ts": "h2-new", "src/c.ts": "h3" },
298
+ reanalyzeAll: true,
299
+ };
300
+ const plan = planIndex(walked, state);
301
+ assert.deepEqual(plan.send, ["src/a.ts", "src/b.ts", "src/c.ts"]);
302
+ assert.deepEqual(plan.remove, []);
303
+ assert.equal(plan.unchanged, 0);
304
+ });
305
+
306
+ it("sends everything with empty state (first index)", () => {
307
+ const plan = planIndex(walked, { files: {}, reanalyzeAll: true });
308
+ assert.equal(plan.send.length, 3);
309
+ assert.equal(plan.remove.length, 0);
310
+ assert.equal(plan.unchanged, 0);
311
+ });
312
+
313
+ it("force re-analyzes everything and skips deletion detection", () => {
314
+ const state = {
315
+ files: { "src/a.ts": "h1", "src/gone.ts": "hx" },
316
+ reanalyzeAll: false,
317
+ };
318
+ const plan = planIndex(walked, state, { force: true });
319
+ assert.equal(plan.send.length, 3);
320
+ assert.deepEqual(plan.remove, []);
321
+ assert.equal(plan.unchanged, 0);
322
+ });
323
+
324
+ it("tolerates a null state (old server / fetch failure)", () => {
325
+ const plan = planIndex(walked, null);
326
+ assert.equal(plan.send.length, 3);
327
+ assert.equal(plan.unchanged, 0);
328
+ });
329
+ });
package/src/setup.js CHANGED
@@ -55,6 +55,11 @@ const PROVIDER_MODELS = {
55
55
  { label: "text-embedding-3-large (3072d, more accurate)", value: "text-embedding-3-large" },
56
56
  { label: "text-embedding-ada-002 (1536d, legacy)", value: "text-embedding-ada-002" },
57
57
  ],
58
+ azure: [
59
+ { label: "text-embedding-3-small (1536d, fast & cheap)", value: "text-embedding-3-small" },
60
+ { label: "text-embedding-3-large (3072d, more accurate)", value: "text-embedding-3-large" },
61
+ { label: "text-embedding-ada-002 (1536d, legacy)", value: "text-embedding-ada-002" },
62
+ ],
58
63
  mistral: [
59
64
  { label: "mistral-embed (1024d)", value: "mistral-embed" },
60
65
  ],
@@ -73,7 +78,7 @@ const PROVIDER_MODELS = {
73
78
  ],
74
79
  };
75
80
 
76
- const DEFAULT_MODEL = { openai: "text-embedding-3-small", mistral: "mistral-embed", voyage: "voyage-code-2", ollama: "nomic-embed-text" };
81
+ const DEFAULT_MODEL = { openai: "text-embedding-3-small", azure: "text-embedding-3-small", mistral: "mistral-embed", voyage: "voyage-code-2", ollama: "nomic-embed-text" };
77
82
 
78
83
  // Minimal embedded docker-compose as fallback
79
84
  const EMBEDDED_COMPOSE = `services:
@@ -127,10 +132,18 @@ const EMBEDDED_COMPOSE = `services:
127
132
  - OLLAMA_MODEL=\${EMBEDDING_OLLAMA_MODEL:-nomic-embed-text}
128
133
  - OPENAI_API_KEY=\${EMBEDDING_OPENAI_API_KEY:-}
129
134
  - OPENAI_MODEL=\${EMBEDDING_OPENAI_MODEL:-text-embedding-3-small}
135
+ - OPENAI_BASE_URL=\${EMBEDDING_OPENAI_BASE_URL:-}
130
136
  - MISTRAL_API_KEY=\${EMBEDDING_MISTRAL_API_KEY:-}
131
137
  - MISTRAL_MODEL=\${EMBEDDING_MISTRAL_MODEL:-mistral-embed}
138
+ - MISTRAL_BASE_URL=\${EMBEDDING_MISTRAL_BASE_URL:-}
132
139
  - VOYAGE_API_KEY=\${EMBEDDING_VOYAGE_API_KEY:-}
133
140
  - VOYAGE_MODEL=\${EMBEDDING_VOYAGE_MODEL:-voyage-code-2}
141
+ - VOYAGE_BASE_URL=\${EMBEDDING_VOYAGE_BASE_URL:-}
142
+ - AZURE_OPENAI_ENDPOINT=\${EMBEDDING_AZURE_ENDPOINT:-}
143
+ - AZURE_OPENAI_API_KEY=\${EMBEDDING_AZURE_API_KEY:-}
144
+ - AZURE_OPENAI_MODEL=\${EMBEDDING_AZURE_MODEL:-text-embedding-3-small}
145
+ - AZURE_OPENAI_API_VERSION=\${EMBEDDING_AZURE_API_VERSION:-2024-02-01}
146
+ - AZURE_OPENAI_EMBEDDING_DIMENSIONS=\${EMBEDDING_AZURE_EMBEDDING_DIMENSIONS:-}
134
147
  - REPOSITORIES_PATH=/repos
135
148
  - YATS_PORT=__MCP_PORT__
136
149
  - EMBEDDING_BATCH_SIZE=\${EMBEDDING_BATCH_SIZE:-__BATCH_SIZE__}
@@ -430,13 +443,32 @@ async function loadEnv() {
430
443
  // Merge embedding + benchmark keys into the env map before writing ~/.yats/.env.
431
444
  // Benchmark agent keys are added empty (if missing) so users see exactly what to
432
445
  // fill in for `yats benchmark`; any existing values are preserved.
433
- export function applyEnvKeys(envMap, { provider, apiKey, model }) {
446
+ //
447
+ // Everything is persisted so the whole setup is visible in ~/.yats/.env:
448
+ // provider → EMBEDDING_PROVIDER (+ YATS_PROVIDER alias)
449
+ // api key → EMBEDDING_<PROVIDER>_API_KEY
450
+ // model → EMBEDDING_<PROVIDER>_MODEL (Azure: deployment name)
451
+ // url → EMBEDDING_<PROVIDER>_BASE_URL / EMBEDDING_AZURE_ENDPOINT
452
+ export function applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVersion }) {
434
453
  envMap.EMBEDDING_PROVIDER = provider;
435
454
  envMap.YATS_PROVIDER = provider;
436
455
  if (provider === "openai" && apiKey) envMap.EMBEDDING_OPENAI_API_KEY = apiKey;
437
456
  if (provider === "mistral" && apiKey) envMap.EMBEDDING_MISTRAL_API_KEY = apiKey;
438
457
  if (provider === "voyage" && apiKey) envMap.EMBEDDING_VOYAGE_API_KEY = apiKey;
439
- const modelVar = { openai: "EMBEDDING_OPENAI_MODEL", mistral: "EMBEDDING_MISTRAL_MODEL", voyage: "EMBEDDING_VOYAGE_MODEL", ollama: "EMBEDDING_OLLAMA_MODEL" }[provider];
458
+ if (provider === "azure") {
459
+ if (apiKey) envMap.EMBEDDING_AZURE_API_KEY = apiKey;
460
+ if (baseUrl) envMap.EMBEDDING_AZURE_ENDPOINT = baseUrl;
461
+ envMap.EMBEDDING_AZURE_API_VERSION = apiVersion || "2024-02-01";
462
+ }
463
+ if (baseUrl) {
464
+ const baseVar = {
465
+ openai: "EMBEDDING_OPENAI_BASE_URL",
466
+ mistral: "EMBEDDING_MISTRAL_BASE_URL",
467
+ voyage: "EMBEDDING_VOYAGE_BASE_URL",
468
+ }[provider];
469
+ if (baseVar) envMap[baseVar] = baseUrl;
470
+ }
471
+ const modelVar = { openai: "EMBEDDING_OPENAI_MODEL", azure: "EMBEDDING_AZURE_MODEL", mistral: "EMBEDDING_MISTRAL_MODEL", voyage: "EMBEDDING_VOYAGE_MODEL", ollama: "EMBEDDING_OLLAMA_MODEL" }[provider];
440
472
  if (model && modelVar) envMap[modelVar] = model;
441
473
  for (const k of ["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GEMINI_API_KEY", "DEEPSEEK_API_KEY"]) {
442
474
  if (!(k in envMap)) envMap[k] = "";
@@ -447,19 +479,44 @@ export function applyEnvKeys(envMap, { provider, apiKey, model }) {
447
479
  return envMap;
448
480
  }
449
481
 
450
- async function testApiConnection(provider, apiKey) {
451
- const endpoints = {
452
- openai: { url: "https://api.openai.com/v1/embeddings", key: apiKey, body: { model: "text-embedding-3-small", input: ["test"] } },
453
- mistral: { url: "https://api.mistral.ai/v1/embeddings", key: apiKey, body: { model: "mistral-embed", input: ["test"] } },
454
- voyage: { url: "https://api.voyageai.com/v1/embeddings", key: apiKey, body: { model: "voyage-3-lite", input: ["test"] } },
482
+ // Verify a provider's connection before writing anything.
483
+ // - openai/mistral/voyage: Bearer auth against {baseUrl}/embeddings, where
484
+ // baseUrl is the provider default or a user-supplied custom endpoint.
485
+ // - azure: api-key auth against
486
+ // {endpoint}/openai/deployments/{deployment}/embeddings?api-version=...
487
+ async function testApiConnection(provider, apiKey, { baseUrl, model, apiVersion } = {}) {
488
+ const defaults = {
489
+ openai: { base: "https://api.openai.com/v1", model: "text-embedding-3-small" },
490
+ mistral: { base: "https://api.mistral.ai/v1", model: "mistral-embed" },
491
+ voyage: { base: "https://api.voyageai.com/v1", model: "voyage-3-lite" },
455
492
  };
456
- const cfg = endpoints[provider];
457
- if (!cfg) return { ok: false, error: "Unknown provider" };
493
+
494
+ const modelName = model || defaults[provider]?.model || "text-embedding-3-small";
495
+ let url;
496
+ let headers;
497
+
498
+ if (provider === "azure") {
499
+ if (!baseUrl) return { ok: false, error: "Azure endpoint URL is required" };
500
+ let base = baseUrl.replace(/\/+$/, "").split("?")[0];
501
+ if (!base.includes("/openai/deployments/")) {
502
+ base = `${base}/openai/deployments/${modelName}`;
503
+ }
504
+ if (!base.endsWith("/embeddings")) base = `${base}/embeddings`;
505
+ url = `${base}?api-version=${apiVersion || "2024-02-01"}`;
506
+ headers = { "Content-Type": "application/json", "api-key": apiKey };
507
+ } else {
508
+ const cfg = defaults[provider];
509
+ if (!cfg) return { ok: false, error: "Unknown provider" };
510
+ const base = (baseUrl || cfg.base).replace(/\/+$/, "");
511
+ url = `${base}/embeddings`;
512
+ headers = { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` };
513
+ }
514
+
458
515
  try {
459
- const res = await fetch(cfg.url, {
516
+ const res = await fetch(url, {
460
517
  method: "POST",
461
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${cfg.key}` },
462
- body: JSON.stringify(cfg.body),
518
+ headers,
519
+ body: JSON.stringify({ model: modelName, input: ["test"] }),
463
520
  signal: AbortSignal.timeout(15000),
464
521
  });
465
522
  if (res.ok) return { ok: true };
@@ -474,9 +531,14 @@ async function main(options = {}) {
474
531
  // Load pre-filled values from .env (if exists) or CLI flags
475
532
  const env = loadEnv();
476
533
  const nonInteractive = options.nonInteractive || false;
534
+ const prefillProvider = options.provider || env.YATS_PROVIDER || env.EMBEDDING_PROVIDER || null;
535
+ const keyVar = { openai: "EMBEDDING_OPENAI_API_KEY", azure: "EMBEDDING_AZURE_API_KEY", mistral: "EMBEDDING_MISTRAL_API_KEY", voyage: "EMBEDDING_VOYAGE_API_KEY" }[prefillProvider];
536
+ const baseVar = { openai: "EMBEDDING_OPENAI_BASE_URL", azure: "EMBEDDING_AZURE_ENDPOINT", mistral: "EMBEDDING_MISTRAL_BASE_URL", voyage: "EMBEDDING_VOYAGE_BASE_URL" }[prefillProvider];
477
537
  const prefill = {
478
- provider: options.provider || env.YATS_PROVIDER || env.EMBEDDING_PROVIDER || null,
479
- apiKey: options.apiKey || env.EMBEDDING_OPENAI_API_KEY || env.EMBEDDING_MISTRAL_API_KEY || env.EMBEDDING_VOYAGE_API_KEY || null,
538
+ provider: prefillProvider,
539
+ apiKey: options.apiKey || (keyVar && env[keyVar]) || null,
540
+ baseUrl: options.endpoint || (baseVar && env[baseVar]) || null,
541
+ model: options.model || null,
480
542
  port: options.port ? parseInt(options.port, 10) : null,
481
543
  batch: options.batch ? parseInt(options.batch, 10) : null,
482
544
  noDocs: options.noDocs || false,
@@ -550,17 +612,52 @@ async function main(options = {}) {
550
612
  provider = await choose("How should I generate embeddings for your code?", [
551
613
  { label: "Ollama (local, private, included) — recommended", value: "ollama" },
552
614
  { label: "OpenAI (cloud, needs API key)", value: "openai" },
615
+ { label: "Azure OpenAI (cloud, needs endpoint URL + API key)", value: "azure" },
553
616
  { label: "Mistral (cloud, needs API key)", value: "mistral" },
554
617
  { label: "Voyage AI (cloud, optimized for code, needs API key)", value: "voyage" },
555
618
  ]);
556
619
  }
557
620
 
621
+ const providerNames = { openai: "OpenAI", azure: "Azure OpenAI", mistral: "Mistral", voyage: "Voyage AI" };
558
622
  let apiKey = "";
559
- let model = DEFAULT_MODEL[provider];
623
+ let baseUrl = "";
624
+ const apiVersion = "2024-02-01";
625
+ let model = prefill.model || DEFAULT_MODEL[provider];
626
+
627
+ // Azure needs an endpoint URL — ask for it before the API key.
628
+ if (provider === "azure") {
629
+ step("Step 2 — Azure OpenAI endpoint URL");
630
+ if (nonInteractive && prefill.baseUrl) {
631
+ baseUrl = prefill.baseUrl;
632
+ console.log(` Endpoint: ${baseUrl}`);
633
+ } else {
634
+ const rlAzure = createInterface({ input: process.stdin, output: process.stdout });
635
+ const prompt = prefill.baseUrl
636
+ ? ` ${B}Endpoint URL${R} [${prefill.baseUrl}]: `
637
+ : ` ${B}Endpoint URL (e.g. https://my-resource.openai.azure.com):${R} `;
638
+ baseUrl = (await ask(rlAzure, prompt)).trim();
639
+ if (!baseUrl && prefill.baseUrl) baseUrl = prefill.baseUrl;
640
+ rlAzure.close();
641
+ if (!baseUrl) {
642
+ console.log(` ${RED}✗${R} Azure requires an endpoint URL.`);
643
+ process.exit(1);
644
+ }
645
+ }
646
+ console.log("");
647
+ }
648
+
649
+ // Azure: the "model" is the deployment name — pick it before the API key so
650
+ // the connection test hits the real deployment.
651
+ if (provider === "azure" && !nonInteractive) {
652
+ step("Step 3 — Azure deployment name");
653
+ console.log(` ${D}The name of your embeddings deployment in Azure.${R}`);
654
+ console.log("");
655
+ model = await choose("Which deployment?", PROVIDER_MODELS.azure);
656
+ console.log("");
657
+ }
560
658
 
561
659
  if (provider !== "ollama") {
562
- const providerNames = { openai: "OpenAI", mistral: "Mistral", voyage: "Voyage AI" };
563
- step(`Step 2 — ${providerNames[provider]} API key`);
660
+ step(`Step ${provider === "azure" ? "4" : "2"} — ${providerNames[provider]} API key`);
564
661
 
565
662
  if (nonInteractive && prefill.apiKey) {
566
663
  apiKey = prefill.apiKey;
@@ -580,6 +677,26 @@ async function main(options = {}) {
580
677
  console.log(` ${Y}⚠${R} This is a paid service — you may be charged for API usage.`);
581
678
  console.log("");
582
679
 
680
+ // Optional custom endpoint (OpenAI-compatible providers only — Azure has
681
+ // its own endpoint step above). Works with any proxy or OpenAI-compatible
682
+ // gateway; leave empty for the provider default.
683
+ if (["openai", "mistral", "voyage"].includes(provider)) {
684
+ if (nonInteractive && prefill.baseUrl) {
685
+ baseUrl = prefill.baseUrl;
686
+ console.log(` Custom endpoint: ${baseUrl}`);
687
+ } else {
688
+ const rlUrl = createInterface({ input: process.stdin, output: process.stdout });
689
+ const prompt = prefill.baseUrl
690
+ ? ` ${B}Custom endpoint URL (Enter = provider default)${R} [${prefill.baseUrl}]: `
691
+ : ` ${B}Custom endpoint URL? (Enter = provider default; e.g. a local proxy)${R}: `;
692
+ baseUrl = (await ask(rlUrl, prompt)).trim();
693
+ if (!baseUrl && prefill.baseUrl) baseUrl = prefill.baseUrl;
694
+ rlUrl.close();
695
+ if (baseUrl) console.log(` ${G}✓${R} Custom endpoint: ${baseUrl}`);
696
+ }
697
+ console.log("");
698
+ }
699
+
583
700
  // Optional: test connection
584
701
  if (!nonInteractive) {
585
702
  const rlTest = createInterface({ input: process.stdin, output: process.stdout });
@@ -587,7 +704,11 @@ async function main(options = {}) {
587
704
  rlTest.close();
588
705
  if (testAnswer.toLowerCase() !== "n") {
589
706
  const sTest = spinner("Testing API connection...");
590
- const result = await testApiConnection(provider, apiKey);
707
+ const result = await testApiConnection(provider, apiKey, {
708
+ baseUrl,
709
+ model: provider === "azure" ? model : undefined,
710
+ apiVersion,
711
+ });
591
712
  if (result.ok) {
592
713
  sTest.done(true);
593
714
  console.log("");
@@ -615,18 +736,23 @@ async function main(options = {}) {
615
736
  console.log("");
616
737
  }
617
738
 
618
- // Embedding model (every provider)
619
- if (nonInteractive) {
620
- console.log(` Embedding model: ${model}`);
621
- } else {
622
- step(provider === "ollama" ? "Step 2 — Embedding model" : "Step 3 — Embedding model");
623
- model = await choose("Which embedding model?", PROVIDER_MODELS[provider]);
624
- console.log("");
739
+ // Embedding model (every provider except Azure, where the deployment name
740
+ // was chosen above)
741
+ if (provider !== "azure") {
742
+ if (nonInteractive) {
743
+ console.log(` Embedding model: ${model}`);
744
+ } else {
745
+ step(provider === "ollama" ? "Step 2 — Embedding model" : "Step 3 — Embedding model");
746
+ model = await choose("Which embedding model?", PROVIDER_MODELS[provider]);
747
+ console.log("");
748
+ }
749
+ } else if (nonInteractive) {
750
+ console.log(` Azure deployment: ${model}`);
625
751
  }
626
752
 
627
753
  // Step 4: Embedding batch size
628
- const BATCH_DEFAULTS = { openai: 200, mistral: 200, voyage: 100, ollama: 4 };
629
- const BATCH_MAX = { openai: 2048, mistral: 1024, voyage: 128, ollama: 4 };
754
+ const BATCH_DEFAULTS = { openai: 200, azure: 200, mistral: 200, voyage: 100, ollama: 4 };
755
+ const BATCH_MAX = { openai: 2048, azure: 2048, mistral: 1024, voyage: 128, ollama: 4 };
630
756
  const defaultBatch = prefill.batch || BATCH_DEFAULTS[provider];
631
757
  const maxBatch = BATCH_MAX[provider];
632
758
  let batchSize = defaultBatch;
@@ -732,16 +858,17 @@ async function main(options = {}) {
732
858
  // Confirm
733
859
  if (!nonInteractive && !prefill.skipConfirm) {
734
860
  step(`Step ${pathsToIndex.length ? "6" : "5"} — Confirm`);
735
- const providerName = provider === "ollama"
736
- ? `Ollama (${model})`
737
- : { openai: "OpenAI", mistral: "Mistral", voyage: "Voyage AI" }[provider];
861
+ const providerName = provider === "ollama" || provider === "azure"
862
+ ? `${provider === "ollama" ? "Ollama" : providerNames[provider]} (${model})`
863
+ : providerNames[provider];
738
864
  box([
739
865
  `${B}Provider:${R} ${providerName}`,
866
+ ...(baseUrl ? [`${B}Endpoint:${R} ${baseUrl}`] : []),
740
867
  `${B}Port:${R} ${String(mcpPort)}`,
741
868
  ...(pathsToIndex.length ? [`${B}Pre-index:${R} ${String(pathsToIndex.length + " directorie(s)")}`] : []),
742
869
  `${B}Batch:${R} ${String(batchSize)}`,
743
870
  `${B}Index docs:${R} ${indexDocs ? "Yes (max " + docMaxFiles + " files)" : "No"}`,
744
- `${B}API calls:${R} ${provider === "ollama" ? "None (runs locally)" : `To ${provider} API`}`,
871
+ `${B}API calls:${R} ${provider === "ollama" ? "None (runs locally)" : `To ${providerNames[provider] ?? provider} API`}`,
745
872
  `${B}Disk needed:${R} ${provider === "ollama" ? "~3GB" : "~1GB"}`,
746
873
  ]);
747
874
  console.log("");
@@ -775,7 +902,7 @@ async function main(options = {}) {
775
902
 
776
903
  // Persist keys to ~/.yats/.env — canonical source (embedding + benchmark keys).
777
904
  const envMap = loadEnv();
778
- applyEnvKeys(envMap, { provider, apiKey, model });
905
+ applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVersion });
779
906
  writeFileSync(ENV_FILE, Object.entries(envMap).map(([k, v]) => `${k}=${v}`).join("\n") + "\n");
780
907
 
781
908
  // Pull the YATS Docker image from GitHub Container Registry
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Tests — setup wizard env persistence (applyEnvKeys).
3
+ *
4
+ * Covers the Azure OpenAI provider, custom endpoints for OpenAI-compatible
5
+ * providers, and reconfiguration between providers.
6
+ */
7
+
8
+ import { describe, it } from "node:test";
9
+ import assert from "node:assert/strict";
10
+
11
+ import { applyEnvKeys } from "./setup.js";
12
+
13
+ describe("applyEnvKeys", () => {
14
+ it("persists Azure OpenAI endpoint, key, model, and api version", () => {
15
+ const env = applyEnvKeys({}, {
16
+ provider: "azure",
17
+ apiKey: "az-key",
18
+ model: "text-embedding-3-large",
19
+ baseUrl: "https://my-resource.openai.azure.com",
20
+ });
21
+
22
+ assert.equal(env.EMBEDDING_PROVIDER, "azure");
23
+ assert.equal(env.YATS_PROVIDER, "azure");
24
+ assert.equal(env.EMBEDDING_AZURE_API_KEY, "az-key");
25
+ assert.equal(env.EMBEDDING_AZURE_ENDPOINT, "https://my-resource.openai.azure.com");
26
+ assert.equal(env.EMBEDDING_AZURE_MODEL, "text-embedding-3-large");
27
+ assert.equal(env.EMBEDDING_AZURE_API_VERSION, "2024-02-01");
28
+ });
29
+
30
+ it("persists a custom endpoint for OpenAI-compatible providers", () => {
31
+ const env = applyEnvKeys({}, {
32
+ provider: "openai",
33
+ apiKey: "oai-key",
34
+ model: "text-embedding-3-small",
35
+ baseUrl: "https://proxy.corp.local/v1",
36
+ });
37
+
38
+ assert.equal(env.EMBEDDING_OPENAI_BASE_URL, "https://proxy.corp.local/v1");
39
+ assert.equal(env.EMBEDDING_OPENAI_API_KEY, "oai-key");
40
+ assert.equal(env.EMBEDDING_OPENAI_MODEL, "text-embedding-3-small");
41
+ // No Azure keys are written for non-Azure providers.
42
+ assert.ok(!("EMBEDDING_AZURE_API_KEY" in env));
43
+ assert.ok(!("EMBEDDING_AZURE_ENDPOINT" in env));
44
+ });
45
+
46
+ it("does not write a base URL when none is given", () => {
47
+ const env = applyEnvKeys({}, {
48
+ provider: "mistral",
49
+ apiKey: "m-key",
50
+ model: "mistral-embed",
51
+ });
52
+
53
+ assert.ok(!("EMBEDDING_MISTRAL_BASE_URL" in env));
54
+ assert.equal(env.EMBEDDING_MISTRAL_API_KEY, "m-key");
55
+ });
56
+
57
+ it("switches providers without losing unrelated keys", () => {
58
+ const before = applyEnvKeys({}, {
59
+ provider: "openai",
60
+ apiKey: "oai-key",
61
+ model: "text-embedding-3-small",
62
+ baseUrl: "https://old-proxy/v1",
63
+ });
64
+ const env = applyEnvKeys(before, {
65
+ provider: "azure",
66
+ apiKey: "az-key",
67
+ model: "text-embedding-3-small",
68
+ baseUrl: "https://my-resource.openai.azure.com",
69
+ });
70
+
71
+ assert.equal(env.EMBEDDING_PROVIDER, "azure");
72
+ assert.equal(env.EMBEDDING_AZURE_API_KEY, "az-key");
73
+ // The old OpenAI key/baseUrl remain but are inert (provider is azure).
74
+ assert.equal(env.EMBEDDING_OPENAI_API_KEY, "oai-key");
75
+ assert.equal(env.EMBEDDING_OPENAI_BASE_URL, "https://old-proxy/v1");
76
+ });
77
+
78
+ it("preserves existing benchmark keys and adds missing empty ones", () => {
79
+ const env = applyEnvKeys({ ANTHROPIC_API_KEY: "ant-key" }, {
80
+ provider: "ollama",
81
+ model: "nomic-embed-text",
82
+ });
83
+
84
+ assert.equal(env.ANTHROPIC_API_KEY, "ant-key");
85
+ assert.equal(env.OPENAI_API_KEY, "");
86
+ assert.equal(env.GEMINI_API_KEY, "");
87
+ assert.equal(env.DEEPSEEK_API_KEY, "");
88
+ });
89
+ });