inkmap-mcp 0.3.10 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.11";
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",
@@ -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;
1198
1435
  var init_license = __esm({
1199
1436
  "packages/cli/dist/license.js"() {
1200
1437
  "use strict";
@@ -1203,21 +1440,64 @@ 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();
1208
1454
  }
1209
1455
  });
1210
1456
 
1211
- // packages/cli/dist/server.js
1212
- function insideRoot(root, target) {
1457
+ // packages/cli/dist/workspace-fs.js
1458
+ function insideOrEqual(root, target) {
1213
1459
  if (root === target)
1214
1460
  return true;
1215
1461
  const rel = (0, import_node_path2.relative)(root, target);
1216
1462
  return Boolean(rel && !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path2.sep));
1217
1463
  }
1464
+ function hasHiddenSegment(root, target) {
1465
+ const rel = (0, import_node_path2.relative)(root, target);
1466
+ if (!rel || rel === ".")
1467
+ return false;
1468
+ return rel.split(import_node_path2.sep).some((part) => part.startsWith("."));
1469
+ }
1470
+ async function hasSymlinkUnderRoot(realRoot, rawTarget) {
1471
+ let cur = rawTarget;
1472
+ while (cur && cur !== (0, import_node_path2.dirname)(cur)) {
1473
+ const st = await (0, import_promises2.lstat)(cur);
1474
+ if (st.isSymbolicLink())
1475
+ return true;
1476
+ if (await (0, import_promises2.realpath)(cur) === realRoot)
1477
+ return false;
1478
+ cur = (0, import_node_path2.dirname)(cur);
1479
+ }
1480
+ return false;
1481
+ }
1482
+ function uriToPath(uri, platform = process.platform) {
1483
+ if (typeof uri !== "string" || !uri.trim())
1484
+ return null;
1485
+ const trimmed = uri.trim();
1486
+ const windows = platform === "win32";
1487
+ try {
1488
+ if (trimmed.startsWith("file://")) {
1489
+ const path = (0, import_node_url.fileURLToPath)(trimmed.replace(/^file:\/\/\/([a-zA-Z])%3[aA](?=\/|$)/, "file:///$1:"), { windows });
1490
+ return windows && /^[a-zA-Z]:$/.test(path) ? path + "\\" : path;
1491
+ }
1492
+ if ((windows ? import_node_path2.win32 : import_node_path2.posix).isAbsolute(trimmed))
1493
+ return trimmed;
1494
+ } catch {
1495
+ }
1496
+ return null;
1497
+ }
1218
1498
  async function findProjectRoot(filePath) {
1219
- let cur = (0, import_node_path2.dirname)(filePath);
1220
1499
  const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1500
+ let cur = (0, import_node_path2.dirname)(filePath);
1221
1501
  while (cur && cur !== (0, import_node_path2.dirname)(cur) && cur !== home) {
1222
1502
  try {
1223
1503
  await (0, import_promises2.lstat)((0, import_node_path2.join)(cur, ".git"));
@@ -1228,7 +1508,7 @@ async function findProjectRoot(filePath) {
1228
1508
  }
1229
1509
  return (0, import_node_path2.dirname)(filePath);
1230
1510
  }
1231
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1511
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
1232
1512
  const found = [];
1233
1513
  async function walk(dir, depth) {
1234
1514
  if (depth > maxDepth || found.length >= maxFiles)
@@ -1250,12 +1530,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1250
1530
  await walk(full, depth + 1);
1251
1531
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
1252
1532
  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
- }
1533
+ const info = await (0, import_promises2.lstat)(full);
1534
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1535
+ continue;
1536
+ const real = await (0, import_promises2.realpath)(full);
1537
+ if (real === full && insideOrEqual(rootDir, real))
1538
+ found.push({ path: real, mtimeMs: info.mtimeMs });
1259
1539
  } catch {
1260
1540
  }
1261
1541
  }
@@ -1263,60 +1543,250 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1263
1543
  }
1264
1544
  await walk(rootDir, 0);
1265
1545
  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);
1546
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1547
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1548
+ if (am !== bm)
1549
+ return am - bm;
1550
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1551
+ return b.mtimeMs - a.mtimeMs;
1552
+ return a.path.localeCompare(b.path);
1271
1553
  });
1272
1554
  return found;
1273
1555
  }
1556
+ async function discoverAntigravityProjects() {
1557
+ const projectsDir = (0, import_node_path2.join)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".gemini", "config"), "projects");
1558
+ const roots = [];
1559
+ let entries = [];
1560
+ try {
1561
+ entries = await (0, import_promises2.readdir)(projectsDir);
1562
+ } catch {
1563
+ return roots;
1564
+ }
1565
+ for (const name of entries) {
1566
+ if (!name.endsWith(".json"))
1567
+ continue;
1568
+ try {
1569
+ const data = JSON.parse(await (0, import_promises2.readFile)((0, import_node_path2.join)(projectsDir, name), "utf8"));
1570
+ const resources = Array.isArray(data?.projectResources?.resources) ? data.projectResources.resources : [];
1571
+ for (const r2 of resources) {
1572
+ const p2 = uriToPath(r2?.gitFolder?.folderUri || r2?.folderUri);
1573
+ if (!p2)
1574
+ continue;
1575
+ const real = await (0, import_promises2.realpath)(p2).catch(() => null);
1576
+ if (real)
1577
+ roots.push({ path: real, name: String(data.name || (0, import_node_path2.basename)(real)) });
1578
+ }
1579
+ } catch {
1580
+ }
1581
+ }
1582
+ return roots;
1583
+ }
1584
+ function targetStateFile() {
1585
+ return (0, import_node_path2.join)(process.env.INKMAP_HOME || (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap"), "antigravity-target.json");
1586
+ }
1587
+ async function readTargetSelection() {
1588
+ try {
1589
+ const raw = JSON.parse(await (0, import_promises2.readFile)(targetStateFile(), "utf8"));
1590
+ if (typeof raw?.file !== "string" || !/\.md$/i.test(raw.file))
1591
+ return null;
1592
+ const info = await (0, import_promises2.lstat)(raw.file);
1593
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1594
+ return null;
1595
+ const file2 = await (0, import_promises2.realpath)(raw.file);
1596
+ if (file2 !== raw.file)
1597
+ return null;
1598
+ const workspace = typeof raw.workspace === "string" ? await (0, import_promises2.realpath)(raw.workspace).catch(() => (0, import_node_path2.dirname)(file2)) : (0, import_node_path2.dirname)(file2);
1599
+ if (!insideOrEqual(workspace, file2))
1600
+ return null;
1601
+ return { file: file2, workspace, seq: Number(raw.seq) || 0, ...raw.editorOnly === true && { editorOnly: true } };
1602
+ } catch {
1603
+ return null;
1604
+ }
1605
+ }
1606
+ function createSerialQueue() {
1607
+ let tail = Promise.resolve();
1608
+ return function serialized(work) {
1609
+ const next = tail.then(work);
1610
+ tail = next.catch(() => {
1611
+ });
1612
+ return next;
1613
+ };
1614
+ }
1615
+ function createWorkspaceAccess() {
1616
+ const sessionWorkspaces = /* @__PURE__ */ new Map();
1617
+ async function allowedRoots(extraWorkspaceUris = []) {
1618
+ const roots = /* @__PURE__ */ new Map();
1619
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1620
+ const configDir = await (0, import_promises2.realpath)(process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path2.join)(home, ".gemini", "config")).catch(() => "");
1621
+ const addRoot = async (rawPath, active, label) => {
1622
+ if (!rawPath)
1623
+ return;
1624
+ const real = await (0, import_promises2.realpath)(rawPath).catch(() => null);
1625
+ if (!real || (0, import_node_path2.dirname)(real) === real || real === home)
1626
+ return;
1627
+ if (configDir && insideOrEqual(configDir, real))
1628
+ return;
1629
+ const existing = roots.get(real);
1630
+ if (!existing)
1631
+ roots.set(real, { path: real, name: label || (0, import_node_path2.basename)(real), active });
1632
+ else if (active)
1633
+ existing.active = true;
1634
+ };
1635
+ for (const raw of (process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter).filter(Boolean)) {
1636
+ await addRoot(uriToPath(raw) || (0, import_node_path2.resolve)(raw), true);
1637
+ }
1638
+ for (const uri of extraWorkspaceUris) {
1639
+ if (typeof uri === "string" && uri.trim())
1640
+ await addRoot(uriToPath(uri) || (0, import_node_path2.resolve)(uri.trim()), true);
1641
+ }
1642
+ for (const [path, name] of sessionWorkspaces)
1643
+ await addRoot(path, true, name);
1644
+ const target = await readTargetSelection();
1645
+ if (target)
1646
+ await addRoot(target.workspace, roots.size === 0);
1647
+ for (const project of await discoverAntigravityProjects())
1648
+ await addRoot(project.path, false, project.name);
1649
+ if (roots.size === 0)
1650
+ await addRoot(process.cwd(), true);
1651
+ return { roots: [...roots.values()], target };
1652
+ }
1653
+ async function assertAllowedFile(candidatePath, extraWorkspaceUris = [], registerOutside = false) {
1654
+ if (typeof candidatePath !== "string" || !candidatePath.trim()) {
1655
+ throw new Error(say("\u672A\u6307\u5B9A Markdown \u6587\u4EF6\u3002", "No Markdown file was given."));
1656
+ }
1657
+ const { roots, target } = await allowedRoots(extraWorkspaceUris);
1658
+ const trimmed = candidatePath.trim();
1659
+ let raw = uriToPath(trimmed);
1660
+ if (!raw) {
1661
+ const base = roots.find((r2) => r2.active)?.path || roots[0]?.path || process.cwd();
1662
+ raw = (0, import_node_path2.isAbsolute)(trimmed) ? (0, import_node_path2.resolve)(trimmed) : (0, import_node_path2.resolve)(base, trimmed);
1663
+ }
1664
+ const notMarkdown = () => new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
1665
+ if (!/\.md$/i.test(raw))
1666
+ throw notMarkdown();
1667
+ const info = await (0, import_promises2.lstat)(raw).catch(() => null);
1668
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
1669
+ throw new Error(say("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002", "Choose a regular Markdown file up to 5 MiB."));
1670
+ }
1671
+ const real = await (0, import_promises2.realpath)(raw);
1672
+ if (!/\.md$/i.test(real))
1673
+ throw notMarkdown();
1674
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1675
+ const brainRoot = await (0, import_promises2.realpath)((0, import_node_path2.join)(home, ".gemini", "antigravity", "brain")).catch(() => null);
1676
+ const inBrainArtifact = Boolean(brainRoot && insideOrEqual(brainRoot, real) && !hasHiddenSegment(brainRoot, real) && !await hasSymlinkUnderRoot(brainRoot, raw));
1677
+ const hiddenError = () => new Error(say("\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002", "Files in hidden folders are not allowed."));
1678
+ const symlinkError = () => new Error(say("\u4E0D\u652F\u6301\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002", "Files inside symlinked folders are not allowed."));
1679
+ if (!inBrainArtifact && insideOrEqual(home, real) && hasHiddenSegment(home, real))
1680
+ throw hiddenError();
1681
+ const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, real));
1682
+ if (!inBrainArtifact && !(target && target.file === real) && !matchedRoot) {
1683
+ if (!registerOutside) {
1684
+ throw new Error(say("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u5141\u8BB8\u7684\u5DE5\u4F5C\u533A\u6216\u9879\u76EE\u76EE\u5F55\u5185\u3002", "This file is outside the allowed workspaces and projects."));
1685
+ }
1686
+ const project = await findProjectRoot(real);
1687
+ if (await hasSymlinkUnderRoot(project, raw))
1688
+ throw symlinkError();
1689
+ if (hasHiddenSegment(project, real))
1690
+ throw hiddenError();
1691
+ sessionWorkspaces.set(project, (0, import_node_path2.basename)(project));
1692
+ return real;
1693
+ }
1694
+ if (matchedRoot) {
1695
+ if (await hasSymlinkUnderRoot(matchedRoot.path, raw))
1696
+ throw symlinkError();
1697
+ if (hasHiddenSegment(matchedRoot.path, real))
1698
+ throw hiddenError();
1699
+ }
1700
+ return real;
1701
+ }
1702
+ return { allowedRoots, assertAllowedFile };
1703
+ }
1704
+ var import_promises2, import_node_os2, import_node_path2, import_node_url, say, MAX_MARKDOWN_BYTES, SKIP_SCAN_DIRS, MARKMAP_RE;
1705
+ var init_workspace_fs = __esm({
1706
+ "packages/cli/dist/workspace-fs.js"() {
1707
+ "use strict";
1708
+ import_promises2 = require("node:fs/promises");
1709
+ import_node_os2 = require("node:os");
1710
+ import_node_path2 = require("node:path");
1711
+ import_node_url = require("node:url");
1712
+ init_license();
1713
+ say = (zh, en) => detectOsLocale() === "zh" ? zh : en;
1714
+ MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
1715
+ SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
1716
+ ".git",
1717
+ ".hg",
1718
+ ".svn",
1719
+ "node_modules",
1720
+ "dist",
1721
+ "dist-codex",
1722
+ "dist-workbuddy",
1723
+ "build",
1724
+ "out",
1725
+ ".next",
1726
+ ".nuxt",
1727
+ ".agents",
1728
+ ".agent",
1729
+ ".gemini",
1730
+ ".codex",
1731
+ ".venv",
1732
+ "venv",
1733
+ "target",
1734
+ "coverage",
1735
+ ".tmp"
1736
+ ]);
1737
+ MARKMAP_RE = /\.markmap\.md$/i;
1738
+ }
1739
+ });
1740
+
1741
+ // packages/cli/dist/server.js
1274
1742
  function docName(path) {
1275
- return (0, import_node_path2.basename)(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1743
+ return (0, import_node_path3.basename)(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1276
1744
  }
1277
1745
  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");
1746
+ const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1747
+ return (0, import_node_path3.join)(base, "view-state", hash(key) + ".json");
1280
1748
  }
1281
1749
  async function readDiskViewState(key) {
1282
1750
  try {
1283
- return sanitizeViewState(JSON.parse(await (0, import_promises2.readFile)(viewStateFile(key), "utf8")));
1751
+ return sanitizeViewState(JSON.parse(await (0, import_promises3.readFile)(viewStateFile(key), "utf8")));
1284
1752
  } catch {
1285
1753
  return void 0;
1286
1754
  }
1287
1755
  }
1288
1756
  async function writeDiskViewState(key, state) {
1289
1757
  const target = viewStateFile(key);
1290
- await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(target), { recursive: true, mode: 448 });
1758
+ await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(target), { recursive: true, mode: 448 });
1291
1759
  const temp = `${target}.${process.pid}.${Date.now()}`;
