inkmap-mcp 0.3.7 → 0.3.10

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.
@@ -1,5 +1,5 @@
1
1
  // packages/antigravity/src/main.mjs
2
- import { execFile } from "node:child_process";
2
+ import { execFile, spawn as spawn2 } from "node:child_process";
3
3
  import { createHash as createHash2 } from "node:crypto";
4
4
  import { readFileSync, readdirSync } from "node:fs";
5
5
  import { lstat as lstat3, readdir as readdir2, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
@@ -398,6 +398,52 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
398
398
  };
399
399
  poll();
400
400
  }
401
+ async function sendPendingTelemetry() {
402
+ if (disposed || !pendingEvents.size)
403
+ return;
404
+ let origin;
405
+ try {
406
+ origin = billingOrigin(getOrigin());
407
+ } catch {
408
+ return;
409
+ }
410
+ if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
411
+ if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
412
+ return;
413
+ const customHome = process.env.INKMAP_HOME || "";
414
+ if (customHome && (customHome.startsWith("/tmp/") || customHome.startsWith("/private/tmp/") || customHome.includes("/var/folders/") || customHome.includes("inkmap-npm-isolated-") || customHome.includes("inkmap-antigravity-mcp-") || customHome.includes("inkmap-local-editor-") || customHome.includes("inkmap-harness-"))) {
415
+ return;
416
+ }
417
+ }
418
+ const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
419
+ if (disposed || !id || !pendingEvents.size)
420
+ return;
421
+ await (trial ??= startTrial());
422
+ const events = {};
423
+ for (const [k, v] of pendingEvents.entries())
424
+ events[k] = v;
425
+ pendingEvents.clear();
426
+ const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
427
+ const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
428
+ const hostName = detectedHost || inferNodeHost();
429
+ await fetch(origin + "/billing/v1/telemetry", {
430
+ method: "POST",
431
+ headers: { "content-type": "application/json" },
432
+ redirect: "error",
433
+ body: JSON.stringify({
434
+ product: PRODUCT.id,
435
+ installId: id,
436
+ host: hostName,
437
+ os,
438
+ version: "0.3.10",
439
+ locale: clientLocale(),
440
+ tier,
441
+ events
442
+ }),
443
+ signal: AbortSignal.timeout(5e3)
444
+ }).catch(() => {
445
+ });
446
+ }
401
447
  return {
402
448
  async state() {
403
449
  await (trial ??= startTrial());
@@ -713,55 +759,17 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
713
759
  return;
714
760
  telemetryTimer = setTimeout(() => {
715
761
  telemetryTimer = void 0;
716
- void (async () => {
717
- if (disposed || !pendingEvents.size)
718
- return;
719
- let origin;
720
- try {
721
- origin = billingOrigin(getOrigin());
722
- } catch {
723
- return;
724
- }
725
- if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
726
- if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
727
- return;
728
- const customHome = process.env.INKMAP_HOME || "";
729
- if (customHome && (customHome.startsWith("/tmp/") || customHome.startsWith("/private/tmp/") || customHome.includes("/var/folders/") || customHome.includes("inkmap-npm-isolated-") || customHome.includes("inkmap-antigravity-mcp-") || customHome.includes("inkmap-local-editor-") || customHome.includes("inkmap-harness-"))) {
730
- return;
731
- }
732
- }
733
- const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
734
- if (disposed || !id || !pendingEvents.size)
735
- return;
736
- await (trial ??= startTrial());
737
- const events = {};
738
- for (const [k, v] of pendingEvents.entries())
739
- events[k] = v;
740
- pendingEvents.clear();
741
- const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
742
- const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
743
- const hostName = detectedHost || inferNodeHost();
744
- await fetch(origin + "/billing/v1/telemetry", {
745
- method: "POST",
746
- headers: { "content-type": "application/json" },
747
- redirect: "error",
748
- body: JSON.stringify({
749
- product: PRODUCT.id,
750
- installId: id,
751
- host: hostName,
752
- os,
753
- version: "0.3.7",
754
- locale: clientLocale(),
755
- tier,
756
- events
757
- }),
758
- signal: AbortSignal.timeout(5e3)
759
- }).catch(() => {
760
- });
761
- })();
762
+ void sendPendingTelemetry();
762
763
  }, 800);
763
764
  telemetryTimer.unref();
764
765
  },
