@open-document/core 0.13.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-CvsOak5B.js → build-CyBlmrjS.js} +1 -1
- package/dist/{check-CbUBwYmf.js → check-DUKDEem-.js} +3 -3
- package/dist/cli/bin.js +10 -21
- package/dist/{config-BWtOZ1jc.d.ts → config-cAV1OCuY.d.ts} +9 -1
- package/dist/{config-CltJJVsw.js → config-cNpYUpF6.js} +2746 -369
- package/dist/{context-CWgfsHoE.js → context-BPApOW9n.js} +1 -1
- package/dist/{dev-B8H2qT6G.js → dev-DrnOvsX3.js} +1 -1
- package/dist/{diff-BvIjjgnc.js → diff-BPMD2Knh.js} +2 -2
- package/dist/{export-DX30_s2q.js → export-DeVtL8aX.js} +3 -3
- package/dist/{import-DgsdJT5e.js → import-WAgWsuOv.js} +3 -2
- package/dist/index.d.ts +2 -2
- package/dist/ops/index.d.ts +3 -1
- package/dist/ops/index.js +2 -2
- package/dist/{ops-CSR5RlrE.js → ops-raK6424A.js} +2 -854
- package/dist/{preview-DYMUNjXL.js → preview-B8Vw9QCh.js} +1 -1
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/{templates-B5Tz0AKb.js → templates-D9jAFJ8R.js} +3 -3
- package/dist/vite/index.d.ts +1 -1
- package/dist/vite/index.js +1 -1
- package/package.json +1 -1
- package/skills/create-doc/SKILL.md +1 -1
- package/skills/doc-authoring/SKILL.md +6 -0
- package/src/app/app.tsx +2 -0
- package/src/app/components/agent/agent-dock.tsx +75 -0
- package/src/app/components/agent/agent-markdown.tsx +45 -0
- package/src/app/components/agent/agent-panel.tsx +690 -0
- package/src/app/components/agent/agent-presence.tsx +74 -0
- package/src/app/components/agent/composer.tsx +120 -0
- package/src/app/components/agent/connect-view.tsx +183 -0
- package/src/app/components/agent/history-view.tsx +134 -0
- package/src/app/components/agent/provider-logo.tsx +23 -0
- package/src/app/components/agent/transcript.tsx +609 -0
- package/src/app/components/comments/comments-panel.tsx +26 -2
- package/src/app/components/inspector/inspector.tsx +17 -0
- package/src/app/components/note-markdown.tsx +85 -0
- package/src/app/components/page-error-boundary.tsx +84 -0
- package/src/app/components/page-frame.tsx +2 -1
- package/src/app/components/panel/resize-handle.tsx +129 -0
- package/src/app/components/ui/button.tsx +97 -0
- package/src/app/components/ui/popover.tsx +144 -0
- package/src/app/components/ui/tooltip.tsx +123 -0
- package/src/app/lib/agent/use-agent.ts +543 -0
- package/src/app/lib/diagnostics.ts +13 -0
- package/src/app/lib/docx/from-dom.ts +91 -6
- package/src/app/lib/docx/ooxml.test.ts +58 -0
- package/src/app/lib/docx/ooxml.ts +58 -9
- package/src/app/lib/export-dom.ts +2 -1
- package/src/app/lib/export-pdf.ts +2 -1
- package/src/app/lib/i18n-ja/agent-panel.ts +107 -0
- package/src/app/lib/i18n-ja/agent.ts +9 -0
- package/src/app/lib/i18n-ja/index.ts +9 -1
- package/src/app/lib/i18n-ko/agent-panel.ts +106 -0
- package/src/app/lib/i18n-ko/agent.ts +9 -0
- package/src/app/lib/i18n-ko/index.ts +9 -1
- package/src/app/lib/i18n-zh-cn/agent-panel.ts +105 -0
- package/src/app/lib/i18n-zh-cn/agent.ts +9 -0
- package/src/app/lib/i18n-zh-cn/index.ts +9 -1
- package/src/app/lib/i18n-zh-tw/agent-panel.ts +105 -0
- package/src/app/lib/i18n-zh-tw/agent.ts +9 -0
- package/src/app/lib/i18n-zh-tw/index.ts +9 -1
- package/src/app/lib/note-markdown.ts +116 -0
- package/src/app/lib/toast.ts +50 -0
- package/src/app/lib/use-auto-grow.ts +15 -0
- package/src/app/lib/use-doc-titles.ts +28 -0
- package/src/app/lib/use-locale.ts +144 -0
- package/src/app/lib/utils.ts +4 -0
- package/src/app/routes/doc-preview.tsx +103 -0
- package/src/app/routes/doc.tsx +118 -11
- package/src/app/routes/home.tsx +43 -8
- package/src/app/styles.css +193 -0
|
@@ -1,19 +1,22 @@
|
|
|
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
12
|
import { normalizePath } from "vite";
|
|
11
|
-
import { execFile } from "node:child_process";
|
|
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";
|
|
15
17
|
import tailwindcss from "@tailwindcss/vite";
|
|
16
18
|
import react from "@vitejs/plugin-react";
|
|
19
|
+
import os from "node:os";
|
|
17
20
|
//#region src/vite/routes/context.ts
|
|
18
21
|
function makeContext(opts) {
|
|
19
22
|
const userCwd = opts.userCwd;
|
|
@@ -30,10 +33,25 @@ function makeContext(opts) {
|
|
|
30
33
|
...opts.serverOrigin !== void 0 ? { serverOrigin: opts.serverOrigin } : {}
|
|
31
34
|
};
|
|
32
35
|
}
|
|
33
|
-
|
|
36
|
+
var BodyTooLargeError = class extends Error {
|
|
37
|
+
constructor() {
|
|
38
|
+
super("request body too large");
|
|
39
|
+
this.name = "BodyTooLargeError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
async function readBody(req, limit = Number.POSITIVE_INFINITY) {
|
|
34
43
|
return await new Promise((resolve, reject) => {
|
|
35
44
|
const chunks = [];
|
|
36
|
-
|
|
45
|
+
let size = 0;
|
|
46
|
+
req.on("data", (c) => {
|
|
47
|
+
size += c.length;
|
|
48
|
+
if (size > limit) {
|
|
49
|
+
req.destroy();
|
|
50
|
+
reject(new BodyTooLargeError());
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
chunks.push(c);
|
|
54
|
+
});
|
|
37
55
|
req.on("end", () => {
|
|
38
56
|
const raw = Buffer.concat(chunks).toString("utf8");
|
|
39
57
|
if (!raw) return resolve({});
|
|
@@ -444,7 +462,7 @@ function findMetaObject(ast) {
|
|
|
444
462
|
}
|
|
445
463
|
return null;
|
|
446
464
|
}
|
|
447
|
-
function jsString$
|
|
465
|
+
function jsString$2(value) {
|
|
448
466
|
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
|
|
449
467
|
}
|
|
450
468
|
function validateDocTitle(v) {
|
|
@@ -473,10 +491,10 @@ function setMetaString(source, field, value) {
|
|
|
473
491
|
const p = prop;
|
|
474
492
|
if (p.computed) continue;
|
|
475
493
|
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== field) continue;
|
|
476
|
-
return source.slice(0, p.value.start) + jsString$
|
|
494
|
+
return source.slice(0, p.value.start) + jsString$2(value) + source.slice(p.value.end);
|
|
477
495
|
}
|
|
478
496
|
const open = object.start + 1;
|
|
479
|
-
const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$
|
|
497
|
+
const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$2(value)},\n` : `\n ${field}: ${jsString$2(value)},`;
|
|
480
498
|
return source.slice(0, open) + inserted + source.slice(open);
|
|
481
499
|
}
|
|
482
500
|
function readMetaTitle(source) {
|
|
@@ -751,6 +769,56 @@ async function deleteDocument(ctx, docId) {
|
|
|
751
769
|
}
|
|
752
770
|
});
|
|
753
771
|
}
|
|
772
|
+
/**
|
|
773
|
+
* A blank document under a placeholder id (`untitled`, `untitled-2`, …) from the
|
|
774
|
+
* `blank` template, for the agent panel to draft into. It gets a real id from
|
|
775
|
+
* `renameDocDir` once something has been written.
|
|
776
|
+
*/
|
|
777
|
+
async function createBlankDocument(ctx) {
|
|
778
|
+
const { createFromTemplate } = await Promise.resolve().then(() => templates_exports);
|
|
779
|
+
const taken = new Set(await listDocIds$1(ctx));
|
|
780
|
+
for (let n = 1; n < 1e3; n++) {
|
|
781
|
+
const id = n === 1 ? "untitled" : `untitled-${n}`;
|
|
782
|
+
if (taken.has(id)) continue;
|
|
783
|
+
return { id: (await createFromTemplate(ctx, {
|
|
784
|
+
template: "blank",
|
|
785
|
+
docId: id
|
|
786
|
+
})).id };
|
|
787
|
+
}
|
|
788
|
+
throw new OpsError(409, "no free document id");
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Moves a document to a new folder name — `desired`, else `desired-2`, … — and
|
|
792
|
+
* carries its folder assignment with it. The id is the folder, so this is the
|
|
793
|
+
* one operation that changes a document's id.
|
|
794
|
+
*/
|
|
795
|
+
async function renameDocDir(ctx, docId, desired) {
|
|
796
|
+
const from = docDir(ctx, docId);
|
|
797
|
+
if (!DOC_ID_RE.test(desired)) throw new OpsError(400, `invalid document id: ${desired}`);
|
|
798
|
+
if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
|
|
799
|
+
const taken = new Set(await listDocIds$1(ctx));
|
|
800
|
+
for (let n = 1; n < 1e3; n++) {
|
|
801
|
+
const id = n === 1 ? desired : `${desired}-${n}`;
|
|
802
|
+
if (id === docId) return { id };
|
|
803
|
+
if (taken.has(id)) continue;
|
|
804
|
+
try {
|
|
805
|
+
await fs.rename(from, docDir(ctx, id));
|
|
806
|
+
} catch (err) {
|
|
807
|
+
const code = err.code;
|
|
808
|
+
if (code === "EEXIST" || code === "ENOTEMPTY") continue;
|
|
809
|
+
throw err;
|
|
810
|
+
}
|
|
811
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
812
|
+
const folderId = manifest.assignments[docId];
|
|
813
|
+
if (folderId) {
|
|
814
|
+
delete manifest.assignments[docId];
|
|
815
|
+
manifest.assignments[id] = folderId;
|
|
816
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
817
|
+
}
|
|
818
|
+
return { id };
|
|
819
|
+
}
|
|
820
|
+
throw new OpsError(409, "no free document id");
|
|
821
|
+
}
|
|
754
822
|
//#endregion
|
|
755
823
|
//#region src/ops/concurrency.ts
|
|
756
824
|
/**
|
|
@@ -923,382 +991,2212 @@ async function revertChange(ctx, docId, opts) {
|
|
|
923
991
|
});
|
|
924
992
|
}
|
|
925
993
|
//#endregion
|
|
926
|
-
//#region src/
|
|
927
|
-
const
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
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";
|
|
952
|
-
}
|
|
953
|
-
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
954
|
-
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
994
|
+
//#region src/agent/install.ts
|
|
995
|
+
const LOCKFILES = [
|
|
996
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
997
|
+
["yarn.lock", "yarn"],
|
|
998
|
+
["bun.lockb", "bun"],
|
|
999
|
+
["bun.lock", "bun"],
|
|
1000
|
+
["package-lock.json", "npm"]
|
|
1001
|
+
];
|
|
1002
|
+
async function fileExists(file) {
|
|
1003
|
+
try {
|
|
1004
|
+
await fs.access(file);
|
|
1005
|
+
return true;
|
|
1006
|
+
} catch {
|
|
1007
|
+
return false;
|
|
1008
|
+
}
|
|
955
1009
|
}
|
|
956
|
-
function
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
if (
|
|
960
|
-
if (
|
|
961
|
-
if (
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1010
|
+
async function detectPackageManager(cwd) {
|
|
1011
|
+
const ua = process.env.npm_config_user_agent ?? "";
|
|
1012
|
+
if (ua.startsWith("pnpm")) return "pnpm";
|
|
1013
|
+
if (ua.startsWith("yarn")) return "yarn";
|
|
1014
|
+
if (ua.startsWith("bun")) return "bun";
|
|
1015
|
+
if (ua.startsWith("npm")) return "npm";
|
|
1016
|
+
let dir = cwd;
|
|
1017
|
+
while (true) {
|
|
1018
|
+
for (const [lockfile, pm] of LOCKFILES) if (await fileExists(path.join(dir, lockfile))) return pm;
|
|
1019
|
+
const parent = path.dirname(dir);
|
|
1020
|
+
if (parent === dir) return "npm";
|
|
1021
|
+
dir = parent;
|
|
1022
|
+
}
|
|
966
1023
|
}
|
|
967
|
-
function
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
1024
|
+
async function runCommand(spec, cwd, timeoutMs) {
|
|
1025
|
+
const label = [spec.cmd, ...spec.args].join(" ");
|
|
1026
|
+
await new Promise((resolve, reject) => {
|
|
1027
|
+
const child = spawn(spec.cmd, spec.args, {
|
|
1028
|
+
cwd,
|
|
1029
|
+
env: process.env,
|
|
1030
|
+
shell: process.platform === "win32",
|
|
1031
|
+
stdio: [
|
|
1032
|
+
"ignore",
|
|
1033
|
+
"ignore",
|
|
1034
|
+
"pipe"
|
|
1035
|
+
],
|
|
1036
|
+
windowsHide: true
|
|
1037
|
+
});
|
|
1038
|
+
let stderr = "";
|
|
1039
|
+
const timer = setTimeout(() => {
|
|
1040
|
+
child.kill();
|
|
1041
|
+
reject(/* @__PURE__ */ new Error(`${label} timed out`));
|
|
1042
|
+
}, timeoutMs);
|
|
1043
|
+
child.stderr.on("data", (chunk) => {
|
|
1044
|
+
stderr = (stderr + chunk.toString("utf8")).slice(-2e3);
|
|
1045
|
+
});
|
|
1046
|
+
child.on("error", (err) => {
|
|
1047
|
+
clearTimeout(timer);
|
|
1048
|
+
reject(err);
|
|
1049
|
+
});
|
|
1050
|
+
child.on("close", (code) => {
|
|
1051
|
+
clearTimeout(timer);
|
|
1052
|
+
if (code === 0) return resolve();
|
|
1053
|
+
reject(new Error(stderr.trim() || `${label} exited with code ${code ?? "unknown"}`));
|
|
1054
|
+
});
|
|
1055
|
+
});
|
|
974
1056
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
1057
|
+
//#endregion
|
|
1058
|
+
//#region src/editing/placeholder-id.ts
|
|
1059
|
+
/** The folder a document gets before it has a name: renamed once the agent has written it. */
|
|
1060
|
+
const UNTITLED_DOC_ID_RE = /^untitled(-\d+)?$/;
|
|
1061
|
+
//#endregion
|
|
1062
|
+
//#region src/agent/provider.ts
|
|
1063
|
+
var ProviderUnavailableError = class extends Error {
|
|
1064
|
+
constructor(provider) {
|
|
1065
|
+
super(`${provider.name} is not connected: install ${provider.sdkPackage} in this workspace to use it from the agent panel.`);
|
|
1066
|
+
this.name = "ProviderUnavailableError";
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
const DETAIL_MAX = 400;
|
|
1070
|
+
function clipDetail(value) {
|
|
1071
|
+
if (value === void 0 || value === null) return null;
|
|
1072
|
+
const text = typeof value === "string" ? value : safeJson(value);
|
|
1073
|
+
if (!text) return null;
|
|
1074
|
+
const oneLine = text.replace(/\s+/g, " ").trim();
|
|
1075
|
+
return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, 399)}…` : oneLine;
|
|
1076
|
+
}
|
|
1077
|
+
function safeJson(value) {
|
|
1078
|
+
try {
|
|
1079
|
+
return JSON.stringify(value);
|
|
1080
|
+
} catch {
|
|
1081
|
+
return String(value);
|
|
1082
|
+
}
|
|
978
1083
|
}
|
|
979
|
-
function
|
|
980
|
-
|
|
981
|
-
const
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
1084
|
+
function parseQuestions(input) {
|
|
1085
|
+
const raw = Array.isArray(input.questions) ? input.questions : [];
|
|
1086
|
+
const questions = [];
|
|
1087
|
+
for (const q of raw) {
|
|
1088
|
+
if (!q || typeof q !== "object") continue;
|
|
1089
|
+
const r = q;
|
|
1090
|
+
const options = Array.isArray(r.options) ? r.options.map((o) => {
|
|
1091
|
+
if (!o || typeof o !== "object") return null;
|
|
1092
|
+
const opt = o;
|
|
1093
|
+
if (typeof opt.label !== "string") return null;
|
|
1094
|
+
return {
|
|
1095
|
+
label: opt.label,
|
|
1096
|
+
description: typeof opt.description === "string" ? opt.description : void 0
|
|
1097
|
+
};
|
|
1098
|
+
}).filter((o) => o !== null) : [];
|
|
1099
|
+
if (typeof r.question !== "string") continue;
|
|
1100
|
+
questions.push({
|
|
1101
|
+
header: typeof r.header === "string" ? r.header : "",
|
|
1102
|
+
question: r.question,
|
|
1103
|
+
options,
|
|
1104
|
+
multiSelect: r.multiSelect === true
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
return questions;
|
|
986
1108
|
}
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1109
|
+
//#endregion
|
|
1110
|
+
//#region src/agent/prompt.ts
|
|
1111
|
+
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.";
|
|
1112
|
+
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.";
|
|
1113
|
+
function systemPromptAppend(askInstruction, opts) {
|
|
1114
|
+
const preview = opts.origin ? `${opts.origin}/d/<id>/preview?p=<page>` : "/d/<id>/preview?p=<page> on the dev server";
|
|
1115
|
+
return [
|
|
1116
|
+
"You are running inside the open-doc dev server, driven from its in-app agent panel in the browser rather than a terminal.",
|
|
1117
|
+
`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.`,
|
|
1118
|
+
"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.",
|
|
1119
|
+
SECTION_BY_SECTION,
|
|
1120
|
+
opts.canOpenBrowser === false ? "Your sandbox cannot start a browser, so `open-doc check` and the page preview fail here: do not run them. Keep the file compiling after every write; the user sees each save on the page and can run the check themselves." : `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"].`,
|
|
1121
|
+
"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.",
|
|
1122
|
+
askInstruction
|
|
1123
|
+
].join(" ");
|
|
1124
|
+
}
|
|
1125
|
+
function buildTurnPrompt(text, context, docsDir = "docs") {
|
|
1126
|
+
const lines = contextLines(context, docsDir);
|
|
1127
|
+
if (lines.length === 0) return text;
|
|
1128
|
+
return `${text}\n\n<open-doc-context>\n${lines.join("\n")}\n</open-doc-context>`;
|
|
1129
|
+
}
|
|
1130
|
+
const escapeTag = (s) => s.replace(/</g, "<");
|
|
1131
|
+
function contextLines(context, docsDir) {
|
|
1132
|
+
if (!context?.docId) return [];
|
|
1133
|
+
const file = `${docsDir}/${context.docId}/index.tsx`;
|
|
1134
|
+
const lines = [];
|
|
1135
|
+
if (context.newDoc) {
|
|
1136
|
+
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);
|
|
1137
|
+
return lines;
|
|
1138
|
+
}
|
|
1139
|
+
lines.push(`The user is viewing document "${context.docId}": ${file}.`);
|
|
1140
|
+
if (UNTITLED_DOC_ID_RE.test(context.docId)) lines.push(DOC_SLUG);
|
|
1141
|
+
if (context.docTitle) lines.push(`<doc-title>${escapeTag(context.docTitle)}</doc-title>`);
|
|
1142
|
+
if (context.pageNumber && context.totalPages) lines.push(`They are on page ${context.pageNumber} of ${context.totalPages} as the document prints.`);
|
|
1143
|
+
if (context.selection) {
|
|
1144
|
+
const { line, column, tagName, text } = context.selection;
|
|
1145
|
+
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.`);
|
|
1146
|
+
if (text) lines.push(`<selected-text>${escapeTag(text)}</selected-text>`);
|
|
1147
|
+
}
|
|
1148
|
+
if (context.pendingComments) lines.push(`There are ${context.pendingComments} pending @doc-comment markers in this document's source.`);
|
|
1149
|
+
return lines;
|
|
1150
|
+
}
|
|
1151
|
+
const DOC_SLUG_RE = /\s*<doc-slug>\s*([^<]*?)\s*<\/doc-slug>\s*/gi;
|
|
1152
|
+
function extractDocSlug(text) {
|
|
1153
|
+
let slug = null;
|
|
1154
|
+
for (const match of text.matchAll(DOC_SLUG_RE)) slug = match[1] || slug;
|
|
1155
|
+
return slug;
|
|
1156
|
+
}
|
|
1157
|
+
function stripDocSlug(text) {
|
|
1158
|
+
return text.replace(DOC_SLUG_RE, "\n").replace(/\s*<doc-slug>[^<]*$/i, "").trimEnd();
|
|
1159
|
+
}
|
|
1160
|
+
const QUESTIONS_RE = /<open-doc-questions>([\s\S]*?)<\/open-doc-questions>/i;
|
|
1161
|
+
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.";
|
|
1162
|
+
function extractQuestionBlock(text) {
|
|
1163
|
+
const match = QUESTIONS_RE.exec(text);
|
|
1164
|
+
if (!match) return null;
|
|
1165
|
+
const body = match[1].trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
1166
|
+
let raw;
|
|
1167
|
+
try {
|
|
1168
|
+
raw = JSON.parse(body);
|
|
1169
|
+
} catch {
|
|
1170
|
+
return null;
|
|
1171
|
+
}
|
|
1172
|
+
const questions = parseQuestions({ questions: Array.isArray(raw) ? raw : raw?.questions });
|
|
1173
|
+
if (questions.length === 0) return null;
|
|
1174
|
+
return {
|
|
1175
|
+
text: text.replace(QUESTIONS_RE, "").trim(),
|
|
1176
|
+
questions
|
|
1177
|
+
};
|
|
990
1178
|
}
|
|
991
|
-
function
|
|
992
|
-
|
|
1179
|
+
function answersPrompt(questions, answers) {
|
|
1180
|
+
if (!answers) return "I skipped your questions. Continue the task with your best judgement and sensible defaults.";
|
|
1181
|
+
return `My answers:\n${questions.map((q) => `- ${q.question} ${answers[q.question] || "(no answer)"}`).join("\n")}\n\nContinue the task with these answers.`;
|
|
993
1182
|
}
|
|
994
|
-
|
|
995
|
-
|
|
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;
|
|
1183
|
+
function editedPrompt(original, text) {
|
|
1184
|
+
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
1185
|
}
|
|
1003
|
-
function
|
|
1004
|
-
return
|
|
1186
|
+
function rewoundPrompt(text) {
|
|
1187
|
+
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
1188
|
}
|
|
1006
1189
|
//#endregion
|
|
1007
|
-
//#region src/
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1190
|
+
//#region src/agent/detect.ts
|
|
1191
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
1192
|
+
const VERSION_TIMEOUT_MS = 5e3;
|
|
1193
|
+
function findOnPath(command, env = process.env) {
|
|
1194
|
+
const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
|
|
1195
|
+
const exts = IS_WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
|
|
1196
|
+
for (const dir of dirs) for (const ext of exts) {
|
|
1197
|
+
const candidate = path.join(dir, command + ext.toLowerCase());
|
|
1198
|
+
try {
|
|
1199
|
+
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
|
|
1200
|
+
} catch {}
|
|
1201
|
+
}
|
|
1202
|
+
return null;
|
|
1014
1203
|
}
|
|
1015
|
-
function
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
return
|
|
1204
|
+
function findSpawnableCli(command, env = process.env) {
|
|
1205
|
+
const found = findOnPath(command, env);
|
|
1206
|
+
if (!found || !IS_WINDOWS) return found;
|
|
1207
|
+
return found.toLowerCase().endsWith(".exe") ? found : null;
|
|
1208
|
+
}
|
|
1209
|
+
const versionCache = /* @__PURE__ */ new Map();
|
|
1210
|
+
function commandVersion(file) {
|
|
1211
|
+
let cached = versionCache.get(file);
|
|
1212
|
+
if (!cached) {
|
|
1213
|
+
cached = readVersion(file);
|
|
1214
|
+
versionCache.set(file, cached);
|
|
1215
|
+
}
|
|
1216
|
+
return cached;
|
|
1019
1217
|
}
|
|
1020
|
-
function
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1218
|
+
function readVersion(file) {
|
|
1219
|
+
return new Promise((resolve) => {
|
|
1220
|
+
let out = "";
|
|
1221
|
+
let child;
|
|
1222
|
+
try {
|
|
1223
|
+
child = spawn(file, ["--version"], {
|
|
1224
|
+
stdio: [
|
|
1225
|
+
"ignore",
|
|
1226
|
+
"pipe",
|
|
1227
|
+
"pipe"
|
|
1228
|
+
],
|
|
1229
|
+
shell: IS_WINDOWS,
|
|
1230
|
+
windowsHide: true
|
|
1231
|
+
});
|
|
1232
|
+
} catch {
|
|
1233
|
+
resolve(null);
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
const timer = setTimeout(() => {
|
|
1237
|
+
child.kill();
|
|
1238
|
+
resolve(null);
|
|
1239
|
+
}, VERSION_TIMEOUT_MS);
|
|
1240
|
+
child.stdout?.on("data", (c) => {
|
|
1241
|
+
out += c.toString("utf8");
|
|
1242
|
+
});
|
|
1243
|
+
child.stderr?.on("data", (c) => {
|
|
1244
|
+
out += c.toString("utf8");
|
|
1245
|
+
});
|
|
1246
|
+
child.on("error", () => {
|
|
1247
|
+
clearTimeout(timer);
|
|
1248
|
+
resolve(null);
|
|
1249
|
+
});
|
|
1250
|
+
child.on("close", () => {
|
|
1251
|
+
clearTimeout(timer);
|
|
1252
|
+
resolve(parseVersion(out));
|
|
1253
|
+
});
|
|
1254
|
+
});
|
|
1024
1255
|
}
|
|
1025
|
-
function
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1256
|
+
function parseVersion(output) {
|
|
1257
|
+
const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
|
|
1258
|
+
return m ? m[1] : null;
|
|
1259
|
+
}
|
|
1260
|
+
function entryFromPackageJson(pkg) {
|
|
1261
|
+
const root = pickExport(pkg.exports);
|
|
1262
|
+
if (root) return root;
|
|
1263
|
+
return pkg.module ?? pkg.main ?? null;
|
|
1264
|
+
}
|
|
1265
|
+
function pickExport(exportsField) {
|
|
1266
|
+
if (!exportsField) return null;
|
|
1267
|
+
if (typeof exportsField === "string") return exportsField;
|
|
1268
|
+
if (typeof exportsField !== "object") return null;
|
|
1269
|
+
const record = exportsField;
|
|
1270
|
+
return pickCondition(Object.keys(record).some((k) => k.startsWith(".")) ? record["."] : exportsField);
|
|
1271
|
+
}
|
|
1272
|
+
function pickCondition(target) {
|
|
1273
|
+
if (!target) return null;
|
|
1274
|
+
if (typeof target === "string") return target;
|
|
1275
|
+
if (Array.isArray(target)) {
|
|
1276
|
+
for (const t of target) {
|
|
1277
|
+
const hit = pickCondition(t);
|
|
1278
|
+
if (hit) return hit;
|
|
1279
|
+
}
|
|
1030
1280
|
return null;
|
|
1031
1281
|
}
|
|
1282
|
+
if (typeof target !== "object") return null;
|
|
1283
|
+
const record = target;
|
|
1284
|
+
for (const key of [
|
|
1285
|
+
"import",
|
|
1286
|
+
"node",
|
|
1287
|
+
"default",
|
|
1288
|
+
"require"
|
|
1289
|
+
]) if (key in record) {
|
|
1290
|
+
const hit = pickCondition(record[key]);
|
|
1291
|
+
if (hit) return hit;
|
|
1292
|
+
}
|
|
1293
|
+
return null;
|
|
1032
1294
|
}
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1295
|
+
function resolveWorkspacePackage(userCwd, name) {
|
|
1296
|
+
let dir = path.resolve(userCwd);
|
|
1297
|
+
while (true) {
|
|
1298
|
+
const pkgJsonPath = path.join(dir, "node_modules", name, "package.json");
|
|
1299
|
+
if (existsSync(pkgJsonPath)) {
|
|
1300
|
+
let pkg;
|
|
1301
|
+
try {
|
|
1302
|
+
pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
|
|
1303
|
+
} catch {
|
|
1304
|
+
return null;
|
|
1305
|
+
}
|
|
1306
|
+
const entry = entryFromPackageJson(pkg);
|
|
1307
|
+
if (!entry) return null;
|
|
1308
|
+
const pkgDir = path.dirname(pkgJsonPath);
|
|
1309
|
+
return {
|
|
1310
|
+
dir: pkgDir,
|
|
1311
|
+
version: pkg.version ?? "0.0.0",
|
|
1312
|
+
entry: path.resolve(pkgDir, entry)
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
const parent = path.dirname(dir);
|
|
1316
|
+
if (parent === dir) return null;
|
|
1317
|
+
dir = parent;
|
|
1044
1318
|
}
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
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 };
|
|
1319
|
+
}
|
|
1320
|
+
async function importWorkspacePackage(userCwd, name) {
|
|
1321
|
+
const resolved = resolveWorkspacePackage(userCwd, name);
|
|
1322
|
+
if (!resolved) return null;
|
|
1323
|
+
return await import(pathToFileURL(resolved.entry).href);
|
|
1075
1324
|
}
|
|
1076
1325
|
//#endregion
|
|
1077
|
-
//#region src/
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1326
|
+
//#region src/agent/types.ts
|
|
1327
|
+
const AGENT_PROVIDER_IDS = ["codex"];
|
|
1328
|
+
const AGENT_EFFORTS = [
|
|
1329
|
+
"minimal",
|
|
1330
|
+
"low",
|
|
1331
|
+
"medium",
|
|
1332
|
+
"high",
|
|
1333
|
+
"xhigh",
|
|
1334
|
+
"max"
|
|
1335
|
+
];
|
|
1336
|
+
function isAgentProviderId(value) {
|
|
1337
|
+
return typeof value === "string" && AGENT_PROVIDER_IDS.includes(value);
|
|
1338
|
+
}
|
|
1339
|
+
function isAgentEffort(value) {
|
|
1340
|
+
return typeof value === "string" && AGENT_EFFORTS.includes(value);
|
|
1341
|
+
}
|
|
1342
|
+
function sessionSummary(session) {
|
|
1343
|
+
const { providerSessionId: _p, providerCheckpoint: _c, trimmed: _t, items: _i, ...summary } = session;
|
|
1344
|
+
return summary;
|
|
1345
|
+
}
|
|
1346
|
+
//#endregion
|
|
1347
|
+
//#region src/agent/providers/codex.ts
|
|
1348
|
+
const CODEX_SDK_PACKAGE = "@openai/codex-sdk";
|
|
1349
|
+
const CODEX_DEFAULT_MODEL = {
|
|
1350
|
+
id: "",
|
|
1351
|
+
label: "Default",
|
|
1352
|
+
efforts: [
|
|
1353
|
+
"low",
|
|
1354
|
+
"medium",
|
|
1355
|
+
"high"
|
|
1356
|
+
]
|
|
1357
|
+
};
|
|
1358
|
+
function parseCodexModelsCache(raw) {
|
|
1359
|
+
const list = raw?.models;
|
|
1360
|
+
if (!Array.isArray(list)) return [];
|
|
1361
|
+
const models = [];
|
|
1362
|
+
for (const entry of list) {
|
|
1363
|
+
if (!entry || typeof entry !== "object") continue;
|
|
1364
|
+
const m = entry;
|
|
1365
|
+
if (typeof m.slug !== "string" || !m.slug) continue;
|
|
1366
|
+
if (m.visibility !== void 0 && m.visibility !== "list") continue;
|
|
1367
|
+
const efforts = (Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : []).map((l) => l && typeof l === "object" ? l.effort : l).filter(isAgentEffort);
|
|
1368
|
+
models.push({
|
|
1369
|
+
option: {
|
|
1370
|
+
id: m.slug,
|
|
1371
|
+
label: typeof m.display_name === "string" && m.display_name ? m.display_name : m.slug,
|
|
1372
|
+
efforts
|
|
1373
|
+
},
|
|
1374
|
+
priority: typeof m.priority === "number" ? m.priority : Number.MAX_SAFE_INTEGER
|
|
1375
|
+
});
|
|
1083
1376
|
}
|
|
1377
|
+
return models.sort((a, b) => a.priority - b.priority).map((m) => m.option);
|
|
1084
1378
|
}
|
|
1085
|
-
async function
|
|
1086
|
-
const
|
|
1087
|
-
if (!entry) return null;
|
|
1379
|
+
async function readCodexModels() {
|
|
1380
|
+
const home = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
|
|
1088
1381
|
try {
|
|
1089
|
-
|
|
1382
|
+
const models = parseCodexModelsCache(JSON.parse(await fs.readFile(path.join(home, "models_cache.json"), "utf8")));
|
|
1383
|
+
return models.length > 0 ? models : [CODEX_DEFAULT_MODEL];
|
|
1090
1384
|
} catch {
|
|
1091
|
-
return
|
|
1385
|
+
return [CODEX_DEFAULT_MODEL];
|
|
1092
1386
|
}
|
|
1093
1387
|
}
|
|
1094
|
-
function
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1388
|
+
function createCodexMapper(emit) {
|
|
1389
|
+
const started = /* @__PURE__ */ new Set();
|
|
1390
|
+
let resultSeen = false;
|
|
1391
|
+
const startTool = (item, name, title, detail) => {
|
|
1392
|
+
if (started.has(item.id)) return;
|
|
1393
|
+
started.add(item.id);
|
|
1394
|
+
emit({
|
|
1395
|
+
type: "tool-start",
|
|
1396
|
+
id: item.id,
|
|
1397
|
+
name,
|
|
1398
|
+
title,
|
|
1399
|
+
detail
|
|
1400
|
+
});
|
|
1401
|
+
};
|
|
1402
|
+
const describe = (item) => {
|
|
1403
|
+
switch (item.type) {
|
|
1404
|
+
case "command_execution": return {
|
|
1405
|
+
name: "command",
|
|
1406
|
+
title: "Run command",
|
|
1407
|
+
detail: clipDetail(item.command)
|
|
1408
|
+
};
|
|
1409
|
+
case "file_change": return {
|
|
1410
|
+
name: "file_change",
|
|
1411
|
+
title: "Edit",
|
|
1412
|
+
detail: clipDetail(item.changes.map((c) => c.path).join(", "))
|
|
1413
|
+
};
|
|
1414
|
+
case "mcp_tool_call": return {
|
|
1415
|
+
name: "mcp",
|
|
1416
|
+
title: `${item.server}: ${item.tool}`,
|
|
1417
|
+
detail: null
|
|
1418
|
+
};
|
|
1419
|
+
case "web_search": return {
|
|
1420
|
+
name: "web_search",
|
|
1421
|
+
title: "Web search",
|
|
1422
|
+
detail: clipDetail(item.query)
|
|
1423
|
+
};
|
|
1424
|
+
default: return {
|
|
1425
|
+
name: item.type,
|
|
1426
|
+
title: item.type,
|
|
1427
|
+
detail: null
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
};
|
|
1431
|
+
const handleItem = (phase, item) => {
|
|
1432
|
+
switch (item.type) {
|
|
1433
|
+
case "agent_message": {
|
|
1434
|
+
if (phase !== "completed" || !item.text.trim()) return;
|
|
1435
|
+
const asked = extractQuestionBlock(item.text);
|
|
1436
|
+
const text = asked ? asked.text : item.text;
|
|
1437
|
+
if (text) {
|
|
1438
|
+
emit({
|
|
1439
|
+
type: "text-start",
|
|
1440
|
+
id: item.id
|
|
1441
|
+
});
|
|
1442
|
+
emit({
|
|
1443
|
+
type: "text-end",
|
|
1444
|
+
id: item.id,
|
|
1445
|
+
text
|
|
1446
|
+
});
|
|
1123
1447
|
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1448
|
+
if (asked) emit({
|
|
1449
|
+
type: "questions",
|
|
1450
|
+
questions: asked.questions
|
|
1127
1451
|
});
|
|
1452
|
+
return;
|
|
1128
1453
|
}
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
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
|
|
1454
|
+
case "error":
|
|
1455
|
+
if (phase === "completed") emit({
|
|
1456
|
+
type: "error",
|
|
1457
|
+
text: item.message
|
|
1458
|
+
});
|
|
1459
|
+
return;
|
|
1460
|
+
case "command_execution":
|
|
1461
|
+
case "file_change":
|
|
1462
|
+
case "mcp_tool_call":
|
|
1463
|
+
case "web_search": {
|
|
1464
|
+
const { name, title, detail } = describe(item);
|
|
1465
|
+
startTool(item, name, title, detail);
|
|
1466
|
+
if (phase === "completed") {
|
|
1467
|
+
const status = "status" in item ? item.status : "completed";
|
|
1468
|
+
emit({
|
|
1469
|
+
type: "tool-end",
|
|
1470
|
+
id: item.id,
|
|
1471
|
+
ok: status !== "failed"
|
|
1154
1472
|
});
|
|
1155
1473
|
}
|
|
1156
|
-
|
|
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 });
|
|
1474
|
+
return;
|
|
1171
1475
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1476
|
+
default: return;
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
return {
|
|
1480
|
+
get resultSeen() {
|
|
1481
|
+
return resultSeen;
|
|
1482
|
+
},
|
|
1483
|
+
handle(event) {
|
|
1484
|
+
if (!event || typeof event !== "object") return;
|
|
1485
|
+
switch (event.type) {
|
|
1486
|
+
case "thread.started":
|
|
1487
|
+
emit({
|
|
1488
|
+
type: "session-id",
|
|
1489
|
+
id: event.thread_id
|
|
1490
|
+
});
|
|
1183
1491
|
return;
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
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);
|
|
1492
|
+
case "item.started":
|
|
1493
|
+
handleItem("started", event.item);
|
|
1494
|
+
return;
|
|
1495
|
+
case "item.updated":
|
|
1496
|
+
handleItem("updated", event.item);
|
|
1497
|
+
return;
|
|
1498
|
+
case "item.completed":
|
|
1499
|
+
handleItem("completed", event.item);
|
|
1500
|
+
return;
|
|
1501
|
+
case "turn.failed":
|
|
1502
|
+
resultSeen = true;
|
|
1503
|
+
emit({
|
|
1504
|
+
type: "error",
|
|
1505
|
+
text: event.error.message
|
|
1217
1506
|
});
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
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)
|
|
1507
|
+
emit({
|
|
1508
|
+
type: "result",
|
|
1509
|
+
durationMs: null,
|
|
1510
|
+
costUsd: null
|
|
1230
1511
|
});
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
if (!target) return json(res, 400, { error: "invalid name" });
|
|
1237
|
-
if (target === filename) return json(res, 200, {
|
|
1238
|
-
ok: true,
|
|
1239
|
-
name: filename
|
|
1512
|
+
return;
|
|
1513
|
+
case "error":
|
|
1514
|
+
emit({
|
|
1515
|
+
type: "error",
|
|
1516
|
+
text: event.message
|
|
1240
1517
|
});
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
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
|
|
1518
|
+
return;
|
|
1519
|
+
case "turn.completed":
|
|
1520
|
+
resultSeen = true;
|
|
1521
|
+
emit({
|
|
1522
|
+
type: "result",
|
|
1523
|
+
durationMs: null,
|
|
1524
|
+
costUsd: null
|
|
1256
1525
|
});
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1526
|
+
return;
|
|
1527
|
+
default: return;
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
function createCodexProvider() {
|
|
1533
|
+
return {
|
|
1534
|
+
id: "codex",
|
|
1535
|
+
name: "Codex",
|
|
1536
|
+
sdkPackage: CODEX_SDK_PACKAGE,
|
|
1537
|
+
askInstruction: TEXT_QUESTIONS_INSTRUCTION,
|
|
1538
|
+
canRewind: false,
|
|
1539
|
+
canOpenBrowser: false,
|
|
1540
|
+
cliCommand: "codex",
|
|
1541
|
+
models: readCodexModels,
|
|
1542
|
+
async run(opts) {
|
|
1543
|
+
const sdk = await importWorkspacePackage(opts.cwd, CODEX_SDK_PACKAGE);
|
|
1544
|
+
if (!sdk || typeof sdk.Codex !== "function") throw new ProviderUnavailableError(this);
|
|
1545
|
+
const localCli = findSpawnableCli("codex");
|
|
1546
|
+
const codex = new sdk.Codex(localCli ? { codexPathOverride: localCli } : {});
|
|
1547
|
+
const threadOptions = {
|
|
1548
|
+
workingDirectory: opts.cwd,
|
|
1549
|
+
skipGitRepoCheck: true,
|
|
1550
|
+
sandboxMode: "workspace-write",
|
|
1551
|
+
approvalPolicy: "never",
|
|
1552
|
+
...opts.model ? { model: opts.model } : {},
|
|
1553
|
+
...opts.effort ? { modelReasoningEffort: opts.effort } : {}
|
|
1554
|
+
};
|
|
1555
|
+
const thread = opts.resume ? codex.resumeThread(opts.resume, threadOptions) : codex.startThread(threadOptions);
|
|
1556
|
+
const input = opts.resume ? opts.prompt : `${opts.systemPromptAppend}\n\n${opts.prompt}`;
|
|
1557
|
+
const mapper = createCodexMapper(opts.emit);
|
|
1558
|
+
const { events } = await thread.runStreamed(input, { signal: opts.signal });
|
|
1559
|
+
try {
|
|
1560
|
+
for await (const event of events) mapper.handle(event);
|
|
1561
|
+
} catch (err) {
|
|
1562
|
+
if (opts.signal.aborted || mapper.resultSeen) return;
|
|
1563
|
+
throw err;
|
|
1564
|
+
}
|
|
1565
|
+
if (thread.id) opts.emit({
|
|
1566
|
+
type: "session-id",
|
|
1567
|
+
id: thread.id
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
//#endregion
|
|
1573
|
+
//#region src/agent/providers/index.ts
|
|
1574
|
+
function createProviders() {
|
|
1575
|
+
return { codex: createCodexProvider() };
|
|
1576
|
+
}
|
|
1577
|
+
//#endregion
|
|
1578
|
+
//#region src/agent/store.ts
|
|
1579
|
+
const MAX_SESSIONS = 30;
|
|
1580
|
+
const MAX_ITEMS_PER_SESSION = 400;
|
|
1581
|
+
const SAVE_DEBOUNCE_MS = 150;
|
|
1582
|
+
const TITLE_MAX = 60;
|
|
1583
|
+
function newId(prefix) {
|
|
1584
|
+
return `${prefix}-${randomBytes(6).toString("hex")}`;
|
|
1585
|
+
}
|
|
1586
|
+
function titleFromPrompt(text) {
|
|
1587
|
+
const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0);
|
|
1588
|
+
if (!line) return "Untitled";
|
|
1589
|
+
return line.length > TITLE_MAX ? `${line.slice(0, 59)}…` : line;
|
|
1590
|
+
}
|
|
1591
|
+
function readPersisted(file) {
|
|
1592
|
+
if (!existsSync(file)) return [];
|
|
1593
|
+
try {
|
|
1594
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
1595
|
+
if (parsed?.version !== 1 || !Array.isArray(parsed.sessions)) return [];
|
|
1596
|
+
return parsed.sessions.filter((s) => isAgentProviderId(s.provider)).map((s) => ({
|
|
1597
|
+
...s,
|
|
1598
|
+
status: "idle",
|
|
1599
|
+
items: s.items.map(closePending)
|
|
1600
|
+
}));
|
|
1601
|
+
} catch {
|
|
1602
|
+
return [];
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
function closePending(item) {
|
|
1606
|
+
if (item.kind === "assistant" && item.streaming) return {
|
|
1607
|
+
...item,
|
|
1608
|
+
streaming: false
|
|
1609
|
+
};
|
|
1610
|
+
if (item.kind === "tool" && item.status === "running") return {
|
|
1611
|
+
...item,
|
|
1612
|
+
status: "error"
|
|
1613
|
+
};
|
|
1614
|
+
if (item.kind === "question" && item.status === "pending") return {
|
|
1615
|
+
...item,
|
|
1616
|
+
status: "cancelled"
|
|
1617
|
+
};
|
|
1618
|
+
if (item.kind === "permission" && item.status === "pending") return {
|
|
1619
|
+
...item,
|
|
1620
|
+
status: "denied"
|
|
1621
|
+
};
|
|
1622
|
+
return item;
|
|
1623
|
+
}
|
|
1624
|
+
function createSessionStore(opts) {
|
|
1625
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
1626
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1627
|
+
let saveTimer = null;
|
|
1628
|
+
let seq = 0;
|
|
1629
|
+
const order = /* @__PURE__ */ new Map();
|
|
1630
|
+
if (opts.file) for (const s of readPersisted(opts.file)) {
|
|
1631
|
+
sessions.set(s.id, s);
|
|
1632
|
+
order.set(s.id, seq++);
|
|
1633
|
+
}
|
|
1634
|
+
const emit = (event) => {
|
|
1635
|
+
for (const l of listeners) l(event);
|
|
1636
|
+
};
|
|
1637
|
+
const scheduleSave = () => {
|
|
1638
|
+
if (!opts.file) return;
|
|
1639
|
+
if (saveTimer) clearTimeout(saveTimer);
|
|
1640
|
+
saveTimer = setTimeout(() => {
|
|
1641
|
+
saveTimer = null;
|
|
1642
|
+
save();
|
|
1643
|
+
}, SAVE_DEBOUNCE_MS);
|
|
1644
|
+
};
|
|
1645
|
+
const writeSnapshot = async (file) => {
|
|
1646
|
+
const body = {
|
|
1647
|
+
version: 1,
|
|
1648
|
+
sessions: list().flatMap((s) => sessions.get(s.id) ?? [])
|
|
1649
|
+
};
|
|
1650
|
+
const tmp = `${file}.tmp`;
|
|
1651
|
+
try {
|
|
1652
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
1653
|
+
await fs.writeFile(tmp, JSON.stringify(body), {
|
|
1654
|
+
encoding: "utf8",
|
|
1655
|
+
mode: 384
|
|
1656
|
+
});
|
|
1657
|
+
await fs.rename(tmp, file);
|
|
1658
|
+
} catch (err) {
|
|
1659
|
+
console.error("[open-doc] failed to save agent sessions:", err);
|
|
1660
|
+
await fs.rm(tmp, { force: true }).catch(() => {});
|
|
1661
|
+
}
|
|
1662
|
+
};
|
|
1663
|
+
let saving = Promise.resolve();
|
|
1664
|
+
const save = () => {
|
|
1665
|
+
const file = opts.file;
|
|
1666
|
+
if (!file) return saving;
|
|
1667
|
+
saving = saving.then(() => writeSnapshot(file));
|
|
1668
|
+
return saving;
|
|
1669
|
+
};
|
|
1670
|
+
const touch = (session) => {
|
|
1671
|
+
session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1672
|
+
order.set(session.id, seq++);
|
|
1673
|
+
emit({
|
|
1674
|
+
type: "session",
|
|
1675
|
+
session: sessionSummary(session)
|
|
1676
|
+
});
|
|
1677
|
+
scheduleSave();
|
|
1678
|
+
};
|
|
1679
|
+
const require = (id) => {
|
|
1680
|
+
const session = sessions.get(id);
|
|
1681
|
+
if (!session) throw new Error(`unknown agent session: ${id}`);
|
|
1682
|
+
return session;
|
|
1683
|
+
};
|
|
1684
|
+
function list() {
|
|
1685
|
+
return Array.from(sessions.values()).sort((a, b) => {
|
|
1686
|
+
if (a.updatedAt !== b.updatedAt) return a.updatedAt < b.updatedAt ? 1 : -1;
|
|
1687
|
+
return (order.get(b.id) ?? 0) - (order.get(a.id) ?? 0);
|
|
1688
|
+
}).map(sessionSummary);
|
|
1689
|
+
}
|
|
1690
|
+
function get(id) {
|
|
1691
|
+
return sessions.get(id) ?? null;
|
|
1692
|
+
}
|
|
1693
|
+
function create(provider, docId) {
|
|
1694
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1695
|
+
const session = {
|
|
1696
|
+
id: newId("s"),
|
|
1697
|
+
provider,
|
|
1698
|
+
title: "New session",
|
|
1699
|
+
createdAt: now,
|
|
1700
|
+
updatedAt: now,
|
|
1701
|
+
status: "idle",
|
|
1702
|
+
docId,
|
|
1703
|
+
providerSessionId: null,
|
|
1704
|
+
items: []
|
|
1705
|
+
};
|
|
1706
|
+
sessions.set(session.id, session);
|
|
1707
|
+
order.set(session.id, seq++);
|
|
1708
|
+
const idle = list().filter((s) => s.status === "idle");
|
|
1709
|
+
for (const stale of idle.slice(MAX_SESSIONS)) {
|
|
1710
|
+
sessions.delete(stale.id);
|
|
1711
|
+
order.delete(stale.id);
|
|
1712
|
+
emit({
|
|
1713
|
+
type: "session-removed",
|
|
1714
|
+
sessionId: stale.id
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
touch(session);
|
|
1718
|
+
return session;
|
|
1719
|
+
}
|
|
1720
|
+
function remove(id) {
|
|
1721
|
+
if (!sessions.delete(id)) return false;
|
|
1722
|
+
order.delete(id);
|
|
1723
|
+
emit({
|
|
1724
|
+
type: "session-removed",
|
|
1725
|
+
sessionId: id
|
|
1726
|
+
});
|
|
1727
|
+
scheduleSave();
|
|
1728
|
+
return true;
|
|
1729
|
+
}
|
|
1730
|
+
function patch(id, changes) {
|
|
1731
|
+
const session = require(id);
|
|
1732
|
+
Object.assign(session, changes);
|
|
1733
|
+
touch(session);
|
|
1734
|
+
return session;
|
|
1735
|
+
}
|
|
1736
|
+
function appendItem(sessionId, item) {
|
|
1737
|
+
const session = require(sessionId);
|
|
1738
|
+
session.items.push(item);
|
|
1739
|
+
if (session.items.length > MAX_ITEMS_PER_SESSION) {
|
|
1740
|
+
session.items.splice(0, session.items.length - MAX_ITEMS_PER_SESSION);
|
|
1741
|
+
session.trimmed = true;
|
|
1742
|
+
}
|
|
1743
|
+
emit({
|
|
1744
|
+
type: "item",
|
|
1745
|
+
sessionId,
|
|
1746
|
+
item
|
|
1747
|
+
});
|
|
1748
|
+
touch(session);
|
|
1749
|
+
return item;
|
|
1750
|
+
}
|
|
1751
|
+
function updateItem(sessionId, itemId, kind, changes) {
|
|
1752
|
+
const session = require(sessionId);
|
|
1753
|
+
const index = session.items.findIndex((i) => i.id === itemId && i.kind === kind);
|
|
1754
|
+
if (index === -1) return null;
|
|
1755
|
+
const next = {
|
|
1756
|
+
...session.items[index],
|
|
1757
|
+
...changes
|
|
1758
|
+
};
|
|
1759
|
+
session.items[index] = next;
|
|
1760
|
+
emit({
|
|
1761
|
+
type: "item",
|
|
1762
|
+
sessionId,
|
|
1763
|
+
item: next
|
|
1764
|
+
});
|
|
1765
|
+
touch(session);
|
|
1766
|
+
return next;
|
|
1767
|
+
}
|
|
1768
|
+
function truncateFrom(sessionId, itemId) {
|
|
1769
|
+
const session = require(sessionId);
|
|
1770
|
+
const index = session.items.findIndex((i) => i.id === itemId);
|
|
1771
|
+
if (index === -1) return false;
|
|
1772
|
+
session.items.splice(index);
|
|
1773
|
+
emit({
|
|
1774
|
+
type: "truncate",
|
|
1775
|
+
sessionId,
|
|
1776
|
+
itemId
|
|
1777
|
+
});
|
|
1778
|
+
touch(session);
|
|
1779
|
+
return true;
|
|
1780
|
+
}
|
|
1781
|
+
function appendDelta(sessionId, itemId, text) {
|
|
1782
|
+
if (!text) return;
|
|
1783
|
+
const item = require(sessionId).items.find((i) => i.id === itemId);
|
|
1784
|
+
if (item?.kind !== "assistant") return;
|
|
1785
|
+
item.text += text;
|
|
1786
|
+
emit({
|
|
1787
|
+
type: "delta",
|
|
1788
|
+
sessionId,
|
|
1789
|
+
itemId,
|
|
1790
|
+
text
|
|
1791
|
+
});
|
|
1792
|
+
scheduleSave();
|
|
1793
|
+
}
|
|
1794
|
+
function subscribe(listener) {
|
|
1795
|
+
listeners.add(listener);
|
|
1796
|
+
return () => {
|
|
1797
|
+
listeners.delete(listener);
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
async function flush() {
|
|
1801
|
+
if (saveTimer) {
|
|
1802
|
+
clearTimeout(saveTimer);
|
|
1803
|
+
saveTimer = null;
|
|
1804
|
+
}
|
|
1805
|
+
await save();
|
|
1806
|
+
}
|
|
1807
|
+
return {
|
|
1808
|
+
list,
|
|
1809
|
+
get,
|
|
1810
|
+
create,
|
|
1811
|
+
remove,
|
|
1812
|
+
patch,
|
|
1813
|
+
appendItem,
|
|
1814
|
+
updateItem,
|
|
1815
|
+
truncateFrom,
|
|
1816
|
+
appendDelta,
|
|
1817
|
+
subscribe,
|
|
1818
|
+
flush
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
//#endregion
|
|
1822
|
+
//#region src/agent/runner.ts
|
|
1823
|
+
function cancelPrompt(prompt) {
|
|
1824
|
+
if (prompt.kind === "question") prompt.resolve(null);
|
|
1825
|
+
else prompt.resolve(false);
|
|
1826
|
+
}
|
|
1827
|
+
function createAgentRunner(opts) {
|
|
1828
|
+
const { userCwd, writableRoots, store, providers, onTurnEnd } = opts;
|
|
1829
|
+
const promptOptions = opts.promptOptions ?? (() => ({ docsDir: "docs" }));
|
|
1830
|
+
const running = /* @__PURE__ */ new Map();
|
|
1831
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1832
|
+
const lastOptions = /* @__PURE__ */ new Map();
|
|
1833
|
+
const now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
1834
|
+
function isRunning(sessionId) {
|
|
1835
|
+
return running.has(sessionId);
|
|
1836
|
+
}
|
|
1837
|
+
async function send(sessionId, options) {
|
|
1838
|
+
const session = store.get(sessionId);
|
|
1839
|
+
if (!session) throw new Error(`unknown agent session: ${sessionId}`);
|
|
1840
|
+
if (running.has(sessionId)) throw new Error("session is already running");
|
|
1841
|
+
const text = options.text.trim();
|
|
1842
|
+
if (!text) throw new Error("empty prompt");
|
|
1843
|
+
const provider = providers[session.provider];
|
|
1844
|
+
let context = options.context;
|
|
1845
|
+
let promptText = text;
|
|
1846
|
+
let resumeAt = null;
|
|
1847
|
+
if (options.edit) {
|
|
1848
|
+
const index = session.items.findIndex((i) => i.id === options.edit);
|
|
1849
|
+
const target = session.items[index];
|
|
1850
|
+
if (target?.kind !== "user") throw new Error("unknown message");
|
|
1851
|
+
if (!session.trimmed && !session.items.slice(0, index).some((i) => i.kind === "user")) {
|
|
1852
|
+
store.patch(sessionId, {
|
|
1853
|
+
providerSessionId: null,
|
|
1854
|
+
providerCheckpoint: null
|
|
1855
|
+
});
|
|
1856
|
+
if (target.newDoc && context) context = {
|
|
1857
|
+
...context,
|
|
1858
|
+
newDoc: true
|
|
1859
|
+
};
|
|
1860
|
+
} else if (provider.canRewind && target.resumeAt) {
|
|
1861
|
+
resumeAt = target.resumeAt;
|
|
1862
|
+
store.patch(sessionId, { providerCheckpoint: resumeAt });
|
|
1863
|
+
promptText = rewoundPrompt(text);
|
|
1864
|
+
} else promptText = editedPrompt(target.text, text);
|
|
1865
|
+
store.truncateFrom(sessionId, target.id);
|
|
1866
|
+
}
|
|
1867
|
+
const controller = new AbortController();
|
|
1868
|
+
running.set(sessionId, controller);
|
|
1869
|
+
lastOptions.set(sessionId, {
|
|
1870
|
+
...options,
|
|
1871
|
+
context,
|
|
1872
|
+
edit: void 0
|
|
1873
|
+
});
|
|
1874
|
+
if (session.items.length === 0) store.patch(sessionId, { title: titleFromPrompt(text) });
|
|
1875
|
+
if (options.context?.docId && !session.docId) store.patch(sessionId, { docId: options.context.docId });
|
|
1876
|
+
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" });
|
|
1877
|
+
const userItemId = options.answering ?? newId("u");
|
|
1878
|
+
if (!options.answering) store.appendItem(sessionId, {
|
|
1879
|
+
kind: "user",
|
|
1880
|
+
id: userItemId,
|
|
1881
|
+
ts: now(),
|
|
1882
|
+
text,
|
|
1883
|
+
...session.providerCheckpoint ? { resumeAt: session.providerCheckpoint } : {},
|
|
1884
|
+
...context?.newDoc ? { newDoc: true } : {}
|
|
1885
|
+
});
|
|
1886
|
+
store.patch(sessionId, { status: "running" });
|
|
1887
|
+
const openText = /* @__PURE__ */ new Set();
|
|
1888
|
+
const openTools = /* @__PURE__ */ new Set();
|
|
1889
|
+
const startedAt = Date.now();
|
|
1890
|
+
let resultSeen = false;
|
|
1891
|
+
const appendQuestion = (questions) => store.appendItem(sessionId, {
|
|
1892
|
+
kind: "question",
|
|
1893
|
+
id: newId("q"),
|
|
1894
|
+
ts: now(),
|
|
1895
|
+
questions,
|
|
1896
|
+
answers: null,
|
|
1897
|
+
status: "pending"
|
|
1898
|
+
});
|
|
1899
|
+
const emit = (event) => {
|
|
1900
|
+
if (!store.get(sessionId)) return;
|
|
1901
|
+
switch (event.type) {
|
|
1902
|
+
case "session-id":
|
|
1903
|
+
store.patch(sessionId, { providerSessionId: event.id });
|
|
1904
|
+
return;
|
|
1905
|
+
case "checkpoint":
|
|
1906
|
+
store.patch(sessionId, { providerCheckpoint: event.id });
|
|
1907
|
+
return;
|
|
1908
|
+
case "text-start":
|
|
1909
|
+
openText.add(event.id);
|
|
1910
|
+
store.appendItem(sessionId, {
|
|
1911
|
+
kind: "assistant",
|
|
1912
|
+
id: event.id,
|
|
1913
|
+
ts: now(),
|
|
1914
|
+
text: "",
|
|
1915
|
+
streaming: true
|
|
1916
|
+
});
|
|
1917
|
+
return;
|
|
1918
|
+
case "text-delta":
|
|
1919
|
+
if (!openText.has(event.id)) emit({
|
|
1920
|
+
type: "text-start",
|
|
1921
|
+
id: event.id
|
|
1922
|
+
});
|
|
1923
|
+
store.appendDelta(sessionId, event.id, event.text);
|
|
1924
|
+
return;
|
|
1925
|
+
case "text-end": {
|
|
1926
|
+
if (!openText.has(event.id)) {
|
|
1927
|
+
if (!event.text) return;
|
|
1928
|
+
emit({
|
|
1929
|
+
type: "text-start",
|
|
1930
|
+
id: event.id
|
|
1931
|
+
});
|
|
1266
1932
|
}
|
|
1267
|
-
|
|
1933
|
+
openText.delete(event.id);
|
|
1934
|
+
const changes = event.text !== null ? {
|
|
1935
|
+
streaming: false,
|
|
1936
|
+
text: event.text
|
|
1937
|
+
} : { streaming: false };
|
|
1938
|
+
store.updateItem(sessionId, event.id, "assistant", changes);
|
|
1939
|
+
return;
|
|
1268
1940
|
}
|
|
1941
|
+
case "tool-start":
|
|
1942
|
+
openTools.add(event.id);
|
|
1943
|
+
store.appendItem(sessionId, {
|
|
1944
|
+
kind: "tool",
|
|
1945
|
+
id: event.id,
|
|
1946
|
+
ts: now(),
|
|
1947
|
+
name: event.name,
|
|
1948
|
+
title: event.title,
|
|
1949
|
+
detail: event.detail,
|
|
1950
|
+
status: "running"
|
|
1951
|
+
});
|
|
1952
|
+
return;
|
|
1953
|
+
case "tool-end":
|
|
1954
|
+
openTools.delete(event.id);
|
|
1955
|
+
store.updateItem(sessionId, event.id, "tool", { status: event.ok ? "done" : "error" });
|
|
1956
|
+
return;
|
|
1957
|
+
case "error":
|
|
1958
|
+
store.appendItem(sessionId, {
|
|
1959
|
+
kind: "error",
|
|
1960
|
+
id: newId("e"),
|
|
1961
|
+
ts: now(),
|
|
1962
|
+
text: event.text
|
|
1963
|
+
});
|
|
1964
|
+
return;
|
|
1965
|
+
case "questions":
|
|
1966
|
+
appendQuestion(event.questions);
|
|
1967
|
+
return;
|
|
1968
|
+
case "result":
|
|
1969
|
+
resultSeen = true;
|
|
1970
|
+
store.appendItem(sessionId, {
|
|
1971
|
+
kind: "result",
|
|
1972
|
+
id: newId("r"),
|
|
1973
|
+
ts: now(),
|
|
1974
|
+
durationMs: event.durationMs ?? Date.now() - startedAt,
|
|
1975
|
+
costUsd: event.costUsd,
|
|
1976
|
+
aborted: false
|
|
1977
|
+
});
|
|
1978
|
+
return;
|
|
1269
1979
|
}
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1980
|
+
};
|
|
1981
|
+
const askUser = (questions) => new Promise((resolve) => {
|
|
1982
|
+
if (controller.signal.aborted) return resolve(null);
|
|
1983
|
+
const item = appendQuestion(questions);
|
|
1984
|
+
pending.set(item.id, {
|
|
1985
|
+
kind: "question",
|
|
1986
|
+
resolve: (answers) => {
|
|
1987
|
+
pending.delete(item.id);
|
|
1988
|
+
store.updateItem(sessionId, item.id, "question", {
|
|
1989
|
+
answers,
|
|
1990
|
+
status: answers ? "answered" : "cancelled"
|
|
1991
|
+
});
|
|
1992
|
+
resolve(answers);
|
|
1993
|
+
}
|
|
1994
|
+
});
|
|
1995
|
+
});
|
|
1996
|
+
const requestPermission = (request) => new Promise((resolve) => {
|
|
1997
|
+
if (controller.signal.aborted) return resolve(false);
|
|
1998
|
+
const item = store.appendItem(sessionId, {
|
|
1999
|
+
kind: "permission",
|
|
2000
|
+
id: newId("p"),
|
|
2001
|
+
ts: now(),
|
|
2002
|
+
tool: request.tool,
|
|
2003
|
+
title: request.title,
|
|
2004
|
+
detail: request.detail,
|
|
2005
|
+
status: options.autoApprove ? "allowed" : "pending"
|
|
2006
|
+
});
|
|
2007
|
+
if (options.autoApprove) return resolve(true);
|
|
2008
|
+
pending.set(item.id, {
|
|
2009
|
+
kind: "permission",
|
|
2010
|
+
resolve: (allow) => {
|
|
2011
|
+
pending.delete(item.id);
|
|
2012
|
+
store.updateItem(sessionId, item.id, "permission", { status: allow ? "allowed" : "denied" });
|
|
2013
|
+
resolve(allow);
|
|
2014
|
+
}
|
|
2015
|
+
});
|
|
2016
|
+
});
|
|
2017
|
+
const finish = () => {
|
|
2018
|
+
running.delete(sessionId);
|
|
2019
|
+
if (!store.get(sessionId)) return;
|
|
2020
|
+
for (const id of openText) store.updateItem(sessionId, id, "assistant", { streaming: false });
|
|
2021
|
+
for (const id of openTools) store.updateItem(sessionId, id, "tool", { status: "error" });
|
|
2022
|
+
if (!resultSeen) store.appendItem(sessionId, {
|
|
2023
|
+
kind: "result",
|
|
2024
|
+
id: newId("r"),
|
|
2025
|
+
ts: now(),
|
|
2026
|
+
durationMs: Date.now() - startedAt,
|
|
2027
|
+
costUsd: null,
|
|
2028
|
+
aborted: controller.signal.aborted
|
|
2029
|
+
});
|
|
2030
|
+
store.patch(sessionId, { status: "idle" });
|
|
2031
|
+
if (onTurnEnd) Promise.resolve().then(() => onTurnEnd({
|
|
2032
|
+
sessionId,
|
|
2033
|
+
userItemId
|
|
2034
|
+
})).catch((err) => {
|
|
2035
|
+
console.error("[open-doc] agent turn-end handler failed:", err);
|
|
2036
|
+
});
|
|
2037
|
+
};
|
|
2038
|
+
const promptOpts = promptOptions();
|
|
2039
|
+
const prompt = buildTurnPrompt(promptText, context, promptOpts.docsDir);
|
|
2040
|
+
provider.run({
|
|
2041
|
+
cwd: userCwd,
|
|
2042
|
+
writableRoots,
|
|
2043
|
+
prompt,
|
|
2044
|
+
systemPromptAppend: systemPromptAppend(provider.askInstruction, {
|
|
2045
|
+
...promptOpts,
|
|
2046
|
+
canOpenBrowser: provider.canOpenBrowser
|
|
2047
|
+
}),
|
|
2048
|
+
resume: session.providerSessionId,
|
|
2049
|
+
resumeAt,
|
|
2050
|
+
model: options.model ?? null,
|
|
2051
|
+
effort: options.effort ?? null,
|
|
2052
|
+
signal: controller.signal,
|
|
2053
|
+
emit,
|
|
2054
|
+
askUser,
|
|
2055
|
+
requestPermission
|
|
2056
|
+
}).catch((err) => {
|
|
2057
|
+
if (controller.signal.aborted) return;
|
|
2058
|
+
emit({
|
|
2059
|
+
type: "error",
|
|
2060
|
+
text: err instanceof Error ? err.message : String(err)
|
|
2061
|
+
});
|
|
2062
|
+
}).finally(finish);
|
|
2063
|
+
}
|
|
2064
|
+
function stop(sessionId) {
|
|
2065
|
+
const controller = running.get(sessionId);
|
|
2066
|
+
if (!controller) return false;
|
|
2067
|
+
const session = store.get(sessionId);
|
|
2068
|
+
if (session) for (const item of session.items) {
|
|
2069
|
+
const prompt = pending.get(item.id);
|
|
2070
|
+
if (prompt) cancelPrompt(prompt);
|
|
2071
|
+
}
|
|
2072
|
+
controller.abort();
|
|
2073
|
+
return true;
|
|
2074
|
+
}
|
|
2075
|
+
function respond(sessionId, itemId, payload, next = {}) {
|
|
2076
|
+
if (!store.get(sessionId)?.items.some((i) => i.id === itemId)) return false;
|
|
2077
|
+
const prompt = pending.get(itemId);
|
|
2078
|
+
if (!prompt) return answerInNextTurn(sessionId, itemId, payload, next);
|
|
2079
|
+
if ("cancel" in payload) {
|
|
2080
|
+
cancelPrompt(prompt);
|
|
2081
|
+
return true;
|
|
2082
|
+
}
|
|
2083
|
+
if (prompt.kind === "question" && "answers" in payload) {
|
|
2084
|
+
prompt.resolve(payload.answers);
|
|
2085
|
+
return true;
|
|
2086
|
+
}
|
|
2087
|
+
if (prompt.kind === "permission" && "allow" in payload) {
|
|
2088
|
+
prompt.resolve(payload.allow);
|
|
2089
|
+
return true;
|
|
2090
|
+
}
|
|
2091
|
+
return false;
|
|
2092
|
+
}
|
|
2093
|
+
function answerInNextTurn(sessionId, itemId, payload, next) {
|
|
2094
|
+
const item = store.get(sessionId)?.items.find((i) => i.id === itemId);
|
|
2095
|
+
if (item?.kind !== "question" || item.status !== "pending" || running.has(sessionId)) return false;
|
|
2096
|
+
if (!("answers" in payload) && !("cancel" in payload)) return false;
|
|
2097
|
+
const answers = "answers" in payload ? payload.answers : null;
|
|
2098
|
+
store.updateItem(sessionId, itemId, "question", {
|
|
2099
|
+
answers,
|
|
2100
|
+
status: answers ? "answered" : "cancelled"
|
|
2101
|
+
});
|
|
2102
|
+
const previous = {
|
|
2103
|
+
...lastOptions.get(sessionId),
|
|
2104
|
+
...next
|
|
2105
|
+
};
|
|
2106
|
+
const context = previous.context ? {
|
|
2107
|
+
...previous.context,
|
|
2108
|
+
newDoc: void 0
|
|
2109
|
+
} : void 0;
|
|
2110
|
+
send(sessionId, {
|
|
2111
|
+
...previous,
|
|
2112
|
+
context,
|
|
2113
|
+
text: answersPrompt(item.questions, answers),
|
|
2114
|
+
answering: itemId
|
|
2115
|
+
}).catch((err) => {
|
|
2116
|
+
console.error("[open-doc] agent turn failed:", err);
|
|
2117
|
+
});
|
|
2118
|
+
return true;
|
|
2119
|
+
}
|
|
2120
|
+
function stopAll() {
|
|
2121
|
+
for (const id of Array.from(running.keys())) stop(id);
|
|
2122
|
+
}
|
|
2123
|
+
return {
|
|
2124
|
+
send,
|
|
2125
|
+
stop,
|
|
2126
|
+
respond,
|
|
2127
|
+
isRunning,
|
|
2128
|
+
stopAll
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
//#endregion
|
|
2132
|
+
//#region src/agent/status.ts
|
|
2133
|
+
const INSTALL_TIMEOUT_MS = 6e5;
|
|
2134
|
+
async function providerStatus(userCwd, provider) {
|
|
2135
|
+
const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
|
|
2136
|
+
const cliPath = findOnPath(provider.cliCommand);
|
|
2137
|
+
const [cliVersion, models] = await Promise.all([cliPath ? commandVersion(cliPath) : null, provider.models()]);
|
|
2138
|
+
return {
|
|
2139
|
+
id: provider.id,
|
|
2140
|
+
name: provider.name,
|
|
2141
|
+
sdkPackage: provider.sdkPackage,
|
|
2142
|
+
sdkVersion: sdk?.version ?? null,
|
|
2143
|
+
cliCommand: provider.cliCommand,
|
|
2144
|
+
cliFound: cliPath !== null,
|
|
2145
|
+
cliVersion,
|
|
2146
|
+
ready: sdk !== null,
|
|
2147
|
+
models
|
|
2148
|
+
};
|
|
2149
|
+
}
|
|
2150
|
+
async function agentStatus(userCwd, providers, packageManager) {
|
|
2151
|
+
return {
|
|
2152
|
+
enabled: true,
|
|
2153
|
+
packageManager,
|
|
2154
|
+
providers: await Promise.all(Object.values(providers).map((provider) => providerStatus(userCwd, provider)))
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
function installCommandFor(packageManager, pkg) {
|
|
2158
|
+
switch (packageManager) {
|
|
2159
|
+
case "pnpm": return {
|
|
2160
|
+
cmd: "pnpm",
|
|
2161
|
+
args: [
|
|
2162
|
+
"add",
|
|
2163
|
+
"-D",
|
|
2164
|
+
pkg
|
|
2165
|
+
]
|
|
2166
|
+
};
|
|
2167
|
+
case "yarn": return {
|
|
2168
|
+
cmd: "yarn",
|
|
2169
|
+
args: [
|
|
2170
|
+
"add",
|
|
2171
|
+
"-D",
|
|
2172
|
+
pkg
|
|
2173
|
+
]
|
|
2174
|
+
};
|
|
2175
|
+
case "bun": return {
|
|
2176
|
+
cmd: "bun",
|
|
2177
|
+
args: [
|
|
2178
|
+
"add",
|
|
2179
|
+
"-d",
|
|
2180
|
+
pkg
|
|
2181
|
+
]
|
|
2182
|
+
};
|
|
2183
|
+
case "npm": return {
|
|
2184
|
+
cmd: "npm",
|
|
2185
|
+
args: [
|
|
2186
|
+
"install",
|
|
2187
|
+
"-D",
|
|
2188
|
+
pkg
|
|
2189
|
+
]
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
function installSdk(packageManager, pkg, cwd) {
|
|
2194
|
+
return runCommand(installCommandFor(packageManager, pkg), cwd, INSTALL_TIMEOUT_MS);
|
|
2195
|
+
}
|
|
2196
|
+
//#endregion
|
|
2197
|
+
//#region src/http/request-guard.ts
|
|
2198
|
+
function firstHeaderValue(value) {
|
|
2199
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
2200
|
+
return value ?? null;
|
|
2201
|
+
}
|
|
2202
|
+
function headerValue(req, name) {
|
|
2203
|
+
return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
|
|
2204
|
+
}
|
|
2205
|
+
function firstCommaToken(value) {
|
|
2206
|
+
if (!value) return null;
|
|
2207
|
+
const [first] = value.split(",", 1);
|
|
2208
|
+
return first?.trim() || null;
|
|
2209
|
+
}
|
|
2210
|
+
function requestProto(req) {
|
|
2211
|
+
const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
|
|
2212
|
+
if (forwarded === "http" || forwarded === "https") return forwarded;
|
|
2213
|
+
return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
2214
|
+
}
|
|
2215
|
+
function normalizedOrigin(origin) {
|
|
2216
|
+
try {
|
|
2217
|
+
const url = new URL(origin);
|
|
2218
|
+
return `${url.protocol}//${url.host}`.toLowerCase();
|
|
2219
|
+
} catch {
|
|
2220
|
+
return null;
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
/**
|
|
2224
|
+
* The dev server writes to the user's filesystem, so every mutating endpoint is
|
|
2225
|
+
* guarded against a page on another origin driving it through the browser.
|
|
2226
|
+
*/
|
|
2227
|
+
function validateMutationRequest(req, opts = {}) {
|
|
2228
|
+
if (opts.requireJsonBody) {
|
|
2229
|
+
if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
|
|
2230
|
+
ok: false,
|
|
2231
|
+
status: 415,
|
|
2232
|
+
error: "content-type must be application/json"
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
|
|
2236
|
+
ok: false,
|
|
2237
|
+
status: 403,
|
|
2238
|
+
error: "cross-site request blocked"
|
|
2239
|
+
};
|
|
2240
|
+
const originRaw = headerValue(req, "origin");
|
|
2241
|
+
if (!originRaw) return { ok: true };
|
|
2242
|
+
if (originRaw.toLowerCase() === "null") return {
|
|
2243
|
+
ok: false,
|
|
2244
|
+
status: 403,
|
|
2245
|
+
error: "opaque origin is not allowed"
|
|
2246
|
+
};
|
|
2247
|
+
const actualOrigin = normalizedOrigin(originRaw);
|
|
2248
|
+
if (!actualOrigin) return {
|
|
2249
|
+
ok: false,
|
|
2250
|
+
status: 403,
|
|
2251
|
+
error: "invalid origin header"
|
|
2252
|
+
};
|
|
2253
|
+
const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
|
|
2254
|
+
if (!host) return {
|
|
2255
|
+
ok: false,
|
|
2256
|
+
status: 400,
|
|
2257
|
+
error: "missing host header"
|
|
2258
|
+
};
|
|
2259
|
+
if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
|
|
2260
|
+
ok: false,
|
|
2261
|
+
status: 403,
|
|
2262
|
+
error: "origin mismatch"
|
|
2263
|
+
};
|
|
2264
|
+
return { ok: true };
|
|
2265
|
+
}
|
|
2266
|
+
/** The agent runs commands in the workspace, so only this machine may drive it. */
|
|
2267
|
+
function isLoopbackRequest(req) {
|
|
2268
|
+
const address = req.socket.remoteAddress ?? "";
|
|
2269
|
+
return address === "::1" || address.startsWith("127.") || address.startsWith("::ffff:127.");
|
|
2270
|
+
}
|
|
2271
|
+
//#endregion
|
|
2272
|
+
//#region src/files/assets.ts
|
|
2273
|
+
const GLOBAL_SCOPE = "@global";
|
|
2274
|
+
const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
|
|
2275
|
+
const MIME_BY_EXT = {
|
|
2276
|
+
png: "image/png",
|
|
2277
|
+
jpg: "image/jpeg",
|
|
2278
|
+
jpeg: "image/jpeg",
|
|
2279
|
+
gif: "image/gif",
|
|
2280
|
+
svg: "image/svg+xml",
|
|
2281
|
+
webp: "image/webp",
|
|
2282
|
+
avif: "image/avif",
|
|
2283
|
+
ico: "image/x-icon",
|
|
2284
|
+
pdf: "application/pdf",
|
|
2285
|
+
woff: "font/woff",
|
|
2286
|
+
woff2: "font/woff2",
|
|
2287
|
+
ttf: "font/ttf",
|
|
2288
|
+
otf: "font/otf",
|
|
2289
|
+
csv: "text/csv; charset=utf-8",
|
|
2290
|
+
json: "application/json",
|
|
2291
|
+
txt: "text/plain; charset=utf-8",
|
|
2292
|
+
md: "text/markdown; charset=utf-8"
|
|
2293
|
+
};
|
|
2294
|
+
function mimeForFilename(name) {
|
|
2295
|
+
const dot = name.lastIndexOf(".");
|
|
2296
|
+
if (dot < 0) return "application/octet-stream";
|
|
2297
|
+
return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
|
|
2298
|
+
}
|
|
2299
|
+
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
2300
|
+
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
2301
|
+
}
|
|
2302
|
+
function validateAssetName(v) {
|
|
2303
|
+
if (typeof v !== "string") return null;
|
|
2304
|
+
const trimmed = v.trim();
|
|
2305
|
+
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
2306
|
+
if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
|
|
2307
|
+
if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
|
|
2308
|
+
if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
|
|
2309
|
+
const dot = trimmed.lastIndexOf(".");
|
|
2310
|
+
if (dot <= 0 || dot === trimmed.length - 1) return null;
|
|
2311
|
+
return trimmed;
|
|
2312
|
+
}
|
|
2313
|
+
function resolveAssetsDir(docsRoot, docId) {
|
|
2314
|
+
if (!DOC_ID_RE.test(docId)) return null;
|
|
2315
|
+
const docDir = path.resolve(docsRoot, docId);
|
|
2316
|
+
if (!docDir.startsWith(docsRoot + path.sep)) return null;
|
|
2317
|
+
const assetsDir = path.resolve(docDir, "assets");
|
|
2318
|
+
if (assetsDir !== path.join(docDir, "assets")) return null;
|
|
2319
|
+
return assetsDir;
|
|
2320
|
+
}
|
|
2321
|
+
function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
|
|
2322
|
+
if (scope === "@global") return globalAssetsRoot;
|
|
2323
|
+
return resolveAssetsDir(docsRoot, scope);
|
|
2324
|
+
}
|
|
2325
|
+
function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
|
|
2326
|
+
if (!validateAssetName(filename)) return null;
|
|
2327
|
+
const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
|
|
2328
|
+
if (!dir) return null;
|
|
2329
|
+
const file = path.resolve(dir, filename);
|
|
2330
|
+
if (!file.startsWith(dir + path.sep)) return null;
|
|
2331
|
+
return file;
|
|
2332
|
+
}
|
|
2333
|
+
/** How a document imports an asset — the string we look for when counting usages. */
|
|
2334
|
+
function assetImportPath(scope, filename) {
|
|
2335
|
+
return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
|
|
2336
|
+
}
|
|
2337
|
+
function escapeRegExp(value) {
|
|
2338
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2339
|
+
}
|
|
2340
|
+
/**
|
|
2341
|
+
* Counts references to an asset in a document's source. Matches the quoted path
|
|
2342
|
+
* in both import statements and `new URL('./assets/x.png', import.meta.url)`,
|
|
2343
|
+
* which is every form the authoring skill sanctions.
|
|
2344
|
+
*/
|
|
2345
|
+
function countAssetUsages(source, importPath) {
|
|
2346
|
+
const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
|
|
2347
|
+
return source.match(quoted)?.length ?? 0;
|
|
2348
|
+
}
|
|
2349
|
+
function findReferencedAssets(source, importPaths) {
|
|
2350
|
+
return importPaths.filter((p) => countAssetUsages(source, p) > 0);
|
|
2351
|
+
}
|
|
2352
|
+
//#endregion
|
|
2353
|
+
//#region src/import/lang.ts
|
|
2354
|
+
const TRADITIONAL = "們這個說為國來會時對過還後點經學發應麼與實體關開種現當於從際";
|
|
2355
|
+
const SIMPLIFIED = "们这个说为国来会时对过还后点经学发应么与实体关开种现当于从际";
|
|
2356
|
+
const count = (text, re) => text.match(re)?.length ?? 0;
|
|
2357
|
+
/**
|
|
2358
|
+
* The language a Markdown file is written in, when it is one whose sheets
|
|
2359
|
+
* need to say so — Chinese, Japanese, Korean — or `undefined` for anything
|
|
2360
|
+
* else, which the document then leaves at its default.
|
|
2361
|
+
*/
|
|
2362
|
+
function detectLang(text) {
|
|
2363
|
+
const han = count(text, /\p{Script=Han}/gu);
|
|
2364
|
+
const kana = count(text, /[\p{Script=Hiragana}\p{Script=Katakana}]/gu);
|
|
2365
|
+
const hangul = count(text, /\p{Script=Hangul}/gu);
|
|
2366
|
+
const latin = count(text, /\p{Script=Latin}/gu);
|
|
2367
|
+
const cjk = han + kana + hangul;
|
|
2368
|
+
if (cjk === 0 || cjk < latin * .25) return void 0;
|
|
2369
|
+
if (hangul > han + kana) return "ko";
|
|
2370
|
+
if (kana > 0 && kana >= han * .05) return "ja";
|
|
2371
|
+
let traditional = 0;
|
|
2372
|
+
let simplified = 0;
|
|
2373
|
+
for (const char of text) {
|
|
2374
|
+
const t = TRADITIONAL.indexOf(char);
|
|
2375
|
+
const s = SIMPLIFIED.indexOf(char);
|
|
2376
|
+
if (t !== -1 && SIMPLIFIED[t] !== char) traditional++;
|
|
2377
|
+
if (s !== -1 && TRADITIONAL[s] !== char) simplified++;
|
|
2378
|
+
}
|
|
2379
|
+
return simplified > traditional ? "zh-Hans" : "zh-Hant";
|
|
2380
|
+
}
|
|
2381
|
+
//#endregion
|
|
2382
|
+
//#region src/import/markdown.ts
|
|
2383
|
+
const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
|
|
2384
|
+
const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
|
|
2385
|
+
const HR_RE = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
|
|
2386
|
+
const QUOTE_RE = /^ {0,3}> ?(.*)$/;
|
|
2387
|
+
const UL_RE = /^(\s*)([-*+])\s+(.*)$/;
|
|
2388
|
+
const OL_RE = /^(\s*)(\d{1,9})[.)]\s+(.*)$/;
|
|
2389
|
+
const SETEXT_RE = /^ {0,3}(=+|-+)\s*$/;
|
|
2390
|
+
const TABLE_DELIM_RE = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
|
|
2391
|
+
function splitLines(source) {
|
|
2392
|
+
return source.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
|
|
2393
|
+
}
|
|
2394
|
+
function parseFrontmatter$1(lines) {
|
|
2395
|
+
if (lines[0]?.trim() !== "---") return {
|
|
2396
|
+
frontmatter: {},
|
|
2397
|
+
rest: lines
|
|
2398
|
+
};
|
|
2399
|
+
const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
|
|
2400
|
+
if (end === -1) return {
|
|
2401
|
+
frontmatter: {},
|
|
2402
|
+
rest: lines
|
|
2403
|
+
};
|
|
2404
|
+
const frontmatter = {};
|
|
2405
|
+
for (const line of lines.slice(1, end)) {
|
|
2406
|
+
const match = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
2407
|
+
if (!match) continue;
|
|
2408
|
+
frontmatter[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, "");
|
|
2409
|
+
}
|
|
2410
|
+
return {
|
|
2411
|
+
frontmatter,
|
|
2412
|
+
rest: lines.slice(end + 1)
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
function splitRow(line) {
|
|
2416
|
+
const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
|
|
2417
|
+
const cells = [];
|
|
2418
|
+
let current = "";
|
|
2419
|
+
for (let i = 0; i < trimmed.length; i++) {
|
|
2420
|
+
const char = trimmed[i];
|
|
2421
|
+
if (char === "\\" && trimmed[i + 1] === "|") {
|
|
2422
|
+
current += "|";
|
|
2423
|
+
i++;
|
|
2424
|
+
continue;
|
|
2425
|
+
}
|
|
2426
|
+
if (char === "|") {
|
|
2427
|
+
cells.push(current.trim());
|
|
2428
|
+
current = "";
|
|
2429
|
+
continue;
|
|
1273
2430
|
}
|
|
2431
|
+
current += char;
|
|
2432
|
+
}
|
|
2433
|
+
cells.push(current.trim());
|
|
2434
|
+
return cells;
|
|
2435
|
+
}
|
|
2436
|
+
function parseAlign(line) {
|
|
2437
|
+
return splitRow(line).map((cell) => {
|
|
2438
|
+
const left = cell.startsWith(":");
|
|
2439
|
+
const right = cell.endsWith(":");
|
|
2440
|
+
if (left && right) return "center";
|
|
2441
|
+
if (right) return "right";
|
|
2442
|
+
if (left) return "left";
|
|
2443
|
+
return null;
|
|
1274
2444
|
});
|
|
1275
2445
|
}
|
|
2446
|
+
function indentOf(line) {
|
|
2447
|
+
return line.length - line.trimStart().length;
|
|
2448
|
+
}
|
|
2449
|
+
function isBlockStart(line) {
|
|
2450
|
+
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);
|
|
2451
|
+
}
|
|
2452
|
+
function parseMarkdown(source) {
|
|
2453
|
+
const { frontmatter, rest } = parseFrontmatter$1(splitLines(source));
|
|
2454
|
+
return {
|
|
2455
|
+
frontmatter,
|
|
2456
|
+
blocks: parseBlocks(rest)
|
|
2457
|
+
};
|
|
2458
|
+
}
|
|
2459
|
+
function parseBlocks(lines) {
|
|
2460
|
+
const blocks = [];
|
|
2461
|
+
let i = 0;
|
|
2462
|
+
while (i < lines.length) {
|
|
2463
|
+
const line = lines[i];
|
|
2464
|
+
if (line.trim() === "") {
|
|
2465
|
+
i++;
|
|
2466
|
+
continue;
|
|
2467
|
+
}
|
|
2468
|
+
const fence = line.match(FENCE_RE);
|
|
2469
|
+
if (fence) {
|
|
2470
|
+
const marker = fence[1];
|
|
2471
|
+
const value = [];
|
|
2472
|
+
i++;
|
|
2473
|
+
while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {
|
|
2474
|
+
value.push(lines[i]);
|
|
2475
|
+
i++;
|
|
2476
|
+
}
|
|
2477
|
+
i++;
|
|
2478
|
+
blocks.push({
|
|
2479
|
+
type: "code",
|
|
2480
|
+
lang: fence[2] || null,
|
|
2481
|
+
value: value.join("\n")
|
|
2482
|
+
});
|
|
2483
|
+
continue;
|
|
2484
|
+
}
|
|
2485
|
+
const atx = line.match(ATX_RE);
|
|
2486
|
+
if (atx) {
|
|
2487
|
+
blocks.push({
|
|
2488
|
+
type: "heading",
|
|
2489
|
+
level: atx[1].length,
|
|
2490
|
+
children: parseInline(atx[2])
|
|
2491
|
+
});
|
|
2492
|
+
i++;
|
|
2493
|
+
continue;
|
|
2494
|
+
}
|
|
2495
|
+
if (HR_RE.test(line)) {
|
|
2496
|
+
blocks.push({ type: "hr" });
|
|
2497
|
+
i++;
|
|
2498
|
+
continue;
|
|
2499
|
+
}
|
|
2500
|
+
if (QUOTE_RE.test(line)) {
|
|
2501
|
+
const inner = [];
|
|
2502
|
+
while (i < lines.length && (QUOTE_RE.test(lines[i]) || lines[i].trim() !== "")) {
|
|
2503
|
+
const match = lines[i].match(QUOTE_RE);
|
|
2504
|
+
if (!match && lines[i].trim() === "") break;
|
|
2505
|
+
inner.push(match ? match[1] : lines[i]);
|
|
2506
|
+
i++;
|
|
2507
|
+
}
|
|
2508
|
+
blocks.push({
|
|
2509
|
+
type: "quote",
|
|
2510
|
+
children: parseBlocks(inner)
|
|
2511
|
+
});
|
|
2512
|
+
continue;
|
|
2513
|
+
}
|
|
2514
|
+
if (UL_RE.test(line) || OL_RE.test(line)) {
|
|
2515
|
+
const { block, next } = parseList(lines, i);
|
|
2516
|
+
blocks.push(block);
|
|
2517
|
+
i = next;
|
|
2518
|
+
continue;
|
|
2519
|
+
}
|
|
2520
|
+
if (line.includes("|") && lines[i + 1] !== void 0 && TABLE_DELIM_RE.test(lines[i + 1])) {
|
|
2521
|
+
const head = splitRow(line).map(parseInline);
|
|
2522
|
+
const align = parseAlign(lines[i + 1]);
|
|
2523
|
+
const rows = [];
|
|
2524
|
+
i += 2;
|
|
2525
|
+
while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
|
|
2526
|
+
rows.push(splitRow(lines[i]).map(parseInline));
|
|
2527
|
+
i++;
|
|
2528
|
+
}
|
|
2529
|
+
blocks.push({
|
|
2530
|
+
type: "table",
|
|
2531
|
+
head,
|
|
2532
|
+
rows,
|
|
2533
|
+
align
|
|
2534
|
+
});
|
|
2535
|
+
continue;
|
|
2536
|
+
}
|
|
2537
|
+
const paragraph = [];
|
|
2538
|
+
while (i < lines.length && lines[i].trim() !== "") {
|
|
2539
|
+
const next = lines[i + 1];
|
|
2540
|
+
if (next !== void 0 && SETEXT_RE.test(next)) {
|
|
2541
|
+
paragraph.push(lines[i]);
|
|
2542
|
+
i += 2;
|
|
2543
|
+
blocks.push({
|
|
2544
|
+
type: "heading",
|
|
2545
|
+
level: next.trim().startsWith("=") ? 1 : 2,
|
|
2546
|
+
children: parseInline(paragraph.join(" "))
|
|
2547
|
+
});
|
|
2548
|
+
paragraph.length = 0;
|
|
2549
|
+
break;
|
|
2550
|
+
}
|
|
2551
|
+
if (paragraph.length > 0 && isBlockStart(lines[i])) break;
|
|
2552
|
+
paragraph.push(lines[i]);
|
|
2553
|
+
i++;
|
|
2554
|
+
}
|
|
2555
|
+
if (paragraph.length > 0) {
|
|
2556
|
+
const text = paragraph.join("\n");
|
|
2557
|
+
const figure = asStandaloneImage(text);
|
|
2558
|
+
blocks.push(figure ?? {
|
|
2559
|
+
type: "paragraph",
|
|
2560
|
+
children: parseInline(text)
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
return blocks;
|
|
2565
|
+
}
|
|
2566
|
+
/** An image alone in its paragraph is a figure, not a run of inline content. */
|
|
2567
|
+
function asStandaloneImage(text) {
|
|
2568
|
+
const match = text.trim().match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
|
|
2569
|
+
if (!match) return null;
|
|
2570
|
+
return {
|
|
2571
|
+
type: "figure",
|
|
2572
|
+
alt: match[1],
|
|
2573
|
+
src: match[2]
|
|
2574
|
+
};
|
|
2575
|
+
}
|
|
2576
|
+
function parseList(lines, start) {
|
|
2577
|
+
const first = lines[start];
|
|
2578
|
+
const ordered = OL_RE.test(first);
|
|
2579
|
+
const startNumber = ordered ? Number(first.match(OL_RE)?.[2] ?? 1) : 1;
|
|
2580
|
+
const baseIndent = indentOf(first);
|
|
2581
|
+
const items = [];
|
|
2582
|
+
let i = start;
|
|
2583
|
+
let current = null;
|
|
2584
|
+
const flush = () => {
|
|
2585
|
+
if (current) items.push(parseBlocks(current));
|
|
2586
|
+
current = null;
|
|
2587
|
+
};
|
|
2588
|
+
while (i < lines.length) {
|
|
2589
|
+
const line = lines[i];
|
|
2590
|
+
if (line.trim() === "") {
|
|
2591
|
+
const next = lines[i + 1];
|
|
2592
|
+
if (next === void 0 || next.trim() !== "" && indentOf(next) <= baseIndent && !isItem(next)) break;
|
|
2593
|
+
current?.push("");
|
|
2594
|
+
i++;
|
|
2595
|
+
continue;
|
|
2596
|
+
}
|
|
2597
|
+
const match = line.match(ordered ? OL_RE : UL_RE) ?? line.match(ordered ? UL_RE : OL_RE);
|
|
2598
|
+
if (match && indentOf(line) <= baseIndent) {
|
|
2599
|
+
flush();
|
|
2600
|
+
current = [match[3]];
|
|
2601
|
+
i++;
|
|
2602
|
+
continue;
|
|
2603
|
+
}
|
|
2604
|
+
if (indentOf(line) > baseIndent && current) {
|
|
2605
|
+
current.push(line.slice(Math.min(indentOf(line), baseIndent + 2)));
|
|
2606
|
+
i++;
|
|
2607
|
+
continue;
|
|
2608
|
+
}
|
|
2609
|
+
break;
|
|
2610
|
+
}
|
|
2611
|
+
flush();
|
|
2612
|
+
return {
|
|
2613
|
+
block: {
|
|
2614
|
+
type: "list",
|
|
2615
|
+
ordered,
|
|
2616
|
+
start: startNumber,
|
|
2617
|
+
items
|
|
2618
|
+
},
|
|
2619
|
+
next: i
|
|
2620
|
+
};
|
|
2621
|
+
function isItem(line) {
|
|
2622
|
+
return UL_RE.test(line) || OL_RE.test(line);
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
const INLINE_RE = /(!\[[^\]]*\]\([^)\s]+(?:\s+"[^"]*")?\))|(\[[^\]]*\]\([^)\s]*(?:\s+"[^"]*")?\))|(`+)([^`]*?)\3|(\*\*|__)(?=\S)([\s\S]*?\S)\5|(\*|_)(?=\S)([\s\S]*?\S)\7|(<[^>\s]+@[^>\s]+>)|(https?:\/\/[^\s<>"')\]]+)/;
|
|
2626
|
+
function parseInline(source) {
|
|
2627
|
+
const out = [];
|
|
2628
|
+
let rest = maskEscapes(source);
|
|
2629
|
+
const pushText = (value) => {
|
|
2630
|
+
if (value === "") return;
|
|
2631
|
+
value.split(/(?: {2}|\\)\n|\n/).forEach((part, index) => {
|
|
2632
|
+
if (index > 0) out.push({ type: "break" });
|
|
2633
|
+
const text = unmask(part);
|
|
2634
|
+
if (text !== "") out.push({
|
|
2635
|
+
type: "text",
|
|
2636
|
+
value: text
|
|
2637
|
+
});
|
|
2638
|
+
});
|
|
2639
|
+
};
|
|
2640
|
+
while (rest.length > 0) {
|
|
2641
|
+
const match = rest.match(INLINE_RE);
|
|
2642
|
+
if (!match || match.index === void 0) break;
|
|
2643
|
+
pushText(rest.slice(0, match.index));
|
|
2644
|
+
const token = match[0];
|
|
2645
|
+
if (match[1]) {
|
|
2646
|
+
const image = token.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
|
|
2647
|
+
if (image) out.push({
|
|
2648
|
+
type: "image",
|
|
2649
|
+
alt: unmask(image[1]),
|
|
2650
|
+
src: unmask(image[2])
|
|
2651
|
+
});
|
|
2652
|
+
} else if (match[2]) {
|
|
2653
|
+
const link = token.match(/^\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)$/);
|
|
2654
|
+
if (link) out.push({
|
|
2655
|
+
type: "link",
|
|
2656
|
+
href: unmask(link[2]),
|
|
2657
|
+
children: parseInline(link[1])
|
|
2658
|
+
});
|
|
2659
|
+
} else if (match[3]) out.push({
|
|
2660
|
+
type: "code",
|
|
2661
|
+
value: unmask(match[4].trim())
|
|
2662
|
+
});
|
|
2663
|
+
else if (match[5]) out.push({
|
|
2664
|
+
type: "strong",
|
|
2665
|
+
children: parseInline(match[6])
|
|
2666
|
+
});
|
|
2667
|
+
else if (match[7]) out.push({
|
|
2668
|
+
type: "em",
|
|
2669
|
+
children: parseInline(match[8])
|
|
2670
|
+
});
|
|
2671
|
+
else if (match[9]) {
|
|
2672
|
+
const address = token.slice(1, -1);
|
|
2673
|
+
out.push({
|
|
2674
|
+
type: "link",
|
|
2675
|
+
href: `mailto:${address}`,
|
|
2676
|
+
children: [{
|
|
2677
|
+
type: "text",
|
|
2678
|
+
value: address
|
|
2679
|
+
}]
|
|
2680
|
+
});
|
|
2681
|
+
} else if (match[10]) {
|
|
2682
|
+
const url = unmask(token);
|
|
2683
|
+
out.push({
|
|
2684
|
+
type: "link",
|
|
2685
|
+
href: url,
|
|
2686
|
+
children: [{
|
|
2687
|
+
type: "text",
|
|
2688
|
+
value: url
|
|
2689
|
+
}]
|
|
2690
|
+
});
|
|
2691
|
+
}
|
|
2692
|
+
rest = rest.slice(match.index + token.length);
|
|
2693
|
+
}
|
|
2694
|
+
pushText(rest);
|
|
2695
|
+
return out;
|
|
2696
|
+
}
|
|
2697
|
+
const ESCAPE_RE = /\\([\\`*_{}[\]()#+\-.!|>~])/g;
|
|
2698
|
+
const MASK_RE = /\u0000(\d+)\u0000/g;
|
|
2699
|
+
/**
|
|
2700
|
+
* The inline scanner is a regex over delimiters, which cannot see a preceding
|
|
2701
|
+
* backslash. Escaped characters are swapped for a sentinel before scanning and
|
|
2702
|
+
* restored on the way out, so `\*not emphasis\*` survives as literal text.
|
|
2703
|
+
*/
|
|
2704
|
+
function maskEscapes(value) {
|
|
2705
|
+
return value.replace(ESCAPE_RE, (_, char) => `\u0000${char.charCodeAt(0)}\u0000`);
|
|
2706
|
+
}
|
|
2707
|
+
function unmask(value) {
|
|
2708
|
+
return value.replace(MASK_RE, (_, code) => String.fromCharCode(Number(code)));
|
|
2709
|
+
}
|
|
2710
|
+
/** Flattens inline content to plain text — for titles, alt text, and outline labels. */
|
|
2711
|
+
function inlineText(nodes) {
|
|
2712
|
+
return nodes.map((node) => {
|
|
2713
|
+
switch (node.type) {
|
|
2714
|
+
case "text":
|
|
2715
|
+
case "code": return node.value;
|
|
2716
|
+
case "strong":
|
|
2717
|
+
case "em":
|
|
2718
|
+
case "link": return inlineText(node.children);
|
|
2719
|
+
case "image": return node.alt;
|
|
2720
|
+
case "break": return " ";
|
|
2721
|
+
default: return "";
|
|
2722
|
+
}
|
|
2723
|
+
}).join("").replace(/\s+/g, " ").trim();
|
|
2724
|
+
}
|
|
1276
2725
|
//#endregion
|
|
1277
|
-
//#region src/
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
2726
|
+
//#region src/import/to-tsx.ts
|
|
2727
|
+
/** JSX text is written literally; only these characters have to be escaped. */
|
|
2728
|
+
function jsxText(text) {
|
|
2729
|
+
return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
|
|
2730
|
+
}
|
|
2731
|
+
function jsString$1(value) {
|
|
2732
|
+
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
|
|
2733
|
+
}
|
|
2734
|
+
function attr(value) {
|
|
2735
|
+
return `"${value.replace(/"/g, """)}"`;
|
|
2736
|
+
}
|
|
2737
|
+
function collectImageSources(blocks) {
|
|
2738
|
+
const out = [];
|
|
2739
|
+
const walkInline = (nodes) => {
|
|
2740
|
+
for (const node of nodes) if (node.type === "image") out.push(node.src);
|
|
2741
|
+
else if (node.type === "strong" || node.type === "em" || node.type === "link") walkInline(node.children);
|
|
2742
|
+
};
|
|
2743
|
+
const walk = (list) => {
|
|
2744
|
+
for (const block of list) switch (block.type) {
|
|
2745
|
+
case "figure":
|
|
2746
|
+
out.push(block.src);
|
|
2747
|
+
break;
|
|
2748
|
+
case "heading":
|
|
2749
|
+
case "paragraph":
|
|
2750
|
+
walkInline(block.children);
|
|
2751
|
+
break;
|
|
2752
|
+
case "quote":
|
|
2753
|
+
walk(block.children);
|
|
2754
|
+
break;
|
|
2755
|
+
case "list":
|
|
2756
|
+
for (const item of block.items) walk(item);
|
|
2757
|
+
break;
|
|
2758
|
+
case "table":
|
|
2759
|
+
for (const cell of block.head) walkInline(cell);
|
|
2760
|
+
for (const row of block.rows) for (const cell of row) walkInline(cell);
|
|
2761
|
+
}
|
|
2762
|
+
};
|
|
2763
|
+
walk(blocks);
|
|
2764
|
+
return out;
|
|
2765
|
+
}
|
|
2766
|
+
function imageSrc(src, images) {
|
|
2767
|
+
const known = images?.get(src);
|
|
2768
|
+
return known ? `{${known.ident}}` : attr(src);
|
|
2769
|
+
}
|
|
2770
|
+
function renderInline(nodes, images) {
|
|
2771
|
+
return nodes.map((node) => {
|
|
2772
|
+
switch (node.type) {
|
|
2773
|
+
case "text": return jsxText(node.value);
|
|
2774
|
+
case "strong": return `<strong>${renderInline(node.children, images)}</strong>`;
|
|
2775
|
+
case "em": return `<em>${renderInline(node.children, images)}</em>`;
|
|
2776
|
+
case "code": return `<code style={codeInline}>${jsxText(node.value)}</code>`;
|
|
2777
|
+
case "link": return `<a href=${attr(node.href)} style={link}>${renderInline(node.children, images)}</a>`;
|
|
2778
|
+
case "image": return `<img src=${imageSrc(node.src, images)} alt=${attr(node.alt)} style={inlineImg} />`;
|
|
2779
|
+
case "break": return "<br />";
|
|
2780
|
+
default: return "";
|
|
2781
|
+
}
|
|
2782
|
+
}).join("");
|
|
2783
|
+
}
|
|
2784
|
+
const HEADING_STYLE = {
|
|
2785
|
+
1: "h1",
|
|
2786
|
+
2: "h2",
|
|
2787
|
+
3: "h3",
|
|
2788
|
+
4: "h4"
|
|
2789
|
+
};
|
|
2790
|
+
function alignStyle(align) {
|
|
2791
|
+
return align && align !== "left" ? ` align={${jsString$1(align)}}` : "";
|
|
2792
|
+
}
|
|
2793
|
+
function renderBlock(block, images, indent) {
|
|
2794
|
+
const pad = indent;
|
|
2795
|
+
switch (block.type) {
|
|
2796
|
+
case "heading": {
|
|
2797
|
+
const level = Math.min(block.level, 4);
|
|
2798
|
+
const tag = level >= 4 ? "h4" : `h${level}`;
|
|
2799
|
+
return `${pad}<${tag} style={${HEADING_STYLE[level] ?? "h3"}}>${renderInline(block.children, images)}</${tag}>`;
|
|
2800
|
+
}
|
|
2801
|
+
case "paragraph": return `${pad}<p style={p}>${renderInline(block.children, images)}</p>`;
|
|
2802
|
+
case "hr": return `${pad}<hr style={rule} />`;
|
|
2803
|
+
case "code": return `${pad}<pre style={pre}>{${jsString$1(block.value)}}</pre>`;
|
|
2804
|
+
case "quote": return [
|
|
2805
|
+
`${pad}<blockquote style={quote}>`,
|
|
2806
|
+
...block.children.map((child) => renderBlock(child, images, `${pad} `)),
|
|
2807
|
+
`${pad}</blockquote>`
|
|
2808
|
+
].join("\n");
|
|
2809
|
+
case "figure": {
|
|
2810
|
+
const caption = block.alt ? `\n${pad} <figcaption style={caption}>${jsxText(block.alt)}</figcaption>` : "";
|
|
2811
|
+
return [
|
|
2812
|
+
`${pad}<figure style={figure}>`,
|
|
2813
|
+
`${pad} <img src=${imageSrc(block.src, images)} alt=${attr(block.alt)} style={img} />${caption}`,
|
|
2814
|
+
`${pad}</figure>`
|
|
2815
|
+
].join("\n");
|
|
2816
|
+
}
|
|
2817
|
+
case "list": {
|
|
2818
|
+
const tag = block.ordered ? "ol" : "ul";
|
|
2819
|
+
const startAttr = block.ordered && block.start !== 1 ? ` start={${block.start}}` : "";
|
|
2820
|
+
const items = block.items.map((item) => {
|
|
2821
|
+
const inner = item.map((child, index) => child.type === "paragraph" && index === 0 ? `${renderInline(child.children, images)}` : `\n${renderBlock(child, images, `${pad} `)}`).join("");
|
|
2822
|
+
return `${pad} <li style={li}>${inner.startsWith("\n") ? `${inner}\n${pad} ` : inner}</li>`;
|
|
2823
|
+
});
|
|
2824
|
+
return [
|
|
2825
|
+
`${pad}<${tag} style={${tag}}${startAttr}>`,
|
|
2826
|
+
...items,
|
|
2827
|
+
`${pad}</${tag}>`
|
|
2828
|
+
].join("\n");
|
|
2829
|
+
}
|
|
2830
|
+
case "table": {
|
|
2831
|
+
const head = block.head.map((cell, i) => `${pad} <Th${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Th>`).join("\n");
|
|
2832
|
+
const rows = block.rows.map((row) => [
|
|
2833
|
+
`${pad} <tr>`,
|
|
2834
|
+
...row.map((cell, i) => `${pad} <Td${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Td>`),
|
|
2835
|
+
`${pad} </tr>`
|
|
2836
|
+
].join("\n")).join("\n");
|
|
2837
|
+
return [
|
|
2838
|
+
`${pad}<table style={table}>`,
|
|
2839
|
+
`${pad} <thead>`,
|
|
2840
|
+
`${pad} <tr>`,
|
|
2841
|
+
head,
|
|
2842
|
+
`${pad} </tr>`,
|
|
2843
|
+
`${pad} </thead>`,
|
|
2844
|
+
`${pad} <tbody>`,
|
|
2845
|
+
rows,
|
|
2846
|
+
`${pad} </tbody>`,
|
|
2847
|
+
`${pad}</table>`
|
|
2848
|
+
].join("\n");
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
function titleFrom(parsed, opts) {
|
|
2853
|
+
if (opts.title) return opts.title;
|
|
2854
|
+
if (parsed.frontmatter.title) return parsed.frontmatter.title;
|
|
2855
|
+
const heading = parsed.blocks.find((block) => block.type === "heading" && block.level === 1);
|
|
2856
|
+
if (heading && heading.type === "heading") return inlineText(heading.children);
|
|
2857
|
+
return opts.docId.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());
|
|
2858
|
+
}
|
|
2859
|
+
const STYLES = `const page = {
|
|
2860
|
+
width: '100%',
|
|
2861
|
+
height: '100%',
|
|
2862
|
+
boxSizing: 'border-box' as const,
|
|
2863
|
+
padding: 'var(--od-margin)',
|
|
2864
|
+
background: 'var(--od-bg)',
|
|
2865
|
+
color: 'var(--od-text)',
|
|
2866
|
+
fontFamily: 'var(--od-font-body)',
|
|
2867
|
+
fontSize: 'var(--od-size-body)',
|
|
2868
|
+
lineHeight: 'var(--od-leading)',
|
|
2869
|
+
position: 'relative' as const,
|
|
2870
|
+
};
|
|
2871
|
+
|
|
2872
|
+
const h1 = {
|
|
2873
|
+
fontFamily: 'var(--od-font-heading)',
|
|
2874
|
+
fontSize: 'var(--od-size-h1)',
|
|
2875
|
+
lineHeight: 1.2,
|
|
2876
|
+
fontWeight: 650,
|
|
2877
|
+
margin: '0 0 18px',
|
|
2878
|
+
};
|
|
2879
|
+
|
|
2880
|
+
const h2 = { ...h1, fontSize: 'var(--od-size-h2)', margin: '26px 0 12px' };
|
|
2881
|
+
const h3 = { ...h1, fontSize: 'var(--od-size-h3)', fontWeight: 600, margin: '20px 0 8px' };
|
|
2882
|
+
const h4 = { ...h3, fontSize: 'var(--od-size-body)', margin: '16px 0 6px' };
|
|
2883
|
+
const p = { margin: '0 0 12px' };
|
|
2884
|
+
// The viewer's CSS reset strips list markers, so both are set back explicitly.
|
|
2885
|
+
const ul = { margin: '0 0 12px', paddingLeft: 22, listStyle: 'disc outside' };
|
|
2886
|
+
const ol = { ...ul, listStyle: 'decimal outside' };
|
|
2887
|
+
const li = { margin: '0 0 5px' };
|
|
2888
|
+
const link = { color: 'var(--od-accent)', textDecoration: 'none' };
|
|
2889
|
+
const rule = { border: 0, borderTop: '1px solid var(--od-rule)', margin: '20px 0' };
|
|
2890
|
+
|
|
2891
|
+
const codeInline = {
|
|
2892
|
+
fontFamily: 'var(--od-font-mono)',
|
|
2893
|
+
fontSize: '0.92em',
|
|
2894
|
+
background: 'var(--od-rule)',
|
|
2895
|
+
borderRadius: 3,
|
|
2896
|
+
padding: '1px 4px',
|
|
2897
|
+
};
|
|
2898
|
+
|
|
2899
|
+
const pre = {
|
|
2900
|
+
fontFamily: 'var(--od-font-mono)',
|
|
2901
|
+
fontSize: 11,
|
|
2902
|
+
lineHeight: 1.5,
|
|
2903
|
+
background: 'var(--od-rule)',
|
|
2904
|
+
borderRadius: 'var(--od-radius)',
|
|
2905
|
+
padding: '10px 12px',
|
|
2906
|
+
margin: '0 0 14px',
|
|
2907
|
+
whiteSpace: 'pre-wrap' as const,
|
|
2908
|
+
overflowWrap: 'anywhere' as const,
|
|
2909
|
+
};
|
|
2910
|
+
|
|
2911
|
+
const quote = {
|
|
2912
|
+
margin: '0 0 14px',
|
|
2913
|
+
padding: '2px 0 2px 14px',
|
|
2914
|
+
borderLeft: '2px solid var(--od-accent)',
|
|
2915
|
+
color: 'var(--od-muted)',
|
|
2916
|
+
};
|
|
2917
|
+
|
|
2918
|
+
const table = {
|
|
2919
|
+
width: '100%',
|
|
2920
|
+
borderCollapse: 'collapse' as const,
|
|
2921
|
+
tableLayout: 'fixed' as const,
|
|
2922
|
+
margin: '0 0 16px',
|
|
2923
|
+
};
|
|
2924
|
+
|
|
2925
|
+
const figure = { margin: '0 0 16px' };
|
|
2926
|
+
const img = { width: '100%', display: 'block' as const };
|
|
2927
|
+
const inlineImg = { maxWidth: '100%', verticalAlign: 'middle' as const };
|
|
2928
|
+
const caption = { fontSize: 'var(--od-size-caption)', color: 'var(--od-muted)', margin: '6px 0 0' };
|
|
2929
|
+
|
|
2930
|
+
const Th = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
|
|
2931
|
+
<th
|
|
2932
|
+
style={{
|
|
2933
|
+
textAlign: align,
|
|
2934
|
+
fontFamily: 'var(--od-font-heading)',
|
|
2935
|
+
fontSize: 11,
|
|
2936
|
+
fontWeight: 600,
|
|
2937
|
+
letterSpacing: '0.04em',
|
|
2938
|
+
textTransform: 'uppercase',
|
|
2939
|
+
color: 'var(--od-muted)',
|
|
2940
|
+
borderBottom: '1px solid var(--od-rule)',
|
|
2941
|
+
padding: '0 8px 6px',
|
|
2942
|
+
}}
|
|
2943
|
+
>
|
|
2944
|
+
{children}
|
|
2945
|
+
</th>
|
|
2946
|
+
);
|
|
2947
|
+
|
|
2948
|
+
const Td = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
|
|
2949
|
+
<td
|
|
2950
|
+
style={{
|
|
2951
|
+
textAlign: align,
|
|
2952
|
+
fontSize: 12,
|
|
2953
|
+
padding: '7px 8px',
|
|
2954
|
+
borderBottom: '1px solid var(--od-rule)',
|
|
2955
|
+
fontVariantNumeric: align === 'right' ? 'tabular-nums' : undefined,
|
|
2956
|
+
}}
|
|
2957
|
+
>
|
|
2958
|
+
{children}
|
|
2959
|
+
</td>
|
|
2960
|
+
);
|
|
2961
|
+
|
|
2962
|
+
const Footer = () => {
|
|
2963
|
+
const n = useDocPageNumber();
|
|
2964
|
+
const total = useDocPageCount();
|
|
2965
|
+
return (
|
|
2966
|
+
<div
|
|
2967
|
+
style={{
|
|
2968
|
+
position: 'absolute',
|
|
2969
|
+
left: 'var(--od-margin)',
|
|
2970
|
+
right: 'var(--od-margin)',
|
|
2971
|
+
bottom: 40,
|
|
2972
|
+
display: 'flex',
|
|
2973
|
+
justifyContent: 'space-between',
|
|
2974
|
+
fontSize: 'var(--od-size-caption)',
|
|
2975
|
+
color: 'var(--od-muted)',
|
|
2976
|
+
}}
|
|
2977
|
+
>
|
|
2978
|
+
<span>{DOC_TITLE}</span>
|
|
2979
|
+
<span style={{ fontVariantNumeric: 'tabular-nums' }}>
|
|
2980
|
+
{n} / {total}
|
|
2981
|
+
</span>
|
|
2982
|
+
</div>
|
|
2983
|
+
);
|
|
2984
|
+
};`;
|
|
2985
|
+
const DESIGN = `export const design: DesignSystem = {
|
|
2986
|
+
palette: {
|
|
2987
|
+
bg: '#ffffff',
|
|
2988
|
+
text: '#16181d',
|
|
2989
|
+
muted: '#6b7280',
|
|
2990
|
+
accent: '#2563eb',
|
|
2991
|
+
rule: '#e5e7eb',
|
|
2992
|
+
},
|
|
2993
|
+
fonts: {
|
|
2994
|
+
heading: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
|
|
2995
|
+
body: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
|
|
2996
|
+
mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace',
|
|
2997
|
+
},
|
|
2998
|
+
typeScale: { title: 44, h1: 28, h2: 20, h3: 16, body: 14, caption: 10 },
|
|
2999
|
+
margin: 76,
|
|
3000
|
+
leading: 1.55,
|
|
3001
|
+
radius: 6,
|
|
3002
|
+
};`;
|
|
3003
|
+
/**
|
|
3004
|
+
* Turns parsed markdown into a document module. The output is ordinary authored
|
|
3005
|
+
* TSX — inline styles, real heading tags, plain JSX text — so the outline, the
|
|
3006
|
+
* inspector, and the design panel all work on an imported document exactly as
|
|
3007
|
+
* they do on a hand-written one.
|
|
3008
|
+
*/
|
|
3009
|
+
function generateDocumentSource(parsed, opts) {
|
|
3010
|
+
const title = titleFrom(parsed, opts);
|
|
3011
|
+
const subtitle = opts.subtitle ?? parsed.frontmatter.subtitle;
|
|
3012
|
+
const author = opts.author ?? parsed.frontmatter.author;
|
|
3013
|
+
const theme = opts.theme ?? parsed.frontmatter.theme;
|
|
3014
|
+
const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
|
|
3015
|
+
const orientation = opts.orientation ?? parsed.frontmatter.orientation;
|
|
3016
|
+
const lang = opts.lang ?? parsed.frontmatter.lang;
|
|
3017
|
+
const cover = opts.cover !== false;
|
|
3018
|
+
let blocks = parsed.blocks;
|
|
3019
|
+
const first = blocks[0];
|
|
3020
|
+
if (cover && first?.type === "heading" && first.level === 1 && inlineText(first.children) === title) blocks = blocks.slice(1);
|
|
3021
|
+
const images = opts.images;
|
|
3022
|
+
const imports = images ? [...images.values()] : [];
|
|
3023
|
+
const head = [
|
|
3024
|
+
`import type { ReactNode } from 'react';`,
|
|
3025
|
+
`import {\n${[
|
|
3026
|
+
"type DesignSystem",
|
|
3027
|
+
"type DocEntry",
|
|
3028
|
+
"type DocMeta",
|
|
3029
|
+
...cover || opts.contents ? ["type DocPage"] : [],
|
|
3030
|
+
...opts.contents ? ["TableOfContents"] : [],
|
|
3031
|
+
"flow",
|
|
3032
|
+
"useDocPageCount",
|
|
3033
|
+
"useDocPageNumber"
|
|
3034
|
+
].map((name) => ` ${name},`).join("\n")}\n} from '@open-document/core';`,
|
|
3035
|
+
...imports.map((image) => `import ${image.ident} from './assets/${image.filename}';`)
|
|
3036
|
+
].join("\n");
|
|
3037
|
+
const styles = STYLES.replace("{DOC_TITLE}", jsxText(title));
|
|
3038
|
+
const coverPage = cover ? `const Cover: DocPage = () => (
|
|
3039
|
+
<div style={{ ...page, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
|
|
3040
|
+
${subtitle ? ` <p style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--od-accent)', margin: 0 }}>
|
|
3041
|
+
${jsxText(subtitle)}
|
|
3042
|
+
</p>\n` : ""} <h1 style={{ ...h1, fontSize: 'var(--od-size-title)', margin: '16px 0 12px' }} data-od-outline="skip">
|
|
3043
|
+
${jsxText(title)}
|
|
3044
|
+
</h1>
|
|
3045
|
+
${author ? ` <p style={{ color: 'var(--od-muted)', margin: 0 }}>${jsxText(author)}</p>\n` : ""} </div>
|
|
3046
|
+
);` : "";
|
|
3047
|
+
const contentsPage = opts.contents ? `const Contents: DocPage = () => (
|
|
3048
|
+
<div style={page}>
|
|
3049
|
+
<h1 style={h1} data-od-outline="skip">
|
|
3050
|
+
Contents
|
|
3051
|
+
</h1>
|
|
3052
|
+
<TableOfContents maxLevel={2} />
|
|
3053
|
+
</div>
|
|
3054
|
+
);` : "";
|
|
3055
|
+
const body = `const Body = flow(
|
|
3056
|
+
<>
|
|
3057
|
+
${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
|
|
3058
|
+
</>,
|
|
3059
|
+
{ footer: Footer },
|
|
3060
|
+
);`;
|
|
3061
|
+
const metaFields = [
|
|
3062
|
+
` title: ${jsString$1(title)},`,
|
|
3063
|
+
...subtitle ? [` subtitle: ${jsString$1(subtitle)},`] : [],
|
|
3064
|
+
...author ? [` author: ${jsString$1(author)},`] : [],
|
|
3065
|
+
...pageSize ? [` pageSize: ${jsString$1(pageSize)},`] : [],
|
|
3066
|
+
...orientation ? [` orientation: ${jsString$1(orientation)},`] : [],
|
|
3067
|
+
...theme ? [` theme: ${jsString$1(theme)},`] : [],
|
|
3068
|
+
...lang ? [` lang: ${jsString$1(lang)},`] : [],
|
|
3069
|
+
` createdAt: ${jsString$1(opts.createdAt)},`
|
|
3070
|
+
];
|
|
3071
|
+
const entries = [
|
|
3072
|
+
...cover ? ["Cover"] : [],
|
|
3073
|
+
...opts.contents ? ["Contents"] : [],
|
|
3074
|
+
"Body"
|
|
3075
|
+
];
|
|
3076
|
+
return {
|
|
3077
|
+
source: [
|
|
3078
|
+
head,
|
|
3079
|
+
"",
|
|
3080
|
+
DESIGN,
|
|
3081
|
+
"",
|
|
3082
|
+
styles,
|
|
3083
|
+
"",
|
|
3084
|
+
...coverPage ? [coverPage, ""] : [],
|
|
3085
|
+
...contentsPage ? [contentsPage, ""] : [],
|
|
3086
|
+
body,
|
|
3087
|
+
"",
|
|
3088
|
+
`export const meta: DocMeta = {\n${metaFields.join("\n")}\n};`,
|
|
3089
|
+
`export default [${entries.join(", ")}] satisfies DocEntry[];`,
|
|
3090
|
+
""
|
|
3091
|
+
].join("\n"),
|
|
3092
|
+
title,
|
|
3093
|
+
blockCount: blocks.length
|
|
3094
|
+
};
|
|
3095
|
+
}
|
|
3096
|
+
//#endregion
|
|
3097
|
+
//#region src/ops/import.ts
|
|
3098
|
+
const REMOTE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
|
|
3099
|
+
function slugify(value, fallback = "document") {
|
|
3100
|
+
const slug = value.normalize("NFKD").toLowerCase().replace(/['"]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
3101
|
+
return DOC_ID_RE.test(slug) ? slug : fallback;
|
|
3102
|
+
}
|
|
3103
|
+
function uniqueId(base, taken) {
|
|
3104
|
+
if (!taken.has(base)) return base;
|
|
3105
|
+
for (let n = 2; n < 1e3; n++) {
|
|
3106
|
+
const candidate = `${base}-${n}`;
|
|
3107
|
+
if (!taken.has(candidate)) return candidate;
|
|
3108
|
+
}
|
|
3109
|
+
throw new OpsError(409, `could not find a free id for ${base}`);
|
|
3110
|
+
}
|
|
3111
|
+
function identFor(index) {
|
|
3112
|
+
return `figure${index + 1}`;
|
|
3113
|
+
}
|
|
3114
|
+
/**
|
|
3115
|
+
* Reads markdown and writes a real open-doc document: `flow()` body, inline
|
|
3116
|
+
* styles, a cover, and any local images copied into the document's own assets
|
|
3117
|
+
* folder. Nothing about the result is special-cased — it is the same shape an
|
|
3118
|
+
* agent would have written by hand, and every editing surface works on it.
|
|
3119
|
+
*/
|
|
3120
|
+
async function importMarkdown(ctx, opts) {
|
|
3121
|
+
const sourceFile = opts.file ? path.resolve(ctx.userCwd, opts.file) : null;
|
|
3122
|
+
if (sourceFile && !sourceFile.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `file must sit inside the workspace: ${opts.file}`);
|
|
3123
|
+
let markdown = opts.markdown;
|
|
3124
|
+
if (markdown === void 0) {
|
|
3125
|
+
if (!sourceFile) throw new OpsError(400, "pass either `markdown` or `file`");
|
|
1282
3126
|
try {
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
3127
|
+
markdown = await fs.readFile(sourceFile, "utf8");
|
|
3128
|
+
} catch {
|
|
3129
|
+
throw new OpsError(404, `file not found: ${opts.file}`);
|
|
3130
|
+
}
|
|
3131
|
+
}
|
|
3132
|
+
if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
|
|
3133
|
+
const parsed = parseMarkdown(markdown);
|
|
3134
|
+
const language = opts.lang ?? (parsed.frontmatter.lang ? void 0 : detectLang(markdown));
|
|
3135
|
+
const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
|
|
3136
|
+
if (pageSize !== void 0 && !isPageSizeName(pageSize)) throw new OpsError(422, `unsupported pageSize \`${pageSize}\` — use ${PAGE_SIZE_NAMES.join(", ")}`);
|
|
3137
|
+
const orientation = opts.orientation ?? parsed.frontmatter.orientation;
|
|
3138
|
+
if (orientation !== void 0 && !isOrientation(orientation)) throw new OpsError(422, `unsupported orientation \`${orientation}\` — use ${ORIENTATIONS.join(", ")}`);
|
|
3139
|
+
const fallbackName = sourceFile ? path.basename(sourceFile).replace(/\.mdx?$/i, "") : "document";
|
|
3140
|
+
const requestedId = opts.docId ?? slugify(opts.title ?? parsed.frontmatter.title ?? fallbackName);
|
|
3141
|
+
if (opts.docId && !DOC_ID_RE.test(opts.docId)) throw new OpsError(400, `invalid document id: ${opts.docId}`);
|
|
3142
|
+
const docId = opts.docId ?? uniqueId(requestedId, new Set(await listDocIds$1(ctx)));
|
|
3143
|
+
const baseDir = sourceFile ? path.dirname(sourceFile) : ctx.userCwd;
|
|
3144
|
+
const images = /* @__PURE__ */ new Map();
|
|
3145
|
+
const missing = [];
|
|
3146
|
+
const staged = [];
|
|
3147
|
+
const usedNames = /* @__PURE__ */ new Set();
|
|
3148
|
+
for (const src of new Set(collectImageSources(parsed.blocks))) {
|
|
3149
|
+
if (REMOTE_RE.test(src)) continue;
|
|
3150
|
+
const from = path.resolve(baseDir, src.split(/[?#]/)[0]);
|
|
3151
|
+
if (!from.startsWith(ctx.userCwd + path.sep) || !existsSync(from)) {
|
|
3152
|
+
missing.push(src);
|
|
3153
|
+
continue;
|
|
3154
|
+
}
|
|
3155
|
+
const safe = validateAssetName(path.basename(from));
|
|
3156
|
+
if (!safe) {
|
|
3157
|
+
missing.push(src);
|
|
3158
|
+
continue;
|
|
1300
3159
|
}
|
|
3160
|
+
const filename = usedNames.has(safe) ? `${images.size + 1}-${safe}` : safe;
|
|
3161
|
+
usedNames.add(filename);
|
|
3162
|
+
images.set(src, {
|
|
3163
|
+
source: src,
|
|
3164
|
+
ident: identFor(images.size),
|
|
3165
|
+
filename
|
|
3166
|
+
});
|
|
3167
|
+
staged.push({
|
|
3168
|
+
from,
|
|
3169
|
+
filename
|
|
3170
|
+
});
|
|
3171
|
+
}
|
|
3172
|
+
const generated = generateDocumentSource(parsed, {
|
|
3173
|
+
docId,
|
|
3174
|
+
...opts.title !== void 0 ? { title: opts.title } : {},
|
|
3175
|
+
...opts.subtitle !== void 0 ? { subtitle: opts.subtitle } : {},
|
|
3176
|
+
...opts.author !== void 0 ? { author: opts.author } : {},
|
|
3177
|
+
...opts.theme !== void 0 ? { theme: opts.theme } : {},
|
|
3178
|
+
...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
|
|
3179
|
+
...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
|
|
3180
|
+
...language ? { lang: language } : {},
|
|
3181
|
+
...opts.cover !== void 0 ? { cover: opts.cover } : {},
|
|
3182
|
+
...opts.contents !== void 0 ? { contents: opts.contents } : {},
|
|
3183
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3184
|
+
images
|
|
1301
3185
|
});
|
|
3186
|
+
const created = await createDocument(ctx, docId, generated.source);
|
|
3187
|
+
if (staged.length > 0) {
|
|
3188
|
+
const assetsDir = path.join(ctx.docsRoot, docId, "assets");
|
|
3189
|
+
await fs.mkdir(assetsDir, { recursive: true });
|
|
3190
|
+
for (const { from, filename } of staged) await fs.copyFile(from, path.join(assetsDir, filename));
|
|
3191
|
+
}
|
|
3192
|
+
return {
|
|
3193
|
+
id: created.id,
|
|
3194
|
+
entry: created.entry,
|
|
3195
|
+
title: generated.title,
|
|
3196
|
+
blocks: generated.blockCount,
|
|
3197
|
+
assets: staged.map((asset) => asset.filename),
|
|
3198
|
+
missingAssets: missing
|
|
3199
|
+
};
|
|
1302
3200
|
}
|
|
1303
3201
|
//#endregion
|
|
1304
3202
|
//#region src/vite/themes-plugin.ts
|
|
@@ -1596,6 +3494,11 @@ async function fileDocument(ctx, docId, folderId) {
|
|
|
1596
3494
|
}
|
|
1597
3495
|
//#endregion
|
|
1598
3496
|
//#region src/ops/templates.ts
|
|
3497
|
+
var templates_exports = /* @__PURE__ */ __exportAll({
|
|
3498
|
+
createFromTemplate: () => createFromTemplate,
|
|
3499
|
+
listTemplates: () => listTemplates,
|
|
3500
|
+
suggestDocId: () => suggestDocId
|
|
3501
|
+
});
|
|
1599
3502
|
const TEMPLATE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
1600
3503
|
const MANIFEST = "template.json";
|
|
1601
3504
|
async function readTemplateDir(dir, name, source) {
|
|
@@ -1686,42 +3589,503 @@ async function createFromTemplate(ctx, opts) {
|
|
|
1686
3589
|
};
|
|
1687
3590
|
}
|
|
1688
3591
|
//#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"));
|
|
3592
|
+
//#region src/vite/routes/templates.ts
|
|
3593
|
+
/**
|
|
3594
|
+
* Tells the dev server a document was just written, instead of waiting for the
|
|
3595
|
+
* file watcher. On Linux the watcher can be late to a folder created and
|
|
3596
|
+
* filled in one go, and the browser, already sent to the new document, finds
|
|
3597
|
+
* none until it notices.
|
|
3598
|
+
*/
|
|
3599
|
+
function announceDocument(server, ctx, docId) {
|
|
3600
|
+
server.watcher.emit("add", path.join(ctx.docsRoot, docId, "index.tsx"));
|
|
3601
|
+
}
|
|
3602
|
+
function registerTemplateRoutes(server, ctx) {
|
|
3603
|
+
server.middlewares.use("/__templates", async (req, res, next) => {
|
|
3604
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
3605
|
+
const method = req.method ?? "GET";
|
|
3606
|
+
try {
|
|
3607
|
+
if (method === "GET" && url.pathname === "/") return json(res, 200, { templates: await listTemplates(ctx) });
|
|
3608
|
+
const create = url.pathname.match(/^\/([^/]+)\/create$/);
|
|
3609
|
+
if (create && method === "POST") {
|
|
3610
|
+
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
3611
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
3612
|
+
const body = await readBody(req);
|
|
3613
|
+
const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
3614
|
+
const docId = text(body.docId);
|
|
3615
|
+
const title = text(body.title);
|
|
3616
|
+
const result = await createFromTemplate(ctx, {
|
|
3617
|
+
template: decodeURIComponent(create[1]),
|
|
3618
|
+
...docId ? { docId } : {},
|
|
3619
|
+
...title ? { title } : {}
|
|
3620
|
+
});
|
|
3621
|
+
const folderId = text(body.folderId);
|
|
3622
|
+
if (folderId) await fileDocument(ctx, result.id, folderId);
|
|
3623
|
+
announceDocument(server, ctx, result.id);
|
|
3624
|
+
return json(res, 200, {
|
|
3625
|
+
ok: true,
|
|
3626
|
+
docId: result.id
|
|
3627
|
+
});
|
|
3628
|
+
}
|
|
3629
|
+
return next();
|
|
3630
|
+
} catch (err) {
|
|
3631
|
+
if (err instanceof OpsError) return json(res, err.status, { error: err.message });
|
|
3632
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
3633
|
+
}
|
|
3634
|
+
});
|
|
3635
|
+
}
|
|
3636
|
+
//#endregion
|
|
3637
|
+
//#region src/vite/routes/agent.ts
|
|
3638
|
+
function parseContext(raw) {
|
|
3639
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
3640
|
+
const r = raw;
|
|
3641
|
+
const ctx = {};
|
|
3642
|
+
if (typeof r.docId === "string" && DOC_ID_RE.test(r.docId)) ctx.docId = r.docId;
|
|
3643
|
+
if (typeof r.docTitle === "string") ctx.docTitle = r.docTitle.slice(0, 120);
|
|
3644
|
+
if (typeof r.pageNumber === "number" && Number.isFinite(r.pageNumber)) ctx.pageNumber = Math.max(1, Math.floor(r.pageNumber));
|
|
3645
|
+
if (typeof r.totalPages === "number" && Number.isFinite(r.totalPages)) ctx.totalPages = Math.max(1, Math.floor(r.totalPages));
|
|
3646
|
+
if (typeof r.pendingComments === "number" && Number.isFinite(r.pendingComments)) ctx.pendingComments = Math.max(0, Math.floor(r.pendingComments));
|
|
3647
|
+
if (r.newDoc === true) ctx.newDoc = true;
|
|
3648
|
+
const sel = r.selection;
|
|
3649
|
+
if (sel && typeof sel === "object") {
|
|
3650
|
+
const s = sel;
|
|
3651
|
+
if (typeof s.line === "number" && typeof s.column === "number") ctx.selection = {
|
|
3652
|
+
line: Math.max(1, Math.floor(s.line)),
|
|
3653
|
+
column: Math.max(0, Math.floor(s.column)),
|
|
3654
|
+
tagName: typeof s.tagName === "string" ? s.tagName.slice(0, 32) : "element",
|
|
3655
|
+
text: typeof s.text === "string" ? s.text.slice(0, 120) : ""
|
|
3656
|
+
};
|
|
3657
|
+
}
|
|
3658
|
+
return ctx;
|
|
3659
|
+
}
|
|
3660
|
+
const MODEL_RE = /^[\w.:[\]-]{1,80}$/;
|
|
3661
|
+
function parseModel(raw) {
|
|
3662
|
+
return typeof raw === "string" && MODEL_RE.test(raw) ? raw : null;
|
|
3663
|
+
}
|
|
3664
|
+
async function renamePlaceholderDoc(server, ctx, store, broadcast, turn) {
|
|
3665
|
+
const session = store.get(turn.sessionId);
|
|
3666
|
+
const docId = session?.docId;
|
|
3667
|
+
if (!session || !docId || !UNTITLED_DOC_ID_RE.test(docId)) return;
|
|
3668
|
+
const start = session.items.findIndex((i) => i.id === turn.userItemId);
|
|
3669
|
+
let marked = null;
|
|
3670
|
+
for (const item of session.items.slice(start + 1)) {
|
|
3671
|
+
if (item.kind !== "assistant") continue;
|
|
3672
|
+
const slug = extractDocSlug(item.text);
|
|
3673
|
+
if (slug === null) continue;
|
|
3674
|
+
marked = slug;
|
|
3675
|
+
store.updateItem(session.id, item.id, "assistant", { text: stripDocSlug(item.text) });
|
|
3676
|
+
}
|
|
3677
|
+
if (store.list().some((s) => s.docId === docId && s.status === "running")) return;
|
|
3678
|
+
const entry = resolveEntry(ctx, docId);
|
|
3679
|
+
if (!entry) return;
|
|
3680
|
+
let source;
|
|
3681
|
+
try {
|
|
3682
|
+
source = await fs.readFile(entry, "utf8");
|
|
3683
|
+
} catch {
|
|
3684
|
+
return;
|
|
3685
|
+
}
|
|
3686
|
+
const title = readMetaTitle(source);
|
|
3687
|
+
if (!title || title === "Untitled document") return;
|
|
3688
|
+
const desired = slugify(marked ?? "", "") || slugify(title, "");
|
|
3689
|
+
if (!desired || UNTITLED_DOC_ID_RE.test(desired)) return;
|
|
3690
|
+
if (store.list().some((s) => s.docId === docId && s.status === "running")) return;
|
|
3691
|
+
const renamed = await renameDocDir(ctx, docId, desired).catch(() => null);
|
|
3692
|
+
if (!renamed || renamed.id === docId) return;
|
|
3693
|
+
for (const s of store.list()) if (s.docId === docId) store.patch(s.id, { docId: renamed.id });
|
|
3694
|
+
announceDocument(server, ctx, renamed.id);
|
|
3695
|
+
broadcast({
|
|
3696
|
+
type: "doc-renamed",
|
|
3697
|
+
from: docId,
|
|
3698
|
+
to: renamed.id
|
|
3699
|
+
});
|
|
3700
|
+
}
|
|
3701
|
+
function parseRespond(raw) {
|
|
3702
|
+
if (!raw || typeof raw !== "object") return null;
|
|
3703
|
+
const r = raw;
|
|
3704
|
+
if (r.cancel === true) return { cancel: true };
|
|
3705
|
+
if (typeof r.allow === "boolean") return { allow: r.allow };
|
|
3706
|
+
if (r.answers && typeof r.answers === "object") {
|
|
3707
|
+
const answers = {};
|
|
3708
|
+
for (const [k, v] of Object.entries(r.answers)) if (typeof v === "string") answers[k] = v;
|
|
3709
|
+
return { answers };
|
|
3710
|
+
}
|
|
3711
|
+
return null;
|
|
3712
|
+
}
|
|
3713
|
+
function parseTurnSettings(raw) {
|
|
3714
|
+
const settings = {};
|
|
3715
|
+
const context = parseContext(raw.context);
|
|
3716
|
+
if (context) settings.context = context;
|
|
3717
|
+
if (typeof raw.autoApprove === "boolean") settings.autoApprove = raw.autoApprove;
|
|
3718
|
+
if ("model" in raw) settings.model = parseModel(raw.model);
|
|
3719
|
+
if ("effort" in raw) settings.effort = isAgentEffort(raw.effort) ? raw.effort : null;
|
|
3720
|
+
return settings;
|
|
3721
|
+
}
|
|
3722
|
+
const AGENT_BODY_LIMIT = 1048576;
|
|
3723
|
+
function registerAgentRoutes(server, ctx) {
|
|
3724
|
+
const providers = createProviders();
|
|
3725
|
+
const store = createSessionStore({ file: path.join(ctx.userCwd, "node_modules", ".open-doc", "agent-sessions.json") });
|
|
3726
|
+
const streams = /* @__PURE__ */ new Set();
|
|
3727
|
+
const broadcast = (event) => {
|
|
3728
|
+
const frame = `data: ${JSON.stringify(event)}\n\n`;
|
|
3729
|
+
for (const stream of streams) stream.write(frame);
|
|
3730
|
+
};
|
|
3731
|
+
const heartbeat = setInterval(() => {
|
|
3732
|
+
for (const stream of streams) stream.write(": ping\n\n");
|
|
3733
|
+
}, 25e3);
|
|
3734
|
+
heartbeat.unref();
|
|
3735
|
+
const runner = createAgentRunner({
|
|
3736
|
+
userCwd: ctx.userCwd,
|
|
3737
|
+
writableRoots: [ctx.docsRoot, ctx.globalAssetsRoot],
|
|
3738
|
+
promptOptions: () => {
|
|
3739
|
+
const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
|
|
3740
|
+
return {
|
|
3741
|
+
docsDir: ctx.docsDir,
|
|
3742
|
+
...origin ? { origin } : {}
|
|
3743
|
+
};
|
|
3744
|
+
},
|
|
3745
|
+
store,
|
|
3746
|
+
providers,
|
|
3747
|
+
onTurnEnd: (turn) => renamePlaceholderDoc(server, ctx, store, broadcast, turn)
|
|
3748
|
+
});
|
|
3749
|
+
store.subscribe(broadcast);
|
|
3750
|
+
server.httpServer?.on("close", () => {
|
|
3751
|
+
clearInterval(heartbeat);
|
|
3752
|
+
for (const stream of streams) stream.end();
|
|
3753
|
+
runner.stopAll();
|
|
3754
|
+
store.flush();
|
|
3755
|
+
});
|
|
3756
|
+
const installsInFlight = /* @__PURE__ */ new Map();
|
|
3757
|
+
server.middlewares.use("/__agent", async (req, res, next) => {
|
|
3758
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
3759
|
+
const method = req.method ?? "GET";
|
|
3760
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
3761
|
+
const enabled = isLoopbackRequest(req);
|
|
3762
|
+
try {
|
|
3763
|
+
if (method === "GET" && url.pathname === "/status") {
|
|
3764
|
+
res.setHeader("cache-control", "no-store");
|
|
3765
|
+
if (!enabled) return json(res, 200, {
|
|
3766
|
+
enabled: false,
|
|
3767
|
+
packageManager: "",
|
|
3768
|
+
providers: []
|
|
3769
|
+
});
|
|
3770
|
+
const pm = await detectPackageManager(ctx.userCwd);
|
|
3771
|
+
return json(res, 200, await agentStatus(ctx.userCwd, providers, pm));
|
|
3772
|
+
}
|
|
3773
|
+
if (!enabled) return json(res, 404, { error: "agent panel disabled" });
|
|
3774
|
+
if (method === "GET" && url.pathname === "/events") {
|
|
3775
|
+
res.writeHead(200, {
|
|
3776
|
+
"content-type": "text/event-stream",
|
|
3777
|
+
"cache-control": "no-store",
|
|
3778
|
+
connection: "keep-alive"
|
|
3779
|
+
});
|
|
3780
|
+
res.write(": connected\n\n");
|
|
3781
|
+
streams.add(res);
|
|
3782
|
+
const drop = () => streams.delete(res);
|
|
3783
|
+
res.on("close", drop);
|
|
3784
|
+
res.on("error", drop);
|
|
3785
|
+
return;
|
|
3786
|
+
}
|
|
3787
|
+
if (method === "POST" && url.pathname === "/install") {
|
|
3788
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
3789
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
3790
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
3791
|
+
if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
|
|
3792
|
+
const provider = providers[body.provider];
|
|
3793
|
+
const pm = await detectPackageManager(ctx.userCwd);
|
|
3794
|
+
const pkg = provider.sdkPackage;
|
|
3795
|
+
let install = installsInFlight.get(pkg);
|
|
3796
|
+
if (!install) {
|
|
3797
|
+
install = installSdk(pm, pkg, ctx.userCwd).finally(() => installsInFlight.delete(pkg));
|
|
3798
|
+
installsInFlight.set(pkg, install);
|
|
3799
|
+
}
|
|
3800
|
+
await install;
|
|
3801
|
+
return json(res, 200, { ok: true });
|
|
3802
|
+
}
|
|
3803
|
+
if (method === "GET" && url.pathname === "/sessions") {
|
|
3804
|
+
res.setHeader("cache-control", "no-store");
|
|
3805
|
+
return json(res, 200, { sessions: store.list() });
|
|
3806
|
+
}
|
|
3807
|
+
if (method === "POST" && url.pathname === "/sessions") {
|
|
3808
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
3809
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
3810
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
3811
|
+
if (!isAgentProviderId(body.provider)) return json(res, 400, { error: "invalid provider" });
|
|
3812
|
+
const docId = typeof body.docId === "string" && DOC_ID_RE.test(body.docId) ? body.docId : null;
|
|
3813
|
+
return json(res, 200, store.create(body.provider, docId));
|
|
3814
|
+
}
|
|
3815
|
+
if (segments[0] === "sessions" && segments[1]) {
|
|
3816
|
+
const id = segments[1];
|
|
3817
|
+
const action = segments[2];
|
|
3818
|
+
const session = store.get(id);
|
|
3819
|
+
if (!session) return json(res, 404, { error: "session not found" });
|
|
3820
|
+
if (method === "GET" && !action) {
|
|
3821
|
+
res.setHeader("cache-control", "no-store");
|
|
3822
|
+
return json(res, 200, session);
|
|
3823
|
+
}
|
|
3824
|
+
if (method === "DELETE" && !action) {
|
|
3825
|
+
const guard = validateMutationRequest(req);
|
|
3826
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
3827
|
+
runner.stop(id);
|
|
3828
|
+
store.remove(id);
|
|
3829
|
+
return json(res, 200, { ok: true });
|
|
3830
|
+
}
|
|
3831
|
+
if (method === "POST" && action === "messages") {
|
|
3832
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
3833
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
3834
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
3835
|
+
if (typeof body.text !== "string" || !body.text.trim()) return json(res, 400, { error: "missing text" });
|
|
3836
|
+
if (runner.isRunning(id)) return json(res, 409, { error: "session is already running" });
|
|
3837
|
+
if (body.edit !== void 0 && !session.items.some((i) => i.id === body.edit && i.kind === "user")) return json(res, 400, { error: "unknown message" });
|
|
3838
|
+
await runner.send(id, {
|
|
3839
|
+
text: body.text,
|
|
3840
|
+
context: parseContext(body.context),
|
|
3841
|
+
autoApprove: body.autoApprove === true,
|
|
3842
|
+
model: parseModel(body.model),
|
|
3843
|
+
effort: isAgentEffort(body.effort) ? body.effort : null,
|
|
3844
|
+
edit: typeof body.edit === "string" ? body.edit : void 0
|
|
3845
|
+
});
|
|
3846
|
+
return json(res, 202, { ok: true });
|
|
3847
|
+
}
|
|
3848
|
+
if (method === "POST" && action === "stop") {
|
|
3849
|
+
const guard = validateMutationRequest(req);
|
|
3850
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
3851
|
+
return json(res, 200, { ok: runner.stop(id) });
|
|
3852
|
+
}
|
|
3853
|
+
if (method === "POST" && action === "respond") {
|
|
3854
|
+
const guard = validateMutationRequest(req, { requireJsonBody: true });
|
|
3855
|
+
if (!guard.ok) return json(res, guard.status, { error: guard.error });
|
|
3856
|
+
const body = await readBody(req, AGENT_BODY_LIMIT);
|
|
3857
|
+
const payload = parseRespond(body);
|
|
3858
|
+
if (typeof body.itemId !== "string" || !payload) return json(res, 400, { error: "invalid response" });
|
|
3859
|
+
const ok = runner.respond(id, body.itemId, payload, parseTurnSettings(body));
|
|
3860
|
+
return json(res, ok ? 200 : 409, ok ? { ok } : { error: "nothing pending" });
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
next();
|
|
3864
|
+
} catch (err) {
|
|
3865
|
+
if (err instanceof BodyTooLargeError) return json(res, 413, { error: err.message });
|
|
3866
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
3867
|
+
}
|
|
3868
|
+
});
|
|
3869
|
+
}
|
|
3870
|
+
//#endregion
|
|
3871
|
+
//#region src/vite/routes/assets.ts
|
|
3872
|
+
async function listDocIds(docsRoot) {
|
|
3873
|
+
try {
|
|
3874
|
+
return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
|
|
3875
|
+
} catch {
|
|
3876
|
+
return [];
|
|
3877
|
+
}
|
|
1698
3878
|
}
|
|
1699
|
-
function
|
|
1700
|
-
|
|
3879
|
+
async function readDocSource(docsRoot, docId) {
|
|
3880
|
+
const entry = resolveDocEntry(docsRoot, docId);
|
|
3881
|
+
if (!entry) return null;
|
|
3882
|
+
try {
|
|
3883
|
+
return await fs.readFile(entry, "utf8");
|
|
3884
|
+
} catch {
|
|
3885
|
+
return null;
|
|
3886
|
+
}
|
|
3887
|
+
}
|
|
3888
|
+
function registerAssetRoutes(server, ctx) {
|
|
3889
|
+
server.middlewares.use("/__assets", async (req, res, next) => {
|
|
1701
3890
|
const url = new URL(req.url ?? "/", "http://local");
|
|
1702
3891
|
const method = req.method ?? "GET";
|
|
1703
3892
|
try {
|
|
1704
|
-
|
|
1705
|
-
const
|
|
1706
|
-
|
|
3893
|
+
const listMatch = url.pathname.match(/^\/([^/]+)\/?$/);
|
|
3894
|
+
const fileMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)$/);
|
|
3895
|
+
const usagesMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/usages$/);
|
|
3896
|
+
if (usagesMatch && method === "GET") {
|
|
3897
|
+
const scope = decodeURIComponent(usagesMatch[1]);
|
|
3898
|
+
const filename = decodeURIComponent(usagesMatch[2]);
|
|
3899
|
+
if (!validateAssetName(filename)) return json(res, 400, { error: "invalid path" });
|
|
3900
|
+
const isGlobal = scope === GLOBAL_SCOPE;
|
|
3901
|
+
if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
|
|
3902
|
+
const importPath = assetImportPath(scope, filename);
|
|
3903
|
+
const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
|
|
3904
|
+
const usages = [];
|
|
3905
|
+
let totalCount = 0;
|
|
3906
|
+
for (const docId of docIds) {
|
|
3907
|
+
const source = await readDocSource(ctx.docsRoot, docId);
|
|
3908
|
+
if (source === null) continue;
|
|
3909
|
+
const count = countAssetUsages(source, importPath);
|
|
3910
|
+
if (count > 0) {
|
|
3911
|
+
usages.push({
|
|
3912
|
+
docId,
|
|
3913
|
+
count
|
|
3914
|
+
});
|
|
3915
|
+
totalCount += count;
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
return json(res, 200, {
|
|
3919
|
+
usages,
|
|
3920
|
+
totalCount
|
|
3921
|
+
});
|
|
3922
|
+
}
|
|
3923
|
+
if (listMatch && method === "GET") {
|
|
3924
|
+
const scope = decodeURIComponent(listMatch[1]);
|
|
3925
|
+
const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
3926
|
+
if (!scopedDir) return json(res, 400, { error: "invalid scope" });
|
|
3927
|
+
let entries;
|
|
3928
|
+
try {
|
|
3929
|
+
entries = await fs.readdir(scopedDir);
|
|
3930
|
+
} catch (err) {
|
|
3931
|
+
if (err.code === "ENOENT") return json(res, 200, { assets: [] });
|
|
3932
|
+
throw err;
|
|
3933
|
+
}
|
|
3934
|
+
const assets = [];
|
|
3935
|
+
for (const name of entries) {
|
|
3936
|
+
if (!validateAssetName(name)) continue;
|
|
3937
|
+
const stat = await fs.stat(path.join(scopedDir, name));
|
|
3938
|
+
if (!stat.isFile()) continue;
|
|
3939
|
+
assets.push({
|
|
3940
|
+
name,
|
|
3941
|
+
size: stat.size,
|
|
3942
|
+
createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
|
|
3943
|
+
mtime: stat.mtimeMs,
|
|
3944
|
+
mime: mimeForFilename(name),
|
|
3945
|
+
url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(name)}`,
|
|
3946
|
+
importPath: assetImportPath(scope, name),
|
|
3947
|
+
unused: true
|
|
3948
|
+
});
|
|
3949
|
+
}
|
|
3950
|
+
assets.sort((a, b) => a.name.localeCompare(b.name));
|
|
3951
|
+
if (assets.length > 0) {
|
|
3952
|
+
const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
|
|
3953
|
+
const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
|
|
3954
|
+
const paths = assets.map((a) => a.importPath);
|
|
3955
|
+
for (const docId of scanIds) {
|
|
3956
|
+
const source = await readDocSource(ctx.docsRoot, docId);
|
|
3957
|
+
if (source === null) continue;
|
|
3958
|
+
for (const p of findReferencedAssets(source, paths)) {
|
|
3959
|
+
const asset = pathToAsset.get(p);
|
|
3960
|
+
if (asset) asset.unused = false;
|
|
3961
|
+
}
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
return json(res, 200, { assets });
|
|
3965
|
+
}
|
|
3966
|
+
if (fileMatch) {
|
|
3967
|
+
const scope = decodeURIComponent(fileMatch[1]);
|
|
3968
|
+
const filename = decodeURIComponent(fileMatch[2]);
|
|
3969
|
+
const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
|
|
3970
|
+
if (!file) return json(res, 400, { error: "invalid path" });
|
|
3971
|
+
if (method === "GET") try {
|
|
3972
|
+
const buf = await fs.readFile(file);
|
|
3973
|
+
res.statusCode = 200;
|
|
3974
|
+
res.setHeader("content-type", mimeForFilename(filename));
|
|
3975
|
+
res.setHeader("cache-control", "no-store");
|
|
3976
|
+
res.end(buf);
|
|
3977
|
+
return;
|
|
3978
|
+
} catch (err) {
|
|
3979
|
+
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
3980
|
+
throw err;
|
|
3981
|
+
}
|
|
3982
|
+
if (method === "POST") {
|
|
3983
|
+
const requestCheck = validateMutationRequest(req);
|
|
3984
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
3985
|
+
const overwrite = url.searchParams.get("overwrite") === "1";
|
|
3986
|
+
const lenHeader = req.headers["content-length"];
|
|
3987
|
+
const len = typeof lenHeader === "string" ? Number(lenHeader) : NaN;
|
|
3988
|
+
if (Number.isFinite(len) && len > 26214400) return json(res, 413, { error: "file too large" });
|
|
3989
|
+
if (!overwrite) try {
|
|
3990
|
+
await fs.access(file);
|
|
3991
|
+
return json(res, 409, { error: "asset exists" });
|
|
3992
|
+
} catch {}
|
|
3993
|
+
const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
3994
|
+
if (!scopedDir) return json(res, 400, { error: "invalid scope" });
|
|
3995
|
+
await fs.mkdir(scopedDir, { recursive: true });
|
|
3996
|
+
const chunks = [];
|
|
3997
|
+
let total = 0;
|
|
3998
|
+
let oversized = false;
|
|
3999
|
+
await new Promise((resolve, reject) => {
|
|
4000
|
+
req.on("data", (c) => {
|
|
4001
|
+
total += c.length;
|
|
4002
|
+
if (total > 26214400) {
|
|
4003
|
+
oversized = true;
|
|
4004
|
+
req.destroy();
|
|
4005
|
+
return;
|
|
4006
|
+
}
|
|
4007
|
+
chunks.push(c);
|
|
4008
|
+
});
|
|
4009
|
+
req.on("end", () => resolve());
|
|
4010
|
+
req.on("error", reject);
|
|
4011
|
+
});
|
|
4012
|
+
if (oversized) return json(res, 413, { error: "file too large" });
|
|
4013
|
+
await fs.writeFile(file, Buffer.concat(chunks));
|
|
4014
|
+
const stat = await fs.stat(file);
|
|
4015
|
+
return json(res, 200, {
|
|
4016
|
+
ok: true,
|
|
4017
|
+
name: filename,
|
|
4018
|
+
size: stat.size,
|
|
4019
|
+
createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
|
|
4020
|
+
mtime: stat.mtimeMs,
|
|
4021
|
+
mime: mimeForFilename(filename),
|
|
4022
|
+
url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
|
|
4023
|
+
importPath: assetImportPath(scope, filename)
|
|
4024
|
+
});
|
|
4025
|
+
}
|
|
4026
|
+
if (method === "PATCH") {
|
|
4027
|
+
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
4028
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4029
|
+
const target = validateAssetName((await readBody(req)).name);
|
|
4030
|
+
if (!target) return json(res, 400, { error: "invalid name" });
|
|
4031
|
+
if (target === filename) return json(res, 200, {
|
|
4032
|
+
ok: true,
|
|
4033
|
+
name: filename
|
|
4034
|
+
});
|
|
4035
|
+
const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
|
|
4036
|
+
if (!dest) return json(res, 400, { error: "invalid name" });
|
|
4037
|
+
try {
|
|
4038
|
+
await fs.access(dest);
|
|
4039
|
+
return json(res, 409, { error: "target exists" });
|
|
4040
|
+
} catch {}
|
|
4041
|
+
try {
|
|
4042
|
+
await fs.rename(file, dest);
|
|
4043
|
+
} catch (err) {
|
|
4044
|
+
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
4045
|
+
throw err;
|
|
4046
|
+
}
|
|
4047
|
+
return json(res, 200, {
|
|
4048
|
+
ok: true,
|
|
4049
|
+
name: target
|
|
4050
|
+
});
|
|
4051
|
+
}
|
|
4052
|
+
if (method === "DELETE") {
|
|
4053
|
+
const requestCheck = validateMutationRequest(req);
|
|
4054
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4055
|
+
try {
|
|
4056
|
+
await fs.unlink(file);
|
|
4057
|
+
} catch (err) {
|
|
4058
|
+
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
4059
|
+
throw err;
|
|
4060
|
+
}
|
|
4061
|
+
return json(res, 200, { ok: true });
|
|
4062
|
+
}
|
|
4063
|
+
}
|
|
4064
|
+
return next();
|
|
4065
|
+
} catch (err) {
|
|
4066
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
4067
|
+
}
|
|
4068
|
+
});
|
|
4069
|
+
}
|
|
4070
|
+
//#endregion
|
|
4071
|
+
//#region src/vite/routes/changes.ts
|
|
4072
|
+
function registerChangesRoutes(server, ctx) {
|
|
4073
|
+
server.middlewares.use("/__changes", async (req, res, next) => {
|
|
4074
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
4075
|
+
const method = req.method ?? "GET";
|
|
4076
|
+
try {
|
|
4077
|
+
if (method === "GET" && url.pathname === "/") return json(res, 200, await readChanges(ctx, url.searchParams.get("docId") ?? "", url.searchParams.get("since") || "HEAD"));
|
|
4078
|
+
if (method === "GET" && url.pathname === "/revisions") return json(res, 200, { revisions: await listRevisions(ctx, url.searchParams.get("docId") ?? "") });
|
|
4079
|
+
if (method === "POST" && url.pathname === "/revert") {
|
|
1707
4080
|
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
1708
4081
|
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
1709
4082
|
const body = await readBody(req);
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
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
|
-
});
|
|
4083
|
+
if (typeof body.docId !== "string" || typeof body.file !== "string" || typeof body.hunk !== "string") return json(res, 400, { error: "invalid payload" });
|
|
4084
|
+
return json(res, 200, await revertChange(ctx, body.docId, {
|
|
4085
|
+
file: body.file,
|
|
4086
|
+
hunk: body.hunk,
|
|
4087
|
+
...typeof body.since === "string" ? { since: body.since } : {}
|
|
4088
|
+
}));
|
|
1725
4089
|
}
|
|
1726
4090
|
return next();
|
|
1727
4091
|
} catch (err) {
|
|
@@ -1739,6 +4103,16 @@ function registerDocRoutes(server, ctx) {
|
|
|
1739
4103
|
try {
|
|
1740
4104
|
const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
|
|
1741
4105
|
const idMatch = url.pathname.match(/^\/([^/]+)$/);
|
|
4106
|
+
if (url.pathname === "/" && method === "POST") {
|
|
4107
|
+
const requestCheck = validateMutationRequest(req);
|
|
4108
|
+
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
4109
|
+
const result = await createBlankDocument(ctx);
|
|
4110
|
+
announceDocument(server, ctx, result.id);
|
|
4111
|
+
return json(res, 200, {
|
|
4112
|
+
ok: true,
|
|
4113
|
+
docId: result.id
|
|
4114
|
+
});
|
|
4115
|
+
}
|
|
1742
4116
|
if (duplicateMatch && method === "POST") {
|
|
1743
4117
|
const requestCheck = validateMutationRequest(req);
|
|
1744
4118
|
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
@@ -3659,6 +6033,7 @@ function apiPlugin(opts) {
|
|
|
3659
6033
|
registerEditRoutes(server, ctx);
|
|
3660
6034
|
registerChangesRoutes(server, ctx);
|
|
3661
6035
|
registerTemplateRoutes(server, ctx);
|
|
6036
|
+
if (opts.agent !== false) registerAgentRoutes(server, ctx);
|
|
3662
6037
|
}
|
|
3663
6038
|
};
|
|
3664
6039
|
}
|
|
@@ -4319,6 +6694,7 @@ async function createViteConfig(opts) {
|
|
|
4319
6694
|
return {
|
|
4320
6695
|
base: config.base ?? "/",
|
|
4321
6696
|
root: APP_ROOT,
|
|
6697
|
+
cacheDir: path.join(userCwd, "node_modules", ".vite", opts.headless ? "open-doc-headless" : "open-doc"),
|
|
4322
6698
|
configFile: false,
|
|
4323
6699
|
envDir: userCwd,
|
|
4324
6700
|
plugins: [
|
|
@@ -4347,7 +6723,8 @@ async function createViteConfig(opts) {
|
|
|
4347
6723
|
userCwd,
|
|
4348
6724
|
docsDir,
|
|
4349
6725
|
assetsDir,
|
|
4350
|
-
coreVersion: CORE_VERSION
|
|
6726
|
+
coreVersion: CORE_VERSION,
|
|
6727
|
+
agent: !opts.headless && config.agent?.enabled !== false
|
|
4351
6728
|
}),
|
|
4352
6729
|
...opts.headless ? [] : [currentPlugin({
|
|
4353
6730
|
userCwd,
|
|
@@ -4405,4 +6782,4 @@ async function createViteConfig(opts) {
|
|
|
4405
6782
|
};
|
|
4406
6783
|
}
|
|
4407
6784
|
//#endregion
|
|
4408
|
-
export {
|
|
6785
|
+
export { docDir as A, revertChange as C, OpsError as D, withFileLock as E, renameDocument as F, resolveEntry as I, writeDocument as L, listDocIds$1 as M, listDocuments as N, createDocument as O, readDocument as P, makeContext as R, readChanges as S, hashSource as T, readTheme as _, writeText as a, slugify as b, listTemplates as c, deleteAsset as d, fileDocument as f, listThemes as g, listFolders as h, writeEdits as i, duplicateDocument as j, deleteDocument 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, assertExpectedSource as w, listRevisions as x, importMarkdown as y };
|