1292
1760
  try {
1293
- await (0, import_promises2.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1294
- await (0, import_promises2.rename)(temp, target);
1761
+ await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1762
+ await (0, import_promises3.rename)(temp, target);
1295
1763
  } finally {
1296
- await (0, import_promises2.rm)(temp, { force: true }).catch(() => {
1764
+ await (0, import_promises3.rm)(temp, { force: true }).catch(() => {
1297
1765
  });
1298
1766
  }
1299
1767
  }
1300
1768
  async function fileSource(file2, log = () => {
1301
1769
  }) {
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())
1770
+ const path = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(file2)).catch(() => (0, import_node_path3.resolve)(file2));
1771
+ if (!(await (0, import_promises3.stat)(path)).isFile())
1304
1772
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1305
- const dir = (0, import_node_path2.dirname)(path);
1773
+ const dir = (0, import_node_path3.dirname)(path);
1306
1774
  return {
1307
1775
  name: docName(path),
1308
1776
  key: path,
1309
1777
  dir,
1310
- read: () => (0, import_promises2.readFile)(path, "utf8"),
1778
+ read: () => (0, import_promises3.readFile)(path, "utf8"),
1311
1779
  async write(md) {
1312
- await (0, import_promises2.writeFile)(path, md, "utf8");
1780
+ await (0, import_promises3.writeFile)(path, md, "utf8");
1313
1781
  log(`\u5DF2\u5199\u56DE ${path}`);
1314
1782
  },
1315
1783
  watch(onChange) {
1316
1784
  const watcher = (0, import_node_fs.watch)(dir, (_2, changed) => {
1317
- if (!changed || changed === (0, import_node_path2.basename)(path))
1785
+ if (!changed || changed === (0, import_node_path3.basename)(path))
1318
1786
  onChange();
1319
1787
  });
1788
+ watcher.on("error", () => {
1789
+ });
1320
1790
  return () => watcher.close();
1321
1791
  },
1322
1792
  readView: () => readDiskViewState(path),
@@ -1324,8 +1794,15 @@ async function fileSource(file2, log = () => {
1324
1794
  };
1325
1795
  }
1326
1796
  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)));
1797
+ let decoded;
1798
+ try {
1799
+ decoded = decodeURIComponent(rel);
1800
+ } catch {
1801
+ return null;
1802
+ }
1803
+ const resolvedRoot = (0, import_node_path3.resolve)(root);
1804
+ const base = resolvedRoot.endsWith(import_node_path3.sep) ? resolvedRoot : resolvedRoot + import_node_path3.sep;
1805
+ const full = (0, import_node_path3.normalize)((0, import_node_path3.join)(resolvedRoot, decoded));
1329
1806
  return full.startsWith(base) ? full : null;
1330
1807
  }
1331
1808
  async function openBrowserWindow(url2) {
@@ -1354,7 +1831,7 @@ async function openBrowserWindow(url2) {
1354
1831
  await run("xdg-open", [url2]);
1355
1832
  }
1356
1833
  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 = [] }) {
1834
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1358
1835
  if (sidebar && host !== "127.0.0.1")
1359
1836
  throw new Error("The sidebar bridge requires loopback.");
1360
1837
  const prefix = sidebar ? `/s/${(0, import_node_crypto2.randomBytes)(24).toString("hex")}/` : "/";
@@ -1365,7 +1842,9 @@ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.
1365
1842
  let version2 = hash(current);
1366
1843
  let viewState = await activeSource.readView?.();
1367
1844
  const clients = /* @__PURE__ */ new Set();
1368
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1845
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1846
+ const allowedHosts = /* @__PURE__ */ new Set();
1847
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1369
1848
  const docState = () => ({
1370
1849
  name: activeSource.name,
1371
1850
  md: current,
@@ -1400,36 +1879,36 @@ data: ${JSON.stringify(data)}
1400
1879
  broadcast();
1401
1880
  }
1402
1881
  let pending;
1403
- let unwatch = activeSource.watch(() => {
1882
+ const scheduleRefresh = () => {
1404
1883
  clearTimeout(pending);
1405
- pending = setTimeout(async () => {
1406
- void serialized(refresh).catch(() => {
1407
- });
1408
- }, 80);
1409
- });
1884
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1885
+ }), 80);
1886
+ };
1887
+ let unwatch = activeSource.watch(scheduleRefresh);
1888
+ const canonicalActiveKey = async () => activeSource.key ? await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key) : void 0;
1410
1889
  async function collectWorkspaceFiles() {
1411
1890
  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 });
1891
+ if (activeSource.key && !confineToWorkspaceRoots) {
1892
+ const realKey = await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key);
1893
+ const projRoot = await (0, import_promises3.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path3.dirname)(realKey));
1894
+ roots.set(projRoot, { path: projRoot, name: (0, import_node_path3.basename)(projRoot), active: true });
1416
1895
  }
1417
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter)].filter(Boolean);
1896
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter)].filter(Boolean);
1418
1897
  for (const raw of envRoots) {
1419
- const real = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(raw)).catch(() => null);
1898
+ const real = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(raw)).catch(() => null);
1420
1899
  if (real && !roots.has(real)) {
1421
- roots.set(real, { path: real, name: (0, import_node_path2.basename)(real), active: roots.size === 0 });
1900
+ roots.set(real, { path: real, name: (0, import_node_path3.basename)(real), active: roots.size === 0 });
1422
1901
  }
1423
1902
  }
1424
1903
  const items = [];
1425
1904
  const seen = /* @__PURE__ */ new Set();
1426
1905
  for (const root of roots.values()) {
1427
- const files = await scanProjectMarkdownFiles(root.path);
1906
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1428
1907
  for (const f2 of files) {
1429
1908
  if (seen.has(f2))
1430
1909
  continue;
1431
1910
  seen.add(f2);
1432
- const rel = (0, import_node_path2.relative)(root.path, f2);
1911
+ const rel = (0, import_node_path3.relative)(root.path, f2);
1433
1912
  items.push({
1434
1913
  path: f2,
1435
1914
  label: `${root.name} / ${rel}`,
@@ -1437,43 +1916,52 @@ data: ${JSON.stringify(data)}
1437
1916
  });
1438
1917
  }
1439
1918
  }
1440
- if (activeSource.key && !seen.has(activeSource.key)) {
1919
+ const activeReal = await canonicalActiveKey();
1920
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1441
1921
  items.unshift({
1442
1922
  path: activeSource.key,
1443
- label: `${(0, import_node_path2.basename)(activeSource.dir)} / ${(0, import_node_path2.basename)(activeSource.key)}`,
1923
+ label: `${(0, import_node_path3.basename)(activeSource.dir)} / ${(0, import_node_path3.basename)(activeSource.key)}`,
1444
1924
  group: "active"
1445
1925
  });
1446
1926
  }
1447
1927
  return { roots: [...roots.values()], files: items };
1448
1928
  }
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)
1929
+ const zh = () => detectOsLocale() === "zh";
1930
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1931
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1932
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1933
+ throw notMarkdown();
1934
+ const resolvedCandidate = (0, import_node_path3.resolve)(candidatePath);
1935
+ const rawStat = await (0, import_promises3.lstat)(resolvedCandidate).catch(() => null);
1936
+ const realTarget = await (0, import_promises3.realpath)(resolvedCandidate).catch(() => null);
1937
+ const targetStat = realTarget ? await (0, import_promises3.stat)(realTarget).catch(() => null) : null;
1938
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1939
+ throw new HttpError(403, zh() ? "\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002" : "Choose a regular Markdown file up to 5 MiB.");
1940
+ }
1941
+ if (!/\.md$/i.test(realTarget))
1942
+ throw notMarkdown();
1943
+ if (!trustCaller) {
1944
+ const { roots } = await collectWorkspaceFiles();
1945
+ const matchedRoot = roots.find((r2) => insideOrEqual(r2.path, realTarget));
1946
+ if (!matchedRoot) {
1947
+ throw new HttpError(403, zh() ? "\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002" : "This file is outside the current workspace.");
1948
+ }
1949
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1950
+ throw new HttpError(403, zh() ? "\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002" : "Files in hidden folders are not allowed.");
1951
+ }
1952
+ }
1953
+ if (await canonicalActiveKey() === realTarget)
1463
1954
  return;
1955
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1956
+ const text = await next.read();
1957
+ const nextView = await next.readView?.();
1464
1958
  clearTimeout(pending);
1465
1959
  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
- });
1960
+ activeSource = next;
1961
+ current = text;
1962
+ version2 = hash(text);
1963
+ viewState = nextView;
1964
+ unwatch = activeSource.watch(scheduleRefresh);
1477
1965
  broadcast();
1478
1966
  }
1479
1967
  const json2 = (res, status, body) => {
@@ -1486,7 +1974,7 @@ data: ${JSON.stringify(data)}
1486
1974
  req.on("data", (c) => {
1487
1975
  size += c.length;
1488
1976
  if (size > MAX_BODY) {
1489
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1977
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1490
1978
  req.destroy();
1491
1979
  } else
1492
1980
  chunks.push(c);
@@ -1498,16 +1986,23 @@ data: ${JSON.stringify(data)}
1498
1986
  if (!full)
1499
1987
  return json2(res, 403, { error: "forbidden" });
1500
1988
  try {
1501
- const ext = (0, import_node_path2.extname)(full).toLowerCase();
1989
+ const ext = (0, import_node_path3.extname)(full).toLowerCase();
1502
1990
  if (ext === ".html") {
1503
1991
  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}">`);
1992
+ const htmlText = (await (0, import_promises3.readFile)(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1505
1993
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1506
1994
  res.end(htmlText, "utf8");
1507
1995
  return;
1508
1996
  }
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" });
1997
+ const body = await (0, import_promises3.readFile)(full);
1998
+ const headers = {
1999
+ "content-type": TYPES[ext] ?? "application/octet-stream",
2000
+ "cache-control": sidebar ? "no-store" : "no-cache"
2001
+ };
2002
+ if (ext === ".svg") {
2003
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
2004
+ }
2005
+ res.writeHead(200, headers);
1511
2006
  res.end(body);
1512
2007
  } catch {
1513
2008
  json2(res, 404, { error: "not found" });
@@ -1516,18 +2011,27 @@ data: ${JSON.stringify(data)}
1516
2011
  const server = (0, import_node_http.createServer)(async (req, res) => {
1517
2012
  try {
1518
2013
  const url2 = new URL(req.url ?? "/", "http://localhost");
2014
+ const reqHost = req.headers.host ?? "";
2015
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1519
2016
  if (sidebar) {
1520
2017
  res.setHeader("Referrer-Policy", "no-referrer");
1521
2018
  res.setHeader("X-Content-Type-Options", "nosniff");
1522
2019
  res.setHeader("Cache-Control", "no-store");
1523
2020
  res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'");
1524
- if (req.headers.host !== `127.0.0.1:${bound}` || !url2.pathname.startsWith(prefix))
2021
+ if (reqHost !== `127.0.0.1:${bound}` || !url2.pathname.startsWith(prefix))
1525
2022
  return json2(res, 404, { error: "not found" });
1526
2023
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1527
2024
  return json2(res, 403, { error: "forbidden" });
1528
2025
  }
1529
2026
  url2.pathname = "/" + url2.pathname.slice(prefix.length);
2027
+ } else if (!hostAllowed) {
2028
+ return json2(res, 403, { error: "forbidden" });
1530
2029
  }
2030
+ const sameOriginWrite = () => {
2031
+ const origin = req.headers.origin;
2032
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
2033
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
2034
+ };
1531
2035
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url2.pathname)) {
1532
2036
  res.writeHead(302, { Location: "/" + url2.search });
1533
2037
  return res.end();
@@ -1551,6 +2055,8 @@ data: ${JSON.stringify(data)}
1551
2055
  });
1552
2056
  }
1553
2057
  if (url2.pathname === "/api/view" && req.method === "PUT") {
2058
+ if (!sameOriginWrite())
2059
+ return json2(res, 403, { error: "forbidden" });
1554
2060
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1555
2061
  if (cleaned) {
1556
2062
  viewState = cleaned;
@@ -1560,9 +2066,11 @@ data: ${JSON.stringify(data)}
1560
2066
  return json2(res, 200, { ok: true });
1561
2067
  }
1562
2068
  if (url2.pathname === "/api/doc" && req.method === "PUT") {
2069
+ if (!sameOriginWrite())
2070
+ return json2(res, 403, { error: "forbidden" });
1563
2071
  const { md, baseVersion } = JSON.parse(await readBody(req));
1564
2072
  if (typeof md !== "string")
1565
- return json2(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
2073
+ return json2(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1566
2074
  if (!hasAccess(await license?.state() ?? { pro: false }))
1567
2075
  return json2(res, 403, { error: "Inkmap trial expired" });
1568
2076
  return await serialized(async () => {
@@ -1574,31 +2082,24 @@ data: ${JSON.stringify(data)}
1574
2082
  current = md;
1575
2083
  version2 = hash(md);
1576
2084
  license?.track?.("doc_edit");
1577
- if (sidebar)
1578
- broadcast();
2085
+ broadcast();
1579
2086
  }
1580
2087
  return json2(res, 200, { version: version2 });
1581
2088
  });
1582
2089
  }
1583
2090
  if (url2.pathname === "/api/license" && req.method === "GET")
1584
2091
  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
2092
  if (url2.pathname === "/api/open" && req.method === "POST") {
1592
- if (!sameOriginPost())
2093
+ if (!sameOriginWrite())
1593
2094
  return json2(res, 403, { error: "forbidden" });
1594
2095
  const { file: file2 } = JSON.parse(await readBody(req));
1595
- await serialized(() => switchSourceToFile(String(file2 ?? "")));
2096
+ await serialized(() => switchSourceToFile(String(file2 ?? ""), false));
1596
2097
  license?.track?.("doc_open");
1597
2098
  const { files } = await collectWorkspaceFiles();
1598
2099
  return json2(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1599
2100
  }
1600
2101
  if (url2.pathname === "/api/telemetry" && req.method === "POST") {
1601
- if (!sameOriginPost())
2102
+ if (!sameOriginWrite())
1602
2103
  return json2(res, 403, { error: "forbidden" });
1603
2104
  const { event } = JSON.parse(await readBody(req));
1604
2105
  if (typeof event === "string" && event)
@@ -1606,45 +2107,43 @@ data: ${JSON.stringify(data)}
1606
2107
  return json2(res, 200, { ok: true });
1607
2108
  }
1608
2109
  if (url2.pathname === "/api/open-browser" && req.method === "POST") {
1609
- if (!sameOriginPost())
2110
+ if (!sameOriginWrite())
1610
2111
  return json2(res, 403, { error: "forbidden" });
1611
2112
  if (license && !hasAccess(await license.state())) {
1612
2113
  return json2(res, 402, { error: detectOsLocale() === "zh" ? "\u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u5148\u89E3\u9501\u6216\u6062\u590D Pro\u3002" : "Trial expired. Unlock or restore Pro first." });
1613
2114
  }
1614
2115
  license?.track?.("feature_browser");
1615
2116
  if (!sidebar) {
1616
- const directUrl = `http://${host}:${bound}/`;
2117
+ const directUrl = `http://${urlHost}:${bound}/`;
1617
2118
  await openBrowserWindow(directUrl);
1618
2119
  return json2(res, 200, { ok: true, url: directUrl });
1619
2120
  }
1620
2121
  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
- })();
2122
+ browserCompanion = serve({
2123
+ source: activeSource,
2124
+ webRoot,
2125
+ host: "127.0.0.1",
2126
+ port: 0,
2127
+ license,
2128
+ sidebar: false,
2129
+ workspaceRoots,
2130
+ confineToWorkspaceRoots,
2131
+ openSource,
2132
+ allowPurchase: canPurchase
2133
+ });
1635
2134
  browserCompanion.catch(() => {
1636
2135
  browserCompanion = null;
1637
2136
  });
1638
2137
  }
1639
2138
  const companion = await browserCompanion;
1640
2139
  if (activeSource.key)
1641
- await companion.switchToFile?.(activeSource.key).catch(() => {
2140
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1642
2141
  });
1643
2142
  await openBrowserWindow(companion.url);
1644
2143
  return json2(res, 200, { ok: true, url: companion.url });
1645
2144
  }
1646
2145
  if (url2.pathname === "/api/checkout" && req.method === "POST") {
1647
- if (!sameOriginPost())
2146
+ if (!sameOriginWrite())
1648
2147
  return json2(res, 403, { error: "forbidden" });
1649
2148
  const { mode, locale } = JSON.parse(await readBody(req));
1650
2149
  if (mode !== "buy" && mode !== "restore")
@@ -1656,7 +2155,7 @@ data: ${JSON.stringify(data)}
1656
2155
  return json2(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1657
2156
  }
1658
2157
  if (url2.pathname === "/api/order-pro" && req.method === "POST") {
1659
- if (!sameOriginPost())
2158
+ if (!sameOriginWrite())
1660
2159
  return json2(res, 403, { error: "forbidden" });
1661
2160
  if (!canPurchase)
1662
2161
  return json2(res, 403, { error: "forbidden" });
@@ -1668,7 +2167,7 @@ data: ${JSON.stringify(data)}
1668
2167
  return json2(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1669
2168
  }
1670
2169
  if (url2.pathname === "/api/phone-send" && req.method === "POST") {
1671
- if (!sameOriginPost())
2170
+ if (!sameOriginWrite())
1672
2171
  return json2(res, 403, { error: "forbidden" });
1673
2172
  if (!license || typeof license.sendPhoneCode !== "function")
1674
2173
  return json2(res, 501, { fallback: true });
@@ -1676,21 +2175,21 @@ data: ${JSON.stringify(data)}
1676
2175
  return json2(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1677
2176
  }
1678
2177
  if (url2.pathname === "/api/phone-verify" && req.method === "POST") {
1679
- if (!sameOriginPost())
2178
+ if (!sameOriginWrite())
1680
2179
  return json2(res, 403, { error: "forbidden" });
1681
2180
  if (!license || typeof license.signInByPhone !== "function")
1682
2181
  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 ?? "")) });
2182
+ const { phone, code, locale } = JSON.parse(await readBody(req));
2183
+ return json2(res, 200, {
2184
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
2185
+ });
1685
2186
  }
1686
2187
  if (url2.pathname === "/api/signout" && req.method === "POST") {
1687
- if (!sameOriginPost())
2188
+ if (!sameOriginWrite())
1688
2189
  return json2(res, 403, { error: "forbidden" });
1689
2190
  await license?.deactivate();
1690
2191
  return json2(res, 200, await license?.state() ?? { pro: false });
1691
2192
  }
1692
- if (url2.pathname === "/api/ads")
1693
- return json2(res, 200, sidebar ? [] : await ads?.() ?? []);
1694
2193
  if (url2.pathname === "/api/events") {
1695
2194
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1696
2195
  res.write(": connected\n\n");
@@ -1702,17 +2201,21 @@ data: ${JSON.stringify(data)}
1702
2201
  return void res.writeHead(204).end();
1703
2202
  if (url2.pathname.startsWith("/doc-assets/")) {
1704
2203
  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)))
2204
+ if (asset) {
2205
+ const root = await (0, import_promises3.realpath)(activeSource.dir).catch(() => null);
2206
+ asset = await (0, import_promises3.realpath)(asset).catch(() => null);
2207
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
2208
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1709
2209
  asset = null;
1710
2210
  }
1711
2211
  return sendFile(res, asset);
1712
2212
  }
