inkmap-mcp 0.3.10 → 0.3.13

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.13";
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",
@@ -748,7 +920,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
748
920
  return;
749
921
  if (hostHint)
750
922
  detectedHost = hostHint;
751
- if (!sentAppOpen) {
923
+ if (!sentAppOpen && !PASSIVE_TELEMETRY_EVENTS.has(event)) {
752
924
  sentAppOpen = true;
753
925
  pendingEvents.set("app_open", (pendingEvents.get("app_open") ?? 0) + 1);
754
926
  }
@@ -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);
@@ -781,6 +953,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
781
953
  }
782
954
  };
783
955
  }
956
+ var PASSIVE_TELEMETRY_EVENTS = /* @__PURE__ */ new Set(["plugin_activate", "plugin_install", "onboarding_view"]);
784
957
  function inferNodeHost() {
785
958
  if (process.env.INKMAP_HOST)
786
959
  return process.env.INKMAP_HOST;
@@ -800,31 +973,39 @@ function inferNodeHost() {
800
973
  }
801
974
  return "cli";
802
975
  }
803
- async function localInstallId() {
804
- const path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "install-id");
805
- let value;
976
+ async function atomicCreateIfMissing(path, initialContent) {
806
977
  try {
807
- value = (await readFile(path, "utf8")).trim();
978
+ return await readFile(path, "utf8");
808
979
  } catch (error) {
809
980
  if (error.code !== "ENOENT")
810
981
  throw error;
811
982
  await mkdir(dirname(path), { recursive: true, mode: 448 });
812
- const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
813
983
  const temporary = path + "." + randomUUID();
814
984
  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;
985
+ await writeFile(temporary, initialContent, { mode: 384, flag: "wx" });
986
+ await link(temporary, path).catch(async (err) => {
987
+ if (err.code === "EEXIST")
988
+ return;
989
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
990
+ await rename(temporary, path);
991
+ return;
992
+ }
993
+ throw err;
819
994
  });
820
995
  } finally {
821
- await rm(temporary, { force: true });
996
+ await rm(temporary, { force: true }).catch(() => {
997
+ });
822
998
  }
823
- value = (await readFile(path, "utf8")).trim();
999
+ return await readFile(path, "utf8");
824
1000
  }
1001
+ }
1002
+ async function localInstallId() {
1003
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "install-id");
1004
+ const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
1005
+ const value = (await atomicCreateIfMissing(path, generated)).trim();
825
1006
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
826
1007
  }
827
- function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "billing-session")) {
1008
+ function fileSessionStorage(path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "billing-session")) {
828
1009
  return {
829
1010
  read: () => readFile(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
830
1011
  async write(token) {
@@ -842,40 +1023,28 @@ function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(
842
1023
  };
843
1024
  }
844
1025
  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
- }
1026
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "trial-start");
1027
+ const value = await atomicCreateIfMissing(path, String(Date.now()));
866
1028
  const started = Number(value);
867
1029
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
868
1030
  }
869
- var AD_TTL = 6 * 60 * 60 * 1e3;
870
1031
 
871
1032
  // packages/cli/dist/server.js
872
1033
  import { spawn } from "node:child_process";
873
1034
  import { createHash, randomBytes } from "node:crypto";
874
1035
  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";
1036
+ 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
1037
  import { createServer } from "node:http";
1038
+ import { homedir as homedir3 } from "node:os";
1039
+ 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";
1040
+
1041
+ // packages/cli/dist/workspace-fs.js
1042
+ import { lstat, readdir, readFile as readFile2, realpath } from "node:fs/promises";
877
1043
  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";
1044
+ import { basename, delimiter, dirname as dirname2, isAbsolute, join as join2, posix, relative, resolve, sep as sep2, win32 } from "node:path";
1045
+ import { fileURLToPath } from "node:url";
1046
+ var say = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1047
+ var MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
879
1048
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
880
1049
  ".git",
881
1050
  ".hg",
@@ -898,15 +1067,50 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
898
1067
  "coverage",
899
1068
  ".tmp"
900
1069
  ]);
901
- function insideRoot(root, target) {
1070
+ var MARKMAP_RE = /\.markmap\.md$/i;
1071
+ function insideOrEqual(root, target) {
902
1072
  if (root === target)
903
1073
  return true;
904
1074
  const rel = relative(root, target);
905
- return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep));
1075
+ return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep2));
1076
+ }
1077
+ function hasHiddenSegment(root, target) {
1078
+ const rel = relative(root, target);
1079
+ if (!rel || rel === ".")
1080
+ return false;
1081
+ return rel.split(sep2).some((part) => part.startsWith("."));
1082
+ }
1083
+ async function hasSymlinkUnderRoot(realRoot, rawTarget) {
1084
+ let cur = rawTarget;
1085
+ while (cur && cur !== dirname2(cur)) {
1086
+ const st = await lstat(cur);
1087
+ if (st.isSymbolicLink())
1088
+ return true;
1089
+ if (await realpath(cur) === realRoot)
1090
+ return false;
1091
+ cur = dirname2(cur);
1092
+ }
1093
+ return false;
1094
+ }
1095
+ function uriToPath(uri, platform = process.platform) {
1096
+ if (typeof uri !== "string" || !uri.trim())
1097
+ return null;
1098
+ const trimmed = uri.trim();
1099
+ const windows = platform === "win32";
1100
+ try {
1101
+ if (trimmed.startsWith("file://")) {
1102
+ const path = fileURLToPath(trimmed.replace(/^file:\/\/\/([a-zA-Z])%3[aA](?=\/|$)/, "file:///$1:"), { windows });
1103
+ return windows && /^[a-zA-Z]:$/.test(path) ? path + "\\" : path;
1104
+ }
1105
+ if ((windows ? win32 : posix).isAbsolute(trimmed))
1106
+ return trimmed;
1107
+ } catch {
1108
+ }
1109
+ return null;
906
1110
  }
907
1111
  async function findProjectRoot(filePath) {
908
- let cur = dirname2(filePath);
909
1112
  const home = await realpath(homedir2()).catch(() => homedir2());
1113
+ let cur = dirname2(filePath);
910
1114
  while (cur && cur !== dirname2(cur) && cur !== home) {
911
1115
  try {
912
1116
  await lstat(join2(cur, ".git"));
@@ -917,7 +1121,7 @@ async function findProjectRoot(filePath) {
917
1121
  }
918
1122
  return dirname2(filePath);
919
1123
  }
920
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1124
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
921
1125
  const found = [];
922
1126
  async function walk(dir, depth) {
923
1127
  if (depth > maxDepth || found.length >= maxFiles)
@@ -939,12 +1143,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
939
1143
  await walk(full, depth + 1);
940
1144
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
941
1145
  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
- }
1146
+ const info = await lstat(full);
1147
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1148
+ continue;
1149
+ const real = await realpath(full);
1150
+ if (real === full && insideOrEqual(rootDir, real))
1151
+ found.push({ path: real, mtimeMs: info.mtimeMs });
948
1152
  } catch {
949
1153
  }
950
1154
  }
