inkmap-mcp 0.3.10 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -52,33 +52,13 @@ function trialDaysLeft(state, now = Date.now()) {
52
52
  const remaining = (state.trialUntil ?? 0) - now;
53
53
  return remaining > 0 ? Math.ceil(remaining / DAY_MS) : 0;
54
54
  }
55
- function sanitizeAds(input2) {
56
- if (!Array.isArray(input2))
57
- return [];
58
- const str = (v2, max) => typeof v2 === "string" && v2.trim() ? v2.trim().slice(0, max) : void 0;
59
- const out = [];
60
- for (const raw of input2.slice(0, 20)) {
61
- const r2 = raw;
62
- const id = str(r2?.id, 64);
63
- const title = str(r2?.title, 60);
64
- const text = str(r2?.text, 140);
65
- const url2 = str(r2?.url, 500);
66
- if (!id || !title || !text || !url2 || !/^https:\/\//.test(url2))
67
- continue;
68
- const locale = r2.locale === "zh" || r2.locale === "en" ? r2.locale : void 0;
69
- out.push({ id, title, text, url: url2, cta: str(r2.cta, 20), locale });
70
- }
71
- return out;
72
- }
73
55
  var PRODUCT, YUNFAN_BILLING_ORIGIN, DAY_MS, TRIAL_MS;
74
56
  var init_product = __esm({
75
57
  "packages/core/dist/product.js"() {
76
58
  "use strict";
77
59
  PRODUCT = {
78
60
  id: "inkmap-pro",
79
- entitlement: "inkmap.pro",
80
- /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
81
- adFeedUrl: ""
61
+ entitlement: "inkmap.pro"
82
62
  };
83
63
  YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
84
64
  DAY_MS = 24 * 60 * 60 * 1e3;
@@ -95,38 +75,134 @@ __export(dist_exports, {
95
75
  YUNFAN_BILLING_ORIGIN: () => YUNFAN_BILLING_ORIGIN,
96
76
  billingFlowUrl: () => billingFlowUrl,
97
77
  documentSetting: () => documentSetting,
78
+ frontMatterTitle: () => frontMatterTitle,
98
79
  hasAccess: () => hasAccess,
99
80
  isRich: () => isRich,
100
81
  parse: () => parse,
101
82
  plainText: () => plainText,
102
- sanitizeAds: () => sanitizeAds,
103
83
  sanitizeViewState: () => sanitizeViewState,
104
84
  serialize: () => serialize,
105
85
  serializeWithLines: () => serializeWithLines,
106
86
  trialDaysLeft: () => trialDaysLeft,
107
- withDocumentSetting: () => withDocumentSetting
87
+ withDocumentSetting: () => withDocumentSetting,
88
+ withFrontMatterTitle: () => withFrontMatterTitle
108
89
  });
109
- function parse(markdown, title = "Untitled") {
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";
110
188
  const text = markdown.replace(/\r\n?/g, "\n");
111
- const trailingNewline = text.endsWith("\n");
112
- const lines = (trailingNewline ? text.slice(0, -1) : text).split("\n");
189
+ const trailingNewline = markdown === "" ? true : text.endsWith("\n");
190
+ const lines = text === "" ? [""] : (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
113
191
  let frontMatter = "";
114
192
  let i = 0;
115
193
  if (lines[0] === "---") {
116
194
  const end = lines.indexOf("---", 1);
117
- if (end > 0) {
195
+ if (end > 0 && isFrontMatterBlock(lines, end)) {
118
196
  frontMatter = lines.slice(0, end + 1).join("\n") + "\n";
119
197
  i = end + 1;
120
- const t = frontMatter.match(/^title:\s*(.+)$/m);
121
- if (t)
122
- title = t[1].trim().replace(/^["']|["']$/g, "");
198
+ title = frontMatterTitle(frontMatter) ?? title;
123
199
  }
124
200
  }
125
201
  const top = { md: title, kind: "heading", level: 0, children: [] };
126
202
  const stack = [{ node: top, indent: -1, content: 0, heading: 0 }];
127
203
  let blank = 0;
128
204
  let leadingBlank = -1;
129
- let inFence = false;
205
+ let fence = null;
130
206
  let current = null;
131
207
  const pendingDividers = [];
132
208
  const attach = (node2) => {
@@ -142,10 +218,10 @@ function parse(markdown, title = "Untitled") {
142
218
  };
143
219
  for (; i < lines.length; i++) {
144
220
  const line = lines[i];
145
- if (inFence) {
221
+ if (fence) {
146
222
  appendLine(current, line);
147
- if (FENCE.test(line)) {
148
- inFence = false;
223
+ if (closesFence(line, fence)) {
224
+ fence = null;
149
225
  if (current?.node.unindentedBlock)
150
226
  current = null;
151
227
  }
@@ -170,20 +246,21 @@ function parse(markdown, title = "Untitled") {
170
246
  blank = 0;
171
247
  continue;
172
248
  }
173
- const item = isThematic ? null : ITEM.exec(line);
174
- const heading = item ? null : HEADING.exec(line);
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);
175
253
  if (current && !item && !heading && (indent >= current.content || !blank && current.node.kind === "item" && indent > 0)) {
176
254
  flushBlank(current);
177
255
  appendLine(current, line);
178
- if (FENCE.test(line))
179
- inFence = true;
256
+ fence = openFence(line);
180
257
  continue;
181
258
  }
182
259
  if (heading) {
183
- const level = heading[1].length;
260
+ const { level, text: headingText } = heading;
184
261
  while (stack.length > 1 && (stack[stack.length - 1].heading === void 0 || stack[stack.length - 1].heading >= level))
185
262
  stack.pop();
186
- const node3 = { md: heading[2], kind: "heading", level, children: [] };
263
+ const node3 = { md: headingText, kind: "heading", level, children: [] };
187
264
  attach(node3);
188
265
  stack.push({ node: node3, indent: -1, content: 0, heading: level });
189
266
  current = null;
@@ -192,19 +269,20 @@ function parse(markdown, title = "Untitled") {
192
269
  if (item) {
193
270
  while (stack.length > 1 && stack[stack.length - 1].heading === void 0 && stack[stack.length - 1].indent >= indent)
194
271
  stack.pop();
195
- const node3 = { md: item[4], kind: "item", marker: item[2], children: [] };
272
+ const itemText = item[4] ?? "";
273
+ const node3 = { md: itemText, kind: "item", marker: item[2], children: [] };
196
274
  attach(node3);
197
- current = { node: node3, indent, content: indent + item[2].length + item[3].length };
275
+ current = { node: node3, indent, content: indent + item[2].length + (item[3]?.length ?? 1) };
198
276
  stack.push(current);
199
- if (FENCE.test(item[4]))
200
- inFence = true;
277
+ fence = openFence(itemText);
201
278
  continue;
202
279
  }
203
- if (!blank && indent === 0 && FENCE.test(line) && current && current.node.kind === "item") {
280
+ const startedFence = openFence(line);
281
+ if (!blank && indent === 0 && startedFence && current && current.node.kind === "item") {
204
282
  const node3 = { md: line, kind: "block", unindentedBlock: true, children: [] };
205
283
  attach(node3);
206
284
  current = { node: node3, indent: 0, content: 0 };
207
- inFence = true;
285
+ fence = startedFence;
208
286
  continue;
209
287
  }
210
288
  while (stack.length > 1 && stack[stack.length - 1].heading === void 0)
@@ -212,8 +290,7 @@ function parse(markdown, title = "Untitled") {
212
290
  const node2 = { md: line.slice(indent), kind: "block", children: [] };
213
291
  attach(node2);
214
292
  current = { node: node2, indent, content: indent };
215
- if (FENCE.test(line))
216
- inFence = true;
293
+ fence = startedFence;
217
294
  }
218
295
  function flushBlank(frame) {
219
296
  for (; blank > 0; blank--)
@@ -226,10 +303,11 @@ function parse(markdown, title = "Untitled") {
226
303
  leadingBlank = 0;
227
304
  const trailingDividers = pendingDividers.length ? pendingDividers.splice(0) : void 0;
228
305
  const tops = top.children;
306
+ const extras = { ...trailingDividers && { trailingDividers }, ...bom && { bom: true } };
229
307
  if (tops.length === 1 && tops[0].kind === "heading") {
230
- return { frontMatter, leadingBlank, root: tops[0], syntheticRoot: false, trailingNewline, ...trailingDividers && { trailingDividers } };
308
+ return { frontMatter, leadingBlank, root: tops[0], syntheticRoot: false, trailingNewline, eol, ...extras };
231
309
  }
232
- return { frontMatter, leadingBlank, root: top, syntheticRoot: true, trailingNewline, ...trailingDividers && { trailingDividers } };
310
+ return { frontMatter, leadingBlank, root: top, syntheticRoot: true, trailingNewline, eol, ...extras };
233
311
  }
234
312
  function serialize(doc) {
235
313
  return serializeWithLines(doc).md;
@@ -237,14 +315,16 @@ function serialize(doc) {
237
315
  function serializeWithLines(doc) {
238
316
  const out = [];
239
317
  const lines = /* @__PURE__ */ new Map();
240
- const offset = doc.frontMatter ? doc.frontMatter.split("\n").length - 1 : 0;
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;
241
321
  const blanks = (n = 0) => {
242
322
  for (let k2 = 0; k2 < n; k2++)
243
323
  out.push("");
244
324
  };
245
325
  const pushLines = (first, md, pad) => {
246
- const [head, ...rest] = md.split("\n");
247
- out.push(first + head);
326
+ const [head, ...rest] = md.replace(/\r\n?/g, "\n").split("\n");
327
+ out.push(head === "" ? first.trimEnd() : first + head);
248
328
  for (const l of rest)
249
329
  out.push(l === "" ? "" : pad + l);
250
330
  };
@@ -258,26 +338,33 @@ function serializeWithLines(doc) {
258
338
  });
259
339
  return true;
260
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));
261
346
  const write = (node2, parent, indent, headingLevel, first = false) => {
262
347
  const keepSectionSpacing = parent.kind === "heading" || node2.kind === "item";
263
348
  const hadDividers = parent.kind === "heading" ? emitDividers(node2.dividersBefore, first) : false;
264
349
  if (!first || hadDividers)
265
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("");
266
354
  lines.set(node2, offset + out.length);
267
- if (node2.kind === "heading" && parent.kind === "heading") {
268
- const level = node2.level && node2.level > headingLevel ? node2.level : headingLevel + 1;
269
- pushLines("#".repeat(Math.min(level, 6)) + " ", node2.md, "");
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, "");
270
358
  node2.children.forEach((c) => write(c, node2, 0, level));
271
359
  return;
272
360
  }
273
- if (node2.kind === "block" && (parent.kind === "heading" || node2.unindentedBlock)) {
274
- pushLines("", node2.md, "");
275
- node2.children.forEach((c) => write(c, node2, 0, headingLevel));
361
+ if (writtenRaw(node2, parent)) {
362
+ pushLines("", protectText("", node2.md, followed(node2)), "");
276
363
  return;
277
364
  }
278
365
  const marker = node2.kind === "item" && node2.marker ? node2.marker : "-";
279
366
  const pad = " ".repeat(indent);
280
- pushLines(pad + marker + " ", node2.md, " ".repeat(indent + marker.length + 1));
367
+ pushLines(pad + marker + " ", protectText(marker + " ", node2.md, followed(node2)), " ".repeat(indent + marker.length + 1));
281
368
  node2.children.forEach((c) => write(c, node2, indent + marker.length + 1, headingLevel));
282
369
  };
283
370
  blanks(doc.leadingBlank);
@@ -285,17 +372,18 @@ function serializeWithLines(doc) {
285
372
  lines.set(doc.root, offset + out.length);
286
373
  doc.root.children.forEach((c, k2) => write(c, doc.root, 0, 0, k2 === 0));
287
374
  } else {
288
- const level = doc.root.level || 1;
375
+ const level = Math.min(doc.root.level || 1, 6);
289
376
  if (emitDividers(doc.root.dividersBefore, true)) {
290
377
  blanks(doc.root.blankBefore);
291
378
  }
292
379
  lines.set(doc.root, offset + out.length);
293
- pushLines("#".repeat(level) + " ", doc.root.md, "");
380
+ pushLines("#".repeat(level) + " ", doc.root.md.replace(/\s*\r?\n\s*/g, " "), "");
294
381
  doc.root.children.forEach((c) => write(c, doc.root, 0, level));
295
382
  }
296
383
  emitDividers(doc.trailingDividers, out.length === 0);
297
- const body = out.join("\n");
298
- return { md: doc.frontMatter + body + (doc.trailingNewline ? "\n" : ""), lines };
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 };
299
387
  }
300
388
  function isRich(md) {
301
389
  return /\n|[`*_\\|<>[\]!~]|\$[^\s$][\s\S]*\$|\$\$[\s\S]+\$\$|^#|^\d+\.\s/.test(md);
@@ -304,27 +392,36 @@ function plainText(md) {
304
392
  return md.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[`*_~]|\\(?=.)/g, "").replace(/\s*\n\s*/g, " ").trim();
305
393
  }
306
394
  function documentSetting(frontMatter, key) {
307
- const section = frontMatter.match(SETTINGS_SECTION)?.[1] ?? "";
308
- const value = section.match(new RegExp(`^[ \\t]+${key}:[ \\t]*(.*)$`, "m"))?.[1].trim();
309
- return value ? value.replace(/^["']|["']$/g, "") : void 0;
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;
310
399
  }
311
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");
312
403
  const line = ` ${key}: ${value}
313
404
  `;
314
- if (!frontMatter)
315
- return `---
405
+ let updated;
406
+ if (!norm)
407
+ updated = `---
316
408
  inkmap:
317
409
  ${line}---
318
410
  `;
319
- const section = frontMatter.match(SETTINGS_SECTION);
320
- if (!section)
321
- return frontMatter.replace(/---\n$/, `inkmap:
411
+ else {
412
+ const section = norm.match(SETTINGS_SECTION);
413
+ if (!section)
414
+ updated = norm.replace(/---\n$/, `inkmap:
322
415
  ${line}---
323
416
  `);
324
- const keyLine = new RegExp(`^[ \\t]+${key}:.*\\n`, "m");
325
- const body = keyLine.test(section[1]) ? section[1].replace(keyLine, line) : section[1] + line;
326
- return frontMatter.replace(SETTINGS_SECTION, `inkmap:
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:
327
421
  ${body}`);
422
+ }
423
+ }
424
+ return eol === "\r\n" ? updated.replace(/\n/g, "\r\n") : updated;
328
425
  }
329
426
  function sanitizeViewState(raw) {
330
427
  if (!raw || typeof raw !== "object")
@@ -349,77 +446,99 @@ function sanitizeViewState(raw) {
349
446
  }
350
447
  return folds || view ? { ...folds && { folds }, ...view && { view } } : void 0;
351
448
  }
352
- var THEMATIC_BREAK, ITEM, HEADING, FENCE, indentOf, isBlank, SETTINGS_SECTION;
449
+ var THEMATIC_BREAK, ITEM, YAML_KEY, TITLE_LINE, indentOf, isBlank, SETTINGS_SECTION;
353
450
  var init_dist = __esm({
354
451
  "packages/core/dist/index.js"() {
355
452
  "use strict";
356
453
  init_product();
357
454
  THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/;
358
- ITEM = /^(\s*)([-*+]|\d+[.)])(\s+)(.*)$/;
359
- HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
360
- FENCE = /^\s*(```|~~~)/;
455
+ ITEM = /^(\s*)([-*+]|\d+[.)])(?:([ \t]+)(.*))?$/;
456
+ YAML_KEY = /^(?:"[^"]*"|'[^']*'|[^\s#"'-].*?)[ \t]*:(?:[ \t]|$)/;
457
+ TITLE_LINE = /^title:[ \t]*(\S.*)$/m;
361
458
  indentOf = (line) => line.length - line.trimStart().length;
362
459
  isBlank = (line) => line.trim() === "";
363
460
  SETTINGS_SECTION = /^inkmap:[ \t]*\n((?:[ \t]+.*\n)*)/m;
364
461
  }
365
462
  });
366
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.13";
470
+ }
471
+ });
472
+
367
473
  // packages/cli/dist/license.js
368
474
  var license_exports = {};
369
475
  __export(license_exports, {
370
- adFeed: () => adFeed,
371
- billingOrigin: () => billingOrigin,
372
476
  detectOsLocale: () => detectOsLocale,
373
477
  fileSessionStorage: () => fileSessionStorage,
374
- licenseService: () => licenseService
478
+ licenseService: () => licenseService,
479
+ parseAppleLanguages: () => parseAppleLanguages,
480
+ resolveOsLocale: () => resolveOsLocale
375
481
  });
376
- function detectOsLocale() {
377
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
378
- if (/^zh\b/i.test(explicit))
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))
379
493
  return "zh";
380
- if (/^en\b/i.test(explicit))
494
+ if (EN_LOCALE_RE.test(explicit))
381
495
  return "en";
382
- if (cachedOsLocale)
383
- return cachedOsLocale;
384
- let domestic = false;
385
- try {
386
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
387
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
388
- 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);
389
504
  }
390
- } catch {
391
- }
392
- if (!domestic) {
393
- if (process.platform === "darwin") {
394
- try {
395
- const out = (0, import_node_child_process.execFileSync)("defaults", ["read", "-g", "AppleLanguages"], {
396
- encoding: "utf8",
397
- timeout: 800,
398
- stdio: ["ignore", "pipe", "ignore"]
399
- });
400
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
401
- if (/^zh\b/i.test(firstLang))
402
- domestic = true;
403
- } catch {
404
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
405
- if (/^zh\b/i.test(raw))
406
- domestic = true;
407
- }
408
- } else if (process.platform === "win32") {
409
- try {
410
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
411
- if (/^zh\b/i.test(loc))
412
- domestic = true;
413
- } catch {
414
- }
415
- } else {
416
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
417
- if (/^zh\b/i.test(raw))
418
- 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 {
419
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 {
420
526
  }
421
- cachedOsLocale = domestic ? "zh" : "en";
422
- 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());
423
542
  }
424
543
  function billingOrigin(raw) {
425
544
  if (!raw)
@@ -430,7 +549,7 @@ function billingOrigin(raw) {
430
549
  }
431
550
  return url2.origin;
432
551
  }
433
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
552
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
434
553
  const listeners = /* @__PURE__ */ new Set();
435
554
  let current = { pro: false };
436
555
  let trial;
@@ -442,6 +561,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
442
561
  let detectedHost = defaultHost;
443
562
  const pendingEvents = /* @__PURE__ */ new Map();
444
563
  let lastCheck = 0;
564
+ let fastPollUntil = 0;
565
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
566
+ let flowCreation;
445
567
  let disposed = false;
446
568
  let generation = 0;
447
569
  let connection;
@@ -449,12 +571,33 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
449
571
  let pendingWrite = Promise.resolve();
450
572
  let pendingCheckout;
451
573
  let cachedOrder;
452
- let magicPollTimer;
453
- let magicSession = 0;
454
- function stopMagicPoll() {
455
- ++magicSession;
456
- clearTimeout(magicPollTimer);
457
- 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;
458
601
  }
459
602
  function mergeCookies(existing, response) {
460
603
  const map2 = /* @__PURE__ */ new Map();
@@ -485,12 +628,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
485
628
  }
486
629
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
487
630
  }
488
- function clientLocale(hint) {
489
- const h2 = (hint || "").trim();
490
- if (/^zh\b/i.test(h2))
491
- return "zh";
492
- if (/^en\b/i.test(h2))
493
- return "en";
631
+ function clientLocale(_uiLocaleHint) {
494
632
  return detectOsLocale();
495
633
  }
496
634
  function writeSession(operation) {
@@ -522,7 +660,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
522
660
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
523
661
  throw new Error("Invalid Inkmap checkout response.");
524
662
  }
525
- return { origin, url: url2, token: data.token, ...cookie && { cookie } };
663
+ return { origin, url: url2, token: data.token, locale: loc, ...cookie && { cookie } };
526
664
  }
527
665
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
528
666
  const loc = clientLocale(localeHint);
@@ -584,12 +722,26 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
584
722
  pro,
585
723
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
586
724
  ...connected && { connected: true },
587
- ...cleanAccount && { account: cleanAccount }
725
+ ...cleanAccount && { account: cleanAccount },
726
+ ...lastSignIn && { lastSignIn }
588
727
  };
589
728
  for (const listener of listeners)
590
729
  listener(current);
591
730
  }
592
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
+ }
593
745
  const trialUntil = await localTrialDeadline().catch(() => void 0);
594
746
  if (disposed || trialUntil === void 0)
595
747
  return;
@@ -641,7 +793,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
641
793
  return await writeSession(async () => {
642
794
  if (version2 !== generation || disposed)
643
795
  return;
644
- await storage.write(void 0).catch(() => {
796
+ await storage.write(signedOutRecord()).catch(() => {
645
797
  });
646
798
  update(false);
647
799
  });
@@ -665,48 +817,134 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
665
817
  });
666
818
  return connection;
667
819
  }
668
- function startMagicPoll(origin, pendingToken) {
669
- stopMagicPoll();
670
- const id = magicSession;
671
- const deadline = Date.now() + 10 * 6e4;
672
- const poll = () => {
673
- 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)
870
+ return;
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)
674
879
  return;
675
- magicPollTimer = setTimeout(async () => {
676
- if (disposed || id !== magicSession)
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()))
677
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 = {};
678
903
  try {
679
- const res = await entitlement(origin, pendingToken);
680
- if (disposed || id !== magicSession)
681
- return;
682
- if (res.status === 401) {
683
- stopMagicPoll();
684
- return;
685
- }
686
- if (res.ok) {
687
- const body = await res.json();
688
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
689
- stopMagicPoll();
690
- await writeSession(async () => {
691
- if (disposed || origin !== billingOrigin(getOrigin()))
692
- return;
693
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
694
- ++generation;
695
- activeOrigin = origin;
696
- applyEntitlement(body);
697
- schedule(body.active === true ? 6e4 : 2500);
698
- });
699
- return;
700
- }
701
- }
904
+ record2 = JSON.parse(await storage.read() || "{}");
702
905
  } catch {
703
906
  }
704
- if (!disposed && id === magicSession && Date.now() < deadline)
705
- poll();
706
- }, 2e3);
707
- magicPollTimer.unref();
708
- };
709
- 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);
710
948
  }
711
949
  async function sendPendingTelemetry() {
712
950
  if (disposed || !pendingEvents.size)
@@ -721,7 +959,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
721
959
  if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
722
960
  return;
723
961
  const customHome = process.env.INKMAP_HOME || "";
724
- 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-"))) {
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-"))) {
725
964
  return;
726
965
  }
727
966
  }
@@ -745,7 +984,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
745
984
  installId: id,
746
985
  host: hostName,
747
986
  os,
748
- version: "0.3.10",
987
+ version: INKMAP_VERSION,
749
988
  locale: clientLocale(),
750
989
  tier,
751
990
  events
@@ -757,13 +996,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
757
996
  return {
758
997
  async state() {
759
998
  await (trial ??= startTrial());
760
- if (Date.now() - lastCheck >= 4e3)
999
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
1000
+ if (Date.now() - lastCheck >= interval)
761
1001
  await refresh();
1002
+ await parkUnpaidSession();
762
1003
  return current;
763
1004
  },
764
1005
  async connect(mode, localeHint) {
765
1006
  if (loginOnly && mode !== "restore")
766
1007
  throw new Error("Only Yunfan account sign-in is available.");
1008
+ expectPurchase();
767
1009
  const origin = billingOrigin(getOrigin());
768
1010
  const loc = clientLocale(localeHint);
769
1011
  const version2 = generation;
@@ -805,7 +1047,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
805
1047
  if (version2 !== generation || disposed || origin !== billingOrigin(getOrigin())) {
806
1048
  throw new Error("The Yunfan account session changed. Please try again.");
807
1049
  }
808
- 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 } }));
809
1052
  ++generation;
810
1053
  lastCheck = 0;
811
1054
  if (mode !== "buy" || !current.connected)
@@ -817,8 +1060,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
817
1060
  async orderPro(localeHint) {
818
1061
  if (loginOnly)
819
1062
  throw new Error("Only Yunfan account sign-in is available.");
1063
+ expectPurchase();
820
1064
  const origin = billingOrigin(getOrigin());
821
- 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) {
822
1067
  const hit = cachedOrder.result;
823
1068
  cachedOrder = void 0;
824
1069
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -844,7 +1089,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
844
1089
  await writeSession(async () => {
845
1090
  if (version2 !== generation || disposed || origin !== billingOrigin(getOrigin()))
846
1091
  return;
847
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
1092
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
848
1093
  if (persist) {
849
1094
  ++generation;
850
1095
  lastCheck = 0;
@@ -893,34 +1138,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
893
1138
  async sendPhoneCode(phone, localeHint) {
894
1139
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254)
895
1140
  return phoneFailure(400);
1141
+ expectPurchase();
896
1142
  const isEmail = phone.includes("@");
897
1143
  const locale = clientLocale(localeHint);
898
1144
  try {
899
1145
  const origin = billingOrigin(getOrigin());
900
1146
  if (!loginOnly) {
901
1147
  try {
902
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
903
- 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;
904
1155
  }
905
1156
  const sendAction = isEmail ? "email/send" : "sms";
906
1157
  const sendBody = isEmail ? { email: phone, locale } : { phone };
907
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
908
- if (smsRes.status === 410 || smsRes.status === 404) {
909
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
910
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
911
- }
912
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
913
- 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 };
914
1169
  } catch {
915
1170
  pendingCheckout = void 0;
916
1171
  }
917
1172
  }
918
1173
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
919
1174
  if (response.status === 204) {
1175
+ await rememberSignIn(phone);
920
1176
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
921
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
922
- startMagicPoll(origin, pendingToken);
923
- }
1177
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken))
1178
+ await waitFor(origin, pendingToken, phone);
924
1179
  return { ok: true, value: void 0 };
925
1180
  }
926
1181
  return phoneFailure(response.status);
@@ -928,41 +1183,47 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
928
1183
  return phoneFailure();
929
1184
  }
930
1185
  },
931
- async signInByPhone(phone, code) {
1186
+ async signInByPhone(phone, code, localeHint) {
932
1187
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code))
933
1188
  return phoneFailure(400);
934
1189
  const isEmail = phone.includes("@");
1190
+ const locale = clientLocale(localeHint);
935
1191
  const version2 = generation;
936
1192
  try {
937
1193
  const origin = billingOrigin(getOrigin());
938
1194
  let token;
939
1195
  let checkoutUrl;
940
1196
  let cookie;
941
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
1197
+ const flow = pendingCheckout;
1198
+ if (!loginOnly && flow && flow.origin === origin) {
942
1199
  const verifyAction = isEmail ? "email/verify" : "login";
943
1200
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
944
- 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);
945
1202
  if (!loginRes.ok) {
946
- if (loginRes.status === 410 || loginRes.status === 404)
947
- 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
+ }
948
1207
  return phoneFailure(loginRes.status);
949
1208
  }
950
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
951
- token = pendingCheckout.token;
952
- checkoutUrl = pendingCheckout.url;
953
- pendingCheckout = void 0;
954
- 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);
955
1215
  if (orderRes?.ok) {
956
1216
  cookie = mergeCookies(cookie, orderRes);
957
1217
  const orderData = await orderRes.json().catch(() => null);
958
1218
  if (orderData && typeof orderData === "object") {
959
1219
  if (orderData.active === true) {
960
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
1220
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
961
1221
  } else if (typeof orderData.qr === "string" && orderData.qr) {
962
1222
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
963
1223
  cachedOrder = {
964
1224
  at: Date.now(),
965
1225
  origin,
1226
+ locale,
966
1227
  result: {
967
1228
  status: "qr",
968
1229
  qr,
@@ -971,12 +1232,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
971
1232
  }
972
1233
  };
973
1234
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
974
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
1235
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
975
1236
  }
976
1237
  }
977
1238
  }
978
1239
  } else {
979
- const response = await phoneRequest(origin, "verify", phone, code);
1240
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
980
1241
  if (response.status !== 201)
981
1242
  return phoneFailure(response.status);
982
1243
  cookie = mergeCookies(void 0, response);
@@ -1004,11 +1265,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
1004
1265
  }
1005
1266
  if (cachedOrder?.result.status === "active")
1006
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
+ }
1007
1273
  return await writeSession(async () => {
1008
1274
  if (version2 !== generation || disposed || origin !== billingOrigin(getOrigin()))
1009
1275
  return phoneFailure();
1010
- stopMagicPoll();
1011
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
1276
+ clearWaiting();
1277
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
1012
1278
  ++generation;
1013
1279
  activeOrigin = origin;
1014
1280
  applyEntitlement(state);
@@ -1022,12 +1288,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
1022
1288
  }
1023
1289
  },
1024
1290
  async deactivate() {
1025
- stopMagicPoll();
1291
+ clearWaiting();
1026
1292
  pendingCheckout = void 0;
1027
1293
  cachedOrder = void 0;
1028
1294
  const saved = await writeSession(async () => {
1029
1295
  const previous = await storage.read();
1030
- await storage.write(void 0);
1296
+ await storage.write(signedOutRecord());
1031
1297
  ++generation;
1032
1298
  clearTimeout(timer);
1033
1299
  lastCheck = 0;
@@ -1038,7 +1304,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
1038
1304
  return;
1039
1305
  try {
1040
1306
  const { origin, token } = JSON.parse(saved);
1041
- if (origin !== billingOrigin(getOrigin()))
1307
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string")
1042
1308
  return;
1043
1309
  await fetch(origin + "/billing/v1/entitlement", {
1044
1310
  method: "DELETE",
@@ -1058,7 +1324,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
1058
1324
  return;
1059
1325
  if (hostHint)
1060
1326
  detectedHost = hostHint;
1061
- if (!sentAppOpen) {
1327
+ if (!sentAppOpen && !PASSIVE_TELEMETRY_EVENTS.has(event)) {
1062
1328
  sentAppOpen = true;
1063
1329
  pendingEvents.set("app_open", (pendingEvents.get("app_open") ?? 0) + 1);
1064
1330
  }
@@ -1082,7 +1348,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
1082
1348
  },
1083
1349
  dispose() {
1084
1350
  disposed = true;
1085
- stopMagicPoll();
1351
+ clearWaiting();
1086
1352
  clearTimeout(trialTimer);
1087
1353
  clearTimeout(timer);
1088
1354
  clearTimeout(telemetryTimer);
@@ -1110,31 +1376,39 @@ function inferNodeHost() {
1110
1376
  }
1111
1377
  return "cli";
1112
1378
  }
1113
- async function localInstallId() {
1114
- const path = (0, import_node_path.join)(process.env.INKMAP_HOME ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
1115
- let value;
1379
+ async function atomicCreateIfMissing(path, initialContent) {
1116
1380
  try {
1117
- value = (await (0, import_promises.readFile)(path, "utf8")).trim();
1381
+ return await (0, import_promises.readFile)(path, "utf8");
1118
1382
  } catch (error62) {
1119
1383
  if (error62.code !== "ENOENT")
1120
1384
  throw error62;
1121
1385
  await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true, mode: 448 });
1122
- const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
1123
1386
  const temporary = path + "." + (0, import_node_crypto.randomUUID)();
1124
1387
  try {
1125
- await (0, import_promises.writeFile)(temporary, generated, { mode: 384, flag: "wx" });
1126
- await (0, import_promises.link)(temporary, path).catch((err) => {
1127
- if (err.code !== "EEXIST")
1128
- 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;
1129
1397
  });
1130
1398
  } finally {
1131
- await (0, import_promises.rm)(temporary, { force: true });
1399
+ await (0, import_promises.rm)(temporary, { force: true }).catch(() => {
1400
+ });
1132
1401
  }
1133
- value = (await (0, import_promises.readFile)(path, "utf8")).trim();
1402
+ return await (0, import_promises.readFile)(path, "utf8");
1134
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();
1135
1409
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
1136
1410
  }
1137
- 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")) {
1138
1412
  return {
1139
1413
  read: () => (0, import_promises.readFile)(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
1140
1414
  async write(token) {
@@ -1152,49 +1426,12 @@ function fileSessionStorage(path = (0, import_node_path.join)(process.env.INKMAP
1152
1426
  };
1153
1427
  }
1154
1428
  async function localTrialDeadline() {
1155
- const path = (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap", "trial-start");
1156
- const now = Date.now();
1157
- let value;
1158
- try {
1159
- value = await (0, import_promises.readFile)(path, "utf8");
1160
- } catch (error62) {
1161
- if (error62.code !== "ENOENT")
1162
- throw error62;
1163
- await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true, mode: 448 });
1164
- const temporary = path + "." + (0, import_node_crypto.randomUUID)();
1165
- try {
1166
- await (0, import_promises.writeFile)(temporary, String(now), { mode: 384, flag: "wx" });
1167
- await (0, import_promises.link)(temporary, path).catch((error63) => {
1168
- if (error63.code !== "EEXIST")
1169
- throw error63;
1170
- });
1171
- } finally {
1172
- await (0, import_promises.rm)(temporary, { force: true });
1173
- }
1174
- value = await (0, import_promises.readFile)(path, "utf8");
1175
- }
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()));
1176
1431
  const started = Number(value);
1177
1432
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
1178
1433
  }
1179
- function adFeed(url2) {
1180
- let cache;
1181
- return async () => {
1182
- if (!url2)
1183
- return [];
1184
- if (cache && Date.now() - cache.at < AD_TTL)
1185
- return cache.ads;
1186
- try {
1187
- const res = await fetch(url2, { signal: AbortSignal.timeout(5e3), headers: { accept: "application/json" } });
1188
- const ads = res.ok ? sanitizeAds(await res.json()) : [];
1189
- cache = { at: Date.now(), ads };
1190
- return ads;
1191
- } catch {
1192
- cache = { at: Date.now(), ads: [] };
1193
- return [];
1194
- }
1195
- };
1196
- }
1197
- 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, PASSIVE_TELEMETRY_EVENTS;
1198
1435
  var init_license = __esm({
1199
1436
  "packages/cli/dist/license.js"() {
1200
1437
  "use strict";
@@ -1203,21 +1440,65 @@ var init_license = __esm({
1203
1440
  import_node_crypto = require("node:crypto");
1204
1441
  import_node_os = require("node:os");
1205
1442
  import_node_path = require("node:path");
1443
+ init_version();
1206
1444
  init_dist();
1207
- 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();
1454
+ PASSIVE_TELEMETRY_EVENTS = /* @__PURE__ */ new Set(["plugin_activate", "plugin_install", "onboarding_view"]);
1208
1455
  }
1209
1456
  });
1210
1457
 
1211
- // packages/cli/dist/server.js
1212
- function insideRoot(root, target) {
1458
+ // packages/cli/dist/workspace-fs.js
1459
+ function insideOrEqual(root, target) {
1213
1460
  if (root === target)
1214
1461
  return true;
1215
1462
  const rel = (0, import_node_path2.relative)(root, target);
1216
1463
  return Boolean(rel && !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path2.sep));
1217
1464
  }
1465
+ function hasHiddenSegment(root, target) {
1466
+ const rel = (0, import_node_path2.relative)(root, target);
1467
+ if (!rel || rel === ".")
1468
+ return false;
1469
+ return rel.split(import_node_path2.sep).some((part) => part.startsWith("."));
1470
+ }
1471
+ async function hasSymlinkUnderRoot(realRoot, rawTarget) {
1472
+ let cur = rawTarget;
1473
+ while (cur && cur !== (0, import_node_path2.dirname)(cur)) {
1474
+ const st = await (0, import_promises2.lstat)(cur);
1475
+ if (st.isSymbolicLink())
1476
+ return true;
1477
+ if (await (0, import_promises2.realpath)(cur) === realRoot)
1478
+ return false;
1479
+ cur = (0, import_node_path2.dirname)(cur);
1480
+ }
1481
+ return false;
1482
+ }
1483
+ function uriToPath(uri, platform = process.platform) {
1484
+ if (typeof uri !== "string" || !uri.trim())
1485
+ return null;
1486
+ const trimmed = uri.trim();
1487
+ const windows = platform === "win32";
1488
+ try {
1489
+ if (trimmed.startsWith("file://")) {
1490
+ const path = (0, import_node_url.fileURLToPath)(trimmed.replace(/^file:\/\/\/([a-zA-Z])%3[aA](?=\/|$)/, "file:///$1:"), { windows });
1491
+ return windows && /^[a-zA-Z]:$/.test(path) ? path + "\\" : path;
1492
+ }
1493
+ if ((windows ? import_node_path2.win32 : import_node_path2.posix).isAbsolute(trimmed))
1494
+ return trimmed;
1495
+ } catch {
1496
+ }
1497
+ return null;
1498
+ }
1218
1499
  async function findProjectRoot(filePath) {
1219
- let cur = (0, import_node_path2.dirname)(filePath);
1220
1500
  const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1501
+ let cur = (0, import_node_path2.dirname)(filePath);
1221
1502
  while (cur && cur !== (0, import_node_path2.dirname)(cur) && cur !== home) {
1222
1503
  try {
1223
1504
  await (0, import_promises2.lstat)((0, import_node_path2.join)(cur, ".git"));
@@ -1228,7 +1509,7 @@ async function findProjectRoot(filePath) {
1228
1509
  }
1229
1510
  return (0, import_node_path2.dirname)(filePath);
1230
1511
  }
1231
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1512
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
1232
1513
  const found = [];
1233
1514
  async function walk(dir, depth) {
1234
1515
  if (depth > maxDepth || found.length >= maxFiles)
@@ -1250,12 +1531,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1250
1531
  await walk(full, depth + 1);
1251
1532
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
1252
1533
  try {
1253
- const st = await (0, import_promises2.lstat)(full);
1254
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
1255
- const real = await (0, import_promises2.realpath)(full);
1256
- if (real === full && insideRoot(rootDir, real))
1257
- found.push(real);
1258
- }
1534
+ const info = await (0, import_promises2.lstat)(full);
1535
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1536
+ continue;
1537
+ const real = await (0, import_promises2.realpath)(full);
1538
+ if (real === full && insideOrEqual(rootDir, real))
1539
+ found.push({ path: real, mtimeMs: info.mtimeMs });
1259
1540
  } catch {
1260
1541
  }
1261
1542
  }
@@ -1263,60 +1544,250 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1263
1544
  }
1264
1545
  await walk(rootDir, 0);
1265
1546
  found.sort((a, b) => {
1266
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
1267
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
1268
- if (aM !== bM)
1269
- return aM - bM;
1270
- return a.localeCompare(b);
1547
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1548
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1549
+ if (am !== bm)
1550
+ return am - bm;
1551
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1552
+ return b.mtimeMs - a.mtimeMs;
1553
+ return a.path.localeCompare(b.path);
1271
1554
  });
1272
1555
  return found;
1273
1556
  }
1557
+ async function discoverAntigravityProjects() {
1558
+ 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");
1559
+ const roots = [];
1560
+ let entries = [];
1561
+ try {
1562
+ entries = await (0, import_promises2.readdir)(projectsDir);
1563
+ } catch {
1564
+ return roots;
1565
+ }
1566
+ for (const name of entries) {
1567
+ if (!name.endsWith(".json"))
1568
+ continue;
1569
+ try {
1570
+ const data = JSON.parse(await (0, import_promises2.readFile)((0, import_node_path2.join)(projectsDir, name), "utf8"));
1571
+ const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
1572
+ for (const r2 of resources) {
1573
+ const p2 = uriToPath(r2?.gitFolder?.folderUri || r2?.folderUri);
1574
+ if (!p2)
1575
+ continue;
1576
+ const real = await (0, import_promises2.realpath)(p2).catch(() => null);
1577
+ if (real)
1578
+ roots.push({ path: real, name: String(data.name || (0, import_node_path2.basename)(real)) });
1579
+ }
1580
+ } catch {
1581
+ }
1582
+ }
1583
+ return roots;
1584
+ }
1585
+ function targetStateFile() {
1586
+ return (0, import_node_path2.join)(process.env.INKMAP_HOME || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap"), "antigravity-target.json");
1587
+ }
1588
+ async function readTargetSelection() {
1589
+ try {
1590
+ const raw = JSON.parse(await (0, import_promises2.readFile)(targetStateFile(), "utf8"));
1591
+ if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
1592
+ return null;
1593
+ const info = await (0, import_promises2.lstat)(raw.file);
1594
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1595
+ return null;
1596
+ const file2 = await (0, import_promises2.realpath)(raw.file);
1597
+ if (file2 !== raw.file)
1598
+ return null;
1599
+ 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);
1600
+ if (!insideOrEqual(workspace, file2))
1601
+ return null;
1602
+ return { file: file2, workspace, seq: Number(raw.seq) || 0, ...raw.editorOnly === true && { editorOnly: true } };
1603
+ } catch {
1604
+ return null;
1605
+ }
1606
+ }
1607
+ function createSerialQueue() {
1608
+ let tail = Promise.resolve();
1609
+ return function serialized(work) {
1610
+ const next = tail.then(work);
1611
+ tail = next.catch(() => {
1612
+ });
1613
+ return next;
1614
+ };
1615
+ }
1616
+ function createWorkspaceAccess() {
1617
+ const sessionWorkspaces = /* @__PURE__ */ new Map();
1618
+ async function allowedRoots(extraWorkspaceUris = []) {
1619
+ const roots = /* @__PURE__ */ new Map();
1620
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1621
+ const configDir = await (0, import_promises2.realpath)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path2.join)(home, ".gemini", "config")).catch(() => "");
1622
+ const addRoot = async (rawPath, active, label) => {
1623
+ if (!rawPath)
1624
+ return;
1625
+ const real = await (0, import_promises2.realpath)(rawPath).catch(() => null);
1626
+ if (!real || (0, import_node_path2.dirname)(real) === real || real === home)
1627
+ return;
1628
+ if (configDir && insideOrEqual(configDir, real))
1629
+ return;
1630
+ const existing = roots.get(real);
1631
+ if (!existing)
1632
+ roots.set(real, { path: real, name: label || (0, import_node_path2.basename)(real), active });
1633
+ else if (active)
1634
+ existing.active = true;
1635
+ };
1636
+ for (const raw of (process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter).filter(Boolean)) {
1637
+ await addRoot(uriToPath(raw) || (0, import_node_path2.resolve)(raw), true);
1638
+ }
1639
+ for (const uri of extraWorkspaceUris) {
1640
+ if (typeof uri === "string" && uri.trim())
1641
+ await addRoot(uriToPath(uri) || (0, import_node_path2.resolve)(uri.trim()), true);
1642
+ }
1643
+ for (const [path, name] of sessionWorkspaces)
1644
+ await addRoot(path, true, name);
1645
+ const target = await readTargetSelection();
1646
+ if (target)
1647
+ await addRoot(target.workspace, roots.size === 0);
1648
+ for (const project of await discoverAntigravityProjects())
1649
+ await addRoot(project.path, false, project.name);
1650
+ if (roots.size === 0)
1651
+ await addRoot(process.cwd(), true);
1652
+ return { roots: [...roots.values()], target };
1653
+ }
1654
+ async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], registerOutside = false) {
1655
+ if (typeof candidatePath !== "string" || !candidatePath.trim()) {
1656
+ throw new Error(say("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002", "No Markdown file was given."));
1657
+ }
1658
+ const { roots, target } = await allowedRoots(extraWorkspaceUris);
1659
+ const trimmed = candidatePath.trim();
1660
+ let raw = uriToPath(trimmed);
1661
+ if (!raw) {
1662
+ const base = roots.find((r2) => r2.active)?.path || roots[0]?.path || process.cwd();
1663
+ raw = (0, import_node_path2.isAbsolute)(trimmed) ? (0, import_node_path2.resolve)(trimmed) : (0, import_node_path2.resolve)(base, trimmed);
1664
+ }
1665
+ const notMarkdown = () => new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
1666
+ if (!/\.md$/i.test(raw))
1667
+ throw notMarkdown();
1668
+ const info = await (0, import_promises2.lstat)(raw).catch(() => null);
1669
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
1670
+ 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."));
1671
+ }
1672
+ const real = await (0, import_promises2.realpath)(raw);
1673
+ if (!/\.md$/i.test(real))
1674
+ throw notMarkdown();
1675
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1676
+ const brainRoot = await (0, import_promises2.realpath)((0, import_node_path2.join)(home, ".gemini", "antigravity", "brain")).catch(() => null);
1677
+ const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !hasHiddenSegment(brainRoot, real) && !await hasSymlinkUnderRoot(brainRoot, raw));
1678
+ 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."));
1679
+ 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."));
1680
+ if (!inBrainArtifact && insideOrEqual(home, real) && hasHiddenSegment(home, real))
1681
+ throw hiddenError();
1682
+ const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, real));
1683
+ if (!inBrainArtifact && !(target && target.file === real) && !matchedRoot) {
1684
+ if (!registerOutside) {
1685
+ 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."));
1686
+ }
1687
+ const project = await findProjectRoot(real);
1688
+ if (await hasSymlinkUnderRoot(project, raw))
1689
+ throw symlinkError();
1690
+ if (hasHiddenSegment(project, real))
1691
+ throw hiddenError();
1692
+ sessionWorkspaces.set(project, (0, import_node_path2.basename)(project));
1693
+ return real;
1694
+ }
1695
+ if (matchedRoot) {
1696
+ if (await hasSymlinkUnderRoot(matchedRoot.path, raw))
1697
+ throw symlinkError();
1698
+ if (hasHiddenSegment(matchedRoot.path, real))
1699
+ throw hiddenError();
1700
+ }
1701
+ return real;
1702
+ }
1703
+ return { allowedRoots, assertAllowedFile };
1704
+ }
1705
+ var import_promises2, import_node_os2, import_node_path2, import_node_url, say, MAX_MARKDOWN_BYTES, SKIP_SCAN_DIRS, MARKMAP_RE;
1706
+ var init_workspace_fs = __esm({
1707
+ "packages/cli/dist/workspace-fs.js"() {
1708
+ "use strict";
1709
+ import_promises2 = require("node:fs/promises");
1710
+ import_node_os2 = require("node:os");
1711
+ import_node_path2 = require("node:path");
1712
+ import_node_url = require("node:url");
1713
+ init_license();
1714
+ say = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1715
+ MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
1716
+ SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
1717
+ ".git",
1718
+ ".hg",
1719
+ ".svn",
1720
+ "node_modules",
1721
+ "dist",
1722
+ "dist-codex",
1723
+ "dist-workbuddy",
1724
+ "build",
1725
+ "out",
1726
+ ".next",
1727
+ ".nuxt",
1728
+ ".agents",
1729
+ ".agent",
1730
+ ".gemini",
1731
+ ".codex",
1732
+ ".venv",
1733
+ "venv",
1734
+ "target",
1735
+ "coverage",
1736
+ ".tmp"
1737
+ ]);
1738
+ MARKMAP_RE = /\.markmap\.md$/i;
1739
+ }
1740
+ });
1741
+
1742
+ // packages/cli/dist/server.js
1274
1743
  function docName(path) {
1275
- return (0, import_node_path2.basename)(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1744
+ return (0, import_node_path3.basename)(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1276
1745
  }
1277
1746
  function viewStateFile(key) {
1278
- const base = process.env.INKMAP_HOME ?? (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap");
1279
- return (0, import_node_path2.join)(base, "view-state", hash(key) + ".json");
1747
+ const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1748
+ return (0, import_node_path3.join)(base, "view-state", hash(key) + ".json");
1280
1749
  }
1281
1750
  async function readDiskViewState(key) {
1282
1751
  try {
1283
- return sanitizeViewState(JSON.parse(await (0, import_promises2.readFile)(viewStateFile(key), "utf8")));
1752
+ return sanitizeViewState(JSON.parse(await (0, import_promises3.readFile)(viewStateFile(key), "utf8")));
1284
1753
  } catch {
1285
1754
  return void 0;
1286
1755
  }
1287
1756
  }
1288
1757
  async function writeDiskViewState(key, state) {
1289
1758
  const target = viewStateFile(key);
1290
- await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(target), { recursive: true, mode: 448 });
1759
+ await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(target), { recursive: true, mode: 448 });
1291
1760
  const temp = `${target}.${process.pid}.${Date.now()}`;
1292
1761
  try {
1293
- await (0, import_promises2.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1294
- await (0, import_promises2.rename)(temp, target);
1762
+ await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1763
+ await (0, import_promises3.rename)(temp, target);
1295
1764
  } finally {
1296
- await (0, import_promises2.rm)(temp, { force: true }).catch(() => {
1765
+ await (0, import_promises3.rm)(temp, { force: true }).catch(() => {
1297
1766
  });
1298
1767
  }
1299
1768
  }
1300
1769
  async function fileSource(file2, log = () => {
1301
1770
  }) {
1302
- const path = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(file2)).catch(() => (0, import_node_path2.resolve)(file2));
1303
- if (!(await (0, import_promises2.stat)(path)).isFile())
1771
+ const path = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(file2)).catch(() => (0, import_node_path3.resolve)(file2));
1772
+ if (!(await (0, import_promises3.stat)(path)).isFile())
1304
1773
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1305
- const dir = (0, import_node_path2.dirname)(path);
1774
+ const dir = (0, import_node_path3.dirname)(path);
1306
1775
  return {
1307
1776
  name: docName(path),
1308
1777
  key: path,
1309
1778
  dir,
1310
- read: () => (0, import_promises2.readFile)(path, "utf8"),
1779
+ read: () => (0, import_promises3.readFile)(path, "utf8"),
1311
1780
  async write(md) {
1312
- await (0, import_promises2.writeFile)(path, md, "utf8");
1781
+ await (0, import_promises3.writeFile)(path, md, "utf8");
1313
1782
  log(`\u5DF2\u5199\u56DE ${path}`);
1314
1783
  },
1315
1784
  watch(onChange) {
1316
1785
  const watcher = (0, import_node_fs.watch)(dir, (_2, changed) => {
1317
- if (!changed || changed === (0, import_node_path2.basename)(path))
1786
+ if (!changed || changed === (0, import_node_path3.basename)(path))
1318
1787
  onChange();
1319
1788
  });
1789
+ watcher.on("error", () => {
1790
+ });
1320
1791
  return () => watcher.close();
1321
1792
  },
1322
1793
  readView: () => readDiskViewState(path),
@@ -1324,8 +1795,15 @@ async function fileSource(file2, log = () => {
1324
1795
  };
1325
1796
  }
1326
1797
  function within(root, rel) {
1327
- const base = root.endsWith(import_node_path2.sep) ? root : root + import_node_path2.sep;
1328
- const full = (0, import_node_path2.normalize)((0, import_node_path2.join)(root, decodeURIComponent(rel)));
1798
+ let decoded;
1799
+ try {
1800
+ decoded = decodeURIComponent(rel);
1801
+ } catch {
1802
+ return null;
1803
+ }
1804
+ const resolvedRoot = (0, import_node_path3.resolve)(root);
1805
+ const base = resolvedRoot.endsWith(import_node_path3.sep) ? resolvedRoot : resolvedRoot + import_node_path3.sep;
1806
+ const full = (0, import_node_path3.normalize)((0, import_node_path3.join)(resolvedRoot, decoded));
1329
1807
  return full.startsWith(base) ? full : null;
1330
1808
  }
1331
1809
  async function openBrowserWindow(url2) {
@@ -1354,7 +1832,7 @@ async function openBrowserWindow(url2) {
1354
1832
  await run("xdg-open", [url2]);
1355
1833
  }
1356
1834
  async function serve({ source: initialSource, webRoot, port = 4377, host = "127.0.0.1", log = () => {
1357
- }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1835
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1358
1836
  if (sidebar && host !== "127.0.0.1")
1359
1837
  throw new Error("The sidebar bridge requires loopback.");
1360
1838
  const prefix = sidebar ? `/s/${(0, import_node_crypto2.randomBytes)(24).toString("hex")}/` : "/";
@@ -1365,7 +1843,9 @@ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.
1365
1843
  let version2 = hash(current);
1366
1844
  let viewState = await activeSource.readView?.();
1367
1845
  const clients = /* @__PURE__ */ new Set();
1368
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1846
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1847
+ const allowedHosts = /* @__PURE__ */ new Set();
1848
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1369
1849
  const docState = () => ({
1370
1850
  name: activeSource.name,
1371
1851
  md: current,
@@ -1400,36 +1880,36 @@ data: ${JSON.stringify(data)}
1400
1880
  broadcast();
1401
1881
  }
1402
1882
  let pending;
1403
- let unwatch = activeSource.watch(() => {
1883
+ const scheduleRefresh = () => {
1404
1884
  clearTimeout(pending);
1405
- pending = setTimeout(async () => {
1406
- void serialized(refresh).catch(() => {
1407
- });
1408
- }, 80);
1409
- });
1885
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1886
+ }), 80);
1887
+ };
1888
+ let unwatch = activeSource.watch(scheduleRefresh);
1889
+ const canonicalActiveKey = async () => activeSource.key ? await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key) : void 0;
1410
1890
  async function collectWorkspaceFiles() {
1411
1891
  const roots = /* @__PURE__ */ new Map();
1412
- if (activeSource.key) {
1413
- const realKey = await (0, import_promises2.realpath)(activeSource.key).catch(() => activeSource.key);
1414
- const projRoot = await (0, import_promises2.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path2.dirname)(realKey));
1415
- roots.set(projRoot, { path: projRoot, name: (0, import_node_path2.basename)(projRoot), active: true });
1892
+ if (activeSource.key && !confineToWorkspaceRoots) {
1893
+ const realKey = await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key);
1894
+ const projRoot = await (0, import_promises3.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path3.dirname)(realKey));
1895
+ roots.set(projRoot, { path: projRoot, name: (0, import_node_path3.basename)(projRoot), active: true });
1416
1896
  }
1417
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter)].filter(Boolean);
1897
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter)].filter(Boolean);
1418
1898
  for (const raw of envRoots) {
1419
- const real = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(raw)).catch(() => null);
1899
+ const real = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(raw)).catch(() => null);
1420
1900
  if (real && !roots.has(real)) {
1421
- roots.set(real, { path: real, name: (0, import_node_path2.basename)(real), active: roots.size === 0 });
1901
+ roots.set(real, { path: real, name: (0, import_node_path3.basename)(real), active: roots.size === 0 });
1422
1902
  }
1423
1903
  }
1424
1904
  const items = [];
1425
1905
  const seen = /* @__PURE__ */ new Set();
1426
1906
  for (const root of roots.values()) {
1427
- const files = await scanProjectMarkdownFiles(root.path);
1907
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1428
1908
  for (const f2 of files) {
1429
1909
  if (seen.has(f2))
1430
1910
  continue;
1431
1911
  seen.add(f2);
1432
- const rel = (0, import_node_path2.relative)(root.path, f2);
1912
+ const rel = (0, import_node_path3.relative)(root.path, f2);
1433
1913
  items.push({
1434
1914
  path: f2,
1435
1915
  label: `${root.name} / ${rel}`,
@@ -1437,43 +1917,52 @@ data: ${JSON.stringify(data)}
1437
1917
  });
1438
1918
  }
1439
1919
  }
1440
- if (activeSource.key && !seen.has(activeSource.key)) {
1920
+ const activeReal = await canonicalActiveKey();
1921
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1441
1922
  items.unshift({
1442
1923
  path: activeSource.key,
1443
- label: `${(0, import_node_path2.basename)(activeSource.dir)} / ${(0, import_node_path2.basename)(activeSource.key)}`,
1924
+ label: `${(0, import_node_path3.basename)(activeSource.dir)} / ${(0, import_node_path3.basename)(activeSource.key)}`,
1444
1925
  group: "active"
1445
1926
  });
1446
1927
  }
1447
1928
  return { roots: [...roots.values()], files: items };
1448
1929
  }
1449
- async function switchSourceToFile(candidatePath) {
1450
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1451
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1452
- }
1453
- const realTarget = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(candidatePath));
1454
- const st = await (0, import_promises2.lstat)(realTarget);
1455
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1456
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1457
- }
1458
- const { roots } = await collectWorkspaceFiles();
1459
- if (roots.length > 0 && !roots.some((r2) => insideRoot(r2.path, realTarget))) {
1460
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1461
- }
1462
- if (activeSource.key === realTarget)
1930
+ const zh = () => detectOsLocale() === "zh";
1931
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1932
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1933
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1934
+ throw notMarkdown();
1935
+ const resolvedCandidate = (0, import_node_path3.resolve)(candidatePath);
1936
+ const rawStat = await (0, import_promises3.lstat)(resolvedCandidate).catch(() => null);
1937
+ const realTarget = await (0, import_promises3.realpath)(resolvedCandidate).catch(() => null);
1938
+ const targetStat = realTarget ? await (0, import_promises3.stat)(realTarget).catch(() => null) : null;
1939
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1940
+ 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.");
1941
+ }
1942
+ if (!/\.md$/i.test(realTarget))
1943
+ throw notMarkdown();
1944
+ if (!trustCaller) {
1945
+ const { roots } = await collectWorkspaceFiles();
1946
+ const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, realTarget));
1947
+ if (!matchedRoot) {
1948
+ 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.");
1949
+ }
1950
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1951
+ 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.");
1952
+ }
1953
+ }
1954
+ if (await canonicalActiveKey() === realTarget)
1463
1955
  return;
1956
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1957
+ const text = await next.read();
1958
+ const nextView = await next.readView?.();
1464
1959
  clearTimeout(pending);
1465
1960
  unwatch();
1466
- activeSource = await fileSource(realTarget, log);
1467
- current = await activeSource.read();
1468
- version2 = hash(current);
1469
- viewState = await activeSource.readView?.();
1470
- unwatch = activeSource.watch(() => {
1471
- clearTimeout(pending);
1472
- pending = setTimeout(async () => {
1473
- void serialized(refresh).catch(() => {
1474
- });
1475
- }, 80);
1476
- });
1961
+ activeSource = next;
1962
+ current = text;
1963
+ version2 = hash(text);
1964
+ viewState = nextView;
1965
+ unwatch = activeSource.watch(scheduleRefresh);
1477
1966
  broadcast();
1478
1967
  }
1479
1968
  const json2 = (res, status, body) => {
@@ -1486,7 +1975,7 @@ data: ${JSON.stringify(data)}
1486
1975
  req.on("data", (c) => {
1487
1976
  size += c.length;
1488
1977
  if (size > MAX_BODY) {
1489
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1978
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1490
1979
  req.destroy();
1491
1980
  } else
1492
1981
  chunks.push(c);
@@ -1498,16 +1987,23 @@ data: ${JSON.stringify(data)}
1498
1987
  if (!full)
1499
1988
  return json2(res, 403, { error: "forbidden" });
1500
1989
  try {
1501
- const ext = (0, import_node_path2.extname)(full).toLowerCase();
1990
+ const ext = (0, import_node_path3.extname)(full).toLowerCase();
1502
1991
  if (ext === ".html") {
1503
1992
  const osLoc = detectOsLocale();
1504
- const htmlText = (await (0, import_promises2.readFile)(full, "utf8")).replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1993
+ const htmlText = (await (0, import_promises3.readFile)(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1505
1994
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1506
1995
  res.end(htmlText, "utf8");
1507
1996
  return;
1508
1997
  }
1509
- const body = await (0, import_promises2.readFile)(full);
1510
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1998
+ const body = await (0, import_promises3.readFile)(full);
1999
+ const headers = {
2000
+ "content-type": TYPES[ext] ?? "application/octet-stream",
2001
+ "cache-control": sidebar ? "no-store" : "no-cache"
2002
+ };
2003
+ if (ext === ".svg") {
2004
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
2005
+ }
2006
+ res.writeHead(200, headers);
1511
2007
  res.end(body);
1512
2008
  } catch {
1513
2009
  json2(res, 404, { error: "not found" });
@@ -1516,18 +2012,27 @@ data: ${JSON.stringify(data)}
1516
2012
  const server = (0, import_node_http.createServer)(async (req, res) => {
1517
2013
  try {
1518
2014
  const url2 = new URL(req.url ?? "/", "http://localhost");
2015
+ const reqHost = req.headers.host ?? "";
2016
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1519
2017
  if (sidebar) {
1520
2018
  res.setHeader("Referrer-Policy", "no-referrer");
1521
2019
  res.setHeader("X-Content-Type-Options", "nosniff");
1522
2020
  res.setHeader("Cache-Control", "no-store");
1523
2021
  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'");
1524
- if (req.headers.host !== `127.0.0.1:${bound}` || !url2.pathname.startsWith(prefix))
2022
+ if (reqHost !== `127.0.0.1:${bound}` || !url2.pathname.startsWith(prefix))
1525
2023
  return json2(res, 404, { error: "not found" });
1526
2024
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1527
2025
  return json2(res, 403, { error: "forbidden" });
1528
2026
  }
1529
2027
  url2.pathname = "/" + url2.pathname.slice(prefix.length);
2028
+ } else if (!hostAllowed) {
2029
+ return json2(res, 403, { error: "forbidden" });
1530
2030
  }
2031
+ const sameOriginWrite = () => {
2032
+ const origin = req.headers.origin;
2033
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
2034
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
2035
+ };
1531
2036
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url2.pathname)) {
1532
2037
  res.writeHead(302, { Location: "/" + url2.search });
1533
2038
  return res.end();
@@ -1551,6 +2056,8 @@ data: ${JSON.stringify(data)}
1551
2056
  });
1552
2057
  }
1553
2058
  if (url2.pathname === "/api/view" && req.method === "PUT") {
2059
+ if (!sameOriginWrite())
2060
+ return json2(res, 403, { error: "forbidden" });
1554
2061
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1555
2062
  if (cleaned) {
1556
2063
  viewState = cleaned;
@@ -1560,9 +2067,11 @@ data: ${JSON.stringify(data)}
1560
2067
  return json2(res, 200, { ok: true });
1561
2068
  }
1562
2069
  if (url2.pathname === "/api/doc" && req.method === "PUT") {
2070
+ if (!sameOriginWrite())
2071
+ return json2(res, 403, { error: "forbidden" });
1563
2072
  const { md, baseVersion } = JSON.parse(await readBody(req));
1564
2073
  if (typeof md !== "string")
1565
- return json2(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
2074
+ return json2(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1566
2075
  if (!hasAccess(await license?.state() ?? { pro: false }))
1567
2076
  return json2(res, 403, { error: "Inkmap trial expired" });
1568
2077
  return await serialized(async () => {
@@ -1574,31 +2083,24 @@ data: ${JSON.stringify(data)}
1574
2083
  current = md;
1575
2084
  version2 = hash(md);
1576
2085
  license?.track?.("doc_edit");
1577
- if (sidebar)
1578
- broadcast();
2086
+ broadcast();
1579
2087
  }
1580
2088
  return json2(res, 200, { version: version2 });
1581
2089
  });
1582
2090
  }
1583
2091
  if (url2.pathname === "/api/license" && req.method === "GET")
1584
2092
  return json2(res, 200, await license?.state() ?? { pro: false });
1585
- const sameOriginPost = () => {
1586
- const origin = req.headers.origin;
1587
- const reqHost = req.headers.host;
1588
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1589
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1590
- };
1591
2093
  if (url2.pathname === "/api/open" && req.method === "POST") {
1592
- if (!sameOriginPost())
2094
+ if (!sameOriginWrite())
1593
2095
  return json2(res, 403, { error: "forbidden" });
1594
2096
  const { file: file2 } = JSON.parse(await readBody(req));
1595
- await serialized(() => switchSourceToFile(String(file2 ?? "")));
2097
+ await serialized(() => switchSourceToFile(String(file2 ?? ""), false));
1596
2098
  license?.track?.("doc_open");
1597
2099
  const { files } = await collectWorkspaceFiles();
1598
2100
  return json2(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1599
2101
  }
1600
2102
  if (url2.pathname === "/api/telemetry" && req.method === "POST") {
1601
- if (!sameOriginPost())
2103
+ if (!sameOriginWrite())
1602
2104
  return json2(res, 403, { error: "forbidden" });
1603
2105
  const { event } = JSON.parse(await readBody(req));
1604
2106
  if (typeof event === "string" && event)
@@ -1606,45 +2108,43 @@ data: ${JSON.stringify(data)}
1606
2108
  return json2(res, 200, { ok: true });
1607
2109
  }
1608
2110
  if (url2.pathname === "/api/open-browser" && req.method === "POST") {
1609
- if (!sameOriginPost())
2111
+ if (!sameOriginWrite())
1610
2112
  return json2(res, 403, { error: "forbidden" });
1611
2113
  if (license && !hasAccess(await license.state())) {
1612
2114
  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." });
1613
2115
  }
1614
2116
  license?.track?.("feature_browser");
1615
2117
  if (!sidebar) {
1616
- const directUrl = `http://${host}:${bound}/`;
2118
+ const directUrl = `http://${urlHost}:${bound}/`;
1617
2119
  await openBrowserWindow(directUrl);
1618
2120
  return json2(res, 200, { ok: true, url: directUrl });
1619
2121
  }
1620
2122
  if (!browserCompanion) {
1621
- browserCompanion = (async () => {
1622
- const src = activeSource.key ? await fileSource(activeSource.key) : activeSource;
1623
- return serve({
1624
- source: src,
1625
- webRoot,
1626
- host: "127.0.0.1",
1627
- port: 0,
1628
- license,
1629
- ads,
1630
- sidebar: false,
1631
- loginOnly: false,
1632
- workspaceRoots
1633
- });
1634
- })();
2123
+ browserCompanion = serve({
2124
+ source: activeSource,
2125
+ webRoot,
2126
+ host: "127.0.0.1",
2127
+ port: 0,
2128
+ license,
2129
+ sidebar: false,
2130
+ workspaceRoots,
2131
+ confineToWorkspaceRoots,
2132
+ openSource,
2133
+ allowPurchase: canPurchase
2134
+ });
1635
2135
  browserCompanion.catch(() => {
1636
2136
  browserCompanion = null;
1637
2137
  });
1638
2138
  }
1639
2139
  const companion = await browserCompanion;
1640
2140
  if (activeSource.key)
1641
- await companion.switchToFile?.(activeSource.key).catch(() => {
2141
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1642
2142
  });
1643
2143
  await openBrowserWindow(companion.url);
1644
2144
  return json2(res, 200, { ok: true, url: companion.url });
1645
2145
  }
1646
2146
  if (url2.pathname === "/api/checkout" && req.method === "POST") {
1647
- if (!sameOriginPost())
2147
+ if (!sameOriginWrite())
1648
2148
  return json2(res, 403, { error: "forbidden" });
1649
2149
  const { mode, locale } = JSON.parse(await readBody(req));
1650
2150
  if (mode !== "buy" && mode !== "restore")
@@ -1656,7 +2156,7 @@ data: ${JSON.stringify(data)}
1656
2156
  return json2(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1657
2157
  }
1658
2158
  if (url2.pathname === "/api/order-pro" && req.method === "POST") {
1659
- if (!sameOriginPost())
2159
+ if (!sameOriginWrite())
1660
2160
  return json2(res, 403, { error: "forbidden" });
1661
2161
  if (!canPurchase)
1662
2162
  return json2(res, 403, { error: "forbidden" });
@@ -1668,7 +2168,7 @@ data: ${JSON.stringify(data)}
1668
2168
  return json2(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1669
2169
  }
1670
2170
  if (url2.pathname === "/api/phone-send" && req.method === "POST") {
1671
- if (!sameOriginPost())
2171
+ if (!sameOriginWrite())
1672
2172
  return json2(res, 403, { error: "forbidden" });
1673
2173
  if (!license || typeof license.sendPhoneCode !== "function")
1674
2174
  return json2(res, 501, { fallback: true });
@@ -1676,21 +2176,21 @@ data: ${JSON.stringify(data)}
1676
2176
  return json2(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1677
2177
  }
1678
2178
  if (url2.pathname === "/api/phone-verify" && req.method === "POST") {
1679
- if (!sameOriginPost())
2179
+ if (!sameOriginWrite())
1680
2180
  return json2(res, 403, { error: "forbidden" });
1681
2181
  if (!license || typeof license.signInByPhone !== "function")
1682
2182
  return json2(res, 501, { fallback: true });
1683
- const { phone, code } = JSON.parse(await readBody(req));
1684
- return json2(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
2183
+ const { phone, code, locale } = JSON.parse(await readBody(req));
2184
+ return json2(res, 200, {
2185
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
2186
+ });
1685
2187
  }
1686
2188
  if (url2.pathname === "/api/signout" && req.method === "POST") {
1687
- if (!sameOriginPost())
2189
+ if (!sameOriginWrite())
1688
2190
  return json2(res, 403, { error: "forbidden" });
1689
2191
  await license?.deactivate();
1690
2192
  return json2(res, 200, await license?.state() ?? { pro: false });
1691
2193
  }
1692
- if (url2.pathname === "/api/ads")
1693
- return json2(res, 200, sidebar ? [] : await ads?.() ?? []);
1694
2194
  if (url2.pathname === "/api/events") {
1695
2195
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1696
2196
  res.write(": connected\n\n");
@@ -1702,17 +2202,21 @@ data: ${JSON.stringify(data)}
1702
2202
  return void res.writeHead(204).end();
1703
2203
  if (url2.pathname.startsWith("/doc-assets/")) {
1704
2204
  let asset = within(activeSource.dir, url2.pathname.slice("/doc-assets/".length));
1705
- if (sidebar && asset) {
1706
- const root = await (0, import_promises2.realpath)(activeSource.dir);
1707
- asset = await (0, import_promises2.realpath)(asset).catch(() => null);
1708
- if (asset && (!asset.startsWith(root + import_node_path2.sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset)))
2205
+ if (asset) {
2206
+ const root = await (0, import_promises3.realpath)(activeSource.dir).catch(() => null);
2207
+ asset = await (0, import_promises3.realpath)(asset).catch(() => null);
2208
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
2209
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1709
2210
  asset = null;
1710
2211
  }
1711
2212
  return sendFile(res, asset);
1712
2213
  }
1713
2214
  return sendFile(res, within(webRoot, url2.pathname === "/" ? "index.html" : url2.pathname.slice(1)));
1714
2215
  } catch (err) {
1715
- json2(res, 500, { error: err instanceof Error ? err.message : String(err) });
2216
+ if (res.headersSent)
2217
+ return void res.end();
2218
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
2219
+ json2(res, status, { error: err instanceof Error ? err.message : String(err) });
1716
2220
  }
1717
2221
  });
1718
2222
  const listen = (p2) => new Promise((ok, fail) => {
@@ -1723,15 +2227,26 @@ data: ${JSON.stringify(data)}
1723
2227
  });
1724
2228
  });
1725
2229
  try {
1726
- bound = await listen(port);
2230
+ try {
2231
+ bound = await listen(port);
2232
+ } catch (err) {
2233
+ if (err.code !== "EADDRINUSE")
2234
+ throw err;
2235
+ bound = await listen(0);
2236
+ }
1727
2237
  } catch (err) {
1728
- if (err.code !== "EADDRINUSE")
1729
- throw err;
1730
- bound = await listen(0);
2238
+ clearTimeout(pending);
2239
+ unwatch();
2240
+ unlisten();
2241
+ throw err;
1731
2242
  }
1732
2243
  return {
1733
- url: `http://${host}:${bound}${prefix}`,
1734
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
2244
+ url: `http://${urlHost}:${bound}${prefix}`,
2245
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
2246
+ allowHost: (extraHost) => {
2247
+ if (extraHost)
2248
+ allowedHosts.add(extraHost.toLowerCase());
2249
+ },
1735
2250
  close: () => new Promise((done) => {
1736
2251
  clearTimeout(pending);
1737
2252
  unwatch();
@@ -1745,7 +2260,7 @@ data: ${JSON.stringify(data)}
1745
2260
  })
1746
2261
  };
1747
2262
  }
1748
- var import_node_child_process2, import_node_crypto2, import_node_fs, import_promises2, import_node_http, import_node_os2, import_node_path2, SKIP_SCAN_DIRS, MAX_BODY, TYPES, hash;
2263
+ 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;
1749
2264
  var init_server = __esm({
1750
2265
  "packages/cli/dist/server.js"() {
1751
2266
  "use strict";
@@ -1753,33 +2268,12 @@ var init_server = __esm({
1753
2268
  import_node_child_process2 = require("node:child_process");
1754
2269
  import_node_crypto2 = require("node:crypto");
1755
2270
  import_node_fs = require("node:fs");
1756
- import_promises2 = require("node:fs/promises");
2271
+ import_promises3 = require("node:fs/promises");
1757
2272
  import_node_http = require("node:http");
1758
- import_node_os2 = require("node:os");
1759
- import_node_path2 = require("node:path");
2273
+ import_node_os3 = require("node:os");
2274
+ import_node_path3 = require("node:path");
1760
2275
  init_license();
1761
- SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
1762
- ".git",
1763
- ".hg",
1764
- ".svn",
1765
- "node_modules",
1766
- "dist",
1767
- "dist-codex",
1768
- "dist-workbuddy",
1769
- "build",
1770
- "out",
1771
- ".next",
1772
- ".nuxt",
1773
- ".agents",
1774
- ".agent",
1775
- ".gemini",
1776
- ".codex",
1777
- ".venv",
1778
- "venv",
1779
- "target",
1780
- "coverage",
1781
- ".tmp"
1782
- ]);
2276
+ init_workspace_fs();
1783
2277
  MAX_BODY = 20 * 1024 * 1024;
1784
2278
  TYPES = {
1785
2279
  ".html": "text/html; charset=utf-8",
@@ -1791,11 +2285,22 @@ var init_server = __esm({
1791
2285
  ".jpeg": "image/jpeg",
1792
2286
  ".gif": "image/gif",
1793
2287
  ".webp": "image/webp",
2288
+ ".avif": "image/avif",
2289
+ ".bmp": "image/bmp",
2290
+ ".ico": "image/x-icon",
1794
2291
  ".woff2": "font/woff2",
1795
2292
  ".woff": "font/woff",
1796
2293
  ".ttf": "font/ttf",
1797
2294
  ".json": "application/json"
1798
2295
  };
2296
+ HttpError = class extends Error {
2297
+ status;
2298
+ constructor(status, message) {
2299
+ super(message);
2300
+ this.status = status;
2301
+ }
2302
+ };
2303
+ LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
1799
2304
  hash = (s) => (0, import_node_crypto2.createHash)("sha1").update(s).digest("hex");
1800
2305
  }
1801
2306
  });
@@ -34494,50 +34999,50 @@ var require_fast_uri = __commonJS({
34494
34999
  schemelessOptions.skipEscape = true;
34495
35000
  return serialize2(resolved, schemelessOptions);
34496
35001
  }
34497
- function resolveComponent(base, relative3, options, skipNormalization) {
35002
+ function resolveComponent(base, relative4, options, skipNormalization) {
34498
35003
  const target = {};
34499
35004
  if (!skipNormalization) {
34500
35005
  base = parse4(serialize2(base, options), options);
34501
- relative3 = parse4(serialize2(relative3, options), options);
35006
+ relative4 = parse4(serialize2(relative4, options), options);
34502
35007
  }
34503
35008
  options = options || {};
34504
- if (!options.tolerant && relative3.scheme) {
34505
- target.scheme = relative3.scheme;
34506
- target.userinfo = relative3.userinfo;
34507
- target.host = relative3.host;
34508
- target.port = relative3.port;
34509
- target.path = removeDotSegments(relative3.path || "");
34510
- target.query = relative3.query;
35009
+ if (!options.tolerant && relative4.scheme) {
35010
+ target.scheme = relative4.scheme;
35011
+ target.userinfo = relative4.userinfo;
35012
+ target.host = relative4.host;
35013
+ target.port = relative4.port;
35014
+ target.path = removeDotSegments(relative4.path || "");
35015
+ target.query = relative4.query;
34511
35016
  } else {
34512
- if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
34513
- target.userinfo = relative3.userinfo;
34514
- target.host = relative3.host;
34515
- target.port = relative3.port;
34516
- target.path = removeDotSegments(relative3.path || "");
34517
- target.query = relative3.query;
35017
+ if (relative4.userinfo !== void 0 || relative4.host !== void 0 || relative4.port !== void 0) {
35018
+ target.userinfo = relative4.userinfo;
35019
+ target.host = relative4.host;
35020
+ target.port = relative4.port;
35021
+ target.path = removeDotSegments(relative4.path || "");
35022
+ target.query = relative4.query;
34518
35023
  } else {
34519
- if (!relative3.path) {
35024
+ if (!relative4.path) {
34520
35025
  target.path = base.path;
34521
- if (relative3.query !== void 0) {
34522
- target.query = relative3.query;
35026
+ if (relative4.query !== void 0) {
35027
+ target.query = relative4.query;
34523
35028
  } else {
34524
35029
  target.query = base.query;
34525
35030
  }
34526
35031
  } else {
34527
- if (relative3.path[0] === "/") {
34528
- target.path = removeDotSegments(relative3.path);
35032
+ if (relative4.path[0] === "/") {
35033
+ target.path = removeDotSegments(relative4.path);
34529
35034
  } else {
34530
35035
  const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
34531
35036
  if (baseHasAuthority && !base.path) {
34532
- target.path = "/" + relative3.path;
35037
+ target.path = "/" + relative4.path;
34533
35038
  } else if (!base.path) {
34534
- target.path = relative3.path;
35039
+ target.path = relative4.path;
34535
35040
  } else {
34536
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
35041
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative4.path;
34537
35042
  }
34538
35043
  target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
34539
35044
  }
34540
- target.query = relative3.query;
35045
+ target.query = relative4.query;
34541
35046
  }
34542
35047
  target.userinfo = base.userinfo;
34543
35048
  target.host = base.host;
@@ -34545,7 +35050,7 @@ var require_fast_uri = __commonJS({
34545
35050
  }
34546
35051
  target.scheme = base.scheme;
34547
35052
  }
34548
- target.fragment = relative3.fragment;
35053
+ target.fragment = relative4.fragment;
34549
35054
  return target;
34550
35055
  }
34551
35056
  function equal(uriA, uriB, options) {
@@ -39749,286 +40254,50 @@ container holding the app. Specify either width or maxWidth, and either height o
39749
40254
  });
39750
40255
 
39751
40256
  // packages/cli/dist/mcp-files.js
39752
- function targetStateFile() {
39753
- const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
39754
- return (0, import_node_path3.join)(base, "antigravity-target.json");
39755
- }
39756
- function insideOrEqual(root, target) {
39757
- if (root === target)
39758
- return true;
39759
- const rel = (0, import_node_path3.relative)(root, target);
39760
- return Boolean(rel && !(0, import_node_path3.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path3.sep));
39761
- }
39762
- function hasHiddenSegment(root, target) {
39763
- const rel = (0, import_node_path3.relative)(root, target);
39764
- if (!rel || rel === ".")
39765
- return false;
39766
- return rel.split(import_node_path3.sep).some((part) => part.startsWith("."));
39767
- }
39768
- async function hasSymlinkUnderRoot(realRoot, rawTarget) {
39769
- let cur = rawTarget;
39770
- while (cur && cur !== (0, import_node_path3.dirname)(cur)) {
39771
- const st = await (0, import_promises3.lstat)(cur);
39772
- if (st.isSymbolicLink())
39773
- return true;
39774
- const realCur = await (0, import_promises3.realpath)(cur);
39775
- if (realCur === realRoot)
39776
- return false;
39777
- cur = (0, import_node_path3.dirname)(cur);
39778
- }
39779
- return false;
39780
- }
39781
- function uriToPath(uri) {
39782
- if (typeof uri !== "string" || !uri.trim())
39783
- return null;
39784
- const trimmed = uri.trim();
39785
- try {
39786
- if (trimmed.startsWith("file://"))
39787
- return (0, import_node_url.fileURLToPath)(trimmed);
39788
- if ((0, import_node_path3.isAbsolute)(trimmed))
39789
- return trimmed;
39790
- } catch {
39791
- }
39792
- return null;
39793
- }
39794
- async function findGitRoot(filePath) {
39795
- let cur = (0, import_node_path3.dirname)(filePath);
39796
- const home = await (0, import_promises3.realpath)((0, import_node_os3.homedir)()).catch(() => (0, import_node_os3.homedir)());
39797
- while (cur && cur !== (0, import_node_path3.dirname)(cur) && cur !== home) {
39798
- try {
39799
- await (0, import_promises3.lstat)((0, import_node_path3.join)(cur, ".git"));
39800
- return cur;
39801
- } catch {
39802
- }
39803
- cur = (0, import_node_path3.dirname)(cur);
39804
- }
39805
- return (0, import_node_path3.dirname)(filePath);
40257
+ function nextTargetSeq() {
40258
+ lastTargetSeq = Math.max(Date.now(), lastTargetSeq + 1);
40259
+ return lastTargetSeq;
39806
40260
  }
39807
40261
  async function writeTargetSelection(filePath, workspaceDir, extra) {
39808
- const real = await (0, import_promises3.realpath)(filePath);
39809
- const info = await (0, import_promises3.lstat)(real);
39810
- if (!info.isFile() || info.size > MAX_BYTES || !/\.md$/i.test(real)) {
39811
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
40262
+ const real = await (0, import_promises4.realpath)(filePath);
40263
+ const info = await (0, import_promises4.lstat)(real);
40264
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES || !/\.md$/i.test(real)) {
40265
+ 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."));
39812
40266
  }
39813
- const workspace = workspaceDir ? await (0, import_promises3.realpath)(workspaceDir).catch(() => findGitRoot(real)) : await findGitRoot(real);
40267
+ const workspace = workspaceDir ? await (0, import_promises4.realpath)(workspaceDir).catch(() => findProjectRoot(real)) : await findProjectRoot(real);
39814
40268
  const statePath = targetStateFile();
39815
- await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(statePath), { recursive: true, mode: 448 });
40269
+ await (0, import_promises4.mkdir)((0, import_node_path4.dirname)(statePath), { recursive: true, mode: 448 });
40270
+ const seq = nextTargetSeq();
39816
40271
  const payload = {
39817
40272
  file: real,
39818
40273
  workspace,
39819
- seq: Date.now(),
40274
+ seq,
39820
40275
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
39821
40276
  ...extra?.openInEditorPane && { openInEditorPane: true },
39822
- ...extra?.editorUrl && { editorUrl: extra.editorUrl }
40277
+ ...extra?.editorUrl && { editorUrl: extra.editorUrl },
40278
+ ...extra?.editorOnly && { editorOnly: true }
39823
40279
  };
39824
- const tmp = `${statePath}.${process.pid}.${Date.now()}`;
40280
+ const tmp = `${statePath}.${process.pid}.${seq}`;
39825
40281
  try {
39826
- await (0, import_promises3.writeFile)(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
39827
- await (0, import_promises3.rename)(tmp, statePath);
40282
+ await (0, import_promises4.writeFile)(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
40283
+ await (0, import_promises4.rename)(tmp, statePath);
39828
40284
  } catch (err) {
39829
- await (0, import_promises3.rm)(tmp, { force: true }).catch(() => {
40285
+ await (0, import_promises4.rm)(tmp, { force: true }).catch(() => {
39830
40286
  });
39831
40287
  throw err;
39832
40288
  }
39833
40289
  return payload;
39834
40290
  }
39835
- async function readTargetSelection() {
39836
- try {
39837
- const raw = JSON.parse(await (0, import_promises3.readFile)(targetStateFile(), "utf8"));
39838
- if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
39839
- return null;
39840
- const info = await (0, import_promises3.lstat)(raw.file);
39841
- if (!info.isFile() || info.size > MAX_BYTES)
39842
- return null;
39843
- const file2 = await (0, import_promises3.realpath)(raw.file);
39844
- if (file2 !== raw.file)
39845
- return null;
39846
- 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);
39847
- if (!insideOrEqual(workspace, file2))
39848
- return null;
39849
- return { file: file2, workspace, seq: Number(raw.seq) || 0 };
39850
- } catch {
39851
- return null;
39852
- }
39853
- }
39854
- async function discoverAntigravityProjects() {
39855
- 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");
39856
- const roots = [];
39857
- let entries = [];
39858
- try {
39859
- entries = await (0, import_promises3.readdir)(projectsDir);
39860
- } catch {
39861
- return roots;
39862
- }
39863
- for (const name of entries) {
39864
- if (!name.endsWith(".json"))
39865
- continue;
39866
- try {
39867
- const data = JSON.parse(await (0, import_promises3.readFile)((0, import_node_path3.join)(projectsDir, name), "utf8"));
39868
- const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
39869
- for (const r2 of resources) {
39870
- const uri = r2?.gitFolder?.folderUri || r2?.folderUri;
39871
- const p2 = uriToPath(uri);
39872
- if (!p2)
39873
- continue;
39874
- const real = await (0, import_promises3.realpath)(p2).catch(() => null);
39875
- if (real)
39876
- roots.push({ path: real, name: String(data.name || (0, import_node_path3.basename)(real)) });
39877
- }
39878
- } catch {
39879
- }
39880
- }
39881
- return roots;
39882
- }
39883
- async function scanMarkdownFiles(rootDir) {
39884
- const found = [];
39885
- async function walk(dir, depth) {
39886
- if (depth > MAX_SCAN_DEPTH || found.length >= MAX_FILES)
39887
- return;
39888
- let entries;
39889
- try {
39890
- entries = await (0, import_promises3.readdir)(dir, { withFileTypes: true });
39891
- } catch {
39892
- return;
39893
- }
39894
- for (const entry of entries) {
39895
- if (found.length >= MAX_FILES)
39896
- break;
39897
- if (entry.name.startsWith("."))
39898
- continue;
39899
- const full = (0, import_node_path3.join)(dir, entry.name);
39900
- if (entry.isDirectory()) {
39901
- if (!SKIP_DIRS.has(entry.name))
39902
- await walk(full, depth + 1);
39903
- } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
39904
- try {
39905
- const info = await (0, import_promises3.lstat)(full);
39906
- if (info.isFile() && info.size <= MAX_BYTES) {
39907
- const real = await (0, import_promises3.realpath)(full);
39908
- if (real === full && insideOrEqual(rootDir, real)) {
39909
- found.push({ path: real, mtimeMs: info.mtimeMs });
39910
- }
39911
- }
39912
- } catch {
39913
- }
39914
- }
39915
- }
39916
- }
39917
- await walk(rootDir, 0);
39918
- found.sort((a, b) => {
39919
- const aMarkmap = /\.markmap\.md$/i.test(a.path) ? 0 : 1;
39920
- const bMarkmap = /\.markmap\.md$/i.test(b.path) ? 0 : 1;
39921
- if (aMarkmap !== bMarkmap)
39922
- return aMarkmap - bMarkmap;
39923
- if (Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
39924
- return b.mtimeMs - a.mtimeMs;
39925
- return a.path.localeCompare(b.path);
39926
- });
39927
- return found;
39928
- }
39929
40291
  function createMcpWorkspaceManager() {
39930
40292
  let activeFile = null;
39931
40293
  let internalSeq = 0;
39932
- const sessionWorkspaces = /* @__PURE__ */ new Map();
40294
+ const serialized = createSerialQueue();
40295
+ const access = createWorkspaceAccess();
39933
40296
  async function allowedRoots(extraWorkspaceUris = []) {
39934
- const roots = /* @__PURE__ */ new Map();
39935
- const home = await (0, import_promises3.realpath)((0, import_node_os3.homedir)()).catch(() => (0, import_node_os3.homedir)());
39936
- const configDir = await (0, import_promises3.realpath)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path3.join)(home, ".gemini", "config")).catch(() => "");
39937
- const addRoot = async (rawPath, active, label) => {
39938
- if (!rawPath)
39939
- return;
39940
- const real = await (0, import_promises3.realpath)(rawPath).catch(() => null);
39941
- if (!real || real === import_node_path3.sep || real === home)
39942
- return;
39943
- if (configDir && insideOrEqual(configDir, real))
39944
- return;
39945
- if (!roots.has(real)) {
39946
- roots.set(real, { path: real, name: label || (0, import_node_path3.basename)(real), active });
39947
- } else if (active) {
39948
- roots.get(real).active = true;
39949
- }
39950
- };
39951
- const envRoots = (process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter).filter(Boolean);
39952
- for (const r2 of envRoots) {
39953
- await addRoot(uriToPath(r2) || (0, import_node_path3.resolve)(r2), true);
39954
- }
39955
- for (const uri of extraWorkspaceUris) {
39956
- await addRoot(uriToPath(uri) || (0, import_node_path3.resolve)(uri), true);
39957
- }
39958
- for (const [p2, name] of sessionWorkspaces) {
39959
- await addRoot(p2, true, name);
39960
- }
39961
- const target = await readTargetSelection();
39962
- if (target) {
39963
- await addRoot(target.workspace, roots.size === 0);
39964
- }
39965
- for (const proj of await discoverAntigravityProjects()) {
39966
- await addRoot(proj.path, false, proj.name);
39967
- }
39968
- if (roots.size === 0) {
39969
- await addRoot(process.cwd(), true);
39970
- }
39971
- const effectiveSeq = Math.max(internalSeq, target?.seq || 0);
39972
- return { roots: [...roots.values()], target, effectiveSeq };
39973
- }
39974
- async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], allowRegisterFromModel = false) {
39975
- if (!candidatePath?.trim())
39976
- throw new Error("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002");
39977
- const { roots, target } = await allowedRoots(extraWorkspaceUris);
39978
- const trimmed = candidatePath.trim();
39979
- let raw = uriToPath(trimmed);
39980
- if (!raw) {
39981
- if ((0, import_node_path3.isAbsolute)(trimmed)) {
39982
- raw = (0, import_node_path3.resolve)(trimmed);
39983
- } else {
39984
- const baseRoot = roots.find((r2) => r2.active)?.path || roots[0]?.path || process.cwd();
39985
- raw = (0, import_node_path3.resolve)(baseRoot, trimmed);
39986
- }
39987
- }
39988
- if (!/\.md$/i.test(raw))
39989
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
39990
- const info = await (0, import_promises3.lstat)(raw);
39991
- if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_BYTES) {
39992
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002");
39993
- }
39994
- const real = await (0, import_promises3.realpath)(raw);
39995
- if (!/\.md$/i.test(real)) {
39996
- throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u6216\u975E Markdown \u6587\u4EF6\u3002");
39997
- }
39998
- const home = await (0, import_promises3.realpath)((0, import_node_os3.homedir)()).catch(() => (0, import_node_os3.homedir)());
39999
- const brainRoot = await (0, import_promises3.realpath)((0, import_node_path3.join)(home, ".gemini", "antigravity", "brain")).catch(() => null);
40000
- const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !hasHiddenSegment(brainRoot, real));
40001
- if (!inBrainArtifact && insideOrEqual(home, real) && hasHiddenSegment(home, real)) {
40002
- throw new Error("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u914D\u7F6E\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
40003
- }
40004
- const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, real));
40005
- const permitted = inBrainArtifact || target && target.file === real || Boolean(matchedRoot);
40006
- if (!permitted) {
40007
- if (!allowRegisterFromModel) {
40008
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u6216\u9879\u76EE\u76EE\u5F55\u5185\u3002");
40009
- }
40010
- const ws = await findGitRoot(real);
40011
- if (await hasSymlinkUnderRoot(ws, raw)) {
40012
- throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
40013
- }
40014
- if (hasHiddenSegment(ws, real)) {
40015
- throw new Error("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
40016
- }
40017
- sessionWorkspaces.set(ws, (0, import_node_path3.basename)(ws));
40018
- const savedTarget = await writeTargetSelection(real, ws);
40019
- internalSeq = Math.max(internalSeq, savedTarget.seq);
40020
- return real;
40021
- }
40022
- if (matchedRoot) {
40023
- if (await hasSymlinkUnderRoot(matchedRoot.path, raw)) {
40024
- throw new Error("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
40025
- }
40026
- if (hasHiddenSegment(matchedRoot.path, real)) {
40027
- throw new Error("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002");
40028
- }
40029
- }
40030
- return real;
40297
+ const { roots, target } = await access.allowedRoots(extraWorkspaceUris);
40298
+ return { roots, target, effectiveSeq: Math.max(internalSeq, target?.seq || 0) };
40031
40299
  }
40300
+ const assertAllowedFile = access.assertAllowedFile;
40032
40301
  async function readDocState(filePath) {
40033
40302
  const source = await fileSource(filePath);
40034
40303
  const [md, viewState] = await Promise.all([source.read(), source.readView?.()]);
@@ -40047,25 +40316,25 @@ function createMcpWorkspaceManager() {
40047
40316
  const seen = /* @__PURE__ */ new Set();
40048
40317
  if (target && !seen.has(target.file)) {
40049
40318
  const owner = roots.find((r2) => insideOrEqual(r2.path, target.file));
40050
- const rel = owner ? (0, import_node_path3.relative)(owner.path, target.file) : (0, import_node_path3.basename)(target.file);
40319
+ const rel = owner ? (0, import_node_path4.relative)(owner.path, target.file) : (0, import_node_path4.basename)(target.file);
40051
40320
  items.push({
40052
40321
  path: target.file,
40053
- uri: (0, import_node_url.pathToFileURL)(target.file).href,
40322
+ uri: (0, import_node_url2.pathToFileURL)(target.file).href,
40054
40323
  label: owner && roots.length > 1 ? `${owner.name} / ${rel}` : rel,
40055
40324
  group: owner?.active ? "active" : "project"
40056
40325
  });
40057
40326
  seen.add(target.file);
40058
40327
  }
40059
40328
  for (const root of roots) {
40060
- const files = await scanMarkdownFiles(root.path);
40329
+ const files = await scanMarkdownFiles(root.path, { byRecent: true });
40061
40330
  for (const entry of files) {
40062
40331
  if (seen.has(entry.path))
40063
40332
  continue;
40064
40333
  seen.add(entry.path);
40065
- const rel = (0, import_node_path3.relative)(root.path, entry.path);
40334
+ const rel = (0, import_node_path4.relative)(root.path, entry.path);
40066
40335
  items.push({
40067
40336
  path: entry.path,
40068
- uri: (0, import_node_url.pathToFileURL)(entry.path).href,
40337
+ uri: (0, import_node_url2.pathToFileURL)(entry.path).href,
40069
40338
  label: roots.length > 1 ? `${root.name} / ${rel}` : rel,
40070
40339
  group: root.active ? "active" : "project"
40071
40340
  });
@@ -40074,7 +40343,7 @@ function createMcpWorkspaceManager() {
40074
40343
  return { files: items, target, targetSeq: effectiveSeq };
40075
40344
  }
40076
40345
  return {
40077
- async open(options = {}) {
40346
+ open: (options = {}) => serialized(async () => {
40078
40347
  const extraUris = options.workspace ? [options.workspace] : [];
40079
40348
  let explicitFile = null;
40080
40349
  if (options.path?.trim()) {
@@ -40085,10 +40354,11 @@ function createMcpWorkspaceManager() {
40085
40354
  });
40086
40355
  internalSeq = Math.max(internalSeq, saved.seq);
40087
40356
  } else {
40088
- internalSeq = Math.max(internalSeq + 1, Date.now());
40357
+ internalSeq = Math.max(internalSeq + 1, nextTargetSeq());
40089
40358
  }
40090
40359
  }
40091
40360
  const { files, target, targetSeq } = await collectFiles(extraUris);
40361
+ let finalTargetSeq = targetSeq;
40092
40362
  let chosen = explicitFile;
40093
40363
  if (!chosen && target?.file)
40094
40364
  chosen = target.file;
@@ -40101,16 +40371,17 @@ function createMcpWorkspaceManager() {
40101
40371
  if (chosen && !explicitFile && options.fromModel && options.openInEditorPane) {
40102
40372
  const saved = await writeTargetSelection(chosen, options.workspace, { openInEditorPane: true });
40103
40373
  internalSeq = Math.max(internalSeq, saved.seq);
40374
+ finalTargetSeq = Math.max(finalTargetSeq, saved.seq);
40104
40375
  }
40105
40376
  if (!chosen) {
40106
40377
  return {
40107
40378
  files,
40108
40379
  currentFile: null,
40109
40380
  currentFileUri: null,
40110
- targetSeq,
40381
+ targetSeq: finalTargetSeq,
40111
40382
  doc: {
40112
40383
  name: "Inkmap",
40113
- 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",
40384
+ 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"),
40114
40385
  version: "empty",
40115
40386
  writable: false
40116
40387
  }
@@ -40121,17 +40392,17 @@ function createMcpWorkspaceManager() {
40121
40392
  return {
40122
40393
  files,
40123
40394
  currentFile: chosen,
40124
- currentFileUri: (0, import_node_url.pathToFileURL)(chosen).href,
40125
- targetSeq,
40395
+ currentFileUri: (0, import_node_url2.pathToFileURL)(chosen).href,
40396
+ targetSeq: finalTargetSeq,
40126
40397
  doc
40127
40398
  };
40128
- },
40129
- async poll(options = {}) {
40399
+ }),
40400
+ poll: (options = {}) => serialized(async () => {
40130
40401
  const target = await readTargetSelection();
40131
40402
  const effectiveSeq = Math.max(internalSeq, target?.seq || 0);
40132
40403
  const clientSeq = Number(options.targetSeq) || 0;
40133
- const desiredFile = target && target.seq >= internalSeq ? target.file : activeFile;
40134
- if (desiredFile && effectiveSeq > clientSeq && desiredFile !== options.file) {
40404
+ const desiredFile = target && target.seq > clientSeq && !target.editorOnly ? target.file : null;
40405
+ if (desiredFile && desiredFile !== options.file) {
40135
40406
  activeFile = desiredFile;
40136
40407
  const [{ doc }, { files }] = await Promise.all([
40137
40408
  readDocState(desiredFile),
@@ -40139,7 +40410,7 @@ function createMcpWorkspaceManager() {
40139
40410
  ]);
40140
40411
  return {
40141
40412
  switchedFile: desiredFile,
40142
- currentFileUri: (0, import_node_url.pathToFileURL)(desiredFile).href,
40413
+ currentFileUri: (0, import_node_url2.pathToFileURL)(desiredFile).href,
40143
40414
  files,
40144
40415
  targetSeq: effectiveSeq,
40145
40416
  doc
@@ -40158,14 +40429,14 @@ function createMcpWorkspaceManager() {
40158
40429
  } catch {
40159
40430
  return { unchanged: true, targetSeq: effectiveSeq };
40160
40431
  }
40161
- },
40162
- async save(options) {
40432
+ }),
40433
+ save: (options) => serialized(async () => {
40163
40434
  const target = options.file || activeFile;
40164
40435
  if (!target)
40165
- throw new Error("\u672A\u9009\u62E9\u8981\u4FDD\u5B58\u7684 Markdown \u6587\u4EF6\u3002");
40436
+ throw new Error(say("\u672A\u9009\u62E9\u8981\u4FDD\u5B58\u7684 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected to save."));
40166
40437
  const file2 = await assertAllowedFile(target);
40167
- if (typeof options.md !== "string" || Buffer.byteLength(options.md, "utf8") > MAX_BYTES) {
40168
- throw new Error("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002");
40438
+ if (typeof options.md !== "string" || Buffer.byteLength(options.md, "utf8") > MAX_MARKDOWN_BYTES) {
40439
+ 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."));
40169
40440
  }
40170
40441
  const { source, doc } = await readDocState(file2);
40171
40442
  if (options.baseVersion && options.baseVersion !== doc.version) {
@@ -40176,8 +40447,8 @@ function createMcpWorkspaceManager() {
40176
40447
  }
40177
40448
  activeFile = file2;
40178
40449
  return { ok: true, version: sha1(options.md) };
40179
- },
40180
- async saveView(options) {
40450
+ }),
40451
+ saveView: (options) => serialized(async () => {
40181
40452
  const target = options.file || activeFile;
40182
40453
  if (!target)
40183
40454
  return { ok: false };
@@ -40191,46 +40462,22 @@ function createMcpWorkspaceManager() {
40191
40462
  });
40192
40463
  }
40193
40464
  return { ok: true };
40194
- }
40465
+ })
40195
40466
  };
40196
40467
  }
40197
- 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;
40468
+ var import_node_crypto3, import_promises4, import_node_path4, import_node_url2, sha1, lastTargetSeq;
40198
40469
  var init_mcp_files = __esm({
40199
40470
  "packages/cli/dist/mcp-files.js"() {
40200
40471
  "use strict";
40201
40472
  import_node_crypto3 = require("node:crypto");
40202
- import_promises3 = require("node:fs/promises");
40203
- import_node_os3 = require("node:os");
40204
- import_node_path3 = require("node:path");
40205
- import_node_url = require("node:url");
40473
+ import_promises4 = require("node:fs/promises");
40474
+ import_node_path4 = require("node:path");
40475
+ import_node_url2 = require("node:url");
40206
40476
  init_dist();
40207
40477
  init_server();
40208
- MAX_BYTES = 5 * 1024 * 1024;
40209
- MAX_SCAN_DEPTH = 4;
40210
- MAX_FILES = 200;
40211
- SKIP_DIRS = /* @__PURE__ */ new Set([
40212
- ".git",
40213
- ".hg",
40214
- ".svn",
40215
- "node_modules",
40216
- "dist",
40217
- "dist-codex",
40218
- "dist-workbuddy",
40219
- "build",
40220
- "out",
40221
- ".next",
40222
- ".nuxt",
40223
- ".agents",
40224
- ".agent",
40225
- ".gemini",
40226
- ".codex",
40227
- ".venv",
40228
- "venv",
40229
- "target",
40230
- "coverage",
40231
- ".tmp"
40232
- ]);
40478
+ init_workspace_fs();
40233
40479
  sha1 = (text) => (0, import_node_crypto3.createHash)("sha1").update(text).digest("hex");
40480
+ lastTargetSeq = 0;
40234
40481
  }
40235
40482
  });
40236
40483
 
@@ -40241,33 +40488,49 @@ __export(codex_exports, {
40241
40488
  serveCodex: () => serveCodex
40242
40489
  });
40243
40490
  function resolveWebRoot() {
40244
- return WEB_ROOT_CANDIDATES.find((dir) => (0, import_node_fs2.existsSync)((0, import_node_path4.join)(dir, "index.html"))) ?? null;
40491
+ return WEB_ROOT_CANDIDATES.find((dir) => (0, import_node_fs2.existsSync)((0, import_node_path5.join)(dir, "index.html"))) ?? null;
40245
40492
  }
40246
40493
  function openSystemBrowser(url2) {
40247
40494
  if (process.env.INKMAP_NO_OPEN === "1")
40248
40495
  return;
40249
40496
  const [cmd, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url2]] : ["xdg-open", [url2]];
40250
- (0, import_node_child_process3.spawn)(cmd, args, { stdio: "ignore", detached: true }).unref();
40497
+ const child = (0, import_node_child_process3.spawn)(cmd, args, { stdio: "ignore", detached: true });
40498
+ child.on("error", () => {
40499
+ });
40500
+ child.unref();
40501
+ }
40502
+ async function validatedMarkdownFile(path) {
40503
+ if (!path || !/\.md$/i.test(path))
40504
+ throw new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
40505
+ const info = await (0, import_promises5.lstat)(path);
40506
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
40507
+ 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."));
40508
+ }
40509
+ const real = await (0, import_promises5.realpath)(path);
40510
+ const home = await (0, import_promises5.realpath)((0, import_node_os4.homedir)()).catch(() => (0, import_node_os4.homedir)());
40511
+ if (!/\.md$/i.test(real) || insideOrEqual(home, real) && hasHiddenSegment(home, real)) {
40512
+ throw new Error(say("\u4E0D\u652F\u6301\u8BBF\u95EE\u8BE5\u6587\u4EF6\u3002", "This file cannot be opened."));
40513
+ }
40514
+ return real;
40251
40515
  }
40252
40516
  async function createInkmapMcpServer(options = {}) {
40253
40517
  const loadHtml = async () => {
40254
- const raw = options.html ?? await (0, import_promises4.readFile)(HTML, "utf8").catch((error62) => {
40518
+ const raw = options.html ?? await (0, import_promises5.readFile)(HTML, "utf8").catch((error62) => {
40255
40519
  if (error62.code === "ENOENT") {
40256
40520
  throw new Error("MCP App editor assets are missing. Run npm run build:sidebars.");
40257
40521
  }
40258
40522
  throw error62;
40259
40523
  });
40260
40524
  const osLoc = detectOsLocale();
40261
- return raw.replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
40525
+ return raw.replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
40262
40526
  };
40263
40527
  await loadHtml();
40264
40528
  const billingOrigin2 = options.billingOrigin ?? (() => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN);
40265
40529
  const billing = licenseService(fileSessionStorage(), billingOrigin2, { loginOnly: true });
40266
40530
  let browserBilling;
40267
40531
  const fallbackEditors = /* @__PURE__ */ new Map();
40268
- const ads = adFeed(PRODUCT.adFeedUrl);
40269
40532
  const workspaces = createMcpWorkspaceManager();
40270
- const server = new McpServer({ name: "inkmap", version: "0.3.10" });
40533
+ const server = new McpServer({ name: "inkmap", version: INKMAP_VERSION });
40271
40534
  function isAntigravityHost() {
40272
40535
  const clientName = server.server.getClientVersion()?.name ?? "";
40273
40536
  if (/antigravity/i.test(clientName))
@@ -40305,9 +40568,9 @@ async function createInkmapMcpServer(options = {}) {
40305
40568
  const clientName = server.server.getClientVersion()?.name ?? "";
40306
40569
  let extDir = null;
40307
40570
  if (/cursor/i.test(clientName)) {
40308
- extDir = (0, import_node_path4.join)(process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".cursor"), "extensions");
40571
+ extDir = (0, import_node_path5.join)(process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".cursor"), "extensions");
40309
40572
  } else if (/visual studio code|vscode/i.test(clientName)) {
40310
- extDir = (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".vscode", "extensions");
40573
+ extDir = (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".vscode", "extensions");
40311
40574
  }
40312
40575
  if (!extDir || !(0, import_node_fs2.existsSync)(extDir))
40313
40576
  return false;
@@ -40327,12 +40590,12 @@ async function createInkmapMcpServer(options = {}) {
40327
40590
  async function waitForEditorBridgeAck(seq, timeoutMs = 280) {
40328
40591
  if (!seq)
40329
40592
  return false;
40330
- const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".inkmap");
40331
- const ackPath = (0, import_node_path4.join)(inkmapDir, "antigravity-target-ack.json");
40593
+ const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".inkmap");
40594
+ const ackPath = (0, import_node_path5.join)(inkmapDir, "antigravity-target-ack.json");
40332
40595
  const deadline = Date.now() + timeoutMs;
40333
40596
  while (Date.now() < deadline) {
40334
40597
  try {
40335
- const raw = JSON.parse(await (0, import_promises4.readFile)(ackPath, "utf8"));
40598
+ const raw = JSON.parse(await (0, import_promises5.readFile)(ackPath, "utf8"));
40336
40599
  if (raw && raw.ok === true && Number(raw.seq) >= seq) {
40337
40600
  return true;
40338
40601
  }
@@ -40356,9 +40619,7 @@ async function createInkmapMcpServer(options = {}) {
40356
40619
  webRoot,
40357
40620
  port: 0,
40358
40621
  license: browserBilling,
40359
- ads,
40360
40622
  sidebar: false,
40361
- loginOnly: false,
40362
40623
  ideWorkspace: false
40363
40624
  });
40364
40625
  })();
@@ -40366,7 +40627,7 @@ async function createInkmapMcpServer(options = {}) {
40366
40627
  pending.catch(() => fallbackEditors.delete("__workspace__"));
40367
40628
  }
40368
40629
  const served = await pending;
40369
- await served.switchToFile?.(filePath).catch(() => {
40630
+ await served.switchToFile?.(filePath, { trustCaller: true }).catch(() => {
40370
40631
  });
40371
40632
  if (launchSystemBrowser) {
40372
40633
  openSystemBrowser(served.url);
@@ -40440,7 +40701,7 @@ async function createInkmapMcpServer(options = {}) {
40440
40701
  currentFileUri: opened.currentFileUri,
40441
40702
  targetSeq: opened.targetSeq,
40442
40703
  license: { ...license },
40443
- ...openInRightEditor && { openedInEditorPane: true },
40704
+ ...(ackedByExtension || cursorHost) && { openedInEditorPane: true },
40444
40705
  ...ackedByExtension && { ackedByExtension: true },
40445
40706
  ...editorUrl && { editorUrl },
40446
40707
  ...includeDoc && { doc: opened.doc }
@@ -40497,7 +40758,7 @@ async function createInkmapMcpServer(options = {}) {
40497
40758
  _meta: appOnly
40498
40759
  }, async ({ file: file2, md, baseVersion }) => {
40499
40760
  if (!hasAccess(await billing.state())) {
40500
- 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");
40761
+ 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."));
40501
40762
  }
40502
40763
  const saved = await workspaces.save({ file: file2, md, baseVersion });
40503
40764
  if (saved.ok)
@@ -40525,13 +40786,14 @@ async function createInkmapMcpServer(options = {}) {
40525
40786
  _meta: appOnly
40526
40787
  }, async ({ file: file2 }) => {
40527
40788
  if (!hasAccess(await billing.state())) {
40528
- 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");
40789
+ 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."));
40529
40790
  }
40530
- const opened = await workspaces.open({ path: file2, fromModel: false });
40531
- if (!opened.currentFile)
40532
- throw new Error("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002");
40791
+ const hostFile = file2?.startsWith("file://") ? await validatedMarkdownFile(uriToPath(file2)) : null;
40792
+ const target = hostFile ?? (await workspaces.open({ path: file2, fromModel: false })).currentFile;
40793
+ if (!target)
40794
+ throw new Error(say("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected."));
40533
40795
  billing.track?.("feature_browser", 1, detectMcpHost());
40534
- const url2 = await openFallbackBrowserEditor(opened.currentFile);
40796
+ const url2 = await openFallbackBrowserEditor(target);
40535
40797
  return { content: [], structuredContent: { url: url2 ?? "" } };
40536
40798
  });
40537
40799
  server.registerTool("inkmap_focus_editor", {
@@ -40544,10 +40806,12 @@ async function createInkmapMcpServer(options = {}) {
40544
40806
  }, async ({ file: file2 }) => {
40545
40807
  const opened = await workspaces.open({ path: file2, fromModel: false });
40546
40808
  if (!opened.currentFile)
40547
- throw new Error("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002");
40809
+ throw new Error(say("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected."));
40548
40810
  const url2 = await openFallbackBrowserEditor(opened.currentFile, false);
40549
40811
  const payload = await writeTargetSelection(opened.currentFile, void 0, {
40550
40812
  openInEditorPane: true,
40813
+ // Asked for by one panel's UI: the IDE focuses the file, other open panels stay on their documents.
40814
+ editorOnly: true,
40551
40815
  ...url2 && { editorUrl: url2 }
40552
40816
  });
40553
40817
  const acked = await waitForEditorBridgeAck(payload.seq, 450);
@@ -40575,10 +40839,10 @@ async function createInkmapMcpServer(options = {}) {
40575
40839
  }, async ({ phone, locale }) => ({ content: [], structuredContent: { result: await billing.sendPhoneCode(phone, locale) } }));
40576
40840
  server.registerTool("inkmap_phone_verify", {
40577
40841
  title: "Verify phone sign-in code",
40578
- inputSchema: { phone: external_exports.string(), code: external_exports.string() },
40842
+ inputSchema: { phone: external_exports.string(), code: external_exports.string(), locale: external_exports.string().optional() },
40579
40843
  annotations: { destructiveHint: false },
40580
40844
  _meta: appOnly
40581
- }, async ({ phone, code }) => ({ content: [], structuredContent: { result: await billing.signInByPhone(phone, code) } }));
40845
+ }, async ({ phone, code, locale }) => ({ content: [], structuredContent: { result: await billing.signInByPhone(phone, code, locale) } }));
40582
40846
  server.registerTool("inkmap_disconnect_access", {
40583
40847
  title: "Disconnect Inkmap access",
40584
40848
  annotations: { destructiveHint: true },
@@ -40597,7 +40861,7 @@ async function serveCodex() {
40597
40861
  };
40598
40862
  await server.connect(transport);
40599
40863
  }
40600
- var import_node_child_process3, import_node_fs2, import_promises4, import_node_os4, import_node_path4, import_node_url2, UI, HTML, WEB_ROOT_CANDIDATES, INLINE_DOC_LIMIT, appOnly;
40864
+ 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;
40601
40865
  var init_codex = __esm({
40602
40866
  "packages/cli/dist/codex.js"() {
40603
40867
  "use strict";
@@ -40606,21 +40870,23 @@ var init_codex = __esm({
40606
40870
  init_server4();
40607
40871
  import_node_child_process3 = require("node:child_process");
40608
40872
  import_node_fs2 = require("node:fs");
40609
- import_promises4 = require("node:fs/promises");
40873
+ import_promises5 = require("node:fs/promises");
40610
40874
  import_node_os4 = require("node:os");
40611
- import_node_path4 = require("node:path");
40612
- import_node_url2 = require("node:url");
40875
+ import_node_path5 = require("node:path");
40876
+ import_node_url3 = require("node:url");
40613
40877
  init_zod();
40614
40878
  init_dist();
40615
40879
  init_license();
40616
40880
  init_mcp_files();
40881
+ init_version();
40882
+ init_workspace_fs();
40617
40883
  init_server();
40618
40884
  UI = "ui://inkmap/markdown.html";
40619
40885
  HTML = new URL("./codex.html", inkmapModuleUrl);
40620
40886
  WEB_ROOT_CANDIDATES = [
40621
- (0, import_node_url2.fileURLToPath)(new URL("./web/", inkmapModuleUrl)),
40622
- (0, import_node_url2.fileURLToPath)(new URL("./sidecars/inkmap/web/", inkmapModuleUrl)),
40623
- (0, import_node_url2.fileURLToPath)(new URL("../web/", inkmapModuleUrl))
40887
+ (0, import_node_url3.fileURLToPath)(new URL("./web/", inkmapModuleUrl)),
40888
+ (0, import_node_url3.fileURLToPath)(new URL("./sidecars/inkmap/web/", inkmapModuleUrl)),
40889
+ (0, import_node_url3.fileURLToPath)(new URL("../web/", inkmapModuleUrl))
40624
40890
  ];
40625
40891
  INLINE_DOC_LIMIT = 256 * 1024;
40626
40892
  appOnly = { ui: { visibility: ["app"] } };
@@ -40630,9 +40896,46 @@ var init_codex = __esm({
40630
40896
  // packages/cli/dist/install.js
40631
40897
  var install_exports = {};
40632
40898
  __export(install_exports, {
40633
- runInstall: () => runInstall,
40634
40899
  runInstallCli: () => runInstallCli
40635
40900
  });
40901
+ function quoteWinArg(arg) {
40902
+ return `"${arg.replace(/"/g, '""').replace(/%/g, '"^%"')}"`;
40903
+ }
40904
+ function probeCliCommand(cmd, args = ["--version"]) {
40905
+ try {
40906
+ if (process.platform === "win32" && !cmd.toLowerCase().endsWith(".exe")) {
40907
+ const commandLine = `"${[cmd, ...args].map(quoteWinArg).join(" ")}"`;
40908
+ const res = (0, import_node_child_process4.spawnSync)("cmd.exe", ["/d", "/s", "/c", commandLine], {
40909
+ stdio: "ignore",
40910
+ windowsVerbatimArguments: true,
40911
+ windowsHide: true
40912
+ });
40913
+ return res.status === 0;
40914
+ }
40915
+ return (0, import_node_child_process4.spawnSync)(cmd, args, { stdio: "ignore" }).status === 0;
40916
+ } catch {
40917
+ return false;
40918
+ }
40919
+ }
40920
+ function execCliSync(cmd, args, options = {}) {
40921
+ if (process.platform === "win32" && !cmd.toLowerCase().endsWith(".exe")) {
40922
+ const commandLine = `"${[cmd, ...args].map(quoteWinArg).join(" ")}"`;
40923
+ const res = (0, import_node_child_process4.spawnSync)("cmd.exe", ["/d", "/s", "/c", commandLine], {
40924
+ ...options,
40925
+ encoding: options.encoding ?? "utf8",
40926
+ stdio: options.stdio ?? "pipe",
40927
+ windowsVerbatimArguments: true,
40928
+ windowsHide: true
40929
+ });
40930
+ if (res.error)
40931
+ throw res.error;
40932
+ if (res.status !== 0) {
40933
+ throw new Error(String(res.stderr || res.stdout || `${cmd} exited with code ${res.status}`).trim());
40934
+ }
40935
+ return String(res.stdout ?? "");
40936
+ }
40937
+ return (0, import_node_child_process4.execFileSync)(cmd, args, options) ?? "";
40938
+ }
40636
40939
  function crc32(buf) {
40637
40940
  let c = 4294967295;
40638
40941
  for (let i = 0; i < buf.length; i++) {
@@ -40724,47 +41027,47 @@ function isChineseTerminalLocale() {
40724
41027
  return detectOsLocale() === "zh";
40725
41028
  }
40726
41029
  function getInkmapHome() {
40727
- return process.env.INKMAP_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".inkmap");
41030
+ return process.env.INKMAP_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".inkmap");
40728
41031
  }
40729
41032
  function getClaudeDesktopDir() {
40730
41033
  if (process.env.INKMAP_CLAUDE_CONFIG_DIR)
40731
41034
  return process.env.INKMAP_CLAUDE_CONFIG_DIR;
40732
41035
  if (process.platform === "darwin") {
40733
- return (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Library", "Application Support", "Claude");
41036
+ return (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Library", "Application Support", "Claude");
40734
41037
  }
40735
41038
  if (process.platform === "win32") {
40736
- const appData = process.env.APPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Roaming");
40737
- return (0, import_node_path5.join)(appData, "Claude");
41039
+ const appData = process.env.APPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Roaming");
41040
+ return (0, import_node_path6.join)(appData, "Claude");
40738
41041
  }
40739
- const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".config");
40740
- return (0, import_node_path5.join)(xdg, "Claude");
41042
+ const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".config");
41043
+ return (0, import_node_path6.join)(xdg, "Claude");
40741
41044
  }
40742
41045
  function getCursorDir() {
40743
- return process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".cursor");
41046
+ return process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".cursor");
40744
41047
  }
40745
41048
  function getVscodeDir() {
40746
- return process.env.INKMAP_VSCODE_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".vscode");
41049
+ return process.env.INKMAP_VSCODE_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".vscode");
40747
41050
  }
40748
41051
  function getClaudeCodeConfigPath() {
40749
- return process.env.INKMAP_CLAUDE_CODE_CONFIG || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".claude.json");
41052
+ return process.env.INKMAP_CLAUDE_CODE_CONFIG || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".claude.json");
40750
41053
  }
40751
41054
  function getAntigravityConfigDir() {
40752
- return process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".gemini", "config");
41055
+ return process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".gemini", "config");
40753
41056
  }
40754
41057
  function findCursorCommand() {
40755
41058
  if (process.env.INKMAP_ISOLATED_DETECT)
40756
41059
  return null;
40757
- if ((0, import_node_child_process4.spawnSync)("cursor", ["--version"], { stdio: "ignore" }).status === 0)
41060
+ if (probeCliCommand("cursor"))
40758
41061
  return "cursor";
40759
41062
  if (process.platform === "darwin") {
40760
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40761
- const cmd = (0, import_node_path5.join)(dir, "Cursor.app/Contents/Resources/app/bin/cursor");
41063
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41064
+ const cmd = (0, import_node_path6.join)(dir, "Cursor.app/Contents/Resources/app/bin/cursor");
40762
41065
  if ((0, import_node_fs3.existsSync)(cmd))
40763
41066
  return cmd;
40764
41067
  }
40765
41068
  } else if (process.platform === "win32") {
40766
- const localApp = process.env.LOCALAPPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Local");
40767
- const cmd = (0, import_node_path5.join)(localApp, "Programs", "cursor", "resources", "app", "bin", "cursor.cmd");
41069
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41070
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "cursor", "resources", "app", "bin", "cursor.cmd");
40768
41071
  if ((0, import_node_fs3.existsSync)(cmd))
40769
41072
  return cmd;
40770
41073
  }
@@ -40773,17 +41076,17 @@ function findCursorCommand() {
40773
41076
  function findVscodeCommand() {
40774
41077
  if (process.env.INKMAP_ISOLATED_DETECT)
40775
41078
  return null;
40776
- if ((0, import_node_child_process4.spawnSync)("code", ["--version"], { stdio: "ignore" }).status === 0)
41079
+ if (probeCliCommand("code"))
40777
41080
  return "code";
40778
41081
  if (process.platform === "darwin") {
40779
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40780
- const cmd = (0, import_node_path5.join)(dir, "Visual Studio Code.app/Contents/Resources/app/bin/code");
41082
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41083
+ const cmd = (0, import_node_path6.join)(dir, "Visual Studio Code.app/Contents/Resources/app/bin/code");
40781
41084
  if ((0, import_node_fs3.existsSync)(cmd))
40782
41085
  return cmd;
40783
41086
  }
40784
41087
  } else if (process.platform === "win32") {
40785
- const localApp = process.env.LOCALAPPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Local");
40786
- const cmd = (0, import_node_path5.join)(localApp, "Programs", "Microsoft VS Code", "bin", "code.cmd");
41088
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41089
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "Microsoft VS Code", "bin", "code.cmd");
40787
41090
  if ((0, import_node_fs3.existsSync)(cmd))
40788
41091
  return cmd;
40789
41092
  }
@@ -40793,11 +41096,11 @@ function findCodexCommand() {
40793
41096
  if (process.env.INKMAP_CODEX_BIN) {
40794
41097
  return (0, import_node_fs3.existsSync)(process.env.INKMAP_CODEX_BIN) ? process.env.INKMAP_CODEX_BIN : null;
40795
41098
  }
40796
- if ((0, import_node_child_process4.spawnSync)("codex", ["--version"], { stdio: "ignore" }).status === 0)
41099
+ if (probeCliCommand("codex"))
40797
41100
  return "codex";
40798
41101
  if (process.platform === "darwin") {
40799
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40800
- const cmd = (0, import_node_path5.join)(dir, "ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
41102
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41103
+ const cmd = (0, import_node_path6.join)(dir, "ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
40801
41104
  if ((0, import_node_fs3.existsSync)(cmd))
40802
41105
  return cmd;
40803
41106
  }
@@ -40805,7 +41108,7 @@ function findCodexCommand() {
40805
41108
  return null;
40806
41109
  }
40807
41110
  function getDshHome() {
40808
- return process.env.DSH_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".dsh");
41111
+ return process.env.DSH_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".dsh");
40809
41112
  }
40810
41113
  function findDshCommand() {
40811
41114
  if (process.env.INKMAP_DSH_BIN) {
@@ -40813,17 +41116,17 @@ function findDshCommand() {
40813
41116
  }
40814
41117
  if (process.env.INKMAP_ISOLATED_DETECT)
40815
41118
  return null;
40816
- if ((0, import_node_child_process4.spawnSync)("dsh", ["--version"], { stdio: "ignore" }).status === 0)
41119
+ if (probeCliCommand("dsh"))
40817
41120
  return "dsh";
40818
41121
  if (process.platform === "darwin") {
40819
- for (const dir of ["/Applications", (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Applications")]) {
40820
- const cmd = (0, import_node_path5.join)(dir, "DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
41122
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41123
+ const cmd = (0, import_node_path6.join)(dir, "DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
40821
41124
  if ((0, import_node_fs3.existsSync)(cmd))
40822
41125
  return cmd;
40823
41126
  }
40824
41127
  } else if (process.platform === "win32") {
40825
- const localApp = process.env.LOCALAPPDATA || (0, import_node_path5.join)((0, import_node_os5.homedir)(), "AppData", "Local");
40826
- const cmd = (0, import_node_path5.join)(localApp, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd");
41128
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41129
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd");
40827
41130
  if ((0, import_node_fs3.existsSync)(cmd))
40828
41131
  return cmd;
40829
41132
  }
@@ -40832,18 +41135,18 @@ function findDshCommand() {
40832
41135
  function detectInstalledTargets() {
40833
41136
  const found = [];
40834
41137
  const claudeDir = getClaudeDesktopDir();
40835
- 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")))) {
41138
+ 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")))) {
40836
41139
  found.push("claude");
40837
41140
  }
40838
41141
  const claudeCodeCfg = getClaudeCodeConfigPath();
40839
- if ((0, import_node_fs3.existsSync)(claudeCodeCfg) || !process.env.INKMAP_ISOLATED_DETECT && (0, import_node_child_process4.spawnSync)("claude", ["--version"], { stdio: "ignore" }).status === 0) {
41142
+ if ((0, import_node_fs3.existsSync)(claudeCodeCfg) || !process.env.INKMAP_ISOLATED_DETECT && probeCliCommand("claude")) {
40840
41143
  found.push("claude-code");
40841
41144
  }
40842
41145
  if ((0, import_node_fs3.existsSync)(getCursorDir()) || Boolean(findCursorCommand())) {
40843
41146
  found.push("cursor");
40844
41147
  }
40845
41148
  const agyDir = getAntigravityConfigDir();
40846
- 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"))) {
41149
+ 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"))) {
40847
41150
  found.push("antigravity");
40848
41151
  }
40849
41152
  if (!process.env.INKMAP_ISOLATED_DETECT && findCodexCommand()) {
@@ -40851,7 +41154,7 @@ function detectInstalledTargets() {
40851
41154
  } else if (process.env.INKMAP_CODEX_BIN && (0, import_node_fs3.existsSync)(process.env.INKMAP_CODEX_BIN)) {
40852
41155
  found.push("codex");
40853
41156
  }
40854
- 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)) {
41157
+ 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)) {
40855
41158
  found.push("deepseek");
40856
41159
  }
40857
41160
  return found;
@@ -40874,73 +41177,73 @@ function readJsonObject(filePath) {
40874
41177
  return parsed;
40875
41178
  }
40876
41179
  function writeJsonAtomic(filePath, data) {
40877
- (0, import_node_fs3.mkdirSync)((0, import_node_path5.dirname)(filePath), { recursive: true });
41180
+ (0, import_node_fs3.mkdirSync)((0, import_node_path6.dirname)(filePath), { recursive: true });
40878
41181
  const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
40879
41182
  (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
40880
41183
  (0, import_node_fs3.renameSync)(tmp, filePath);
40881
41184
  }
40882
41185
  function stageStandaloneMcpApp() {
40883
- const appDir = (0, import_node_path5.join)(getInkmapHome(), "mcp-app");
41186
+ const appDir = (0, import_node_path6.join)(getInkmapHome(), "mcp-app");
40884
41187
  (0, import_node_fs3.mkdirSync)(appDir, { recursive: true });
40885
- const bundledCli = (0, import_node_path5.join)(DIST_DIR, "cli.cjs");
40886
- const bundledHtml = (0, import_node_path5.join)(DIST_DIR, "codex.html");
40887
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
40888
- const monorepoAntigravity = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
41188
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41189
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41190
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41191
+ const monorepoAntigravity = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
40889
41192
  if ((0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml)) {
40890
- (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path5.join)(appDir, "cli.cjs"));
40891
- (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path5.join)(appDir, "codex.html"));
41193
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(appDir, "cli.cjs"));
41194
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(appDir, "codex.html"));
40892
41195
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
40893
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(appDir, "web"), { recursive: true, force: true });
40894
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(appDir, "web"), { recursive: true });
41196
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(appDir, "web"), { recursive: true, force: true });
41197
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(appDir, "web"), { recursive: true });
40895
41198
  }
40896
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(appDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41199
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(appDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
40897
41200
  for (const notice of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40898
- const src = (0, import_node_path5.join)(PKG_ROOT, notice);
41201
+ const src = (0, import_node_path6.join)(PKG_ROOT, notice);
40899
41202
  if ((0, import_node_fs3.existsSync)(src))
40900
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(appDir, notice));
41203
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(appDir, notice));
40901
41204
  }
40902
- return { serverScript: (0, import_node_path5.join)(appDir, "server.cjs"), appDir };
41205
+ return { serverScript: (0, import_node_path6.join)(appDir, "server.cjs"), appDir };
40903
41206
  }
40904
- 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"))) {
40905
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoAntigravity, "server.cjs"), (0, import_node_path5.join)(appDir, "server.cjs"));
40906
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoAntigravity, "codex.html"), (0, import_node_path5.join)(appDir, "codex.html"));
40907
- const sidecarWeb = (0, import_node_path5.join)(monorepoAntigravity, "sidecars", "inkmap", "web");
41207
+ 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"))) {
41208
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoAntigravity, "server.cjs"), (0, import_node_path6.join)(appDir, "server.cjs"));
41209
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoAntigravity, "codex.html"), (0, import_node_path6.join)(appDir, "codex.html"));
41210
+ const sidecarWeb = (0, import_node_path6.join)(monorepoAntigravity, "sidecars", "inkmap", "web");
40908
41211
  if ((0, import_node_fs3.existsSync)(sidecarWeb)) {
40909
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(appDir, "web"), { recursive: true, force: true });
40910
- (0, import_node_fs3.cpSync)(sidecarWeb, (0, import_node_path5.join)(appDir, "web"), { recursive: true });
41212
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(appDir, "web"), { recursive: true, force: true });
41213
+ (0, import_node_fs3.cpSync)(sidecarWeb, (0, import_node_path6.join)(appDir, "web"), { recursive: true });
40911
41214
  }
40912
41215
  for (const notice of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40913
- const src = (0, import_node_path5.join)(monorepoAntigravity, notice);
41216
+ const src = (0, import_node_path6.join)(monorepoAntigravity, notice);
40914
41217
  if ((0, import_node_fs3.existsSync)(src))
40915
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(appDir, notice));
41218
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(appDir, notice));
40916
41219
  }
40917
- return { serverScript: (0, import_node_path5.join)(appDir, "server.cjs"), appDir };
41220
+ return { serverScript: (0, import_node_path6.join)(appDir, "server.cjs"), appDir };
40918
41221
  }
40919
- const devBin = (0, import_node_path5.join)(PKG_ROOT, "bin", "inkmap.js");
41222
+ const devBin = (0, import_node_path6.join)(PKG_ROOT, "bin", "inkmap.js");
40920
41223
  if ((0, import_node_fs3.existsSync)(devBin) && (0, import_node_fs3.existsSync)(bundledHtml)) {
40921
41224
  return { serverScript: devBin, appDir };
40922
41225
  }
40923
41226
  throw new Error("\u672A\u627E\u5230\u5DF2\u6784\u5EFA\u7684 MCP App \u8D44\u6E90\uFF08codex.html\uFF09\u3002/ Built MCP App assets are missing.");
40924
41227
  }
40925
41228
  function installIdeExtension(editorDir, cliCmd) {
40926
- const vscodeBundle = (0, import_node_path5.join)(DIST_DIR, "bundles", "vscode");
40927
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
40928
- 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"))) {
41229
+ const vscodeBundle = (0, import_node_path6.join)(DIST_DIR, "bundles", "vscode");
41230
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41231
+ 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"))) {
40929
41232
  return null;
40930
41233
  }
40931
- const extPkg = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path5.join)(vscodeBundle, "package.json"), "utf8"));
40932
- const version2 = extPkg.version || "0.3.6";
40933
- const staging = (0, import_node_fs3.mkdtempSync)((0, import_node_path5.join)((0, import_node_os5.tmpdir)(), "inkmap-vsix-"));
41234
+ const extPkg = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path6.join)(vscodeBundle, "package.json"), "utf8"));
41235
+ const version2 = extPkg.version;
41236
+ const staging = (0, import_node_fs3.mkdtempSync)((0, import_node_path6.join)((0, import_node_os5.tmpdir)(), "inkmap-vsix-"));
40934
41237
  try {
40935
- const extStaging = (0, import_node_path5.join)(staging, "extension");
41238
+ const extStaging = (0, import_node_path6.join)(staging, "extension");
40936
41239
  (0, import_node_fs3.cpSync)(vscodeBundle, extStaging, { recursive: true });
40937
41240
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
40938
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(extStaging, "dist", "web"), { recursive: true });
41241
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(extStaging, "dist", "web"), { recursive: true });
40939
41242
  }
40940
41243
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md", "README.md"]) {
40941
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41244
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
40942
41245
  if ((0, import_node_fs3.existsSync)(src))
40943
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(extStaging, doc));
41246
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(extStaging, doc));
40944
41247
  }
40945
41248
  if (cliCmd) {
40946
41249
  const contentTypesXml = `<?xml version="1.0" encoding="utf-8"?>
@@ -40953,7 +41256,7 @@ function installIdeExtension(editorDir, cliCmd) {
40953
41256
  ];
40954
41257
  const walk = (dir, prefix) => {
40955
41258
  for (const item of (0, import_node_fs3.readdirSync)(dir, { withFileTypes: true })) {
40956
- const full = (0, import_node_path5.join)(dir, item.name);
41259
+ const full = (0, import_node_path6.join)(dir, item.name);
40957
41260
  const rel = `${prefix}/${item.name}`;
40958
41261
  if (item.isDirectory())
40959
41262
  walk(full, rel);
@@ -40962,23 +41265,65 @@ function installIdeExtension(editorDir, cliCmd) {
40962
41265
  }
40963
41266
  };
40964
41267
  walk(extStaging, "extension");
40965
- const vsixPath = (0, import_node_path5.join)(staging, `inkmap-${version2}.vsix`);
41268
+ const vsixPath = (0, import_node_path6.join)(staging, `inkmap-${version2}.vsix`);
40966
41269
  (0, import_node_fs3.writeFileSync)(vsixPath, buildZipBuffer(entries));
40967
41270
  try {
40968
- (0, import_node_child_process4.execFileSync)(cliCmd, ["--install-extension", vsixPath, "--force"], { stdio: "pipe" });
40969
- return (0, import_node_path5.join)(editorDir, "extensions", `inkmap.inkmap-vscode-${version2}`);
41271
+ execCliSync(cliCmd, ["--install-extension", vsixPath, "--force"], { stdio: "pipe" });
41272
+ return (0, import_node_path6.join)(editorDir, "extensions", `inkmap.inkmap-vscode-${version2}`);
40970
41273
  } catch {
40971
41274
  }
40972
41275
  }
40973
- const extRoot = (0, import_node_path5.join)(editorDir, "extensions");
41276
+ const extRoot = (0, import_node_path6.join)(editorDir, "extensions");
40974
41277
  (0, import_node_fs3.mkdirSync)(extRoot, { recursive: true });
40975
41278
  for (const old of (0, import_node_fs3.readdirSync)(extRoot)) {
40976
41279
  if (old.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
40977
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(extRoot, old), { recursive: true, force: true });
41280
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(extRoot, old), { recursive: true, force: true });
40978
41281
  }
40979
41282
  }
40980
- const dest = (0, import_node_path5.join)(extRoot, `inkmap.inkmap-vscode-${version2}`);
41283
+ const folderName = `inkmap.inkmap-vscode-${version2}`;
41284
+ const dest = (0, import_node_path6.join)(extRoot, folderName);
40981
41285
  (0, import_node_fs3.cpSync)(extStaging, dest, { recursive: true });
41286
+ try {
41287
+ const obsoletePath = (0, import_node_path6.join)(extRoot, ".obsolete");
41288
+ if ((0, import_node_fs3.existsSync)(obsoletePath)) {
41289
+ const obs = JSON.parse((0, import_node_fs3.readFileSync)(obsoletePath, "utf8"));
41290
+ let changedObs = false;
41291
+ for (const key of Object.keys(obs)) {
41292
+ if (key.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
41293
+ delete obs[key];
41294
+ changedObs = true;
41295
+ }
41296
+ }
41297
+ if (changedObs)
41298
+ writeJsonAtomic(obsoletePath, obs);
41299
+ }
41300
+ const registryPath = (0, import_node_path6.join)(extRoot, "extensions.json");
41301
+ const existingList = (0, import_node_fs3.existsSync)(registryPath) ? JSON.parse((0, import_node_fs3.readFileSync)(registryPath, "utf8")) : [];
41302
+ if (Array.isArray(existingList)) {
41303
+ const filtered = existingList.filter((item) => String(item?.identifier?.id ?? "").toLowerCase() !== "inkmap.inkmap-vscode");
41304
+ const destUrl = (0, import_node_url4.pathToFileURL)(dest);
41305
+ filtered.push({
41306
+ identifier: { id: "inkmap.inkmap-vscode" },
41307
+ version: version2,
41308
+ location: {
41309
+ $mid: 1,
41310
+ fsPath: dest,
41311
+ external: destUrl.href,
41312
+ path: destUrl.pathname,
41313
+ scheme: "file"
41314
+ },
41315
+ relativeLocation: folderName,
41316
+ metadata: {
41317
+ installedTimestamp: Date.now(),
41318
+ source: "vsix"
41319
+ }
41320
+ });
41321
+ const tmp = `${registryPath}.${process.pid}.${Date.now()}.tmp`;
41322
+ (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(filtered), "utf8");
41323
+ (0, import_node_fs3.renameSync)(tmp, registryPath);
41324
+ }
41325
+ } catch {
41326
+ }
40982
41327
  return dest;
40983
41328
  } finally {
40984
41329
  (0, import_node_fs3.rmSync)(staging, { recursive: true, force: true });
@@ -40988,19 +41333,34 @@ function uninstallIdeExtension(editorDir, cliCmd) {
40988
41333
  let removed = false;
40989
41334
  if (cliCmd) {
40990
41335
  try {
40991
- (0, import_node_child_process4.execFileSync)(cliCmd, ["--uninstall-extension", "inkmap.inkmap-vscode"], { stdio: "pipe" });
41336
+ execCliSync(cliCmd, ["--uninstall-extension", "inkmap.inkmap-vscode"], { stdio: "pipe" });
40992
41337
  removed = true;
40993
41338
  } catch {
40994
41339
  }
40995
41340
  }
40996
- const extRoot = (0, import_node_path5.join)(editorDir, "extensions");
41341
+ const extRoot = (0, import_node_path6.join)(editorDir, "extensions");
40997
41342
  if ((0, import_node_fs3.existsSync)(extRoot)) {
40998
41343
  for (const entry of (0, import_node_fs3.readdirSync)(extRoot)) {
40999
41344
  if (entry.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
41000
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(extRoot, entry), { recursive: true, force: true });
41345
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(extRoot, entry), { recursive: true, force: true });
41001
41346
  removed = true;
41002
41347
  }
41003
41348
  }
41349
+ try {
41350
+ const registryPath = (0, import_node_path6.join)(extRoot, "extensions.json");
41351
+ if ((0, import_node_fs3.existsSync)(registryPath)) {
41352
+ const existingList = JSON.parse((0, import_node_fs3.readFileSync)(registryPath, "utf8"));
41353
+ if (Array.isArray(existingList)) {
41354
+ const filtered = existingList.filter((item) => String(item?.identifier?.id ?? "").toLowerCase() !== "inkmap.inkmap-vscode");
41355
+ if (filtered.length !== existingList.length) {
41356
+ const tmp = `${registryPath}.${process.pid}.${Date.now()}.tmp`;
41357
+ (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(filtered), "utf8");
41358
+ (0, import_node_fs3.renameSync)(tmp, registryPath);
41359
+ }
41360
+ }
41361
+ }
41362
+ } catch {
41363
+ }
41004
41364
  }
41005
41365
  return removed;
41006
41366
  }
@@ -41009,7 +41369,7 @@ function buildMcpEntry(serverScript, workspaces, existingEntry, withTypeStdio =
41009
41369
  const args = isDirectServer ? [serverScript] : [serverScript, "mcp"];
41010
41370
  const prevEnv = existingEntry && typeof existingEntry === "object" && !Array.isArray(existingEntry) && typeof existingEntry.env === "object" ? { ...existingEntry.env } : {};
41011
41371
  if (workspaces.length > 0) {
41012
- prevEnv.INKMAP_WORKSPACES = workspaces.map((w2) => (0, import_node_path5.resolve)(w2)).join(import_node_path5.delimiter);
41372
+ prevEnv.INKMAP_WORKSPACES = workspaces.map((w2) => (0, import_node_path6.resolve)(w2)).join(import_node_path6.delimiter);
41013
41373
  }
41014
41374
  const entry = {};
41015
41375
  if (withTypeStdio)
@@ -41059,81 +41419,106 @@ async function refreshAntigravityMcp() {
41059
41419
  } catch {
41060
41420
  }
41061
41421
  }
41062
- async function installAntigravityPlugin() {
41063
- const pluginsDir = (0, import_node_path5.join)(getAntigravityConfigDir(), "plugins");
41064
- const destination = (0, import_node_path5.join)(pluginsDir, "inkmap");
41065
- const bundledAgy = (0, import_node_path5.join)(DIST_DIR, "bundles", "antigravity");
41066
- const bundledCli = (0, import_node_path5.join)(DIST_DIR, "cli.cjs");
41067
- const bundledHtml = (0, import_node_path5.join)(DIST_DIR, "codex.html");
41068
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
41069
- const monorepoAgy = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
41422
+ async function installAntigravityPlugin(workspaces = []) {
41423
+ const pluginsDir = (0, import_node_path6.join)(getAntigravityConfigDir(), "plugins");
41424
+ const destination = (0, import_node_path6.join)(pluginsDir, "inkmap");
41425
+ const bundledAgy = (0, import_node_path6.join)(DIST_DIR, "bundles", "antigravity");
41426
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41427
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41428
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41429
+ const monorepoAgy = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
41070
41430
  (0, import_node_fs3.mkdirSync)(pluginsDir, { recursive: true });
41071
41431
  (0, import_node_fs3.rmSync)(destination, { recursive: true, force: true });
41072
- 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)) {
41432
+ 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)) {
41073
41433
  (0, import_node_fs3.cpSync)(bundledAgy, destination, { recursive: true });
41074
- (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path5.join)(destination, "cli.cjs"));
41075
- (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path5.join)(destination, "codex.html"));
41076
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(destination, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41434
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(destination, "cli.cjs"));
41435
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(destination, "codex.html"));
41436
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(destination, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41077
41437
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
41078
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(destination, "sidecars", "inkmap", "web"), { recursive: true });
41438
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(destination, "sidecars", "inkmap", "web"), { recursive: true });
41079
41439
  }
41080
41440
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md", "README.md"]) {
41081
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41441
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
41082
41442
  if ((0, import_node_fs3.existsSync)(src))
41083
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(destination, doc));
41443
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(destination, doc));
41084
41444
  }
41085
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoAgy, "plugin.json"))) {
41445
+ } else if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAgy, "plugin.json"))) {
41086
41446
  (0, import_node_fs3.cpSync)(monorepoAgy, destination, { recursive: true });
41087
41447
  } else {
41088
41448
  throw new Error("\u672A\u627E\u5230 Antigravity \u63D2\u4EF6\u8D44\u6E90 / Antigravity plugin bundle not found.");
41089
41449
  }
41450
+ if (workspaces.length > 0) {
41451
+ try {
41452
+ const mcpCfgPath = (0, import_node_path6.join)(destination, "mcp_config.json");
41453
+ if ((0, import_node_fs3.existsSync)(mcpCfgPath)) {
41454
+ const cfg = readJsonObject(mcpCfgPath);
41455
+ const servers = cfg.mcpServers && typeof cfg.mcpServers === "object" && !Array.isArray(cfg.mcpServers) ? { ...cfg.mcpServers } : {};
41456
+ if (servers.inkmap && typeof servers.inkmap === "object") {
41457
+ servers.inkmap = {
41458
+ ...servers.inkmap,
41459
+ env: {
41460
+ ...servers.inkmap.env && typeof servers.inkmap.env === "object" ? servers.inkmap.env : {},
41461
+ INKMAP_WORKSPACES: workspaces.map((w2) => (0, import_node_path6.resolve)(w2)).join(import_node_path6.delimiter)
41462
+ }
41463
+ };
41464
+ cfg.mcpServers = servers;
41465
+ writeJsonAtomic(mcpCfgPath, cfg);
41466
+ }
41467
+ }
41468
+ } catch {
41469
+ }
41470
+ }
41090
41471
  await refreshAntigravityMcp();
41091
41472
  return destination;
41092
41473
  }
41093
- function installCodexPlugin() {
41474
+ function installCodexPlugin(zh) {
41094
41475
  const codex = findCodexCommand();
41095
41476
  if (!codex) {
41096
41477
  throw new Error("\u672A\u68C0\u6D4B\u5230 codex \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 ChatGPT Desktop \u6216 Codex CLI / Codex CLI not found.");
41097
41478
  }
41098
- const bundledCodex = (0, import_node_path5.join)(DIST_DIR, "bundles", "codex");
41099
- const bundledCli = (0, import_node_path5.join)(DIST_DIR, "cli.cjs");
41100
- const bundledHtml = (0, import_node_path5.join)(DIST_DIR, "codex.html");
41101
- const monorepoCodexRoot = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars");
41102
- const destination = (0, import_node_path5.join)(getInkmapHome(), "codex-marketplace");
41479
+ const bundledCodex = (0, import_node_path6.join)(DIST_DIR, "bundles", "codex");
41480
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41481
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41482
+ const monorepoCodexRoot = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars");
41483
+ const destination = (0, import_node_path6.join)(getInkmapHome(), "codex-marketplace");
41103
41484
  (0, import_node_fs3.mkdirSync)(destination, { recursive: true });
41104
41485
  const marketplaceRoot = (0, import_node_fs3.realpathSync)(destination);
41105
- 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)) {
41486
+ 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);
41487
+ 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"));
41488
+ if (!fromNpmBundle && !fromMonorepo)
41489
+ throw new Error("\u672A\u627E\u5230 Codex \u63D2\u4EF6\u8D44\u6E90 / Codex plugin bundle not found.");
41490
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(marketplaceRoot, ".agents"), { recursive: true, force: true });
41491
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(marketplaceRoot, "inkmap-codex"), { recursive: true, force: true });
41492
+ if (fromNpmBundle) {
41106
41493
  (0, import_node_fs3.cpSync)(bundledCodex, marketplaceRoot, { recursive: true });
41107
- const pluginDir = (0, import_node_path5.join)(marketplaceRoot, "inkmap-codex");
41108
- (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path5.join)(pluginDir, "cli.cjs"));
41109
- (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path5.join)(pluginDir, "codex.html"));
41110
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(pluginDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41494
+ const pluginDir = (0, import_node_path6.join)(marketplaceRoot, "inkmap-codex");
41495
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(pluginDir, "cli.cjs"));
41496
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(pluginDir, "codex.html"));
41497
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(pluginDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41111
41498
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
41112
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41499
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
41113
41500
  if ((0, import_node_fs3.existsSync)(src))
41114
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(pluginDir, doc));
41501
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(pluginDir, doc));
41115
41502
  }
41116
- } 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"))) {
41117
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoCodexRoot, ".agents"), (0, import_node_path5.join)(marketplaceRoot, ".agents"), { recursive: true });
41118
- (0, import_node_fs3.cpSync)((0, import_node_path5.join)(monorepoCodexRoot, "inkmap-codex"), (0, import_node_path5.join)(marketplaceRoot, "inkmap-codex"), { recursive: true });
41119
41503
  } else {
41120
- throw new Error("\u672A\u627E\u5230 Codex \u63D2\u4EF6\u8D44\u6E90 / Codex plugin bundle not found.");
41504
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoCodexRoot, ".agents"), (0, import_node_path6.join)(marketplaceRoot, ".agents"), { recursive: true });
41505
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoCodexRoot, "inkmap-codex"), (0, import_node_path6.join)(marketplaceRoot, "inkmap-codex"), { recursive: true });
41121
41506
  }
41122
41507
  const marketplaceName = "inkmap-local";
41123
- const rawList = (0, import_node_child_process4.execFileSync)(codex, ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
41508
+ const rawList = execCliSync(codex, ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
41124
41509
  const { marketplaces = [] } = JSON.parse(rawList);
41125
41510
  const existing = marketplaces.find((entry) => entry.name === marketplaceName);
41126
41511
  if (!existing) {
41127
- (0, import_node_child_process4.execFileSync)(codex, ["plugin", "marketplace", "add", marketplaceRoot], { stdio: "pipe" });
41512
+ execCliSync(codex, ["plugin", "marketplace", "add", marketplaceRoot], { stdio: "pipe" });
41128
41513
  }
41129
- (0, import_node_child_process4.execFileSync)(codex, ["plugin", "add", `inkmap-codex@${marketplaceName}`], { stdio: "pipe" });
41514
+ execCliSync(codex, ["plugin", "add", `inkmap-codex@${marketplaceName}`], { stdio: "pipe" });
41130
41515
  return {
41131
41516
  location: marketplaceRoot,
41132
- 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"
41517
+ 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"
41133
41518
  };
41134
41519
  }
41135
41520
  function configureDshMarketIndex(profileDir) {
41136
- const pkgPath = (0, import_node_path5.join)(profileDir, "package.json");
41521
+ const pkgPath = (0, import_node_path6.join)(profileDir, "package.json");
41137
41522
  if ((0, import_node_fs3.existsSync)(pkgPath)) {
41138
41523
  try {
41139
41524
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(pkgPath, "utf8"));
@@ -41153,52 +41538,56 @@ function configureDshMarketIndex(profileDir) {
41153
41538
  } catch {
41154
41539
  }
41155
41540
  }
41156
- const patchPath = (0, import_node_path5.join)(profileDir, "cordis.patch.yml");
41541
+ const patchPath = (0, import_node_path6.join)(profileDir, "cordis.patch.yml");
41157
41542
  const indexUrl = "https://zhiyuanv.com/dsh-index.json";
41158
41543
  try {
41159
41544
  const existing = (0, import_node_fs3.existsSync)(patchPath) ? (0, import_node_fs3.readFileSync)(patchPath, "utf8") : "";
41160
41545
  if (!existing.includes(indexUrl)) {
41161
- const snippet = `
41162
- - id: plugin-market
41546
+ const snippet = `- id: plugin-market
41163
41547
  name: "@deepseek-ai/dsh-plugin-market"
41164
41548
  config:
41165
41549
  indexes:
41166
41550
  - ${indexUrl}
41167
41551
  `;
41168
- (0, import_node_fs3.writeFileSync)(patchPath, existing.replace(/\n*$/, "") + snippet, "utf8");
41552
+ const trimmed = existing.trim();
41553
+ if (!trimmed || trimmed === "[]") {
41554
+ (0, import_node_fs3.writeFileSync)(patchPath, snippet, "utf8");
41555
+ } else if (!/^\s*-\s*id:\s*plugin-market\b/m.test(existing)) {
41556
+ (0, import_node_fs3.writeFileSync)(patchPath, existing.replace(/\n*$/, "\n\n") + snippet, "utf8");
41557
+ }
41169
41558
  }
41170
41559
  } catch {
41171
41560
  }
41172
41561
  }
41173
- function installDeepSeekHarnessPlugin() {
41174
- const bundledHarness = (0, import_node_path5.join)(DIST_DIR, "bundles", "harness");
41175
- const bundledWeb = (0, import_node_path5.join)(DIST_DIR, "web");
41176
- const monorepoHarness = (0, import_node_path5.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "dsh-inkmap");
41177
- const stagedDir = (0, import_node_path5.join)(getInkmapHome(), "dsh-inkmap");
41562
+ function installDeepSeekHarnessPlugin(zh) {
41563
+ const bundledHarness = (0, import_node_path6.join)(DIST_DIR, "bundles", "harness");
41564
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41565
+ const monorepoHarness = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "dsh-inkmap");
41566
+ const stagedDir = (0, import_node_path6.join)(getInkmapHome(), "dsh-inkmap");
41178
41567
  (0, import_node_fs3.rmSync)(stagedDir, { recursive: true, force: true });
41179
41568
  (0, import_node_fs3.mkdirSync)(stagedDir, { recursive: true });
41180
- if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(bundledHarness, "package.json")) && (0, import_node_fs3.existsSync)(bundledWeb)) {
41569
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledHarness, "package.json")) && (0, import_node_fs3.existsSync)(bundledWeb)) {
41181
41570
  (0, import_node_fs3.cpSync)(bundledHarness, stagedDir, { recursive: true });
41182
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(stagedDir, "web"), { recursive: true });
41571
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(stagedDir, "web"), { recursive: true });
41183
41572
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
41184
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41573
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
41185
41574
  if ((0, import_node_fs3.existsSync)(src))
41186
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(stagedDir, doc));
41575
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(stagedDir, doc));
41187
41576
  }
41188
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoHarness, "package.json"))) {
41577
+ } else if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoHarness, "package.json"))) {
41189
41578
  (0, import_node_fs3.cpSync)(monorepoHarness, stagedDir, { recursive: true });
41190
41579
  } else {
41191
41580
  throw new Error("\u672A\u627E\u5230 DeepSeek Harness \u63D2\u4EF6\u8D44\u6E90 / DeepSeek Harness plugin bundle not found.");
41192
41581
  }