1713
2213
  return sendFile(res, within(webRoot, url2.pathname === "/" ? "index.html" : url2.pathname.slice(1)));
1714
2214
  } catch (err) {
1715
- json2(res, 500, { error: err instanceof Error ? err.message : String(err) });
2215
+ if (res.headersSent)
2216
+ return void res.end();
2217
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
2218
+ json2(res, status, { error: err instanceof Error ? err.message : String(err) });
1716
2219
  }
1717
2220
  });
1718
2221
  const listen = (p2) => new Promise((ok, fail) => {
@@ -1723,15 +2226,26 @@ data: ${JSON.stringify(data)}
1723
2226
  });
1724
2227
  });
1725
2228
  try {
1726
- bound = await listen(port);
2229
+ try {
2230
+ bound = await listen(port);
2231
+ } catch (err) {
2232
+ if (err.code !== "EADDRINUSE")
2233
+ throw err;
2234
+ bound = await listen(0);
2235
+ }
1727
2236
  } catch (err) {
1728
- if (err.code !== "EADDRINUSE")
1729
- throw err;
1730
- bound = await listen(0);
2237
+ clearTimeout(pending);
2238
+ unwatch();
2239
+ unlisten();
2240
+ throw err;
1731
2241
  }
1732
2242
  return {
1733
- url: `http://${host}:${bound}${prefix}`,
1734
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
2243
+ url: `http://${urlHost}:${bound}${prefix}`,
2244
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
2245
+ allowHost: (extraHost) => {
2246
+ if (extraHost)
2247
+ allowedHosts.add(extraHost.toLowerCase());
2248
+ },
1735
2249
  close: () => new Promise((done) => {
1736
2250
  clearTimeout(pending);
1737
2251
  unwatch();
@@ -1745,7 +2259,7 @@ data: ${JSON.stringify(data)}
1745
2259
  })
1746
2260
  };