@@ -952,14 +1156,166 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
952
1156
  }
953
1157
  await walk(rootDir, 0);
954
1158
  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);
1159
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1160
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1161
+ if (am !== bm)
1162
+ return am - bm;
1163
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1164
+ return b.mtimeMs - a.mtimeMs;
1165
+ return a.path.localeCompare(b.path);
960
1166
  });
961
1167
  return found;
962
1168
  }
1169
+ async function discoverAntigravityProjects() {
1170
+ const projectsDir = join2(process.env.ANTIGRAVITY_CONFIG_DIR || join2(homedir2(), ".gemini", "config"), "projects");
1171
+ const roots = [];
1172
+ let entries = [];
1173
+ try {
1174
+ entries = await readdir(projectsDir);
1175
+ } catch {
1176
+ return roots;
1177
+ }
1178
+ for (const name of entries) {
1179
+ if (!name.endsWith(".json"))
1180
+ continue;
1181
+ try {
1182
+ const data = JSON.parse(await readFile2(join2(projectsDir, name), "utf8"));
1183
+ const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
1184
+ for (const r of resources) {
1185
+ const p = uriToPath(r?.gitFolder?.folderUri || r?.folderUri);
1186
+ if (!p)
1187
+ continue;
1188
+ const real = await realpath(p).catch(() => null);
1189
+ if (real)
1190
+ roots.push({ path: real, name: String(data.name || basename(real)) });
1191
+ }
1192
+ } catch {
1193
+ }
1194
+ }
1195
+ return roots;
1196
+ }
1197
+ function targetStateFile() {
1198
+ return join2(process.env.INKMAP_HOME || join2(homedir2(), ".inkmap"), "antigravity-target.json");
1199
+ }
1200
+ async function readTargetSelection() {
1201
+ try {
1202
+ const raw = JSON.parse(await readFile2(targetStateFile(), "utf8"));
1203
+ if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
1204
+ return null;
1205
+ const info = await lstat(raw.file);
1206
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1207
+ return null;
1208
+ const file = await realpath(raw.file);
1209
+ if (file !== raw.file)
1210
+ return null;
1211
+ const workspace = typeof raw.workspace === "string" ? await realpath(raw.workspace).catch(() => dirname2(file)) : dirname2(file);
1212
+ if (!insideOrEqual(workspace, file))
1213
+ return null;
1214
+ return { file, workspace, seq: Number(raw.seq) || 0, ...raw.editorOnly === true && { editorOnly: true } };
1215
+ } catch {
1216
+ return null;
1217
+ }
1218
+ }
1219
+ function createSerialQueue() {
1220
+ let tail = Promise.resolve();
1221
+ return function serialized(work) {
1222
+ const next = tail.then(work);
1223
+ tail = next.catch(() => {
1224
+ });
1225
+ return next;
1226
+ };
1227
+ }
1228
+ function createWorkspaceAccess() {
1229
+ const sessionWorkspaces = /* @__PURE__ */ new Map();
1230
+ async function allowedRoots(extraWorkspaceUris = []) {
1231
+ const roots = /* @__PURE__ */ new Map();
1232
+ const home = await realpath(homedir2()).catch(() => homedir2());
1233
+ const configDir = await realpath(process.env.ANTIGRAVITY_CONFIG_DIR || join2(home, ".gemini", "config")).catch(() => "");
1234
+ const addRoot = async (rawPath, active, label) => {
1235
+ if (!rawPath)
1236
+ return;
1237
+ const real = await realpath(rawPath).catch(() => null);
1238
+ if (!real || dirname2(real) === real || real === home)
1239
+ return;
1240
+ if (configDir && insideOrEqual(configDir, real))
1241
+ return;
1242
+ const existing = roots.get(real);
1243
+ if (!existing)
1244
+ roots.set(real, { path: real, name: label || basename(real), active });
1245
+ else if (active)
1246
+ existing.active = true;
1247
+ };
1248
+ for (const raw of (process.env.INKMAP_WORKSPACES || "").split(delimiter).filter(Boolean)) {
1249
+ await addRoot(uriToPath(raw) || resolve(raw), true);
1250
+ }
1251
+ for (const uri of extraWorkspaceUris) {
1252
+ if (typeof uri === "string" && uri.trim())
1253
+ await addRoot(uriToPath(uri) || resolve(uri.trim()), true);
1254
+ }
1255
+ for (const [path, name] of sessionWorkspaces)
1256
+ await addRoot(path, true, name);
1257
+ const target = await readTargetSelection();
1258
+ if (target)
1259
+ await addRoot(target.workspace, roots.size === 0);
1260
+ for (const project of await discoverAntigravityProjects())
1261
+ await addRoot(project.path, false, project.name);
1262
+ if (roots.size === 0)
1263
+ await addRoot(process.cwd(), true);
1264
+ return { roots: [...roots.values()], target };
1265
+ }
1266
+ async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], registerOutside = false) {
1267
+ if (typeof candidatePath !== "string" || !candidatePath.trim()) {
1268
+ throw new Error(say("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002", "No Markdown file was given."));
1269
+ }
1270
+ const { roots, target } = await allowedRoots(extraWorkspaceUris);
1271
+ const trimmed = candidatePath.trim();
1272
+ let raw = uriToPath(trimmed);
1273
+ if (!raw) {
1274
+ const base = roots.find((r) => r.active)?.path || roots[0]?.path || process.cwd();
1275
+ raw = isAbsolute(trimmed) ? resolve(trimmed) : resolve(base, trimmed);
1276
+ }
1277
+ const notMarkdown = () => new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
1278
+ if (!/\.md$/i.test(raw))
1279
+ throw notMarkdown();
1280
+ const info = await lstat(raw).catch(() => null);
1281
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
1282
+ 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."));
1283
+ }
1284
+ const real = await realpath(raw);
1285
+ if (!/\.md$/i.test(real))
1286
+ throw notMarkdown();
1287
+ const home = await realpath(homedir2()).catch(() => homedir2());
1288
+ const brainRoot = await realpath(join2(home, ".gemini", "antigravity", "brain")).catch(() => null);
1289
+ const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !hasHiddenSegment(brainRoot, real) && !await hasSymlinkUnderRoot(brainRoot, raw));
1290
+ 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."));
1291
+ 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."));
1292
+ if (!inBrainArtifact && insideOrEqual(home, real) && hasHiddenSegment(home, real))
1293
+ throw hiddenError();
1294
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, real));
1295
+ if (!inBrainArtifact && !(target && target.file === real) && !matchedRoot) {
1296
+ if (!registerOutside) {
1297
+ 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."));
1298
+ }
1299
+ const project = await findProjectRoot(real);
1300
+ if (await hasSymlinkUnderRoot(project, raw))
1301
+ throw symlinkError();
1302
+ if (hasHiddenSegment(project, real))
1303
+ throw hiddenError();
1304
+ sessionWorkspaces.set(project, basename(project));
1305
+ return real;
1306
+ }
1307
+ if (matchedRoot) {
1308
+ if (await hasSymlinkUnderRoot(matchedRoot.path, raw))
1309
+ throw symlinkError();
1310
+ if (hasHiddenSegment(matchedRoot.path, real))
1311
+ throw hiddenError();
1312
+ }
1313
+ return real;
1314
+ }
1315
+ return { allowedRoots, assertAllowedFile };
1316
+ }
1317
+
1318
+ // packages/cli/dist/server.js
963
1319
  var MAX_BODY = 20 * 1024 * 1024;
