inkmap-mcp 0.3.10 → 0.3.11

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.
@@ -2,17 +2,15 @@
2
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
- import { lstat as lstat3, readdir as readdir2, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
5
+ import { lstat as lstat3, readFile as readFile4, realpath as realpath3 } from "node:fs/promises";
6
6
  import { homedir as homedir4 } from "node:os";
7
- import { basename as basename2, dirname as dirname4, extname as extname2, isAbsolute as isAbsolute3, join as join4, normalize as normalize2, relative as relative3, resolve as resolve3, sep as sep3 } from "node:path";
8
- import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { basename as basename3, dirname as dirname4, extname as extname2, join as join4, normalize as normalize2, relative as relative3 } from "node:path";
8
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
9
9
 
10
10
  // packages/core/dist/product.js
11
11
  var PRODUCT = {
12
12
  id: "inkmap-pro",
13
- entitlement: "inkmap.pro",
14
- /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
15
- adFeedUrl: ""
13
+ entitlement: "inkmap.pro"
16
14
  };
17
15
  var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
18
16
  function billingFlowUrl(raw, origin, mode, legacy = false) {
@@ -60,56 +58,83 @@ function sanitizeViewState(raw) {
60
58
  import { execFileSync } from "node:child_process";
61
59
  import { link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
62
60
  import { randomUUID } from "node:crypto";
63
- import { homedir } from "node:os";
64
- import { dirname, join } from "node:path";
61
+ import { homedir, tmpdir } from "node:os";
62
+ import { dirname, join, sep } from "node:path";
63
+
64
+ // packages/cli/dist/version.js
65
+ var INKMAP_VERSION = "0.3.11";
66
+
67
+ // packages/cli/dist/license.js
68
+ var ZH_LOCALE_RE = /^zh(?:[-_.]|$)/i;
69
+ var EN_LOCALE_RE = /^en(?:[-_.]|$)/i;
65
70
  var cachedOsLocale;
66
- function detectOsLocale() {
67
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
68
- if (/^zh\b/i.test(explicit))
71
+ var WAIT_FAST_MS = 2500;
72
+ var WAIT_SLOW_MS = 3e4;
73
+ var WAIT_FAST_FOR_MS = 30 * 6e4;
74
+ var WAIT_MAX_MS = 3 * 24 * 60 * 6e4;
75
+ var MAX_WAITING = 5;
76
+ function isWaitingToken(value) {
77
+ const w = value;
78
+ return Boolean(w) && typeof w.origin === "string" && typeof w.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(w.token) && typeof w.email === "string" && typeof w.since === "number" && typeof w.fastUntil === "number";
79
+ }
80
+ var DOMESTIC_TIME_ZONE = /^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i;
81
+ function parseAppleLanguages(output) {
82
+ const match = /^\(\s*(?:"([^"]+)"|([^\s,)]+))/m.exec(output);
83
+ return match?.[1] ?? match?.[2] ?? "";
84
+ }
85
+ var posixLocale = (env) => (env.LC_ALL || env.LC_MESSAGES || env.LANG || "").trim();
86
+ function resolveOsLocale(probe) {
87
+ const explicit = (probe.env.INKMAP_LOCALE || "").trim();
88
+ if (ZH_LOCALE_RE.test(explicit))
69
89
  return "zh";
70
- if (/^en\b/i.test(explicit))
90
+ if (EN_LOCALE_RE.test(explicit))
71
91
  return "en";
72
- if (cachedOsLocale)
73
- return cachedOsLocale;
74
- let domestic = false;
75
- try {
76
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
77
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
78
- domestic = true;
92
+ if (DOMESTIC_TIME_ZONE.test(probe.timeZone))
93
+ return "zh";
94
+ let language = "";
95
+ if (probe.platform === "darwin") {
96
+ try {
97
+ language = parseAppleLanguages(probe.run("defaults", ["read", "-g", "AppleLanguages"]));
98
+ } catch {
99
+ language = posixLocale(probe.env);
79
100
  }
80
- } catch {
81
- }
82
- if (!domestic) {
83
- if (process.platform === "darwin") {
84
- try {
85
- const out = execFileSync("defaults", ["read", "-g", "AppleLanguages"], {
86
- encoding: "utf8",
87
- timeout: 800,
88
- stdio: ["ignore", "pipe", "ignore"]
89
- });
90
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
91
- if (/^zh\b/i.test(firstLang))
92
- domestic = true;
93
- } catch {
94
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
95
- if (/^zh\b/i.test(raw))
96
- domestic = true;
97
- }
98
- } else if (process.platform === "win32") {
99
- try {
100
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
101
- if (/^zh\b/i.test(loc))
102
- domestic = true;
103
- } catch {
104
- }
105
- } else {
106
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
107
- if (/^zh\b/i.test(raw))
108
- domestic = true;
101
+ } else if (probe.platform === "win32") {
102
+ try {
103
+ const output = probe.run("reg", ["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]);
104
+ language = /LocaleName\s+REG_\w+\s+(\S+)/i.exec(output)?.[1] ?? "";
105
+ } catch {
109
106
  }
107
+ if (!language)
108
+ language = probe.intlLocale;
109
+ } else {
110
+ language = posixLocale(probe.env);
111
+ }
112
+ return ZH_LOCALE_RE.test(language) ? "zh" : "en";
113
+ }
114
+ function systemLocaleProbe() {
115
+ let timeZone = "";
116
+ let intlLocale = "";
117
+ try {
118
+ const options = Intl.DateTimeFormat().resolvedOptions();
119
+ timeZone = options.timeZone || "";
120
+ intlLocale = options.locale || "";
121
+ } catch {
110
122
  }
111
- cachedOsLocale = domestic ? "zh" : "en";
112
- return cachedOsLocale;
123
+ return {
124
+ platform: process.platform,
125
+ env: process.env,
126
+ timeZone,
127
+ intlLocale,
128
+ run: (command, args) => execFileSync(command, args, { encoding: "utf8", timeout: 800, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] })
129
+ };
130
+ }
131
+ function detectOsLocale() {
132
+ const explicit = (process.env.INKMAP_LOCALE || "").trim();
133
+ if (ZH_LOCALE_RE.test(explicit))
134
+ return "zh";
135
+ if (EN_LOCALE_RE.test(explicit))
136
+ return "en";
137
+ return cachedOsLocale ??= resolveOsLocale(systemLocaleProbe());
113
138
  }
114
139
  function billingOrigin(raw) {
115
140
  if (!raw)
@@ -120,7 +145,7 @@ function billingOrigin(raw) {
120
145
  }
121
146
  return url.origin;
122
147
  }
123
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
148
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
124
149
  const listeners = /* @__PURE__ */ new Set();
125
150
  let current = { pro: false };
126
151
  let trial;
@@ -132,6 +157,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
132
157
  let detectedHost = defaultHost;
133
158
  const pendingEvents = /* @__PURE__ */ new Map();
134
159
  let lastCheck = 0;
160
+ let fastPollUntil = 0;
161
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
162
+ let flowCreation;
135
163
  let disposed = false;
136
164
  let generation = 0;
137
165
  let connection;
@@ -139,12 +167,33 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
139
167
  let pendingWrite = Promise.resolve();
140
168
  let pendingCheckout;
141
169
  let cachedOrder;
142
- let magicPollTimer;
143
- let magicSession = 0;
144
- function stopMagicPoll() {
145
- ++magicSession;
146
- clearTimeout(magicPollTimer);
147
- magicPollTimer = void 0;
170
+ let waiting = [];
171
+ let waitTimer;
172
+ let waitRound = 0;
173
+ let lastSignIn;
174
+ const sessionRecord = (fields) => JSON.stringify({ ...fields, ...lastSignIn && { lastSignIn } });
175
+ const signedOutRecord = () => lastSignIn || waiting.length ? JSON.stringify({ ...lastSignIn && { lastSignIn }, ...waiting.length && { waiting } }) : void 0;
176
+ async function rememberSignIn(id) {
177
+ const clean = id.trim().slice(0, 254);
178
+ if (!clean || clean === lastSignIn)
179
+ return;
180
+ lastSignIn = clean;
181
+ current = { ...current, lastSignIn };
182
+ await writeSession(async () => {
183
+ let record = {};
184
+ try {
185
+ record = JSON.parse(await storage.read() || "{}");
186
+ } catch {
187
+ }
188
+ await storage.write(JSON.stringify({ ...record, lastSignIn }));
189
+ }).catch(() => {
190
+ });
191
+ }
192
+ function clearWaiting() {
193
+ waiting = [];
194
+ ++waitRound;
195
+ clearTimeout(waitTimer);
196
+ waitTimer = void 0;
148
197
  }
149
198
  function mergeCookies(existing, response) {
150
199
  const map = /* @__PURE__ */ new Map();
@@ -175,12 +224,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
175
224
  }
176
225
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
177
226
  }
178
- function clientLocale(hint) {
179
- const h = (hint || "").trim();
180
- if (/^zh\b/i.test(h))
181
- return "zh";
182
- if (/^en\b/i.test(h))
183
- return "en";
227
+ function clientLocale(_uiLocaleHint) {
184
228
  return detectOsLocale();
185
229
  }
186
230
  function writeSession(operation) {
@@ -212,7 +256,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
212
256
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
213
257
  throw new Error("Invalid Inkmap checkout response.");
214
258
  }
215
- return { origin, url, token: data.token, ...cookie && { cookie } };
259
+ return { origin, url, token: data.token, locale: loc, ...cookie && { cookie } };
216
260
  }
217
261
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
218
262
  const loc = clientLocale(localeHint);
@@ -274,12 +318,26 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
274
318
  pro,
275
319
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
276
320
  ...connected && { connected: true },
277
- ...cleanAccount && { account: cleanAccount }
321
+ ...cleanAccount && { account: cleanAccount },
322
+ ...lastSignIn && { lastSignIn }
278
323
  };
279
324
  for (const listener of listeners)
280
325
  listener(current);
281
326
  }
282
327
  async function startTrial() {
328
+ try {
329
+ const record = JSON.parse(await storage.read() || "{}");
330
+ const remembered = record.lastSignIn;
331
+ if (typeof remembered === "string" && remembered.trim() && !lastSignIn) {
332
+ lastSignIn = remembered.trim().slice(0, 254);
333
+ current = { ...current, lastSignIn };
334
+ }
335
+ if (typeof record.token !== "string" && Array.isArray(record.waiting) && !waiting.length) {
336
+ waiting = record.waiting.filter(isWaitingToken).slice(-MAX_WAITING);
337
+ scheduleWait(waitPollMs);
338
+ }
339
+ } catch {
340
+ }
283
341
  const trialUntil = await localTrialDeadline().catch(() => void 0);
284
342
  if (disposed || trialUntil === void 0)
285
343
  return;
@@ -331,7 +389,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
331
389
  return await writeSession(async () => {
332
390
  if (version !== generation || disposed)
333
391
  return;
334
- await storage.write(void 0).catch(() => {
392
+ await storage.write(signedOutRecord()).catch(() => {
335
393
  });
336
394
  update(false);
337
395
  });
@@ -355,48 +413,134 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
355
413
  });
356
414
  return connection;
357
415
  }
358
- function startMagicPoll(origin, pendingToken) {
359
- stopMagicPoll();
360
- const id = magicSession;
361
- const deadline = Date.now() + 10 * 6e4;
362
- const poll = () => {
363
- if (disposed || id !== magicSession || Date.now() >= deadline)
416
+ async function mustPayFirst() {
417
+ if (!loginOnly)
418
+ return false;
419
+ await (trial ??= startTrial());
420
+ return current.trialUntil !== void 0 && current.trialUntil <= Date.now();
421
+ }
422
+ async function waitFor(origin, token, email) {
423
+ const now = Date.now();
424
+ const same = (other) => !other || !email || other.toLowerCase() === email.toLowerCase();
425
+ waiting = waiting.filter((w) => w.token !== token && same(w.email)).map((w) => ({ ...w, fastUntil: now + WAIT_FAST_FOR_MS }));
426
+ waiting.push({ origin, token, email, since: now, fastUntil: now + WAIT_FAST_FOR_MS });
427
+ waiting = waiting.slice(-MAX_WAITING);
428
+ scheduleWait(waitPollMs);
429
+ await writeSession(async () => {
430
+ let record = {};
431
+ try {
432
+ record = JSON.parse(await storage.read() || "{}");
433
+ } catch {
434
+ }
435
+ if (typeof record.token !== "string")
436
+ await storage.write(signedOutRecord());
437
+ }).catch(() => {
438
+ });
439
+ }
440
+ function scheduleWait(delay) {
441
+ clearTimeout(waitTimer);
442
+ if (disposed || !waiting.length)
443
+ return;
444
+ waitTimer = setTimeout(() => void checkWaiting(), delay);
445
+ waitTimer.unref();
446
+ }
447
+ async function checkWaiting() {
448
+ const round = ++waitRound;
449
+ const now = Date.now();
450
+ const before = waiting.length;
451
+ let origin;
452
+ try {
453
+ origin = billingOrigin(getOrigin());
454
+ } catch {
455
+ return scheduleWait(WAIT_SLOW_MS);
456
+ }
457
+ waiting = waiting.filter((w) => w.origin === origin && now - w.since < WAIT_MAX_MS);
458
+ for (const w of [...waiting]) {
459
+ let response;
460
+ try {
461
+ response = await entitlement(w.origin, w.token);
462
+ } catch {
463
+ continue;
464
+ }
465
+ if (disposed || round !== waitRound)
466
+ return;
467
+ if (response.status === 401) {
468
+ waiting = waiting.filter((other) => other !== w);
469
+ continue;
470
+ }
471
+ if (!response.ok)
472
+ continue;
473
+ const body = await response.json().catch(() => null);
474
+ if (disposed || round !== waitRound)
364
475
  return;
365
- magicPollTimer = setTimeout(async () => {
366
- if (disposed || id !== magicSession)
476
+ if (body?.connected !== true || body.entitlement !== PRODUCT.entitlement)
477
+ continue;
478
+ if (body.active !== true && await mustPayFirst())
479
+ continue;
480
+ if (disposed || round !== waitRound)
481
+ return;
482
+ await writeSession(async () => {
483
+ if (disposed || round !== waitRound || w.origin !== billingOrigin(getOrigin()))
367
484
  return;
485
+ clearWaiting();
486
+ await storage.write(sessionRecord({ origin: w.origin, token: w.token }));
487
+ ++generation;
488
+ activeOrigin = w.origin;
489
+ applyEntitlement(body);
490
+ schedule(body.active === true ? 6e4 : 2500);
491
+ });
492
+ return;
493
+ }
494
+ if (disposed || round !== waitRound)
495
+ return;
496
+ if (waiting.length !== before) {
497
+ await writeSession(async () => {
498
+ let record = {};
368
499
  try {
369
- const res = await entitlement(origin, pendingToken);
370
- if (disposed || id !== magicSession)
371
- return;
372
- if (res.status === 401) {
373
- stopMagicPoll();
374
- return;
375
- }
376
- if (res.ok) {
377
- const body = await res.json();
378
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
379
- stopMagicPoll();
380
- await writeSession(async () => {
381
- if (disposed || origin !== billingOrigin(getOrigin()))
382
- return;
383
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
384
- ++generation;
385
- activeOrigin = origin;
386
- applyEntitlement(body);
387
- schedule(body.active === true ? 6e4 : 2500);
388
- });
389
- return;
390
- }
391
- }
500
+ record = JSON.parse(await storage.read() || "{}");
392
501
  } catch {
393
502
  }
394
- if (!disposed && id === magicSession && Date.now() < deadline)
395
- poll();
396
- }, 2e3);
397
- magicPollTimer.unref();
398
- };
399
- poll();
503
+ if (typeof record.token !== "string")
504
+ await storage.write(signedOutRecord());
505
+ }).catch(() => {
506
+ });
507
+ }
508
+ scheduleWait(waiting.some((w) => Date.now() < w.fastUntil) ? waitPollMs : WAIT_SLOW_MS);
509
+ }
510
+ async function parkUnpaidSession() {
511
+ if (current.pro || !current.connected || !await mustPayFirst())
512
+ return;
513
+ await writeSession(async () => {
514
+ if (current.pro || !current.connected)
515
+ return;
516
+ let record = {};
517
+ try {
518
+ record = JSON.parse(await storage.read() || "{}");
519
+ } catch {
520
+ }
521
+ if (typeof record.token !== "string" || typeof record.origin !== "string")
522
+ return;
523
+ const response = await entitlement(record.origin, record.token).catch(() => null);
524
+ if (!response?.ok)
525
+ return;
526
+ const latest = await response.json().catch(() => null);
527
+ if (!latest || latest.active === true || latest.connected !== true) {
528
+ if (latest)
529
+ applyEntitlement(latest);
530
+ return;
531
+ }
532
+ ++generation;
533
+ clearTimeout(timer);
534
+ lastCheck = 0;
535
+ const now = Date.now();
536
+ waiting = [
537
+ ...waiting.filter((w) => w.token !== record.token),
538
+ { origin: record.origin, token: record.token, email: lastSignIn ?? "", since: now, fastUntil: now + WAIT_FAST_FOR_MS }
539
+ ].slice(-MAX_WAITING);
540
+ await storage.write(signedOutRecord());
541
+ update(false);
542
+ });
543
+ scheduleWait(waitPollMs);
400
544
  }
401
545
  async function sendPendingTelemetry() {
402
546
  if (disposed || !pendingEvents.size)
@@ -411,7 +555,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
411
555
  if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
412
556
  return;
413
557
  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-"))) {
558
+ const sysTmp = tmpdir();
559
+ if (customHome && (customHome === sysTmp || customHome.startsWith(sysTmp + sep) || 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
560
  return;
416
561
  }
417
562
  }
@@ -435,7 +580,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
435
580
  installId: id,
436
581
  host: hostName,
437
582
  os,
438
- version: "0.3.10",
583
+ version: INKMAP_VERSION,
439
584
  locale: clientLocale(),
440
585
  tier,
441
586
  events
@@ -447,13 +592,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
447
592
  return {
448
593
  async state() {
449
594
  await (trial ??= startTrial());
450
- if (Date.now() - lastCheck >= 4e3)
595
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
596
+ if (Date.now() - lastCheck >= interval)
451
597
  await refresh();
598
+ await parkUnpaidSession();
452
599
  return current;
453
600
  },
454
601
  async connect(mode, localeHint) {
455
602
  if (loginOnly && mode !== "restore")
456
603
  throw new Error("Only Yunfan account sign-in is available.");
604
+ expectPurchase();
457
605
  const origin = billingOrigin(getOrigin());
458
606
  const loc = clientLocale(localeHint);
459
607
  const version = generation;
@@ -495,7 +643,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
495
643
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
496
644
  throw new Error("The Yunfan account session changed. Please try again.");
497
645
  }
498
- await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
646
+ clearWaiting();
647
+ await storage.write(sessionRecord({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
499
648
  ++generation;
500
649
  lastCheck = 0;
501
650
  if (mode !== "buy" || !current.connected)
@@ -507,8 +656,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
507
656
  async orderPro(localeHint) {
508
657
  if (loginOnly)
509
658
  throw new Error("Only Yunfan account sign-in is available.");
659
+ expectPurchase();
510
660
  const origin = billingOrigin(getOrigin());
511
- if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
661
+ const loc = clientLocale(localeHint);
662
+ if (cachedOrder && cachedOrder.origin === origin && cachedOrder.locale === loc && Date.now() - cachedOrder.at < 8e3) {
512
663
  const hit = cachedOrder.result;
513
664
  cachedOrder = void 0;
514
665
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -534,7 +685,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
534
685
  await writeSession(async () => {
535
686
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
536
687
  return;
537
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
688
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
538
689
  if (persist) {
539
690
  ++generation;
540
691
  lastCheck = 0;
@@ -583,34 +734,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
583
734
  async sendPhoneCode(phone, localeHint) {
584
735
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254)
585
736
  return phoneFailure(400);
737
+ expectPurchase();
586
738
  const isEmail = phone.includes("@");
587
739
  const locale = clientLocale(localeHint);
588
740
  try {
589
741
  const origin = billingOrigin(getOrigin());
590
742
  if (!loginOnly) {
591
743
  try {
592
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
593
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
744
+ const newFlow = () => flowCreation ??= createCheckoutFlow(origin, void 0, void 0, locale).finally(() => {
745
+ flowCreation = void 0;
746
+ });
747
+ let flow = pendingCheckout;
748
+ if (!flow || flow.origin !== origin || flow.locale !== locale) {
749
+ flow = await newFlow();
750
+ pendingCheckout = flow;
594
751
  }
595
752
  const sendAction = isEmail ? "email/send" : "sms";
596
753
  const sendBody = isEmail ? { email: phone, locale } : { phone };
597
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
598
- if (smsRes.status === 410 || smsRes.status === 404) {
599
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
600
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
754
+ let smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
755
+ if (smsRes.status === 401 || smsRes.status === 403 || smsRes.status === 404 || smsRes.status === 410) {
756
+ flow = await newFlow();
757
+ pendingCheckout = flow;
758
+ smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
601
759
  }
602
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
603
- return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
760
+ flow.cookie = mergeCookies(flow.cookie, smsRes);
761
+ if (smsRes.status !== 204)
762
+ return phoneFailure(smsRes.status);
763
+ await rememberSignIn(phone);
764
+ return { ok: true, value: void 0 };
604
765
  } catch {
605
766
  pendingCheckout = void 0;
606
767
  }
607
768
  }
608
769
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
609
770
  if (response.status === 204) {
771
+ await rememberSignIn(phone);
610
772
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
611
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
612
- startMagicPoll(origin, pendingToken);
613
- }
773
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken))
774
+ await waitFor(origin, pendingToken, phone);
614
775
  return { ok: true, value: void 0 };
615
776
  }
616
777
  return phoneFailure(response.status);
@@ -618,41 +779,47 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
618
779
  return phoneFailure();
619
780
  }
620
781
  },
621
- async signInByPhone(phone, code) {
782
+ async signInByPhone(phone, code, localeHint) {
622
783
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code))
623
784
  return phoneFailure(400);
624
785
  const isEmail = phone.includes("@");
786
+ const locale = clientLocale(localeHint);
625
787
  const version = generation;
626
788
  try {
627
789
  const origin = billingOrigin(getOrigin());
628
790
  let token;
629
791
  let checkoutUrl;
630
792
  let cookie;
631
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
793
+ const flow = pendingCheckout;
794
+ if (!loginOnly && flow && flow.origin === origin) {
632
795
  const verifyAction = isEmail ? "email/verify" : "login";
633
796
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
634
- const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
797
+ const loginRes = await checkoutPost(flow.url, verifyAction, origin, verifyBody, flow.token, flow.cookie, locale);
635
798
  if (!loginRes.ok) {
636
- if (loginRes.status === 410 || loginRes.status === 404)
637
- pendingCheckout = void 0;
799
+ if (loginRes.status === 401 || loginRes.status === 403 || loginRes.status === 404 || loginRes.status === 410) {
800
+ if (pendingCheckout === flow)
801
+ pendingCheckout = void 0;
802
+ }
638
803
  return phoneFailure(loginRes.status);
639
804
  }
640
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
641
- token = pendingCheckout.token;
642
- checkoutUrl = pendingCheckout.url;
643
- pendingCheckout = void 0;
644
- const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
805
+ cookie = mergeCookies(flow.cookie, loginRes);
806
+ token = flow.token;
807
+ checkoutUrl = flow.url;
808
+ if (pendingCheckout === flow)
809
+ pendingCheckout = void 0;
810
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie, locale).catch(() => null);
645
811
  if (orderRes?.ok) {
646
812
  cookie = mergeCookies(cookie, orderRes);
647
813
  const orderData = await orderRes.json().catch(() => null);
648
814
  if (orderData && typeof orderData === "object") {
649
815
  if (orderData.active === true) {
650
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
816
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
651
817
  } else if (typeof orderData.qr === "string" && orderData.qr) {
652
818
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
653
819
  cachedOrder = {
654
820
  at: Date.now(),
655
821
  origin,
822
+ locale,
656
823
  result: {
657
824
  status: "qr",
658
825
  qr,
@@ -661,12 +828,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
661
828
  }
662
829
  };
663
830
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
664
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
831
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
665
832
  }
666
833
  }
667
834
  }
668
835
  } else {
669
- const response = await phoneRequest(origin, "verify", phone, code);
836
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
670
837
  if (response.status !== 201)
671
838
  return phoneFailure(response.status);
672
839
  cookie = mergeCookies(void 0, response);
@@ -694,11 +861,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
694
861
  }
695
862
  if (cachedOrder?.result.status === "active")
696
863
  state.active = true;
864
+ if (!checkoutUrl && state.active !== true && await mustPayFirst()) {
865
+ await rememberSignIn(phone);
866
+ await waitFor(origin, token, phone);
867
+ return { ok: false, reason: "notPro" };
868
+ }
697
869
  return await writeSession(async () => {
698
870
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
699
871
  return phoneFailure();
700
- stopMagicPoll();
701
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
872
+ clearWaiting();
873
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
702
874
  ++generation;
703
875
  activeOrigin = origin;
704
876
  applyEntitlement(state);
@@ -712,12 +884,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
712
884
  }
713
885
  },
714
886
  async deactivate() {
715
- stopMagicPoll();
887
+ clearWaiting();
716
888
  pendingCheckout = void 0;
717
889
  cachedOrder = void 0;
718
890
  const saved = await writeSession(async () => {
719
891
  const previous = await storage.read();
720
- await storage.write(void 0);
892
+ await storage.write(signedOutRecord());
721
893
  ++generation;
722
894
  clearTimeout(timer);
723
895
  lastCheck = 0;
@@ -728,7 +900,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
728
900
  return;
729
901
  try {
730
902
  const { origin, token } = JSON.parse(saved);
731
- if (origin !== billingOrigin(getOrigin()))
903
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string")
732
904
  return;
733
905
  await fetch(origin + "/billing/v1/entitlement", {
734
906
  method: "DELETE",
@@ -772,7 +944,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
772
944
  },
773
945
  dispose() {
774
946
  disposed = true;
775
- stopMagicPoll();
947
+ clearWaiting();
776
948
  clearTimeout(trialTimer);
777
949
  clearTimeout(timer);
778
950
  clearTimeout(telemetryTimer);
@@ -800,31 +972,39 @@ function inferNodeHost() {
800
972
  }
801
973
  return "cli";
802
974
  }
803
- async function localInstallId() {
804
- const path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "install-id");
805
- let value;
975
+ async function atomicCreateIfMissing(path, initialContent) {
806
976
  try {
807
- value = (await readFile(path, "utf8")).trim();
977
+ return await readFile(path, "utf8");
808
978
  } catch (error) {
809
979
  if (error.code !== "ENOENT")
810
980
  throw error;
811
981
  await mkdir(dirname(path), { recursive: true, mode: 448 });
812
- const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
813
982
  const temporary = path + "." + randomUUID();
814
983
  try {
815
- await writeFile(temporary, generated, { mode: 384, flag: "wx" });
816
- await link(temporary, path).catch((err) => {
817
- if (err.code !== "EEXIST")
818
- throw err;
984
+ await writeFile(temporary, initialContent, { mode: 384, flag: "wx" });
985
+ await link(temporary, path).catch(async (err) => {
986
+ if (err.code === "EEXIST")
987
+ return;
988
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
989
+ await rename(temporary, path);
990
+ return;
991
+ }
992
+ throw err;
819
993
  });
820
994
  } finally {
821
- await rm(temporary, { force: true });
995
+ await rm(temporary, { force: true }).catch(() => {
996
+ });
822
997
  }
823
- value = (await readFile(path, "utf8")).trim();
998
+ return await readFile(path, "utf8");
824
999
  }
1000
+ }
1001
+ async function localInstallId() {
1002
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "install-id");
1003
+ const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
1004
+ const value = (await atomicCreateIfMissing(path, generated)).trim();
825
1005
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
826
1006
  }
827
- function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "billing-session")) {
1007
+ function fileSessionStorage(path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "billing-session")) {
828
1008
  return {
829
1009
  read: () => readFile(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
830
1010
  async write(token) {
@@ -842,40 +1022,28 @@ function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(
842
1022
  };
843
1023
  }
844
1024
  async function localTrialDeadline() {
845
- const path = join(homedir(), ".inkmap", "trial-start");
846
- const now = Date.now();
847
- let value;
848
- try {
849
- value = await readFile(path, "utf8");
850
- } catch (error) {
851
- if (error.code !== "ENOENT")
852
- throw error;
853
- await mkdir(dirname(path), { recursive: true, mode: 448 });
854
- const temporary = path + "." + randomUUID();
855
- try {
856
- await writeFile(temporary, String(now), { mode: 384, flag: "wx" });
857
- await link(temporary, path).catch((error2) => {
858
- if (error2.code !== "EEXIST")
859
- throw error2;
860
- });
861
- } finally {
862
- await rm(temporary, { force: true });
863
- }
864
- value = await readFile(path, "utf8");
865
- }
1025
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "trial-start");
1026
+ const value = await atomicCreateIfMissing(path, String(Date.now()));
866
1027
  const started = Number(value);
867
1028
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
868
1029
  }
869
- var AD_TTL = 6 * 60 * 60 * 1e3;
870
1030
 
871
1031
  // packages/cli/dist/server.js
872
1032
  import { spawn } from "node:child_process";
873
1033
  import { createHash, randomBytes } from "node:crypto";
874
1034
  import { watch } from "node:fs";
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";
1035
+ import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, realpath as realpath2, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
876
1036
  import { createServer } from "node:http";
1037
+ import { homedir as homedir3 } from "node:os";
1038
+ import { basename as basename2, delimiter as delimiter2, dirname as dirname3, extname, join as join3, normalize, relative as relative2, resolve as resolve2, sep as sep3 } from "node:path";
1039
+
1040
+ // packages/cli/dist/workspace-fs.js
1041
+ import { lstat, readdir, readFile as readFile2, realpath } from "node:fs/promises";
877
1042
  import { homedir as homedir2 } from "node:os";
878
- import { basename, delimiter, dirname as dirname2, extname, isAbsolute, join as join2, normalize, relative, resolve, sep } from "node:path";
1043
+ import { basename, delimiter, dirname as dirname2, isAbsolute, join as join2, posix, relative, resolve, sep as sep2, win32 } from "node:path";
1044
+ import { fileURLToPath } from "node:url";
1045
+ var say = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1046
+ var MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
879
1047
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
880
1048
  ".git",
881
1049
  ".hg",
@@ -898,15 +1066,50 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
898
1066
  "coverage",
899
1067
  ".tmp"
900
1068
  ]);
901
- function insideRoot(root, target) {
1069
+ var MARKMAP_RE = /\.markmap\.md$/i;
1070
+ function insideOrEqual(root, target) {
902
1071
  if (root === target)
903
1072
  return true;
904
1073
  const rel = relative(root, target);
905
- return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep));
1074
+ return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep2));
1075
+ }
1076
+ function hasHiddenSegment(root, target) {
1077
+ const rel = relative(root, target);
1078
+ if (!rel || rel === ".")
1079
+ return false;
1080
+ return rel.split(sep2).some((part) => part.startsWith("."));
1081
+ }
1082
+ async function hasSymlinkUnderRoot(realRoot, rawTarget) {
1083
+ let cur = rawTarget;
1084
+ while (cur && cur !== dirname2(cur)) {
1085
+ const st = await lstat(cur);
1086
+ if (st.isSymbolicLink())
1087
+ return true;
1088
+ if (await realpath(cur) === realRoot)
1089
+ return false;
1090
+ cur = dirname2(cur);
1091
+ }
1092
+ return false;
1093
+ }
1094
+ function uriToPath(uri, platform = process.platform) {
1095
+ if (typeof uri !== "string" || !uri.trim())
1096
+ return null;
1097
+ const trimmed = uri.trim();
1098
+ const windows = platform === "win32";
1099
+ try {
1100
+ if (trimmed.startsWith("file://")) {
1101
+ const path = fileURLToPath(trimmed.replace(/^file:\/\/\/([a-zA-Z])%3[aA](?=\/|$)/, "file:///$1:"), { windows });
1102
+ return windows && /^[a-zA-Z]:$/.test(path) ? path + "\\" : path;
1103
+ }
1104
+ if ((windows ? win32 : posix).isAbsolute(trimmed))
1105
+ return trimmed;
1106
+ } catch {
1107
+ }
1108
+ return null;
906
1109
  }
907
1110
  async function findProjectRoot(filePath) {
908
- let cur = dirname2(filePath);
909
1111
  const home = await realpath(homedir2()).catch(() => homedir2());
1112
+ let cur = dirname2(filePath);
910
1113
  while (cur && cur !== dirname2(cur) && cur !== home) {
911
1114
  try {
912
1115
  await lstat(join2(cur, ".git"));
@@ -917,7 +1120,7 @@ async function findProjectRoot(filePath) {
917
1120
  }
918
1121
  return dirname2(filePath);
919
1122
  }
920
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1123
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
921
1124
  const found = [];
922
1125
  async function walk(dir, depth) {
923
1126
  if (depth > maxDepth || found.length >= maxFiles)
@@ -939,12 +1142,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
939
1142
  await walk(full, depth + 1);
940
1143
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
941
1144
  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
- }
1145
+ const info = await lstat(full);
1146
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1147
+ continue;
1148
+ const real = await realpath(full);
1149
+ if (real === full && insideOrEqual(rootDir, real))
1150
+ found.push({ path: real, mtimeMs: info.mtimeMs });
948
1151
  } catch {
949
1152
  }
950
1153
  }
@@ -952,14 +1155,166 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
952
1155
  }
953
1156
  await walk(rootDir, 0);
954
1157
  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);
1158
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1159
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1160
+ if (am !== bm)
1161
+ return am - bm;
1162
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1163
+ return b.mtimeMs - a.mtimeMs;
1164
+ return a.path.localeCompare(b.path);
960
1165
  });
961
1166
  return found;
962
1167
  }
1168
+ async function discoverAntigravityProjects() {
1169
+ const projectsDir = join2(process.env.ANTIGRAVITY_CONFIG_DIR || join2(homedir2(), ".gemini", "config"), "projects");
1170
+ const roots = [];
1171
+ let entries = [];
1172
+ try {
1173
+ entries = await readdir(projectsDir);
1174
+ } catch {
1175
+ return roots;
1176
+ }
1177
+ for (const name of entries) {
1178
+ if (!name.endsWith(".json"))
1179
+ continue;
1180
+ try {
1181
+ const data = JSON.parse(await readFile2(join2(projectsDir, name), "utf8"));
1182
+ const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
1183
+ for (const r of resources) {
1184
+ const p = uriToPath(r?.gitFolder?.folderUri || r?.folderUri);
1185
+ if (!p)
1186
+ continue;
1187
+ const real = await realpath(p).catch(() => null);
1188
+ if (real)
1189
+ roots.push({ path: real, name: String(data.name || basename(real)) });
1190
+ }
1191
+ } catch {
1192
+ }
1193
+ }
1194
+ return roots;
1195
+ }
1196
+ function targetStateFile() {
1197
+ return join2(process.env.INKMAP_HOME || join2(homedir2(), ".inkmap"), "antigravity-target.json");
1198
+ }
1199
+ async function readTargetSelection() {
1200
+ try {
1201
+ const raw = JSON.parse(await readFile2(targetStateFile(), "utf8"));
1202
+ if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
1203
+ return null;
1204
+ const info = await lstat(raw.file);
1205
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1206
+ return null;
1207
+ const file = await realpath(raw.file);
1208
+ if (file !== raw.file)
1209
+ return null;
1210
+ const workspace = typeof raw.workspace === "string" ? await realpath(raw.workspace).catch(() => dirname2(file)) : dirname2(file);
1211
+ if (!insideOrEqual(workspace, file))
1212
+ return null;
1213
+ return { file, workspace, seq: Number(raw.seq) || 0, ...raw.editorOnly === true && { editorOnly: true } };
1214
+ } catch {
1215
+ return null;
1216
+ }
1217
+ }
1218
+ function createSerialQueue() {
1219
+ let tail = Promise.resolve();
1220
+ return function serialized(work) {
1221
+ const next = tail.then(work);
1222
+ tail = next.catch(() => {
1223
+ });
1224
+ return next;
1225
+ };
1226
+ }
1227
+ function createWorkspaceAccess() {
1228
+ const sessionWorkspaces = /* @__PURE__ */ new Map();
1229
+ async function allowedRoots(extraWorkspaceUris = []) {
1230
+ const roots = /* @__PURE__ */ new Map();
1231
+ const home = await realpath(homedir2()).catch(() => homedir2());
1232
+ const configDir = await realpath(process.env.ANTIGRAVITY_CONFIG_DIR || join2(home, ".gemini", "config")).catch(() => "");
1233
+ const addRoot = async (rawPath, active, label) => {
1234
+ if (!rawPath)
1235
+ return;
1236
+ const real = await realpath(rawPath).catch(() => null);
1237
+ if (!real || dirname2(real) === real || real === home)
1238
+ return;
1239
+ if (configDir && insideOrEqual(configDir, real))
1240
+ return;
1241
+ const existing = roots.get(real);
1242
+ if (!existing)
1243
+ roots.set(real, { path: real, name: label || basename(real), active });
1244
+ else if (active)
1245
+ existing.active = true;
1246
+ };
1247
+ for (const raw of (process.env.INKMAP_WORKSPACES || "").split(delimiter).filter(Boolean)) {
1248
+ await addRoot(uriToPath(raw) || resolve(raw), true);
1249
+ }
1250
+ for (const uri of extraWorkspaceUris) {
1251
+ if (typeof uri === "string" && uri.trim())
1252
+ await addRoot(uriToPath(uri) || resolve(uri.trim()), true);
1253
+ }
1254
+ for (const [path, name] of sessionWorkspaces)
1255
+ await addRoot(path, true, name);
1256
+ const target = await readTargetSelection();
1257
+ if (target)
1258
+ await addRoot(target.workspace, roots.size === 0);
1259
+ for (const project of await discoverAntigravityProjects())
1260
+ await addRoot(project.path, false, project.name);
1261
+ if (roots.size === 0)
1262
+ await addRoot(process.cwd(), true);
1263
+ return { roots: [...roots.values()], target };
1264
+ }
1265
+ async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], registerOutside = false) {
1266
+ if (typeof candidatePath !== "string" || !candidatePath.trim()) {
1267
+ throw new Error(say("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002", "No Markdown file was given."));
1268
+ }
1269
+ const { roots, target } = await allowedRoots(extraWorkspaceUris);
1270
+ const trimmed = candidatePath.trim();
1271
+ let raw = uriToPath(trimmed);
1272
+ if (!raw) {
1273
+ const base = roots.find((r) => r.active)?.path || roots[0]?.path || process.cwd();
1274
+ raw = isAbsolute(trimmed) ? resolve(trimmed) : resolve(base, trimmed);
1275
+ }
1276
+ const notMarkdown = () => new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
1277
+ if (!/\.md$/i.test(raw))
1278
+ throw notMarkdown();
1279
+ const info = await lstat(raw).catch(() => null);
1280
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
1281
+ throw new Error(say("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002", "Choose a regular Markdown file up to 5 MiB."));
1282
+ }
1283
+ const real = await realpath(raw);
1284
+ if (!/\.md$/i.test(real))
1285
+ throw notMarkdown();
1286
+ const home = await realpath(homedir2()).catch(() => homedir2());
1287
+ const brainRoot = await realpath(join2(home, ".gemini", "antigravity", "brain")).catch(() => null);
1288
+ const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !hasHiddenSegment(brainRoot, real) && !await hasSymlinkUnderRoot(brainRoot, raw));
1289
+ const hiddenError = () => new Error(say("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002", "Files in hidden folders are not allowed."));
1290
+ const symlinkError = () => new Error(say("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002", "Files inside symlinked folders are not allowed."));
1291
+ if (!inBrainArtifact && insideOrEqual(home, real) && hasHiddenSegment(home, real))
1292
+ throw hiddenError();
1293
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, real));
1294
+ if (!inBrainArtifact && !(target && target.file === real) && !matchedRoot) {
1295
+ if (!registerOutside) {
1296
+ throw new Error(say("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u6216\u9879\u76EE\u76EE\u5F55\u5185\u3002", "This file is outside the allowed workspaces and projects."));
1297
+ }
1298
+ const project = await findProjectRoot(real);
1299
+ if (await hasSymlinkUnderRoot(project, raw))
1300
+ throw symlinkError();
1301
+ if (hasHiddenSegment(project, real))
1302
+ throw hiddenError();
1303
+ sessionWorkspaces.set(project, basename(project));
1304
+ return real;
1305
+ }
1306
+ if (matchedRoot) {
1307
+ if (await hasSymlinkUnderRoot(matchedRoot.path, raw))
1308
+ throw symlinkError();
1309
+ if (hasHiddenSegment(matchedRoot.path, real))
1310
+ throw hiddenError();
1311
+ }
1312
+ return real;
1313
+ }
1314
+ return { allowedRoots, assertAllowedFile };
1315
+ }
1316
+
1317
+ // packages/cli/dist/server.js
963
1318
  var MAX_BODY = 20 * 1024 * 1024;
964
1319
  var TYPES = {
965
1320
  ".html": "text/html; charset=utf-8",
@@ -971,29 +1326,40 @@ var TYPES = {
971
1326
  ".jpeg": "image/jpeg",
972
1327
  ".gif": "image/gif",
973
1328
  ".webp": "image/webp",
1329
+ ".avif": "image/avif",
1330
+ ".bmp": "image/bmp",
1331
+ ".ico": "image/x-icon",
974
1332
  ".woff2": "font/woff2",
975
1333
  ".woff": "font/woff",
976
1334
  ".ttf": "font/ttf",
977
1335
  ".json": "application/json"
978
1336
  };
1337
+ var HttpError = class extends Error {
1338
+ status;
1339
+ constructor(status, message) {
1340
+ super(message);
1341
+ this.status = status;
1342
+ }
1343
+ };
1344
+ var LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
979
1345
  var hash = (s) => createHash("sha1").update(s).digest("hex");
980
1346
  function docName(path) {
981
- return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1347
+ return basename2(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
982
1348
  }
983
1349
  function viewStateFile(key) {
984
- const base = process.env.INKMAP_HOME ?? join2(homedir2(), ".inkmap");
985
- return join2(base, "view-state", hash(key) + ".json");
1350
+ const base = process.env.INKMAP_HOME || join3(homedir3(), ".inkmap");
1351
+ return join3(base, "view-state", hash(key) + ".json");
986
1352
  }
987
1353
  async function readDiskViewState(key) {
988
1354
  try {
989
- return sanitizeViewState(JSON.parse(await readFile2(viewStateFile(key), "utf8")));
1355
+ return sanitizeViewState(JSON.parse(await readFile3(viewStateFile(key), "utf8")));
990
1356
  } catch {
991
1357
  return void 0;
992
1358
  }
993
1359
  }
994
1360
  async function writeDiskViewState(key, state) {
995
1361
  const target = viewStateFile(key);
996
- await mkdir2(dirname2(target), { recursive: true, mode: 448 });
1362
+ await mkdir2(dirname3(target), { recursive: true, mode: 448 });
997
1363
  const temp = `${target}.${process.pid}.${Date.now()}`;
998
1364
  try {
999
1365
  await writeFile2(temp, JSON.stringify(state), { mode: 384 });
@@ -1005,24 +1371,26 @@ async function writeDiskViewState(key, state) {
1005
1371
  }
1006
1372
  async function fileSource(file, log = () => {
1007
1373
  }) {
1008
- const path = await realpath(resolve(file)).catch(() => resolve(file));
1374
+ const path = await realpath2(resolve2(file)).catch(() => resolve2(file));
1009
1375
  if (!(await stat(path)).isFile())
1010
1376
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1011
- const dir = dirname2(path);
1377
+ const dir = dirname3(path);
1012
1378
  return {
1013
1379
  name: docName(path),
1014
1380
  key: path,
1015
1381
  dir,
1016
- read: () => readFile2(path, "utf8"),
1382
+ read: () => readFile3(path, "utf8"),
1017
1383
  async write(md) {
1018
1384
  await writeFile2(path, md, "utf8");
1019
1385
  log(`\u5DF2\u5199\u56DE ${path}`);
1020
1386
  },
1021
1387
  watch(onChange) {
1022
1388
  const watcher = watch(dir, (_, changed) => {
1023
- if (!changed || changed === basename(path))
1389
+ if (!changed || changed === basename2(path))
1024
1390
  onChange();
1025
1391
  });
1392
+ watcher.on("error", () => {
1393
+ });
1026
1394
  return () => watcher.close();
1027
1395
  },
1028
1396
  readView: () => readDiskViewState(path),
@@ -1030,8 +1398,15 @@ async function fileSource(file, log = () => {
1030
1398
  };
1031
1399
  }
1032
1400
  function within(root, rel) {
1033
- const base = root.endsWith(sep) ? root : root + sep;
1034
- const full = normalize(join2(root, decodeURIComponent(rel)));
1401
+ let decoded;
1402
+ try {
1403
+ decoded = decodeURIComponent(rel);
1404
+ } catch {
1405
+ return null;
1406
+ }
1407
+ const resolvedRoot = resolve2(root);
1408
+ const base = resolvedRoot.endsWith(sep3) ? resolvedRoot : resolvedRoot + sep3;
1409
+ const full = normalize(join3(resolvedRoot, decoded));
1035
1410
  return full.startsWith(base) ? full : null;
1036
1411
  }
1037
1412
  async function openBrowserWindow(url) {
@@ -1060,7 +1435,7 @@ async function openBrowserWindow(url) {
1060
1435
  await run("xdg-open", [url]);
1061
1436
  }
1062
1437
  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 = [] }) {
1438
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1064
1439
  if (sidebar && host !== "127.0.0.1")
1065
1440
  throw new Error("The sidebar bridge requires loopback.");
1066
1441
  const prefix = sidebar ? `/s/${randomBytes(24).toString("hex")}/` : "/";
@@ -1071,7 +1446,9 @@ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.
1071
1446
  let version = hash(current);
1072
1447
  let viewState = await activeSource.readView?.();
1073
1448
  const clients = /* @__PURE__ */ new Set();
1074
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1449
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1450
+ const allowedHosts = /* @__PURE__ */ new Set();
1451
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1075
1452
  const docState = () => ({
1076
1453
  name: activeSource.name,
1077
1454
  md: current,
@@ -1106,36 +1483,36 @@ data: ${JSON.stringify(data)}
1106
1483
  broadcast();
1107
1484
  }
1108
1485
  let pending;
1109
- let unwatch = activeSource.watch(() => {
1486
+ const scheduleRefresh = () => {
1110
1487
  clearTimeout(pending);
1111
- pending = setTimeout(async () => {
1112
- void serialized(refresh).catch(() => {
1113
- });
1114
- }, 80);
1115
- });
1488
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1489
+ }), 80);
1490
+ };
1491
+ let unwatch = activeSource.watch(scheduleRefresh);
1492
+ const canonicalActiveKey = async () => activeSource.key ? await realpath2(activeSource.key).catch(() => activeSource.key) : void 0;
1116
1493
  async function collectWorkspaceFiles() {
1117
1494
  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 });
1495
+ if (activeSource.key && !confineToWorkspaceRoots) {
1496
+ const realKey = await realpath2(activeSource.key).catch(() => activeSource.key);
1497
+ const projRoot = await realpath2(await findProjectRoot(realKey)).catch(() => dirname3(realKey));
1498
+ roots.set(projRoot, { path: projRoot, name: basename2(projRoot), active: true });
1122
1499
  }
1123
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter)].filter(Boolean);
1500
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter2)].filter(Boolean);
1124
1501
  for (const raw of envRoots) {
1125
- const real = await realpath(resolve(raw)).catch(() => null);
1502
+ const real = await realpath2(resolve2(raw)).catch(() => null);
1126
1503
  if (real && !roots.has(real)) {
1127
- roots.set(real, { path: real, name: basename(real), active: roots.size === 0 });
1504
+ roots.set(real, { path: real, name: basename2(real), active: roots.size === 0 });
1128
1505
  }
1129
1506
  }
1130
1507
  const items = [];
1131
1508
  const seen = /* @__PURE__ */ new Set();
1132
1509
  for (const root of roots.values()) {
1133
- const files = await scanProjectMarkdownFiles(root.path);
1510
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1134
1511
  for (const f of files) {
1135
1512
  if (seen.has(f))
1136
1513
  continue;
1137
1514
  seen.add(f);
1138
- const rel = relative(root.path, f);
1515
+ const rel = relative2(root.path, f);
1139
1516
  items.push({
1140
1517
  path: f,
1141
1518
  label: `${root.name} / ${rel}`,
@@ -1143,43 +1520,52 @@ data: ${JSON.stringify(data)}
1143
1520
  });
1144
1521
  }
1145
1522
  }
1146
- if (activeSource.key && !seen.has(activeSource.key)) {
1523
+ const activeReal = await canonicalActiveKey();
1524
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1147
1525
  items.unshift({
1148
1526
  path: activeSource.key,
1149
- label: `${basename(activeSource.dir)} / ${basename(activeSource.key)}`,
1527
+ label: `${basename2(activeSource.dir)} / ${basename2(activeSource.key)}`,
1150
1528
  group: "active"
1151
1529
  });
1152
1530
  }
1153
1531
  return { roots: [...roots.values()], files: items };
1154
1532
  }
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");
1533
+ const zh = () => detectOsLocale() === "zh";
1534
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1535
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1536
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1537
+ throw notMarkdown();
1538
+ const resolvedCandidate = resolve2(candidatePath);
1539
+ const rawStat = await lstat2(resolvedCandidate).catch(() => null);
1540
+ const realTarget = await realpath2(resolvedCandidate).catch(() => null);
1541
+ const targetStat = realTarget ? await stat(realTarget).catch(() => null) : null;
1542
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1543
+ throw new HttpError(403, zh() ? "\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002" : "Choose a regular Markdown file up to 5 MiB.");
1163
1544
  }
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");
1545
+ if (!/\.md$/i.test(realTarget))
1546
+ throw notMarkdown();
1547
+ if (!trustCaller) {
1548
+ const { roots } = await collectWorkspaceFiles();
1549
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, realTarget));
1550
+ if (!matchedRoot) {
1551
+ throw new HttpError(403, zh() ? "\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002" : "This file is outside the current workspace.");
1552
+ }
1553
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1554
+ throw new HttpError(403, zh() ? "\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002" : "Files in hidden folders are not allowed.");
1555
+ }
1167
1556
  }
