@okhay-p/mivra 0.1.6 → 0.1.7

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 (47) hide show
  1. package/dist/{chunk-DYXNHODU.js → chunk-M62PZTK3.js} +117 -4
  2. package/dist/chunk-M62PZTK3.js.map +7 -0
  3. package/dist/{chunk-KE5ZEREE.js → chunk-T5WM74CI.js} +2 -1
  4. package/dist/{chunk-B47HA6IQ.js → chunk-TKDX5OCX.js} +739 -478
  5. package/dist/chunk-TKDX5OCX.js.map +7 -0
  6. package/dist/cli.js +492 -123
  7. package/dist/cli.js.map +4 -4
  8. package/dist/{client-4UG5W5NJ.js → client-76YUHG4T.js} +2 -2
  9. package/dist/exercise-child.js +1 -1
  10. package/dist/extract-child.js +2 -2
  11. package/dist/python-child.js +1 -1
  12. package/dist/{start-SX3BCBIN.js → start-GVAACONX.js} +14504 -12040
  13. package/dist/start-GVAACONX.js.map +7 -0
  14. package/drizzle/0021_strange_gamma_corps.sql +2 -0
  15. package/drizzle/0022_fast_forgotten_one.sql +28 -0
  16. package/drizzle/0023_low_wiccan.sql +17 -0
  17. package/drizzle/0024_windy_annihilus.sql +1 -0
  18. package/drizzle/0025_brief_rictor.sql +6 -0
  19. package/drizzle/0026_greedy_sally_floyd.sql +1 -0
  20. package/drizzle/0027_regular_calypso.sql +41 -0
  21. package/drizzle/0028_lazy_agent_zero.sql +17 -0
  22. package/drizzle/meta/0021_snapshot.json +2313 -0
  23. package/drizzle/meta/0022_snapshot.json +2529 -0
  24. package/drizzle/meta/0023_snapshot.json +2654 -0
  25. package/drizzle/meta/0024_snapshot.json +2662 -0
  26. package/drizzle/meta/0025_snapshot.json +2707 -0
  27. package/drizzle/meta/0026_snapshot.json +2714 -0
  28. package/drizzle/meta/0027_snapshot.json +2816 -0
  29. package/drizzle/meta/0028_snapshot.json +2940 -0
  30. package/drizzle/meta/_journal.json +56 -0
  31. package/package.json +1 -1
  32. package/web/assets/exercise-workers/{exercise.worker-DzC1lTCg.js → exercise.worker-LCHlYekD.js} +11 -11
  33. package/web/assets/exercise-workers/python-exercise.worker-DeTriNjh.js +236 -0
  34. package/web/assets/index-CQjNLnxP.js +540 -0
  35. package/web/assets/index-DpV5il_3.css +1 -0
  36. package/web/assets/{module-ES6BEMUI-Chb6aYUZ.js → module-ES6BEMUI-B2wjplZC.js} +1 -1
  37. package/web/assets/render.worker-OksjuBjV.js +537 -0
  38. package/web/index.html +2 -2
  39. package/dist/chunk-B47HA6IQ.js.map +0 -7
  40. package/dist/chunk-DYXNHODU.js.map +0 -7
  41. package/dist/start-SX3BCBIN.js.map +0 -7
  42. package/web/assets/exercise-workers/python-exercise.worker-CtSr-syJ.js +0 -236
  43. package/web/assets/index-D3M-SX0V.js +0 -538
  44. package/web/assets/index-DUFQVtIh.css +0 -1
  45. package/web/assets/render.worker-D6KYAHiU.js +0 -537
  46. /package/dist/{chunk-KE5ZEREE.js.map → chunk-T5WM74CI.js.map} +0 -0
  47. /package/dist/{client-4UG5W5NJ.js.map → client-76YUHG4T.js.map} +0 -0
package/dist/cli.js CHANGED
@@ -32,14 +32,14 @@ import {
32
32
  VaultImportResult,
33
33
  VaultImportView,
34
34
  normaliseOutput
35
- } from "./chunk-B47HA6IQ.js";
35
+ } from "./chunk-TKDX5OCX.js";
36
36
  import "./chunk-PZ5AY32C.js";
37
37
 
38
38
  // src/cli.ts
39
39
  import { spawn as spawn2 } from "node:child_process";
40
40
  import { createInterface as createInterface2 } from "node:readline";
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";
41
+ import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync3, openSync as openSync2, readFileSync as readFileSync5 } from "node:fs";
42
+ import { join as join9 } from "node:path";
43
43
  import { fileURLToPath } from "node:url";
44
44
 
45
45
  // ../server/src/config.ts
@@ -89,6 +89,10 @@ Commands:
89
89
  check Run your program on the current milestone's cases and record the result in Mivra
90
90
  --timeout <seconds> Time limit for each run (default: 10)
91
91
  --dry-run List exactly what would be sent for review, without running or sending anything