964
1320
  var TYPES = {
965
1321
  ".html": "text/html; charset=utf-8",
@@ -971,29 +1327,40 @@ var TYPES = {
971
1327
  ".jpeg": "image/jpeg",
972
1328
  ".gif": "image/gif",
973
1329
  ".webp": "image/webp",
1330
+ ".avif": "image/avif",
1331
+ ".bmp": "image/bmp",
1332
+ ".ico": "image/x-icon",
974
1333
  ".woff2": "font/woff2",
975
1334
  ".woff": "font/woff",
976
1335
  ".ttf": "font/ttf",
977
1336
  ".json": "application/json"
978
1337
  };
1338
+ var HttpError = class extends Error {
1339
+ status;
1340
+ constructor(status, message) {
1341
+ super(message);
1342
+ this.status = status;
1343
+ }
1344
+ };
1345
+ var LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
979
1346
  var hash = (s) => createHash("sha1").update(s).digest("hex");
980
1347
  function docName(path) {
981
- return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1348
+ return basename2(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
982
1349
  }
983
1350
  function viewStateFile(key) {
984
- const base = process.env.INKMAP_HOME ?? join2(homedir2(), ".inkmap");
985
- return join2(base, "view-state", hash(key) + ".json");
1351
+ const base = process.env.INKMAP_HOME || join3(homedir3(), ".inkmap");
1352
+ return join3(base, "view-state", hash(key) + ".json");
986
1353
  }
987
1354
  async function readDiskViewState(key) {
988
1355
  try {
989
- return sanitizeViewState(JSON.parse(await readFile2(viewStateFile(key), "utf8")));
1356
+ return sanitizeViewState(JSON.parse(await readFile3(viewStateFile(key), "utf8")));
990
1357
  } catch {
991
1358
  return void 0;
992
1359
  }
993
1360
  }
994
1361
  async function writeDiskViewState(key, state) {
995
1362
  const target = viewStateFile(key);
996
- await mkdir2(dirname2(target), { recursive: true, mode: 448 });
1363
+ await mkdir2(dirname3(target), { recursive: true, mode: 448 });
997
1364
  const temp = `${target}.${process.pid}.${Date.now()}`;
998
1365
  try {
999
1366
  await writeFile2(temp, JSON.stringify(state), { mode: 384 });
@@ -1005,24 +1372,26 @@ async function writeDiskViewState(key, state) {
1005
1372
  }
1006
1373
  async function fileSource(file, log = () => {
1007
1374
  }) {
1008
- const path = await realpath(resolve(file)).catch(() => resolve(file));
1375
+ const path = await realpath2(resolve2(file)).catch(() => resolve2(file));
1009
1376
  if (!(await stat(path)).isFile())
1010
1377
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1011
- const dir = dirname2(path);
1378
+ const dir = dirname3(path);
1012
1379
  return {
1013
1380
  name: docName(path),
1014
1381
  key: path,
1015
1382
  dir,
1016
- read: () => readFile2(path, "utf8"),
1383
+ read: () => readFile3(path, "utf8"),
1017
1384
  async write(md) {
1018
1385
  await writeFile2(path, md, "utf8");
1019
1386
  log(`\u5DF2\u5199\u56DE ${path}`);
1020
1387
  },
1021
1388
  watch(onChange) {
1022
1389
  const watcher = watch(dir, (_, changed) => {
1023
- if (!changed || changed === basename(path))
1390
+ if (!changed || changed === basename2(path))
1024
1391
  onChange();
1025
1392
  });
1393
+ watcher.on("error", () => {
1394
+ });
1026
1395
  return () => watcher.close();
1027
1396
  },
1028
1397
  readView: () => readDiskViewState(path),
@@ -1030,8 +1399,15 @@ async function fileSource(file, log = () => {
1030
1399
  };
1031
1400
  }
1032
1401
  function within(root, rel) {
1033
- const base = root.endsWith(sep) ? root : root + sep;
1034
- const full = normalize(join2(root, decodeURIComponent(rel)));
1402
+ let decoded;
1403
+ try {
1404
+ decoded = decodeURIComponent(rel);
1405
+ } catch {
1406
+ return null;
1407
+ }
1408
+ const resolvedRoot = resolve2(root);
1409
+ const base = resolvedRoot.endsWith(sep3) ? resolvedRoot : resolvedRoot + sep3;
1410
+ const full = normalize(join3(resolvedRoot, decoded));
1035
1411
  return full.startsWith(base) ? full : null;
1036
1412
  }
1037
1413
  async function openBrowserWindow(url) {
@@ -1060,7 +1436,7 @@ async function openBrowserWindow(url) {
1060
1436
  await run("xdg-open", [url]);
1061
1437
  }
1062
1438
  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 = [] }) {
1439
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1064
1440
  if (sidebar && host !== "127.0.0.1")
1065
1441
  throw new Error("The sidebar bridge requires loopback.");
1066
1442
  const prefix = sidebar ? `/s/${randomBytes(24).toString("hex")}/` : "/";
@@ -1071,7 +1447,9 @@ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.
1071
1447
  let version = hash(current);
1072
1448
  let viewState = await activeSource.readView?.();
1073
1449
  const clients = /* @__PURE__ */ new Set();
1074
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1450
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1451
+ const allowedHosts = /* @__PURE__ */ new Set();
1452
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1075
1453
  const docState = () => ({
1076
1454
  name: activeSource.name,
1077
1455
  md: current,
@@ -1106,36 +1484,36 @@ data: ${JSON.stringify(data)}
1106
1484
  broadcast();
1107
1485
  }
1108
1486
  let pending;
1109
- let unwatch = activeSource.watch(() => {
1487
+ const scheduleRefresh = () => {
1110
1488
  clearTimeout(pending);
1111
- pending = setTimeout(async () => {
1112
- void serialized(refresh).catch(() => {
1113
- });
1114
- }, 80);
1115
- });
1489
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1490
+ }), 80);
1491
+ };
1492
+ let unwatch = activeSource.watch(scheduleRefresh);
1493
+ const canonicalActiveKey = async () => activeSource.key ? await realpath2(activeSource.key).catch(() => activeSource.key) : void 0;
1116
1494
  async function collectWorkspaceFiles() {
1117
1495
  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 });
1496
+ if (activeSource.key && !confineToWorkspaceRoots) {
1497
+ const realKey = await realpath2(activeSource.key).catch(() => activeSource.key);
1498
+ const projRoot = await realpath2(await findProjectRoot(realKey)).catch(() => dirname3(realKey));
1499
+ roots.set(projRoot, { path: projRoot, name: basename2(projRoot), active: true });
1122
1500
  }
1123
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter)].filter(Boolean);
1501
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter2)].filter(Boolean);
1124
1502
  for (const raw of envRoots) {
1125
- const real = await realpath(resolve(raw)).catch(() => null);
1503
+ const real = await realpath2(resolve2(raw)).catch(() => null);
1126
1504
  if (real && !roots.has(real)) {
1127
- roots.set(real, { path: real, name: basename(real), active: roots.size === 0 });
1505
+ roots.set(real, { path: real, name: basename2(real), active: roots.size === 0 });
1128
1506
  }
1129
1507
  }
