@penguinharness/use-bento-slides 0.2.18 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +37 -0
  2. package/README.zh.md +37 -0
  3. package/THIRD-PARTY-NOTICES.md +30 -0
  4. package/ifaces.json +63 -0
  5. package/package.json +19 -21
  6. package/skills/bento-slides/SKILL.md +89 -29
  7. package/skills/bento-slides/references/bento-agents.md +511 -0
  8. package/workbenches/slides/index.ts +677 -0
  9. package/workbenches/slides/package.json +43 -0
  10. package/workbenches/slides/ui/app.js +1101 -0
  11. package/workbenches/slides/ui/bridge.js +190 -0
  12. package/workbenches/slides/ui/conversation-view.js +206 -0
  13. package/workbenches/slides/ui/conversation.css +95 -0
  14. package/workbenches/slides/ui/conversation.js +115 -0
  15. package/workbenches/slides/ui/deck-files.css +279 -0
  16. package/workbenches/slides/ui/deck-files.js +189 -0
  17. package/workbenches/slides/ui/file-menu.js +72 -0
  18. package/workbenches/slides/ui/icon.svg +9 -0
  19. package/workbenches/slides/ui/index.html +252 -0
  20. package/workbenches/slides/ui/model-choice.js +298 -0
  21. package/workbenches/slides/ui/model-control.tsx +90 -0
  22. package/workbenches/slides/ui/powerpoint.js +196 -0
  23. package/workbenches/slides/ui/sample.bento.json +33 -0
  24. package/workbenches/slides/ui/strings.js +184 -0
  25. package/workbenches/slides/ui/style.css +505 -0
  26. package/workbenches/slides/ui/sync.js +268 -0
  27. package/workbenches/slides/ui/template-picker.js +128 -0
  28. package/workbenches/slides/ui/templates.js +256 -0
  29. package/workbenches/slides/ui/vendor/LICENSE-bento.txt +21 -0
  30. package/workbenches/slides/ui/vendor/LICENSE-jszip.txt +25 -0
  31. package/workbenches/slides/ui/vendor/LICENSE-pptxgen.txt +21 -0
  32. package/workbenches/slides/ui/vendor/bento-slides-1.2.13.runtime.txt +310 -0
  33. package/workbenches/slides/ui/vendor/pptxgen-4.0.1.bundle.js +96 -0