1747
2261
  }
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;
2262
+ var import_node_child_process2, import_node_crypto2, import_node_fs, import_promises3, import_node_http, import_node_os3, import_node_path3, MAX_BODY, TYPES, HttpError, LOOPBACK_HOST, hash;
1749
2263
  var init_server = __esm({
1750
2264
  "packages/cli/dist/server.js"() {
1751
2265
  "use strict";
@@ -1753,33 +2267,12 @@ var init_server = __esm({
1753
2267
  import_node_child_process2 = require("node:child_process");
1754
2268
  import_node_crypto2 = require("node:crypto");
1755
2269
  import_node_fs = require("node:fs");
1756
- import_promises2 = require("node:fs/promises");
2270
+ import_promises3 = require("node:fs/promises");
1757
2271
  import_node_http = require("node:http");
1758
- import_node_os2 = require("node:os");
1759
- import_node_path2 = require("node:path");
2272
+ import_node_os3 = require("node:os");
2273
+ import_node_path3 = require("node:path");
1760
2274
  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
- ]);
2275
+ init_workspace_fs();
1783
2276
  MAX_BODY = 20 * 1024 * 1024;
1784
2277
  TYPES = {
1785
2278
  ".html": "text/html; charset=utf-8",
@@ -1791,11 +2284,22 @@ var init_server = __esm({
1791
2284
  ".jpeg": "image/jpeg",
1792
2285
  ".gif": "image/gif",
1793
2286
  ".webp": "image/webp",
2287
+ ".avif": "image/avif",
2288
+ ".bmp": "image/bmp",
2289
+ ".ico": "image/x-icon",
1794
2290
  ".woff2": "font/woff2",
1795
2291
  ".woff": "font/woff",
1796
2292
  ".ttf": "font/ttf",
1797
2293
  ".json": "application/json"
1798
2294
  };
2295
+ HttpError = class extends Error {
2296
+ status;
2297
+ constructor(status, message) {
2298
+ super(message);
2299
+ this.status = status;
2300
+ }
2301
+ };
2302
+ LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
1799
2303
  hash = (s) => (0, import_node_crypto2.createHash)("sha1").update(s).digest("hex");
1800
2304
  }
1801
2305
  });
@@ -34494,50 +34998,50 @@ var require_fast_uri = __commonJS({
34494
34998
  schemelessOptions.skipEscape = true;
34495
34999
  return serialize2(resolved, schemelessOptions);
34496
35000
  }
34497
- function resolveComponent(base, relative3, options, skipNormalization) {
35001
+ function resolveComponent(base, relative4, options, skipNormalization) {
34498
35002
  const target = {};
34499
35003
  if (!skipNormalization) {
34500
35004
  base = parse4(serialize2(base, options), options);
34501
- relative3 = parse4(serialize2(relative3, options), options);
35005
+ relative4 = parse4(serialize2(relative4, options), options);
34502
35006
  }
34503
35007
  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;
35008
+ if (!options.tolerant && relative4.scheme) {
35009
+ target.scheme = relative4.scheme;
35010
+ target.userinfo = relative4.userinfo;
35011
+ target.host = relative4.host;
35012
+ target.port = relative4.port;
35013
+ target.path = removeDotSegments(relative4.path || "");
35014
+ target.query = relative4.query;
34511
35015
  } 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;
35016
+ if (relative4.userinfo !== void 0 || relative4.host !== void 0 || relative4.port !== void 0) {
35017
+ target.userinfo = relative4.userinfo;
35018
+ target.host = relative4.host;
35019
+ target.port = relative4.port;
35020
+ target.path = removeDotSegments(relative4.path || "");
35021
+ target.query = relative4.query;
34518
35022
  } else {
34519
- if (!relative3.path) {
35023
+ if (!relative4.path) {
34520
35024
  target.path = base.path;
34521
- if (relative3.query !== void 0) {
34522
- target.query = relative3.query;
35025
+ if (relative4.query !== void 0) {
35026
+ target.query = relative4.query;
34523
35027
  } else {
34524
35028
  target.query = base.query;
34525
35029
  }
34526
35030
  } else {
34527
- if (relative3.path[0] === "/") {
34528
- target.path = removeDotSegments(relative3.path);
35031
+ if (relative4.path[0] === "/") {
35032
+ target.path = removeDotSegments(relative4.path);
34529
35033
  } else {
34530
35034
  const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
34531
35035
  if (baseHasAuthority && !base.path) {
34532
- target.path = "/" + relative3.path;
35036
+ target.path = "/" + relative4.path;
34533
35037
  } else if (!base.path) {
34534
- target.path = relative3.path;
35038
+ target.path = relative4.path;
34535
35039
  } else {
34536
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
35040
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative4.path;
34537
35041
  }
34538
35042
  target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
34539
35043
  }
34540
- target.query = relative3.query;
35044
+ target.query = relative4.query;
34541
35045
  }
34542
35046
  target.userinfo = base.userinfo;
34543
35047
  target.host = base.host;
@@ -34545,7 +35049,7 @@ var require_fast_uri = __commonJS({
34545
35049
  }
34546
35050
  target.scheme = base.scheme;
34547
35051
  }
34548
- target.fragment = relative3.fragment;
35052
+ target.fragment = relative4.fragment;
34549
35053
  return target;
34550
35054
  }
34551
35055
  function equal(uriA, uriB, options) {
@@ -39749,286 +40253,50 @@ container holding the app. Specify either width or maxWidth, and either height o
39749
40253
  });
39750
40254
 
39751
40255
  // 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);
40256
+ function nextTargetSeq() {
40257
+ lastTargetSeq = Math.max(Date.now(), lastTargetSeq + 1);
40258
+ return lastTargetSeq;
39806
40259
  }
39807
40260
  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");
40261
+ const real = await (0, import_promises4.realpath)(filePath);
40262
+ const info = await (0, import_promises4.lstat)(real);
40263
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES || !/\.md$/i.test(real)) {
40264
+ throw new Error(say("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file up to 5 MiB."));
39812
40265
  }
39813
- const workspace = workspaceDir ? await (0, import_promises3.realpath)(workspaceDir).catch(() => findGitRoot(real)) : await findGitRoot(real);
40266
+ const workspace = workspaceDir ? await (0, import_promises4.realpath)(workspaceDir).catch(() => findProjectRoot(real)) : await findProjectRoot(real);
39814
40267
  const statePath = targetStateFile();
39815
- await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(statePath), { recursive: true, mode: 448 });
40268
+ await (0, import_promises4.mkdir)((0, import_node_path4.dirname)(statePath), { recursive: true, mode: 448 });
40269
+ const seq = nextTargetSeq();
39816
40270
  const payload = {
39817
40271
  file: real,
39818
40272
  workspace,
39819
- seq: Date.now(),
40273
+ seq,
39820
40274
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
39821
40275
  ...extra?.openInEditorPane && { openInEditorPane: true },
39822
- ...extra?.editorUrl && { editorUrl: extra.editorUrl }
40276
+ ...extra?.editorUrl && { editorUrl: extra.editorUrl },
40277
+ ...extra?.editorOnly && { editorOnly: true }
39823
40278
  };
39824
- const tmp = `${statePath}.${process.pid}.${Date.now()}`;
40279
+ const tmp = `${statePath}.${process.pid}.${seq}`;
39825
40280
  try {
39826
- await (0, import_promises3.writeFile)(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
39827
- await (0, import_promises3.rename)(tmp, statePath);
40281
+ await (0, import_promises4.writeFile)(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
40282
+ await (0, import_promises4.rename)(tmp, statePath);
39828
40283
  } catch (err) {
39829
- await (0, import_promises3.rm)(tmp, { force: true }).catch(() => {
40284
+ await (0, import_promises4.rm)(tmp, { force: true }).catch(() => {
39830
40285
  });
39831
40286
  throw err;
39832
40287
  }
39833
40288
  return payload;
39834
40289
  }
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
40290
  function createMcpWorkspaceManager() {
39930
40291
  let activeFile = null;
39931
40292
  let internalSeq = 0;
39932
- const sessionWorkspaces = /* @__PURE__ */ new Map();
40293
+ const serialized = createSerialQueue();
40294
+ const access = createWorkspaceAccess();
39933
40295
  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;
40296
+ const { roots, target } = await access.allowedRoots(extraWorkspaceUris);
40297
+ return { roots, target, effectiveSeq: Math.max(internalSeq, target?.seq || 0) };
40031
40298
  }
40299
+ const assertAllowedFile = access.assertAllowedFile;
40032
40300
  async function readDocState(filePath) {
40033
40301
  const source = await fileSource(filePath);
40034
40302
  const [md, viewState] = await Promise.all([source.read(), source.readView?.()]);
@@ -40047,25 +40315,25 @@ function createMcpWorkspaceManager() {
40047
40315
  const seen = /* @__PURE__ */ new Set();
40048
40316
  if (target && !seen.has(target.file)) {
40049
40317
  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);
40318
+ const rel = owner ? (0, import_node_path4.relative)(owner.path, target.file) : (0, import_node_path4.basename)(target.file);
40051
40319
  items.push({
40052
40320
  path: target.file,
40053
- uri: (0, import_node_url.pathToFileURL)(target.file).href,
40321
+ uri: (0, import_node_url2.pathToFileURL)(target.file).href,
40054
40322
  label: owner && roots.length > 1 ? `${owner.name} / ${rel}` : rel,
40055
40323
  group: owner?.active ? "active" : "project"
40056
40324
  });
40057
40325
  seen.add(target.file);
40058
40326
  }
40059
40327
  for (const root of roots) {
40060
- const files = await scanMarkdownFiles(root.path);
40328
+ const files = await scanMarkdownFiles(root.path, { byRecent: true });
40061
40329
  for (const entry of files) {
40062
40330
  if (seen.has(entry.path))
40063
40331
  continue;
40064
40332
  seen.add(entry.path);
40065
- const rel = (0, import_node_path3.relative)(root.path, entry.path);
40333
+ const rel = (0, import_node_path4.relative)(root.path, entry.path);
40066
40334
  items.push({
40067
40335
  path: entry.path,
40068
- uri: (0, import_node_url.pathToFileURL)(entry.path).href,
40336
+ uri: (0, import_node_url2.pathToFileURL)(entry.path).href,
40069
40337
  label: roots.length > 1 ? `${root.name} / ${rel}` : rel,
40070
40338
  group: root.active ? "active" : "project"
40071
40339
  });
@@ -40074,7 +40342,7 @@ function createMcpWorkspaceManager() {
40074
40342
  return { files: items, target, targetSeq: effectiveSeq };
40075
40343
  }
40076
40344
  return {
40077
- async open(options = {}) {
40345
+ open: (options = {}) => serialized(async () => {
40078
40346
  const extraUris = options.workspace ? [options.workspace] : [];
40079
40347
  let explicitFile = null;
40080
40348
  if (options.path?.trim()) {
@@ -40085,10 +40353,11 @@ function createMcpWorkspaceManager() {
40085
40353
  });
40086
40354
  internalSeq = Math.max(internalSeq, saved.seq);
40087
40355
  } else {
40088
- internalSeq = Math.max(internalSeq + 1, Date.now());
40356
+ internalSeq = Math.max(internalSeq + 1, nextTargetSeq());
40089
40357
  }
40090
40358
  }
40091
40359
  const { files, target, targetSeq } = await collectFiles(extraUris);
40360
+ let finalTargetSeq = targetSeq;
40092
40361
  let chosen = explicitFile;
40093
40362
  if (!chosen && target?.file)
40094
40363
  chosen = target.file;
@@ -40101,16 +40370,17 @@ function createMcpWorkspaceManager() {
40101
40370
  if (chosen && !explicitFile && options.fromModel && options.openInEditorPane) {
40102
40371
  const saved = await writeTargetSelection(chosen, options.workspace, { openInEditorPane: true });
40103
40372
  internalSeq = Math.max(internalSeq, saved.seq);
40373
+ finalTargetSeq = Math.max(finalTargetSeq, saved.seq);
40104
40374
  }
40105
40375
  if (!chosen) {
40106
40376
  return {
40107
40377
  files,
40108
40378
  currentFile: null,
40109
40379
  currentFileUri: null,
40110
- targetSeq,
40380
+ targetSeq: finalTargetSeq,
40111
40381
  doc: {
40112
40382
  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",
40383
+ md: say("# Inkmap\n\n- \u8BF7\u5728\u5F53\u524D\u5DE5\u4F5C\u533A\u4E2D\u6DFB\u52A0\u6216\u9009\u62E9\u4E00\u4EFD `.md` / `.markmap.md` \u6587\u4EF6\n- \u6216\u5728\u5BF9\u8BDD\u4E2D\u8BA9 AI \u7528 Inkmap \u6253\u5F00\u6307\u5B9A\u6587\u6863\n", "# Inkmap\n\n- Add or pick a `.md` / `.markmap.md` file in this workspace\n- Or ask the AI to open a document with Inkmap\n"),
40114
40384
  version: "empty",
40115
40385
  writable: false
40116
40386
  }
@@ -40121,17 +40391,17 @@ function createMcpWorkspaceManager() {
40121
40391
  return {
40122
40392
  files,
40123
40393
  currentFile: chosen,
40124
- currentFileUri: (0, import_node_url.pathToFileURL)(chosen).href,
40125
- targetSeq,
40394
+ currentFileUri: (0, import_node_url2.pathToFileURL)(chosen).href,
40395
+ targetSeq: finalTargetSeq,
40126
40396
  doc
40127
40397
  };
40128
- },
40129
- async poll(options = {}) {
40398
+ }),
40399
+ poll: (options = {}) => serialized(async () => {
40130
40400
  const target = await readTargetSelection();
40131
40401
  const effectiveSeq = Math.max(internalSeq, target?.seq || 0);
40132
40402
  const clientSeq = Number(options.targetSeq) || 0;
40133
- const desiredFile = target && target.seq >= internalSeq ? target.file : activeFile;
40134
- if (desiredFile && effectiveSeq > clientSeq && desiredFile !== options.file) {
40403
+ const desiredFile = target && target.seq > clientSeq && !target.editorOnly ? target.file : null;
40404
+ if (desiredFile && desiredFile !== options.file) {
40135
40405
  activeFile = desiredFile;
40136
40406
  const [{ doc }, { files }] = await Promise.all([
40137
40407
  readDocState(desiredFile),
@@ -40139,7 +40409,7 @@ function createMcpWorkspaceManager() {
40139
40409
  ]);
40140
40410
  return {
40141
40411
  switchedFile: desiredFile,
40142
- currentFileUri: (0, import_node_url.pathToFileURL)(desiredFile).href,
40412
+ currentFileUri: (0, import_node_url2.pathToFileURL)(desiredFile).href,
40143
40413
  files,
40144
40414
  targetSeq: effectiveSeq,
40145
40415
  doc
@@ -40158,14 +40428,14 @@ function createMcpWorkspaceManager() {
40158
40428
  } catch {
40159
40429
  return { unchanged: true, targetSeq: effectiveSeq };
40160
40430
  }
40161
- },
40162
- async save(options) {
40431
+ }),
40432
+ save: (options) => serialized(async () => {
40163
40433
  const target = options.file || activeFile;
40164
40434
  if (!target)
40165
- throw new Error("\u672A\u9009\u62E9\u8981\u4FDD\u5B58\u7684 Markdown \u6587\u4EF6\u3002");
40435
+ throw new Error(say("\u672A\u9009\u62E9\u8981\u4FDD\u5B58\u7684 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected to save."));
40166
40436
  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");
40437
+ if (typeof options.md !== "string" || Buffer.byteLength(options.md, "utf8") > MAX_MARKDOWN_BYTES) {
40438
+ throw new Error(say("Markdown \u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7 5 MiB \u9650\u5236\u3002", "The Markdown is invalid or larger than 5 MiB."));
40169
40439
  }
40170
40440
  const { source, doc } = await readDocState(file2);
40171
40441
  if (options.baseVersion && options.baseVersion !== doc.version) {
@@ -40176,8 +40446,8 @@ function createMcpWorkspaceManager() {
40176
40446
  }
40177
40447
  activeFile = file2;
40178
40448
  return { ok: true, version: sha1(options.md) };
40179
- },
40180
- async saveView(options) {
40449
+ }),
40450
+ saveView: (options) => serialized(async () => {
40181
40451
  const target = options.file || activeFile;
40182
40452
  if (!target)
40183
40453
  return { ok: false };
@@ -40191,46 +40461,22 @@ function createMcpWorkspaceManager() {
40191
40461
  });
40192
40462
  }
40193
40463
  return { ok: true };
40194
- }
40464
+ })
40195
40465
  };
40196
40466
  }
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;
40467
+ var import_node_crypto3, import_promises4, import_node_path4, import_node_url2, sha1, lastTargetSeq;
40198
40468
  var init_mcp_files = __esm({
40199
40469
  "packages/cli/dist/mcp-files.js"() {
40200
40470
  "use strict";
40201
40471
  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");
40472
+ import_promises4 = require("node:fs/promises");
40473
+ import_node_path4 = require("node:path");
40474
+ import_node_url2 = require("node:url");
40206
40475
  init_dist();
40207
40476
  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
- ]);
40477
+ init_workspace_fs();
40233
40478
  sha1 = (text) => (0, import_node_crypto3.createHash)("sha1").update(text).digest("hex");
40479
+ lastTargetSeq = 0;
40234
40480
  }
40235
40481
  });
40236
40482
 
@@ -40241,33 +40487,49 @@ __export(codex_exports, {
40241
40487
  serveCodex: () => serveCodex
40242
40488
  });
40243
40489
  function resolveWebRoot() {
40244
- return WEB_ROOT_CANDIDATES.find((dir) => (0, import_node_fs2.existsSync)((0, import_node_path4.join)(dir, "index.html"))) ?? null;
40490
+ return WEB_ROOT_CANDIDATES.find((dir) => (0, import_node_fs2.existsSync)((0, import_node_path5.join)(dir, "index.html"))) ?? null;
40245
40491
  }
40246
40492
  function openSystemBrowser(url2) {
40247
40493
  if (process.env.INKMAP_NO_OPEN === "1")
40248
40494
  return;
40249
40495
  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();
40496
+ const child = (0, import_node_child_process3.spawn)(cmd, args, { stdio: "ignore", detached: true });
40497
+ child.on("error", () => {
40498
+ });
40499
+ child.unref();
40500
+ }
40501
+ async function validatedMarkdownFile(path) {
40502
+ if (!path || !/\.md$/i.test(path))
40503
+ throw new Error(say("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002", "Choose a .md or .markmap.md file."));
40504
+ const info = await (0, import_promises5.lstat)(path);
40505
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_MARKDOWN_BYTES) {
40506
+ throw new Error(say("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002", "Choose a regular Markdown file up to 5 MiB."));
40507
+ }
40508
+ const real = await (0, import_promises5.realpath)(path);
40509
+ const home = await (0, import_promises5.realpath)((0, import_node_os4.homedir)()).catch(() => (0, import_node_os4.homedir)());
40510
+ if (!/\.md$/i.test(real) || insideOrEqual(home, real) && hasHiddenSegment(home, real)) {
40511
+ throw new Error(say("\u4E0D\u652F\u6301\u8BBF\u95EE\u8BE5\u6587\u4EF6\u3002", "This file cannot be opened."));
40512
+ }
40513
+ return real;
40251
40514
  }
40252
40515
  async function createInkmapMcpServer(options = {}) {
40253
40516
  const loadHtml = async () => {
40254
- const raw = options.html ?? await (0, import_promises4.readFile)(HTML, "utf8").catch((error62) => {
40517
+ const raw = options.html ?? await (0, import_promises5.readFile)(HTML, "utf8").catch((error62) => {
40255
40518
  if (error62.code === "ENOENT") {
40256
40519
  throw new Error("MCP App editor assets are missing. Run npm run build:sidebars.");
40257
40520
  }
40258
40521
  throw error62;
40259
40522
  });
40260
40523
  const osLoc = detectOsLocale();
40261
- return raw.replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
40524
+ return raw.replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
40262
40525
  };
40263
40526
  await loadHtml();
40264
40527
  const billingOrigin2 = options.billingOrigin ?? (() => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN);
40265
40528
  const billing = licenseService(fileSessionStorage(), billingOrigin2, { loginOnly: true });
40266
40529
  let browserBilling;
40267
40530
  const fallbackEditors = /* @__PURE__ */ new Map();
40268
- const ads = adFeed(PRODUCT.adFeedUrl);
40269
40531
  const workspaces = createMcpWorkspaceManager();
40270
- const server = new McpServer({ name: "inkmap", version: "0.3.10" });
40532
+ const server = new McpServer({ name: "inkmap", version: INKMAP_VERSION });
40271
40533
  function isAntigravityHost() {
40272
40534
  const clientName = server.server.getClientVersion()?.name ?? "";
40273
40535
  if (/antigravity/i.test(clientName))
@@ -40305,9 +40567,9 @@ async function createInkmapMcpServer(options = {}) {
40305
40567
  const clientName = server.server.getClientVersion()?.name ?? "";
40306
40568
  let extDir = null;
40307
40569
  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");
40570
+ extDir = (0, import_node_path5.join)(process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".cursor"), "extensions");
40309
40571
  } else if (/visual studio code|vscode/i.test(clientName)) {
40310
- extDir = (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".vscode", "extensions");
40572
+ extDir = (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".vscode", "extensions");
40311
40573
  }
40312
40574
  if (!extDir || !(0, import_node_fs2.existsSync)(extDir))
40313
40575
  return false;
@@ -40327,12 +40589,12 @@ async function createInkmapMcpServer(options = {}) {
40327
40589
  async function waitForEditorBridgeAck(seq, timeoutMs = 280) {
40328
40590
  if (!seq)
40329
40591
  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");
40592
+ const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".inkmap");
40593
+ const ackPath = (0, import_node_path5.join)(inkmapDir, "antigravity-target-ack.json");
40332
40594
  const deadline = Date.now() + timeoutMs;
40333
40595
  while (Date.now() < deadline) {
40334
40596
  try {
40335
- const raw = JSON.parse(await (0, import_promises4.readFile)(ackPath, "utf8"));
40597
+ const raw = JSON.parse(await (0, import_promises5.readFile)(ackPath, "utf8"));
40336
40598
  if (raw && raw.ok === true && Number(raw.seq) >= seq) {
40337
40599
  return true;
40338
40600
  }
@@ -40356,9 +40618,7 @@ async function createInkmapMcpServer(options = {}) {
40356
40618
  webRoot,
40357
40619
  port: 0,
40358
40620
  license: browserBilling,
40359
- ads,
40360
40621
  sidebar: false,
40361
- loginOnly: false,
40362
40622
  ideWorkspace: false
40363
40623
  });
40364
40624
  })();
@@ -40366,7 +40626,7 @@ async function createInkmapMcpServer(options = {}) {
40366
40626
  pending.catch(() => fallbackEditors.delete("__workspace__"));
40367
40627
  }
40368
40628
  const served = await pending;
40369
- await served.switchToFile?.(filePath).catch(() => {
40629
+ await served.switchToFile?.(filePath, { trustCaller: true }).catch(() => {
40370
40630
  });
40371
40631
  if (launchSystemBrowser) {
40372
40632
  openSystemBrowser(served.url);
@@ -40440,7 +40700,7 @@ async function createInkmapMcpServer(options = {}) {
40440
40700
  currentFileUri: opened.currentFileUri,
40441
40701
  targetSeq: opened.targetSeq,
40442
40702
  license: { ...license },
40443
- ...openInRightEditor && { openedInEditorPane: true },
40703
+ ...(ackedByExtension || cursorHost) && { openedInEditorPane: true },
40444
40704
  ...ackedByExtension && { ackedByExtension: true },
40445
40705
  ...editorUrl && { editorUrl },
40446
40706
  ...includeDoc && { doc: opened.doc }
@@ -40497,7 +40757,7 @@ async function createInkmapMcpServer(options = {}) {
40497
40757
  _meta: appOnly
40498
40758
  }, async ({ file: file2, md, baseVersion }) => {
40499
40759
  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");
40760
+ throw new Error(say("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro \u6743\u76CA\u3002", "The Inkmap trial has ended. Sign in with the account that bought Pro to restore it."));
40501
40761
  }
40502
40762
  const saved = await workspaces.save({ file: file2, md, baseVersion });
40503
40763
  if (saved.ok)
@@ -40525,13 +40785,14 @@ async function createInkmapMcpServer(options = {}) {
40525
40785
  _meta: appOnly
40526
40786
  }, async ({ file: file2 }) => {
40527
40787
  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");
40788
+ throw new Error(say("Inkmap \u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u6062\u590D Pro \u6743\u76CA\u3002", "The Inkmap trial has ended. Sign in with the account that bought Pro to restore it."));
40529
40789
  }
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");
40790
+ const hostFile = file2?.startsWith("file://") ? await validatedMarkdownFile(uriToPath(file2)) : null;
40791
+ const target = hostFile ?? (await workspaces.open({ path: file2, fromModel: false })).currentFile;
40792
+ if (!target)
40793
+ throw new Error(say("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected."));
40533
40794
  billing.track?.("feature_browser", 1, detectMcpHost());
40534
- const url2 = await openFallbackBrowserEditor(opened.currentFile);
40795
+ const url2 = await openFallbackBrowserEditor(target);
40535
40796
  return { content: [], structuredContent: { url: url2 ?? "" } };
40536
40797
  });
40537
40798
  server.registerTool("inkmap_focus_editor", {
@@ -40544,10 +40805,12 @@ async function createInkmapMcpServer(options = {}) {
40544
40805
  }, async ({ file: file2 }) => {
40545
40806
  const opened = await workspaces.open({ path: file2, fromModel: false });
40546
40807
  if (!opened.currentFile)
40547
- throw new Error("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002");
40808
+ throw new Error(say("\u672A\u9009\u62E9 Markdown \u6587\u4EF6\u3002", "No Markdown file is selected."));
40548
40809
  const url2 = await openFallbackBrowserEditor(opened.currentFile, false);
40549
40810
  const payload = await writeTargetSelection(opened.currentFile, void 0, {
40550
40811
  openInEditorPane: true,
40812
+ // Asked for by one panel's UI: the IDE focuses the file, other open panels stay on their documents.
40813
+ editorOnly: true,
40551
40814
  ...url2 && { editorUrl: url2 }
40552
40815
  });
40553
40816
  const acked = await waitForEditorBridgeAck(payload.seq, 450);
@@ -40575,10 +40838,10 @@ async function createInkmapMcpServer(options = {}) {
40575
40838
  }, async ({ phone, locale }) => ({ content: [], structuredContent: { result: await billing.sendPhoneCode(phone, locale) } }));
40576
40839
  server.registerTool("inkmap_phone_verify", {
40577
40840
  title: "Verify phone sign-in code",
40578
- inputSchema: { phone: external_exports.string(), code: external_exports.string() },
40841
+ inputSchema: { phone: external_exports.string(), code: external_exports.string(), locale: external_exports.string().optional() },
40579
40842
  annotations: { destructiveHint: false },
40580
40843
  _meta: appOnly
40581
- }, async ({ phone, code }) => ({ content: [], structuredContent: { result: await billing.signInByPhone(phone, code) } }));
40844
+ }, async ({ phone, code, locale }) => ({ content: [], structuredContent: { result: await billing.signInByPhone(phone, code, locale) } }));
40582
40845
  server.registerTool("inkmap_disconnect_access", {
40583
40846
  title: "Disconnect Inkmap access",
40584
40847
  annotations: { destructiveHint: true },
@@ -40597,7 +40860,7 @@ async function serveCodex() {
40597
40860
  };
40598
40861
  await server.connect(transport);
40599
40862
  }
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;
40863
+ var import_node_child_process3, import_node_fs2, import_promises5, import_node_os4, import_node_path5, import_node_url3, UI, HTML, WEB_ROOT_CANDIDATES, INLINE_DOC_LIMIT, appOnly;
40601
40864
  var init_codex = __esm({
40602
40865
  "packages/cli/dist/codex.js"() {
40603
40866
  "use strict";
@@ -40606,21 +40869,23 @@ var init_codex = __esm({
40606
40869
  init_server4();
40607
40870
  import_node_child_process3 = require("node:child_process");
40608
40871
  import_node_fs2 = require("node:fs");
40609
- import_promises4 = require("node:fs/promises");
40872
+ import_promises5 = require("node:fs/promises");
40610
40873
  import_node_os4 = require("node:os");
40611
- import_node_path4 = require("node:path");
40612
- import_node_url2 = require("node:url");
40874
+ import_node_path5 = require("node:path");
40875
+ import_node_url3 = require("node:url");
40613
40876
  init_zod();
40614
40877
  init_dist();
40615
40878
  init_license();
40616
40879
  init_mcp_files();
40880
+ init_version();
40881
+ init_workspace_fs();
40617
40882
  init_server();
40618
40883
  UI = "ui://inkmap/markdown.html";
40619
40884
  HTML = new URL("./codex.html", inkmapModuleUrl);
40620
40885
  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))
40886
+ (0, import_node_url3.fileURLToPath)(new URL("./web/", inkmapModuleUrl)),
40887
+ (0, import_node_url3.fileURLToPath)(new URL("./sidecars/inkmap/web/", inkmapModuleUrl)),
40888
+ (0, import_node_url3.fileURLToPath)(new URL("../web/", inkmapModuleUrl))
40624
40889
  ];
40625
40890
  INLINE_DOC_LIMIT = 256 * 1024;
40626
40891
  appOnly = { ui: { visibility: ["app"] } };
@@ -40630,9 +40895,46 @@ var init_codex = __esm({
40630
40895
  // packages/cli/dist/install.js
40631
40896
  var install_exports = {};
40632
40897
  __export(install_exports, {
40633
- runInstall: () => runInstall,
40634
40898
  runInstallCli: () => runInstallCli
40635
40899
  });
40900
+ function quoteWinArg(arg) {
40901
+ return `"${arg.replace(/"/g, '""').replace(/%/g, '"^%"')}"`;
40902
+ }
40903
+ function probeCliCommand(cmd, args = ["--version"]) {
40904
+ try {
40905
+ if (process.platform === "win32" && !cmd.toLowerCase().endsWith(".exe")) {
40906
+ const commandLine = `"${[cmd, ...args].map(quoteWinArg).join(" ")}"`;
40907
+ const res = (0, import_node_child_process4.spawnSync)("cmd.exe", ["/d", "/s", "/c", commandLine], {
40908
+ stdio: "ignore",
40909
+ windowsVerbatimArguments: true,
40910
+ windowsHide: true
40911
+ });
40912
+ return res.status === 0;
40913
+ }
40914
+ return (0, import_node_child_process4.spawnSync)(cmd, args, { stdio: "ignore" }).status === 0;
40915
+ } catch {
40916
+ return false;
40917
+ }
40918
+ }
40919
+ function execCliSync(cmd, args, options = {}) {
40920
+ if (process.platform === "win32" && !cmd.toLowerCase().endsWith(".exe")) {
40921
+ const commandLine = `"${[cmd, ...args].map(quoteWinArg).join(" ")}"`;
40922
+ const res = (0, import_node_child_process4.spawnSync)("cmd.exe", ["/d", "/s", "/c", commandLine], {
40923
+ ...options,
40924
+ encoding: options.encoding ?? "utf8",
40925
+ stdio: options.stdio ?? "pipe",
40926
+ windowsVerbatimArguments: true,
40927
+ windowsHide: true
40928
+ });
40929
+ if (res.error)
40930
+ throw res.error;
40931
+ if (res.status !== 0) {
40932
+ throw new Error(String(res.stderr || res.stdout || `${cmd} exited with code ${res.status}`).trim());
40933
+ }
40934
+ return String(res.stdout ?? "");
40935
+ }
40936
+ return (0, import_node_child_process4.execFileSync)(cmd, args, options) ?? "";
40937
+ }
40636
40938
  function crc32(buf) {
40637
40939
  let c = 4294967295;
40638
40940
  for (let i = 0; i < buf.length; i++) {
@@ -40724,47 +41026,47 @@ function isChineseTerminalLocale() {
40724
41026
  return detectOsLocale() === "zh";
40725
41027
  }
40726
41028
  function getInkmapHome() {
40727
- return process.env.INKMAP_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".inkmap");
41029
+ return process.env.INKMAP_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".inkmap");
40728
41030
  }
40729
41031
  function getClaudeDesktopDir() {
40730
41032
  if (process.env.INKMAP_CLAUDE_CONFIG_DIR)
40731
41033
  return process.env.INKMAP_CLAUDE_CONFIG_DIR;
40732
41034
  if (process.platform === "darwin") {
40733
- return (0, import_node_path5.join)((0, import_node_os5.homedir)(), "Library", "Application Support", "Claude");
41035
+ return (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Library", "Application Support", "Claude");
40734
41036
  }
40735
41037
  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");
41038
+ const appData = process.env.APPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Roaming");
41039
+ return (0, import_node_path6.join)(appData, "Claude");
40738
41040
  }
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");
41041
+ const xdg = process.env.XDG_CONFIG_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".config");
41042
+ return (0, import_node_path6.join)(xdg, "Claude");
40741
41043
  }
40742
41044
  function getCursorDir() {
40743
- return process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".cursor");
41045
+ return process.env.INKMAP_CURSOR_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".cursor");
40744
41046
  }
40745
41047
  function getVscodeDir() {
40746
- return process.env.INKMAP_VSCODE_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".vscode");
41048
+ return process.env.INKMAP_VSCODE_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".vscode");
40747
41049
  }
40748
41050
  function getClaudeCodeConfigPath() {
40749
- return process.env.INKMAP_CLAUDE_CODE_CONFIG || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".claude.json");
41051
+ return process.env.INKMAP_CLAUDE_CODE_CONFIG || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".claude.json");
40750
41052
  }
40751
41053
  function getAntigravityConfigDir() {
40752
- return process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".gemini", "config");
41054
+ return process.env.ANTIGRAVITY_CONFIG_DIR || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".gemini", "config");
40753
41055
  }
40754
41056
  function findCursorCommand() {
40755
41057
  if (process.env.INKMAP_ISOLATED_DETECT)
40756
41058
  return null;
40757
- if ((0, import_node_child_process4.spawnSync)("cursor", ["--version"], { stdio: "ignore" }).status === 0)
41059
+ if (probeCliCommand("cursor"))
40758
41060
  return "cursor";
40759
41061
  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");
41062
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41063
+ const cmd = (0, import_node_path6.join)(dir, "Cursor.app/Contents/Resources/app/bin/cursor");
40762
41064
  if ((0, import_node_fs3.existsSync)(cmd))
40763
41065
  return cmd;
40764
41066
  }
40765
41067
  } 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");
41068
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41069
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "cursor", "resources", "app", "bin", "cursor.cmd");
40768
41070
  if ((0, import_node_fs3.existsSync)(cmd))
40769
41071
  return cmd;
40770
41072
  }
@@ -40773,17 +41075,17 @@ function findCursorCommand() {
40773
41075
  function findVscodeCommand() {
40774
41076
  if (process.env.INKMAP_ISOLATED_DETECT)
40775
41077
  return null;
40776
- if ((0, import_node_child_process4.spawnSync)("code", ["--version"], { stdio: "ignore" }).status === 0)
41078
+ if (probeCliCommand("code"))
40777
41079
  return "code";
40778
41080
  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");
41081
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41082
+ const cmd = (0, import_node_path6.join)(dir, "Visual Studio Code.app/Contents/Resources/app/bin/code");
40781
41083
  if ((0, import_node_fs3.existsSync)(cmd))
40782
41084
  return cmd;
40783
41085
  }
40784
41086
  } 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");
41087
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41088
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "Microsoft VS Code", "bin", "code.cmd");
40787
41089
  if ((0, import_node_fs3.existsSync)(cmd))
40788
41090
  return cmd;
40789
41091
  }
@@ -40793,11 +41095,11 @@ function findCodexCommand() {
40793
41095
  if (process.env.INKMAP_CODEX_BIN) {
40794
41096
  return (0, import_node_fs3.existsSync)(process.env.INKMAP_CODEX_BIN) ? process.env.INKMAP_CODEX_BIN : null;
40795
41097
  }
40796
- if ((0, import_node_child_process4.spawnSync)("codex", ["--version"], { stdio: "ignore" }).status === 0)
41098
+ if (probeCliCommand("codex"))
40797
41099
  return "codex";
40798
41100
  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");
41101
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41102
+ const cmd = (0, import_node_path6.join)(dir, "ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
40801
41103
  if ((0, import_node_fs3.existsSync)(cmd))
40802
41104
  return cmd;
40803
41105
  }
@@ -40805,7 +41107,7 @@ function findCodexCommand() {
40805
41107
  return null;
40806
41108
  }
40807
41109
  function getDshHome() {
40808
- return process.env.DSH_HOME || (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".dsh");
41110
+ return process.env.DSH_HOME || (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".dsh");
40809
41111
  }
40810
41112
  function findDshCommand() {
40811
41113
  if (process.env.INKMAP_DSH_BIN) {
@@ -40813,17 +41115,17 @@ function findDshCommand() {
40813
41115
  }
40814
41116
  if (process.env.INKMAP_ISOLATED_DETECT)
40815
41117
  return null;
40816
- if ((0, import_node_child_process4.spawnSync)("dsh", ["--version"], { stdio: "ignore" }).status === 0)
41118
+ if (probeCliCommand("dsh"))
40817
41119
  return "dsh";
40818
41120
  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");
41121
+ for (const dir of ["/Applications", (0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications")]) {
41122
+ const cmd = (0, import_node_path6.join)(dir, "DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
40821
41123
  if ((0, import_node_fs3.existsSync)(cmd))
40822
41124
  return cmd;
40823
41125
  }
40824
41126
  } 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");
41127
+ const localApp = process.env.LOCALAPPDATA || (0, import_node_path6.join)((0, import_node_os5.homedir)(), "AppData", "Local");
41128
+ const cmd = (0, import_node_path6.join)(localApp, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd");
40827
41129
  if ((0, import_node_fs3.existsSync)(cmd))
40828
41130
  return cmd;
40829
41131
  }
@@ -40832,18 +41134,18 @@ function findDshCommand() {
40832
41134
  function detectInstalledTargets() {
40833
41135
  const found = [];
40834
41136
  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")))) {
41137
+ if ((0, import_node_fs3.existsSync)(claudeDir) || process.platform === "darwin" && ((0, import_node_fs3.existsSync)("/Applications/Claude.app") || (0, import_node_fs3.existsSync)((0, import_node_path6.join)((0, import_node_os5.homedir)(), "Applications", "Claude.app")))) {
40836
41138
  found.push("claude");
40837
41139
  }
40838
41140
  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) {
41141
+ if ((0, import_node_fs3.existsSync)(claudeCodeCfg) || !process.env.INKMAP_ISOLATED_DETECT && probeCliCommand("claude")) {
40840
41142
  found.push("claude-code");
40841
41143
  }
40842
41144
  if ((0, import_node_fs3.existsSync)(getCursorDir()) || Boolean(findCursorCommand())) {
40843
41145
  found.push("cursor");
40844
41146
  }
40845
41147
  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"))) {
41148
+ if ((0, import_node_fs3.existsSync)(agyDir) || !process.env.ANTIGRAVITY_CONFIG_DIR && (0, import_node_fs3.existsSync)((0, import_node_path6.join)((0, import_node_os5.homedir)(), ".gemini", "antigravity"))) {
40847
41149
  found.push("antigravity");
40848
41150
  }
40849
41151
  if (!process.env.INKMAP_ISOLATED_DETECT && findCodexCommand()) {
@@ -40851,7 +41153,7 @@ function detectInstalledTargets() {
40851
41153
  } else if (process.env.INKMAP_CODEX_BIN && (0, import_node_fs3.existsSync)(process.env.INKMAP_CODEX_BIN)) {
40852
41154
  found.push("codex");
40853
41155
  }
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)) {
41156
+ if (!process.env.INKMAP_ISOLATED_DETECT && (findDshCommand() || (0, import_node_fs3.existsSync)((0, import_node_path6.join)(getDshHome(), "profiles", "desktop"))) || process.env.INKMAP_DSH_BIN && (0, import_node_fs3.existsSync)(process.env.INKMAP_DSH_BIN)) {
40855
41157
  found.push("deepseek");
40856
41158
  }
40857
41159
  return found;
@@ -40874,73 +41176,73 @@ function readJsonObject(filePath) {
40874
41176
  return parsed;
40875
41177
  }
40876
41178
  function writeJsonAtomic(filePath, data) {
40877
- (0, import_node_fs3.mkdirSync)((0, import_node_path5.dirname)(filePath), { recursive: true });
41179
+ (0, import_node_fs3.mkdirSync)((0, import_node_path6.dirname)(filePath), { recursive: true });
40878
41180
  const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
40879
41181
  (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
40880
41182
  (0, import_node_fs3.renameSync)(tmp, filePath);
40881
41183
  }
40882
41184
  function stageStandaloneMcpApp() {
40883
- const appDir = (0, import_node_path5.join)(getInkmapHome(), "mcp-app");
41185
+ const appDir = (0, import_node_path6.join)(getInkmapHome(), "mcp-app");
40884
41186
  (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");
41187
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41188
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41189
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41190
+ const monorepoAntigravity = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
40889
41191
  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"));
41192
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(appDir, "cli.cjs"));
41193
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(appDir, "codex.html"));
40892
41194
  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 });
41195
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(appDir, "web"), { recursive: true, force: true });
41196
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(appDir, "web"), { recursive: true });
40895
41197
  }
40896
- (0, import_node_fs3.writeFileSync)((0, import_node_path5.join)(appDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41198
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(appDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
40897
41199
  for (const notice of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40898
- const src = (0, import_node_path5.join)(PKG_ROOT, notice);
41200
+ const src = (0, import_node_path6.join)(PKG_ROOT, notice);
40899
41201
  if ((0, import_node_fs3.existsSync)(src))
40900
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(appDir, notice));
41202
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(appDir, notice));
40901
41203
  }
40902
- return { serverScript: (0, import_node_path5.join)(appDir, "server.cjs"), appDir };
41204
+ return { serverScript: (0, import_node_path6.join)(appDir, "server.cjs"), appDir };
40903
41205
  }
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");
41206
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAntigravity, "server.cjs")) && (0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAntigravity, "codex.html"))) {
41207
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoAntigravity, "server.cjs"), (0, import_node_path6.join)(appDir, "server.cjs"));
41208
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoAntigravity, "codex.html"), (0, import_node_path6.join)(appDir, "codex.html"));
41209
+ const sidecarWeb = (0, import_node_path6.join)(monorepoAntigravity, "sidecars", "inkmap", "web");
40908
41210
  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 });
41211
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(appDir, "web"), { recursive: true, force: true });
41212
+ (0, import_node_fs3.cpSync)(sidecarWeb, (0, import_node_path6.join)(appDir, "web"), { recursive: true });
40911
41213
  }