1130
1508
  const items = [];
1131
1509
  const seen = /* @__PURE__ */ new Set();
1132
1510
  for (const root of roots.values()) {
1133
- const files = await scanProjectMarkdownFiles(root.path);
1511
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1134
1512
  for (const f of files) {
1135
1513
  if (seen.has(f))
1136
1514
  continue;
1137
1515
  seen.add(f);
1138
- const rel = relative(root.path, f);
1516
+ const rel = relative2(root.path, f);
1139
1517
  items.push({
1140
1518
  path: f,
1141
1519
  label: `${root.name} / ${rel}`,
@@ -1143,43 +1521,52 @@ data: ${JSON.stringify(data)}
1143
1521
  });
1144
1522
  }
1145
1523
  }
1146
- if (activeSource.key && !seen.has(activeSource.key)) {
1524
+ const activeReal = await canonicalActiveKey();
1525
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1147
1526
  items.unshift({
1148
1527
  path: activeSource.key,
1149
- label: `${basename(activeSource.dir)} / ${basename(activeSource.key)}`,
1528
+ label: `${basename2(activeSource.dir)} / ${basename2(activeSource.key)}`,
1150
1529
  group: "active"
1151
1530
  });
1152
1531
  }
1153
1532
  return { roots: [...roots.values()], files: items };
1154
1533
  }
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");
1534
+ const zh = () => detectOsLocale() === "zh";
1535
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1536
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1537
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1538
+ throw notMarkdown();
1539
+ const resolvedCandidate = resolve2(candidatePath);
1540
+ const rawStat = await lstat2(resolvedCandidate).catch(() => null);
1541
+ const realTarget = await realpath2(resolvedCandidate).catch(() => null);
1542
+ const targetStat = realTarget ? await stat(realTarget).catch(() => null) : null;
1543
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1544
+ 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
1545
  }
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");
1546
+ if (!/\.md$/i.test(realTarget))
1547
+ throw notMarkdown();
1548
+ if (!trustCaller) {
1549
+ const { roots } = await collectWorkspaceFiles();
1550
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, realTarget));
1551
+ if (!matchedRoot) {
1552
+ 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.");
1553
+ }
1554
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1555
+ 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.");
1556
+ }
1167
1557
  }
1168
- if (activeSource.key === realTarget)
1558
+ if (await canonicalActiveKey() === realTarget)
1169
1559
  return;
1560
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1561
+ const text = await next.read();
1562
+ const nextView = await next.readView?.();
1170
1563
  clearTimeout(pending);
1171
1564
  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
- });
1565
+ activeSource = next;
1566
+ current = text;
1567
+ version = hash(text);
1568
+ viewState = nextView;
1569
+ unwatch = activeSource.watch(scheduleRefresh);
1183
1570
  broadcast();
1184
1571
  }
1185
1572
  const json = (res, status, body) => {
@@ -1192,7 +1579,7 @@ data: ${JSON.stringify(data)}
1192
1579
  req.on("data", (c) => {
1193
1580
  size += c.length;
1194
1581
  if (size > MAX_BODY) {
1195
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1582
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1196
1583
  req.destroy();
1197
1584
  } else
1198
1585
  chunks.push(c);
@@ -1207,13 +1594,20 @@ data: ${JSON.stringify(data)}
1207
1594
  const ext = extname(full).toLowerCase();
1208
1595
  if (ext === ".html") {
1209
1596
  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}">`);
1597
+ const htmlText = (await readFile3(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1211
1598
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1212
1599
  res.end(htmlText, "utf8");
1213
1600
  return;
1214
1601
  }
1215
- const body = await readFile2(full);
1216
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1602
+ const body = await readFile3(full);
1603
+ const headers = {
1604
+ "content-type": TYPES[ext] ?? "application/octet-stream",
1605
+ "cache-control": sidebar ? "no-store" : "no-cache"
1606
+ };
1607
+ if (ext === ".svg") {
1608
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
1609
+ }
1610
+ res.writeHead(200, headers);
1217
1611
  res.end(body);
1218
1612
  } catch {
1219
1613
  json(res, 404, { error: "not found" });
@@ -1222,18 +1616,27 @@ data: ${JSON.stringify(data)}
1222
1616
  const server = createServer(async (req, res) => {
1223
1617
  try {
1224
1618
  const url = new URL(req.url ?? "/", "http://localhost");
1619
+ const reqHost = req.headers.host ?? "";
1620
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1225
1621
  if (sidebar) {
1226
1622
  res.setHeader("Referrer-Policy", "no-referrer");
1227
1623
  res.setHeader("X-Content-Type-Options", "nosniff");
1228
1624
  res.setHeader("Cache-Control", "no-store");
1229
1625
  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))
1626
+ if (reqHost !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix))
1231
1627
  return json(res, 404, { error: "not found" });
1232
1628
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1233
1629
  return json(res, 403, { error: "forbidden" });
1234
1630
  }
1235
1631
  url.pathname = "/" + url.pathname.slice(prefix.length);
1632
+ } else if (!hostAllowed) {
1633
+ return json(res, 403, { error: "forbidden" });
1236
1634
  }
1635
+ const sameOriginWrite = () => {
1636
+ const origin = req.headers.origin;
1637
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
1638
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
1639
+ };
1237
1640
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1238
1641
  res.writeHead(302, { Location: "/" + url.search });
1239
1642
  return res.end();
@@ -1257,6 +1660,8 @@ data: ${JSON.stringify(data)}
1257
1660
  });
1258
1661
  }
