@tobos/cli 0.4.29 → 0.4.31

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 CHANGED
@@ -2,24 +2,24 @@
2
2
  import { createRequire as __tobosRequire } from 'node:module';
3
3
  const require = __tobosRequire(import.meta.url);
4
4
  import {
5
- formatMediaJson,
6
5
  formatProblems,
7
- mediaTypeOf
8
- } from "./chunk-TQNXR6KB.js";
6
+ mediaTypeOf,
7
+ mergeText,
8
+ parseMediaJson,
9
+ unpackTar
10
+ } from "./chunk-T2JISWY5.js";
9
11
  import {
10
12
  ASK_THE_PERSON,
11
13
  CliError,
12
14
  EXIT,
13
15
  createOutput,
14
- offerUpdate,
15
- update
16
- } from "./chunk-BEVE4YBG.js";
17
- import {
18
16
  define_TOBOS_SKILL_default,
19
17
  init_define_TOBOS_PRESENT_TYPES,
20
18
  init_define_TOBOS_SKILL,
21
- init_define_TOBOS_TOOLCHAIN
22
- } from "./chunk-3SEPIUUD.js";
19
+ init_define_TOBOS_TOOLCHAIN,
20
+ offerUpdate,
21
+ update
22
+ } from "./chunk-XG2KKGXE.js";
23
23
 
24
24
  // src/main.ts
25
25
  init_define_TOBOS_PRESENT_TYPES();
@@ -68,7 +68,10 @@ function write(stored) {
68
68
  renameSync(next, file);
69
69
  }
70
70
  function save(update2) {
71
- write({ ...read(), ...update2 });
71
+ const stored = read();
72
+ const elsewhere = update2.server !== void 0 && update2.server !== stored.server;
73
+ const kept = elsewhere ? { server: stored.server } : stored;
74
+ write({ ...kept, ...update2 });
72
75
  }
73
76
  function forget() {
74
77
  write({ server: read().server });
@@ -80,16 +83,18 @@ function settings() {
80
83
  } catch (error) {
81
84
  if (!process.env.TOBOS_SERVER || !process.env.TOBOS_TOKEN) throw error;
82
85
  }
86
+ const server = (process.env.TOBOS_SERVER || stored.server || DEFAULT_SERVER).replace(/\/$/, "");
87
+ const own = (stored.server || DEFAULT_SERVER).replace(/\/$/, "") === server;
83
88
  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
89
+ server,
90
+ token: process.env.TOBOS_TOKEN || (own ? stored.token : void 0),
91
+ email: own ? stored.email : void 0,
92
+ device: stored.device
88
93
  };
89
94
  }
90
95
 
91
96
  // src/api.ts
92
- var VERSION = true ? "0.4.29" : "dev";
97
+ var VERSION = true ? "0.4.31" : "dev";
93
98
  function newer(a, b) {
94
99
  const parse = (v) => /^\d+\.\d+\.\d+/.test(v) ? v.split(".").map((n) => parseInt(n)) : null;
95
100
  const x = parse(a);
@@ -132,12 +137,12 @@ async function request(path, options = {}) {
132
137
  if (!options.anonymous) {
133
138
  if (!token)
134
139
  throw new CliError(
135
- "Not logged in. Ask the person you work for for their e-mail address, then run `tobos login <email>`.",
140
+ "Not logged in: run `tobos login`, and give the person the address it prints.",
136
141
  EXIT.auth
137
142
  );
138
143
  if (new URL(target).origin !== new URL(server).origin)
139
144
  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}\`.`,
145
+ `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 --server ${target}\`.`,
141
146
  EXIT.auth
142
147
  );
143
148
  headers.authorization = `Bearer ${token}`;
@@ -164,9 +169,9 @@ async function request(path, options = {}) {
164
169
  `Can't reach ${target}: ${error.cause ?? error.message}`
165
170
  );
166
171
  }
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`);
172
+ const latest2 = response.headers.get("tobos-latest-cli");
173
+ if (latest2 && newer(latest2, VERSION))
174
+ offerUpdate(`tobos ${latest2} is out (you have ${VERSION}): npm i -g @tobos/cli`);
170
175
  return response;
171
176
  }
172
177
 
@@ -174,176 +179,312 @@ async function request(path, options = {}) {
174
179
  init_define_TOBOS_PRESENT_TYPES();
175
180
  init_define_TOBOS_SKILL();
176
181
  init_define_TOBOS_TOOLCHAIN();
177
- import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "node:fs";
182
+ import { existsSync as existsSync3, statSync as statSync2 } from "node:fs";
178
183
  import { hostname } from "node:os";
179
- import { dirname as dirname3, join as join7, relative as relative2, resolve as resolve2 } from "node:path";
184
+ import { join as join5, relative as relative2, resolve as resolve2 } from "node:path";
180
185
 
181
- // ../deck/src/node.ts
186
+ // src/copy.ts
182
187
  init_define_TOBOS_PRESENT_TYPES();
183
188
  init_define_TOBOS_SKILL();
184
189
  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
- };
190
+ import { execFileSync } from "node:child_process";
191
+ import { createHash } from "node:crypto";
192
+ import {
193
+ existsSync,
194
+ lstatSync,
195
+ statSync,
196
+ mkdirSync as mkdirSync2,
197
+ readdirSync,
198
+ readFileSync as readFileSync2,
199
+ rmSync,
200
+ writeFileSync as writeFileSync2
201
+ } from "node:fs";
202
+ import { isUtf8 } from "node:buffer";
203
+ import { dirname, join as join2, relative, resolve, sep } from "node:path";
204
+ var BASE = join2(".tobos", "base.json");
205
+ var ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
206
+ var NOT_THE_DECK = /* @__PURE__ */ new Set([".tobos", ".git", "node_modules", "sources"]);
207
+ function parseId(id) {
208
+ if (!ID.test(id)) throw new CliError(`"${id}" is not a deck's id; \`tobos ls\` lists them.`);
209
+ return id;
215
210
  }
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
- )
211
+ function findCopy(start = process.cwd()) {
212
+ for (let dir2 = resolve(start); ; dir2 = dirname(dir2)) {
213
+ if (existsSync(join2(dir2, BASE)))
214
+ return { root: dir2, base: JSON.parse(readFileSync2(join2(dir2, BASE), "utf8")) };
215
+ if (existsSync(join2(dir2, ".git")) && existsSync(join2(dir2, "deck.json"))) return { root: dir2 };
216
+ if (dirname(dir2) === dir2) return void 0;
217
+ }
218
+ }
219
+ function requireCopy(start) {
220
+ const found = findCopy(start);
221
+ if (!found)
222
+ throw new CliError(
223
+ "Not in a deck: no .tobos/base.json here or above. `tobos pull <id>` makes one."
250
224
  );
251
- child.on("close", (code) => resolve3({ code: code ?? 1, stdout, stderr }));
252
- });
225
+ if (!found.base)
226
+ throw new CliError(
227
+ `${found.root} is a clone from before: run \`tobos pull\` there once, which makes it a working copy.`
228
+ );
229
+ return found;
253
230
  }
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;
231
+ function writeBase(root, base) {
232
+ mkdirSync2(join2(root, ".tobos"), { recursive: true });
233
+ writeFileSync2(join2(root, BASE), `${JSON.stringify(base, null, 2)}
234
+ `);
259
235
  }
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`;
236
+ var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
237
+ function held(path) {
238
+ const parts = path.split("/");
239
+ return parts.every((part) => part !== "" && part !== "." && part !== ".." && !part.includes("\\")) && // Any case: a disk that ignores it would write `.TOBOS/` over the copy's own `.tobos/`.
240
+ !NOT_THE_DECK.has(parts[0].toLowerCase()) && !parts.includes(".DS_Store");
264
241
  }
265
- function credentialConfig(server) {
266
- return [
267
- "-c",
268
- `credential.${server}.helper=`,
269
- "-c",
270
- `credential.${server}.helper=${credentialHelper()}`
271
- ];
242
+ function throughLink(root, path) {
243
+ let at = root;
244
+ for (const part of path.split("/")) {
245
+ at = join2(at, part);
246
+ try {
247
+ if (lstatSync(at).isSymbolicLink()) return true;
248
+ } catch {
249
+ return false;
250
+ }
251
+ }
252
+ return false;
272
253
  }
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")}`
254
+ function copyFiles(root) {
255
+ const files = /* @__PURE__ */ new Map();
256
+ const walk = (dir2) => {
257
+ for (const entry of readdirSync(dir2, { withFileTypes: true })) {
258
+ const path = join2(dir2, entry.name);
259
+ const name = relative(root, path).split(sep).join("/");
260
+ if (dir2 === root && NOT_THE_DECK.has(entry.name) || entry.name === ".DS_Store") continue;
261
+ if (entry.isDirectory()) walk(path);
262
+ else if (entry.isFile()) files.set(name, sha256(readFileSync2(path)));
263
+ }
281
264
  };
265
+ walk(root);
266
+ return files;
282
267
  }
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;
268
+ async function latest(deck, server) {
269
+ const response = await request(`/api/decks/${deck}/export`, { server });
270
+ if (!response.ok) throw failure(response, await response.json().catch(() => ({})));
271
+ const rev = response.headers.get("tobos-rev");
272
+ const files = unpackTar(new Uint8Array(await response.arrayBuffer()));
273
+ const media = parseMediaJson(textOf(files.get("media.json"))).media;
274
+ const hashes = new Map([...files].map(([path, bytes]) => [path, sha256(bytes)]));
275
+ for (const [name, entry] of Object.entries(media)) hashes.set(`media/${name}`, entry.hash);
276
+ return { rev, files, media, hashes };
277
+ }
278
+ var textOf = (bytes) => bytes ? Buffer.from(bytes).toString("utf8") : "{}";
279
+ async function mediaBytes(deck, server, hash) {
280
+ const response = await request(`/api/media/${hash}?deck=${deck}`, { server });
281
+ if (!response.ok) throw failure(response, await response.json().catch(() => ({})));
282
+ return new Uint8Array(await response.arrayBuffer());
283
+ }
284
+ async function pullInto(root, deck, server, base, { note, clone = false }) {
285
+ const now = await latest(deck, server);
286
+ const local = existsSync(root) ? copyFiles(root) : /* @__PURE__ */ new Map();
287
+ const was = new Map(Object.entries(base?.files ?? {}));
288
+ const next = new Map([...now.hashes].filter(([path]) => held(path)));
289
+ const changed = [];
290
+ const conflicts = [];
291
+ const fetched = /* @__PURE__ */ new Map();
292
+ const bytesOf = async (path, hash) => {
293
+ const file2 = now.files.get(path);
294
+ if (file2) return file2;
295
+ if (!fetched.has(hash))
296
+ fetched.set(hash, await mediaBytes(deck, server, hash).catch(() => null));
297
+ return fetched.get(hash);
298
+ };
299
+ const paths = /* @__PURE__ */ new Set([...was.keys(), ...next.keys(), ...local.keys()]);
300
+ for (const path of paths) {
301
+ if (!held(path)) continue;
302
+ const [b, s] = [was.get(path), next.get(path)];
303
+ const l = local.get(path);
304
+ if (s === l) continue;
305
+ const file2 = join2(root, ...path.split("/"));
306
+ if (throughLink(root, path)) {
307
+ note(`left ${path} as it is: a link in this copy leads to it`);
308
+ if (b === void 0) next.delete(path);
309
+ else next.set(path, b);
310
+ continue;
311
+ }
312
+ const fresh = !base || l === b || clone && path.startsWith("media/") && l === void 0;
313
+ if (!fresh && s === b) continue;
314
+ if (fresh) {
315
+ if (s === void 0) rmSync(file2, { force: true });
316
+ else {
317
+ const bytes = await bytesOf(path, s);
318
+ if (!bytes) {
319
+ note(`couldn't fetch ${path}: the server may have lost it; a later pull tries again`);
320
+ if (l === void 0 || b === void 0) next.delete(path);
321
+ else next.set(path, b);
322
+ continue;
323
+ }
324
+ write2(file2, bytes);
325
+ }
326
+ changed.push(path);
327
+ continue;
328
+ }
329
+ const ours = l === void 0 ? void 0 : readFileSync2(file2);
330
+ const theirs = s === void 0 ? void 0 : await bytesOf(path, s);
331
+ const older = b === void 0 ? new Uint8Array() : await fileAt(deck, server, base.rev, path);
332
+ const texts = [older, ours, theirs].every((bytes) => bytes && isUtf8(bytes));
333
+ const merged = texts ? mergeText(textOf(older), textOf(ours), textOf(theirs)) : void 0;
334
+ if (merged !== void 0) write2(file2, Buffer.from(merged));
335
+ else if (texts) {
336
+ write2(file2, Buffer.from(marked(textOf(ours), textOf(theirs))));
337
+ note(`conflict: ${path}, between <<<<<<< and >>>>>>>`);
338
+ conflicts.push(path);
339
+ } else {
340
+ if (ours) write2(join2(root, ".tobos", "conflicts", ...path.split("/")), ours);
341
+ if (theirs) write2(file2, theirs);
342
+ else if (s === void 0) rmSync(file2, { force: true });
343
+ else {
344
+ if (b === void 0) next.delete(path);
345
+ else next.set(path, b);
346
+ continue;
347
+ }
348
+ note(
349
+ `conflict: ${path} changed on both sides; the server's is here now${ours ? `, yours in .tobos/conflicts/${path}` : ""}`
350
+ );
351
+ conflicts.push(path);
352
+ }
353
+ changed.push(path);
308
354
  }
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] };
355
+ writeBase(root, { deck, server, rev: now.rev, files: Object.fromEntries(next) });
356
+ return { rev: now.rev, changed, conflicts };
314
357
  }