40912
41214
  for (const notice of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
40913
- const src = (0, import_node_path5.join)(monorepoAntigravity, notice);
41215
+ const src = (0, import_node_path6.join)(monorepoAntigravity, notice);
40914
41216
  if ((0, import_node_fs3.existsSync)(src))
40915
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(appDir, notice));
41217
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(appDir, notice));
40916
41218
  }
40917
- return { serverScript: (0, import_node_path5.join)(appDir, "server.cjs"), appDir };
41219
+ return { serverScript: (0, import_node_path6.join)(appDir, "server.cjs"), appDir };
40918
41220
  }
40919
- const devBin = (0, import_node_path5.join)(PKG_ROOT, "bin", "inkmap.js");
41221
+ const devBin = (0, import_node_path6.join)(PKG_ROOT, "bin", "inkmap.js");
40920
41222
  if ((0, import_node_fs3.existsSync)(devBin) && (0, import_node_fs3.existsSync)(bundledHtml)) {
40921
41223
  return { serverScript: devBin, appDir };
40922
41224
  }
40923
41225
  throw new Error("\u672A\u627E\u5230\u5DF2\u6784\u5EFA\u7684 MCP App \u8D44\u6E90\uFF08codex.html\uFF09\u3002/ Built MCP App assets are missing.");