1259
1662
  if (url.pathname === "/api/view" && req.method === "PUT") {
1663
+ if (!sameOriginWrite())
1664
+ return json(res, 403, { error: "forbidden" });
1260
1665
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1261
1666
  if (cleaned) {
1262
1667
  viewState = cleaned;
@@ -1266,9 +1671,11 @@ data: ${JSON.stringify(data)}
1266
1671
  return json(res, 200, { ok: true });
1267
1672
  }
1268
1673
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1674
+ if (!sameOriginWrite())
1675
+ return json(res, 403, { error: "forbidden" });
1269
1676
  const { md, baseVersion } = JSON.parse(await readBody(req));
1270
1677
  if (typeof md !== "string")
1271
- return json(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1678
+ return json(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1272
1679
  if (!hasAccess(await license?.state() ?? { pro: false }))
1273
1680
  return json(res, 403, { error: "Inkmap trial expired" });
1274
1681
  return await serialized(async () => {
@@ -1280,31 +1687,24 @@ data: ${JSON.stringify(data)}
1280
1687
  current = md;
1281
1688
  version = hash(md);
1282
1689
  license?.track?.("doc_edit");
1283
- if (sidebar)
1284
- broadcast();
1690
+ broadcast();
1285
1691
  }
1286
1692
  return json(res, 200, { version });
1287
1693
  });
1288
1694
  }
1289
1695
  if (url.pathname === "/api/license" && req.method === "GET")
1290
1696
  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
1697
  if (url.pathname === "/api/open" && req.method === "POST") {
1298
- if (!sameOriginPost())
1698
+ if (!sameOriginWrite())
1299
1699
  return json(res, 403, { error: "forbidden" });
1300
1700
  const { file } = JSON.parse(await readBody(req));
1301
- await serialized(() => switchSourceToFile(String(file ?? "")));
1701
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1302
1702
  license?.track?.("doc_open");
1303
1703
  const { files } = await collectWorkspaceFiles();
1304
1704
  return json(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1305
1705
  }
1306
1706
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1307
- if (!sameOriginPost())
1707
+ if (!sameOriginWrite())
1308
1708
  return json(res, 403, { error: "forbidden" });
1309
1709
  const { event } = JSON.parse(await readBody(req));
1310
1710
  if (typeof event === "string" && event)
@@ -1312,45 +1712,43 @@ data: ${JSON.stringify(data)}
1312
1712
  return json(res, 200, { ok: true });
1313
1713
  }
1314
1714
  if (url.pathname === "/api/open-browser" && req.method === "POST") {
1315
- if (!sameOriginPost())
1715
+ if (!sameOriginWrite())
1316
1716
  return json(res, 403, { error: "forbidden" });
1317
1717
  if (license && !hasAccess(await license.state())) {
1318
1718
  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
1719
  }
1320
1720
  license?.track?.("feature_browser");
1321
1721
  if (!sidebar) {
1322
- const directUrl = `http://${host}:${bound}/`;
1722
+ const directUrl = `http://${urlHost}:${bound}/`;
1323
1723
  await openBrowserWindow(directUrl);
1324
1724
  return json(res, 200, { ok: true, url: directUrl });
1325
1725
  }
1326
1726
  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
- })();
1727
+ browserCompanion = serve({
1728
+ source: activeSource,
1729
+ webRoot,
1730
+ host: "127.0.0.1",
1731
+ port: 0,
1732
+ license,
1733
+ sidebar: false,
1734
+ workspaceRoots,
1735
+ confineToWorkspaceRoots,
1736
+ openSource,
1737
+ allowPurchase: canPurchase
1738
+ });
1341
1739
  browserCompanion.catch(() => {
1342
1740
  browserCompanion = null;
1343
1741
  });
1344
1742
  }
1345
1743
  const companion = await browserCompanion;
1346
1744
  if (activeSource.key)
1347
- await companion.switchToFile?.(activeSource.key).catch(() => {
1745
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1348
1746
  });
1349
1747
  await openBrowserWindow(companion.url);
1350
1748
  return json(res, 200, { ok: true, url: companion.url });
1351
1749
  }
1352
1750
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1353
- if (!sameOriginPost())
1751
+ if (!sameOriginWrite())
1354
1752
  return json(res, 403, { error: "forbidden" });
1355
1753
  const { mode, locale } = JSON.parse(await readBody(req));
1356
1754
  if (mode !== "buy" && mode !== "restore")
@@ -1362,7 +1760,7 @@ data: ${JSON.stringify(data)}
1362
1760
  return json(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1363
1761
  }
1364
1762
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1365
- if (!sameOriginPost())
1763
+ if (!sameOriginWrite())
1366
1764
  return json(res, 403, { error: "forbidden" });
1367
1765
  if (!canPurchase)
1368
1766
  return json(res, 403, { error: "forbidden" });
@@ -1374,7 +1772,7 @@ data: ${JSON.stringify(data)}
1374
1772
  return json(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1375
1773
  }
1376
1774
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1377
- if (!sameOriginPost())
1775
+ if (!sameOriginWrite())
1378
1776
  return json(res, 403, { error: "forbidden" });
1379
1777
  if (!license || typeof license.sendPhoneCode !== "function")
1380
1778
  return json(res, 501, { fallback: true });
@@ -1382,21 +1780,21 @@ data: ${JSON.stringify(data)}
1382
1780
  return json(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1383
1781
  }
1384
1782
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1385
- if (!sameOriginPost())
1783
+ if (!sameOriginWrite())
1386
1784
  return json(res, 403, { error: "forbidden" });
