@tobos/cli 0.4.18 → 0.4.20

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.
package/dist/cli.js ADDED
@@ -0,0 +1,1343 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __tobosRequire } from 'node:module';
3
+ const require = __tobosRequire(import.meta.url);
4
+ import {
5
+ formatMediaJson,
6
+ formatProblems,
7
+ mediaTypeOf
8
+ } from "./chunk-L3I6AVL4.js";
9
+ import {
10
+ ASK_THE_PERSON,
11
+ CliError,
12
+ EXIT,
13
+ createOutput,
14
+ offerUpdate,
15
+ update
16
+ } from "./chunk-4CLH25WE.js";
17
+ import {
18
+ define_TOBOS_SKILL_default,
19
+ init_define_TOBOS_PRESENT_TYPES,
20
+ init_define_TOBOS_SKILL,
21
+ init_define_TOBOS_TOOLCHAIN
22
+ } from "./chunk-O52ON2LV.js";
23
+
24
+ // src/main.ts
25
+ init_define_TOBOS_PRESENT_TYPES();
26
+ init_define_TOBOS_SKILL();
27
+ init_define_TOBOS_TOOLCHAIN();
28
+ import { parseArgs } from "node:util";
29
+
30
+ // src/api.ts
31
+ init_define_TOBOS_PRESENT_TYPES();
32
+ init_define_TOBOS_SKILL();
33
+ init_define_TOBOS_TOOLCHAIN();
34
+
35
+ // src/config.ts
36
+ init_define_TOBOS_PRESENT_TYPES();
37
+ init_define_TOBOS_SKILL();
38
+ init_define_TOBOS_TOOLCHAIN();
39
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
40
+ import { homedir } from "node:os";
41
+ import { join } from "node:path";
42
+ var DEFAULT_SERVER = "https://app.tobos.ai";
43
+ var dir = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "tobos");
44
+ var file = join(dir, "config.json");
45
+ function read() {
46
+ let text;
47
+ try {
48
+ text = readFileSync(file, "utf8");
49
+ } catch (error) {
50
+ const { code } = error;
51
+ if (code === "ENOENT") return {};
52
+ throw new CliError(`Can't read ${file} (${code}): fix or remove it, then log in again.`);
53
+ }
54
+ let stored;
55
+ try {
56
+ stored = JSON.parse(text);
57
+ } catch {
58
+ }
59
+ if (typeof stored === "object" && stored !== null && !Array.isArray(stored)) return stored;
60
+ process.stderr.write(`${file} isn't a JSON object: \`tobos login\` writes it afresh.
61
+ `);
62
+ return {};
63
+ }
64
+ function write(stored) {
65
+ mkdirSync(dir, { recursive: true, mode: 448 });
66
+ const next = `${file}.${process.pid}`;
67
+ writeFileSync(next, JSON.stringify(stored, null, 2) + "\n", { mode: 384 });
68
+ renameSync(next, file);
69
+ }
70
+ function save(update2) {
71
+ write({ ...read(), ...update2 });
72
+ }
73
+ function forget() {
74
+ write({ server: read().server });
75
+ }
76
+ function settings() {
77
+ let stored = {};
78
+ try {
79
+ stored = read();
80
+ } catch (error) {
81
+ if (!process.env.TOBOS_SERVER || !process.env.TOBOS_TOKEN) throw error;
82
+ }
83
+ return {
84
+ server: (process.env.TOBOS_SERVER || stored.server || DEFAULT_SERVER).replace(/\/$/, ""),
85
+ token: process.env.TOBOS_TOKEN || stored.token,
86
+ email: stored.email,
87
+ pending: stored.pending
88
+ };
89
+ }
90
+
91
+ // src/api.ts
92
+ var VERSION = true ? "0.4.20" : "dev";
93
+ function newer(a, b) {
94
+ const parse = (v) => /^\d+\.\d+\.\d+/.test(v) ? v.split(".").map((n) => parseInt(n)) : null;
95
+ const x = parse(a);
96
+ const y = parse(b);
97
+ if (!x || !y) return false;
98
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
99
+ return false;
100
+ }
101
+ async function api(path, options = {}) {
102
+ const response = await request(path, options);
103
+ const text = await response.text();
104
+ let data;
105
+ try {
106
+ data = text ? JSON.parse(text) : {};
107
+ } catch {
108
+ data = { error: text.slice(0, 500) };
109
+ }
110
+ if (!response.ok) throw failure(response, data);
111
+ return data;
112
+ }
113
+ function failure(response, data, prefix = "") {
114
+ const { error, message, ...extra } = data;
115
+ const said = prefix + (error ?? message ?? `${response.status} ${response.statusText}`);
116
+ const limit = response.status === 402 || response.status === 423;
117
+ return new CliError(
118
+ limit ? `${said}
119
+ ${ASK_THE_PERSON}` : said,
120
+ response.status === 401 ? EXIT.auth : limit ? EXIT.limit : EXIT.error,
121
+ { ...extra, status: response.status }
122
+ );
123
+ }
124
+ async function request(path, options = {}) {
125
+ const { server, token } = settings();
126
+ const target = options.server ?? server;
127
+ const headers = {
128
+ "user-agent": `tobos/${VERSION}`,
129
+ accept: "application/json"
130
+ };
131
+ headers.origin = target;
132
+ if (!options.anonymous) {
133
+ if (!token)
134
+ throw new CliError(
135
+ "Not logged in. Ask the person you work for for their e-mail address, then run `tobos login <email>`.",
136
+ EXIT.auth
137
+ );
138
+ if (new URL(target).origin !== new URL(server).origin)
139
+ throw new CliError(
140
+ `This deck is on ${target}, but you are logged in to ${server}, and the token goes only there. Log in to the deck's server with \`tobos login <email> --server ${target}\`.`,
141
+ EXIT.auth
142
+ );
143
+ headers.authorization = `Bearer ${token}`;
144
+ }
145
+ let body;
146
+ if (options.body instanceof Uint8Array || options.body instanceof ReadableStream) {
147
+ body = options.body;
148
+ if (options.contentType) headers["content-type"] = options.contentType;
149
+ } else if (options.body !== void 0) {
150
+ headers["content-type"] = "application/json";
151
+ body = JSON.stringify(options.body);
152
+ }
153
+ const url = `${target}${path}`;
154
+ let response;
155
+ try {
156
+ response = await fetch(url, {
157
+ method: options.method ?? (body ? "POST" : "GET"),
158
+ headers,
159
+ body,
160
+ duplex: "half"
161
+ });
162
+ } catch (error) {
163
+ throw new CliError(
164
+ `Can't reach ${target}: ${error.cause ?? error.message}`
165
+ );
166
+ }
167
+ const latest = response.headers.get("tobos-latest-cli");
168
+ if (latest && newer(latest, VERSION))
169
+ offerUpdate(`tobos ${latest} is out (you have ${VERSION}): npm i -g @tobos/cli`);
170
+ return response;
171
+ }
172
+
173
+ // src/commands.ts
174
+ init_define_TOBOS_PRESENT_TYPES();
175
+ init_define_TOBOS_SKILL();
176
+ init_define_TOBOS_TOOLCHAIN();
177
+ import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "node:fs";
178
+ import { hostname } from "node:os";
179
+ import { dirname as dirname3, join as join7, relative as relative2, resolve as resolve2 } from "node:path";
180
+
181
+ // ../deck/src/node.ts
182
+ init_define_TOBOS_PRESENT_TYPES();
183
+ init_define_TOBOS_SKILL();
184
+ init_define_TOBOS_TOOLCHAIN();
185
+ import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
186
+ import { join as join2 } from "node:path";
187
+ var SKIP = /* @__PURE__ */ new Set([".git", "node_modules", "media", "sources", ".tobos"]);
188
+ function directoryTree(root, only) {
189
+ const allowed = only === void 0 ? void 0 : new Set(only);
190
+ const files = [];
191
+ const visit = (dir2, prefix) => {
192
+ for (const entry of readdirSync(dir2, { withFileTypes: true })) {
193
+ if (prefix === "" && SKIP.has(entry.name)) continue;
194
+ if (entry.name === ".DS_Store" || entry.name === "node_modules") continue;
195
+ const path = prefix + entry.name;
196
+ if (entry.isDirectory()) visit(join2(dir2, entry.name), path + "/");
197
+ else if (entry.isFile() && (allowed?.has(path) ?? true)) files.push(path);
198
+ }
199
+ };
200
+ visit(root, "");
201
+ files.sort();
202
+ const listed = new Set(files);
203
+ return {
204
+ files: () => files,
205
+ // Only what was listed: no path can reach outside the folder.
206
+ read: (path) => {
207
+ if (!listed.has(path)) return void 0;
208
+ try {
209
+ return new Uint8Array(readFileSync2(join2(root, path)));
210
+ } catch (error) {
211
+ throw new Error(`${path} can't be read: ${error.message}`);
212
+ }
213
+ }
214
+ };
215
+ }
216
+
217
+ // src/deck-dir.ts
218
+ init_define_TOBOS_PRESENT_TYPES();
219
+ init_define_TOBOS_SKILL();
220
+ init_define_TOBOS_TOOLCHAIN();
221
+ import { existsSync } from "node:fs";
222
+ import { dirname, join as join3, resolve } from "node:path";
223
+
224
+ // src/git.ts
225
+ init_define_TOBOS_PRESENT_TYPES();
226
+ init_define_TOBOS_SKILL();
227
+ init_define_TOBOS_TOOLCHAIN();
228
+ import { spawn } from "node:child_process";
229
+ import { realpathSync } from "node:fs";
230
+ function git(args, options = {}) {
231
+ return new Promise((resolve3, reject) => {
232
+ const child = spawn("git", args, {
233
+ cwd: options.cwd,
234
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...options.env }
235
+ });
236
+ let stdout = "";
237
+ let stderr = "";
238
+ child.stdout.setEncoding("utf8");
239
+ child.stderr.setEncoding("utf8");
240
+ child.stdout.on("data", (d) => stdout += d);
241
+ child.stderr.on("data", (d) => {
242
+ stderr += d;
243
+ if (options.echo) process.stderr.write(d);
244
+ });
245
+ child.on(
246
+ "error",
247
+ (error) => reject(
248
+ error.code === "ENOENT" ? new CliError("git is not installed. Tobos keeps every deck in git; install it first.") : error
249
+ )
250
+ );
251
+ child.on("close", (code) => resolve3({ code: code ?? 1, stdout, stderr }));
252
+ });
253
+ }
254
+ async function gitOk(args, options = {}) {
255
+ const result = await git(args, options);
256
+ if (result.code !== 0) throw new CliError(`git ${args[0]} failed:
257
+ ${result.stderr.trim()}`);
258
+ return result.stdout;
259
+ }
260
+ function credentialHelper() {
261
+ const script = realpathSync(process.argv[1]);
262
+ const quote = (s) => `'${s.replace(/'/g, "'\\''")}'`;
263
+ return `!f() { [ "$1" = get ] || exit 0; exec ${quote(process.execPath)} ${quote(script)} credential get; }; f`;
264
+ }
265
+ function credentialConfig(server) {
266
+ return [
267
+ "-c",
268
+ `credential.${server}.helper=`,
269
+ "-c",
270
+ `credential.${server}.helper=${credentialHelper()}`
271
+ ];
272
+ }
273
+ function authEnv(server) {
274
+ const { server: ours, token } = settings();
275
+ if (!token || new URL(ours).origin !== new URL(server).origin) return {};
276
+ const n = Number(process.env.GIT_CONFIG_COUNT) || 0;
277
+ return {
278
+ GIT_CONFIG_COUNT: String(n + 1),
279
+ [`GIT_CONFIG_KEY_${n}`]: `http.${server}.extraHeader`,
280
+ [`GIT_CONFIG_VALUE_${n}`]: `Authorization: Basic ${Buffer.from(`tobos:${token}`).toString("base64")}`
281
+ };
282
+ }
283
+ async function refreshCredentials(dir2, server) {
284
+ const configured = await git(["config", "--local", "--get-all", `credential.${server}.helper`], {
285
+ cwd: dir2
286
+ });
287
+ if (configured.code !== 0) return;
288
+ if (configured.stdout === `
289
+ ${credentialHelper()}
290
+ `) return;
291
+ await configureCredentials(dir2, server);
292
+ }
293
+ async function configureCredentials(dir2, server) {
294
+ await gitOk(["config", "--replace-all", `credential.${server}.helper`, ""], { cwd: dir2 });
295
+ await gitOk(["config", "--add", `credential.${server}.helper`, credentialHelper()], { cwd: dir2 });
296
+ }
297
+
298
+ // src/deck-dir.ts
299
+ var ID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
300
+ var REMOTE = new RegExp(`^(https?://[^/]+)/git/(${ID})\\.git$`);
301
+ async function findDeck(start = process.cwd()) {
302
+ let dir2 = resolve(start);
303
+ while (!existsSync(join3(dir2, "deck.json"))) {
304
+ const up = dirname(dir2);
305
+ if (up === dir2)
306
+ throw new CliError("Not in a deck: no deck.json here or above. `tobos clone` one first.");
307
+ dir2 = up;
308
+ }
309
+ const remote = await git(["remote", "get-url", "origin"], { cwd: dir2 }).catch(() => void 0);
310
+ const match = remote && remote.code === 0 ? REMOTE.exec(remote.stdout.trim()) : null;
311
+ if (!match) return { root: dir2 };
312
+ await refreshCredentials(dir2, match[1]).catch(() => void 0);
313
+ return { root: dir2, server: match[1], id: match[2] };
314
+ }
315
+ async function requireRemote(start) {
316
+ const deck = await findDeck(start);
317
+ if (!deck.id || !deck.server)
318
+ throw new CliError(
319
+ `${deck.root} isn't linked to a deck on a Tobos server (no matching git remote "origin").`
320
+ );
321
+ return deck;
322
+ }
323
+ function parseId(id) {
324
+ if (!new RegExp(`^${ID}$`).test(id))
325
+ throw new CliError(`"${id}" is not a deck's id; \`tobos decks\` lists them.`);
326
+ return id;
327
+ }
328
+
329
+ // src/media.ts
330
+ init_define_TOBOS_PRESENT_TYPES();
331
+ init_define_TOBOS_SKILL();
332
+ init_define_TOBOS_TOOLCHAIN();
333
+ import { createHash } from "node:crypto";
334
+ import {
335
+ createReadStream,
336
+ existsSync as existsSync2,
337
+ lstatSync,
338
+ mkdirSync as mkdirSync2,
339
+ readdirSync as readdirSync2,
340
+ readFileSync as readFileSync3,
341
+ realpathSync as realpathSync2,
342
+ statSync,
343
+ writeFileSync as writeFileSync2
344
+ } from "node:fs";
345
+ import { join as join4, relative, sep } from "node:path";
346
+ import { Readable } from "node:stream";
347
+ var LOSSLESS = /\.(wav|aiff?|flac)$/i;
348
+ var shellWord = (path) => /^[\w./-]+$/.test(path) ? path : `'${path.replaceAll("'", "'\\''")}'`;
349
+ function sizeNote(name, size) {
350
+ const mb = Math.round(size / 1e6);
351
+ if (LOSSLESS.test(name) && size > 1e6) {
352
+ const from = shellWord(`media/${name}`);
353
+ const to = shellWord(`media/${name.replace(LOSSLESS, ".m4a")}`);
354
+ return `note: media/${name} is lossless sound, ${mb} MB. As AAC it takes a fraction of that, and sounds the same in a room: ffmpeg -i ${from} -c:a aac -b:a 128k ${to}`;
355
+ }
356
+ if (size > 25e6)
357
+ return `note: media/${name} is ${mb} MB. Every viewer downloads it; size it for the stage.`;
358
+ return void 0;
359
+ }
360
+ function hashFile(path) {
361
+ return new Promise((resolve3, reject) => {
362
+ const hash = createHash("sha256");
363
+ createReadStream(path).on("data", (d) => hash.update(d)).on("end", () => resolve3(hash.digest("hex"))).on("error", reject);
364
+ });
365
+ }
366
+ function walk(dir2) {
367
+ if (!existsSync2(dir2) || !lstatSync(dir2).isDirectory()) return [];
368
+ return readdirSync2(dir2, { withFileTypes: true }).flatMap(
369
+ (d) => d.name.startsWith(".") ? [] : d.isDirectory() ? walk(join4(dir2, d.name)) : d.isFile() ? [join4(dir2, d.name)] : []
370
+ );
371
+ }
372
+ function mediaFile(root, name) {
373
+ const parts = name.split(process.platform === "win32" ? /[\\/]/ : "/");
374
+ if (name.startsWith("/") || name.includes("\0") || parts.some((p) => p === "" || p === ".."))
375
+ throw new CliError(`media.json names "${name}", which isn't a file in media/.`);
376
+ const path = join4(root, "media", name);
377
+ const refused = new CliError(
378
+ `media/${name} is a link or a folder, not a file: media/ holds files only.`
379
+ );
380
+ let entry;
381
+ try {
382
+ entry = lstatSync(path, { throwIfNoEntry: false });
383
+ } catch (error) {
384
+ const code = error.code;
385
+ if (code === "ENOTDIR" || code === "ENAMETOOLONG") return path;
386
+ throw refused;
387
+ }
388
+ if (entry && (!entry.isFile() || realpathSync2(path) !== join4(realpathSync2(root), "media", name)))
389
+ throw refused;
390
+ return path;
391
+ }
392
+ async function syncMediaJson(root) {
393
+ const file2 = join4(root, "media.json");
394
+ const before = existsSync2(file2) ? readFileSync3(file2, "utf8") : "{}\n";
395
+ const media = JSON.parse(before);
396
+ const cacheFile = join4(root, ".tobos", "media-cache.json");
397
+ let cache = {};
398
+ try {
399
+ cache = JSON.parse(readFileSync3(cacheFile, "utf8"));
400
+ } catch {
401
+ }
402
+ for (const name of Object.keys(media))
403
+ if (!(process.platform === "win32" && name.includes("\\"))) mediaFile(root, name);
404
+ const dir2 = join4(root, "media");
405
+ for (const path of walk(dir2)) {
406
+ const name = relative(dir2, path).split(sep).join("/");
407
+ const { size, mtimeMs } = statSync(path);
408
+ const cached = cache[name];
409
+ const hash = cached && cached.size === size && cached.mtime === mtimeMs ? cached.hash : await hashFile(path);
410
+ cache[name] = { size, mtime: mtimeMs, hash };
411
+ media[name] = {
412
+ hash,
413
+ size,
414
+ type: mediaTypeOf(name)
415
+ };
416
+ }
417
+ mkdirSync2(join4(root, ".tobos"), { recursive: true });
418
+ writeFileSync2(cacheFile, JSON.stringify(cache));
419
+ const sorted = Object.fromEntries(Object.entries(media).sort(([a], [b]) => a.localeCompare(b)));
420
+ const after = formatMediaJson(sorted);
421
+ if (after !== before) writeFileSync2(file2, after);
422
+ return { media: sorted, changed: after !== before };
423
+ }
424
+ async function uploadMedia(root, media, server, deck, note) {
425
+ const hashes = [...new Set(Object.values(media).map((m) => m.hash))];
426
+ if (hashes.length === 0) return [];
427
+ const { missing } = await api("/api/media/missing", {
428
+ body: { hashes },
429
+ server
430
+ });
431
+ const uploaded = [];
432
+ for (const hash of missing) {
433
+ const [name, entry] = Object.entries(media).find(([, m]) => m.hash === hash);
434
+ const path = mediaFile(root, name);
435
+ if (!existsSync2(path))
436
+ throw new CliError(
437
+ `media/${name} is in media.json but not on this machine, and the server doesn't have it.`
438
+ );
439
+ note(`uploading media/${name} (${Math.round(entry.size / 1e3)} kB)`);
440
+ const response = await request(`/api/media/${hash}?deck=${deck}`, {
441
+ method: "PUT",
442
+ body: Readable.toWeb(createReadStream(path)),
443
+ contentType: entry.type,
444
+ server
445
+ });
446
+ if (!response.ok)
447
+ throw failure(
448
+ response,
449
+ await response.json().catch(() => ({})),
450
+ `Uploading media/${name} failed: `
451
+ );
452
+ uploaded.push(name);
453
+ }
454
+ return uploaded;
455
+ }
456
+
457
+ // src/open-url.ts
458
+ init_define_TOBOS_PRESENT_TYPES();
459
+ init_define_TOBOS_SKILL();
460
+ init_define_TOBOS_TOOLCHAIN();
461
+ import { spawn as spawn2 } from "node:child_process";
462
+ async function openUrl(url) {
463
+ if (!/^https?:$/.test(URL.parse(url)?.protocol ?? "")) return false;
464
+ const env = process.env;
465
+ if (env.CI || env.TOBOS_NO_BROWSER || env.SSH_CONNECTION) return false;
466
+ if (process.platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return false;
467
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
468
+ const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
469
+ try {
470
+ const child = spawn2(command, args, { stdio: "ignore", detached: true });
471
+ child.unref();
472
+ return await new Promise((resolve3) => {
473
+ let timer;
474
+ const done = (opened) => {
475
+ clearTimeout(timer);
476
+ resolve3(opened);
477
+ };
478
+ child.once("error", () => done(false));
479
+ child.once("exit", (code) => done(code === 0));
480
+ child.once("spawn", () => timer = setTimeout(() => done(true), 1500));
481
+ });
482
+ } catch {
483
+ return false;
484
+ }
485
+ }
486
+
487
+ // src/format.ts
488
+ init_define_TOBOS_PRESENT_TYPES();
489
+ init_define_TOBOS_SKILL();
490
+ init_define_TOBOS_TOOLCHAIN();
491
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
492
+ import { join as join5 } from "node:path";
493
+ async function writeFormatGuide(root, server) {
494
+ const dir2 = join5(root, ".tobos");
495
+ mkdirSync3(dir2, { recursive: true });
496
+ const format = await request("/api/format", { anonymous: true, server });
497
+ if (!format.ok)
498
+ throw new CliError(`Couldn't fetch the format guide from ${server} (${format.status}).`);
499
+ writeFileSync3(join5(dir2, "FORMAT.md"), await format.text());
500
+ }
501
+
502
+ // src/skill.ts
503
+ init_define_TOBOS_PRESENT_TYPES();
504
+ init_define_TOBOS_SKILL();
505
+ init_define_TOBOS_TOOLCHAIN();
506
+ import {
507
+ existsSync as existsSync3,
508
+ mkdirSync as mkdirSync4,
509
+ readdirSync as readdirSync3,
510
+ readFileSync as readFileSync4,
511
+ renameSync as renameSync2,
512
+ rmSync,
513
+ writeFileSync as writeFileSync4
514
+ } from "node:fs";
515
+ import { homedir as homedir2 } from "node:os";
516
+ import { dirname as dirname2, join as join6 } from "node:path";
517
+ var SKILL_NAME = "tobos-present";
518
+ function readTree(root) {
519
+ const files = {};
520
+ for (const entry of readdirSync3(root, { recursive: true, withFileTypes: true }))
521
+ if (entry.isFile()) {
522
+ const path = join6(entry.parentPath, entry.name);
523
+ files[path.slice(root.length).replace(/^[\\/]/, "").split("\\").join("/")] = readFileSync4(path, "utf8");
524
+ }
525
+ return files;
526
+ }
527
+ function bundled() {
528
+ if (typeof define_TOBOS_SKILL_default !== "undefined") return define_TOBOS_SKILL_default;
529
+ return readTree(new URL(`../../agent-pack/skills/${SKILL_NAME}/`, import.meta.url).pathname);
530
+ }
531
+ function targets() {
532
+ const home = homedir2();
533
+ return [
534
+ {
535
+ dir: join6(process.env.CLAUDE_CONFIG_DIR || join6(home, ".claude"), "skills", SKILL_NAME),
536
+ harnesses: ["Claude Code", "OpenCode", "Cursor", "GitHub Copilot", "Goose"]
537
+ },
538
+ {
539
+ dir: join6(home, ".agents", "skills", SKILL_NAME),
540
+ harnesses: ["Codex", "OpenCode", "Cursor", "Gemini CLI", "GitHub Copilot", "Amp"]
541
+ }
542
+ ];
543
+ }
544
+ function write2(dir2, files, version) {
545
+ const next = `${dir2}.next-${process.pid}`;
546
+ for (const [path, text] of Object.entries(files)) {
547
+ mkdirSync4(dirname2(join6(next, path)), { recursive: true });
548
+ writeFileSync4(join6(next, path), text);
549
+ }
550
+ writeFileSync4(join6(next, "VERSION"), `${version}
551
+ `);
552
+ rmSync(dir2, { recursive: true, force: true });
553
+ try {
554
+ renameSync2(next, dir2);
555
+ } catch (error) {
556
+ rmSync(next, { recursive: true, force: true });
557
+ if (!existsSync3(join6(dir2, "VERSION"))) throw error;
558
+ }
559
+ }
560
+ var refusedCodes = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS"]);
561
+ function place(target, files, version) {
562
+ try {
563
+ write2(target.dir, files, version);
564
+ return { ...target, action: "installed" };
565
+ } catch (error) {
566
+ const code = error.code;
567
+ if (code && refusedCodes.has(code))
568
+ return { ...target, action: "refused", reason: error.message };
569
+ throw error;
570
+ }
571
+ }
572
+ function install(options = {}) {
573
+ const files = options.files ?? bundled();
574
+ return targets().map((t) => place(t, files, options.version ?? VERSION));
575
+ }
576
+ function refresh(options = {}) {
577
+ const version = options.version ?? VERSION;
578
+ return targets().filter((t) => existsSync3(join6(t.dir, "SKILL.md")) && newer(version, installed(t.dir))).map((t) => place(t, options.files ?? bundled(), version)).filter((r) => r.action === "refused");
579
+ }
580
+ function installed(dir2) {
581
+ try {
582
+ return readFileSync4(join6(dir2, "VERSION"), "utf8").trim();
583
+ } catch {
584
+ return "0.0.0";
585
+ }
586
+ }
587
+
588
+ // src/commands.ts
589
+ var TERMS_NOTICE = "If the address is new, using the code accepts https://tobos.ai/terms.";
590
+ async function login(out, args) {
591
+ const server = (args.values.server || settings().server).replace(/\/$/, "");
592
+ const client = `the tobos CLI on ${hostname()}`;
593
+ const email = args.positionals[0]?.trim().toLowerCase();
594
+ const code = args.values.code;
595
+ if (!code) {
596
+ if (!email)
597
+ throw new CliError(
598
+ "Log in with the e-mail address of the person you work for: `tobos login <email>`."
599
+ );
600
+ await api("/api/login", { anonymous: true, server, body: { email, client } });
601
+ save({ server, pending: email });
602
+ out.result(
603
+ { sent: email, next: "tobos login --code <code>", terms: TERMS_NOTICE },
604
+ () => `Sent a 6-digit code to ${email}; it works for 10 minutes. Ask the person for it in one line: check the inbox, or spam, and paste the code here. ${TERMS_NOTICE} Then run:
605
+
606
+ tobos login --code <code>`
607
+ );
608
+ return;
609
+ }
610
+ const address = email ?? settings().pending;
611
+ if (!address)
612
+ throw new CliError("Which address got the code? `tobos login <email> --code <code>`.");
613
+ const { token } = await api("/api/login/verify", {
614
+ anonymous: true,
615
+ server,
616
+ body: { email: address, code, client }
617
+ });
618
+ save({ server, token, pending: void 0 });
619
+ const me = await api("/api/me", { server });
620
+ save({ email: me.email });
621
+ out.result({ email: me.email, server }, () => `Logged in as ${me.email}.`);
622
+ }
623
+ async function logout(out) {
624
+ let revoked = false;
625
+ if (settings().token)
626
+ try {
627
+ await api("/api/logout", { method: "POST", body: {} });
628
+ revoked = true;
629
+ } catch (error) {
630
+ out.note(`(couldn't revoke the token on the server: ${error.message})`, true);
631
+ }
632
+ forget();
633
+ out.result(
634
+ { loggedOut: true, revoked },
635
+ () => revoked ? "Logged out. The token no longer works anywhere." : "Logged out on this machine; the server still knows the token."
636
+ );
637
+ }
638
+ async function whoami(out) {
639
+ const me = await api("/api/me");
640
+ out.result({ ...me, server: settings().server }, () => `${me.email} on ${settings().server}`);
641
+ }
642
+ function aboutDeck(d) {
643
+ const can = { editor: "you edit", presenter: "you present", viewer: "you view" };
644
+ const notes = [
645
+ d.kind === "template" && "template",
646
+ d.role && d.role !== "owner" && `${d.owner ?? "someone else"}\u2019s, ${can[d.role]}`,
647
+ d.archived && "archived: read-only"
648
+ ].filter(Boolean);
649
+ return notes.length ? ` (${notes.join("; ")})` : "";
650
+ }
651
+ async function decks(out) {
652
+ const { decks: decks2 } = await api("/api/decks");
653
+ out.result(
654
+ { decks: decks2 },
655
+ () => decks2.length === 0 ? 'No decks yet. `tobos new "Title"` starts one.' : decks2.map((d) => `${d.id} ${d.title}${aboutDeck(d)}`).join("\n")
656
+ );
657
+ }
658
+ async function cloneInto(out, info, dir2) {
659
+ const { server } = settings();
660
+ if (existsSync4(dir2)) throw new CliError(`${dir2} already exists.`);
661
+ out.note(`cloning ${info.title} into ${dir2}`);
662
+ await gitOk([...credentialConfig(server), "clone", "--quiet", info.git, dir2], {
663
+ env: authEnv(server)
664
+ });
665
+ await configureCredentials(dir2, server);
666
+ return writeFormatGuide(dir2, server);
667
+ }
668
+ async function clone(out, args) {
669
+ const given = args.positionals[0];
670
+ if (!given) throw new CliError("Which deck? `tobos clone <id>` (`tobos decks` lists them).");
671
+ const id = parseId(given);
672
+ const info = await api(`/api/decks/${id}`);
673
+ const dir2 = resolve2(args.positionals[1] ?? id);
674
+ await cloneInto(out, info, dir2);
675
+ out.result(
676
+ { ...info, dir: dir2 },
677
+ () => `Cloned ${info.title} into ${relative2(process.cwd(), dir2) || "."}.
678
+ Read AGENTS.md there first. Preview: ${info.url}`
679
+ );
680
+ }
681
+ async function create(out, args) {
682
+ const title = args.positionals.join(" ").trim();
683
+ if (!title) throw new CliError('What is it called? `tobos new "My talk"`.');
684
+ const info = await api("/api/decks", {
685
+ body: {
686
+ title,
687
+ from: args.values.from,
688
+ template: Boolean(args.values.template)
689
+ }
690
+ });
691
+ let dir2;
692
+ if (!args.values["no-clone"]) {
693
+ dir2 = resolve2(args.values.dir ?? info.id);
694
+ await cloneInto(out, info, dir2);
695
+ }
696
+ out.result(
697
+ { ...info, dir: dir2 ?? null },
698
+ () => [
699
+ `Created ${info.title}: ${info.url}`,
700
+ dir2 ? `Cloned into ${relative2(process.cwd(), dir2) || "."}. Read AGENTS.md there first.` : ""
701
+ ].filter(Boolean).join("\n")
702
+ );
703
+ }
704
+ async function pull(out) {
705
+ const deck = await requireRemote();
706
+ const result = await git(
707
+ [...credentialConfig(deck.server), "pull", "--ff-only", "--quiet", "origin", "main"],
708
+ { cwd: deck.root, env: authEnv(deck.server) }
709
+ );
710
+ if (result.code !== 0)
711
+ throw new CliError(
712
+ `Couldn't fast-forward to the server's main:
713
+ ${result.stderr.trim()}
714
+ Commit or stash your changes, then merge with \`git pull\`.`
715
+ );
716
+ await writeFormatGuide(deck.root, deck.server);
717
+ const rev = (await gitOk(["rev-parse", "HEAD"], { cwd: deck.root })).trim();
718
+ out.result({ id: deck.id, rev }, () => `Up to date with the server (${rev.slice(0, 7)}).`);
719
+ }
720
+ async function pushedFiles(root) {
721
+ try {
722
+ const prefix = await git(["rev-parse", "--show-prefix"], { cwd: root });
723
+ if (prefix.code !== 0 || prefix.stdout.trim() !== "") return void 0;
724
+ const listed = await git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
725
+ cwd: root
726
+ });
727
+ return listed.code === 0 ? listed.stdout.split("\0").filter(Boolean) : void 0;
728
+ } catch {
729
+ return void 0;
730
+ }
731
+ }
732
+ async function runCheck(dir2) {
733
+ const { buildDeck } = await import("./src-HNFV4MW7.js");
734
+ const started = performance.now();
735
+ const files = await pushedFiles(dir2.root);
736
+ const result = await buildDeck(directoryTree(dir2.root, files));
737
+ return { ...result, files, ms: Math.round(performance.now() - started) };
738
+ }
739
+ var remoteLines = (stderr) => stderr.split("\n").filter((l) => l.startsWith("remote: ")).map((l) => l.slice(8));
740
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
741
+ var MEDIA_LIMIT = /^tobos: (This deck belongs to .+, whose )?Tobos \w+ keeps .+ of media/;
742
+ function pushFailure(output, remote) {
743
+ const forThePerson = `${remote.map((line) => line.replace(/^tobos: /, "")).join("\n")}
744
+ ${ASK_THE_PERSON}`;
745
+ if (remote.some((line) => /^tobos: This (deck|template) is archived/.test(line)))
746
+ return { message: forThePerson, exit: EXIT.limit, archived: true };
747
+ if (remote.some((line) => MEDIA_LIMIT.test(line)))
748
+ return { message: forThePerson, exit: EXIT.limit, limit: "media" };
749
+ if (/non-fast-forward|fetch first/.test(output))
750
+ return {
751
+ message: "The server has changes you don't have. Run `tobos pull` (or `git pull`), then push again.",
752
+ exit: EXIT.error
753
+ };
754
+ if (remote.some((line) => line.startsWith("tobos: rejected:")))
755
+ return { message: `The server rejected the deck.
756
+ ${remote.join("\n")}`, exit: EXIT.problems };
757
+ if (/Authentication failed|returned error: 401|could not read Username/i.test(output))
758
+ return {
759
+ message: "The server didn't take your login. Run `tobos login` again, then push.",
760
+ exit: EXIT.auth
761
+ };
762
+ if (/returned error: 403/.test(output))
763
+ return {
764
+ message: "You may not push to this deck: ask its owner to make you an editor.",
765
+ exit: EXIT.error
766
+ };
767
+ if (remote.length > 0)
768
+ return { message: `The server refused the push.
769
+ ${remote.join("\n")}`, exit: EXIT.error };
770
+ if (/Could not resolve host|Failed to connect|Connection refused|SSL|certificate/i.test(output))
771
+ return {
772
+ message: `Couldn't reach the server: nothing was pushed. Try again.
773
+ ${output.trim()}`,
774
+ exit: EXIT.error
775
+ };
776
+ if (/timed out|Connection reset|unexpected disconnect|RPC failed/i.test(output))
777
+ return {
778
+ message: `The connection broke off, and the push may have gone through. Run \`tobos pull\` to see where the server is, then push again if it still lacks your change.
779
+ ${output.trim()}`,
780
+ exit: EXIT.error
781
+ };
782
+ return { message: `The push failed.
783
+ ${output.trim()}`, exit: EXIT.error };
784
+ }
785
+ function problemSummary(problems) {
786
+ const errors = problems.filter((p) => p.severity === "error").length;
787
+ return { errors, warnings: problems.length - errors };
788
+ }
789
+ async function check(out, args) {
790
+ const deck = await findDeck(args.positionals[0]);
791
+ await syncMediaJson(deck.root);
792
+ const result = await runCheck(deck);
793
+ if (args.values.types) {
794
+ const { checkTypes } = await import("./types-NZUVJ337.js");
795
+ const sent = result.files && new Set(result.files);
796
+ result.problems.push(
797
+ ...(await checkTypes(deck.root, (m) => out.note(m))).filter((p) => sent?.has(p.file) ?? true)
798
+ );
799
+ }
800
+ const { errors, warnings } = problemSummary(result.problems);
801
+ const scenes = result.manifest?.chapters.reduce((n, c) => n + c.scenes.length, 0) ?? 0;
802
+ const beats = result.manifest?.chapters.reduce(
803
+ (n, c) => n + c.scenes.reduce((m, s) => m + s.beats.length, 0),
804
+ 0
805
+ ) ?? 0;
806
+ out.result(
807
+ { ok: errors === 0, errors, warnings, problems: result.problems, scenes, beats, ms: result.ms },
808
+ () => [
809
+ formatProblems(result.problems),
810
+ errors === 0 ? `\u2713 ${plural(scenes, "scene")}, ${plural(beats, "beat")}${warnings ? `, ${plural(warnings, "warning")}` : ""} (${result.ms} ms)` : `\u2717 ${plural(errors, "error")}${warnings ? `, ${plural(warnings, "warning")}` : ""}`
811
+ ].filter(Boolean).join("\n")
812
+ );
813
+ if (errors > 0) process.exitCode = EXIT.problems;
814
+ }
815
+ async function pushWorkingCopy(out, deck, message) {
816
+ const { root, server } = deck;
817
+ const { media } = await syncMediaJson(root);
818
+ const result = await runCheck(deck);
819
+ const { errors, warnings } = problemSummary(result.problems);
820
+ if (errors > 0) return { ok: false, errors, warnings, problems: result.problems };
821
+ for (const [name, entry] of Object.entries(media)) {
822
+ const note = sizeNote(name, entry.size);
823
+ if (note) out.note(note, true);
824
+ }
825
+ const uploaded = await uploadMedia(root, media, server, deck.id, (m) => out.note(m));
826
+ await gitOk(["add", "-A"], { cwd: root });
827
+ const committed = (await gitOk(["diff", "--cached", "--name-only"], { cwd: root })).split("\n").filter(Boolean);
828
+ for (const file2 of committed) out.note(` ${file2}`);
829
+ if (committed.length > 0)
830
+ await gitOk(["commit", "--quiet", "-m", message || "Update the deck"], {
831
+ cwd: root,
832
+ env: await identity(root)
833
+ });
834
+ out.note("pushing\u2026");
835
+ const pushed = await git(
836
+ [...credentialConfig(server), "push", "--porcelain", "origin", "HEAD:main"],
837
+ { cwd: root, echo: !out.json, env: authEnv(server) }
838
+ );
839
+ const remote = remoteLines(pushed.stderr);
840
+ if (pushed.code !== 0) {
841
+ const { message: message2, exit, ...extra } = pushFailure(pushed.stdout + pushed.stderr, remote);
842
+ throw new CliError(message2, exit, { remote, ...extra });
843
+ }
844
+ const rev = (await gitOk(["rev-parse", "HEAD"], { cwd: root })).trim();
845
+ return { ok: true, rev, committed, uploaded, warnings, remote };
846
+ }
847
+ async function push(out, args) {
848
+ const deck = await requireRemote();
849
+ const result = await pushWorkingCopy(out, deck, args.values.message);
850
+ if (!result.ok) {
851
+ out.result(
852
+ { ...result, pushed: false },
853
+ () => `${formatProblems(result.problems)}
854
+ \u2717 Not pushed: ${plural(result.errors, "error")}. Fix them and push again.`
855
+ );
856
+ process.exitCode = EXIT.problems;
857
+ return;
858
+ }
859
+ const url = `${deck.server}/${deck.id}`;
860
+ out.result(
861
+ { ...result, pushed: true, url },
862
+ () => `\u2713 Pushed ${result.rev.slice(0, 7)}${result.uploaded.length ? ` with ${plural(result.uploaded.length, "media file")}` : ""}. Live at ${url}`
863
+ );
864
+ }
865
+ async function pushIfChanged(out, id, message) {
866
+ const found = await findDeck().catch(() => void 0);
867
+ if (!found?.server || found.id !== id) return { pushed: false, uploaded: [] };
868
+ const deck = found;
869
+ const dirty = (await gitOk(["status", "--porcelain"], { cwd: deck.root })).trim() !== "";
870
+ const head = await git(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: deck.root });
871
+ const remote = await git(["rev-parse", "--verify", "--quiet", "origin/main"], { cwd: deck.root });
872
+ if (!dirty && head.stdout.trim() === remote.stdout.trim())
873
+ return { pushed: false, uploaded: [] };
874
+ const result = await pushWorkingCopy(out, deck, message);
875
+ if (!result.ok)
876
+ throw new CliError(
877
+ `${formatProblems(result.problems)}
878
+ \u2717 ${plural(result.errors, "error")} in your working copy. Fix them and try again.`,
879
+ EXIT.problems,
880
+ { problems: result.problems }
881
+ );
882
+ return { pushed: true, uploaded: result.uploaded };
883
+ }
884
+ async function identity(root) {
885
+ if ((await git(["config", "user.email"], { cwd: root })).code === 0) return {};
886
+ const who = settings().email;
887
+ return {
888
+ GIT_AUTHOR_NAME: who ?? "tobos",
889
+ GIT_AUTHOR_EMAIL: who ?? "tobos@localhost",
890
+ GIT_COMMITTER_NAME: who ?? "tobos",
891
+ GIT_COMMITTER_EMAIL: who ?? "tobos@localhost"
892
+ };
893
+ }
894
+ async function viewUrl(id, view, hours) {
895
+ return api(`/api/decks/${id}/view`, { body: { view, hours } });
896
+ }
897
+ async function deckId(args) {
898
+ if (typeof args.values.deck === "string") return parseId(args.values.deck);
899
+ return (await requireRemote()).id;
900
+ }
901
+ async function open(out, args) {
902
+ const position = args.positionals[0];
903
+ if (!position && typeof args.values.deck !== "string" && !await findDeck().catch(() => null))
904
+ return openApp(out);
905
+ const view = args.values.presenter ? "presenter" : void 0;
906
+ const id = await deckId(args);
907
+ const { pushed } = await pushIfChanged(out, id);
908
+ const { url } = await viewUrl(id, view, 12);
909
+ const full = position ? `${url}#${position}` : url;
910
+ const opened = !args.values.print && await openUrl(full);
911
+ out.result({ url: full, opened, pushed }, () => full);
912
+ }
913
+ async function openApp(out) {
914
+ const { url, code } = await api("/api/login/browser", {
915
+ method: "POST"
916
+ });
917
+ const page = `${new URL(url).origin}/login`;
918
+ out.result(
919
+ { url, code, page },
920
+ () => code ? `Open this link, or enter ${code} at ${page}. It works once, within 10 minutes.
921
+ ${url}` : `Open this link. It works once, within 10 minutes.
922
+ ${url}`
923
+ );
924
+ }
925
+ async function storyTx(id, ops) {
926
+ try {
927
+ return await api(`/api/decks/${id}/story/tx`, {
928
+ body: { ops, agent: process.env.TOBOS_AGENT || void 0 }
929
+ });
930
+ } catch (error) {
931
+ if (error instanceof CliError && (error.extra.status === 409 || error.extra.status === 422)) {
932
+ const now = error.extra.paragraph;
933
+ throw new CliError(
934
+ now ? `${error.message}
935
+ It is now:
936
+ \xB6 ${now.id} ${now.text}` : error.message,
937
+ error.extra.status === 409 ? EXIT.conflict : EXIT.error,
938
+ error.extra
939
+ );
940
+ }
941
+ throw error;
942
+ }
943
+ }
944
+ async function story(out, args) {
945
+ const [action, ...rest] = args.positionals;
946
+ const id = await deckId(args);
947
+ if (!action) {
948
+ const story2 = await api(`/api/decks/${id}/story`);
949
+ out.result(
950
+ { ...story2 },
951
+ () => story2.paragraphs.length ? story2.paragraphs.map((p) => `\xB6 ${p.id.padEnd(4)} ${p.text}`).join("\n\n") : 'No story yet. `tobos story add "\u2026"` writes its first paragraph.'
952
+ );
953
+ return;
954
+ }
955
+ if (action === "edit") {
956
+ const [paragraph, find, replace] = rest;
957
+ if (!paragraph || find === void 0 || replace === void 0)
958
+ throw new CliError(
959
+ '`tobos story edit <\xB6 id> "the exact text" "what replaces it"` (`tobos story` shows the ids).'
960
+ );
961
+ const result = await storyTx(id, [{ op: "set", id: paragraph, find, replace }]);
962
+ out.result({ ...result, paragraph }, () => `Changed ${paragraph}.`);
963
+ return;
964
+ }
965
+ if (action === "add") {
966
+ const text = rest.join(" ").trim();
967
+ if (!text) throw new CliError('`tobos story add [--after <\xB6 id>] "the paragraph"`.');
968
+ const after = args.values.after ?? "end";
969
+ const result = await storyTx(id, [
970
+ { op: "insert", after: after === "start" ? null : after, text, key: "new:1" }
971
+ ]);
972
+ const paragraph = result.ids["new:1"] ?? null;
973
+ out.result({ ...result, paragraph }, () => `Added ${paragraph}.`);
974
+ return;
975
+ }
976
+ if (action === "delete") {
977
+ const paragraph = rest[0];
978
+ if (!paragraph) throw new CliError("`tobos story delete <\xB6 id>`.");
979
+ const result = await storyTx(id, [{ op: "delete", id: paragraph }]);
980
+ out.result({ ...result, paragraph }, () => `Deleted ${paragraph}.`);
981
+ return;
982
+ }
983
+ throw new CliError(`No \`tobos story ${action}\`: edit, add or delete.`);
984
+ }
985
+ var waiting = (p) => p.joined ? "" : ` (invited, not logged in yet${p.lapsesAt ? `; lapses ${new Date(p.lapsesAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}` : ""})`;
986
+ var CAN = {
987
+ edit: "editor",
988
+ present: "presenter",
989
+ view: "viewer",
990
+ use: "viewer"
991
+ };
992
+ var CAN_WORDS = {
993
+ owner: "owner",
994
+ editor: "can edit",
995
+ presenter: "can present",
996
+ viewer: "can view"
997
+ };
998
+ var canWords = (role, kind = "deck") => kind === "template" && role === "viewer" ? "can use" : CAN_WORDS[role];
999
+ async function people(out, args) {
1000
+ const id = await deckId(args);
1001
+ const { people: people2, kind } = await api(`/api/decks/${id}/people`);
1002
+ out.result(
1003
+ { ...kind ? { kind } : {}, people: people2 },
1004
+ () => people2.map(
1005
+ (p) => `${p.email.padEnd(32)} ${canWords(p.role, kind)}${p.paused ? ", paused: views until the plan allows more editors" : ""}${waiting(p)}`
1006
+ ).join("\n")
1007
+ );
1008
+ }
1009
+ async function invite(out, args) {
1010
+ const email = args.positionals[0];
1011
+ const level = CAN[String(args.values.can)];
1012
+ if (!email || !level)
1013
+ throw new CliError(
1014
+ "Invite whom, to do what? `tobos invite <email> --can edit`, `--can present` or `--can view`; to a template, `--can edit` or `--can use`."
1015
+ );
1016
+ const id = await deckId(args);
1017
+ const done = await api(`/api/decks/${id}/people`, { body: { email, level } });
1018
+ const now = `${done.email} ${canWords(done.level, done.kind)} now`;
1019
+ out.result(
1020
+ done,
1021
+ () => done.mailed ? `${now}; they got a mail with the way in.` : done.mailFailed ? `${now}, but the invite mail couldn't be sent: send them ${done.link}` : done.link ? `${now}. They had an invite to it in the last day, so no second mail: send them ${done.link}` : `${now}.`
1022
+ );
1023
+ }
1024
+ async function uninvite(out, args) {
1025
+ const email = args.positionals[0];
1026
+ if (!email) throw new CliError("Take whom off? `tobos uninvite <email>`.");
1027
+ const id = await deckId(args);
1028
+ const done = await api(`/api/decks/${id}/people`, {
1029
+ method: "DELETE",
1030
+ body: { email }
1031
+ });
1032
+ out.result(
1033
+ done,
1034
+ () => `${done.removed} is off the ${done.kind ?? "deck"}; their access has ended.`
1035
+ );
1036
+ }
1037
+ async function exportTarget(args, file2) {
1038
+ if (args.values.out) return resolve2(args.values.out);
1039
+ const deck = await findDeck().catch(() => void 0);
1040
+ if (!deck) return resolve2(file2);
1041
+ mkdirSync5(join7(deck.root, ".tobos", "exports"), { recursive: true });
1042
+ return join7(deck.root, ".tobos", "exports", file2);
1043
+ }
1044
+ async function exportDeck(out, args) {
1045
+ const kind = args.positionals[0];
1046
+ if (kind !== "pdf") throw new CliError("Export what? `tobos export pdf`.");
1047
+ const id = await deckId(args);
1048
+ out.note("getting the PDF of the latest push\u2026");
1049
+ const response = await request(`/api/decks/${id}/deck.pdf`);
1050
+ if (!response.ok) {
1051
+ const text = await response.text();
1052
+ let data;
1053
+ try {
1054
+ data = JSON.parse(text);
1055
+ } catch {
1056
+ data = { error: text.slice(0, 500) };
1057
+ }
1058
+ throw failure(response, data);
1059
+ }
1060
+ const pdf = new Uint8Array(await response.arrayBuffer());
1061
+ const target = await exportTarget(args, `${id}.pdf`);
1062
+ mkdirSync5(dirname3(target), { recursive: true });
1063
+ writeFileSync5(target, pdf);
1064
+ const pages = Buffer.from(pdf).toString("latin1").match(/\/Type\s*\/Page(?![s\w])/g)?.length ?? 0;
1065
+ out.result(
1066
+ { file: target, pages },
1067
+ () => `Wrote ${relative2(process.cwd(), target)} (${pages} pages).`
1068
+ );
1069
+ }
1070
+ async function render(out, args) {
1071
+ const { renderBeats } = await import("./render-CRDYQFP2.js");
1072
+ const deck = await findDeck().catch(() => void 0);
1073
+ const id = typeof args.values.deck === "string" ? parseId(args.values.deck) : deck?.id;
1074
+ if (!id) throw new CliError("Run this inside a cloned deck, or pass --deck <id>.");
1075
+ const { pushed, uploaded } = await pushIfChanged(out, id, args.values.message);
1076
+ const view = await viewUrl(id, "render");
1077
+ const { url } = view;
1078
+ const rev = view.rev ?? void 0;
1079
+ const targets2 = [];
1080
+ const { scenes } = view;
1081
+ const wanted = args.values.all ? scenes.map((s) => s.id) : args.positionals;
1082
+ if (wanted.length === 0)
1083
+ throw new CliError("Render what? `tobos render scene/beat`, `tobos render scene`, or `--all`.");
1084
+ for (const ref of wanted) {
1085
+ const [sceneId, beat] = ref.split("/");
1086
+ const scene = scenes.find((s) => s.id === sceneId);
1087
+ if (!scene) throw new CliError(`No scene "${sceneId}" in deck.json.`);
1088
+ if (beat) {
1089
+ const id2 = /^\d+$/.test(beat) ? scene.beats[Number(beat)] : beat;
1090
+ if (!id2 || !scene.beats.includes(id2))
1091
+ throw new CliError(`No beat "${beat}" in scene "${sceneId}".`);
1092
+ targets2.push(`${scene.id}/${id2}`);
1093
+ } else targets2.push(...scene.beats.map((b) => `${scene.id}/${b}`));
1094
+ }
1095
+ const root = deck?.id === id ? deck.root : ".";
1096
+ const dir2 = resolve2(args.values.out ?? join7(root, ".tobos", "render"));
1097
+ const { files, errors } = await renderBeats(url, targets2, {
1098
+ dir: dir2,
1099
+ film: Boolean(args.values.film),
1100
+ frames: Number(args.values.frames ?? 6),
1101
+ scale: Number(args.values.scale ?? 1),
1102
+ note: (m) => out.note(m)
1103
+ });
1104
+ out.result(
1105
+ { rev, pushed, uploaded, files, errors },
1106
+ () => files.map(
1107
+ (f) => `${f.position.padEnd(28)} ${relative2(process.cwd(), f.path)}${f.late ? " (not fully drawn)" : ""}`
1108
+ ).join("\n")
1109
+ );
1110
+ }
1111
+ async function skill(out, args) {
1112
+ if (args.positionals[0] !== "install")
1113
+ throw new CliError(
1114
+ "`tobos skill install` installs the skill; there is no other skill command."
1115
+ );
1116
+ const targets2 = install();
1117
+ const refused = targets2.filter((t) => t.action === "refused");
1118
+ if (refused.length)
1119
+ throw new CliError(
1120
+ `Couldn't write the skill to ${refused.map((t) => t.dir).join(" or ")}: ${refused[0].reason}. A harness's sandbox can stop writes outside the working folder: ask the person to approve the command, or to run \`tobos skill install\` themselves.`,
1121
+ EXIT.error,
1122
+ { targets: targets2 }
1123
+ );
1124
+ const next = "New sessions of the harness load the skill.";
1125
+ out.result(
1126
+ { skill: SKILL_NAME, version: VERSION, targets: targets2, next },
1127
+ () => [
1128
+ `The ${SKILL_NAME} skill (${VERSION}):`,
1129
+ ...targets2.map((t) => ` ${t.dir} (${t.harnesses.join(", ")})`),
1130
+ next
1131
+ ].join("\n")
1132
+ );
1133
+ }
1134
+ async function credential(args) {
1135
+ if (args.positionals[0] !== "get") return;
1136
+ const input = readFileSync5(0, "utf8");
1137
+ const fields = Object.fromEntries(
1138
+ input.split("\n").filter((l) => l.includes("=")).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)])
1139
+ );
1140
+ let stored;
1141
+ try {
1142
+ stored = settings();
1143
+ } catch (error) {
1144
+ process.stderr.write(`tobos: ${error.message}
1145
+ `);
1146
+ return;
1147
+ }
1148
+ const { server, token } = stored;
1149
+ const target = new URL(server);
1150
+ if (!token || fields.host !== target.host || `${fields.protocol}:` !== target.protocol) return;
1151
+ process.stdout.write(`username=tobos
1152
+ password=${token}
1153
+ `);
1154
+ }
1155
+
1156
+ // src/main.ts
1157
+ var HELP = `tobos ${VERSION}: the command line of Tobos, the office suite your coding agent works in.
1158
+
1159
+ Account
1160
+ tobos login <email> [--server URL] e-mail a login code to the person (signs them up if new)
1161
+ tobos login --code <code> finish: the code they read from the mail
1162
+ tobos logout forget this machine's token
1163
+ tobos whoami who you are, on which server
1164
+ tobos decks your decks and templates, by id, and those shared
1165
+ with you; an archived one is read-only
1166
+
1167
+ Working on a deck
1168
+ tobos new "Title" [--dir dir] [--no-clone] create a deck and clone it here, into ./<id>
1169
+ (or into dir; --no-clone: only create it)
1170
+ tobos clone <id> [dir] clone a deck, with the agent pack
1171
+ tobos pull get the latest pushes and the format guide
1172
+ tobos check [--types] compile and check the deck, offline (~1 s);
1173
+ --types: TypeScript too (installs a checker once)
1174
+ tobos push [-m "what changed"] upload media, commit, push; the server checks it
1175
+
1176
+ Looking at it (from the working copy, render and open push what changed first; with --deck <id>,
1177
+ from anywhere)
1178
+ tobos render scene/beat | scene | --all PNGs of beats, for you to look at
1179
+ [--film] [--frames 6] [--out dir] --film: frames through the animation
1180
+ [--scale 2] [-m "what changed"] --scale: pixels per stage pixel; -m: for the push
1181
+ tobos open [scene/beat] [--presenter] the deck in a browser (prints the URL, which opens once)
1182
+ [--print] --print: print the URL only, open nothing
1183
+ tobos open outside a deck: a link, or its code for /login,
1184
+ that logs a browser in once; show the person both
1185
+ tobos export pdf [--out file] the deck's PDF, as its page and its link give it:
1186
+ a page per scene at its last beat, no polls
1187
+
1188
+ The story (what the speaker says, held by the server; a scene mentioned: [Title](scene:<id>),
1189
+ a beat: [Title](scene:<id>/<beat>))
1190
+ tobos story the text, by \xB6 id
1191
+ tobos story edit <\xB6> "old" "new" change it, anchored on the exact text
1192
+ tobos story add [--after <\xB6>] "\u2026" a new paragraph (at the end, or after \xB6)
1193
+ tobos story delete <\xB6> a paragraph goes
1194
+ TOBOS_AGENT=<name> says which agent you are: the
1195
+ deck's page marks what you wrote
1196
+
1197
+ People on a deck or template (from its working copy, or --deck <id>)
1198
+ tobos people who is on it, what each may do, and when a
1199
+ waiting invite lapses
1200
+ tobos invite <email> --can edit|present|view
1201
+ its owner puts them on it, mailed the way in;
1202
+ someone on it already gets the new level. On a
1203
+ template, --can edit|use
1204
+ tobos uninvite <email> take them off, and their access ends at once;
1205
+ with your own address, leave it
1206
+
1207
+ The skill (what your harness reads to know Tobos without this help)
1208
+ tobos skill install put it where Claude Code, Codex, OpenCode and others
1209
+ read skills; later CLIs keep it up to date
1210
+
1211
+ Templates (decks people start from: a new deck copies a template's master/)
1212
+ tobos new "Title" --from <id> start a deck from that template (default: Tobos
1213
+ simple; \`tobos decks\` lists the person's own)
1214
+ tobos new "Our brand" --template a new template: a copy of Tobos simple (or of --from)
1215
+
1216
+ Every command takes --json and then prints one JSON object.
1217
+ Exit codes: 0 ok, 1 error, 2 the deck has problems, 3 not logged in, 4 the story changed
1218
+ meanwhile (the reply has the paragraph as it is now: anchor on that and try again), 5 a plan's
1219
+ limit or an archived deck: the person decides what to do, so show them the message and wait.
1220
+ `;
1221
+ var COMMON = {
1222
+ json: { type: "boolean" },
1223
+ help: { type: "boolean", short: "h" }
1224
+ };
1225
+ var TABLE = {
1226
+ login: {
1227
+ run: login,
1228
+ options: { server: { type: "string" }, code: { type: "string" } }
1229
+ },
1230
+ logout: { run: logout },
1231
+ whoami: { run: whoami },
1232
+ decks: { run: decks },
1233
+ new: {
1234
+ run: create,
1235
+ options: {
1236
+ dir: { type: "string" },
1237
+ "no-clone": { type: "boolean" },
1238
+ from: { type: "string" },
1239
+ template: { type: "boolean" }
1240
+ }
1241
+ },
1242
+ clone: { run: clone },
1243
+ pull: { run: pull },
1244
+ check: { run: check, options: { types: { type: "boolean" } } },
1245
+ push: { run: push, options: { message: { type: "string", short: "m" } } },
1246
+ open: {
1247
+ run: open,
1248
+ options: {
1249
+ presenter: { type: "boolean" },
1250
+ deck: { type: "string" },
1251
+ print: { type: "boolean" }
1252
+ }
1253
+ },
1254
+ export: {
1255
+ run: exportDeck,
1256
+ options: {
1257
+ out: { type: "string" },
1258
+ deck: { type: "string" }
1259
+ }
1260
+ },
1261
+ people: { run: people, options: { deck: { type: "string" } } },
1262
+ invite: {
1263
+ run: invite,
1264
+ options: { can: { type: "string" }, deck: { type: "string" } }
1265
+ },
1266
+ uninvite: { run: uninvite, options: { deck: { type: "string" } } },
1267
+ skill: { run: skill },
1268
+ story: {
1269
+ run: story,
1270
+ options: { deck: { type: "string" }, after: { type: "string" } }
1271
+ },
1272
+ render: {
1273
+ run: render,
1274
+ options: {
1275
+ all: { type: "boolean" },
1276
+ film: { type: "boolean" },
1277
+ frames: { type: "string" },
1278
+ out: { type: "string" },
1279
+ scale: { type: "string" },
1280
+ deck: { type: "string" },
1281
+ message: { type: "string", short: "m" }
1282
+ }
1283
+ }
1284
+ };
1285
+ async function main(argv) {
1286
+ const [name, ...rest] = argv;
1287
+ if (!name || name === "help" || name === "--help" || name === "-h") {
1288
+ process.stdout.write(HELP);
1289
+ return;
1290
+ }
1291
+ if (name === "--version" || name === "-v" || name === "version") {
1292
+ process.stdout.write(`${VERSION}
1293
+ `);
1294
+ return;
1295
+ }
1296
+ if (name === "credential") {
1297
+ await credential({ positionals: rest, values: {} });
1298
+ return;
1299
+ }
1300
+ const command = TABLE[name];
1301
+ const json = rest.includes("--json");
1302
+ const out = createOutput(json);
1303
+ try {
1304
+ if (!command) throw new CliError(`Unknown command "${name}". \`tobos help\` lists them.`);
1305
+ let parsed;
1306
+ try {
1307
+ parsed = parseArgs({
1308
+ args: rest,
1309
+ options: { ...COMMON, ...command.options },
1310
+ allowPositionals: true
1311
+ });
1312
+ } catch (error) {
1313
+ throw new CliError(`${error.message}. \`tobos help\` shows the options.`);
1314
+ }
1315
+ if (parsed.values.help) {
1316
+ process.stdout.write(HELP);
1317
+ return;
1318
+ }
1319
+ if (name !== "skill")
1320
+ for (const { dir: dir2, reason } of refresh())
1321
+ out.note(
1322
+ `Couldn't update the skill in ${dir2} (${reason}); \`tobos skill install\`, run where it may write there, does.`
1323
+ );
1324
+ await command.run(out, {
1325
+ positionals: parsed.positionals,
1326
+ values: parsed.values
1327
+ });
1328
+ } catch (error) {
1329
+ const known = error instanceof CliError;
1330
+ const message = known ? error.message : `${error.stack ?? error}`;
1331
+ if (json)
1332
+ process.stdout.write(
1333
+ `${JSON.stringify({ ok: false, error: message, ...known ? error.extra : {}, ...update ? { update } : {} })}
1334
+ `
1335
+ );
1336
+ else process.stderr.write(`tobos: ${message}
1337
+ `);
1338
+ process.exitCode = known ? error.exit : EXIT.error;
1339
+ }
1340
+ if (update && !json) process.stderr.write(`${update}
1341
+ `);
1342
+ }
1343
+ await main(process.argv.slice(2));