41193
41582
  const realStaged = (0, import_node_fs3.realpathSync)(stagedDir);
41194
41583
  const dshCmd = findDshCommand();
41195
- const profileDir = (0, import_node_path5.join)(getDshHome(), "profiles", "desktop");
41584
+ const profileDir = (0, import_node_path6.join)(getDshHome(), "profiles", "desktop");
41196
41585
  if (dshCmd) {
41197
- (0, import_node_child_process4.execFileSync)(dshCmd, ["plugin", "--profile", "desktop", "add", realStaged], { stdio: "pipe" });
41586
+ execCliSync(dshCmd, ["plugin", "--profile", "desktop", "add", realStaged], { stdio: "pipe" });
41198
41587
  } else if ((0, import_node_fs3.existsSync)(profileDir)) {
41199
- const nodeModulesTarget = (0, import_node_path5.join)(profileDir, "node_modules", "dsh-inkmap");
41588
+ const nodeModulesTarget = (0, import_node_path6.join)(profileDir, "node_modules", "dsh-inkmap");
41200
41589
  (0, import_node_fs3.rmSync)(nodeModulesTarget, { recursive: true, force: true });
41201
- (0, import_node_fs3.mkdirSync)((0, import_node_path5.join)(profileDir, "node_modules"), { recursive: true });
41590
+ (0, import_node_fs3.mkdirSync)((0, import_node_path6.join)(profileDir, "node_modules"), { recursive: true });
41202
41591
  (0, import_node_fs3.cpSync)(realStaged, nodeModulesTarget, { recursive: true });
41203
41592
  } else {
41204
41593
  throw new Error("\u672A\u68C0\u6D4B\u5230 DeepSeek Harness \u5BA2\u6237\u7AEF / DeepSeek Harness not found.");
@@ -41208,7 +41597,7 @@ function installDeepSeekHarnessPlugin() {
41208
41597
  }
41209
41598
  return {
41210
41599
  location: (0, import_node_fs3.existsSync)(profileDir) ? profileDir : realStaged,
41211
- 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"
41600
+ 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)"
41212
41601
  };
