@open-document/core 0.13.3 → 0.14.1

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 (68) hide show
  1. package/dist/{build-CvsOak5B.js → build-I0cgoERP.js} +1 -1
  2. package/dist/{check-CbUBwYmf.js → check-Dys96QSL.js} +3 -3
  3. package/dist/cli/bin.js +10 -21
  4. package/dist/{config-BWtOZ1jc.d.ts → config-cAV1OCuY.d.ts} +9 -1
  5. package/dist/{context-CWgfsHoE.js → context-C-osJW5f.js} +1 -1
  6. package/dist/{dev-B8H2qT6G.js → dev-CC4PrIOC.js} +1 -1
  7. package/dist/{diff-BvIjjgnc.js → diff-DhutD4TJ.js} +2 -2
  8. package/dist/{export-DX30_s2q.js → export-KrajVJO7.js} +3 -3
  9. package/dist/{import-DgsdJT5e.js → import-Yv34za3L.js} +3 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/ops/index.d.ts +3 -1
  12. package/dist/ops/index.js +2 -2
  13. package/dist/ops-Dux5HlkH.js +401 -0
  14. package/dist/{preview-DYMUNjXL.js → preview-7eqn9Wzf.js} +1 -1
  15. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  16. package/dist/{config-CltJJVsw.js → session-BSbrC5gK.js} +3268 -385
  17. package/dist/{templates-B5Tz0AKb.js → templates-s-VLTSRc.js} +3 -3
  18. package/dist/vite/index.d.ts +1 -1
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +1 -1
  21. package/skills/create-doc/SKILL.md +1 -1
  22. package/skills/doc-authoring/SKILL.md +6 -0
  23. package/src/app/app.tsx +2 -0
  24. package/src/app/components/agent/agent-dock.tsx +75 -0
  25. package/src/app/components/agent/agent-markdown.tsx +45 -0
  26. package/src/app/components/agent/agent-panel.tsx +695 -0
  27. package/src/app/components/agent/agent-presence.tsx +74 -0
  28. package/src/app/components/agent/composer.tsx +120 -0
  29. package/src/app/components/agent/connect-view.tsx +183 -0
  30. package/src/app/components/agent/history-view.tsx +134 -0
  31. package/src/app/components/agent/provider-logo.tsx +23 -0
  32. package/src/app/components/agent/transcript.tsx +717 -0
  33. package/src/app/components/comments/comments-panel.tsx +26 -2
  34. package/src/app/components/inspector/inspector.tsx +17 -0
  35. package/src/app/components/note-markdown.tsx +85 -0
  36. package/src/app/components/page-error-boundary.tsx +84 -0
  37. package/src/app/components/page-frame.tsx +2 -1
  38. package/src/app/components/panel/resize-handle.tsx +129 -0
  39. package/src/app/components/ui/button.tsx +97 -0
  40. package/src/app/components/ui/popover.tsx +144 -0
  41. package/src/app/components/ui/tooltip.tsx +123 -0
  42. package/src/app/lib/agent/use-agent.ts +543 -0
  43. package/src/app/lib/diagnostics.ts +13 -0
  44. package/src/app/lib/export-dom.ts +2 -1
  45. package/src/app/lib/export-pdf.ts +2 -1
  46. package/src/app/lib/i18n-ja/agent-panel.ts +115 -0
  47. package/src/app/lib/i18n-ja/agent.ts +9 -0
  48. package/src/app/lib/i18n-ja/index.ts +9 -1
  49. package/src/app/lib/i18n-ko/agent-panel.ts +114 -0
  50. package/src/app/lib/i18n-ko/agent.ts +9 -0
  51. package/src/app/lib/i18n-ko/index.ts +9 -1
  52. package/src/app/lib/i18n-zh-cn/agent-panel.ts +113 -0
  53. package/src/app/lib/i18n-zh-cn/agent.ts +9 -0
  54. package/src/app/lib/i18n-zh-cn/index.ts +9 -1
  55. package/src/app/lib/i18n-zh-tw/agent-panel.ts +113 -0
  56. package/src/app/lib/i18n-zh-tw/agent.ts +9 -0
  57. package/src/app/lib/i18n-zh-tw/index.ts +9 -1
  58. package/src/app/lib/note-markdown.ts +116 -0
  59. package/src/app/lib/toast.ts +50 -0
  60. package/src/app/lib/use-auto-grow.ts +15 -0
  61. package/src/app/lib/use-doc-titles.ts +28 -0
  62. package/src/app/lib/use-locale.ts +151 -0
  63. package/src/app/lib/utils.ts +4 -0
  64. package/src/app/routes/doc-preview.tsx +103 -0
  65. package/src/app/routes/doc.tsx +118 -11
  66. package/src/app/routes/home.tsx +43 -8
  67. package/src/app/styles.css +193 -0
  68. package/dist/ops-CSR5RlrE.js +0 -1673
@@ -1,19 +1,23 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
1
2
  import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-CKf3ptOE.js";
3
+ import { c as isPageSizeName, i as ORIENTATIONS, o as PAGE_SIZE_NAMES, s as isOrientation } from "./sdk-CqNZzbkz.js";
2
4
  import { t as corePackageRoot } from "./package-version-C89gtYSk.js";