1168
- if (activeSource.key === realTarget)
1557
+ if (await canonicalActiveKey() === realTarget)
1169
1558
  return;
1559
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1560
+ const text = await next.read();
1561
+ const nextView = await next.readView?.();
1170
1562
  clearTimeout(pending);
1171
1563
  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
- });
1564
+ activeSource = next;
1565
+ current = text;
1566
+ version = hash(text);
1567
+ viewState = nextView;
1568
+ unwatch = activeSource.watch(scheduleRefresh);
1183
1569
  broadcast();
1184
1570
  }
1185
1571
  const json = (res, status, body) => {
@@ -1192,7 +1578,7 @@ data: ${JSON.stringify(data)}
1192
1578
  req.on("data", (c) => {
1193
1579
  size += c.length;
1194
1580
  if (size > MAX_BODY) {
1195
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1581
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1196
1582
  req.destroy();
1197
1583
  } else
1198
1584
  chunks.push(c);
@@ -1207,13 +1593,20 @@ data: ${JSON.stringify(data)}
1207
1593
  const ext = extname(full).toLowerCase();
1208
1594
  if (ext === ".html") {
1209
1595
  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}">`);
1596
+ const htmlText = (await readFile3(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1211
1597
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1212
1598
  res.end(htmlText, "utf8");
1213
1599
  return;
1214
1600
  }
1215
- const body = await readFile2(full);
1216
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1601
+ const body = await readFile3(full);
1602
+ const headers = {
1603
+ "content-type": TYPES[ext] ?? "application/octet-stream",
1604
+ "cache-control": sidebar ? "no-store" : "no-cache"
1605
+ };
1606
+ if (ext === ".svg") {
1607
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
1608
+ }
1609
+ res.writeHead(200, headers);
1217
1610
  res.end(body);
1218
1611
  } catch {
1219
1612
  json(res, 404, { error: "not found" });
@@ -1222,18 +1615,27 @@ data: ${JSON.stringify(data)}
1222
1615
  const server = createServer(async (req, res) => {
1223
1616
  try {
1224
1617
  const url = new URL(req.url ?? "/", "http://localhost");
1618
+ const reqHost = req.headers.host ?? "";
1619
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1225
1620
  if (sidebar) {
1226
1621
  res.setHeader("Referrer-Policy", "no-referrer");
1227
1622
  res.setHeader("X-Content-Type-Options", "nosniff");
1228
1623
  res.setHeader("Cache-Control", "no-store");
1229
1624
  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))
1625
+ if (reqHost !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix))
1231
1626
  return json(res, 404, { error: "not found" });
1232
1627
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1233
1628
  return json(res, 403, { error: "forbidden" });
1234
1629
  }
1235
1630
  url.pathname = "/" + url.pathname.slice(prefix.length);
1631
+ } else if (!hostAllowed) {
1632
+ return json(res, 403, { error: "forbidden" });
1236
1633
  }
1634
+ const sameOriginWrite = () => {
1635
+ const origin = req.headers.origin;
1636
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
1637
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
1638
+ };
1237
1639
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1238
1640
  res.writeHead(302, { Location: "/" + url.search });
1239
1641
  return res.end();
@@ -1257,6 +1659,8 @@ data: ${JSON.stringify(data)}
1257
1659
  });
1258
1660
  }