1387
1785
  if (!license || typeof license.signInByPhone !== "function")
1388
1786
  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 ?? "")) });
1787
+ const { phone, code, locale } = JSON.parse(await readBody(req));
1788
+ return json(res, 200, {
1789
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
1790
+ });
1391
1791
  }
1392
1792
  if (url.pathname === "/api/signout" && req.method === "POST") {
1393
- if (!sameOriginPost())
1793
+ if (!sameOriginWrite())
1394
1794
  return json(res, 403, { error: "forbidden" });
1395
1795
  await license?.deactivate();
1396
1796
  return json(res, 200, await license?.state() ?? { pro: false });
1397
1797
  }
1398
- if (url.pathname === "/api/ads")
1399
- return json(res, 200, sidebar ? [] : await ads?.() ?? []);
1400
1798
  if (url.pathname === "/api/events") {
1401
1799
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1402
1800
  res.write(": connected\n\n");
@@ -1408,17 +1806,21 @@ data: ${JSON.stringify(data)}
1408
1806
  return void res.writeHead(204).end();
1409
1807
  if (url.pathname.startsWith("/doc-assets/")) {
1410
1808
  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)))
1809
+ if (asset) {
1810
+ const root = await realpath2(activeSource.dir).catch(() => null);
1811
+ asset = await realpath2(asset).catch(() => null);
1812
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
1813
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1415
1814
  asset = null;
1416
1815
  }
1417
1816
  return sendFile(res, asset);
1418
1817
  }
1419
1818
  return sendFile(res, within(webRoot, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1420
1819
  } catch (err) {
1421
- json(res, 500, { error: err instanceof Error ? err.message : String(err) });
1820
+ if (res.headersSent)
1821
+ return void res.end();
1822
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
1823
+ json(res, status, { error: err instanceof Error ? err.message : String(err) });
1422
1824
  }
1423
1825
  });
1424
1826
  const listen = (p) => new Promise((ok, fail) => {
@@ -1429,15 +1831,26 @@ data: ${JSON.stringify(data)}
1429
1831
  });
1430
1832
  });
1431
1833
  try {
1432
- bound = await listen(port);
1834
+ try {
1835
+ bound = await listen(port);
1836
+ } catch (err) {
1837
+ if (err.code !== "EADDRINUSE")
1838
+ throw err;
1839
+ bound = await listen(0);
1840
+ }
1433
1841
  } catch (err) {
1434
- if (err.code !== "EADDRINUSE")
1435
- throw err;
1436
- bound = await listen(0);
1842
+ clearTimeout(pending);
1843
+ unwatch();
1844
+ unlisten();
1845
+ throw err;
1437
1846
  }
