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.
package/dist/cli.cjs CHANGED
@@ -48,23 +48,9 @@ function billingFlowUrl(raw, origin, mode, legacy = false) {
48
48
  function hasAccess(state, now = Date.now()) {
49
49
  return state.pro || (state.trialUntil ?? 0) > now;
50
50
  }
51
- function sanitizeAds(input2) {
52
- if (!Array.isArray(input2))
53
- return [];
54
- const str = (v2, max) => typeof v2 === "string" && v2.trim() ? v2.trim().slice(0, max) : void 0;
55
- const out = [];
56
- for (const raw of input2.slice(0, 20)) {
57
- const r2 = raw;
58
- const id = str(r2?.id, 64);
59
- const title = str(r2?.title, 60);
60
- const text = str(r2?.text, 140);
61
- const url2 = str(r2?.url, 500);
62
- if (!id || !title || !text || !url2 || !/^https:\/\//.test(url2))
63
- continue;
64
- const locale = r2.locale === "zh" || r2.locale === "en" ? r2.locale : void 0;
65
- out.push({ id, title, text, url: url2, cta: str(r2.cta, 20), locale });
66
- }
67
- return out;
51
+ function trialDaysLeft(state, now = Date.now()) {
52
+ const remaining = (state.trialUntil ?? 0) - now;
53
+ return remaining > 0 ? Math.ceil(remaining / DAY_MS) : 0;
68
54
  }
69
55
  var PRODUCT, YUNFAN_BILLING_ORIGIN, DAY_MS, TRIAL_MS;
70
56
  var init_product = __esm({
@@ -72,9 +58,7 @@ var init_product = __esm({
72
58
  "use strict";
73
59
  PRODUCT = {
74
60
  id: "inkmap-pro",
75
- entitlement: "inkmap.pro",
76
- /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
77
- adFeedUrl: ""
61
+ entitlement: "inkmap.pro"
78
62
  };
79
63
  YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
80
64
  DAY_MS = 24 * 60 * 60 * 1e3;
@@ -83,6 +67,362 @@ var init_product = __esm({
83
67
  });
84
68
 
85
69
  // packages/core/dist/index.js
70
+ var dist_exports = {};
71
+ __export(dist_exports, {
72
+ DAY_MS: () => DAY_MS,
73
+ PRODUCT: () => PRODUCT,
74
+ TRIAL_MS: () => TRIAL_MS,
75
+ YUNFAN_BILLING_ORIGIN: () => YUNFAN_BILLING_ORIGIN,
76
+ billingFlowUrl: () => billingFlowUrl,
77
+ documentSetting: () => documentSetting,
78
+ frontMatterTitle: () => frontMatterTitle,
79
+ hasAccess: () => hasAccess,
80
+ isRich: () => isRich,
81
+ parse: () => parse,
82
+ plainText: () => plainText,
83
+ sanitizeViewState: () => sanitizeViewState,
84
+ serialize: () => serialize,
85
+ serializeWithLines: () => serializeWithLines,
86
+ trialDaysLeft: () => trialDaysLeft,
87
+ withDocumentSetting: () => withDocumentSetting,
88
+ withFrontMatterTitle: () => withFrontMatterTitle
89
+ });
90
+ function parseHeading(line) {
91
+ const m2 = /^(#{1,6})(?:[ \t]+(.*))?$/.exec(line);
92
+ if (!m2)
93
+ return null;
94
+ const rest = (m2[2] ?? "").replace(/[ \t]+$/, "");
95
+ const text = /^#+$/.test(rest) ? "" : rest.replace(/[ \t]+#+$/, "").replace(/[ \t]+$/, "");
96
+ return { level: m2[1].length, text };
97
+ }
98
+ function openFence(line) {
99
+ const m2 = /^\s*(`{3,}|~{3,})(.*)$/.exec(line);
100
+ if (!m2)
101
+ return null;
102
+ const char = m2[1][0];
103
+ if (char === "`" && m2[2].includes("`"))
104
+ return null;
105
+ return { char, len: m2[1].length };
106
+ }
107
+ function closesFence(line, fence) {
108
+ const m2 = /^\s*(`{3,}|~{3,})[ \t]*$/.exec(line);
109
+ return Boolean(m2 && m2[1][0] === fence.char && m2[1].length >= fence.len);
110
+ }
111
+ function isFrontMatterBlock(lines, end) {
112
+ if (end === 1)
113
+ return true;
114
+ if (isBlank(lines[1]))
115
+ return false;
116
+ let hasKey = false;
117
+ for (let k2 = 1; k2 < end; k2++) {
118
+ const ln = lines[k2];
119
+ if (isBlank(ln) || /^[ \t]*#/.test(ln) || /^[ \t]+/.test(ln) || /^-[ \t]/.test(ln))
120
+ continue;
121
+ if (!YAML_KEY.test(ln))
122
+ return false;
123
+ hasKey = true;
124
+ }
125
+ return hasKey;
126
+ }
127
+ function yamlScalar(raw, stripComment) {
128
+ const double = /^"((?:[^"\\]|\\.)*)"(?:[ \t]+#.*)?$/.exec(raw);
129
+ if (double) {
130
+ try {
131
+ return JSON.parse(`"${double[1]}"`);
132
+ } catch {
133
+ return double[1];
134
+ }
135
+ }
136
+ const single = /^'((?:[^']|'')*)'(?:[ \t]+#.*)?$/.exec(raw);
137
+ if (single)
138
+ return single[1].replace(/''/g, "'");
139
+ return (stripComment ? raw.replace(/[ \t]+#.*$/, "") : raw).trim();
140
+ }
141
+ function frontMatterTitle(frontMatter) {
142
+ const value = frontMatter.replace(/\r\n?/g, "\n").match(TITLE_LINE)?.[1].trim();
143
+ if (!value || /^[>|][-+]?$/.test(value))
144
+ return void 0;
145
+ return yamlScalar(value, false) || void 0;
146
+ }
147
+ function withFrontMatterTitle(frontMatter, title, eol) {
148
+ const nl = eol ?? (frontMatter.includes("\r\n") ? "\r\n" : "\n");
149
+ const line = `title: ${JSON.stringify(title.replace(/\s*\r?\n\s*/g, " "))}`;
150
+ const norm = frontMatter.replace(/\r\n?/g, "\n");
151
+ let updated;
152
+ if (!norm)
153
+ updated = `---
154
+ ${line}
155
+ ---
156
+ `;
157
+ else if (/^title:/m.test(norm))
158
+ updated = norm.replace(/^title:.*(?:\n[ \t]+.*)*$/m, () => line);
159
+ else
160
+ updated = norm.replace(/---\n?$/, () => `${line}
161
+ ---
162
+ `);
163
+ return nl === "\r\n" ? updated.replace(/\n/g, "\r\n") : updated;
164
+ }
165
+ function closeOpenFence(md) {
166
+ let fence = null;
167
+ for (const line of md.split("\n")) {
168
+ if (fence) {
169
+ if (closesFence(line, fence))
170
+ fence = null;
171
+ } else {
172
+ fence = openFence(line);
173
+ }
174
+ }
175
+ return fence ? `${md}
176
+ ${fence.char.repeat(fence.len)}` : md;
177
+ }
178
+ function protectText(prefix, md, followed) {
179
+ const [first] = md.split("\n", 1);
180
+ if (THEMATIC_BREAK.test(prefix + first) || followed && !md.includes("\n") && openFence(md))
181
+ md = "\\" + md;
182
+ return followed ? closeOpenFence(md) : md;
183
+ }
184
+ function parse(source, title = "Untitled") {
185
+ const bom = source.startsWith("\uFEFF");
186
+ const markdown = bom ? source.slice(1) : source;
187
+ const eol = markdown.includes("\r\n") ? "\r\n" : "\n";
188
+ const text = markdown.replace(/\r\n?/g, "\n");
189
+ const trailingNewline = markdown === "" ? true : text.endsWith("\n");
190
+ const lines = text === "" ? [""] : (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
191
+ let frontMatter = "";
192
+ let i = 0;
193
+ if (lines[0] === "---") {
194
+ const end = lines.indexOf("---", 1);
195
+ if (end > 0 && isFrontMatterBlock(lines, end)) {
196
+ frontMatter = lines.slice(0, end + 1).join("\n") + "\n";
197
+ i = end + 1;
198
+ title = frontMatterTitle(frontMatter) ?? title;
199
+ }
200
+ }
201
+ const top = { md: title, kind: "heading", level: 0, children: [] };
202
+ const stack = [{ node: top, indent: -1, content: 0, heading: 0 }];
203
+ let blank = 0;
204
+ let leadingBlank = -1;
205
+ let fence = null;
206
+ let current = null;
207
+ const pendingDividers = [];
208
+ const attach = (node2) => {
209
+ if (pendingDividers.length) {
210
+ node2.dividersBefore = pendingDividers.splice(0);
211
+ }
212
+ if (leadingBlank < 0)
213
+ leadingBlank = blank;
214
+ else if (blank)
215
+ node2.blankBefore = blank;
216
+ blank = 0;
217
+ stack[stack.length - 1].node.children.push(node2);
218
+ };
219
+ for (; i < lines.length; i++) {
220
+ const line = lines[i];
221
+ if (fence) {
222
+ appendLine(current, line);
223
+ if (closesFence(line, fence)) {
224
+ fence = null;
225
+ if (current?.node.unindentedBlock)
226
+ current = null;
227
+ }
228
+ continue;
229
+ }
230
+ if (isBlank(line)) {
231
+ blank++;
232
+ continue;
233
+ }
234
+ const indent = indentOf(line);
235
+ const isThematic = THEMATIC_BREAK.test(line);
236
+ if (isThematic && (!current || current.node.kind !== "item" || indent < current.content)) {
237
+ while (stack.length > 1 && stack[stack.length - 1].heading === void 0)
238
+ stack.pop();
239
+ current = null;
240
+ if (leadingBlank < 0) {
241
+ leadingBlank = blank;
242
+ pendingDividers.push({ blankBefore: 0, line });
243
+ } else {
244
+ pendingDividers.push({ blankBefore: blank, line });
245
+ }
246
+ blank = 0;
247
+ continue;
248
+ }
249
+ let item = isThematic ? null : ITEM.exec(line);
250
+ if (item && item[4] === void 0 && !blank && current?.node.kind === "block")
251
+ item = null;
252
+ const heading = item ? null : parseHeading(line);
253
+ if (current && !item && !heading && (indent >= current.content || !blank && current.node.kind === "item" && indent > 0)) {
254
+ flushBlank(current);
255
+ appendLine(current, line);
256
+ fence = openFence(line);
257
+ continue;
258
+ }
259
+ if (heading) {
260
+ const { level, text: headingText } = heading;
261
+ while (stack.length > 1 && (stack[stack.length - 1].heading === void 0 || stack[stack.length - 1].heading >= level))
262
+ stack.pop();
263
+ const node3 = { md: headingText, kind: "heading", level, children: [] };
264
+ attach(node3);
265
+ stack.push({ node: node3, indent: -1, content: 0, heading: level });
266
+ current = null;
267
+ continue;
268
+ }
269
+ if (item) {
270
+ while (stack.length > 1 && stack[stack.length - 1].heading === void 0 && stack[stack.length - 1].indent >= indent)
271
+ stack.pop();
272
+ const itemText = item[4] ?? "";
273
+ const node3 = { md: itemText, kind: "item", marker: item[2], children: [] };
274
+ attach(node3);
275
+ current = { node: node3, indent, content: indent + item[2].length + (item[3]?.length ?? 1) };
276
+ stack.push(current);
277
+ fence = openFence(itemText);
278
+ continue;
279
+ }
280
+ const startedFence = openFence(line);
281
+ if (!blank && indent === 0 && startedFence && current && current.node.kind === "item") {
282
+ const node3 = { md: line, kind: "block", unindentedBlock: true, children: [] };
283
+ attach(node3);
284
+ current = { node: node3, indent: 0, content: 0 };
285
+ fence = startedFence;
286
+ continue;
287
+ }
288
+ while (stack.length > 1 && stack[stack.length - 1].heading === void 0)
289
+ stack.pop();
290
+ const node2 = { md: line.slice(indent), kind: "block", children: [] };
291
+ attach(node2);
292
+ current = { node: node2, indent, content: indent };
293
+ fence = startedFence;
294
+ }
295
+ function flushBlank(frame) {
296
+ for (; blank > 0; blank--)
297
+ frame.node.md += "\n";
298
+ }
299
+ function appendLine(frame, line) {
300
+ frame.node.md += "\n" + (isBlank(line) ? "" : line.slice(Math.min(frame.content, indentOf(line))));
301
+ }
302
+ if (leadingBlank < 0)
303
+ leadingBlank = 0;
304
+ const trailingDividers = pendingDividers.length ? pendingDividers.splice(0) : void 0;
305
+ const tops = top.children;
306
+ const extras = { ...trailingDividers && { trailingDividers }, ...bom && { bom: true } };
307
+ if (tops.length === 1 && tops[0].kind === "heading") {
308
+ return { frontMatter, leadingBlank, root: tops[0], syntheticRoot: false, trailingNewline, eol, ...extras };
309
+ }
310
+ return { frontMatter, leadingBlank, root: top, syntheticRoot: true, trailingNewline, eol, ...extras };
311
+ }
312
+ function serialize(doc) {
313
+ return serializeWithLines(doc).md;
314
+ }
315
+ function serializeWithLines(doc) {
316
+ const out = [];
317
+ const lines = /* @__PURE__ */ new Map();
318
+ const eol = doc.eol ?? "\n";
319
+ const normFm = doc.frontMatter ? doc.frontMatter.replace(/\r\n?/g, "\n") : "";
320
+ const offset = normFm ? normFm.split("\n").length - 1 : 0;
321
+ const blanks = (n = 0) => {
322
+ for (let k2 = 0; k2 < n; k2++)
323
+ out.push("");
324
+ };
325
+ const pushLines = (first, md, pad) => {
326
+ const [head, ...rest] = md.replace(/\r\n?/g, "\n").split("\n");
327
+ out.push(head === "" ? first.trimEnd() : first + head);
328
+ for (const l of rest)
329
+ out.push(l === "" ? "" : pad + l);
330
+ };
331
+ const emitDividers = (divs, skipFirstBlank = false) => {
332
+ if (!divs?.length)
333
+ return false;
334
+ divs.forEach((d2, idx) => {
335
+ if (!(skipFirstBlank && idx === 0))
336
+ blanks(d2.blankBefore);
337
+ out.push(d2.line);
338
+ });
339
+ return true;
340
+ };
341
+ let lastNode = doc.root;
342
+ while (lastNode.children.length)
343
+ lastNode = lastNode.children[lastNode.children.length - 1];
344
+ const followed = (node2) => node2 !== lastNode || Boolean(doc.trailingDividers?.length);
345
+ const writtenRaw = (node2, parent) => node2.kind === "block" && node2.children.length === 0 && (parent.kind === "heading" || Boolean(node2.unindentedBlock));
346
+ const write = (node2, parent, indent, headingLevel, first = false) => {
347
+ const keepSectionSpacing = parent.kind === "heading" || node2.kind === "item";
348
+ const hadDividers = parent.kind === "heading" ? emitDividers(node2.dividersBefore, first) : false;
349
+ if (!first || hadDividers)
350
+ blanks(keepSectionSpacing ? node2.blankBefore : 0);
351
+ const prev = parent.children[parent.children.indexOf(node2) - 1];
352
+ if (node2.kind === "item" && node2.md.split("\n", 1)[0] === "" && prev && writtenRaw(prev, parent) && out.at(-1))
353
+ out.push("");
354
+ lines.set(node2, offset + out.length);
355
+ if (node2.kind === "heading" && parent.kind === "heading" && headingLevel < 6 && !/\r|\n/.test(node2.md)) {
356
+ const level = node2.level && node2.level > headingLevel && node2.level <= 6 ? node2.level : headingLevel + 1;
357
+ pushLines("#".repeat(level) + " ", node2.md, "");
358
+ node2.children.forEach((c) => write(c, node2, 0, level));
359
+ return;
360
+ }
361
+ if (writtenRaw(node2, parent)) {
362
+ pushLines("", protectText("", node2.md, followed(node2)), "");
363
+ return;
364
+ }
365
+ const marker = node2.kind === "item" && node2.marker ? node2.marker : "-";
366
+ const pad = " ".repeat(indent);
367
+ pushLines(pad + marker + " ", protectText(marker + " ", node2.md, followed(node2)), " ".repeat(indent + marker.length + 1));
368
+ node2.children.forEach((c) => write(c, node2, indent + marker.length + 1, headingLevel));
369
+ };
370
+ blanks(doc.leadingBlank);
371
+ if (doc.syntheticRoot) {
372
+ lines.set(doc.root, offset + out.length);
373
+ doc.root.children.forEach((c, k2) => write(c, doc.root, 0, 0, k2 === 0));
374
+ } else {
375
+ const level = Math.min(doc.root.level || 1, 6);
376
+ if (emitDividers(doc.root.dividersBefore, true)) {
377
+ blanks(doc.root.blankBefore);
378
+ }
379
+ lines.set(doc.root, offset + out.length);
380
+ pushLines("#".repeat(level) + " ", doc.root.md.replace(/\s*\r?\n\s*/g, " "), "");
381
+ doc.root.children.forEach((c) => write(c, doc.root, 0, level));
382
+ }
383
+ emitDividers(doc.trailingDividers, out.length === 0);
384
+ const body = out.join(eol);
385
+ const fmOut = eol === "\r\n" ? normFm.replace(/\n/g, "\r\n") : normFm;
386
+ return { md: (doc.bom ? "\uFEFF" : "") + fmOut + body + (doc.trailingNewline && out.length > 0 ? eol : ""), lines };
387
+ }
388
+ function isRich(md) {
389
+ return /\n|[`*_\\|<>[\]!~]|\$[^\s$][\s\S]*\$|\$\$[\s\S]+\$\$|^#|^\d+\.\s/.test(md);
390
+ }
391
+ function plainText(md) {
392
+ return md.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[`*_~]|\\(?=.)/g, "").replace(/\s*\n\s*/g, " ").trim();
393
+ }
394
+ function documentSetting(frontMatter, key) {
395
+ const norm = frontMatter.replace(/\r\n?/g, "\n");
396
+ const section = norm.match(SETTINGS_SECTION)?.[1] ?? "";
397
+ const raw = section.match(new RegExp(`^[ \\t]+${key}:[ \\t]*(.*)$`, "m"))?.[1].trim();
398
+ return raw && yamlScalar(raw, true) || void 0;
399
+ }
400
+ function withDocumentSetting(frontMatter, key, value) {
401
+ const eol = frontMatter.includes("\r\n") ? "\r\n" : "\n";
402
+ const norm = frontMatter.replace(/\r\n?/g, "\n");
403
+ const line = ` ${key}: ${value}
404
+ `;
405
+ let updated;
406
+ if (!norm)
407
+ updated = `---
408
+ inkmap:
409
+ ${line}---
410
+ `;
411
+ else {
412
+ const section = norm.match(SETTINGS_SECTION);
413
+ if (!section)
414
+ updated = norm.replace(/---\n$/, `inkmap:
415
+ ${line}---
416
+ `);
417
+ else {
418
+ const keyLine = new RegExp(`^[ \\t]+${key}:.*\\n`, "m");
419
+ const body = keyLine.test(section[1]) ? section[1].replace(keyLine, line) : section[1] + line;
420
+ updated = norm.replace(SETTINGS_SECTION, `inkmap:
421
+ ${body}`);
422
+ }
423
+ }
424
+ return eol === "\r\n" ? updated.replace(/\n/g, "\r\n") : updated;
425
+ }
86
426
  function sanitizeViewState(raw) {
87
427
  if (!raw || typeof raw !== "object")
88
428
  return void 0;
@@ -106,61 +446,99 @@ function sanitizeViewState(raw) {
106
446
  }
107
447
  return folds || view ? { ...folds && { folds }, ...view && { view } } : void 0;
108
448
  }
449
+ var THEMATIC_BREAK, ITEM, YAML_KEY, TITLE_LINE, indentOf, isBlank, SETTINGS_SECTION;
109
450
  var init_dist = __esm({
110
451
  "packages/core/dist/index.js"() {
111
452
  "use strict";
112
453
  init_product();
454
+ THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/;
455
+ ITEM = /^(\s*)([-*+]|\d+[.)])(?:([ \t]+)(.*))?$/;
456
+ YAML_KEY = /^(?:"[^"]*"|'[^']*'|[^\s#"'-].*?)[ \t]*:(?:[ \t]|$)/;
457
+ TITLE_LINE = /^title:[ \t]*(\S.*)$/m;
458
+ indentOf = (line) => line.length - line.trimStart().length;
459
+ isBlank = (line) => line.trim() === "";
460
+ SETTINGS_SECTION = /^inkmap:[ \t]*\n((?:[ \t]+.*\n)*)/m;
461
+ }
462
+ });
463
+
464
+ // packages/cli/dist/version.js
465
+ var INKMAP_VERSION;
466
+ var init_version = __esm({
467
+ "packages/cli/dist/version.js"() {
468
+ "use strict";
469
+ INKMAP_VERSION = "0.3.11";
113
470
  }
114
471
  });
115
472
 
116
473
  // packages/cli/dist/license.js
117
- function detectOsLocale() {
118
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
119
- if (/^zh\b/i.test(explicit))
474
+ var license_exports = {};
475
+ __export(license_exports, {
476
+ detectOsLocale: () => detectOsLocale,
477
+ fileSessionStorage: () => fileSessionStorage,
478
+ licenseService: () => licenseService,
479
+ parseAppleLanguages: () => parseAppleLanguages,
480
+ resolveOsLocale: () => resolveOsLocale
481
+ });
482
+ function isWaitingToken(value) {
483
+ const w2 = value;
484
+ return Boolean(w2) && typeof w2.origin === "string" && typeof w2.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(w2.token) && typeof w2.email === "string" && typeof w2.since === "number" && typeof w2.fastUntil === "number";
485
+ }
486
+ function parseAppleLanguages(output2) {
487
+ const match = /^\(\s*(?:"([^"]+)"|([^\s,)]+))/m.exec(output2);
488
+ return match?.[1] ?? match?.[2] ?? "";
489
+ }
490
+ function resolveOsLocale(probe) {
491
+ const explicit = (probe.env.INKMAP_LOCALE || "").trim();
492
+ if (ZH_LOCALE_RE.test(explicit))
120
493
  return "zh";
121
- if (/^en\b/i.test(explicit))
494
+ if (EN_LOCALE_RE.test(explicit))
122
495
  return "en";
123
- if (cachedOsLocale)
124
- return cachedOsLocale;
125
- let domestic = false;
126
- try {
127
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
128
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
129
- domestic = true;
496
+ if (DOMESTIC_TIME_ZONE.test(probe.timeZone))
497
+ return "zh";
498
+ let language = "";
499
+ if (probe.platform === "darwin") {
500
+ try {
501
+ language = parseAppleLanguages(probe.run("defaults", ["read", "-g", "AppleLanguages"]));
502
+ } catch {
503
+ language = posixLocale(probe.env);
130
504
  }
131
- } catch {
132
- }
133
- if (!domestic) {
134
- if (process.platform === "darwin") {
135
- try {
136
- const out = (0, import_node_child_process.execFileSync)("defaults", ["read", "-g", "AppleLanguages"], {
137
- encoding: "utf8",
138
- timeout: 800,
139
- stdio: ["ignore", "pipe", "ignore"]
140
- });
141
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
142
- if (/^zh\b/i.test(firstLang))
143
- domestic = true;
144
- } catch {
145
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
146
- if (/^zh\b/i.test(raw))
147
- domestic = true;
148
- }
149
- } else if (process.platform === "win32") {
150
- try {
151
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
152
- if (/^zh\b/i.test(loc))
153
- domestic = true;
154
- } catch {
155
- }
156
- } else {
157
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
158
- if (/^zh\b/i.test(raw))
159
- domestic = true;
505
+ } else if (probe.platform === "win32") {
506
+ try {
507
+ const output2 = probe.run("reg", ["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]);
508
+ language = /LocaleName\s+REG_\w+\s+(\S+)/i.exec(output2)?.[1] ?? "";
509
+ } catch {
160
510
  }
511
+ if (!language)
512
+ language = probe.intlLocale;
513
+ } else {
514
+ language = posixLocale(probe.env);
515
+ }
516
+ return ZH_LOCALE_RE.test(language) ? "zh" : "en";
517
+ }
518
+ function systemLocaleProbe() {
519
+ let timeZone = "";
520
+ let intlLocale = "";
521
+ try {
522
+ const options = Intl.DateTimeFormat().resolvedOptions();
523
+ timeZone = options.timeZone || "";
524
+ intlLocale = options.locale || "";
525
+ } catch {
161
526
  }
162
- cachedOsLocale = domestic ? "zh" : "en";
163
- return cachedOsLocale;
527
+ return {
528
+ platform: process.platform,
529
+ env: process.env,
530
+ timeZone,
531
+ intlLocale,
532
+ run: (command, args) => (0, import_node_child_process.execFileSync)(command, args, { encoding: "utf8", timeout: 800, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] })
533
+ };
534
+ }
535
+ function detectOsLocale() {
536
+ const explicit = (process.env.INKMAP_LOCALE || "").trim();
537
+ if (ZH_LOCALE_RE.test(explicit))
538
+ return "zh";
539
+ if (EN_LOCALE_RE.test(explicit))
540
+ return "en";
541
+ return cachedOsLocale ??= resolveOsLocale(systemLocaleProbe());
164
542
  }
165
543
  function billingOrigin(raw) {
166
544
  if (!raw)
@@ -171,7 +549,7 @@ function billingOrigin(raw) {
171
549
  }
172
550
  return url2.origin;
173
551
  }
174
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
552
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
175
553
  const listeners = /* @__PURE__ */ new Set();
176
554
  let current = { pro: false };
177
555
  let trial;
@@ -183,6 +561,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
183
561
  let detectedHost = defaultHost;
184
562
  const pendingEvents = /* @__PURE__ */ new Map();
185
563
  let lastCheck = 0;
564
+ let fastPollUntil = 0;
565
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
566
+ let flowCreation;
186
567
  let disposed = false;
187
568
  let generation = 0;
188
569
  let connection;
@@ -190,12 +571,33 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
190
571
  let pendingWrite = Promise.resolve();
191
572
  let pendingCheckout;
192
573
  let cachedOrder;
193
- let magicPollTimer;
194
- let magicSession = 0;
195
- function stopMagicPoll() {
196
- ++magicSession;
197
- clearTimeout(magicPollTimer);
198
- magicPollTimer = void 0;
574
+ let waiting = [];
575
+ let waitTimer;
576
+ let waitRound = 0;
577
+ let lastSignIn;
578
+ const sessionRecord = (fields) => JSON.stringify({ ...fields, ...lastSignIn && { lastSignIn } });
579
+ const signedOutRecord = () => lastSignIn || waiting.length ? JSON.stringify({ ...lastSignIn && { lastSignIn }, ...waiting.length && { waiting } }) : void 0;
580
+ async function rememberSignIn(id) {
581
+ const clean = id.trim().slice(0, 254);
582
+ if (!clean || clean === lastSignIn)
583
+ return;
584
+ lastSignIn = clean;
585
+ current = { ...current, lastSignIn };
586
+ await writeSession(async () => {
587
+ let record2 = {};
588
+ try {
589
+ record2 = JSON.parse(await storage.read() || "{}");
590
+ } catch {
591
+ }
592
+ await storage.write(JSON.stringify({ ...record2, lastSignIn }));
593
+ }).catch(() => {
594
+ });
595
+ }
596
+ function clearWaiting() {
597
+ waiting = [];
598
+ ++waitRound;
599
+ clearTimeout(waitTimer);
600
+ waitTimer = void 0;
199
601
  }
200
602
  function mergeCookies(existing, response) {
201
603
  const map2 = /* @__PURE__ */ new Map();
@@ -226,12 +628,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
226
628
  }
227
629
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
228
630
  }
229
- function clientLocale(hint) {
230
- const h2 = (hint || "").trim();
231
- if (/^zh\b/i.test(h2))
232
- return "zh";
233
- if (/^en\b/i.test(h2))
234
- return "en";
631
+ function clientLocale(_uiLocaleHint) {
235
632
  return detectOsLocale();
236
633
  }
237
634
  function writeSession(operation) {
@@ -263,7 +660,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
263
660
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
264
661
  throw new Error("Invalid Inkmap checkout response.");
265
662
  }
266
- return { origin, url: url2, token: data.token, ...cookie && { cookie } };
663
+ return { origin, url: url2, token: data.token, locale: loc, ...cookie && { cookie } };
267
664
  }
268
665
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
269
666
  const loc = clientLocale(localeHint);
@@ -325,12 +722,26 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
325
722
  pro,
326
723
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
327
724
  ...connected && { connected: true },
328
- ...cleanAccount && { account: cleanAccount }
725
+ ...cleanAccount && { account: cleanAccount },
726
+ ...lastSignIn && { lastSignIn }
329
727
  };
330
728
  for (const listener of listeners)
331
729
  listener(current);
332
730
  }
333
731
  async function startTrial() {
732
+ try {
733
+ const record2 = JSON.parse(await storage.read() || "{}");
734
+ const remembered = record2.lastSignIn;
735
+ if (typeof remembered === "string" && remembered.trim() && !lastSignIn) {
736
+ lastSignIn = remembered.trim().slice(0, 254);
737
+ current = { ...current, lastSignIn };
738
+ }
739
+ if (typeof record2.token !== "string" && Array.isArray(record2.waiting) && !waiting.length) {
740
+ waiting = record2.waiting.filter(isWaitingToken).slice(-MAX_WAITING);
741
+ scheduleWait(waitPollMs);
742
+ }
743
+ } catch {
744
+ }
334
745
  const trialUntil = await localTrialDeadline().catch(() => void 0);
335
746
  if (disposed || trialUntil === void 0)
336
747
  return;
@@ -382,7 +793,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
382
793
  return await writeSession(async () => {
383
794
  if (version2 !== generation || disposed)
384
795
  return;
385
- await storage.write(void 0).catch(() => {
796
+ await storage.write(signedOutRecord()).catch(() => {
386
797
  });
387
798
  update(false);
388
799
  });
@@ -406,59 +817,195 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
406
817
  });
407
818
  return connection;
408
819
  }
409
- function startMagicPoll(origin, pendingToken) {
410
- stopMagicPoll();
411
- const id = magicSession;
412
- const deadline = Date.now() + 10 * 6e4;
413
- const poll = () => {
414
- if (disposed || id !== magicSession || Date.now() >= deadline)
820
+ async function mustPayFirst() {
821
+ if (!loginOnly)
822
+ return false;
823
+ await (trial ??= startTrial());
824
+ return current.trialUntil !== void 0 && current.trialUntil <= Date.now();
825
+ }
826
+ async function waitFor(origin, token, email3) {
827
+ const now = Date.now();
828
+ const same = (other) => !other || !email3 || other.toLowerCase() === email3.toLowerCase();
829
+ waiting = waiting.filter((w2) => w2.token !== token && same(w2.email)).map((w2) => ({ ...w2, fastUntil: now + WAIT_FAST_FOR_MS }));
830
+ waiting.push({ origin, token, email: email3, since: now, fastUntil: now + WAIT_FAST_FOR_MS });
831
+ waiting = waiting.slice(-MAX_WAITING);
832
+ scheduleWait(waitPollMs);
833
+ await writeSession(async () => {
834
+ let record2 = {};
835
+ try {
836
+ record2 = JSON.parse(await storage.read() || "{}");
837
+ } catch {
838
+ }
839
+ if (typeof record2.token !== "string")
840
+ await storage.write(signedOutRecord());
841
+ }).catch(() => {
842
+ });
843
+ }
844
+ function scheduleWait(delay) {
845
+ clearTimeout(waitTimer);
846
+ if (disposed || !waiting.length)
847
+ return;
848
+ waitTimer = setTimeout(() => void checkWaiting(), delay);
849
+ waitTimer.unref();
850
+ }
851
+ async function checkWaiting() {
852
+ const round = ++waitRound;
853
+ const now = Date.now();
854
+ const before = waiting.length;
855
+ let origin;
856
+ try {
857
+ origin = billingOrigin(getOrigin());
858
+ } catch {
859
+ return scheduleWait(WAIT_SLOW_MS);
860
+ }
861
+ waiting = waiting.filter((w2) => w2.origin === origin && now - w2.since < WAIT_MAX_MS);
862
+ for (const w2 of [...waiting]) {
863
+ let response;
864
+ try {
865
+ response = await entitlement(w2.origin, w2.token);
866
+ } catch {
867
+ continue;
868
+ }
869
+ if (disposed || round !== waitRound)
415
870
  return;
416
- magicPollTimer = setTimeout(async () => {
417
- if (disposed || id !== magicSession)
871
+ if (response.status === 401) {
872
+ waiting = waiting.filter((other) => other !== w2);
873
+ continue;
874
+ }
875
+ if (!response.ok)
876
+ continue;
877
+ const body = await response.json().catch(() => null);
878
+ if (disposed || round !== waitRound)
879
+ return;
880
+ if (body?.connected !== true || body.entitlement !== PRODUCT.entitlement)
881
+ continue;
882
+ if (body.active !== true && await mustPayFirst())
883
+ continue;
884
+ if (disposed || round !== waitRound)
885
+ return;
886
+ await writeSession(async () => {
887
+ if (disposed || round !== waitRound || w2.origin !== billingOrigin(getOrigin()))
418
888
  return;
889
+ clearWaiting();
890
+ await storage.write(sessionRecord({ origin: w2.origin, token: w2.token }));
891
+ ++generation;
892
+ activeOrigin = w2.origin;
893
+ applyEntitlement(body);
894
+ schedule(body.active === true ? 6e4 : 2500);
895
+ });
896
+ return;
897
+ }
898
+ if (disposed || round !== waitRound)
899
+ return;
900
+ if (waiting.length !== before) {
901
+ await writeSession(async () => {
902
+ let record2 = {};
419
903
  try {
420
- const res = await entitlement(origin, pendingToken);
421
- if (disposed || id !== magicSession)
422
- return;
423
- if (res.status === 401) {
424
- stopMagicPoll();
425
- return;
426
- }
427
- if (res.ok) {
428
- const body = await res.json();
429
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
430
- stopMagicPoll();
431
- await writeSession(async () => {
432
- if (disposed || origin !== billingOrigin(getOrigin()))
433
- return;
434
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
435
- ++generation;
436
- activeOrigin = origin;
437
- applyEntitlement(body);
438
- schedule(body.active === true ? 6e4 : 2500);
439
- });
440
- return;
441
- }
442
- }
904
+ record2 = JSON.parse(await storage.read() || "{}");
443
905
  } catch {
444
906
  }
445
- if (!disposed && id === magicSession && Date.now() < deadline)
446
- poll();
447
- }, 2e3);
448
- magicPollTimer.unref();
449
- };
450
- poll();
907
+ if (typeof record2.token !== "string")
908
+ await storage.write(signedOutRecord());
909
+ }).catch(() => {
910
+ });
911
+ }
912
+ scheduleWait(waiting.some((w2) => Date.now() < w2.fastUntil) ? waitPollMs : WAIT_SLOW_MS);
913
+ }
914
+ async function parkUnpaidSession() {
915
+ if (current.pro || !current.connected || !await mustPayFirst())
916
+ return;
917
+ await writeSession(async () => {
918
+ if (current.pro || !current.connected)
919
+ return;
920
+ let record2 = {};
921
+ try {
922
+ record2 = JSON.parse(await storage.read() || "{}");
923
+ } catch {
924
+ }
925
+ if (typeof record2.token !== "string" || typeof record2.origin !== "string")
926
+ return;
927
+ const response = await entitlement(record2.origin, record2.token).catch(() => null);
928
+ if (!response?.ok)
929
+ return;
930
+ const latest = await response.json().catch(() => null);
931
+ if (!latest || latest.active === true || latest.connected !== true) {
932
+ if (latest)
933
+ applyEntitlement(latest);
934
+ return;
935
+ }
936
+ ++generation;
937
+ clearTimeout(timer);
938
+ lastCheck = 0;
939
+ const now = Date.now();
940
+ waiting = [
941
+ ...waiting.filter((w2) => w2.token !== record2.token),
942
+ { origin: record2.origin, token: record2.token, email: lastSignIn ?? "", since: now, fastUntil: now + WAIT_FAST_FOR_MS }
943
+ ].slice(-MAX_WAITING);
944
+ await storage.write(signedOutRecord());
945
+ update(false);
946
+ });
947
+ scheduleWait(waitPollMs);
948
+ }
949
+ async function sendPendingTelemetry() {
950
+ if (disposed || !pendingEvents.size)
951
+ return;
952
+ let origin;
953
+ try {
954
+ origin = billingOrigin(getOrigin());
955
+ } catch {
956
+ return;
957
+ }
958
+ if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
959
+ if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
960
+ return;
961
+ const customHome = process.env.INKMAP_HOME || "";
962
+ const sysTmp = (0, import_node_os.tmpdir)();
963
+ if (customHome && (customHome === sysTmp || customHome.startsWith(sysTmp + import_node_path.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-"))) {
964
+ return;
965
+ }
966
+ }
967
+ const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
968
+ if (disposed || !id || !pendingEvents.size)
969
+ return;
970
+ await (trial ??= startTrial());
971
+ const events = {};
972
+ for (const [k2, v2] of pendingEvents.entries())
973
+ events[k2] = v2;
974
+ pendingEvents.clear();
975
+ const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
976
+ const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
977
+ const hostName = detectedHost || inferNodeHost();
978
+ await fetch(origin + "/billing/v1/telemetry", {
979
+ method: "POST",
980
+ headers: { "content-type": "application/json" },
981
+ redirect: "error",
982
+ body: JSON.stringify({
983
+ product: PRODUCT.id,
984
+ installId: id,
985
+ host: hostName,
986
+ os,
987
+ version: INKMAP_VERSION,
988
+ locale: clientLocale(),
989
+ tier,
990
+ events
991
+ }),
992
+ signal: AbortSignal.timeout(5e3)
993
+ }).catch(() => {
994
+ });
451
995
  }
452
996
  return {
453
997
  async state() {
454
998
  await (trial ??= startTrial());
455
- if (Date.now() - lastCheck >= 4e3)
999
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
1000
+ if (Date.now() - lastCheck >= interval)
456
1001
  await refresh();
1002
+ await parkUnpaidSession();
457
1003
  return current;
458
1004
  },
459
1005
  async connect(mode, localeHint) {
460
1006
  if (loginOnly && mode !== "restore")
461
1007
  throw new Error("Only Yunfan account sign-in is available.");
1008
+ expectPurchase();
462
1009
  const origin = billingOrigin(getOrigin());
463
1010
  const loc = clientLocale(localeHint);
464
1011
  const version2 = generation;
@@ -500,7 +1047,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
500
1047
  if (version2 !== generation || disposed || origin !== billingOrigin(getOrigin())) {
501
1048
  throw new Error("The Yunfan account session changed. Please try again.");
502
1049
  }
503
- await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url2 } }));
1050
+ clearWaiting();
1051
+ await storage.write(sessionRecord({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url2 } }));
504
1052
  ++generation;
505
1053
  lastCheck = 0;
506
1054
  if (mode !== "buy" || !current.connected)
@@ -512,8 +1060,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
512
1060
  async orderPro(localeHint) {
513
1061
  if (loginOnly)
514
1062
  throw new Error("Only Yunfan account sign-in is available.");
1063
+ expectPurchase();
515
1064
  const origin = billingOrigin(getOrigin());
516
- if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
1065
+ const loc = clientLocale(localeHint);
1066
+ if (cachedOrder && cachedOrder.origin === origin && cachedOrder.locale === loc && Date.now() - cachedOrder.at < 8e3) {
517
1067
  const hit = cachedOrder.result;
518
1068
  cachedOrder = void 0;
519
1069
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -539,7 +1089,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
539
1089
  await writeSession(async () => {
540
1090
  if (version2 !== generation || disposed || origin !== billingOrigin(getOrigin()))
541
1091
  return;
542
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
1092
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
543
1093
  if (persist) {
544
1094
  ++generation;
545
1095
  lastCheck = 0;
@@ -588,34 +1138,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
588
1138
  async sendPhoneCode(phone, localeHint) {
589
1139
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254)
590
1140
  return phoneFailure(400);
1141
+ expectPurchase();
591
1142
  const isEmail = phone.includes("@");
592
1143
  const locale = clientLocale(localeHint);
593
1144
  try {
594
1145
  const origin = billingOrigin(getOrigin());
595
1146
  if (!loginOnly) {
596
1147
  try {
597
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
598
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
1148
+ const newFlow = () => flowCreation ??= createCheckoutFlow(origin, void 0, void 0, locale).finally(() => {
1149
+ flowCreation = void 0;
1150
+ });
1151
+ let flow = pendingCheckout;
1152
+ if (!flow || flow.origin !== origin || flow.locale !== locale) {
1153
+ flow = await newFlow();
1154
+ pendingCheckout = flow;
599
1155
  }
600
1156
  const sendAction = isEmail ? "email/send" : "sms";
601
1157
  const sendBody = isEmail ? { email: phone, locale } : { phone };
602
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
603
- if (smsRes.status === 410 || smsRes.status === 404) {
604
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
605
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
606
- }
607
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
608
- return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
1158
+ let smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
1159
+ if (smsRes.status === 401 || smsRes.status === 403 || smsRes.status === 404 || smsRes.status === 410) {
1160
+ flow = await newFlow();
1161
+ pendingCheckout = flow;
1162
+ smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
1163
+ }
1164
+ flow.cookie = mergeCookies(flow.cookie, smsRes);
1165
+ if (smsRes.status !== 204)
1166
+ return phoneFailure(smsRes.status);
1167
+ await rememberSignIn(phone);
1168
+ return { ok: true, value: void 0 };
609
1169
  } catch {
610
1170
  pendingCheckout = void 0;
611
1171
  }
612
1172
  }
613
1173
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
614
1174
  if (response.status === 204) {
1175
+ await rememberSignIn(phone);
615
1176
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
616
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
617
- startMagicPoll(origin, pendingToken);
618
- }
1177
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken))
1178
+ await waitFor(origin, pendingToken, phone);
619
1179
  return { ok: true, value: void 0 };
620
1180
  }
621
1181
  return phoneFailure(response.status);
@@ -623,41 +1183,47 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
623
1183
  return phoneFailure();
624
1184
  }
625
1185
  },
626
- async signInByPhone(phone, code) {
1186
+ async signInByPhone(phone, code, localeHint) {
627
1187
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code))
628
1188
  return phoneFailure(400);
629
1189
  const isEmail = phone.includes("@");
1190
+ const locale = clientLocale(localeHint);
630
1191
  const version2 = generation;
631
1192
  try {
632
1193
  const origin = billingOrigin(getOrigin());
633
1194
  let token;
634
1195
  let checkoutUrl;
635
1196
  let cookie;
636
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
1197
+ const flow = pendingCheckout;
1198
+ if (!loginOnly && flow && flow.origin === origin) {
637
1199
  const verifyAction = isEmail ? "email/verify" : "login";
638
1200
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
639
- const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
1201
+ const loginRes = await checkoutPost(flow.url, verifyAction, origin, verifyBody, flow.token, flow.cookie, locale);
640
1202
  if (!loginRes.ok) {
641
- if (loginRes.status === 410 || loginRes.status === 404)
642
- pendingCheckout = void 0;
1203
+ if (loginRes.status === 401 || loginRes.status === 403 || loginRes.status === 404 || loginRes.status === 410) {
1204
+ if (pendingCheckout === flow)
1205
+ pendingCheckout = void 0;
1206
+ }
643
1207
  return phoneFailure(loginRes.status);
644
1208
  }
645
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
646
- token = pendingCheckout.token;
647
- checkoutUrl = pendingCheckout.url;
648
- pendingCheckout = void 0;
649
- const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
1209
+ cookie = mergeCookies(flow.cookie, loginRes);
1210
+ token = flow.token;
1211
+ checkoutUrl = flow.url;
1212
+ if (pendingCheckout === flow)
1213
+ pendingCheckout = void 0;
1214
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie, locale).catch(() => null);
650
1215
  if (orderRes?.ok) {
651
1216
  cookie = mergeCookies(cookie, orderRes);
652
1217
  const orderData = await orderRes.json().catch(() => null);
653
1218
  if (orderData && typeof orderData === "object") {
654
1219
  if (orderData.active === true) {
655
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
1220
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
656
1221
  } else if (typeof orderData.qr === "string" && orderData.qr) {
657
1222
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
658
1223
  cachedOrder = {
659
1224
  at: Date.now(),
660
1225
  origin,
1226
+ locale,
661
1227
  result: {
662
1228
  status: "qr",
663
1229
  qr,
@@ -666,12 +1232,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
666
1232
  }
667
1233
  };
668
1234
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
669
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
1235
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
670
1236
  }
671
1237
  }
672
1238
  }
673
1239
  } else {
674
- const response = await phoneRequest(origin, "verify", phone, code);
1240
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
675
1241
  if (response.status !== 201)
676
1242
  return phoneFailure(response.status);
677
1243
  cookie = mergeCookies(void 0, response);
@@ -699,11 +1265,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
699
1265
  }
700
1266
  if (cachedOrder?.result.status === "active")
701
1267
  state.active = true;
1268
+ if (!checkoutUrl && state.active !== true && await mustPayFirst()) {
1269
+ await rememberSignIn(phone);
1270
+ await waitFor(origin, token, phone);
1271
+ return { ok: false, reason: "notPro" };
1272
+ }
702
1273
  return await writeSession(async () => {
703
1274
  if (version2 !== generation || disposed || origin !== billingOrigin(getOrigin()))
704
1275
  return phoneFailure();
705
- stopMagicPoll();
706
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
1276
+ clearWaiting();
1277
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
707
1278
  ++generation;
708
1279
  activeOrigin = origin;
709
1280
  applyEntitlement(state);
@@ -717,12 +1288,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
717
1288
  }
718
1289
  },
719
1290
  async deactivate() {
720
- stopMagicPoll();
1291
+ clearWaiting();
721
1292
  pendingCheckout = void 0;
722
1293
  cachedOrder = void 0;
723
1294
  const saved = await writeSession(async () => {
724
1295
  const previous = await storage.read();
725
- await storage.write(void 0);
1296
+ await storage.write(signedOutRecord());
726
1297
  ++generation;
727
1298
  clearTimeout(timer);
728
1299
  lastCheck = 0;
@@ -733,7 +1304,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
733
1304
  return;
734
1305
  try {
735
1306
  const { origin, token } = JSON.parse(saved);
736
- if (origin !== billingOrigin(getOrigin()))
1307
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string")
737
1308
  return;
738
1309
  await fetch(origin + "/billing/v1/entitlement", {
739
1310
  method: "DELETE",
@@ -764,58 +1335,20 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
764
1335
  return;
765
1336
  telemetryTimer = setTimeout(() => {
766
1337
  telemetryTimer = void 0;
767
- void (async () => {
768
- if (disposed || !pendingEvents.size)
769
- return;
770
- let origin;
771
- try {
772
- origin = billingOrigin(getOrigin());
773
- } catch {
774
- return;
775
- }
776
- if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
777
- if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
778
- return;
779
- const customHome = process.env.INKMAP_HOME || "";
780
- 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-"))) {
781
- return;
782
- }
783
- }
784
- const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
785
- if (disposed || !id || !pendingEvents.size)
786
- return;
787
- await (trial ??= startTrial());
788
- const events = {};
789
- for (const [k2, v2] of pendingEvents.entries())
790
- events[k2] = v2;
791
- pendingEvents.clear();
792
- const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
793
- const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
794
- const hostName = detectedHost || inferNodeHost();
795
- await fetch(origin + "/billing/v1/telemetry", {
796
- method: "POST",
797
- headers: { "content-type": "application/json" },
798
- redirect: "error",
799
- body: JSON.stringify({
800
- product: PRODUCT.id,
801
- installId: id,
802
- host: hostName,
803
- os,
804
- version: "0.3.8",
805
- locale: clientLocale(),
806
- tier,
807
- events
808
- }),
809
- signal: AbortSignal.timeout(5e3)
810
- }).catch(() => {
811
- });
812
- })();
1338
+ void sendPendingTelemetry();
813
1339
  }, 800);
814
1340
  telemetryTimer.unref();
815
1341
  },
1342
+ async flushTelemetry() {
1343
+ if (telemetryTimer) {
1344
+ clearTimeout(telemetryTimer);
1345
+ telemetryTimer = void 0;
1346
+ }
1347
+ await sendPendingTelemetry();
1348
+ },
816
1349
  dispose() {
817
1350
  disposed = true;
818
- stopMagicPoll();
1351
+ clearWaiting();
819
1352
  clearTimeout(trialTimer);
820
1353
  clearTimeout(timer);
821
1354
  clearTimeout(telemetryTimer);
@@ -835,35 +1368,47 @@ function inferNodeHost() {
835
1368
  return "cursor";
836
1369
  if (app.includes("windsurf"))
837
1370
  return "windsurf";
1371
+ if (app.includes("trae"))
1372
+ return "trae";
1373
+ if (app.includes("qoder"))
1374
+ return "qoder";
838
1375
  return "vscode";
839
1376
  }
840
1377
  return "cli";
841
1378
  }
842
- async function localInstallId() {
843
- const path = (0, import_node_path.join)(process.env.INKMAP_HOME ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
844
- let value;
1379
+ async function atomicCreateIfMissing(path, initialContent) {
845
1380
  try {
846
- value = (await (0, import_promises.readFile)(path, "utf8")).trim();
1381
+ return await (0, import_promises.readFile)(path, "utf8");
847
1382
  } catch (error62) {
848
1383
  if (error62.code !== "ENOENT")
849
1384
  throw error62;
850
1385
  await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true, mode: 448 });
851
- const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
852
1386
  const temporary = path + "." + (0, import_node_crypto.randomUUID)();
853
1387
  try {
854
- await (0, import_promises.writeFile)(temporary, generated, { mode: 384, flag: "wx" });
855
- await (0, import_promises.link)(temporary, path).catch((err) => {
856
- if (err.code !== "EEXIST")
857
- throw err;
1388
+ await (0, import_promises.writeFile)(temporary, initialContent, { mode: 384, flag: "wx" });
1389
+ await (0, import_promises.link)(temporary, path).catch(async (err) => {
1390
+ if (err.code === "EEXIST")
1391
+ return;
1392
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
1393
+ await (0, import_promises.rename)(temporary, path);
1394
+ return;
1395
+ }
1396
+ throw err;
858
1397
  });
859
1398
  } finally {
860
- await (0, import_promises.rm)(temporary, { force: true });
1399
+ await (0, import_promises.rm)(temporary, { force: true }).catch(() => {
1400
+ });
861
1401
  }
862
- value = (await (0, import_promises.readFile)(path, "utf8")).trim();
1402
+ return await (0, import_promises.readFile)(path, "utf8");
863
1403
  }
1404
+ }
1405
+ async function localInstallId() {
1406
+ const path = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
1407
+ const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
1408
+ const value = (await atomicCreateIfMissing(path, generated)).trim();
864
1409
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
865
1410
  }
866
- function fileSessionStorage(path = (0, import_node_path.join)(process.env.INKMAP_HOME ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "billing-session")) {
1411
+ function fileSessionStorage(path = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "billing-session")) {
867
1412
  return {
868
1413
  read: () => (0, import_promises.readFile)(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
869
1414
  async write(token) {
@@ -881,49 +1426,12 @@ function fileSessionStorage(path = (0, import_node_path.join)(process.env.INKMAP
881
1426
  };
882
1427
  }
883
1428
  async function localTrialDeadline() {
884
- const path = (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap", "trial-start");
885
- const now = Date.now();
886
- let value;
887
- try {
888
- value = await (0, import_promises.readFile)(path, "utf8");
889
- } catch (error62) {
890
- if (error62.code !== "ENOENT")
891
- throw error62;
892
- await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true, mode: 448 });
893
- const temporary = path + "." + (0, import_node_crypto.randomUUID)();
894
- try {
895
- await (0, import_promises.writeFile)(temporary, String(now), { mode: 384, flag: "wx" });
896
- await (0, import_promises.link)(temporary, path).catch((error63) => {
897
- if (error63.code !== "EEXIST")
898
- throw error63;
899
- });
900
- } finally {
901
- await (0, import_promises.rm)(temporary, { force: true });
902
- }
903
- value = await (0, import_promises.readFile)(path, "utf8");
904
- }
1429
+ const path = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "trial-start");
1430
+ const value = await atomicCreateIfMissing(path, String(Date.now()));
905
1431
  const started = Number(value);
906
1432
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
907
1433
  }
908
- function adFeed(url2) {
909
- let cache;
910
- return async () => {
911
- if (!url2)
912
- return [];
913
- if (cache && Date.now() - cache.at < AD_TTL)
914
- return cache.ads;
915
- try {
916
- const res = await fetch(url2, { signal: AbortSignal.timeout(5e3), headers: { accept: "application/json" } });
917
- const ads = res.ok ? sanitizeAds(await res.json()) : [];
918
- cache = { at: Date.now(), ads };
919
- return ads;
920
- } catch {
921
- cache = { at: Date.now(), ads: [] };
922
- return [];
923
- }
924
- };
925
- }
926
- var import_node_child_process, import_promises, import_node_crypto, import_node_os, import_node_path, cachedOsLocale, AD_TTL;
1434
+ var import_node_child_process, import_promises, import_node_crypto, import_node_os, import_node_path, ZH_LOCALE_RE, EN_LOCALE_RE, cachedOsLocale, WAIT_FAST_MS, WAIT_SLOW_MS, WAIT_FAST_FOR_MS, WAIT_MAX_MS, MAX_WAITING, DOMESTIC_TIME_ZONE, posixLocale;
927
1435
  var init_license = __esm({
928
1436
  "packages/cli/dist/license.js"() {
929
1437
  "use strict";
@@ -932,21 +1440,64 @@ var init_license = __esm({
932
1440
  import_node_crypto = require("node:crypto");
933
1441
  import_node_os = require("node:os");
934
1442
  import_node_path = require("node:path");
1443
+ init_version();
935
1444
  init_dist();
936
- AD_TTL = 6 * 60 * 60 * 1e3;
1445
+ ZH_LOCALE_RE = /^zh(?:[-_.]|$)/i;
1446
+ EN_LOCALE_RE = /^en(?:[-_.]|$)/i;
1447
+ WAIT_FAST_MS = 2500;
1448
+ WAIT_SLOW_MS = 3e4;
1449
+ WAIT_FAST_FOR_MS = 30 * 6e4;
1450
+ WAIT_MAX_MS = 3 * 24 * 60 * 6e4;
1451
+ MAX_WAITING = 5;
1452
+ DOMESTIC_TIME_ZONE = /^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i;
1453
+ posixLocale = (env) => (env.LC_ALL || env.LC_MESSAGES || env.LANG || "").trim();
937
1454
  }
938
1455
  });
939
1456
 
940
- // packages/cli/dist/server.js
941
- function insideRoot(root, target) {
1457
+ // packages/cli/dist/workspace-fs.js
1458
+ function insideOrEqual(root, target) {
942
1459
  if (root === target)
943
1460
  return true;
944
1461
  const rel = (0, import_node_path2.relative)(root, target);
945
1462
  return Boolean(rel && !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path2.sep));
946
1463
  }
1464
+ function hasHiddenSegment(root, target) {
1465
+ const rel = (0, import_node_path2.relative)(root, target);
1466
+ if (!rel || rel === ".")
1467
+ return false;
1468
+ return rel.split(import_node_path2.sep).some((part) => part.startsWith("."));
1469
+ }
1470
+ async function hasSymlinkUnderRoot(realRoot, rawTarget) {
1471
+ let cur = rawTarget;
1472
+ while (cur && cur !== (0, import_node_path2.dirname)(cur)) {
1473
+ const st = await (0, import_promises2.lstat)(cur);
1474
+ if (st.isSymbolicLink())
1475
+ return true;
1476
+ if (await (0, import_promises2.realpath)(cur) === realRoot)
1477
+ return false;
1478
+ cur = (0, import_node_path2.dirname)(cur);
1479
+ }
1480
+ return false;
1481
+ }
1482
+ function uriToPath(uri, platform = process.platform) {
1483
+ if (typeof uri !== "string" || !uri.trim())
1484
+ return null;
1485
+ const trimmed = uri.trim();
1486
+ const windows = platform === "win32";
1487
+ try {
1488
+ if (trimmed.startsWith("file://")) {
1489
+ const path = (0, import_node_url.fileURLToPath)(trimmed.replace(/^file:\/\/\/([a-zA-Z])%3[aA](?=\/|$)/, "file:///$1:"), { windows });
1490
+ return windows && /^[a-zA-Z]:$/.test(path) ? path + "\\" : path;
1491
+ }
1492
+ if ((windows ? import_node_path2.win32 : import_node_path2.posix).isAbsolute(trimmed))
1493
+ return trimmed;
1494
+ } catch {
1495
+ }
1496
+ return null;
1497
+ }
947
1498
  async function findProjectRoot(filePath) {
948
- let cur = (0, import_node_path2.dirname)(filePath);
949
1499
  const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1500
+ let cur = (0, import_node_path2.dirname)(filePath);
950
1501
  while (cur && cur !== (0, import_node_path2.dirname)(cur) && cur !== home) {
951
1502
  try {
952
1503
  await (0, import_promises2.lstat)((0, import_node_path2.join)(cur, ".git"));
@@ -957,7 +1508,7 @@ async function findProjectRoot(filePath) {
957
1508
  }
958
1509
  return (0, import_node_path2.dirname)(filePath);
959
1510
  }
960
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1511
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
961
1512
  const found = [];
962
1513
  async function walk(dir, depth) {
963
1514
  if (depth > maxDepth || found.length >= maxFiles)
@@ -979,12 +1530,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
979
1530
  await walk(full, depth + 1);
980
1531
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
981
1532
  try {
982
- const st = await (0, import_promises2.lstat)(full);
983
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
984
- const real = await (0, import_promises2.realpath)(full);
985
- if (real === full && insideRoot(rootDir, real))
986
- found.push(real);
987
- }
1533
+ const info = await (0, import_promises2.lstat)(full);
1534
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1535
+ continue;
1536
+ const real = await (0, import_promises2.realpath)(full);
1537
+ if (real === full && insideOrEqual(rootDir, real))
1538
+ found.push({ path: real, mtimeMs: info.mtimeMs });
988
1539
  } catch {
989
1540
  }
990
1541
  }
@@ -992,60 +1543,250 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
992
1543
  }
993
1544
  await walk(rootDir, 0);
994
1545
  found.sort((a, b) => {
995
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
996
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
997
- if (aM !== bM)
998
- return aM - bM;
999
- return a.localeCompare(b);
1546
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1547
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1548
+ if (am !== bm)
1549
+ return am - bm;
1550
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1551
+ return b.mtimeMs - a.mtimeMs;
1552
+ return a.path.localeCompare(b.path);
1000
1553
  });
1001
1554
  return found;
1002
1555
  }
1556
+ async function discoverAntigravityProjects() {
1557
+ const projectsDir = (0, import_node_path2.join)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".gemini", "config"), "projects");
1558
+ const roots = [];
1559
+ let entries = [];
1560
+ try {
1561
+ entries = await (0, import_promises2.readdir)(projectsDir);
1562
+ } catch {
1563
+ return roots;
1564
+ }
1565
+ for (const name of entries) {
1566
+ if (!name.endsWith(".json"))
1567
+ continue;
1568
+ try {
1569
+ const data = JSON.parse(await (0, import_promises2.readFile)((0, import_node_path2.join)(projectsDir, name), "utf8"));
1570
+ const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
1571
+ for (const r2 of resources) {
1572
+ const p2 = uriToPath(r2?.gitFolder?.folderUri || r2?.folderUri);
1573
+ if (!p2)
1574
+ continue;
1575
+ const real = await (0, import_promises2.realpath)(p2).catch(() => null);
1576
+ if (real)
1577
+ roots.push({ path: real, name: String(data.name || (0, import_node_path2.basename)(real)) });
1578
+ }
1579
+ } catch {
1580
+ }
1581
+ }
1582
+ return roots;
1583
+ }
1584
+ function targetStateFile() {
1585
+ return (0, import_node_path2.join)(process.env.INKMAP_HOME || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap"), "antigravity-target.json");
1586
+ }
1587
+ async function readTargetSelection() {
1588
+ try {
1589
+ const raw = JSON.parse(await (0, import_promises2.readFile)(targetStateFile(), "utf8"));
1590
+ if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
1591
+ return null;
1592
+ const info = await (0, import_promises2.lstat)(raw.file);
1593
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1594
+ return null;
1595
+ const file2 = await (0, import_promises2.realpath)(raw.file);
1596
+ if (file2 !== raw.file)
1597
+ return null;
1598
+ const workspace = typeof raw.workspace === "string" ? await (0, import_promises2.realpath)(raw.workspace).catch(() => (0, import_node_path2.dirname)(file2)) : (0, import_node_path2.dirname)(file2);
1599
+ if (!insideOrEqual(workspace, file2))
1600
+ return null;
1601
+ return { file: file2, workspace, seq: Number(raw.seq) || 0, ...raw.editorOnly === true && { editorOnly: true } };
1602
+ } catch {
1603
+ return null;
1604
+ }
1605
+ }
1606
+ function createSerialQueue() {
1607
+ let tail = Promise.resolve();
1608
+ return function serialized(work) {
1609
+ const next = tail.then(work);
1610
+ tail = next.catch(() => {
1611
+ });
1612
+ return next;
1613
+ };
1614
+ }
1615
+ function createWorkspaceAccess() {
1616
+ const sessionWorkspaces = /* @__PURE__ */ new Map();
1617
+ async function allowedRoots(extraWorkspaceUris = []) {
1618
+ const roots = /* @__PURE__ */ new Map();
1619
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1620
+ const configDir = await (0, import_promises2.realpath)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path2.join)(home, ".gemini", "config")).catch(() => "");
1621
+ const addRoot = async (rawPath, active, label) => {
1622
+ if (!rawPath)
1623
+ return;
1624
+ const real = await (0, import_promises2.realpath)(rawPath).catch(() => null);
1625
+ if (!real || (0, import_node_path2.dirname)(real) === real || real === home)
1626
+ return;
1627
+ if (configDir && insideOrEqual(configDir, real))
1628
+ return;
1629
+ const existing = roots.get(real);
1630
+ if (!existing)
1631
+ roots.set(real, { path: real, name: label || (0, import_node_path2.basename)(real), active });
1632
+ else if (active)
1633
+ existing.active = true;
1634
+ };
1635
+ for (const raw of (process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter).filter(Boolean)) {
1636
+ await addRoot(uriToPath(raw) || (0, import_node_path2.resolve)(raw), true);
1637
+ }
1638
+ for (const uri of extraWorkspaceUris) {
1639
+ if (typeof uri === "string" && uri.trim())
1640
+ await addRoot(uriToPath(uri) || (0, import_node_path2.resolve)(uri.trim()), true);
1641
+ }
1642
+ for (const [path, name] of sessionWorkspaces)
1643
+ await addRoot(path, true, name);
1644
+ const target = await readTargetSelection();
1645
+ if (target)
1646
+ await addRoot(target.workspace, roots.size === 0);
1647
+ for (const project of await discoverAntigravityProjects())
1648
+ await addRoot(project.path, false, project.name);
1649
+ if (roots.size === 0)
1650
+ await addRoot(process.cwd(), true);
1651
+ return { roots: [...roots.values()], target };
1652
+ }
1653
+ async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], registerOutside = false) {
1654
+ if (typeof candidatePath !== "string" || !candidatePath.trim()) {
1655
+ throw new Error(say("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002", "No Markdown file was given."));
1656
+ }
1657
+ const { roots, target } = await allowedRoots(extraWorkspaceUris);
1658
+ const trimmed = candidatePath.trim();
1659
+ let raw = uriToPath(trimmed);
1660
+ if (!raw) {
1661
+ const base = roots.find((r2) => r2.active)?.path || roots[0]?.path || process.cwd();
1662
+ raw = (0, import_node_path2.isAbsolute)(trimmed) ? (0, import_node_path2.resolve)(trimmed) : (0, import_node_path2.resolve)(base, trimmed);
1663
+ }
1664
+ const notMarkdown = () => new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
1665
+ if (!/\.md$/i.test(raw))
1666
+ throw notMarkdown();
1667
+ const info = await (0, import_promises2.lstat)(raw).catch(() => null);
1668
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
1669
+ 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."));
1670
+ }
1671
+ const real = await (0, import_promises2.realpath)(raw);
1672
+ if (!/\.md$/i.test(real))
1673
+ throw notMarkdown();
1674
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1675
+ const brainRoot = await (0, import_promises2.realpath)((0, import_node_path2.join)(home, ".gemini", "antigravity", "brain")).catch(() => null);
1676
+ const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !hasHiddenSegment(brainRoot, real) && !await hasSymlinkUnderRoot(brainRoot, raw));
1677
+ 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."));
1678
+ 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."));
1679
+ if (!inBrainArtifact && insideOrEqual(home, real) && hasHiddenSegment(home, real))
1680
+ throw hiddenError();
1681
+ const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, real));
1682
+ if (!inBrainArtifact && !(target && target.file === real) && !matchedRoot) {
1683
+ if (!registerOutside) {
1684
+ 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."));
1685
+ }
1686
+ const project = await findProjectRoot(real);
1687
+ if (await hasSymlinkUnderRoot(project, raw))
1688
+ throw symlinkError();
1689
+ if (hasHiddenSegment(project, real))
1690
+ throw hiddenError();
1691
+ sessionWorkspaces.set(project, (0, import_node_path2.basename)(project));
1692
+ return real;
1693
+ }
1694
+ if (matchedRoot) {
1695
+ if (await hasSymlinkUnderRoot(matchedRoot.path, raw))
1696
+ throw symlinkError();
1697
+ if (hasHiddenSegment(matchedRoot.path, real))
1698
+ throw hiddenError();
1699
+ }
1700
+ return real;
1701
+ }
1702
+ return { allowedRoots, assertAllowedFile };
1703
+ }
1704
+ var import_promises2, import_node_os2, import_node_path2, import_node_url, say, MAX_MARKDOWN_BYTES, SKIP_SCAN_DIRS, MARKMAP_RE;
1705
+ var init_workspace_fs = __esm({
1706
+ "packages/cli/dist/workspace-fs.js"() {
1707
+ "use strict";
1708
+ import_promises2 = require("node:fs/promises");
1709
+ import_node_os2 = require("node:os");
1710
+ import_node_path2 = require("node:path");
1711
+ import_node_url = require("node:url");
1712
+ init_license();
1713
+ say = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1714
+ MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
1715
+ SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
1716
+ ".git",
1717
+ ".hg",
1718
+ ".svn",
1719
+ "node_modules",
1720
+ "dist",
1721
+ "dist-codex",
1722
+ "dist-workbuddy",
1723
+ "build",
1724
+ "out",
1725
+ ".next",
1726
+ ".nuxt",
1727
+ ".agents",
1728
+ ".agent",
1729
+ ".gemini",
1730
+ ".codex",
1731
+ ".venv",
1732
+ "venv",
1733
+ "target",
1734
+ "coverage",
1735
+ ".tmp"
1736
+ ]);
1737
+ MARKMAP_RE = /\.markmap\.md$/i;
1738
+ }
1739
+ });
1740
+
1741
+ // packages/cli/dist/server.js
1003
1742
  function docName(path) {
1004
- return (0, import_node_path2.basename)(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1743
+ return (0, import_node_path3.basename)(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1005
1744
  }
1006
1745
  function viewStateFile(key) {
1007
- const base = process.env.INKMAP_HOME ?? (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap");
1008
- return (0, import_node_path2.join)(base, "view-state", hash(key) + ".json");
1746
+ const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1747
+ return (0, import_node_path3.join)(base, "view-state", hash(key) + ".json");
1009
1748
  }
1010
1749
  async function readDiskViewState(key) {
1011
1750
  try {
1012
- return sanitizeViewState(JSON.parse(await (0, import_promises2.readFile)(viewStateFile(key), "utf8")));
1751
+ return sanitizeViewState(JSON.parse(await (0, import_promises3.readFile)(viewStateFile(key), "utf8")));
1013
1752
  } catch {
1014
1753
  return void 0;
1015
1754
  }
1016
1755
  }
1017
1756
  async function writeDiskViewState(key, state) {
1018
1757
  const target = viewStateFile(key);
1019
- await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(target), { recursive: true, mode: 448 });
1758
+ await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(target), { recursive: true, mode: 448 });
1020
1759
  const temp = `${target}.${process.pid}.${Date.now()}`;
1021
1760
  try {
1022
- await (0, import_promises2.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1023
- await (0, import_promises2.rename)(temp, target);
1761
+ await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1762
+ await (0, import_promises3.rename)(temp, target);
1024
1763
  } finally {
1025
- await (0, import_promises2.rm)(temp, { force: true }).catch(() => {
1764
+ await (0, import_promises3.rm)(temp, { force: true }).catch(() => {
1026
1765
  });
1027
1766
  }
1028
1767
  }
1029
1768
  async function fileSource(file2, log = () => {
1030
1769
  }) {
1031
- const path = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(file2)).catch(() => (0, import_node_path2.resolve)(file2));
1032
- if (!(await (0, import_promises2.stat)(path)).isFile())
1770
+ const path = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(file2)).catch(() => (0, import_node_path3.resolve)(file2));
1771
+ if (!(await (0, import_promises3.stat)(path)).isFile())
1033
1772
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1034
- const dir = (0, import_node_path2.dirname)(path);
1773
+ const dir = (0, import_node_path3.dirname)(path);
1035
1774
  return {
1036
1775
  name: docName(path),
1037
1776
  key: path,
1038
1777
  dir,
1039
- read: () => (0, import_promises2.readFile)(path, "utf8"),
1778
+ read: () => (0, import_promises3.readFile)(path, "utf8"),
1040
1779
  async write(md) {
1041
- await (0, import_promises2.writeFile)(path, md, "utf8");
1780
+ await (0, import_promises3.writeFile)(path, md, "utf8");
1042
1781
  log(`\u5DF2\u5199\u56DE ${path}`);
1043
1782
  },
1044
1783
  watch(onChange) {
1045
1784
  const watcher = (0, import_node_fs.watch)(dir, (_2, changed) => {
1046
- if (!changed || changed === (0, import_node_path2.basename)(path))
1785
+ if (!changed || changed === (0, import_node_path3.basename)(path))
1047
1786
  onChange();
1048
1787
  });
1788
+ watcher.on("error", () => {
1789
+ });
1049
1790
  return () => watcher.close();
1050
1791
  },
1051
1792
  readView: () => readDiskViewState(path),
@@ -1053,22 +1794,57 @@ async function fileSource(file2, log = () => {
1053
1794
  };
1054
1795
  }
1055
1796
  function within(root, rel) {
1056
- const base = root.endsWith(import_node_path2.sep) ? root : root + import_node_path2.sep;
1057
- const full = (0, import_node_path2.normalize)((0, import_node_path2.join)(root, decodeURIComponent(rel)));
1797
+ let decoded;
1798
+ try {
1799
+ decoded = decodeURIComponent(rel);
1800
+ } catch {
1801
+ return null;
1802
+ }
1803
+ const resolvedRoot = (0, import_node_path3.resolve)(root);
1804
+ const base = resolvedRoot.endsWith(import_node_path3.sep) ? resolvedRoot : resolvedRoot + import_node_path3.sep;
1805
+ const full = (0, import_node_path3.normalize)((0, import_node_path3.join)(resolvedRoot, decoded));
1058
1806
  return full.startsWith(base) ? full : null;
1059
1807
  }
1808
+ async function openBrowserWindow(url2) {
1809
+ if (process.env.INKMAP_NO_OPEN === "1" || !/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+\//.test(url2))
1810
+ return;
1811
+ const run = (cmd, args) => new Promise((done) => {
1812
+ const child = (0, import_node_child_process2.spawn)(cmd, args, { stdio: "ignore", detached: true });
1813
+ child.on("error", () => done(false));
1814
+ child.on("exit", (code) => done(code === 0));
1815
+ child.unref();
1816
+ });
1817
+ if (process.platform === "darwin") {
1818
+ if (await run("open", ["-a", "Google Chrome", url2]))
1819
+ return;
1820
+ await run("open", [url2]);
1821
+ return;
1822
+ }
1823
+ if (process.platform === "win32") {
1824
+ if (await run("cmd", ["/c", "start", "", "chrome", url2]))
1825
+ return;
1826
+ await run("cmd", ["/c", "start", "", url2]);
1827
+ return;
1828
+ }
1829
+ if (await run("google-chrome", [url2]))
1830
+ return;
1831
+ await run("xdg-open", [url2]);
1832
+ }
1060
1833
  async function serve({ source: initialSource, webRoot, port = 4377, host = "127.0.0.1", log = () => {
1061
- }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1834
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1062
1835
  if (sidebar && host !== "127.0.0.1")
1063
1836
  throw new Error("The sidebar bridge requires loopback.");
1064
1837
  const prefix = sidebar ? `/s/${(0, import_node_crypto2.randomBytes)(24).toString("hex")}/` : "/";
1065
1838
  let activeSource = initialSource;
1839
+ let browserCompanion = null;
1066
1840
  let bound;
1067
1841
  let current = await activeSource.read();
1068
1842
  let version2 = hash(current);
1069
1843
  let viewState = await activeSource.readView?.();
1070
1844
  const clients = /* @__PURE__ */ new Set();
1071
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1845
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1846
+ const allowedHosts = /* @__PURE__ */ new Set();
1847
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1072
1848
  const docState = () => ({
1073
1849
  name: activeSource.name,
1074
1850
  md: current,
@@ -1103,36 +1879,36 @@ data: ${JSON.stringify(data)}
1103
1879
  broadcast();
1104
1880
  }
1105
1881
  let pending;
1106
- let unwatch = activeSource.watch(() => {
1882
+ const scheduleRefresh = () => {
1107
1883
  clearTimeout(pending);
1108
- pending = setTimeout(async () => {
1109
- void serialized(refresh).catch(() => {
1110
- });
1111
- }, 80);
1112
- });
1884
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1885
+ }), 80);
1886
+ };
1887
+ let unwatch = activeSource.watch(scheduleRefresh);
1888
+ const canonicalActiveKey = async () => activeSource.key ? await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key) : void 0;
1113
1889
  async function collectWorkspaceFiles() {
1114
1890
  const roots = /* @__PURE__ */ new Map();
1115
- if (activeSource.key) {
1116
- const realKey = await (0, import_promises2.realpath)(activeSource.key).catch(() => activeSource.key);
1117
- const projRoot = await (0, import_promises2.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path2.dirname)(realKey));
1118
- roots.set(projRoot, { path: projRoot, name: (0, import_node_path2.basename)(projRoot), active: true });
1891
+ if (activeSource.key && !confineToWorkspaceRoots) {
1892
+ const realKey = await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key);
1893
+ const projRoot = await (0, import_promises3.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path3.dirname)(realKey));
1894
+ roots.set(projRoot, { path: projRoot, name: (0, import_node_path3.basename)(projRoot), active: true });
1119
1895
  }
1120
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter)].filter(Boolean);
1896
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter)].filter(Boolean);
1121
1897
  for (const raw of envRoots) {
1122
- const real = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(raw)).catch(() => null);
1898
+ const real = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(raw)).catch(() => null);
1123
1899
  if (real && !roots.has(real)) {
1124
- roots.set(real, { path: real, name: (0, import_node_path2.basename)(real), active: roots.size === 0 });
1900
+ roots.set(real, { path: real, name: (0, import_node_path3.basename)(real), active: roots.size === 0 });
1125
1901
  }