40924
41226
  }
40925
41227
  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"))) {
41228
+ const vscodeBundle = (0, import_node_path6.join)(DIST_DIR, "bundles", "vscode");
41229
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41230
+ if (!(0, import_node_fs3.existsSync)((0, import_node_path6.join)(vscodeBundle, "package.json")) || !(0, import_node_fs3.existsSync)((0, import_node_path6.join)(vscodeBundle, "dist", "extension.js"))) {
40929
41231
  return null;
40930
41232
  }
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-"));
41233
+ const extPkg = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path6.join)(vscodeBundle, "package.json"), "utf8"));
41234
+ const version2 = extPkg.version;
41235
+ const staging = (0, import_node_fs3.mkdtempSync)((0, import_node_path6.join)((0, import_node_os5.tmpdir)(), "inkmap-vsix-"));
40934
41236
  try {
40935
- const extStaging = (0, import_node_path5.join)(staging, "extension");
41237
+ const extStaging = (0, import_node_path6.join)(staging, "extension");
40936
41238
  (0, import_node_fs3.cpSync)(vscodeBundle, extStaging, { recursive: true });
40937
41239
  if ((0, import_node_fs3.existsSync)(bundledWeb)) {
40938
- (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path5.join)(extStaging, "dist", "web"), { recursive: true });
41240
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(extStaging, "dist", "web"), { recursive: true });
40939
41241
  }
40940
41242
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md", "README.md"]) {
40941
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41243
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
40942
41244
  if ((0, import_node_fs3.existsSync)(src))
40943
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(extStaging, doc));
41245
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(extStaging, doc));
40944
41246
  }
40945
41247
  if (cliCmd) {
40946
41248
  const contentTypesXml = `<?xml version="1.0" encoding="utf-8"?>
@@ -40953,7 +41255,7 @@ function installIdeExtension(editorDir, cliCmd) {
40953
41255
  ];
40954
41256
  const walk = (dir, prefix) => {
40955
41257
  for (const item of (0, import_node_fs3.readdirSync)(dir, { withFileTypes: true })) {
40956
- const full = (0, import_node_path5.join)(dir, item.name);
41258
+ const full = (0, import_node_path6.join)(dir, item.name);
40957
41259
  const rel = `${prefix}/${item.name}`;
40958
41260
  if (item.isDirectory())
40959
41261
  walk(full, rel);
@@ -40962,23 +41264,65 @@ function installIdeExtension(editorDir, cliCmd) {
40962
41264
  }
40963
41265
  };
40964
41266
  walk(extStaging, "extension");
40965
- const vsixPath = (0, import_node_path5.join)(staging, `inkmap-${version2}.vsix`);
41267
+ const vsixPath = (0, import_node_path6.join)(staging, `inkmap-${version2}.vsix`);
40966
41268
  (0, import_node_fs3.writeFileSync)(vsixPath, buildZipBuffer(entries));
40967
41269
  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}`);
41270
+ execCliSync(cliCmd, ["--install-extension", vsixPath, "--force"], { stdio: "pipe" });
41271
+ return (0, import_node_path6.join)(editorDir, "extensions", `inkmap.inkmap-vscode-${version2}`);
40970
41272
  } catch {
40971
41273
  }
40972
41274
  }
40973
- const extRoot = (0, import_node_path5.join)(editorDir, "extensions");
41275
+ const extRoot = (0, import_node_path6.join)(editorDir, "extensions");
40974
41276
  (0, import_node_fs3.mkdirSync)(extRoot, { recursive: true });
40975
41277
  for (const old of (0, import_node_fs3.readdirSync)(extRoot)) {
40976
41278
  if (old.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
40977
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(extRoot, old), { recursive: true, force: true });
41279
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(extRoot, old), { recursive: true, force: true });
40978
41280
  }
40979
41281
  }
40980
- const dest = (0, import_node_path5.join)(extRoot, `inkmap.inkmap-vscode-${version2}`);
41282
+ const folderName = `inkmap.inkmap-vscode-${version2}`;
41283
+ const dest = (0, import_node_path6.join)(extRoot, folderName);
40981
41284
  (0, import_node_fs3.cpSync)(extStaging, dest, { recursive: true });
41285
+ try {
41286
+ const obsoletePath = (0, import_node_path6.join)(extRoot, ".obsolete");
41287
+ if ((0, import_node_fs3.existsSync)(obsoletePath)) {
41288
+ const obs = JSON.parse((0, import_node_fs3.readFileSync)(obsoletePath, "utf8"));
41289
+ let changedObs = false;
41290
+ for (const key of Object.keys(obs)) {
41291
+ if (key.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
41292
+ delete obs[key];
41293
+ changedObs = true;
41294
+ }
41295
+ }
41296
+ if (changedObs)
41297
+ writeJsonAtomic(obsoletePath, obs);
41298
+ }
41299
+ const registryPath = (0, import_node_path6.join)(extRoot, "extensions.json");
41300
+ const existingList = (0, import_node_fs3.existsSync)(registryPath) ? JSON.parse((0, import_node_fs3.readFileSync)(registryPath, "utf8")) : [];
41301
+ if (Array.isArray(existingList)) {
41302
+ const filtered = existingList.filter((item) => String(item?.identifier?.id ?? "").toLowerCase() !== "inkmap.inkmap-vscode");
41303
+ const destUrl = (0, import_node_url4.pathToFileURL)(dest);
41304
+ filtered.push({
41305
+ identifier: { id: "inkmap.inkmap-vscode" },
41306
+ version: version2,
41307
+ location: {
41308
+ $mid: 1,
41309
+ fsPath: dest,
41310
+ external: destUrl.href,
41311
+ path: destUrl.pathname,
41312
+ scheme: "file"
41313
+ },
41314
+ relativeLocation: folderName,
41315
+ metadata: {
41316
+ installedTimestamp: Date.now(),
41317
+ source: "vsix"
41318
+ }
41319
+ });
41320
+ const tmp = `${registryPath}.${process.pid}.${Date.now()}.tmp`;
41321
+ (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(filtered), "utf8");
41322
+ (0, import_node_fs3.renameSync)(tmp, registryPath);
41323
+ }
41324
+ } catch {
41325
+ }
40982
41326
  return dest;
40983
41327
  } finally {
40984
41328
  (0, import_node_fs3.rmSync)(staging, { recursive: true, force: true });
@@ -40988,19 +41332,34 @@ function uninstallIdeExtension(editorDir, cliCmd) {
40988
41332
  let removed = false;
40989
41333
  if (cliCmd) {
40990
41334
  try {
40991
- (0, import_node_child_process4.execFileSync)(cliCmd, ["--uninstall-extension", "inkmap.inkmap-vscode"], { stdio: "pipe" });
41335
+ execCliSync(cliCmd, ["--uninstall-extension", "inkmap.inkmap-vscode"], { stdio: "pipe" });
40992
41336
  removed = true;
40993
41337
  } catch {
40994
41338
  }
40995
41339
  }
40996
- const extRoot = (0, import_node_path5.join)(editorDir, "extensions");
41340
+ const extRoot = (0, import_node_path6.join)(editorDir, "extensions");
40997
41341
  if ((0, import_node_fs3.existsSync)(extRoot)) {
40998
41342
  for (const entry of (0, import_node_fs3.readdirSync)(extRoot)) {
40999
41343
  if (entry.toLowerCase().startsWith("inkmap.inkmap-vscode")) {
41000
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(extRoot, entry), { recursive: true, force: true });
41344
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(extRoot, entry), { recursive: true, force: true });
41001
41345
  removed = true;
41002
41346
  }
41003
41347
  }
41348
+ try {
41349
+ const registryPath = (0, import_node_path6.join)(extRoot, "extensions.json");
41350
+ if ((0, import_node_fs3.existsSync)(registryPath)) {
41351
+ const existingList = JSON.parse((0, import_node_fs3.readFileSync)(registryPath, "utf8"));
41352
+ if (Array.isArray(existingList)) {
41353
+ const filtered = existingList.filter((item) => String(item?.identifier?.id ?? "").toLowerCase() !== "inkmap.inkmap-vscode");
41354
+ if (filtered.length !== existingList.length) {
41355
+ const tmp = `${registryPath}.${process.pid}.${Date.now()}.tmp`;
41356
+ (0, import_node_fs3.writeFileSync)(tmp, JSON.stringify(filtered), "utf8");
41357
+ (0, import_node_fs3.renameSync)(tmp, registryPath);
41358
+ }
41359
+ }
41360
+ }
41361
+ } catch {
41362
+ }
41004
41363
  }
41005
41364
  return removed;
41006
41365
  }
@@ -41009,7 +41368,7 @@ function buildMcpEntry(serverScript, workspaces, existingEntry, withTypeStdio =
41009
41368
  const args = isDirectServer ? [serverScript] : [serverScript, "mcp"];
41010
41369
  const prevEnv = existingEntry && typeof existingEntry === "object" && !Array.isArray(existingEntry) && typeof existingEntry.env === "object" ? { ...existingEntry.env } : {};
41011
41370
  if (workspaces.length > 0) {
41012
- prevEnv.INKMAP_WORKSPACES = workspaces.map((w2) => (0, import_node_path5.resolve)(w2)).join(import_node_path5.delimiter);
41371
+ prevEnv.INKMAP_WORKSPACES = workspaces.map((w2) => (0, import_node_path6.resolve)(w2)).join(import_node_path6.delimiter);
41013
41372
  }
41014
41373
  const entry = {};
41015
41374
  if (withTypeStdio)
@@ -41059,81 +41418,106 @@ async function refreshAntigravityMcp() {
41059
41418
  } catch {
41060
41419
  }
41061
41420
  }
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");
41421
+ async function installAntigravityPlugin(workspaces = []) {
41422
+ const pluginsDir = (0, import_node_path6.join)(getAntigravityConfigDir(), "plugins");
41423
+ const destination = (0, import_node_path6.join)(pluginsDir, "inkmap");
41424
+ const bundledAgy = (0, import_node_path6.join)(DIST_DIR, "bundles", "antigravity");
41425
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41426
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41427
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41428
+ const monorepoAgy = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "inkmap-antigravity", "inkmap");
41070
41429
  (0, import_node_fs3.mkdirSync)(pluginsDir, { recursive: true });
41071
41430
  (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)) {
41431
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledAgy, "plugin.json")) && (0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml)) {
41073
41432
  (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 });
41433
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(destination, "cli.cjs"));
41434
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(destination, "codex.html"));
41435
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(destination, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41077
41436
  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 });
41437
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(destination, "sidecars", "inkmap", "web"), { recursive: true });
41079
41438
  }
41080
41439
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md", "README.md"]) {
41081
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41440
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
41082
41441
  if ((0, import_node_fs3.existsSync)(src))
41083
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(destination, doc));
41442
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(destination, doc));
41084
41443
  }
41085
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoAgy, "plugin.json"))) {
41444
+ } else if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoAgy, "plugin.json"))) {
41086
41445
  (0, import_node_fs3.cpSync)(monorepoAgy, destination, { recursive: true });
41087
41446
  } else {
41088
41447
  throw new Error("\u672A\u627E\u5230 Antigravity \u63D2\u4EF6\u8D44\u6E90 / Antigravity plugin bundle not found.");
41089
41448
  }
41449
+ if (workspaces.length > 0) {
41450
+ try {
41451
+ const mcpCfgPath = (0, import_node_path6.join)(destination, "mcp_config.json");
41452
+ if ((0, import_node_fs3.existsSync)(mcpCfgPath)) {
41453
+ const cfg = readJsonObject(mcpCfgPath);
41454
+ const servers = cfg.mcpServers && typeof cfg.mcpServers === "object" && !Array.isArray(cfg.mcpServers) ? { ...cfg.mcpServers } : {};
41455
+ if (servers.inkmap && typeof servers.inkmap === "object") {
41456
+ servers.inkmap = {
41457
+ ...servers.inkmap,
41458
+ env: {
41459
+ ...servers.inkmap.env && typeof servers.inkmap.env === "object" ? servers.inkmap.env : {},
41460
+ INKMAP_WORKSPACES: workspaces.map((w2) => (0, import_node_path6.resolve)(w2)).join(import_node_path6.delimiter)
41461
+ }
41462
+ };
41463
+ cfg.mcpServers = servers;
41464
+ writeJsonAtomic(mcpCfgPath, cfg);
41465
+ }
41466
+ }
41467
+ } catch {
41468
+ }
41469
+ }
41090
41470
  await refreshAntigravityMcp();