@@ -0,0 +1,1101 @@
1
+ // The Slides page: presentation files, the Bento editor in a sandboxed frame, and a rail that asks
2
+ // the Agent to change the open deck.
3
+ //
4
+ // One deck is one file the handler serves. The page keeps the editor and the file in step:
5
+ // - the person edits -> the frame reports the document -> saved to the file;
6
+ // - the Agent edits -> the handler's stream says the file changed -> loaded into the editor,
7
+ // with whatever the person did meanwhile replayed on top (./sync.js).
8
+ // The editor never talks to anything but this page: its frame has no origin of its own and a
9
+ // policy that allows no connection, so the Bento runtime cannot reach the network or the app.
10
+ import { exportPowerPoint } from "./powerpoint.js";
11
+ import { setupTemplatePicker } from "./template-picker.js";
12
+ import { deckFiles } from "./deck-files.js";
13
+ import { setupFileMenu } from "./file-menu.js";
14
+ import { bridge, connectSave, captureSave, editorDocument, editorToken } from "./bridge.js";
15
+ import { newConversation, readConversation } from "./conversation.js";
16
+ import { setupModelChoice } from "./model-choice.js";
17
+ import { showConversation } from "./conversation-view.js";
18
+ import { S, locale } from "./strings.js";
19
+ import {
20
+ deckFromHtml,
21
+ diff,
22
+ formatDeck,
23
+ htmlWithDeck,
24
+ isEmpty,
25
+ parseDeck,
26
+ rebase,
27
+ } from "./sync.js";
28
+
29
+ const RUNTIME = "vendor/bento-slides-1.2.13.runtime.txt";
30
+ const SDK = "../sdk/workbench.js";
31
+ const SAVE_AFTER_MS = 700;
32
+ const LOAD_TIMEOUT_MS = 30_000;
33
+ const TAG = "__slides";
34
+ /** What the editor's frame may load: itself, inline, and nothing over the network. */
35
+ const FRAME_POLICY = [
36
+ "default-src 'none'",
37
+ "script-src 'unsafe-inline' 'unsafe-eval' blob:",
38
+ "style-src 'unsafe-inline'",
39
+ "img-src data: blob:",
40
+ "font-src data:",
41
+ "media-src data: blob:",
42
+ "connect-src 'none'",
43
+ "base-uri 'none'",
44
+ "form-action 'none'",
45
+ ].join("; ");
46
+
47
+ const $ = (id) => document.getElementById(id);
48
+ const app = $("app");
49
+ const frame = $("editor");
50
+
51
+ document.documentElement.lang = locale === "zh" ? "zh-CN" : "en";
52
+ for (const el of document.querySelectorAll("[data-copy]")) el.textContent = S[el.dataset.copy];
53
+ frame.title = S.frameTitle;
54
+ frame.parentElement.setAttribute("aria-label", S.frameTitle);
55
+ $("player-frame").title = S.present;
56
+ $("player").setAttribute("aria-label", S.present);
57
+ setupFileMenu($("file-button"), $("file-menu"));
58
+ $("save-shortcut").textContent = /Mac|iPhone|iPad/i.test(navigator.platform) ? "⌘S" : "Ctrl+S";
59
+ app.dataset.rail = matchMedia("(max-width: 850px)").matches ? "off" : "on";
60
+ $("rail-toggle").setAttribute("aria-pressed", String(app.dataset.rail === "on"));
61
+ $("prompt").placeholder = S.promptPlaceholder;
62
+ $("start-prompt").placeholder = S.startPlaceholder;
63
+
64
+ const api = (path, init) => fetch(`../api${path}`, init);
65
+ const send = (path, method, body) =>
66
+ api(path, {
67
+ method,
68
+ headers: { "content-type": "application/json" },
69
+ body: JSON.stringify(body),
70
+ });
71
+ async function getJson(path) {
72
+ const res = await api(path);
73
+ if (!res.ok) throw new Error(`${res.status}`);
74
+ return res.json();
75
+ }
76
+
77
+ let runtime = null;
78
+ let decks = [];
79
+ /** The open deck, or null: see `openDeck` for its fields. */
80
+ let open = null;
81
+ let cursor = { index: 0, slideId: null, selection: [] };
82
+
83
+ // ---- views -------------------------------------------------------------------------------
84
+
85
+ function setView(view) {
86
+ app.dataset.view = view;
87
+ }
88
+ function setSync(key, tone = "") {
89
+ $("sync").textContent = key === "" ? "" : S[key];
90
+ $("sync").dataset.tone = tone;
91
+ }
92
+ let noticeTimer = null;
93
+ /** A line under the bar; `ms` 0 keeps it up, `action` adds a button that does something about it. */
94
+ function notice(text, ms = 12_000, action = null) {
95
+ const line = $("notice");
96
+ line.replaceChildren(text);
97
+ if (action !== null) {
98
+ const button = document.createElement("button");
99
+ button.type = "button";
100
+ button.className = "link";
101
+ button.textContent = action.label;
102
+ button.onclick = () => {
103
+ line.hidden = true;
104
+ action.run();
105
+ };
106
+ line.append(" ", button);
107
+ }
108
+ line.hidden = false;
109
+ clearTimeout(noticeTimer);
110
+ if (ms > 0) noticeTimer = setTimeout(() => (line.hidden = true), ms);
111
+ }
112
+
113
+ let listRequest = 0;
114
+ let connected = false;
115
+ const filesPage = deckFiles({
116
+ onOpen: (id) => openDeck(id).catch(() => notice(filesPage.openFailed)),
117
+ onRename: async (deck, title) => {
118
+ const current = await getJson(`/decks/${deck.id}`);
119
+ const doc = parseDeck(current.text);
120
+ // Preserve concurrent edits and the file's identity, its history, and its linked conversation.
121
+ if ((doc.title?.trim() || deck.id) !== deck.title.trim())
122
+ throw Object.assign(new Error(), { status: 409 });
123
+ doc.title = title;
124
+ const response = await send(`/decks/${deck.id}`, "PUT", {
125
+ text: formatDeck(doc),
126
+ base: current.rev,
127
+ });
128
+ if (!response.ok)
129
+ throw Object.assign(new Error(String(response.status)), { status: response.status });
130
+ await refreshDecks();
131
+ },
132
+ onDelete: (id) => removeFile(id),
133
+ onRefresh: () => (connected ? refreshDecks() : start()),
134
+ onBack: () => showFiles().catch(() => notice(S.transferFailed)),
135
+ });
136
+
137
+ async function refreshDecks() {
138
+ const request = ++listRequest;
139
+ try {
140
+ const result = await getJson("/decks");
141
+ if (request !== listRequest) return;
142
+ decks = result.decks;
143
+ } catch {
144
+ if (request === listRequest) filesPage.render(decks, "error");
145
+ return;
146
+ }
147
+ filesPage.render(decks, "ready");
148
+ const current = decks.find((deck) => deck.id === open?.id);
149
+ $("deck-title").textContent = current?.title || open?.shown?.title || S.untitled;
150
+ }
151
+
152
+ // ---- the editor frame ---------------------------------------------------------------------
153
+
154
+ /** The Bento runtime with `doc` in it, the frame's policy, and the bridge that reports to us. */
155
+ function frameHead(token) {
156
+ const policy = `<meta http-equiv="Content-Security-Policy" content="${FRAME_POLICY}">`;
157
+ // The host provides loading and save feedback. Bento's disk-only notice has a single
158
+ // acknowledgement button. Recovery and file-conflict banners have multiple actions.
159
+ const embeddedChrome = `<style>
160
+ html #bento-splash,
161
+ .ed-recover:has(> span:first-child + button.ed-btn-primary:last-child) { display: none; }
162
+ </style>`;
163
+ return (
164
+ policy +
165
+ embeddedChrome +
166
+ `<script>(${connectSave.toString()})(${JSON.stringify(token)},(${captureSave.toString()}),${JSON.stringify(S.saveDeck)})</` +
167
+ "script>"
168
+ );
169
+ }
170
+
171
+ function editorHtml(doc, token) {
172
+ const script =
173
+ `<script>(${bridge.toString()})(${JSON.stringify(token)},${JSON.stringify(locale === "zh" ? "zh-Hans" : "en")})</` +
174
+ "script>";
175
+ return htmlWithDeck(runtime, editorDocument(doc))
176
+ .replace(/<head>/i, () => `<head>${frameHead(token)}`)
177
+ .replace(/<\/body>/i, `${script}</body>`);
178
+ }
179
+
180
+ let loads = 0;
181
+ const waiting = new Map();
182
+ /** Hands the editor a document; resolves with what it held just before and what it shows now. */
183
+ function loadIntoEditor(o, doc) {
184
+ return frameRequest(o, { type: "load", json: JSON.stringify(doc) });
185
+ }
186
+
187
+ function frameRequest(o, request) {
188
+ const id = ++loads;
189
+ return new Promise((resolve, reject) => {
190
+ const timer = setTimeout(() => {
191
+ waiting.delete(id);
192
+ reject(new Error(S.transferFailed));
193
+ }, LOAD_TIMEOUT_MS);
194
+ waiting.set(id, (message) => {
195
+ clearTimeout(timer);
196
+ resolve(message);
197
+ });
198
+ frame.contentWindow.postMessage({ [TAG]: 1, token: o.token, id, ...request }, "*");
199
+ });
200
+ }
201
+
202
+ async function currentDocument(o) {
203
+ return o.ready ? (await frameRequest(o, { type: "read" })).doc : o.mine;
204
+ }
205
+
206
+ async function savedSnapshot(o) {
207
+ return inTurn(o, async () => {
208
+ if (open !== o || !o.ready || o.gone) throw new Error(o.gone ? S.gone : S.transferFailed);
209
+ const doc = await currentDocument(o);
210
+ if (open !== o) throw new Error(S.transferFailed);
211
+ o.mine = doc;
212
+ clearTimeout(o.timer);
213
+ await save(o, true);
214
+ if (open !== o || o.gone || unsaved(o).length) throw new Error(S.notSaved);
215
+ return o.mine;
216
+ });
217
+ }
218
+
219
+ async function saveCurrent() {
220
+ if (!open) return;
221
+ try {
222
+ await savedSnapshot(open);
223
+ } catch (error) {
224
+ setSync("notSaved", "attention");
225
+ notice(S.saveFailed(error.message));
226
+ }
227
+ }
228
+ $("save").onclick = saveCurrent;
229
+ function saveKey(event) {
230
+ if (open && app.dataset.view === "deck" && captureSave(event)) void saveCurrent();
231
+ }
232
+ window.addEventListener("keydown", saveKey, true);
233
+ // The App's own toolbar can hold focus while its workbench is open. Handle its shortcut
234
+ // only while this page is visible and the user is in this workbench's app or window.
235
+ try {
236
+ const host = window.parent;
237
+ if (host !== window) {
238
+ const onHostKey = (event) => {
239
+ if (!frameElement?.getClientRects().length) return;
240
+ const win = frameElement.closest('[role="dialog"], section[aria-label]');
241
+ if (host.location.pathname.startsWith("/app/") || (win && win.contains(event.target)))
242
+ saveKey(event);
243
+ };
244
+ host.addEventListener("keydown", onHostKey, true);
245
+ window.addEventListener(
246
+ "pagehide",
247
+ () => host.removeEventListener("keydown", onHostKey, true),
248
+ { once: true },
249
+ );
250
+ }
251
+ } catch {
252
+ /* The workbench can also run in a cross-origin host. */
253
+ }
254
+
255
+ window.addEventListener("message", (event) => {
256
+ const message = event.data;
257
+ if (!message || message[TAG] !== 1 || open === null || message.token !== open.token) return;
258
+ if (
259
+ message.type === "save" &&
260
+ (event.source === frame.contentWindow ||
261
+ ($("player").open && event.source === $("player-frame").contentWindow))
262
+ ) {
263
+ void saveCurrent();
264
+ return;
265
+ }
266
+ if (event.source !== frame.contentWindow) return;
267
+ if (message.type === "ready") {
268
+ open.shown = message.doc;
269
+ open.mine = message.doc;
270
+ open.ready = true;
271
+ frame.inert = false;
272
+ setSync("synced");
273
+ void refreshDecks();
274
+ } else if (message.type === "changed") {
275
+ open.mine = message.doc;
276
+ scheduleSave(open);
277
+ } else if (message.type === "loaded" || message.type === "read") {
278
+ waiting.get(message.id)?.(message);
279
+ waiting.delete(message.id);
280
+ } else if (message.type === "cursor") {
281
+ cursor = { index: message.index, slideId: message.slideId, selection: message.selection };
282
+ renderContext();
283
+ }
284
+ });
285
+
286
+ function renderContext() {
287
+ const total = open?.mine?.slides?.length ?? 0;
288
+ const parts = total > 0 ? [S.contextSlide(Math.min(cursor.index + 1, total), total)] : [];
289
+ if (cursor.selection.length > 0) parts.push(S.contextSelection(cursor.selection.length));
290
+ $("context").textContent = parts.join(" · ");
291
+ }
292
+
293
+ // ---- keeping the editor and the file in step ----------------------------------------------
294
+
295
+ /** Runs `work` after whatever this deck is already doing: saves and loads never interleave. */
296
+ function inTurn(o, work) {
297
+ const run = o.turn.then(work, work);
298
+ o.turn = run.catch(() => undefined);
299
+ return run;
300
+ }
301
+
302
+ /** Edits the person made that the file does not hold yet. */
303
+ const unsaved = (o) => [...o.carry, diff(o.shown, o.mine)].filter((edits) => !isEmpty(edits));
304
+
305
+ function scheduleSave(o) {
306
+ clearTimeout(o.timer);
307
+ setSync("saving", "busy");
308
+ o.timer = setTimeout(() => void inTurn(o, () => save(o)), SAVE_AFTER_MS);
309
+ }
310
+
311
+ async function save(o, explicit = false) {
312
+ if (open !== o || !o.ready || o.gone) return;
313
+ if (unsaved(o).length === 0) {
314
+ setSync("synced");
315
+ return;
316
+ }
317
+ const mine = o.mine;
318
+ let res;
319
+ try {
320
+ res = await send(`/decks/${o.id}`, "PUT", { text: formatDeck(mine), base: o.rev });
321
+ } catch (error) {
322
+ setSync("offline", "attention");
323
+ if (explicit) throw error;
324
+ return;
325
+ }
326
+ if (res.status === 409) {
327
+ const current = await res.json();
328
+ await takeTheirs(o, current.rev, current.text, explicit);
329
+ return;
330
+ }
331
+ if (res.status === 404) {
332
+ deckGone(o);
333
+ if (explicit) throw new Error(S.gone);
334
+ return;
335
+ }
336
+ if (!res.ok) {
337
+ const detail = await res.json().catch(() => null);
338
+ const why = detail?.error?.message || detail?.error || `HTTP ${res.status}`;
339
+ setSync("notSaved", "attention");
340
+ if (explicit) throw new Error(String(why));
341
+ notice(S.saveFailed(why));
342
+ return;
343
+ }
344
+ o.rev = (await res.json()).rev;
345
+ o.base = parseDeck(formatDeck(mine));
346
+ o.shown = mine;
347
+ o.carry = [];
348
+ if (o.mine !== mine) scheduleSave(o);
349
+ else setSync("synced");
350
+ void refreshDecks();
351
+ }
352
+
353
+ /**
354
+ * The file moved on under the editor (the Agent wrote it): put its document in the editor with
355
+ * the person's unsaved edits replayed on it, then save the result when there were any.
356
+ */
357
+ async function takeTheirs(o, rev, text, explicit = false) {
358
+ if (open !== o || rev === o.rev) return;
359
+ let theirs;
360
+ try {
361
+ theirs = parseDeck(text);
362
+ } catch (err) {
363
+ // Half-written by the Agent, or broken: the editor keeps what it has until the next write.
364
+ notice(S.badFile(err instanceof Error ? err.message : String(err)));
365
+ return;
366
+ }
367
+ const clashes = [];
368
+ for (let round = 0; round < 4; round++) {
369
+ const used = o.mine;
370
+ const pending = unsaved(o);
371
+ let doc = theirs;
372
+ for (const edits of pending) {
373
+ const merged = rebase(doc, edits, o.base);
374
+ doc = merged.doc;
375
+ clashes.push(...merged.clashes);
376
+ }
377
+ const loaded = await loadIntoEditor(o, doc);
378
+ if (open !== o) return;
379
+ // What the person did between our reading of the editor and the editor taking the document.
380
+ const late = diff(used, loaded.before);
381
+ o.carry = pending;
382
+ o.shown = loaded.doc;
383
+ o.mine = loaded.doc;
384
+ o.base = theirs;
385
+ o.rev = rev;
386
+ if (isEmpty(late)) break;
387
+ o.carry = [...pending, late];
388
+ }
389
+ if (clashes.length > 0) notice(S.clashes(clashes.length));
390
+ if (o.carry.length > 0) {
391
+ setSync("merged", "busy");
392
+ await save(o, explicit);
393
+ } else {
394
+ setSync("theirs", "busy");
395
+ setTimeout(() => open === o && unsaved(o).length === 0 && setSync("synced"), 2500);
396
+ }
397
+ renderContext();
398
+ void refreshDecks();
399
+ }
400
+
401
+ async function fileChanged(o) {
402
+ const res = await api(`/decks/${o.id}`).catch(() => null);
403
+ if (res === null || open !== o) return;
404
+ if (res.status === 404) {
405
+ deckGone(o);
406
+ return;
407
+ }
408
+ if (!res.ok) return;
409
+ const current = await res.json();
410
+ if (o.gone) {
411
+ // The file is back: the deck is in step with it again from here.
412
+ o.gone = false;
413
+ $("notice").hidden = true;
414
+ }
415
+ await inTurn(o, () => takeTheirs(o, current.rev, current.text));
416
+ }
417
+
418
+ /**
419
+ * The open deck's file was removed (the Agent deleted it, or another page did). The editor keeps
420
+ * what the person sees and saves nothing more; they can keep it as a new deck.
421
+ */
422
+ function deckGone(o) {
423
+ if (open !== o || o.gone) return;
424
+ o.gone = true;
425
+ clearTimeout(o.timer);
426
+ setSync("");
427
+ notice(S.gone, 0, {
428
+ label: S.keepCopy,
429
+ run: () => void createDeck(o.mine?.title || S.untitled, o.mine ?? o.base),
430
+ });
431
+ }
432
+
433
+ // ---- decks --------------------------------------------------------------------------------
434
+
435
+ let opening = 0;
436
+ async function openDeck(id) {
437
+ const next = ++opening;
438
+ const previous = open;
439
+ if (previous?.ready && !previous.gone) {
440
+ const latest = await currentDocument(previous);
441
+ if (next !== opening) return;
442
+ previous.mine = latest;
443
+ clearTimeout(previous.timer);
444
+ await inTurn(previous, () => save(previous));
445
+ if (next !== opening || unsaved(previous).length) return;
446
+ }
447
+ const current = await getJson(`/decks/${id}`);
448
+ if (runtime === null) {
449
+ const response = await fetch(RUNTIME);
450
+ if (!response.ok) throw new Error(String(response.status));
451
+ runtime = await response.text();
452
+ }
453
+ if (next !== opening) return;
454
+ let doc;
455
+ try {
456
+ doc = parseDeck(current.text);
457
+ } catch (err) {
458
+ notice(S.badFile(err instanceof Error ? err.message : String(err)));
459
+ return;
460
+ }
461
+ stopFollowing();
462
+ talk = { sessionId: null, status: null, messages: [] };
463
+ open = {
464
+ id,
465
+ token: editorToken(),
466
+ /** The file's revision the editor is in step with, and its document. */
467
+ rev: current.rev,
468
+ base: doc,
469
+ /** The editor's document when it was last in step with the file; and now. */
470
+ shown: doc,
471
+ mine: doc,
472
+ /** Edits already in the editor that no save has put in the file. */
473
+ carry: [],
474
+ ready: false,
475
+ /** The file was removed under the editor: nothing is saved until it is back. */
476
+ gone: false,
477
+ timer: null,
478
+ turn: Promise.resolve(),
479
+ };
480
+ cursor = { index: 0, slideId: null, selection: [] };
481
+ setView("deck");
482
+ setSync("opening");
483
+ $("deck-title").textContent = doc.title || S.untitled;
484
+ frame.inert = true;
485
+ frame.srcdoc = editorHtml(doc, open.token);
486
+ renderContext();
487
+ await refreshDecks();
488
+ await refreshTalk();
489
+ }
490
+
491
+ async function createDeck(title, doc) {
492
+ const res = await send("/decks", "POST", { id: title, text: formatDeck(doc) });
493
+ if (!res.ok) throw new Error(`${res.status}`);
494
+ const { id } = await res.json();
495
+ await openDeck(id);
496
+ return id;
497
+ }
498
+
499
+ const blankDeck = (title) => ({
500
+ format: "bento/slides",
501
+ version: 1,
502
+ title,
503
+ size: { width: 1280, height: 720 },
504
+ theme: {
505
+ background: "#FFFFFF",
506
+ color: "#141310",
507
+ accent: "#E8442E",
508
+ fontFamily: "system-ui, sans-serif",
509
+ },
510
+ slides: [
511
+ {
512
+ id: "s1",
513
+ background: "#FFFFFF",
514
+ transition: "none",
515
+ notes: "",
516
+ elements: [
517
+ {
518
+ id: "title",
519
+ type: "text",
520
+ role: "title",
521
+ x: 96,
522
+ y: 260,
523
+ w: 1088,
524
+ h: 160,
525
+ rotation: 0,
526
+ opacity: 1,
527
+ html: title.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"),
528
+ fontSize: 72,
529
+ fontFamily: "system-ui, sans-serif",
530
+ fontWeight: 800,
531
+ color: "#141310",
532
+ align: "left",
533
+ valign: "top",
534
+ lineHeight: 1.1,
535
+ },
536
+ ],
537
+ },
538
+ ],
539
+ });
540
+
541
+ async function importFile(file) {
542
+ try {
543
+ const text = await file.text();
544
+ const doc = /\.json$/i.test(file.name) ? parseDeck(text) : deckFromHtml(text);
545
+ await createDeck(doc.title || file.name.replace(/\.(bento\.)?(html|json)$/i, ""), doc);
546
+ } catch (err) {
547
+ notice(S.importFailed(err instanceof Error ? err.message : String(err)));
548
+ }
549
+ }
550
+
551
+ async function exportDeck() {
552
+ if (open === null) return;
553
+ const doc = await savedSnapshot(open);
554
+ await downloadDeck(doc.title, "bento.html", htmlWithDeck(runtime, doc));
555
+ }
556
+
557
+ async function downloadDeck(title, suffix, bytes) {
558
+ const name = `${(title || "deck").replace(/[\\/:*?"<>|]+/g, " ").trim() || "deck"}.${suffix}`;
559
+ const res = await api(`/export?name=${encodeURIComponent(name)}`, {
560
+ method: "POST",
561
+ headers: { "content-type": "application/octet-stream" },
562
+ body: bytes,
563
+ });
564
+ if (!res.ok) throw new Error(S.transferFailed);
565
+ const link = document.createElement("a");
566
+ link.href = `../api/${(await res.json()).href}`;
567
+ link.download = name;
568
+ document.body.append(link);
569
+ link.click();
570
+ link.remove();
571
+ }
572
+
573
+ // ---- history and deletion -----------------------------------------------------------------
574
+
575
+ const when = (ms) =>
576
+ new Date(ms).toLocaleString(locale === "zh" ? "zh-CN" : "en", {
577
+ month: "short",
578
+ day: "numeric",
579
+ hour: "2-digit",
580
+ minute: "2-digit",
581
+ });
582
+
583
+ let historyRequest = 0;
584
+ async function showHistory() {
585
+ const request = ++historyRequest;
586
+ const deck = open;
587
+ if (!deck) return;
588
+ const dialog = $("history-dialog");
589
+ const status = $("history-status");
590
+ const list = $("history-menu");
591
+ list.replaceChildren();
592
+ status.hidden = false;
593
+ status.textContent = S.historyLoading;
594
+ dialog.showModal();
595
+ try {
596
+ const { versions } = await getJson(`/decks/${deck.id}/history`);
597
+ if (request !== historyRequest || !dialog.open || open !== deck) return;
598
+ status.hidden = versions.length > 0;
599
+ status.textContent = versions.length ? "" : S.historyEmpty;
600
+ for (const version of versions) {
601
+ const row = document.createElement("li");
602
+ const author = document.createElement("strong");
603
+ author.textContent = S.versionBy[version.by] ?? version.by;
604
+ const time = document.createElement("time");
605
+ time.dateTime = new Date(version.at).toISOString();
606
+ time.textContent = when(version.at);
607
+ const button = document.createElement("button");
608
+ button.type = "button";
609
+ button.textContent = S.restoreVersion;
610
+ button.setAttribute(
611
+ "aria-label",
612
+ [S.restoreVersion, author.textContent, time.textContent].join(" · "),
613
+ );
614
+ button.onclick = () => {
615
+ dialog.close();
616
+ void restore(deck, version.name);
617
+ };
618
+ row.append(author, time, button);
619
+ list.append(row);
620
+ }
621
+ } catch {
622
+ if (request === historyRequest) status.textContent = S.historyFailed;
623
+ }
624
+ }
625
+
626
+ /**
627
+ * Puts an earlier version in the editor as the person's own edit: it is saved like one (the
628
+ * Agent's later changes are replayed on it the usual way), and Bento's undo takes it back.
629
+ */
630
+ async function restore(o, name) {
631
+ let doc;
632
+ try {
633
+ doc = parseDeck((await getJson(`/decks/${o.id}/history/${encodeURIComponent(name)}`)).text);
634
+ } catch (err) {
635
+ notice(S.restoreFailed(err instanceof Error ? err.message : String(err)));
636
+ return;
637
+ }
638
+ const taken = await inTurn(o, async () => {
639
+ if (open !== o) return false;
640
+ const loaded = await loadIntoEditor(o, doc);
641
+ if (open !== o) return false;
642
+ o.mine = loaded.doc;
643
+ return true;
644
+ }).catch(() => false);
645
+ if (taken) scheduleSave(o);
646
+ }
647
+
648
+ /** Closes the open deck: the editor goes blank and nothing of it is saved any more. */
649
+ function closeDeck() {
650
+ if (open === null) return;
651
+ clearTimeout(open.timer);
652
+ open.gone = true;
653
+ open = null;
654
+ stopFollowing();
655
+ frame.srcdoc = "";
656
+ }
657
+
658
+ async function showFiles() {
659
+ const next = ++opening;
660
+ const previous = open;
661
+ if (previous?.ready) {
662
+ if (!previous.gone) await savedSnapshot(previous);
663
+ if (next !== opening || unsaved(previous).length) return;
664
+ }
665
+ closeDeck();
666
+ setView("start");
667
+ $("start-blank").focus();
668
+ await refreshDecks();
669
+ }
670
+
671
+ async function removeFile(id) {
672
+ const res = await api(`/decks/${id}`, { method: "DELETE" });
673
+ if (!res.ok) throw new Error(String(res.status));
674
+ await refreshDecks();
675
+ }
676
+
677
+ // ---- asking the Agent ---------------------------------------------------------------------
678
+
679
+ let sdk; // undefined until tried, null when this server has none
680
+ let reader = null;
681
+ let transcript = newConversation();
682
+ let followedId = null;
683
+ let approvals = [];
684
+ let decidingCalls = new Set();
685
+ let approvalRead = 0;
686
+ let renderFrame = null;
687
+ let talk = { sessionId: null, status: null, messages: [] };
688
+
689
+ const models = setupModelChoice({
690
+ $,
691
+ notice,
692
+ send,
693
+ loadSdk,
694
+ currentDeck: () => open,
695
+ currentTalk: () => talk,
696
+ refreshTalk,
697
+ });
698
+
699
+ async function loadSdk() {
700
+ if (sdk !== undefined) return sdk;
701
+ try {
702
+ sdk = await import(SDK);
703
+ } catch {
704
+ sdk = null;
705
+ }
706
+ return sdk;
707
+ }
708
+
709
+ function stopFollowing() {
710
+ reader?.close();
711
+ reader = null;
712
+ followedId = null;
713
+ approvals = [];
714
+ decidingCalls = new Set();
715
+ ++approvalRead;
716
+ transcript = newConversation();
717
+ if (renderFrame !== null) cancelAnimationFrame(renderFrame);
718
+ renderFrame = null;
719
+ }
720
+
721
+ async function pendingApprovals(sessionId) {
722
+ if (!sdk || followedId !== sessionId) return;
723
+ const revision = ++approvalRead;
724
+ try {
725
+ const res = await sdk.transport.get(
726
+ "/sessions/" + encodeURIComponent(sessionId) + "/approvals",
727
+ );
728
+ if (revision === approvalRead && followedId === sessionId) {
729
+ approvals = res.body?.approvals || [];
730
+ scheduleTalk();
731
+ }
732
+ } catch {
733
+ // The next Session status refresh retries the read. Keep the last actionable request.
734
+ }
735
+ }
736
+
737
+ async function decideApproval(sessionId, toolId, decision) {
738
+ if (!sdk || followedId !== sessionId || decidingCalls.has(toolId)) return;
739
+ const pending = decidingCalls;
740
+ pending.add(toolId);
741
+ scheduleTalk();
742
+ const path =
743
+ "/sessions/" + encodeURIComponent(sessionId) + "/approvals/" + encodeURIComponent(toolId);
744
+ try {
745
+ await sdk.transport.post(path, { decision });
746
+ } catch (error) {
747
+ if (followedId === sessionId) notice(String(error.message || error));
748
+ } finally {
749
+ await pendingApprovals(sessionId);
750
+ pending.delete(toolId);
751
+ if (followedId === sessionId) scheduleTalk();
752
+ }
753
+ }
754
+
755
+ function renderTalk() {
756
+ const running = talk.status !== null && talk.status !== "idle";
757
+ const sessionId = talk.sessionId;
758
+ showConversation($("talk"), talk.messages, transcript, {
759
+ locale,
760
+ running,
761
+ hint: S.hintEmpty,
762
+ retry: ask,
763
+ approvals,
764
+ decidingCalls,
765
+ decide: (id, decision) => decideApproval(sessionId, id, decision),
766
+ });
767
+ $("stop").hidden = !running || !sdk;
768
+ models.draw();
769
+ }
770
+
771
+ function scheduleTalk() {
772
+ if (renderFrame !== null) return;
773
+ renderFrame = requestAnimationFrame(() => {
774
+ renderFrame = null;
775
+ renderTalk();
776
+ });
777
+ }
778
+
779
+ async function follow(sessionId) {
780
+ if (followedId === sessionId && reader !== null) return;
781
+ stopFollowing();
782
+ const deck = open;
783
+ followedId = sessionId;
784
+ if (!(await loadSdk()) || !deck || open !== deck || followedId !== sessionId) return;
785
+ // The rail retains 40 messages. The SDK window counts whole Tasks, not
786
+ // records, so even a long tool run is restored with its own original turn.
787
+ const mine = (reader = sdk.followSession(sessionId, { tailLimit: 40 }));
788
+ mine.on("event", ({ record, source }) => {
789
+ if (reader !== mine) return;
790
+ readConversation(transcript, record);
791
+ if (source === "live" && record.payload?.type === "tool_call" && talk.status !== "idle")
792
+ void pendingApprovals(sessionId);
793
+ if (record.payload?.type === "task_end" && talk.status !== "idle") {
794
+ clearTimeout(talkTimer);
795
+ talkTimer = setTimeout(() => void refreshTalk(), 150);
796
+ }
797
+ scheduleTalk();
798
+ });
799
+ mine.on("reset", () => {
800
+ if (reader === mine) {
801
+ transcript = newConversation();
802
+ scheduleTalk();
803
+ }
804
+ });
805
+ mine.on("error", () => {
806
+ if (reader === mine) reader = null;
807
+ });
808
+ }
809
+
810
+ let talkTimer = null;
811
+ let talkRevision = 0;
812
+ async function refreshTalk() {
813
+ clearTimeout(talkTimer);
814
+ if (open === null) return;
815
+ const deck = open;
816
+ const id = deck.id;
817
+ const revision = ++talkRevision;
818
+ let next;
819
+ try {
820
+ next = await getJson(`/ask?deck=${encodeURIComponent(id)}`);
821
+ } catch {
822
+ if (
823
+ open === deck &&
824
+ revision === talkRevision &&
825
+ (deck.waitingChoice || deck.pendingModel || (talk.status && talk.status !== "idle"))
826
+ ) {
827
+ talkTimer = setTimeout(() => void refreshTalk(), 4000);
828
+ }
829
+ return;
830
+ }
831
+ if (open !== deck || talkRevision !== revision) return;
832
+ talk = next;
833
+ if (talk.sessionId) {
834
+ try {
835
+ await models.readSessionModel(deck, talk.sessionId);
836
+ deck.choiceReadFailed = false;
837
+ } catch {
838
+ if (open === deck && !deck.choiceReadFailed && (deck.pendingModel || deck.waitingChoice)) {
839
+ deck.choiceReadFailed = true;
840
+ notice(S.choiceReadFailed);
841
+ }
842
+ }
843
+ if (open !== deck || revision !== talkRevision) return;
844
+ } else if (!talk.sessionId) {
845
+ deck.model = null;
846
+ deck.waitingChoice = null;
847
+ deck.pendingModel = null;
848
+ deck.effort = null;
849
+ }
850
+ const running = talk.status !== null && talk.status !== "idle";
851
+ if (talk.sessionId !== null && (followedId !== talk.sessionId || reader === null))
852
+ void follow(talk.sessionId);
853
+ if (talk.sessionId === null) stopFollowing();
854
+ // The stream says when a task ends; this is for a server without it, and for a missed end.
855
+ if (running || deck.pendingModel || deck.waitingChoice) {
856
+ if (talk.sessionId) void pendingApprovals(talk.sessionId);
857
+ talkTimer = setTimeout(
858
+ () => void refreshTalk(),
859
+ deck.pendingModel || deck.waitingChoice ? 700 : 4000,
860
+ );
861
+ } else {
862
+ ++approvalRead;
863
+ approvals = [];
864
+ }
865
+ renderTalk();
866
+ }
867
+
868
+ async function ask(text, firstModel = null) {
869
+ if (open === null || open.savingChoice || text.trim() === "") return;
870
+ const o = open;
871
+ // What the person just did reaches the file before the Agent reads it.
872
+ clearTimeout(o.timer);
873
+ await inTurn(o, () => save(o));
874
+ if (open !== o) return;
875
+ ++talkRevision;
876
+ talk.messages = [
877
+ ...talk.messages,
878
+ { role: "user", text: text.trim(), at: new Date().toISOString() },
879
+ ];
880
+ talk.status = "running";
881
+
882
+ renderTalk();
883
+ let res;
884
+ try {
885
+ res = await send("/ask", "POST", {
886
+ deck: o.id,
887
+ ...(firstModel ? { model: firstModel } : {}),
888
+ text,
889
+ slide: cursor.slideId === null ? null : { id: cursor.slideId, number: cursor.index + 1 },
890
+ selection: cursor.selection,
891
+ });
892
+ } catch (err) {
893
+ res = { ok: false, status: String(err) };
894
+ }
895
+ if (open !== o) return;
896
+ if (!res.ok) {
897
+ // The server's error is a string, or `{ code, message }` when the request never reached the
898
+ // handler (a Project with no default model is the common one).
899
+ const error = res.json ? (await res.json().catch(() => null))?.error : null;
900
+ const text =
901
+ error?.code === "no_default_model"
902
+ ? S.noModel
903
+ : S.askFailed(String(error?.message ?? error ?? res.status));
904
+ talk.messages = [...talk.messages, { role: "error", text }];
905
+ talk.status = "idle";
906
+ renderTalk();
907
+ return;
908
+ }
909
+ const { sessionId } = await res.json();
910
+ talk.sessionId = sessionId;
911
+ void models.readSessionModel(o, sessionId).catch(() => undefined);
912
+ ++talkRevision;
913
+ await follow(sessionId);
914
+ talkTimer = setTimeout(() => void refreshTalk(), 4000);
915
+ }
916
+
917
+ // ---- wiring -------------------------------------------------------------------------------
918
+
919
+ $("history").onclick = () => void showHistory();
920
+ setupTemplatePicker({ blankDeck, createDeck });
921
+ $("present").onclick = async () => {
922
+ if (!open) return;
923
+ try {
924
+ const doc = await savedSnapshot(open);
925
+ $("player-title").textContent = doc.title;
926
+ const launch =
927
+ '<script>const start=()=>{const go=document.querySelector(".ed-playgo");if(go){loaded.disconnect();go.click();}};const loaded=new MutationObserver(start);loaded.observe(document.body,{childList:true,subtree:true});start();</' +
928
+ "script>";
929
+ $("player-frame").srcdoc = htmlWithDeck(runtime, { ...doc, readonly: true })
930
+ .replace(/<head>/i, () => `<head>${frameHead(open.token)}`)
931
+ .replace(/<\/body>/i, launch + "</body>");
932
+ $("player").showModal();
933
+ $("player-frame").focus();
934
+ } catch {
935
+ notice(S.transferFailed);
936
+ }
937
+ };
938
+ $("player-close").onclick = () => $("player").close();
939
+ $("player").onclose = () => {
940
+ $("player-frame").removeAttribute("srcdoc");
941
+ };
942
+ $("import").onclick = $("start-import").onclick = () => $("file").click();
943
+ $("file").onchange = () => {
944
+ const [file] = $("file").files;
945
+ $("file").value = "";
946
+ if (file) void importFile(file);
947
+ };
948
+ $("pptx").onclick = async () => {
949
+ if (!open) return;
950
+ $("pptx").disabled = true;
951
+ try {
952
+ const doc = await savedSnapshot(open);
953
+ await downloadDeck(doc.title, "pptx", await exportPowerPoint(doc));
954
+ } catch (e) {
955
+ notice(e.message === "unsupportedPowerPoint" ? S.unsupportedPowerPoint : S.transferFailed);
956
+ } finally {
957
+ $("pptx").disabled = false;
958
+ }
959
+ };
960
+ $("export").onclick = () => void exportDeck().catch(() => notice(S.transferFailed));
961
+ $("rail-toggle").onclick = () => {
962
+ const off = app.dataset.rail !== "off";
963
+ app.dataset.rail = off ? "off" : "on";
964
+ $("rail-toggle").setAttribute("aria-pressed", String(!off));
965
+ };
966
+ $("ask").onsubmit = (event) => {
967
+ event.preventDefault();
968
+ if ($("send").disabled) return;
969
+ // No default model and none chosen for this deck: the request could only fail. Keep the text
970
+ // and open the model picker instead.
971
+ if (models.needsModel(open)) {
972
+ notice(S.noModel);
973
+ models.pick(false);
974
+ return;
975
+ }
976
+ const text = $("prompt").value;
977
+ $("prompt").value = "";
978
+ void ask(text);
979
+ };
980
+ $("prompt").onkeydown = (event) => {
981
+ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
982
+ event.preventDefault();
983
+ $("ask").requestSubmit();
984
+ }
985
+ };
986
+ $("stop").onclick = () => talk.sessionId && sdk && void sdk.abortSession(talk.sessionId);
987
+ $("rail-reset").onclick = async () => {
988
+ if (open === null) return;
989
+ ++talkRevision;
990
+ await send("/ask/reset", "POST", { deck: open.id });
991
+ await refreshTalk();
992
+ };
993
+ $("start-sample").onclick = async () => {
994
+ const doc = parseDeck(await (await fetch("sample.bento.json")).text());
995
+ if (locale === "zh") {
996
+ doc.title = "用四页了解 PenguinHarness";
997
+ const [cover, overview, chart, start] = doc.slides;
998
+ cover.notes = "读出标题,给观众一点时间思考。";
999
+ cover.elements.find((e) => e.id === "headline").html = "越用越懂你工作的智能体";
1000
+ overview.notes = "用三句话概括智能体能做什么。";
1001
+ const labels = {
1002
+ headline: "它能做什么",
1003
+ "card-1-title": "动手执行",
1004
+ "card-1-body": "在你的工作区里,使用你选择的工具、技能和沙盒完成任务。",
1005
+ "card-2-title": "记住经验",
1006
+ "card-2-body": "在智能体状态中保留技能、记忆和应用,下次继续用。",
1007
+ "card-3-title": "积累改进",
1008
+ "card-3-body": "在基准测试上验证每次调整,只保留得分更高的改动。",
1009
+ };
1010
+ for (const element of overview.elements)
1011
+ if (labels[element.id]) element.html = labels[element.id];
1012
+ chart.notes = "图中是示例分数,可以请智能体换成自己的数据。";
1013
+ chart.elements.find((e) => e.id === "headline").html = "每轮改进的得分";
1014
+ const option = chart.elements.find((e) => e.id === "chart").option;
1015
+ option.xAxis.data = ["第 0 轮", "第 1 轮", "第 2 轮", "第 3 轮"];
1016
+ option.series[0].name = "示例得分";
1017
+ start.notes = "最后介绍上手的三个步骤。";
1018
+ const steps = [
1019
+ "开始使用",
1020
+ "<b>1.</b> 安装桌面应用或命令行工具。",
1021
+ "<b>2.</b> 添加模型,开始一次对话。",
1022
+ "<b>3.</b> 从插件市场安装你需要的工具。",
1023
+ ];
1024
+ start.elements
1025
+ .filter((e) => e.type === "text")
1026
+ .forEach((e, index) => {
1027
+ e.html = steps[index];
1028
+ });
1029
+ }
1030
+ await createDeck(doc.title, doc);
1031
+ };
1032
+ $("start-ask").onsubmit = async (event) => {
1033
+ event.preventDefault();
1034
+ const text = $("start-prompt").value.trim();
1035
+ if (text === "") return;
1036
+ const title = text.split(/[\n。.!?!?]/)[0].slice(0, 40) || S.untitled;
1037
+ const chosen = models.startChoice();
1038
+ if (!chosen && models.needsModel(null)) {
1039
+ notice(S.noModel);
1040
+ models.pick(true);
1041
+ return;
1042
+ }
1043
+ await createDeck(title, blankDeck(title));
1044
+ const deck = open;
1045
+ if (!deck) return;
1046
+ try {
1047
+ await models.prepareStart(deck);
1048
+ } catch (error) {
1049
+ if (open === deck) {
1050
+ $("prompt").value = text;
1051
+ notice(S.choiceFailed(String(error.message || error)));
1052
+ }
1053
+ return;
1054
+ }
1055
+ if (open === deck) await ask(text, chosen);
1056
+ models.clearStartChoice();
1057
+ };
1058
+
1059
+ function listen() {
1060
+ document.addEventListener("visibilitychange", () => {
1061
+ if (document.visibilityState === "visible" && app.dataset.view === "start") void refreshDecks();
1062
+ });
1063
+ const events = new EventSource("../api/events");
1064
+ let lost = false;
1065
+ events.onerror = () => {
1066
+ lost = true;
1067
+ };
1068
+ events.onopen = () => {
1069
+ if (!lost) return;
1070
+ lost = false;
1071
+ // What changed while the stream was down was never announced: look again.
1072
+ void refreshDecks();
1073
+ if (open !== null) void fileChanged(open);
1074
+ };
1075
+ events.addEventListener("decks", (event) => {
1076
+ const { changed, removed } = JSON.parse(event.data);
1077
+ void refreshDecks();
1078
+ if (open === null) return;
1079
+ if (removed.includes(open.id)) deckGone(open);
1080
+ else if (changed.includes(open.id)) void fileChanged(open);
1081
+ });
1082
+ }
1083
+
1084
+ async function start() {
1085
+ setView("start");
1086
+ filesPage.render(decks, "loading");
1087
+ try {
1088
+ const info = await getJson("/info");
1089
+ if (!info.supported) {
1090
+ setView("unsupported");
1091
+ return;
1092
+ }
1093
+ connected = true;
1094
+ listen();
1095
+ await refreshDecks();
1096
+ } catch {
1097
+ filesPage.render(decks, "error");
1098
+ }
1099
+ }
1100
+
1101
+ void start();