@open-slide/core 2.3.2 → 2.4.0

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 (85) hide show
  1. package/dist/{build-8lRsgsO4.js → build-D7GwYl8d.js} +1 -1
  2. package/dist/cli/bin.js +4 -4
  3. package/dist/{config-DJ8ZOe7C.d.ts → config-CfhtJxQH.d.ts} +1 -1
  4. package/dist/{config-D2Mq1vSW.js → config-D4uPk_tM.js} +383 -138
  5. package/dist/{dev-BvefEp1Q.js → dev-DyCDMbHB.js} +10 -10
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +9 -1
  8. package/dist/locale/index.d.ts +1 -1
  9. package/dist/locale/index.js +1 -1
  10. package/dist/{preview-D8ognobz.js → preview-DjIFvt0K.js} +1 -1
  11. package/dist/{types-tdaXSyah.d.ts → types-ZfArJF0d.d.ts} +20 -13
  12. package/dist/{update-BivdNgL3.js → update-BKhRM7o4.js} +30 -3
  13. package/dist/vite/index.d.ts +1 -1
  14. package/dist/vite/index.js +1 -1
  15. package/dist/{zh-tw-DXcqQTrA.js → zh-tw-D7LfGVmA.js} +215 -65
  16. package/package.json +4 -5
  17. package/src/agent/provider.ts +8 -1
  18. package/src/agent/types.ts +17 -2
  19. package/src/app/app.tsx +2 -0
  20. package/src/app/components/agent/agent-markdown.tsx +3 -6
  21. package/src/app/components/agent/agent-panel.tsx +36 -258
  22. package/src/app/components/agent/agent-presence.tsx +1 -1
  23. package/src/app/components/agent/composer.tsx +52 -24
  24. package/src/app/components/agent/effort-slider.tsx +172 -0
  25. package/src/app/components/agent/model-menu.tsx +170 -0
  26. package/src/app/components/agent/permission-menu.tsx +88 -0
  27. package/src/app/components/agent/transcript.tsx +23 -31
  28. package/src/app/components/command/home-command-menu.tsx +4 -1
  29. package/src/app/components/command/slide-command-menu.tsx +4 -1
  30. package/src/app/components/export-progress-toast.tsx +3 -1
  31. package/src/app/components/inspector/asset-picker-dialog.tsx +1 -1
  32. package/src/app/components/inspector/comment-layer.tsx +3 -3
  33. package/src/app/components/inspector/inline-text-editor.tsx +1 -12
  34. package/src/app/components/inspector/inspect-overlay.tsx +9 -1
  35. package/src/app/components/inspector/inspector-panel.tsx +8 -35
  36. package/src/app/components/inspector/inspector-provider.tsx +177 -36
  37. package/src/app/components/inspector/page-panel.tsx +270 -0
  38. package/src/app/components/language-toggle.tsx +13 -11
  39. package/src/app/components/note-markdown.test.tsx +12 -6
  40. package/src/app/components/note-markdown.tsx +16 -21
  41. package/src/app/components/overview-grid.tsx +3 -3
  42. package/src/app/components/panel/editor-sidebar.tsx +43 -8
  43. package/src/app/components/panel/panel-shell.tsx +9 -5
  44. package/src/app/components/panel/save-card.tsx +1 -1
  45. package/src/app/components/sidebar/folder-item.tsx +4 -1
  46. package/src/app/components/sidebar/sidebar.tsx +11 -8
  47. package/src/app/components/style-panel/design-provider.tsx +48 -11
  48. package/src/app/components/style-panel/use-design.ts +6 -1
  49. package/src/app/components/theme-toggle.tsx +16 -22
  50. package/src/app/components/thumbnail-rail.tsx +68 -49
  51. package/src/app/components/ui/context-menu.tsx +9 -10
  52. package/src/app/components/ui/dialog.tsx +2 -4
  53. package/src/app/components/ui/dropdown-menu.tsx +9 -10
  54. package/src/app/components/ui/popover.tsx +1 -1
  55. package/src/app/components/ui/select.tsx +2 -2
  56. package/src/app/components/ui/sonner.tsx +2 -2
  57. package/src/app/index.html +7 -0
  58. package/src/app/lib/agent/use-agent.ts +131 -37
  59. package/src/app/lib/desktop-host.ts +31 -0
  60. package/src/app/lib/desktop-routes.test.ts +54 -0
  61. package/src/app/lib/desktop-routes.ts +22 -0
  62. package/src/app/lib/desktop.ts +106 -0
  63. package/src/app/lib/export-pdf.ts +15 -7
  64. package/src/app/lib/inspector/color.ts +51 -0
  65. package/src/app/lib/inspector/fiber.ts +6 -0
  66. package/src/app/lib/inspector/use-editor.ts +2 -1
  67. package/src/app/lib/inspector/use-notes.test.ts +209 -0
  68. package/src/app/lib/inspector/use-notes.ts +331 -57
  69. package/src/app/lib/inspector/use-visual-editor.ts +9 -1
  70. package/src/app/lib/locale-store.ts +14 -2
  71. package/src/app/lib/note-markdown.test.ts +69 -5
  72. package/src/app/lib/note-markdown.ts +97 -22
  73. package/src/app/lib/transition.test.ts +84 -1
  74. package/src/app/lib/transition.ts +43 -0
  75. package/src/app/lib/unsaved.test.ts +253 -0
  76. package/src/app/lib/unsaved.ts +155 -0
  77. package/src/app/routes/home.tsx +1 -1
  78. package/src/app/routes/slide.tsx +114 -117
  79. package/src/app/styles.css +421 -1
  80. package/src/locale/en.ts +40 -15
  81. package/src/locale/es.ts +40 -17
  82. package/src/locale/ja.ts +40 -15
  83. package/src/locale/types.ts +19 -14
  84. package/src/locale/zh-cn.ts +40 -14
  85. package/src/locale/zh-tw.ts +40 -14
@@ -1,13 +1,13 @@
1
1
  import { n as defaultDesign } from "./design-Cpqx7SJs.js";