1126
1902
  }
1127
1903
  const items = [];
1128
1904
  const seen = /* @__PURE__ */ new Set();
1129
1905
  for (const root of roots.values()) {
1130
- const files = await scanProjectMarkdownFiles(root.path);
1906
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1131
1907
  for (const f2 of files) {
1132
1908
  if (seen.has(f2))
1133
1909
  continue;
1134
1910
  seen.add(f2);
1135
- const rel = (0, import_node_path2.relative)(root.path, f2);
1911
+ const rel = (0, import_node_path3.relative)(root.path, f2);
1136
1912
  items.push({
1137
1913
  path: f2,
1138
1914
  label: `${root.name} / ${rel}`,
@@ -1140,43 +1916,52 @@ data: ${JSON.stringify(data)}
1140
1916
  });
1141
1917
  }
1142
1918
  }
1143
- if (activeSource.key && !seen.has(activeSource.key)) {
1919
+ const activeReal = await canonicalActiveKey();
1920
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1144
1921
  items.unshift({
1145
1922
  path: activeSource.key,
1146
- label: `${(0, import_node_path2.basename)(activeSource.dir)} / ${(0, import_node_path2.basename)(activeSource.key)}`,
1923
+ label: `${(0, import_node_path3.basename)(activeSource.dir)} / ${(0, import_node_path3.basename)(activeSource.key)}`,
1147
1924
  group: "active"
1148
1925
  });
1149
1926
  }
