@okhay-p/mivra 0.1.5 → 0.1.6

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.
Files changed (44) hide show
  1. package/README.md +1 -0
  2. package/THIRD_PARTY_NOTICES.md +250 -0
  3. package/dist/chunk-B47HA6IQ.js +2294 -0
  4. package/dist/chunk-B47HA6IQ.js.map +7 -0
  5. package/dist/{chunk-ODFBAPPH.js → chunk-DYXNHODU.js} +9 -3
  6. package/dist/chunk-DYXNHODU.js.map +7 -0
  7. package/dist/{chunk-KUKQU7EQ.js → chunk-VHOVRHI3.js} +38 -10
  8. package/dist/{chunk-KUKQU7EQ.js.map → chunk-VHOVRHI3.js.map} +2 -2
  9. package/dist/cli.js +726 -49
  10. package/dist/cli.js.map +4 -4
  11. package/dist/{client-5YDLS4KV.js → client-4UG5W5NJ.js} +2 -2
  12. package/dist/exercise-child.js +37 -0
  13. package/dist/exercise-child.js.map +7 -0
  14. package/dist/extract-child.js +1 -1
  15. package/dist/python-child.js +51 -0
  16. package/dist/python-child.js.map +7 -0
  17. package/dist/{start-2RXX57ZZ.js → start-SX3BCBIN.js} +1204 -236
  18. package/dist/start-SX3BCBIN.js.map +7 -0
  19. package/drizzle/0019_public_doctor_faustus.sql +1 -0
  20. package/drizzle/0020_early_wolfpack.sql +3 -0
  21. package/drizzle/meta/0019_snapshot.json +2288 -0
  22. package/drizzle/meta/0020_snapshot.json +2297 -0
  23. package/drizzle/meta/_journal.json +14 -0
  24. package/package.json +6 -1
  25. package/web/assets/emscripten-module-uFzwHH0Y.wasm +0 -0
  26. package/web/assets/emscripten-module.browser-D72eEgXo.js +1 -0
  27. package/web/assets/exercise-workers/exercise.worker-DzC1lTCg.js +265 -0
  28. package/web/assets/exercise-workers/python-exercise.worker-CtSr-syJ.js +236 -0
  29. package/web/assets/ffi-4V2b7xu3.js +1 -0
  30. package/web/assets/index-D3M-SX0V.js +538 -0
  31. package/web/assets/index-DUFQVtIh.css +1 -0
  32. package/web/assets/module-ES6BEMUI-Chb6aYUZ.js +1 -0
  33. package/web/assets/notes-graph.worker-Dqb5HK34.js +1 -0
  34. package/web/assets/render.worker-D6KYAHiU.js +537 -0
  35. package/web/index.html +2 -2
  36. package/dist/chunk-ODFBAPPH.js.map +0 -7
  37. package/dist/chunk-YACRW47X.js +0 -1203
  38. package/dist/chunk-YACRW47X.js.map +0 -7
  39. package/dist/start-2RXX57ZZ.js.map +0 -7
  40. package/web/assets/index-DJ2D5ZXo.css +0 -1
  41. package/web/assets/index-DcYzUL1W.js +0 -413
  42. package/web/assets/notes-graph.worker-DaVQvftJ.js +0 -1
  43. package/web/assets/render.worker-BAfybD27.js +0 -416
  44. /package/dist/{client-5YDLS4KV.js.map → client-4UG5W5NJ.js.map} +0 -0
package/dist/cli.js CHANGED
@@ -5,26 +5,41 @@ import {
5
5
  ChatGptError,
6
6
  PROVIDER_ENV,
7
7
  PROVIDER_LABELS,
8
+ ServerToken,
8
9
  TOKEN_FILE,
9
10
  chatGptFileStore,
10
11
  createChatGptSession,
11
12
  createCredentialStore,
12
- providerIds
13
- } from "./chunk-KUKQU7EQ.js";
13
+ loadOrCreateToken,
14
+ providerIds,
15
+ readRemoteServer,
16
+ removeRemoteServer,
17
+ saveRemoteServer
18
+ } from "./chunk-VHOVRHI3.js";
14
19
  import {
20
+ CourseView,
21
+ MAX_CASE_OUTPUT_CHARS,
22
+ MAX_MILESTONE_STDERR_CHARS,
15
23
  MAX_NOTE_CHARS,
24
+ MAX_REVIEW_FILES,
25
+ MAX_REVIEW_FILE_CHARS,
26
+ MAX_REVIEW_PATH_CHARS,
27
+ MAX_REVIEW_TOTAL_CHARS,
16
28
  MAX_VAULT_BYTES,
17
29
  MAX_VAULT_FILES,
30
+ MilestoneCases,
31
+ MilestoneCheckResult,
18
32
  VaultImportResult,
19
- VaultImportView
20
- } from "./chunk-YACRW47X.js";
33
+ VaultImportView,
34
+ normaliseOutput
35
+ } from "./chunk-B47HA6IQ.js";
21
36
  import "./chunk-PZ5AY32C.js";
22
37
 
23
38
  // src/cli.ts
24
39
  import { spawn as spawn2 } from "node:child_process";
25
40
  import { createInterface as createInterface2 } from "node:readline";
26
- import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
27
- import { join as join5 } from "node:path";
41
+ import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync4 } from "node:fs";
42
+ import { join as join7 } from "node:path";
28
43
  import { fileURLToPath } from "node:url";
29
44
 
30
45
  // ../server/src/config.ts
@@ -63,6 +78,17 @@ Commands:
63
78
  auth logout chatgpt Sign out of ChatGPT
64
79
  import obsidian <folder> Import an Obsidian vault's notes into a running Mivra; run it again to re-import