2
- import { A as reorderNotesArrayInSource, C as duplicatePageInDefaultExportInSource, D as removePageFromDefaultExportInSource, E as removeNotesElementInSource, F as validateSlideName, I as isLoopbackRequest, L as validateMutationRequest, M as rmSlideDir, N as slugifyTitle, O as renameSlideDir, P as updateMetaTitleInSource, S as duplicateNotesElementInSource, T as readMetaTitleInSource, _ as writeManifest, a as json, b as SLIDE_ID_RE, c as readSlideSource, d as foldersManifestPath, f as newFolderId, g as validateReorder, h as validateName, i as BodyTooLargeError, j as resolveSlideEntry, k as reorderDefaultExportPagesInSource, l as resolveSlideEntryPath, m as validateIcon, n as registerUpdateRoutes, o as makeContext, p as readManifest, r as runCommand, s as readBody, t as detectPackageManager, u as FOLDER_ID_RE, v as shortId, w as duplicateSlideDir, x as createBlankSlideDir } from "./update-BivdNgL3.js";
2
+ import { A as reorderDefaultExportPagesInSource, B as SHUTDOWN_GRACE_MS, C as duplicatePageInDefaultExportInSource, D as removeNotesElementInSource, E as readMetaTitleInSource, F as updateMetaTitleInSource, G as isLoopbackRequest, H as isSupervised, I as validateSlideName, K as validateMutationRequest, M as resolveSlideEntry, N as rmSlideDir, O as removePageFromDefaultExportInSource, P as slugifyTitle, S as duplicateNotesElementInSource, T as pageLayoutOfSource, V as isManagedCore, _ as writeManifest, a as json, b as SLIDE_ID_RE, c as readSlideSource, d as foldersManifestPath, f as newFolderId, g as validateReorder, h as validateName, i as BodyTooLargeError, j as reorderNotesArrayInSource, k as renameSlideDir, l as resolveSlideEntryPath, m as validateIcon, n as registerUpdateRoutes, o as makeContext, p as readManifest, r as runCommand, s as readBody, t as detectPackageManager, u as FOLDER_ID_RE, v as shortId, w as duplicateSlideDir, x as createBlankSlideDir } from "./update-BKhRM7o4.js";
3
3
  import { createRequire } from "node:module";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
7
7
  import { spawn } from "node:child_process";
8
8
  import fs from "node:fs/promises";
9
- import { parse } from "@babel/parser";
10
9
  import { randomBytes, randomUUID } from "node:crypto";
10
+ import { parse } from "@babel/parser";
11
11
  import tailwindcss from "@tailwindcss/vite";
12
12
  import react from "@vitejs/plugin-react";
13
13
  import os from "node:os";
