yats-toolkit 0.5.0 → 0.6.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.
@@ -7,8 +7,22 @@ import assert from "node:assert/strict";
7
7
  import { writeFileSync, mkdirSync, rmSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { tmpdir } from "node:os";
10
+ import { execFileSync } from "node:child_process";
11
+ import { fileURLToPath } from "node:url";
10
12
 
11
- import { loadYatsEnv, shouldSkipFile, DEFAULT_DOC_EXTENSIONS } from "./indexer.js";
13
+ import {
14
+ loadYatsEnv,
15
+ shouldSkipFile,
16
+ loadRepoConfig,
17
+ validateRepoConfig,
18
+ mergeRepoConfig,
19
+ configErrorText,
20
+ planIndex,
21
+ DEFAULT_DOC_EXTENSIONS,
22
+ } from "./indexer.js";
23
+
24
+ const __dirname = fileURLToPath(new URL(".", import.meta.url));
25
+ const SETUP_JS = join(__dirname, "..", "bin", "setup.js");
12
26
 
13
27
  describe("loadYatsEnv", () => {
14
28
  let dir;
@@ -85,3 +99,231 @@ describe("shouldSkipFile", () => {
85
99
  );
86
100
  });
87
101
  });
102
+
103
+ describe(".yats/config.json — repo config (P6)", () => {
104
+ let repo;
105
+
106
+ before(() => {
107
+ repo = join(tmpdir(), `yats-repo-config-test-${Date.now()}`);
108
+ mkdirSync(join(repo, ".yats"), { recursive: true });
109
+ });
110
+
111
+ after(() => {
112
+ try { rmSync(repo, { recursive: true }); } catch {}
113
+ });
114
+
115
+ function writeConfig(content) {
116
+ writeFileSync(join(repo, ".yats", "config.json"), content);
117
+ }
118
+
119
+ it("returns defaults when the file does not exist", () => {
120
+ const res = loadRepoConfig(repo);
121
+ assert.equal(res.ok, true);
122
+ assert.equal(res.exists, false);
123
+ assert.deepEqual(res.config, {});
124
+ });
125
+
126
+ it("loads a valid config", () => {
127
+ writeConfig(JSON.stringify({
128
+ indexDocs: false,
129
+ docExtensions: [".md"],
130
+ docPatterns: ["docs/", "README.md"],
131
+ ignoredDirs: ["sandbox"],
132
+ skipExtensions: [".snap"],
133
+ }));
134
+ const res = loadRepoConfig(repo);
135
+ assert.equal(res.ok, true);
136
+ assert.equal(res.exists, true);
137
+ assert.equal(res.config.indexDocs, false);
138
+ assert.deepEqual(res.config.docPatterns, ["docs/", "README.md"]);
139
+ });
140
+
141
+ it("rejects malformed JSON with a clear error", () => {
142
+ writeConfig("{ not json");
143
+ const res = loadRepoConfig(repo);
144
+ assert.equal(res.ok, false);
145
+ assert.ok(res.error.includes("not valid JSON"), `error should mention JSON: ${res.error}`);
146
+ });
147
+
148
+ it("rejects wrong types with a clear error", () => {
149
+ writeConfig(JSON.stringify({ indexDocs: "no", ignoredDirs: "sandbox", docPatterns: [1] }));
150
+ const res = loadRepoConfig(repo);
151
+ assert.equal(res.ok, false);
152
+ assert.ok(res.error.includes("indexDocs"), `error should mention indexDocs: ${res.error}`);
153
+ assert.ok(res.error.includes("ignoredDirs"), `error should mention ignoredDirs: ${res.error}`);
154
+ assert.ok(res.error.includes("docPatterns"), `error should mention docPatterns: ${res.error}`);
155
+ });
156
+
157
+ it("rejects non-object roots", () => {
158
+ writeConfig("[1,2,3]");
159
+ const res = validateRepoConfig("[1,2,3]");
160
+ assert.equal(res.ok, false);
161
+ assert.ok(res.error.includes("object"));
162
+ });
163
+
164
+ it("configErrorText tells the AI client how to fix and retry", () => {
165
+ const text = configErrorText("/repo", "/repo/.yats/config.json", "not valid JSON: Unexpected token");
166
+ assert.ok(text.includes("Invalid repo config"), "names the problem");
167
+ assert.ok(text.includes("not valid JSON"), "includes the specific error");
168
+ assert.ok(text.includes("yats index /repo"), "gives the exact re-run command");
169
+ assert.ok(text.includes("--no-config"), "offers the bypass flag");
170
+ assert.ok(text.includes("Delete the file"), "offers falling back to defaults");
171
+ assert.ok(text.includes('"docPatterns"'), "shows the schema");
172
+ });
173
+ });
174
+
175
+ describe("mergeRepoConfig — machine vs repo (P6)", () => {
176
+ const globalEnv = {
177
+ DOC_EXTENSIONS: ".md,.rst",
178
+ SKIP_EXTENSIONS: ".lock,.min.js",
179
+ IGNORED_DIRS: "vendor,dist",
180
+ };
181
+
182
+ it("unions ignoredDirs and skipExtensions", () => {
183
+ const m = mergeRepoConfig(globalEnv, {
184
+ ignoredDirs: ["sandbox"],
185
+ skipExtensions: [".snap"],
186
+ });
187
+ assert.deepEqual(m.ignoredDirs, ["vendor", "dist", "sandbox"]);
188
+ assert.deepEqual(m.skipExtensions, [".lock", ".min.js", ".snap"]);
189
+ });
190
+
191
+ it("replaces docExtensions when the repo sets them (even empty)", () => {
192
+ const replaced = mergeRepoConfig(globalEnv, { docExtensions: [".mdx"] });
193
+ assert.deepEqual(replaced.docExtensions, [".mdx"]);
194
+
195
+ const emptied = mergeRepoConfig(globalEnv, { docExtensions: [] });
196
+ assert.deepEqual(emptied.docExtensions, [], "empty array disables docs for the repo");
197
+ });
198
+
199
+ it("keeps global docExtensions when the repo does not set them", () => {
200
+ const m = mergeRepoConfig(globalEnv, {});
201
+ assert.deepEqual(m.docExtensions, [".md", ".rst"]);
202
+ assert.equal(m.docPatterns, null);
203
+ assert.equal(m.indexDocs, true);
204
+ });
205
+
206
+ it("repo indexDocs:false turns docs off", () => {
207
+ const m = mergeRepoConfig(globalEnv, { indexDocs: false });
208
+ assert.equal(m.indexDocs, false);
209
+ });
210
+ });
211
+
212
+ describe("shouldSkipFile — docPatterns whitelist (P6)", () => {
213
+ const docExtensions = [".md"];
214
+
215
+ it("only sends doc files matching a pattern (code files always sent)", () => {
216
+ const opts = { docExtensions, docPatterns: ["docs/", "README.md"] };
217
+ assert.equal(shouldSkipFile("docs/guide.md", opts), false, "docs/ matches");
218
+ assert.equal(shouldSkipFile("README.md", opts), false, "README.md matches");
219
+ assert.equal(shouldSkipFile("notes.md", opts), true, "notes.md is outside the whitelist");
220
+ assert.equal(shouldSkipFile("src/main.ts", opts), false, "code is never filtered by docPatterns");
221
+ });
222
+
223
+ it("without patterns every doc file is sent", () => {
224
+ assert.equal(shouldSkipFile("notes.md", { docExtensions, docPatterns: null }), false);
225
+ });
226
+ });
227
+
228
+ describe("indexRepo — malformed config stops the run (P6)", () => {
229
+ let repo;
230
+
231
+ before(() => {
232
+ repo = join(tmpdir(), `yats-broken-config-test-${Date.now()}`);
233
+ mkdirSync(join(repo, ".yats"), { recursive: true });
234
+ });
235
+
236
+ after(() => {
237
+ try { rmSync(repo, { recursive: true }); } catch {}
238
+ });
239
+
240
+ it("exits 1 with fix instructions before indexing anything", () => {
241
+ writeFileSync(join(repo, ".yats", "config.json"), "{ broken json");
242
+ try {
243
+ execFileSync(process.execPath, [SETUP_JS, "index", repo], {
244
+ encoding: "utf-8",
245
+ stdio: "pipe",
246
+ });
247
+ assert.fail("should have exited non-zero");
248
+ } catch (err) {
249
+ assert.equal(err.status, 1);
250
+ const out = `${err.stdout ?? ""}\n${err.stderr ?? ""}`;
251
+ assert.ok(out.includes("Invalid repo config"), out);
252
+ assert.ok(out.includes("yats index"), out);
253
+ assert.ok(out.includes("--no-config"), out);
254
+ // It must NOT even try to reach the server — config is checked first.
255
+ assert.ok(!out.includes("Cannot reach YATS"), out);
256
+ }
257
+ });
258
+
259
+ it("a valid config proceeds (fails later on the unreachable server)", () => {
260
+ writeFileSync(join(repo, ".yats", "config.json"), JSON.stringify({ indexDocs: false }));
261
+ try {
262
+ execFileSync(process.execPath, [SETUP_JS, "index", repo], {
263
+ encoding: "utf-8",
264
+ stdio: "pipe",
265
+ env: { ...process.env, YATS_URL: "http://127.0.0.1:1" },
266
+ });
267
+ assert.fail("should have exited non-zero");
268
+ } catch (err) {
269
+ assert.equal(err.status, 1);
270
+ const out = `${err.stdout ?? ""}\n${err.stderr ?? ""}`;
271
+ assert.ok(!out.includes("Invalid repo config"), out);
272
+ assert.ok(out.includes("Cannot reach YATS"), out);
273
+ }
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,15 +132,23 @@ 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
- - EMBEDDING_BATCH_SIZE=__BATCH_SIZE__
137
- - INDEX_DOCS=__INDEX_DOCS__
138
- - DOC_MAX_FILES=__DOC_MAX__
149
+ - EMBEDDING_BATCH_SIZE=\${EMBEDDING_BATCH_SIZE:-__BATCH_SIZE__}
150
+ - INDEX_DOCS=\${INDEX_DOCS:-__INDEX_DOCS__}
151
+ - DOC_MAX_FILES=\${DOC_MAX_FILES:-__DOC_MAX__}
139
152
  - DOC_EXTENSIONS=\${DOC_EXTENSIONS:-__DOC_EXTENSIONS__}
140
153
  - SKIP_EXTENSIONS=\${SKIP_EXTENSIONS:-__SKIP_EXTENSIONS__}
141
154
  - IGNORED_DIRS=\${IGNORED_DIRS:-__IGNORED_DIRS__}
@@ -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
+ });