inkmap-mcp 0.3.8 → 0.3.11

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