@@ -161,21 +161,20 @@ function rewoundPrompt(text) {
161
161
  //#region src/agent/detect.ts
162
162
  const IS_WINDOWS = process.platform === "win32";
163
163
  const VERSION_TIMEOUT_MS = 5e3;
164
- function findOnPath(command, env = process.env) {
164
+ function findOnPath(command, env = process.env, accept = () => true) {
165
165
  const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
166
166
  const exts = IS_WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
167
167
  for (const dir of dirs) for (const ext of exts) {
168
168
  const candidate = path.join(dir, command + ext.toLowerCase());
169
169
  try {
170
- if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
170
+ if (statSync(candidate, { throwIfNoEntry: false })?.isFile() && accept(candidate)) return candidate;
171
171
  } catch {}
172
172
  }
173
173
  return null;
174
174
  }
175
175
  function findSpawnableCli(command, env = process.env) {
176
- const found = findOnPath(command, env);
177
- if (!found || !IS_WINDOWS) return found;
178
- return found.toLowerCase().endsWith(".exe") ? found : null;
176
+ if (!IS_WINDOWS) return findOnPath(command, env);
177
+ return findOnPath(command, env, (candidate) => candidate.toLowerCase().endsWith(".exe"));
179
178
  }
180
179
  const versionCache = /* @__PURE__ */ new Map();
181
180
  function commandVersion(file) {
@@ -228,6 +227,18 @@ function parseVersion(output) {
228
227
  const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
229
228
  return m ? m[1] : null;
230
229
  }
230
+ function versionAtLeast(version, floor) {
231
+ if (!version) return false;
232
+ const parts = (v) => v.split(/[-+]/)[0].split(".").map(Number);
233
+ const have = parts(version);
234
+ const need = parts(floor);
235
+ for (let i = 0; i < need.length; i++) {
236
+ const a = have[i] ?? 0;
237
+ if (Number.isNaN(a)) return false;
238
+ if (a !== need[i]) return a > need[i];
239
+ }
240
+ return true;
241
+ }
231
242
  function entryFromPackageJson(pkg) {
232
243
  const root = pickExport(pkg.exports);
233
244
  if (root) return root;
@@ -266,30 +277,39 @@ function pickCondition(target) {
266
277
  function resolveWorkspacePackage(userCwd, name) {
267
278
  let dir = path.resolve(userCwd);
268
279
  while (true) {
269
- const pkgJsonPath = path.join(dir, "node_modules", name, "package.json");
270
- if (existsSync(pkgJsonPath)) {
271
- let pkg;
272
- try {
273
- pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
274
- } catch {
275
- return null;
276
- }
277
- const entry = entryFromPackageJson(pkg);
278
- if (!entry) return null;
279
- const pkgDir = path.dirname(pkgJsonPath);
280
- return {
281
- dir: pkgDir,
282
- version: pkg.version ?? "0.0.0",
283
- entry: path.resolve(pkgDir, entry)
284
- };
285
- }
280
+ const pkgDir = path.join(dir, "node_modules", name);
281
+ if (existsSync(path.join(pkgDir, "package.json"))) return readPackageAt(pkgDir);
286
282
  const parent = path.dirname(dir);
287
283
  if (parent === dir) return null;
288
284
  dir = parent;
289
285
  }
290
286
  }
291
- async function importWorkspacePackage(userCwd, name) {
292
- const resolved = resolveWorkspacePackage(userCwd, name);
287
+ function readPackageAt(pkgDir) {
288
+ let pkg;
289
+ try {
290
+ pkg = JSON.parse(readFileSync(path.join(pkgDir, "package.json"), "utf8"));
291
+ } catch {
292
+ return null;
293
+ }
294
+ const entry = entryFromPackageJson(pkg);
295
+ if (!entry) return null;
296
+ return {
297
+ dir: pkgDir,
298
+ version: pkg.version ?? "0.0.0",
299
+ entry: path.resolve(pkgDir, entry)
300
+ };
301
+ }
302
+ function resolveAgentPackage(userCwd, name, env = process.env) {
303
+ const own = resolveWorkspacePackage(userCwd, name);
304
+ if (own) return own;
305
+ for (const dir of (env["OPEN_SLIDE_AGENT_MODULES"] ?? "").split(path.delimiter).filter(Boolean)) {
306
+ const pkgDir = path.join(dir, name);
307
+ if (existsSync(path.join(pkgDir, "package.json"))) return readPackageAt(pkgDir);
308
+ }
309
+ return null;
310
+ }
311
+ async function importAgentPackage(userCwd, name) {
312
+ const resolved = resolveAgentPackage(userCwd, name);
293
313
  if (!resolved) return null;
294
314
  return await import(pathToFileURL(resolved.entry).href);
295
315
  }
@@ -326,6 +346,22 @@ const EDIT_TOOLS = /* @__PURE__ */ new Set([
326
346
  "Write",
327
347
  "NotebookEdit"
328
348
  ]);
349
+ const CLAUDE_PERMISSION_MODES = {
350
+ supervised: "default",
351
+ acceptEdits: "acceptEdits",
352
+ auto: "auto",
353
+ fullAccess: "bypassPermissions"
354
+ };
355
+ const AUTO_MODE_SDK = "0.2.91";
356
+ const AUTO_MODE_CLI = "2.1.91";
357
+ function claudePermissionMode(mode, autoSupported) {
358
+ if (mode === "auto" && !autoSupported) return "default";
359
+ return CLAUDE_PERMISSION_MODES[mode];
360
+ }
361
+ async function supportsAutoMode(cwd, localCli) {
362
+ if (!versionAtLeast(resolveAgentPackage(cwd, CLAUDE_SDK_PACKAGE)?.version, AUTO_MODE_SDK)) return false;
363
+ return !localCli || versionAtLeast(await commandVersion(localCli), AUTO_MODE_CLI);
364
+ }
329
365
  function claudeEffort(effort) {
330
366
  return effort && effort !== "minimal" ? effort : void 0;
331
367
  }
@@ -513,7 +549,7 @@ function createClaudeProvider() {
513
549
  return CLAUDE_MODELS;
514
550
  },
515
551
  async run(opts) {
516
- const sdk = await importWorkspacePackage(opts.cwd, CLAUDE_SDK_PACKAGE);
552
+ const sdk = await importAgentPackage(opts.cwd, CLAUDE_SDK_PACKAGE);
517
553
  if (!sdk || typeof sdk.query !== "function") throw new ProviderUnavailableError(this);
518
554
  const mapper = createClaudeMapper(opts.emit, opts.cwd);
519
555
  if (opts.signal.aborted) return;
@@ -536,7 +572,7 @@ function createClaudeProvider() {
536
572
  };
537
573
  }
538
574
  const target = input.file_path ?? input.notebook_path;
539
- if (EDIT_TOOLS.has(toolName) && isInsideRoots(opts.cwd, target, opts.writableRoots)) return {
575
+ if (opts.permissionMode !== "supervised" && EDIT_TOOLS.has(toolName) && isInsideRoots(opts.cwd, target, opts.writableRoots)) return {
540
576
  behavior: "allow",
541
577
  updatedInput: input
542
578
  };
@@ -554,13 +590,15 @@ function createClaudeProvider() {
554
590
  };
555
591
  };
556
592
  const localCli = findSpawnableCli("claude");
593
+ const autoSupported = opts.permissionMode === "auto" && await supportsAutoMode(opts.cwd, localCli);
557
594
  const effort = claudeEffort(opts.effort);
558
595
  let stderr = "";
559
596
  const stream = sdk.query({
560
597
  prompt: opts.prompt,
561
598
  options: {
562
599
  cwd: opts.cwd,
563
- permissionMode: "default",
600
+ permissionMode: claudePermissionMode(opts.permissionMode, autoSupported),
601
+ ...opts.permissionMode === "fullAccess" ? { allowDangerouslySkipPermissions: true } : {},
564
602
  settingSources: [
565
603
  "user",
566
604
  "project",
@@ -606,18 +644,34 @@ const AGENT_EFFORTS = [
606
644
  "xhigh",
607
645
  "max"
608
646
  ];
647
+ const AGENT_PERMISSION_MODES = [
648
+ "supervised",
649
+ "acceptEdits",
650
+ "auto",
651
+ "fullAccess"
652
+ ];
653
+ function isAgentPermissionMode(value) {
654
+ return typeof value === "string" && AGENT_PERMISSION_MODES.includes(value);
655
+ }
609
656
  function isAgentProviderId(value) {
610
657
  return typeof value === "string" && AGENT_PROVIDER_IDS.includes(value);
611
658
  }
612
659
  function isAgentEffort(value) {
613
660
  return typeof value === "string" && AGENT_EFFORTS.includes(value);
614
661
  }
662
+ const AGENT_EVENT = "open-slide:agent";
615
663
  function sessionSummary(session) {
616
664
  const { providerSessionId: _p, providerCheckpoint: _c, trimmed: _t, items: _i, ...summary } = session;
617
665
  return summary;
618
666
  }
619
667
  //#endregion
620
668
  //#region src/agent/providers/codex.ts
669
+ const CODEX_SANDBOXES = {
670
+ supervised: "read-only",
671
+ acceptEdits: "workspace-write",
672
+ auto: "workspace-write",
673
+ fullAccess: "danger-full-access"
674
+ };
621
675
  const CODEX_SDK_PACKAGE = "@openai/codex-sdk";
622
676
  const CODEX_DEFAULT_MODEL = {
623
677
  id: "",
@@ -812,14 +866,14 @@ function createCodexProvider() {
812
866
  cliCommand: "codex",
813
867
  models: readCodexModels,
814
868
  async run(opts) {
815
- const sdk = await importWorkspacePackage(opts.cwd, CODEX_SDK_PACKAGE);
869
+ const sdk = await importAgentPackage(opts.cwd, CODEX_SDK_PACKAGE);
816
870
  if (!sdk || typeof sdk.Codex !== "function") throw new ProviderUnavailableError(this);
817
871
  const localCli = findSpawnableCli("codex");
818
872
  const codex = new sdk.Codex(localCli ? { codexPathOverride: localCli } : {});
819
873
  const threadOptions = {
820
874
  workingDirectory: opts.cwd,
821
875
  skipGitRepoCheck: true,
822
- sandboxMode: "workspace-write",
876
+ sandboxMode: CODEX_SANDBOXES[opts.permissionMode],
823
877
  approvalPolicy: "never",
824
878
  ...opts.model ? { model: opts.model } : {},
825
879
  ...opts.effort ? { modelReasoningEffort: opts.effort } : {}
@@ -900,32 +954,34 @@ function createSessionStore(opts) {
900
954
  const sessions = /* @__PURE__ */ new Map();
901
955
  const listeners = /* @__PURE__ */ new Set();
902
956
  let saveTimer = null;
957
+ let closed = false;
903
958
  let seq = 0;
904
959
  const order = /* @__PURE__ */ new Map();
905
960
  if (opts.file) for (const s of readPersisted(opts.file)) {
906
961
  sessions.set(s.id, s);
907
962
  order.set(s.id, seq++);
908
963
  }
964
+ let rev = 0;
909
965
  const emit = (event) => {
910
- for (const l of listeners) l(event);
966
+ const numbered = {
967
+ ...event,
968
+ rev: ++rev
969
+ };
970
+ for (const l of listeners) l(numbered);
911
971
  };
912
972
  const scheduleSave = () => {
913
- if (!opts.file) return;
973
+ if (!opts.file || closed) return;
914
974
  if (saveTimer) clearTimeout(saveTimer);
915
975
  saveTimer = setTimeout(() => {
916
976
  saveTimer = null;
917
977
  save();
918
978
  }, SAVE_DEBOUNCE_MS);
919
979
  };
920
- const writeSnapshot = async (file) => {
921
- const body = {
922
- version: 1,
923
- sessions: list().flatMap((s) => sessions.get(s.id) ?? [])
924
- };
980
+ const writeSnapshot = async (file, body) => {
925
981
  const tmp = `${file}.tmp`;
926
982
  try {
927
983
  await fs.mkdir(path.dirname(file), { recursive: true });
928
- await fs.writeFile(tmp, JSON.stringify(body), {
984
+ await fs.writeFile(tmp, body, {
929
985
  encoding: "utf8",
930
986
  mode: 384
931
987
  });
@@ -938,8 +994,12 @@ function createSessionStore(opts) {
938
994
  let saving = Promise.resolve();
939
995
  const save = () => {
940
996
  const file = opts.file;
941
- if (!file) return saving;
942
- saving = saving.then(() => writeSnapshot(file));
997
+ if (!file || closed) return saving;
998
+ const body = JSON.stringify({
999
+ version: 1,
1000
+ sessions: list().flatMap((s) => sessions.get(s.id) ?? [])
1001
+ });
1002
+ saving = saving.then(() => writeSnapshot(file, body));
943
1003
  return saving;
944
1004
  };
945
1005
  const touch = (session) => {
@@ -1079,6 +1139,11 @@ function createSessionStore(opts) {
1079
1139
  }
1080
1140
  await save();
1081
1141
  }
1142
+ async function close() {
1143
+ const last = flush();
1144
+ closed = true;
1145
+ await last;
1146
+ }
1082
1147
  return {
1083
1148
  list,
1084
1149
  get,
@@ -1090,7 +1155,9 @@ function createSessionStore(opts) {
1090
1155
  truncateFrom,
1091
1156
  appendDelta,
1092
1157
  subscribe,
1093
- flush
1158
+ flush,
1159
+ close,
1160
+ rev: () => rev
1094
1161
  };
1095
1162
  }
1096
1163
  //#endregion
@@ -1104,6 +1171,7 @@ function createAgentRunner(opts) {
1104
1171
  const running = /* @__PURE__ */ new Map();
1105
1172
  const pending = /* @__PURE__ */ new Map();
1106
1173
  const lastOptions = /* @__PURE__ */ new Map();
1174
+ const turns = /* @__PURE__ */ new Set();
1107
1175
  const now = () => (/* @__PURE__ */ new Date()).toISOString();
1108
1176
  function isRunning(sessionId) {
1109
1177
  return running.has(sessionId);
@@ -1267,6 +1335,7 @@ function createAgentRunner(opts) {
1267
1335
  }
1268
1336
  });
1269
1337
  });
1338
+ const permissionMode = options.permissionMode ?? "auto";
1270
1339
  const requestPermission = (request) => new Promise((resolve) => {
1271
1340
  if (controller.signal.aborted) return resolve(false);
1272
1341
  const item = store.appendItem(sessionId, {
@@ -1276,9 +1345,8 @@ function createAgentRunner(opts) {
1276
1345
  tool: request.tool,
1277
1346
  title: request.title,
1278
1347
  detail: request.detail,
1279
- status: options.autoApprove ? "allowed" : "pending"
1348
+ status: "pending"
1280
1349
  });
1281
- if (options.autoApprove) return resolve(true);
1282
1350
  pending.set(item.id, {
1283
1351
  kind: "permission",
1284
1352
  resolve: (allow) => {
@@ -1302,7 +1370,8 @@ function createAgentRunner(opts) {
1302
1370
  aborted: controller.signal.aborted
1303
1371
  });
1304
1372
  store.patch(sessionId, { status: "idle" });
1305
- if (onTurnEnd) Promise.resolve().then(() => onTurnEnd({
1373
+ if (!onTurnEnd) return;
1374
+ return Promise.resolve().then(() => onTurnEnd({
1306
1375
  sessionId,
1307
1376
  userItemId
1308
1377
  })).catch((err) => {
@@ -1310,7 +1379,7 @@ function createAgentRunner(opts) {
1310
1379
  });
1311
1380
  };
1312
1381
  const prompt = buildTurnPrompt(promptText, context);
1313
- provider.run({
1382
+ const turn = provider.run({
1314
1383
  cwd: userCwd,
1315
1384
  writableRoots,
1316
1385
  prompt,
@@ -1319,6 +1388,7 @@ function createAgentRunner(opts) {
1319
1388
  resumeAt,
1320
1389
  model: options.model ?? null,
1321
1390
  effort: options.effort ?? null,
1391
+ permissionMode,
1322
1392
  signal: controller.signal,
1323
1393
  emit,
1324
1394
  askUser,
@@ -1330,6 +1400,8 @@ function createAgentRunner(opts) {
1330
1400
  text: err instanceof Error ? err.message : String(err)
1331
1401
  });
1332
1402
  }).finally(finish);
1403
+ turns.add(turn);
1404
+ turn.finally(() => turns.delete(turn));
1333
1405
  }
1334
1406
  function stop(sessionId) {
1335
1407
  const controller = running.get(sessionId);
@@ -1387,8 +1459,9 @@ function createAgentRunner(opts) {
1387
1459
  });
1388
1460
  return true;
1389
1461
  }
1390
- function stopAll() {
1462
+ async function stopAll() {
1391
1463
  for (const id of Array.from(running.keys())) stop(id);
1464
+ await Promise.allSettled(turns);
1392
1465
  }
1393
1466
  return {
1394
1467
  send,
@@ -1402,7 +1475,7 @@ function createAgentRunner(opts) {
1402
1475
  //#region src/agent/status.ts
1403
1476
  const INSTALL_TIMEOUT_MS = 6e5;
1404
1477
  async function providerStatus(userCwd, provider) {
1405
- const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
1478
+ const sdk = resolveAgentPackage(userCwd, provider.sdkPackage);
1406
1479
  const cliPath = findOnPath(provider.cliCommand);
1407
1480
  const [cliVersion, models] = await Promise.all([cliPath ? commandVersion(cliPath) : null, provider.models()]);
1408
1481
  return {
@@ -1746,6 +1819,24 @@ async function loadUserConfig(userCwd) {
1746
1819
  }, file, userCwd, "silent"))?.config ?? {};
1747
1820
  }
1748
1821
  //#endregion
1822
+ //#region src/vite/routes/agent-events.ts
1823
+ function createAgentBroadcast(ws, enabled) {
1824
+ const sockets = /* @__PURE__ */ new Set();
1825
+ ws.on("connection", (socket, req) => {
1826
+ if (!enabled || !isLoopbackRequest(req)) return;
1827
+ sockets.add(socket);
1828
+ socket.on("close", () => sockets.delete(socket));
1829
+ });
1830
+ return (event) => {
1831
+ const frame = JSON.stringify({
1832
+ type: "custom",
1833
+ event: AGENT_EVENT,
1834
+ data: event
1835
+ });
1836
+ for (const socket of sockets) if (socket.readyState === socket.OPEN) socket.send(frame);
1837
+ };
1838
+ }
1839
+ //#endregion
1749
1840
  //#region src/vite/routes/agent.ts
1750
1841
  function parseContext(raw) {
1751
1842
  if (!raw || typeof raw !== "object") return void 0;
@@ -1773,7 +1864,7 @@ const MODEL_RE = /^[\w.:[\]-]{1,80}$/;
1773
1864
  function parseModel(raw) {
1774
1865
  return typeof raw === "string" && MODEL_RE.test(raw) ? raw : null;
1775
1866
  }
1776
- async function renamePlaceholderDeck(server, ctx, store, broadcast, turn) {
1867
+ async function renamePlaceholderDeck(server, ctx, store, broadcast, closing, turn) {
1777
1868
  const session = store.get(turn.sessionId);
1778
1869
  const slideId = session?.slideId;
1779
1870
  if (!session || !slideId || !UNTITLED_SLIDE_ID_RE.test(slideId)) return;
@@ -1800,6 +1891,7 @@ async function renamePlaceholderDeck(server, ctx, store, broadcast, turn) {
1800
1891
  const desired = slugifyTitle(marked ?? "") || slugifyTitle(meta.title);
1801
1892
  if (!desired || UNTITLED_SLIDE_ID_RE.test(desired)) return;
1802
1893
  if (store.list().some((s) => s.slideId === slideId && s.status === "running")) return;
1894
+ if (closing()) return;
1803
1895
  recordWrite(entry);
1804
1896
  const renamed = await renameSlideDir(ctx.slidesRoot, slideId, desired);
1805
1897
  if (!renamed.ok) return;
@@ -1835,38 +1927,42 @@ function parseTurnSettings(raw) {
1835
1927
  const settings = {};
1836
1928
  const context = parseContext(raw.context);
1837
1929
  if (context) settings.context = context;
1838
- if (typeof raw.autoApprove === "boolean") settings.autoApprove = raw.autoApprove;
1930
+ if (isAgentPermissionMode(raw.permissionMode)) settings.permissionMode = raw.permissionMode;
1839
1931
  if ("model" in raw) settings.model = parseModel(raw.model);
1840
1932
  if ("effort" in raw) settings.effort = isAgentEffort(raw.effort) ? raw.effort : null;
1841
1933
  return settings;
1842
1934
  }
1843
1935
  const AGENT_BODY_LIMIT = 1048576;
1936
+ const STOP_TIMEOUT_MS = SHUTDOWN_GRACE_MS - 1e3;
1937
+ var ClosingError = class extends Error {};
1844
1938
  function registerAgentRoutes(server, ctx) {
1845
1939
  const providers = createProviders();
1846
1940
  const store = createSessionStore({ file: path.join(ctx.userCwd, "node_modules", ".open-slide", "agent-sessions.json") });
1847
- const streams = /* @__PURE__ */ new Set();
1848
- const broadcast = (event) => {
1849
- const frame = `data: ${JSON.stringify(event)}\n\n`;
1850
- for (const stream of streams) stream.write(frame);
1851
- };
1852
- const heartbeat = setInterval(() => {
1853
- for (const stream of streams) stream.write(": ping\n\n");
1854
- }, 25e3);
1855
- heartbeat.unref();
1941
+ const broadcast = createAgentBroadcast(server.ws, ctx.agentEnabled);
1942
+ let closed = null;
1856
1943
  const runner = createAgentRunner({
1857
1944
  userCwd: ctx.userCwd,
1858
1945
  writableRoots: [ctx.slidesRoot, ctx.globalAssetsRoot],
1859
1946
  store,
1860
1947
  providers,
1861
- onTurnEnd: (turn) => renamePlaceholderDeck(server, ctx, store, broadcast, turn)
1948
+ onTurnEnd: (turn) => renamePlaceholderDeck(server, ctx, store, broadcast, () => closed !== null, turn)
1862
1949
  });
1863
1950
  store.subscribe(broadcast);
1864
- server.httpServer?.on("close", () => {
1865
- clearInterval(heartbeat);
1866
- for (const stream of streams) stream.end();
1867
- runner.stopAll();
1868
- store.flush();
1869
- });
1951
+ const close = () => {
1952
+ closed ??= (async () => {
1953
+ let timer;
1954
+ const timeout = new Promise((resolve) => {
1955
+ timer = setTimeout(resolve, STOP_TIMEOUT_MS);
1956
+ });
1957
+ await Promise.race([runner.stopAll(), timeout]);
1958
+ clearTimeout(timer);
1959
+ await store.close();
1960
+ })();
1961
+ return closed;
1962
+ };
1963
+ const assertOpen = () => {
1964
+ if (closed) throw new ClosingError();
1965
+ };
1870
1966
  const installsInFlight = /* @__PURE__ */ new Map();
1871
1967
  server.middlewares.use("/__agent", async (req, res, next) => {
1872
1968
  const url = new URL(req.url ?? "/", "http://local");
@@ -1885,23 +1981,12 @@ function registerAgentRoutes(server, ctx) {
1885
1981
  return json(res, 200, await agentStatus(ctx.userCwd, providers, pm));
1886
1982
  }
1887
1983
  if (!enabled) return json(res, 404, { error: "agent panel disabled" });
1888
- if (method === "GET" && url.pathname === "/events") {
1889
- res.writeHead(200, {
1890
- "content-type": "text/event-stream",
1891
- "cache-control": "no-store",
1892
- connection: "keep-alive"
1893
- });
1894
- res.write(": connected\n\n");
1895
- streams.add(res);
1896
- const drop = () => streams.delete(res);
1897
- res.on("close", drop);
1898
- res.on("error", drop);
1899
- return;
1900
- }
1984
+ if (method !== "GET") assertOpen();
1901
1985
  if (method === "POST" && url.pathname === "/install") {
1902
1986
  const guard = validateMutationRequest(req, { requireJsonBody: true });
1903
1987
  if (!guard.ok) return json(res, guard.status, { error: guard.error });
1904
1988
  const body = await readBody(req, AGENT_BODY_LIMIT);
1989
+ assertOpen();
1905
1990
  if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
1906
1991
  const provider = providers[body.provider];
1907
1992
  const pm = await detectPackageManager(ctx.userCwd);
@@ -1916,12 +2001,16 @@ function registerAgentRoutes(server, ctx) {
1916
2001
  }
1917
2002
  if (method === "GET" && url.pathname === "/sessions") {
1918
2003
  res.setHeader("cache-control", "no-store");
1919
- return json(res, 200, { sessions: store.list() });
2004
+ return json(res, 200, {
2005
+ sessions: store.list(),
2006
+ rev: store.rev()
2007
+ });
1920
2008
  }
1921
2009
  if (method === "POST" && url.pathname === "/sessions") {
1922
2010
  const guard = validateMutationRequest(req, { requireJsonBody: true });
1923
2011
  if (!guard.ok) return json(res, guard.status, { error: guard.error });
1924
2012
  const body = await readBody(req, AGENT_BODY_LIMIT);
2013
+ assertOpen();
1925
2014
  if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
1926
2015
  const slideId = typeof body.slideId === "string" && SLIDE_ID_RE.test(body.slideId) ? body.slideId : null;
1927
2016
  return json(res, 200, store.create(body.provider, slideId));
@@ -1933,7 +2022,10 @@ function registerAgentRoutes(server, ctx) {
1933
2022
  if (!session) return json(res, 404, { error: "session not found" });
1934
2023
  if (method === "GET" && !action) {
1935
2024
  res.setHeader("cache-control", "no-store");
1936
- return json(res, 200, session);
2025
+ return json(res, 200, {
2026
+ ...session,
2027
+ rev: store.rev()
2028
+ });
1937
2029
  }
1938
2030
  if (method === "DELETE" && !action) {
1939
2031
  const guard = validateMutationRequest(req);
@@ -1946,13 +2038,14 @@ function registerAgentRoutes(server, ctx) {
1946
2038
  const guard = validateMutationRequest(req, { requireJsonBody: true });
1947
2039
  if (!guard.ok) return json(res, guard.status, { error: guard.error });
1948
2040
  const body = await readBody(req, AGENT_BODY_LIMIT);
2041
+ assertOpen();
1949
2042
  if (typeof body.text !== "string" || !body.text.trim()) return json(res, 400, { error: "missing text" });
1950
2043
  if (runner.isRunning(id)) return json(res, 409, { error: "session is already running" });
1951
2044
  if (body.edit !== void 0 && !session.items.some((i) => i.id === body.edit && i.kind === "user")) return json(res, 400, { error: "unknown message" });
1952
2045
  await runner.send(id, {
1953
2046
  text: body.text,
1954
2047
  context: parseContext(body.context),
1955
- autoApprove: body.autoApprove === true,
2048
+ permissionMode: isAgentPermissionMode(body.permissionMode) ? body.permissionMode : void 0,
1956
2049
  model: parseModel(body.model),
1957
2050
  effort: isAgentEffort(body.effort) ? body.effort : null,
1958
2051
  edit: typeof body.edit === "string" ? body.edit : void 0
@@ -1968,6 +2061,7 @@ function registerAgentRoutes(server, ctx) {
1968
2061
  const guard = validateMutationRequest(req, { requireJsonBody: true });
1969
2062
  if (!guard.ok) return json(res, guard.status, { error: guard.error });
1970
2063
  const body = await readBody(req, AGENT_BODY_LIMIT);
2064
+ assertOpen();
1971
2065
  const payload = parseRespond(body);
1972
2066
  if (typeof body.itemId !== "string" || !payload) return json(res, 400, { error: "invalid response" });
1973
2067
  const ok = runner.respond(id, body.itemId, payload, parseTurnSettings(body));
@@ -1977,9 +2071,11 @@ function registerAgentRoutes(server, ctx) {
1977
2071
  next();
1978
2072
  } catch (err) {
1979
2073
  if (err instanceof BodyTooLargeError) return json(res, 413, { error: err.message });
2074
+ if (err instanceof ClosingError) return json(res, 503, { error: "the dev server is shutting down" });
1980
2075
  json(res, 500, { error: String(err.message ?? err) });
1981
2076
  }
1982
2077
  });
2078
+ return close;
1983
2079
  }
1984
2080
  //#endregion
1985
2081
  //#region src/editing/babel-walk.ts
@@ -2215,6 +2311,7 @@ function elementTextMatches(element, prevText) {
2215
2311
  return textRangeContent(collectTextRangeParts(element)) === prevText;
2216
2312
  }
2217
2313
  function findElementForEdit(ast, line, column, ops) {
2314
+ if (ops.some((op) => op.kind === "remove-element")) return findJsxByStart(ast, line, column);
2218
2315
  const element = findInnermostJsxElement(ast, line, column);
2219
2316
  const prevText = fallbackTextForOps(ops);
2220
2317
  if (prevText === null) return element;
@@ -2894,6 +2991,34 @@ function planReplacePlaceholder(ast, element, assetPath) {
2894
2991
  elementSplice: spliceRange(element, `<img src={${identifier}} alt=${jsString(hint)} style={{ ${styleParts.join(", ")} }} />`)
2895
2992
  };
2896
2993
  }
2994
+ function isJsxChild(ast, element) {
2995
+ let found = false;
2996
+ walkJsx(ast, (n) => {
2997
+ if ((t.isJSXElement(n) || t.isJSXFragment(n)) && n.children.includes(element)) {
2998
+ found = true;
2999
+ return "stop";
3000
+ }
3001
+ });
3002
+ return found;
3003
+ }
3004
+ function planRemoveElement(ast, source, element) {
3005
+ if (!isJsxChild(ast, element)) return spliceRange(element, "null");
3006
+ const start = element.start ?? 0;
3007
+ const end = element.end ?? 0;
3008
+ const lineStart = source.lastIndexOf("\n", start - 1) + 1;
3009
+ const newline = source.indexOf("\n", end);
3010
+ const lineEnd = newline === -1 ? source.length : newline;
3011
+ if (source.slice(lineStart, start).trim() || source.slice(end, lineEnd).trim()) return {
3012
+ from: start,
3013
+ to: end,
3014
+ text: ""
3015
+ };
3016
+ return {
3017
+ from: lineStart,
3018
+ to: newline === -1 ? lineEnd : newline + 1,
3019
+ text: ""
3020
+ };
3021
+ }
2897
3022
  function applyEdit(source, line, column, ops) {
2898
3023
  const plan = planEdit(source, line, column, ops);
2899
3024
  if (!plan.ok) return plan;
@@ -2919,6 +3044,10 @@ function planEdit(source, line, column, ops, exactLocation = false) {
2919
3044
  status: 422,
2920
3045
  error: "no JSX element at location"
2921
3046
  };
3047
+ if (ops.some((op) => op.kind === "remove-element")) return {
3048
+ ok: true,
3049
+ splices: [planRemoveElement(ast, source, element)]
3050
+ };
2922
3051
  const splices = [];
2923
3052
  const styleOps = ops.flatMap((op) => op.kind === "set-style" ? [{
2924
3053
  key: op.key,
@@ -4059,11 +4188,9 @@ function registerGfontsRoutes(server) {
4059
4188
  }
4060
4189
  });
4061
4190
  }
4062
- const DEV_SUPERVISED_ENV = "OPEN_SLIDE_DEV_SUPERVISED";
4191
+ //#endregion
4192
+ //#region src/vite/routes/restart.ts
4063
4193
  const executionId = randomUUID();
4064
- function isSupervised() {
4065
- return process.env[DEV_SUPERVISED_ENV] === "1";
4066
- }
4067
4194
  function registerRestartRoutes(server) {
4068
4195
  server.middlewares.use("/__server-status", (req, res, next) => {
4069
4196
  if ((req.method ?? "GET") !== "GET") return next();
@@ -4083,7 +4210,36 @@ function registerRestartRoutes(server) {
4083
4210
  });
4084
4211
  }
4085
4212
  //#endregion
4213
+ //#region src/vite/file-lock.ts
4214
+ const tails = /* @__PURE__ */ new Map();
4215
+ function withFileLock(file, task) {
4216
+ const result = (tails.get(file) ?? Promise.resolve()).then(task);
4217
+ const tail = result.catch(() => {});
4218
+ tails.set(file, tail);
4219
+ tail.then(() => {
4220
+ if (tails.get(file) === tail) tails.delete(file);
4221
+ });
4222
+ return result;
4223
+ }
4224
+ //#endregion
4086
4225
  //#region src/vite/routes/slides.ts
4226
+ function editSlideSource(entry, edit) {
4227
+ return withFileLock(entry, async () => {
4228
+ let source;
4229
+ try {
4230
+ source = await fs.readFile(entry, "utf8");
4231
+ } catch {
4232
+ return {
4233
+ ok: false,
4234
+ status: 404,
4235
+ error: "slide not found"
4236
+ };
4237
+ }
4238
+ const result = edit(source);
4239
+ if (result.ok && result.source !== source) await fs.writeFile(entry, result.source, "utf8");
4240
+ return result;
4241
+ });
4242
+ }
4087
4243
  function registerSlideRoutes(server, ctx) {
4088
4244
  server.middlewares.use("/__slides", async (req, res, next) => {
4089
4245
  const url = new URL(req.url ?? "/", "http://local");
@@ -4116,21 +4272,30 @@ function registerSlideRoutes(server, ctx) {
4116
4272
  }
4117
4273
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
4118
4274
  if (!entry) return json(res, 400, { error: "invalid slideId" });
4119
- let source;
4120
- try {
4121
- source = await fs.readFile(entry, "utf8");
4122
- } catch {
4123
- return json(res, 404, { error: "slide not found" });
4124
- }
4125
- const reordered = reorderDefaultExportPagesInSource(source, order);
4126
- if (reordered === null) return json(res, 422, { error: "could not reorder pages — order must be a permutation of the existing array" });
4127
- const withNotes = reorderNotesArrayInSource(reordered, order);
4128
- if (withNotes === null) return json(res, 422, { error: "could not reorder pages — `notes` export has an unexpected shape" });
4129
- if (withNotes !== source) await fs.writeFile(entry, withNotes, "utf8");
4275
+ const result = await editSlideSource(entry, (source) => {
4276
+ const reordered = reorderDefaultExportPagesInSource(source, order);
4277
+ if (reordered === null) return {
4278
+ ok: false,
4279
+ status: 422,
4280
+ error: "could not reorder pages — order must be a permutation of the existing array"
4281
+ };
4282
+ const withNotes = reorderNotesArrayInSource(reordered, order);
4283
+ if (withNotes === null) return {
4284
+ ok: false,
4285
+ status: 422,
4286
+ error: "could not reorder pages — `notes` export has an unexpected shape"
4287
+ };
4288
+ return {
4289
+ ok: true,
4290
+ source: withNotes
4291
+ };
4292
+ });
4293
+ if (!result.ok) return json(res, result.status, { error: result.error });
4130
4294
  return json(res, 200, {
4131
4295
  ok: true,
4132
4296
  slideId,
4133
- order
4297
+ order,
4298
+ layout: pageLayoutOfSource(result.source)
4134
4299
  });
4135
4300
  }
4136
4301
  const pageOpMatch = url.pathname.match(/^\/([^/]+)\/pages\/(\d+)(?:\/([a-z]+))?$/);
@@ -4146,21 +4311,30 @@ function registerSlideRoutes(server, ctx) {
4146
4311
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4147
4312
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
4148
4313
  if (!entry) return json(res, 400, { error: "invalid slideId" });
4149
- let source;
4150
- try {
4151
- source = await fs.readFile(entry, "utf8");
4152
- } catch {
4153
- return json(res, 404, { error: "slide not found" });
4154
- }
4155
- const updated = isDelete ? removePageFromDefaultExportInSource(source, pageIndex) : duplicatePageInDefaultExportInSource(source, pageIndex);
4156
- if (updated === null) return json(res, 422, { error: isDelete ? "could not delete page — index out of range or default export is not an array" : "could not duplicate page — index out of range or default export is not an array" });
4157
- const withNotes = isDelete ? removeNotesElementInSource(updated, pageIndex) : duplicateNotesElementInSource(updated, pageIndex);
4158
- if (withNotes === null) return json(res, 422, { error: isDelete ? "could not delete page — `notes` export has an unexpected shape" : "could not duplicate page — `notes` export has an unexpected shape" });
4159
- if (withNotes !== source) await fs.writeFile(entry, withNotes, "utf8");
4314
+ const result = await editSlideSource(entry, (source) => {
4315
+ const updated = isDelete ? removePageFromDefaultExportInSource(source, pageIndex) : duplicatePageInDefaultExportInSource(source, pageIndex);
4316
+ if (updated === null) return {
4317
+ ok: false,
4318
+ status: 422,
4319
+ error: isDelete ? "could not delete page — index out of range or default export is not an array" : "could not duplicate page — index out of range or default export is not an array"
4320
+ };
4321
+ const withNotes = isDelete ? removeNotesElementInSource(updated, pageIndex) : duplicateNotesElementInSource(updated, pageIndex);
4322
+ if (withNotes === null) return {
4323
+ ok: false,
4324
+ status: 422,
4325
+ error: isDelete ? "could not delete page — `notes` export has an unexpected shape" : "could not duplicate page — `notes` export has an unexpected shape"
4326
+ };
4327
+ return {
4328
+ ok: true,
4329
+ source: withNotes
4330
+ };
4331
+ });
4332
+ if (!result.ok) return json(res, result.status, { error: result.error });
4160
4333
  return json(res, 200, {
4161
4334
  ok: true,
4162
4335
  slideId,
4163
- index: pageIndex
4336
+ index: pageIndex,
4337
+ layout: pageLayoutOfSource(result.source)
4164
4338
  });
4165
4339
  }
4166
4340
  const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
@@ -4196,15 +4370,19 @@ function registerSlideRoutes(server, ctx) {
4196
4370
  if (!name) return json(res, 400, { error: "invalid name" });
4197
4371
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
4198
4372
  if (!entry) return json(res, 400, { error: "invalid slideId" });
4199
- let source;
4200
- try {
4201
- source = await fs.readFile(entry, "utf8");
4202
- } catch {
4203
- return json(res, 404, { error: "slide not found" });
4204
- }
4205
- const updated = updateMetaTitleInSource(source, name);
4206
- if (updated === null) return json(res, 422, { error: "could not locate a safe place to write meta.title in index.tsx" });
4207
- if (updated !== source) await fs.writeFile(entry, updated, "utf8");
4373
+ const result = await editSlideSource(entry, (source) => {
4374
+ const updated = updateMetaTitleInSource(source, name);
4375
+ if (updated === null) return {
4376
+ ok: false,
4377
+ status: 422,
4378
+ error: "could not locate a safe place to write meta.title in index.tsx"
4379
+ };
4380
+ return {
4381
+ ok: true,
4382
+ source: updated
4383
+ };
4384
+ });
4385
+ if (!result.ok) return json(res, result.status, { error: result.error });
4208
4386
  server.ws.send({ type: "full-reload" });
4209
4387
  return json(res, 200, {
4210
4388
  ok: true,
@@ -4307,10 +4485,13 @@ function registerWatchers(server, ctx) {
4307
4485
  //#endregion
4308
4486
  //#region src/vite/api-plugin.ts
4309
4487
  function apiPlugin(opts) {
4488
+ const agents = /* @__PURE__ */ new WeakMap();
4489
+ let running = null;
4310
4490
  return {
4311
4491
  name: "open-slide:api",
4312
4492
  apply: "serve",
4313
- configureServer(server) {
4493
+ async configureServer(server) {
4494
+ await running?.();
4314
4495
  const ctx = makeContext(opts);
4315
4496
  registerWatchers(server, ctx);
4316
4497
  registerEditRoutes(server, ctx);
@@ -4322,7 +4503,12 @@ function apiPlugin(opts) {
4322
4503
  registerFolderRoutes(server, ctx);
4323
4504
  registerUpdateRoutes(server, ctx);
4324
4505
  registerRestartRoutes(server);
4325
- registerAgentRoutes(server, ctx);
4506
+ const closeAgent = registerAgentRoutes(server, ctx);
4507
+ running = closeAgent;
4508
+ for (const environment of Object.values(server.environments)) agents.set(environment, closeAgent);
4509
+ },
4510
+ async closeBundle() {
4511
+ await agents.get(this.environment)?.();
4326
4512
  }
4327
4513
  };
4328
4514
  }
@@ -4929,6 +5115,42 @@ function applyNotesEdit(source, index, text) {
4929
5115
  source: source.slice(0, found.arrayStart) + replacement + source.slice(found.arrayEnd)
4930
5116
  };
4931
5117
  }
5118
+ function readPageLayout(file) {
5119
+ return withFileLock(file, async () => {
5120
+ const source = await readSlideSource(file);
5121
+ return source === null ? null : pageLayoutOfSource(source);
5122
+ });
5123
+ }
5124
+ function saveNotes(file, index, text, layout) {
5125
+ return withFileLock(file, async () => {
5126
+ const source = await readSlideSource(file);
5127
+ if (source === null) return {
5128
+ ok: false,
5129
+ status: 404,
5130
+ error: "slide not found"
5131
+ };
5132
+ if (layout !== void 0) {
5133
+ const current = pageLayoutOfSource(source);
5134
+ if (current !== layout) return {
5135
+ ok: false,
5136
+ status: 409,
5137
+ error: "pages changed since these notes were edited",
5138
+ layout: current
5139
+ };
5140
+ }
5141
+ const result = applyNotesEdit(source, index, text);
5142
+ if (!result.ok) return result;
5143
+ const changed = result.source !== source;
5144
+ if (changed) {
5145
+ recordWrite(file);
5146
+ await fs.writeFile(file, result.source, "utf8");
5147
+ }
5148
+ return {
5149
+ ok: true,
5150
+ changed
5151
+ };
5152
+ });
5153
+ }
4932
5154
  function notesPlugin(opts) {
4933
5155
  const slidesRoot = path.resolve(opts.userCwd, opts.slidesDir ?? "slides");
4934
5156
  return {
@@ -4940,7 +5162,18 @@ function notesPlugin(opts) {
4940
5162
  configureServer(server) {
4941
5163
  server.middlewares.use("/__notes", async (req, res, next) => {
4942
5164
  const url = new URL(req.url ?? "/", "http://local");
4943
- if ((req.method ?? "GET") !== "PUT" || url.pathname !== "/") return next();
5165
+ const method = req.method ?? "GET";
5166
+ if (url.pathname !== "/") return next();
5167
+ if (method === "GET") try {
5168
+ const file = resolveSlideEntry(slidesRoot, url.searchParams.get("slideId") ?? "");
5169
+ if (!file) return json(res, 400, { error: "invalid slideId" });
5170
+ const layout = await readPageLayout(file);
5171
+ if (layout === null) return json(res, 404, { error: "slide not found" });
5172
+ return json(res, 200, { layout });
5173
+ } catch (err) {
5174
+ return json(res, 500, { error: String(err.message ?? err) });
5175
+ }
5176
+ if (method !== "PUT") return next();
4944
5177
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
4945
5178
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4946
5179
  try {
@@ -4950,18 +5183,15 @@ function notesPlugin(opts) {
4950
5183
  if (!file) return json(res, 400, { error: "invalid slideId" });
4951
5184
  if (typeof body.index !== "number") return json(res, 400, { error: "missing index" });
4952
5185
  if (typeof body.text !== "string") return json(res, 400, { error: "missing text" });
4953
- const source = await readSlideSource(file);
4954
- if (source === null) return json(res, 404, { error: "slide not found" });
4955
- const result = applyNotesEdit(source, body.index, body.text);
4956
- if (!result.ok) return json(res, result.status, { error: result.error });
4957
- const changed = result.source !== source;
4958
- if (changed) {
4959
- recordWrite(file);
4960
- await fs.writeFile(file, result.source, "utf8");
4961
- }
5186
+ if (body.layout !== void 0 && typeof body.layout !== "string") return json(res, 400, { error: "invalid layout" });
5187
+ const result = await saveNotes(file, body.index, body.text, body.layout);
5188
+ if (!result.ok) return json(res, result.status, {
5189
+ error: result.error,
5190
+ layout: result.layout
5191
+ });
4962
5192
  return json(res, 200, {
4963
5193
  ok: true,
4964
- changed
5194
+ changed: result.changed
4965
5195
  });
4966
5196
  } catch (err) {
4967
5197
  json(res, 500, { error: String(err.message ?? err) });
@@ -5197,7 +5427,7 @@ async function createViteConfig(opts) {
5197
5427
  const themesAbs = path.resolve(userCwd, themesDir);
5198
5428
  const assetsAbs = path.resolve(userCwd, assetsDir);
5199
5429
  return {
5200
- base: config.base ?? "/",
5430
+ base: isManagedCore() ? "/" : config.base ?? "/",
5201
5431
  root: APP_ROOT,
5202
5432
  configFile: false,
5203
5433
  envDir: userCwd,
@@ -5235,11 +5465,26 @@ async function createViteConfig(opts) {
5235
5465
  }),
5236
5466
  serverInfoPlugin({ userCwd })
5237
5467
  ],
5468
+ cacheDir: process.env["OPEN_SLIDE_CACHE_DIR"] || void 0,
5238
5469
  resolve: {
5239
- alias: {
5240
- "@": APP_ROOT,
5241
- "@assets": assetsAbs
5242
- },
5470
+ alias: [
5471
+ {
5472
+ find: "@",
5473
+ replacement: APP_ROOT
5474
+ },
5475
+ {
5476
+ find: "@assets",
5477
+ replacement: assetsAbs
5478
+ },
5479
+ {
5480
+ find: /^@open-slide\/core$/,
5481
+ replacement: path.join(PKG_ROOT, "dist", "index.js")
5482
+ },
5483
+ {
5484
+ find: /^@open-slide\/core\/locale$/,
5485
+ replacement: path.join(PKG_ROOT, "dist", "locale", "index.js")
5486
+ }
5487
+ ],
5243
5488
  dedupe: ["react", "react-dom"]
5244
5489
  },
5245
5490
  optimizeDeps: {
@@ -5288,4 +5533,4 @@ async function createViteConfig(opts) {
5288
5533
  };
5289
5534
  }
5290
5535
  //#endregion
5291
- export { DEV_SUPERVISED_ENV as n, createViteConfig as t };
5536
+ export { createViteConfig as t };