65
80
  --name <name> Name the import (default: the folder's name)
81
+ link <course> Link this folder to a project course, in .mivra.json (no secrets; safe to commit)
82
+ --run <command> How to run your program, e.g. "./build/mycc {input}": {input} becomes the path to a
83
+ file holding a case's input, which also comes on stdin. Runs without a shell
84
+ --run-output <command> For cases that run your program's output (e.g. assembly): {output} is its path
85
+ link --server <url> Use the Mivra at this address (on another computer) for link and check. Asks for its
86
+ token (or pipe it in) and saves both in the data dir, never in .mivra.json
87
+ link --local Go back to the Mivra running on this computer
88
+ token Print this Mivra's token, for \`mivra link --server\` on another computer
89
+ check Run your program on the current milestone's cases and record the result in Mivra
90
+ --timeout <seconds> Time limit for each run (default: 10)
91
+ --dry-run List exactly what would be sent for review, without running or sending anything
66
92
  uninstall Stop Mivra and ask whether to delete its data, before you remove the package
67
93
  --delete-data Delete the data without asking
68
94
  --keep-data Keep the data without asking
@@ -71,6 +97,18 @@ Providers: ${providerIds.join(", ")}
71
97
  Data lives in ~/.mivra, or MIVRA_DATA_DIR.`;
72
98
  var UsageError = class extends Error {
73
99
  };
100
+ function serverUrl(input) {
101
+ let url;
102
+ try {
103
+ url = new URL(input.trim());
104
+ } catch {
105
+ throw new UsageError(`--server needs an address such as https://mivra.example.ts.net, not "${input}".`);
106
+ }
107
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new UsageError("--server needs an http:// or https:// address.");
108
+ if (url.username || url.password) throw new UsageError("Leave the user name and password out of --server: Mivra asks for its token separately.");
109
+ if (url.pathname !== "/" && url.pathname !== "" || url.search || url.hash) throw new UsageError(`--server takes the address Mivra opens at, without a path: ${url.origin}`);
110
+ return url.origin;
111
+ }
74
112
  var provider = (value) => {
75
113
  if (!value) throw new UsageError(`Name a provider: ${providerIds.join(", ")}.`);
76
114
  if (!providerIds.includes(value)) throw new UsageError(`Unknown provider "${value}". Use one of: ${providerIds.join(", ")}.`);
@@ -86,6 +124,12 @@ function parseCommand(argv) {
86
124
  options: {
87
125
  port: { type: "string" },
88
126
  name: { type: "string" },
127
+ run: { type: "string" },
128
+ "run-output": { type: "string" },
129
+ server: { type: "string" },
130
+ local: { type: "boolean", default: false },
131
+ timeout: { type: "string" },
132
+ "dry-run": { type: "boolean", default: false },
89
133
  detach: { type: "boolean", default: false },
90
134
  open: { type: "boolean", default: true },
91
135
  check: { type: "boolean", default: true },
@@ -144,6 +188,33 @@ function parseCommand(argv) {
144
188
  if (!arg) throw new UsageError("Give the vault's folder: `mivra import obsidian <folder>`.");
145
189
  tooMany(3);
146
190
  return { name: "import-obsidian", folder: arg, ...values.name === void 0 ? {} : { importName: values.name } };
191
+ case "link": {
192
+ tooMany(2);
193
+ const runOutput = values["run-output"]?.trim();
194
+ const server2 = values.server === void 0 ? void 0 : serverUrl(values.server);
195
+ if (server2 && values.local) throw new UsageError("Use --server or --local, not both.");
196
+ if (!sub) {
197
+ if (server2 || values.local) {
198
+ if (values.run !== void 0 || runOutput) throw new UsageError('Give the course\'s id with --run: `mivra link <course> --run "<command>"`.');
199
+ return { name: "link", ...server2 ? { server: server2 } : {}, local: values.local };
200
+ }
201
+ throw new UsageError('Give the course\'s id, as the milestone in Mivra shows it: `mivra link <course> --run "<command>"`.');
202
+ }
203
+ if (!values.run?.trim()) throw new UsageError('Say how to run your program with --run, e.g. `mivra link <course> --run "./build/mycc {input}"`.');
204
+ return { name: "link", course: sub, run: values.run.trim(), ...runOutput ? { runOutput } : {}, ...server2 ? { server: server2 } : {}, local: values.local };
205
+ }
206
+ case "token":
207
+ tooMany(1);
208
+ return { name: "token" };
209
+ case "check": {
210
+ tooMany(1);
211
+ let timeoutS = 10;
212
+ if (values.timeout !== void 0) {
213
+ timeoutS = Number(values.timeout);
214
+ if (!Number.isFinite(timeoutS) || timeoutS < 1 || timeoutS > 600) throw new UsageError(`--timeout needs a number of seconds from 1 to 600, not "${values.timeout}".`);
215
+ }
216
+ return { name: "check", timeoutS, dryRun: values["dry-run"] };
217
+ }
147
218
  case "uninstall":
148
219
  tooMany(1);
149
220
  if (values["delete-data"] && values["keep-data"]) throw new UsageError("Use --delete-data or --keep-data, not both.");
@@ -288,7 +359,7 @@ async function readSecret(prompt, input = process.stdin, output = process.stderr
288
359
  input.setRawMode(true);
289
360
  input.resume();
290
361
  input.setEncoding("utf8");
291
- return new Promise((resolve2, reject) => {
362
+ return new Promise((resolve3, reject) => {
292
363
  let value = "";
293
364
  const done = (error) => {
294
365
  input.setRawMode(false);
@@ -296,7 +367,7 @@ async function readSecret(prompt, input = process.stdin, output = process.stderr
296
367
  input.off("data", onData);
297
368
  output.write("\n");
298
369
  if (error) reject(error);
299
- else resolve2(value.trim());
370
+ else resolve3(value.trim());
300
371
  };
301
372
  const onData = (chunk) => {
302
373
  for (const char of chunk) {
@@ -312,9 +383,9 @@ async function readSecret(prompt, input = process.stdin, output = process.stderr
312
383
  async function confirm(question, input = process.stdin, output = process.stderr) {
313
384
  output.write(question);
314
385
  const lines = createInterface({ input, terminal: false });
315
- const answer = await new Promise((resolve2) => {
316
- lines.once("line", resolve2);
317
- lines.once("close", () => resolve2(""));
386
+ const answer = await new Promise((resolve3) => {
387
+ lines.once("line", resolve3);
388
+ lines.once("close", () => resolve3(""));
318
389
  });
319
390
  lines.close();
320
391
  input.pause();
@@ -322,17 +393,612 @@ async function confirm(question, input = process.stdin, output = process.stderr)
322
393
  return /^(y|yes)$/i.test(answer.trim());
323
394
  }
324
395
 
396
+ // src/project.ts
397
+ import { mkdtempSync, readFileSync as readFileSync2, rmSync as rmSync2, writeFileSync } from "node:fs";
398
+ import { tmpdir } from "node:os";
399
+ import { dirname, join as join4, resolve } from "node:path";
400
+ import { z as z2 } from "zod";
401
+
402
+ // src/repo-files.ts
403
+ import { execFile } from "node:child_process";
404
+ import { lstat, readFile, realpath } from "node:fs/promises";
405
+ import { basename, isAbsolute, join as join3, relative, sep } from "node:path";
406
+ var LOCKFILES = /* @__PURE__ */ new Set(["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock", "cargo.lock", "poetry.lock", "pipfile.lock", "uv.lock", "composer.lock", "gemfile.lock", "go.sum", "flake.lock", "mix.lock", "pubspec.lock", "podfile.lock", "packages.lock.json"]);
407
+ var SECRET_DIRS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".azure", ".kube", ".docker", "secrets", ".secrets"]);
408
+ var SECRET_NAMES = /* @__PURE__ */ new Set([
409
+ ".npmrc",
410
+ ".pypirc",
411
+ ".netrc",
412
+ "_netrc",
413
+ ".git-credentials",
414
+ ".htpasswd",
415
+ ".pgpass",
416
+ ".dockercfg",
417
+ "credentials",
418
+ "authorized_keys",
419
+ "known_hosts",
420
+ "terraform.tfvars"
421
+ ]);
422
+ var SECRET_PATTERNS = [
423
+ /^\.env($|[-_.])/,
424
+ // .env, .env.local, .env-production, .env_prod, .env.example: all of them
425
+ /\.env$/,
426
+ // prod.env
427
+ /^\.?envrc$/,
428
+ /\.(pem|key|p8|p12|pfx|jks|keystore|ppk|asc|gpg|kdbx|tfstate|tfvars|secret|secrets)$/,
429
+ /\.tfstate\.backup$/,
430
+ /^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/,
431
+ /credential/,
432
+ /^secrets?\./,
433
+ /^service[-_]?account.*\.json$/,
434
+ /^client_secret.*\.json$/,
435
+ // Tokens, keys and passwords kept in data files (not source files: a lexer's token.c is code, not a secret).
436
+ /(^|[-_.])(api[-_]?keys?|keys?|(access|auth|api|bearer|refresh|github|slack|bot)[-_]?tokens?|passwords?|passwd|secrets?)([-_.][^/]*)?\.(json|ya?ml|toml|ini|cfg|conf|txt|properties|xml)$/
437
+ ];
438
+ var KEY_DIRS = /* @__PURE__ */ new Set(["keys", ".keys", "apikeys", "api-keys", "api_keys"]);
439
+ var DATA_FILE = /(^[^.]+$)|\.(json|ya?ml|toml|ini|cfg|conf|txt|properties|xml|env)$/;
440
+ var PRIVATE_KEY = /-----BEGIN ([A-Z0-9]+ )*PRIVATE KEY( BLOCK)?-----/;
441
+ function looksSecret(path) {
442
+ const parts = path.split(/[\\/]/).map((p) => p.toLowerCase());
443
+ const secretName = (name2) => SECRET_NAMES.has(name2) || SECRET_PATTERNS.some((pattern) => pattern.test(name2));
444
+ if (parts.slice(0, -1).some((dir) => SECRET_DIRS.has(dir) || secretName(dir))) return true;
445
+ const name = parts.at(-1) ?? "";
446
+ if (parts.slice(0, -1).some((dir) => KEY_DIRS.has(dir)) && DATA_FILE.test(name)) return true;
447
+ return secretName(name);
448
+ }
449
+ function git(cwd, args) {
450
+ return new Promise((resolve3, reject) => {
451
+ execFile(
452
+ "git",
453
+ ["-c", "core.quotepath=off", ...args],
454
+ { cwd, maxBuffer: 64 * 1024 * 1024, windowsHide: true, encoding: "utf8" },
455
+ (error, stdout) => error ? reject(error) : resolve3(stdout)
456
+ );
457
+ });
458
+ }
459
+ var splitZ = (text) => text.split("\0").filter((p) => p !== "");
460
+ var toSlash = (path) => path.split(sep).join("/");
461
+ async function changedPaths(root2, since) {
462
+ const untracked = splitZ(await git(root2, ["ls-files", "-z", "--others", "--exclude-standard"]));
463
+ if (since && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(since)) {
464
+ const known = await git(root2, ["cat-file", "-e", `${since}^{commit}`]).then(
465
+ () => true,
466
+ () => false
467
+ );
468
+ if (known) {
469
+ const fields = splitZ(await git(root2, ["diff", "--name-status", "-z", "--no-renames", "--relative", since, "--", "."]));
470
+ const paths = [];
471
+ const deleted = [];
472
+ for (let i = 0; i + 1 < fields.length; i += 2) {
473
+ (fields[i] === "D" ? deleted : paths).push(fields[i + 1]);
474
+ }
475
+ return { paths: [.../* @__PURE__ */ new Set([...paths, ...untracked])], deleted, sinceUsed: true };
476
+ }
477
+ }
478
+ const tracked = splitZ(await git(root2, ["ls-files", "-z", "--cached"]));
479
+ return { paths: [.../* @__PURE__ */ new Set([...tracked, ...untracked])], deleted: [], sinceUsed: false };
480
+ }
481
+ async function readCandidate(root2, realRoot, path) {
482
+ if (looksSecret(path)) return { ok: false, reason: "secret" };
483
+ if (LOCKFILES.has(basename(path).toLowerCase())) return { ok: false, reason: "lockfile" };
484
+ if (path.length > MAX_REVIEW_PATH_CHARS) return { ok: false, reason: "too_large" };
485
+ const full = join3(root2, path);
486
+ let info;
487
+ try {
488
+ info = await lstat(full);
489
+ } catch {
490
+ return { ok: false, reason: "gone" };
491
+ }
492
+ if (!info.isFile()) return { ok: false, reason: "not_a_file" };
493
+ const real = await realpath(full).catch(() => void 0);
494
+ const rel = real === void 0 ? void 0 : relative(realRoot, real);
495
+ if (rel === void 0 || rel === "" || rel.startsWith("..") || isAbsolute(rel)) return { ok: false, reason: "not_a_file" };
496
+ if (info.size > MAX_REVIEW_FILE_CHARS * 4) return { ok: false, reason: "too_large" };
497
+ const bytes = await readFile(full).catch(() => void 0);
498
+ if (!bytes) return { ok: false, reason: "gone" };
499
+ if (bytes.subarray(0, 8e3).includes(0)) return { ok: false, reason: "binary" };
500
+ const content = bytes.toString("utf8");
501
+ if (PRIVATE_KEY.test(content)) return { ok: false, reason: "secret" };
502
+ if (content.length > MAX_REVIEW_FILE_CHARS) return { ok: false, reason: "too_large" };
503
+ return { ok: true, content };
504
+ }
505
+ async function collectChanges(root2, since) {
506
+ try {
507
+ if ((await git(root2, ["rev-parse", "--is-inside-work-tree"])).trim() !== "true") throw new Error("not a work tree");
508
+ } catch {
509
+ return {
510
+ source: "none",
511
+ note: "This folder isn't in a git repository (or git isn't installed), so Mivra can't tell which files to send for review, or which are ignored. Run `git init` here.",
512
+ sinceUsed: false,
513
+ files: [],
514
+ skipped: [],
515
+ deleted: []
516
+ };
517
+ }
518
+ const commit = (await git(root2, ["rev-parse", "--verify", "-q", "HEAD"]).catch(() => "")).trim();
519
+ const { paths, deleted, sinceUsed } = await changedPaths(root2, since);
520
+ const realRoot = await realpath(root2);
521
+ const files = [];
522
+ const skipped = [];
523
+ let total = 0;
524
+ for (const path of paths.map(toSlash).sort()) {
525
+ const read = await readCandidate(root2, realRoot, path);
526
+ if (!read.ok) {
527
+ if (read.reason !== "gone") skipped.push({ path, reason: read.reason });
528
+ continue;
529
+ }
530
+ if (files.length >= MAX_REVIEW_FILES || total + read.content.length > MAX_REVIEW_TOTAL_CHARS) {
531
+ skipped.push({ path, reason: "size_cap" });
532
+ continue;
533
+ }
534
+ total += read.content.length;
535
+ files.push({ path, content: read.content });
536
+ }
537
+ return {
538
+ source: "git",
539
+ .../^[0-9a-f]{40}([0-9a-f]{24})?$/.test(commit) ? { commit } : {},
540
+ sinceUsed,
541
+ files,
542
+ skipped,
543
+ deleted: deleted.map(toSlash).filter((p) => !looksSecret(p) && p.length <= MAX_REVIEW_PATH_CHARS).slice(0, 1e3)
544
+ };
545
+ }
546
+ var SENDABLE = /* @__PURE__ */ new Set(["binary", "too_large", "size_cap", "lockfile"]);
547
+ function changesToSend(changes) {
548
+ return {
549
+ source: changes.source,
550
+ ...changes.commit ? { commit: changes.commit } : {},
551
+ files: changes.files,
552
+ skipped: changes.skipped.filter((s) => SENDABLE.has(s.reason)).slice(0, 1e3),
553
+ deleted: changes.deleted
554
+ };
555
+ }
556
+
557
+ // src/run-command.ts
558
+ import { spawn as nodeSpawn, spawnSync } from "node:child_process";
559
+ import crossSpawn from "cross-spawn";
560
+ var CommandError = class extends Error {
561
+ };
562
+ var SHELL_OPERATORS = /* @__PURE__ */ new Set(["|", "&", ";", "<", ">", "(", ")", "$", "`"]);
563
+ function splitCommand(command, platform = process.platform) {
564
+ const windows = platform === "win32";
565
+ const args = [];
566
+ let current;
567
+ let quote;
568
+ for (let i = 0; i < command.length; i++) {
569
+ const c = command[i];
570
+ if (quote === "'") {
571
+ if (c === "'") quote = void 0;
572
+ else current = (current ?? "") + c;
573
+ } else if (quote === '"') {
574
+ if (c === '"') quote = void 0;
575
+ else if (!windows && c === "\\" && i + 1 < command.length && '"\\$`'.includes(command[i + 1])) current = (current ?? "") + command[++i];
576
+ else current = (current ?? "") + c;
577
+ } else if (/\s/.test(c)) {
578
+ if (current !== void 0) args.push(current);
579
+ current = void 0;
580
+ } else if (c === "'" || c === '"') {
581
+ quote = c;
582
+ current ??= "";
583
+ } else if (!windows && c === "\\") {
584
+ if (i + 1 >= command.length) throw new CommandError("The command ends with a backslash.");
585
+ current = (current ?? "") + command[++i];
586
+ } else if (SHELL_OPERATORS.has(c)) {
587
+ throw new CommandError(
588
+ `Mivra runs the command directly, without a shell, so "${c}" can't be used unquoted. Put pipes, redirects or several steps in a script and run that, e.g. ./check.sh {input}.`
589
+ );
590
+ } else current = (current ?? "") + c;
591
+ }
592
+ if (quote) throw new CommandError(`The command has an unclosed ${quote === '"' ? "double" : "single"} quote.`);
593
+ if (current !== void 0) args.push(current);
594
+ if (args.length === 0) throw new CommandError("The command is empty.");
595
+ return args;
596
+ }
597
+ function fillPlaceholders(args, paths) {
598
+ return args.map((arg) => arg.replaceAll("{input}", paths.input ?? "{input}").replaceAll("{output}", paths.output ?? "{output}"));
599
+ }
600
+ var STDERR_KEEP_CHARS = 2e3;
601
+ var DRAIN_MS = 500;
602
+ var KILL_WAIT_MS = 2e3;
603
+ function windowsKillScript(pid, since) {
604
+ return [
605
+ `$since = [datetime]::Parse('${since.toISOString()}').ToUniversalTime().AddSeconds(-1)`,
606
+ "$all = @(Get-CimInstance Win32_Process | Where-Object { $_.CreationDate -and $_.CreationDate.ToUniversalTime() -ge $since })",
607
+ `$ids = @(${pid})`,
608
+ "$queue = [System.Collections.Generic.Queue[int]]::new(); $queue.Enqueue(" + pid + ")",
609
+ "while ($queue.Count -gt 0) { $p = $queue.Dequeue(); foreach ($c in $all) { if ($c.ParentProcessId -eq $p -and $ids -notcontains $c.ProcessId) { $ids += $c.ProcessId; $queue.Enqueue($c.ProcessId) } } }",
610
+ "foreach ($i in $ids) { if ($i -eq " + pid + " -or ($all | Where-Object ProcessId -eq $i)) { Stop-Process -Id $i -Force -ErrorAction SilentlyContinue } }"
611
+ ].join("; ");
612
+ }
613
+ function killTree(child, startedAt) {
614
+ if (child.pid === void 0) return;
615
+ if (process.platform === "win32") {
616
+ const ps = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", windowsKillScript(child.pid, startedAt)], { stdio: "ignore", windowsHide: true, timeout: 15e3 });
617
+ if (ps.error || ps.status !== 0) spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
618
+ return;
619
+ }
620
+ try {
621
+ process.kill(-child.pid, "SIGKILL");
622
+ } catch {
623
+ child.kill("SIGKILL");
624
+ }
625
+ }
626
+ var active;
627
+ var stopCurrent = () => active && killTree(active.child, active.startedAt);
628
+ function runProgram(args, { cwd, stdin, limits, env = process.env }) {
629
+ return new Promise((resolve3) => {
630
+ const [file, ...rest] = args;
631
+ let child;
632
+ const startedAt = /* @__PURE__ */ new Date();
633
+ try {
634
+ const spawn3 = process.platform === "win32" ? crossSpawn : nodeSpawn;
635
+ child = spawn3(file, rest, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
636
+ } catch (error2) {
637
+ return resolve3({ stdout: "", stderr: "", exitCode: null, error: "start_failed", startError: error2.message });
638
+ }
639
+ active = { child, startedAt };
640
+ const stdout = [];
641
+ let stderr = "";
642
+ let bytes = 0;
643
+ let error;
644
+ let startError;
645
+ let exitCode = null;
646
+ let settled = false;
647
+ const timers = [];
648
+ const finish = () => {
649
+ if (settled) return;
650
+ settled = true;
651
+ for (const timer of timers) clearTimeout(timer);
652
+ if (active?.child === child) active = void 0;
653
+ killTree(child, startedAt);
654
+ child.stdout?.destroy();
655
+ child.stderr?.destroy();
656
+ resolve3({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: stderr.slice(-STDERR_KEEP_CHARS), exitCode: error ? null : exitCode, ...error ? { error } : {}, ...startError ? { startError } : {} });
657
+ };
658
+ const stop2 = (reason) => {
659
+ if (error || settled) return;
660
+ error = reason;
661
+ killTree(child, startedAt);
662
+ timers.push(setTimeout(finish, KILL_WAIT_MS));
663
+ };
664
+ const count = (chunk) => {
665
+ bytes += chunk.length;
666
+ if (bytes > limits.maxOutputBytes) stop2("output_limit");
667
+ return bytes <= limits.maxOutputBytes;
668
+ };
669
+ child.stdout.on("data", (chunk) => {
670
+ if (count(chunk)) stdout.push(chunk);
671
+ });
672
+ child.stderr.setEncoding("utf8");
673
+ child.stderr.on("data", (chunk) => {
674
+ if (count(Buffer.from(chunk))) stderr = (stderr + chunk).slice(-STDERR_KEEP_CHARS * 2);
675
+ });
676
+ child.once("error", (e) => {
677
+ startError = e.message;
678
+ error ??= "start_failed";
679
+ finish();
680
+ });
681
+ child.once("exit", (code) => {
682
+ exitCode = code;
683
+ timers.push(setTimeout(finish, DRAIN_MS));
684
+ });
685
+ child.once("close", finish);
686
+ timers.push(setTimeout(() => stop2("timeout"), limits.timeoutMs));
687
+ child.stdin.on("error", () => {
688
+ });
689
+ child.stdin.end(stdin);
690
+ });
691
+ }
692
+
693
+ // src/project.ts
694
+ var LINK_FILE = ".mivra.json";
695
+ var LinkFile = z2.object({
696
+ course: z2.string().min(1),
697
+ /** The learner's command, e.g. `./build/mycc {input}`. */
698
+ run: z2.string().min(1),
699
+ /** For cases that run the program's output (e.g. generated assembly): a command with `{output}`. */
700
+ runOutput: z2.string().min(1).optional()
701
+ });
702
+ var MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
703
+ var ProjectError = class extends Error {
704
+ };
705
+ async function server(dataDir) {
706
+ const remote = readRemoteServer(dataDir);
707
+ if (remote) return { ...remote, remote: true };
708
+ const local = await running(dataDir);
709
+ if (!local) throw new ProjectError("Mivra isn't running. Start it with `mivra start --detach`, then try again.");
710
+ try {
711
+ return { url: local.url, token: readFileSync2(join4(dataDir, TOKEN_FILE), "utf8").trim(), remote: false };
712
+ } catch {
713
+ throw new ProjectError(`Couldn't read Mivra's API token from ${join4(dataDir, TOKEN_FILE)}.`);
714
+ }
715
+ }
716
+ function client({ url, token, remote }) {
717
+ const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
718
+ const relink = `Get its token from Settings \u2192 Connect a CLI, or \`mivra token\` where it runs, and run \`mivra link --server ${url}\` again.`;
719
+ return async (path, init = {}, timeoutMs = 3e4) => {
720
+ let res;
721
+ try {
722
+ res = await fetch(`${url}/api${path}`, { ...init, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
723
+ } catch {
724
+ throw new ProjectError(remote ? `Couldn't reach Mivra at ${url}. Check it's running and that this computer can reach it.` : `Couldn't reach Mivra at ${url}.`);
725
+ }
726
+ if (res.ok) return res.json();
727
+ if (res.status >= 300 && res.status < 400) throw redirected(url, res);
728
+ const message = (await res.json().catch(() => ({}))).error;
729
+ if (remote && res.status === 401) throw new ProjectError(`Mivra at ${url} didn't accept the token. ${relink}`);
730
+ if (remote && res.status === 403 && message === "Host not allowed") throw hostRefused(url);
731
+ throw new ProjectError(typeof message === "string" ? message : `Mivra answered ${res.status}.`);
732
+ };
733
+ }
734
+ async function connect(dataDir) {
735
+ const found = await server(dataDir);
736
+ return { url: found.url, remote: found.remote, call: client(found) };
737
+ }
738
+ var hostRefused = (url) => new ProjectError(`Mivra at ${url} doesn't accept requests for ${new URL(url).hostname}. Add it to MIVRA_ALLOWED_HOSTS where Mivra runs, and restart it.`);
739
+ var redirected = (url, res) => {
740
+ const location = res.headers.get("location");
741
+ return new ProjectError(`${url} redirects${location ? ` to ${location}` : ""}, which Mivra doesn't follow. Use Mivra's own address: \`mivra link --server <url>\`.`);
742
+ };
743
+ async function isMivra(url) {
744
+ let res;
745
+ try {
746
+ res = await fetch(`${url}/api/health`, { redirect: "manual", signal: AbortSignal.timeout(1e4) });
747
+ } catch {
748
+ return false;
749
+ }
750
+ if (res.status >= 300 && res.status < 400) throw redirected(url, res);
751
+ const body = await res.json().catch(() => ({}));
752
+ if (res.status === 403 && body.error === "Host not allowed") throw hostRefused(url);
753
+ return res.ok && body.ok === true;
754
+ }
755
+ async function connectRemote(url, dataDir, readToken, io) {
756
+ if (!await isMivra(url)) throw new ProjectError(`There's no Mivra answering at ${url}. Check the address, and that Mivra is running there.`);
757
+ let input;
758
+ try {
759
+ input = await readToken();
760
+ } catch (error) {
761
+ throw new ProjectError(error.message);
762
+ }
763
+ const token = ServerToken.safeParse(input);
764
+ if (!token.success) throw new ProjectError(input ? token.error.issues[0].message : "No token given.");
765
+ await client({ url, token: token.data, remote: true })("/settings/tasks");
766
+ saveRemoteServer(dataDir, { url, token: token.data });
767
+ io.out(`Connected to Mivra at ${url}. Its address and token are saved in ${join4(dataDir, CREDENTIALS_FILE)}, not in .mivra.json.`);
768
+ const { hostname, protocol } = new URL(url);
769
+ if (protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(hostname)) {
770
+ io.err("The token goes over plain HTTP to that address. That's only safe on a network that encrypts traffic itself, such as a tailnet.");
771
+ }
772
+ }
773
+ function checkCommand(command, where) {
774
+ try {
775
+ splitCommand(command);
776
+ } catch (error) {
777
+ if (error instanceof CommandError) throw new ProjectError(`${where}: ${error.message}`);
778
+ throw error;
779
+ }
780
+ }
781
+ function failed(error, io) {
782
+ if (error instanceof ProjectError) io.err(error.message);
783
+ else if (error instanceof z2.ZodError) io.err("Mivra answered with something this `mivra` doesn't understand. Update it to the same version as the running Mivra.");
784
+ else throw error;
785
+ return 1;
786
+ }
787
+ async function link({ course, run, runOutput, server: url, local }, { dataDir, cwd, readToken }, io) {
788
+ try {
789
+ if (run !== void 0) checkCommand(run, "--run");
790
+ if (runOutput !== void 0) {
791
+ checkCommand(runOutput, "--run-output");
792
+ if (!runOutput.includes("{output}")) throw new ProjectError(`--run-output needs {output} where the path to your program's output goes, e.g. "./run-asm.sh {output}".`);
793
+ }
794
+ if (local) io.out(removeRemoteServer(dataDir) ? "Forgot the remote Mivra: link and check use the one running on this computer again." : "Link and check already use the Mivra running on this computer.");
795
+ if (url) await connectRemote(url, dataDir, readToken, io);
796
+ if (course === void 0 || run === void 0) return 0;
797
+ const { call, url: at, remote } = await connect(dataDir);
798
+ const found = CourseView.parse(await call(`/courses/${encodeURIComponent(course)}`));
799
+ if (found.kind !== "project") throw new ProjectError(`"${found.goal}" isn't a project course, so there's nothing to check from a repository.`);
800
+ const path = join4(cwd, LINK_FILE);
801
+ const file = { course: found.id, run, ...runOutput ? { runOutput } : {} };
802
+ writeFileSync(path, `${JSON.stringify(file, null, 2)}
803
+ `);
804
+ io.out(`Linked this folder to "${found.goal}"${remote ? ` on Mivra at ${at}` : ""} in ${path}. It holds no secrets, so you can commit it.`);
805
+ io.out(`Mivra will run: ${run}${run.includes("{input}") ? "" : " (each case's input comes on stdin; add {input} to get it as a file path too)"}`);
806
+ io.out("Run `mivra check` here to check the current milestone.");
807
+ return 0;
808
+ } catch (error) {
809
+ return failed(error, io);
810
+ }
811
+ }
812
+ function findLink(cwd) {
813
+ let dir = resolve(cwd);
814
+ for (; ; ) {
815
+ const path = join4(dir, LINK_FILE);
816
+ let text;
817
+ try {
818
+ text = readFileSync2(path, "utf8");
819
+ } catch {
820
+ }
821
+ if (text !== void 0) {
822
+ let parsed;
823
+ try {
824
+ parsed = LinkFile.safeParse(JSON.parse(text));
825
+ } catch {
826
+ throw new ProjectError(`${path} isn't valid JSON. Run \`mivra link\` again to rewrite it.`);
827
+ }
828
+ if (!parsed.success) throw new ProjectError(`${path} needs "course" and "run". Run \`mivra link\` again to rewrite it.`);
829
+ return { path, file: parsed.data };
830
+ }
831
+ const parent = dirname(dir);
832
+ if (parent === dir) throw new ProjectError(`No ${LINK_FILE} here or above. Link this folder to a project course first: \`mivra link <course> --run "<command>"\`.`);
833
+ dir = parent;
834
+ }
835
+ }
836
+ function caseResult(run) {
837
+ const stdout = normaliseOutput(run.stdout);
838
+ const stderr = run.stderr.slice(-MAX_MILESTONE_STDERR_CHARS);
839
+ return {
840
+ stdout: stdout.slice(0, MAX_CASE_OUTPUT_CHARS),
841
+ ...stdout.length > MAX_CASE_OUTPUT_CHARS ? { truncated: true } : {},
842
+ ...stderr ? { stderr } : {},
843
+ exitCode: run.exitCode,
844
+ ...run.error ? { error: run.error } : {}
845
+ };
846
+ }
847
+ async function runCase(link2, testCase, { cwd, limits }) {
848
+ const dir = mkdtempSync(join4(tmpdir(), "mivra-check-"));
849
+ try {
850
+ const input = join4(dir, "input");
851
+ writeFileSync(input, testCase.input);
852
+ const first = await runProgram(fillPlaceholders(splitCommand(link2.run), { input }), { cwd, stdin: testCase.input, limits });
853
+ if (testCase.compare !== "run_output" || first.error || first.exitCode !== 0) return { result: caseResult(first), startError: first.startError };
854
+ if (!link2.runOutput) return { result: { stdout: "", exitCode: null, error: "no_run_output_command" } };
855
+ const output = join4(dir, "output");
856
+ writeFileSync(output, first.stdout);
857
+ const second = await runProgram(fillPlaceholders(splitCommand(link2.runOutput), { input, output }), { cwd, stdin: "", limits });
858
+ return { result: caseResult(second), startError: second.startError };
859
+ } finally {
860
+ rmSync2(dir, { recursive: true, force: true });
861
+ }
862
+ }
863
+ var ERROR_TEXT = {
864
+ timeout: "stopped: it took longer than the time limit",
865
+ output_limit: "stopped: it printed more than the output limit",
866
+ start_failed: "couldn't start",
867
+ no_run_output_command: 'this case runs your program\'s output: set a command for that with `mivra link <course> --run "\u2026" --run-output "\u2026 {output}"`'
868
+ };
869
+ var excerpt = (text, lines = 8) => {
870
+ const all = text.split("\n");
871
+ const shown = all.slice(0, lines).map((line) => ` ${line}`);
872
+ return [...shown, ...all.length > lines ? [` \u2026 (${all.length - lines} more lines)`] : []].join("\n");
873
+ };
874
+ var CHECK_TIMEOUT_MS = 5 * 6e4;
875
+ var kb = (chars) => `${(chars / 1024).toFixed(1)} KB`;
876
+ var SKIP_TEXT = {
877
+ secret: "looks like it holds a secret: never sent, not even its name",
878
+ not_a_file: "a link or folder: never followed",
879
+ binary: "binary",
880
+ too_large: "too large to review",
881
+ size_cap: "over the size Mivra sends for one check",
882
+ lockfile: "a lockfile"
883
+ };
884
+ function describeChanges(changes, io, { full }) {
885
+ if (changes.source === "none") {
886
+ io.out(changes.note ?? "No files to send.");
887
+ return;
888
+ }
889
+ const total = changes.files.reduce((sum, f) => sum + f.content.length, 0);
890
+ const what = changes.sinceUsed ? "changed since the last passed milestone" : "in the repository (no earlier passed milestone to compare with)";
891
+ if (!full) {
892
+ io.out(`Sending ${changes.files.length} ${changes.files.length === 1 ? "file" : "files"} (${kb(total)}) ${what} for review${changes.skipped.length ? `, leaving out ${changes.skipped.length}` : ""}. See them with \`mivra check --dry-run\`.`);
893
+ return;
894
+ }
895
+ io.out(changes.files.length === 0 ? `No files ${what} to send.` : `Files ${what} that would be sent for review (${changes.files.length}, ${kb(total)}):`);
896
+ for (const file of changes.files) io.out(` ${file.path} (${kb(file.content.length)})`);
897
+ if (changes.skipped.length > 0) {
898
+ io.out("Not sent:");
899
+ for (const skip of changes.skipped) io.out(` ${skip.path} (${SKIP_TEXT[skip.reason]})`);
900
+ }
901
+ if (changes.deleted.length > 0) io.out(`Named as deleted: ${changes.deleted.join(", ")}`);
902
+ if (changes.commit) io.out(`Commit: ${changes.commit}`);
903
+ }
904
+ var CRITERIA = [
905
+ ["noHardCodedOutputs", "Computes its output"],
906
+ ["concept", "Shows the milestone's concept"],
907
+ ["quality", "Code quality"]
908
+ ];
909
+ function showReview(review, io) {
910
+ if (review.status === "skipped") {
911
+ io.out(review.reason === "tests_failed" ? "Review: not yet, since the tests must pass first." : "Review: nothing was sent to review, so the milestone can't pass yet.");
912
+ return;
913
+ }
914
+ if (review.status === "failed") {
915
+ io.out(`Review: it didn't finish (${review.error}). Run mivra check again.`);
916
+ return;
917
+ }
918
+ const { review: verdict } = review;
919
+ io.out(`Review (judged by a model, ${verdict.model}): ${verdict.approved ? "approved" : "changes requested"}`);
920
+ for (const [key, label] of CRITERIA) io.out(` ${verdict[key].passed ? "pass" : "FAIL"} ${label}: ${verdict[key].note}`);
921
+ io.out(` ${verdict.summary}`);
922
+ for (const suggestion of verdict.suggestions) io.out(` - ${suggestion}`);
923
+ if (!verdict.approved) io.out(" You can dispute the verdict from the milestone in Mivra.");
924
+ }
925
+ async function check({ timeoutS, dryRun = false }, { dataDir, cwd }, io) {
926
+ const onInterrupt = () => {
927
+ stopCurrent();
928
+ process.exit(130);
929
+ };
930
+ process.once("SIGINT", onInterrupt);
931
+ try {
932
+ const found = findLink(cwd);
933
+ const root2 = dirname(found.path);
934
+ checkCommand(found.file.run, `"run" in ${found.path}`);
935
+ if (found.file.runOutput) checkCommand(found.file.runOutput, `"runOutput" in ${found.path}`);
936
+ const { call, url, remote } = await connect(dataDir);
937
+ if (remote) io.out(`Checking against Mivra at ${url}; your program runs here.`);
938
+ const milestone = MilestoneCases.parse(await call(`/courses/${encodeURIComponent(found.file.course)}/milestone`));
939
+ const count = milestone.checkType === "review" ? "checked by review" : `${milestone.cases.length} ${milestone.cases.length === 1 ? "case" : "cases"}`;
940
+ io.out(`Milestone ${milestone.position}: ${milestone.title} (${count})`);
941
+ const changes = await collectChanges(root2, milestone.since);
942
+ if (dryRun) {
943
+ if (milestone.cases.length > 0) io.out(`A check would run your command on ${milestone.cases.length} ${milestone.cases.length === 1 ? "case" : "cases"} and send what it printed.`);
944
+ describeChanges(changes, io, { full: true });
945
+ io.out("Nothing was run or sent.");
946
+ return 0;
947
+ }
948
+ const limits = { timeoutMs: timeoutS * 1e3, maxOutputBytes: MAX_OUTPUT_BYTES };
949
+ const results = [];
950
+ for (const testCase of milestone.cases) {
951
+ const { result, startError } = await runCase(found.file, testCase, { cwd: root2, limits });
952
+ results.push(result);
953
+ if (startError) {
954
+ io.err(`Couldn't run your command (${startError}). Check the commands in ${found.path}; they run from ${root2}.`);
955
+ return 1;
956
+ }
957
+ }
958
+ describeChanges(changes, io, { full: false });
959
+ const body = { results, revision: milestone.revision, ...changesToSend(changes) };
960
+ const graded = MilestoneCheckResult.parse(
961
+ await call(`/artifacts/${encodeURIComponent(milestone.artifactId)}/checks`, { method: "POST", body: JSON.stringify(body) }, CHECK_TIMEOUT_MS)
962
+ );
963
+ milestone.cases.forEach((testCase, i) => {
964
+ const passed2 = graded.grade.cases[i]?.passed ?? false;
965
+ io.out(` ${passed2 ? "pass" : "FAIL"} ${testCase.name}`);
966
+ if (passed2) return;
967
+ const result = results[i];
968
+ if (result.error) io.out(` ${ERROR_TEXT[result.error]}`);
969
+ else {
970
+ if (result.exitCode !== 0) io.out(` exited with code ${result.exitCode}`);
971
+ io.out(` expected:
972
+ ${excerpt(graded.expected[i] ?? "")}`);
973
+ io.out(` got:${result.stdout ? `
974
+ ${excerpt(result.stdout)}` : " (nothing)"}${result.truncated ? "\n \u2026 (cut short)" : ""}`);
975
+ }
976
+ if (result.stderr) io.out(` stderr:
977
+ ${excerpt(result.stderr, 4)}`);
978
+ });
979
+ const { passed, total } = graded.grade;
980
+ if (total > 0) io.out(passed === total ? `All ${total} cases passed.` : `${passed} of ${total} cases passed.`);
981
+ showReview(graded.review, io);
982
+ io.out(graded.passed ? "Milestone passed. Recorded in Mivra." : "Not passed yet. Recorded in Mivra.");
983
+ return graded.passed ? 0 : 1;
984
+ } catch (error) {
985
+ return failed(error, io);
986
+ } finally {
987
+ process.removeListener("SIGINT", onInterrupt);
988
+ }
989
+ }
990
+
325
991
  // src/uninstall.ts
326
- import { existsSync, readdirSync, rmSync as rmSync2, rmdirSync } from "node:fs";
327
- import { join as join3 } from "node:path";
992
+ import { existsSync, readdirSync, rmSync as rmSync3, rmdirSync } from "node:fs";
993
+ import { join as join5 } from "node:path";
328
994
  var PACKAGE = "@okhay-p/mivra";
329
995
  var DATA_FILES = ["mivra.db", "mivra.db-wal", "mivra.db-shm", "mivra.db-journal", CREDENTIALS_FILE, CHATGPT_FILE, TOKEN_FILE, STATE_FILE, LOG_FILE];
330
996
  var BACKUPS_DIR = "backups";
331
997
  var GENERATED_BACKUP = /^mivra-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.db$/;
332
998
  function mivraFiles(dataDir) {
333
- const files = DATA_FILES.filter((name) => existsSync(join3(dataDir, name)));
999
+ const files = DATA_FILES.filter((name) => existsSync(join5(dataDir, name)));
334
1000
  try {
335
- for (const name of readdirSync(join3(dataDir, BACKUPS_DIR))) if (GENERATED_BACKUP.test(name)) files.push(join3(BACKUPS_DIR, name));
1001
+ for (const name of readdirSync(join5(dataDir, BACKUPS_DIR))) if (GENERATED_BACKUP.test(name)) files.push(join5(BACKUPS_DIR, name));
336
1002
  } catch {
337
1003
  }
338
1004
  return files;
@@ -370,12 +1036,12 @@ async function deleteDataIn(dataDir, entries, err2) {
370
1036
  } catch {
371
1037
  }
372
1038
  try {
373
- for (const name of entries) rmSync2(join3(dataDir, name), { force: true });
1039
+ for (const name of entries) rmSync3(join5(dataDir, name), { force: true });
374
1040
  } catch (error) {
375
1041
  err2(`Couldn't delete everything in ${dataDir}: ${error.message}`);
376
1042
  return false;
377
1043
  }
378
- for (const dir of [join3(dataDir, BACKUPS_DIR), dataDir]) {
1044
+ for (const dir of [join5(dataDir, BACKUPS_DIR), dataDir]) {
379
1045
  try {
380
1046
  if (readdirSync(dir).length === 0) rmdirSync(dir);
381
1047
  } catch {
@@ -385,8 +1051,8 @@ async function deleteDataIn(dataDir, entries, err2) {
385
1051
  }
386
1052
 
387
1053
  // src/vault.ts
388
- import { readFileSync as readFileSync2, readdirSync as readdirSync2, statSync } from "node:fs";
389
- import { basename, join as join4, relative, resolve, sep } from "node:path";
1054
+ import { readFileSync as readFileSync3, readdirSync as readdirSync2, statSync } from "node:fs";
1055
+ import { basename as basename2, join as join6, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
390
1056
  var VaultReadError = class extends Error {
391
1057
  };
392
1058
  function readVault(root2) {
@@ -405,11 +1071,11 @@ function readVault(root2) {
405
1071
  const folder = folders.pop();
406
1072
  for (const entry of readdirSync2(folder, { withFileTypes: true })) {
407
1073
  if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
408
- const full = join4(folder, entry.name);
1074
+ const full = join6(folder, entry.name);
409
1075
  if (entry.isDirectory()) folders.push(full);
410
1076
  else if (entry.isFile() && /\.md$/i.test(entry.name)) {
411
1077
  if (files.length >= MAX_VAULT_FILES) throw new VaultReadError(`The vault has more than ${MAX_VAULT_FILES} notes, more than one import can take.`);
412
- const path = relative(root2, full).split(sep).join("/");
1078
+ const path = relative2(root2, full).split(sep2).join("/");
413
1079
  const size = statSync(full).size;
414
1080
  if (size > MAX_NOTE_CHARS * 4) {
415
1081
  tooLong.push(path);
@@ -417,7 +1083,7 @@ function readVault(root2) {
417
1083
  }
418
1084
  bytes += size;
419
1085
  if (bytes > MAX_VAULT_BYTES) throw new VaultReadError(`The vault's notes come to more than ${MAX_VAULT_BYTES / (1024 * 1024)} MB, more than one import can take.`);
420
- const text = readFileSync2(full, "utf8");
1086
+ const text = readFileSync3(full, "utf8");
421
1087
  if (text.length > MAX_NOTE_CHARS) tooLong.push(path);
422
1088
  else files.push({ path, text });
423
1089
  }
@@ -428,7 +1094,7 @@ function readVault(root2) {
428
1094
  }
429
1095
  var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
430
1096
  async function importObsidian(folder, name, dataDir, io) {
431
- const root2 = resolve(folder);
1097
+ const root2 = resolve2(folder);
432
1098
  let vault;
433
1099
  try {
434
1100
  vault = readVault(root2);
@@ -437,25 +1103,25 @@ async function importObsidian(folder, name, dataDir, io) {
437
1103
  io.err(error.message);
438
1104
  return 1;
439
1105
  }
440
- const importName = (name ?? basename(root2)).trim();
1106
+ const importName = (name ?? basename2(root2)).trim();
441
1107
  if (vault.files.length === 0) {
442
1108
  io.err(`No Markdown notes found in ${root2}.`);
443
1109
  return 1;
444
1110
  }
445
- const server = await running(dataDir);
446
- if (!server) {
1111
+ const server2 = await running(dataDir);
1112
+ if (!server2) {
447
1113
  io.err("Mivra isn't running. Start it with `mivra start --detach`, then import again.");
448
1114
  return 1;
449
1115
  }
450
1116
  let token;
451
1117
  try {
452
- token = readFileSync2(join4(dataDir, TOKEN_FILE), "utf8").trim();
1118
+ token = readFileSync3(join6(dataDir, TOKEN_FILE), "utf8").trim();
453
1119
  } catch {
454
- io.err(`Couldn't read Mivra's API token from ${join4(dataDir, TOKEN_FILE)}.`);
1120
+ io.err(`Couldn't read Mivra's API token from ${join6(dataDir, TOKEN_FILE)}.`);
455
1121
  return 1;
456
1122
  }
457
1123
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
458
- const listed = await fetch(`${server.url}/api/imports`, { headers });
1124
+ const listed = await fetch(`${server2.url}/api/imports`, { headers });
459
1125
  if (!listed.ok) {
460
1126
  io.err(`Mivra refused to list imports (${listed.status}).`);
461
1127
  return 1;
@@ -466,7 +1132,7 @@ async function importObsidian(folder, name, dataDir, io) {
466
1132
  io.err(`The vault's notes come to more than ${MAX_VAULT_BYTES / (1024 * 1024)} MB, more than one import can take.`);
467
1133
  return 1;
468
1134
  }
469
- const res = await fetch(existing ? `${server.url}/api/imports/${existing.id}/files` : `${server.url}/api/imports`, {
1135
+ const res = await fetch(existing ? `${server2.url}/api/imports/${existing.id}/files` : `${server2.url}/api/imports`, {
470
1136
  method: existing ? "PUT" : "POST",
471
1137
  headers,
472
1138
  body
@@ -490,9 +1156,9 @@ async function importObsidian(folder, name, dataDir, io) {
490
1156
  // src/cli.ts
491
1157
  var root = fileURLToPath(new URL("..", import.meta.url));
492
1158
  var firstExisting = (...paths) => paths.find((p) => existsSync2(p)) ?? paths[0];
493
- var webDist = () => firstExisting(join5(root, "web"), join5(root, "../web/dist"));
494
- var migrations = () => firstExisting(join5(root, "drizzle"), join5(root, "../server/drizzle"));
495
- var version = () => JSON.parse(readFileSync3(join5(root, "package.json"), "utf8")).version;
1159
+ var webDist = () => firstExisting(join7(root, "web"), join7(root, "../web/dist"));
1160
+ var migrations = () => firstExisting(join7(root, "drizzle"), join7(root, "../server/drizzle"));
1161
+ var version = () => JSON.parse(readFileSync4(join7(root, "package.json"), "utf8")).version;
496
1162
  var out = (message) => process.stdout.write(`${message}
497
1163
  `);
498
1164
  var err = (message) => process.stderr.write(`${message}
@@ -542,6 +1208,12 @@ ${USAGE}`);
542
1208
  return authLogout(config);
543
1209
  case "import-obsidian":
544
1210
  return importObsidian(command.folder, command.importName, config.dataDir, { out, err });
1211
+ case "link":
1212
+ return link(command, { dataDir: config.dataDir, cwd: process.cwd(), readToken: () => readSecret("Paste the Mivra token (hidden): ") }, { out, err });
1213
+ case "token":
1214
+ return printToken(config.dataDir);
1215
+ case "check":
1216
+ return check(command, { dataDir: config.dataDir, cwd: process.cwd() }, { out, err });
545
1217
  case "uninstall":
546
1218
  return uninstall({ dataDir: config.dataDir, deleteData: command.deleteData, stop: () => stop(config.dataDir), confirm, out, err });
547
1219
  }
@@ -569,14 +1241,14 @@ async function startForeground(command, base, env) {
569
1241
  }
570
1242
  claimed = claim(config.dataDir);
571
1243
  if (!claimed.ok) {
572
- err(`Another Mivra (process ${claimed.holder.pid}) holds ${join5(config.dataDir, STATE_FILE)} but doesn't answer. If it isn't running, delete that file.`);
1244
+ err(`Another Mivra (process ${claimed.holder.pid}) holds ${join7(config.dataDir, STATE_FILE)} but doesn't answer. If it isn't running, delete that file.`);
573
1245
  return 1;
574
1246
  }
575
1247
  }
576
- const [{ PortInUseError, startServer }, { NewerDatabaseError }] = await Promise.all([import("./start-2RXX57ZZ.js"), import("./client-5YDLS4KV.js")]);
577
- let server;
1248
+ const [{ PortInUseError, startServer }, { NewerDatabaseError }] = await Promise.all([import("./start-SX3BCBIN.js"), import("./client-4UG5W5NJ.js")]);
1249
+ let server2;
578
1250
  try {
579
- server = await startServer({ config, env, webDist: webDist(), migrationsFolder: migrations(), portFallback: true, log: err });
1251
+ server2 = await startServer({ config, env, webDist: webDist(), migrationsFolder: migrations(), portFallback: true, log: err });
580
1252
  } catch (error) {
581
1253
  clearState(config.dataDir, process.pid);
582
1254
  if (error instanceof PortInUseError) {
@@ -604,23 +1276,23 @@ ${error.message}`);
604
1276
  process.exit(0);
605
1277
  };
606
1278
  setTimeout(exit, 5e3).unref();
607
- void server.close().then(exit, exit);
1279
+ void server2.close().then(exit, exit);
608
1280
  };
609
1281
  process.once("SIGINT", shutdown);
610
1282
  process.once("SIGTERM", shutdown);
611
1283
  process.once("SIGHUP", shutdown);
612
- writeState(config.dataDir, { pid: process.pid, port: server.port, url: server.url, startedAt: readState(config.dataDir)?.startedAt ?? (/* @__PURE__ */ new Date()).toISOString() });
613
- if (server.port !== config.port) err(`Port ${config.port} is in use, so Mivra is on ${server.port}.`);
614
- out(`Mivra is running at ${server.url}`);
1284
+ writeState(config.dataDir, { pid: process.pid, port: server2.port, url: server2.url, startedAt: readState(config.dataDir)?.startedAt ?? (/* @__PURE__ */ new Date()).toISOString() });
1285
+ if (server2.port !== config.port) err(`Port ${config.port} is in use, so Mivra is on ${server2.port}.`);
1286
+ out(`Mivra is running at ${server2.url}`);
615
1287
  out(env.MIVRA_DETACHED === "1" ? `Data: ${config.dataDir}` : `Data: ${config.dataDir}. Press Ctrl+C to stop.`);
616
- if (command.open) openBrowser(server.url);
1288
+ if (command.open) openBrowser(server2.url);
617
1289
  return new Promise(() => {
618
1290
  });
619
1291
  }
620
1292
  var DETACH_TIMEOUT_MS = 6e4;
621
1293
  async function startDetached(command, config, env) {
622
1294
  if (await alreadyRunning(config.dataDir, command.open)) return 0;
623
- const logPath = join5(config.dataDir, LOG_FILE);
1295
+ const logPath = join7(config.dataDir, LOG_FILE);
624
1296
  mkdirSync2(config.dataDir, { recursive: true });
625
1297
  const log = openSync2(logPath, "a", 384);
626
1298
  const args = [...process.execArgv, process.argv[1], "start", "--no-open", ...command.port === void 0 ? [] : ["--port", String(command.port)]];
@@ -662,7 +1334,7 @@ ${tail(logPath)}`);
662
1334
  }
663
1335
  function tail(path, lines = 20) {
664
1336
  try {
665
- return readFileSync3(path, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
1337
+ return readFileSync4(path, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
666
1338
  } catch {
667
1339
  return "(no log)";
668
1340
  }
@@ -680,7 +1352,7 @@ async function stop(dataDir) {
680
1352
  return 1;
681
1353
  }
682
1354
  if (!await running(dataDir)) {
683
- err(`Process ${state.pid} is recorded as Mivra but nothing answers at ${state.url}, so it was left alone. If Mivra isn't running, delete ${join5(dataDir, "mivra.pid")}.`);
1355
+ err(`Process ${state.pid} is recorded as Mivra but nothing answers at ${state.url}, so it was left alone. If Mivra isn't running, delete ${join7(dataDir, "mivra.pid")}.`);
684
1356
  return 1;
685
1357
  }
686
1358
  process.kill(state.pid, "SIGTERM");
@@ -695,7 +1367,7 @@ async function stop(dataDir) {
695
1367
  return 0;
696
1368
  }
697
1369
  var fromEnvMessage = (provider2) => `${PROVIDER_ENV[provider2]} is set in this environment, and it takes precedence over a saved key. Change or unset it instead.`;
698
- async function authSet(provider2, check, config, env) {
1370
+ async function authSet(provider2, check2, config, env) {
699
1371
  const credentials = createCredentialStore({ dataDir: config.dataDir, env });
700
1372
  if (env[PROVIDER_ENV[provider2]]?.trim()) {
701
1373
  err(fromEnvMessage(provider2));
@@ -714,8 +1386,8 @@ async function authSet(provider2, check, config, env) {
714
1386
  return 1;
715
1387
  }
716
1388
  credentials.set(provider2, key.data);
717
- out(`Saved the ${PROVIDER_LABELS[provider2]} key to ${join5(config.dataDir, CREDENTIALS_FILE)}. A running Mivra uses it from the next reply.`);
718
- if (!check) return 0;
1389
+ out(`Saved the ${PROVIDER_LABELS[provider2]} key to ${join7(config.dataDir, CREDENTIALS_FILE)}. A running Mivra uses it from the next reply.`);
1390
+ if (!check2) return 0;
719
1391
  const baseUrl = provider2 === "anthropic" ? env.ANTHROPIC_BASE_URL : provider2 === "openai" ? env.OPENAI_BASE_URL : void 0;
720
1392
  const { checkProviderKey } = await import("./key-check-WJ4CVZV5.js");
721
1393
  const result = await checkProviderKey(provider2, key.data, { baseUrl });
@@ -763,7 +1435,7 @@ async function authLogin(newAccount, open, config) {
763
1435
  err(result.notice ?? "Sign-in didn't finish.");
764
1436
  return 1;
765
1437
  }
766
- out(`Signed in to ChatGPT${result.email ? ` as ${result.email}` : ""}, saved in ${join5(config.dataDir, CHATGPT_FILE)}. A running Mivra uses it from the next reply.`);
1438
+ out(`Signed in to ChatGPT${result.email ? ` as ${result.email}` : ""}, saved in ${join7(config.dataDir, CHATGPT_FILE)}. A running Mivra uses it from the next reply.`);
767
1439
  return 0;
768
1440
  }
769
1441
  async function authLogout(config) {
@@ -776,6 +1448,11 @@ async function authLogout(config) {
776
1448
  out(revoked ? "Signed out of ChatGPT." : "Signed out of ChatGPT here, but ChatGPT didn't confirm it. To be sure, disconnect Mivra in ChatGPT's settings.");
777
1449
  return 0;
778
1450
  }
1451
+ function printToken(dataDir) {
1452
+ err(`Mivra's token, from ${join7(dataDir, TOKEN_FILE)}. On the other computer, run \`mivra link --server <this Mivra's address>\` and paste it there. Anyone with it can use this Mivra, so keep it private.`);
1453
+ out(loadOrCreateToken(dataDir));
1454
+ return 0;
1455
+ }
779
1456
  function authRemove(provider2, config, env) {
780
1457
  const removed = createCredentialStore({ dataDir: config.dataDir, env }).remove(provider2);
781
1458
  if (removed === "env") {