broader-vids 0.1.0 → 0.1.3

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.
@@ -1,482 +1,482 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
-
4
- const fs = require("node:fs");
5
- const os = require("node:os");
6
- const path = require("node:path");
7
- const { createHash, randomUUID } = require("node:crypto");
8
- const {
9
- withRuntimeUse,
10
- withSetup,
11
- setupInProgress,
12
- } = require("./runtime-lock.cjs");
13
- const { spawnSync } = require("node:child_process");
14
-
15
- function defaultRoot(env = process.env, platform = process.platform) {
16
- const fallback =
17
- platform === "win32"
18
- ? path.join(env.USERPROFILE || os.homedir(), "AppData", "Local")
19
- : path.join(os.homedir(), ".local", "share");
20
- return path.join(env.LOCALAPPDATA || fallback, "broader-vids");
21
- }
22
-
23
- function dataRoot(args, env = process.env, selected) {
24
- let override;
25
- for (let index = 0; index < args.length; index += 1) {
26
- if (args[index] === "--data-dir") override = args[++index];
27
- else if (args[index].startsWith("--data-dir="))
28
- override = args[index].slice("--data-dir=".length);
29
- else continue;
30
- if (!override || override.startsWith("--"))
31
- throw new Error("--data-dir requires a path");
32
- }
33
- return path.resolve(
34
- override || env.BROADER_VIDS_DATA_DIR || selected || defaultRoot(env),
35
- );
36
- }
37
-
38
- function selectionFile(env = process.env) {
39
- return path.join(defaultRoot(env), "launcher.json");
40
- }
41
-
42
- function selectedRoot(env = process.env) {
43
- const file = selectionFile(env);
44
- if (!fs.existsSync(file)) return undefined;
45
- const value = JSON.parse(fs.readFileSync(file, "utf8"));
46
- if (
47
- !value ||
48
- typeof value !== "object" ||
49
- value.version !== 1 ||
50
- typeof value.data_directory !== "string" ||
51
- !path.isAbsolute(value.data_directory)
52
- )
53
- throw new Error(
54
- "Invalid saved data selection; use broader-vids data reset or choose a directory with data use.",
55
- );
56
- return value.data_directory;
57
- }
58
-
59
- function resolvedRoot(args) {
60
- const explicit = args.some(
61
- (value) => value === "--data-dir" || value.startsWith("--data-dir="),
62
- );
63
- return dataRoot(
64
- args,
65
- process.env,
66
- explicit || process.env.BROADER_VIDS_DATA_DIR ? undefined : selectedRoot(),
67
- );
68
- }
69
-
70
- function selectRoot(directory, env = process.env) {
71
- if (!directory || directory.startsWith("--"))
72
- throw new Error("data use requires a directory path.");
73
- if (fs.existsSync(directory) && !fs.statSync(directory).isDirectory())
74
- throw new Error("Choose a directory, not a file.");
75
- const target = selectionFile(env);
76
- const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
77
- fs.mkdirSync(path.dirname(target), { recursive: true });
78
- try {
79
- fs.writeFileSync(
80
- temporary,
81
- JSON.stringify(
82
- { version: 1, data_directory: path.resolve(directory) },
83
- null,
84
- 2,
85
- ),
86
- { flag: "wx", mode: 0o600 },
87
- );
88
- fs.renameSync(temporary, target);
89
- } finally {
90
- if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
91
- }
92
- }
93
-
94
- function commandIndex(args) {
95
- let index = 0;
96
- while (index < args.length) {
97
- if (args[index] === "--data-dir") index += 2;
98
- else if (args[index].startsWith("--data-dir=")) index += 1;
99
- else return index;
100
- }
101
- return -1;
102
- }
103
-
104
- function invoke(command, args) {
105
- const result = spawnSync(command, args, {
106
- stdio: "inherit",
107
- shell: false,
108
- env: { ...process.env, BROADER_VIDS_LAUNCHER: __filename },
109
- });
110
- if (result.error)
111
- throw new Error(
112
- `Could not launch ${path.basename(command)} (${result.error.code || "unknown error"})`,
113
- );
114
- if (result.status !== 0) {
115
- const error = new Error(
116
- `${path.basename(command)} did not complete successfully.`,
117
- );
118
- error.exitCode = result.status ?? (result.signal === "SIGINT" ? 130 : 1);
119
- throw error;
120
- }
121
- }
122
-
123
- function cacheWheel(source, root) {
124
- const content = fs.readFileSync(source);
125
- const digest = createHash("sha256").update(content).digest("hex");
126
- const directory = path.join(root, "wheels", digest);
127
- const destination = path.join(directory, path.basename(source));
128
- fs.mkdirSync(directory, { recursive: true });
129
- if (
130
- !fs.existsSync(destination) ||
131
- !fs.readFileSync(destination).equals(content)
132
- ) {
133
- const temporary = path.join(directory, `.${randomUUID()}.tmp`);
134
- try {
135
- fs.writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
136
- fs.renameSync(temporary, destination);
137
- } finally {
138
- if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
139
- }
140
- }
141
- return destination;
142
- }
143
-
144
- function bundledWheel(packageRoot, version) {
145
- const prefix = `broader_vids-${version.replace("-alpha.", "a")}-`;
146
- const folder = path.join(packageRoot, "python");
147
- const wheels = fs.existsSync(folder)
148
- ? fs
149
- .readdirSync(folder)
150
- .filter((name) => name.startsWith(prefix) && name.endsWith(".whl"))
151
- : [];
152
- if (wheels.length !== 1)
153
- throw new Error(
154
- "The package needs exactly one matching bundled wheel; in a checkout run: uv build --out-dir python",
155
- );
156
- return path.join(folder, wheels[0]);
157
- }
158
-
159
- function wheelDigest(wheel) {
160
- return createHash("sha256").update(fs.readFileSync(wheel)).digest("hex");
161
- }
162
-
163
- function requirementDigests(packageRoot, groups) {
164
- return Object.fromEntries(
165
- groups.map((group) => [
166
- group,
167
- createHash("sha256")
168
- .update(
169
- fs.readFileSync(
170
- path.join(packageRoot, "python", `${group}-requirements.txt`),
171
- ),
172
- )
173
- .digest("hex"),
174
- ]),
175
- );
176
- }
177
-
178
- function validGroups(groups) {
179
- return (
180
- Array.isArray(groups) &&
181
- (JSON.stringify(groups) === JSON.stringify(["core"]) ||
182
- JSON.stringify(groups) === JSON.stringify(["core", "evidence"]) ||
183
- JSON.stringify(groups) === JSON.stringify(["core", "evidence", "asr"]))
184
- );
185
- }
186
-
187
- function runtimeBuildMatches(runtime, digest, packageRoot) {
188
- const file = path.join(runtime, "broader-vids-build.json");
189
- try {
190
- if (fs.statSync(file).size > 4096) return false;
191
- const receipt = JSON.parse(fs.readFileSync(file, "utf8"));
192
- if (
193
- receipt?.version !== 2 ||
194
- receipt.wheel_sha256 !== digest ||
195
- !validGroups(receipt.groups)
196
- )
197
- return false;
198
- const expected = requirementDigests(packageRoot, receipt.groups);
199
- return (
200
- JSON.stringify(receipt.requirements_sha256) === JSON.stringify(expected)
201
- );
202
- } catch {
203
- return false;
204
- }
205
- }
206
-
207
- function recordRuntimeBuild(runtime, digest, packageRoot, groups) {
208
- const target = path.join(runtime, "broader-vids-build.json");
209
- const temporary = path.join(runtime, `.build-${randomUUID()}.tmp`);
210
- try {
211
- fs.writeFileSync(
212
- temporary,
213
- JSON.stringify({
214
- version: 2,
215
- wheel_sha256: digest,
216
- groups,
217
- requirements_sha256: requirementDigests(packageRoot, groups),
218
- }),
219
- { flag: "wx", mode: 0o600 },
220
- );
221
- fs.renameSync(temporary, target);
222
- } finally {
223
- if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
224
- }
225
- }
226
-
227
- function main(args = process.argv.slice(2)) {
228
- const packageRoot = path.resolve(__dirname, "..");
229
- const manifest = JSON.parse(
230
- fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"),
231
- );
232
- const index = commandIndex(args);
233
- if (args[index] === "plugin") {
234
- if (
235
- index === 0 &&
236
- args.length === 2 &&
237
- ["--help", "-h"].includes(args[1])
238
- ) {
239
- console.log("Usage: broader-vids plugin install");
240
- return;
241
- }
242
- if (index !== 0 || args.length !== 2 || args[1] !== "install")
243
- throw new Error(
244
- "Use broader-vids plugin install without profile arguments.",
245
- );
246
- const result = require("./plugin-install.cjs").installPlugin(
247
- manifest.version,
248
- invoke,
249
- );
250
- console.log(JSON.stringify(result, null, 2));
251
- console.log(
252
- "Start a new Codex conversation and invoke the Broader Vids setup skill.",
253
- );
254
- return;
255
- }
256
- if (args[index] === "data") {
257
- const operation = args[index + 1] || "show";
258
- if (operation === "use" && args.length === index + 3)
259
- selectRoot(args[index + 2]);
260
- else if (operation === "reset" && args.length === index + 2) {
261
- const file = selectionFile();
262
- if (fs.existsSync(file)) fs.unlinkSync(file);
263
- } else if (operation !== "show" || args.length > index + 2)
264
- throw new Error("Use data show, data use PATH, or data reset.");
265
- console.log(
266
- JSON.stringify(
267
- { data_directory: resolvedRoot(args), selection_file: selectionFile() },
268
- null,
269
- 2,
270
- ),
271
- );
272
- return;
273
- }
274
- const root = resolvedRoot(args);
275
- const runtime = path.join(root, "runtimes", manifest.version);
276
- const executable =
277
- process.platform === "win32"
278
- ? path.join(runtime, "Scripts", "python.exe")
279
- : path.join(runtime, "bin", "python");
280
- if (["reset", "clean"].includes(args[index])) {
281
- const operation = args[index];
282
- const values = args.slice(index + 1);
283
- if (values.length === 1 && ["--help", "-h"].includes(values[0])) {
284
- console.log(
285
- `Usage: broader-vids [--data-dir PATH] ${operation} [--apply --confirm-path ABSOLUTE_PATH]`,
286
- );
287
- return;
288
- }
289
- let applyChange = false,
290
- confirmation;
291
- for (let item = 0; item < values.length; item += 1) {
292
- if (values[item] === "--apply") applyChange = true;
293
- else if (values[item] === "--confirm-path") confirmation = values[++item];
294
- else if (values[item].startsWith("--confirm-path="))
295
- confirmation = values[item].slice("--confirm-path=".length);
296
- else
297
- throw new Error(
298
- "Use reset or clean with optional --apply --confirm-path ABSOLUTE_PATH.",
299
- );
300
- }
301
- const data = require("./profile-data.cjs");
302
- const result = applyChange
303
- ? data.apply(root, operation, packageRoot, confirmation)
304
- : data.preview(root, operation, packageRoot);
305
- console.log(JSON.stringify(result, null, 2));
306
- if (result.status === "partial") process.exitCode = 2;
307
- return;
308
- }
309
- if (args[commandIndex(args)] === "setup") {
310
- const sourceWheel = bundledWheel(packageRoot, manifest.version);
311
- const wheelRoot = path.dirname(sourceWheel);
312
- return withSetup(root, () => {
313
- require("./profile-data.cjs").ensureMarker(root);
314
- const receipt = path.join(runtime, "broader-vids-build.json");
315
- if (fs.existsSync(receipt)) fs.unlinkSync(receipt);
316
- if (!fs.existsSync(executable))
317
- invoke("uv", [
318
- "venv",
319
- "--allow-existing",
320
- "--python",
321
- ">=3.12",
322
- runtime,
323
- ]);
324
- const wheel = cacheWheel(sourceWheel, root);
325
- invoke("uv", [
326
- "pip",
327
- "install",
328
- "--python",
329
- executable,
330
- "--reinstall",
331
- "--no-index",
332
- "--no-deps",
333
- wheel,
334
- ]);
335
- const extras = args.includes("--asr")
336
- ? ["evidence", "asr"]
337
- : args.includes("--evidence")
338
- ? ["evidence"]
339
- : [];
340
- const groups = ["core", ...extras];
341
- for (const extra of groups) {
342
- invoke("uv", [
343
- "pip",
344
- "install",
345
- "--python",
346
- executable,
347
- "--require-hashes",
348
- "-r",
349
- path.join(wheelRoot, `${extra}-requirements.txt`),
350
- ]);
351
- }
352
- recordRuntimeBuild(runtime, wheelDigest(wheel), packageRoot, groups);
353
- console.log(
354
- JSON.stringify(
355
- {
356
- status: "installed",
357
- runtime,
358
- data_directory: root,
359
- next_action:
360
- "Complete the setup skill and run onboarding complete to verify readiness.",
361
- },
362
- null,
363
- 2,
364
- ),
365
- );
366
- });
367
- }
368
- if (fs.existsSync(path.join(root, ".reset-pending")))
369
- throw new Error(
370
- "A reset is unfinished. Preview reset or clean, then complete that action before using this profile.",
371
- );
372
- if (setupInProgress(root)) {
373
- const error = new Error(
374
- "Runtime installation holds this profile. Wait for setup to finish. Check surviving child processes before repairing a stale installation lock.",
375
- );
376
- error.code = "RUNTIME_BUSY";
377
- throw error;
378
- }
379
- if (!fs.existsSync(executable)) {
380
- if (
381
- ["preflight", "recommend", "onboarding"].includes(
382
- args[commandIndex(args)],
383
- )
384
- ) {
385
- console.log(
386
- JSON.stringify(
387
- {
388
- status: "setup_required",
389
- data_directory: root,
390
- checks: {
391
- runtime: {
392
- status: "missing",
393
- remedy:
394
- "Run the setup skill, or setup --evidence with this same --data-dir.",
395
- },
396
- },
397
- },
398
- null,
399
- 2,
400
- ),
401
- );
402
- process.exitCode = 2;
403
- return;
404
- }
405
- throw new Error(
406
- "Broader Vids runtime is missing; run broader-vids setup --evidence with the same --data-dir first.",
407
- );
408
- }
409
- return withRuntimeUse(root, () => {
410
- const stopDashboard =
411
- args[index] === "dashboard" && args[index + 1] === "stop";
412
- if (
413
- !stopDashboard &&
414
- !runtimeBuildMatches(
415
- runtime,
416
- wheelDigest(bundledWheel(packageRoot, manifest.version)),
417
- packageRoot,
418
- )
419
- ) {
420
- const error = new Error(
421
- "The installed Python engine does not match the bundled build, or its build receipt is missing. Stop the dashboard, then run setup --evidence with this same --data-dir to refresh it. Existing preferences and sign-in stay intact.",
422
- );
423
- error.code = "RUNTIME_BUILD_MISMATCH";
424
- error.data_directory = root;
425
- throw error;
426
- }
427
- return invoke(executable, [
428
- "-m",
429
- "broader_vids",
430
- "--data-dir",
431
- root,
432
- ...args,
433
- ]);
434
- });
435
- }
436
-
437
- module.exports = {
438
- defaultRoot,
439
- dataRoot,
440
- commandIndex,
441
- cacheWheel,
442
- selectedRoot,
443
- selectRoot,
444
- bundledWheel,
445
- wheelDigest,
446
- runtimeBuildMatches,
447
- recordRuntimeBuild,
448
- requirementDigests,
449
- };
450
- if (require.main === module) {
451
- try {
452
- main();
453
- } catch (error) {
454
- if (error.code === "RUNTIME_BUSY")
455
- console.log(
456
- JSON.stringify(
457
- {
458
- status: "blocked",
459
- checks: { runtime: { status: "busy", remedy: error.message } },
460
- },
461
- null,
462
- 2,
463
- ),
464
- );
465
- else if (error.code === "RUNTIME_BUILD_MISMATCH")
466
- console.log(
467
- JSON.stringify(
468
- {
469
- status: "setup_required",
470
- data_directory: error.data_directory,
471
- checks: {
472
- runtime: { status: "unverified", remedy: error.message },
473
- },
474
- },
475
- null,
476
- 2,
477
- ),
478
- );
479
- else console.error(`broader-vids: ${error.message}`);
480
- process.exitCode = error.exitCode || 2;
481
- }
482
- }
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const fs = require("node:fs");
5
+ const os = require("node:os");
6
+ const path = require("node:path");
7
+ const { createHash, randomUUID } = require("node:crypto");
8
+ const {
9
+ withRuntimeUse,
10
+ withSetup,
11
+ setupInProgress,
12
+ } = require("./runtime-lock.cjs");
13
+ const { spawnSync } = require("node:child_process");
14
+
15
+ function defaultRoot(env = process.env, platform = process.platform) {
16
+ const fallback =
17
+ platform === "win32"
18
+ ? path.join(env.USERPROFILE || os.homedir(), "AppData", "Local")
19
+ : path.join(os.homedir(), ".local", "share");
20
+ return path.join(env.LOCALAPPDATA || fallback, "broader-vids");
21
+ }
22
+
23
+ function dataRoot(args, env = process.env, selected) {
24
+ let override;
25
+ for (let index = 0; index < args.length; index += 1) {
26
+ if (args[index] === "--data-dir") override = args[++index];
27
+ else if (args[index].startsWith("--data-dir="))
28
+ override = args[index].slice("--data-dir=".length);
29
+ else continue;
30
+ if (!override || override.startsWith("--"))
31
+ throw new Error("--data-dir requires a path");
32
+ }
33
+ return path.resolve(
34
+ override || env.BROADER_VIDS_DATA_DIR || selected || defaultRoot(env),
35
+ );
36
+ }
37
+
38
+ function selectionFile(env = process.env) {
39
+ return path.join(defaultRoot(env), "launcher.json");
40
+ }
41
+
42
+ function selectedRoot(env = process.env) {
43
+ const file = selectionFile(env);
44
+ if (!fs.existsSync(file)) return undefined;
45
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
46
+ if (
47
+ !value ||
48
+ typeof value !== "object" ||
49
+ value.version !== 1 ||
50
+ typeof value.data_directory !== "string" ||
51
+ !path.isAbsolute(value.data_directory)
52
+ )
53
+ throw new Error(
54
+ "Invalid saved data selection; use broader-vids data reset or choose a directory with data use.",
55
+ );
56
+ return value.data_directory;
57
+ }
58
+
59
+ function resolvedRoot(args) {
60
+ const explicit = args.some(
61
+ (value) => value === "--data-dir" || value.startsWith("--data-dir="),
62
+ );
63
+ return dataRoot(
64
+ args,
65
+ process.env,
66
+ explicit || process.env.BROADER_VIDS_DATA_DIR ? undefined : selectedRoot(),
67
+ );
68
+ }
69
+
70
+ function selectRoot(directory, env = process.env) {
71
+ if (!directory || directory.startsWith("--"))
72
+ throw new Error("data use requires a directory path.");
73
+ if (fs.existsSync(directory) && !fs.statSync(directory).isDirectory())
74
+ throw new Error("Choose a directory, not a file.");
75
+ const target = selectionFile(env);
76
+ const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
77
+ fs.mkdirSync(path.dirname(target), { recursive: true });
78
+ try {
79
+ fs.writeFileSync(
80
+ temporary,
81
+ JSON.stringify(
82
+ { version: 1, data_directory: path.resolve(directory) },
83
+ null,
84
+ 2,
85
+ ),
86
+ { flag: "wx", mode: 0o600 },
87
+ );
88
+ fs.renameSync(temporary, target);
89
+ } finally {
90
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
91
+ }
92
+ }
93
+
94
+ function commandIndex(args) {
95
+ let index = 0;
96
+ while (index < args.length) {
97
+ if (args[index] === "--data-dir") index += 2;
98
+ else if (args[index].startsWith("--data-dir=")) index += 1;
99
+ else return index;
100
+ }
101
+ return -1;
102
+ }
103
+
104
+ function invoke(command, args) {
105
+ const result = spawnSync(command, args, {
106
+ stdio: "inherit",
107
+ shell: false,
108
+ env: { ...process.env, BROADER_VIDS_LAUNCHER: __filename },
109
+ });
110
+ if (result.error)
111
+ throw new Error(
112
+ `Could not launch ${path.basename(command)} (${result.error.code || "unknown error"})`,
113
+ );
114
+ if (result.status !== 0) {
115
+ const error = new Error(
116
+ `${path.basename(command)} did not complete successfully.`,
117
+ );
118
+ error.exitCode = result.status ?? (result.signal === "SIGINT" ? 130 : 1);
119
+ throw error;
120
+ }
121
+ }
122
+
123
+ function cacheWheel(source, root) {
124
+ const content = fs.readFileSync(source);
125
+ const digest = createHash("sha256").update(content).digest("hex");
126
+ const directory = path.join(root, "wheels", digest);
127
+ const destination = path.join(directory, path.basename(source));
128
+ fs.mkdirSync(directory, { recursive: true });
129
+ if (
130
+ !fs.existsSync(destination) ||
131
+ !fs.readFileSync(destination).equals(content)
132
+ ) {
133
+ const temporary = path.join(directory, `.${randomUUID()}.tmp`);
134
+ try {
135
+ fs.writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
136
+ fs.renameSync(temporary, destination);
137
+ } finally {
138
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
139
+ }
140
+ }
141
+ return destination;
142
+ }
143
+
144
+ function bundledWheel(packageRoot, version) {
145
+ const prefix = `broader_vids-${version.replace("-alpha.", "a")}-`;
146
+ const folder = path.join(packageRoot, "python");
147
+ const wheels = fs.existsSync(folder)
148
+ ? fs
149
+ .readdirSync(folder)
150
+ .filter((name) => name.startsWith(prefix) && name.endsWith(".whl"))
151
+ : [];
152
+ if (wheels.length !== 1)
153
+ throw new Error(
154
+ "The package needs exactly one matching bundled wheel; in a checkout run: uv build --out-dir python",
155
+ );
156
+ return path.join(folder, wheels[0]);
157
+ }
158
+
159
+ function wheelDigest(wheel) {
160
+ return createHash("sha256").update(fs.readFileSync(wheel)).digest("hex");
161
+ }
162
+
163
+ function requirementDigests(packageRoot, groups) {
164
+ return Object.fromEntries(
165
+ groups.map((group) => [
166
+ group,
167
+ createHash("sha256")
168
+ .update(
169
+ fs.readFileSync(
170
+ path.join(packageRoot, "python", `${group}-requirements.txt`),
171
+ ),
172
+ )
173
+ .digest("hex"),
174
+ ]),
175
+ );
176
+ }
177
+
178
+ function validGroups(groups) {
179
+ return (
180
+ Array.isArray(groups) &&
181
+ (JSON.stringify(groups) === JSON.stringify(["core"]) ||
182
+ JSON.stringify(groups) === JSON.stringify(["core", "evidence"]) ||
183
+ JSON.stringify(groups) === JSON.stringify(["core", "evidence", "asr"]))
184
+ );
185
+ }
186
+
187
+ function runtimeBuildMatches(runtime, digest, packageRoot) {
188
+ const file = path.join(runtime, "broader-vids-build.json");
189
+ try {
190
+ if (fs.statSync(file).size > 4096) return false;
191
+ const receipt = JSON.parse(fs.readFileSync(file, "utf8"));
192
+ if (
193
+ receipt?.version !== 2 ||
194
+ receipt.wheel_sha256 !== digest ||
195
+ !validGroups(receipt.groups)
196
+ )
197
+ return false;
198
+ const expected = requirementDigests(packageRoot, receipt.groups);
199
+ return (
200
+ JSON.stringify(receipt.requirements_sha256) === JSON.stringify(expected)
201
+ );
202
+ } catch {
203
+ return false;
204
+ }
205
+ }
206
+
207
+ function recordRuntimeBuild(runtime, digest, packageRoot, groups) {
208
+ const target = path.join(runtime, "broader-vids-build.json");
209
+ const temporary = path.join(runtime, `.build-${randomUUID()}.tmp`);
210
+ try {
211
+ fs.writeFileSync(
212
+ temporary,
213
+ JSON.stringify({
214
+ version: 2,
215
+ wheel_sha256: digest,
216
+ groups,
217
+ requirements_sha256: requirementDigests(packageRoot, groups),
218
+ }),
219
+ { flag: "wx", mode: 0o600 },
220
+ );
221
+ fs.renameSync(temporary, target);
222
+ } finally {
223
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
224
+ }
225
+ }
226
+
227
+ function main(args = process.argv.slice(2)) {
228
+ const packageRoot = path.resolve(__dirname, "..");
229
+ const manifest = JSON.parse(
230
+ fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"),
231
+ );
232
+ const index = commandIndex(args);
233
+ if (args[index] === "plugin") {
234
+ if (
235
+ index === 0 &&
236
+ args.length === 2 &&
237
+ ["--help", "-h"].includes(args[1])
238
+ ) {
239
+ console.log("Usage: broader-vids plugin install");
240
+ return;
241
+ }
242
+ if (index !== 0 || args.length !== 2 || args[1] !== "install")
243
+ throw new Error(
244
+ "Use broader-vids plugin install without profile arguments.",
245
+ );
246
+ const result = require("./plugin-install.cjs").installPlugin(
247
+ manifest.version,
248
+ invoke,
249
+ );
250
+ console.log(JSON.stringify(result, null, 2));
251
+ console.log(
252
+ "Start a new Codex conversation and invoke the Broader Vids setup skill.",
253
+ );
254
+ return;
255
+ }
256
+ if (args[index] === "data") {
257
+ const operation = args[index + 1] || "show";
258
+ if (operation === "use" && args.length === index + 3)
259
+ selectRoot(args[index + 2]);
260
+ else if (operation === "reset" && args.length === index + 2) {
261
+ const file = selectionFile();
262
+ if (fs.existsSync(file)) fs.unlinkSync(file);
263
+ } else if (operation !== "show" || args.length > index + 2)
264
+ throw new Error("Use data show, data use PATH, or data reset.");
265
+ console.log(
266
+ JSON.stringify(
267
+ { data_directory: resolvedRoot(args), selection_file: selectionFile() },
268
+ null,
269
+ 2,
270
+ ),
271
+ );
272
+ return;
273
+ }
274
+ const root = resolvedRoot(args);
275
+ const runtime = path.join(root, "runtimes", manifest.version);
276
+ const executable =
277
+ process.platform === "win32"
278
+ ? path.join(runtime, "Scripts", "python.exe")
279
+ : path.join(runtime, "bin", "python");
280
+ if (["reset", "clean"].includes(args[index])) {
281
+ const operation = args[index];
282
+ const values = args.slice(index + 1);
283
+ if (values.length === 1 && ["--help", "-h"].includes(values[0])) {
284
+ console.log(
285
+ `Usage: broader-vids [--data-dir PATH] ${operation} [--apply --confirm-path ABSOLUTE_PATH]`,
286
+ );
287
+ return;
288
+ }
289
+ let applyChange = false,
290
+ confirmation;
291
+ for (let item = 0; item < values.length; item += 1) {
292
+ if (values[item] === "--apply") applyChange = true;
293
+ else if (values[item] === "--confirm-path") confirmation = values[++item];
294
+ else if (values[item].startsWith("--confirm-path="))
295
+ confirmation = values[item].slice("--confirm-path=".length);
296
+ else
297
+ throw new Error(
298
+ "Use reset or clean with optional --apply --confirm-path ABSOLUTE_PATH.",
299
+ );
300
+ }
301
+ const data = require("./profile-data.cjs");
302
+ const result = applyChange
303
+ ? data.apply(root, operation, packageRoot, confirmation)
304
+ : data.preview(root, operation, packageRoot);
305
+ console.log(JSON.stringify(result, null, 2));
306
+ if (result.status === "partial") process.exitCode = 2;
307
+ return;
308
+ }
309
+ if (args[commandIndex(args)] === "setup") {
310
+ const sourceWheel = bundledWheel(packageRoot, manifest.version);
311
+ const wheelRoot = path.dirname(sourceWheel);
312
+ return withSetup(root, () => {
313
+ require("./profile-data.cjs").ensureMarker(root);
314
+ const receipt = path.join(runtime, "broader-vids-build.json");
315
+ if (fs.existsSync(receipt)) fs.unlinkSync(receipt);
316
+ if (!fs.existsSync(executable))
317
+ invoke("uv", [
318
+ "venv",
319
+ "--allow-existing",
320
+ "--python",
321
+ ">=3.12",
322
+ runtime,
323
+ ]);
324
+ const wheel = cacheWheel(sourceWheel, root);
325
+ invoke("uv", [
326
+ "pip",
327
+ "install",
328
+ "--python",
329
+ executable,
330
+ "--reinstall",
331
+ "--no-index",
332
+ "--no-deps",
333
+ wheel,
334
+ ]);
335
+ const extras = args.includes("--asr")
336
+ ? ["evidence", "asr"]
337
+ : args.includes("--evidence")
338
+ ? ["evidence"]
339
+ : [];
340
+ const groups = ["core", ...extras];
341
+ for (const extra of groups) {
342
+ invoke("uv", [
343
+ "pip",
344
+ "install",
345
+ "--python",
346
+ executable,
347
+ "--require-hashes",
348
+ "-r",
349
+ path.join(wheelRoot, `${extra}-requirements.txt`),
350
+ ]);
351
+ }
352
+ recordRuntimeBuild(runtime, wheelDigest(wheel), packageRoot, groups);
353
+ console.log(
354
+ JSON.stringify(
355
+ {
356
+ status: "installed",
357
+ runtime,
358
+ data_directory: root,
359
+ next_action:
360
+ "Complete the setup skill and run onboarding complete to verify readiness.",
361
+ },
362
+ null,
363
+ 2,
364
+ ),
365
+ );
366
+ });
367
+ }
368
+ if (fs.existsSync(path.join(root, ".reset-pending")))
369
+ throw new Error(
370
+ "A reset is unfinished. Preview reset or clean, then complete that action before using this profile.",
371
+ );
372
+ if (setupInProgress(root)) {
373
+ const error = new Error(
374
+ "Runtime installation holds this profile. Wait for setup to finish. Check surviving child processes before repairing a stale installation lock.",
375
+ );
376
+ error.code = "RUNTIME_BUSY";
377
+ throw error;
378
+ }
379
+ if (!fs.existsSync(executable)) {
380
+ if (
381
+ ["preflight", "recommend", "onboarding"].includes(
382
+ args[commandIndex(args)],
383
+ )
384
+ ) {
385
+ console.log(
386
+ JSON.stringify(
387
+ {
388
+ status: "setup_required",
389
+ data_directory: root,
390
+ checks: {
391
+ runtime: {
392
+ status: "missing",
393
+ remedy:
394
+ "Run the setup skill, or setup --evidence with this same --data-dir.",
395
+ },
396
+ },
397
+ },
398
+ null,
399
+ 2,
400
+ ),
401
+ );
402
+ process.exitCode = 2;
403
+ return;
404
+ }
405
+ throw new Error(
406
+ "Broader Vids runtime is missing; run broader-vids setup --evidence with the same --data-dir first.",
407
+ );
408
+ }
409
+ return withRuntimeUse(root, () => {
410
+ const stopDashboard =
411
+ args[index] === "dashboard" && args[index + 1] === "stop";
412
+ if (
413
+ !stopDashboard &&
414
+ !runtimeBuildMatches(
415
+ runtime,
416
+ wheelDigest(bundledWheel(packageRoot, manifest.version)),
417
+ packageRoot,
418
+ )
419
+ ) {
420
+ const error = new Error(
421
+ "The installed Python engine does not match the bundled build, or its build receipt is missing. Stop the dashboard, then run setup --evidence with this same --data-dir to refresh it. Existing preferences and sign-in stay intact.",
422
+ );
423
+ error.code = "RUNTIME_BUILD_MISMATCH";
424
+ error.data_directory = root;
425
+ throw error;
426
+ }
427
+ return invoke(executable, [
428
+ "-m",
429
+ "broader_vids",
430
+ "--data-dir",
431
+ root,
432
+ ...args,
433
+ ]);
434
+ });
435
+ }
436
+
437
+ module.exports = {
438
+ defaultRoot,
439
+ dataRoot,
440
+ commandIndex,
441
+ cacheWheel,
442
+ selectedRoot,
443
+ selectRoot,
444
+ bundledWheel,
445
+ wheelDigest,
446
+ runtimeBuildMatches,
447
+ recordRuntimeBuild,
448
+ requirementDigests,
449
+ };
450
+ if (require.main === module) {
451
+ try {
452
+ main();
453
+ } catch (error) {
454
+ if (error.code === "RUNTIME_BUSY")
455
+ console.log(
456
+ JSON.stringify(
457
+ {
458
+ status: "blocked",
459
+ checks: { runtime: { status: "busy", remedy: error.message } },
460
+ },
461
+ null,
462
+ 2,
463
+ ),
464
+ );
465
+ else if (error.code === "RUNTIME_BUILD_MISMATCH")
466
+ console.log(
467
+ JSON.stringify(
468
+ {
469
+ status: "setup_required",
470
+ data_directory: error.data_directory,
471
+ checks: {
472
+ runtime: { status: "unverified", remedy: error.message },
473
+ },
474
+ },
475
+ null,
476
+ 2,
477
+ ),
478
+ );
479
+ else console.error(`broader-vids: ${error.message}`);
480
+ process.exitCode = error.exitCode || 2;
481
+ }
482
+ }