Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
executable file
·2273 lines (2226 loc) · 142 KB
/
Copy pathserver.mjs
File metadata and controls
executable file
·2273 lines (2226 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/* PinDeck: local server.
pindeck [deck-dir | deck.html] [--port 5180] [--provider claude|codex] [--model <name>] [--asset-root <dir>] (or: node server.mjs ...)
- serves the editor UI and the deck (with a bridge script injected in edit mode)
- pushes file changes to the browser (server-sent events) for live reload
- runs one long-lived backend process for the chat sidebar
- snapshots files around every assistant turn for diffs and undo
- answers `cli.mjs layout|shot|slides|pdf|pdf-figure` for the assistant's self-checks, exports and PDF figures
- exports the deck as a PDF handout or a PDF presentation (build steps on separate pages)
- stores figures and audio attached to chat messages in <deck>/figures/ for the assistant to use, and attached
PDFs (papers, reports, figures) in ~/.pindeck-v4, outside the deck
- imports slides from PowerPoint files in the deck's own layouts
Listens on 127.0.0.1 only; the editor, the deck and every API call need the per-run token (a login
cookie in the browser, a header for the CLI).
Runtime files (chat, screenshots, backups) live in ~/.pindeck-v4, never in the deck or the package. */
import http from "node:http";
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { spawn, execFile, execFileSync } from "node:child_process";
import { fileURLToPath, pathToFileURL } from "node:url";
import { assignEids, parse, findSlides, slideSelector, deckSize, setStyles, getInner, getOuter, setInner, insertAfter, removeElement, deleteTarget, fileRefs, insertSlide, moveSlide, getNotes, setNotes, setAttr, elementEnd, decode } from "./lib/eids.mjs";
import { unifiedDiff } from "./lib/diff.mjs";
import { ClaudeSession } from "./lib/claude.mjs";
import { CodexSession } from "./lib/codex.mjs";
import { createDeckTools } from "./lib/agent-tools.mjs";
import { PROVIDERS, migrateSettings, selectModel, handoverSummary, curateModels } from "./lib/models.mjs";
import { formatLayout, formatPin } from "./lib/layout.mjs";
import { printLayout, printPdf, chromeReason, ROOT_ARGS, PDF_HEAD_TAG, PDF_PAGE_TAG } from "./lib/pdf.mjs";
import { readPptx } from "./lib/pptx.mjs";
import { exportPdf as pptxToPdf, renderJobs, renderAvailable, pdfInfo } from "./lib/pptx-render.mjs";
import { buildImport, planSlides } from "./lib/pptx-import.mjs";
import { isSupportedPlatform, detectCapabilities, publicCapabilities, capabilityPrompt, parsePort, cliCommand, useCliCommand, cliRefusal, findExecutable } from "./lib/capabilities.mjs";
import { unsupportedMessage } from "./lib/frameworks.mjs";
import { readInstructions } from "./lib/instructions.mjs";
import { writeAtomic, sameContent, revision, scanFiles, scanChanges } from "./lib/deck-files.mjs";
import { deckTarget, homeDir, homeWarning } from "./lib/deck-target.mjs";
import { listDecks, linkProblem } from "./lib/deck-list.mjs";
import { assetRoots } from "./lib/asset-roots.mjs";
import { registerServer, printLogin, alive } from "./lib/servers.mjs";
import { goodHost, presentHost, LOGIN_PAGE, createLogin, openOnEnter } from "./lib/login.mjs";
import { USAGE } from "./lib/usage.mjs";
import { indexDeck, commentFromPin, locate, loadReview, saveReview, packet, request as commentsRequest, reviewFiles } from "./lib/review.mjs";
/* ---- Config ------------------------------------------------------------------ */
/* Started by the front (pindeck, front.mjs) for one of the decks it serves: the front logs browsers in and
prints the links; this server tells it its address over IPC. */
const FRONT = !!process.env.PINDECK_FRONT && !!process.send;
const EDITOR_DIR = path.dirname(fileURLToPath(import.meta.url));
const VERSION = JSON.parse(fs.readFileSync(path.join(EDITOR_DIR, "package.json"), "utf8")).version;
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) { console.log(USAGE); process.exit(0); }
const opt = (name, dflt) => { const i = argv.indexOf(name); return i >= 0 ? argv.splice(i, 2)[1] : dflt; };
const portArg = opt("--port", process.env.PORT || 5180);
const assetArgs = [];
for (let a; (a = opt("--asset-root")) !== undefined;) assetArgs.push(a);
let PORT = parsePort(portArg); // the port actually bound once listening (--port 0 picks a free one)
if (PORT === null) { console.error(`Invalid port "${portArg}": use a number from 1 to 65535.\n\n${USAGE}`); process.exit(2); }
if (!isSupportedPlatform(process.platform)) {
const { showPlatformNotice } = await import("./lib/platform-notice.mjs");
await showPlatformNotice(PORT);
process.exit(0);
}
const LOGIN = argv[0] === "login";
if (LOGIN) argv.shift();
const PROVIDER = opt("--provider", "");
const MODEL = opt("--model", "");
if (process.env.CLAUDE_MODEL && !LOGIN && !FRONT) // PinDeck 2 read it; behind the front, the front says so
console.warn(`CLAUDE_MODEL is not used by PinDeck 3: choose the model in the editor's model menu, or start with --model ${process.env.CLAUDE_MODEL}.`);
/* The deck: a file (talk.html), or a folder, which means its index.html (see lib/deck-target.mjs) */
const { dir: DECK_DIR, file: DECK_FILE, named: NAMED, name: DECK_NAME, key: deckKey, source: SOURCE } = deckTarget(argv[0] || process.cwd());
/* A Quarto deck (SOURCE: talk.qmd): DECK_FILE is what Quarto renders from it, build output. The assistant edits
the sources; PinDeck renders after every change (see Quarto below) and adds its element ids to the output. */
const OUTPUTS = SOURCE ? [DECK_FILE, DECK_FILE.replace(/\.html$/i, "_files"), ".quarto"] : [];
const isOutput = (rel) => OUTPUTS.some((o) => rel === o || rel.startsWith(o + "/"));
const EDITABLE = SOURCE ? [SOURCE, DECK_FILE] : [DECK_FILE, "theme.css"]; // both backends may edit these (a Quarto deck: its source)
/* A Quarto deck's format extensions (_extensions/[<org>/]<name>/, e.g. Ocean) carry their own brand.css and vendor/ */
function extensionBrands() {
try {
return fs.readdirSync(path.join(DECK_DIR, "_extensions"), { recursive: true }).map((f) => String(f).split(path.sep).join("/"))
.filter((f) => /(^|\/)brand\.css$/.test(f) && !f.includes("vendor/")).map((f) => `_extensions/${f}`);
} catch { return []; }
}
const BRANDS = SOURCE ? extensionBrands() : [];
const LOCKED = ["brand.css", ...BRANDS]; // never, enforced twice
const HOME_DIR = homeDir();
const STATE_DIR = path.join(HOME_DIR, "decks", deckKey);
const SHOT_DIR = path.join(STATE_DIR, "shots");
const SHOT_NAME = /^[\w-][\w.-]*\.png$/; // a file name in SHOT_DIR, as the editor may ask for it
const PDF_DIR = path.join(STATE_DIR, "attachments"); // attached PDFs: reading material, not part of the deck
/* pindeck login: a new one-time login link from the PinDeck that serves the deck (see lib/servers.mjs) */
if (LOGIN) await printLogin(HOME_DIR, argv[0] ? deckTarget(argv[0]) : null);
const TOKEN = crypto.randomBytes(16).toString("hex");
/* The deck's pages are untrusted content: a deck (or a template, or a script the assistant wrote) must not
reach the API, the chat or other decks. They are served with a sandbox policy, which gives them an origin
of their own (no cookie, no token, no access to the editor page), under /v/<VIEW_TOKEN>/: a path that
lets them load their own files, and nothing else. */
const VIEW = `/v/${crypto.randomBytes(16).toString("hex")}`;
const SANDBOX = "sandbox allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads allow-presentation";
let ORIGIN = `http://127.0.0.1:${PORT}`; // set again from the bound port once listening
const CLI_REL = path.relative(DECK_DIR, path.join(EDITOR_DIR, "cli.mjs")).split(path.sep).join("/");
const CLI_CMD = cliCommand(CLI_REL);
const CAPS = detectCapabilities();
/* ---- Quarto ----------------------------------------------------------------------------------------
`quarto render <source>` makes DECK_FILE. One render at a time; a change to a source while one runs renders
again when it ends. What the assistant checks (shot, layout, slides, pdf) waits for the render, so it always
sees its last edit. Quarto's own errors go to the chat, and to the assistant. */
const QUARTO = SOURCE ? findExecutable(process.env.QUARTO_BIN || "quarto") : null;
const RENDER_TIMEOUT = 180000;
const SOURCE_FILE = /\.(qmd|md|scss|css|ya?ml|bib|csl|lua|js|html?|png|jpe?g|gif|svg|webp|pdf|mp4|wav|mp3)$/i; // what a render reads
/* Quarto's message, without colours and its JavaScript stack: what says what is wrong in the source */
const quartoError = (stderr) => `Quarto could not render ${SOURCE}:\n` + String(stderr).replace(/\x1b\[[0-9;]*m/g, "")
.split(/\nStack trace:|\n\s+at /)[0].trim().split("\n").slice(-25).join("\n");
function renderSync() {
console.log(`Rendering ${SOURCE} with Quarto…`);
try { execFileSync(QUARTO.path, ["render", SOURCE], { cwd: DECK_DIR, stdio: ["ignore", "ignore", "pipe"], timeout: RENDER_TIMEOUT }); }
catch (e) { return quartoError(e.stderr || e.message); }
return fs.existsSync(path.join(DECK_DIR, DECK_FILE)) ? null
: `Quarto rendered ${SOURCE}, but not to ${DECK_FILE} beside it (an output-dir in _quarto.yml?). PinDeck needs the HTML next to its source.`;
}
let startRenderError = null; // a failed render at start with an older output: PinDeck opens that, the assistant fixes the source
if (SOURCE && !LOGIN) {
if (!QUARTO.path) { console.error(`${SOURCE} is a Quarto deck, and Quarto is not installed (${QUARTO.reason}). Install it from https://quarto.org.`); process.exit(1); }
const mtime = (f) => { try { return fs.statSync(path.join(DECK_DIR, f)).mtimeMs; } catch { return 0; } };
if (mtime(DECK_FILE) < mtime(SOURCE)) {
const failed = renderSync();
if (failed && !fs.existsSync(path.join(DECK_DIR, DECK_FILE))) { console.error(failed); process.exit(1); }
if (failed) { console.error(failed + `\nOpening the last render of ${SOURCE}.`); startRenderError = failed; }
}
}
/* Checks before anything is written: a deck that cannot be opened or saved is left exactly as it is. */
function checkDeck() {
const file = path.join(DECK_DIR, DECK_FILE);
if (!fs.existsSync(file)) return `No ${DECK_FILE} in ${DECK_DIR}`;
const linked = linkProblem(DECK_DIR, DECK_FILE);
if (linked) return linked + " Nothing was changed.";
try { fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK); }
catch { return `${file} cannot be read and written (check its permissions).`; }
// saving replaces the file through a temporary file next to it, so the folder must be writable too
try { fs.accessSync(DECK_DIR, fs.constants.W_OK); }
catch { return `${DECK_DIR} is not writable: PinDeck saves the deck through a temporary file in that folder.`; }
return null;
}
const homeNote = !FRONT && homeWarning(HOME_DIR); // behind the front, the front says it
if (homeNote) console.warn(homeNote);
const deckProblem = checkDeck();
if (deckProblem) {
console.error(`${deckProblem}\n\n${USAGE}`);
process.exit(1);
}
// reveal.js, or a deck that names its slides: another framework's deck is left exactly as it is (no ids, no state)
const deckAtStart = fs.readFileSync(path.join(DECK_DIR, DECK_FILE), "utf8");
const ENDS_HTML = /<\/html>\s*$/i;
const frameworkProblem = unsupportedMessage(deckAtStart, DECK_FILE);
if (frameworkProblem) {
console.error(frameworkProblem);
process.exit(1);
}
/* One PinDeck per deck: two deck servers on one state folder would overwrite each other's chat and undo. The
one that has the deck open holds STATE_DIR/open.json; a second one says where the deck is open and stops,
before anything is written. */
const LOCK_FILE = path.join(STATE_DIR, "open.json");
const lockHolder = () => {
try { const o = JSON.parse(fs.readFileSync(LOCK_FILE, "utf8")); return o.pid !== process.pid && alive(o.pid) ? o : null; } catch { return null; }
};
const openElsewhere = (o) => `${path.join(DECK_DIR, DECK_FILE)} is open in another PinDeck already (${o.url}, process ${o.pid}). ` +
`Use that one, or stop it first: two PinDecks on one deck would overwrite each other's chat and undo.`;
if (lockHolder()) { console.error(openElsewhere(lockHolder())); process.exit(1); }
/* Runtime files hold the token, the chat and attachments: private to the user. Written only after the
port is bound (see Start), so a failed start leaves no state behind. The server file (lib/servers.mjs) lets
pindeck login and cli.mjs find this server; behind the front, login goes to the front (a deck server's port
is no use to a browser behind a tunnel), and the assistant's CLI gets this server's address. */
let unregister = () => {};
function writeServerInfo() {
for (const d of [HOME_DIR, STATE_DIR, SHOT_DIR]) fs.mkdirSync(d, { recursive: true, mode: 0o700 });
const lock = JSON.stringify({ pid: process.pid, url: process.env.PINDECK_FRONT_URL || ORIGIN });
try { fs.writeFileSync(LOCK_FILE, lock, { flag: "wx", mode: 0o600 }); }
catch (e) {
if (e.code !== "EEXIST") throw e;
const other = lockHolder();
if (other) throw Object.assign(new Error(openElsewhere(other)), { plain: true });
fs.writeFileSync(LOCK_FILE, lock, { mode: 0o600 }); // left by a PinDeck that is gone
}
unregister = registerServer(HOME_DIR, { url: ORIGIN, token: TOKEN, key: deckKey, deckDir: DECK_DIR, deckFile: DECK_FILE,
...(FRONT ? { behindFront: true } : {}) });
}
/* On exit: only our own files, never those of a PinDeck started since for this or another deck. */
function removeServerInfo() {
unregister();
try { if (JSON.parse(fs.readFileSync(LOCK_FILE, "utf8")).pid === process.pid) fs.rmSync(LOCK_FILE, { force: true }); } catch {}
}
/* ---- Small helpers --------------------------------------------------------------- */
const MIME = { html: "text/html; charset=utf-8", css: "text/css; charset=utf-8", js: "text/javascript; charset=utf-8",
mjs: "text/javascript; charset=utf-8", json: "application/json", svg: "image/svg+xml", png: "image/png",
jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", ico: "image/x-icon",
woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", wav: "audio/wav", mp3: "audio/mpeg",
ogg: "audio/ogg", oga: "audio/ogg", opus: "audio/ogg", m4a: "audio/mp4", aac: "audio/aac", flac: "audio/flac",
mp4: "video/mp4", webm: "video/webm", mov: "video/quicktime", pdf: "application/pdf", md: "text/plain; charset=utf-8" };
const hash = (s) => crypto.createHash("sha1").update(s).digest("hex");
const readDeck = (f) => { try { return fs.readFileSync(path.join(DECK_DIR, f), "utf8"); } catch { return null; } };
/* A deck made without reveal.js names its slides with <meta name="pindeck:slides"> (null for reveal.js) and
their size with <meta name="pindeck:size">. Read from the deck as it is now, so a changed tag counts from
the next headless run or Claude session. Headless Chrome opens such a deck at the slide size, so a
screenshot is the slide itself. */
function deckSlides() {
const tree = parse(readDeck(DECK_FILE) || "");
const selector = slideSelector(tree);
return { selector, size: (selector && deckSize(tree)) || { width: 1280, height: 720 } };
}
/* Why the deck no longer names slides PinDeck can use (a tag changed while PinDeck runs), or null: the
start-up check's message, which the editor shows and Claude is told */
function deckProblemNow() {
const html = readDeck(DECK_FILE);
return (html != null && unsupportedMessage(html, DECK_FILE)?.replace(/ Nothing was changed\.$/, "")) || null;
}
let deckNow = { selector: deckSlides().selector, problem: null }; // for the editor; kept current by scheduleFlush
const ourWrites = new Map(); // file -> { hash, manual } of what we wrote, to tell our writes from others
function writeDeck(f, content, manual = false) {
ourWrites.set(f, { hash: hash(content), manual });
writeAtomic(path.join(DECK_DIR, f), content);
}
/* A file PinDeck itself writes or deletes in the deck folder (an upload, a picture, an export, a file Undo
brings back or removes) must be there once symlinks are followed: a figures/ or export/ that links
elsewhere is not written through, as serving refuses to read through it. */
function deckPath(rel) {
const abs = path.join(DECK_DIR, rel);
let p = abs;
while (!fs.existsSync(p) && path.dirname(p) !== p) p = path.dirname(p);
const real = realOr(p), deck = realOr(DECK_DIR);
if (real !== deck && !real.startsWith(deck + path.sep))
throw Object.assign(new Error(`${rel} leads out of the deck folder (through a symlink): PinDeck does not write or delete there.`), { status: 409 });
return abs;
}
const removeDeckFile = (rel) => fs.rmSync(deckPath(rel), { force: true });
/* Other files PinDeck writes into the deck (uploads, imported pictures, undo/redo of deleted files) */
function writeDeckFile(rel, data, manual = true) {
const abs = deckPath(rel);
state.turn?.touched.add(rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
ourWrites.set(rel, { hash: hash(data.toString("utf8")), manual }); // manual: no slide reload for a new file
writeAtomic(abs, data);
}
const snapshot = (files) => Object.fromEntries(files.map((f) => [f, readDeck(f)]));
/* A change (a Claude turn or a hand edit) keeps each file it touched as it was before and after: text as
a string, or as a Buffer from a scan of the whole deck (null: the file did not exist). */
const changeFiles = (t) => [...new Set([...Object.keys(t.before), ...Object.keys(t.after)])];
const isText = (v) => v == null || typeof v === "string" || !v.includes(0);
const asText = (v) => (v == null ? "" : String(v));
const isAs = (rel, v) => sameContent(path.join(DECK_DIR, rel), v ?? null);
function putDeckFile(rel, v) { // undo and redo: back to v (null: remove the file)
if (v == null) return removeDeckFile(rel);
fs.mkdirSync(path.dirname(path.join(DECK_DIR, rel)), { recursive: true });
writeDeck(rel, v);
}
function fileChange(rel, before, after) {
if (!isText(before) || !isText(after)) return { file: rel, added: 0, removed: 0, binary: true };
const d = unifiedDiff(asText(before), asText(after), rel);
return { file: rel, added: d.added, removed: d.removed };
}
const fileDiff = (rel, before, after) => (!isText(before) || !isText(after)
? `Binary file ${rel} ${before == null ? "added" : after == null ? "deleted" : "changed"}`
: unifiedDiff(asText(before), asText(after), rel).text);
/* The revision of the editable files: sent with every API answer, checked on the editor's changes */
const deckRev = () => revision(DECK_DIR, EDITABLE);
const json = (res, code, obj) => {
res.writeHead(code, { "content-type": "application/json", "x-deck-rev": deckRev() });
res.end(JSON.stringify(obj));
};
/* A change from the editor made on files that have changed since it loaded them: refused (409), nothing
written. The editor keeps the user's text and reloads. Requests without a revision (older tabs, the
notes sent while the tab closes) are not checked. */
function staleEdit(res, b) {
if (b.rev == null || b.rev === deckRev()) return false;
json(res, 409, { code: "stale", rev: deckRev(),
error: "The deck changed outside PinDeck since this slide was shown, so your change was not saved. The slide has been reloaded." });
return true;
}
const text = (res, code, s) => { res.writeHead(code, { "content-type": "text/plain; charset=utf-8" }); res.end(s); };
async function body(req) {
let s = "";
req.setEncoding("utf8");
for await (const c of req) { s += c; if (s.length > 5e6) throw new Error("body too large"); }
return s ? JSON.parse(s) : {};
}
function safeJoin(base, rel) {
const p = path.resolve(base, "." + path.posix.normalize("/" + decodeURIComponent(rel)));
return p === base || p.startsWith(base + path.sep) ? p : null;
}
/* ---- Server-sent events ------------------------------------------------------------ */
const clients = new Set();
function broadcast(type, data) {
const msg = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of clients) res.write(msg);
}
setInterval(() => { for (const res of clients) res.write(": ping\n\n"); }, 20000);
/* ---- Element ids ----------------------------------------------------------------------- */
let backedUp = false;
function runEidPass() {
const html = readDeck(DECK_FILE);
if (html == null) return { changed: false, assigned: [] }; // being replaced by another program: next time
const r = assignEids(html);
if (r.changed) {
if (!backedUp) {
const ts = new Date().toISOString().replace(/[:.]/g, "-");
fs.mkdirSync(path.join(STATE_DIR, "backups"), { recursive: true, mode: 0o700 });
fs.writeFileSync(path.join(STATE_DIR, "backups", `index-${ts}.html`), html, { mode: 0o600 });
backedUp = true;
}
writeDeck(DECK_FILE, r.html);
refreshGit();
}
return r;
}
/* With the "pindeck-ids" git filter (`node cli.mjs git-setup`) git strips the ids from commits and
diffs. But git lists a file as modified whenever its size differs from what it recorded, without
comparing contents, and adding ids changes the size. So after adding ids PinDeck re-records the file
in git (`git add`), but only when that changes nothing: its content without ids must equal what git
already has staged. A file with real edits is left alone and shows as modified, as it should. */
let gitFilter = null; // null: not checked yet
const git = (args, cb) => execFile("git", ["-C", DECK_DIR, ...args], { encoding: "utf8" }, (err, out) => cb(err, (out || "").trim()));
function refreshGit() {
// another git command (an IDE's `git status`) may hold the index lock: try again a few times, checking afresh
const run = (tries = 3) => git(["hash-object", `--path=${DECK_FILE}`, DECK_FILE], (e1, cleaned) => {
if (e1 || !cleaned) return;
git(["ls-files", "-s", "--", DECK_FILE], (e2, entry) => {
const staged = entry.split(/\s+/)[1];
if (!e2 && staged === cleaned) git(["add", "--", DECK_FILE], (e3) => { if (e3 && tries > 1) setTimeout(() => run(tries - 1), 300); });
});
});
if (gitFilter === null) {
git(["check-attr", "filter", "--", DECK_FILE], (err, out) => {
gitFilter = !err && /: filter: pindeck-ids$/.test(out);
if (gitFilter) run();
});
} else if (gitFilter) run();
}
function slideList() {
const html = readDeck(DECK_FILE);
return findSlides(parse(html)).map((s, index) => ({ index, eid: s.attrs["data-eid"]?.value || null, id: s.attrs.id?.value || null }));
}
function resolveSlide(spec) {
const slides = slideList();
if (!spec || spec === "current") return slides[state.current?.index ?? 0] || slides[0];
if (/^\d+$/.test(spec)) return slides[+spec - 1];
// or the slide's own id attribute (Quarto's heading anchor, which stays when the title changes)
return slides.find((s) => s.eid === spec) || slides.find((s) => s.id === spec) || slides.find((s) => s.eid && s.eid.startsWith(spec));
}
/* ---- Headless Chrome (screenshots, and layout when no editor tab is open) --------------- */
const CHROME = CAPS.chromePath; // null when Chrome features are unavailable (see lib/capabilities.mjs)
/* Headless Chrome on macOS often lingers long after it has written its output, so we
watch the output and stop Chrome as soon as `done(stdout, stderr)` says we have it. */
let chromeSeq = 0;
/* The page gets the window's size too. Chrome lays it out about 87 px shorter than the window (room for
a toolbar it does not draw) and grows it only for the screenshot itself, too late for some versions
to lay the slide out again, so shot and dump lay the deck out for this size (see bridge.js). As vw and
vh, not width and height: reveal.js reads the page address's query as configuration, so those would
replace the deck's own slide size. */
function sized(url, size) {
const u = new URL(url);
u.searchParams.set("vw", size.width);
u.searchParams.set("vh", size.height);
return u.href;
}
function chrome(args, done, signal) {
if (!CHROME) return Promise.reject(new Error(`Screenshots are not available: ${CAPS.screenshot.reason}.`));
return new Promise((resolve, reject) => {
// a profile per run: concurrent runs must not share one
const profile = path.join(STATE_DIR, "chrome", `p${process.pid}-${++chromeSeq}`);
const { size } = deckSlides();
const proc = spawn(CHROME, ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", ...ROOT_ARGS,
"--no-default-browser-check", "--disable-extensions", "--mute-audio", `--user-data-dir=${profile}`,
`--window-size=${size.width},${size.height}`, "--force-device-scale-factor=1", "--virtual-time-budget=5000",
...args.map((a) => a.startsWith(ORIGIN + "/") ? chromeStart(profile, sized(a, size)) : a)]);
let out = "", err = "", finished = false;
const finish = (fn, v) => {
if (finished) return;
finished = true;
clearTimeout(timer);
proc.kill("SIGKILL");
setTimeout(() => fs.rm(profile, { recursive: true, force: true }, () => {}), 500);
fn(v);
};
const check = () => { if (done(out, err)) finish(resolve, out); };
proc.stdout.on("data", (d) => { out += d; check(); });
proc.stderr.on("data", (d) => { err += d; check(); });
proc.on("error", (e) => finish(reject, e));
// "close", not "exit": at exit Chrome's last output (the line saying the file is written) may still be unread
proc.on("close", () => (done(out, err) ? finish(resolve, out)
: finish(reject, new Error(`Chrome exited without output${chromeReason(err) ? `: ${chromeReason(err)}` : "."}`))));
const timer = setTimeout(() => finish(reject, new Error("Chrome timed out.")), 25000);
signal?.addEventListener("abort", () => finish(reject, new Error("Stopped.")), { once: true });
});
}
const deckUrl = (mode, params = {}) =>
`${ORIGIN}${VIEW}${DECK_PAGE}?` + new URLSearchParams({ editor: mode, showHiddenSlides: "true", ...params });
/* A screenshot of a slide with the pins of a message on it: those the message carries when the user asks for
one, those of the latest message when the assistant does (cli.mjs shot). Never pins the editor no longer
shows, or another tab's. */
async function takeShot(slide, pins = state.lastPins, signal) {
pins = pins.filter((p) => p.slide?.eid === slide.eid).map((p) => ({ n: p.n, eid: p.eid, at: p.at, point: p.point }));
const out = path.join(SHOT_DIR, `${slide.eid.replace(/[^\w-]/g, "_")}-${Date.now()}.png`);
await chrome([`--screenshot=${out}`, deckUrl("shot", { slide: slide.eid, pins: JSON.stringify(pins) })],
(_o, err) => /bytes written to file/.test(err) && fs.existsSync(out), signal);
if (!fs.existsSync(out)) throw new Error("Chrome did not write the screenshot.");
// keep the folder small
const old = fs.readdirSync(SHOT_DIR).map((f) => path.join(SHOT_DIR, f))
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs).slice(40);
old.forEach((f) => fs.rmSync(f, { force: true }));
return out;
}
async function measureHeadless(slide) {
const dom = await chrome(["--dump-dom", deckUrl("dump", { slide: slide.eid })], (o) => /<\/html>\s*$/i.test(o));
const m = /<script id="__editor_layout" type="application\/json">([\s\S]*?)<\/script>/.exec(dom);
if (!m) throw new Error("Headless layout measurement failed.");
const r = JSON.parse(m[1]);
if (r.error) throw new Error(r.error);
return r;
}
/* Measuring in the editor tab is fast and is exactly what the user sees. */
const pending = new Map();
let measureSeq = 0;
function measureInEditor(slide) {
if (!clients.size) return Promise.reject(new Error("no editor tab"));
const id = ++measureSeq;
broadcast("measure", { id, index: slide.index, eid: slide.eid });
return new Promise((resolve, reject) => {
const t = setTimeout(() => { pending.delete(id); reject(new Error("editor did not answer")); }, 8000);
pending.set(id, { resolve, reject, t });
});
}
const measure = (slide) => measureInEditor(slide).catch((e) => {
if (CAPS.headlessLayout.available) return measureHeadless(slide);
throw Object.assign(new Error(`Layout needs the editor open in a browser (${e.message}); ` +
`headless layout is not available: ${CAPS.headlessLayout.reason}.`), { status: 503 });
});
/* PDF export. handout: one page per slide, build steps in their final state.
presentation: one page per build step (a slide with two clicks gives three pages).
Files go to <deck>/export/. One export at a time. */
let exportQueue = Promise.resolve(), snapSeq = 0;
const snapshots = new Map(); // id -> static print layout, served next to the deck page as __pindeck-print-<id>.html
function exportPdf(kind, includeHidden = false) {
if (!CAPS.pdfExport.available) return Promise.reject(Object.assign(new Error(`PDF export is not available: ${CAPS.pdfExport.reason}.`), { status: 501 }));
const split = kind === "presentation";
const name = `${DECK_NAME}-${split ? "presentation" : "handout"}.pdf`;
const out = path.join(DECK_DIR, "export", name); // checked when the export runs (deckPath)
const profile = (step) => path.join(STATE_DIR, "chrome", `pdf-${process.pid}-${Date.now()}-${step}`);
const run = async () => {
deckPath(`export/${name}`);
fs.mkdirSync(path.dirname(out), { recursive: true });
const layoutProfile = profile("layout"), printProfile = profile("print");
const html = await printLayout(CHROME, chromeStart(layoutProfile,
`${ORIGIN}${VIEW}${DECK_PAGE}?editor=pdf&print-pdf&pdfSeparateFragments=${split}&showHiddenSlides=${!!includeHidden}`), layoutProfile);
const id = `${process.pid}-${++snapSeq}`;
snapshots.set(id, html);
try { await printPdf(CHROME, chromeStart(printProfile, `${ORIGIN}${VIEW}${DECK_BASE}__pindeck-print-${id}.html`), out, printProfile); }
finally { snapshots.delete(id); }
return { kind: split ? "presentation" : "handout", path: out, rel: path.relative(DECK_DIR, out),
url: `deck/export/${encodeURIComponent(name)}`, bytes: fs.statSync(out).size };
};
const job = exportQueue.then(run, run);
exportQueue = job.catch(() => {});
return job;
}
/* ---- Chat state and the selected backend session --------------------------------------------- */
const CHAT_FILE = path.join(STATE_DIR, "chat.json");
const state = {
chat: [], seq: 0, busy: false, model: MODEL || null, switching: false, preparing: null, sessionId: null, provider: "claude", handover: "", sessionArchive: [],
turns: [], redo: [], turn: null, notes: [], lastPins: [], current: null,
conversation: 1, // counts the conversations of this run: a new chat or another provider starts the next
uploads: new Set(), // files uploaded for the next message; removable until it is sent
pdfFigures: new Set(), // figures/ files written by pdf-figure, which it may overwrite
};
try {
const saved = JSON.parse(fs.readFileSync(CHAT_FILE, "utf8"));
Object.assign(state, { chat: saved.chat || [], seq: saved.seq || 0, sessionId: saved.sessionId || null, provider: saved.provider || "claude",
handover: saved.handover || "", sessionArchive: saved.sessionArchive || [], saved: saved.settings || null, hasChat: true });
} catch {}
/* Saved shortly after the last change, in one atomic write: overlapping writes could leave a broken file. */
let chatTimer = null;
function writeChat() {
clearTimeout(chatTimer);
chatTimer = null;
try {
writeAtomic(CHAT_FILE, JSON.stringify({ chat: state.chat.slice(-400), seq: state.seq, sessionId: state.sessionId,
provider: state.provider, handover: state.handover, sessionArchive: state.sessionArchive.slice(-50),
settings: deckSettings ?? undefined }));
} catch (e) { console.error(e.message); }
}
const saveChat = () => { chatTimer ??= setTimeout(writeChat, 100); };
function addEntry(entry) {
entry.id = ++state.seq;
entry.time = Date.now();
state.chat.push(entry);
broadcast("chat", entry);
saveChat();
return entry;
}
const liveTurns = () => state.turns.filter((t) => !t.undone);
const changeLabel = (t) => (t ? (t.kind === "manual" ? t.label : "AI change") : null);
/* Provider, model and effort belong to each deck, with its conversation: saved in its chat.json when chosen
in the menu, so another deck's choice never moves this deck's conversation to another backend. config.json
holds the last choice, which a new deck starts with, and each model's preferred effort. --provider and
--model apply to this run only. The v3 preview uses its own state directory so v2 can keep running. */
const CONFIG_FILE = path.join(HOME_DIR, "config.json");
const isObject = (o) => !!o && typeof o === "object" && !Array.isArray(o);
function readConfig(warn = false) {
try {
const c = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
if (isObject(c)) return c;
if (warn) console.warn(`${CONFIG_FILE} does not hold settings ({ ... }); using the defaults.`);
} catch (e) { if (warn && e.code !== "ENOENT") console.warn(`${CONFIG_FILE} is not valid JSON; using the defaults.`); }
return {};
}
const preferencesOf = (c) => Object.fromEntries(Object.entries(isObject(c.effortPreferences) ? c.effortPreferences : {}).filter(([, v]) => typeof v === "string"));
const fileConfig = readConfig(true);
let effortPreferences = preferencesOf(fileConfig);
const defaults = migrateSettings(fileConfig);
// the legacy single effort (v2): the preference of the model it was chosen for
if (fileConfig.effort && defaults.model) effortPreferences[`${defaults.provider}:${defaults.model}`] ??= defaults.effort;
let deckSettings = isObject(state.saved) && PROVIDERS.includes(state.saved.provider) ? migrateSettings(state.saved) : null;
const settings = deckSettings ? { ...deckSettings }
// a chat saved before decks kept their own settings: its provider, with that provider's default model
: state.hasChat && state.provider !== defaults.provider ? { provider: state.provider, model: state.provider === "claude" ? "sonnet" : "", effort: null }
: { ...defaults };
const ownSettings = { ...settings }; // without --provider and --model, which apply to this run only
const startNotices = []; // added to the chat once the port is bound (a failed start writes nothing)
if (PROVIDER) {
if (!PROVIDERS.includes(PROVIDER)) { console.error(`Unknown provider "${PROVIDER}": use claude or codex.\n\n${USAGE}`); process.exit(2); }
if (PROVIDER !== settings.provider) Object.assign(settings, { provider: PROVIDER, model: PROVIDER === "claude" ? "sonnet" : "", effort: null });
}
if (MODEL && MODEL !== settings.model) Object.assign(settings, { model: MODEL, effort: null }); // this run only, not saved
if (settings.effort == null) settings.effort = effortPreferences[`${settings.provider}:${settings.model}`] ?? null;
// A saved conversation belongs to its provider: --provider for another one starts a new conversation, and says so
if (state.provider !== settings.provider && (state.sessionId || state.chat.length)) {
if (state.sessionId) state.sessionArchive.push({ provider: state.provider, id: state.sessionId });
state.sessionId = null; state.handover = "";
const why = PROVIDER === settings.provider ? `for this run (--provider ${PROVIDER})` : "(this deck's own choice)";
startNotices.push({ kind: "notice", fresh: true, text: `Switched to ${providerName(settings.provider)} ${why} · New conversation.` });
}
state.provider = settings.provider;
/* Asset roots (--asset-root, and "assetRoots" in config.json): folders outside the deck whose files the
deck may use. The outermost one that contains the deck is served at /files/, with the deck page inside
it, so a relative path such as ../shared/style.css reaches its file. Every file served, from the deck
or from /files/, must really lie (after following symlinks) inside the deck folder or an asset root:
a symlink that leads anywhere else is refused. */
// on its own a missing one stops the start; behind the front, which lists decks only from roots that exist,
// one that is gone since the front started is left out with a warning, so the deck still opens
const { roots: ASSET_ROOTS, missing: missingRoots } = assetRoots(assetArgs, fileConfig);
for (const r of missingRoots) {
if (!FRONT) { console.error(`Asset root ${r} is not a folder.\n\n${USAGE}`); process.exit(2); }
console.warn(`Asset root ${r} is not a folder (any more): left out.`);
}
const within = (dir, p) => p === dir || p.startsWith(dir + path.sep);
const realOr = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
const SERVE_ROOT = ASSET_ROOTS.filter((r) => within(r, DECK_DIR)).sort((a, b) => a.length - b.length)[0] || null;
const ALLOWED_REAL = [DECK_DIR, ...ASSET_ROOTS].map(realOr);
const encPath = (rel) => rel.split(path.sep).filter(Boolean).map(encodeURIComponent).join("/");
/* The deck page's URL, and the folder URL its relative paths resolve against */
const DECK_PAGE = SERVE_ROOT ? `/files/${[encPath(path.relative(SERVE_ROOT, DECK_DIR)), encodeURIComponent(DECK_FILE)].filter(Boolean).join("/")}`
: `/deck/${encodeURIComponent(DECK_FILE)}`;
const DECK_BASE = DECK_PAGE.slice(0, DECK_PAGE.lastIndexOf("/") + 1);
/* A file to serve: inside its base by path, and inside the deck or an asset root once symlinks are
followed. null: refuse. A missing file passes, and is answered 404. */
function servable(base, rel) {
const f = safeJoin(base, rel);
if (!f) return null;
let real;
try { real = fs.realpathSync(f); } catch { return f; }
return ALLOWED_REAL.some((d) => within(d, real)) ? f : null;
}
let catalog = { claude: { models: [] }, codex: { models: [] } };
let session = null, starting = null;
const status = () => ({ busy: state.busy, switching: state.switching, preparing: !!state.preparing, model: state.model, sessionId: state.sessionId, settings: { ...settings },
running: !!session?.running, provider: settings.provider, models: catalog, deck: DECK_DIR, deckFile: DECK_FILE,
chrome: CAPS.screenshot.available, slideSelector: deckNow.selector, deckProblem: deckNow.problem,
capabilities: publicCapabilities(CAPS), rev: deckRev(), view: VIEW.slice(1) + "/",
undo: changeLabel(liveTurns().at(-1)), undoId: liveTurns().at(-1)?.id ?? null, redo: changeLabel(state.redo.at(-1)),
source: SOURCE, rendering: !!rendering, renderError });
/* Pushed to the editors on every change. The model lists (both providers' catalogs) go along only when they
changed since the last push: the editor keeps the last ones it got. */
let catalogSent = "";
const pushStatus = () => {
const st = status(), lists = JSON.stringify(catalog);
if (lists === catalogSent) delete st.models;
catalogSent = lists;
broadcast("status", st);
};
const systemPrompt = fs.readFileSync(path.join(EDITOR_DIR, "lib/system-prompt.md"), "utf8")
.replaceAll("{{CLI}}", CLI_CMD).replaceAll("{{DECK}}", DECK_FILE) + capabilityPrompt(CAPS, CLI_CMD) +
// a template's own notes usually say index.html; other decks may share this folder
(NAMED ? `\n\n## This deck's file\nThe slides are in ${DECK_FILE}. Where the deck's notes below say index.html, they mean ` +
`${DECK_FILE}. Other .html files in this folder are other decks: do not edit them.\n` : "") +
(ASSET_ROOTS.length ? `\n\n## Files outside the deck folder\nThe deck may use files in ${ASSET_ROOTS.join(", ")}: refer to ` +
`them with paths relative to ${DECK_FILE} (such as ../shared/style.css). You can read them; do not edit them, ` +
`other decks may use them too.\n` : "");
/* A Quarto deck: what to edit, and how its output relates to the source */
const quartoInstructions = () => SOURCE ? `\n\n## This deck is made with Quarto
${DECK_FILE} is rendered by Quarto from ${SOURCE}: it is build output, locked, and overwritten by every render. Make every ` +
`change in ${SOURCE} (Quarto Markdown: \`##\` headings start slides and become the slides' id attributes, \`::: {.notes}\` holds ` +
`speaker notes, \`::: {.incremental}\` and \`. . .\` make build steps, \`{ojs}\` cells are Observable JS; when you change a ` +
`slide's title, keep its id by adding \`{#<old id>}\` to the heading, so comments and links still find the slide), or in the files it uses ` +
`(its .scss theme, figures). Where these instructions say to edit ${DECK_FILE} or theme.css, edit ${SOURCE} or its stylesheet ` +
`instead. Pins and element ids (data-eid) name elements of the rendered HTML: read ${DECK_FILE} to see what they are, then ` +
`find the matching text in ${SOURCE}. PinDeck renders after every change you save; ${CLI_CMD} shot, layout and slides wait ` +
`for that render, and report Quarto's error if it fails. Interactive OJS output is drawn in the browser, so screenshots show it ` +
`only once its libraries have loaded.\n` + (BRANDS.length ? `The deck's look comes from a Quarto format extension (` +
BRANDS.map((b) => b.replace(/\/brand\.css$/, "/")).join(", ") + `): read its README.md for the slide layouts and classes. ` +
`Its brand.css and vendor/ are locked, like brand.css in an HTML deck; its theme.css takes the talk's own styles.\n` : "") : "";
/* For a deck made without reveal.js: what its slides are, from its selector as it is at each session start */
function slidesInstructions() {
const { selector } = deckSlides();
return selector ? `\n\n## Slides of this deck\nThis deck is not made with reveal.js: its slides are the elements matching the ` +
`CSS selector \`${selector}\` (<meta name="pindeck:slides">), and the deck's own script shows them. Where these ` +
`instructions say <section> or reveal.js, read an element matching that selector, and that script. A new slide is ` +
`a new such element next to the others; keep the pindeck meta tags. Hidden slides (data-visibility="hidden") are ` +
`left out of PinDeck's PDF exports; whether presenting skips them depends on the deck's script.\n` : "";
}
/* What Claude may never change, whatever the edit rules allow: the locked brand files, vendored libraries,
git's own files, and other decks in this folder (a named deck shares its folder with them). Deny rules
win over allow rules; a locked file changed anyway is restored after the turn (lock 2 in finishTurn). */
function lockedPaths() {
const { files, folders } = otherDecks();
return [...LOCKED, "vendor/**", ...BRANDS.map((b) => b.replace(/brand\.css$/, "vendor/**")), ".git", ".git/**", ".pindeck", ".pindeck/**", ...OUTPUTS.flatMap((o) => [o, `${o}/**`]), ...files, ...folders.map((f) => `${f}/**`)];
}
/* The other decks in this deck's folder: its other .html files, and the subfolders that hold a deck of their
own (as the deck menu lists them). Neither the assistant nor this deck's undo touches them. */
function otherDecks() {
let files = [];
try { files = fs.readdirSync(DECK_DIR).filter((f) => /\.html$/i.test(f) && f !== DECK_FILE); } catch {}
const folders = [...new Set(listDecks([DECK_DIR]).filter((d) => !d.problem && d.dir !== DECK_DIR)
.map((d) => path.relative(DECK_DIR, d.dir).split(path.sep).join("/")))];
return { files, folders };
}
const scanDeck = () => { const { files, folders } = otherDecks(); return scanFiles(DECK_DIR, { skip: [...files, ...folders, ...OUTPUTS] }); };
/* Decks that share a folder share its files (theme.css, figures/): while the assistant of one works, that of
another may change them too. Each deck server keeps the times of its turns in a file of its own under
turns/<folder>/; a turn that overlapped another deck's keeps only the files its own assistant said it wrote. */
const TURNS_DIR = path.join(HOME_DIR, "turns", hash(DECK_DIR).slice(0, 12));
const TURNS_FILE = path.join(TURNS_DIR, `${deckKey}.json`);
let turnTimes = []; // [{ start, end }] of this deck's recent turns
function logTurnTime(t) {
const now = Date.now();
turnTimes = turnTimes.filter((x) => x === t || (x.end ?? now) > now - 3600000).slice(-20);
if (!turnTimes.includes(t)) turnTimes.push(t);
try {
fs.mkdirSync(TURNS_DIR, { recursive: true, mode: 0o700 });
writeAtomic(TURNS_FILE, JSON.stringify({ deck: DECK_FILE === "index.html" ? path.basename(DECK_DIR) : DECK_FILE, pid: process.pid, turns: turnTimes }));
} catch (e) { console.error(e.message); }
}
/* The other decks whose assistant worked in this folder at some time since start: their names */
function othersWorkedSince(start) {
const now = Date.now(), names = [];
let files = [];
try { files = fs.readdirSync(TURNS_DIR).filter((f) => f.endsWith(".json") && f !== `${deckKey}.json`); } catch {}
for (const f of files) {
try {
const o = JSON.parse(fs.readFileSync(path.join(TURNS_DIR, f), "utf8"));
const running = alive(o.pid);
// a turn still open in a server that is gone ended when that server did, at the latest
if (o.turns.some((x) => (x.end ?? (running ? now : x.start)) >= start)) names.push(o.deck);
} catch {}
}
return names;
}
/* Claude Code loads no settings files (--setting-sources ""): an allow rule in the user's, the deck's
or a parent repo's settings would let Claude run more than PinDeck grants (and the user's hooks and
MCP servers have no place in a slide editor). That also skips CLAUDE.md files, so the deck's own go
into the system prompt instead, read afresh at each session start: CLAUDE.md and AGENTS.md (the name
other coding agents read), with their @path imports (lib/instructions.mjs). Parent folders' files are
not loaded; a deck imports shared rules explicitly. The CLI path written there becomes this server's
command (useCliCommand). */
function deckInstructions() {
return ["CLAUDE.md", "AGENTS.md"].map((name) => {
const s = readInstructions(path.join(DECK_DIR, name));
return s ? `\n\n## The deck's ${name}\n${useCliCommand(s, CLI_CMD)}\n` : "";
}).join("");
}
// a function: ORIGIN is known only once the port is bound
const agentEnv = () => ({ DECK_EDITOR_URL: ORIGIN, DECK_EDITOR_TOKEN: TOKEN });
const agentTools = createDeckTools({ deckDir: DECK_DIR, deckFile: DECK_FILE, readDirs: [SHOT_DIR, PDF_DIR, ...ASSET_ROOTS],
locked: lockedPaths, cliFile: path.join(EDITOR_DIR, "cli.mjs"), pdfTextFile: path.join(EDITOR_DIR, "lib/pdf-text.jxa.js"),
env: agentEnv });
const codexInstructions = () => systemPrompt.replace(/## Attached files[\s\S]*?## Hand edits/, `## Tools and attachments
Figures and audio are already saved under figures/. Keep their paths and use the deck's existing figure/audio patterns. Do not rename or move attachments.
Use pindeck_read for text files, images and PDF pages (supply page: 1, then further pages as needed).
Use pindeck_edit for exact replacements in ${DECK_FILE}, theme.css and the deck's other files, and pindeck_write to create a new file in the deck folder. Never change brand.css.
Use pindeck_command with separate command and args for layout, shot, slides, element (the HTML of data-eid ids), pdf, pdf-figure, resolve or reply.
Do not use shell commands, native file edits, or other tools to bypass these restrictions.
When context mentions Read, use pindeck_read. Read screenshots with pindeck_read.
Read README.md and the deck instructions below for conventions. Use layout after every visual change.
PDF tables should be reconstructed as HTML; pdf-figure renders figures. Audio is embedded by path.
## Hand edits`) + slidesInstructions() + quartoInstructions() + deckInstructions();
function makeSession(choice) {
let initial = null;
const options = {
cwd: DECK_DIR,
env: agentEnv,
onEvent: ev => {
if (ev.type === "system" && ev.subtype === "init") initial = ev;
if (session === agent) handleEvent(ev);
},
onExit: error => {
if (session !== agent) return;
if (state.turn) finishTurn({ error: error.message });
pushStatus();
},
};
/* Claude Code: any file in the deck folder (Edit rules cover Write too; Write is named as well, to be
explicit), PinDeck's own commands, never the locked paths. Deny rules win over allow rules. */
const agent = choice.provider === "codex" ? new CodexSession({ ...options, settings: choice,
instructions: codexInstructions(), tools: agentTools }) : new ClaudeSession({ ...options,
// a tool the rules do not allow comes to PinDeck (--permission-prompt-tool stdio), always refused: with the right command if it was the CLI
denyMessage: (r) => r?.tool_name === "Bash" ? cliRefusal(r.input?.command, CLI_CMD) : null,
args: () => ["--append-system-prompt", systemPrompt + slidesInstructions() + quartoInstructions() + deckInstructions(),
"--setting-sources", "", "--strict-mcp-config", "--safe-mode", "--disable-slash-commands", // no settings files, no MCP servers or connectors
"--permission-mode", "default", "--permission-prompt-tool", "stdio", "--tools", "Read,Glob,Grep,Edit,Write,Bash",
"--allowedTools", ...readRules(), "Edit(./**)", "Write(./**)",
...["layout", "shot", "slides", "element", "pdf", "pdf-figure", "resolve", "reply"].map(command => `Bash(${CLI_CMD} ${command}:*)`),
"--disallowedTools", ...lockedPaths().flatMap((f) => [`Edit(./${f})`, `Write(./${f})`]),
...(choice.model ? ["--model", choice.model] : []), ...(choice.effort ? ["--effort", choice.effort] : [])],
});
agent.initialEvent = () => initial;
return agent;
}
/* Claude reads what Codex's tools may read (agentTools' readDirs): the deck, screenshots, attached PDFs and
asset roots, each by its path and its real path ("//" starts an absolute path in a rule) */
function readRules() {
const dirs = [SHOT_DIR, PDF_DIR, ...ASSET_ROOTS].flatMap((d) => { try { return [d, fs.realpathSync(d)]; } catch { return [d]; } });
const globs = ["./**", ...new Set(dirs.map((d) => `/${d}/**`))];
return ["Read", "Glob", "Grep"].flatMap((tool) => globs.map((g) => `${tool}(${g})`));
}
const providerAvailable = (provider) => detectCapabilities()[provider];
/* Every backend process that is stopped is waited for on exit: the discovery helpers, the session a switch
replaced, the current one. */
const retiring = new Set(), discoveryAgents = new Set();
function retire(agent) {
if (!agent) return;
const stopped = agent.stop();
retiring.add(stopped);
stopped.finally(() => retiring.delete(stopped));
}
/* What each backend offers. Asking means starting a backend process, so it is done once per provider at a
time, and the answer is shared: through models.json in the state folder, for the other deck servers too,
for 10 minutes (Refresh models asks again). A message waits only for its own provider's list. */
const MODELS_FILE = path.join(HOME_DIR, "models.json"), MODELS_TTL = 10 * 60000;
const asking = {}; // provider -> promise of its discovery
function cachedModels() {
try {
const c = JSON.parse(fs.readFileSync(MODELS_FILE, "utf8"));
return Date.now() - c.time < MODELS_TTL && c.catalog && typeof c.catalog === "object" ? c.catalog : {};
} catch { return {}; }
}
function cacheModels() {
const ok = Object.fromEntries(Object.entries(catalog).filter(([, c]) => c.models.length && !c.error));
if (!Object.keys(ok).length) return;
try { writeAtomic(MODELS_FILE, JSON.stringify({ time: Date.now(), catalog: { ...cachedModels(), ...ok } })); } catch {}
}
function discoverProvider(provider) {
if (asking[provider]) return asking[provider];
asking[provider] = (async () => {
if (!providerAvailable(provider).available) { catalog[provider] = { models: [], error: providerAvailable(provider).reason }; return; }
const agent = makeSession({ provider, model: "", effort: null });
discoveryAgents.add(agent);
try {
if (provider === "codex") await agent.connect(); else await agent.start();
catalog[provider] = { models: curateModels(provider, agent.models || []), error: null };
} catch (e) { catalog[provider] = { models: [], error: e.message }; }
finally { discoveryAgents.delete(agent); retire(agent); }
})().finally(() => { delete asking[provider]; });
return asking[provider];
}
/* providers: which to ask; fresh: ask the backends even when another deck server asked lately */
async function discoverModels({ providers = ["claude", "codex"], fresh = false } = {}) {
const cached = fresh ? {} : cachedModels();
await Promise.all(providers.map((p) => {
if (cached[p]?.models?.length && providerAvailable(p).available) { catalog[p] = cached[p]; return null; }
return discoverProvider(p);
}));
cacheModels();
pushStatus();
return catalog;
}
/* The model and effort as they will be used, once the backend has said what it offers: a saved or given
model it does not offer gives way to its default model (and the chat says so), an effort the model does
not offer to the model's preferred or default one. Shown before the first message is sent. */
function settle() {
const { models, error } = catalog[settings.provider];
if (!models.length || error) return; // discovery failed: its error answers the next message
let model = models.find((m) => m.id === settings.model);
if (!model) {
model = models.find((m) => m.isDefault) || models.find((m) => m.curated) || models[0];
if (settings.model) addEntry({ kind: "notice", text: `The model "${settings.model}" is not available from ${providerName(settings.provider)} now: using ${model.label} instead.` });
Object.assign(settings, { model: model.id, effort: null });
}
if (!model.efforts.includes(settings.effort)) {
const preferred = effortPreferences[`${settings.provider}:${model.id}`];
settings.effort = model.efforts.includes(preferred) ? preferred : model.defaultEffort ?? null;
}
}
async function ensureSession() {
if (starting) return starting;
if (session?.running || quitting) return;
const available = providerAvailable(settings.provider);
if (!available.available) throw new Error(available.reason);
starting = (async () => {
if (!catalog[settings.provider].models.length) await discoverModels({ providers: [settings.provider] });
settle();
Object.assign(settings, selectModel(catalog, settings, {}));
// a deck without a choice of its own keeps the one its conversation starts with, not the next one another
// deck saves in config.json; a run-only --provider or --model is not kept
if (!deckSettings) {
deckSettings = PROVIDER || MODEL ? { ...ownSettings } : { provider: settings.provider, model: settings.model, effort: settings.effort };
saveChat();
}
const agent = makeSession({ ...settings });
session = agent;
try {
await agent.start(state.sessionId);
// the session's own start lists the models too: the freshest list there is
if (agent.models?.length) { catalog[settings.provider] = { models: curateModels(settings.provider, agent.models), error: null }; cacheModels(); }
if (session === agent) pushStatus();
}
catch (e) { retire(agent); throw e; }
})().finally(() => { starting = null; });
return starting;
}
function providerName(p) { return p === "codex" ? "OpenAI / ChatGPT" : "Claude"; }
/* config.json as it is now (another deck may have written it since this one started), with this choice and
its effort preferences merged in, in one atomic write */
function saveConfig(choice, preferences) {
const now = readConfig();
writeAtomic(CONFIG_FILE, JSON.stringify({ ...now, ...choice, effortPreferences: { ...preferencesOf(now), ...preferences } }, null, 2) + "\n");
}
async function changeSettings(requested) {
if (state.busy || starting) throw new Error("Wait until the current request finishes before switching.");
effortPreferences = { ...effortPreferences, ...preferencesOf(readConfig()) }; // as other decks left them
const choice = selectModel(catalog, settings, requested, effortPreferences);
if (Object.keys(choice).every(k => choice[k] === settings[k])) return;
const changingProvider = choice.provider !== settings.provider;
if (changingProvider && !["summary", "fresh"].includes(requested.handover)) throw new Error("Choose whether to pass a summary or start fresh.");
const old = session;
// Codex owns a single writer per thread. Model/effort are turn parameters, so keep its writer.
const reuse = !changingProvider && choice.provider === "codex" && old?.running;
const candidate = reuse ? old : makeSession(choice);
state.busy = true; state.switching = true; pushStatus();
try {
if (!reuse) await candidate.start(changingProvider ? null : state.sessionId);
if (!candidate.running) throw new Error("The new backend stopped before it was ready.");
const summary = changingProvider && requested.handover === "summary" ? handoverSummary(state.chat) : "";
if (changingProvider && state.sessionId) state.sessionArchive.push({ provider: state.provider, id: state.sessionId });
const changed = {}; // only the preferences this choice sets: the model left, and the model chosen
if (settings.effort) changed[`${settings.provider}:${settings.model}`] = settings.effort;
if (choice.effort) changed[`${choice.provider}:${choice.model}`] = choice.effort;
try { saveConfig(choice, changed); } catch (e) { console.error(e.message); }
effortPreferences = { ...effortPreferences, ...changed };
Object.assign(settings, choice);
deckSettings = { ...choice };
state.provider = choice.provider;
if (changingProvider) { state.sessionId = candidate.sessionId || null; state.handover = summary; state.model = null; state.conversation++; }
if (reuse) candidate.settings = choice;
session = candidate;
if (!reuse && candidate.initialEvent()) handleEvent(candidate.initialEvent());
if (!reuse) retire(old);
saveChat();
addEntry({ kind: "notice", ...(changingProvider && !summary ? { fresh: true } : {}), text: changingProvider
? `Switched to ${providerName(choice.provider)} · ${summary ? "Conversation summary will be shared" : "New conversation"}.`
: `Model: ${choice.model}${choice.effort ? ` · ${choice.effort} effort` : ""}. The conversation continues.` });
} catch (e) { if (session !== candidate) retire(candidate); throw e; }
finally { state.busy = false; state.switching = false; pushStatus(); }
}
function toolSummary(name, input = {}) {
// files outside the deck (screenshots, attached PDFs) by their name only
const base = (p) => {
if (!p) return "";
const r = path.relative(DECK_DIR, p);
return !r || r.startsWith("..") ? path.basename(p) : r;
};
// a picture in the screenshots folder: the chat shows it
const shotOf = (p) => (p && realOr(path.dirname(path.resolve(p))) === realOr(SHOT_DIR) && SHOT_NAME.test(path.basename(p)) ? { shot: path.basename(p) } : {});
switch (name) {
case "pindeck_read": return { name: "Read", detail: base(input.path), ...shotOf(input.path) };
case "pindeck_edit": case "pindeck_write": return { name: "Edit", detail: base(input.path) };
case "pindeck_command": return { name: input.command || "Command", detail: (input.args || []).join(" ") };
case "Read": return { name: "Read", detail: base(input.file_path), ...shotOf(input.file_path) };
case "Edit": case "MultiEdit": case "Write": return { name: "Edit", detail: base(input.file_path) };
case "Bash": {
// a PinDeck command only when the whole command is one: a script that ends in `cli.mjs layout`
// must show as the script, or a refused script looks like a refused layout check
const cmd = String(input.command || "").trim();
const m = cmd.startsWith(CLI_CMD + " ") && cmd.slice(CLI_CMD.length).match(/^\s+([\w-]+)\s*([^\n;&|<>`$]*)$/);
const names = { shot: "Screenshot", layout: "Check layout", element: "Read element", "pdf-figure": "PDF figure", resolve: "Resolve comment", reply: "Reply to comment" };
return m ? { name: names[m[1]] || m[1], detail: m[1] === "pdf-figure" ? m[2].trim().replace(/^\S*\//, "") : m[2].trim() }
: { name: "Run", detail: cmd.split("\n")[0].slice(0, 80) };
}
case "Glob": case "Grep": return { name, detail: input.pattern || "" };
default: return { name, detail: "" };
}
}
const toolEntries = new Map(); // tool_use_id -> entry
// the tools that write a file, and the argument that names it (Claude's, then those of PinDeck's Codex bridge)
const WRITES = { Edit: "file_path", MultiEdit: "file_path", Write: "file_path", NotebookEdit: "notebook_path",
pindeck_edit: "path", pindeck_write: "path" };
const DECK_REAL = realOr(DECK_DIR);
const deckRel = (p) => {
const abs = path.resolve(DECK_DIR, p);
const rel = path.relative(abs.startsWith(DECK_REAL + path.sep) ? DECK_REAL : DECK_DIR, abs);
return rel.split(path.sep).join("/");
};
function handleEvent(ev) {
if (ev.type === "system" && ev.subtype === "init") {
state.model = ev.model || state.model;
state.sessionId = ev.session_id;
saveChat();
pushStatus();
} else if (ev.type === "assistant" && state.turn) {
for (const b of ev.message?.content || []) {
if (b.type === "text" && b.text.trim()) addEntry({ kind: "assistant", text: b.text.trim() });
if (b.type === "tool_use") {
toolEntries.set(b.id, addEntry({ kind: "tool", ...toolSummary(b.name, b.input) }));
const file = WRITES[b.name] && b.input?.[WRITES[b.name]];
if (typeof file === "string") state.turn.touched.add(deckRel(file));
}
}
} else if (ev.type === "user" && state.turn) {
for (const b of ev.message?.content || []) {
if (b.type === "tool_result" && b.is_error) {
const e = toolEntries.get(b.tool_use_id);
const msg = (Array.isArray(b.content) ? b.content.map((c) => c.text || "").join(" ") : String(b.content || "")).slice(0, 200);
if (e) { e.error = msg; broadcast("chat-update", e); }
}
}
} else if (ev.type === "result" && state.turn) {
finishTurn({
error: ev.is_error && ev.subtype !== "success" ? (ev.subtype === "error_during_execution" ? "Stopped." : ev.result || ev.subtype) : null,
cost: ev.total_cost_usd, duration: ev.duration_ms,
denials: (ev.permission_denials || []).map((d) => toolSummary(d.tool_name, d.tool_input)),
});
}
}
function startTurn(promptText, userEntry) {
// every deck file as it is now: the assistant may change any of them (not brand.css or vendor/), and undo
// takes back all it changed
state.turn = { id: userEntry.id, before: snapshot([...EDITABLE, ...LOCKED]), gitConfig: readDeck(".git/config"), hadGit: fs.existsSync(path.join(DECK_DIR, ".git")), scan: scanDeck(), touched: new Set(),
time: { start: Date.now(), end: null } };
logTurnTime(state.turn.time);
state.busy = true;
pushStatus();
const turn = state.turn;
const context = state.handover ? state.handover + "\n\n" + promptText : promptText;
ensureSession().then(async () => {
if (state.turn !== turn || turn.cancelled) return;
const sendingSession = session;
await session.send([{ type: "text", text: context }]);
if (session === sendingSession) { state.handover = ""; saveChat(); }
}).catch(e => { if (state.turn === turn) finishTurn({ error: e.message }); });
}
function finishTurn({ error, cost, duration, denials = [] }) {
const turn = state.turn;
state.turn = null;
state.busy = false;
if (!turn) return pushStatus();
// Lock 2: restore any locked file that changed during the turn
const restored = [];
for (const f of LOCKED) {
const now = readDeck(f);
if (now === turn.before[f]) continue;
if (turn.before[f] != null) writeDeck(f, turn.before[f]);
else fs.rmSync(path.join(DECK_DIR, f), { force: true }); // a locked file that the assistant created
restored.push(f);
}
// .git/config can make git run commands (filters, fsmonitor), and PinDeck runs git after the id pass: an
// assistant must not change it, by whatever path or spelling it got there
if (readDeck(".git/config") !== turn.gitConfig) {
try {
if (turn.gitConfig == null) fs.rmSync(path.join(DECK_DIR, ".git/config"), { force: true });
else fs.writeFileSync(path.join(DECK_DIR, ".git/config"), turn.gitConfig);
restored.push(".git/config");
} catch (e) { console.error(e.message); }
}