1259
1661
  if (url.pathname === "/api/view" && req.method === "PUT") {
1662
+ if (!sameOriginWrite())
1663
+ return json(res, 403, { error: "forbidden" });
1260
1664
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1261
1665
  if (cleaned) {
1262
1666
  viewState = cleaned;
@@ -1266,9 +1670,11 @@ data: ${JSON.stringify(data)}
1266
1670
  return json(res, 200, { ok: true });
1267
1671
  }
1268
1672
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1673
+ if (!sameOriginWrite())
1674
+ return json(res, 403, { error: "forbidden" });
1269
1675
  const { md, baseVersion } = JSON.parse(await readBody(req));
1270
1676
  if (typeof md !== "string")
1271
- return json(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1677
+ return json(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1272
1678
  if (!hasAccess(await license?.state() ?? { pro: false }))
1273
1679
  return json(res, 403, { error: "Inkmap trial expired" });
1274
1680
  return await serialized(async () => {
@@ -1280,31 +1686,24 @@ data: ${JSON.stringify(data)}
1280
1686
  current = md;
1281
1687
  version = hash(md);
1282
1688
  license?.track?.("doc_edit");
1283
- if (sidebar)
1284
- broadcast();
1689
+ broadcast();
1285
1690
  }
1286
1691
  return json(res, 200, { version });
1287
1692
  });
1288
1693
  }
1289
1694
  if (url.pathname === "/api/license" && req.method === "GET")
1290
1695
  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
1696
  if (url.pathname === "/api/open" && req.method === "POST") {
1298
- if (!sameOriginPost())
1697
+ if (!sameOriginWrite())
1299
1698
  return json(res, 403, { error: "forbidden" });
1300
1699
  const { file } = JSON.parse(await readBody(req));
1301
- await serialized(() => switchSourceToFile(String(file ?? "")));
1700
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1302
1701
  license?.track?.("doc_open");
1303
1702
  const { files } = await collectWorkspaceFiles();
1304
1703
  return json(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1305
1704
  }
1306
1705
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1307
- if (!sameOriginPost())
1706
+ if (!sameOriginWrite())
1308
1707
  return json(res, 403, { error: "forbidden" });
1309
1708
  const { event } = JSON.parse(await readBody(req));
1310
1709
  if (typeof event === "string" && event)
@@ -1312,45 +1711,43 @@ data: ${JSON.stringify(data)}
1312
1711
  return json(res, 200, { ok: true });
1313
1712
  }
1314
1713
  if (url.pathname === "/api/open-browser" && req.method === "POST") {
1315
- if (!sameOriginPost())
1714
+ if (!sameOriginWrite())
1316
1715
  return json(res, 403, { error: "forbidden" });
1317
1716
  if (license && !hasAccess(await license.state())) {
1318
1717
  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
1718
  }
1320
1719
  license?.track?.("feature_browser");
1321
1720
  if (!sidebar) {
1322
- const directUrl = `http://${host}:${bound}/`;
1721
+ const directUrl = `http://${urlHost}:${bound}/`;
1323
1722
  await openBrowserWindow(directUrl);
1324
1723
  return json(res, 200, { ok: true, url: directUrl });
1325
1724
  }
1326
1725
  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
- })();
1726
+ browserCompanion = serve({
1727
+ source: activeSource,
1728
+ webRoot,
1729
+ host: "127.0.0.1",
1730
+ port: 0,
1731
+ license,
1732
+ sidebar: false,
1733
+ workspaceRoots,
1734
+ confineToWorkspaceRoots,
1735
+ openSource,
1736
+ allowPurchase: canPurchase
1737
+ });
1341
1738
  browserCompanion.catch(() => {
1342
1739
  browserCompanion = null;
1343
1740
  });