41091
41471
  return destination;
41092
41472
  }
41093
- function installCodexPlugin() {
41473
+ function installCodexPlugin(zh) {
41094
41474
  const codex = findCodexCommand();
41095
41475
  if (!codex) {
41096
41476
  throw new Error("\u672A\u68C0\u6D4B\u5230 codex \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 ChatGPT Desktop \u6216 Codex CLI / Codex CLI not found.");
41097
41477
  }
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");
41478
+ const bundledCodex = (0, import_node_path6.join)(DIST_DIR, "bundles", "codex");
41479
+ const bundledCli = (0, import_node_path6.join)(DIST_DIR, "cli.cjs");
41480
+ const bundledHtml = (0, import_node_path6.join)(DIST_DIR, "codex.html");
41481
+ const monorepoCodexRoot = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars");
41482
+ const destination = (0, import_node_path6.join)(getInkmapHome(), "codex-marketplace");
41103
41483
  (0, import_node_fs3.mkdirSync)(destination, { recursive: true });
41104
41484
  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)) {
41485
+ const fromNpmBundle = (0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledCodex, ".agents")) && (0, import_node_fs3.existsSync)(bundledCli) && (0, import_node_fs3.existsSync)(bundledHtml);
41486
+ const fromMonorepo = (0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoCodexRoot, "inkmap-codex")) && (0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoCodexRoot, ".agents"));
41487
+ if (!fromNpmBundle && !fromMonorepo)
41488
+ throw new Error("\u672A\u627E\u5230 Codex \u63D2\u4EF6\u8D44\u6E90 / Codex plugin bundle not found.");
41489
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(marketplaceRoot, ".agents"), { recursive: true, force: true });
41490
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(marketplaceRoot, "inkmap-codex"), { recursive: true, force: true });
41491
+ if (fromNpmBundle) {
41106
41492
  (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 });
41493
+ const pluginDir = (0, import_node_path6.join)(marketplaceRoot, "inkmap-codex");
41494
+ (0, import_node_fs3.cpSync)(bundledCli, (0, import_node_path6.join)(pluginDir, "cli.cjs"));
41495
+ (0, import_node_fs3.cpSync)(bundledHtml, (0, import_node_path6.join)(pluginDir, "codex.html"));
41496
+ (0, import_node_fs3.writeFileSync)((0, import_node_path6.join)(pluginDir, "server.cjs"), SERVER_WRAPPER, { mode: 493 });
41111
41497
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
41112
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41498
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
41113
41499
  if ((0, import_node_fs3.existsSync)(src))
41114
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(pluginDir, doc));
41500
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(pluginDir, doc));
41115
41501
  }
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
41502
  } else {
41120
- throw new Error("\u672A\u627E\u5230 Codex \u63D2\u4EF6\u8D44\u6E90 / Codex plugin bundle not found.");
41503
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoCodexRoot, ".agents"), (0, import_node_path6.join)(marketplaceRoot, ".agents"), { recursive: true });
41504
+ (0, import_node_fs3.cpSync)((0, import_node_path6.join)(monorepoCodexRoot, "inkmap-codex"), (0, import_node_path6.join)(marketplaceRoot, "inkmap-codex"), { recursive: true });
41121
41505
  }
41122
41506
  const marketplaceName = "inkmap-local";