1150
1927
  return { roots: [...roots.values()], files: items };
1151
1928
  }
1152
- async function switchSourceToFile(candidatePath) {
1153
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1154
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1155
- }
1156
- const realTarget = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(candidatePath));
1157
- const st = await (0, import_promises2.lstat)(realTarget);
1158
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1159
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1160
- }
1161
- const { roots } = await collectWorkspaceFiles();
1162
- if (roots.length > 0 && !roots.some((r2) => insideRoot(r2.path, realTarget))) {
1163
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1164
- }
1165
- if (activeSource.key === realTarget)
1929
+ const zh = () => detectOsLocale() === "zh";
1930
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1931
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1932
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1933
+ throw notMarkdown();
1934
+ const resolvedCandidate = (0, import_node_path3.resolve)(candidatePath);
1935
+ const rawStat = await (0, import_promises3.lstat)(resolvedCandidate).catch(() => null);
1936
+ const realTarget = await (0, import_promises3.realpath)(resolvedCandidate).catch(() => null);
1937
+ const targetStat = realTarget ? await (0, import_promises3.stat)(realTarget).catch(() => null) : null;
1938
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1939
+ 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.");
1940
+ }
1941
+ if (!/\.md$/i.test(realTarget))
1942
+ throw notMarkdown();
1943
+ if (!trustCaller) {
1944
+ const { roots } = await collectWorkspaceFiles();
1945
+ const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, realTarget));
1946
+ if (!matchedRoot) {
1947
+ 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.");
1948
+ }
1949
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1950
+ 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.");
1951
+ }
1952
+ }
1953
+ if (await canonicalActiveKey() === realTarget)
1166
1954
  return;
1955
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1956
+ const text = await next.read();
1957
+ const nextView = await next.readView?.();
1167
1958
  clearTimeout(pending);
1168
1959
  unwatch();
1169
- activeSource = await fileSource(realTarget, log);
1170
- current = await activeSource.read();
1171
- version2 = hash(current);
1172
- viewState = await activeSource.readView?.();
1173
- unwatch = activeSource.watch(() => {
1174
- clearTimeout(pending);
1175
- pending = setTimeout(async () => {
1176
- void serialized(refresh).catch(() => {
1177
- });
1178
- }, 80);
1179
- });
1960
+ activeSource = next;
1961
+ current = text;
1962
+ version2 = hash(text);
1963
+ viewState = nextView;
1964
+ unwatch = activeSource.watch(scheduleRefresh);
1180
1965
  broadcast();
1181
1966
  }