1344
1741
  }
1345
1742
  const companion = await browserCompanion;
1346
1743
  if (activeSource.key)
1347
- await companion.switchToFile?.(activeSource.key).catch(() => {
1744
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1348
1745
  });
1349
1746
  await openBrowserWindow(companion.url);
1350
1747
  return json(res, 200, { ok: true, url: companion.url });
1351
1748
  }
1352
1749
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1353
- if (!sameOriginPost())
1750
+ if (!sameOriginWrite())
1354
1751
  return json(res, 403, { error: "forbidden" });
1355
1752
  const { mode, locale } = JSON.parse(await readBody(req));
1356
1753
  if (mode !== "buy" && mode !== "restore")
@@ -1362,7 +1759,7 @@ data: ${JSON.stringify(data)}
1362
1759
  return json(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1363
1760
  }
1364
1761
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1365
- if (!sameOriginPost())
1762
+ if (!sameOriginWrite())
1366
1763
  return json(res, 403, { error: "forbidden" });
1367
1764
  if (!canPurchase)
1368
1765
  return json(res, 403, { error: "forbidden" });
@@ -1374,7 +1771,7 @@ data: ${JSON.stringify(data)}
1374
1771
  return json(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1375
1772
  }
1376
1773
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1377
- if (!sameOriginPost())
1774
+ if (!sameOriginWrite())
1378
1775
  return json(res, 403, { error: "forbidden" });