41123
- const rawList = (0, import_node_child_process4.execFileSync)(codex, ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
41507
+ const rawList = execCliSync(codex, ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
41124
41508
  const { marketplaces = [] } = JSON.parse(rawList);
41125
41509
  const existing = marketplaces.find((entry) => entry.name === marketplaceName);
41126
41510
  if (!existing) {
41127
- (0, import_node_child_process4.execFileSync)(codex, ["plugin", "marketplace", "add", marketplaceRoot], { stdio: "pipe" });
41511
+ execCliSync(codex, ["plugin", "marketplace", "add", marketplaceRoot], { stdio: "pipe" });
41128
41512
  }
41129
- (0, import_node_child_process4.execFileSync)(codex, ["plugin", "add", `inkmap-codex@${marketplaceName}`], { stdio: "pipe" });
41513
+ execCliSync(codex, ["plugin", "add", `inkmap-codex@${marketplaceName}`], { stdio: "pipe" });
41130
41514
  return {
41131
41515
  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"
41516
+ note: zh ? "\u91CD\u542F ChatGPT Desktop \u540E\uFF0C\u5728 Codex \u6A21\u5F0F\u70B9\u51FB .md \u6587\u4EF6\u6253\u5F00\u83DC\u5355\u9009\u62E9 Inkmap Mind Map" : "Restart ChatGPT Desktop, then open any .md file in Codex mode with Inkmap Mind Map"
41133
41517
  };
41134
41518
  }
41135
41519
  function configureDshMarketIndex(profileDir) {
41136
- const pkgPath = (0, import_node_path5.join)(profileDir, "package.json");
41520
+ const pkgPath = (0, import_node_path6.join)(profileDir, "package.json");
41137
41521
  if ((0, import_node_fs3.existsSync)(pkgPath)) {
41138
41522
  try {
41139
41523
  const pkg = JSON.parse((0, import_node_fs3.readFileSync)(pkgPath, "utf8"));
@@ -41153,52 +41537,56 @@ function configureDshMarketIndex(profileDir) {
41153
41537
  } catch {
41154
41538
  }
41155
41539
  }
41156
- const patchPath = (0, import_node_path5.join)(profileDir, "cordis.patch.yml");
41540
+ const patchPath = (0, import_node_path6.join)(profileDir, "cordis.patch.yml");
41157
41541
  const indexUrl = "https://zhiyuanv.com/dsh-index.json";
41158
41542
  try {
41159
41543
  const existing = (0, import_node_fs3.existsSync)(patchPath) ? (0, import_node_fs3.readFileSync)(patchPath, "utf8") : "";
41160
41544
  if (!existing.includes(indexUrl)) {
41161
- const snippet = `
41162
- - id: plugin-market
41545
+ const snippet = `- id: plugin-market
41163
41546
  name: "@deepseek-ai/dsh-plugin-market"
41164
41547
  config:
41165
41548
  indexes:
41166
41549
  - ${indexUrl}
41167
41550
  `;
41168
- (0, import_node_fs3.writeFileSync)(patchPath, existing.replace(/\n*$/, "") + snippet, "utf8");
41551
+ const trimmed = existing.trim();
41552
+ if (!trimmed || trimmed === "[]") {
41553
+ (0, import_node_fs3.writeFileSync)(patchPath, snippet, "utf8");
41554
+ } else if (!/^\s*-\s*id:\s*plugin-market\b/m.test(existing)) {
41555
+ (0, import_node_fs3.writeFileSync)(patchPath, existing.replace(/\n*$/, "\n\n") + snippet, "utf8");
41556
+ }
41169
41557
  }
41170
41558
  } catch {
41171
41559
  }
41172
41560
  }
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");
41561
+ function installDeepSeekHarnessPlugin(zh) {
41562
+ const bundledHarness = (0, import_node_path6.join)(DIST_DIR, "bundles", "harness");
41563
+ const bundledWeb = (0, import_node_path6.join)(DIST_DIR, "web");
41564
+ const monorepoHarness = (0, import_node_path6.resolve)(PKG_ROOT, "..", "..", "dist", "sidebars", "dsh-inkmap");
41565
+ const stagedDir = (0, import_node_path6.join)(getInkmapHome(), "dsh-inkmap");
41178
41566
  (0, import_node_fs3.rmSync)(stagedDir, { recursive: true, force: true });
41179
41567
  (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)) {
41568
+ if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(bundledHarness, "package.json")) && (0, import_node_fs3.existsSync)(bundledWeb)) {
41181
41569
  (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 });
41570
+ (0, import_node_fs3.cpSync)(bundledWeb, (0, import_node_path6.join)(stagedDir, "web"), { recursive: true });
41183
41571
  for (const doc of ["LICENSE.md", "THIRD_PARTY_NOTICES.md"]) {
41184
- const src = (0, import_node_path5.join)(PKG_ROOT, doc);
41572
+ const src = (0, import_node_path6.join)(PKG_ROOT, doc);
41185
41573
  if ((0, import_node_fs3.existsSync)(src))
41186
- (0, import_node_fs3.cpSync)(src, (0, import_node_path5.join)(stagedDir, doc));
41574
+ (0, import_node_fs3.cpSync)(src, (0, import_node_path6.join)(stagedDir, doc));
41187
41575
  }
41188
- } else if ((0, import_node_fs3.existsSync)((0, import_node_path5.join)(monorepoHarness, "package.json"))) {
41576
+ } else if ((0, import_node_fs3.existsSync)((0, import_node_path6.join)(monorepoHarness, "package.json"))) {
41189
41577
  (0, import_node_fs3.cpSync)(monorepoHarness, stagedDir, { recursive: true });
41190
41578
  } else {
41191
41579
  throw new Error("\u672A\u627E\u5230 DeepSeek Harness \u63D2\u4EF6\u8D44\u6E90 / DeepSeek Harness plugin bundle not found.");
41192
41580
  }
41193
41581
  const realStaged = (0, import_node_fs3.realpathSync)(stagedDir);
41194
41582
  const dshCmd = findDshCommand();
41195
- const profileDir = (0, import_node_path5.join)(getDshHome(), "profiles", "desktop");
41583
+ const profileDir = (0, import_node_path6.join)(getDshHome(), "profiles", "desktop");
41196
41584
  if (dshCmd) {
41197
- (0, import_node_child_process4.execFileSync)(dshCmd, ["plugin", "--profile", "desktop", "add", realStaged], { stdio: "pipe" });
41585
+ execCliSync(dshCmd, ["plugin", "--profile", "desktop", "add", realStaged], { stdio: "pipe" });
41198
41586
  } else if ((0, import_node_fs3.existsSync)(profileDir)) {
41199
- const nodeModulesTarget = (0, import_node_path5.join)(profileDir, "node_modules", "dsh-inkmap");
41587
+ const nodeModulesTarget = (0, import_node_path6.join)(profileDir, "node_modules", "dsh-inkmap");
41200
41588
  (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 });
41589
+ (0, import_node_fs3.mkdirSync)((0, import_node_path6.join)(profileDir, "node_modules"), { recursive: true });
41202
41590
  (0, import_node_fs3.cpSync)(realStaged, nodeModulesTarget, { recursive: true });
41203
41591
  } else {
41204
41592
  throw new Error("\u672A\u68C0\u6D4B\u5230 DeepSeek Harness \u5BA2\u6237\u7AEF / DeepSeek Harness not found.");
@@ -41208,7 +41596,7 @@ function installDeepSeekHarnessPlugin() {
41208
41596
  }
41209
41597
  return {
41210
41598
  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"
41599
+ note: zh ? "\u5DF2\u5728 DeepSeek Harness\u300C\u63D2\u4EF6\u300D\u9875\u542F\u7528 Inkmap \u601D\u7EF4\u5BFC\u56FE\u4E0E\u63D2\u4EF6\u7D22\u5F15\uFF08\u9884\u89C8 .md \u6587\u4EF6\u70B9\u51FB\u53F3\u4E0A\u89D2 Inkmap \u5373\u53EF\u6253\u5F00\uFF09" : "Enabled Inkmap mind map in DeepSeek Harness (open any .md preview and click Inkmap in the top-right)"
41212
41600
  };
41213
41601
  }
41214
41602
  async function runInstall(options = {}) {
@@ -41221,7 +41609,7 @@ async function runInstall(options = {}) {
41221
41609
  const toRemove = explicitTargets ?? ["claude", "claude-code", "cursor", "vscode", "antigravity", "codex", "deepseek"];
41222
41610
  for (const target of toRemove) {
41223
41611
  if (target === "claude") {
41224
- const cfg = (0, import_node_path5.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41612
+ const cfg = (0, import_node_path6.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41225
41613
  if (removeMcpJsonConfig(cfg))
41226
41614
  result.removed.push({ target, location: cfg });
41227
41615
  } else if (target === "claude-code") {
@@ -41229,38 +41617,49 @@ async function runInstall(options = {}) {
41229
41617
  if (removeMcpJsonConfig(cfg))
41230
41618
  result.removed.push({ target, location: cfg });
41231
41619
  } else if (target === "cursor") {
41232
- const cfg = (0, import_node_path5.join)(getCursorDir(), "mcp.json");
41620
+ const cfg = (0, import_node_path6.join)(getCursorDir(), "mcp.json");
41233
41621
  const removedMcp = removeMcpJsonConfig(cfg);
41234
41622
  const removedExt = uninstallIdeExtension(getCursorDir(), findCursorCommand());
41235
41623
  if (removedMcp || removedExt)
41236
41624
  result.removed.push({ target, location: cfg });
41237
41625
  } else if (target === "vscode") {
41238
41626
  if (uninstallIdeExtension(getVscodeDir(), findVscodeCommand())) {
41239
- result.removed.push({ target, location: (0, import_node_path5.join)(getVscodeDir(), "extensions") });
41627
+ result.removed.push({ target, location: (0, import_node_path6.join)(getVscodeDir(), "extensions") });
41240
41628
  }
41241
41629
  } else if (target === "antigravity") {
41242
- const dir = (0, import_node_path5.join)(getAntigravityConfigDir(), "plugins", "inkmap");
41630
+ const dir = (0, import_node_path6.join)(getAntigravityConfigDir(), "plugins", "inkmap");
41243
41631
  if ((0, import_node_fs3.existsSync)(dir)) {
41244
41632
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
41245
41633
  await refreshAntigravityMcp();
41246
41634
  result.removed.push({ target, location: dir });
41247
41635
  }
41248
41636
  } else if (target === "codex") {
41249
- const dir = (0, import_node_path5.join)(getInkmapHome(), "codex-marketplace");
41637
+ const codexCmd = findCodexCommand();
41638
+ if (codexCmd) {
41639
+ try {
41640
+ execCliSync(codexCmd, ["plugin", "remove", "inkmap-codex@inkmap-local"], { stdio: "pipe" });
41641
+ } catch {
41642
+ }
41643
+ try {
41644
+ execCliSync(codexCmd, ["plugin", "marketplace", "remove", "inkmap-local"], { stdio: "pipe" });
41645
+ } catch {
41646
+ }
41647
+ }
41648
+ const dir = (0, import_node_path6.join)(getInkmapHome(), "codex-marketplace");
41250
41649
  if ((0, import_node_fs3.existsSync)(dir)) {
41251
41650
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
41252
41651
  result.removed.push({ target, location: dir });
41253
41652
  }
41254
41653
  } else if (target === "deepseek") {
41255
41654
  const dshCmd = findDshCommand();
41256
- const profileDir = (0, import_node_path5.join)(getDshHome(), "profiles", "desktop");
41655
+ const profileDir = (0, import_node_path6.join)(getDshHome(), "profiles", "desktop");
41257
41656
  if (dshCmd && (0, import_node_fs3.existsSync)(profileDir)) {
41258
41657
  try {
41259
- (0, import_node_child_process4.execFileSync)(dshCmd, ["plugin", "--profile", "desktop", "remove", "dsh-inkmap"], { stdio: "pipe" });
41658
+ execCliSync(dshCmd, ["plugin", "--profile", "desktop", "remove", "dsh-inkmap"], { stdio: "pipe" });
41260
41659
  } catch {
41261
41660
  }
41262
41661
  }
41263
- const dir = (0, import_node_path5.join)(getInkmapHome(), "dsh-inkmap");
41662
+ const dir = (0, import_node_path6.join)(getInkmapHome(), "dsh-inkmap");
41264
41663
  if ((0, import_node_fs3.existsSync)(dir)) {
41265
41664
  (0, import_node_fs3.rmSync)(dir, { recursive: true, force: true });
41266
41665
  result.removed.push({ target, location: profileDir });
@@ -41268,7 +41667,7 @@ async function runInstall(options = {}) {
41268
41667
  }
41269
41668
  }
41270
41669
  if (!explicitTargets) {
41271
- (0, import_node_fs3.rmSync)((0, import_node_path5.join)(getInkmapHome(), "mcp-app"), { recursive: true, force: true });
41670
+ (0, import_node_fs3.rmSync)((0, import_node_path6.join)(getInkmapHome(), "mcp-app"), { recursive: true, force: true });
41272
41671
  }
41273
41672
  if (result.removed.length === 0) {
41274
41673
  log("[inkmap] \u672A\u53D1\u73B0\u5DF2\u5B89\u88C5\u7684 Inkmap \u5BA2\u6237\u7AEF\u914D\u7F6E / No installed Inkmap client configs found.");
@@ -41280,6 +41679,7 @@ async function runInstall(options = {}) {
41280
41679
  return result;
41281
41680
  }
41282
41681
  const { serverScript, appDir } = stageStandaloneMcpApp();
41682
+ const zhLocale = isChineseTerminalLocale();
41283
41683
  if (targets.length === 0) {
41284
41684
  log(`[inkmap] \u5DF2\u5C06 MCP App \u6838\u5FC3\u6587\u4EF6\u5C31\u7EEA\u5230: ${appDir}`);
41285
41685
  log("[inkmap] \u672A\u5728\u9ED8\u8BA4\u76EE\u5F55\u68C0\u6D4B\u5230\u5DF2\u5B89\u88C5\u7684 AI \u5BA2\u6237\u7AEF\uFF0C\u53EF\u6307\u5B9A\u5BA2\u6237\u7AEF\u540D\u79F0\u5F3A\u5236\u751F\u6210\u914D\u7F6E\uFF1A");
@@ -41289,16 +41689,17 @@ async function runInstall(options = {}) {
41289
41689
  log(" npx -y inkmap-mcp@latest install vscode # VS Code (\u539F\u751F\u7F16\u8F91\u5668\u6269\u5C55)");
41290
41690
  log(" npx -y inkmap-mcp@latest install antigravity # Google Antigravity");
41291
41691
  log(" npx -y inkmap-mcp@latest install codex # OpenAI Codex Desktop");
41692
+ log(" npx -y inkmap-mcp@latest install deepseek # DeepSeek Harness");
41292
41693
  return result;
41293
41694
  }
41294
41695
  for (const target of targets) {
41295
41696
  if (target === "claude") {
41296
- const cfg = (0, import_node_path5.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41697
+ const cfg = (0, import_node_path6.join)(getClaudeDesktopDir(), "claude_desktop_config.json");
41297
41698
  upsertMcpJsonConfig(cfg, serverScript, workspaces, false);
41298
41699
  result.installed.push({
41299
41700
  target,
41300
41701
  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"
41702
+ note: zhLocale ? "\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u542F Claude Desktop \u540E\uFF0C\u5BF9 Claude \u8BF4\u201C\u7528 Inkmap \u6253\u5F00 xxx.md\u201D\u5373\u53EF" : "Quit and restart Claude Desktop, then ask Claude to open any .md file with Inkmap"
41302
41703
  });
41303
41704
  } else if (target === "claude-code") {
41304
41705
  const cfg = getClaudeCodeConfigPath();
@@ -41306,13 +41707,13 @@ async function runInstall(options = {}) {
41306
41707
  result.installed.push({
41307
41708
  target,
41308
41709
  location: cfg,
41309
- note: "\u5728 Claude Code \u4E2D\u5DF2\u6CE8\u518C\u5168\u5C40 inkmap MCP \u670D\u52A1"
41710
+ note: zhLocale ? "\u5728 Claude Code \u4E2D\u5DF2\u6CE8\u518C\u5168\u5C40 inkmap MCP \u670D\u52A1" : "Registered global inkmap MCP server in Claude Code"
41310
41711
  });
41311
41712
  } else if (target === "cursor") {
41312
- const cfg = (0, import_node_path5.join)(getCursorDir(), "mcp.json");
41713
+ const cfg = (0, import_node_path6.join)(getCursorDir(), "mcp.json");
41313
41714
  upsertMcpJsonConfig(cfg, serverScript, workspaces, false);
41314
41715
  const extLoc = installIdeExtension(getCursorDir(), findCursorCommand());
41315
- const cursorServerDir = (0, import_node_path5.join)((0, import_node_os5.homedir)(), ".cursor-server");
41716
+ const cursorServerDir = (0, import_node_path6.join)((0, import_node_os5.homedir)(), ".cursor-server");
41316
41717
  if ((0, import_node_fs3.existsSync)(cursorServerDir)) {
41317
41718
  try {
41318
41719
  installIdeExtension(cursorServerDir, null);
@@ -41322,7 +41723,7 @@ async function runInstall(options = {}) {
41322
41723
  result.installed.push({
41323
41724
  target,
41324
41725
  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"
41726
+ note: zhLocale ? "\u5DF2\u540C\u65F6\u5B89\u88C5 MCP \u670D\u52A1\u4E0E\u53F3\u4FA7\u4E3B\u7F16\u8F91\u533A\u5BFC\u56FE\u6269\u5C55\uFF08Reload Window \u540E\u5BF9\u8BDD\u53EF\u76F4\u63A5\u6253\u5F00\u53F3\u4FA7\u5BFC\u56FE\u6807\u7B7E\uFF09" : "Installed both MCP server and native right-pane mind map extension (Reload Window to activate)"
41326
41727
  });
41327
41728
  } else if (target === "vscode") {
41328
41729
  const extLoc = installIdeExtension(getVscodeDir(), findVscodeCommand());
@@ -41330,19 +41731,19 @@ async function runInstall(options = {}) {
41330
41731
  result.installed.push({
41331
41732
  target,
41332
41733
  location: extLoc,
41333
- note: "\u5DF2\u5728 VS Code \u5B89\u88C5\u539F\u751F Inkmap \u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668\u6269\u5C55"
41734
+ note: zhLocale ? "\u5DF2\u5728 VS Code \u5B89\u88C5\u539F\u751F Inkmap \u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668\u6269\u5C55" : "Installed native Inkmap mind map editor extension in VS Code"
41334
41735
  });
41335
41736
  }
41336
41737
  } else if (target === "antigravity") {
41337
- const loc = await installAntigravityPlugin();
41738
+ const loc = await installAntigravityPlugin(workspaces);
41338
41739
  result.installed.push({
41339
41740
  target,
41340
41741
  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"
41742
+ note: zhLocale ? "\u5728 Antigravity \u5BF9\u8BDD\u4E2D\u8BA9 AI \u7528 Inkmap \u6253\u5F00 .md \u6587\u4EF6\uFF0C\u6216\u70B9\u51FB\u53F3\u4FA7\u9762\u677F + \u9009\u62E9 Inkmap" : "Ask AI in Antigravity chat to open a .md file with Inkmap, or open Inkmap from the right-hand pane + button"
41342
41743
  });
41343
41744
  } else if (target === "codex") {
41344
41745
  try {
41345
- const installedCodex = installCodexPlugin();
41746
+ const installedCodex = installCodexPlugin(zhLocale);
41346
41747
  result.installed.push({
41347
41748
  target,
41348
41749
  location: installedCodex.location,
@@ -41355,7 +41756,7 @@ async function runInstall(options = {}) {
41355
41756
  }
41356
41757
  } else if (target === "deepseek") {
41357
41758
  try {
41358
- const installedDsh = installDeepSeekHarnessPlugin();
41759
+ const installedDsh = installDeepSeekHarnessPlugin(zhLocale);
41359
41760
  result.installed.push({
41360
41761
  target,
41361
41762
  location: installedDsh.location,
@@ -41368,7 +41769,6 @@ async function runInstall(options = {}) {
41368
41769
  }
41369
41770
  }
41370
41771
  }
41371
- const zhLocale = isChineseTerminalLocale();
41372
41772
  if (zhLocale) {
41373
41773
  log(`[inkmap] \u5B89\u88C5\u5B8C\u6210\uFF08Node: ${process.execPath}\uFF09\uFF1A`);
41374
41774
  for (const item of result.installed) {
@@ -41390,6 +41790,8 @@ async function runInstall(options = {}) {
41390
41790
  log(`[inkmap] Installation complete (Node: ${process.execPath}):`);
41391
41791
  for (const item of result.installed) {
41392
41792
  log(` \u2713 ${item.target.padEnd(12)} -> ${item.location}`);
41793
+ if (item.note)
41794
+ log(` ${item.note}`);
41393
41795
  }
41394
41796
  log("");
41395
41797
  log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
@@ -41444,17 +41846,17 @@ async function runInstallCli(argv, uninstall = false) {
41444
41846
  const val = argv[++i];
41445
41847
  if (!val)
41446
41848
  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));
41849
+ workspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41448
41850
  continue;
41449
41851
  }
41450
41852
  if (arg.startsWith("--workspace=")) {
41451
41853
  const val = arg.slice("--workspace=".length);
41452
- workspaces.push(...val.split(import_node_path5.delimiter).filter(Boolean));
41854
+ workspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41453
41855
  continue;
41454
41856
  }
41455
41857
  const normalized = normalizeTarget(arg);
41456
41858
  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`);
41859
+ throw new Error(`\u672A\u77E5\u5BA2\u6237\u7AEF\u76EE\u6807: ${arg}\uFF08\u652F\u6301: claude, claude-code, cursor, vscode, antigravity, codex, deepseek, all\uFF09`);
41458
41860
  }
41459
41861
  if (normalized === "all") {
41460
41862
  explicitAll = true;
@@ -41468,19 +41870,19 @@ async function runInstallCli(argv, uninstall = false) {
41468
41870
  uninstall
41469
41871
  });
41470
41872
  }
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;
41873
+ var import_node_child_process4, import_node_fs3, import_node_os5, import_node_path6, import_node_url4, import_node_zlib, DIST_DIR, PKG_ROOT, SERVER_WRAPPER, CRC_TABLE;
41472
41874
  var init_install = __esm({
41473
41875
  "packages/cli/dist/install.js"() {
41474
41876
  "use strict";
41475
41877
  import_node_child_process4 = require("node:child_process");
41476
41878
  import_node_fs3 = require("node:fs");
41477
41879
  import_node_os5 = require("node:os");
41478
- import_node_path5 = require("node:path");
41479
- import_node_url3 = require("node:url");
41880
+ import_node_path6 = require("node:path");
41881
+ import_node_url4 = require("node:url");
41480
41882
  import_node_zlib = require("node:zlib");
41481
41883
  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, "..");
41884
+ DIST_DIR = (0, import_node_path6.dirname)((0, import_node_url4.fileURLToPath)(inkmapModuleUrl));
41885
+ PKG_ROOT = (0, import_node_path6.resolve)(DIST_DIR, "..");
41484
41886
  SERVER_WRAPPER = `#!/usr/bin/env node
41485
41887
  "use strict";
41486
41888
  require("./cli.cjs").main(["mcp", ...process.argv.slice(2)]).catch(err => {
@@ -41509,13 +41911,13 @@ __export(index_exports, {
41509
41911
  });
41510
41912
  module.exports = __toCommonJS(index_exports);
41511
41913
  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");
41914
+ var import_node_path7 = require("node:path");
41915
+ var import_node_url5 = require("node:url");
41514
41916
  init_dist();
41515
41917
  init_license();
41516
41918
  init_server();
41517
- var INKMAP_VERSION = "0.3.10";
41518
- var WEB_ROOT = (0, import_node_url4.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
41919
+ init_version();
41920
+ var WEB_ROOT = (0, import_node_url5.fileURLToPath)(new URL("./web/", inkmapModuleUrl));
41519
41921
  var USAGE = `Inkmap v${INKMAP_VERSION} \u2014 Markdown \u4EA4\u4E92\u601D\u7EF4\u5BFC\u56FE\u7F16\u8F91\u5668 & MCP App
41520
41922
 
41521
41923
  \u7528\u6CD5 / Usage\uFF1A
@@ -41529,14 +41931,17 @@ var USAGE = `Inkmap v${INKMAP_VERSION} \u2014 Markdown \u4EA4\u4E92\u601D\u7EF4\
41529
41931
  \u5728\u672C\u5730\u6D4F\u89C8\u5668\u4E2D\u4EE5\u601D\u7EF4\u5BFC\u56FE\u6253\u5F00\u5E76\u5B9E\u65F6\u53CC\u5411\u7F16\u8F91 Markdown \u6587\u4EF6`;
41530
41932
  function openBrowser(url2) {
41531
41933
  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();
41934
+ const child = (0, import_node_child_process5.spawn)(cmd, args, { stdio: "ignore", detached: true });
41935
+ child.on("error", () => {
41936
+ });
41937
+ child.unref();
41533
41938
  }
41534
41939
  function appendEnvWorkspaces(dirs) {
41535
41940
  if (dirs.length === 0)
41536
41941
  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);
41942
+ const resolved = dirs.map((d2) => (0, import_node_path7.resolve)(d2));
41943
+ const current = (process.env.INKMAP_WORKSPACES || "").split(import_node_path7.delimiter).filter(Boolean);
41944
+ process.env.INKMAP_WORKSPACES = [.../* @__PURE__ */ new Set([...current, ...resolved])].join(import_node_path7.delimiter);
41540
41945
  }
41541
41946
  async function main(argv) {
41542
41947
  if (argv.length === 0 && !process.stdin.isTTY) {
@@ -41563,9 +41968,9 @@ async function main(argv) {
41563
41968
  const val = argv[++i];
41564
41969
  if (!val)
41565
41970
  throw new Error("--workspace \u9700\u8981\u76EE\u5F55\u8DEF\u5F84");
41566
- extraWorkspaces.push(...val.split(import_node_path6.delimiter).filter(Boolean));
41971
+ extraWorkspaces.push(...val.split(import_node_path7.delimiter).filter(Boolean));
41567
41972
  } else if (arg.startsWith("--workspace=")) {
41568
- extraWorkspaces.push(...arg.slice("--workspace=".length).split(import_node_path6.delimiter).filter(Boolean));
41973
+ extraWorkspaces.push(...arg.slice("--workspace=".length).split(import_node_path7.delimiter).filter(Boolean));
41569
41974
  } else if (arg === "-h" || arg === "--help") {
41570
41975
  console.log(USAGE);
41571
41976
  return;
@@ -41619,7 +42024,6 @@ ${USAGE}`);
41619
42024
  port: port ?? (sidebar ? 0 : void 0),
41620
42025
  log,
41621
42026
  license,
41622
- ads: adFeed(PRODUCT.adFeedUrl),
41623
42027
  sidebar,
41624
42028
  sidebarPurchase
41625
42029
  });