92
+ --approve Approve the commands in .mivra.json for this folder without asking. Check runs only
93
+ commands you approved here: \`mivra link\` approves the ones it writes, and a
94
+ .mivra.json that's new here or changed (from a clone or a pull) needs approving again
95
+ --watch Watch the project folder and re-run check when files change
92
96
  uninstall Stop Mivra and ask whether to delete its data, before you remove the package
93
97
  --delete-data Delete the data without asking
94
98
  --keep-data Keep the data without asking
@@ -130,6 +134,8 @@ function parseCommand(argv) {
130
134
  local: { type: "boolean", default: false },
131
135
  timeout: { type: "string" },
132
136
  "dry-run": { type: "boolean", default: false },
137
+ approve: { type: "boolean", default: false },
138
+ watch: { type: "boolean", default: false },
133
139
  detach: { type: "boolean", default: false },
134
140
  open: { type: "boolean", default: true },
135
141
  check: { type: "boolean", default: true },
@@ -213,7 +219,9 @@ function parseCommand(argv) {
213
219
  timeoutS = Number(values.timeout);
214
220
  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
221
  }
216
- return { name: "check", timeoutS, dryRun: values["dry-run"] };
222
+ if (values.approve && values["dry-run"]) throw new UsageError("Use --approve or --dry-run, not both: a dry run runs nothing.");
223
+ if (values.watch && values["dry-run"]) throw new UsageError("Use --watch or --dry-run, not both: a dry run runs once and runs nothing.");
224
+ return { name: "check", timeoutS, dryRun: values["dry-run"], approve: values.approve, watch: values.watch };
217
225
  }
218
226
  case "uninstall":
219
227
  tooMany(1);
@@ -392,17 +400,63 @@ async function confirm(question, input = process.stdin, output = process.stderr)
392
400
  if (!input.isTTY) output.write("\n");
393
401
  return /^(y|yes)$/i.test(answer.trim());
394
402
  }
403
+ var canAsk = (streams = process) => Boolean(streams.stdin.isTTY && streams.stdout.isTTY && streams.stderr.isTTY);
395
404
 
396
405
  // src/project.ts
397
- import { mkdtempSync, readFileSync as readFileSync2, rmSync as rmSync2, writeFileSync } from "node:fs";
406
+ import { mkdtempSync, readFileSync as readFileSync3, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
398
407
  import { tmpdir } from "node:os";
399
- import { dirname, join as join4, resolve } from "node:path";
408
+ import { dirname, join as join6, resolve } from "node:path";
409
+ import { z as z3 } from "zod";
410
+
411
+ // src/approval.ts
412
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, realpathSync, renameSync as renameSync2, rmSync as rmSync2, writeFileSync } from "node:fs";
413
+ import { join as join3 } from "node:path";
400
414
  import { z as z2 } from "zod";
415
+ var APPROVALS_FILE = "approved-commands.json";
416
+ var Record = z2.object({ course: z2.string(), run: z2.string(), runOutput: z2.string().optional(), approvedAt: z2.string() });
417
+ var File = z2.object({ checkouts: z2.record(z2.string(), Record) });
418
+ var checkoutKey = (dir) => realpathSync(dir);
419
+ function read(dataDir) {
420
+ try {
421
+ const parsed = File.safeParse(JSON.parse(readFileSync2(join3(dataDir, APPROVALS_FILE), "utf8")));
422
+ if (parsed.success) return parsed.data;
423
+ } catch {
424
+ }
425
+ return { checkouts: {} };
426
+ }
427
+ function isApproved(dataDir, dir, wanted) {
428
+ const record = read(dataDir).checkouts[checkoutKey(dir)];
429
+ return record !== void 0 && record.course === wanted.course && record.run === wanted.run && record.runOutput === wanted.runOutput;
430
+ }
431
+ function approve(dataDir, dir, approved) {
432
+ const file = read(dataDir);
433
+ file.checkouts[checkoutKey(dir)] = {
434
+ course: approved.course,
435
+ run: approved.run,
436
+ ...approved.runOutput !== void 0 ? { runOutput: approved.runOutput } : {},
437
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
438
+ };
439
+ mkdirSync2(dataDir, { recursive: true });
440
+ const path = join3(dataDir, APPROVALS_FILE);
441
+ const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
442
+ try {
443
+ writeFileSync(temp, `${JSON.stringify(file, null, 2)}
444
+ `, { mode: 384 });
445
+ renameSync2(temp, path);
446
+ } catch (error) {
447
+ rmSync2(temp, { force: true });
448
+ throw error;
449
+ }
450
+ }
451
+ var shown = (text) => (
452
+ // eslint-disable-next-line no-control-regex
453
+ text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)
454
+ );
401
455
 
402
456
  // src/repo-files.ts
403
457
  import { execFile } from "node:child_process";
404
458
  import { lstat, readFile, realpath } from "node:fs/promises";
405
- import { basename, isAbsolute, join as join3, relative, sep } from "node:path";
459
+ import { basename, isAbsolute, join as join4, relative, sep } from "node:path";
406
460
  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
461
  var SECRET_DIRS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".azure", ".kube", ".docker", "secrets", ".secrets"]);
408
462
  var SECRET_NAMES = /* @__PURE__ */ new Set([
@@ -482,7 +536,7 @@ async function readCandidate(root2, realRoot, path) {
482
536
  if (looksSecret(path)) return { ok: false, reason: "secret" };
483
537
  if (LOCKFILES.has(basename(path).toLowerCase())) return { ok: false, reason: "lockfile" };
484
538
  if (path.length > MAX_REVIEW_PATH_CHARS) return { ok: false, reason: "too_large" };
485
- const full = join3(root2, path);
539
+ const full = join4(root2, path);
486
540
  let info;
487
541
  try {
488
542
  info = await lstat(full);
@@ -522,17 +576,17 @@ async function collectChanges(root2, since) {
522
576
  const skipped = [];
523
577
  let total = 0;
524
578
  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 });
579
+ const read2 = await readCandidate(root2, realRoot, path);
580
+ if (!read2.ok) {
581
+ if (read2.reason !== "gone") skipped.push({ path, reason: read2.reason });
528
582
  continue;
529
583
  }
530
- if (files.length >= MAX_REVIEW_FILES || total + read.content.length > MAX_REVIEW_TOTAL_CHARS) {
584
+ if (files.length >= MAX_REVIEW_FILES || total + read2.content.length > MAX_REVIEW_TOTAL_CHARS) {
531
585
  skipped.push({ path, reason: "size_cap" });
532
586
  continue;
533
587
  }
534
- total += read.content.length;
535
- files.push({ path, content: read.content });
588
+ total += read2.content.length;
589
+ files.push({ path, content: read2.content });
536
590
  }
537
591
  return {
538
592
  source: "git",
@@ -690,14 +744,215 @@ function runProgram(args, { cwd, stdin, limits, env = process.env }) {
690
744
  });
691
745
  }
692
746
 
747
+ // src/watch.ts
748
+ import { lstatSync, readdirSync, watch } from "node:fs";
749
+ import { join as join5, relative as relative2 } from "node:path";
750
+ var IGNORED_DIRS = /* @__PURE__ */ new Set([
751
+ ".git",
752
+ "node_modules",
753
+ "dist",
754
+ "build",
755
+ "target",
756
+ "out",
757
+ ".next",
758
+ ".nuxt",
759
+ ".cache",
760
+ ".turbo",
761
+ "__pycache__",
762
+ ".pytest_cache",
763
+ ".mypy_cache",
764
+ ".venv",
765
+ "venv",
766
+ "coverage"
767
+ ]);
768
+ var MAX_WATCHED_DIRS = 2e3;
769
+ function isIgnoredEntry(name) {
770
+ if (!name) return false;
771
+ if (IGNORED_DIRS.has(name)) return true;
772
+ if (name === ".DS_Store" || name.endsWith("~") || name.endsWith(".swp") || name.endsWith(".swo") || name.endsWith(".tmp")) return true;
773
+ if (name.startsWith("#") && name.endsWith("#")) return true;
774
+ return false;
775
+ }
776
+ function isIgnoredPath(relativePath) {
777
+ if (!relativePath || relativePath === ".") return false;
778
+ return relativePath.split(/[/\\]+/).some((segment) => segment !== "" && isIgnoredEntry(segment));
779
+ }
780
+ function watchDirectory(root2, onChange, { maxDirs = MAX_WATCHED_DIRS, onWarning } = {}) {
781
+ const watchers = /* @__PURE__ */ new Map();
782
+ let closed = false;
783
+ let warnedLimit = false;
784
+ let warnedError = false;
785
+ const warnLimit = () => {
786
+ if (warnedLimit) return;
787
+ warnedLimit = true;
788
+ onWarning?.(`Watch limit reached (${maxDirs} directories); changes in deeper folders may not trigger automatic re-runs.`);
789
+ };
790
+ const warnError = () => {
791
+ if (warnedError) return;
792
+ warnedError = true;
793
+ onWarning?.(`Couldn't watch all directories in ${root2}; some file changes may not trigger automatic re-runs.`);
794
+ };
795
+ const removeDir = (dir) => {
796
+ const existing = watchers.get(dir);
797
+ if (!existing) return;
798
+ watchers.delete(dir);
799
+ try {
800
+ existing.close();
801
+ } catch {
802
+ }
803
+ };
804
+ const addDir = (dir) => {
805
+ if (closed || watchers.has(dir)) return;
806
+ if (watchers.size >= maxDirs) {
807
+ warnLimit();
808
+ return;
809
+ }
810
+ let watcher;
811
+ try {
812
+ watcher = watch(dir, { persistent: true }, (_event, filename) => {
813
+ if (closed) return;
814
+ if (typeof filename === "string" && filename.length > 0) {
815
+ if (isIgnoredEntry(filename)) return;
816
+ const full = join5(dir, filename);
817
+ const rel2 = relative2(root2, full);
818
+ if (isIgnoredPath(rel2)) return;
819
+ try {
820
+ const stat = lstatSync(full);
821
+ if (!stat.isSymbolicLink() && stat.isDirectory()) addTree(full);
822
+ } catch {
823
+ removeDir(full);
824
+ }
825
+ onChange(rel2);
826
+ return;
827
+ }
828
+ const rel = relative2(root2, dir);
829
+ if (!isIgnoredPath(rel)) onChange(rel || ".");
830
+ });
831
+ } catch {
832
+ warnError();
833
+ return;
834
+ }
835
+ watcher.on("error", () => removeDir(dir));
836
+ watchers.set(dir, watcher);
837
+ };
838
+ const addTree = (dir) => {
839
+ if (closed) return;
840
+ if (watchers.size >= maxDirs) {
841
+ warnLimit();
842
+ return;
843
+ }
844
+ addDir(dir);
845
+ let entries;
846
+ try {
847
+ entries = readdirSync(dir, { withFileTypes: true });
848
+ } catch {
849
+ return;
850
+ }
851
+ for (const entry of entries) {
852
+ if (closed) return;
853
+ if (entry.isSymbolicLink() || !entry.isDirectory()) continue;
854
+ if (isIgnoredEntry(entry.name)) continue;
855
+ if (watchers.size >= maxDirs) {
856
+ warnLimit();
857
+ return;
858
+ }
859
+ addTree(join5(dir, entry.name));
860
+ }
861
+ };
862
+ addTree(root2);
863
+ return {
864
+ close() {
865
+ closed = true;
866
+ for (const watcher of watchers.values()) {
867
+ try {
868
+ watcher.close();
869
+ } catch {
870
+ }
871
+ }
872
+ watchers.clear();
873
+ }
874
+ };
875
+ }
876
+ function createWatchScheduler({
877
+ debounceMs,
878
+ run
879
+ }) {
880
+ let running2 = false;
881
+ let pending = false;
882
+ let stopped = false;
883
+ let timer;
884
+ let inFlight;
885
+ const schedule = () => {
886
+ if (stopped) return;
887
+ if (timer !== void 0) clearTimeout(timer);
888
+ timer = setTimeout(() => {
889
+ timer = void 0;
890
+ void execute();
891
+ }, debounceMs);
892
+ };
893
+ const execute = async () => {
894
+ if (stopped || running2) return;
895
+ running2 = true;
896
+ pending = false;
897
+ const current = (async () => {
898
+ try {
899
+ await run();
900
+ } finally {
901
+ running2 = false;
902
+ if (!stopped && pending) {
903
+ pending = false;
904
+ schedule();
905
+ }
906
+ }
907
+ })();
908
+ inFlight = current;
909
+ await current;
910
+ if (inFlight === current) inFlight = void 0;
911
+ };
912
+ return {
913
+ trigger() {
914
+ if (stopped) return;
915
+ if (running2) {
916
+ pending = true;
917
+ return;
918
+ }
919
+ schedule();
920
+ },
921
+ async runNow() {
922
+ if (stopped) return;
923
+ if (timer !== void 0) {
924
+ clearTimeout(timer);
925
+ timer = void 0;
926
+ }
927
+ if (running2) {
928
+ pending = true;
929
+ await inFlight;
930
+ return;
931
+ }
932
+ await execute();
933
+ },
934
+ stop() {
935
+ stopped = true;
936
+ pending = false;
937
+ if (timer !== void 0) {
938
+ clearTimeout(timer);
939
+ timer = void 0;
940
+ }
941
+ },
942
+ async waitForIdle() {
943
+ await inFlight;
944
+ }
945
+ };
946
+ }
947
+
693
948
  // src/project.ts