1438
1847
  return {
1439
- url: `http://${host}:${bound}${prefix}`,
1440
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1848
+ url: `http://${urlHost}:${bound}${prefix}`,
1849
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
1850
+ allowHost: (extraHost) => {
1851
+ if (extraHost)
1852
+ allowedHosts.add(extraHost.toLowerCase());
1853
+ },
1441
1854
  close: () => new Promise((done) => {
1442
1855
  clearTimeout(pending);
1443
1856
  unwatch();
@@ -1452,79 +1865,8 @@ data: ${JSON.stringify(data)}
1452
1865
  };
1453
1866
  }
1454
1867
 
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
1868
  // packages/antigravity/src/main.mjs
1527
- var __dirname = dirname4(fileURLToPath(import.meta.url));
1869
+ var __dirname = dirname4(fileURLToPath2(import.meta.url));
1528
1870
  var defaultWebRoot = join4(__dirname, "web");
1529
1871
  var SidecarResponse = class {
1530
1872
  constructor(body, { contentType = "text/plain", status = 200, headers } = {}) {
@@ -1534,27 +1876,6 @@ var SidecarResponse = class {
1534
1876
  this.headers = headers;
1535
1877
  }
1536
1878
  };
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
1879
  var TYPES2 = {
1559
1880
  ".html": "text/html; charset=utf-8",
1560
1881
  ".js": "application/javascript; charset=utf-8",
@@ -1565,103 +1886,15 @@ var TYPES2 = {
1565
1886
  ".jpeg": "image/jpeg",
1566
1887
  ".gif": "image/gif",
1567
1888
  ".webp": "image/webp",
1889
+ ".avif": "image/avif",
1890
+ ".bmp": "image/bmp",
1891
+ ".ico": "image/x-icon",
1568
1892
  ".woff2": "font/woff2",
1569
1893
  ".woff": "font/woff",
1570
1894
  ".ttf": "font/ttf",
1571
1895
  ".json": "application/json; charset=utf-8"
1572
1896
  };
1573
1897
  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
1898
  function openExternalUrl(url) {
1666
1899
  if (typeof url !== "string" || !/^https:\/\//i.test(url)) return;
1667
1900
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
@@ -1699,49 +1932,18 @@ function createAntigravitySidecar({
1699
1932
  let browserLicense = null;
1700
1933
  let browserServed = null;
1701
1934
  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
- }
1935
+ const serialized = createSerialQueue();
1936
+ const say2 = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1937
+ const browserRoots = [];
1938
+ const panelFiles = /* @__PURE__ */ new Map();
1939
+ const rememberPanel = (panel, file) => {
1940
+ if (typeof panel !== "string" || !panel || !file) return;
1941
+ panelFiles.delete(panel);
1942
+ panelFiles.set(panel, file);
1943
+ if (panelFiles.size > 64) panelFiles.delete(panelFiles.keys().next().value);
1944
+ };
1945
+ const { allowedRoots, assertAllowedFile } = createWorkspaceAccess();
1946
+ const assertAllowedMarkdownFile = (candidatePath, workspaceUris = []) => assertAllowedFile(candidatePath, workspaceUris);
1745
1947
  async function readDocState(filePath) {
1746
1948
  const source = await fileSource(filePath);
1747
1949
  const [md, viewState] = await Promise.all([source.read(), source.readView?.()]);
@@ -1762,7 +1964,7 @@ function createAntigravitySidecar({
1762
1964
  const seen = /* @__PURE__ */ new Set();
1763
1965
  if (target && !seen.has(target.file)) {
1764
1966
  const owner = roots.find((r) => insideOrEqual(r.path, target.file));
1765
- const rel = owner ? relative3(owner.path, target.file) : basename2(target.file);
1967
+ const rel = owner ? relative3(owner.path, target.file) : basename3(target.file);
1766
1968
  items.push({
1767
1969
  path: target.file,
1768
1970
  uri: pathToFileURL(target.file).href,
@@ -1772,7 +1974,7 @@ function createAntigravitySidecar({
1772
1974
  seen.add(target.file);
1773
1975
  }
1774
1976
  for (const root of roots) {
1775
- const files = await scanMarkdownFiles(root.path);
1977
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1776
1978
  for (const file of files) {
1777
1979
  if (seen.has(file)) continue;
1778
1980
  seen.add(file);
@@ -1788,32 +1990,23 @@ function createAntigravitySidecar({
1788
1990
  return { files: items, target };
1789
1991
  }
1790
1992
  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
- );
1993
+ 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
1994
  app.page("/", () => {
1796
- console.log("[inkmap] GET /");
1797
- return pageHtml;
1995
+ const osLoc = detectOsLocale();
1996
+ return rawHtml.replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`).replace("<head>", () => `<head>
1997
+ ${cspMeta}
1998
+ <script src="/preload.js"></script>
1999
+ <script src="/bridge.js"></script>`);
1798
2000
  });
1799
2001
  const bridgeJs = readFileSync(join4(__dirname, "bridge.js"), "utf8");
1800
- app.page("/bridge.js", () => {
1801
- console.log("[inkmap] GET /bridge.js");
1802
- return bridgeJs;
1803
- });
2002
+ app.page("/bridge.js", () => bridgeJs);
1804
2003
  app.api("/bridge.js", () => new SidecarResponse(bridgeJs, { contentType: "application/javascript; charset=utf-8" }), "GET");
2004
+ let preloadedAppJs = null;
1805
2005
  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
- });
2006
+ preloadedAppJs = readFileSync(join4(webRoot, "app.js"), "utf8");
2007
+ app.page("/app.js", () => preloadedAppJs);
1811
2008
  } catch {
1812
2009
  }
1813
- app.api("/api/debug", async (data) => {
1814
- console.log("[inkmap] CLIENT_DEBUG:", JSON.stringify(data));
1815
- return { ok: true };
1816
- }, "POST");
1817
2010
  function registerStaticDir(dir, prefix = "") {
1818
2011
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1819
2012
  const full = join4(dir, entry.name);
@@ -1822,21 +2015,17 @@ function createAntigravitySidecar({
1822
2015
  registerStaticDir(full, route);
1823
2016
  } else if (entry.isFile() && route !== "/index.html") {
1824
2017
  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");
2018
+ const body = route === "/app.js" && preloadedAppJs ? Buffer.from(preloadedAppJs, "utf8") : readFileSync(full);
2019
+ app.api(route, () => new SidecarResponse(body, {
2020
+ contentType,
2021
+ headers: { "Cache-Control": "private, max-age=3600" }
2022
+ }), "GET");
1833
2023
  }
1834
2024
  }
1835
2025
  }
1836
2026
  registerStaticDir(webRoot);
1837
- app.api("/api/init", async (data) => {
2027
+ app.api("/api/init", (data) => serialized(async () => {
1838
2028
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1839
- console.log(`[inkmap] /api/init workspaces=${JSON.stringify(workspaceUris)} requested=${data?.requestedFile || ""}`);
1840
2029
  const { files, target } = await collectFiles(workspaceUris);
1841
2030
  let chosen = null;
1842
2031
  if (typeof data?.requestedFile === "string" && data.requestedFile.trim()) {
@@ -1862,13 +2051,17 @@ function createAntigravitySidecar({
1862
2051
  license: lic,
1863
2052
  doc: {
1864
2053
  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",
2054
+ md: say2(
2055
+ "# 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",
2056
+ '# Inkmap\n\n- Add or pick a `.md` / `.markmap.md` file in this workspace\n- Or ask the AI: "Open <file> with Inkmap"\n'
2057
+ ),
1866
2058
  version: "empty",
1867
2059
  writable: false
1868
2060
  }
1869
2061
  };
1870
2062
  }
1871
2063
  activeFile = chosen;
2064
+ rememberPanel(data?.panel, chosen);
1872
2065
  license.track?.("doc_open", 1, "antigravity");
1873
2066
  const { doc } = await readDocState(chosen);
1874
2067
  return {
@@ -1879,11 +2072,12 @@ function createAntigravitySidecar({
1879
2072
  license: lic,
1880
2073
  doc
1881
2074
  };
1882
- }, "POST");
1883
- app.api("/api/open", async (data) => {
2075
+ }), "POST");
2076
+ app.api("/api/open", (data) => serialized(async () => {
1884
2077
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1885
2078
  const file = await assertAllowedMarkdownFile(data?.file, workspaceUris);
1886
2079
  activeFile = file;
2080
+ rememberPanel(data?.panel, file);
1887
2081
  license.track?.("doc_open", 1, "antigravity");
1888
2082
  const [{ doc }, { files, target }] = await Promise.all([
1889
2083
  readDocState(file),
@@ -1896,13 +2090,13 @@ function createAntigravitySidecar({
1896
2090
  targetSeq: target?.seq || 0,
1897
2091
  doc
1898
2092
  };
1899
- }, "POST");
1900
- const pollHandler = async (data) => {
2093
+ }), "POST");
2094
+ const pollHandler = (data) => serialized(async () => {
1901
2095
  const target = await readTargetSelection();
1902
2096
  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}`);
2097
+ if (target && target.seq > clientSeq && !target.editorOnly && target.file !== data?.file) {
1905
2098
  activeFile = target.file;
2099
+ rememberPanel(data?.panel, target.file);
1906
2100
  const { doc } = await readDocState(target.file);
1907
2101
  return {
1908
2102
  switchedFile: target.file,
@@ -1914,7 +2108,8 @@ function createAntigravitySidecar({
1914
2108
  const file = data?.file || activeFile;
1915
2109
  if (!file) return { unchanged: true, targetSeq: target?.seq || clientSeq };
1916
2110
  try {
1917
- const { doc } = await readDocState(file);
2111
+ const valid = await assertAllowedMarkdownFile(file, Array.isArray(data?.workspaceUris) ? data.workspaceUris : []);
2112
+ const { doc } = await readDocState(valid);
1918
2113
  if (data?.version && doc.version !== data.version) {
1919
2114
  return { changed: true, doc, targetSeq: target?.seq || clientSeq };
1920
2115
  }
@@ -1922,18 +2117,18 @@ function createAntigravitySidecar({
1922
2117
  } catch {
1923
2118
  return { unchanged: true, targetSeq: target?.seq || clientSeq };
1924
2119
  }
1925
- };
2120
+ });
1926
2121
  app.api("/api/poll", pollHandler, "GET");
1927
2122
  app.api("/api/poll", pollHandler, "POST");
1928
- app.api("/api/save", async (data) => {
2123
+ app.api("/api/save", (data) => serialized(async () => {
1929
2124
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1930
2125
  const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris);
1931
2126
  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");
2127
+ if (typeof md !== "string" || Buffer.byteLength(md, "utf8") > MAX_MARKDOWN_BYTES) {
2128
+ 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
2129
  }
1935
2130
  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");
2131
+ 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
2132
  }
1938
2133
  const { source, doc } = await readDocState(file);
1939
2134
  if (data?.baseVersion && data.baseVersion !== doc.version) {
@@ -1944,19 +2139,20 @@ function createAntigravitySidecar({
1944
2139
  license.track?.("doc_edit", 1, "antigravity");
1945
2140
  }
1946
2141
  return { ok: true, version: hash2(md) };
1947
- }, "POST");
2142
+ }), "POST");
1948
2143
  app.api("/api/telemetry", async (data) => {
1949
2144
  const ev = typeof data?.event === "string" ? data.event : "";
1950
2145
  if (ev) license.track?.(ev, 1, "antigravity");
1951
2146
  return { ok: true };
1952
2147
  }, "POST");
1953
- app.api("/api/open-browser", async (data) => {
2148
+ app.api("/api/open-browser", (data) => serialized(async () => {
1954
2149
  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");
2150
+ 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
2151
  }
1957
2152
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1958
2153
  const targetFile = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris);
1959
2154
  const { roots } = await allowedRoots(workspaceUris);
2155
+ browserRoots.splice(0, browserRoots.length, ...roots.map((r) => r.path));
1960
2156
  license.track?.("feature_browser", 1, "antigravity");
1961
2157
  if (!browserServed) {
1962
2158
  browserServed = (async () => {
@@ -1968,8 +2164,7 @@ function createAntigravitySidecar({
1968
2164
  port: 0,
1969
2165
  license: browserLicense,
1970
2166
  sidebar: false,
1971
- loginOnly: false,
1972
- workspaceRoots: roots.map((r) => r.path)
2167
+ workspaceRoots: browserRoots
1973
2168
  });
1974
2169
  })();
1975
2170
  browserServed.catch(() => {
@@ -1977,12 +2172,12 @@ function createAntigravitySidecar({
1977
2172
  });
1978
2173
  }
1979
2174
  const served = await browserServed;
1980
- await served.switchToFile?.(targetFile).catch(() => {
2175
+ await served.switchToFile?.(targetFile, { trustCaller: true }).catch(() => {
1981
2176
  });
1982
2177
  await openBrowserWindow2(served.url);
1983
2178
  return { ok: true, url: served.url };
1984
- }, "POST");
1985
- app.api("/api/view", async (data) => {
2179
+ }), "POST");
2180
+ app.api("/api/view", (data) => serialized(async () => {
1986
2181
  const workspaceUris = Array.isArray(data?.workspaceUris) ? data.workspaceUris : [];
1987
2182
  const file = await assertAllowedMarkdownFile(data?.file || activeFile, workspaceUris).catch(() => null);
1988
2183
  if (!file) return { ok: false };
@@ -1993,18 +2188,21 @@ function createAntigravitySidecar({
1993
2188
  });
1994
2189
  }
1995
2190
  return { ok: true };
1996
- }, "POST");
2191
+ }), "POST");
1997
2192
  app.api("/api/license", async () => await license.state(), "GET");
1998
- app.api("/api/checkout", async () => {
1999
- const url = await license.connect("restore");
2193
+ app.api("/api/checkout", async (data) => {
2194
+ const locale = typeof data?.locale === "string" ? data.locale : void 0;
2195
+ const url = await license.connect("restore", locale);
2000
2196
  openExternalUrl(url);
2001
2197
  return { url };
2002
2198
  }, "POST");
2003
2199
  app.api("/api/phone-send", async (data) => {
2004
- return { result: await license.sendPhoneCode(String(data?.phone ?? "")) };
2200
+ const locale = typeof data?.locale === "string" ? data.locale : void 0;
2201
+ return { result: await license.sendPhoneCode(String(data?.phone ?? ""), locale) };
2005
2202
  }, "POST");
2006
2203
  app.api("/api/phone-verify", async (data) => {
2007
- return { result: await license.signInByPhone(String(data?.phone ?? ""), String(data?.code ?? "")) };
2204
+ const locale = typeof data?.locale === "string" ? data.locale : void 0;
2205
+ return { result: await license.signInByPhone(String(data?.phone ?? ""), String(data?.code ?? ""), locale) };
2008
2206
  }, "POST");
2009
2207
  app.api("/api/signout", async () => {
2010
2208
  await license.deactivate();
@@ -2012,7 +2210,7 @@ function createAntigravitySidecar({
2012
2210
  }, "POST");
2013
2211
  app.api("/api/doc-asset", async (data) => {
2014
2212
  const notFound = () => new SidecarResponse("not found", { status: 404 });
2015
- const file = activeFile;
2213
+ const file = typeof data?.panel === "string" && panelFiles.get(data.panel) || activeFile;
2016
2214
  const rel = typeof data?.path === "string" ? data.path.replace(/\?.*$/, "") : "";
2017
2215
  if (!file || !rel) return notFound();
2018
2216
  try {
@@ -2020,13 +2218,18 @@ function createAntigravitySidecar({
2020
2218
  const candidate = normalize2(join4(dir, decodeURIComponent(rel)));
2021
2219
  if (!insideOrEqual(dir, candidate) || candidate === dir) return notFound();
2022
2220
  const realAsset = await realpath3(candidate);
2023
- if (!insideOrEqual(dir, realAsset) || !/\.(?:png|jpe?g|gif|webp|svg)$/i.test(realAsset)) return notFound();
2221
+ if (!insideOrEqual(dir, realAsset) || !/\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i.test(realAsset)) return notFound();
2024
2222
  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), {
2223
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES) return notFound();
2224
+ const ext = extname2(realAsset).toLowerCase();
2225
+ const type = TYPES2[ext] || "application/octet-stream";
2226
+ const headers = { "Cache-Control": "no-cache" };
2227
+ if (ext === ".svg") {
2228
+ headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
2229
+ }
2230
+ return new SidecarResponse(await readFile4(realAsset), {
2028
2231
  contentType: type,
2029
- headers: { "Cache-Control": "no-cache" }
2232
+ headers
2030
2233
  });
2031
2234
  } catch {
2032
2235
  return notFound();