315
- async function requireRemote(start) {
316
- const deck = await findDeck(start);
317
- if (!deck.id || !deck.server)
358
+ function marked(ours, theirs) {
359
+ const end = (text) => text.endsWith("\n") || text === "" ? text : `${text}
360
+ `;
361
+ return `<<<<<<< yours
362
+ ${end(ours)}=======
363
+ ${end(theirs)}>>>>>>> tobos
364
+ `;
365
+ }
366
+ async function fileAt(deck, server, rev, path) {
367
+ const response = await request(
368
+ `/api/decks/${deck}/files/${path.split("/").map(encodeURIComponent).join("/")}${rev ? `?rev=${rev}` : ""}`,
369
+ { server }
370
+ );
371
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : new Uint8Array();
372
+ }
373
+ function write2(file2, bytes) {
374
+ mkdirSync2(dirname(file2), { recursive: true });
375
+ writeFileSync2(file2, bytes);
376
+ }
377
+ async function baseOfClone(root) {
378
+ const run = (args) => execFileSync("git", args, {
379
+ cwd: root,
380
+ encoding: "utf8",
381
+ stdio: ["ignore", "pipe", "ignore"]
382
+ }).trim();
383
+ let remote;
384
+ let rev;
385
+ try {
386
+ remote = run(["remote", "get-url", "origin"]);
387
+ rev = run(["merge-base", "HEAD", "origin/main"]);
388
+ } catch {
318
389
  throw new CliError(
319
- `${deck.root} isn't linked to a deck on a Tobos server (no matching git remote "origin").`
390
+ `${root} is a clone from before, and git can't say what it was cloned from. Pull the deck afresh: \`tobos pull <id> <folder>\`.`
320
391
  );
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;
392
+ }
393
+ const match = /^(https?:\/\/[^/]+)\/git\/([0-9a-f-]{36})\.git$/.exec(remote);
394
+ if (!match) throw new CliError(`${root} is a clone of no Tobos deck (its remote is ${remote}).`);
395
+ const [, server, deck] = match;
396
+ const { files } = await api(
397
+ `/api/decks/${deck}/files?rev=${rev}`,
398
+ { server }
399
+ );
400
+ const hashes = Object.fromEntries(files.map((f) => [f.path, f.hash]));
401
+ const json = files.some((f) => f.path === "media.json") ? await fileAt(deck, server, rev, "media.json") : void 0;
402
+ const media = parseMediaJson(textOf(json)).media;
403
+ for (const [name, entry] of Object.entries(media)) hashes[`media/${name}`] = entry.hash;
404
+ return { deck, server, rev, files: hashes };
405
+ }
406
+ function changesOf(copy) {
407
+ const local = copyFiles(copy.root);
408
+ const changes = [];
409
+ for (const [path, hash] of local)
410
+ if (path !== "media.json" && copy.base.files[path] !== hash) changes.push({ path, hash });
411
+ for (const path of Object.keys(copy.base.files))
412
+ if (path !== "media.json" && !local.has(path)) changes.push({ path, hash: null });
413
+ return changes;
414
+ }
415
+ async function writeCopy(copy, message, { dry = false, note }) {
416
+ const { root, base } = copy;
417
+ const changes = changesOf(copy);
418
+ const files = /* @__PURE__ */ Object.create(null);
419
+ for (const { path, hash } of changes) {
420
+ if (hash === null) files[path] = null;
421
+ else if (path.startsWith("media/")) files[path] = { hash };
422
+ else {
423
+ const bytes = readFileSync2(join2(root, ...path.split("/")));
424
+ files[path] = isUtf8(bytes) ? Buffer.from(bytes).toString("utf8") : { base64: Buffer.from(bytes).toString("base64") };
425
+ }
426
+ }
427
+ const body = { base: base.rev, message, dry, files };
428
+ const uploaded = [];
429
+ for (let tries = 1; ; tries++) {
430
+ const response = await request(`/api/decks/${base.deck}/files`, {
431
+ method: "POST",
432
+ body,
433
+ server: base.server
434
+ });
435
+ const data = await response.json().catch(() => ({}));
436
+ if (response.ok) return { ...data, sent: changes.map((c) => c.path), uploaded };
437
+ if (data.error === "media" && tries <= 3) {
438
+ const media = [...copyFiles(root)].filter(([path]) => path.startsWith("media/"));
439
+ const sizes = new Map(
440
+ media.map(([path, hash]) => [hash, statSync(join2(root, ...path.split("/"))).size])
441
+ );
442
+ const total = [...sizes.values()].reduce((sum, size) => sum + size, 0);
443
+ const shows = Math.max(0, total - (data.elsewhere ?? 0));
444
+ for (const hash of data.hashes ?? []) {
445
+ const path = media.find(([, h]) => h === hash)?.[0];
446
+ if (!path)
447
+ throw new CliError(
448
+ `The server lacks a file of media/ (${hash}) that this copy doesn't have either: drop it on the deck's page again, or put it in media/ and push.`
449
+ );
450
+ note(`uploading ${path}`);
451
+ const put = await request(`/api/media/${hash}?deck=${base.deck}&shows=${shows}`, {
452
+ method: "PUT",
453
+ body: readFileSync2(join2(root, ...path.split("/"))),
454
+ // The type its name gives it, which the server keeps and serves it as.
455
+ contentType: mediaTypeOf(path.slice("media/".length)),
456
+ server: base.server
457
+ });
458
+ if (!put.ok)
459
+ throw failure(put, await put.json().catch(() => ({})), `Uploading ${path} failed: `);
460
+ uploaded.push(path);
461
+ }
462
+ continue;
463
+ }
464
+ if (data.error === "conflict")
465
+ throw new CliError(
466
+ `${data.message ?? "The deck changed meanwhile."}
467
+ Run \`tobos pull\`, which merges what changed, then push again.`,
468
+ EXIT.conflict,
469
+ { ...data, status: response.status }
470
+ );
471
+ if (data.error === "problems")
472
+ throw new CliError(
473
+ data.message ?? "The check refused it.",
474
+ EXIT.problems,
475
+ {
476
+ problems: data.problems,
477
+ status: response.status
478
+ }
479
+ );
480
+ throw failure(response, data);
481
+ }
327
482
  }
328
483
 
329
484
  // src/media.ts
330
485
  init_define_TOBOS_PRESENT_TYPES();
331
486
  init_define_TOBOS_SKILL();
332
487
  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
488
  var LOSSLESS = /\.(wav|aiff?|flac)$/i;
348
489
  var shellWord = (path) => /^[\w./-]+$/.test(path) ? path : `'${path.replaceAll("'", "'\\''")}'`;
349
490
  function sizeNote(name, size) {
@@ -357,110 +498,12 @@ function sizeNote(name, size) {
357
498
  return `note: media/${name} is ${mb} MB. Every viewer downloads it; size it for the stage.`;
358
499
  return void 0;
359
500
  }
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, elsewhere = 0 } = await api(
428
- "/api/media/missing",
429
- { body: { hashes, deck }, server }
430
- );
431
- const sizes = Object.fromEntries(Object.values(media).map((m) => [m.hash, m.size]));
432
- const shows = Object.values(sizes).reduce((sum, size) => sum + size, 0) - elsewhere;
433
- const uploaded = [];
434
- for (const hash of missing) {
435
- const [name, entry] = Object.entries(media).find(([, m]) => m.hash === hash);
436
- const path = mediaFile(root, name);
437
- if (!existsSync2(path))
438
- throw new CliError(
439
- `media/${name} is on a slide but not on this machine, and the server doesn't have it: put it in media/, then push again.`
440
- );
441
- note(`uploading media/${name} (${Math.round(entry.size / 1e3)} kB)`);
442
- const response = await request(`/api/media/${hash}?deck=${deck}&shows=${shows}`, {
443
- method: "PUT",
444
- body: Readable.toWeb(createReadStream(path)),
445
- contentType: entry.type,
446
- server
447
- });
448
- if (!response.ok)
449
- throw failure(
450
- response,
451
- await response.json().catch(() => ({})),
452
- `Uploading media/${name} failed: `
453
- );
454
- uploaded.push(name);
455
- }
456
- return uploaded;
457
- }
458
501
 