1379
1776
  if (!license || typeof license.sendPhoneCode !== "function")
1380
1777
  return json(res, 501, { fallback: true });
@@ -1382,21 +1779,21 @@ data: ${JSON.stringify(data)}
1382
1779
  return json(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1383
1780
  }
1384
1781
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1385
- if (!sameOriginPost())
1782
+ if (!sameOriginWrite())
1386
1783
  return json(res, 403, { error: "forbidden" });
1387
1784
  if (!license || typeof license.signInByPhone !== "function")
1388
1785
  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 ?? "")) });
1786
+ const { phone, code, locale } = JSON.parse(await readBody(req));
1787
+ return json(res, 200, {
1788
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
1789
+ });
1391
1790
  }
1392
1791
  if (url.pathname === "/api/signout" && req.method === "POST") {
1393
- if (!sameOriginPost())
1792
+ if (!sameOriginWrite())
1394
1793
  return json(res, 403, { error: "forbidden" });
1395
1794
  await license?.deactivate();
1396
1795
  return json(res, 200, await license?.state() ?? { pro: false });
1397
1796
  }
1398
- if (url.pathname === "/api/ads")
1399
- return json(res, 200, sidebar ? [] : await ads?.() ?? []);
1400
1797
  if (url.pathname === "/api/events") {
1401
1798
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1402
1799
  res.write(": connected\n\n");
@@ -1408,17 +1805,21 @@ data: ${JSON.stringify(data)}
1408
1805
  return void res.writeHead(204).end();
1409
1806
  if (url.pathname.startsWith("/doc-assets/")) {
1410
1807
  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)))