694
949
  var LINK_FILE = ".mivra.json";
695
- var LinkFile = z2.object({
696
- course: z2.string().min(1),
950
+ var LinkFile = z3.object({
951
+ course: z3.string().min(1),
697
952
  /** The learner's command, e.g. `./build/mycc {input}`. */
698
- run: z2.string().min(1),
953
+ run: z3.string().min(1),
699
954
  /** For cases that run the program's output (e.g. generated assembly): a command with `{output}`. */
700
- runOutput: z2.string().min(1).optional()
955
+ runOutput: z3.string().min(1).optional()
701
956
  });
702
957
  var MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
703
958
  var ProjectError = class extends Error {
@@ -708,19 +963,22 @@ async function server(dataDir) {
708
963
  const local = await running(dataDir);
709
964
  if (!local) throw new ProjectError("Mivra isn't running. Start it with `mivra start --detach`, then try again.");
710
965
  try {
711
- return { url: local.url, token: readFileSync2(join4(dataDir, TOKEN_FILE), "utf8").trim(), remote: false };
966
+ return { url: local.url, token: readFileSync3(join6(dataDir, TOKEN_FILE), "utf8").trim(), remote: false };
712
967
  } catch {
713
- throw new ProjectError(`Couldn't read Mivra's API token from ${join4(dataDir, TOKEN_FILE)}.`);
968
+ throw new ProjectError(`Couldn't read Mivra's API token from ${join6(dataDir, TOKEN_FILE)}.`);
714
969
  }
715
970
  }
716
971
  function client({ url, token, remote }) {
717
972
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
718
973
  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) => {
974
+ return async (path, init = {}, timeoutMs = 3e4, abortSignal) => {
720
975
  let res;
976
+ const timeout = AbortSignal.timeout(timeoutMs);
977
+ const signal = abortSignal ? AbortSignal.any([timeout, abortSignal]) : timeout;
721
978
  try {
722
- res = await fetch(`${url}/api${path}`, { ...init, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
723
- } catch {
979
+ res = await fetch(`${url}/api${path}`, { ...init, headers, redirect: "manual", signal });
980
+ } catch (error) {
981
+ if (abortSignal?.aborted) throw error;
724
982
  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
983
  }
726
984
  if (res.ok) return res.json();
@@ -764,7 +1022,7 @@ async function connectRemote(url, dataDir, readToken, io) {
764
1022
  if (!token.success) throw new ProjectError(input ? token.error.issues[0].message : "No token given.");
765
1023
  await client({ url, token: token.data, remote: true })("/settings/tasks");
766
1024
  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.`);
1025
+ io.out(`Connected to Mivra at ${url}. Its address and token are saved in ${join6(dataDir, CREDENTIALS_FILE)}, not in .mivra.json.`);
768
1026
  const { hostname, protocol } = new URL(url);
769
1027
  if (protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(hostname)) {
770
1028
  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.");
@@ -780,7 +1038,7 @@ function checkCommand(command, where) {
780
1038
  }
781
1039
  function failed(error, io) {
782
1040
  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.");
1041
+ else if (error instanceof z3.ZodError) io.err("Mivra answered with something this `mivra` doesn't understand. Update it to the same version as the running Mivra.");
784
1042
  else throw error;
785
1043
  return 1;
786
1044
  }
@@ -797,11 +1055,12 @@ async function link({ course, run, runOutput, server: url, local }, { dataDir, c
797
1055
  const { call, url: at, remote } = await connect(dataDir);
798
1056
  const found = CourseView.parse(await call(`/courses/${encodeURIComponent(course)}`));
799
1057
  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);
1058
+ const path = join6(cwd, LINK_FILE);
801
1059
  const file = { course: found.id, run, ...runOutput ? { runOutput } : {} };
802
- writeFileSync(path, `${JSON.stringify(file, null, 2)}
1060
+ writeFileSync2(path, `${JSON.stringify(file, null, 2)}
803
1061
  `);
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.`);
1062
+ approve(dataDir, cwd, file);
1063
+ io.out(`Linked this folder to "${found.goal}"${remote ? ` on Mivra at ${at}` : ""} in ${path}. It holds no secrets, so you can commit it: a checkout it's cloned into asks before \`mivra check\` runs its commands.`);
805
1064
  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
1065
  io.out("Run `mivra check` here to check the current milestone.");
807
1066
  return 0;
@@ -812,10 +1071,10 @@ async function link({ course, run, runOutput, server: url, local }, { dataDir, c
812
1071
  function findLink(cwd) {
813
1072
  let dir = resolve(cwd);
814
1073
  for (; ; ) {
815
- const path = join4(dir, LINK_FILE);
1074
+ const path = join6(dir, LINK_FILE);
816
1075
  let text;
817
1076
  try {
818
- text = readFileSync2(path, "utf8");
1077
+ text = readFileSync3(path, "utf8");
819
1078
  } catch {
820
1079
  }
821
1080
  if (text !== void 0) {
@@ -833,6 +1092,21 @@ function findLink(cwd) {
833
1092
  dir = parent;
834
1093
  }
835
1094
  }
1095
+ async function ensureApproved({ path, file }, { dataDir, approveNow, ask }, io) {
1096
+ const root2 = dirname(path);
1097
+ if (isApproved(dataDir, root2, file)) return;
1098
+ if (!approveNow) {
1099
+ io.err(`${path} asks to run commands you haven't approved for this folder (it's new here, or its course or commands changed since you last approved them):`);
1100
+ io.err(` course: ${shown(file.course)}`);
1101
+ io.err(` run: ${shown(file.run)}`);
1102
+ if (file.runOutput !== void 0) io.err(` run-output: ${shown(file.runOutput)}`);
1103
+ io.err(`They'd run from ${root2} with your permissions. Only approve them if you trust them.`);
1104
+ if (!ask) throw new ProjectError("Nothing was run. To approve these commands for this folder, run `mivra check --approve`, or rewrite them with `mivra link`.");
1105
+ if (!await ask("Run them now, and approve them for this folder? [y/N] ")) throw new ProjectError("Nothing was run.");
1106
+ }
1107
+ approve(dataDir, root2, file);
1108
+ io.err(`Approved these commands for ${root2}. Mivra asks again if .mivra.json changes them.`);
1109
+ }
836
1110
  function caseResult(run) {
837
1111
  const stdout = normaliseOutput(run.stdout);
838
1112
  const stderr = run.stderr.slice(-MAX_MILESTONE_STDERR_CHARS);
@@ -845,19 +1119,19 @@ function caseResult(run) {
845
1119
  };
846
1120
  }
847
1121
  async function runCase(link2, testCase, { cwd, limits }) {
848
- const dir = mkdtempSync(join4(tmpdir(), "mivra-check-"));
1122
+ const dir = mkdtempSync(join6(tmpdir(), "mivra-check-"));
849
1123
  try {
850
- const input = join4(dir, "input");
851
- writeFileSync(input, testCase.input);
1124
+ const input = join6(dir, "input");
1125
+ writeFileSync2(input, testCase.input);
852
1126
  const first = await runProgram(fillPlaceholders(splitCommand(link2.run), { input }), { cwd, stdin: testCase.input, limits });
853
1127
  if (testCase.compare !== "run_output" || first.error || first.exitCode !== 0) return { result: caseResult(first), startError: first.startError };
854
1128
  if (!link2.runOutput) return { result: { stdout: "", exitCode: null, error: "no_run_output_command" } };
855
- const output = join4(dir, "output");
856
- writeFileSync(output, first.stdout);
1129
+ const output = join6(dir, "output");
1130
+ writeFileSync2(output, first.stdout);
857
1131
  const second = await runProgram(fillPlaceholders(splitCommand(link2.runOutput), { input, output }), { cwd, stdin: "", limits });
858
1132
  return { result: caseResult(second), startError: second.startError };
859
1133
  } finally {
860
- rmSync2(dir, { recursive: true, force: true });
1134
+ rmSync3(dir, { recursive: true, force: true });
861
1135
  }
862
1136
  }
863
1137
  var ERROR_TEXT = {
@@ -868,8 +1142,8 @@ var ERROR_TEXT = {
868
1142
  };
869
1143
  var excerpt = (text, lines = 8) => {
870
1144
  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");
1145
+ const shown2 = all.slice(0, lines).map((line) => ` ${line}`);
1146
+ return [...shown2, ...all.length > lines ? [` \u2026 (${all.length - lines} more lines)`] : []].join("\n");
873
1147
  };
874
1148
  var CHECK_TIMEOUT_MS = 5 * 6e4;
875
1149
  var kb = (chars) => `${(chars / 1024).toFixed(1)} KB`;
@@ -922,83 +1196,172 @@ function showReview(review, io) {
922
1196
  for (const suggestion of verdict.suggestions) io.out(` - ${suggestion}`);
923
1197
  if (!verdict.approved) io.out(" You can dispute the verdict from the milestone in Mivra.");
924
1198
  }
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
- }
1199
+ var WATCH_DEBOUNCE_MS = 500;
1200
+ async function runSingleCheck(found, { timeoutS, dryRun, dataDir, signal }, io) {
1201
+ const root2 = dirname(found.path);
1202
+ const { call, url, remote } = await connect(dataDir);
1203
+ if (signal?.aborted) return 0;
1204
+ if (remote) io.out(`Checking against Mivra at ${url}; your program runs here.`);
1205
+ const milestone = MilestoneCases.parse(await call(`/courses/${encodeURIComponent(found.file.course)}/milestone`, {}, 3e4, signal));
1206
+ if (signal?.aborted) return 0;
1207
+ const count = milestone.checkType === "review" ? "checked by review" : `${milestone.cases.length} ${milestone.cases.length === 1 ? "case" : "cases"}`;
1208
+ io.out(`Milestone ${milestone.position}: ${milestone.title} (${count})`);
1209
+ const changes = await collectChanges(root2, milestone.since);
1210
+ if (signal?.aborted) return 0;
1211
+ if (dryRun) {
1212
+ 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.`);
1213
+ describeChanges(changes, io, { full: true });
1214
+ io.out("Nothing was run or sent.");
1215
+ return 0;
1216
+ }
1217
+ const limits = { timeoutMs: timeoutS * 1e3, maxOutputBytes: MAX_OUTPUT_BYTES };
1218
+ const results = [];
1219
+ for (const testCase of milestone.cases) {
1220
+ if (signal?.aborted) return 0;
1221
+ const { result, startError } = await runCase(found.file, testCase, { cwd: root2, limits });
1222
+ if (signal?.aborted) return 0;
1223
+ results.push(result);
1224
+ if (startError) {
1225
+ io.err(`Couldn't run your command (${startError}). Check the commands in ${found.path}; they run from ${root2}.`);
1226
+ return 1;
957
1227
  }
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:
1228
+ }
1229
+ describeChanges(changes, io, { full: false });
1230
+ const body = { results, revision: milestone.revision, ...changesToSend(changes) };
1231
+ const graded = MilestoneCheckResult.parse(
1232
+ await call(`/artifacts/${encodeURIComponent(milestone.artifactId)}/checks`, { method: "POST", body: JSON.stringify(body) }, CHECK_TIMEOUT_MS, signal)
1233
+ );
1234
+ if (signal?.aborted) return 0;
1235
+ milestone.cases.forEach((testCase, i) => {
1236
+ const passed2 = graded.grade.cases[i]?.passed ?? false;
1237
+ io.out(` ${passed2 ? "pass" : "FAIL"} ${testCase.name}`);
1238
+ if (passed2) return;
1239
+ const result = results[i];
1240
+ if (result.error) io.out(` ${ERROR_TEXT[result.error]}`);
1241
+ else {
1242
+ if (result.exitCode !== 0) io.out(` exited with code ${result.exitCode}`);
1243
+ io.out(` expected:
972
1244
  ${excerpt(graded.expected[i] ?? "")}`);
973
- io.out(` got:${result.stdout ? `
1245
+ io.out(` got:${result.stdout ? `
974
1246
  ${excerpt(result.stdout)}` : " (nothing)"}${result.truncated ? "\n \u2026 (cut short)" : ""}`);
975
- }
976
- if (result.stderr) io.out(` stderr:
1247
+ }
1248
+ if (result.stderr) io.out(` stderr:
977
1249
  ${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;
1250
+ });
1251
+ const { passed, total } = graded.grade;
1252
+ if (total > 0) io.out(passed === total ? `All ${total} cases passed.` : `${passed} of ${total} cases passed.`);
1253
+ showReview(graded.review, io);
1254
+ io.out(graded.passed ? "Milestone passed. Recorded in Mivra." : "Not passed yet. Recorded in Mivra.");
1255
+ return graded.passed ? 0 : 1;
1256
+ }
1257
+ async function check({ timeoutS, dryRun = false, approve: approveNow = false, watch: watch2 = false }, { dataDir, cwd, ask, watchDebounceMs = WATCH_DEBOUNCE_MS, signal }, io) {
1258
+ if (!watch2) {
1259
+ const onInterrupt = () => {
1260
+ stopCurrent();
1261
+ process.exit(130);
1262
+ };
1263
+ process.once("SIGINT", onInterrupt);
1264
+ try {
1265
+ const found = findLink(cwd);
1266
+ checkCommand(found.file.run, `"run" in ${found.path}`);
1267
+ if (found.file.runOutput) checkCommand(found.file.runOutput, `"runOutput" in ${found.path}`);
1268
+ if (!dryRun) await ensureApproved(found, { dataDir, approveNow, ask }, io);
1269
+ return await runSingleCheck(found, { timeoutS, dryRun, dataDir, signal }, io);
1270
+ } catch (error) {
1271
+ return failed(error, io);
1272
+ } finally {
1273
+ process.removeListener("SIGINT", onInterrupt);
1274
+ }
1275
+ }
1276
+ let initialFound;
1277
+ try {
1278
+ initialFound = findLink(cwd);
1279
+ checkCommand(initialFound.file.run, `"run" in ${initialFound.path}`);
1280
+ if (initialFound.file.runOutput) checkCommand(initialFound.file.runOutput, `"runOutput" in ${initialFound.path}`);
1281
+ await ensureApproved(initialFound, { dataDir, approveNow, ask }, io);
984
1282
  } catch (error) {
985
1283
  return failed(error, io);
1284
+ }
1285
+ const root2 = dirname(initialFound.path);
1286
+ const controller = new AbortController();
1287
+ let watcher;
1288
+ let stopping = false;
1289
+ let finishWatch;
1290
+ const done = new Promise((resolve3) => {
1291
+ finishWatch = resolve3;
1292
+ });
1293
+ let firstRun = true;
1294
+ const scheduler = createWatchScheduler({
1295
+ debounceMs: watchDebounceMs,
1296
+ run: async () => {
1297
+ if (stopping) return;
1298
+ const isInitial = firstRun;
1299
+ firstRun = false;
1300
+ try {
1301
+ let current = initialFound;
1302
+ if (!isInitial) {
1303
+ io.out("\nChanges detected \u2014 re-running check\u2026");
1304
+ current = findLink(root2);
1305
+ if (dirname(current.path) !== root2) {
1306
+ throw new ProjectError(`${initialFound.path} is no longer there. Run \`mivra link\` again.`);
1307
+ }
1308
+ checkCommand(current.file.run, `"run" in ${current.path}`);
1309
+ if (current.file.runOutput) checkCommand(current.file.runOutput, `"runOutput" in ${current.path}`);
1310
+ await ensureApproved(current, { dataDir, approveNow: false }, io);
1311
+ }
1312
+ await runSingleCheck(current, { timeoutS, dryRun: false, dataDir, signal: controller.signal }, io);
1313
+ } catch (error) {
1314
+ if (!stopping && !controller.signal.aborted) failed(error, io);
1315
+ }
1316
+ }
1317
+ });
1318
+ const shutdown = () => {
1319
+ if (stopping) return;
1320
+ stopping = true;
1321
+ scheduler.stop();
1322
+ watcher?.close();
1323
+ watcher = void 0;
1324
+ controller.abort();
1325
+ stopCurrent();
1326
+ finishWatch?.();
1327
+ };
1328
+ process.once("SIGINT", shutdown);
1329
+ process.once("SIGTERM", shutdown);
1330
+ if (signal) {
1331
+ if (signal.aborted) shutdown();
1332
+ else signal.addEventListener("abort", shutdown, { once: true });
1333
+ }
1334
+ try {
1335
+ if (!stopping) {
1336
+ watcher = watchDirectory(root2, () => scheduler.trigger(), { onWarning: (message) => io.err(message) });
1337
+ }
1338
+ await scheduler.runNow();
1339
+ if (!stopping) {
1340
+ io.out(`
1341
+ Watching ${root2} for changes\u2026 Press Ctrl+C to stop.`);
1342
+ await done;
1343
+ }
1344
+ return 0;
986
1345
  } finally {
987
- process.removeListener("SIGINT", onInterrupt);
1346
+ shutdown();
1347
+ await scheduler.waitForIdle();
1348
+ process.removeListener("SIGINT", shutdown);
1349
+ process.removeListener("SIGTERM", shutdown);
1350
+ signal?.removeEventListener("abort", shutdown);
988
1351
  }
989
1352
  }
990
1353
 
991
1354
  // src/uninstall.ts
992
- import { existsSync, readdirSync, rmSync as rmSync3, rmdirSync } from "node:fs";
993
- import { join as join5 } from "node:path";
1355
+ import { existsSync, readdirSync as readdirSync2, rmSync as rmSync4, rmdirSync } from "node:fs";
1356
+ import { join as join7 } from "node:path";
994
1357
  var PACKAGE = "@okhay-p/mivra";
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];
1358
+ var DATA_FILES = ["mivra.db", "mivra.db-wal", "mivra.db-shm", "mivra.db-journal", CREDENTIALS_FILE, CHATGPT_FILE, TOKEN_FILE, STATE_FILE, LOG_FILE, APPROVALS_FILE];
996
1359
  var BACKUPS_DIR = "backups";
997
1360
  var GENERATED_BACKUP = /^mivra-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.db$/;
998
1361
  function mivraFiles(dataDir) {
999
- const files = DATA_FILES.filter((name) => existsSync(join5(dataDir, name)));
1362
+ const files = DATA_FILES.filter((name) => existsSync(join7(dataDir, name)));
1000
1363
  try {
1001
- for (const name of readdirSync(join5(dataDir, BACKUPS_DIR))) if (GENERATED_BACKUP.test(name)) files.push(join5(BACKUPS_DIR, name));
1364
+ for (const name of readdirSync2(join7(dataDir, BACKUPS_DIR))) if (GENERATED_BACKUP.test(name)) files.push(join7(BACKUPS_DIR, name));
1002
1365
  } catch {
1003
1366
  }
1004
1367
  return files;
@@ -1036,14 +1399,14 @@ async function deleteDataIn(dataDir, entries, err2) {
1036
1399
  } catch {
1037
1400
  }
1038
1401
  try {
1039
- for (const name of entries) rmSync3(join5(dataDir, name), { force: true });
1402
+ for (const name of entries) rmSync4(join7(dataDir, name), { force: true });
1040
1403
  } catch (error) {
1041
1404
  err2(`Couldn't delete everything in ${dataDir}: ${error.message}`);
1042
1405
  return false;
1043
1406
  }
1044
- for (const dir of [join5(dataDir, BACKUPS_DIR), dataDir]) {
1407
+ for (const dir of [join7(dataDir, BACKUPS_DIR), dataDir]) {
1045
1408
  try {
1046
- if (readdirSync(dir).length === 0) rmdirSync(dir);
1409
+ if (readdirSync2(dir).length === 0) rmdirSync(dir);
1047
1410
  } catch {
1048
1411
  }
1049
1412
  }
@@ -1051,8 +1414,8 @@ async function deleteDataIn(dataDir, entries, err2) {
1051
1414
  }
1052
1415
 
1053
1416
  // src/vault.ts
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";
1417
+ import { readFileSync as readFileSync4, readdirSync as readdirSync3, statSync } from "node:fs";
1418
+ import { basename as basename2, join as join8, relative as relative3, resolve as resolve2, sep as sep2 } from "node:path";
1056
1419
  var VaultReadError = class extends Error {
1057
1420
  };
1058
1421
  function readVault(root2) {
@@ -1069,13 +1432,13 @@ function readVault(root2) {
1069
1432
  let bytes = 0;
1070
1433
  while (folders.length > 0) {
1071
1434
  const folder = folders.pop();
1072
- for (const entry of readdirSync2(folder, { withFileTypes: true })) {
1435
+ for (const entry of readdirSync3(folder, { withFileTypes: true })) {
1073
1436
  if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
1074
- const full = join6(folder, entry.name);
1437
+ const full = join8(folder, entry.name);
1075
1438
  if (entry.isDirectory()) folders.push(full);
1076
1439
  else if (entry.isFile() && /\.md$/i.test(entry.name)) {
1077
1440
  if (files.length >= MAX_VAULT_FILES) throw new VaultReadError(`The vault has more than ${MAX_VAULT_FILES} notes, more than one import can take.`);
1078
- const path = relative2(root2, full).split(sep2).join("/");
1441
+ const path = relative3(root2, full).split(sep2).join("/");
1079
1442
  const size = statSync(full).size;
1080
1443
  if (size > MAX_NOTE_CHARS * 4) {
1081
1444
  tooLong.push(path);
@@ -1083,7 +1446,7 @@ function readVault(root2) {
1083
1446
  }
1084
1447
  bytes += size;
1085
1448
  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.`);
1086
- const text = readFileSync3(full, "utf8");
1449
+ const text = readFileSync4(full, "utf8");
1087
1450
  if (text.length > MAX_NOTE_CHARS) tooLong.push(path);
1088
1451
  else files.push({ path, text });
1089
1452
  }
@@ -1115,9 +1478,9 @@ async function importObsidian(folder, name, dataDir, io) {
1115
1478
  }
1116
1479
  let token;
1117
1480
  try {
1118
- token = readFileSync3(join6(dataDir, TOKEN_FILE), "utf8").trim();
1481
+ token = readFileSync4(join8(dataDir, TOKEN_FILE), "utf8").trim();
1119
1482
  } catch {
1120
- io.err(`Couldn't read Mivra's API token from ${join6(dataDir, TOKEN_FILE)}.`);
1483
+ io.err(`Couldn't read Mivra's API token from ${join8(dataDir, TOKEN_FILE)}.`);
1121
1484
  return 1;
1122
1485
  }
1123
1486
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
@@ -1156,9 +1519,9 @@ async function importObsidian(folder, name, dataDir, io) {
1156
1519
  // src/cli.ts
1157
1520
  var root = fileURLToPath(new URL("..", import.meta.url));
1158
1521
  var firstExisting = (...paths) => paths.find((p) => existsSync2(p)) ?? paths[0];
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;
1522
+ var webDist = () => firstExisting(join9(root, "web"), join9(root, "../web/dist"));
1523
+ var migrations = () => firstExisting(join9(root, "drizzle"), join9(root, "../server/drizzle"));
1524
+ var version = () => JSON.parse(readFileSync5(join9(root, "package.json"), "utf8")).version;
1162
1525
  var out = (message) => process.stdout.write(`${message}
1163
1526
  `);
1164
1527
  var err = (message) => process.stderr.write(`${message}
@@ -1213,7 +1576,13 @@ ${USAGE}`);
1213
1576
  case "token":
1214
1577
  return printToken(config.dataDir);
1215
1578
  case "check":
1216
- return check(command, { dataDir: config.dataDir, cwd: process.cwd() }, { out, err });
1579
+ return check(
1580
+ command,
1581
+ // Asks only at a terminal, where the question and commands (on stderr) are seen; piped, redirected or in a
1582
+ // script, unapproved commands are refused instead.
1583
+ { dataDir: config.dataDir, cwd: process.cwd(), ...canAsk() ? { ask: (question) => confirm(question) } : {} },
1584
+ { out, err }
1585
+ );
1217
1586
  case "uninstall":
1218
1587
  return uninstall({ dataDir: config.dataDir, deleteData: command.deleteData, stop: () => stop(config.dataDir), confirm, out, err });
1219
1588
  }
@@ -1241,11 +1610,11 @@ async function startForeground(command, base, env) {
1241
1610
  }
1242
1611
  claimed = claim(config.dataDir);
1243
1612
  if (!claimed.ok) {
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.`);
1613
+ err(`Another Mivra (process ${claimed.holder.pid}) holds ${join9(config.dataDir, STATE_FILE)} but doesn't answer. If it isn't running, delete that file.`);
1245
1614
  return 1;
1246
1615
  }
1247
1616
  }
1248
- const [{ PortInUseError, startServer }, { NewerDatabaseError }] = await Promise.all([import("./start-SX3BCBIN.js"), import("./client-4UG5W5NJ.js")]);
1617
+ const [{ PortInUseError, startServer }, { NewerDatabaseError }] = await Promise.all([import("./start-GVAACONX.js"), import("./client-76YUHG4T.js")]);
1249
1618
  let server2;
1250
1619
  try {
1251
1620
  server2 = await startServer({ config, env, webDist: webDist(), migrationsFolder: migrations(), portFallback: true, log: err });
@@ -1292,8 +1661,8 @@ ${error.message}`);
1292
1661
  var DETACH_TIMEOUT_MS = 6e4;
1293
1662
  async function startDetached(command, config, env) {
1294
1663
  if (await alreadyRunning(config.dataDir, command.open)) return 0;
1295
- const logPath = join7(config.dataDir, LOG_FILE);
1296
- mkdirSync2(config.dataDir, { recursive: true });
1664
+ const logPath = join9(config.dataDir, LOG_FILE);
1665
+ mkdirSync3(config.dataDir, { recursive: true });
1297
1666
  const log = openSync2(logPath, "a", 384);
1298
1667
  const args = [...process.execArgv, process.argv[1], "start", "--no-open", ...command.port === void 0 ? [] : ["--port", String(command.port)]];
1299
1668
  const child = spawn2(process.execPath, args, {
@@ -1334,7 +1703,7 @@ ${tail(logPath)}`);
1334
1703
  }
1335
1704
  function tail(path, lines = 20) {
1336
1705
  try {
1337
- return readFileSync4(path, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
1706
+ return readFileSync5(path, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
1338
1707
  } catch {
1339
1708
  return "(no log)";
1340
1709
  }
@@ -1352,7 +1721,7 @@ async function stop(dataDir) {
1352
1721
  return 1;
1353
1722
  }
1354
1723
  if (!await running(dataDir)) {
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")}.`);
1724
+ 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 ${join9(dataDir, "mivra.pid")}.`);
1356
1725
  return 1;
1357
1726
  }
1358
1727
  process.kill(state.pid, "SIGTERM");
@@ -1386,7 +1755,7 @@ async function authSet(provider2, check2, config, env) {
1386
1755
  return 1;
1387
1756
  }
1388
1757
  credentials.set(provider2, key.data);
1389
- out(`Saved the ${PROVIDER_LABELS[provider2]} key to ${join7(config.dataDir, CREDENTIALS_FILE)}. A running Mivra uses it from the next reply.`);
1758
+ out(`Saved the ${PROVIDER_LABELS[provider2]} key to ${join9(config.dataDir, CREDENTIALS_FILE)}. A running Mivra uses it from the next reply.`);
1390
1759
  if (!check2) return 0;
1391
1760
  const baseUrl = provider2 === "anthropic" ? env.ANTHROPIC_BASE_URL : provider2 === "openai" ? env.OPENAI_BASE_URL : void 0;
1392
1761
  const { checkProviderKey } = await import("./key-check-WJ4CVZV5.js");
@@ -1435,7 +1804,7 @@ async function authLogin(newAccount, open, config) {
1435
1804
  err(result.notice ?? "Sign-in didn't finish.");
1436
1805
  return 1;
1437
1806
  }
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.`);
1807
+ out(`Signed in to ChatGPT${result.email ? ` as ${result.email}` : ""}, saved in ${join9(config.dataDir, CHATGPT_FILE)}. A running Mivra uses it from the next reply.`);
1439
1808
  return 0;
1440
1809
  }
1441
1810
  async function authLogout(config) {
@@ -1449,7 +1818,7 @@ async function authLogout(config) {
1449
1818
  return 0;
1450
1819
  }
1451
1820
  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.`);
1821
+ err(`Mivra's token, from ${join9(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
1822
  out(loadOrCreateToken(dataDir));
1454
1823
  return 0;
1455
1824
  }