459
502
  // src/open-url.ts
460
503
  init_define_TOBOS_PRESENT_TYPES();
461
504
  init_define_TOBOS_SKILL();
462
505
  init_define_TOBOS_TOOLCHAIN();
463
- import { spawn as spawn2 } from "node:child_process";
506
+ import { spawn } from "node:child_process";
464
507
  async function openUrl(url) {
465
508
  if (!/^https?:$/.test(URL.parse(url)?.protocol ?? "")) return false;
466
509
  const env = process.env;
@@ -469,7 +512,7 @@ async function openUrl(url) {
469
512
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
470
513
  const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
471
514
  try {
472
- const child = spawn2(command, args, { stdio: "ignore", detached: true });
515
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
473
516
  child.unref();
474
517
  return await new Promise((resolve3) => {
475
518
  let timer;
@@ -491,14 +534,14 @@ init_define_TOBOS_PRESENT_TYPES();
491
534
  init_define_TOBOS_SKILL();
492
535
  init_define_TOBOS_TOOLCHAIN();
493
536
  import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
494
- import { join as join5 } from "node:path";
537
+ import { join as join3 } from "node:path";
495
538
  async function writeFormatGuide(root, server) {
496
- const dir2 = join5(root, ".tobos");
539
+ const dir2 = join3(root, ".tobos");
497
540
  mkdirSync3(dir2, { recursive: true });
498
541
  const format = await request("/api/format", { anonymous: true, server });
499
542
  if (!format.ok)
500
543
  throw new CliError(`Couldn't fetch the format guide from ${server} (${format.status}).`);
501
- writeFileSync3(join5(dir2, "FORMAT.md"), await format.text());
544
+ writeFileSync3(join3(dir2, "FORMAT.md"), await format.text());
502
545
  }
503
546
 
504
547
  // src/skill.ts
@@ -506,23 +549,23 @@ init_define_TOBOS_PRESENT_TYPES();
506
549
  init_define_TOBOS_SKILL();
507
550
  init_define_TOBOS_TOOLCHAIN();
508
551
  import {
509
- existsSync as existsSync3,
552
+ existsSync as existsSync2,
510
553
  mkdirSync as mkdirSync4,
511
- readdirSync as readdirSync3,
512
- readFileSync as readFileSync4,
554
+ readdirSync as readdirSync2,
555
+ readFileSync as readFileSync3,
513
556
  renameSync as renameSync2,
514
- rmSync,
557
+ rmSync as rmSync2,
515
558
  writeFileSync as writeFileSync4
516
559
  } from "node:fs";
517
560
  import { homedir as homedir2 } from "node:os";
518
- import { dirname as dirname2, join as join6 } from "node:path";
561
+ import { dirname as dirname2, join as join4 } from "node:path";
519
562
  var SKILL_NAME = "tobos-present";
520
563
  function readTree(root) {
521
564
  const files = {};
522
- for (const entry of readdirSync3(root, { recursive: true, withFileTypes: true }))
565
+ for (const entry of readdirSync2(root, { recursive: true, withFileTypes: true }))
523
566
  if (entry.isFile()) {
524
- const path = join6(entry.parentPath, entry.name);
525
- files[path.slice(root.length).replace(/^[\\/]/, "").split("\\").join("/")] = readFileSync4(path, "utf8");
567
+ const path = join4(entry.parentPath, entry.name);
568
+ files[path.slice(root.length).replace(/^[\\/]/, "").split("\\").join("/")] = readFileSync3(path, "utf8");
526
569
  }
527
570
  return files;
528
571
  }
@@ -534,35 +577,35 @@ function targets() {
534
577
  const home = homedir2();
535
578
  return [
536
579
  {
537
- dir: join6(process.env.CLAUDE_CONFIG_DIR || join6(home, ".claude"), "skills", SKILL_NAME),
580
+ dir: join4(process.env.CLAUDE_CONFIG_DIR || join4(home, ".claude"), "skills", SKILL_NAME),
538
581
  harnesses: ["Claude Code", "OpenCode", "Cursor", "GitHub Copilot", "Goose"]
539
582
  },
540
583
  {
541
- dir: join6(home, ".agents", "skills", SKILL_NAME),
584
+ dir: join4(home, ".agents", "skills", SKILL_NAME),
542
585
  harnesses: ["Codex", "OpenCode", "Cursor", "Gemini CLI", "GitHub Copilot", "Amp"]
543
586
  }
544
587
  ];
545
588
  }
546
- function write2(dir2, files, version) {
589
+ function write3(dir2, files, version) {
547
590
  const next = `${dir2}.next-${process.pid}`;
548
591
  for (const [path, text] of Object.entries(files)) {
549
- mkdirSync4(dirname2(join6(next, path)), { recursive: true });
550
- writeFileSync4(join6(next, path), text);
592
+ mkdirSync4(dirname2(join4(next, path)), { recursive: true });
593
+ writeFileSync4(join4(next, path), text);
551
594
  }
552
- writeFileSync4(join6(next, "VERSION"), `${version}
595
+ writeFileSync4(join4(next, "VERSION"), `${version}
553
596
  `);
554
- rmSync(dir2, { recursive: true, force: true });
597
+ rmSync2(dir2, { recursive: true, force: true });
555
598
  try {
556
599
  renameSync2(next, dir2);
557
600
  } catch (error) {
558
- rmSync(next, { recursive: true, force: true });
559
- if (!existsSync3(join6(dir2, "VERSION"))) throw error;
601
+ rmSync2(next, { recursive: true, force: true });
602
+ if (!existsSync2(join4(dir2, "VERSION"))) throw error;
560
603
  }
561
604
  }
562
605
  var refusedCodes = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS"]);
563
606
  function place(target, files, version) {
564
607
  try {
565
- write2(target.dir, files, version);
608
+ write3(target.dir, files, version);
566
609
  return { ...target, action: "installed" };
567
610
  } catch (error) {
568
611
  const code = error.code;
@@ -577,51 +620,105 @@ function install(options = {}) {
577
620
  }
578
621
  function refresh(options = {}) {
579
622
  const version = options.version ?? VERSION;
580
- 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");
623
+ return targets().filter((t) => existsSync2(join4(t.dir, "SKILL.md")) && newer(version, installed(t.dir))).map((t) => place(t, options.files ?? bundled(), version)).filter((r) => r.action === "refused");
581
624
  }
582
625
  function installed(dir2) {
583
626
  try {
584
- return readFileSync4(join6(dir2, "VERSION"), "utf8").trim();
627
+ return readFileSync3(join4(dir2, "VERSION"), "utf8").trim();
585
628
  } catch {
586
629
  return "0.0.0";
587
630
  }
588
631
  }
589
632
 
590
633
  // src/commands.ts
591
- var TERMS_NOTICE = "If the address is new, using the code accepts https://tobos.ai/terms.";
634
+ var LOGIN_WAIT_MS = 9e4;
592
635
  async function login(out, args) {
593
636
  const server = (args.values.server || settings().server).replace(/\/$/, "");
594
- const client = `the tobos CLI on ${hostname()}`;
595
- const email = args.positionals[0]?.trim().toLowerCase();
596
- const code = args.values.code;
597
- if (!code) {
598
- if (!email)
599
- throw new CliError(
600
- "Log in with the e-mail address of the person you work for: `tobos login <email>`."
637
+ const kept = settings().device;
638
+ let device = kept && kept.server === server && Date.parse(kept.expires) > Date.now() ? kept : void 0;
639
+ let opened = false;
640
+ if (!device) {
641
+ const started = await api("/oauth/device", {
642
+ anonymous: true,
643
+ server,
644
+ body: { label: `the tobos CLI on ${hostname()}` }
645
+ });
646
+ device = {
647
+ server,
648
+ deviceCode: started.device_code,
649
+ userCode: started.user_code,
650
+ url: started.verification_uri_complete,
651
+ interval: started.interval,
652
+ expires: new Date(Date.now() + started.expires_in * 1e3).toISOString()
653
+ };
654
+ save({ server, device });
655
+ opened = await openUrl(device.url);
656
+ if (!opened) {
657
+ out.result(
658
+ { waiting: true, url: device.url, code: device.userCode, next: "tobos login" },
659
+ () => `Give the person this address, to open where they like, a phone too: they log in there and approve this machine (a first login signs them up, and accepts https://tobos.ai/terms).
660
+
661
+ ${device.url}
662
+
663
+ The page shows the code ${device.userCode}. Once they approved it, run \`tobos login\` again.`
601
664
  );
602
- await api("/api/login", { anonymous: true, server, body: { email, client } });
603
- save({ server, pending: email });
665
+ process.exitCode = EXIT.auth;
666
+ return;
667
+ }
668
+ out.note(`Opened ${device.url} in the browser: approve the code ${device.userCode} there.`);
669
+ }
670
+ const token = await waitForApproval(device, (m) => out.note(m));
671
+ if (!token) {
604
672
  out.result(
605
- { sent: email, next: "tobos login --code <code>", terms: TERMS_NOTICE },
606
- () => `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:
673
+ { waiting: true, url: device.url, code: device.userCode, next: "tobos login" },
674
+ () => [
675
+ `Not approved yet. The person approves this machine at
607
676
 
608
- tobos login --code <code>`
677
+ ${device.url}`,
678
+ `where the page shows the code ${device.userCode}. Then run \`tobos login\` again.`
679
+ ].join("\n\n")
609
680
  );
681
+ process.exitCode = EXIT.auth;
610
682
  return;
611
683
  }
612
- const address = email ?? settings().pending;
613
- if (!address)
614
- throw new CliError("Which address got the code? `tobos login <email> --code <code>`.");
615
- const { token } = await api("/api/login/verify", {
616
- anonymous: true,
617
- server,
618
- body: { email: address, code, client }
619
- });
620
- save({ server, token, pending: void 0 });
684
+ save({ server, token, device: void 0 });
621
685
  const me = await api("/api/me", { server });
622
686
  save({ email: me.email });
623
687
  out.result({ email: me.email, server }, () => `Logged in as ${me.email}.`);
624
688
  }
689
+ async function waitForApproval(device, note) {
690
+ const until = Date.now() + LOGIN_WAIT_MS;
691
+ let interval = device.interval * 1e3;
692
+ note(`waiting for the person to approve ${device.userCode}\u2026`);
693
+ while (Date.now() < until) {
694
+ const response = await request("/oauth/token", {
695
+ anonymous: true,
696
+ server: device.server,
697
+ body: {
698
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
699
+ device_code: device.deviceCode
700
+ }
701
+ });
702
+ const answer = await response.json().catch(() => ({}));
703
+ if (answer.access_token) return answer.access_token;
704
+ if (answer.error === "slow_down") interval += 5e3;
705
+ else if (answer.error === "access_denied") {
706
+ save({ device: void 0 });
707
+ throw new CliError("The person chose not to connect this machine.", EXIT.auth);
708
+ } else if (answer.error === "expired_token" || answer.error === "invalid_grant") {
709
+ save({ device: void 0 });
710
+ throw new CliError(
711
+ "The code expired before the person approved it. Run `tobos login` again for a new one.",
712
+ EXIT.auth
713
+ );
714
+ } else if (answer.error !== "authorization_pending")
715
+ throw new CliError(
716
+ `${device.server} answered ${response.status} rather than whether the person approved. Run \`tobos login\` again: it waits on the same code.`
717
+ );
718
+ await new Promise((done) => setTimeout(done, interval));
719
+ }
720
+ return void 0;
721
+ }
625
722
  async function logout(out) {
626
723
  let revoked = false;
627
724
  if (settings().token)
@@ -651,11 +748,11 @@ function aboutDeck(d) {
651
748
  return notes.length ? ` (${notes.join("; ")})` : "";
652
749
  }
653
750
  var inFolder = (path) => path === "/" ? "" : `${path}/`;
654
- async function decks(out, args) {
751
+ async function ls(out, args) {
655
752
  const path = args.positionals[0];
656
753
  if (path !== void 0) {
657
754
  const listed = await api(
658
- `/api/drive?${new URLSearchParams({ path })}`
755
+ `/api/decks?${new URLSearchParams({ path })}`
659
756
  );
660
757
  out.result(
661
758
  listed,
@@ -663,10 +760,10 @@ async function decks(out, args) {
663
760
  );
664
761
  return;
665
762
  }
666
- const { decks: decks2 } = await api("/api/decks");
763
+ const { decks } = await api("/api/decks");
667
764
  out.result(
668
- { decks: decks2 },
669
- () => decks2.length === 0 ? 'No decks yet. `tobos new "Title"` starts one.' : decks2.map((d) => `${d.id} ${inFolder(d.folder ?? "/")}${d.title}${aboutDeck(d)}`).join("\n")
765
+ { decks },
766
+ () => decks.length === 0 ? 'No decks yet. `tobos new "Title"` starts one.' : decks.map((d) => `${d.id} ${inFolder(d.folder ?? "/")}${d.title}${aboutDeck(d)}`).join("\n")
670
767
  );
671
768
  }
672
769
  async function mv(out, args) {
@@ -685,32 +782,52 @@ async function mv(out, args) {
685
782
  });
686
783
  out.result(moved, () => `Moved ${plural(named.length, "item")} into ${moved.to}.`);
687
784
  }
688
- async function cloneInto(out, info, dir2) {
689
- const { server } = settings();
690
- if (existsSync4(dir2)) throw new CliError(`${dir2} already exists.`);
691
- out.note(`cloning ${info.title} into ${dir2}`);
692
- await gitOk([...credentialConfig(server), "clone", "--quiet", info.git, dir2], {
693
- env: authEnv(server)
694
- });
695
- await configureCredentials(dir2, server);
696
- return writeFormatGuide(dir2, server);
697
- }
698
- async function clone(out, args) {
785
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
786
+ async function pull(out, args) {
699
787
  const given = args.positionals[0];
700
- if (!given) throw new CliError("Which deck? `tobos clone <id>` (`tobos decks` lists them).");
701
- const id = parseId(given);
702
- const info = await api(`/api/decks/${id}`);
703
- const dir2 = resolve2(args.positionals[1] ?? id);
704
- await cloneInto(out, info, dir2);
705
- out.result(
706
- { ...info, dir: dir2 },
707
- () => `Cloned ${info.title} into ${relative2(process.cwd(), dir2) || "."}.
788
+ const note = (m) => out.note(m);
789
+ if (given) {
790
+ const id = parseId(given);
791
+ const info = await api(`/api/decks/${id}`);
792
+ const dir2 = resolve2(args.positionals[1] ?? id);
793
+ if (existsSync3(dir2)) throw new CliError(`${dir2} already exists.`);
794
+ await pullCopy(out, info, dir2);
795
+ out.result(
796
+ { ...info, dir: dir2 },
797
+ () => `Pulled ${info.title} into ${relative2(process.cwd(), dir2) || "."}.
708
798
  Read AGENTS.md there first. Preview: ${info.url}`
799
+ );
800
+ return;
801
+ }
802
+ const found = findCopy();
803
+ if (!found) throw new CliError("Not in a deck. `tobos pull <id>` makes a copy of one.");
804
+ const base = found.base ?? await baseOfClone(found.root);
805
+ const pulled = await pullInto(found.root, base.deck, base.server, base, {
806
+ note,
807
+ clone: !found.base
808
+ });
809
+ await writeFormatGuide(found.root, base.server);
810
+ out.result(
811
+ { id: base.deck, ...pulled },
812
+ () => [
813
+ `In step with the server (${pulled.rev?.slice(0, 7) ?? "no version yet"}): ${plural(pulled.changed.length, "file")} changed.`,
814
+ pulled.conflicts.length ? `${plural(pulled.conflicts.length, "conflict")}, between <<<<<<< and >>>>>>> in each: resolve them, then push.
815
+ ${pulled.conflicts.join("\n")}` : ""
816
+ ].filter(Boolean).join("\n")
709
817
  );
818
+ if (pulled.conflicts.length) process.exitCode = EXIT.conflict;
819
+ }
820
+ async function pullCopy(out, info, dir2) {
821
+ const { server } = settings();
822
+ out.note(`pulling ${info.title} into ${dir2}`);
823
+ await pullInto(dir2, info.id, server, void 0, { note: (m) => out.note(m) });
824
+ await writeFormatGuide(dir2, server);
710
825
  }
711
826
  async function create(out, args) {
712
827
  const title = args.positionals.join(" ").trim();
713
828
  if (!title) throw new CliError('What is it called? `tobos new "My talk"`.');
829
+ if (!args.values["no-pull"] && typeof args.values.dir === "string" && existsSync3(resolve2(args.values.dir)))
830
+ throw new CliError(`${resolve2(args.values.dir)} already exists.`);
714
831
  const info = await api("/api/decks", {
715
832
  body: {
716
833
  title,
@@ -719,240 +836,127 @@ async function create(out, args) {
719
836
  }
720
837
  });
721
838
  let dir2;
722
- if (!args.values["no-clone"]) {
839
+ if (!args.values["no-pull"]) {
723
840
  dir2 = resolve2(args.values.dir ?? info.id);
724
- await cloneInto(out, info, dir2);
841
+ if (existsSync3(dir2)) throw new CliError(`${dir2} already exists.`);
842
+ await pullCopy(out, info, dir2);
725
843
  }
726
844
  out.result(
727
845
  { ...info, dir: dir2 ?? null },
728
846
  () => [
729
847
  `Created ${info.title}: ${info.url}`,
730
- dir2 ? `Cloned into ${relative2(process.cwd(), dir2) || "."}. Read AGENTS.md there first.` : ""
848
+ dir2 ? `Pulled into ${relative2(process.cwd(), dir2) || "."}. Read AGENTS.md there first.` : ""
731
849
  ].filter(Boolean).join("\n")
732
850
  );
733
851
  }
734
- async function pull(out) {
735
- const deck = await requireRemote();
736
- const result = await git(
737
- [...credentialConfig(deck.server), "pull", "--ff-only", "--quiet", "origin", "main"],
738
- { cwd: deck.root, env: authEnv(deck.server) }
739
- );
740
- if (result.code !== 0)
741
- throw new CliError(
742
- `Couldn't fast-forward to the server's main:
743
- ${result.stderr.trim()}
744
- Commit or stash your changes, then merge with \`git pull\`.`
745
- );
746
- await writeFormatGuide(deck.root, deck.server);
747
- const rev = (await gitOk(["rev-parse", "HEAD"], { cwd: deck.root })).trim();
748
- out.result({ id: deck.id, rev }, () => `Up to date with the server (${rev.slice(0, 7)}).`);
749
- }
750
- async function pushedFiles(root) {
751
- try {
752
- const prefix = await git(["rev-parse", "--show-prefix"], { cwd: root });
753
- if (prefix.code !== 0 || prefix.stdout.trim() !== "") return void 0;
754
- const listed = await git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
755
- cwd: root
756
- });
757
- return listed.code === 0 ? listed.stdout.split("\0").filter(Boolean) : void 0;
758
- } catch {
759
- return void 0;
760
- }
761
- }
762
- async function runCheck(dir2) {
763
- const { buildDeck } = await import("./src-K2VVILG5.js");
764
- const started = performance.now();
765
- const files = await pushedFiles(dir2.root);
766
- const result = await buildDeck(directoryTree(dir2.root, files));
767
- return { ...result, files, ms: Math.round(performance.now() - started) };
768
- }
769
- var remoteLines = (stderr) => stderr.split("\n").filter((l) => l.startsWith("remote: ")).map((l) => l.slice(8));
770
- var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
771
- var MEDIA_LIMIT = /^tobos: (This deck belongs to .+, whose )?Tobos \w+ keeps .+ of media/;
772
- function pushFailure(output, remote) {
773
- const forThePerson = `${remote.map((line) => line.replace(/^tobos: /, "")).join("\n")}
774
- ${ASK_THE_PERSON}`;
775
- if (remote.some((line) => /^tobos: This (deck|template) is archived/.test(line)))
776
- return { message: forThePerson, exit: EXIT.limit, archived: true };
777
- if (remote.some((line) => MEDIA_LIMIT.test(line)))
778
- return { message: forThePerson, exit: EXIT.limit, limit: "media" };
779
- if (/non-fast-forward|fetch first/.test(output))
780
- return {
781
- message: "The server has changes you don't have. Run `tobos pull` (or `git pull`), then push again.",
782
- exit: EXIT.error
783
- };
784
- if (remote.some((line) => line.startsWith("tobos: rejected:")))
785
- return { message: `The server rejected the deck.
786
- ${remote.join("\n")}`, exit: EXIT.problems };
787
- if (/Authentication failed|returned error: 401|could not read Username/i.test(output))
788
- return {
789
- message: "The server didn't take your login. Run `tobos login` again, then push.",
790
- exit: EXIT.auth
791
- };
792
- if (/returned error: 403/.test(output))
793
- return {
794
- message: "You may not push to this deck: ask its owner to make you an editor.",
795
- exit: EXIT.error
796
- };
797
- if (remote.length > 0)
798
- return { message: `The server refused the push.
799
- ${remote.join("\n")}`, exit: EXIT.error };
800
- if (/Could not resolve host|Failed to connect|Connection refused|SSL|certificate/i.test(output))
801
- return {
802
- message: `Couldn't reach the server: nothing was pushed. Try again.
803
- ${output.trim()}`,
804
- exit: EXIT.error
805
- };
806
- if (/timed out|Connection reset|unexpected disconnect|RPC failed/i.test(output))
807
- return {
808
- 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.
809
- ${output.trim()}`,
810
- exit: EXIT.error
811
- };
812
- return { message: `The push failed.
813
- ${output.trim()}`, exit: EXIT.error };
814
- }
815
852
  function problemSummary(problems) {
816
853
  const errors = problems.filter((p) => p.severity === "error").length;
817
854
  return { errors, warnings: problems.length - errors };
818
855
  }
856
+ function noteSizes(out, root, paths) {
857
+ for (const path of paths.filter((p) => p.startsWith("media/"))) {
858
+ const file2 = join5(root, ...path.split("/"));
859
+ if (!existsSync3(file2)) continue;
860
+ const note = sizeNote(path.slice("media/".length), statSync2(file2).size);
861
+ if (note) out.note(note, true);
862
+ }
863
+ }
819
864
  async function check(out, args) {
820
- const deck = await findDeck(args.positionals[0]);
821
- await syncMediaJson(deck.root);
822
- const result = await runCheck(deck);
865
+ const copy = requireCopy(args.positionals[0]);
866
+ const started = performance.now();
867
+ const unchanged = changesOf(copy).length === 0;
868
+ const written = unchanged ? { problems: [] } : await writeCopy(copy, "Checked", { dry: true, note: (m) => out.note(m) }).catch(
869
+ (error) => {
870
+ if (error instanceof CliError && error.exit === EXIT.problems)
871
+ return { problems: error.extra.problems ?? [], refused: true };
872
+ throw error;
873
+ }
874
+ );
875
+ const problems = [...written.problems];
823
876
  if (args.values.types) {
824
- const { checkTypes } = await import("./types-BX3YXER7.js");
825
- const sent = result.files && new Set(result.files);
826
- result.problems.push(
827
- ...(await checkTypes(deck.root, (m) => out.note(m))).filter((p) => sent?.has(p.file) ?? true)
828
- );
877
+ const { checkTypes } = await import("./types-XT3SUHKX.js");
878
+ problems.push(...await checkTypes(copy.root, (m) => out.note(m)));
829
879
  }
830
- const { errors, warnings } = problemSummary(result.problems);
831
- const scenes = result.manifest?.chapters.reduce((n, c) => n + c.scenes.length, 0) ?? 0;
832
- const beats = result.manifest?.chapters.reduce(
833
- (n, c) => n + c.scenes.reduce((m, s) => m + s.beats.length, 0),
834
- 0
835
- ) ?? 0;
880
+ const { errors, warnings } = problemSummary(problems);
881
+ const ms = Math.round(performance.now() - started);
836
882
  out.result(
837
- { ok: errors === 0, errors, warnings, problems: result.problems, scenes, beats, ms: result.ms },
883
+ { ok: errors === 0, changed: !unchanged, errors, warnings, problems, ms },
838
884
  () => [
839
- formatProblems(result.problems),
840
- errors === 0 ? `\u2713 ${plural(scenes, "scene")}, ${plural(beats, "beat")}${warnings ? `, ${plural(warnings, "warning")}` : ""} (${result.ms} ms)` : `\u2717 ${plural(errors, "error")}${warnings ? `, ${plural(warnings, "warning")}` : ""}`
885
+ unchanged ? "Nothing changed in the copy: the version it is of passed the check when it landed." : "",
886
+ formatProblems(problems),
887
+ errors === 0 ? unchanged ? "" : `\u2713 The check takes it${warnings ? `, with ${plural(warnings, "warning")}` : ""} (${ms} ms)` : `\u2717 ${plural(errors, "error")}${warnings ? `, ${plural(warnings, "warning")}` : ""}`
841
888
  ].filter(Boolean).join("\n")
842
889
  );
843
890
  if (errors > 0) process.exitCode = EXIT.problems;
844
891
  }
845
- async function pushWorkingCopy(out, deck, message) {
846
- const { root, server } = deck;
847
- const { media } = await syncMediaJson(root);
848
- const result = await runCheck(deck);
849
- const { errors, warnings } = problemSummary(result.problems);
850
- if (errors > 0) return { ok: false, errors, warnings, problems: result.problems };
851
- const { mediaInUse } = await import("./src-K2VVILG5.js");
852
- const shown = result.manifest ? mediaInUse(result.manifest) : media;
853
- for (const [name, entry] of Object.entries(shown)) {
854
- const note = sizeNote(name, entry.size);
855
- if (note) out.note(note, true);
856
- }
857
- const uploaded = await uploadMedia(root, shown, server, deck.id, (m) => out.note(m));
858
- await gitOk(["add", "-A"], { cwd: root });
859
- const committed = (await gitOk(["diff", "--cached", "--name-only"], { cwd: root })).split("\n").filter(Boolean);
860
- for (const file2 of committed) out.note(` ${file2}`);
861
- if (committed.length > 0)
862
- await gitOk(["commit", "--quiet", "-m", message || "Update the deck"], {
863
- cwd: root,
864
- env: await identity(root)
865
- });
866
- out.note("pushing\u2026");
867
- const pushed = await git(
868
- [...credentialConfig(server), "push", "--porcelain", "origin", "HEAD:main"],
869
- { cwd: root, echo: !out.json, env: authEnv(server) }
892
+ async function pushCopy(out, copy, message) {
893
+ const changes = changesOf(copy);
894
+ if (changes.length === 0) return { pushed: false, rev: copy.base.rev, uploaded: [] };
895
+ noteSizes(
896
+ out,
897
+ copy.root,
898
+ changes.filter((c) => c.hash).map((c) => c.path)
870
899
  );
871
- const remote = remoteLines(pushed.stderr);
872
- if (pushed.code !== 0) {
873
- const { message: message2, exit, ...extra } = pushFailure(pushed.stdout + pushed.stderr, remote);
874
- throw new CliError(message2, exit, { remote, ...extra });
900
+ for (const { path, hash } of changes) out.note(` ${hash ? "" : "deleted "}${path}`);
901
+ out.note("pushing\u2026");
902
+ const written = await writeCopy(copy, message || "Update the deck", { note: (m) => out.note(m) });
903
+ try {
904
+ await pullInto(
905
+ copy.root,
906
+ copy.base.deck,
907
+ copy.base.server,
908
+ { ...copy.base, files: Object.fromEntries(copyFiles(copy.root)) },
909
+ { note: (m) => out.note(m) }
910
+ );
911
+ } catch (error) {
912
+ out.note(
913
+ `Pushed, but the copy couldn't take the version it made: run \`tobos pull\`. (${error.message})`,
914
+ true
915
+ );
875
916
  }
876
- const rev = (await gitOk(["rev-parse", "HEAD"], { cwd: root })).trim();
877
- return { ok: true, rev, committed, uploaded, warnings, remote };
917
+ return {
918
+ pushed: true,
919
+ rev: written.rev,
920
+ uploaded: written.uploaded,
921
+ problems: written.problems
922
+ };
878
923
  }
879
924
  async function push(out, args) {
880
- const deck = await requireRemote();
881
- const result = await pushWorkingCopy(out, deck, args.values.message);
882
- if (!result.ok) {
883
- out.result(
884
- { ...result, pushed: false },
885
- () => `${formatProblems(result.problems)}
886
- \u2717 Not pushed: ${plural(result.errors, "error")}. Fix them and push again.`
887
- );
888
- process.exitCode = EXIT.problems;
889
- return;
890
- }
891
- const url = `${deck.server}/${deck.id}`;
925
+ const copy = requireCopy();
926
+ const result = await pushCopy(out, copy, args.values.message);
927
+ const url = `${copy.base.server}/${copy.base.deck}`;
892
928
  out.result(
893
- { ...result, pushed: true, url },
894
- () => `\u2713 Pushed ${result.rev.slice(0, 7)}${result.uploaded.length ? ` with ${plural(result.uploaded.length, "media file")}` : ""}. Live at ${url}`
929
+ { ...result, url },
930
+ () => result.pushed ? `\u2713 Pushed ${result.rev?.slice(0, 7)}${result.uploaded.length ? ` with ${plural(result.uploaded.length, "media file")}` : ""}. Live at ${url}` : `Nothing to push: the copy is as the server has it. Live at ${url}`
895
931
  );
896
932
  }
897
933
  async function pushIfChanged(out, id, message) {
898
- const found = await findDeck().catch(() => void 0);
899
- if (!found?.server || found.id !== id) return { pushed: false, uploaded: [] };
900
- const deck = found;
901
- const dirty = (await gitOk(["status", "--porcelain"], { cwd: deck.root })).trim() !== "";
902
- const head = await git(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: deck.root });
903
- const remote = await git(["rev-parse", "--verify", "--quiet", "origin/main"], { cwd: deck.root });
904
- if (!dirty && head.stdout.trim() === remote.stdout.trim())
905
- return { pushed: false, uploaded: [] };
906
- const result = await pushWorkingCopy(out, deck, message);
907
- if (!result.ok)
908
- throw new CliError(
909
- `${formatProblems(result.problems)}
910
- \u2717 ${plural(result.errors, "error")} in your working copy. Fix them and try again.`,
911
- EXIT.problems,
912
- { problems: result.problems }
913
- );
914
- return { pushed: true, uploaded: result.uploaded };
915
- }
916
- async function identity(root) {
917
- if ((await git(["config", "user.email"], { cwd: root })).code === 0) return {};
918
- const who = settings().email;
919
- return {
920
- GIT_AUTHOR_NAME: who ?? "tobos",
921
- GIT_AUTHOR_EMAIL: who ?? "tobos@localhost",
922
- GIT_COMMITTER_NAME: who ?? "tobos",
923
- GIT_COMMITTER_EMAIL: who ?? "tobos@localhost"
924
- };
934
+ const found = findCopy();
935
+ if (!found?.base || found.base.deck !== id) return { pushed: false, uploaded: [] };
936
+ const { pushed, uploaded } = await pushCopy(out, found, message);
937
+ return { pushed, uploaded };
925
938
  }
926
939
  async function viewUrl(id, view, hours) {
927
940
  return api(`/api/decks/${id}/view`, { body: { view, hours } });
928
941
  }
929
942
  async function deckId(args) {
930
943
  if (typeof args.values.deck === "string") return parseId(args.values.deck);
931
- return (await requireRemote()).id;
944
+ return requireCopy().base.deck;
932
945
  }
933
946
  async function open(out, args) {
934
947
  const position = args.positionals[0];
935
- if (!position && typeof args.values.deck !== "string" && !await findDeck().catch(() => null))
936
- return openApp(out);
937
- const view = args.values.presenter ? "presenter" : void 0;
948
+ if (!position && typeof args.values.deck !== "string" && !findCopy()?.base) return openApp(out);
938
949
  const id = await deckId(args);
939
950
  const { pushed } = await pushIfChanged(out, id);
940
- const { url } = await viewUrl(id, view, 12);
951
+ const url = args.values.presenter ? (await viewUrl(id, "presenter", 12)).url : `${settings().server}/${id}`;
941
952
  const full = position ? `${url}#${position}` : url;
942
953
  const opened = !args.values.print && await openUrl(full);
943
954
  out.result({ url: full, opened, pushed }, () => full);
944
955
  }
945
956
  async function openApp(out) {
946
- const { url, code } = await api("/api/login/browser", {
947
- method: "POST"
948
- });
949
- const page = `${new URL(url).origin}/login`;
950
- out.result(
951
- { url, code, page },
952
- () => code ? `Open this link, or enter ${code} at ${page}. It works once, within 10 minutes.
953
- ${url}` : `Open this link. It works once, within 10 minutes.
954
- ${url}`
955
- );
957
+ const url = `${settings().server}/`;
958
+ const opened = await openUrl(url);
959
+ out.result({ url, opened }, () => url);
956
960
  }
957
961
  async function storyTx(id, ops) {
958
962
  try {
@@ -1014,44 +1018,12 @@ async function story(out, args) {
1014
1018
  }
1015
1019
  throw new CliError(`No \`tobos story ${action}\`: edit, add or delete.`);
1016
1020
  }
1017
- async function exportTarget(args, file2) {
1018
- if (args.values.out) return resolve2(args.values.out);
1019
- const deck = await findDeck().catch(() => void 0);
1020
- if (!deck) return resolve2(file2);
1021
- mkdirSync5(join7(deck.root, ".tobos", "exports"), { recursive: true });
1022
- return join7(deck.root, ".tobos", "exports", file2);
1023
- }
1024
- async function exportDeck(out, args) {
1025
- const kind = args.positionals[0];
1026
- if (kind !== "pdf") throw new CliError("Export what? `tobos export pdf`.");
1027
- const id = await deckId(args);
1028
- out.note("getting the PDF of the latest push\u2026");
1029
- const response = await request(`/api/decks/${id}/deck.pdf`);
1030
- if (!response.ok) {
1031
- const text = await response.text();
1032
- let data;
1033
- try {
1034
- data = JSON.parse(text);
1035
- } catch {
1036
- data = { error: text.slice(0, 500) };
1037
- }
1038
- throw failure(response, data);
1039
- }
1040
- const pdf = new Uint8Array(await response.arrayBuffer());
1041
- const target = await exportTarget(args, `${id}.pdf`);
1042
- mkdirSync5(dirname3(target), { recursive: true });
1043
- writeFileSync5(target, pdf);
1044
- const pages = Buffer.from(pdf).toString("latin1").match(/\/Type\s*\/Page(?![s\w])/g)?.length ?? 0;
1045
- out.result(
1046
- { file: target, pages },
1047
- () => `Wrote ${relative2(process.cwd(), target)} (${pages} pages).`
1048
- );
1049
- }
1050
1021
  async function render(out, args) {
1051
- const { renderBeats } = await import("./render-C7UKAYCT.js");
1052
- const deck = await findDeck().catch(() => void 0);
1022
+ const { renderBeats } = await import("./render-RISSGSJN.js");
1023
+ const copy = findCopy();
1024
+ const deck = copy?.base ? { id: copy.base.deck, root: copy.root } : void 0;
1053
1025
  const id = typeof args.values.deck === "string" ? parseId(args.values.deck) : deck?.id;
1054
- if (!id) throw new CliError("Run this inside a cloned deck, or pass --deck <id>.");
1026
+ if (!id) throw new CliError("Run this inside a deck you pulled, or pass --deck <id>.");
1055
1027
  const { pushed, uploaded } = await pushIfChanged(out, id, args.values.message);
1056
1028
  const view = await viewUrl(id, "render");
1057
1029
  const { url } = view;
@@ -1073,7 +1045,7 @@ async function render(out, args) {
1073
1045
  } else targets2.push(...scene.beats.map((b) => `${scene.id}/${b}`));
1074
1046
  }
1075
1047
  const root = deck?.id === id ? deck.root : ".";
1076
- const dir2 = resolve2(args.values.out ?? join7(root, ".tobos", "render"));
1048
+ const dir2 = resolve2(args.values.out ?? join5(root, ".tobos", "render"));
1077
1049
  const { files, errors } = await renderBeats(url, targets2, {
1078
1050
  dir: dir2,
1079
1051
  film: Boolean(args.values.film),
@@ -1111,37 +1083,17 @@ async function skill(out, args) {
1111
1083
  ].join("\n")
1112
1084
  );
1113
1085
  }
1114
- async function credential(args) {
1115
- if (args.positionals[0] !== "get") return;
1116
- const input = readFileSync5(0, "utf8");
1117
- const fields = Object.fromEntries(
1118
- input.split("\n").filter((l) => l.includes("=")).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)])
1119
- );
1120
- let stored;
1121
- try {
1122
- stored = settings();
1123
- } catch (error) {
1124
- process.stderr.write(`tobos: ${error.message}
1125
- `);
1126
- return;
1127
- }
1128
- const { server, token } = stored;
1129
- const target = new URL(server);
1130
- if (!token || fields.host !== target.host || `${fields.protocol}:` !== target.protocol) return;
1131
- process.stdout.write(`username=tobos
1132
- password=${token}
1133
- `);
1134
- }
1135
1086
 
1136
1087
  // src/main.ts
1137
1088
  var HELP = `tobos ${VERSION}: the command line of Tobos, the office suite your coding agent works in.
1138
1089
 
1139
1090
  Account
1140
- tobos login <email> [--server URL] e-mail a login code to the person (signs them up if new)
1141
- tobos login --code <code> finish: the code they read from the mail
1091
+ tobos login [--server URL] connect this machine: prints an address for the
1092
+ person to open and approve (logging in, or signing
1093
+ up, there); run it again once they did
1142
1094
  tobos logout forget this machine's token
1143
1095
  tobos whoami who you are, on which server
1144
- tobos decks [/path] your decks and templates, by id, each in its folder,
1096
+ tobos ls [/path] your decks and templates, by id, each in its folder,
1145
1097
  and those shared with you; an archived one is
1146
1098
  read-only. With a path: what that folder holds,
1147
1099
  its folders, then its decks
@@ -1150,26 +1102,27 @@ Folders (your decks and templates in a tree; a deck by its id or title, a folder
1150
1102
  tobos mv <deck or /folder>\u2026 </path> move them into that folder, made if there is none;
1151
1103
  a folder a move empties goes
1152
1104
 
1153
- Working on a deck
1154
- tobos new "Title" [--dir dir] [--no-clone] create a deck and clone it here, into ./<id>
1155
- (or into dir; --no-clone: only create it)
1156
- tobos clone <id> [dir] clone a deck, with the agent pack
1157
- tobos pull get the latest pushes and the format guide
1158
- tobos check [--types] compile and check the deck, offline (~1 s);
1159
- --types: TypeScript too (installs a checker once)
1160
- tobos push [-m "what changed"] upload media, commit, push; the server checks it
1105
+ Working on a deck (a working copy: no git; the server keeps the versions)
1106
+ tobos new "Title" [--dir dir] [--no-pull] create a deck and pull it here, into ./<id>
1107
+ (or into dir; --no-pull: only create it)
1108
+ tobos pull <id> [dir] a working copy of a deck, with the agent pack
1109
+ tobos pull the latest version into the copy, merged with your
1110
+ changes; a conflict is left between <<<<<<< and
1111
+ >>>>>>> to resolve; and the format guide
1112
+ tobos check [--types] the server's check of your changes; nothing lands;
1113
+ --types: TypeScript too, here (installs a checker once)
1114
+ tobos push [-m "what changed"] your changes as one version, media uploaded; the
1115
+ server checks it, and it goes live
1161
1116
 
1162
1117
  Looking at it (from the working copy, render and open push what changed first; with --deck <id>,
1163
1118
  from anywhere)
1164
1119
  tobos render scene/beat | scene | --all PNGs of beats, for you to look at
1165
1120
  [--film] [--frames 6] [--out dir] --film: frames through the animation
1166
1121
  [--scale 2] [-m "what changed"] --scale: pixels per stage pixel; -m: for the push
1167
- tobos open [scene/beat] [--presenter] the deck in a browser (prints the URL, which opens once)
1168
- [--print] --print: print the URL only, open nothing
1169
- tobos open outside a deck: a link, or its code for /login,
1170
- that logs a browser in once; show the person both
1171
- tobos export pdf [--out file] the deck's PDF, as its page and its link give it:
1172
- a page per scene at its last beat, no polls
1122
+ tobos open [scene/beat] [--presenter] the deck's page in a browser (--presenter: a
1123
+ [--print] presenter's link, which opens once); --print: print
1124
+ the URL only, open nothing
1125
+ tobos open outside a deck: the person's decks, in Tobos
1173
1126
 
1174
1127
  The story (what the speaker says, held by the server; a scene mentioned: [Title](scene:<id>),
1175
1128
  a beat: [Title](scene:<id>/<beat>))
@@ -1186,13 +1139,14 @@ The skill (what your harness reads to know Tobos without this help)
1186
1139
 
1187
1140
  Templates (decks people start from: a new deck copies a template's master/)
1188
1141
  tobos new "Title" --from <id> start a deck from that template (default: Tobos
1189
- simple; \`tobos decks\` lists the person's own)
1142
+ simple; \`tobos ls\` lists the person's own)
1190
1143
  tobos new "Our brand" --template a new template: a copy of Tobos simple (or of --from)
1191
1144
 
1192
1145
  Every command takes --json and then prints one JSON object.
1193
- Exit codes: 0 ok, 1 error, 2 the deck has problems, 3 not logged in, 4 the story changed
1194
- meanwhile (the reply has the paragraph as it is now: anchor on that and try again), 5 a plan's
1195
- limit or an archived deck: the person decides what to do, so show them the message and wait.
1146
+ Exit codes: 0 ok, 1 error, 2 the deck has problems, 3 not logged in (or not yet approved), 4 a conflict: someone
1147
+ changed the same lines (pull, resolve, push again; for the story, the reply has the paragraph as
1148
+ it is now), 5 a plan's limit or an archived deck: the person decides what to do, so show them the
1149
+ message and wait.
1196
1150
  `;
1197
1151
  var COMMON = {
1198
1152
  json: { type: "boolean" },
@@ -1201,22 +1155,21 @@ var COMMON = {
1201
1155
  var TABLE = {
1202
1156
  login: {
1203
1157
  run: login,
1204
- options: { server: { type: "string" }, code: { type: "string" } }
1158
+ options: { server: { type: "string" } }
1205
1159
  },
1206
1160
  logout: { run: logout },
1207
1161
  whoami: { run: whoami },
1208
- decks: { run: decks },
1162
+ ls: { run: ls },
1209
1163
  new: {
1210
1164
  run: create,
1211
1165
  options: {
1212
1166
  dir: { type: "string" },
1213
- "no-clone": { type: "boolean" },
1167
+ "no-pull": { type: "boolean" },
1214
1168
  from: { type: "string" },
1215
1169
  template: { type: "boolean" }
1216
1170
  }
1217
1171
  },
1218
1172
  mv: { run: mv },
1219
- clone: { run: clone },
1220
1173
  pull: { run: pull },
1221
1174
  check: { run: check, options: { types: { type: "boolean" } } },
1222
1175
  push: { run: push, options: { message: { type: "string", short: "m" } } },
@@ -1228,13 +1181,6 @@ var TABLE = {
1228
1181
  print: { type: "boolean" }
1229
1182
  }
1230
1183
  },
1231
- export: {
1232
- run: exportDeck,
1233
- options: {
1234
- out: { type: "string" },
1235
- deck: { type: "string" }
1236
- }
1237
- },
1238
1184
  skill: { run: skill },
1239
1185
  story: {
1240
1186
  run: story,
@@ -1264,10 +1210,6 @@ async function main(argv) {
1264
1210
  `);
1265
1211
  return;
1266
1212
  }
1267
- if (name === "credential") {
1268
- await credential({ positionals: rest, values: {} });
1269
- return;
1270
- }
1271
1213
  const command = TABLE[name];
1272
1214
  const json = rest.includes("--json");
1273
1215
  const out = createOutput(json);