766
+ async flushTelemetry() {
767
+ if (telemetryTimer) {
768
+ clearTimeout(telemetryTimer);
769
+ telemetryTimer = void 0;
770
+ }
771
+ await sendPendingTelemetry();
772
+ },
765
773
  dispose() {
766
774
  disposed = true;
767
775
  stopMagicPoll();
@@ -784,6 +792,10 @@ function inferNodeHost() {
784
792
  return "cursor";
785
793
  if (app.includes("windsurf"))
786
794
  return "windsurf";
795
+ if (app.includes("trae"))
796
+ return "trae";
797
+ if (app.includes("qoder"))
798
+ return "qoder";
787
799
  return "vscode";
788
800
  }
789
801
  return "cli";
@@ -857,12 +869,113 @@ async function localTrialDeadline() {
857
869
  var AD_TTL = 6 * 60 * 60 * 1e3;
858
870
 
859
871
  // packages/cli/dist/server.js
872
+ import { spawn } from "node:child_process";
860
873
  import { createHash, randomBytes } from "node:crypto";
861
874
  import { watch } from "node:fs";
862
875
  import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
876
+ import { createServer } from "node:http";
863
877
  import { homedir as homedir2 } from "node:os";
864
878
  import { basename, delimiter, dirname as dirname2, extname, isAbsolute, join as join2, normalize, relative, resolve, sep } from "node:path";
879
+ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
880
+ ".git",
881
+ ".hg",
882
+ ".svn",
883
+ "node_modules",
884
+ "dist",
885
+ "dist-codex",
886
+ "dist-workbuddy",
887
+ "build",
888
+ "out",
889
+ ".next",
890
+ ".nuxt",
891
+ ".agents",
892
+ ".agent",
893
+ ".gemini",
894
+ ".codex",
895
+ ".venv",
896
+ "venv",
897
+ "target",
898
+ "coverage",
899
+ ".tmp"
900
+ ]);
901
+ function insideRoot(root, target) {
902
+ if (root === target)
903
+ return true;
904
+ const rel = relative(root, target);
905
+ return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep));
906
+ }
907
+ async function findProjectRoot(filePath) {
908
+ let cur = dirname2(filePath);
909
+ const home = await realpath(homedir2()).catch(() => homedir2());
910
+ while (cur && cur !== dirname2(cur) && cur !== home) {
911
+ try {
912
+ await lstat(join2(cur, ".git"));
913
+ return cur;
914
+ } catch {
915
+ }
916
+ cur = dirname2(cur);
917
+ }
918
+ return dirname2(filePath);
919
+ }
920
+ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
921
+ const found = [];
922
+ async function walk(dir, depth) {
923
+ if (depth > maxDepth || found.length >= maxFiles)
924
+ return;
925
+ let entries;
926
+ try {
927
+ entries = await readdir(dir, { withFileTypes: true });
928
+ } catch {
929
+ return;
930
+ }
931
+ for (const entry of entries) {
932
+ if (found.length >= maxFiles)
933
+ break;
934
+ if (entry.name.startsWith("."))
935
+ continue;
936
+ const full = join2(dir, entry.name);
937
+ if (entry.isDirectory()) {
938
+ if (!SKIP_SCAN_DIRS.has(entry.name))
939
+ await walk(full, depth + 1);
940
+ } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
941
+ try {
942
+ const st = await lstat(full);
943
+ if (st.isFile() && st.size <= 5 * 1024 * 1024) {
944
+ const real = await realpath(full);
945
+ if (real === full && insideRoot(rootDir, real))
946
+ found.push(real);
947
+ }
948
+ } catch {
949
+ }
950
+ }
951
+ }
952
+ }
953
+ await walk(rootDir, 0);
954
+ found.sort((a, b) => {
955
+ const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
956
+ const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
957
+ if (aM !== bM)
958
+ return aM - bM;
959
+ return a.localeCompare(b);
960
+ });
961
+ return found;
962
+ }
865
963
  var MAX_BODY = 20 * 1024 * 1024;