1808
+ if (asset) {
1809
+ const root = await realpath2(activeSource.dir).catch(() => null);
1810
+ asset = await realpath2(asset).catch(() => null);
1811
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
1812
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1415
1813
  asset = null;
1416
1814
  }
1417
1815
  return sendFile(res, asset);
1418
1816
  }
1419
1817
  return sendFile(res, within(webRoot, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1420
1818
  } catch (err) {
1421
- json(res, 500, { error: err instanceof Error ? err.message : String(err) });
1819
+ if (res.headersSent)
1820
+ return void res.end();
1821
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
1822
+ json(res, status, { error: err instanceof Error ? err.message : String(err) });
1422
1823
  }
1423
1824
  });
1424
1825
  const listen = (p) => new Promise((ok, fail) => {
@@ -1429,15 +1830,26 @@ data: ${JSON.stringify(data)}
1429
1830
  });
1430
1831
  });
1431
1832
  try {
1432
- bound = await listen(port);
1833
+ try {
1834
+ bound = await listen(port);
1835
+ } catch (err) {
1836
+ if (err.code !== "EADDRINUSE")
1837
+ throw err;
1838
+ bound = await listen(0);
1839
+ }
1433
1840
  } catch (err) {
1434
- if (err.code !== "EADDRINUSE")
1435
- throw err;
1436
- bound = await listen(0);
1841
+ clearTimeout(pending);
1842
+ unwatch();
1843
+ unlisten();
1844
+ throw err;
1437
1845
  }
