byok.test.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import test from "node:test";
  2. import assert from "node:assert/strict";
  3. import { createServer } from "node:http";
  4. import { spawn } from "node:child_process";
  5. import {
  6. mkdtempSync,
  7. mkdirSync,
  8. rmSync,
  9. existsSync,
  10. readFileSync,
  11. writeFileSync,
  12. } from "node:fs";
  13. import { tmpdir } from "node:os";
  14. import path from "node:path";
  15. import { fileURLToPath } from "node:url";
  16. import Database from "better-sqlite3";
  17. import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
  18. import { withoutProxyEnvironment } from "./offline-environment.mjs";
  19. const cli = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
  20. // This fixture validates BYOK transport and real Runtime persistence, not model quality.
  21. test(
  22. "BYOK runs without managed login and resumes its saved conversation",
  23. { timeout: 90000 },
  24. async (t) => {
  25. const fixtureDir = mkdtempSync(path.join(tmpdir(), "minimax-code-byok-"));
  26. const dataDir = path.join(fixtureDir, "data");
  27. const workspaceDir = path.join(fixtureDir, "workspace");
  28. mkdirSync(workspaceDir);
  29. const dbPath = path.join(dataDir, "v2", "sqlite", "runtime-state.sqlite");
  30. mkdirSync(path.dirname(dbPath), { recursive: true });
  31. const legacyDb = new Database(dbPath);
  32. try {
  33. // An upgrade must ignore a previously enabled cloud-indexing preference.
  34. legacyDb.exec(`
  35. CREATE TABLE local_runtime_preferences (key TEXT PRIMARY KEY, value_json TEXT NOT NULL);
  36. INSERT INTO local_runtime_preferences VALUES ('workspace-indexing-enabled', 'true');
  37. `);
  38. } finally {
  39. legacyDb.close();
  40. }
  41. const requests = [];
  42. const readMarker = `ACTUAL_FILE_CONTENT_${Date.now()}`;
  43. writeFileSync(path.join(workspaceDir, "read-fixture.txt"), readMarker);
  44. let toolRequested = false;
  45. let rejectConnection = false;
  46. const networkAudit = path.join(dataDir, "network-audit.log");
  47. const server = createServer(async (req, res) => {
  48. let raw = "";
  49. for await (const chunk of req) raw += chunk;
  50. const body = JSON.parse(raw);
  51. requests.push({ url: req.url, auth: req.headers.authorization, body });
  52. if (!req.url?.endsWith("/chat/completions")) {
  53. res.writeHead(404).end();
  54. return;
  55. }
  56. if (rejectConnection) {
  57. res.writeHead(401, { "content-type": "application/json" }).end(
  58. JSON.stringify({ error: { message: "Synthetic invalid credential" } }),
  59. );
  60. return;
  61. }
  62. if (!body.stream) {
  63. res.writeHead(200, { "content-type": "application/json" }).end(
  64. JSON.stringify({
  65. id: "fixture",
  66. object: "chat.completion",
  67. model: "fixture-model",
  68. choices: [
  69. {
  70. index: 0,
  71. message: { role: "assistant", content: "LOCAL_BYOK_OK" },
  72. finish_reason: "stop",
  73. },
  74. ],
  75. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  76. }),
  77. );
  78. return;
  79. }
  80. res.writeHead(200, { "content-type": "text/event-stream" });
  81. if (
  82. JSON.stringify(body.messages).includes("TOOL_READ_TEST") &&
  83. !toolRequested
  84. ) {
  85. toolRequested = true;
  86. assert.ok(body.tools?.some((tool) => tool.function?.name === "read"));
  87. for (const delta of [
  88. {
  89. choices: [
  90. {
  91. index: 0,
  92. delta: {
  93. role: "assistant",
  94. tool_calls: [
  95. {
  96. index: 0,
  97. id: "read-fixture-call",
  98. type: "function",
  99. function: {
  100. name: "read",
  101. arguments: JSON.stringify({
  102. path: path.join(workspaceDir, "read-fixture.txt"),
  103. }),
  104. },
  105. },
  106. ],
  107. },
  108. finish_reason: null,
  109. },
  110. ],
  111. },
  112. { choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] },
  113. ])
  114. res.write(
  115. `data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture-model", ...delta })}\n\n`,
  116. );
  117. res.end("data: [DONE]\n\n");
  118. return;
  119. }
  120. for (const chunk of [
  121. {
  122. choices: [
  123. {
  124. index: 0,
  125. delta: { role: "assistant", content: "LOCAL_BYOK_OK" },
  126. finish_reason: null,
  127. },
  128. ],
  129. },
  130. {
  131. choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
  132. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  133. },
  134. ])
  135. res.write(
  136. `data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture-model", ...chunk })}\n\n`,
  137. );
  138. res.end("data: [DONE]\n\n");
  139. });
  140. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  141. t.after(async () => {
  142. server.closeAllConnections();
  143. await new Promise((resolve) => server.close(resolve));
  144. try {
  145. assert.equal(
  146. existsSync(networkAudit),
  147. false,
  148. existsSync(networkAudit)
  149. ? readFileSync(networkAudit, "utf8")
  150. : "Unexpected external request",
  151. );
  152. } finally {
  153. rmSync(fixtureDir, { recursive: true, force: true });
  154. }
  155. });
  156. const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;
  157. const env = {
  158. MINIMAX_DATA_DIR: dataDir,
  159. MAVIS_DATA_DIR: dataDir,
  160. MCODE_PROVIDER_API_KEY: "fixture-only-key",
  161. MCODE_TEST_ALLOWED_ORIGIN: new URL(baseUrl).origin,
  162. MCODE_TEST_NETWORK_AUDIT: networkAudit,
  163. MCODE_TEST_MANAGED_OFFLINE: "1",
  164. MCODE_TEST_PROCESS_PROBE: "1",
  165. NODE_OPTIONS: `--import=${new URL("./network-deny.mjs", import.meta.url).href}`,
  166. };
  167. let commandSequence = 0;
  168. async function run(args, environment = process.env) {
  169. const startedAt = Date.now();
  170. const label = args.slice(0, 2).join(" ");
  171. const requestCountAtStart = requests.length;
  172. const diagnosticsDir = path.join(dataDir, `cli-diagnostics-${++commandSequence}`);
  173. const commandArgs = args[0] === "exec"
  174. ? [...args, "--diagnostics-dir", diagnosticsDir]
  175. : args;
  176. return new Promise((resolve, reject) => {
  177. const child = spawn(process.execPath, [cli, ...commandArgs], {
  178. cwd: workspaceDir,
  179. env: { ...withoutProxyEnvironment(environment), ...env },
  180. stdio: ["ignore", "pipe", "pipe"],
  181. });
  182. let stdout = "",
  183. stderr = "";
  184. let timeoutError;
  185. const timer = setTimeout(() => {
  186. const progressPath = path.join(diagnosticsDir, "progress.jsonl");
  187. let progress = "No execution progress recorded";
  188. try {
  189. if (existsSync(progressPath))
  190. progress = readFileSync(progressPath, "utf8").slice(-12000);
  191. } catch (error) {
  192. progress = `Unable to read execution progress: ${error.message}`;
  193. }
  194. timeoutError = new Error(
  195. `Timed out after ${Date.now() - startedAt}ms: ${label}\n` +
  196. `Fixture requests during command: ${requests.length - requestCountAtStart}\n` +
  197. `stdout (tail): ${stdout.slice(-12000)}\nstderr (tail): ${stderr.slice(-12000)}\n` +
  198. `execution progress (tail): ${progress}`,
  199. );
  200. child.kill("SIGKILL");
  201. child.stdout.destroy();
  202. child.stderr.destroy();
  203. }, 35000);
  204. child.stdout.on("data", (chunk) => {
  205. stdout += chunk;
  206. });
  207. child.stderr.on("data", (chunk) => {
  208. stderr += chunk;
  209. });
  210. child.once("error", (error) => {
  211. clearTimeout(timer);
  212. reject(error);
  213. });
  214. child.once("close", (code) => {
  215. clearTimeout(timer);
  216. t.diagnostic(`${label}: exit ${code} after ${Date.now() - startedAt}ms`);
  217. if (timeoutError) {
  218. reject(timeoutError);
  219. return;
  220. }
  221. code === 0
  222. ? resolve(stdout)
  223. : reject(new Error(`CLI exited ${code}: ${stderr}\n${stdout}`));
  224. });
  225. });
  226. }
  227. await run([
  228. "provider",
  229. "add",
  230. "--name",
  231. "Fixture",
  232. "--base-url",
  233. baseUrl,
  234. "--api-format",
  235. "openai-completions",
  236. "--model",
  237. "fixture-model",
  238. ]);
  239. assert.equal(requests.length, 0, "Adding without --use must not test or activate");
  240. const snapshot = JSON.parse(await run(["provider", "list", "--json"]));
  241. assert.equal(
  242. snapshot.providers.some((p) => p.kind === "minimax-oauth"),
  243. true,
  244. );
  245. const selected = snapshot.providers.find(
  246. (p) => p.kind === "custom" && p.name === "Fixture",
  247. );
  248. assert.ok(selected?.hasApiKey);
  249. const proxyNames = [
  250. "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
  251. "http_proxy", "https_proxy", "all_proxy", "no_proxy",
  252. ];
  253. const cleanEnvironment = Object.fromEntries(
  254. Object.entries(process.env).filter(([name]) => !proxyNames.includes(name)),
  255. );
  256. const proxyValue = (name) => name.toLowerCase() === "no_proxy"
  257. ? "*"
  258. : "http://127.0.0.1:9";
  259. for (const [label, proxies] of [
  260. ["no proxy", {}],
  261. ...proxyNames.map((name) => [name, { [name]: proxyValue(name) }]),
  262. ["uppercase and lowercase together", Object.fromEntries(
  263. proxyNames.map((name) => [name, proxyValue(name)]),
  264. )],
  265. ]) {
  266. await t.test(`offline BYOK ignores ambient proxies: ${label}`, async () => {
  267. const environment = Object.freeze({ ...cleanEnvironment, ...proxies });
  268. // NO_PROXY alone does not enable proxy mode, so check its isolation explicitly.
  269. const isolated = withoutProxyEnvironment(environment);
  270. for (const name of proxyNames) assert.equal(isolated[name], "");
  271. assert.equal(isolated.PATH, environment.PATH);
  272. const beforeRequests = requests.length;
  273. const managedAudit = `${networkAudit}.managed`;
  274. const beforeManaged = readFileSync(managedAudit, "utf8").length;
  275. await run([
  276. "provider", "test", selected.providerId, "--model", "fixture-model",
  277. ], environment);
  278. assert.ok(requests.length > beforeRequests, "The local provider must receive the request");
  279. assert.equal(requests[beforeRequests].body.model, "fixture-model");
  280. assert.match(
  281. readFileSync(managedAudit, "utf8").slice(beforeManaged),
  282. /https:\/\/models\.dev\/api\.json|\/mavis\/api\/v1\/models-dev\/catalog/,
  283. );
  284. assert.equal(existsSync(networkAudit), false, "No outbound network attempt is allowed");
  285. for (const [name, value] of Object.entries(proxies)) assert.equal(environment[name], value);
  286. });
  287. }
  288. const configPath = path.join(dataDir, "config.yaml");
  289. const savedConfig = () => parseYaml(readFileSync(configPath, "utf8"));
  290. assert.equal(savedConfig().defaultModel, "minimax/MiniMax-M3");
  291. assert.equal(savedConfig().custom_provider.fixture.models["fixture-model"].limit, undefined);
  292. assert.equal(selected.active, false);
  293. assert.equal(selected.models[0].contextLimit, undefined);
  294. assert.equal(selected.models[0].maxOutputTokens, undefined);
  295. const addArgs = [
  296. "provider", "add", "--name", "Limited", "--base-url", baseUrl,
  297. "--api-format", "openai-completions", "--model", "fixture-model",
  298. "--model", "second-model", "--context-limit", "32768", "--output-limit", "4096", "--use",
  299. ];
  300. const beforeFailure = readFileSync(configPath, "utf8");
  301. rejectConnection = true;
  302. await assert.rejects(run(addArgs), /Provider connection test failed.*Nothing was saved/s);
  303. assert.equal(readFileSync(configPath, "utf8"), beforeFailure);
  304. rejectConnection = false;
  305. const beforeAdd = requests.length;
  306. assert.match(await run(addArgs), /Provider added and selected: Limited/);
  307. assert.ok(requests.length > beforeAdd, "Activation must test the candidate before saving");
  308. assert.equal(requests[beforeAdd].body.model, "fixture-model");
  309. const config = savedConfig();
  310. assert.equal(config.defaultModel, "custom_provider:limited/fixture-model");
  311. for (const model of ["fixture-model", "second-model"]) {
  312. assert.deepEqual(config.custom_provider.limited.models[model].limit, { context: 32768, output: 4096 });
  313. }
  314. const configured = JSON.parse(await run(["provider", "list", "--json"])).providers.find(
  315. (provider) => provider.name === "Limited",
  316. );
  317. assert.equal(configured.active, true);
  318. assert.equal(configured.models[0].selected, true);
  319. for (const model of configured.models) {
  320. assert.equal(model.contextLimit, 32768);
  321. assert.equal(model.maxOutputTokens, 4096);
  322. }
  323. const beforeSaveOnly = requests.length;
  324. for (const [name, flag, limit] of [
  325. ["context-only", "--context-limit", { context: 32768 }],
  326. ["output-only", "--output-limit", { output: 32768 }],
  327. ]) {
  328. await run([
  329. "provider", "add", "--name", name, "--base-url", baseUrl,
  330. "--api-format", "openai-completions", "--model", "fixture-model", flag, "32768",
  331. ]);
  332. assert.deepEqual(savedConfig().custom_provider[name].models["fixture-model"].limit, limit);
  333. assert.equal(savedConfig().defaultModel, config.defaultModel);
  334. }
  335. assert.equal(requests.length, beforeSaveOnly, "Limits alone must not test or select a model");
  336. // Exercise the metadata persisted by provider preset import through real
  337. // config reload, headless validation and the OpenAI-compatible request body.
  338. const effortConfig = savedConfig();
  339. effortConfig.custom_provider.fixture.models["kimi-k3"] = {
  340. reasoning: true,
  341. thinking: { effortOptions: ["low", "high", "max"] },
  342. };
  343. writeFileSync(configPath, stringifyYaml(effortConfig));
  344. const effortModel = `${selected.providerId}/kimi-k3`;
  345. for (const effort of ["low", "high", "max"]) {
  346. const beforeEffort = requests.length;
  347. await run(["exec", "EFFORT_TEST", "--model", effortModel, "--effort", effort,
  348. "--timeout", "20s", "--max-steps", "1"]);
  349. // Background title generation is a separate non-streaming request and
  350. // does not use the turn's effort selection.
  351. const modelRequests = requests.slice(beforeEffort).filter(
  352. (r) => r.body.model === "kimi-k3" && r.body.stream === true,
  353. );
  354. assert.ok(modelRequests.length > 0);
  355. for (const request of modelRequests) assert.equal(request.body.reasoning_effort, effort);
  356. }
  357. const beforeInvalidEffort = requests.length;
  358. await assert.rejects(run(["exec", "EFFORT_TEST", "--model", effortModel,
  359. "--effort", "medium", "--timeout", "20s", "--max-steps", "1"]),
  360. /Available levels: low, high, max/);
  361. assert.equal(requests.length, beforeInvalidEffort, "Invalid effort must fail before transport");
  362. const modelArgs = ["--model", `${selected.providerId}/fixture-model`];
  363. // The first run must work through the saved default, without --model or managed login.
  364. const first = await run([
  365. "exec",
  366. "Remember this marker: SOURCE_REPOSITORY_TEST",
  367. "--timeout",
  368. "20s",
  369. "--max-steps",
  370. "1",
  371. ]);
  372. assert.match(first, /LOCAL_BYOK_OK/);
  373. await assert.rejects(run([
  374. 'exec', 'Managed model still requires its own login',
  375. '--model', 'minimax/MiniMax-M3', '--timeout', '20s', '--max-steps', '1',
  376. ]), /Sign in to MiniMax/);
  377. const beforeResume = requests.length;
  378. const second = await run([
  379. "exec",
  380. "Repeat the marker",
  381. ...modelArgs,
  382. "--continue",
  383. "--timeout",
  384. "20s",
  385. "--max-steps",
  386. "1",
  387. ]);
  388. assert.match(second, /LOCAL_BYOK_OK/);
  389. assert.ok(
  390. requests
  391. .slice(beforeResume)
  392. .some((r) =>
  393. JSON.stringify(r.body.messages ?? []).includes(
  394. "SOURCE_REPOSITORY_TEST",
  395. ),
  396. ),
  397. JSON.stringify(
  398. requests.map((r) => ({ url: r.url, keys: Object.keys(r.body) })),
  399. ),
  400. );
  401. const toolStart = requests.length;
  402. await run([
  403. "exec",
  404. "TOOL_READ_TEST: read read-fixture.txt",
  405. ...modelArgs,
  406. "--timeout",
  407. "20s",
  408. "--max-steps",
  409. "3",
  410. ]);
  411. assert.equal(toolRequested, true);
  412. assert.ok(
  413. requests
  414. .slice(toolStart)
  415. .some((r) =>
  416. r.body.messages?.some(
  417. (m) =>
  418. m.role === "tool" &&
  419. JSON.stringify(m.content).includes(readMarker),
  420. ),
  421. ),
  422. "The real read tool must return file contents to the provider",
  423. );
  424. assert.ok(requests.length >= 2);
  425. assert.ok(requests.every((r) => r.auth === "Bearer fixture-only-key"));
  426. assert.equal(
  427. requests.some((r) => r.body.tools?.some(
  428. (tool) => tool.function?.name === "workspace_semantic_search",
  429. )),
  430. false,
  431. "The retired workspace search tool must not be exposed to the model",
  432. );
  433. assert.equal(
  434. existsSync(path.join(dataDir, "v2", "workspaces")),
  435. false,
  436. "Startup, completed turns and resume must not create indexing artifacts",
  437. );
  438. const managedAudit = `${networkAudit}.managed`;
  439. assert.doesNotMatch(
  440. existsSync(managedAudit) ? readFileSync(managedAudit, "utf8") : "",
  441. /workspace-indexing/,
  442. "No workspace indexing request may be attempted",
  443. );
  444. const verificationDb = new Database(dbPath, { readonly: true });
  445. try {
  446. assert.deepEqual(
  447. verificationDb.prepare(
  448. "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'local_runtime_workspace_indexing_%'",
  449. ).all(),
  450. [],
  451. "New runtime databases must not create the retired upload queue",
  452. );
  453. } finally {
  454. verificationDb.close();
  455. }
  456. },
  457. );