41213
41602
  }
41214
41603
  async function runInstall(options = {}) {
@@ -41221,7 +41610,7 @@ async function runInstall(options = {}) {
41221
41610
  const toRemove = explicitTargets ?? ["claude", "claude-code", "cursor", "vscode", "antigravity", "codex", "deepseek"];
41222
41611
  for (const target of toRemove) {
41223
41612
  if (target === "claude") {
41224
- const cfg = (0, import_node_path5.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41613
+ const cfg = (0, import_node_path6.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41225
41614
  if (removeMcpJsonConfig(cfg))
41226
41615
  result.removed.push({ target, location: cfg });
41227
41616
  } else if (target === "claude-code") {
@@ -41229,38 +41618,49 @@ async function runInstall(options = {}) {
41229
41618
  if (removeMcpJsonConfig(cfg))
41230
41619
  result.removed.push({ target, location: cfg });
41231
41620
  } else if (target === "cursor") {
41232
- const cfg = (0, import_node_path5.join)(getCursorDir(), "mcp.json");
41621
+ const cfg = (0, import_node_path6.join)(getCursorDir(), "mcp.json");
41233
41622
  const removedMcp = removeMcpJsonConfig(cfg);
41234
41623
  const removedExt = uninstallIdeExtension(getCursorDir(), findCursorCommand());
41235
41624
  if (removedMcp || removedExt)
41236
41625
  result.removed.push({ target, location: cfg });
41237
41626
  } else if (target === "vscode") {
41238
41627
  if (uninstallIdeExtension(getVscodeDir(), findVscodeCommand())) {
41239
- result.removed.push({ target, location: (0, import_node_path5.join)(getVscodeDir(), "extensions") });
41628
+ result.removed.push({ target, location: (0, import_node_path6.join)(getVscodeDir(), "extensions") });
41240
41629
  }
41241
41630
  } else if (target === "antigravity") {
41242
- const dir = (0, import_node_path5.join)(getAntigravityConfigDir(), "plugins", "inkmap");
41631
+ const dir = (0, import_node_path6.join)(getAntigravityConfigDir(), "plugins", "inkmap");
41243
41632
  if ((0, import_node_fs3.existsSync)(dir)) {
41244
41633
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
41245
41634
  await refreshAntigravityMcp();
41246
41635
  result.removed.push({ target, location: dir });
41247
41636
  }
41248
41637
  } else if (target === "codex") {
41249
- const dir = (0, import_node_path5.join)(getInkmapHome(), "codex-marketplace");
41638
+ const codexCmd = findCodexCommand();
41639
+ if (codexCmd) {
41640
+ try {
41641
+ execCliSync(codexCmd, ["plugin", "remove", "inkmap-codex@inkmap-local"], { stdio: "pipe" });
41642
+ } catch {
41643
+ }
41644
+ try {
41645
+ execCliSync(codexCmd, ["plugin", "marketplace", "remove", "inkmap-local"], { stdio: "pipe" });
41646
+ } catch {
41647
+ }
41648
+ }
41649
+ const dir = (0, import_node_path6.join)(getInkmapHome(), "codex-marketplace");
41250
41650
  if ((0, import_node_fs3.existsSync)(dir)) {
41251
41651
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
41252
41652
  result.removed.push({ target, location: dir });
41253
41653
  }
41254
41654
  } else if (target === "deepseek") {
41255
41655
  const dshCmd = findDshCommand();
41256
- const profileDir = (0, import_node_path5.join)(getDshHome(), "profiles", "desktop");
41656
+ const profileDir = (0, import_node_path6.join)(getDshHome(), "profiles", "desktop");
41257
41657
  if (dshCmd && (0, import_node_fs3.existsSync)(profileDir)) {
41258
41658
  try {
41259
- (0, import_node_child_process4.execFileSync)(dshCmd, ["plugin", "--profile", "desktop", "remove", "dsh-inkmap"], { stdio: "pipe" });
41659
+ execCliSync(dshCmd, ["plugin", "--profile", "desktop", "remove", "dsh-inkmap"], { stdio: "pipe" });
41260
41660
  } catch {
41261
41661
  }
41262
41662
  }
41263
- const dir = (0, import_node_path5.join)(getInkmapHome(), "dsh-inkmap");
41663
+ const dir = (0, import_node_path6.join)(getInkmapHome(), "dsh-inkmap");
41264
41664
  if ((0, import_node_fs3.existsSync)(dir)) {
41265
41665
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
41266
41666
  result.removed.push({ target, location: profileDir });
@@ -41268,7 +41668,7 @@ async function runInstall(options = {}) {
41268
41668
  }
41269
41669
  }
41270
41670
  if (!explicitTargets) {
41271
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(getInkmapHome(), "mcp-app"), { recursive: true, force: true });
41671
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(getInkmapHome(), "mcp-app"), { recursive: true, force: true });
41272
41672
  }
41273
41673
  if (result.removed.length === 0) {
41274
41674
  log("[inkmap] \u672A\u53D1\u73B0\u5DF2\u5B89\u88C5\u7684 Inkmap \u5BA2\u6237\u7AEF\u914D\u7F6E / No installed Inkmap client configs found.");
@@ -41280,6 +41680,7 @@ async function runInstall(options = {}) {
41280
41680
  return result;
41281
41681
  }
41282
41682
  const { serverScript, appDir } = stageStandaloneMcpApp();
41683
+ const zhLocale = isChineseTerminalLocale();
41283
41684
  if (targets.length === 0) {
41284
41685
  log(`[inkmap] \u5DF2\u5C06 MCP App \u6838\u5FC3\u6587\u4EF6\u5C31\u7EEA\u5230: ${appDir}`);
41285
41686
  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");
@@ -41289,16 +41690,17 @@ async function runInstall(options = {}) {
41289
41690
  log(" npx -y inkmap-mcp@latest install vscode # VS Code (\u539F\u751F\u7F16\u8F91\u5668\u6269\u5C55)");
41290
41691
  log(" npx -y inkmap-mcp@latest install antigravity # Google Antigravity");
41291
41692
  log(" npx -y inkmap-mcp@latest install codex # OpenAI Codex Desktop");
41693
+ log(" npx -y inkmap-mcp@latest install deepseek # DeepSeek Harness");
41292
41694
  return result;
41293
41695
  }
41294
41696
  for (const target of targets) {
41295
41697
  if (target === "claude") {
41296
- const cfg = (0, import_node_path5.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41698
+ const cfg = (0, import_node_path6.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41297
41699
  upsertMcpJsonConfig(cfg, serverScript, workspaces, false);
41298
41700
  result.installed.push({
41299
41701
  target,
41300
41702
  location: cfg,
41301
- 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"
41703
+ 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"
41302
41704
  });
41303
41705
  } else if (target === "claude-code") {
41304
41706
  const cfg = getClaudeCodeConfigPath();
@@ -41306,13 +41708,13 @@ async function runInstall(options = {}) {
41306
41708
  result.installed.push({
41307
41709
  target,
41308
41710
  location: cfg,
41309
- note: "\u5728 Claude Code \u4E2D\u5DF2\u6CE8\u518C\u5168\u5C40 inkmap MCP \u670D\u52A1"
41711
+ note: zhLocale ? "\u5728 Claude Code \u4E2D\u5DF2\u6CE8\u518C\u5168\u5C40 inkmap MCP \u670D\u52A1" : "Registered global inkmap MCP server in Claude Code"
41310
41712
  });
41311
41713
  } else if (target === "cursor") {
41312
- const cfg = (0, import_node_path5.join)(getCursorDir(), "mcp.json");
41714
+ const cfg = (0, import_node_path6.join)(getCursorDir(), "mcp.json");
41313
41715
  upsertMcpJsonConfig(cfg, serverScript, workspaces, false);
41314
41716
  const extLoc = installIdeExtension(getCursorDir(), findCursorCommand());
41315
- const cursorServerDir = (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".cursor-server");
41717
+ const cursorServerDir = (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".cursor-server");
41316
41718
  if ((0, import_node_fs3.existsSync)(cursorServerDir)) {
41317
41719
  try {
41318
41720
  installIdeExtension(cursorServerDir, null);
@@ -41322,7 +41724,7 @@ async function runInstall(options = {}) {
41322
41724
  result.installed.push({
41323
41725
  target,
41324
41726
  location: extLoc ? `${cfg} + ${extLoc}` : cfg,
41325
- 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"
41727
+ 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)"
41326
41728
  });
41327
41729
  } else if (target === "vscode") {
41328
41730
  const extLoc = installIdeExtension(getVscodeDir(), findVscodeCommand());
@@ -41330,19 +41732,19 @@ async function runInstall(options = {}) {
41330
41732
  result.installed.push({
41331
41733
  target,
41332
41734
  location: extLoc,
41333
- note: "\u5DF2\u5728 VS Code \u5B89\u88C5\u539F\u751F Inkmap \u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668\u6269\u5C55"
41735
+ 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"
41334
41736
  });
41335
41737
  }
41336
41738
  } else if (target === "antigravity") {
41337
- const loc = await installAntigravityPlugin();
41739
+ const loc = await installAntigravityPlugin(workspaces);
41338
41740
  result.installed.push({
41339
41741
  target,
41340
41742
  location: loc,
41341
- 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"
41743
+ 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"
41342
41744
  });
41343
41745
  } else if (target === "codex") {
41344
41746
  try {
41345
- const installedCodex = installCodexPlugin();
41747
+ const installedCodex = installCodexPlugin(zhLocale);
41346
41748
  result.installed.push({
41347
41749
  target,
41348
41750
  location: installedCodex.location,
@@ -41355,7 +41757,7 @@ async function runInstall(options = {}) {
41355
41757
  }
41356
41758
  } else if (target === "deepseek") {
41357
41759
  try {
41358
- const installedDsh = installDeepSeekHarnessPlugin();
41760
+ const installedDsh = installDeepSeekHarnessPlugin(zhLocale);
41359
41761
  result.installed.push({
41360
41762
  target,
41361
41763
  location: installedDsh.location,
@@ -41368,7 +41770,6 @@ async function runInstall(options = {}) {
41368
41770
  }
41369
41771
  }
41370
41772
  }
41371
- const zhLocale = isChineseTerminalLocale();
41372
41773
  if (zhLocale) {
41373
41774
  log(`[inkmap] \u5B89\u88C5\u5B8C\u6210\uFF08Node: ${process.execPath}\uFF09\uFF1A`);
41374
41775
  for (const item of result.installed) {
@@ -41390,6 +41791,8 @@ async function runInstall(options = {}) {
41390
41791
  log(`[inkmap] Installation complete (Node: ${process.execPath}):`);
41391
41792
  for (const item of result.installed) {
41392
41793
  log(` \u2713 ${item.target.padEnd(12)} -> ${item.location}`);
41794
+ if (item.note)
41795
+ log(` ${item.note}`);
41393
41796
  }
41394
41797
  log("");
41395
41798
  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");
@@ -41444,17 +41847,17 @@ async function runInstallCli(argv, uninstall = false) {
41444
41847
  const val = argv[++i];
41445
41848
  if (!val)
41446
41849
  throw new Error("--workspace \u9700\u8981\u63D0\u4F9B\u76EE\u5F55\u8DEF\u5F84 / --workspace requires a directory path");
41447
- workspaces.push(...val.split(import_node_path5.delimiter).filter(Boolean));
41850
+ workspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41448
41851
  continue;
41449
41852
  }
41450
41853
  if (arg.startsWith("--workspace=")) {
41451
41854
  const val = arg.slice("--workspace=".length);
41452
- workspaces.push(...val.split(import_node_path5.delimiter).filter(Boolean));
41855
+ workspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41453
41856
  continue;
41454
41857
  }
41455
41858
  const normalized = normalizeTarget(arg);
41456
41859
  if (!normalized) {
41457
- throw new Error(`\u672A\u77E5\u5BA2\u6237\u7AEF\u76EE\u6807: ${arg}\uFF08\u652F\u6301: claude, claude-code, cursor, vscode, antigravity, codex, all\uFF09`);
41860
+ throw new Error(`\u672A\u77E5\u5BA2\u6237\u7AEF\u76EE\u6807: ${arg}\uFF08\u652F\u6301: claude, claude-code, cursor, vscode, antigravity, codex, deepseek, all\uFF09`);
41458
41861
  }
41459
41862
  if (normalized === "all") {
41460
41863
  explicitAll = true;
@@ -41468,19 +41871,19 @@ async function runInstallCli(argv, uninstall = false) {
41468
41871
  uninstall
41469
41872
  });
41470
41873
  }
41471
- var import_node_child_process4, import_node_fs3, import_node_os5, import_node_path5, import_node_url3, import_node_zlib, DIST_DIR, PKG_ROOT, SERVER_WRAPPER, CRC_TABLE;
41874
+ 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;
41472
41875
  var init_install = __esm({
41473
41876
  "packages/cli/dist/install.js"() {
41474
41877
  "use strict";
41475
41878
  import_node_child_process4 = require("node:child_process");
41476
41879
  import_node_fs3 = require("node:fs");
41477
41880
  import_node_os5 = require("node:os");
41478
- import_node_path5 = require("node:path");
41479
- import_node_url3 = require("node:url");
41881
+ import_node_path6 = require("node:path");
41882
+ import_node_url4 = require("node:url");
41480
41883
  import_node_zlib = require("node:zlib");
41481
41884
  init_license();
41482
- DIST_DIR = (0, import_node_path5.dirname)((0, import_node_url3.fileURLToPath)(inkmapModuleUrl));
41483
- PKG_ROOT = (0, import_node_path5.resolve)(DIST_DIR, "..");
41885
+ DIST_DIR = (0, import_node_path6.dirname)((0, import_node_url4.fileURLToPath)(inkmapModuleUrl));
41886
+ PKG_ROOT = (0, import_node_path6.resolve)(DIST_DIR, "..");
41484
41887
  SERVER_WRAPPER = `#!/usr/bin/env node
41485
41888
  "use strict";
41486
41889
  require("./cli.cjs").main(["mcp", ...process.argv.slice(2)]).catch(err => {
@@ -41509,13 +41912,13 @@ __export(index_exports, {
41509
41912
  });
41510
41913
  module.exports = __toCommonJS(index_exports);
41511
41914
  var import_node_child_process5 = require("node:child_process");
41512
- var import_node_path6 = require("node:path");
41513
- var import_node_url4 = require("node:url");
41915
+ var import_node_path7 = require("node:path");
41916
+ var import_node_url5 = require("node:url");
41514
41917
  init_dist();
41515
41918
  init_license();
41516
41919
  init_server();
41517
- var INKMAP_VERSION = "0.3.10";
41518
- var WEB_ROOT = (0, import_node_url4.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
41920
+ init_version();
41921
+ var WEB_ROOT = (0, import_node_url5.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
41519
41922
  var USAGE = `Inkmap v${INKMAP_VERSION} \u2014 Markdown \u4EA4\u4E92\u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668 & MCP App
41520
41923
 
41521
41924
  \u7528\u6CD5 / Usage\uFF1A
@@ -41529,14 +41932,17 @@ var USAGE = `Inkmap v${INKMAP_VERSION} \u2014 Markdown \u4EA4\u4E92\u601D\u7EF4\
41529
41932
  \u5728\u672C\u5730\u6D4F\u89C8\u5668\u4E2D\u4EE5\u601D\u7EF4\u5BFC\u56FE\u6253\u5F00\u5E76\u5B9E\u65F6\u53CC\u5411\u7F16\u8F91 Markdown \u6587\u4EF6`;
41530
41933
  function openBrowser(url2) {
41531
41934
  const [cmd, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url2]] : ["xdg-open", [url2]];
41532
- (0, import_node_child_process5.spawn)(cmd, args, { stdio: "ignore", detached: true }).unref();
41935
+ const child = (0, import_node_child_process5.spawn)(cmd, args, { stdio: "ignore", detached: true });
41936
+ child.on("error", () => {
41937
+ });
41938
+ child.unref();
41533
41939
  }
41534
41940
  function appendEnvWorkspaces(dirs) {
41535
41941
  if (dirs.length === 0)
41536
41942
  return;
41537
- const resolved = dirs.map((d2) => (0, import_node_path6.resolve)(d2));
41538
- const current = (process.env.INKMAP_WORKSPACES || "").split(import_node_path6.delimiter).filter(Boolean);
41539
- process.env.INKMAP_WORKSPACES = [.../* @__PURE__ */ new Set([...current, ...resolved])].join(import_node_path6.delimiter);
41943
+ const resolved = dirs.map((d2) => (0, import_node_path7.resolve)(d2));
41944
+ const current = (process.env.INKMAP_WORKSPACES || "").split(import_node_path7.delimiter).filter(Boolean);
41945
+ process.env.INKMAP_WORKSPACES = [.../* @__PURE__ */ new Set([...current, ...resolved])].join(import_node_path7.delimiter);
41540
41946
  }
41541
41947
  async function main(argv) {
41542
41948
  if (argv.length === 0 && !process.stdin.isTTY) {
@@ -41563,9 +41969,9 @@ async function main(argv) {
41563
41969
  const val = argv[++i];
41564
41970
  if (!val)
41565
41971
  throw new Error("--workspace \u9700\u8981\u76EE\u5F55\u8DEF\u5F84");
41566
- extraWorkspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41972
+ extraWorkspaces.push(...val.split(import_node_path7.delimiter).filter(Boolean));
41567
41973
  } else if (arg.startsWith("--workspace=")) {
41568
- extraWorkspaces.push(...arg.slice("--workspace=".length).split(import_node_path6.delimiter).filter(Boolean));
41974
+ extraWorkspaces.push(...arg.slice("--workspace=".length).split(import_node_path7.delimiter).filter(Boolean));
41569
41975
  } else if (arg === "-h" || arg === "--help") {
41570
41976
  console.log(USAGE);
41571
41977
  return;
@@ -41619,7 +42025,6 @@ ${USAGE}`);
41619
42025
  port: port ?? (sidebar ? 0 : void 0),
41620
42026
  log,
41621
42027
  license,
41622
- ads: adFeed(PRODUCT.adFeedUrl),
41623
42028
  sidebar,
41624
42029
  sidebarPurchase
41625
42030
  });