964
+ var TYPES = {
965
+ ".html": "text/html; charset=utf-8",
966
+ ".js": "text/javascript; charset=utf-8",
967
+ ".css": "text/css; charset=utf-8",
968
+ ".svg": "image/svg+xml",
969
+ ".png": "image/png",
970
+ ".jpg": "image/jpeg",
971
+ ".jpeg": "image/jpeg",
972
+ ".gif": "image/gif",
973
+ ".webp": "image/webp",
974
+ ".woff2": "font/woff2",
975
+ ".woff": "font/woff",
976
+ ".ttf": "font/ttf",
977
+ ".json": "application/json"
978
+ };
866
979
  var hash = (s) => createHash("sha1").update(s).digest("hex");
867
980
  function docName(path) {
868
981
  return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
@@ -916,6 +1029,428 @@ async function fileSource(file, log = () => {
916
1029
  writeView: (state) => writeDiskViewState(path, state)
917
1030
  };
918
1031
  }
1032
+ function within(root, rel) {
1033
+ const base = root.endsWith(sep) ? root : root + sep;
1034
+ const full = normalize(join2(root, decodeURIComponent(rel)));
1035
+ return full.startsWith(base) ? full : null;
1036
+ }
1037
+ async function openBrowserWindow(url) {
1038
+ if (process.env.INKMAP_NO_OPEN === "1" || !/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+\//.test(url))
1039
+ return;
1040
+ const run = (cmd, args) => new Promise((done) => {
1041
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
1042
+ child.on("error", () => done(false));
1043
+ child.on("exit", (code) => done(code === 0));
1044
+ child.unref();
1045
+ });
1046
+ if (process.platform === "darwin") {
1047
+ if (await run("open", ["-a", "Google Chrome", url]))
1048
+ return;
1049
+ await run("open", [url]);
1050
+ return;
1051
+ }
1052
+ if (process.platform === "win32") {
1053
+ if (await run("cmd", ["/c", "start", "", "chrome", url]))
1054
+ return;
1055
+ await run("cmd", ["/c", "start", "", url]);
1056
+ return;
1057
+ }
1058
+ if (await run("google-chrome", [url]))
1059
+ return;
1060
+ await run("xdg-open", [url]);
1061
+ }
1062
+ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.0.0.1", log = () => {
1063
+ }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1064
+ if (sidebar && host !== "127.0.0.1")
1065
+ throw new Error("The sidebar bridge requires loopback.");
1066
+ const prefix = sidebar ? `/s/${randomBytes(24).toString("hex")}/` : "/";
1067
+ let activeSource = initialSource;
1068
+ let browserCompanion = null;
1069
+ let bound;
1070
+ let current = await activeSource.read();
1071
+ let version = hash(current);
1072
+ let viewState = await activeSource.readView?.();
1073
+ const clients = /* @__PURE__ */ new Set();
1074
+ const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1075
+ const docState = () => ({
1076
+ name: activeSource.name,
1077
+ md: current,
1078
+ version,
1079
+ ...activeSource.key && { currentFile: activeSource.key },
1080
+ ...viewState && { viewState }
1081
+ });
1082
+ const send = (event, data) => {
1083
+ const payload = `event: ${event}
1084
+ data: ${JSON.stringify(data)}
1085
+
1086
+ `;
1087
+ for (const res of clients)
1088
+ res.write(payload);
1089
+ };
1090
+ const broadcast = () => send("change", docState());
1091
+ const unlisten = license?.onChange((state) => send("license", state)) ?? (() => {
1092
+ });
1093
+ let queue = Promise.resolve();
1094
+ function serialized(work) {
1095
+ const result = queue.then(work);
1096
+ queue = result.catch(() => {
1097
+ });
1098
+ return result;
1099
+ }
1100
+ async function refresh() {
1101
+ const text = await activeSource.read();
1102
+ if (hash(text) === version)
1103
+ return;
1104
+ current = text;
1105
+ version = hash(text);
1106
+ broadcast();
1107
+ }
1108
+ let pending;
1109
+ let unwatch = activeSource.watch(() => {
1110
+ clearTimeout(pending);
1111
+ pending = setTimeout(async () => {
1112
+ void serialized(refresh).catch(() => {
1113
+ });
1114
+ }, 80);
1115
+ });
1116
+ async function collectWorkspaceFiles() {
1117
+ const roots = /* @__PURE__ */ new Map();
1118
+ if (activeSource.key) {
1119
+ const realKey = await realpath(activeSource.key).catch(() => activeSource.key);
1120
+ const projRoot = await realpath(await findProjectRoot(realKey)).catch(() => dirname2(realKey));
1121
+ roots.set(projRoot, { path: projRoot, name: basename(projRoot), active: true });
1122
+ }
1123
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter)].filter(Boolean);
1124
+ for (const raw of envRoots) {
1125
+ const real = await realpath(resolve(raw)).catch(() => null);
1126
+ if (real && !roots.has(real)) {
1127
+ roots.set(real, { path: real, name: basename(real), active: roots.size === 0 });
1128
+ }
1129
+ }
1130
+ const items = [];
1131
+ const seen = /* @__PURE__ */ new Set();
1132
+ for (const root of roots.values()) {
1133
+ const files = await scanProjectMarkdownFiles(root.path);
1134
+ for (const f of files) {
1135
+ if (seen.has(f))
1136
+ continue;
1137
+ seen.add(f);
1138
+ const rel = relative(root.path, f);
1139
+ items.push({
1140
+ path: f,
1141
+ label: `${root.name} / ${rel}`,
1142
+ group: root.active ? "active" : "project"
1143
+ });
1144
+ }
1145
+ }
1146
+ if (activeSource.key && !seen.has(activeSource.key)) {
1147
+ items.unshift({
1148
+ path: activeSource.key,
1149
+ label: `${basename(activeSource.dir)} / ${basename(activeSource.key)}`,
1150
+ group: "active"
1151
+ });
1152
+ }
1153
+ return { roots: [...roots.values()], files: items };
1154
+ }
1155
+ async function switchSourceToFile(candidatePath) {
1156
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1157
+ throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1158
+ }
1159
+ const realTarget = await realpath(resolve(candidatePath));
1160
+ const st = await lstat(realTarget);
1161
+ if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1162
+ throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1163
+ }
1164
+ const { roots } = await collectWorkspaceFiles();
1165
+ if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
1166
+ throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1167
+ }
1168
+ if (activeSource.key === realTarget)
1169
+ return;
1170
+ clearTimeout(pending);
1171
+ unwatch();
1172
+ activeSource = await fileSource(realTarget, log);
1173
+ current = await activeSource.read();
1174
+ version = hash(current);
1175
+ viewState = await activeSource.readView?.();
1176
+ unwatch = activeSource.watch(() => {
1177
+ clearTimeout(pending);
1178
+ pending = setTimeout(async () => {
1179
+ void serialized(refresh).catch(() => {
1180
+ });
1181
+ }, 80);
1182
+ });
1183
+ broadcast();
1184
+ }
1185
+ const json = (res, status, body) => {
1186
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1187
+ res.end(JSON.stringify(body));
1188
+ };
1189
+ const readBody = (req) => new Promise((ok, fail) => {
1190
+ let size = 0;
1191
+ const chunks = [];
1192
+ req.on("data", (c) => {
1193
+ size += c.length;
1194
+ if (size > MAX_BODY) {
1195
+ fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1196
+ req.destroy();
1197
+ } else
1198
+ chunks.push(c);
1199
+ });
1200
+ req.on("end", () => ok(Buffer.concat(chunks).toString("utf8")));
1201
+ req.on("error", fail);
1202
+ });
1203
+ const sendFile = async (res, full) => {
1204
+ if (!full)
1205
+ return json(res, 403, { error: "forbidden" });
1206
+ try {
1207
+ const ext = extname(full).toLowerCase();
1208
+ if (ext === ".html") {
1209
+ const osLoc = detectOsLocale();
1210
+ const htmlText = (await readFile2(full, "utf8")).replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1211
+ res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1212
+ res.end(htmlText, "utf8");
1213
+ return;
1214
+ }
1215
+ const body = await readFile2(full);
1216
+ res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1217
+ res.end(body);
1218
+ } catch {
1219
+ json(res, 404, { error: "not found" });
1220
+ }
1221
+ };
1222
+ const server = createServer(async (req, res) => {
1223
+ try {
1224
+ const url = new URL(req.url ?? "/", "http://localhost");
1225
+ if (sidebar) {
1226
+ res.setHeader("Referrer-Policy", "no-referrer");
1227
+ res.setHeader("X-Content-Type-Options", "nosniff");
1228
+ res.setHeader("Cache-Control", "no-store");
1229
+ res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'");
1230
+ if (req.headers.host !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix))
1231
+ return json(res, 404, { error: "not found" });
1232
+ if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1233
+ return json(res, 403, { error: "forbidden" });
1234
+ }
1235
+ url.pathname = "/" + url.pathname.slice(prefix.length);
1236
+ }
1237
+ if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1238
+ res.writeHead(302, { Location: "/" + url.search });
1239
+ return res.end();
1240
+ }
1241
+ if (url.pathname === "/api/doc" && req.method === "GET") {
1242
+ license?.track?.("doc_open");
1243
+ viewState = await activeSource.readView?.() ?? viewState;
1244
+ if (sidebar)
1245
+ await serialized(refresh);
1246
+ return json(res, 200, docState());
1247
+ }
1248
+ if (url.pathname === "/api/files" && req.method === "GET") {
1249
+ const { files } = await collectWorkspaceFiles();
1250
+ return json(res, 200, { currentFile: activeSource.key ?? null, files });
1251
+ }
1252
+ if (url.pathname === "/api/capabilities" && req.method === "GET") {
1253
+ return json(res, 200, {
1254
+ purchase: canPurchase,
1255
+ ...ideWorkspace && { ideWorkspace: true },
1256
+ ...sidebarAccountNavigation && { accountNavigation: "host" }
1257
+ });
1258
+ }
1259
+ if (url.pathname === "/api/view" && req.method === "PUT") {
1260
+ const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1261
+ if (cleaned) {
1262
+ viewState = cleaned;
1263
+ await activeSource.writeView?.(cleaned).catch(() => {
1264
+ });
1265
+ }
1266
+ return json(res, 200, { ok: true });
1267
+ }
1268
+ if (url.pathname === "/api/doc" && req.method === "PUT") {
1269
+ const { md, baseVersion } = JSON.parse(await readBody(req));
1270
+ if (typeof md !== "string")
1271
+ return json(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1272
+ if (!hasAccess(await license?.state() ?? { pro: false }))
1273
+ return json(res, 403, { error: "Inkmap trial expired" });
1274
+ return await serialized(async () => {
1275
+ await refresh();
1276
+ if (baseVersion !== version)
1277
+ return json(res, 409, docState());
1278
+ if (md !== current) {
1279
+ await activeSource.write(md);
1280
+ current = md;
1281
+ version = hash(md);
1282
+ license?.track?.("doc_edit");
1283
+ if (sidebar)
1284
+ broadcast();
1285
+ }
1286
+ return json(res, 200, { version });
1287
+ });
1288
+ }
1289
+ if (url.pathname === "/api/license" && req.method === "GET")
1290
+ return json(res, 200, await license?.state() ?? { pro: false });
1291
+ const sameOriginPost = () => {
1292
+ const origin = req.headers.origin;
1293
+ const reqHost = req.headers.host;
1294
+ const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1295
+ return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1296
+ };
1297
+ if (url.pathname === "/api/open" && req.method === "POST") {
1298
+ if (!sameOriginPost())
1299
+ return json(res, 403, { error: "forbidden" });
1300
+ const { file } = JSON.parse(await readBody(req));
1301
+ await serialized(() => switchSourceToFile(String(file ?? "")));
1302
+ license?.track?.("doc_open");
1303
+ const { files } = await collectWorkspaceFiles();
1304
+ return json(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1305
+ }
1306
+ if (url.pathname === "/api/telemetry" && req.method === "POST") {
1307
+ if (!sameOriginPost())
1308
+ return json(res, 403, { error: "forbidden" });
1309
+ const { event } = JSON.parse(await readBody(req));
1310
+ if (typeof event === "string" && event)
1311
+ license?.track?.(event);
1312
+ return json(res, 200, { ok: true });
1313
+ }
1314
+ if (url.pathname === "/api/open-browser" && req.method === "POST") {
1315
+ if (!sameOriginPost())
1316
+ return json(res, 403, { error: "forbidden" });
1317
+ if (license && !hasAccess(await license.state())) {
1318
+ return json(res, 402, { error: detectOsLocale() === "zh" ? "\u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u5148\u89E3\u9501\u6216\u6062\u590D Pro\u3002" : "Trial expired. Unlock or restore Pro first." });
1319
+ }
1320
+ license?.track?.("feature_browser");
1321
+ if (!sidebar) {
1322
+ const directUrl = `http://${host}:${bound}/`;
1323
+ await openBrowserWindow(directUrl);
1324
+ return json(res, 200, { ok: true, url: directUrl });
1325
+ }
1326
+ if (!browserCompanion) {
1327
+ browserCompanion = (async () => {
1328
+ const src = activeSource.key ? await fileSource(activeSource.key) : activeSource;
1329
+ return serve({
1330
+ source: src,
1331
+ webRoot,
1332
+ host: "127.0.0.1",
1333
+ port: 0,
1334
+ license,
1335
+ ads,
1336
+ sidebar: false,
1337
+ loginOnly: false,
1338
+ workspaceRoots
1339
+ });
1340
+ })();
1341
+ browserCompanion.catch(() => {
1342
+ browserCompanion = null;
1343
+ });
1344
+ }
1345
+ const companion = await browserCompanion;
1346
+ if (activeSource.key)
1347
+ await companion.switchToFile?.(activeSource.key).catch(() => {
1348
+ });
1349
+ await openBrowserWindow(companion.url);
1350
+ return json(res, 200, { ok: true, url: companion.url });
1351
+ }
1352
+ if (url.pathname === "/api/checkout" && req.method === "POST") {
1353
+ if (!sameOriginPost())
1354
+ return json(res, 403, { error: "forbidden" });
1355
+ const { mode, locale } = JSON.parse(await readBody(req));
1356
+ if (mode !== "buy" && mode !== "restore")
1357
+ return json(res, 400, { error: "invalid checkout mode" });
1358
+ if (!canPurchase && mode === "buy")
1359
+ return json(res, 403, { error: "forbidden" });
1360
+ if (!license)
1361
+ return json(res, 503, { error: "Inkmap checkout is unavailable." });
1362
+ return json(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1363
+ }
1364
+ if (url.pathname === "/api/order-pro" && req.method === "POST") {
1365
+ if (!sameOriginPost())
1366
+ return json(res, 403, { error: "forbidden" });
1367
+ if (!canPurchase)
1368
+ return json(res, 403, { error: "forbidden" });
1369
+ if (!license)
1370
+ return json(res, 503, { error: "Inkmap checkout is unavailable." });
1371
+ if (typeof license.orderPro !== "function")
1372
+ return json(res, 501, { fallback: true });
1373
+ const { locale } = JSON.parse(await readBody(req) || "{}");
1374
+ return json(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1375
+ }
1376
+ if (url.pathname === "/api/phone-send" && req.method === "POST") {
1377
+ if (!sameOriginPost())
1378
+ return json(res, 403, { error: "forbidden" });
1379
+ if (!license || typeof license.sendPhoneCode !== "function")
1380
+ return json(res, 501, { fallback: true });
1381
+ const { phone, locale } = JSON.parse(await readBody(req));
1382
+ return json(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1383
+ }
1384
+ if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1385
+ if (!sameOriginPost())
1386
+ return json(res, 403, { error: "forbidden" });
1387
+ if (!license || typeof license.signInByPhone !== "function")
1388
+ return json(res, 501, { fallback: true });
1389
+ const { phone, code } = JSON.parse(await readBody(req));
1390
+ return json(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
1391
+ }
1392
+ if (url.pathname === "/api/signout" && req.method === "POST") {
1393
+ if (!sameOriginPost())
1394
+ return json(res, 403, { error: "forbidden" });
1395
+ await license?.deactivate();
1396
+ return json(res, 200, await license?.state() ?? { pro: false });
1397
+ }
1398
+ if (url.pathname === "/api/ads")
1399
+ return json(res, 200, sidebar ? [] : await ads?.() ?? []);
1400
+ if (url.pathname === "/api/events") {
1401
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1402
+ res.write(": connected\n\n");
1403
+ clients.add(res);
1404
+ req.on("close", () => clients.delete(res));
1405
+ return;
1406
+ }
1407
+ if (url.pathname === "/favicon.ico")
1408
+ return void res.writeHead(204).end();
1409
+ if (url.pathname.startsWith("/doc-assets/")) {
1410
+ let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1411
+ if (sidebar && asset) {
1412
+ const root = await realpath(activeSource.dir);
1413
+ asset = await realpath(asset).catch(() => null);
1414
+ if (asset && (!asset.startsWith(root + sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset)))
1415
+ asset = null;
1416
+ }
1417
+ return sendFile(res, asset);
1418
+ }
1419
+ return sendFile(res, within(webRoot, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1420
+ } catch (err) {
1421
+ json(res, 500, { error: err instanceof Error ? err.message : String(err) });
1422
+ }
1423
+ });
1424
+ const listen = (p) => new Promise((ok, fail) => {
1425
+ server.once("error", fail);
1426
+ server.listen(p, host, () => {
1427
+ server.off("error", fail);
1428
+ ok(server.address().port);
1429
+ });
1430
+ });
1431
+ try {
1432
+ bound = await listen(port);
1433
+ } catch (err) {
1434
+ if (err.code !== "EADDRINUSE")
1435
+ throw err;
1436
+ bound = await listen(0);
1437
+ }
1438
+ return {
1439
+ url: `http://${host}:${bound}${prefix}`,
1440
+ switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1441
+ close: () => new Promise((done) => {
1442
+ clearTimeout(pending);
1443
+ unwatch();
1444
+ unlisten();
1445
+ if (browserCompanion)
1446
+ void browserCompanion.then((s) => s.close()).catch(() => {
1447
+ });
1448
+ for (const res of clients)
1449
+ res.end();
1450
+ server.close(() => done());
1451
+ })
1452
+ };
1453
+ }
919
1454
 
920
1455
  // packages/antigravity/src/select.mjs
921
1456
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -1020,7 +1555,7 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
1020
1555
  "target",
1021
1556
  "coverage"
1022
1557
  ]);
1023
- var TYPES = {
1558
+ var TYPES2 = {
1024
1559
  ".html": "text/html; charset=utf-8",
1025
1560
  ".js": "application/javascript; charset=utf-8",
1026
1561
  ".css": "text/css; charset=utf-8",
@@ -1134,12 +1669,35 @@ function openExternalUrl(url) {
1134
1669
  execFile(cmd, args, () => {
1135
1670
  });
1136
1671
  }
1672
+ async function openBrowserWindow2(url) {
1673
+ if (process.env.INKMAP_NO_OPEN === "1" || typeof url !== "string" || !/^http:\/\/127\.0\.0\.1:[0-9]+\//.test(url)) return;
1674
+ const run = (cmd, args) => new Promise((done) => {
1675
+ const child = spawn2(cmd, args, { stdio: "ignore", detached: true });
1676
+ child.on("error", () => done(false));
1677
+ child.on("exit", (code) => done(code === 0));
1678
+ child.unref();
1679
+ });
1680
+ if (process.platform === "darwin") {
1681
+ if (await run("open", ["-a", "Google Chrome", url])) return;
1682
+ await run("open", [url]);
1683
+ return;
1684
+ }
1685
+ if (process.platform === "win32") {
1686
+ if (await run("cmd", ["/c", "start", "", "chrome", url])) return;
1687
+ await run("cmd", ["/c", "start", "", url]);
1688
+ return;
1689
+ }
1690
+ if (await run("google-chrome", [url])) return;
1691
+ await run("xdg-open", [url]);
1692
+ }
1137
1693
  function createAntigravitySidecar({
1138
1694
  app,
1139
1695
  webRoot = defaultWebRoot,
1140
1696
  billingOrigin: billingOrigin2 = () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN
1141
1697
  } = {}) {
1142
1698
  const license = licenseService(fileSessionStorage(), billingOrigin2, { loginOnly: true, host: "antigravity" });
1699
+ let browserLicense = null;
1700
+ let browserServed = null;
1143
1701
  let activeFile = null;
1144
1702
  async function allowedRoots(workspaceUris = []) {
1145
1703
  const roots = /* @__PURE__ */ new Map();
@@ -1177,8 +1735,10 @@ function createAntigravitySidecar({
1177
1735
  if (!info.isFile() || info.size > MAX_BYTES2) throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002");
1178
1736
  const real = await realpath3(raw);
1179
1737
  if (real !== raw || !/\.md$/i.test(real)) throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u6216\u975E Markdown \u6587\u4EF6\u3002");
1738
+ const brainRoot = await realpath3(join4(homedir4(), ".gemini", "antigravity", "brain")).catch(() => null);
1739
+ const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !real.includes(`${sep3}.system_generated${sep3}`));
1180
1740
  const { roots, target } = await allowedRoots(workspaceUris);
1181
- const permitted = target && target.file === real || roots.some((r) => insideOrEqual(r.path, real));
1741
+ const permitted = inBrainArtifact || target && target.file === real || roots.some((r) => insideOrEqual(r.path, real));
1182
1742
  if (!permitted) throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u6216\u9879\u76EE\u76EE\u5F55\u5185\u3002");
1183
1743
  return real;
1184
1744
  }
@@ -1261,7 +1821,7 @@ function createAntigravitySidecar({
1261
1821
  if (entry.isDirectory()) {
1262
1822
  registerStaticDir(full, route);
1263
1823
  } else if (entry.isFile() && route !== "/index.html") {
1264
- const contentType = TYPES[extname2(entry.name).toLowerCase()] || "application/octet-stream";
1824
+ const contentType = TYPES2[extname2(entry.name).toLowerCase()] || "application/octet-stream";
1265
1825
  const body = readFileSync(full);
1266
1826
  app.api(route, () => {
1267
1827
  console.log(`[inkmap] GET ${route} (${body.length} bytes)`);
@@ -1390,6 +1950,38 @@ function createAntigravitySidecar({
1390
1950
  if (ev) license.track?.(ev, 1, "antigravity");
1391
1951
  return { ok: true };
1392
1952
  }, "POST");
1953
+ app.api("/api/open-browser", async (data) => {
1954
+ if (!hasAccess(await license.state())) {
1955
+ throw new Error("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u5148\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro\u3002");
1956
+ }
1957
+ const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1958
+ const targetFile = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris);
1959
+ const { roots } = await allowedRoots(workspaceUris);
1960
+ license.track?.("feature_browser", 1, "antigravity");
1961
+ if (!browserServed) {
1962
+ browserServed = (async () => {
1963
+ browserLicense ??= licenseService(fileSessionStorage(), billingOrigin2, { host: "antigravity" });
1964
+ return serve({
1965
+ source: await fileSource(targetFile),
1966
+ webRoot,
1967
+ host: "127.0.0.1",
1968
+ port: 0,
1969
+ license: browserLicense,
1970
+ sidebar: false,
1971
+ loginOnly: false,
1972
+ workspaceRoots: roots.map((r) => r.path)
1973
+ });
1974
+ })();
1975
+ browserServed.catch(() => {
1976
+ browserServed = null;
1977
+ });
1978
+ }
1979
+ const served = await browserServed;
1980
+ await served.switchToFile?.(targetFile).catch(() => {
1981
+ });
1982
+ await openBrowserWindow2(served.url);
1983
+ return { ok: true, url: served.url };
1984
+ }, "POST");
1393
1985
  app.api("/api/view", async (data) => {
1394
1986
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1395
1987
  const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris).catch(() => null);
@@ -1431,7 +2023,7 @@ function createAntigravitySidecar({
1431
2023
  if (!insideOrEqual(dir, realAsset) || !/\.(?:png|jpe?g|gif|webp|svg)$/i.test(realAsset)) return notFound();
1432
2024
  const info = await lstat3(realAsset);
1433
2025
  if (!info.isFile() || info.size > MAX_BYTES2) return notFound();
1434
- const type = TYPES[extname2(realAsset).toLowerCase()] || "application/octet-stream";
2026
+ const type = TYPES2[extname2(realAsset).toLowerCase()] || "application/octet-stream";
1435
2027
  return new SidecarResponse(await readFile3(realAsset), {
1436
2028
  contentType: type,
1437
2029
  headers: { "Cache-Control": "no-cache" }
@@ -1440,7 +2032,18 @@ function createAntigravitySidecar({
1440
2032
  return notFound();
1441
2033
  }
1442
2034
  }, "GET");
1443
- return { app, license };
2035
+ return {
2036
+ app,
2037
+ license,
2038
+ close: async () => {
2039
+ browserLicense?.dispose?.();
2040
+ license.dispose?.();
2041
+ if (browserServed) {
2042
+ const s = await browserServed.catch(() => null);
2043
+ await s?.close();
2044
+ }
2045
+ }
2046
+ };
1444
2047
  }
1445
2048
  if (process.env.ANTIGRAVITY_SIDECAR_WEB_PORT) {
1446
2049
  const sdk = await import("sidecar_sdk").catch(