1182
1967
  const json2 = (res, status, body) => {
@@ -1189,7 +1974,7 @@ data: ${JSON.stringify(data)}
1189
1974
  req.on("data", (c) => {
1190
1975
  size += c.length;
1191
1976
  if (size > MAX_BODY) {
1192
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1977
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1193
1978
  req.destroy();
1194
1979
  } else
1195
1980
  chunks.push(c);
@@ -1201,16 +1986,23 @@ data: ${JSON.stringify(data)}
1201
1986
  if (!full)
1202
1987
  return json2(res, 403, { error: "forbidden" });
1203
1988
  try {
1204
- const ext = (0, import_node_path2.extname)(full).toLowerCase();
1989
+ const ext = (0, import_node_path3.extname)(full).toLowerCase();
1205
1990
  if (ext === ".html") {
1206
1991
  const osLoc = detectOsLocale();
1207
- const htmlText = (await (0, import_promises2.readFile)(full, "utf8")).replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1992
+ const htmlText = (await (0, import_promises3.readFile)(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1208
1993
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1209
1994
  res.end(htmlText, "utf8");
1210
1995
  return;
1211
1996
  }
1212
- const body = await (0, import_promises2.readFile)(full);
1213
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1997
+ const body = await (0, import_promises3.readFile)(full);
1998
+ const headers = {
1999
+ "content-type": TYPES[ext] ?? "application/octet-stream",
2000
+ "cache-control": sidebar ? "no-store" : "no-cache"
2001
+ };
2002
+ if (ext === ".svg") {
2003
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
2004
+ }
2005
+ res.writeHead(200, headers);
1214
2006
  res.end(body);
1215
2007
  } catch {
1216
2008
  json2(res, 404, { error: "not found" });
@@ -1219,18 +2011,27 @@ data: ${JSON.stringify(data)}
1219
2011
  const server = (0, import_node_http.createServer)(async (req, res) => {
1220
2012
  try {
1221
2013
  const url2 = new URL(req.url ?? "/", "http://localhost");
2014
+ const reqHost = req.headers.host ?? "";
2015
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1222
2016
  if (sidebar) {
1223
2017
  res.setHeader("Referrer-Policy", "no-referrer");
1224
2018
  res.setHeader("X-Content-Type-Options", "nosniff");
1225
2019
  res.setHeader("Cache-Control", "no-store");
1226
2020
  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'");
1227
- if (req.headers.host !== `127.0.0.1:${bound}` || !url2.pathname.startsWith(prefix))
2021
+ if (reqHost !== `127.0.0.1:${bound}` || !url2.pathname.startsWith(prefix))
1228
2022
  return json2(res, 404, { error: "not found" });
1229
2023
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1230
2024
  return json2(res, 403, { error: "forbidden" });
1231
2025
  }
1232
2026
  url2.pathname = "/" + url2.pathname.slice(prefix.length);
2027
+ } else if (!hostAllowed) {
2028
+ return json2(res, 403, { error: "forbidden" });
1233
2029
  }
2030
+ const sameOriginWrite = () => {
2031
+ const origin = req.headers.origin;
2032
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
2033
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
2034
+ };
1234
2035
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url2.pathname)) {
1235
2036
  res.writeHead(302, { Location: "/" + url2.search });
1236
2037
  return res.end();
@@ -1254,6 +2055,8 @@ data: ${JSON.stringify(data)}
1254
2055
  });
1255
2056
  }
1256
2057
  if (url2.pathname === "/api/view" && req.method === "PUT") {
2058
+ if (!sameOriginWrite())
2059
+ return json2(res, 403, { error: "forbidden" });
1257
2060
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1258
2061
  if (cleaned) {
1259
2062
  viewState = cleaned;
@@ -1263,9 +2066,11 @@ data: ${JSON.stringify(data)}
1263
2066
  return json2(res, 200, { ok: true });
1264
2067
  }
1265
2068
  if (url2.pathname === "/api/doc" && req.method === "PUT") {
2069
+ if (!sameOriginWrite())
2070
+ return json2(res, 403, { error: "forbidden" });
1266
2071
  const { md, baseVersion } = JSON.parse(await readBody(req));
1267
2072
  if (typeof md !== "string")
1268
- return json2(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
2073
+ return json2(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1269
2074
  if (!hasAccess(await license?.state() ?? { pro: false }))
1270
2075
  return json2(res, 403, { error: "Inkmap trial expired" });
1271
2076
  return await serialized(async () => {
@@ -1277,39 +2082,68 @@ data: ${JSON.stringify(data)}
1277
2082
  current = md;
1278
2083
  version2 = hash(md);
1279
2084
  license?.track?.("doc_edit");
1280
- if (sidebar)
1281
- broadcast();
2085
+ broadcast();
1282
2086
  }
1283
2087
  return json2(res, 200, { version: version2 });
1284
2088
  });
1285
2089
  }
1286
2090
  if (url2.pathname === "/api/license" && req.method === "GET")
1287
2091
  return json2(res, 200, await license?.state() ?? { pro: false });
1288
- const sameOriginPost = () => {
1289
- const origin = req.headers.origin;
1290
- const reqHost = req.headers.host;
1291
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1292
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1293
- };
1294
2092
  if (url2.pathname === "/api/open" && req.method === "POST") {
1295
- if (!sameOriginPost())
2093
+ if (!sameOriginWrite())
1296
2094
  return json2(res, 403, { error: "forbidden" });
1297
2095
  const { file: file2 } = JSON.parse(await readBody(req));
1298
- await serialized(() => switchSourceToFile(String(file2 ?? "")));
2096
+ await serialized(() => switchSourceToFile(String(file2 ?? ""), false));
1299
2097
  license?.track?.("doc_open");
1300
2098
  const { files } = await collectWorkspaceFiles();
1301
2099
  return json2(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1302
2100
  }
1303
2101
  if (url2.pathname === "/api/telemetry" && req.method === "POST") {
1304
- if (!sameOriginPost())
2102
+ if (!sameOriginWrite())
1305
2103
  return json2(res, 403, { error: "forbidden" });
1306
2104
  const { event } = JSON.parse(await readBody(req));
1307
2105
  if (typeof event === "string" && event)
1308
2106
  license?.track?.(event);
1309
2107
  return json2(res, 200, { ok: true });
1310
2108
  }
2109
+ if (url2.pathname === "/api/open-browser" && req.method === "POST") {
2110
+ if (!sameOriginWrite())
2111
+ return json2(res, 403, { error: "forbidden" });
2112
+ if (license && !hasAccess(await license.state())) {
2113
+ return json2(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." });
2114
+ }
2115
+ license?.track?.("feature_browser");
2116
+ if (!sidebar) {
2117
+ const directUrl = `http://${urlHost}:${bound}/`;
2118
+ await openBrowserWindow(directUrl);
2119
+ return json2(res, 200, { ok: true, url: directUrl });
2120
+ }
2121
+ if (!browserCompanion) {
2122
+ browserCompanion = serve({
2123
+ source: activeSource,
2124
+ webRoot,
2125
+ host: "127.0.0.1",
2126
+ port: 0,
2127
+ license,
2128
+ sidebar: false,
2129
+ workspaceRoots,
2130
+ confineToWorkspaceRoots,
2131
+ openSource,
2132
+ allowPurchase: canPurchase
2133
+ });
2134
+ browserCompanion.catch(() => {
2135
+ browserCompanion = null;
2136
+ });
2137
+ }
2138
+ const companion = await browserCompanion;
2139
+ if (activeSource.key)
2140
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
2141
+ });
2142
+ await openBrowserWindow(companion.url);
2143
+ return json2(res, 200, { ok: true, url: companion.url });
2144
+ }
1311
2145
  if (url2.pathname === "/api/checkout" && req.method === "POST") {
1312
- if (!sameOriginPost())
2146
+ if (!sameOriginWrite())
1313
2147
  return json2(res, 403, { error: "forbidden" });
1314
2148
  const { mode, locale } = JSON.parse(await readBody(req));
1315
2149
  if (mode !== "buy" && mode !== "restore")
@@ -1321,7 +2155,7 @@ data: ${JSON.stringify(data)}
1321
2155
  return json2(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1322
2156
  }
1323
2157
  if (url2.pathname === "/api/order-pro" && req.method === "POST") {
1324
- if (!sameOriginPost())
2158
+ if (!sameOriginWrite())
1325
2159
  return json2(res, 403, { error: "forbidden" });
1326
2160
  if (!canPurchase)
1327
2161
  return json2(res, 403, { error: "forbidden" });
@@ -1333,7 +2167,7 @@ data: ${JSON.stringify(data)}
1333
2167
  return json2(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1334
2168
  }
1335
2169
  if (url2.pathname === "/api/phone-send" && req.method === "POST") {
1336
- if (!sameOriginPost())
2170
+ if (!sameOriginWrite())
1337
2171
  return json2(res, 403, { error: "forbidden" });
1338
2172
  if (!license || typeof license.sendPhoneCode !== "function")
1339
2173
  return json2(res, 501, { fallback: true });
@@ -1341,21 +2175,21 @@ data: ${JSON.stringify(data)}
1341
2175
  return json2(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1342
2176
  }
1343
2177
  if (url2.pathname === "/api/phone-verify" && req.method === "POST") {
1344
- if (!sameOriginPost())
2178
+ if (!sameOriginWrite())
1345
2179
  return json2(res, 403, { error: "forbidden" });
1346
2180
  if (!license || typeof license.signInByPhone !== "function")
1347
2181
  return json2(res, 501, { fallback: true });
1348
- const { phone, code } = JSON.parse(await readBody(req));
1349
- return json2(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
2182
+ const { phone, code, locale } = JSON.parse(await readBody(req));
2183
+ return json2(res, 200, {
2184
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
2185
+ });
1350
2186
  }
1351
2187
  if (url2.pathname === "/api/signout" && req.method === "POST") {
1352
- if (!sameOriginPost())
2188
+ if (!sameOriginWrite())
1353
2189
  return json2(res, 403, { error: "forbidden" });
1354
2190
  await license?.deactivate();
1355
2191
  return json2(res, 200, await license?.state() ?? { pro: false });
1356
2192
  }
1357
- if (url2.pathname === "/api/ads")
1358
- return json2(res, 200, sidebar ? [] : await ads?.() ?? []);
1359
2193
  if (url2.pathname === "/api/events") {
1360
2194
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1361
2195
  res.write(": connected\n\n");
@@ -1367,17 +2201,21 @@ data: ${JSON.stringify(data)}
1367
2201
  return void res.writeHead(204).end();
1368
2202
  if (url2.pathname.startsWith("/doc-assets/")) {
1369
2203
  let asset = within(activeSource.dir, url2.pathname.slice("/doc-assets/".length));
1370
- if (sidebar && asset) {
1371
- const root = await (0, import_promises2.realpath)(activeSource.dir);
1372
- asset = await (0, import_promises2.realpath)(asset).catch(() => null);
1373
- if (asset && (!asset.startsWith(root + import_node_path2.sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset)))
2204
+ if (asset) {
2205
+ const root = await (0, import_promises3.realpath)(activeSource.dir).catch(() => null);
2206
+ asset = await (0, import_promises3.realpath)(asset).catch(() => null);
2207
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
2208
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1374
2209
  asset = null;
1375
2210
  }
1376
2211
  return sendFile(res, asset);
1377
2212
  }
1378
2213
  return sendFile(res, within(webRoot, url2.pathname === "/" ? "index.html" : url2.pathname.slice(1)));
1379
2214
  } catch (err) {
1380
- json2(res, 500, { error: err instanceof Error ? err.message : String(err) });
2215
+ if (res.headersSent)
2216
+ return void res.end();
2217
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
2218
+ json2(res, status, { error: err instanceof Error ? err.message : String(err) });
1381
2219
  }
1382
2220
  });
1383
2221
  const listen = (p2) => new Promise((ok, fail) => {
@@ -1388,59 +2226,53 @@ data: ${JSON.stringify(data)}
1388
2226
  });
1389
2227
  });
1390
2228
  try {
1391
- bound = await listen(port);
2229
+ try {
2230
+ bound = await listen(port);
2231
+ } catch (err) {
2232
+ if (err.code !== "EADDRINUSE")
2233
+ throw err;
2234
+ bound = await listen(0);
2235
+ }
1392
2236
  } catch (err) {
1393
- if (err.code !== "EADDRINUSE")
1394
- throw err;
1395
- bound = await listen(0);
2237
+ clearTimeout(pending);
2238
+ unwatch();
2239
+ unlisten();
2240
+ throw err;
1396
2241
  }
1397
2242
  return {
1398
- url: `http://${host}:${bound}${prefix}`,
1399
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
2243
+ url: `http://${urlHost}:${bound}${prefix}`,
2244
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
2245
+ allowHost: (extraHost) => {
2246
+ if (extraHost)
2247
+ allowedHosts.add(extraHost.toLowerCase());
2248
+ },
1400
2249
  close: () => new Promise((done) => {
1401
2250
  clearTimeout(pending);
1402
2251
  unwatch();
1403
2252
  unlisten();
2253
+ if (browserCompanion)
2254
+ void browserCompanion.then((s) => s.close()).catch(() => {
2255
+ });
1404
2256
  for (const res of clients)
1405
2257
  res.end();
1406
2258
  server.close(() => done());
1407
2259
  })
1408
2260
  };
1409
2261
  }
1410
- var import_node_crypto2, import_node_fs, import_promises2, import_node_http, import_node_os2, import_node_path2, SKIP_SCAN_DIRS, MAX_BODY, TYPES, hash;
2262
+ var import_node_child_process2, import_node_crypto2, import_node_fs, import_promises3, import_node_http, import_node_os3, import_node_path3, MAX_BODY, TYPES, HttpError, LOOPBACK_HOST, hash;
1411
2263
  var init_server = __esm({
1412
2264
  "packages/cli/dist/server.js"() {
1413
2265
  "use strict";
1414
2266
  init_dist();
2267
+ import_node_child_process2 = require("node:child_process");
1415
2268
  import_node_crypto2 = require("node:crypto");
1416
2269
  import_node_fs = require("node:fs");
1417
- import_promises2 = require("node:fs/promises");
2270
+ import_promises3 = require("node:fs/promises");
1418
2271
  import_node_http = require("node:http");
1419
- import_node_os2 = require("node:os");
1420
- import_node_path2 = require("node:path");
2272
+ import_node_os3 = require("node:os");
2273
+ import_node_path3 = require("node:path");
1421
2274
  init_license();
1422
- SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
1423
- ".git",
1424
- ".hg",
1425
- ".svn",
1426
- "node_modules",
1427
- "dist",
1428
- "dist-codex",
1429
- "dist-workbuddy",
1430
- "build",
1431
- "out",
1432
- ".next",
1433
- ".nuxt",
1434
- ".agents",
1435
- ".agent",
1436
- ".gemini",
1437
- ".codex",
1438
- ".venv",
1439
- "venv",
1440
- "target",
1441
- "coverage",
1442
- ".tmp"
1443
- ]);
2275
+ init_workspace_fs();
1444
2276
  MAX_BODY = 20 * 1024 * 1024;
1445
2277
  TYPES = {
1446
2278
  ".html": "text/html; charset=utf-8",
@@ -1452,11 +2284,22 @@ var init_server = __esm({
1452
2284
  ".jpeg": "image/jpeg",
1453
2285
  ".gif": "image/gif",
1454
2286
  ".webp": "image/webp",
2287
+ ".avif": "image/avif",
2288
+ ".bmp": "image/bmp",
2289
+ ".ico": "image/x-icon",
1455
2290
  ".woff2": "font/woff2",
1456
2291
  ".woff": "font/woff",
1457
2292
  ".ttf": "font/ttf",
1458
2293
  ".json": "application/json"
1459
2294
  };
2295
+ HttpError = class extends Error {
2296
+ status;
2297
+ constructor(status, message) {
2298
+ super(message);
2299
+ this.status = status;
2300
+ }
2301
+ };
2302
+ LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
1460
2303
  hash = (s) => (0, import_node_crypto2.createHash)("sha1").update(s).digest("hex");
1461
2304
  }
1462
2305
  });
@@ -6648,7 +7491,7 @@ function validateFallback(schema, value, _ctx) {
6648
7491
  }
6649
7492
  return result.issues.length === 0;
6650
7493
  }
6651
- var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, COMPILE_INVALID, COMPILE_FALLBACK, validate, validateAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync;
7494
+ var _parse, parse2, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, COMPILE_INVALID, COMPILE_FALLBACK, validate, validateAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync;
6652
7495
  var init_parse = __esm({
6653
7496
  "node_modules/zod/v4/core/parse.js"() {
6654
7497
  init_core();
@@ -6670,7 +7513,7 @@ var init_parse = __esm({
6670
7513
  };
6671
7514
  return fn;
6672
7515
  };
6673
- parse = /* @__PURE__ */ _parse($ZodRealError);
7516
+ parse2 = /* @__PURE__ */ _parse($ZodRealError);
6674
7517
  _parseAsync = (_Err) => {
6675
7518
  const fn = async (schema, value, _ctx, params) => {
6676
7519
  const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
@@ -6724,18 +7567,18 @@ var init_parse = __esm({
6724
7567
  return result.issues.length === 0;
6725
7568
  };
6726
7569
  _encode = (_Err) => {
6727
- const parse3 = _parse(_Err);
7570
+ const parse4 = _parse(_Err);
6728
7571
  const fn = (schema, value, _ctx, _params) => {
6729
7572
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
6730
- return parse3(schema, value, ctx, finalizeParams(fn, _params));
7573
+ return parse4(schema, value, ctx, finalizeParams(fn, _params));
6731
7574
  };
6732
7575
  return fn;
6733
7576
  };
6734
7577
  encode = /* @__PURE__ */ _encode($ZodRealError);
6735
7578
  _decode = (_Err) => {
6736
- const parse3 = _parse(_Err);
7579
+ const parse4 = _parse(_Err);
6737
7580
  const fn = (schema, value, _ctx, _params) => {
6738
- return parse3(schema, value, _ctx, finalizeParams(fn, _params));
7581
+ return parse4(schema, value, _ctx, finalizeParams(fn, _params));
6739
7582
  };
6740
7583
  return fn;
6741
7584
  };
@@ -7660,7 +8503,7 @@ function capSize(inst, size) {
7660
8503
  if (!caps.length)
7661
8504
  return;
7662
8505
  const cap = Math.min(...caps.map((c) => c[0]));
7663
- const parse3 = inst._zod.parse;
8506
+ const parse4 = inst._zod.parse;
7664
8507
  inst._zod.parse = (payload, ctx) => {
7665
8508
  const n = size(payload.value);
7666
8509
  if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
@@ -7674,7 +8517,7 @@ function capSize(inst, size) {
7674
8517
  }
7675
8518
  }
7676
8519
  }
7677
- return parse3(payload, ctx);
8520
+ return parse4(payload, ctx);
7678
8521
  };
7679
8522
  }
7680
8523
  function handleArrayResult(result, final, index) {
@@ -9843,10 +10686,10 @@ var init_schemas = __esm({
9843
10686
  throw new Error("implement() must be called with a function");
9844
10687
  }
9845
10688
  return Object.defineProperty(function(...args) {
9846
- const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
10689
+ const parsedArgs = inst._def.input ? parse2(inst._def.input, args) : args;
9847
10690
  const result = Reflect.apply(func, this, parsedArgs);
9848
10691
  if (inst._def.output) {
9849
- return parse(inst._def.output, result);
10692
+ return parse2(inst._def.output, result);
9850
10693
  }
9851
10694
  return result;
9852
10695
  }, "_zod", { value: inst._zod, enumerable: false });
@@ -22661,7 +23504,7 @@ __export(core_exports2, {
22661
23504
  memoizer: () => memoizer,
22662
23505
  mergeValues: () => mergeValues2,
22663
23506
  meta: () => meta,
22664
- parse: () => parse,
23507
+ parse: () => parse2,
22665
23508
  parseAsync: () => parseAsync,
22666
23509
  parseURLObject: () => parseURLObject,
22667
23510
  prettifyError: () => prettifyError,
@@ -22752,7 +23595,7 @@ var init_schemas2 = __esm({
22752
23595
  own(this, "with", value);
22753
23596
  },
22754
23597
  parse(data, params) {
22755
- return parse(this, data, params, { callee: this.parse });
23598
+ return parse2(this, data, params, { callee: this.parse });
22756
23599
  },
22757
23600
  parseAsync(data, params) {
22758
23601
  return parseAsync(this, data, params, { callee: this.parseAsync });
@@ -23257,13 +24100,13 @@ var init_errors3 = __esm({
23257
24100
  });
23258
24101
 
23259
24102
  // node_modules/zod/v4/classic/parse.js
23260
- var parse2, parseAsync2, safeParse3, safeParseAsync3, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2;
24103
+ var parse3, parseAsync2, safeParse3, safeParseAsync3, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2;
23261
24104
  var init_parse3 = __esm({
23262
24105
  "node_modules/zod/v4/classic/parse.js"() {
23263
24106
  init_core2();
23264
24107
  init_errors3();
23265
24108
  init_core2();
23266
- parse2 = /* @__PURE__ */ _parse(ZodRealError);
24109
+ parse3 = /* @__PURE__ */ _parse(ZodRealError);
23267
24110
  parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
23268
24111
  safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
23269
24112
  safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -24076,7 +24919,7 @@ var init_schemas3 = __esm({
24076
24919
  util_exports.own(this, "~standard", value);
24077
24920
  },
24078
24921
  parse: function _parse2(data, params) {
24079
- return parse2(this, data, params, { callee: _parse2 });
24922
+ return parse3(this, data, params, { callee: _parse2 });
24080
24923
  },
24081
24924
  parseAsync: async function _parseAsync2(data, params) {
24082
24925
  return await parseAsync2(this, data, params, { callee: _parseAsync2 });
@@ -26025,7 +26868,7 @@ __export(external_exports, {
26025
26868
  optional: () => optional,
26026
26869
  output: () => output,
26027
26870
  overwrite: () => _overwrite,
26028
- parse: () => parse2,
26871
+ parse: () => parse3,
26029
26872
  parseAsync: () => parseAsync2,
26030
26873
  partialRecord: () => partialRecord,
26031
26874
  pipe: () => pipe,
@@ -34115,7 +34958,7 @@ var require_fast_uri = __commonJS({
34115
34958
  normalizeString(uri, options);
34116
34959
  } else if (typeof uri === "object") {
34117
34960
  uri = /** @type {T} */
34118
- parse3(serialize(uri, options), options);
34961
+ parse4(serialize2(uri, options), options);
34119
34962
  }
34120
34963
  return uri;
34121
34964
  }
@@ -34153,52 +34996,52 @@ var require_fast_uri = __commonJS({
34153
34996
  throw new Error(resolved.error);
34154
34997
  }
34155
34998
  schemelessOptions.skipEscape = true;
34156
- return serialize(resolved, schemelessOptions);
34999
+ return serialize2(resolved, schemelessOptions);
34157
35000
  }
34158
- function resolveComponent(base, relative3, options, skipNormalization) {
35001
+ function resolveComponent(base, relative4, options, skipNormalization) {
34159
35002
  const target = {};
34160
35003
  if (!skipNormalization) {
34161
- base = parse3(serialize(base, options), options);
34162
- relative3 = parse3(serialize(relative3, options), options);
35004
+ base = parse4(serialize2(base, options), options);
35005
+ relative4 = parse4(serialize2(relative4, options), options);
34163
35006
  }
34164
35007
  options = options || {};
34165
- if (!options.tolerant && relative3.scheme) {
34166
- target.scheme = relative3.scheme;
34167
- target.userinfo = relative3.userinfo;
34168
- target.host = relative3.host;
34169
- target.port = relative3.port;
34170
- target.path = removeDotSegments(relative3.path || "");
34171
- target.query = relative3.query;
35008
+ if (!options.tolerant && relative4.scheme) {
35009
+ target.scheme = relative4.scheme;
35010
+ target.userinfo = relative4.userinfo;
35011
+ target.host = relative4.host;
35012
+ target.port = relative4.port;
35013
+ target.path = removeDotSegments(relative4.path || "");
35014
+ target.query = relative4.query;
34172
35015
  } else {
34173
- if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
34174
- target.userinfo = relative3.userinfo;
34175
- target.host = relative3.host;
34176
- target.port = relative3.port;
34177
- target.path = removeDotSegments(relative3.path || "");
34178
- target.query = relative3.query;
35016
+ if (relative4.userinfo !== void 0 || relative4.host !== void 0 || relative4.port !== void 0) {
35017
+ target.userinfo = relative4.userinfo;
35018
+ target.host = relative4.host;
35019
+ target.port = relative4.port;
35020
+ target.path = removeDotSegments(relative4.path || "");
35021
+ target.query = relative4.query;
34179
35022
  } else {
34180
- if (!relative3.path) {
35023
+ if (!relative4.path) {
34181
35024
  target.path = base.path;
34182
- if (relative3.query !== void 0) {
34183
- target.query = relative3.query;
35025
+ if (relative4.query !== void 0) {
35026
+ target.query = relative4.query;
34184
35027
  } else {
34185
35028
  target.query = base.query;
34186
35029
  }
34187
35030
  } else {
34188
- if (relative3.path[0] === "/") {
34189
- target.path = removeDotSegments(relative3.path);
35031
+ if (relative4.path[0] === "/") {
35032
+ target.path = removeDotSegments(relative4.path);
34190
35033
  } else {
34191
35034
  const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
34192
35035
  if (baseHasAuthority && !base.path) {
34193
- target.path = "/" + relative3.path;
35036
+ target.path = "/" + relative4.path;
34194
35037
  } else if (!base.path) {
34195
- target.path = relative3.path;
35038
+ target.path = relative4.path;
34196
35039
  } else {
34197
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
35040
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative4.path;
34198
35041
  }
34199
35042
  target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
34200
35043
  }
34201
- target.query = relative3.query;
35044
+ target.query = relative4.query;
34202
35045
  }
34203
35046
  target.userinfo = base.userinfo;
34204
35047
  target.host = base.host;
@@ -34206,7 +35049,7 @@ var require_fast_uri = __commonJS({
34206
35049
  }
34207
35050
  target.scheme = base.scheme;
34208
35051
  }
34209
- target.fragment = relative3.fragment;
35052
+ target.fragment = relative4.fragment;
34210
35053
  return target;
34211
35054
  }
34212
35055
  function equal(uriA, uriB, options) {
@@ -34214,7 +35057,7 @@ var require_fast_uri = __commonJS({
34214
35057
  const normalizedB = normalizeComparableURI(uriB, options);
34215
35058
  return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB;
34216
35059
  }
34217
- function serialize(cmpts, opts) {
35060
+ function serialize2(cmpts, opts) {
34218
35061
  const component = {
34219
35062
  host: cmpts.host,
34220
35063
  scheme: cmpts.scheme,
@@ -34477,7 +35320,7 @@ var require_fast_uri = __commonJS({
34477
35320
  }
34478
35321
  return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
34479
35322
  }
34480
- function parse3(uri, opts) {
35323
+ function parse4(uri, opts) {
34481
35324
  return parseWithStatus(uri, opts).parsed;
34482
35325
  }
34483
35326
  function normalizeString(uri, opts) {
@@ -34486,7 +35329,7 @@ var require_fast_uri = __commonJS({
34486
35329
  function normalizeStringWithStatus(uri, opts) {
34487
35330
  const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
34488
35331
  return {
34489
- normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
35332
+ normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize2(parsed, opts),
34490
35333
  malformedAuthorityOrPort,
34491
35334
  malformedPercentEncoding,
34492
35335
  malformedSchemeSpecific,
@@ -34500,7 +35343,7 @@ var require_fast_uri = __commonJS({
34500
35343
  }
34501
35344
  let value;
34502
35345
  try {
34503
- value = typeof uri === "string" ? uri : serialize(uri, opts);
35346
+ value = typeof uri === "string" ? uri : serialize2(uri, opts);
34504
35347
  } catch {
34505
35348
  return void 0;
34506
35349
  }
@@ -34513,8 +35356,8 @@ var require_fast_uri = __commonJS({
34513
35356
  resolve: resolve5,
34514
35357
  resolveComponent,
34515
35358
  equal,
34516
- serialize,
34517
- parse: parse3
35359
+ serialize: serialize2,
35360
+ parse: parse4
34518
35361
  };
34519
35362
  module2.exports = fastUri;
34520
35363
  module2.exports.default = fastUri;
@@ -39410,284 +40253,50 @@ container holding the app. Specify either width or maxWidth, and either height o
39410
40253
  });
39411
40254
 
39412
40255
  // packages/cli/dist/mcp-files.js
39413
- function targetStateFile() {
39414
- const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
39415
- return (0, import_node_path3.join)(base, "antigravity-target.json");
39416
- }
39417
- function insideOrEqual(root, target) {
39418
- if (root === target)
39419
- return true;
39420
- const rel = (0, import_node_path3.relative)(root, target);
39421
- return Boolean(rel && !(0, import_node_path3.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path3.sep));
39422
- }
39423
- function hasHiddenSegment(root, target) {
39424
- const rel = (0, import_node_path3.relative)(root, target);
39425
- if (!rel || rel === ".")
39426
- return false;
39427
- return rel.split(import_node_path3.sep).some((part) => part.startsWith("."));
39428
- }
39429
- async function hasSymlinkUnderRoot(realRoot, rawTarget) {
39430
- let cur = rawTarget;
39431
- while (cur && cur !== (0, import_node_path3.dirname)(cur)) {
39432
- const st = await (0, import_promises3.lstat)(cur);
39433
- if (st.isSymbolicLink())
39434
- return true;
39435
- const realCur = await (0, import_promises3.realpath)(cur);
39436
- if (realCur === realRoot)
39437
- return false;
39438
- cur = (0, import_node_path3.dirname)(cur);
39439
- }
39440
- return false;
39441
- }
39442
- function uriToPath(uri) {
39443
- if (typeof uri !== "string" || !uri.trim())
39444
- return null;
39445
- const trimmed = uri.trim();
39446
- try {
39447
- if (trimmed.startsWith("file://"))
39448
- return (0, import_node_url.fileURLToPath)(trimmed);
39449
- if ((0, import_node_path3.isAbsolute)(trimmed))
39450
- return trimmed;
39451
- } catch {
39452
- }
39453
- return null;
39454
- }
39455
- async function findGitRoot(filePath) {
39456
- let cur = (0, import_node_path3.dirname)(filePath);
39457
- const home = await (0, import_promises3.realpath)((0, import_node_os3.homedir)()).catch(() => (0, import_node_os3.homedir)());
39458
- while (cur && cur !== (0, import_node_path3.dirname)(cur) && cur !== home) {
39459
- try {
39460
- await (0, import_promises3.lstat)((0, import_node_path3.join)(cur, ".git"));
39461
- return cur;
39462
- } catch {
39463
- }
39464
- cur = (0, import_node_path3.dirname)(cur);
39465
- }
39466
- return (0, import_node_path3.dirname)(filePath);
40256
+ function nextTargetSeq() {
40257
+ lastTargetSeq = Math.max(Date.now(), lastTargetSeq + 1);
40258
+ return lastTargetSeq;
39467
40259
  }
39468
40260
  async function writeTargetSelection(filePath, workspaceDir, extra) {
39469
- const real = await (0, import_promises3.realpath)(filePath);
39470
- const info = await (0, import_promises3.lstat)(real);
39471
- if (!info.isFile() || info.size > MAX_BYTES || !/\.md$/i.test(real)) {
39472
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
40261
+ const real = await (0, import_promises4.realpath)(filePath);
40262
+ const info = await (0, import_promises4.lstat)(real);
40263
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES || !/\.md$/i.test(real)) {
40264
+ throw new Error(say("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file up to 5 MiB."));
39473
40265
  }
39474
- const workspace = workspaceDir ? await (0, import_promises3.realpath)(workspaceDir).catch(() => findGitRoot(real)) : await findGitRoot(real);
40266
+ const workspace = workspaceDir ? await (0, import_promises4.realpath)(workspaceDir).catch(() => findProjectRoot(real)) : await findProjectRoot(real);
39475
40267
  const statePath = targetStateFile();
39476
- await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(statePath), { recursive: true, mode: 448 });
40268
+ await (0, import_promises4.mkdir)((0, import_node_path4.dirname)(statePath), { recursive: true, mode: 448 });
40269
+ const seq = nextTargetSeq();
39477
40270
  const payload = {
39478
40271
  file: real,
39479
40272
  workspace,
39480
- seq: Date.now(),
40273
+ seq,
39481
40274
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
39482
40275
  ...extra?.openInEditorPane && { openInEditorPane: true },
39483
- ...extra?.editorUrl && { editorUrl: extra.editorUrl }
40276
+ ...extra?.editorUrl && { editorUrl: extra.editorUrl },
40277
+ ...extra?.editorOnly && { editorOnly: true }
39484
40278
  };
39485
- const tmp = `${statePath}.${process.pid}.${Date.now()}`;
40279
+ const tmp = `${statePath}.${process.pid}.${seq}`;
39486
40280
  try {
39487
- await (0, import_promises3.writeFile)(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
39488
- await (0, import_promises3.rename)(tmp, statePath);
40281
+ await (0, import_promises4.writeFile)(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
40282
+ await (0, import_promises4.rename)(tmp, statePath);
39489
40283
  } catch (err) {
39490
- await (0, import_promises3.rm)(tmp, { force: true }).catch(() => {
40284
+ await (0, import_promises4.rm)(tmp, { force: true }).catch(() => {
39491
40285
  });
39492
40286
  throw err;
39493
40287
  }
39494
40288
  return payload;
39495
40289
  }
39496
- async function readTargetSelection() {
39497
- try {
39498
- const raw = JSON.parse(await (0, import_promises3.readFile)(targetStateFile(), "utf8"));
39499
- if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
39500
- return null;
39501
- const info = await (0, import_promises3.lstat)(raw.file);
39502
- if (!info.isFile() || info.size > MAX_BYTES)
39503
- return null;
39504
- const file2 = await (0, import_promises3.realpath)(raw.file);
39505
- if (file2 !== raw.file)
39506
- return null;
39507
- const workspace = typeof raw.workspace === "string" ? await (0, import_promises3.realpath)(raw.workspace).catch(() => (0, import_node_path3.dirname)(file2)) : (0, import_node_path3.dirname)(file2);
39508
- if (!insideOrEqual(workspace, file2))
39509
- return null;
39510
- return { file: file2, workspace, seq: Number(raw.seq) || 0 };
39511
- } catch {
39512
- return null;
39513
- }
39514
- }
39515
- async function discoverAntigravityProjects() {
39516
- const projectsDir = (0, import_node_path3.join)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".gemini", "config"), "projects");
39517
- const roots = [];
39518
- let entries = [];
39519
- try {
39520
- entries = await (0, import_promises3.readdir)(projectsDir);
39521
- } catch {
39522
- return roots;
39523
- }
39524
- for (const name of entries) {
39525
- if (!name.endsWith(".json"))
39526
- continue;
39527
- try {
39528
- const data = JSON.parse(await (0, import_promises3.readFile)((0, import_node_path3.join)(projectsDir, name), "utf8"));
39529
- const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
39530
- for (const r2 of resources) {
39531
- const uri = r2?.gitFolder?.folderUri || r2?.folderUri;
39532
- const p2 = uriToPath(uri);
39533
- if (!p2)
39534
- continue;
39535
- const real = await (0, import_promises3.realpath)(p2).catch(() => null);
39536
- if (real)
39537
- roots.push({ path: real, name: String(data.name || (0, import_node_path3.basename)(real)) });
39538
- }
39539
- } catch {
39540
- }
39541
- }
39542
- return roots;
39543
- }
39544
- async function scanMarkdownFiles(rootDir) {
39545
- const found = [];
39546
- async function walk(dir, depth) {
39547
- if (depth > MAX_SCAN_DEPTH || found.length >= MAX_FILES)
39548
- return;
39549
- let entries;
39550
- try {
39551
- entries = await (0, import_promises3.readdir)(dir, { withFileTypes: true });
39552
- } catch {
39553
- return;
39554
- }
39555
- for (const entry of entries) {
39556
- if (found.length >= MAX_FILES)
39557
- break;
39558
- if (entry.name.startsWith("."))
39559
- continue;
39560
- const full = (0, import_node_path3.join)(dir, entry.name);
39561
- if (entry.isDirectory()) {
39562
- if (!SKIP_DIRS.has(entry.name))
39563
- await walk(full, depth + 1);
39564
- } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
39565
- try {
39566
- const info = await (0, import_promises3.lstat)(full);
39567
- if (info.isFile() && info.size <= MAX_BYTES) {
39568
- const real = await (0, import_promises3.realpath)(full);
39569
- if (real === full && insideOrEqual(rootDir, real)) {
39570
- found.push({ path: real, mtimeMs: info.mtimeMs });
39571
- }
39572
- }
39573
- } catch {
39574
- }
39575
- }
39576
- }
39577
- }
39578
- await walk(rootDir, 0);
39579
- found.sort((a, b) => {
39580
- const aMarkmap = /\.markmap\.md$/i.test(a.path) ? 0 : 1;
39581
- const bMarkmap = /\.markmap\.md$/i.test(b.path) ? 0 : 1;
39582
- if (aMarkmap !== bMarkmap)
39583
- return aMarkmap - bMarkmap;
39584
- if (Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
39585
- return b.mtimeMs - a.mtimeMs;
39586
- return a.path.localeCompare(b.path);
39587
- });
39588
- return found;
39589
- }
39590
40290
  function createMcpWorkspaceManager() {
39591
40291
  let activeFile = null;
39592
40292
  let internalSeq = 0;
39593
- const sessionWorkspaces = /* @__PURE__ */ new Map();
40293
+ const serialized = createSerialQueue();
40294
+ const access = createWorkspaceAccess();
39594
40295
  async function allowedRoots(extraWorkspaceUris = []) {
39595
- const roots = /* @__PURE__ */ new Map();
39596
- const home = await (0, import_promises3.realpath)((0, import_node_os3.homedir)()).catch(() => (0, import_node_os3.homedir)());
39597
- const configDir = await (0, import_promises3.realpath)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path3.join)(home, ".gemini", "config")).catch(() => "");
39598
- const addRoot = async (rawPath, active, label) => {
39599
- if (!rawPath)
39600
- return;
39601
- const real = await (0, import_promises3.realpath)(rawPath).catch(() => null);
39602
- if (!real || real === import_node_path3.sep || real === home)
39603
- return;
39604
- if (configDir && insideOrEqual(configDir, real))
39605
- return;
39606
- if (!roots.has(real)) {
39607
- roots.set(real, { path: real, name: label || (0, import_node_path3.basename)(real), active });
39608
- } else if (active) {
39609
- roots.get(real).active = true;
39610
- }
39611
- };
39612
- const envRoots = (process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter).filter(Boolean);
39613
- for (const r2 of envRoots) {
39614
- await addRoot(uriToPath(r2) || (0, import_node_path3.resolve)(r2), true);
39615
- }
39616
- for (const uri of extraWorkspaceUris) {
39617
- await addRoot(uriToPath(uri) || (0, import_node_path3.resolve)(uri), true);
39618
- }
39619
- for (const [p2, name] of sessionWorkspaces) {
39620
- await addRoot(p2, true, name);
39621
- }
39622
- const target = await readTargetSelection();
39623
- if (target) {
39624
- await addRoot(target.workspace, roots.size === 0);
39625
- }
39626
- for (const proj of await discoverAntigravityProjects()) {
39627
- await addRoot(proj.path, false, proj.name);
39628
- }
39629
- if (roots.size === 0) {
39630
- await addRoot(process.cwd(), true);
39631
- }
39632
- const effectiveSeq = Math.max(internalSeq, target?.seq || 0);
39633
- return { roots: [...roots.values()], target, effectiveSeq };
39634
- }
39635
- async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], allowRegisterFromModel = false) {
39636
- if (!candidatePath?.trim())
39637
- throw new Error("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002");
39638
- const { roots, target } = await allowedRoots(extraWorkspaceUris);
39639
- const trimmed = candidatePath.trim();
39640
- let raw = uriToPath(trimmed);
39641
- if (!raw) {
39642
- if ((0, import_node_path3.isAbsolute)(trimmed)) {
39643
- raw = (0, import_node_path3.resolve)(trimmed);
39644
- } else {
39645
- const baseRoot = roots.find((r2) => r2.active)?.path || roots[0]?.path || process.cwd();
39646
- raw = (0, import_node_path3.resolve)(baseRoot, trimmed);
39647
- }
39648
- }
39649
- if (!/\.md$/i.test(raw))
39650
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
39651
- const info = await (0, import_promises3.lstat)(raw);
39652
- if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_BYTES) {
39653
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002");
39654
- }
39655
- const real = await (0, import_promises3.realpath)(raw);
39656
- if (!/\.md$/i.test(real)) {
39657
- throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u6216\u975E Markdown \u6587\u4EF6\u3002");
39658
- }
39659
- const home = await (0, import_promises3.realpath)((0, import_node_os3.homedir)()).catch(() => (0, import_node_os3.homedir)());
39660
- if (insideOrEqual(home, real) && hasHiddenSegment(home, real)) {
39661
- throw new Error("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u914D\u7F6E\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
39662
- }
39663
- const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, real));
39664
- const permitted = target && target.file === real || Boolean(matchedRoot);
39665
- if (!permitted) {
39666
- if (!allowRegisterFromModel) {
39667
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u6216\u9879\u76EE\u76EE\u5F55\u5185\u3002");
39668
- }
39669
- const ws = await findGitRoot(real);
39670
- if (await hasSymlinkUnderRoot(ws, raw)) {
39671
- throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
39672
- }
39673
- if (hasHiddenSegment(ws, real)) {
39674
- throw new Error("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
39675
- }
39676
- sessionWorkspaces.set(ws, (0, import_node_path3.basename)(ws));
39677
- const savedTarget = await writeTargetSelection(real, ws);
39678
- internalSeq = Math.max(internalSeq, savedTarget.seq);
39679
- return real;
39680
- }
39681
- if (matchedRoot) {
39682
- if (await hasSymlinkUnderRoot(matchedRoot.path, raw)) {
39683
- throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
39684
- }
39685
- if (hasHiddenSegment(matchedRoot.path, real)) {
39686
- throw new Error("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
39687
- }
39688
- }
39689
- return real;
40296
+ const { roots, target } = await access.allowedRoots(extraWorkspaceUris);
40297
+ return { roots, target, effectiveSeq: Math.max(internalSeq, target?.seq || 0) };
39690
40298
  }
40299
+ const assertAllowedFile = access.assertAllowedFile;
39691
40300
  async function readDocState(filePath) {
39692
40301
  const source = await fileSource(filePath);
39693
40302
  const [md, viewState] = await Promise.all([source.read(), source.readView?.()]);
@@ -39706,25 +40315,25 @@ function createMcpWorkspaceManager() {
39706
40315
  const seen = /* @__PURE__ */ new Set();
39707
40316
  if (target && !seen.has(target.file)) {
39708
40317
  const owner = roots.find((r2) => insideOrEqual(r2.path, target.file));
39709
- const rel = owner ? (0, import_node_path3.relative)(owner.path, target.file) : (0, import_node_path3.basename)(target.file);
40318
+ const rel = owner ? (0, import_node_path4.relative)(owner.path, target.file) : (0, import_node_path4.basename)(target.file);
39710
40319
  items.push({
39711
40320
  path: target.file,
39712
- uri: (0, import_node_url.pathToFileURL)(target.file).href,
40321
+ uri: (0, import_node_url2.pathToFileURL)(target.file).href,
39713
40322
  label: owner && roots.length > 1 ? `${owner.name} / ${rel}` : rel,
39714
40323
  group: owner?.active ? "active" : "project"
39715
40324
  });
39716
40325
  seen.add(target.file);
39717
40326
  }
39718
40327
  for (const root of roots) {
39719
- const files = await scanMarkdownFiles(root.path);
40328
+ const files = await scanMarkdownFiles(root.path, { byRecent: true });
39720
40329
  for (const entry of files) {
39721
40330
  if (seen.has(entry.path))
39722
40331
  continue;
39723
40332
  seen.add(entry.path);
39724
- const rel = (0, import_node_path3.relative)(root.path, entry.path);
40333
+ const rel = (0, import_node_path4.relative)(root.path, entry.path);
39725
40334
  items.push({
39726
40335
  path: entry.path,
39727
- uri: (0, import_node_url.pathToFileURL)(entry.path).href,
40336
+ uri: (0, import_node_url2.pathToFileURL)(entry.path).href,
39728
40337
  label: roots.length > 1 ? `${root.name} / ${rel}` : rel,
39729
40338
  group: root.active ? "active" : "project"
39730
40339
  });
@@ -39733,7 +40342,7 @@ function createMcpWorkspaceManager() {
39733
40342
  return { files: items, target, targetSeq: effectiveSeq };
39734
40343
  }
39735
40344
  return {
39736
- async open(options = {}) {
40345
+ open: (options = {}) => serialized(async () => {
39737
40346
  const extraUris = options.workspace ? [options.workspace] : [];
39738
40347
  let explicitFile = null;
39739
40348
  if (options.path?.trim()) {
@@ -39744,10 +40353,11 @@ function createMcpWorkspaceManager() {
39744
40353
  });
39745
40354
  internalSeq = Math.max(internalSeq, saved.seq);
39746
40355
  } else {
39747
- internalSeq = Math.max(internalSeq + 1, Date.now());
40356
+ internalSeq = Math.max(internalSeq + 1, nextTargetSeq());
39748
40357
  }
39749
40358
  }
39750
40359
  const { files, target, targetSeq } = await collectFiles(extraUris);
40360
+ let finalTargetSeq = targetSeq;
39751
40361
  let chosen = explicitFile;
39752
40362
  if (!chosen && target?.file)
39753
40363
  chosen = target.file;
@@ -39760,16 +40370,17 @@ function createMcpWorkspaceManager() {
39760
40370
  if (chosen && !explicitFile && options.fromModel && options.openInEditorPane) {
39761
40371
  const saved = await writeTargetSelection(chosen, options.workspace, { openInEditorPane: true });
39762
40372
  internalSeq = Math.max(internalSeq, saved.seq);
40373
+ finalTargetSeq = Math.max(finalTargetSeq, saved.seq);
39763
40374
  }
39764
40375
  if (!chosen) {
39765
40376
  return {
39766
40377
  files,
39767
40378
  currentFile: null,
39768
40379
  currentFileUri: null,
39769
- targetSeq,
40380
+ targetSeq: finalTargetSeq,
39770
40381
  doc: {
39771
40382
  name: "Inkmap",
39772
- md: "# Inkmap\n\n- \u8BF7\u5728\u5F53\u524D\u5DE5\u4F5C\u533A\u4E2D\u6DFB\u52A0\u6216\u9009\u62E9\u4E00\u4EFD `.md` / `.markmap.md` \u6587\u4EF6\n- \u6216\u5728\u5BF9\u8BDD\u4E2D\u8BA9 AI \u7528 Inkmap \u6253\u5F00\u6307\u5B9A\u6587\u6863\n",
40383
+ md: say("# Inkmap\n\n- \u8BF7\u5728\u5F53\u524D\u5DE5\u4F5C\u533A\u4E2D\u6DFB\u52A0\u6216\u9009\u62E9\u4E00\u4EFD `.md` / `.markmap.md` \u6587\u4EF6\n- \u6216\u5728\u5BF9\u8BDD\u4E2D\u8BA9 AI \u7528 Inkmap \u6253\u5F00\u6307\u5B9A\u6587\u6863\n", "# Inkmap\n\n- Add or pick a `.md` / `.markmap.md` file in this workspace\n- Or ask the AI to open a document with Inkmap\n"),
39773
40384
  version: "empty",
39774
40385
  writable: false
39775
40386
  }
@@ -39780,17 +40391,17 @@ function createMcpWorkspaceManager() {
39780
40391
  return {
39781
40392
  files,
39782
40393
  currentFile: chosen,
39783
- currentFileUri: (0, import_node_url.pathToFileURL)(chosen).href,
39784
- targetSeq,
40394
+ currentFileUri: (0, import_node_url2.pathToFileURL)(chosen).href,
40395
+ targetSeq: finalTargetSeq,
39785
40396
  doc
39786
40397
  };
39787
- },
39788
- async poll(options = {}) {
40398
+ }),
40399
+ poll: (options = {}) => serialized(async () => {
39789
40400
  const target = await readTargetSelection();
39790
40401
  const effectiveSeq = Math.max(internalSeq, target?.seq || 0);
39791
40402
  const clientSeq = Number(options.targetSeq) || 0;
39792
- const desiredFile = target && target.seq >= internalSeq ? target.file : activeFile;
39793
- if (desiredFile && effectiveSeq > clientSeq && desiredFile !== options.file) {
40403
+ const desiredFile = target && target.seq > clientSeq && !target.editorOnly ? target.file : null;
40404
+ if (desiredFile && desiredFile !== options.file) {
39794
40405
  activeFile = desiredFile;
39795
40406
  const [{ doc }, { files }] = await Promise.all([
39796
40407
  readDocState(desiredFile),
@@ -39798,7 +40409,7 @@ function createMcpWorkspaceManager() {
39798
40409
  ]);
39799
40410
  return {
39800
40411
  switchedFile: desiredFile,
39801
- currentFileUri: (0, import_node_url.pathToFileURL)(desiredFile).href,
40412
+ currentFileUri: (0, import_node_url2.pathToFileURL)(desiredFile).href,
39802
40413
  files,
39803
40414
  targetSeq: effectiveSeq,
39804
40415
  doc
@@ -39817,14 +40428,14 @@ function createMcpWorkspaceManager() {
39817
40428
  } catch {
39818
40429
  return { unchanged: true, targetSeq: effectiveSeq };
39819
40430
  }
39820
- },
39821
- async save(options) {
40431
+ }),
40432
+ save: (options) => serialized(async () => {
39822
40433
  const target = options.file || activeFile;
39823
40434
  if (!target)
39824
- throw new Error("\u672A\u9009\u62E9\u8981\u4FDD\u5B58\u7684 Markdown \u6587\u4EF6\u3002");
40435
+ throw new Error(say("\u672A\u9009\u62E9\u8981\u4FDD\u5B58\u7684 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected to save."));
39825
40436
  const file2 = await assertAllowedFile(target);
39826
- if (typeof options.md !== "string" || Buffer.byteLength(options.md, "utf8") > MAX_BYTES) {
39827
- throw new Error("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002");
40437
+ if (typeof options.md !== "string" || Buffer.byteLength(options.md, "utf8") > MAX_MARKDOWN_BYTES) {
40438
+ throw new Error(say("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002", "The Markdown is invalid or larger than 5 MiB."));
39828
40439
  }
39829
40440
  const { source, doc } = await readDocState(file2);
39830
40441
  if (options.baseVersion && options.baseVersion !== doc.version) {
@@ -39835,8 +40446,8 @@ function createMcpWorkspaceManager() {
39835
40446
  }
39836
40447
  activeFile = file2;
39837
40448
  return { ok: true, version: sha1(options.md) };
39838
- },
39839
- async saveView(options) {
40449
+ }),
40450
+ saveView: (options) => serialized(async () => {
39840
40451
  const target = options.file || activeFile;
39841
40452
  if (!target)
39842
40453
  return { ok: false };
@@ -39850,46 +40461,22 @@ function createMcpWorkspaceManager() {
39850
40461
  });
39851
40462
  }
39852
40463
  return { ok: true };
39853
- }
40464
+ })
39854
40465
  };
39855
40466
  }
39856
- var import_node_crypto3, import_promises3, import_node_os3, import_node_path3, import_node_url, MAX_BYTES, MAX_SCAN_DEPTH, MAX_FILES, SKIP_DIRS, sha1;
40467
+ var import_node_crypto3, import_promises4, import_node_path4, import_node_url2, sha1, lastTargetSeq;
39857
40468
  var init_mcp_files = __esm({
39858
40469
  "packages/cli/dist/mcp-files.js"() {
39859
40470
  "use strict";
39860
40471
  import_node_crypto3 = require("node:crypto");
39861
- import_promises3 = require("node:fs/promises");
39862
- import_node_os3 = require("node:os");
39863
- import_node_path3 = require("node:path");
39864
- import_node_url = require("node:url");
40472
+ import_promises4 = require("node:fs/promises");
40473
+ import_node_path4 = require("node:path");
40474
+ import_node_url2 = require("node:url");
39865
40475
  init_dist();
39866
40476
  init_server();
39867
- MAX_BYTES = 5 * 1024 * 1024;
39868
- MAX_SCAN_DEPTH = 4;
39869
- MAX_FILES = 200;
39870
- SKIP_DIRS = /* @__PURE__ */ new Set([
39871
- ".git",
39872
- ".hg",
39873
- ".svn",
39874
- "node_modules",
39875
- "dist",
39876
- "dist-codex",
39877
- "dist-workbuddy",
39878
- "build",
39879
- "out",
39880
- ".next",
39881
- ".nuxt",
39882
- ".agents",
39883
- ".agent",
39884
- ".gemini",
39885
- ".codex",
39886
- ".venv",
39887
- "venv",
39888
- "target",
39889
- "coverage",
39890
- ".tmp"
39891
- ]);
40477
+ init_workspace_fs();
39892
40478
  sha1 = (text) => (0, import_node_crypto3.createHash)("sha1").update(text).digest("hex");
40479
+ lastTargetSeq = 0;
39893
40480
  }
39894
40481
  });
39895
40482
 
@@ -39899,31 +40486,50 @@ __export(codex_exports, {
39899
40486
  createInkmapMcpServer: () => createInkmapMcpServer,
39900
40487
  serveCodex: () => serveCodex
39901
40488
  });
40489
+ function resolveWebRoot() {
40490
+ return WEB_ROOT_CANDIDATES.find((dir) => (0, import_node_fs2.existsSync)((0, import_node_path5.join)(dir, "index.html"))) ?? null;
40491
+ }
39902
40492
  function openSystemBrowser(url2) {
39903
40493
  if (process.env.INKMAP_NO_OPEN === "1")
39904
40494
  return;
39905
40495
  const [cmd, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url2]] : ["xdg-open", [url2]];
39906
- (0, import_node_child_process2.spawn)(cmd, args, { stdio: "ignore", detached: true }).unref();
40496
+ const child = (0, import_node_child_process3.spawn)(cmd, args, { stdio: "ignore", detached: true });
40497
+ child.on("error", () => {
40498
+ });
40499
+ child.unref();
40500
+ }
40501
+ async function validatedMarkdownFile(path) {
40502
+ if (!path || !/\.md$/i.test(path))
40503
+ throw new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
40504
+ const info = await (0, import_promises5.lstat)(path);
40505
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
40506
+ 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."));
40507
+ }
40508
+ const real = await (0, import_promises5.realpath)(path);
40509
+ const home = await (0, import_promises5.realpath)((0, import_node_os4.homedir)()).catch(() => (0, import_node_os4.homedir)());
40510
+ if (!/\.md$/i.test(real) || insideOrEqual(home, real) && hasHiddenSegment(home, real)) {
40511
+ throw new Error(say("\u4E0D\u652F\u6301\u8BBF\u95EE\u8BE5\u6587\u4EF6\u3002", "This file cannot be opened."));
40512
+ }
40513
+ return real;
39907
40514
  }
39908
40515
  async function createInkmapMcpServer(options = {}) {
39909
40516
  const loadHtml = async () => {
39910
- const raw = options.html ?? await (0, import_promises4.readFile)(HTML, "utf8").catch((error62) => {
40517
+ const raw = options.html ?? await (0, import_promises5.readFile)(HTML, "utf8").catch((error62) => {
39911
40518
  if (error62.code === "ENOENT") {
39912
40519
  throw new Error("MCP App editor assets are missing. Run npm run build:sidebars.");
39913
40520
  }
39914
40521
  throw error62;
39915
40522
  });
39916
40523
  const osLoc = detectOsLocale();
39917
- return raw.replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
40524
+ return raw.replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
39918
40525
  };
39919
40526
  await loadHtml();
39920
40527
  const billingOrigin2 = options.billingOrigin ?? (() => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN);
39921
40528
  const billing = licenseService(fileSessionStorage(), billingOrigin2, { loginOnly: true });
39922
40529
  let browserBilling;
39923
40530
  const fallbackEditors = /* @__PURE__ */ new Map();
39924
- const ads = adFeed(PRODUCT.adFeedUrl);
39925
40531
  const workspaces = createMcpWorkspaceManager();
39926
- const server = new McpServer({ name: "inkmap", version: "0.3.8" });
40532
+ const server = new McpServer({ name: "inkmap", version: INKMAP_VERSION });
39927
40533
  function isAntigravityHost() {
39928
40534
  const clientName = server.server.getClientVersion()?.name ?? "";
39929
40535
  if (/antigravity/i.test(clientName))
@@ -39946,15 +40552,24 @@ async function createInkmapMcpServer(options = {}) {
39946
40552
  return "codex";
39947
40553
  if (clientName.includes("windsurf"))
39948
40554
  return "windsurf";
40555
+ if (clientName.includes("trae"))
40556
+ return "trae";
40557
+ if (clientName.includes("qoder"))
40558
+ return "qoder";
40559
+ if (clientName.includes("deepseek") || clientName.includes("dsh"))
40560
+ return "deepseek";
39949
40561
  return "mcp";
39950
40562
  }
40563
+ server.server.oninitialized = () => {
40564
+ billing.track?.("plugin_activate", 1, detectMcpHost());
40565
+ };
39951
40566
  function hasIdeEditorExtension() {
39952
40567
  const clientName = server.server.getClientVersion()?.name ?? "";
39953
40568
  let extDir = null;
39954
40569
  if (/cursor/i.test(clientName)) {
39955
- extDir = (0, import_node_path4.join)(process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".cursor"), "extensions");
40570
+ extDir = (0, import_node_path5.join)(process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".cursor"), "extensions");
39956
40571
  } else if (/visual studio code|vscode/i.test(clientName)) {
39957
- extDir = (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".vscode", "extensions");
40572
+ extDir = (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".vscode", "extensions");
39958
40573
  }
39959
40574
  if (!extDir || !(0, import_node_fs2.existsSync)(extDir))
39960
40575
  return false;
@@ -39974,12 +40589,12 @@ async function createInkmapMcpServer(options = {}) {
39974
40589
  async function waitForEditorBridgeAck(seq, timeoutMs = 280) {
39975
40590
  if (!seq)
39976
40591
  return false;
39977
- const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".inkmap");
39978
- const ackPath = (0, import_node_path4.join)(inkmapDir, "antigravity-target-ack.json");
40592
+ const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".inkmap");
40593
+ const ackPath = (0, import_node_path5.join)(inkmapDir, "antigravity-target-ack.json");
39979
40594
  const deadline = Date.now() + timeoutMs;
39980
40595
  while (Date.now() < deadline) {
39981
40596
  try {
39982
- const raw = JSON.parse(await (0, import_promises4.readFile)(ackPath, "utf8"));
40597
+ const raw = JSON.parse(await (0, import_promises5.readFile)(ackPath, "utf8"));
39983
40598
  if (raw && raw.ok === true && Number(raw.seq) >= seq) {
39984
40599
  return true;
39985
40600
  }
@@ -39990,7 +40605,8 @@ async function createInkmapMcpServer(options = {}) {
39990
40605
  return false;
39991
40606
  }
39992
40607
  async function openFallbackBrowserEditor(filePath, launchSystemBrowser = true) {
39993
- if (!(0, import_node_fs2.existsSync)(WEB_ROOT))
40608
+ const webRoot = resolveWebRoot();
40609
+ if (!webRoot)
39994
40610
  return void 0;
39995
40611
  let pending = fallbackEditors.get("__workspace__");
39996
40612
  if (!pending) {
@@ -39999,20 +40615,18 @@ async function createInkmapMcpServer(options = {}) {
39999
40615
  browserBilling ??= licenseService(fileSessionStorage(), billingOrigin2);
40000
40616
  return serve({
40001
40617
  source,
40002
- webRoot: WEB_ROOT,
40618
+ webRoot,
40003
40619
  port: 0,
40004
40620
  license: browserBilling,
40005
- ads,
40006
40621
  sidebar: false,
40007
- loginOnly: false,
40008
- ideWorkspace: true
40622
+ ideWorkspace: false
40009
40623
  });
40010
40624
  })();
40011
40625
  fallbackEditors.set("__workspace__", pending);
40012
40626
  pending.catch(() => fallbackEditors.delete("__workspace__"));
40013
40627
  }
40014
40628
  const served = await pending;
40015
- await served.switchToFile?.(filePath).catch(() => {
40629
+ await served.switchToFile?.(filePath, { trustCaller: true }).catch(() => {
40016
40630
  });
40017
40631
  if (launchSystemBrowser) {
40018
40632
  openSystemBrowser(served.url);
@@ -40086,7 +40700,7 @@ async function createInkmapMcpServer(options = {}) {
40086
40700
  currentFileUri: opened.currentFileUri,
40087
40701
  targetSeq: opened.targetSeq,
40088
40702
  license: { ...license },
40089
- ...openInRightEditor && { openedInEditorPane: true },
40703
+ ...(ackedByExtension || cursorHost) && { openedInEditorPane: true },
40090
40704
  ...ackedByExtension && { ackedByExtension: true },
40091
40705
  ...editorUrl && { editorUrl },
40092
40706
  ...includeDoc && { doc: opened.doc }
@@ -40143,7 +40757,7 @@ async function createInkmapMcpServer(options = {}) {
40143
40757
  _meta: appOnly
40144
40758
  }, async ({ file: file2, md, baseVersion }) => {
40145
40759
  if (!hasAccess(await billing.state())) {
40146
- throw new Error("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro \u6743\u76CA\u3002");
40760
+ throw new Error(say("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro \u6743\u76CA\u3002", "The Inkmap trial has ended. Sign in with the account that bought Pro to restore it."));
40147
40761
  }
40148
40762
  const saved = await workspaces.save({ file: file2, md, baseVersion });
40149
40763
  if (saved.ok)
@@ -40170,10 +40784,15 @@ async function createInkmapMcpServer(options = {}) {
40170
40784
  annotations: { readOnlyHint: true },
40171
40785
  _meta: appOnly
40172
40786
  }, async ({ file: file2 }) => {
40173
- const opened = await workspaces.open({ path: file2, fromModel: false });
40174
- if (!opened.currentFile)
40175
- throw new Error("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002");
40176
- const url2 = await openFallbackBrowserEditor(opened.currentFile);
40787
+ if (!hasAccess(await billing.state())) {
40788
+ throw new Error(say("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro \u6743\u76CA\u3002", "The Inkmap trial has ended. Sign in with the account that bought Pro to restore it."));
40789
+ }
40790
+ const hostFile = file2?.startsWith("file://") ? await validatedMarkdownFile(uriToPath(file2)) : null;
40791
+ const target = hostFile ?? (await workspaces.open({ path: file2, fromModel: false })).currentFile;
40792
+ if (!target)
40793
+ throw new Error(say("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected."));
40794
+ billing.track?.("feature_browser", 1, detectMcpHost());
40795
+ const url2 = await openFallbackBrowserEditor(target);
40177
40796
  return { content: [], structuredContent: { url: url2 ?? "" } };
40178
40797
  });
40179
40798
  server.registerTool("inkmap_focus_editor", {
@@ -40186,10 +40805,12 @@ async function createInkmapMcpServer(options = {}) {
40186
40805
  }, async ({ file: file2 }) => {
40187
40806
  const opened = await workspaces.open({ path: file2, fromModel: false });
40188
40807
  if (!opened.currentFile)
40189
- throw new Error("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002");
40808
+ throw new Error(say("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected."));
40190
40809
  const url2 = await openFallbackBrowserEditor(opened.currentFile, false);
40191
40810
  const payload = await writeTargetSelection(opened.currentFile, void 0, {
40192
40811
  openInEditorPane: true,
40812
+ // Asked for by one panel's UI: the IDE focuses the file, other open panels stay on their documents.
40813
+ editorOnly: true,
40193
40814
  ...url2 && { editorUrl: url2 }
40194
40815
  });
40195
40816
  const acked = await waitForEditorBridgeAck(payload.seq, 450);
@@ -40217,10 +40838,10 @@ async function createInkmapMcpServer(options = {}) {
40217
40838
  }, async ({ phone, locale }) => ({ content: [], structuredContent: { result: await billing.sendPhoneCode(phone, locale) } }));
40218
40839
  server.registerTool("inkmap_phone_verify", {
40219
40840
  title: "Verify phone sign-in code",
40220
- inputSchema: { phone: external_exports.string(), code: external_exports.string() },
40841
+ inputSchema: { phone: external_exports.string(), code: external_exports.string(), locale: external_exports.string().optional() },
40221
40842
  annotations: { destructiveHint: false },
40222
40843
  _meta: appOnly
40223
- }, async ({ phone, code }) => ({ content: [], structuredContent: { result: await billing.signInByPhone(phone, code) } }));
40844
+ }, async ({ phone, code, locale }) => ({ content: [], structuredContent: { result: await billing.signInByPhone(phone, code, locale) } }));
40224
40845
  server.registerTool("inkmap_disconnect_access", {
40225
40846
  title: "Disconnect Inkmap access",
40226
40847
  annotations: { destructiveHint: true },
@@ -40239,27 +40860,33 @@ async function serveCodex() {
40239
40860
  };
40240
40861
  await server.connect(transport);
40241
40862
  }
40242
- var import_node_child_process2, import_node_fs2, import_promises4, import_node_os4, import_node_path4, import_node_url2, UI, HTML, WEB_ROOT, INLINE_DOC_LIMIT, appOnly;
40863
+ var import_node_child_process3, import_node_fs2, import_promises5, import_node_os4, import_node_path5, import_node_url3, UI, HTML, WEB_ROOT_CANDIDATES, INLINE_DOC_LIMIT, appOnly;
40243
40864
  var init_codex = __esm({
40244
40865
  "packages/cli/dist/codex.js"() {
40245
40866
  "use strict";
40246
40867
  init_mcp();
40247
40868
  init_stdio2();
40248
40869
  init_server4();
40249
- import_node_child_process2 = require("node:child_process");
40870
+ import_node_child_process3 = require("node:child_process");
40250
40871
  import_node_fs2 = require("node:fs");
40251
- import_promises4 = require("node:fs/promises");
40872
+ import_promises5 = require("node:fs/promises");
40252
40873
  import_node_os4 = require("node:os");
40253
- import_node_path4 = require("node:path");
40254
- import_node_url2 = require("node:url");
40874
+ import_node_path5 = require("node:path");
40875
+ import_node_url3 = require("node:url");
40255
40876
  init_zod();
40256
40877
  init_dist();
40257
40878
  init_license();
40258
40879
  init_mcp_files();
40880
+ init_version();
40881
+ init_workspace_fs();
40259
40882
  init_server();
40260
40883
  UI = "ui://inkmap/markdown.html";
40261
40884
  HTML = new URL("./codex.html", inkmapModuleUrl);
40262
- WEB_ROOT = (0, import_node_url2.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
40885
+ WEB_ROOT_CANDIDATES = [
40886
+ (0, import_node_url3.fileURLToPath)(new URL("./web/", inkmapModuleUrl)),
40887
+ (0, import_node_url3.fileURLToPath)(new URL("./sidecars/inkmap/web/", inkmapModuleUrl)),
40888
+ (0, import_node_url3.fileURLToPath)(new URL("../web/", inkmapModuleUrl))
40889
+ ];
40263
40890
  INLINE_DOC_LIMIT = 256 * 1024;
40264
40891
  appOnly = { ui: { visibility: ["app"] } };
40265
40892
  }
@@ -40268,9 +40895,46 @@ var init_codex = __esm({
40268
40895
  // packages/cli/dist/install.js
40269
40896
  var install_exports = {};
40270
40897
  __export(install_exports, {
40271
- runInstall: () => runInstall,
40272
40898
  runInstallCli: () => runInstallCli
40273
40899
  });
40900
+ function quoteWinArg(arg) {
40901
+ return `"${arg.replace(/"/g, '""').replace(/%/g, '"^%"')}"`;
40902
+ }
40903
+ function probeCliCommand(cmd, args = ["--version"]) {
40904
+ try {
40905
+ if (process.platform === "win32" && !cmd.toLowerCase().endsWith(".exe")) {
40906
+ const commandLine = `"${[cmd, ...args].map(quoteWinArg).join(" ")}"`;
40907
+ const res = (0, import_node_child_process4.spawnSync)("cmd.exe", ["/d", "/s", "/c", commandLine], {
40908
+ stdio: "ignore",
40909
+ windowsVerbatimArguments: true,
40910
+ windowsHide: true
40911
+ });
40912
+ return res.status === 0;
40913
+ }
40914
+ return (0, import_node_child_process4.spawnSync)(cmd, args, { stdio: "ignore" }).status === 0;
40915
+ } catch {
40916
+ return false;
40917
+ }
40918
+ }
40919
+ function execCliSync(cmd, args, options = {}) {
40920
+ if (process.platform === "win32" && !cmd.toLowerCase().endsWith(".exe")) {
40921
+ const commandLine = `"${[cmd, ...args].map(quoteWinArg).join(" ")}"`;
40922
+ const res = (0, import_node_child_process4.spawnSync)("cmd.exe", ["/d", "/s", "/c", commandLine], {
40923
+ ...options,
40924
+ encoding: options.encoding ?? "utf8",
40925
+ stdio: options.stdio ?? "pipe",
40926
+ windowsVerbatimArguments: true,
40927
+ windowsHide: true
40928
+ });
40929
+ if (res.error)
40930
+ throw res.error;
40931
+ if (res.status !== 0) {
40932
+ throw new Error(String(res.stderr || res.stdout || `${cmd} exited with code ${res.status}`).trim());
40933
+ }
40934
+ return String(res.stdout ?? "");
40935
+ }
40936
+ return (0, import_node_child_process4.execFileSync)(cmd, args, options) ?? "";
40937
+ }
40274
40938
  function crc32(buf) {
40275
40939
  let c = 4294967295;
40276
40940
  for (let i = 0; i < buf.length; i++) {
@@ -40362,47 +41026,47 @@ function isChineseTerminalLocale() {
40362
41026
  return detectOsLocale() === "zh";
40363
41027
  }
40364
41028
  function getInkmapHome() {
40365
- return process.env.INKMAP_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".inkmap");
41029
+ return process.env.INKMAP_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".inkmap");
40366
41030
  }
40367
41031
  function getClaudeDesktopDir() {
40368
41032
  if (process.env.INKMAP_CLAUDE_CONFIG_DIR)
40369
41033
  return process.env.INKMAP_CLAUDE_CONFIG_DIR;
40370
41034
  if (process.platform === "darwin") {
40371
- return (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Library", "Application Support", "Claude");
41035
+ return (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Library", "Application Support", "Claude");
40372
41036
  }
40373
41037
  if (process.platform === "win32") {
40374
- const appData = process.env.APPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Roaming");
40375
- return (0, import_node_path5.join)(appData, "Claude");
41038
+ const appData = process.env.APPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Roaming");
41039
+ return (0, import_node_path6.join)(appData, "Claude");
40376
41040
  }
40377
- const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".config");
40378
- return (0, import_node_path5.join)(xdg, "Claude");
41041
+ const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".config");
41042
+ return (0, import_node_path6.join)(xdg, "Claude");
40379
41043
  }
40380
41044
  function getCursorDir() {
40381
- return process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".cursor");
41045
+ return process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".cursor");
40382
41046
  }
40383
41047
  function getVscodeDir() {
40384
- return process.env.INKMAP_VSCODE_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".vscode");
41048
+ return process.env.INKMAP_VSCODE_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".vscode");
40385
41049
  }
40386
41050
  function getClaudeCodeConfigPath() {
40387
- return process.env.INKMAP_CLAUDE_CODE_CONFIG || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".claude.json");
41051
+ return process.env.INKMAP_CLAUDE_CODE_CONFIG || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".claude.json");
40388
41052
  }
40389
41053
  function getAntigravityConfigDir() {
40390
- return process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".gemini", "config");
41054
+ return process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".gemini", "config");
40391
41055
  }
40392
41056
  function findCursorCommand() {
40393
41057
  if (process.env.INKMAP_ISOLATED_DETECT)
40394
41058
  return null;
40395
- if ((0, import_node_child_process3.spawnSync)("cursor", ["--version"], { stdio: "ignore" }).status === 0)
41059
+ if (probeCliCommand("cursor"))
40396
41060
  return "cursor";
40397
41061
  if (process.platform === "darwin") {
40398
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40399
- const cmd = (0, import_node_path5.join)(dir, "Cursor.app/Contents/Resources/app/bin/cursor");
41062
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41063
+ const cmd = (0, import_node_path6.join)(dir, "Cursor.app/Contents/Resources/app/bin/cursor");
40400
41064
  if ((0, import_node_fs3.existsSync)(cmd))
40401
41065
  return cmd;
40402
41066
  }
40403
41067
  } else if (process.platform === "win32") {
40404
- const localApp = process.env.LOCALAPPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Local");
40405
- const cmd = (0, import_node_path5.join)(localApp, "Programs", "cursor", "resources", "app", "bin", "cursor.cmd");
41068
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41069
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "cursor", "resources", "app", "bin", "cursor.cmd");
40406
41070
  if ((0, import_node_fs3.existsSync)(cmd))
40407
41071
  return cmd;
40408
41072
  }
@@ -40411,17 +41075,17 @@ function findCursorCommand() {
40411
41075
  function findVscodeCommand() {
40412
41076
  if (process.env.INKMAP_ISOLATED_DETECT)
40413
41077
  return null;
40414
- if ((0, import_node_child_process3.spawnSync)("code", ["--version"], { stdio: "ignore" }).status === 0)
41078
+ if (probeCliCommand("code"))
40415
41079
  return "code";
40416
41080
  if (process.platform === "darwin") {
40417
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40418
- const cmd = (0, import_node_path5.join)(dir, "Visual Studio Code.app/Contents/Resources/app/bin/code");
41081
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41082
+ const cmd = (0, import_node_path6.join)(dir, "Visual Studio Code.app/Contents/Resources/app/bin/code");
40419
41083
  if ((0, import_node_fs3.existsSync)(cmd))
40420
41084
  return cmd;
40421
41085
  }
40422
41086
  } else if (process.platform === "win32") {
40423
- const localApp = process.env.LOCALAPPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Local");
40424
- const cmd = (0, import_node_path5.join)(localApp, "Programs", "Microsoft VS Code", "bin", "code.cmd");
41087
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41088
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "Microsoft VS Code", "bin", "code.cmd");
40425
41089
  if ((0, import_node_fs3.existsSync)(cmd))
40426
41090
  return cmd;
40427
41091
  }
@@ -40431,11 +41095,11 @@ function findCodexCommand() {
40431
41095
  if (process.env.INKMAP_CODEX_BIN) {
40432
41096
  return (0, import_node_fs3.existsSync)(process.env.INKMAP_CODEX_BIN) ? process.env.INKMAP_CODEX_BIN : null;
40433
41097
  }
40434
- if ((0, import_node_child_process3.spawnSync)("codex", ["--version"], { stdio: "ignore" }).status === 0)
41098
+ if (probeCliCommand("codex"))
40435
41099
  return "codex";
40436
41100
  if (process.platform === "darwin") {
40437
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40438
- const cmd = (0, import_node_path5.join)(dir, "ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
41101
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41102
+ const cmd = (0, import_node_path6.join)(dir, "ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
40439
41103
  if ((0, import_node_fs3.existsSync)(cmd))
40440
41104
  return cmd;
40441
41105
  }
@@ -40443,7 +41107,7 @@ function findCodexCommand() {
40443
41107
  return null;
40444
41108
  }
40445
41109
  function getDshHome() {
40446
- return process.env.DSH_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".dsh");
41110
+ return process.env.DSH_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".dsh");
40447
41111
  }
40448
41112
  function findDshCommand() {
40449
41113
  if (process.env.INKMAP_DSH_BIN) {
@@ -40451,17 +41115,17 @@ function findDshCommand() {
40451
41115
  }
40452
41116
  if (process.env.INKMAP_ISOLATED_DETECT)
40453
41117
  return null;
40454
- if ((0, import_node_child_process3.spawnSync)("dsh", ["--version"], { stdio: "ignore" }).status === 0)
41118
+ if (probeCliCommand("dsh"))
40455
41119
  return "dsh";
40456
41120
  if (process.platform === "darwin") {
40457
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40458
- const cmd = (0, import_node_path5.join)(dir, "DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
41121
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41122
+ const cmd = (0, import_node_path6.join)(dir, "DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
40459
41123
  if ((0, import_node_fs3.existsSync)(cmd))
40460
41124
  return cmd;
40461
41125
  }
40462
41126
  } else if (process.platform === "win32") {
40463
- const localApp = process.env.LOCALAPPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Local");
40464
- const cmd = (0, import_node_path5.join)(localApp, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd");
41127
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41128
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd");
40465
41129
  if ((0, import_node_fs3.existsSync)(cmd))
40466
41130
  return cmd;
40467
41131
  }
@@ -40470,18 +41134,18 @@ function findDshCommand() {
40470
41134
  function detectInstalledTargets() {
40471
41135
  const found = [];
40472
41136
  const claudeDir = getClaudeDesktopDir();
40473
- if ((0, import_node_fs3.existsSync)(claudeDir) || process.platform === "darwin" && ((0, import_node_fs3.existsSync)("/Applications/Claude.app") || (0, import_node_fs3.existsSync)((0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications", "Claude.app")))) {
41137
+ if ((0, import_node_fs3.existsSync)(claudeDir) || process.platform === "darwin" && ((0, import_node_fs3.existsSync)("/Applications/Claude.app") || (0, import_node_fs3.existsSync)((0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications", "Claude.app")))) {
40474
41138
  found.push("claude");
40475
41139
  }
40476
41140
  const claudeCodeCfg = getClaudeCodeConfigPath();
40477
- if ((0, import_node_fs3.existsSync)(claudeCodeCfg) || !process.env.INKMAP_ISOLATED_DETECT && (0, import_node_child_process3.spawnSync)("claude", ["--version"], { stdio: "ignore" }).status === 0) {
41141
+ if ((0, import_node_fs3.existsSync)(claudeCodeCfg) || !process.env.INKMAP_ISOLATED_DETECT && probeCliCommand("claude")) {
40478
41142
  found.push("claude-code");
40479
41143
  }
40480
41144
  if ((0, import_node_fs3.existsSync)(getCursorDir()) || Boolean(findCursorCommand())) {
40481
41145
  found.push("cursor");
40482
41146
  }
40483
41147
  const agyDir = getAntigravityConfigDir();
40484
- if ((0, import_node_fs3.existsSync)(agyDir) || !process.env.ANTIGRAVITY_CONFIG_DIR && (0, import_node_fs3.existsSync)((0, import_node_path5.join)((0, import_node_os5.homedir)(), ".gemini", "antigravity"))) {
41148
+ if ((0, import_node_fs3.existsSync)(agyDir) || !process.env.ANTIGRAVITY_CONFIG_DIR && (0, import_node_fs3.existsSync)((0, import_node_path6.join)((0, import_node_os5.homedir)(), ".gemini", "antigravity"))) {
40485
41149
  found.push("antigravity");
40486
41150
  }
40487
41151
  if (!process.env.INKMAP_ISOLATED_DETECT && findCodexCommand()) {
@@ -40489,7 +41153,7 @@ function detectInstalledTargets() {
40489
41153
  } else if (process.env.INKMAP_CODEX_BIN && (0, import_node_fs3.existsSync)(process.env.INKMAP_CODEX_BIN)) {
40490
41154
  found.push("codex");
40491
41155
  }
40492
- if (!process.env.INKMAP_ISOLATED_DETECT && (findDshCommand() || (0, import_node_fs3.existsSync)((0, import_node_path5.join)(getDshHome(), "profiles", "desktop"))) || process.env.INKMAP_DSH_BIN && (0, import_node_fs3.existsSync)(process.env.INKMAP_DSH_BIN)) {
41156
+ if (!process.env.INKMAP_ISOLATED_DETECT && (findDshCommand() || (0, import_node_fs3.existsSync)((0, import_node_path6.join)(getDshHome(), "profiles", "desktop"))) || process.env.INKMAP_DSH_BIN && (0, import_node_fs3.existsSync)(process.env.INKMAP_DSH_BIN)) {
40493
41157
  found.push("deepseek");
40494
41158
  }
40495
41159
  return found;
@@ -40512,73 +41176,73 @@ function readJsonObject(filePath) {
40512
41176
  return parsed;
40513
41177
  }
40514
41178
  function writeJsonAtomic(filePath, data) {
40515
- (0, import_node_fs3.mkdirSync)((0, import_node_path5.dirname)(filePath), { recursive: true });
41179
+ (0, import_node_fs3.mkdirSync)((0, import_node_path6.dirname)(filePath), { recursive: true });
40516
41180
  const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
40517
41181
  (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
40518
41182
  (0, import_node_fs3.renameSync)(tmp, filePath);
40519
41183
  }
40520
41184
  function stageStandaloneMcpApp() {
40521
- const appDir = (0, import_node_path5.join)(getInkmapHome(), "mcp-app");
41185
+ const appDir = (0, import_node_path6.join)(getInkmapHome(), "mcp-app");
40522
41186
  (0, import_node_fs3.mkdirSync)(appDir, { recursive: true });
40523
- const bundledCli = (0, import_node_path5.join)(DIST_DIR, "cli.cjs");
40524
- const bundledHtml = (0, import_node_path5.join)(DIST_DIR, "codex.html");
40525
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
40526
- const monorepoAntigravity = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
41187
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41188
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41189
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41190
+ const monorepoAntigravity = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
40527
41191
  if ((0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml)) {
40528
- (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path5.join)(appDir, "cli.cjs"));
40529
- (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path5.join)(appDir, "codex.html"));
41192
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(appDir, "cli.cjs"));
41193
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(appDir, "codex.html"));
40530
41194
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
40531
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(appDir, "web"), { recursive: true, force: true });
40532
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(appDir, "web"), { recursive: true });
41195
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(appDir, "web"), { recursive: true, force: true });
41196
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(appDir, "web"), { recursive: true });
40533
41197
  }
40534
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(appDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41198
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(appDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
40535
41199
  for (const notice of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40536
- const src = (0, import_node_path5.join)(PKG_ROOT, notice);
41200
+ const src = (0, import_node_path6.join)(PKG_ROOT, notice);
40537
41201
  if ((0, import_node_fs3.existsSync)(src))
40538
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(appDir, notice));
41202
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(appDir, notice));
40539
41203
  }
40540
- return { serverScript: (0, import_node_path5.join)(appDir, "server.cjs"), appDir };
41204
+ return { serverScript: (0, import_node_path6.join)(appDir, "server.cjs"), appDir };
40541
41205
  }
40542
- if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoAntigravity, "server.cjs")) && (0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoAntigravity, "codex.html"))) {
40543
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoAntigravity, "server.cjs"), (0, import_node_path5.join)(appDir, "server.cjs"));
40544
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoAntigravity, "codex.html"), (0, import_node_path5.join)(appDir, "codex.html"));
40545
- const sidecarWeb = (0, import_node_path5.join)(monorepoAntigravity, "sidecars", "inkmap", "web");
41206
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAntigravity, "server.cjs")) && (0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAntigravity, "codex.html"))) {
41207
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoAntigravity, "server.cjs"), (0, import_node_path6.join)(appDir, "server.cjs"));
41208
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoAntigravity, "codex.html"), (0, import_node_path6.join)(appDir, "codex.html"));
41209
+ const sidecarWeb = (0, import_node_path6.join)(monorepoAntigravity, "sidecars", "inkmap", "web");
40546
41210
  if ((0, import_node_fs3.existsSync)(sidecarWeb)) {
40547
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(appDir, "web"), { recursive: true, force: true });
40548
- (0, import_node_fs3.cpSync)(sidecarWeb, (0, import_node_path5.join)(appDir, "web"), { recursive: true });
41211
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(appDir, "web"), { recursive: true, force: true });
41212
+ (0, import_node_fs3.cpSync)(sidecarWeb, (0, import_node_path6.join)(appDir, "web"), { recursive: true });
40549
41213
  }
40550
41214
  for (const notice of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40551
- const src = (0, import_node_path5.join)(monorepoAntigravity, notice);
41215
+ const src = (0, import_node_path6.join)(monorepoAntigravity, notice);
40552
41216
  if ((0, import_node_fs3.existsSync)(src))
40553
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(appDir, notice));
41217
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(appDir, notice));
40554
41218
  }
40555
- return { serverScript: (0, import_node_path5.join)(appDir, "server.cjs"), appDir };
41219
+ return { serverScript: (0, import_node_path6.join)(appDir, "server.cjs"), appDir };
40556
41220
  }
40557
- const devBin = (0, import_node_path5.join)(PKG_ROOT, "bin", "inkmap.js");
41221
+ const devBin = (0, import_node_path6.join)(PKG_ROOT, "bin", "inkmap.js");
40558
41222
  if ((0, import_node_fs3.existsSync)(devBin) && (0, import_node_fs3.existsSync)(bundledHtml)) {
40559
41223
  return { serverScript: devBin, appDir };
40560
41224
  }
40561
41225
  throw new Error("\u672A\u627E\u5230\u5DF2\u6784\u5EFA\u7684 MCP App \u8D44\u6E90\uFF08codex.html\uFF09\u3002/ Built MCP App assets are missing.");
40562
41226
  }
40563
41227
  function installIdeExtension(editorDir, cliCmd) {
40564
- const vscodeBundle = (0, import_node_path5.join)(DIST_DIR, "bundles", "vscode");
40565
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
40566
- if (!(0, import_node_fs3.existsSync)((0, import_node_path5.join)(vscodeBundle, "package.json")) || !(0, import_node_fs3.existsSync)((0, import_node_path5.join)(vscodeBundle, "dist", "extension.js"))) {
41228
+ const vscodeBundle = (0, import_node_path6.join)(DIST_DIR, "bundles", "vscode");
41229
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41230
+ if (!(0, import_node_fs3.existsSync)((0, import_node_path6.join)(vscodeBundle, "package.json")) || !(0, import_node_fs3.existsSync)((0, import_node_path6.join)(vscodeBundle, "dist", "extension.js"))) {
40567
41231
  return null;
40568
41232
  }
40569
- const extPkg = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path5.join)(vscodeBundle, "package.json"), "utf8"));
40570
- const version2 = extPkg.version || "0.3.6";
40571
- const staging = (0, import_node_fs3.mkdtempSync)((0, import_node_path5.join)((0, import_node_os5.tmpdir)(), "inkmap-vsix-"));
41233
+ const extPkg = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path6.join)(vscodeBundle, "package.json"), "utf8"));
41234
+ const version2 = extPkg.version;
41235
+ const staging = (0, import_node_fs3.mkdtempSync)((0, import_node_path6.join)((0, import_node_os5.tmpdir)(), "inkmap-vsix-"));
40572
41236
  try {
40573
- const extStaging = (0, import_node_path5.join)(staging, "extension");
41237
+ const extStaging = (0, import_node_path6.join)(staging, "extension");
40574
41238
  (0, import_node_fs3.cpSync)(vscodeBundle, extStaging, { recursive: true });
40575
41239
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
40576
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(extStaging, "dist", "web"), { recursive: true });
41240
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(extStaging, "dist", "web"), { recursive: true });
40577
41241
  }
40578
41242
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md", "README.md"]) {
40579
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41243
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
40580
41244
  if ((0, import_node_fs3.existsSync)(src))
40581
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(extStaging, doc));
41245
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(extStaging, doc));
40582
41246
  }
40583
41247
  if (cliCmd) {
40584
41248
  const contentTypesXml = `<?xml version="1.0" encoding="utf-8"?>
@@ -40591,7 +41255,7 @@ function installIdeExtension(editorDir, cliCmd) {
40591
41255
  ];
40592
41256
  const walk = (dir, prefix) => {
40593
41257
  for (const item of (0, import_node_fs3.readdirSync)(dir, { withFileTypes: true })) {
40594
- const full = (0, import_node_path5.join)(dir, item.name);
41258
+ const full = (0, import_node_path6.join)(dir, item.name);
40595
41259
  const rel = `${prefix}/${item.name}`;
40596
41260
  if (item.isDirectory())
40597
41261
  walk(full, rel);
@@ -40600,23 +41264,65 @@ function installIdeExtension(editorDir, cliCmd) {
40600
41264
  }
40601
41265
  };
40602
41266
  walk(extStaging, "extension");
40603
- const vsixPath = (0, import_node_path5.join)(staging, `inkmap-${version2}.vsix`);
41267
+ const vsixPath = (0, import_node_path6.join)(staging, `inkmap-${version2}.vsix`);
40604
41268
  (0, import_node_fs3.writeFileSync)(vsixPath, buildZipBuffer(entries));
40605
41269
  try {
40606
- (0, import_node_child_process3.execFileSync)(cliCmd, ["--install-extension", vsixPath, "--force"], { stdio: "pipe" });
40607
- return (0, import_node_path5.join)(editorDir, "extensions", `inkmap.inkmap-vscode-${version2}`);
41270
+ execCliSync(cliCmd, ["--install-extension", vsixPath, "--force"], { stdio: "pipe" });
41271
+ return (0, import_node_path6.join)(editorDir, "extensions", `inkmap.inkmap-vscode-${version2}`);
40608
41272
  } catch {
40609
41273
  }
40610
41274
  }
40611
- const extRoot = (0, import_node_path5.join)(editorDir, "extensions");
41275
+ const extRoot = (0, import_node_path6.join)(editorDir, "extensions");
40612
41276
  (0, import_node_fs3.mkdirSync)(extRoot, { recursive: true });
40613
41277
  for (const old of (0, import_node_fs3.readdirSync)(extRoot)) {
40614
41278
  if (old.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
40615
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(extRoot, old), { recursive: true, force: true });
41279
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(extRoot, old), { recursive: true, force: true });
40616
41280
  }
40617
41281
  }
40618
- const dest = (0, import_node_path5.join)(extRoot, `inkmap.inkmap-vscode-${version2}`);
41282
+ const folderName = `inkmap.inkmap-vscode-${version2}`;
41283
+ const dest = (0, import_node_path6.join)(extRoot, folderName);
40619
41284
  (0, import_node_fs3.cpSync)(extStaging, dest, { recursive: true });
41285
+ try {
41286
+ const obsoletePath = (0, import_node_path6.join)(extRoot, ".obsolete");
41287
+ if ((0, import_node_fs3.existsSync)(obsoletePath)) {
41288
+ const obs = JSON.parse((0, import_node_fs3.readFileSync)(obsoletePath, "utf8"));
41289
+ let changedObs = false;
41290
+ for (const key of Object.keys(obs)) {
41291
+ if (key.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
41292
+ delete obs[key];
41293
+ changedObs = true;
41294
+ }
41295
+ }
41296
+ if (changedObs)
41297
+ writeJsonAtomic(obsoletePath, obs);
41298
+ }
41299
+ const registryPath = (0, import_node_path6.join)(extRoot, "extensions.json");
41300
+ const existingList = (0, import_node_fs3.existsSync)(registryPath) ? JSON.parse((0, import_node_fs3.readFileSync)(registryPath, "utf8")) : [];
41301
+ if (Array.isArray(existingList)) {
41302
+ const filtered = existingList.filter((item) => String(item?.identifier?.id ?? "").toLowerCase() !== "inkmap.inkmap-vscode");
41303
+ const destUrl = (0, import_node_url4.pathToFileURL)(dest);
41304
+ filtered.push({
41305
+ identifier: { id: "inkmap.inkmap-vscode" },
41306
+ version: version2,
41307
+ location: {
41308
+ $mid: 1,
41309
+ fsPath: dest,
41310
+ external: destUrl.href,
41311
+ path: destUrl.pathname,
41312
+ scheme: "file"
41313
+ },
41314
+ relativeLocation: folderName,
41315
+ metadata: {
41316
+ installedTimestamp: Date.now(),
41317
+ source: "vsix"
41318
+ }
41319
+ });
41320
+ const tmp = `${registryPath}.${process.pid}.${Date.now()}.tmp`;
41321
+ (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(filtered), "utf8");
41322
+ (0, import_node_fs3.renameSync)(tmp, registryPath);
41323
+ }
41324
+ } catch {
41325
+ }
40620
41326
  return dest;
40621
41327
  } finally {
40622
41328
  (0, import_node_fs3.rmSync)(staging, { recursive: true, force: true });
@@ -40626,19 +41332,34 @@ function uninstallIdeExtension(editorDir, cliCmd) {
40626
41332
  let removed = false;
40627
41333
  if (cliCmd) {
40628
41334
  try {
40629
- (0, import_node_child_process3.execFileSync)(cliCmd, ["--uninstall-extension", "inkmap.inkmap-vscode"], { stdio: "pipe" });
41335
+ execCliSync(cliCmd, ["--uninstall-extension", "inkmap.inkmap-vscode"], { stdio: "pipe" });
40630
41336
  removed = true;
40631
41337
  } catch {
40632
41338
  }
40633
41339
  }
40634
- const extRoot = (0, import_node_path5.join)(editorDir, "extensions");
41340
+ const extRoot = (0, import_node_path6.join)(editorDir, "extensions");
40635
41341
  if ((0, import_node_fs3.existsSync)(extRoot)) {
40636
41342
  for (const entry of (0, import_node_fs3.readdirSync)(extRoot)) {
40637
41343
  if (entry.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
40638
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(extRoot, entry), { recursive: true, force: true });
41344
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(extRoot, entry), { recursive: true, force: true });
40639
41345
  removed = true;
40640
41346
  }
40641
41347
  }
41348
+ try {
41349
+ const registryPath = (0, import_node_path6.join)(extRoot, "extensions.json");
41350
+ if ((0, import_node_fs3.existsSync)(registryPath)) {
41351
+ const existingList = JSON.parse((0, import_node_fs3.readFileSync)(registryPath, "utf8"));
41352
+ if (Array.isArray(existingList)) {
41353
+ const filtered = existingList.filter((item) => String(item?.identifier?.id ?? "").toLowerCase() !== "inkmap.inkmap-vscode");
41354
+ if (filtered.length !== existingList.length) {
41355
+ const tmp = `${registryPath}.${process.pid}.${Date.now()}.tmp`;
41356
+ (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(filtered), "utf8");
41357
+ (0, import_node_fs3.renameSync)(tmp, registryPath);
41358
+ }
41359
+ }
41360
+ }
41361
+ } catch {
41362
+ }
40642
41363
  }
40643
41364
  return removed;
40644
41365
  }
@@ -40647,7 +41368,7 @@ function buildMcpEntry(serverScript, workspaces, existingEntry, withTypeStdio =
40647
41368
  const args = isDirectServer ? [serverScript] : [serverScript, "mcp"];
40648
41369
  const prevEnv = existingEntry && typeof existingEntry === "object" && !Array.isArray(existingEntry) && typeof existingEntry.env === "object" ? { ...existingEntry.env } : {};
40649
41370
  if (workspaces.length > 0) {
40650
- prevEnv.INKMAP_WORKSPACES = workspaces.map((w2) => (0, import_node_path5.resolve)(w2)).join(import_node_path5.delimiter);
41371
+ prevEnv.INKMAP_WORKSPACES = workspaces.map((w2) => (0, import_node_path6.resolve)(w2)).join(import_node_path6.delimiter);
40651
41372
  }
40652
41373
  const entry = {};
40653
41374
  if (withTypeStdio)
@@ -40697,81 +41418,106 @@ async function refreshAntigravityMcp() {
40697
41418
  } catch {
40698
41419
  }
40699
41420
  }
40700
- async function installAntigravityPlugin() {
40701
- const pluginsDir = (0, import_node_path5.join)(getAntigravityConfigDir(), "plugins");
40702
- const destination = (0, import_node_path5.join)(pluginsDir, "inkmap");
40703
- const bundledAgy = (0, import_node_path5.join)(DIST_DIR, "bundles", "antigravity");
40704
- const bundledCli = (0, import_node_path5.join)(DIST_DIR, "cli.cjs");
40705
- const bundledHtml = (0, import_node_path5.join)(DIST_DIR, "codex.html");
40706
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
40707
- const monorepoAgy = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
41421
+ async function installAntigravityPlugin(workspaces = []) {
41422
+ const pluginsDir = (0, import_node_path6.join)(getAntigravityConfigDir(), "plugins");
41423
+ const destination = (0, import_node_path6.join)(pluginsDir, "inkmap");
41424
+ const bundledAgy = (0, import_node_path6.join)(DIST_DIR, "bundles", "antigravity");
41425
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41426
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41427
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41428
+ const monorepoAgy = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
40708
41429
  (0, import_node_fs3.mkdirSync)(pluginsDir, { recursive: true });
40709
41430
  (0, import_node_fs3.rmSync)(destination, { recursive: true, force: true });
40710
- if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(bundledAgy, "plugin.json")) && (0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml)) {
41431
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledAgy, "plugin.json")) && (0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml)) {
40711
41432
  (0, import_node_fs3.cpSync)(bundledAgy, destination, { recursive: true });
40712
- (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path5.join)(destination, "cli.cjs"));
40713
- (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path5.join)(destination, "codex.html"));
40714
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(destination, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41433
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(destination, "cli.cjs"));
41434
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(destination, "codex.html"));
41435
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(destination, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
40715
41436
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
40716
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(destination, "sidecars", "inkmap", "web"), { recursive: true });
41437
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(destination, "sidecars", "inkmap", "web"), { recursive: true });
40717
41438
  }
40718
41439
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md", "README.md"]) {
40719
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41440
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
40720
41441
  if ((0, import_node_fs3.existsSync)(src))
40721
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(destination, doc));
41442
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(destination, doc));
40722
41443
  }
40723
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoAgy, "plugin.json"))) {
41444
+ } else if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAgy, "plugin.json"))) {
40724
41445
  (0, import_node_fs3.cpSync)(monorepoAgy, destination, { recursive: true });
40725
41446
  } else {
40726
41447
  throw new Error("\u672A\u627E\u5230 Antigravity \u63D2\u4EF6\u8D44\u6E90 / Antigravity plugin bundle not found.");
40727
41448
  }
41449
+ if (workspaces.length > 0) {
41450
+ try {
41451
+ const mcpCfgPath = (0, import_node_path6.join)(destination, "mcp_config.json");
41452
+ if ((0, import_node_fs3.existsSync)(mcpCfgPath)) {
41453
+ const cfg = readJsonObject(mcpCfgPath);
41454
+ const servers = cfg.mcpServers && typeof cfg.mcpServers === "object" && !Array.isArray(cfg.mcpServers) ? { ...cfg.mcpServers } : {};
41455
+ if (servers.inkmap && typeof servers.inkmap === "object") {
41456
+ servers.inkmap = {
41457
+ ...servers.inkmap,
41458
+ env: {
41459
+ ...servers.inkmap.env && typeof servers.inkmap.env === "object" ? servers.inkmap.env : {},
41460
+ INKMAP_WORKSPACES: workspaces.map((w2) => (0, import_node_path6.resolve)(w2)).join(import_node_path6.delimiter)
41461
+ }
41462
+ };
41463
+ cfg.mcpServers = servers;
41464
+ writeJsonAtomic(mcpCfgPath, cfg);
41465
+ }
41466
+ }
41467
+ } catch {
41468
+ }
41469
+ }
40728
41470
  await refreshAntigravityMcp();
40729
41471
  return destination;
40730
41472
  }
40731
- function installCodexPlugin() {
41473
+ function installCodexPlugin(zh) {
40732
41474
  const codex = findCodexCommand();
40733
41475
  if (!codex) {
40734
41476
  throw new Error("\u672A\u68C0\u6D4B\u5230 codex \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 ChatGPT Desktop \u6216 Codex CLI / Codex CLI not found.");
40735
41477
  }
40736
- const bundledCodex = (0, import_node_path5.join)(DIST_DIR, "bundles", "codex");
40737
- const bundledCli = (0, import_node_path5.join)(DIST_DIR, "cli.cjs");
40738
- const bundledHtml = (0, import_node_path5.join)(DIST_DIR, "codex.html");
40739
- const monorepoCodexRoot = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars");
40740
- const destination = (0, import_node_path5.join)(getInkmapHome(), "codex-marketplace");
41478
+ const bundledCodex = (0, import_node_path6.join)(DIST_DIR, "bundles", "codex");
41479
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41480
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41481
+ const monorepoCodexRoot = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars");
41482
+ const destination = (0, import_node_path6.join)(getInkmapHome(), "codex-marketplace");
40741
41483
  (0, import_node_fs3.mkdirSync)(destination, { recursive: true });
40742
41484
  const marketplaceRoot = (0, import_node_fs3.realpathSync)(destination);
40743
- if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(bundledCodex, ".agents")) && (0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml)) {
41485
+ const fromNpmBundle = (0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledCodex, ".agents")) && (0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml);
41486
+ const fromMonorepo = (0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoCodexRoot, "inkmap-codex")) && (0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoCodexRoot, ".agents"));
41487
+ if (!fromNpmBundle && !fromMonorepo)
41488
+ throw new Error("\u672A\u627E\u5230 Codex \u63D2\u4EF6\u8D44\u6E90 / Codex plugin bundle not found.");
41489
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(marketplaceRoot, ".agents"), { recursive: true, force: true });
41490
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(marketplaceRoot, "inkmap-codex"), { recursive: true, force: true });
41491
+ if (fromNpmBundle) {
40744
41492
  (0, import_node_fs3.cpSync)(bundledCodex, marketplaceRoot, { recursive: true });
40745
- const pluginDir = (0, import_node_path5.join)(marketplaceRoot, "inkmap-codex");
40746
- (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path5.join)(pluginDir, "cli.cjs"));
40747
- (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path5.join)(pluginDir, "codex.html"));
40748
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(pluginDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41493
+ const pluginDir = (0, import_node_path6.join)(marketplaceRoot, "inkmap-codex");
41494
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(pluginDir, "cli.cjs"));
41495
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(pluginDir, "codex.html"));
41496
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(pluginDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
40749
41497
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40750
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41498
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
40751
41499
  if ((0, import_node_fs3.existsSync)(src))
40752
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(pluginDir, doc));
41500
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(pluginDir, doc));
40753
41501
  }
40754
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoCodexRoot, "inkmap-codex")) && (0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoCodexRoot, ".agents"))) {
40755
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoCodexRoot, ".agents"), (0, import_node_path5.join)(marketplaceRoot, ".agents"), { recursive: true });
40756
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoCodexRoot, "inkmap-codex"), (0, import_node_path5.join)(marketplaceRoot, "inkmap-codex"), { recursive: true });
40757
41502
  } else {
40758
- throw new Error("\u672A\u627E\u5230 Codex \u63D2\u4EF6\u8D44\u6E90 / Codex plugin bundle not found.");
41503
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoCodexRoot, ".agents"), (0, import_node_path6.join)(marketplaceRoot, ".agents"), { recursive: true });
41504
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoCodexRoot, "inkmap-codex"), (0, import_node_path6.join)(marketplaceRoot, "inkmap-codex"), { recursive: true });
40759
41505
  }
40760
41506
  const marketplaceName = "inkmap-local";
40761
- const rawList = (0, import_node_child_process3.execFileSync)(codex, ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
41507
+ const rawList = execCliSync(codex, ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
40762
41508
  const { marketplaces = [] } = JSON.parse(rawList);
40763
41509
  const existing = marketplaces.find((entry) => entry.name === marketplaceName);
40764
41510
  if (!existing) {
40765
- (0, import_node_child_process3.execFileSync)(codex, ["plugin", "marketplace", "add", marketplaceRoot], { stdio: "pipe" });
41511
+ execCliSync(codex, ["plugin", "marketplace", "add", marketplaceRoot], { stdio: "pipe" });
40766
41512
  }
40767
- (0, import_node_child_process3.execFileSync)(codex, ["plugin", "add", `inkmap-codex@${marketplaceName}`], { stdio: "pipe" });
41513
+ execCliSync(codex, ["plugin", "add", `inkmap-codex@${marketplaceName}`], { stdio: "pipe" });
40768
41514
  return {
40769
41515
  location: marketplaceRoot,
40770
- note: "\u91CD\u542F ChatGPT Desktop \u540E\uFF0C\u5728 Codex \u6A21\u5F0F\u70B9\u51FB .md \u6587\u4EF6\u6253\u5F00\u83DC\u5355\u9009\u62E9 Inkmap Mind Map"
41516
+ note: zh ? "\u91CD\u542F ChatGPT Desktop \u540E\uFF0C\u5728 Codex \u6A21\u5F0F\u70B9\u51FB .md \u6587\u4EF6\u6253\u5F00\u83DC\u5355\u9009\u62E9 Inkmap Mind Map" : "Restart ChatGPT Desktop, then open any .md file in Codex mode with Inkmap Mind Map"
40771
41517
  };
40772
41518
  }
40773
41519
  function configureDshMarketIndex(profileDir) {
40774
- const pkgPath = (0, import_node_path5.join)(profileDir, "package.json");
41520
+ const pkgPath = (0, import_node_path6.join)(profileDir, "package.json");
40775
41521
  if ((0, import_node_fs3.existsSync)(pkgPath)) {
40776
41522
  try {
40777
41523
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(pkgPath, "utf8"));
@@ -40791,52 +41537,56 @@ function configureDshMarketIndex(profileDir) {
40791
41537
  } catch {
40792
41538
  }
40793
41539
  }
40794
- const patchPath = (0, import_node_path5.join)(profileDir, "cordis.patch.yml");
41540
+ const patchPath = (0, import_node_path6.join)(profileDir, "cordis.patch.yml");
40795
41541
  const indexUrl = "https://zhiyuanv.com/dsh-index.json";
40796
41542
  try {
40797
41543
  const existing = (0, import_node_fs3.existsSync)(patchPath) ? (0, import_node_fs3.readFileSync)(patchPath, "utf8") : "";
40798
41544
  if (!existing.includes(indexUrl)) {
40799
- const snippet = `
40800
- - id: plugin-market
41545
+ const snippet = `- id: plugin-market
40801
41546
  name: "@deepseek-ai/dsh-plugin-market"
40802
41547
  config:
40803
41548
  indexes:
40804
41549
  - ${indexUrl}
40805
41550
  `;
40806
- (0, import_node_fs3.writeFileSync)(patchPath, existing.replace(/\n*$/, "") + snippet, "utf8");
41551
+ const trimmed = existing.trim();
41552
+ if (!trimmed || trimmed === "[]") {
41553
+ (0, import_node_fs3.writeFileSync)(patchPath, snippet, "utf8");
41554
+ } else if (!/^\s*-\s*id:\s*plugin-market\b/m.test(existing)) {
41555
+ (0, import_node_fs3.writeFileSync)(patchPath, existing.replace(/\n*$/, "\n\n") + snippet, "utf8");
41556
+ }
40807
41557
  }
40808
41558
  } catch {
40809
41559
  }
40810
41560
  }
40811
- function installDeepSeekHarnessPlugin() {
40812
- const bundledHarness = (0, import_node_path5.join)(DIST_DIR, "bundles", "harness");
40813
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
40814
- const monorepoHarness = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "dsh-inkmap");
40815
- const stagedDir = (0, import_node_path5.join)(getInkmapHome(), "dsh-inkmap");
41561
+ function installDeepSeekHarnessPlugin(zh) {
41562
+ const bundledHarness = (0, import_node_path6.join)(DIST_DIR, "bundles", "harness");
41563
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41564
+ const monorepoHarness = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "dsh-inkmap");
41565
+ const stagedDir = (0, import_node_path6.join)(getInkmapHome(), "dsh-inkmap");
40816
41566
  (0, import_node_fs3.rmSync)(stagedDir, { recursive: true, force: true });
40817
41567
  (0, import_node_fs3.mkdirSync)(stagedDir, { recursive: true });
40818
- if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(bundledHarness, "package.json")) && (0, import_node_fs3.existsSync)(bundledWeb)) {
41568
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledHarness, "package.json")) && (0, import_node_fs3.existsSync)(bundledWeb)) {
40819
41569
  (0, import_node_fs3.cpSync)(bundledHarness, stagedDir, { recursive: true });
40820
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(stagedDir, "web"), { recursive: true });
41570
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(stagedDir, "web"), { recursive: true });
40821
41571
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40822
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41572
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
40823
41573
  if ((0, import_node_fs3.existsSync)(src))
40824
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(stagedDir, doc));
41574
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(stagedDir, doc));
40825
41575
  }
40826
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoHarness, "package.json"))) {
41576
+ } else if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoHarness, "package.json"))) {
40827
41577
  (0, import_node_fs3.cpSync)(monorepoHarness, stagedDir, { recursive: true });
40828
41578
  } else {
40829
41579
  throw new Error("\u672A\u627E\u5230 DeepSeek Harness \u63D2\u4EF6\u8D44\u6E90 / DeepSeek Harness plugin bundle not found.");
40830
41580
  }
40831
41581
  const realStaged = (0, import_node_fs3.realpathSync)(stagedDir);
40832
41582
  const dshCmd = findDshCommand();
40833
- const profileDir = (0, import_node_path5.join)(getDshHome(), "profiles", "desktop");
41583
+ const profileDir = (0, import_node_path6.join)(getDshHome(), "profiles", "desktop");
40834
41584
  if (dshCmd) {
40835
- (0, import_node_child_process3.execFileSync)(dshCmd, ["plugin", "--profile", "desktop", "add", realStaged], { stdio: "pipe" });
41585
+ execCliSync(dshCmd, ["plugin", "--profile", "desktop", "add", realStaged], { stdio: "pipe" });
40836
41586
  } else if ((0, import_node_fs3.existsSync)(profileDir)) {
40837
- const nodeModulesTarget = (0, import_node_path5.join)(profileDir, "node_modules", "dsh-inkmap");
41587
+ const nodeModulesTarget = (0, import_node_path6.join)(profileDir, "node_modules", "dsh-inkmap");
40838
41588
  (0, import_node_fs3.rmSync)(nodeModulesTarget, { recursive: true, force: true });
40839
- (0, import_node_fs3.mkdirSync)((0, import_node_path5.join)(profileDir, "node_modules"), { recursive: true });
41589
+ (0, import_node_fs3.mkdirSync)((0, import_node_path6.join)(profileDir, "node_modules"), { recursive: true });
40840
41590
  (0, import_node_fs3.cpSync)(realStaged, nodeModulesTarget, { recursive: true });
40841
41591
  } else {
40842
41592
  throw new Error("\u672A\u68C0\u6D4B\u5230 DeepSeek Harness \u5BA2\u6237\u7AEF / DeepSeek Harness not found.");
@@ -40846,7 +41596,7 @@ function installDeepSeekHarnessPlugin() {
40846
41596
  }
40847
41597
  return {
40848
41598
  location: (0, import_node_fs3.existsSync)(profileDir) ? profileDir : realStaged,
40849
- note: "\u5DF2\u5728 DeepSeek Harness\u300C\u63D2\u4EF6\u300D\u9875\u542F\u7528 Inkmap \u601D\u7EF4\u5BFC\u56FE\u4E0E\u63D2\u4EF6\u7D22\u5F15\uFF08\u9884\u89C8 .md \u6587\u4EF6\u70B9\u51FB\u53F3\u4E0A\u89D2 Inkmap \u5373\u53EF\u6253\u5F00\uFF09"
41599
+ note: zh ? "\u5DF2\u5728 DeepSeek Harness\u300C\u63D2\u4EF6\u300D\u9875\u542F\u7528 Inkmap \u601D\u7EF4\u5BFC\u56FE\u4E0E\u63D2\u4EF6\u7D22\u5F15\uFF08\u9884\u89C8 .md \u6587\u4EF6\u70B9\u51FB\u53F3\u4E0A\u89D2 Inkmap \u5373\u53EF\u6253\u5F00\uFF09" : "Enabled Inkmap mind map in DeepSeek Harness (open any .md preview and click Inkmap in the top-right)"
40850
41600
  };
40851
41601
  }
40852
41602
  async function runInstall(options = {}) {
@@ -40859,7 +41609,7 @@ async function runInstall(options = {}) {
40859
41609
  const toRemove = explicitTargets ?? ["claude", "claude-code", "cursor", "vscode", "antigravity", "codex", "deepseek"];
40860
41610
  for (const target of toRemove) {
40861
41611
  if (target === "claude") {
40862
- const cfg = (0, import_node_path5.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41612
+ const cfg = (0, import_node_path6.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
40863
41613
  if (removeMcpJsonConfig(cfg))
40864
41614
  result.removed.push({ target, location: cfg });
40865
41615
  } else if (target === "claude-code") {
@@ -40867,38 +41617,49 @@ async function runInstall(options = {}) {
40867
41617
  if (removeMcpJsonConfig(cfg))
40868
41618
  result.removed.push({ target, location: cfg });
40869
41619
  } else if (target === "cursor") {
40870
- const cfg = (0, import_node_path5.join)(getCursorDir(), "mcp.json");
41620
+ const cfg = (0, import_node_path6.join)(getCursorDir(), "mcp.json");
40871
41621
  const removedMcp = removeMcpJsonConfig(cfg);
40872
41622
  const removedExt = uninstallIdeExtension(getCursorDir(), findCursorCommand());
40873
41623
  if (removedMcp || removedExt)
40874
41624
  result.removed.push({ target, location: cfg });
40875
41625
  } else if (target === "vscode") {
40876
41626
  if (uninstallIdeExtension(getVscodeDir(), findVscodeCommand())) {
40877
- result.removed.push({ target, location: (0, import_node_path5.join)(getVscodeDir(), "extensions") });
41627
+ result.removed.push({ target, location: (0, import_node_path6.join)(getVscodeDir(), "extensions") });
40878
41628
  }
40879
41629
  } else if (target === "antigravity") {
40880
- const dir = (0, import_node_path5.join)(getAntigravityConfigDir(), "plugins", "inkmap");
41630
+ const dir = (0, import_node_path6.join)(getAntigravityConfigDir(), "plugins", "inkmap");
40881
41631
  if ((0, import_node_fs3.existsSync)(dir)) {
40882
41632
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
40883
41633
  await refreshAntigravityMcp();
40884
41634
  result.removed.push({ target, location: dir });
40885
41635
  }
40886
41636
  } else if (target === "codex") {
40887
- const dir = (0, import_node_path5.join)(getInkmapHome(), "codex-marketplace");
41637
+ const codexCmd = findCodexCommand();
41638
+ if (codexCmd) {
41639
+ try {
41640
+ execCliSync(codexCmd, ["plugin", "remove", "inkmap-codex@inkmap-local"], { stdio: "pipe" });
41641
+ } catch {
41642
+ }
41643
+ try {
41644
+ execCliSync(codexCmd, ["plugin", "marketplace", "remove", "inkmap-local"], { stdio: "pipe" });
41645
+ } catch {
41646
+ }
41647
+ }
41648
+ const dir = (0, import_node_path6.join)(getInkmapHome(), "codex-marketplace");
40888
41649
  if ((0, import_node_fs3.existsSync)(dir)) {
40889
41650
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
40890
41651
  result.removed.push({ target, location: dir });
40891
41652
  }
40892
41653
  } else if (target === "deepseek") {
40893
41654
  const dshCmd = findDshCommand();
40894
- const profileDir = (0, import_node_path5.join)(getDshHome(), "profiles", "desktop");
41655
+ const profileDir = (0, import_node_path6.join)(getDshHome(), "profiles", "desktop");
40895
41656
  if (dshCmd && (0, import_node_fs3.existsSync)(profileDir)) {
40896
41657
  try {
40897
- (0, import_node_child_process3.execFileSync)(dshCmd, ["plugin", "--profile", "desktop", "remove", "dsh-inkmap"], { stdio: "pipe" });
41658
+ execCliSync(dshCmd, ["plugin", "--profile", "desktop", "remove", "dsh-inkmap"], { stdio: "pipe" });
40898
41659
  } catch {
40899
41660
  }
40900
41661
  }
40901
- const dir = (0, import_node_path5.join)(getInkmapHome(), "dsh-inkmap");
41662
+ const dir = (0, import_node_path6.join)(getInkmapHome(), "dsh-inkmap");
40902
41663
  if ((0, import_node_fs3.existsSync)(dir)) {
40903
41664
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
40904
41665
  result.removed.push({ target, location: profileDir });
@@ -40906,7 +41667,7 @@ async function runInstall(options = {}) {
40906
41667
  }
40907
41668
  }
40908
41669
  if (!explicitTargets) {
40909
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(getInkmapHome(), "mcp-app"), { recursive: true, force: true });
41670
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(getInkmapHome(), "mcp-app"), { recursive: true, force: true });
40910
41671
  }
40911
41672
  if (result.removed.length === 0) {
40912
41673
  log("[inkmap] \u672A\u53D1\u73B0\u5DF2\u5B89\u88C5\u7684 Inkmap \u5BA2\u6237\u7AEF\u914D\u7F6E / No installed Inkmap client configs found.");
@@ -40918,6 +41679,7 @@ async function runInstall(options = {}) {
40918
41679
  return result;
40919
41680
  }
40920
41681
  const { serverScript, appDir } = stageStandaloneMcpApp();
41682
+ const zhLocale = isChineseTerminalLocale();
40921
41683
  if (targets.length === 0) {
40922
41684
  log(`[inkmap] \u5DF2\u5C06 MCP App \u6838\u5FC3\u6587\u4EF6\u5C31\u7EEA\u5230: ${appDir}`);
40923
41685
  log("[inkmap] \u672A\u5728\u9ED8\u8BA4\u76EE\u5F55\u68C0\u6D4B\u5230\u5DF2\u5B89\u88C5\u7684 AI \u5BA2\u6237\u7AEF\uFF0C\u53EF\u6307\u5B9A\u5BA2\u6237\u7AEF\u540D\u79F0\u5F3A\u5236\u751F\u6210\u914D\u7F6E\uFF1A");
@@ -40927,16 +41689,17 @@ async function runInstall(options = {}) {
40927
41689
  log(" npx -y inkmap-mcp@latest install vscode # VS Code (\u539F\u751F\u7F16\u8F91\u5668\u6269\u5C55)");
40928
41690
  log(" npx -y inkmap-mcp@latest install antigravity # Google Antigravity");
40929
41691
  log(" npx -y inkmap-mcp@latest install codex # OpenAI Codex Desktop");
41692
+ log(" npx -y inkmap-mcp@latest install deepseek # DeepSeek Harness");
40930
41693
  return result;
40931
41694
  }
40932
41695
  for (const target of targets) {
40933
41696
  if (target === "claude") {
40934
- const cfg = (0, import_node_path5.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41697
+ const cfg = (0, import_node_path6.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
40935
41698
  upsertMcpJsonConfig(cfg, serverScript, workspaces, false);
40936
41699
  result.installed.push({
40937
41700
  target,
40938
41701
  location: cfg,
40939
- note: "\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u542F Claude Desktop \u540E\uFF0C\u5BF9 Claude \u8BF4\u201C\u7528 Inkmap \u6253\u5F00 xxx.md\u201D\u5373\u53EF"
41702
+ note: zhLocale ? "\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u542F Claude Desktop \u540E\uFF0C\u5BF9 Claude \u8BF4\u201C\u7528 Inkmap \u6253\u5F00 xxx.md\u201D\u5373\u53EF" : "Quit and restart Claude Desktop, then ask Claude to open any .md file with Inkmap"
40940
41703
  });
40941
41704
  } else if (target === "claude-code") {
40942
41705
  const cfg = getClaudeCodeConfigPath();
@@ -40944,13 +41707,13 @@ async function runInstall(options = {}) {
40944
41707
  result.installed.push({
40945
41708
  target,
40946
41709
  location: cfg,
40947
- note: "\u5728 Claude Code \u4E2D\u5DF2\u6CE8\u518C\u5168\u5C40 inkmap MCP \u670D\u52A1"
41710
+ note: zhLocale ? "\u5728 Claude Code \u4E2D\u5DF2\u6CE8\u518C\u5168\u5C40 inkmap MCP \u670D\u52A1" : "Registered global inkmap MCP server in Claude Code"
40948
41711
  });
40949
41712
  } else if (target === "cursor") {
40950
- const cfg = (0, import_node_path5.join)(getCursorDir(), "mcp.json");
41713
+ const cfg = (0, import_node_path6.join)(getCursorDir(), "mcp.json");
40951
41714
  upsertMcpJsonConfig(cfg, serverScript, workspaces, false);
40952
41715
  const extLoc = installIdeExtension(getCursorDir(), findCursorCommand());
40953
- const cursorServerDir = (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".cursor-server");
41716
+ const cursorServerDir = (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".cursor-server");
40954
41717
  if ((0, import_node_fs3.existsSync)(cursorServerDir)) {
40955
41718
  try {
40956
41719
  installIdeExtension(cursorServerDir, null);
@@ -40960,7 +41723,7 @@ async function runInstall(options = {}) {
40960
41723
  result.installed.push({
40961
41724
  target,
40962
41725
  location: extLoc ? `${cfg} + ${extLoc}` : cfg,
40963
- note: "\u5DF2\u540C\u65F6\u5B89\u88C5 MCP \u670D\u52A1\u4E0E\u53F3\u4FA7\u4E3B\u7F16\u8F91\u533A\u5BFC\u56FE\u6269\u5C55\uFF08Reload Window \u540E\u5BF9\u8BDD\u53EF\u76F4\u63A5\u6253\u5F00\u53F3\u4FA7\u5BFC\u56FE\u6807\u7B7E\uFF09"
41726
+ note: zhLocale ? "\u5DF2\u540C\u65F6\u5B89\u88C5 MCP \u670D\u52A1\u4E0E\u53F3\u4FA7\u4E3B\u7F16\u8F91\u533A\u5BFC\u56FE\u6269\u5C55\uFF08Reload Window \u540E\u5BF9\u8BDD\u53EF\u76F4\u63A5\u6253\u5F00\u53F3\u4FA7\u5BFC\u56FE\u6807\u7B7E\uFF09" : "Installed both MCP server and native right-pane mind map extension (Reload Window to activate)"
40964
41727
  });
40965
41728
  } else if (target === "vscode") {
40966
41729
  const extLoc = installIdeExtension(getVscodeDir(), findVscodeCommand());
@@ -40968,19 +41731,19 @@ async function runInstall(options = {}) {
40968
41731
  result.installed.push({
40969
41732
  target,
40970
41733
  location: extLoc,
40971
- note: "\u5DF2\u5728 VS Code \u5B89\u88C5\u539F\u751F Inkmap \u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668\u6269\u5C55"
41734
+ note: zhLocale ? "\u5DF2\u5728 VS Code \u5B89\u88C5\u539F\u751F Inkmap \u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668\u6269\u5C55" : "Installed native Inkmap mind map editor extension in VS Code"
40972
41735
  });
40973
41736
  }
40974
41737
  } else if (target === "antigravity") {
40975
- const loc = await installAntigravityPlugin();
41738
+ const loc = await installAntigravityPlugin(workspaces);
40976
41739
  result.installed.push({
40977
41740
  target,
40978
41741
  location: loc,
40979
- note: "\u5728 Antigravity \u5BF9\u8BDD\u4E2D\u8BA9 AI \u7528 Inkmap \u6253\u5F00 .md \u6587\u4EF6\uFF0C\u6216\u70B9\u51FB\u53F3\u4FA7\u9762\u677F + \u9009\u62E9 Inkmap"
41742
+ note: zhLocale ? "\u5728 Antigravity \u5BF9\u8BDD\u4E2D\u8BA9 AI \u7528 Inkmap \u6253\u5F00 .md \u6587\u4EF6\uFF0C\u6216\u70B9\u51FB\u53F3\u4FA7\u9762\u677F + \u9009\u62E9 Inkmap" : "Ask AI in Antigravity chat to open a .md file with Inkmap, or open Inkmap from the right-hand pane + button"
40980
41743
  });
40981
41744
  } else if (target === "codex") {
40982
41745
  try {
40983
- const installedCodex = installCodexPlugin();
41746
+ const installedCodex = installCodexPlugin(zhLocale);
40984
41747
  result.installed.push({
40985
41748
  target,
40986
41749
  location: installedCodex.location,
@@ -40993,7 +41756,7 @@ async function runInstall(options = {}) {
40993
41756
  }
40994
41757
  } else if (target === "deepseek") {
40995
41758
  try {
40996
- const installedDsh = installDeepSeekHarnessPlugin();
41759
+ const installedDsh = installDeepSeekHarnessPlugin(zhLocale);
40997
41760
  result.installed.push({
40998
41761
  target,
40999
41762
  location: installedDsh.location,
@@ -41006,7 +41769,6 @@ async function runInstall(options = {}) {
41006
41769
  }
41007
41770
  }
41008
41771
  }
41009
- const zhLocale = isChineseTerminalLocale();
41010
41772
  if (zhLocale) {
41011
41773
  log(`[inkmap] \u5B89\u88C5\u5B8C\u6210\uFF08Node: ${process.execPath}\uFF09\uFF1A`);
41012
41774
  for (const item of result.installed) {
@@ -41028,6 +41790,8 @@ async function runInstall(options = {}) {
41028
41790
  log(`[inkmap] Installation complete (Node: ${process.execPath}):`);
41029
41791
  for (const item of result.installed) {
41030
41792
  log(` \u2713 ${item.target.padEnd(12)} -> ${item.location}`);
41793
+ if (item.note)
41794
+ log(` ${item.note}`);
41031
41795
  }
41032
41796
  log("");
41033
41797
  log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
@@ -41040,6 +41804,17 @@ async function runInstall(options = {}) {
41040
41804
  log(" Qoder, WorkBuddy, Claude Desktop, Claude Code, OpenAI Codex, Google Antigravity & Trae!");
41041
41805
  log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
41042
41806
  }
41807
+ if (!options.uninstall && result.installed.length > 0) {
41808
+ try {
41809
+ const { fileSessionStorage: fileSessionStorage2, licenseService: licenseService2 } = await Promise.resolve().then(() => (init_license(), license_exports));
41810
+ const { YUNFAN_BILLING_ORIGIN: YUNFAN_BILLING_ORIGIN2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
41811
+ const svc = licenseService2(fileSessionStorage2(), () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN2, { host: "cli" });
41812
+ svc.track?.("plugin_install", 1, "cli");
41813
+ await Promise.race([svc.flushTelemetry?.(), new Promise((r2) => setTimeout(r2, 1500))]);
41814
+ svc.dispose();
41815
+ } catch {
41816
+ }
41817
+ }
41043
41818
  return result;
41044
41819
  }
41045
41820
  async function runInstallCli(argv, uninstall = false) {
@@ -41071,17 +41846,17 @@ async function runInstallCli(argv, uninstall = false) {
41071
41846
  const val = argv[++i];
41072
41847
  if (!val)
41073
41848
  throw new Error("--workspace \u9700\u8981\u63D0\u4F9B\u76EE\u5F55\u8DEF\u5F84 / --workspace requires a directory path");
41074
- workspaces.push(...val.split(import_node_path5.delimiter).filter(Boolean));
41849
+ workspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41075
41850
  continue;
41076
41851
  }
41077
41852
  if (arg.startsWith("--workspace=")) {
41078
41853
  const val = arg.slice("--workspace=".length);
41079
- workspaces.push(...val.split(import_node_path5.delimiter).filter(Boolean));
41854
+ workspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41080
41855
  continue;
41081
41856
  }
41082
41857
  const normalized = normalizeTarget(arg);
41083
41858
  if (!normalized) {
41084
- throw new Error(`\u672A\u77E5\u5BA2\u6237\u7AEF\u76EE\u6807: ${arg}\uFF08\u652F\u6301: claude, claude-code, cursor, vscode, antigravity, codex, all\uFF09`);
41859
+ throw new Error(`\u672A\u77E5\u5BA2\u6237\u7AEF\u76EE\u6807: ${arg}\uFF08\u652F\u6301: claude, claude-code, cursor, vscode, antigravity, codex, deepseek, all\uFF09`);
41085
41860
  }
41086
41861
  if (normalized === "all") {
41087
41862
  explicitAll = true;
@@ -41095,19 +41870,19 @@ async function runInstallCli(argv, uninstall = false) {
41095
41870
  uninstall
41096
41871
  });
41097
41872
  }
41098
- var import_node_child_process3, import_node_fs3, import_node_os5, import_node_path5, import_node_url3, import_node_zlib, DIST_DIR, PKG_ROOT, SERVER_WRAPPER, CRC_TABLE;
41873
+ var import_node_child_process4, import_node_fs3, import_node_os5, import_node_path6, import_node_url4, import_node_zlib, DIST_DIR, PKG_ROOT, SERVER_WRAPPER, CRC_TABLE;
41099
41874
  var init_install = __esm({
41100
41875
  "packages/cli/dist/install.js"() {
41101
41876
  "use strict";
41102
- import_node_child_process3 = require("node:child_process");
41877
+ import_node_child_process4 = require("node:child_process");
41103
41878
  import_node_fs3 = require("node:fs");
41104
41879
  import_node_os5 = require("node:os");
41105
- import_node_path5 = require("node:path");
41106
- import_node_url3 = require("node:url");
41880
+ import_node_path6 = require("node:path");
41881
+ import_node_url4 = require("node:url");
41107
41882
  import_node_zlib = require("node:zlib");
41108
41883
  init_license();
41109
- DIST_DIR = (0, import_node_path5.dirname)((0, import_node_url3.fileURLToPath)(inkmapModuleUrl));
41110
- PKG_ROOT = (0, import_node_path5.resolve)(DIST_DIR, "..");
41884
+ DIST_DIR = (0, import_node_path6.dirname)((0, import_node_url4.fileURLToPath)(inkmapModuleUrl));
41885
+ PKG_ROOT = (0, import_node_path6.resolve)(DIST_DIR, "..");
41111
41886
  SERVER_WRAPPER = `#!/usr/bin/env node
41112
41887
  "use strict";
41113
41888
  require("./cli.cjs").main(["mcp", ...process.argv.slice(2)]).catch(err => {
@@ -41135,14 +41910,14 @@ __export(index_exports, {
41135
41910
  main: () => main
41136
41911
  });
41137
41912
  module.exports = __toCommonJS(index_exports);
41138
- var import_node_child_process4 = require("node:child_process");
41139
- var import_node_path6 = require("node:path");
41140
- var import_node_url4 = require("node:url");
41913
+ var import_node_child_process5 = require("node:child_process");
41914
+ var import_node_path7 = require("node:path");
41915
+ var import_node_url5 = require("node:url");
41141
41916
  init_dist();
41142
41917
  init_license();
41143
41918
  init_server();
41144
- var INKMAP_VERSION = "0.3.8";
41145
- var WEB_ROOT2 = (0, import_node_url4.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
41919
+ init_version();
41920
+ var WEB_ROOT = (0, import_node_url5.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
41146
41921
  var USAGE = `Inkmap v${INKMAP_VERSION} \u2014 Markdown \u4EA4\u4E92\u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668 & MCP App
41147
41922
 
41148
41923
  \u7528\u6CD5 / Usage\uFF1A
@@ -41156,14 +41931,17 @@ var USAGE = `Inkmap v${INKMAP_VERSION} \u2014 Markdown \u4EA4\u4E92\u601D\u7EF4\
41156
41931
  \u5728\u672C\u5730\u6D4F\u89C8\u5668\u4E2D\u4EE5\u601D\u7EF4\u5BFC\u56FE\u6253\u5F00\u5E76\u5B9E\u65F6\u53CC\u5411\u7F16\u8F91 Markdown \u6587\u4EF6`;
41157
41932
  function openBrowser(url2) {
41158
41933
  const [cmd, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url2]] : ["xdg-open", [url2]];
41159
- (0, import_node_child_process4.spawn)(cmd, args, { stdio: "ignore", detached: true }).unref();
41934
+ const child = (0, import_node_child_process5.spawn)(cmd, args, { stdio: "ignore", detached: true });
41935
+ child.on("error", () => {
41936
+ });
41937
+ child.unref();
41160
41938
  }
41161
41939
  function appendEnvWorkspaces(dirs) {
41162
41940
  if (dirs.length === 0)
41163
41941
  return;
41164
- const resolved = dirs.map((d2) => (0, import_node_path6.resolve)(d2));
41165
- const current = (process.env.INKMAP_WORKSPACES || "").split(import_node_path6.delimiter).filter(Boolean);
41166
- process.env.INKMAP_WORKSPACES = [.../* @__PURE__ */ new Set([...current, ...resolved])].join(import_node_path6.delimiter);
41942
+ const resolved = dirs.map((d2) => (0, import_node_path7.resolve)(d2));
41943
+ const current = (process.env.INKMAP_WORKSPACES || "").split(import_node_path7.delimiter).filter(Boolean);
41944
+ process.env.INKMAP_WORKSPACES = [.../* @__PURE__ */ new Set([...current, ...resolved])].join(import_node_path7.delimiter);
41167
41945
  }
41168
41946
  async function main(argv) {
41169
41947
  if (argv.length === 0 && !process.stdin.isTTY) {
@@ -41190,9 +41968,9 @@ async function main(argv) {
41190
41968
  const val = argv[++i];
41191
41969
  if (!val)
41192
41970
  throw new Error("--workspace \u9700\u8981\u76EE\u5F55\u8DEF\u5F84");
41193
- extraWorkspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41971
+ extraWorkspaces.push(...val.split(import_node_path7.delimiter).filter(Boolean));
41194
41972
  } else if (arg.startsWith("--workspace=")) {
41195
- extraWorkspaces.push(...arg.slice("--workspace=".length).split(import_node_path6.delimiter).filter(Boolean));
41973
+ extraWorkspaces.push(...arg.slice("--workspace=".length).split(import_node_path7.delimiter).filter(Boolean));
41196
41974
  } else if (arg === "-h" || arg === "--help") {
41197
41975
  console.log(USAGE);
41198
41976
  return;
@@ -41242,11 +42020,10 @@ ${USAGE}`);
41242
42020
  const license = licenseService(fileSessionStorage(), () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN);
41243
42021
  const served = await serve({
41244
42022
  source: await fileSource(file2, log),
41245
- webRoot: WEB_ROOT2,
42023
+ webRoot: WEB_ROOT,
41246
42024
  port: port ?? (sidebar ? 0 : void 0),
41247
42025
  log,
41248
42026
  license,
41249
- ads: adFeed(PRODUCT.adFeedUrl),
41250
42027
  sidebar,
41251
42028
  sidebarPurchase
41252
42029
  });