3
5
  import { n as loadUserConfig, r as openDocPlugin, t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
4
6
  import chalk from "chalk";
5
7
  import path from "node:path";
6
8
  import { fileURLToPath, pathToFileURL } from "node:url";
7
9
  import fs from "node:fs/promises";
8
- import { existsSync, readFileSync, realpathSync } from "node:fs";
10
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
9
11
  import fg from "fast-glob";
10
- import { normalizePath } from "vite";
11
- import { execFile } from "node:child_process";
12
+ import { createServer, mergeConfig, normalizePath } from "vite";
13
+ import { execFile, spawn } from "node:child_process";
12
14
  import { promisify } from "node:util";
13
15
  import { parse } from "@babel/parser";
14
- import { createHash, randomUUID } from "node:crypto";
16
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
17
+ import { Buffer as Buffer$1 } from "node:buffer";
15
18
  import tailwindcss from "@tailwindcss/vite";
16
19
  import react from "@vitejs/plugin-react";
20
+ import os from "node:os";
17
21
  //#region src/vite/routes/context.ts
18
22
  function makeContext(opts) {
19
23
  const userCwd = opts.userCwd;
@@ -30,10 +34,25 @@ function makeContext(opts) {
30
34
  ...opts.serverOrigin !== void 0 ? { serverOrigin: opts.serverOrigin } : {}
31
35
  };
32
36
  }
33
- async function readBody(req) {
37
+ var BodyTooLargeError = class extends Error {
38
+ constructor() {
39
+ super("request body too large");
40
+ this.name = "BodyTooLargeError";
41
+ }
42
+ };
43
+ async function readBody(req, limit = Number.POSITIVE_INFINITY) {
34
44
  return await new Promise((resolve, reject) => {
35
45
  const chunks = [];
36
- req.on("data", (c) => chunks.push(c));
46
+ let size = 0;
47
+ req.on("data", (c) => {
48
+ size += c.length;
49
+ if (size > limit) {
50
+ req.destroy();
51
+ reject(new BodyTooLargeError());
52
+ return;
53
+ }
54
+ chunks.push(c);
55
+ });
37
56
  req.on("end", () => {
38
57
  const raw = Buffer.concat(chunks).toString("utf8");
39
58
  if (!raw) return resolve({});
@@ -444,7 +463,7 @@ function findMetaObject(ast) {
444
463
  }
445
464
  return null;
446
465
  }
447
- function jsString$1(value) {
466
+ function jsString$2(value) {
448
467
  return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
449
468
  }
450
469
  function validateDocTitle(v) {
@@ -473,10 +492,10 @@ function setMetaString(source, field, value) {
473
492
  const p = prop;
474
493
  if (p.computed) continue;
475
494
  if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== field) continue;
476
- return source.slice(0, p.value.start) + jsString$1(value) + source.slice(p.value.end);
495
+ return source.slice(0, p.value.start) + jsString$2(value) + source.slice(p.value.end);
477
496
  }
478
497
  const open = object.start + 1;
479
- const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$1(value)},\n` : `\n ${field}: ${jsString$1(value)},`;
498
+ const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$2(value)},\n` : `\n ${field}: ${jsString$2(value)},`;
480
499
  return source.slice(0, open) + inserted + source.slice(open);
481
500
  }
482
501
  function readMetaTitle(source) {
@@ -751,6 +770,56 @@ async function deleteDocument(ctx, docId) {
751
770
  }
752
771
  });
753
772
  }
773
+ /**
774
+ * A blank document under a placeholder id (`untitled`, `untitled-2`, …) from the
775
+ * `blank` template, for the agent panel to draft into. It gets a real id from
776
+ * `renameDocDir` once something has been written.
777
+ */
778
+ async function createBlankDocument(ctx) {
779
+ const { createFromTemplate } = await Promise.resolve().then(() => templates_exports);
780
+ const taken = new Set(await listDocIds$1(ctx));
781
+ for (let n = 1; n < 1e3; n++) {
782
+ const id = n === 1 ? "untitled" : `untitled-${n}`;
783
+ if (taken.has(id)) continue;
784
+ return { id: (await createFromTemplate(ctx, {
785
+ template: "blank",
786
+ docId: id
787
+ })).id };
788
+ }
789
+ throw new OpsError(409, "no free document id");
790
+ }
791
+ /**
792
+ * Moves a document to a new folder name — `desired`, else `desired-2`, … — and
793
+ * carries its folder assignment with it. The id is the folder, so this is the
794
+ * one operation that changes a document's id.
795
+ */
796
+ async function renameDocDir(ctx, docId, desired) {
797
+ const from = docDir(ctx, docId);
798
+ if (!DOC_ID_RE.test(desired)) throw new OpsError(400, `invalid document id: ${desired}`);
799
+ if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
800
+ const taken = new Set(await listDocIds$1(ctx));
801
+ for (let n = 1; n < 1e3; n++) {
802
+ const id = n === 1 ? desired : `${desired}-${n}`;
803
+ if (id === docId) return { id };
804
+ if (taken.has(id)) continue;
805
+ try {
806
+ await fs.rename(from, docDir(ctx, id));
807
+ } catch (err) {
808
+ const code = err.code;
809
+ if (code === "EEXIST" || code === "ENOTEMPTY") continue;
810
+ throw err;
811
+ }
812
+ const manifest = await readManifest(ctx.manifestPath);
813
+ const folderId = manifest.assignments[docId];
814
+ if (folderId) {
815
+ delete manifest.assignments[docId];
816
+ manifest.assignments[id] = folderId;
817
+ await writeManifest(ctx.manifestPath, manifest);
818
+ }
819
+ return { id };
820
+ }
821
+ throw new OpsError(409, "no free document id");
822
+ }
754
823
  //#endregion
755
824
  //#region src/ops/concurrency.ts
756
825
  /**
@@ -922,382 +991,2420 @@ async function revertChange(ctx, docId, opts) {
922
991
  return { ok: true };
923
992
  });
924
993
  }
925
- //#endregion
926
- //#region src/files/assets.ts
927
- const GLOBAL_SCOPE = "@global";
928
- const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
929
- const MIME_BY_EXT = {
930
- png: "image/png",
931
- jpg: "image/jpeg",
932
- jpeg: "image/jpeg",
933
- gif: "image/gif",
934
- svg: "image/svg+xml",
935
- webp: "image/webp",
936
- avif: "image/avif",
937
- ico: "image/x-icon",
938
- pdf: "application/pdf",
939
- woff: "font/woff",
940
- woff2: "font/woff2",
941
- ttf: "font/ttf",
942
- otf: "font/otf",
943
- csv: "text/csv; charset=utf-8",
944
- json: "application/json",
945
- txt: "text/plain; charset=utf-8",
946
- md: "text/markdown; charset=utf-8"
947
- };
948
- function mimeForFilename(name) {
949
- const dot = name.lastIndexOf(".");
950
- if (dot < 0) return "application/octet-stream";
951
- return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
994
+ const CLOCK_SLACK_MS = 1e3;
995
+ /**
996
+ * Whether the dev server should run `open-doc check` for the turn that just
997
+ * ended: only for an agent that cannot start a browser itself, only when the
998
+ * turn ran to its end, and only when it touched the document's source — it
999
+ * used a tool, and the file changed after the message. The mtime alone is not
1000
+ * enough: a document copied or made from a template a moment earlier reads as
1001
+ * fresh to a turn whose agent never even started.
1002
+ */
1003
+ function shouldCheckAfterTurn(opts) {
1004
+ const { session, userItemId, canOpenBrowser, entryMtimeMs } = opts;
1005
+ if (canOpenBrowser || !session.docId || entryMtimeMs === null) return false;
1006
+ const start = session.items.findIndex((i) => i.id === userItemId);
1007
+ if (start === -1) return false;
1008
+ const turn = session.items.slice(start + 1);
1009
+ const result = [...turn].reverse().find((i) => i.kind === "result");
1010
+ if (result?.kind === "result" && result.aborted) return false;
1011
+ if (!turn.some((i) => i.kind === "tool")) return false;
1012
+ const startedAt = Date.parse(session.items[start].ts);
1013
+ return Number.isFinite(startedAt) && entryMtimeMs >= startedAt - CLOCK_SLACK_MS;
1014
+ }
1015
+ /** A check report as the transcript keeps it: errors first, the rest counted. */
1016
+ function checkItemResult(report) {
1017
+ const findings = [...report.findings].sort((a, b) => Number(b.severity === "error") - Number(a.severity === "error") || a.page - b.page).slice(0, 20).map((f) => ({
1018
+ page: f.page,
1019
+ severity: f.severity,
1020
+ message: f.message,
1021
+ ...f.loc ? { loc: f.loc } : {}
1022
+ }));
1023
+ return {
1024
+ pageCount: report.pageCount,
1025
+ findings,
1026
+ total: report.findings.length
1027
+ };
952
1028
  }
953
- function assetCreatedAt(birthtimeMs, mtimeMs) {
954
- return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
1029
+ //#endregion
1030
+ //#region src/agent/install.ts
1031
+ const LOCKFILES = [
1032
+ ["pnpm-lock.yaml", "pnpm"],
1033
+ ["yarn.lock", "yarn"],
1034
+ ["bun.lockb", "bun"],
1035
+ ["bun.lock", "bun"],
1036
+ ["package-lock.json", "npm"]
1037
+ ];
1038
+ async function fileExists(file) {
1039
+ try {
1040
+ await fs.access(file);
1041
+ return true;
1042
+ } catch {
1043
+ return false;
1044
+ }
955
1045
  }
956
- function validateAssetName(v) {
957
- if (typeof v !== "string") return null;
958
- const trimmed = v.trim();
959
- if (trimmed.length < 1 || trimmed.length > 120) return null;
960
- if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
961
- if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
962
- if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
963
- const dot = trimmed.lastIndexOf(".");
964
- if (dot <= 0 || dot === trimmed.length - 1) return null;
965
- return trimmed;
1046
+ async function detectPackageManager(cwd) {
1047
+ const ua = process.env.npm_config_user_agent ?? "";
1048
+ if (ua.startsWith("pnpm")) return "pnpm";
1049
+ if (ua.startsWith("yarn")) return "yarn";
1050
+ if (ua.startsWith("bun")) return "bun";
1051
+ if (ua.startsWith("npm")) return "npm";
1052
+ let dir = cwd;
1053
+ while (true) {
1054
+ for (const [lockfile, pm] of LOCKFILES) if (await fileExists(path.join(dir, lockfile))) return pm;
1055
+ const parent = path.dirname(dir);
1056
+ if (parent === dir) return "npm";
1057
+ dir = parent;
1058
+ }
966
1059
  }
967
- function resolveAssetsDir(docsRoot, docId) {
968
- if (!DOC_ID_RE.test(docId)) return null;
969
- const docDir = path.resolve(docsRoot, docId);
970
- if (!docDir.startsWith(docsRoot + path.sep)) return null;
971
- const assetsDir = path.resolve(docDir, "assets");
972
- if (assetsDir !== path.join(docDir, "assets")) return null;
973
- return assetsDir;
1060
+ async function runCommand(spec, cwd, timeoutMs) {
1061
+ const label = [spec.cmd, ...spec.args].join(" ");
1062
+ await new Promise((resolve, reject) => {
1063
+ const child = spawn(spec.cmd, spec.args, {
1064
+ cwd,
1065
+ env: process.env,
1066
+ shell: process.platform === "win32",
1067
+ stdio: [
1068
+ "ignore",
1069
+ "ignore",
1070
+ "pipe"
1071
+ ],
1072
+ windowsHide: true
1073
+ });
1074
+ let stderr = "";
1075
+ const timer = setTimeout(() => {
1076
+ child.kill();
1077
+ reject(/* @__PURE__ */ new Error(`${label} timed out`));
1078
+ }, timeoutMs);
1079
+ child.stderr.on("data", (chunk) => {
1080
+ stderr = (stderr + chunk.toString("utf8")).slice(-2e3);
1081
+ });
1082
+ child.on("error", (err) => {
1083
+ clearTimeout(timer);
1084
+ reject(err);
1085
+ });
1086
+ child.on("close", (code) => {
1087
+ clearTimeout(timer);
1088
+ if (code === 0) return resolve();
1089
+ reject(new Error(stderr.trim() || `${label} exited with code ${code ?? "unknown"}`));
1090
+ });
1091
+ });
974
1092
  }
975
- function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
976
- if (scope === "@global") return globalAssetsRoot;
977
- return resolveAssetsDir(docsRoot, scope);
1093
+ //#endregion
1094
+ //#region src/editing/placeholder-id.ts
1095
+ /** The folder a document gets before it has a name: renamed once the agent has written it. */
1096
+ const UNTITLED_DOC_ID_RE = /^untitled(-\d+)?$/;
1097
+ //#endregion
1098
+ //#region src/agent/provider.ts
1099
+ var ProviderUnavailableError = class extends Error {
1100
+ constructor(provider) {
1101
+ super(`${provider.name} is not connected: install ${provider.sdkPackage} in this workspace to use it from the agent panel.`);
1102
+ this.name = "ProviderUnavailableError";
1103
+ }
1104
+ };
1105
+ const DETAIL_MAX = 400;
1106
+ function clipDetail(value) {
1107
+ if (value === void 0 || value === null) return null;
1108
+ const text = typeof value === "string" ? value : safeJson(value);
1109
+ if (!text) return null;
1110
+ const oneLine = text.replace(/\s+/g, " ").trim();
1111
+ return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, 399)}…` : oneLine;
1112
+ }
1113
+ function safeJson(value) {
1114
+ try {
1115
+ return JSON.stringify(value);
1116
+ } catch {
1117
+ return String(value);
1118
+ }
978
1119
  }
979
- function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
980
- if (!validateAssetName(filename)) return null;
981
- const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
982
- if (!dir) return null;
983
- const file = path.resolve(dir, filename);
984
- if (!file.startsWith(dir + path.sep)) return null;
985
- return file;
1120
+ function parseQuestions(input) {
1121
+ const raw = Array.isArray(input.questions) ? input.questions : [];
1122
+ const questions = [];
1123
+ for (const q of raw) {
1124
+ if (!q || typeof q !== "object") continue;
1125
+ const r = q;
1126
+ const options = Array.isArray(r.options) ? r.options.map((o) => {
1127
+ if (!o || typeof o !== "object") return null;
1128
+ const opt = o;
1129
+ if (typeof opt.label !== "string") return null;
1130
+ return {
1131
+ label: opt.label,
1132
+ description: typeof opt.description === "string" ? opt.description : void 0
1133
+ };
1134
+ }).filter((o) => o !== null) : [];
1135
+ if (typeof r.question !== "string") continue;
1136
+ questions.push({
1137
+ header: typeof r.header === "string" ? r.header : "",
1138
+ question: r.question,
1139
+ options,
1140
+ multiSelect: r.multiSelect === true
1141
+ });
1142
+ }
1143
+ return questions;
986
1144
  }
987
- /** How a document imports an asset — the string we look for when counting usages. */
988
- function assetImportPath(scope, filename) {
989
- return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
1145
+ //#endregion
1146
+ //#region src/agent/prompt.ts
1147
+ const SECTION_BY_SECTION = "Write a new document section by section so the user can follow along on the page: first replace the file with the imports, meta (keeping its existing createdAt), design and the opening section only, then add each remaining section with its own separate edit, keeping the file compiling after every write.";
1148
+ const DOC_SLUG = "This document's folder still has a placeholder name. Never rename or move the folder yourself: once the document has content, end your final reply with a slug for it on a line of its own as <doc-slug>short-kebab-case-english-slug</doc-slug>, and open-doc renames the folder from it.";
1149
+ function systemPromptAppend(askInstruction, opts) {
1150
+ const preview = opts.origin ? `${opts.origin}/d/<id>/preview?p=<page>` : "/d/<id>/preview?p=<page> on the dev server";
1151
+ return [
1152
+ "You are running inside the open-doc dev server, driven from its in-app agent panel in the browser rather than a terminal.",
1153
+ `The workspace is an open-doc project: documents live under ${opts.docsDir}/<id>/index.tsx and the dev server hot-reloads every edit, so the user sees changes immediately.`,
1154
+ "Use the project skills: create-doc to draft a new document, apply-comments to resolve @doc-comment markers left by the inspector, create-theme for themes, and doc-authoring as the technical reference before writing a page.",
1155
+ SECTION_BY_SECTION,
1156
+ opts.canOpenBrowser === false ? "Your sandbox cannot start a browser, so `open-doc check` and the page preview fail here: do not run them. open-doc runs the check itself once your turn ends and shows the user what it finds, so keep the file compiling after every write." : `After editing a document, run \`pnpm exec open-doc check <id>\` and fix what it reports. To look at one page as it prints, open ${preview} and wait for [data-od-preview-ready="true"].`,
1157
+ "Keep replies short and concrete: the panel is narrow. Prefer doing the work over describing it, and finish with a one-line summary of what changed.",
1158
+ askInstruction
1159
+ ].join(" ");
1160
+ }
1161
+ function buildTurnPrompt(text, context, docsDir = "docs") {
1162
+ const lines = contextLines(context, docsDir);
1163
+ if (lines.length === 0) return text;
1164
+ return `${text}\n\n<open-doc-context>\n${lines.join("\n")}\n</open-doc-context>`;
1165
+ }
1166
+ const escapeTag = (s) => s.replace(/</g, "&lt;");
1167
+ function contextLines(context, docsDir) {
1168
+ if (!context?.docId) return [];
1169
+ const file = `${docsDir}/${context.docId}/index.tsx`;
1170
+ const lines = [];
1171
+ if (context.newDoc) {
1172
+ lines.push(`${file} is a blank document created for this request. Draft the document the user describes into it with the create-doc skill: replace the placeholder content, keep the document id, and do not create another folder.`, "Ask the create-doc scoping questions in a single round, only for what the request leaves unclear; skip any it already answers.", SECTION_BY_SECTION, DOC_SLUG);
1173
+ return lines;
1174
+ }
1175
+ lines.push(`The user is viewing document "${context.docId}": ${file}.`);
1176
+ if (UNTITLED_DOC_ID_RE.test(context.docId)) lines.push(DOC_SLUG);
1177
+ if (context.docTitle) lines.push(`<doc-title>${escapeTag(context.docTitle)}</doc-title>`);
1178
+ if (context.pageNumber && context.totalPages) lines.push(`They are on page ${context.pageNumber} of ${context.totalPages} as the document prints.`);
1179
+ if (context.selection) {
1180
+ const { line, column, tagName, text } = context.selection;
1181
+ lines.push(`They have selected a <${escapeTag(tagName)}> element at ${file}:${line}:${column}.${text ? " Its text is in <selected-text>." : ""} "This element" refers to it.`);
1182
+ if (text) lines.push(`<selected-text>${escapeTag(text)}</selected-text>`);
1183
+ }
1184
+ if (context.pendingComments) lines.push(`There are ${context.pendingComments} pending @doc-comment markers in this document's source.`);
1185
+ return lines;
1186
+ }
1187
+ const DOC_SLUG_RE = /\s*<doc-slug>\s*([^<]*?)\s*<\/doc-slug>\s*/gi;
1188
+ function extractDocSlug(text) {
1189
+ let slug = null;
1190
+ for (const match of text.matchAll(DOC_SLUG_RE)) slug = match[1] || slug;
1191
+ return slug;
1192
+ }
1193
+ function stripDocSlug(text) {
1194
+ return text.replace(DOC_SLUG_RE, "\n").replace(/\s*<doc-slug>[^<]*$/i, "").trimEnd();
1195
+ }
1196
+ const QUESTIONS_RE = /<open-doc-questions>([\s\S]*?)<\/open-doc-questions>/i;
1197
+ const TEXT_QUESTIONS_INSTRUCTION = "You cannot ask the user anything interactively here, and nothing you print in the middle of a turn can be answered. When you need answers before continuing, stop working and end your turn with a final message holding only an <open-doc-questions> block: a JSON array of at most 4 questions shaped like [{\"header\":\"Length\",\"question\":\"How long should it be?\",\"multiSelect\":false,\"options\":[{\"label\":\"2-3 pages (Recommended)\",\"description\":\"A short brief\"}]}], each with 2 to 4 options, written in the user's language. The panel shows them as a form and sends the answers back as your next message. Write nothing after the block and do not continue the task in the same turn.";
1198
+ function extractQuestionBlock(text) {
1199
+ const match = QUESTIONS_RE.exec(text);
1200
+ if (!match) return null;
1201
+ const body = match[1].trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
1202
+ let raw;
1203
+ try {
1204
+ raw = JSON.parse(body);
1205
+ } catch {
1206
+ return null;
1207
+ }
1208
+ const questions = parseQuestions({ questions: Array.isArray(raw) ? raw : raw?.questions });
1209
+ if (questions.length === 0) return null;
1210
+ return {
1211
+ text: text.replace(QUESTIONS_RE, "").trim(),
1212
+ questions
1213
+ };
990
1214
  }
991
- function escapeRegExp(value) {
992
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1215
+ function answersPrompt(questions, answers) {
1216
+ if (!answers) return "I skipped your questions. Continue the task with your best judgement and sensible defaults.";
1217
+ return `My answers:\n${questions.map((q) => `- ${q.question} ${answers[q.question] || "(no answer)"}`).join("\n")}\n\nContinue the task with these answers.`;
993
1218
  }
994
- /**
995
- * Counts references to an asset in a document's source. Matches the quoted path
996
- * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
997
- * which is every form the authoring skill sanctions.
998
- */
999
- function countAssetUsages(source, importPath) {
1000
- const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
1001
- return source.match(quoted)?.length ?? 0;
1219
+ function editedPrompt(original, text) {
1220
+ return `I went back and edited an earlier message of mine. Treat everything after it in this conversation, including your replies, as discarded, and respond to the edited version instead. Files keep whatever changes were already made.\n\n<original-message>\n${escapeTag(original)}\n</original-message>\n\n${text}`;
1002
1221
  }
1003
- function findReferencedAssets(source, importPaths) {
1004
- return importPaths.filter((p) => countAssetUsages(source, p) > 0);
1222
+ function rewoundPrompt(text) {
1223
+ return `${text}\n\n<open-doc-note>I went back and edited this message. Files keep the changes made after it in the discarded part of this conversation, so read the current files before editing them.</open-doc-note>`;
1005
1224
  }
1006
1225
  //#endregion
1007
- //#region src/http/request-guard.ts
1008
- function firstHeaderValue(value) {
1009
- if (Array.isArray(value)) return value[0] ?? null;
1010
- return value ?? null;
1011
- }
1012
- function headerValue(req, name) {
1013
- return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
1226
+ //#region src/agent/detect.ts
1227
+ const IS_WINDOWS = process.platform === "win32";
1228
+ const VERSION_TIMEOUT_MS = 5e3;
1229
+ function findOnPath(command, env = process.env) {
1230
+ const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
1231
+ const exts = IS_WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
1232
+ for (const dir of dirs) for (const ext of exts) {
1233
+ const candidate = path.join(dir, command + ext.toLowerCase());
1234
+ try {
1235
+ if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
1236
+ } catch {}
1237
+ }
1238
+ return null;
1014
1239
  }
1015
- function firstCommaToken(value) {
1016
- if (!value) return null;
1017
- const [first] = value.split(",", 1);
1018
- return first?.trim() || null;
1240
+ function findSpawnableCli(command, env = process.env) {
1241
+ const found = findOnPath(command, env);
1242
+ if (!found || !IS_WINDOWS) return found;
1243
+ return found.toLowerCase().endsWith(".exe") ? found : null;
1244
+ }
1245
+ const versionCache = /* @__PURE__ */ new Map();
1246
+ function commandVersion(file) {
1247
+ let cached = versionCache.get(file);
1248
+ if (!cached) {
1249
+ cached = readVersion(file);
1250
+ versionCache.set(file, cached);
1251
+ }
1252
+ return cached;
1019
1253
  }
1020
- function requestProto(req) {
1021
- const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
1022
- if (forwarded === "http" || forwarded === "https") return forwarded;
1023
- return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
1254
+ function readVersion(file) {
1255
+ return new Promise((resolve) => {
1256
+ let out = "";
1257
+ let child;
1258
+ try {
1259
+ child = spawn(file, ["--version"], {
1260
+ stdio: [
1261
+ "ignore",
1262
+ "pipe",
1263
+ "pipe"
1264
+ ],
1265
+ shell: IS_WINDOWS,
1266
+ windowsHide: true
1267
+ });
1268
+ } catch {
1269
+ resolve(null);
1270
+ return;
1271
+ }
1272
+ const timer = setTimeout(() => {
1273
+ child.kill();
1274
+ resolve(null);
1275
+ }, VERSION_TIMEOUT_MS);
1276
+ child.stdout?.on("data", (c) => {
1277
+ out += c.toString("utf8");
1278
+ });
1279
+ child.stderr?.on("data", (c) => {
1280
+ out += c.toString("utf8");
1281
+ });
1282
+ child.on("error", () => {
1283
+ clearTimeout(timer);
1284
+ resolve(null);
1285
+ });
1286
+ child.on("close", () => {
1287
+ clearTimeout(timer);
1288
+ resolve(parseVersion(out));
1289
+ });
1290
+ });
1024
1291
  }
1025
- function normalizedOrigin(origin) {
1026
- try {
1027
- const url = new URL(origin);
1028
- return `${url.protocol}//${url.host}`.toLowerCase();
1029
- } catch {
1292
+ function parseVersion(output) {
1293
+ const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
1294
+ return m ? m[1] : null;
1295
+ }
1296
+ function entryFromPackageJson(pkg) {
1297
+ const root = pickExport(pkg.exports);
1298
+ if (root) return root;
1299
+ return pkg.module ?? pkg.main ?? null;
1300
+ }
1301
+ function pickExport(exportsField) {
1302
+ if (!exportsField) return null;
1303
+ if (typeof exportsField === "string") return exportsField;
1304
+ if (typeof exportsField !== "object") return null;
1305
+ const record = exportsField;
1306
+ return pickCondition(Object.keys(record).some((k) => k.startsWith(".")) ? record["."] : exportsField);
1307
+ }
1308
+ function pickCondition(target) {
1309
+ if (!target) return null;
1310
+ if (typeof target === "string") return target;
1311
+ if (Array.isArray(target)) {
1312
+ for (const t of target) {
1313
+ const hit = pickCondition(t);
1314
+ if (hit) return hit;
1315
+ }
1030
1316
  return null;
1031
1317
  }
1318
+ if (typeof target !== "object") return null;
1319
+ const record = target;
1320
+ for (const key of [
1321
+ "import",
1322
+ "node",
1323
+ "default",
1324
+ "require"
1325
+ ]) if (key in record) {
1326
+ const hit = pickCondition(record[key]);
1327
+ if (hit) return hit;
1328
+ }
1329
+ return null;
1032
1330
  }
1033
- /**
1034
- * The dev server writes to the user's filesystem, so every mutating endpoint is
1035
- * guarded against a page on another origin driving it through the browser.
1036
- */
1037
- function validateMutationRequest(req, opts = {}) {
1038
- if (opts.requireJsonBody) {
1039
- if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
1040
- ok: false,
1041
- status: 415,
1042
- error: "content-type must be application/json"
1043
- };
1331
+ function resolveWorkspacePackage(userCwd, name) {
1332
+ let dir = path.resolve(userCwd);
1333
+ while (true) {
1334
+ const pkgJsonPath = path.join(dir, "node_modules", name, "package.json");
1335
+ if (existsSync(pkgJsonPath)) {
1336
+ let pkg;
1337
+ try {
1338
+ pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
1339
+ } catch {
1340
+ return null;
1341
+ }
1342
+ const entry = entryFromPackageJson(pkg);
1343
+ if (!entry) return null;
1344
+ const pkgDir = path.dirname(pkgJsonPath);
1345
+ return {
1346
+ dir: pkgDir,
1347
+ version: pkg.version ?? "0.0.0",
1348
+ entry: path.resolve(pkgDir, entry)
1349
+ };
1350
+ }
1351
+ const parent = path.dirname(dir);
1352
+ if (parent === dir) return null;
1353
+ dir = parent;
1044
1354
  }
1045
- if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
1046
- ok: false,
1047
- status: 403,
1048
- error: "cross-site request blocked"
1049
- };
1050
- const originRaw = headerValue(req, "origin");
1051
- if (!originRaw) return { ok: true };
1052
- if (originRaw.toLowerCase() === "null") return {
1053
- ok: false,
1054
- status: 403,
1055
- error: "opaque origin is not allowed"
1056
- };
1057
- const actualOrigin = normalizedOrigin(originRaw);
1058
- if (!actualOrigin) return {
1059
- ok: false,
1060
- status: 403,
1061
- error: "invalid origin header"
1062
- };
1063
- const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
1064
- if (!host) return {
1065
- ok: false,
1066
- status: 400,
1067
- error: "missing host header"
1068
- };
1069
- if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
1070
- ok: false,
1071
- status: 403,
1072
- error: "origin mismatch"
1073
- };
1074
- return { ok: true };
1355
+ }
1356
+ async function importWorkspacePackage(userCwd, name) {
1357
+ const resolved = resolveWorkspacePackage(userCwd, name);
1358
+ if (!resolved) return null;
1359
+ return await import(pathToFileURL(resolved.entry).href);
1075
1360
  }
1076
1361
  //#endregion
1077
- //#region src/vite/routes/assets.ts
1078
- async function listDocIds(docsRoot) {
1079
- try {
1080
- return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
1081
- } catch {
1082
- return [];
1362
+ //#region src/agent/types.ts
1363
+ const AGENT_PROVIDER_IDS = ["codex"];
1364
+ const AGENT_EFFORTS = [
1365
+ "minimal",
1366
+ "low",
1367
+ "medium",
1368
+ "high",
1369
+ "xhigh",
1370
+ "max"
1371
+ ];
1372
+ function isAgentProviderId(value) {
1373
+ return typeof value === "string" && AGENT_PROVIDER_IDS.includes(value);
1374
+ }
1375
+ function isAgentEffort(value) {
1376
+ return typeof value === "string" && AGENT_EFFORTS.includes(value);
1377
+ }
1378
+ function sessionSummary(session) {
1379
+ const { providerSessionId: _p, providerCheckpoint: _c, trimmed: _t, items: _i, ...summary } = session;
1380
+ return summary;
1381
+ }
1382
+ //#endregion
1383
+ //#region src/agent/providers/codex.ts
1384
+ const CODEX_SDK_PACKAGE = "@openai/codex-sdk";
1385
+ const CODEX_DEFAULT_MODEL = {
1386
+ id: "",
1387
+ label: "Default",
1388
+ efforts: [
1389
+ "low",
1390
+ "medium",
1391
+ "high"
1392
+ ]
1393
+ };
1394
+ function parseCodexModelsCache(raw) {
1395
+ const list = raw?.models;
1396
+ if (!Array.isArray(list)) return [];
1397
+ const models = [];
1398
+ for (const entry of list) {
1399
+ if (!entry || typeof entry !== "object") continue;
1400
+ const m = entry;
1401
+ if (typeof m.slug !== "string" || !m.slug) continue;
1402
+ if (m.visibility !== void 0 && m.visibility !== "list") continue;
1403
+ const efforts = (Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : []).map((l) => l && typeof l === "object" ? l.effort : l).filter(isAgentEffort);
1404
+ models.push({
1405
+ option: {
1406
+ id: m.slug,
1407
+ label: typeof m.display_name === "string" && m.display_name ? m.display_name : m.slug,
1408
+ efforts
1409
+ },
1410
+ priority: typeof m.priority === "number" ? m.priority : Number.MAX_SAFE_INTEGER
1411
+ });
1083
1412
  }
1413
+ return models.sort((a, b) => a.priority - b.priority).map((m) => m.option);
1084
1414
  }
1085
- async function readDocSource(docsRoot, docId) {
1086
- const entry = resolveDocEntry(docsRoot, docId);
1087
- if (!entry) return null;
1415
+ async function readCodexModels() {
1416
+ const home = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
1088
1417
  try {
1089
- return await fs.readFile(entry, "utf8");
1418
+ const models = parseCodexModelsCache(JSON.parse(await fs.readFile(path.join(home, "models_cache.json"), "utf8")));
1419
+ return models.length > 0 ? models : [CODEX_DEFAULT_MODEL];
1090
1420
  } catch {
1091
- return null;
1421
+ return [CODEX_DEFAULT_MODEL];
1092
1422
  }
1093
1423
  }
1094
- function registerAssetRoutes(server, ctx) {
1095
- server.middlewares.use("/__assets", async (req, res, next) => {
1096
- const url = new URL(req.url ?? "/", "http://local");
1097
- const method = req.method ?? "GET";
1098
- try {
1099
- const listMatch = url.pathname.match(/^\/([^/]+)\/?$/);
1100
- const fileMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)$/);
1101
- const usagesMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/usages$/);
1102
- if (usagesMatch && method === "GET") {
1103
- const scope = decodeURIComponent(usagesMatch[1]);
1104
- const filename = decodeURIComponent(usagesMatch[2]);
1105
- if (!validateAssetName(filename)) return json(res, 400, { error: "invalid path" });
1106
- const isGlobal = scope === GLOBAL_SCOPE;
1107
- if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
1108
- const importPath = assetImportPath(scope, filename);
1109
- const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
1110
- const usages = [];
1111
- let totalCount = 0;
1112
- for (const docId of docIds) {
1113
- const source = await readDocSource(ctx.docsRoot, docId);
1114
- if (source === null) continue;
1115
- const count = countAssetUsages(source, importPath);
1116
- if (count > 0) {
1117
- usages.push({
1118
- docId,
1119
- count
1120
- });
1121
- totalCount += count;
1122
- }
1424
+ function createCodexMapper(emit) {
1425
+ const started = /* @__PURE__ */ new Set();
1426
+ let resultSeen = false;
1427
+ const startTool = (item, name, title, detail) => {
1428
+ if (started.has(item.id)) return;
1429
+ started.add(item.id);
1430
+ emit({
1431
+ type: "tool-start",
1432
+ id: item.id,
1433
+ name,
1434
+ title,
1435
+ detail
1436
+ });
1437
+ };
1438
+ const describe = (item) => {
1439
+ switch (item.type) {
1440
+ case "command_execution": return {
1441
+ name: "command",
1442
+ title: "Run command",
1443
+ detail: clipDetail(item.command)
1444
+ };
1445
+ case "file_change": return {
1446
+ name: "file_change",
1447
+ title: "Edit",
1448
+ detail: clipDetail(item.changes.map((c) => c.path).join(", "))
1449
+ };
1450
+ case "mcp_tool_call": return {
1451
+ name: "mcp",
1452
+ title: `${item.server}: ${item.tool}`,
1453
+ detail: null
1454
+ };
1455
+ case "web_search": return {
1456
+ name: "web_search",
1457
+ title: "Web search",
1458
+ detail: clipDetail(item.query)
1459
+ };
1460
+ default: return {
1461
+ name: item.type,
1462
+ title: item.type,
1463
+ detail: null
1464
+ };
1465
+ }
1466
+ };
1467
+ const handleItem = (phase, item) => {
1468
+ switch (item.type) {
1469
+ case "agent_message": {
1470
+ if (phase !== "completed" || !item.text.trim()) return;
1471
+ const asked = extractQuestionBlock(item.text);
1472
+ const text = asked ? asked.text : item.text;
1473
+ if (text) {
1474
+ emit({
1475
+ type: "text-start",
1476
+ id: item.id
1477
+ });
1478
+ emit({
1479
+ type: "text-end",
1480
+ id: item.id,
1481
+ text
1482
+ });
1123
1483
  }
1124
- return json(res, 200, {
1125
- usages,
1126
- totalCount
1484
+ if (asked) emit({
1485
+ type: "questions",
1486
+ questions: asked.questions
1127
1487
  });
1488
+ return;
1128
1489
  }
1129
- if (listMatch && method === "GET") {
1130
- const scope = decodeURIComponent(listMatch[1]);
1131
- const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1132
- if (!scopedDir) return json(res, 400, { error: "invalid scope" });
1133
- let entries;
1134
- try {
1135
- entries = await fs.readdir(scopedDir);
1136
- } catch (err) {
1137
- if (err.code === "ENOENT") return json(res, 200, { assets: [] });
1138
- throw err;
1139
- }
1140
- const assets = [];
1141
- for (const name of entries) {
1142
- if (!validateAssetName(name)) continue;
1143
- const stat = await fs.stat(path.join(scopedDir, name));
1144
- if (!stat.isFile()) continue;
1145
- assets.push({
1146
- name,
1147
- size: stat.size,
1148
- createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
1149
- mtime: stat.mtimeMs,
1150
- mime: mimeForFilename(name),
1151
- url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(name)}`,
1152
- importPath: assetImportPath(scope, name),
1153
- unused: true
1490
+ case "error":
1491
+ if (phase === "completed") emit({
1492
+ type: "error",
1493
+ text: item.message
1494
+ });
1495
+ return;
1496
+ case "command_execution":
1497
+ case "file_change":
1498
+ case "mcp_tool_call":
1499
+ case "web_search": {
1500
+ const { name, title, detail } = describe(item);
1501
+ startTool(item, name, title, detail);
1502
+ if (phase === "completed") {
1503
+ const status = "status" in item ? item.status : "completed";
1504
+ emit({
1505
+ type: "tool-end",
1506
+ id: item.id,
1507
+ ok: status !== "failed"
1154
1508
  });
1155
1509
  }
1156
- assets.sort((a, b) => a.name.localeCompare(b.name));
1157
- if (assets.length > 0) {
1158
- const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
1159
- const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
1160
- const paths = assets.map((a) => a.importPath);
1161
- for (const docId of scanIds) {
1162
- const source = await readDocSource(ctx.docsRoot, docId);
1163
- if (source === null) continue;
1164
- for (const p of findReferencedAssets(source, paths)) {
1165
- const asset = pathToAsset.get(p);
1166
- if (asset) asset.unused = false;
1167
- }
1168
- }
1169
- }
1170
- return json(res, 200, { assets });
1510
+ return;
1171
1511
  }
1172
- if (fileMatch) {
1173
- const scope = decodeURIComponent(fileMatch[1]);
1174
- const filename = decodeURIComponent(fileMatch[2]);
1175
- const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1176
- if (!file) return json(res, 400, { error: "invalid path" });
1177
- if (method === "GET") try {
1178
- const buf = await fs.readFile(file);
1179
- res.statusCode = 200;
1180
- res.setHeader("content-type", mimeForFilename(filename));
1181
- res.setHeader("cache-control", "no-store");
1182
- res.end(buf);
1512
+ default: return;
1513
+ }
1514
+ };
1515
+ return {
1516
+ get resultSeen() {
1517
+ return resultSeen;
1518
+ },
1519
+ handle(event) {
1520
+ if (!event || typeof event !== "object") return;
1521
+ switch (event.type) {
1522
+ case "thread.started":
1523
+ emit({
1524
+ type: "session-id",
1525
+ id: event.thread_id
1526
+ });
1183
1527
  return;
1184
- } catch (err) {
1185
- if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1186
- throw err;
1187
- }
1188
- if (method === "POST") {
1189
- const requestCheck = validateMutationRequest(req);
1190
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1191
- const overwrite = url.searchParams.get("overwrite") === "1";
1192
- const lenHeader = req.headers["content-length"];
1193
- const len = typeof lenHeader === "string" ? Number(lenHeader) : NaN;
1194
- if (Number.isFinite(len) && len > 26214400) return json(res, 413, { error: "file too large" });
1195
- if (!overwrite) try {
1196
- await fs.access(file);
1197
- return json(res, 409, { error: "asset exists" });
1198
- } catch {}
1199
- const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1200
- if (!scopedDir) return json(res, 400, { error: "invalid scope" });
1201
- await fs.mkdir(scopedDir, { recursive: true });
1202
- const chunks = [];
1203
- let total = 0;
1204
- let oversized = false;
1205
- await new Promise((resolve, reject) => {
1206
- req.on("data", (c) => {
1207
- total += c.length;
1208
- if (total > 26214400) {
1209
- oversized = true;
1210
- req.destroy();
1211
- return;
1212
- }
1213
- chunks.push(c);
1214
- });
1215
- req.on("end", () => resolve());
1216
- req.on("error", reject);
1528
+ case "item.started":
1529
+ handleItem("started", event.item);
1530
+ return;
1531
+ case "item.updated":
1532
+ handleItem("updated", event.item);
1533
+ return;
1534
+ case "item.completed":
1535
+ handleItem("completed", event.item);
1536
+ return;
1537
+ case "turn.failed":
1538
+ resultSeen = true;
1539
+ emit({
1540
+ type: "error",
1541
+ text: event.error.message
1217
1542
  });
1218
- if (oversized) return json(res, 413, { error: "file too large" });
1219
- await fs.writeFile(file, Buffer.concat(chunks));
1220
- const stat = await fs.stat(file);
1221
- return json(res, 200, {
1222
- ok: true,
1223
- name: filename,
1224
- size: stat.size,
1225
- createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
1226
- mtime: stat.mtimeMs,
1227
- mime: mimeForFilename(filename),
1228
- url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
1229
- importPath: assetImportPath(scope, filename)
1543
+ emit({
1544
+ type: "result",
1545
+ durationMs: null,
1546
+ costUsd: null
1230
1547
  });
1231
- }
1232
- if (method === "PATCH") {
1233
- const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1234
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1235
- const target = validateAssetName((await readBody(req)).name);
1236
- if (!target) return json(res, 400, { error: "invalid name" });
1237
- if (target === filename) return json(res, 200, {
1238
- ok: true,
1239
- name: filename
1548
+ return;
1549
+ case "error":
1550
+ emit({
1551
+ type: "error",
1552
+ text: event.message
1240
1553
  });
1241
- const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
1242
- if (!dest) return json(res, 400, { error: "invalid name" });
1243
- try {
1244
- await fs.access(dest);
1245
- return json(res, 409, { error: "target exists" });
1246
- } catch {}
1247
- try {
1248
- await fs.rename(file, dest);
1249
- } catch (err) {
1250
- if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1251
- throw err;
1252
- }
1253
- return json(res, 200, {
1254
- ok: true,
1255
- name: target
1554
+ return;
1555
+ case "turn.completed":
1556
+ resultSeen = true;
1557
+ emit({
1558
+ type: "result",
1559
+ durationMs: null,
1560
+ costUsd: null
1256
1561
  });
1257
- }
1258
- if (method === "DELETE") {
1259
- const requestCheck = validateMutationRequest(req);
1260
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1261
- try {
1262
- await fs.unlink(file);
1263
- } catch (err) {
1264
- if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1265
- throw err;
1266
- }
1267
- return json(res, 200, { ok: true });
1268
- }
1562
+ return;
1563
+ default: return;
1269
1564
  }
1270
- return next();
1565
+ }
1566
+ };
1567
+ }
1568
+ function createCodexProvider() {
1569
+ return {
1570
+ id: "codex",
1571
+ name: "Codex",
1572
+ sdkPackage: CODEX_SDK_PACKAGE,
1573
+ askInstruction: TEXT_QUESTIONS_INSTRUCTION,
1574
+ canRewind: false,
1575
+ canOpenBrowser: false,
1576
+ cliCommand: "codex",
1577
+ models: readCodexModels,
1578
+ async run(opts) {
1579
+ const sdk = await importWorkspacePackage(opts.cwd, CODEX_SDK_PACKAGE);
1580
+ if (!sdk || typeof sdk.Codex !== "function") throw new ProviderUnavailableError(this);
1581
+ const localCli = findSpawnableCli("codex");
1582
+ const codex = new sdk.Codex(localCli ? { codexPathOverride: localCli } : {});
1583
+ const threadOptions = {
1584
+ workingDirectory: opts.cwd,
1585
+ skipGitRepoCheck: true,
1586
+ sandboxMode: "workspace-write",
1587
+ approvalPolicy: "never",
1588
+ ...opts.model ? { model: opts.model } : {},
1589
+ ...opts.effort ? { modelReasoningEffort: opts.effort } : {}
1590
+ };
1591
+ const thread = opts.resume ? codex.resumeThread(opts.resume, threadOptions) : codex.startThread(threadOptions);
1592
+ const input = opts.resume ? opts.prompt : `${opts.systemPromptAppend}\n\n${opts.prompt}`;
1593
+ const mapper = createCodexMapper(opts.emit);
1594
+ const { events } = await thread.runStreamed(input, { signal: opts.signal });
1595
+ try {
1596
+ for await (const event of events) mapper.handle(event);
1597
+ } catch (err) {
1598
+ if (opts.signal.aborted || mapper.resultSeen) return;
1599
+ throw err;
1600
+ }
1601
+ if (thread.id) opts.emit({
1602
+ type: "session-id",
1603
+ id: thread.id
1604
+ });
1605
+ }
1606
+ };
1607
+ }
1608
+ //#endregion
1609
+ //#region src/agent/providers/index.ts
1610
+ function createProviders() {
1611
+ return { codex: createCodexProvider() };
1612
+ }
1613
+ //#endregion
1614
+ //#region src/agent/store.ts
1615
+ const MAX_SESSIONS = 30;
1616
+ const MAX_ITEMS_PER_SESSION = 400;
1617
+ const SAVE_DEBOUNCE_MS = 150;
1618
+ const TITLE_MAX = 60;
1619
+ function newId(prefix) {
1620
+ return `${prefix}-${randomBytes(6).toString("hex")}`;
1621
+ }
1622
+ function titleFromPrompt(text) {
1623
+ const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0);
1624
+ if (!line) return "Untitled";
1625
+ return line.length > TITLE_MAX ? `${line.slice(0, 59)}…` : line;
1626
+ }
1627
+ function readPersisted(file) {
1628
+ if (!existsSync(file)) return [];
1629
+ try {
1630
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
1631
+ if (parsed?.version !== 1 || !Array.isArray(parsed.sessions)) return [];
1632
+ return parsed.sessions.filter((s) => isAgentProviderId(s.provider)).map((s) => ({
1633
+ ...s,
1634
+ status: "idle",
1635
+ items: s.items.map(closePending)
1636
+ }));
1637
+ } catch {
1638
+ return [];
1639
+ }
1640
+ }
1641
+ function closePending(item) {
1642
+ if (item.kind === "assistant" && item.streaming) return {
1643
+ ...item,
1644
+ streaming: false
1645
+ };
1646
+ if (item.kind === "tool" && item.status === "running") return {
1647
+ ...item,
1648
+ status: "error"
1649
+ };
1650
+ if (item.kind === "question" && item.status === "pending") return {
1651
+ ...item,
1652
+ status: "cancelled"
1653
+ };
1654
+ if (item.kind === "permission" && item.status === "pending") return {
1655
+ ...item,
1656
+ status: "denied"
1657
+ };
1658
+ if (item.kind === "check" && item.status === "running") return {
1659
+ ...item,
1660
+ status: "failed",
1661
+ error: "interrupted"
1662
+ };
1663
+ return item;
1664
+ }
1665
+ function createSessionStore(opts) {
1666
+ const sessions = /* @__PURE__ */ new Map();
1667
+ const listeners = /* @__PURE__ */ new Set();
1668
+ let saveTimer = null;
1669
+ let seq = 0;
1670
+ const order = /* @__PURE__ */ new Map();
1671
+ if (opts.file) for (const s of readPersisted(opts.file)) {
1672
+ sessions.set(s.id, s);
1673
+ order.set(s.id, seq++);
1674
+ }
1675
+ const emit = (event) => {
1676
+ for (const l of listeners) l(event);
1677
+ };
1678
+ const scheduleSave = () => {
1679
+ if (!opts.file) return;
1680
+ if (saveTimer) clearTimeout(saveTimer);
1681
+ saveTimer = setTimeout(() => {
1682
+ saveTimer = null;
1683
+ save();
1684
+ }, SAVE_DEBOUNCE_MS);
1685
+ };
1686
+ const writeSnapshot = async (file) => {
1687
+ const body = {
1688
+ version: 1,
1689
+ sessions: list().flatMap((s) => sessions.get(s.id) ?? [])
1690
+ };
1691
+ const tmp = `${file}.tmp`;
1692
+ try {
1693
+ await fs.mkdir(path.dirname(file), { recursive: true });
1694
+ await fs.writeFile(tmp, JSON.stringify(body), {
1695
+ encoding: "utf8",
1696
+ mode: 384
1697
+ });
1698
+ await fs.rename(tmp, file);
1271
1699
  } catch (err) {
1272
- json(res, 500, { error: String(err.message ?? err) });
1700
+ console.error("[open-doc] failed to save agent sessions:", err);
1701
+ await fs.rm(tmp, { force: true }).catch(() => {});
1702
+ }
1703
+ };
1704
+ let saving = Promise.resolve();
1705
+ const save = () => {
1706
+ const file = opts.file;
1707
+ if (!file) return saving;
1708
+ saving = saving.then(() => writeSnapshot(file));
1709
+ return saving;
1710
+ };
1711
+ const touch = (session) => {
1712
+ session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1713
+ order.set(session.id, seq++);
1714
+ emit({
1715
+ type: "session",
1716
+ session: sessionSummary(session)
1717
+ });
1718
+ scheduleSave();
1719
+ };
1720
+ const require = (id) => {
1721
+ const session = sessions.get(id);
1722
+ if (!session) throw new Error(`unknown agent session: ${id}`);
1723
+ return session;
1724
+ };
1725
+ function list() {
1726
+ return Array.from(sessions.values()).sort((a, b) => {
1727
+ if (a.updatedAt !== b.updatedAt) return a.updatedAt < b.updatedAt ? 1 : -1;
1728
+ return (order.get(b.id) ?? 0) - (order.get(a.id) ?? 0);
1729
+ }).map(sessionSummary);
1730
+ }
1731
+ function get(id) {
1732
+ return sessions.get(id) ?? null;
1733
+ }
1734
+ function create(provider, docId) {
1735
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1736
+ const session = {
1737
+ id: newId("s"),
1738
+ provider,
1739
+ title: "New session",
1740
+ createdAt: now,
1741
+ updatedAt: now,
1742
+ status: "idle",
1743
+ docId,
1744
+ providerSessionId: null,
1745
+ items: []
1746
+ };
1747
+ sessions.set(session.id, session);
1748
+ order.set(session.id, seq++);
1749
+ const idle = list().filter((s) => s.status === "idle");
1750
+ for (const stale of idle.slice(MAX_SESSIONS)) {
1751
+ sessions.delete(stale.id);
1752
+ order.delete(stale.id);
1753
+ emit({
1754
+ type: "session-removed",
1755
+ sessionId: stale.id
1756
+ });
1757
+ }
1758
+ touch(session);
1759
+ return session;
1760
+ }
1761
+ function remove(id) {
1762
+ if (!sessions.delete(id)) return false;
1763
+ order.delete(id);
1764
+ emit({
1765
+ type: "session-removed",
1766
+ sessionId: id
1767
+ });
1768
+ scheduleSave();
1769
+ return true;
1770
+ }
1771
+ function patch(id, changes) {
1772
+ const session = require(id);
1773
+ Object.assign(session, changes);
1774
+ touch(session);
1775
+ return session;
1776
+ }
1777
+ function appendItem(sessionId, item) {
1778
+ const session = require(sessionId);
1779
+ session.items.push(item);
1780
+ if (session.items.length > MAX_ITEMS_PER_SESSION) {
1781
+ session.items.splice(0, session.items.length - MAX_ITEMS_PER_SESSION);
1782
+ session.trimmed = true;
1783
+ }
1784
+ emit({
1785
+ type: "item",
1786
+ sessionId,
1787
+ item
1788
+ });
1789
+ touch(session);
1790
+ return item;
1791
+ }
1792
+ function updateItem(sessionId, itemId, kind, changes) {
1793
+ const session = require(sessionId);
1794
+ const index = session.items.findIndex((i) => i.id === itemId && i.kind === kind);
1795
+ if (index === -1) return null;
1796
+ const next = {
1797
+ ...session.items[index],
1798
+ ...changes
1799
+ };
1800
+ session.items[index] = next;
1801
+ emit({
1802
+ type: "item",
1803
+ sessionId,
1804
+ item: next
1805
+ });
1806
+ touch(session);
1807
+ return next;
1808
+ }
1809
+ function truncateFrom(sessionId, itemId) {
1810
+ const session = require(sessionId);
1811
+ const index = session.items.findIndex((i) => i.id === itemId);
1812
+ if (index === -1) return false;
1813
+ session.items.splice(index);
1814
+ emit({
1815
+ type: "truncate",
1816
+ sessionId,
1817
+ itemId
1818
+ });
1819
+ touch(session);
1820
+ return true;
1821
+ }
1822
+ function appendDelta(sessionId, itemId, text) {
1823
+ if (!text) return;
1824
+ const item = require(sessionId).items.find((i) => i.id === itemId);
1825
+ if (item?.kind !== "assistant") return;
1826
+ item.text += text;
1827
+ emit({
1828
+ type: "delta",
1829
+ sessionId,
1830
+ itemId,
1831
+ text
1832
+ });
1833
+ scheduleSave();
1834
+ }
1835
+ function subscribe(listener) {
1836
+ listeners.add(listener);
1837
+ return () => {
1838
+ listeners.delete(listener);
1839
+ };
1840
+ }
1841
+ async function flush() {
1842
+ if (saveTimer) {
1843
+ clearTimeout(saveTimer);
1844
+ saveTimer = null;
1845
+ }
1846
+ await save();
1847
+ }
1848
+ return {
1849
+ list,
1850
+ get,
1851
+ create,
1852
+ remove,
1853
+ patch,
1854
+ appendItem,
1855
+ updateItem,
1856
+ truncateFrom,
1857
+ appendDelta,
1858
+ subscribe,
1859
+ flush
1860
+ };
1861
+ }
1862
+ //#endregion
1863
+ //#region src/agent/runner.ts
1864
+ function cancelPrompt(prompt) {
1865
+ if (prompt.kind === "question") prompt.resolve(null);
1866
+ else prompt.resolve(false);
1867
+ }
1868
+ function createAgentRunner(opts) {
1869
+ const { userCwd, writableRoots, store, providers, onTurnEnd } = opts;
1870
+ const promptOptions = opts.promptOptions ?? (() => ({ docsDir: "docs" }));
1871
+ const running = /* @__PURE__ */ new Map();
1872
+ const pending = /* @__PURE__ */ new Map();
1873
+ const lastOptions = /* @__PURE__ */ new Map();
1874
+ const now = () => (/* @__PURE__ */ new Date()).toISOString();
1875
+ function isRunning(sessionId) {
1876
+ return running.has(sessionId);
1877
+ }
1878
+ async function send(sessionId, options) {
1879
+ const session = store.get(sessionId);
1880
+ if (!session) throw new Error(`unknown agent session: ${sessionId}`);
1881
+ if (running.has(sessionId)) throw new Error("session is already running");
1882
+ const text = options.text.trim();
1883
+ if (!text) throw new Error("empty prompt");
1884
+ const provider = providers[session.provider];
1885
+ let context = options.context;
1886
+ let promptText = text;
1887
+ let resumeAt = null;
1888
+ if (options.edit) {
1889
+ const index = session.items.findIndex((i) => i.id === options.edit);
1890
+ const target = session.items[index];
1891
+ if (target?.kind !== "user") throw new Error("unknown message");
1892
+ if (!session.trimmed && !session.items.slice(0, index).some((i) => i.kind === "user")) {
1893
+ store.patch(sessionId, {
1894
+ providerSessionId: null,
1895
+ providerCheckpoint: null
1896
+ });
1897
+ if (target.newDoc && context) context = {
1898
+ ...context,
1899
+ newDoc: true
1900
+ };
1901
+ } else if (provider.canRewind && target.resumeAt) {
1902
+ resumeAt = target.resumeAt;
1903
+ store.patch(sessionId, { providerCheckpoint: resumeAt });
1904
+ promptText = rewoundPrompt(text);
1905
+ } else promptText = editedPrompt(target.text, text);
1906
+ store.truncateFrom(sessionId, target.id);
1907
+ }
1908
+ const controller = new AbortController();
1909
+ running.set(sessionId, controller);
1910
+ lastOptions.set(sessionId, {
1911
+ ...options,
1912
+ context,
1913
+ edit: void 0
1914
+ });
1915
+ if (session.items.length === 0) store.patch(sessionId, { title: titleFromPrompt(text) });
1916
+ if (options.context?.docId && !session.docId) store.patch(sessionId, { docId: options.context.docId });
1917
+ for (const item of session.items) if (item.kind === "question" && item.status === "pending" && item.id !== options.answering) store.updateItem(sessionId, item.id, "question", { status: "cancelled" });
1918
+ const userItemId = options.answering ?? newId("u");
1919
+ if (!options.answering) store.appendItem(sessionId, {
1920
+ kind: "user",
1921
+ id: userItemId,
1922
+ ts: now(),
1923
+ text,
1924
+ ...session.providerCheckpoint ? { resumeAt: session.providerCheckpoint } : {},
1925
+ ...context?.newDoc ? { newDoc: true } : {}
1926
+ });
1927
+ store.patch(sessionId, { status: "running" });
1928
+ const openText = /* @__PURE__ */ new Set();
1929
+ const openTools = /* @__PURE__ */ new Set();
1930
+ const startedAt = Date.now();
1931
+ let resultSeen = false;
1932
+ const appendQuestion = (questions) => store.appendItem(sessionId, {
1933
+ kind: "question",
1934
+ id: newId("q"),
1935
+ ts: now(),
1936
+ questions,
1937
+ answers: null,
1938
+ status: "pending"
1939
+ });
1940
+ const emit = (event) => {
1941
+ if (!store.get(sessionId)) return;
1942
+ switch (event.type) {
1943
+ case "session-id":
1944
+ store.patch(sessionId, { providerSessionId: event.id });
1945
+ return;
1946
+ case "checkpoint":
1947
+ store.patch(sessionId, { providerCheckpoint: event.id });
1948
+ return;
1949
+ case "text-start":
1950
+ openText.add(event.id);
1951
+ store.appendItem(sessionId, {
1952
+ kind: "assistant",
1953
+ id: event.id,
1954
+ ts: now(),
1955
+ text: "",
1956
+ streaming: true
1957
+ });
1958
+ return;
1959
+ case "text-delta":
1960
+ if (!openText.has(event.id)) emit({
1961
+ type: "text-start",
1962
+ id: event.id
1963
+ });
1964
+ store.appendDelta(sessionId, event.id, event.text);
1965
+ return;
1966
+ case "text-end": {
1967
+ if (!openText.has(event.id)) {
1968
+ if (!event.text) return;
1969
+ emit({
1970
+ type: "text-start",
1971
+ id: event.id
1972
+ });
1973
+ }
1974
+ openText.delete(event.id);
1975
+ const changes = event.text !== null ? {
1976
+ streaming: false,
1977
+ text: event.text
1978
+ } : { streaming: false };
1979
+ store.updateItem(sessionId, event.id, "assistant", changes);
1980
+ return;
1981
+ }
1982
+ case "tool-start":
1983
+ openTools.add(event.id);
1984
+ store.appendItem(sessionId, {
1985
+ kind: "tool",
1986
+ id: event.id,
1987
+ ts: now(),
1988
+ name: event.name,
1989
+ title: event.title,
1990
+ detail: event.detail,
1991
+ status: "running"
1992
+ });
1993
+ return;
1994
+ case "tool-end":
1995
+ openTools.delete(event.id);
1996
+ store.updateItem(sessionId, event.id, "tool", { status: event.ok ? "done" : "error" });
1997
+ return;
1998
+ case "error":
1999
+ store.appendItem(sessionId, {
2000
+ kind: "error",
2001
+ id: newId("e"),
2002
+ ts: now(),
2003
+ text: event.text
2004
+ });
2005
+ return;
2006
+ case "questions":
2007
+ appendQuestion(event.questions);
2008
+ return;
2009
+ case "result":
2010
+ resultSeen = true;
2011
+ store.appendItem(sessionId, {
2012
+ kind: "result",
2013
+ id: newId("r"),
2014
+ ts: now(),
2015
+ durationMs: event.durationMs ?? Date.now() - startedAt,
2016
+ costUsd: event.costUsd,
2017
+ aborted: false
2018
+ });
2019
+ return;
2020
+ }
2021
+ };
2022
+ const askUser = (questions) => new Promise((resolve) => {
2023
+ if (controller.signal.aborted) return resolve(null);
2024
+ const item = appendQuestion(questions);
2025
+ pending.set(item.id, {
2026
+ kind: "question",
2027
+ resolve: (answers) => {
2028
+ pending.delete(item.id);
2029
+ store.updateItem(sessionId, item.id, "question", {
2030
+ answers,
2031
+ status: answers ? "answered" : "cancelled"
2032
+ });
2033
+ resolve(answers);
2034
+ }
2035
+ });
2036
+ });
2037
+ const requestPermission = (request) => new Promise((resolve) => {
2038
+ if (controller.signal.aborted) return resolve(false);
2039
+ const item = store.appendItem(sessionId, {
2040
+ kind: "permission",
2041
+ id: newId("p"),
2042
+ ts: now(),
2043
+ tool: request.tool,
2044
+ title: request.title,
2045
+ detail: request.detail,
2046
+ status: options.autoApprove ? "allowed" : "pending"
2047
+ });
2048
+ if (options.autoApprove) return resolve(true);
2049
+ pending.set(item.id, {
2050
+ kind: "permission",
2051
+ resolve: (allow) => {
2052
+ pending.delete(item.id);
2053
+ store.updateItem(sessionId, item.id, "permission", { status: allow ? "allowed" : "denied" });
2054
+ resolve(allow);
2055
+ }
2056
+ });
2057
+ });
2058
+ const finish = () => {
2059
+ running.delete(sessionId);
2060
+ if (!store.get(sessionId)) return;
2061
+ for (const id of openText) store.updateItem(sessionId, id, "assistant", { streaming: false });
2062
+ for (const id of openTools) store.updateItem(sessionId, id, "tool", { status: "error" });
2063
+ if (!resultSeen) store.appendItem(sessionId, {
2064
+ kind: "result",
2065
+ id: newId("r"),
2066
+ ts: now(),
2067
+ durationMs: Date.now() - startedAt,
2068
+ costUsd: null,
2069
+ aborted: controller.signal.aborted
2070
+ });
2071
+ store.patch(sessionId, { status: "idle" });
2072
+ if (onTurnEnd) Promise.resolve().then(() => onTurnEnd({
2073
+ sessionId,
2074
+ userItemId
2075
+ })).catch((err) => {
2076
+ console.error("[open-doc] agent turn-end handler failed:", err);
2077
+ });
2078
+ };
2079
+ const promptOpts = promptOptions();
2080
+ const prompt = buildTurnPrompt(promptText, context, promptOpts.docsDir);
2081
+ provider.run({
2082
+ cwd: userCwd,
2083
+ writableRoots,
2084
+ prompt,
2085
+ systemPromptAppend: systemPromptAppend(provider.askInstruction, {
2086
+ ...promptOpts,
2087
+ canOpenBrowser: provider.canOpenBrowser
2088
+ }),
2089
+ resume: session.providerSessionId,
2090
+ resumeAt,
2091
+ model: options.model ?? null,
2092
+ effort: options.effort ?? null,
2093
+ signal: controller.signal,
2094
+ emit,
2095
+ askUser,
2096
+ requestPermission
2097
+ }).catch((err) => {
2098
+ if (controller.signal.aborted) return;
2099
+ emit({
2100
+ type: "error",
2101
+ text: err instanceof Error ? err.message : String(err)
2102
+ });
2103
+ }).finally(finish);
2104
+ }
2105
+ function stop(sessionId) {
2106
+ const controller = running.get(sessionId);
2107
+ if (!controller) return false;
2108
+ const session = store.get(sessionId);
2109
+ if (session) for (const item of session.items) {
2110
+ const prompt = pending.get(item.id);
2111
+ if (prompt) cancelPrompt(prompt);
2112
+ }
2113
+ controller.abort();
2114
+ return true;
2115
+ }
2116
+ function respond(sessionId, itemId, payload, next = {}) {
2117
+ if (!store.get(sessionId)?.items.some((i) => i.id === itemId)) return false;
2118
+ const prompt = pending.get(itemId);
2119
+ if (!prompt) return answerInNextTurn(sessionId, itemId, payload, next);
2120
+ if ("cancel" in payload) {
2121
+ cancelPrompt(prompt);
2122
+ return true;
2123
+ }
2124
+ if (prompt.kind === "question" && "answers" in payload) {
2125
+ prompt.resolve(payload.answers);
2126
+ return true;
2127
+ }
2128
+ if (prompt.kind === "permission" && "allow" in payload) {
2129
+ prompt.resolve(payload.allow);
2130
+ return true;
2131
+ }
2132
+ return false;
2133
+ }
2134
+ function answerInNextTurn(sessionId, itemId, payload, next) {
2135
+ const item = store.get(sessionId)?.items.find((i) => i.id === itemId);
2136
+ if (item?.kind !== "question" || item.status !== "pending" || running.has(sessionId)) return false;
2137
+ if (!("answers" in payload) && !("cancel" in payload)) return false;
2138
+ const answers = "answers" in payload ? payload.answers : null;
2139
+ store.updateItem(sessionId, itemId, "question", {
2140
+ answers,
2141
+ status: answers ? "answered" : "cancelled"
2142
+ });
2143
+ const previous = {
2144
+ ...lastOptions.get(sessionId),
2145
+ ...next
2146
+ };
2147
+ const context = previous.context ? {
2148
+ ...previous.context,
2149
+ newDoc: void 0
2150
+ } : void 0;
2151
+ send(sessionId, {
2152
+ ...previous,
2153
+ context,
2154
+ text: answersPrompt(item.questions, answers),
2155
+ answering: itemId
2156
+ }).catch((err) => {
2157
+ console.error("[open-doc] agent turn failed:", err);
2158
+ });
2159
+ return true;
2160
+ }
2161
+ function stopAll() {
2162
+ for (const id of Array.from(running.keys())) stop(id);
2163
+ }
2164
+ return {
2165
+ send,
2166
+ stop,
2167
+ respond,
2168
+ isRunning,
2169
+ stopAll
2170
+ };
2171
+ }
2172
+ //#endregion
2173
+ //#region src/agent/status.ts
2174
+ const INSTALL_TIMEOUT_MS = 6e5;
2175
+ async function providerStatus(userCwd, provider) {
2176
+ const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
2177
+ const cliPath = findOnPath(provider.cliCommand);
2178
+ const [cliVersion, models] = await Promise.all([cliPath ? commandVersion(cliPath) : null, provider.models()]);
2179
+ return {
2180
+ id: provider.id,
2181
+ name: provider.name,
2182
+ sdkPackage: provider.sdkPackage,
2183
+ sdkVersion: sdk?.version ?? null,
2184
+ cliCommand: provider.cliCommand,
2185
+ cliFound: cliPath !== null,
2186
+ cliVersion,
2187
+ ready: sdk !== null,
2188
+ models
2189
+ };
2190
+ }
2191
+ async function agentStatus(userCwd, providers, packageManager) {
2192
+ return {
2193
+ enabled: true,
2194
+ packageManager,
2195
+ providers: await Promise.all(Object.values(providers).map((provider) => providerStatus(userCwd, provider)))
2196
+ };
2197
+ }
2198
+ function installCommandFor(packageManager, pkg) {
2199
+ switch (packageManager) {
2200
+ case "pnpm": return {
2201
+ cmd: "pnpm",
2202
+ args: [
2203
+ "add",
2204
+ "-D",
2205
+ pkg
2206
+ ]
2207
+ };
2208
+ case "yarn": return {
2209
+ cmd: "yarn",
2210
+ args: [
2211
+ "add",
2212
+ "-D",
2213
+ pkg
2214
+ ]
2215
+ };
2216
+ case "bun": return {
2217
+ cmd: "bun",
2218
+ args: [
2219
+ "add",
2220
+ "-d",
2221
+ pkg
2222
+ ]
2223
+ };
2224
+ case "npm": return {
2225
+ cmd: "npm",
2226
+ args: [
2227
+ "install",
2228
+ "-D",
2229
+ pkg
2230
+ ]
2231
+ };
2232
+ }
2233
+ }
2234
+ function installSdk(packageManager, pkg, cwd) {
2235
+ return runCommand(installCommandFor(packageManager, pkg), cwd, INSTALL_TIMEOUT_MS);
2236
+ }
2237
+ //#endregion
2238
+ //#region src/http/request-guard.ts
2239
+ function firstHeaderValue(value) {
2240
+ if (Array.isArray(value)) return value[0] ?? null;
2241
+ return value ?? null;
2242
+ }
2243
+ function headerValue(req, name) {
2244
+ return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
2245
+ }
2246
+ function firstCommaToken(value) {
2247
+ if (!value) return null;
2248
+ const [first] = value.split(",", 1);
2249
+ return first?.trim() || null;
2250
+ }
2251
+ function requestProto(req) {
2252
+ const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
2253
+ if (forwarded === "http" || forwarded === "https") return forwarded;
2254
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
2255
+ }
2256
+ function normalizedOrigin(origin) {
2257
+ try {
2258
+ const url = new URL(origin);
2259
+ return `${url.protocol}//${url.host}`.toLowerCase();
2260
+ } catch {
2261
+ return null;
2262
+ }
2263
+ }
2264
+ /**
2265
+ * The dev server writes to the user's filesystem, so every mutating endpoint is
2266
+ * guarded against a page on another origin driving it through the browser.
2267
+ */
2268
+ function validateMutationRequest(req, opts = {}) {
2269
+ if (opts.requireJsonBody) {
2270
+ if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
2271
+ ok: false,
2272
+ status: 415,
2273
+ error: "content-type must be application/json"
2274
+ };
2275
+ }
2276
+ if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
2277
+ ok: false,
2278
+ status: 403,
2279
+ error: "cross-site request blocked"
2280
+ };
2281
+ const originRaw = headerValue(req, "origin");
2282
+ if (!originRaw) return { ok: true };
2283
+ if (originRaw.toLowerCase() === "null") return {
2284
+ ok: false,
2285
+ status: 403,
2286
+ error: "opaque origin is not allowed"
2287
+ };
2288
+ const actualOrigin = normalizedOrigin(originRaw);
2289
+ if (!actualOrigin) return {
2290
+ ok: false,
2291
+ status: 403,
2292
+ error: "invalid origin header"
2293
+ };
2294
+ const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
2295
+ if (!host) return {
2296
+ ok: false,
2297
+ status: 400,
2298
+ error: "missing host header"
2299
+ };
2300
+ if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
2301
+ ok: false,
2302
+ status: 403,
2303
+ error: "origin mismatch"
2304
+ };
2305
+ return { ok: true };
2306
+ }
2307
+ /** The agent runs commands in the workspace, so only this machine may drive it. */
2308
+ function isLoopbackRequest(req) {
2309
+ const address = req.socket.remoteAddress ?? "";
2310
+ return address === "::1" || address.startsWith("127.") || address.startsWith("::ffff:127.");
2311
+ }
2312
+ //#endregion
2313
+ //#region src/files/assets.ts
2314
+ const GLOBAL_SCOPE = "@global";
2315
+ const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
2316
+ const MIME_BY_EXT = {
2317
+ png: "image/png",
2318
+ jpg: "image/jpeg",
2319
+ jpeg: "image/jpeg",
2320
+ gif: "image/gif",
2321
+ svg: "image/svg+xml",
2322
+ webp: "image/webp",
2323
+ avif: "image/avif",
2324
+ ico: "image/x-icon",
2325
+ pdf: "application/pdf",
2326
+ woff: "font/woff",
2327
+ woff2: "font/woff2",
2328
+ ttf: "font/ttf",
2329
+ otf: "font/otf",
2330
+ csv: "text/csv; charset=utf-8",
2331
+ json: "application/json",
2332
+ txt: "text/plain; charset=utf-8",
2333
+ md: "text/markdown; charset=utf-8"
2334
+ };
2335
+ function mimeForFilename(name) {
2336
+ const dot = name.lastIndexOf(".");
2337
+ if (dot < 0) return "application/octet-stream";
2338
+ return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
2339
+ }
2340
+ function assetCreatedAt(birthtimeMs, mtimeMs) {
2341
+ return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
2342
+ }
2343
+ function validateAssetName(v) {
2344
+ if (typeof v !== "string") return null;
2345
+ const trimmed = v.trim();
2346
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
2347
+ if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
2348
+ if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
2349
+ if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
2350
+ const dot = trimmed.lastIndexOf(".");
2351
+ if (dot <= 0 || dot === trimmed.length - 1) return null;
2352
+ return trimmed;
2353
+ }
2354
+ function resolveAssetsDir(docsRoot, docId) {
2355
+ if (!DOC_ID_RE.test(docId)) return null;
2356
+ const docDir = path.resolve(docsRoot, docId);
2357
+ if (!docDir.startsWith(docsRoot + path.sep)) return null;
2358
+ const assetsDir = path.resolve(docDir, "assets");
2359
+ if (assetsDir !== path.join(docDir, "assets")) return null;
2360
+ return assetsDir;
2361
+ }
2362
+ function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
2363
+ if (scope === "@global") return globalAssetsRoot;
2364
+ return resolveAssetsDir(docsRoot, scope);
2365
+ }
2366
+ function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
2367
+ if (!validateAssetName(filename)) return null;
2368
+ const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
2369
+ if (!dir) return null;
2370
+ const file = path.resolve(dir, filename);
2371
+ if (!file.startsWith(dir + path.sep)) return null;
2372
+ return file;
2373
+ }
2374
+ /** How a document imports an asset — the string we look for when counting usages. */
2375
+ function assetImportPath(scope, filename) {
2376
+ return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
2377
+ }
2378
+ function escapeRegExp(value) {
2379
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2380
+ }
2381
+ /**
2382
+ * Counts references to an asset in a document's source. Matches the quoted path
2383
+ * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
2384
+ * which is every form the authoring skill sanctions.
2385
+ */
2386
+ function countAssetUsages(source, importPath) {
2387
+ const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
2388
+ return source.match(quoted)?.length ?? 0;
2389
+ }
2390
+ function findReferencedAssets(source, importPaths) {
2391
+ return importPaths.filter((p) => countAssetUsages(source, p) > 0);
2392
+ }
2393
+ //#endregion
2394
+ //#region src/import/lang.ts
2395
+ const TRADITIONAL = "們這個說為國來會時對過還後點經學發應麼與實體關開種現當於從際";
2396
+ const SIMPLIFIED = "们这个说为国来会时对过还后点经学发应么与实体关开种现当于从际";
2397
+ const count = (text, re) => text.match(re)?.length ?? 0;
2398
+ /**
2399
+ * The language a Markdown file is written in, when it is one whose sheets
2400
+ * need to say so — Chinese, Japanese, Korean — or `undefined` for anything
2401
+ * else, which the document then leaves at its default.
2402
+ */
2403
+ function detectLang(text) {
2404
+ const han = count(text, /\p{Script=Han}/gu);
2405
+ const kana = count(text, /[\p{Script=Hiragana}\p{Script=Katakana}]/gu);
2406
+ const hangul = count(text, /\p{Script=Hangul}/gu);
2407
+ const latin = count(text, /\p{Script=Latin}/gu);
2408
+ const cjk = han + kana + hangul;
2409
+ if (cjk === 0 || cjk < latin * .25) return void 0;
2410
+ if (hangul > han + kana) return "ko";
2411
+ if (kana > 0 && kana >= han * .05) return "ja";
2412
+ let traditional = 0;
2413
+ let simplified = 0;
2414
+ for (const char of text) {
2415
+ const t = TRADITIONAL.indexOf(char);
2416
+ const s = SIMPLIFIED.indexOf(char);
2417
+ if (t !== -1 && SIMPLIFIED[t] !== char) traditional++;
2418
+ if (s !== -1 && TRADITIONAL[s] !== char) simplified++;
2419
+ }
2420
+ return simplified > traditional ? "zh-Hans" : "zh-Hant";
2421
+ }
2422
+ //#endregion
2423
+ //#region src/import/markdown.ts
2424
+ const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
2425
+ const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
2426
+ const HR_RE = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
2427
+ const QUOTE_RE = /^ {0,3}> ?(.*)$/;
2428
+ const UL_RE = /^(\s*)([-*+])\s+(.*)$/;
2429
+ const OL_RE = /^(\s*)(\d{1,9})[.)]\s+(.*)$/;
2430
+ const SETEXT_RE = /^ {0,3}(=+|-+)\s*$/;
2431
+ const TABLE_DELIM_RE = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
2432
+ function splitLines(source) {
2433
+ return source.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
2434
+ }
2435
+ function parseFrontmatter$1(lines) {
2436
+ if (lines[0]?.trim() !== "---") return {
2437
+ frontmatter: {},
2438
+ rest: lines
2439
+ };
2440
+ const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
2441
+ if (end === -1) return {
2442
+ frontmatter: {},
2443
+ rest: lines
2444
+ };
2445
+ const frontmatter = {};
2446
+ for (const line of lines.slice(1, end)) {
2447
+ const match = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
2448
+ if (!match) continue;
2449
+ frontmatter[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, "");
2450
+ }
2451
+ return {
2452
+ frontmatter,
2453
+ rest: lines.slice(end + 1)
2454
+ };
2455
+ }
2456
+ function splitRow(line) {
2457
+ const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
2458
+ const cells = [];
2459
+ let current = "";
2460
+ for (let i = 0; i < trimmed.length; i++) {
2461
+ const char = trimmed[i];
2462
+ if (char === "\\" && trimmed[i + 1] === "|") {
2463
+ current += "|";
2464
+ i++;
2465
+ continue;
2466
+ }
2467
+ if (char === "|") {
2468
+ cells.push(current.trim());
2469
+ current = "";
2470
+ continue;
2471
+ }
2472
+ current += char;
2473
+ }
2474
+ cells.push(current.trim());
2475
+ return cells;
2476
+ }
2477
+ function parseAlign(line) {
2478
+ return splitRow(line).map((cell) => {
2479
+ const left = cell.startsWith(":");
2480
+ const right = cell.endsWith(":");
2481
+ if (left && right) return "center";
2482
+ if (right) return "right";
2483
+ if (left) return "left";
2484
+ return null;
2485
+ });
2486
+ }
2487
+ function indentOf(line) {
2488
+ return line.length - line.trimStart().length;
2489
+ }
2490
+ function isBlockStart(line) {
2491
+ return ATX_RE.test(line) || HR_RE.test(line) || QUOTE_RE.test(line) || UL_RE.test(line) || OL_RE.test(line) || FENCE_RE.test(line);
2492
+ }
2493
+ function parseMarkdown(source) {
2494
+ const { frontmatter, rest } = parseFrontmatter$1(splitLines(source));
2495
+ return {
2496
+ frontmatter,
2497
+ blocks: parseBlocks(rest)
2498
+ };
2499
+ }
2500
+ function parseBlocks(lines) {
2501
+ const blocks = [];
2502
+ let i = 0;
2503
+ while (i < lines.length) {
2504
+ const line = lines[i];
2505
+ if (line.trim() === "") {
2506
+ i++;
2507
+ continue;
2508
+ }
2509
+ const fence = line.match(FENCE_RE);
2510
+ if (fence) {
2511
+ const marker = fence[1];
2512
+ const value = [];
2513
+ i++;
2514
+ while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {
2515
+ value.push(lines[i]);
2516
+ i++;
2517
+ }
2518
+ i++;
2519
+ blocks.push({
2520
+ type: "code",
2521
+ lang: fence[2] || null,
2522
+ value: value.join("\n")
2523
+ });
2524
+ continue;
2525
+ }
2526
+ const atx = line.match(ATX_RE);
2527
+ if (atx) {
2528
+ blocks.push({
2529
+ type: "heading",
2530
+ level: atx[1].length,
2531
+ children: parseInline(atx[2])
2532
+ });
2533
+ i++;
2534
+ continue;
2535
+ }
2536
+ if (HR_RE.test(line)) {
2537
+ blocks.push({ type: "hr" });
2538
+ i++;
2539
+ continue;
2540
+ }
2541
+ if (QUOTE_RE.test(line)) {
2542
+ const inner = [];
2543
+ while (i < lines.length && (QUOTE_RE.test(lines[i]) || lines[i].trim() !== "")) {
2544
+ const match = lines[i].match(QUOTE_RE);
2545
+ if (!match && lines[i].trim() === "") break;
2546
+ inner.push(match ? match[1] : lines[i]);
2547
+ i++;
2548
+ }
2549
+ blocks.push({
2550
+ type: "quote",
2551
+ children: parseBlocks(inner)
2552
+ });
2553
+ continue;
2554
+ }
2555
+ if (UL_RE.test(line) || OL_RE.test(line)) {
2556
+ const { block, next } = parseList(lines, i);
2557
+ blocks.push(block);
2558
+ i = next;
2559
+ continue;
2560
+ }
2561
+ if (line.includes("|") && lines[i + 1] !== void 0 && TABLE_DELIM_RE.test(lines[i + 1])) {
2562
+ const head = splitRow(line).map(parseInline);
2563
+ const align = parseAlign(lines[i + 1]);
2564
+ const rows = [];
2565
+ i += 2;
2566
+ while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
2567
+ rows.push(splitRow(lines[i]).map(parseInline));
2568
+ i++;
2569
+ }
2570
+ blocks.push({
2571
+ type: "table",
2572
+ head,
2573
+ rows,
2574
+ align
2575
+ });
2576
+ continue;
2577
+ }
2578
+ const paragraph = [];
2579
+ while (i < lines.length && lines[i].trim() !== "") {
2580
+ const next = lines[i + 1];
2581
+ if (next !== void 0 && SETEXT_RE.test(next)) {
2582
+ paragraph.push(lines[i]);
2583
+ i += 2;
2584
+ blocks.push({
2585
+ type: "heading",
2586
+ level: next.trim().startsWith("=") ? 1 : 2,
2587
+ children: parseInline(paragraph.join(" "))
2588
+ });
2589
+ paragraph.length = 0;
2590
+ break;
2591
+ }
2592
+ if (paragraph.length > 0 && isBlockStart(lines[i])) break;
2593
+ paragraph.push(lines[i]);
2594
+ i++;
2595
+ }
2596
+ if (paragraph.length > 0) {
2597
+ const text = paragraph.join("\n");
2598
+ const figure = asStandaloneImage(text);
2599
+ blocks.push(figure ?? {
2600
+ type: "paragraph",
2601
+ children: parseInline(text)
2602
+ });
2603
+ }
2604
+ }
2605
+ return blocks;
2606
+ }
2607
+ /** An image alone in its paragraph is a figure, not a run of inline content. */
2608
+ function asStandaloneImage(text) {
2609
+ const match = text.trim().match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
2610
+ if (!match) return null;
2611
+ return {
2612
+ type: "figure",
2613
+ alt: match[1],
2614
+ src: match[2]
2615
+ };
2616
+ }
2617
+ function parseList(lines, start) {
2618
+ const first = lines[start];
2619
+ const ordered = OL_RE.test(first);
2620
+ const startNumber = ordered ? Number(first.match(OL_RE)?.[2] ?? 1) : 1;
2621
+ const baseIndent = indentOf(first);
2622
+ const items = [];
2623
+ let i = start;
2624
+ let current = null;
2625
+ const flush = () => {
2626
+ if (current) items.push(parseBlocks(current));
2627
+ current = null;
2628
+ };
2629
+ while (i < lines.length) {
2630
+ const line = lines[i];
2631
+ if (line.trim() === "") {
2632
+ const next = lines[i + 1];
2633
+ if (next === void 0 || next.trim() !== "" && indentOf(next) <= baseIndent && !isItem(next)) break;
2634
+ current?.push("");
2635
+ i++;
2636
+ continue;
2637
+ }
2638
+ const match = line.match(ordered ? OL_RE : UL_RE) ?? line.match(ordered ? UL_RE : OL_RE);
2639
+ if (match && indentOf(line) <= baseIndent) {
2640
+ flush();
2641
+ current = [match[3]];
2642
+ i++;
2643
+ continue;
2644
+ }
2645
+ if (indentOf(line) > baseIndent && current) {
2646
+ current.push(line.slice(Math.min(indentOf(line), baseIndent + 2)));
2647
+ i++;
2648
+ continue;
2649
+ }
2650
+ break;
2651
+ }
2652
+ flush();
2653
+ return {
2654
+ block: {
2655
+ type: "list",
2656
+ ordered,
2657
+ start: startNumber,
2658
+ items
2659
+ },
2660
+ next: i
2661
+ };
2662
+ function isItem(line) {
2663
+ return UL_RE.test(line) || OL_RE.test(line);
2664
+ }
2665
+ }
2666
+ const INLINE_RE = /(!\[[^\]]*\]\([^)\s]+(?:\s+"[^"]*")?\))|(\[[^\]]*\]\([^)\s]*(?:\s+"[^"]*")?\))|(`+)([^`]*?)\3|(\*\*|__)(?=\S)([\s\S]*?\S)\5|(\*|_)(?=\S)([\s\S]*?\S)\7|(<[^>\s]+@[^>\s]+>)|(https?:\/\/[^\s<>"')\]]+)/;
2667
+ function parseInline(source) {
2668
+ const out = [];
2669
+ let rest = maskEscapes(source);
2670
+ const pushText = (value) => {
2671
+ if (value === "") return;
2672
+ value.split(/(?: {2}|\\)\n|\n/).forEach((part, index) => {
2673
+ if (index > 0) out.push({ type: "break" });
2674
+ const text = unmask(part);
2675
+ if (text !== "") out.push({
2676
+ type: "text",
2677
+ value: text
2678
+ });
2679
+ });
2680
+ };
2681
+ while (rest.length > 0) {
2682
+ const match = rest.match(INLINE_RE);
2683
+ if (!match || match.index === void 0) break;
2684
+ pushText(rest.slice(0, match.index));
2685
+ const token = match[0];
2686
+ if (match[1]) {
2687
+ const image = token.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
2688
+ if (image) out.push({
2689
+ type: "image",
2690
+ alt: unmask(image[1]),
2691
+ src: unmask(image[2])
2692
+ });
2693
+ } else if (match[2]) {
2694
+ const link = token.match(/^\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)$/);
2695
+ if (link) out.push({
2696
+ type: "link",
2697
+ href: unmask(link[2]),
2698
+ children: parseInline(link[1])
2699
+ });
2700
+ } else if (match[3]) out.push({
2701
+ type: "code",
2702
+ value: unmask(match[4].trim())
2703
+ });
2704
+ else if (match[5]) out.push({
2705
+ type: "strong",
2706
+ children: parseInline(match[6])
2707
+ });
2708
+ else if (match[7]) out.push({
2709
+ type: "em",
2710
+ children: parseInline(match[8])
2711
+ });
2712
+ else if (match[9]) {
2713
+ const address = token.slice(1, -1);
2714
+ out.push({
2715
+ type: "link",
2716
+ href: `mailto:${address}`,
2717
+ children: [{
2718
+ type: "text",
2719
+ value: address
2720
+ }]
2721
+ });
2722
+ } else if (match[10]) {
2723
+ const url = unmask(token);
2724
+ out.push({
2725
+ type: "link",
2726
+ href: url,
2727
+ children: [{
2728
+ type: "text",
2729
+ value: url
2730
+ }]
2731
+ });
2732
+ }
2733
+ rest = rest.slice(match.index + token.length);
2734
+ }
2735
+ pushText(rest);
2736
+ return out;
2737
+ }
2738
+ const ESCAPE_RE = /\\([\\`*_{}[\]()#+\-.!|>~])/g;
2739
+ const MASK_RE = /\u0000(\d+)\u0000/g;
2740
+ /**
2741
+ * The inline scanner is a regex over delimiters, which cannot see a preceding
2742
+ * backslash. Escaped characters are swapped for a sentinel before scanning and
2743
+ * restored on the way out, so `\*not emphasis\*` survives as literal text.
2744
+ */
2745
+ function maskEscapes(value) {
2746
+ return value.replace(ESCAPE_RE, (_, char) => `\u0000${char.charCodeAt(0)}\u0000`);
2747
+ }
2748
+ function unmask(value) {
2749
+ return value.replace(MASK_RE, (_, code) => String.fromCharCode(Number(code)));
2750
+ }
2751
+ /** Flattens inline content to plain text — for titles, alt text, and outline labels. */
2752
+ function inlineText(nodes) {
2753
+ return nodes.map((node) => {
2754
+ switch (node.type) {
2755
+ case "text":
2756
+ case "code": return node.value;
2757
+ case "strong":
2758
+ case "em":
2759
+ case "link": return inlineText(node.children);
2760
+ case "image": return node.alt;
2761
+ case "break": return " ";
2762
+ default: return "";
2763
+ }
2764
+ }).join("").replace(/\s+/g, " ").trim();
2765
+ }
2766
+ //#endregion
2767
+ //#region src/import/to-tsx.ts
2768
+ /** JSX text is written literally; only these characters have to be escaped. */
2769
+ function jsxText(text) {
2770
+ return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
2771
+ }
2772
+ function jsString$1(value) {
2773
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
2774
+ }
2775
+ function attr(value) {
2776
+ return `"${value.replace(/"/g, "&quot;")}"`;
2777
+ }
2778
+ function collectImageSources(blocks) {
2779
+ const out = [];
2780
+ const walkInline = (nodes) => {
2781
+ for (const node of nodes) if (node.type === "image") out.push(node.src);
2782
+ else if (node.type === "strong" || node.type === "em" || node.type === "link") walkInline(node.children);
2783
+ };
2784
+ const walk = (list) => {
2785
+ for (const block of list) switch (block.type) {
2786
+ case "figure":
2787
+ out.push(block.src);
2788
+ break;
2789
+ case "heading":
2790
+ case "paragraph":
2791
+ walkInline(block.children);
2792
+ break;
2793
+ case "quote":
2794
+ walk(block.children);
2795
+ break;
2796
+ case "list":
2797
+ for (const item of block.items) walk(item);
2798
+ break;
2799
+ case "table":
2800
+ for (const cell of block.head) walkInline(cell);
2801
+ for (const row of block.rows) for (const cell of row) walkInline(cell);
2802
+ }
2803
+ };
2804
+ walk(blocks);
2805
+ return out;
2806
+ }
2807
+ function imageSrc(src, images) {
2808
+ const known = images?.get(src);
2809
+ return known ? `{${known.ident}}` : attr(src);
2810
+ }
2811
+ function renderInline(nodes, images) {
2812
+ return nodes.map((node) => {
2813
+ switch (node.type) {
2814
+ case "text": return jsxText(node.value);
2815
+ case "strong": return `<strong>${renderInline(node.children, images)}</strong>`;
2816
+ case "em": return `<em>${renderInline(node.children, images)}</em>`;
2817
+ case "code": return `<code style={codeInline}>${jsxText(node.value)}</code>`;
2818
+ case "link": return `<a href=${attr(node.href)} style={link}>${renderInline(node.children, images)}</a>`;
2819
+ case "image": return `<img src=${imageSrc(node.src, images)} alt=${attr(node.alt)} style={inlineImg} />`;
2820
+ case "break": return "<br />";
2821
+ default: return "";
2822
+ }
2823
+ }).join("");
2824
+ }
2825
+ const HEADING_STYLE = {
2826
+ 1: "h1",
2827
+ 2: "h2",
2828
+ 3: "h3",
2829
+ 4: "h4"
2830
+ };
2831
+ function alignStyle(align) {
2832
+ return align && align !== "left" ? ` align={${jsString$1(align)}}` : "";
2833
+ }
2834
+ function renderBlock(block, images, indent) {
2835
+ const pad = indent;
2836
+ switch (block.type) {
2837
+ case "heading": {
2838
+ const level = Math.min(block.level, 4);
2839
+ const tag = level >= 4 ? "h4" : `h${level}`;
2840
+ return `${pad}<${tag} style={${HEADING_STYLE[level] ?? "h3"}}>${renderInline(block.children, images)}</${tag}>`;
2841
+ }
2842
+ case "paragraph": return `${pad}<p style={p}>${renderInline(block.children, images)}</p>`;
2843
+ case "hr": return `${pad}<hr style={rule} />`;
2844
+ case "code": return `${pad}<pre style={pre}>{${jsString$1(block.value)}}</pre>`;
2845
+ case "quote": return [
2846
+ `${pad}<blockquote style={quote}>`,
2847
+ ...block.children.map((child) => renderBlock(child, images, `${pad} `)),
2848
+ `${pad}</blockquote>`
2849
+ ].join("\n");
2850
+ case "figure": {
2851
+ const caption = block.alt ? `\n${pad} <figcaption style={caption}>${jsxText(block.alt)}</figcaption>` : "";
2852
+ return [
2853
+ `${pad}<figure style={figure}>`,
2854
+ `${pad} <img src=${imageSrc(block.src, images)} alt=${attr(block.alt)} style={img} />${caption}`,
2855
+ `${pad}</figure>`
2856
+ ].join("\n");
2857
+ }
2858
+ case "list": {
2859
+ const tag = block.ordered ? "ol" : "ul";
2860
+ const startAttr = block.ordered && block.start !== 1 ? ` start={${block.start}}` : "";
2861
+ const items = block.items.map((item) => {
2862
+ const inner = item.map((child, index) => child.type === "paragraph" && index === 0 ? `${renderInline(child.children, images)}` : `\n${renderBlock(child, images, `${pad} `)}`).join("");
2863
+ return `${pad} <li style={li}>${inner.startsWith("\n") ? `${inner}\n${pad} ` : inner}</li>`;
2864
+ });
2865
+ return [
2866
+ `${pad}<${tag} style={${tag}}${startAttr}>`,
2867
+ ...items,
2868
+ `${pad}</${tag}>`
2869
+ ].join("\n");
2870
+ }
2871
+ case "table": {
2872
+ const head = block.head.map((cell, i) => `${pad} <Th${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Th>`).join("\n");
2873
+ const rows = block.rows.map((row) => [
2874
+ `${pad} <tr>`,
2875
+ ...row.map((cell, i) => `${pad} <Td${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Td>`),
2876
+ `${pad} </tr>`
2877
+ ].join("\n")).join("\n");
2878
+ return [
2879
+ `${pad}<table style={table}>`,
2880
+ `${pad} <thead>`,
2881
+ `${pad} <tr>`,
2882
+ head,
2883
+ `${pad} </tr>`,
2884
+ `${pad} </thead>`,
2885
+ `${pad} <tbody>`,
2886
+ rows,
2887
+ `${pad} </tbody>`,
2888
+ `${pad}</table>`
2889
+ ].join("\n");
2890
+ }
2891
+ }
2892
+ }
2893
+ function titleFrom(parsed, opts) {
2894
+ if (opts.title) return opts.title;
2895
+ if (parsed.frontmatter.title) return parsed.frontmatter.title;
2896
+ const heading = parsed.blocks.find((block) => block.type === "heading" && block.level === 1);
2897
+ if (heading && heading.type === "heading") return inlineText(heading.children);
2898
+ return opts.docId.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());
2899
+ }
2900
+ const STYLES = `const page = {
2901
+ width: '100%',
2902
+ height: '100%',
2903
+ boxSizing: 'border-box' as const,
2904
+ padding: 'var(--od-margin)',
2905
+ background: 'var(--od-bg)',
2906
+ color: 'var(--od-text)',
2907
+ fontFamily: 'var(--od-font-body)',
2908
+ fontSize: 'var(--od-size-body)',
2909
+ lineHeight: 'var(--od-leading)',
2910
+ position: 'relative' as const,
2911
+ };
2912
+
2913
+ const h1 = {
2914
+ fontFamily: 'var(--od-font-heading)',
2915
+ fontSize: 'var(--od-size-h1)',
2916
+ lineHeight: 1.2,
2917
+ fontWeight: 650,
2918
+ margin: '0 0 18px',
2919
+ };
2920
+
2921
+ const h2 = { ...h1, fontSize: 'var(--od-size-h2)', margin: '26px 0 12px' };
2922
+ const h3 = { ...h1, fontSize: 'var(--od-size-h3)', fontWeight: 600, margin: '20px 0 8px' };
2923
+ const h4 = { ...h3, fontSize: 'var(--od-size-body)', margin: '16px 0 6px' };
2924
+ const p = { margin: '0 0 12px' };
2925
+ // The viewer's CSS reset strips list markers, so both are set back explicitly.
2926
+ const ul = { margin: '0 0 12px', paddingLeft: 22, listStyle: 'disc outside' };
2927
+ const ol = { ...ul, listStyle: 'decimal outside' };
2928
+ const li = { margin: '0 0 5px' };
2929
+ const link = { color: 'var(--od-accent)', textDecoration: 'none' };
2930
+ const rule = { border: 0, borderTop: '1px solid var(--od-rule)', margin: '20px 0' };
2931
+
2932
+ const codeInline = {
2933
+ fontFamily: 'var(--od-font-mono)',
2934
+ fontSize: '0.92em',
2935
+ background: 'var(--od-rule)',
2936
+ borderRadius: 3,
2937
+ padding: '1px 4px',
2938
+ };
2939
+
2940
+ const pre = {
2941
+ fontFamily: 'var(--od-font-mono)',
2942
+ fontSize: 11,
2943
+ lineHeight: 1.5,
2944
+ background: 'var(--od-rule)',
2945
+ borderRadius: 'var(--od-radius)',
2946
+ padding: '10px 12px',
2947
+ margin: '0 0 14px',
2948
+ whiteSpace: 'pre-wrap' as const,
2949
+ overflowWrap: 'anywhere' as const,
2950
+ };
2951
+
2952
+ const quote = {
2953
+ margin: '0 0 14px',
2954
+ padding: '2px 0 2px 14px',
2955
+ borderLeft: '2px solid var(--od-accent)',
2956
+ color: 'var(--od-muted)',
2957
+ };
2958
+
2959
+ const table = {
2960
+ width: '100%',
2961
+ borderCollapse: 'collapse' as const,
2962
+ tableLayout: 'fixed' as const,
2963
+ margin: '0 0 16px',
2964
+ };
2965
+
2966
+ const figure = { margin: '0 0 16px' };
2967
+ const img = { width: '100%', display: 'block' as const };
2968
+ const inlineImg = { maxWidth: '100%', verticalAlign: 'middle' as const };
2969
+ const caption = { fontSize: 'var(--od-size-caption)', color: 'var(--od-muted)', margin: '6px 0 0' };
2970
+
2971
+ const Th = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
2972
+ <th
2973
+ style={{
2974
+ textAlign: align,
2975
+ fontFamily: 'var(--od-font-heading)',
2976
+ fontSize: 11,
2977
+ fontWeight: 600,
2978
+ letterSpacing: '0.04em',
2979
+ textTransform: 'uppercase',
2980
+ color: 'var(--od-muted)',
2981
+ borderBottom: '1px solid var(--od-rule)',
2982
+ padding: '0 8px 6px',
2983
+ }}
2984
+ >
2985
+ {children}
2986
+ </th>
2987
+ );
2988
+
2989
+ const Td = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
2990
+ <td
2991
+ style={{
2992
+ textAlign: align,
2993
+ fontSize: 12,
2994
+ padding: '7px 8px',
2995
+ borderBottom: '1px solid var(--od-rule)',
2996
+ fontVariantNumeric: align === 'right' ? 'tabular-nums' : undefined,
2997
+ }}
2998
+ >
2999
+ {children}
3000
+ </td>
3001
+ );
3002
+
3003
+ const Footer = () => {
3004
+ const n = useDocPageNumber();
3005
+ const total = useDocPageCount();
3006
+ return (
3007
+ <div
3008
+ style={{
3009
+ position: 'absolute',
3010
+ left: 'var(--od-margin)',
3011
+ right: 'var(--od-margin)',
3012
+ bottom: 40,
3013
+ display: 'flex',
3014
+ justifyContent: 'space-between',
3015
+ fontSize: 'var(--od-size-caption)',
3016
+ color: 'var(--od-muted)',
3017
+ }}
3018
+ >
3019
+ <span>{DOC_TITLE}</span>
3020
+ <span style={{ fontVariantNumeric: 'tabular-nums' }}>
3021
+ {n} / {total}
3022
+ </span>
3023
+ </div>
3024
+ );
3025
+ };`;
3026
+ const DESIGN = `export const design: DesignSystem = {
3027
+ palette: {
3028
+ bg: '#ffffff',
3029
+ text: '#16181d',
3030
+ muted: '#6b7280',
3031
+ accent: '#2563eb',
3032
+ rule: '#e5e7eb',
3033
+ },
3034
+ fonts: {
3035
+ heading: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
3036
+ body: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
3037
+ mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace',
3038
+ },
3039
+ typeScale: { title: 44, h1: 28, h2: 20, h3: 16, body: 14, caption: 10 },
3040
+ margin: 76,
3041
+ leading: 1.55,
3042
+ radius: 6,
3043
+ };`;
3044
+ /**
3045
+ * Turns parsed markdown into a document module. The output is ordinary authored
3046
+ * TSX — inline styles, real heading tags, plain JSX text — so the outline, the
3047
+ * inspector, and the design panel all work on an imported document exactly as
3048
+ * they do on a hand-written one.
3049
+ */
3050
+ function generateDocumentSource(parsed, opts) {
3051
+ const title = titleFrom(parsed, opts);
3052
+ const subtitle = opts.subtitle ?? parsed.frontmatter.subtitle;
3053
+ const author = opts.author ?? parsed.frontmatter.author;
3054
+ const theme = opts.theme ?? parsed.frontmatter.theme;
3055
+ const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
3056
+ const orientation = opts.orientation ?? parsed.frontmatter.orientation;
3057
+ const lang = opts.lang ?? parsed.frontmatter.lang;
3058
+ const cover = opts.cover !== false;
3059
+ let blocks = parsed.blocks;
3060
+ const first = blocks[0];
3061
+ if (cover && first?.type === "heading" && first.level === 1 && inlineText(first.children) === title) blocks = blocks.slice(1);
3062
+ const images = opts.images;
3063
+ const imports = images ? [...images.values()] : [];
3064
+ const head = [
3065
+ `import type { ReactNode } from 'react';`,
3066
+ `import {\n${[
3067
+ "type DesignSystem",
3068
+ "type DocEntry",
3069
+ "type DocMeta",
3070
+ ...cover || opts.contents ? ["type DocPage"] : [],
3071
+ ...opts.contents ? ["TableOfContents"] : [],
3072
+ "flow",
3073
+ "useDocPageCount",
3074
+ "useDocPageNumber"
3075
+ ].map((name) => ` ${name},`).join("\n")}\n} from '@open-document/core';`,
3076
+ ...imports.map((image) => `import ${image.ident} from './assets/${image.filename}';`)
3077
+ ].join("\n");
3078
+ const styles = STYLES.replace("{DOC_TITLE}", jsxText(title));
3079
+ const coverPage = cover ? `const Cover: DocPage = () => (
3080
+ <div style={{ ...page, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
3081
+ ${subtitle ? ` <p style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--od-accent)', margin: 0 }}>
3082
+ ${jsxText(subtitle)}
3083
+ </p>\n` : ""} <h1 style={{ ...h1, fontSize: 'var(--od-size-title)', margin: '16px 0 12px' }} data-od-outline="skip">
3084
+ ${jsxText(title)}
3085
+ </h1>
3086
+ ${author ? ` <p style={{ color: 'var(--od-muted)', margin: 0 }}>${jsxText(author)}</p>\n` : ""} </div>
3087
+ );` : "";
3088
+ const contentsPage = opts.contents ? `const Contents: DocPage = () => (
3089
+ <div style={page}>
3090
+ <h1 style={h1} data-od-outline="skip">
3091
+ Contents
3092
+ </h1>
3093
+ <TableOfContents maxLevel={2} />
3094
+ </div>
3095
+ );` : "";
3096
+ const body = `const Body = flow(
3097
+ <>
3098
+ ${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
3099
+ </>,
3100
+ { footer: Footer },
3101
+ );`;
3102
+ const metaFields = [
3103
+ ` title: ${jsString$1(title)},`,
3104
+ ...subtitle ? [` subtitle: ${jsString$1(subtitle)},`] : [],
3105
+ ...author ? [` author: ${jsString$1(author)},`] : [],
3106
+ ...pageSize ? [` pageSize: ${jsString$1(pageSize)},`] : [],
3107
+ ...orientation ? [` orientation: ${jsString$1(orientation)},`] : [],
3108
+ ...theme ? [` theme: ${jsString$1(theme)},`] : [],
3109
+ ...lang ? [` lang: ${jsString$1(lang)},`] : [],
3110
+ ` createdAt: ${jsString$1(opts.createdAt)},`
3111
+ ];
3112
+ const entries = [
3113
+ ...cover ? ["Cover"] : [],
3114
+ ...opts.contents ? ["Contents"] : [],
3115
+ "Body"
3116
+ ];
3117
+ return {
3118
+ source: [
3119
+ head,
3120
+ "",
3121
+ DESIGN,
3122
+ "",
3123
+ styles,
3124
+ "",
3125
+ ...coverPage ? [coverPage, ""] : [],
3126
+ ...contentsPage ? [contentsPage, ""] : [],
3127
+ body,
3128
+ "",
3129
+ `export const meta: DocMeta = {\n${metaFields.join("\n")}\n};`,
3130
+ `export default [${entries.join(", ")}] satisfies DocEntry[];`,
3131
+ ""
3132
+ ].join("\n"),
3133
+ title,
3134
+ blockCount: blocks.length
3135
+ };
3136
+ }
3137
+ //#endregion
3138
+ //#region src/ops/import.ts
3139
+ const REMOTE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
3140
+ function slugify(value, fallback = "document") {
3141
+ const slug = value.normalize("NFKD").toLowerCase().replace(/['"]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
3142
+ return DOC_ID_RE.test(slug) ? slug : fallback;
3143
+ }
3144
+ function uniqueId(base, taken) {
3145
+ if (!taken.has(base)) return base;
3146
+ for (let n = 2; n < 1e3; n++) {
3147
+ const candidate = `${base}-${n}`;
3148
+ if (!taken.has(candidate)) return candidate;
3149
+ }
3150
+ throw new OpsError(409, `could not find a free id for ${base}`);
3151
+ }
3152
+ function identFor(index) {
3153
+ return `figure${index + 1}`;
3154
+ }
3155
+ /**
3156
+ * Reads markdown and writes a real open-doc document: `flow()` body, inline
3157
+ * styles, a cover, and any local images copied into the document's own assets
3158
+ * folder. Nothing about the result is special-cased — it is the same shape an
3159
+ * agent would have written by hand, and every editing surface works on it.
3160
+ */
3161
+ async function importMarkdown(ctx, opts) {
3162
+ const sourceFile = opts.file ? path.resolve(ctx.userCwd, opts.file) : null;
3163
+ if (sourceFile && !sourceFile.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `file must sit inside the workspace: ${opts.file}`);
3164
+ let markdown = opts.markdown;
3165
+ if (markdown === void 0) {
3166
+ if (!sourceFile) throw new OpsError(400, "pass either `markdown` or `file`");
3167
+ try {
3168
+ markdown = await fs.readFile(sourceFile, "utf8");
3169
+ } catch {
3170
+ throw new OpsError(404, `file not found: ${opts.file}`);
3171
+ }
3172
+ }
3173
+ if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
3174
+ const parsed = parseMarkdown(markdown);
3175
+ const language = opts.lang ?? (parsed.frontmatter.lang ? void 0 : detectLang(markdown));
3176
+ const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
3177
+ if (pageSize !== void 0 && !isPageSizeName(pageSize)) throw new OpsError(422, `unsupported pageSize \`${pageSize}\` — use ${PAGE_SIZE_NAMES.join(", ")}`);
3178
+ const orientation = opts.orientation ?? parsed.frontmatter.orientation;
3179
+ if (orientation !== void 0 && !isOrientation(orientation)) throw new OpsError(422, `unsupported orientation \`${orientation}\` — use ${ORIENTATIONS.join(", ")}`);
3180
+ const fallbackName = sourceFile ? path.basename(sourceFile).replace(/\.mdx?$/i, "") : "document";
3181
+ const requestedId = opts.docId ?? slugify(opts.title ?? parsed.frontmatter.title ?? fallbackName);
3182
+ if (opts.docId && !DOC_ID_RE.test(opts.docId)) throw new OpsError(400, `invalid document id: ${opts.docId}`);
3183
+ const docId = opts.docId ?? uniqueId(requestedId, new Set(await listDocIds$1(ctx)));
3184
+ const baseDir = sourceFile ? path.dirname(sourceFile) : ctx.userCwd;
3185
+ const images = /* @__PURE__ */ new Map();
3186
+ const missing = [];
3187
+ const staged = [];
3188
+ const usedNames = /* @__PURE__ */ new Set();
3189
+ for (const src of new Set(collectImageSources(parsed.blocks))) {
3190
+ if (REMOTE_RE.test(src)) continue;
3191
+ const from = path.resolve(baseDir, src.split(/[?#]/)[0]);
3192
+ if (!from.startsWith(ctx.userCwd + path.sep) || !existsSync(from)) {
3193
+ missing.push(src);
3194
+ continue;
1273
3195
  }
3196
+ const safe = validateAssetName(path.basename(from));
3197
+ if (!safe) {
3198
+ missing.push(src);
3199
+ continue;
3200
+ }
3201
+ const filename = usedNames.has(safe) ? `${images.size + 1}-${safe}` : safe;
3202
+ usedNames.add(filename);
3203
+ images.set(src, {
3204
+ source: src,
3205
+ ident: identFor(images.size),
3206
+ filename
3207
+ });
3208
+ staged.push({
3209
+ from,
3210
+ filename
3211
+ });
3212
+ }
3213
+ const generated = generateDocumentSource(parsed, {
3214
+ docId,
3215
+ ...opts.title !== void 0 ? { title: opts.title } : {},
3216
+ ...opts.subtitle !== void 0 ? { subtitle: opts.subtitle } : {},
3217
+ ...opts.author !== void 0 ? { author: opts.author } : {},
3218
+ ...opts.theme !== void 0 ? { theme: opts.theme } : {},
3219
+ ...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
3220
+ ...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
3221
+ ...language ? { lang: language } : {},
3222
+ ...opts.cover !== void 0 ? { cover: opts.cover } : {},
3223
+ ...opts.contents !== void 0 ? { contents: opts.contents } : {},
3224
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3225
+ images
1274
3226
  });
3227
+ const created = await createDocument(ctx, docId, generated.source);
3228
+ if (staged.length > 0) {
3229
+ const assetsDir = path.join(ctx.docsRoot, docId, "assets");
3230
+ await fs.mkdir(assetsDir, { recursive: true });
3231
+ for (const { from, filename } of staged) await fs.copyFile(from, path.join(assetsDir, filename));
3232
+ }
3233
+ return {
3234
+ id: created.id,
3235
+ entry: created.entry,
3236
+ title: generated.title,
3237
+ blocks: generated.blockCount,
3238
+ assets: staged.map((asset) => asset.filename),
3239
+ missingAssets: missing
3240
+ };
1275
3241
  }
1276
3242
  //#endregion
1277
- //#region src/vite/routes/changes.ts
1278
- function registerChangesRoutes(server, ctx) {
1279
- server.middlewares.use("/__changes", async (req, res, next) => {
1280
- const url = new URL(req.url ?? "/", "http://local");
1281
- const method = req.method ?? "GET";
1282
- try {
1283
- if (method === "GET" && url.pathname === "/") return json(res, 200, await readChanges(ctx, url.searchParams.get("docId") ?? "", url.searchParams.get("since") || "HEAD"));
1284
- if (method === "GET" && url.pathname === "/revisions") return json(res, 200, { revisions: await listRevisions(ctx, url.searchParams.get("docId") ?? "") });
1285
- if (method === "POST" && url.pathname === "/revert") {
1286
- const check = validateMutationRequest(req, { requireJsonBody: true });
1287
- if (!check.ok) return json(res, check.status, { error: check.error });
1288
- const body = await readBody(req);
1289
- if (typeof body.docId !== "string" || typeof body.file !== "string" || typeof body.hunk !== "string") return json(res, 400, { error: "invalid payload" });
1290
- return json(res, 200, await revertChange(ctx, body.docId, {
1291
- file: body.file,
1292
- hunk: body.hunk,
1293
- ...typeof body.since === "string" ? { since: body.since } : {}
1294
- }));
3243
+ //#region src/ops/layout.ts
3244
+ /**
3245
+ * Chromium and a Vite server are expensive to start, and an agent checking its
3246
+ * work calls these back to back. One session is kept warm and closed once
3247
+ * nobody has asked for a while.
3248
+ */
3249
+ const IDLE_MS = 12e4;
3250
+ let shared = null;
3251
+ let pending = null;
3252
+ let idleTimer = null;
3253
+ let leases = 0;
3254
+ function armIdleClose() {
3255
+ if (idleTimer) clearTimeout(idleTimer);
3256
+ idleTimer = setTimeout(() => {
3257
+ if (leases > 0) return;
3258
+ const current = shared;
3259
+ shared = null;
3260
+ idleTimer = null;
3261
+ current?.session.close().catch(() => {});
3262
+ }, IDLE_MS);
3263
+ idleTimer.unref?.();
3264
+ }
3265
+ async function acquire(ctx) {
3266
+ if (shared && shared.origin === ctx.serverOrigin) return shared.session;
3267
+ if (!pending) {
3268
+ const origin = ctx.serverOrigin;
3269
+ pending = createRenderSession({
3270
+ userCwd: ctx.userCwd,
3271
+ origin,
3272
+ deviceScaleFactor: 2
3273
+ }).then((session) => {
3274
+ shared = {
3275
+ session,
3276
+ origin
3277
+ };
3278
+ return session;
3279
+ }).finally(() => {
3280
+ pending = null;
3281
+ });
3282
+ }
3283
+ return pending;
3284
+ }
3285
+ async function withDoc(ctx, docId, fn) {
3286
+ if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
3287
+ let session;
3288
+ try {
3289
+ session = await acquire(ctx);
3290
+ } catch (err) {
3291
+ if (err instanceof RenderUnavailableError) throw new OpsError(501, err.message);
3292
+ throw new OpsError(500, err.message);
3293
+ }
3294
+ leases++;
3295
+ let renderer = null;
3296
+ try {
3297
+ renderer = await session.open(docId);
3298
+ return await fn(renderer);
3299
+ } catch (err) {
3300
+ if (err instanceof OpsError) throw err;
3301
+ throw new OpsError(422, err.message);
3302
+ } finally {
3303
+ await renderer?.close().catch(() => {});
3304
+ leases--;
3305
+ armIdleClose();
3306
+ }
3307
+ }
3308
+ /** Closes the warm browser. Call before the process exits so nothing lingers. */
3309
+ async function closeRenderSession() {
3310
+ if (idleTimer) clearTimeout(idleTimer);
3311
+ idleTimer = null;
3312
+ const current = shared;
3313
+ shared = null;
3314
+ await current?.session.close().catch(() => {});
3315
+ }
3316
+ /**
3317
+ * Renders the document headlessly at true page size and reports what is wrong
3318
+ * with the layout — the part of a document an agent writing React cannot see.
3319
+ */
3320
+ async function checkLayout(ctx, docId) {
3321
+ return withDoc(ctx, docId, async (renderer) => {
3322
+ const report = await renderer.diagnose();
3323
+ return {
3324
+ docId: report.docId || docId,
3325
+ title: report.title,
3326
+ pageCount: report.pageCount,
3327
+ errors: report.findings.filter((f) => f.severity === "error").length,
3328
+ warnings: report.findings.filter((f) => f.severity === "warn").length,
3329
+ findings: report.findings
3330
+ };
3331
+ });
3332
+ }
3333
+ async function renderDocPage(ctx, docId, page) {
3334
+ return withDoc(ctx, docId, async (renderer) => {
3335
+ const bytes = await renderer.screenshot(page);
3336
+ return {
3337
+ docId,
3338
+ page,
3339
+ pageCount: renderer.status.pageCount,
3340
+ mimeType: "image/png",
3341
+ base64: Buffer$1.from(bytes).toString("base64")
3342
+ };
3343
+ });
3344
+ }
3345
+ function resolveOutDir(ctx, outDir) {
3346
+ const resolved = path.resolve(ctx.userCwd, outDir);
3347
+ if (resolved !== ctx.userCwd && !resolved.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${outDir}`);
3348
+ return resolved;
3349
+ }
3350
+ /**
3351
+ * Writes the document's files. With `each`, a document that exports
3352
+ * `records` is laid out and written once per row — `name` (or
3353
+ * `meta.recordName`) names each row's files.
3354
+ */
3355
+ async function exportDocument(ctx, docId, opts = {}) {
3356
+ const format = opts.format ?? "pdf";
3357
+ const dir = resolveOutDir(ctx, opts.outDir ?? "out");
3358
+ return withDoc(ctx, docId, async (renderer) => {
3359
+ await fs.mkdir(dir, { recursive: true });
3360
+ const written = [];
3361
+ const taken = /* @__PURE__ */ new Set();
3362
+ const write = async (name, bytes) => {
3363
+ const file = path.join(dir, name);
3364
+ await fs.writeFile(file, bytes);
3365
+ written.push(path.relative(ctx.userCwd, file));
3366
+ };
3367
+ const free = (base) => {
3368
+ let name = base;
3369
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
3370
+ taken.add(name);
3371
+ return name;
3372
+ };
3373
+ const writeCopy = async (base) => {
3374
+ if (format === "pdf") await write(`${base}.pdf`, await renderer.pdf());
3375
+ else if (format === "html" || format === "docx") {
3376
+ const bundle = format === "html" ? await renderer.html() : await renderer.docx();
3377
+ if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
3378
+ await write(`${base}${path.extname(bundle.filename)}`, Buffer$1.from(bundle.base64, "base64"));
3379
+ } else {
3380
+ const width = String(renderer.status.pageCount).length;
3381
+ for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${base}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
1295
3382
  }
1296
- return next();
1297
- } catch (err) {
1298
- if (err instanceof OpsError) return json(res, err.status, { error: err.message });
1299
- json(res, 500, { error: String(err.message ?? err) });
3383
+ };
3384
+ if (!opts.each) {
3385
+ await writeCopy(docId);
3386
+ return {
3387
+ docId,
3388
+ format,
3389
+ pageCount: renderer.status.pageCount,
3390
+ files: written
3391
+ };
3392
+ }
3393
+ const records = renderer.status.records;
3394
+ if (records === 0) throw new OpsError(422, `${docId} has no records — export \`records\` (rows from a .csv) to write one copy per row`);
3395
+ let pageCount = 0;
3396
+ for (let index = 0; index < records; index++) {
3397
+ const name = await renderer.setRecord(index, opts.name);
3398
+ pageCount += renderer.status.pageCount;
3399
+ await writeCopy(free(name));
1300
3400
  }
3401
+ return {
3402
+ docId,
3403
+ format,
3404
+ pageCount,
3405
+ files: written,
3406
+ records
3407
+ };
1301
3408
  });
1302
3409
  }
1303
3410
  //#endregion
@@ -1596,6 +3703,11 @@ async function fileDocument(ctx, docId, folderId) {
1596
3703
  }
1597
3704
  //#endregion
1598
3705
  //#region src/ops/templates.ts
3706
+ var templates_exports = /* @__PURE__ */ __exportAll({
3707
+ createFromTemplate: () => createFromTemplate,
3708
+ listTemplates: () => listTemplates,
3709
+ suggestDocId: () => suggestDocId
3710
+ });
1599
3711
  const TEMPLATE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
1600
3712
  const MANIFEST = "template.json";
1601
3713
  async function readTemplateDir(dir, name, source) {
@@ -1671,57 +3783,564 @@ async function createFromTemplate(ctx, opts) {
1671
3783
  recursive: true,
1672
3784
  filter: (src) => path.basename(src) !== MANIFEST
1673
3785
  });
1674
- const entry = path.join(dir, "index.tsx");
1675
- let source = await fs.readFile(entry, "utf8");
1676
- source = setMetaString(source, "createdAt", (/* @__PURE__ */ new Date()).toISOString()) ?? source;
1677
- if (title) {
1678
- const placeholder = template.summary.placeholder;
1679
- if (placeholder && !/[{}<>'"\\\n]/.test(title)) source = source.split(placeholder).join(title);
1680
- source = setMetaString(source, "title", title) ?? source;
1681
- }
1682
- await fs.writeFile(entry, source, "utf8");
1683
- return {
1684
- id,
1685
- entry: path.relative(ctx.userCwd, entry)
1686
- };
3786
+ const entry = path.join(dir, "index.tsx");
3787
+ let source = await fs.readFile(entry, "utf8");
3788
+ source = setMetaString(source, "createdAt", (/* @__PURE__ */ new Date()).toISOString()) ?? source;
3789
+ if (title) {
3790
+ const placeholder = template.summary.placeholder;
3791
+ if (placeholder && !/[{}<>'"\\\n]/.test(title)) source = source.split(placeholder).join(title);
3792
+ source = setMetaString(source, "title", title) ?? source;
3793
+ }
3794
+ await fs.writeFile(entry, source, "utf8");
3795
+ return {
3796
+ id,
3797
+ entry: path.relative(ctx.userCwd, entry)
3798
+ };
3799
+ }
3800
+ //#endregion
3801
+ //#region src/vite/routes/templates.ts
3802
+ /**
3803
+ * Tells the dev server a document was just written, instead of waiting for the
3804
+ * file watcher. On Linux the watcher can be late to a folder created and
3805
+ * filled in one go, and the browser, already sent to the new document, finds
3806
+ * none until it notices.
3807
+ */
3808
+ function announceDocument(server, ctx, docId) {
3809
+ server.watcher.emit("add", path.join(ctx.docsRoot, docId, "index.tsx"));
3810
+ }
3811
+ function registerTemplateRoutes(server, ctx) {
3812
+ server.middlewares.use("/__templates", async (req, res, next) => {
3813
+ const url = new URL(req.url ?? "/", "http://local");
3814
+ const method = req.method ?? "GET";
3815
+ try {
3816
+ if (method === "GET" && url.pathname === "/") return json(res, 200, { templates: await listTemplates(ctx) });
3817
+ const create = url.pathname.match(/^\/([^/]+)\/create$/);
3818
+ if (create && method === "POST") {
3819
+ const check = validateMutationRequest(req, { requireJsonBody: true });
3820
+ if (!check.ok) return json(res, check.status, { error: check.error });
3821
+ const body = await readBody(req);
3822
+ const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
3823
+ const docId = text(body.docId);
3824
+ const title = text(body.title);
3825
+ const result = await createFromTemplate(ctx, {
3826
+ template: decodeURIComponent(create[1]),
3827
+ ...docId ? { docId } : {},
3828
+ ...title ? { title } : {}
3829
+ });
3830
+ const folderId = text(body.folderId);
3831
+ if (folderId) await fileDocument(ctx, result.id, folderId);
3832
+ announceDocument(server, ctx, result.id);
3833
+ return json(res, 200, {
3834
+ ok: true,
3835
+ docId: result.id
3836
+ });
3837
+ }
3838
+ return next();
3839
+ } catch (err) {
3840
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
3841
+ json(res, 500, { error: String(err.message ?? err) });
3842
+ }
3843
+ });
3844
+ }
3845
+ //#endregion
3846
+ //#region src/vite/routes/agent.ts
3847
+ function parseContext(raw) {
3848
+ if (!raw || typeof raw !== "object") return void 0;
3849
+ const r = raw;
3850
+ const ctx = {};
3851
+ if (typeof r.docId === "string" && DOC_ID_RE.test(r.docId)) ctx.docId = r.docId;
3852
+ if (typeof r.docTitle === "string") ctx.docTitle = r.docTitle.slice(0, 120);
3853
+ if (typeof r.pageNumber === "number" && Number.isFinite(r.pageNumber)) ctx.pageNumber = Math.max(1, Math.floor(r.pageNumber));
3854
+ if (typeof r.totalPages === "number" && Number.isFinite(r.totalPages)) ctx.totalPages = Math.max(1, Math.floor(r.totalPages));
3855
+ if (typeof r.pendingComments === "number" && Number.isFinite(r.pendingComments)) ctx.pendingComments = Math.max(0, Math.floor(r.pendingComments));
3856
+ if (r.newDoc === true) ctx.newDoc = true;
3857
+ const sel = r.selection;
3858
+ if (sel && typeof sel === "object") {
3859
+ const s = sel;
3860
+ if (typeof s.line === "number" && typeof s.column === "number") ctx.selection = {
3861
+ line: Math.max(1, Math.floor(s.line)),
3862
+ column: Math.max(0, Math.floor(s.column)),
3863
+ tagName: typeof s.tagName === "string" ? s.tagName.slice(0, 32) : "element",
3864
+ text: typeof s.text === "string" ? s.text.slice(0, 120) : ""
3865
+ };
3866
+ }
3867
+ return ctx;
3868
+ }
3869
+ const MODEL_RE = /^[\w.:[\]-]{1,80}$/;
3870
+ function parseModel(raw) {
3871
+ return typeof raw === "string" && MODEL_RE.test(raw) ? raw : null;
3872
+ }
3873
+ async function renamePlaceholderDoc(server, ctx, store, broadcast, turn) {
3874
+ const session = store.get(turn.sessionId);
3875
+ const docId = session?.docId;
3876
+ if (!session || !docId || !UNTITLED_DOC_ID_RE.test(docId)) return;
3877
+ const start = session.items.findIndex((i) => i.id === turn.userItemId);
3878
+ let marked = null;
3879
+ for (const item of session.items.slice(start + 1)) {
3880
+ if (item.kind !== "assistant") continue;
3881
+ const slug = extractDocSlug(item.text);
3882
+ if (slug === null) continue;
3883
+ marked = slug;
3884
+ store.updateItem(session.id, item.id, "assistant", { text: stripDocSlug(item.text) });
3885
+ }
3886
+ if (store.list().some((s) => s.docId === docId && s.status === "running")) return;
3887
+ const entry = resolveEntry(ctx, docId);
3888
+ if (!entry) return;
3889
+ let source;
3890
+ try {
3891
+ source = await fs.readFile(entry, "utf8");
3892
+ } catch {
3893
+ return;
3894
+ }
3895
+ const title = readMetaTitle(source);
3896
+ if (!title || title === "Untitled document") return;
3897
+ const desired = slugify(marked ?? "", "") || slugify(title, "");
3898
+ if (!desired || UNTITLED_DOC_ID_RE.test(desired)) return;
3899
+ if (store.list().some((s) => s.docId === docId && s.status === "running")) return;
3900
+ const renamed = await renameDocDir(ctx, docId, desired).catch(() => null);
3901
+ if (!renamed || renamed.id === docId) return;
3902
+ for (const s of store.list()) if (s.docId === docId) store.patch(s.id, { docId: renamed.id });
3903
+ announceDocument(server, ctx, renamed.id);
3904
+ broadcast({
3905
+ type: "doc-renamed",
3906
+ from: docId,
3907
+ to: renamed.id
3908
+ });
3909
+ }
3910
+ async function checkAfterTurn(server, ctx, store, providers, turn) {
3911
+ const session = store.get(turn.sessionId);
3912
+ const docId = session?.docId;
3913
+ if (!session || !docId) return;
3914
+ if (store.list().some((s) => s.docId === docId && s.status === "running")) return;
3915
+ const entry = resolveEntry(ctx, docId);
3916
+ const entryMtimeMs = entry ? (await fs.stat(entry).catch(() => null))?.mtimeMs ?? null : null;
3917
+ if (!shouldCheckAfterTurn({
3918
+ session,
3919
+ userItemId: turn.userItemId,
3920
+ canOpenBrowser: providers[session.provider]?.canOpenBrowser ?? true,
3921
+ entryMtimeMs
3922
+ })) return;
3923
+ const item = store.appendItem(session.id, {
3924
+ kind: "check",
3925
+ id: newId("c"),
3926
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
3927
+ docId,
3928
+ status: "running",
3929
+ pageCount: null,
3930
+ findings: [],
3931
+ total: 0,
3932
+ error: null
3933
+ });
3934
+ const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
3935
+ try {
3936
+ const report = await checkLayout({
3937
+ ...ctx,
3938
+ ...origin ? { serverOrigin: origin } : {}
3939
+ }, docId);
3940
+ if (!store.get(session.id)) return;
3941
+ store.updateItem(session.id, item.id, "check", {
3942
+ status: "done",
3943
+ ...checkItemResult(report)
3944
+ });
3945
+ } catch (err) {
3946
+ if (!store.get(session.id)) return;
3947
+ store.updateItem(session.id, item.id, "check", {
3948
+ status: "failed",
3949
+ error: err instanceof Error ? err.message : String(err)
3950
+ });
3951
+ }
3952
+ }
3953
+ function parseRespond(raw) {
3954
+ if (!raw || typeof raw !== "object") return null;
3955
+ const r = raw;
3956
+ if (r.cancel === true) return { cancel: true };
3957
+ if (typeof r.allow === "boolean") return { allow: r.allow };
3958
+ if (r.answers && typeof r.answers === "object") {
3959
+ const answers = {};
3960
+ for (const [k, v] of Object.entries(r.answers)) if (typeof v === "string") answers[k] = v;
3961
+ return { answers };
3962
+ }
3963
+ return null;
3964
+ }
3965
+ function parseTurnSettings(raw) {
3966
+ const settings = {};
3967
+ const context = parseContext(raw.context);
3968
+ if (context) settings.context = context;
3969
+ if (typeof raw.autoApprove === "boolean") settings.autoApprove = raw.autoApprove;
3970
+ if ("model" in raw) settings.model = parseModel(raw.model);
3971
+ if ("effort" in raw) settings.effort = isAgentEffort(raw.effort) ? raw.effort : null;
3972
+ return settings;
3973
+ }
3974
+ const AGENT_BODY_LIMIT = 1048576;
3975
+ function registerAgentRoutes(server, ctx) {
3976
+ const providers = createProviders();
3977
+ const store = createSessionStore({ file: path.join(ctx.userCwd, "node_modules", ".open-doc", "agent-sessions.json") });
3978
+ const streams = /* @__PURE__ */ new Set();
3979
+ const broadcast = (event) => {
3980
+ const frame = `data: ${JSON.stringify(event)}\n\n`;
3981
+ for (const stream of streams) stream.write(frame);
3982
+ };
3983
+ const heartbeat = setInterval(() => {
3984
+ for (const stream of streams) stream.write(": ping\n\n");
3985
+ }, 25e3);
3986
+ heartbeat.unref();
3987
+ const runner = createAgentRunner({
3988
+ userCwd: ctx.userCwd,
3989
+ writableRoots: [ctx.docsRoot, ctx.globalAssetsRoot],
3990
+ promptOptions: () => {
3991
+ const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
3992
+ return {
3993
+ docsDir: ctx.docsDir,
3994
+ ...origin ? { origin } : {}
3995
+ };
3996
+ },
3997
+ store,
3998
+ providers,
3999
+ onTurnEnd: async (turn) => {
4000
+ await renamePlaceholderDoc(server, ctx, store, broadcast, turn);
4001
+ await checkAfterTurn(server, ctx, store, providers, turn);
4002
+ }
4003
+ });
4004
+ store.subscribe(broadcast);
4005
+ server.httpServer?.on("close", () => {
4006
+ clearInterval(heartbeat);
4007
+ for (const stream of streams) stream.end();
4008
+ runner.stopAll();
4009
+ store.flush();
4010
+ });
4011
+ const installsInFlight = /* @__PURE__ */ new Map();
4012
+ server.middlewares.use("/__agent", async (req, res, next) => {
4013
+ const url = new URL(req.url ?? "/", "http://local");
4014
+ const method = req.method ?? "GET";
4015
+ const segments = url.pathname.split("/").filter(Boolean);
4016
+ const enabled = isLoopbackRequest(req);
4017
+ try {
4018
+ if (method === "GET" && url.pathname === "/status") {
4019
+ res.setHeader("cache-control", "no-store");
4020
+ if (!enabled) return json(res, 200, {
4021
+ enabled: false,
4022
+ packageManager: "",
4023
+ providers: []
4024
+ });
4025
+ const pm = await detectPackageManager(ctx.userCwd);
4026
+ return json(res, 200, await agentStatus(ctx.userCwd, providers, pm));
4027
+ }
4028
+ if (!enabled) return json(res, 404, { error: "agent panel disabled" });
4029
+ if (method === "GET" && url.pathname === "/events") {
4030
+ res.writeHead(200, {
4031
+ "content-type": "text/event-stream",
4032
+ "cache-control": "no-store",
4033
+ connection: "keep-alive"
4034
+ });
4035
+ res.write(": connected\n\n");
4036
+ streams.add(res);
4037
+ const drop = () => streams.delete(res);
4038
+ res.on("close", drop);
4039
+ res.on("error", drop);
4040
+ return;
4041
+ }
4042
+ if (method === "POST" && url.pathname === "/install") {
4043
+ const guard = validateMutationRequest(req, { requireJsonBody: true });
4044
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
4045
+ const body = await readBody(req, AGENT_BODY_LIMIT);
4046
+ if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
4047
+ const provider = providers[body.provider];
4048
+ const pm = await detectPackageManager(ctx.userCwd);
4049
+ const pkg = provider.sdkPackage;
4050
+ let install = installsInFlight.get(pkg);
4051
+ if (!install) {
4052
+ install = installSdk(pm, pkg, ctx.userCwd).finally(() => installsInFlight.delete(pkg));
4053
+ installsInFlight.set(pkg, install);
4054
+ }
4055
+ await install;
4056
+ return json(res, 200, { ok: true });
4057
+ }
4058
+ if (method === "GET" && url.pathname === "/sessions") {
4059
+ res.setHeader("cache-control", "no-store");
4060
+ return json(res, 200, { sessions: store.list() });
4061
+ }
4062
+ if (method === "POST" && url.pathname === "/sessions") {
4063
+ const guard = validateMutationRequest(req, { requireJsonBody: true });
4064
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
4065
+ const body = await readBody(req, AGENT_BODY_LIMIT);
4066
+ if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
4067
+ const docId = typeof body.docId === "string" && DOC_ID_RE.test(body.docId) ? body.docId : null;
4068
+ return json(res, 200, store.create(body.provider, docId));
4069
+ }
4070
+ if (segments[0] === "sessions" && segments[1]) {
4071
+ const id = segments[1];
4072
+ const action = segments[2];
4073
+ const session = store.get(id);
4074
+ if (!session) return json(res, 404, { error: "session not found" });
4075
+ if (method === "GET" && !action) {
4076
+ res.setHeader("cache-control", "no-store");
4077
+ return json(res, 200, session);
4078
+ }
4079
+ if (method === "DELETE" && !action) {
4080
+ const guard = validateMutationRequest(req);
4081
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
4082
+ runner.stop(id);
4083
+ store.remove(id);
4084
+ return json(res, 200, { ok: true });
4085
+ }
4086
+ if (method === "POST" && action === "messages") {
4087
+ const guard = validateMutationRequest(req, { requireJsonBody: true });
4088
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
4089
+ const body = await readBody(req, AGENT_BODY_LIMIT);
4090
+ if (typeof body.text !== "string" || !body.text.trim()) return json(res, 400, { error: "missing text" });
4091
+ if (runner.isRunning(id)) return json(res, 409, { error: "session is already running" });
4092
+ if (body.edit !== void 0 && !session.items.some((i) => i.id === body.edit && i.kind === "user")) return json(res, 400, { error: "unknown message" });
4093
+ await runner.send(id, {
4094
+ text: body.text,
4095
+ context: parseContext(body.context),
4096
+ autoApprove: body.autoApprove === true,
4097
+ model: parseModel(body.model),
4098
+ effort: isAgentEffort(body.effort) ? body.effort : null,
4099
+ edit: typeof body.edit === "string" ? body.edit : void 0
4100
+ });
4101
+ return json(res, 202, { ok: true });
4102
+ }
4103
+ if (method === "POST" && action === "stop") {
4104
+ const guard = validateMutationRequest(req);
4105
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
4106
+ return json(res, 200, { ok: runner.stop(id) });
4107
+ }
4108
+ if (method === "POST" && action === "respond") {
4109
+ const guard = validateMutationRequest(req, { requireJsonBody: true });
4110
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
4111
+ const body = await readBody(req, AGENT_BODY_LIMIT);
4112
+ const payload = parseRespond(body);
4113
+ if (typeof body.itemId !== "string" || !payload) return json(res, 400, { error: "invalid response" });
4114
+ const ok = runner.respond(id, body.itemId, payload, parseTurnSettings(body));
4115
+ return json(res, ok ? 200 : 409, ok ? { ok } : { error: "nothing pending" });
4116
+ }
4117
+ }
4118
+ next();
4119
+ } catch (err) {
4120
+ if (err instanceof BodyTooLargeError) return json(res, 413, { error: err.message });
4121
+ json(res, 500, { error: String(err.message ?? err) });
4122
+ }
4123
+ });
4124
+ }
4125
+ //#endregion
4126
+ //#region src/vite/routes/assets.ts
4127
+ async function listDocIds(docsRoot) {
4128
+ try {
4129
+ return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
4130
+ } catch {
4131
+ return [];
4132
+ }
4133
+ }
4134
+ async function readDocSource(docsRoot, docId) {
4135
+ const entry = resolveDocEntry(docsRoot, docId);
4136
+ if (!entry) return null;
4137
+ try {
4138
+ return await fs.readFile(entry, "utf8");
4139
+ } catch {
4140
+ return null;
4141
+ }
4142
+ }
4143
+ function registerAssetRoutes(server, ctx) {
4144
+ server.middlewares.use("/__assets", async (req, res, next) => {
4145
+ const url = new URL(req.url ?? "/", "http://local");
4146
+ const method = req.method ?? "GET";
4147
+ try {
4148
+ const listMatch = url.pathname.match(/^\/([^/]+)\/?$/);
4149
+ const fileMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)$/);
4150
+ const usagesMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/usages$/);
4151
+ if (usagesMatch && method === "GET") {
4152
+ const scope = decodeURIComponent(usagesMatch[1]);
4153
+ const filename = decodeURIComponent(usagesMatch[2]);
4154
+ if (!validateAssetName(filename)) return json(res, 400, { error: "invalid path" });
4155
+ const isGlobal = scope === GLOBAL_SCOPE;
4156
+ if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
4157
+ const importPath = assetImportPath(scope, filename);
4158
+ const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
4159
+ const usages = [];
4160
+ let totalCount = 0;
4161
+ for (const docId of docIds) {
4162
+ const source = await readDocSource(ctx.docsRoot, docId);
4163
+ if (source === null) continue;
4164
+ const count = countAssetUsages(source, importPath);
4165
+ if (count > 0) {
4166
+ usages.push({
4167
+ docId,
4168
+ count
4169
+ });
4170
+ totalCount += count;
4171
+ }
4172
+ }
4173
+ return json(res, 200, {
4174
+ usages,
4175
+ totalCount
4176
+ });
4177
+ }
4178
+ if (listMatch && method === "GET") {
4179
+ const scope = decodeURIComponent(listMatch[1]);
4180
+ const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
4181
+ if (!scopedDir) return json(res, 400, { error: "invalid scope" });
4182
+ let entries;
4183
+ try {
4184
+ entries = await fs.readdir(scopedDir);
4185
+ } catch (err) {
4186
+ if (err.code === "ENOENT") return json(res, 200, { assets: [] });
4187
+ throw err;
4188
+ }
4189
+ const assets = [];
4190
+ for (const name of entries) {
4191
+ if (!validateAssetName(name)) continue;
4192
+ const stat = await fs.stat(path.join(scopedDir, name));
4193
+ if (!stat.isFile()) continue;
4194
+ assets.push({
4195
+ name,
4196
+ size: stat.size,
4197
+ createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
4198
+ mtime: stat.mtimeMs,
4199
+ mime: mimeForFilename(name),
4200
+ url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(name)}`,
4201
+ importPath: assetImportPath(scope, name),
4202
+ unused: true
4203
+ });
4204
+ }
4205
+ assets.sort((a, b) => a.name.localeCompare(b.name));
4206
+ if (assets.length > 0) {
4207
+ const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
4208
+ const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
4209
+ const paths = assets.map((a) => a.importPath);
4210
+ for (const docId of scanIds) {
4211
+ const source = await readDocSource(ctx.docsRoot, docId);
4212
+ if (source === null) continue;
4213
+ for (const p of findReferencedAssets(source, paths)) {
4214
+ const asset = pathToAsset.get(p);
4215
+ if (asset) asset.unused = false;
4216
+ }
4217
+ }
4218
+ }
4219
+ return json(res, 200, { assets });
4220
+ }
4221
+ if (fileMatch) {
4222
+ const scope = decodeURIComponent(fileMatch[1]);
4223
+ const filename = decodeURIComponent(fileMatch[2]);
4224
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
4225
+ if (!file) return json(res, 400, { error: "invalid path" });
4226
+ if (method === "GET") try {
4227
+ const buf = await fs.readFile(file);
4228
+ res.statusCode = 200;
4229
+ res.setHeader("content-type", mimeForFilename(filename));
4230
+ res.setHeader("cache-control", "no-store");
4231
+ res.end(buf);
4232
+ return;
4233
+ } catch (err) {
4234
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
4235
+ throw err;
4236
+ }
4237
+ if (method === "POST") {
4238
+ const requestCheck = validateMutationRequest(req);
4239
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4240
+ const overwrite = url.searchParams.get("overwrite") === "1";
4241
+ const lenHeader = req.headers["content-length"];
4242
+ const len = typeof lenHeader === "string" ? Number(lenHeader) : NaN;
4243
+ if (Number.isFinite(len) && len > 26214400) return json(res, 413, { error: "file too large" });
4244
+ if (!overwrite) try {
4245
+ await fs.access(file);
4246
+ return json(res, 409, { error: "asset exists" });
4247
+ } catch {}
4248
+ const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
4249
+ if (!scopedDir) return json(res, 400, { error: "invalid scope" });
4250
+ await fs.mkdir(scopedDir, { recursive: true });
4251
+ const chunks = [];
4252
+ let total = 0;
4253
+ let oversized = false;
4254
+ await new Promise((resolve, reject) => {
4255
+ req.on("data", (c) => {
4256
+ total += c.length;
4257
+ if (total > 26214400) {
4258
+ oversized = true;
4259
+ req.destroy();
4260
+ return;
4261
+ }
4262
+ chunks.push(c);
4263
+ });
4264
+ req.on("end", () => resolve());
4265
+ req.on("error", reject);
4266
+ });
4267
+ if (oversized) return json(res, 413, { error: "file too large" });
4268
+ await fs.writeFile(file, Buffer.concat(chunks));
4269
+ const stat = await fs.stat(file);
4270
+ return json(res, 200, {
4271
+ ok: true,
4272
+ name: filename,
4273
+ size: stat.size,
4274
+ createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
4275
+ mtime: stat.mtimeMs,
4276
+ mime: mimeForFilename(filename),
4277
+ url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
4278
+ importPath: assetImportPath(scope, filename)
4279
+ });
4280
+ }
4281
+ if (method === "PATCH") {
4282
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
4283
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4284
+ const target = validateAssetName((await readBody(req)).name);
4285
+ if (!target) return json(res, 400, { error: "invalid name" });
4286
+ if (target === filename) return json(res, 200, {
4287
+ ok: true,
4288
+ name: filename
4289
+ });
4290
+ const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
4291
+ if (!dest) return json(res, 400, { error: "invalid name" });
4292
+ try {
4293
+ await fs.access(dest);
4294
+ return json(res, 409, { error: "target exists" });
4295
+ } catch {}
4296
+ try {
4297
+ await fs.rename(file, dest);
4298
+ } catch (err) {
4299
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
4300
+ throw err;
4301
+ }
4302
+ return json(res, 200, {
4303
+ ok: true,
4304
+ name: target
4305
+ });
4306
+ }
4307
+ if (method === "DELETE") {
4308
+ const requestCheck = validateMutationRequest(req);
4309
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4310
+ try {
4311
+ await fs.unlink(file);
4312
+ } catch (err) {
4313
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
4314
+ throw err;
4315
+ }
4316
+ return json(res, 200, { ok: true });
4317
+ }
4318
+ }
4319
+ return next();
4320
+ } catch (err) {
4321
+ json(res, 500, { error: String(err.message ?? err) });
4322
+ }
4323
+ });
1687
4324
  }
1688
4325
  //#endregion
1689
- //#region src/vite/routes/templates.ts
1690
- /**
1691
- * Tells the dev server a document was just written, instead of waiting for the
1692
- * file watcher. On Linux the watcher can be late to a folder created and
1693
- * filled in one go, and the browser, already sent to the new document, finds
1694
- * none until it notices.
1695
- */
1696
- function announceDocument(server, ctx, docId) {
1697
- server.watcher.emit("add", path.join(ctx.docsRoot, docId, "index.tsx"));
1698
- }
1699
- function registerTemplateRoutes(server, ctx) {
1700
- server.middlewares.use("/__templates", async (req, res, next) => {
4326
+ //#region src/vite/routes/changes.ts
4327
+ function registerChangesRoutes(server, ctx) {
4328
+ server.middlewares.use("/__changes", async (req, res, next) => {
1701
4329
  const url = new URL(req.url ?? "/", "http://local");
1702
4330
  const method = req.method ?? "GET";
1703
4331
  try {
1704
- if (method === "GET" && url.pathname === "/") return json(res, 200, { templates: await listTemplates(ctx) });
1705
- const create = url.pathname.match(/^\/([^/]+)\/create$/);
1706
- if (create && method === "POST") {
4332
+ if (method === "GET" && url.pathname === "/") return json(res, 200, await readChanges(ctx, url.searchParams.get("docId") ?? "", url.searchParams.get("since") || "HEAD"));
4333
+ if (method === "GET" && url.pathname === "/revisions") return json(res, 200, { revisions: await listRevisions(ctx, url.searchParams.get("docId") ?? "") });
4334
+ if (method === "POST" && url.pathname === "/revert") {
1707
4335
  const check = validateMutationRequest(req, { requireJsonBody: true });
1708
4336
  if (!check.ok) return json(res, check.status, { error: check.error });
1709
4337
  const body = await readBody(req);
1710
- const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
1711
- const docId = text(body.docId);
1712
- const title = text(body.title);
1713
- const result = await createFromTemplate(ctx, {
1714
- template: decodeURIComponent(create[1]),
1715
- ...docId ? { docId } : {},
1716
- ...title ? { title } : {}
1717
- });
1718
- const folderId = text(body.folderId);
1719
- if (folderId) await fileDocument(ctx, result.id, folderId);
1720
- announceDocument(server, ctx, result.id);
1721
- return json(res, 200, {
1722
- ok: true,
1723
- docId: result.id
1724
- });
4338
+ if (typeof body.docId !== "string" || typeof body.file !== "string" || typeof body.hunk !== "string") return json(res, 400, { error: "invalid payload" });
4339
+ return json(res, 200, await revertChange(ctx, body.docId, {
4340
+ file: body.file,
4341
+ hunk: body.hunk,
4342
+ ...typeof body.since === "string" ? { since: body.since } : {}
4343
+ }));
1725
4344
  }
1726
4345
  return next();
1727
4346
  } catch (err) {
@@ -1739,6 +4358,16 @@ function registerDocRoutes(server, ctx) {
1739
4358
  try {
1740
4359
  const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
1741
4360
  const idMatch = url.pathname.match(/^\/([^/]+)$/);
4361
+ if (url.pathname === "/" && method === "POST") {
4362
+ const requestCheck = validateMutationRequest(req);
4363
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4364
+ const result = await createBlankDocument(ctx);
4365
+ announceDocument(server, ctx, result.id);
4366
+ return json(res, 200, {
4367
+ ok: true,
4368
+ docId: result.id
4369
+ });
4370
+ }
1742
4371
  if (duplicateMatch && method === "POST") {
1743
4372
  const requestCheck = validateMutationRequest(req);
1744
4373
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
@@ -3659,6 +6288,7 @@ function apiPlugin(opts) {
3659
6288
  registerEditRoutes(server, ctx);
3660
6289
  registerChangesRoutes(server, ctx);
3661
6290
  registerTemplateRoutes(server, ctx);
6291
+ if (opts.agent !== false) registerAgentRoutes(server, ctx);
3662
6292
  }
3663
6293
  };
3664
6294
  }
@@ -4319,6 +6949,7 @@ async function createViteConfig(opts) {
4319
6949
  return {
4320
6950
  base: config.base ?? "/",
4321
6951
  root: APP_ROOT,
6952
+ cacheDir: path.join(userCwd, "node_modules", ".vite", opts.headless ? "open-doc-headless" : "open-doc"),
4322
6953
  configFile: false,
4323
6954
  envDir: userCwd,
4324
6955
  plugins: [
@@ -4347,7 +6978,8 @@ async function createViteConfig(opts) {
4347
6978
  userCwd,
4348
6979
  docsDir,
4349
6980
  assetsDir,
4350
- coreVersion: CORE_VERSION
6981
+ coreVersion: CORE_VERSION,
6982
+ agent: !opts.headless && config.agent?.enabled !== false
4351
6983
  }),
4352
6984
  ...opts.headless ? [] : [currentPlugin({
4353
6985
  userCwd,
@@ -4405,4 +7037,255 @@ async function createViteConfig(opts) {
4405
7037
  };
4406
7038
  }
4407
7039
  //#endregion
4408
- export { duplicateDocument as A, assertExpectedSource as C, createDocument as D, OpsError as E, resolveEntry as F, writeDocument as I, makeContext as L, listDocuments as M, readDocument as N, deleteDocument as O, renameDocument as P, revertChange as S, withFileLock as T, readTheme as _, writeText as a, listRevisions as b, listTemplates as c, deleteAsset as d, fileDocument as f, listThemes as g, listFolders as h, writeEdits as i, listDocIds$1 as j, docDir as k, suggestDocId as l, listAssets as m, addComment as n, writeTexts as o, findAssetUsages as p, readText as r, createFromTemplate as s, createViteConfig as t, createFolder as u, writeAsset as v, hashSource as w, readChanges as x, validateAssetName as y };
7040
+ //#region src/render/session.ts
7041
+ var RenderUnavailableError = class extends Error {
7042
+ constructor(message) {
7043
+ super(message);
7044
+ this.name = "RenderUnavailableError";
7045
+ }
7046
+ };
7047
+ const INSTALL_HINT = "Headless rendering needs Playwright. Install it in this workspace:\n pnpm add -D playwright && pnpm exec playwright install chromium";
7048
+ async function loadPlaywright() {
7049
+ try {
7050
+ return await import("playwright");
7051
+ } catch {
7052
+ throw new RenderUnavailableError(INSTALL_HINT);
7053
+ }
7054
+ }
7055
+ const DEFAULT_TIMEOUT = 6e4;
7056
+ const PRINT_PAGE_SELECTOR = "#od-print-root .od-print-page";
7057
+ async function bootServer(userCwd) {
7058
+ const base = await createViteConfig({
7059
+ userCwd,
7060
+ headless: true
7061
+ });
7062
+ const config = mergeConfig(base, {
7063
+ logLevel: "silent",
7064
+ server: {
7065
+ port: 0,
7066
+ strictPort: false,
7067
+ open: false
7068
+ }
7069
+ });
7070
+ const server = await createServer(config);
7071
+ await server.listen();
7072
+ const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
7073
+ if (!origin) {
7074
+ await server.close();
7075
+ throw new Error("Could not determine the dev server URL");
7076
+ }
7077
+ return {
7078
+ server,
7079
+ origin
7080
+ };
7081
+ }
7082
+ async function createRenderSession(opts) {
7083
+ const { chromium } = await loadPlaywright();
7084
+ const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT;
7085
+ let server = null;
7086
+ let origin = opts.origin?.replace(/\/$/, "") ?? "";
7087
+ if (!origin) {
7088
+ const booted = await bootServer(opts.userCwd);
7089
+ server = booted.server;
7090
+ origin = booted.origin;
7091
+ }
7092
+ let browser;
7093
+ try {
7094
+ browser = await chromium.launch({ headless: true });
7095
+ } catch (err) {
7096
+ await server?.close();
7097
+ throw new RenderUnavailableError(`${INSTALL_HINT}\n\nChromium failed to launch: ${err.message}`);
7098
+ }
7099
+ return {
7100
+ origin,
7101
+ async open(docId) {
7102
+ const page = await browser.newPage({
7103
+ viewport: {
7104
+ width: 1280,
7105
+ height: 1024
7106
+ },
7107
+ ...opts.deviceScaleFactor !== void 0 ? { deviceScaleFactor: opts.deviceScaleFactor } : {}
7108
+ });
7109
+ const errors = [];
7110
+ page.on("pageerror", (err) => errors.push(String(err?.message ?? err)));
7111
+ await page.goto(`${origin}/d/${encodeURIComponent(docId)}`, {
7112
+ waitUntil: "load",
7113
+ timeout
7114
+ });
7115
+ try {
7116
+ await page.waitForFunction("globalThis.__openDoc ? globalThis.__openDoc.status().ready : false", void 0, { timeout });
7117
+ } catch {
7118
+ await page.close();
7119
+ const detail = errors.length ? `\n${errors.join("\n")}` : "";
7120
+ throw new Error(`Document "${docId}" never finished rendering.${detail}`);
7121
+ }
7122
+ const status = await page.evaluate("globalThis.__openDoc.status()");
7123
+ const renderer = {
7124
+ status,
7125
+ diagnose: () => page.evaluate("globalThis.__openDoc.diagnose()"),
7126
+ async pdf() {
7127
+ await page.evaluate("globalThis.__openDoc.preparePrint()");
7128
+ try {
7129
+ return await page.pdf({
7130
+ printBackground: true,
7131
+ preferCSSPageSize: true,
7132
+ outline: true,
7133
+ tagged: true
7134
+ });
7135
+ } finally {
7136
+ await page.evaluate("globalThis.__openDoc.releasePrint()");
7137
+ }
7138
+ },
7139
+ async screenshot(pageNumber) {
7140
+ if (pageNumber < 1 || pageNumber > status.pageCount) throw new Error(`page ${pageNumber} is out of range — "${docId}" has ${status.pageCount}`);
7141
+ await page.evaluate("globalThis.__openDoc.preparePrint()");
7142
+ await page.emulateMedia({ media: "print" });
7143
+ try {
7144
+ const sheet = await page.$(`${PRINT_PAGE_SELECTOR}:nth-child(${pageNumber})`);
7145
+ if (!sheet) throw new Error(`page ${pageNumber} did not render`);
7146
+ return await sheet.screenshot({ type: "png" });
7147
+ } finally {
7148
+ await page.emulateMedia({ media: null });
7149
+ await page.evaluate("globalThis.__openDoc.releasePrint()");
7150
+ }
7151
+ },
7152
+ async sheets() {
7153
+ await page.evaluate("globalThis.__openDoc.preparePrint()");
7154
+ await page.emulateMedia({ media: "print" });
7155
+ try {
7156
+ const out = [];
7157
+ for (let n = 1; n <= status.pageCount; n++) {
7158
+ const selector = `${PRINT_PAGE_SELECTOR}:nth-child(${n})`;
7159
+ const sheet = await page.$(selector);
7160
+ if (!sheet) throw new Error(`page ${n} did not render`);
7161
+ const png = await sheet.screenshot({ type: "png" });
7162
+ const text = await page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
7163
+ out.push({
7164
+ png,
7165
+ text
7166
+ });
7167
+ }
7168
+ return out;
7169
+ } finally {
7170
+ await page.emulateMedia({ media: null });
7171
+ await page.evaluate("globalThis.__openDoc.releasePrint()");
7172
+ }
7173
+ },
7174
+ html: () => page.evaluate("globalThis.__openDoc.htmlBundle()"),
7175
+ docx: () => page.evaluate("globalThis.__openDoc.docxBundle()"),
7176
+ async setRecord(index, pattern) {
7177
+ const { name } = await page.evaluate(`globalThis.__openDoc.setRecord(${JSON.stringify(index)}, ${pattern === void 0 ? "undefined" : JSON.stringify(pattern)})`);
7178
+ await page.waitForFunction(`(() => { const s = globalThis.__openDoc.status(); return s.ready && s.record === ${JSON.stringify(index)}; })()`, void 0, { timeout });
7179
+ renderer.status = await page.evaluate("globalThis.__openDoc.status()");
7180
+ return name;
7181
+ },
7182
+ close: () => page.close()
7183
+ };
7184
+ return renderer;
7185
+ },
7186
+ async compareImages(before, after) {
7187
+ const page = await browser.newPage();
7188
+ try {
7189
+ const toUrl = (png) => `data:image/png;base64,${Buffer$1.from(png).toString("base64")}`;
7190
+ return await page.evaluate(compareInBrowser, {
7191
+ a: toUrl(before),
7192
+ b: toUrl(after),
7193
+ cell: DIFF_CELL
7194
+ });
7195
+ } finally {
7196
+ await page.close();
7197
+ }
7198
+ },
7199
+ async close() {
7200
+ await browser.close();
7201
+ await server?.close();
7202
+ }
7203
+ };
7204
+ }
7205
+ /** Changed pixels are gathered into cells this many px square before boxing. */
7206
+ const DIFF_CELL = 12;
7207
+ /**
7208
+ * Runs in the page. The browser decodes both PNGs, so nothing on the Node side
7209
+ * has to: draw each onto white, mark every cell where a pixel moved by more
7210
+ * than antialiasing does, and box the clusters of marked cells. Clusters
7211
+ * within two cells of each other join, so one edited paragraph is one box.
7212
+ */
7213
+ async function compareInBrowser({ a, b, cell }) {
7214
+ const load = async (src) => {
7215
+ const image = new Image();
7216
+ image.src = src;
7217
+ await image.decode();
7218
+ return image;
7219
+ };
7220
+ const [x, y] = await Promise.all([load(a), load(b)]);
7221
+ const width = Math.max(x.naturalWidth, y.naturalWidth);
7222
+ const height = Math.max(x.naturalHeight, y.naturalHeight);
7223
+ const pixels = (image) => {
7224
+ const canvas = document.createElement("canvas");
7225
+ canvas.width = width;
7226
+ canvas.height = height;
7227
+ const g = canvas.getContext("2d");
7228
+ if (!g) throw new Error("no 2D canvas");
7229
+ g.fillStyle = "#ffffff";
7230
+ g.fillRect(0, 0, width, height);
7231
+ g.drawImage(image, 0, 0);
7232
+ return g.getImageData(0, 0, width, height).data;
7233
+ };
7234
+ const p = pixels(x);
7235
+ const q = pixels(y);
7236
+ const cols = Math.ceil(width / cell);
7237
+ const rows = Math.ceil(height / cell);
7238
+ const hot = new Uint8Array(cols * rows);
7239
+ let changed = 0;
7240
+ for (let i = 0; i < p.length; i += 4) {
7241
+ if (Math.abs((p[i] ?? 0) - (q[i] ?? 0)) + Math.abs((p[i + 1] ?? 0) - (q[i + 1] ?? 0)) + Math.abs((p[i + 2] ?? 0) - (q[i + 2] ?? 0)) <= 48) continue;
7242
+ changed++;
7243
+ const px = i / 4 % width;
7244
+ const py = Math.floor(i / 4 / width);
7245
+ hot[Math.floor(py / cell) * cols + Math.floor(px / cell)] = 1;
7246
+ }
7247
+ const seen = new Uint8Array(cols * rows);
7248
+ const boxes = [];
7249
+ for (let start = 0; start < hot.length; start++) {
7250
+ if (!hot[start] || seen[start]) continue;
7251
+ let minC = cols;
7252
+ let maxC = 0;
7253
+ let minR = rows;
7254
+ let maxR = 0;
7255
+ const stack = [start];
7256
+ seen[start] = 1;
7257
+ while (stack.length > 0) {
7258
+ const at = stack.pop();
7259
+ const c = at % cols;
7260
+ const r = Math.floor(at / cols);
7261
+ minC = Math.min(minC, c);
7262
+ maxC = Math.max(maxC, c);
7263
+ minR = Math.min(minR, r);
7264
+ maxR = Math.max(maxR, r);
7265
+ for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) {
7266
+ const nr = r + dr;
7267
+ const nc = c + dc;
7268
+ if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
7269
+ const next = nr * cols + nc;
7270
+ if (hot[next] && !seen[next]) {
7271
+ seen[next] = 1;
7272
+ stack.push(next);
7273
+ }
7274
+ }
7275
+ }
7276
+ boxes.push({
7277
+ x: minC * cell,
7278
+ y: minR * cell,
7279
+ width: Math.min(width, (maxC + 1) * cell) - minC * cell,
7280
+ height: Math.min(height, (maxR + 1) * cell) - minR * cell
7281
+ });
7282
+ }
7283
+ return {
7284
+ width,
7285
+ height,
7286
+ changed: changed / (width * height),
7287
+ boxes
7288
+ };
7289
+ }
7290
+ //#endregion
7291
+ export { assertExpectedSource as A, readDocument as B, exportDocument as C, listRevisions as D, slugify as E, deleteDocument as F, resolveEntry as H, docDir as I, duplicateDocument as L, withFileLock as M, OpsError as N, readChanges as O, createDocument as P, listDocIds$1 as R, closeRenderSession as S, importMarkdown as T, writeDocument as U, renameDocument as V, makeContext as W, listFolders as _, readText as a, writeAsset as b, writeTexts as c, suggestDocId as d, createFolder as f, listAssets as g, findAssetUsages as h, addComment as i, hashSource as j, revertChange as k, createFromTemplate as l, fileDocument as m, createRenderSession as n, writeEdits as o, deleteAsset as p, createViteConfig as r, writeText as s, RenderUnavailableError as t, listTemplates as u, listThemes as v, renderDocPage as w, checkLayout as x, readTheme as y, listDocuments as z };