1438
1846
  return {
1439
- url: `http://${host}:${bound}${prefix}`,
1440
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1847
+ url: `http://${urlHost}:${bound}${prefix}`,
1848
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
1849
+ allowHost: (extraHost) => {
1850
+ if (extraHost)
1851
+ allowedHosts.add(extraHost.toLowerCase());
1852
+ },
1441
1853
  close: () => new Promise((done) => {
1442
1854
  clearTimeout(pending);
1443
1855
  unwatch();
@@ -1452,79 +1864,8 @@ data: ${JSON.stringify(data)}
1452
1864
  };
1453
1865
  }
1454
1866
 
1455
- // packages/antigravity/src/select.mjs
1456
- import { randomUUID as randomUUID2 } from "node:crypto";
1457
- import { lstat as lstat2, mkdir as mkdir3, realpath as realpath2, rename as rename3, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
1458
- import { homedir as homedir3 } from "node:os";
1459
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
1460
- var MAX_BYTES = 5 * 1024 * 1024;
1461
- function targetStateFile() {
1462
- const base = process.env.INKMAP_HOME ?? join3(homedir3(), ".inkmap");
1463
- return join3(base, "antigravity-target.json");
1464
- }
1465
- function inside(root, file) {
1466
- const rel = relative2(root, file);
1467
- return Boolean(rel && !isAbsolute2(rel) && rel !== ".." && !rel.startsWith(".." + sep2));
1468
- }
1469
- async function selectTargetFile(rawFile, rawWorkspace) {
1470
- if (typeof rawFile !== "string" || !/\.md$/i.test(rawFile.trim())) {
1471
- throw new Error("\u8BF7\u6307\u5B9A\u4E00\u4E2A .md \u6216 .markmap.md \u6587\u4EF6\u8DEF\u5F84\u3002");
1472
- }
1473
- const candidate = resolve2(rawFile.trim());
1474
- const info = await lstat2(candidate);
1475
- if (!info.isFile() || info.size > MAX_BYTES) {
1476
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002");
1477
- }
1478
- const file = await realpath2(candidate);
1479
- if (file !== candidate && !/\.md$/i.test(file)) {
1480
- throw new Error("\u65E0\u6548\u7684 Markdown \u6587\u4EF6\u8DEF\u5F84\u3002");
1481
- }
1482
- let workspace = dirname3(file);
1483
- if (rawWorkspace) {
1484
- const resolvedWs = await realpath2(resolve2(rawWorkspace)).catch(() => null);
1485
- if (resolvedWs && inside(resolvedWs, file)) workspace = resolvedWs;
1486
- } else {
1487
- const cwd = await realpath2(process.cwd()).catch(() => null);
1488
- if (cwd && inside(cwd, file)) workspace = cwd;
1489
- }
1490
- const statePath = targetStateFile();
1491
- await mkdir3(dirname3(statePath), { recursive: true, mode: 448 });
1492
- const temp = `${statePath}.${process.pid}.${randomUUID2()}`;
1493
- const payload = { file, workspace, seq: Date.now() };
1494
- try {
1495
- await writeFile3(temp, JSON.stringify(payload, null, 2) + "\n", { mode: 384 });
1496
- await rename3(temp, statePath);
1497
- } finally {
1498
- await rm3(temp, { force: true }).catch(() => {
1499
- });
1500
- }
1501
- return payload;
1502
- }
1503
- if (process.argv[1] && /select\.m?js$/i.test(process.argv[1])) {
1504
- const args = process.argv.slice(2);
1505
- let fileArg = "";
1506
- let workspaceArg = "";
1507
- for (let i = 0; i < args.length; i++) {
1508
- if (args[i] === "--workspace" && args[i + 1]) {
1509
- workspaceArg = args[++i];
1510
- } else if (!fileArg) {
1511
- fileArg = args[i];
1512
- }
1513
- }
1514
- selectTargetFile(fileArg, workspaceArg).then(
1515
- ({ file }) => {
1516
- console.log(`\u5DF2\u9009\u5B9A Inkmap \u6587\u6863\uFF1A${file}`);
1517
- console.log("\u5728\u5BF9\u8BDD\u4E2D\u8F93\u51FA\u4EE5\u4E0B\u80F6\u56CA\u6309\u94AE\u5373\u53EF\u5728\u53F3\u4FA7\u6253\u5F00\uFF1A[Inkmap](sidecar://inkmap/inkmap/)");
1518
- },
1519
- (error) => {
1520
- console.error(error instanceof Error ? error.message : String(error));
1521
- process.exitCode = 1;
1522
- }
1523
- );
1524
- }
1525
-
1526
1867
  // packages/antigravity/src/main.mjs
1527
- var __dirname = dirname4(fileURLToPath(import.meta.url));
1868
+ var __dirname = dirname4(fileURLToPath2(import.meta.url));
1528
1869
  var defaultWebRoot = join4(__dirname, "web");
1529
1870
  var SidecarResponse = class {
1530
1871
  constructor(body, { contentType = "text/plain", status = 200, headers } = {}) {
@@ -1534,27 +1875,6 @@ var SidecarResponse = class {
1534
1875
  this.headers = headers;
1535
1876
  }
1536
1877
  };
1537
- var MAX_BYTES2 = 5 * 1024 * 1024;
1538
- var MAX_SCAN_DEPTH = 4;
1539
- var MAX_FILES = 200;
1540
- var SKIP_DIRS = /* @__PURE__ */ new Set([
1541
- ".git",
1542
- ".hg",
1543
- ".svn",
1544
- "node_modules",
1545
- "dist",
1546
- "build",
1547
- "out",
1548
- ".next",
1549
- ".nuxt",
1550
- ".agents",
1551
- ".agent",
1552
- ".gemini",
1553
- ".venv",
1554
- "venv",
1555
- "target",
1556
- "coverage"
1557
- ]);
1558
1878
  var TYPES2 = {
1559
1879
  ".html": "text/html; charset=utf-8",
1560
1880
  ".js": "application/javascript; charset=utf-8",
@@ -1565,103 +1885,15 @@ var TYPES2 = {
1565
1885
  ".jpeg": "image/jpeg",
1566
1886
  ".gif": "image/gif",
1567
1887
  ".webp": "image/webp",
1888
+ ".avif": "image/avif",
1889
+ ".bmp": "image/bmp",
1890
+ ".ico": "image/x-icon",
1568
1891
  ".woff2": "font/woff2",
1569
1892
  ".woff": "font/woff",
1570
1893
  ".ttf": "font/ttf",
1571
1894
  ".json": "application/json; charset=utf-8"
1572
1895
  };
1573
1896
  var hash2 = (text) => createHash2("sha1").update(text).digest("hex");
1574
- function insideOrEqual(root, target) {
1575
- if (root === target) return true;
1576
- const rel = relative3(root, target);
1577
- return Boolean(rel && !isAbsolute3(rel) && rel !== ".." && !rel.startsWith(".." + sep3));
1578
- }
1579
- function uriToPath(uri) {
1580
- if (typeof uri !== "string" || !uri) return null;
1581
- try {
1582
- if (uri.startsWith("file://")) return fileURLToPath(uri);
1583
- if (isAbsolute3(uri)) return uri;
1584
- } catch {
1585
- }
1586
- return null;
1587
- }
1588
- async function readTargetSelection() {
1589
- try {
1590
- const raw = JSON.parse(await readFile3(targetStateFile(), "utf8"));
1591
- if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file)) return null;
1592
- const file = await realpath3(raw.file);
1593
- const info = await lstat3(file);
1594
- if (!info.isFile() || info.size > MAX_BYTES2) return null;
1595
- const workspace = typeof raw.workspace === "string" ? await realpath3(raw.workspace).catch(() => dirname4(file)) : dirname4(file);
1596
- if (!insideOrEqual(workspace, file)) return null;
1597
- return { file, workspace, seq: Number(raw.seq) || 0 };
1598
- } catch {
1599
- return null;
1600
- }
1601
- }
1602
- async function discoverAntigravityProjects() {
1603
- const projectsDir = join4(process.env.ANTIGRAVITY_CONFIG_DIR || join4(homedir4(), ".gemini", "config"), "projects");
1604
- const roots = [];
1605
- let entries = [];
1606
- try {
1607
- entries = await readdir2(projectsDir);
1608
- } catch {
1609
- return roots;
1610
- }
1611
- for (const name of entries) {
1612
- if (!name.endsWith(".json")) continue;
1613
- try {
1614
- const data = JSON.parse(await readFile3(join4(projectsDir, name), "utf8"));
1615
- const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
1616
- for (const r of resources) {
1617
- const uri = r?.gitFolder?.folderUri || r?.folderUri;
1618
- const p = uriToPath(uri);
1619
- if (!p) continue;
1620
- const real = await realpath3(p).catch(() => null);
1621
- if (real) roots.push({ path: real, name: data.name || basename2(real) });
1622
- }
1623
- } catch {
1624
- }
1625
- }
1626
- return roots;
1627
- }
1628
- async function scanMarkdownFiles(rootDir) {
1629
- const found = [];
1630
- async function walk(dir, depth) {
1631
- if (depth > MAX_SCAN_DEPTH || found.length >= MAX_FILES) return;
1632
- let entries = [];
1633
- try {
1634
- entries = await readdir2(dir, { withFileTypes: true });
1635
- } catch {
1636
- return;
1637
- }
1638
- for (const entry of entries) {
1639
- if (found.length >= MAX_FILES) break;
1640
- if (entry.name.startsWith(".") && entry.isDirectory()) continue;
1641
- const full = join4(dir, entry.name);
1642
- if (entry.isDirectory()) {
1643
- if (!SKIP_DIRS.has(entry.name)) await walk(full, depth + 1);
1644
- } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
1645
- try {
1646
- const info = await lstat3(full);
1647
- if (info.isFile() && info.size <= MAX_BYTES2) {
1648
- const real = await realpath3(full);
1649
- if (insideOrEqual(rootDir, real)) found.push(real);
1650
- }
1651
- } catch {
1652
- }
1653
- }
1654
- }
1655
- }
1656
- await walk(rootDir, 0);
1657
- found.sort((a, b) => {
1658
- const aMarkmap = /\.markmap\.md$/i.test(a) ? 0 : 1;
1659
- const bMarkmap = /\.markmap\.md$/i.test(b) ? 0 : 1;
1660
- if (aMarkmap !== bMarkmap) return aMarkmap - bMarkmap;
1661
- return a.localeCompare(b);
1662
- });
1663
- return found;
1664
- }
1665
1897
  function openExternalUrl(url) {
1666
1898
  if (typeof url !== "string" || !/^https:\/\//i.test(url)) return;
1667
1899
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
@@ -1699,49 +1931,18 @@ function createAntigravitySidecar({
1699
1931
  let browserLicense = null;
1700
1932
  let browserServed = null;
1701
1933
  let activeFile = null;
1702
- async function allowedRoots(workspaceUris = []) {
1703
- const roots = /* @__PURE__ */ new Map();
1704
- const uris = Array.isArray(workspaceUris) ? workspaceUris : [];
1705
- for (const uri of uris) {
1706
- const p = uriToPath(uri);
1707
- if (!p) continue;
1708
- const real = await realpath3(p).catch(() => null);
1709
- if (real && !roots.has(real)) {
1710
- roots.set(real, { path: real, name: basename2(real), active: true });
1711
- }
1712
- }
1713
- const target = await readTargetSelection();
1714
- if (target && !roots.has(target.workspace)) {
1715
- roots.set(target.workspace, { path: target.workspace, name: basename2(target.workspace), active: roots.size === 0 });
1716
- }
1717
- for (const proj of await discoverAntigravityProjects()) {
1718
- if (!roots.has(proj.path)) {
1719
- roots.set(proj.path, { path: proj.path, name: proj.name, active: false });
1720
- }
1721
- }
1722
- if (roots.size === 0) {
1723
- const cwd = await realpath3(process.cwd()).catch(() => null);
1724
- if (cwd) roots.set(cwd, { path: cwd, name: basename2(cwd), active: true });
1725
- }
1726
- return { roots: [...roots.values()], target };
1727
- }
1728
- async function assertAllowedMarkdownFile(candidatePath, workspaceUris = []) {
1729
- if (typeof candidatePath !== "string" || !candidatePath.trim()) {
1730
- throw new Error("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002");
1731
- }
1732
- const raw = uriToPath(candidatePath.trim()) || resolve3(candidatePath.trim());
1733
- if (!/\.md$/i.test(raw)) throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1734
- const info = await lstat3(raw);
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");
1736
- const real = await realpath3(raw);
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}`));
1740
- const { roots, target } = await allowedRoots(workspaceUris);
1741
- const permitted = inBrainArtifact || target && target.file === real || roots.some((r) => insideOrEqual(r.path, real));
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");
1743
- return real;
1744
- }
1934
+ const serialized = createSerialQueue();
1935
+ const say2 = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1936
+ const browserRoots = [];
1937
+ const panelFiles = /* @__PURE__ */ new Map();
1938
+ const rememberPanel = (panel, file) => {
1939
+ if (typeof panel !== "string" || !panel || !file) return;
1940
+ panelFiles.delete(panel);
1941
+ panelFiles.set(panel, file);
1942
+ if (panelFiles.size > 64) panelFiles.delete(panelFiles.keys().next().value);
1943
+ };
1944
+ const { allowedRoots, assertAllowedFile } = createWorkspaceAccess();
1945
+ const assertAllowedMarkdownFile = (candidatePath, workspaceUris = []) => assertAllowedFile(candidatePath, workspaceUris);
1745
1946
  async function readDocState(filePath) {
1746
1947
  const source = await fileSource(filePath);
1747
1948
  const [md, viewState] = await Promise.all([source.read(), source.readView?.()]);
@@ -1762,7 +1963,7 @@ function createAntigravitySidecar({
1762
1963
  const seen = /* @__PURE__ */ new Set();
1763
1964
  if (target && !seen.has(target.file)) {
1764
1965
  const owner = roots.find((r) => insideOrEqual(r.path, target.file));
1765
- const rel = owner ? relative3(owner.path, target.file) : basename2(target.file);
1966
+ const rel = owner ? relative3(owner.path, target.file) : basename3(target.file);
1766
1967
  items.push({
1767
1968
  path: target.file,
1768
1969
  uri: pathToFileURL(target.file).href,
@@ -1772,7 +1973,7 @@ function createAntigravitySidecar({
1772
1973
  seen.add(target.file);
1773
1974
  }
1774
1975
  for (const root of roots) {
1775
- const files = await scanMarkdownFiles(root.path);
1976
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1776
1977
  for (const file of files) {
1777
1978
  if (seen.has(file)) continue;
1778
1979
  seen.add(file);
@@ -1788,32 +1989,23 @@ function createAntigravitySidecar({
1788
1989
  return { files: items, target };
1789
1990
  }
1790
1991
  const rawHtml = readFileSync(join4(webRoot, "index.html"), "utf8");
1791
- const pageHtml = rawHtml.replace(
1792
- "<head>",
1793
- '<head>\n <script src="/preload.js"></script>\n <script src="/bridge.js"></script>'
1794
- );
1992
+ const cspMeta = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob: https:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'">`;
1795
1993
  app.page("/", () => {
1796
- console.log("[inkmap] GET /");
1797
- return pageHtml;
1994
+ const osLoc = detectOsLocale();
1995
+ return rawHtml.replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`).replace("<head>", () => `<head>
1996
+ ${cspMeta}
1997
+ <script src="/preload.js"></script>
1998
+ <script src="/bridge.js"></script>`);
1798
1999
  });
1799
2000
  const bridgeJs = readFileSync(join4(__dirname, "bridge.js"), "utf8");
1800
- app.page("/bridge.js", () => {
1801
- console.log("[inkmap] GET /bridge.js");
1802
- return bridgeJs;
1803
- });
2001
+ app.page("/bridge.js", () => bridgeJs);
1804
2002
  app.api("/bridge.js", () => new SidecarResponse(bridgeJs, { contentType: "application/javascript; charset=utf-8" }), "GET");
2003
+ let preloadedAppJs = null;
1805
2004
  try {
1806
- const appJs = readFileSync(join4(webRoot, "app.js"), "utf8");
1807
- app.page("/app.js", () => {
1808
- console.log(`[inkmap] GET /app.js (${appJs.length} chars)`);
1809
- return appJs;
1810
- });
2005
+ preloadedAppJs = readFileSync(join4(webRoot, "app.js"), "utf8");
2006
+ app.page("/app.js", () => preloadedAppJs);
1811
2007
  } catch {
1812
2008
  }
1813
- app.api("/api/debug", async (data) => {
1814
- console.log("[inkmap] CLIENT_DEBUG:", JSON.stringify(data));
1815
- return { ok: true };
1816
- }, "POST");
1817
2009
  function registerStaticDir(dir, prefix = "") {
1818
2010
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1819
2011
  const full = join4(dir, entry.name);
@@ -1822,21 +2014,17 @@ function createAntigravitySidecar({
1822
2014
  registerStaticDir(full, route);
1823
2015
  } else if (entry.isFile() && route !== "/index.html") {
1824
2016
  const contentType = TYPES2[extname2(entry.name).toLowerCase()] || "application/octet-stream";
1825
- const body = readFileSync(full);
1826
- app.api(route, () => {
1827
- console.log(`[inkmap] GET ${route} (${body.length} bytes)`);
1828
- return new SidecarResponse(body, {
1829
- contentType,
1830
- headers: { "Cache-Control": "private, max-age=3600" }
1831
- });
1832
- }, "GET");
2017
+ const body = route === "/app.js" && preloadedAppJs ? Buffer.from(preloadedAppJs, "utf8") : readFileSync(full);
2018
+ app.api(route, () => new SidecarResponse(body, {
2019
+ contentType,
2020
+ headers: { "Cache-Control": "private, max-age=3600" }
2021
+ }), "GET");
1833
2022
  }
1834
2023
  }
1835
2024
  }
1836
2025
  registerStaticDir(webRoot);
1837
- app.api("/api/init", async (data) => {
2026
+ app.api("/api/init", (data) => serialized(async () => {
1838
2027
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1839
- console.log(`[inkmap] /api/init workspaces=${JSON.stringify(workspaceUris)} requested=${data?.requestedFile || ""}`);
1840
2028
  const { files, target } = await collectFiles(workspaceUris);
1841
2029
  let chosen = null;
1842
2030
  if (typeof data?.requestedFile === "string" && data.requestedFile.trim()) {
@@ -1862,13 +2050,17 @@ function createAntigravitySidecar({
1862
2050
  license: lic,
1863
2051
  doc: {
1864
2052
  name: "Inkmap",
1865
- md: "# Inkmap\n\n- \u8BF7\u5728\u5DE5\u4F5C\u533A\u4E2D\u6DFB\u52A0\u6216\u9009\u62E9\u4E00\u4EFD `.md` / `.markmap.md` \u6587\u4EF6\n- \u6216\u5728\u5BF9\u8BDD\u4E2D\u544A\u8BC9 AI\uFF1A\u300C\u7528 Inkmap \u6253\u5F00\u67D0\u6587\u4EF6\u300D\n",
2053
+ md: say2(
2054
+ "# Inkmap\n\n- \u8BF7\u5728\u5DE5\u4F5C\u533A\u4E2D\u6DFB\u52A0\u6216\u9009\u62E9\u4E00\u4EFD `.md` / `.markmap.md` \u6587\u4EF6\n- \u6216\u5728\u5BF9\u8BDD\u4E2D\u544A\u8BC9 AI\uFF1A\u300C\u7528 Inkmap \u6253\u5F00\u67D0\u6587\u4EF6\u300D\n",
2055
+ '# Inkmap\n\n- Add or pick a `.md` / `.markmap.md` file in this workspace\n- Or ask the AI: "Open <file> with Inkmap"\n'
2056
+ ),
1866
2057
  version: "empty",
1867
2058
  writable: false
1868
2059
  }
1869
2060
  };
1870
2061
  }
1871
2062
  activeFile = chosen;
2063
+ rememberPanel(data?.panel, chosen);
1872
2064
  license.track?.("doc_open", 1, "antigravity");
1873
2065
  const { doc } = await readDocState(chosen);
1874
2066
  return {
@@ -1879,11 +2071,12 @@ function createAntigravitySidecar({
1879
2071
  license: lic,
1880
2072
  doc
1881
2073
  };
1882
- }, "POST");
1883
- app.api("/api/open", async (data) => {
2074
+ }), "POST");
2075
+ app.api("/api/open", (data) => serialized(async () => {
1884
2076
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1885
2077
  const file = await assertAllowedMarkdownFile(data?.file, workspaceUris);
1886
2078
  activeFile = file;
2079
+ rememberPanel(data?.panel, file);
1887
2080
  license.track?.("doc_open", 1, "antigravity");
1888
2081
  const [{ doc }, { files, target }] = await Promise.all([
1889
2082
  readDocState(file),
@@ -1896,13 +2089,13 @@ function createAntigravitySidecar({
1896
2089
  targetSeq: target?.seq || 0,
1897
2090
  doc
1898
2091
  };
1899
- }, "POST");
1900
- const pollHandler = async (data) => {
2092
+ }), "POST");
2093
+ const pollHandler = (data) => serialized(async () => {
1901
2094
  const target = await readTargetSelection();
1902
2095
  const clientSeq = Number(data?.targetSeq) || 0;
1903
- if (target && target.seq > clientSeq && target.file !== data?.file) {
1904
- console.log(`[inkmap] /api/poll SWITCH data=${JSON.stringify(data)} targetSeq=${target.seq}`);
2096
+ if (target && target.seq > clientSeq && !target.editorOnly && target.file !== data?.file) {
1905
2097
  activeFile = target.file;
2098
+ rememberPanel(data?.panel, target.file);
1906
2099
  const { doc } = await readDocState(target.file);
1907
2100
  return {
1908
2101
  switchedFile: target.file,
@@ -1914,7 +2107,8 @@ function createAntigravitySidecar({
1914
2107
  const file = data?.file || activeFile;
1915
2108
  if (!file) return { unchanged: true, targetSeq: target?.seq || clientSeq };
1916
2109
  try {
1917
- const { doc } = await readDocState(file);
2110
+ const valid = await assertAllowedMarkdownFile(file, Array.isArray(data?.workspaceUris) ? data.workspaceUris : []);
2111
+ const { doc } = await readDocState(valid);
1918
2112
  if (data?.version && doc.version !== data.version) {
1919
2113
  return { changed: true, doc, targetSeq: target?.seq || clientSeq };
1920
2114
  }
@@ -1922,18 +2116,18 @@ function createAntigravitySidecar({
1922
2116
  } catch {
1923
2117
  return { unchanged: true, targetSeq: target?.seq || clientSeq };
1924
2118
  }
1925
- };
2119
+ });
1926
2120
  app.api("/api/poll", pollHandler, "GET");
1927
2121
  app.api("/api/poll", pollHandler, "POST");
1928
- app.api("/api/save", async (data) => {
2122
+ app.api("/api/save", (data) => serialized(async () => {
1929
2123
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1930
2124
  const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris);
1931
2125
  const md = data?.md;
1932
- if (typeof md !== "string" || Buffer.byteLength(md, "utf8") > MAX_BYTES2) {
1933
- throw new Error("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002");
2126
+ if (typeof md !== "string" || Buffer.byteLength(md, "utf8") > MAX_MARKDOWN_BYTES) {
2127
+ throw new Error(say2("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002", "The Markdown is invalid or larger than 5 MiB."));
1934
2128
  }
1935
2129
  if (!hasAccess(await license.state())) {
1936
- throw new Error("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u6216\u89E3\u9501 Pro\u3002");
2130
+ throw new Error(say2("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u6216\u89E3\u9501 Pro\u3002", "The Inkmap trial has ended. Sign in or unlock Pro."));
1937
2131
  }
1938
2132
  const { source, doc } = await readDocState(file);
1939
2133
  if (data?.baseVersion && data.baseVersion !== doc.version) {
@@ -1944,19 +2138,20 @@ function createAntigravitySidecar({
1944
2138
  license.track?.("doc_edit", 1, "antigravity");
1945
2139
  }
1946
2140
  return { ok: true, version: hash2(md) };
1947
- }, "POST");
2141
+ }), "POST");
1948
2142
  app.api("/api/telemetry", async (data) => {
1949
2143
  const ev = typeof data?.event === "string" ? data.event : "";
1950
2144
  if (ev) license.track?.(ev, 1, "antigravity");
1951
2145
  return { ok: true };
1952
2146
  }, "POST");
1953
- app.api("/api/open-browser", async (data) => {
2147
+ app.api("/api/open-browser", (data) => serialized(async () => {
1954
2148
  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");
2149
+ throw new Error(say2("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u5148\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro\u3002", "The Inkmap trial has ended. Sign in with the account that bought Pro first."));
1956
2150
  }
1957
2151
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1958
2152
  const targetFile = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris);
1959
2153
  const { roots } = await allowedRoots(workspaceUris);
2154
+ browserRoots.splice(0, browserRoots.length, ...roots.map((r) => r.path));
1960
2155
  license.track?.("feature_browser", 1, "antigravity");
1961
2156
  if (!browserServed) {
1962
2157
  browserServed = (async () => {
@@ -1968,8 +2163,7 @@ function createAntigravitySidecar({
1968
2163
  port: 0,
1969
2164
  license: browserLicense,
1970
2165
  sidebar: false,
1971
- loginOnly: false,
1972
- workspaceRoots: roots.map((r) => r.path)
2166
+ workspaceRoots: browserRoots
1973
2167
  });
1974
2168
  })();
1975
2169
  browserServed.catch(() => {
@@ -1977,12 +2171,12 @@ function createAntigravitySidecar({
1977
2171
  });
1978
2172
  }
1979
2173
  const served = await browserServed;
1980
- await served.switchToFile?.(targetFile).catch(() => {
2174
+ await served.switchToFile?.(targetFile, { trustCaller: true }).catch(() => {
1981
2175
  });
1982
2176
  await openBrowserWindow2(served.url);
1983
2177
  return { ok: true, url: served.url };
1984
- }, "POST");
1985
- app.api("/api/view", async (data) => {
2178
+ }), "POST");
2179
+ app.api("/api/view", (data) => serialized(async () => {
1986
2180
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1987
2181
  const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris).catch(() => null);
1988
2182
  if (!file) return { ok: false };
@@ -1993,18 +2187,21 @@ function createAntigravitySidecar({
1993
2187
  });
1994
2188
  }
1995
2189
  return { ok: true };
1996
- }, "POST");
2190
+ }), "POST");
1997
2191
  app.api("/api/license", async () => await license.state(), "GET");
1998
- app.api("/api/checkout", async () => {
1999
- const url = await license.connect("restore");
2192
+ app.api("/api/checkout", async (data) => {
2193
+ const locale = typeof data?.locale === "string" ? data.locale : void 0;
2194
+ const url = await license.connect("restore", locale);
2000
2195
  openExternalUrl(url);
2001
2196
  return { url };
2002
2197
  }, "POST");
2003
2198
  app.api("/api/phone-send", async (data) => {
2004
- return { result: await license.sendPhoneCode(String(data?.phone ?? "")) };
2199
+ const locale = typeof data?.locale === "string" ? data.locale : void 0;
2200
+ return { result: await license.sendPhoneCode(String(data?.phone ?? ""), locale) };
2005
2201
  }, "POST");
2006
2202
  app.api("/api/phone-verify", async (data) => {
2007
- return { result: await license.signInByPhone(String(data?.phone ?? ""), String(data?.code ?? "")) };
2203
+ const locale = typeof data?.locale === "string" ? data.locale : void 0;
2204
+ return { result: await license.signInByPhone(String(data?.phone ?? ""), String(data?.code ?? ""), locale) };
2008
2205
  }, "POST");
2009
2206
  app.api("/api/signout", async () => {
2010
2207
  await license.deactivate();
@@ -2012,7 +2209,7 @@ function createAntigravitySidecar({
2012
2209
  }, "POST");
2013
2210
  app.api("/api/doc-asset", async (data) => {
2014
2211
  const notFound = () => new SidecarResponse("not found", { status: 404 });
2015
- const file = activeFile;
2212
+ const file = typeof data?.panel === "string" && panelFiles.get(data.panel) || activeFile;
2016
2213
  const rel = typeof data?.path === "string" ? data.path.replace(/\?.*$/, "") : "";
2017
2214
  if (!file || !rel) return notFound();
2018
2215
  try {
@@ -2020,13 +2217,18 @@ function createAntigravitySidecar({
2020
2217
  const candidate = normalize2(join4(dir, decodeURIComponent(rel)));
2021
2218
  if (!insideOrEqual(dir, candidate) || candidate === dir) return notFound();
2022
2219
  const realAsset = await realpath3(candidate);
2023
- if (!insideOrEqual(dir, realAsset) || !/\.(?:png|jpe?g|gif|webp|svg)$/i.test(realAsset)) return notFound();
2220
+ if (!insideOrEqual(dir, realAsset) || !/\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i.test(realAsset)) return notFound();
2024
2221
  const info = await lstat3(realAsset);
2025
- if (!info.isFile() || info.size > MAX_BYTES2) return notFound();
2026
- const type = TYPES2[extname2(realAsset).toLowerCase()] || "application/octet-stream";
2027
- return new SidecarResponse(await readFile3(realAsset), {
2222
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES) return notFound();
2223
+ const ext = extname2(realAsset).toLowerCase();
2224
+ const type = TYPES2[ext] || "application/octet-stream";
2225
+ const headers = { "Cache-Control": "no-cache" };
2226
+ if (ext === ".svg") {
2227
+ headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
2228
+ }
2229
+ return new SidecarResponse(await readFile4(realAsset), {
2028
2230
  contentType: type,
2029
- headers: { "Cache-Control": "no-cache" }
2231
+ headers
2030
2232
  });
2031
2233
  } catch {
2032
2234
  return notFound();