deepseek-web-retrieval 0.6.0 → 0.7.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/README.md +79 -10
  3. package/dist/cli.js +2203 -1826
  4. package/docs/adr/0002-shared-config-base-layer.md +43 -0
  5. package/docs/agents/codex.md +48 -27
  6. package/docs/agents/opencode-v2.md +57 -33
  7. package/docs/agents/pi.md +48 -27
  8. package/docs/design/config-layering-design.md +180 -0
  9. package/docs/design/installer-design.md +8 -0
  10. package/docs/integration.md +6 -3
  11. package/docs/research/control-matrix.md +15 -2
  12. package/docs/research/mcp-compatibility.md +4 -1
  13. package/docs/research/ori-question-sourcing.md +336 -0
  14. package/docs/research/result-quality-passthrough.md +159 -0
  15. package/docs/research/search-api-defaults.md +18 -2
  16. package/docs/research/search-inline-content.md +244 -0
  17. package/examples/opencode.global.jsonc +3 -2
  18. package/package.json +2 -1
  19. package/src/core/auth.ts +3 -0
  20. package/src/core/client.ts +26 -4
  21. package/src/core/config-file.ts +168 -0
  22. package/src/core/config-summary.ts +82 -0
  23. package/src/core/constants.ts +15 -1
  24. package/src/core/descriptions.ts +6 -2
  25. package/src/core/env.ts +99 -32
  26. package/src/core/format.ts +19 -1
  27. package/src/core/options.ts +22 -2
  28. package/src/core/search.ts +6 -0
  29. package/src/core/types.ts +11 -0
  30. package/src/installer/cli.ts +50 -16
  31. package/src/installer/config-command.ts +116 -0
  32. package/src/installer/hosts/codex.ts +5 -3
  33. package/src/installer/hosts/opencode.ts +9 -5
  34. package/src/installer/hosts/pi.ts +10 -6
  35. package/src/installer/ownership.ts +54 -1
  36. package/src/installer/paths.ts +7 -1
  37. package/src/installer/state.ts +72 -19
  38. package/src/installer/types.ts +10 -0
  39. package/src/mcp/auth.ts +2 -3
  40. package/src/mcp/cli.ts +4 -3
  41. package/src/mcp/serve.ts +10 -1
  42. package/src/mcp/server.ts +7 -2
  43. package/src/opencode/plugin.ts +22 -2
  44. package/src/pi/extension.ts +78 -9
package/dist/cli.js CHANGED
@@ -15,11 +15,351 @@ var __export = (target, all) => {
15
15
  };
16
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
 
18
- // src/version.ts
18
+ // src/core/constants.ts
19
+ var SEARCH_ENDPOINT = "https://api.deepseek.com/v1/tools/search", FETCH_ENDPOINT = "https://api.deepseek.com/v1/tools/fetch", DEFAULT_SEARCH_COUNT = 10, DEFAULT_MAX_RESULTS = 10, DEFAULT_MIN_RERANK = 0, DEFAULT_MIN_AUTHORITY = 0, DEFAULT_MAX_SUMMARY_CHARS = 1200, DEFAULT_FETCH_MAX_CHARS = 16000, DEFAULT_TIMEOUT_MS = 30000, MIN_TIMEOUT_MS = 1000, MAX_TIMEOUT_MS = 120000, MAX_QUERY_CHARS = 128, MAX_ORI_QUESTION_CHARS = 128, MAX_URL_CHARS = 8192, MAX_ERROR_BODY_CHARS = 2000, MAX_RESPONSE_BYTES, FETCH_TRUNCATION_MARKER = `
20
+
21
+ [content truncated]`, DEFAULT_API_KEY_SOURCE = "auto", DEFAULT_MAX_RETRIES = 2, MAX_RETRIES = 5, DEFAULT_RETRY_BASE_DELAY_MS = 250, MAX_RETRY_DELAY_MS = 1e4, API_KEY_ENV = "DEEPSEEK_API_KEY", ENABLE_SEARCH_ENV = "DEEPSEEK_ENABLE_SEARCH", ENABLE_FETCH_ENV = "DEEPSEEK_ENABLE_FETCH", SEARCH_LOCALIZATION_ENV = "DEEPSEEK_SEARCH_LOCALIZATION";
22
+ var init_constants = __esm(() => {
23
+ MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
24
+ });
25
+
26
+ // src/core/domains.ts
27
+ import { isIP } from "node:net";
28
+ function normalizeDomain(value) {
29
+ const trimmed = value.trim();
30
+ if (!trimmed || /\s/.test(trimmed))
31
+ return;
32
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed);
33
+ if (hasScheme && !/^https?:\/\//i.test(trimmed))
34
+ return;
35
+ let hostname;
36
+ try {
37
+ hostname = new URL(hasScheme ? trimmed : `http://${trimmed}`).hostname;
38
+ } catch {
39
+ return;
40
+ }
41
+ return normalizeHostname(hostname);
42
+ }
43
+ function normalizeHostname(value) {
44
+ return value.trim().toLowerCase().replace(/^\[/, "").replace(/\]$/, "").replace(/\.+$/, "");
45
+ }
46
+ function domainMatches(hostname, domain) {
47
+ const host = normalizeHostname(hostname);
48
+ const target = normalizeHostname(domain);
49
+ if (!host || !target)
50
+ return false;
51
+ return host === target || host.endsWith(`.${target}`);
52
+ }
53
+ function normalizeDomains(values) {
54
+ if (!Array.isArray(values))
55
+ return [];
56
+ const domains = new Set;
57
+ for (const value of values) {
58
+ if (typeof value !== "string")
59
+ continue;
60
+ const domain = normalizeDomain(value);
61
+ if (domain)
62
+ domains.add(domain);
63
+ }
64
+ return [...domains];
65
+ }
66
+ function isPrivateHostname(value) {
67
+ const host = normalizeHostname(value);
68
+ if (!host)
69
+ return true;
70
+ if (host === "localhost" || host === "local")
71
+ return true;
72
+ if (host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan") || host.endsWith(".home.arpa")) {
73
+ return true;
74
+ }
75
+ const version = isIP(host);
76
+ if (version === 4)
77
+ return isPrivateIpv4(host);
78
+ if (version === 6)
79
+ return isPrivateIpv6(host);
80
+ return false;
81
+ }
82
+ function assertFetchHostPolicy(url, options) {
83
+ const host = normalizeHostname(url.hostname);
84
+ if (options.blockPrivateHosts && isPrivateHostname(host)) {
85
+ throw new Error(`Fetch blocked for ${host}: local/private addresses are not reachable by DeepSeek. ` + "Set fetchBlockPrivateHosts=false only if you really need to send the URL.");
86
+ }
87
+ const blocked = options.blockedDomains.find((domain) => domainMatches(host, domain));
88
+ if (blocked) {
89
+ throw new Error(`Fetch blocked for ${host}: matched fetchBlockedDomains entry "${blocked}"`);
90
+ }
91
+ if (options.allowedDomains.length > 0 && !options.allowedDomains.some((domain) => domainMatches(host, domain))) {
92
+ throw new Error(`Fetch not allowed for ${host}: add it to fetchAllowedDomains (exact host or subdomain)`);
93
+ }
94
+ }
95
+ function isPrivateIpv4(host) {
96
+ const parts = host.split(".").map((part) => Number(part));
97
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
98
+ return true;
99
+ }
100
+ const [a, b] = parts;
101
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
102
+ }
103
+ function isPrivateIpv6(host) {
104
+ const value = host.toLowerCase();
105
+ if (value === "::" || value === "::1")
106
+ return true;
107
+ if (value.startsWith("fc") || value.startsWith("fd"))
108
+ return true;
109
+ if (/^fe[89ab]/.test(value))
110
+ return true;
111
+ const dottedMapped = value.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1];
112
+ if (dottedMapped)
113
+ return isPrivateIpv4(dottedMapped);
114
+ const mapped = ipv4FromIpv6Hextets(value, /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
115
+ if (mapped)
116
+ return isPrivateIpv4(mapped);
117
+ const compatible = ipv4FromIpv6Hextets(value, /^::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
118
+ if (compatible)
119
+ return isPrivateIpv4(compatible);
120
+ return false;
121
+ }
122
+ function ipv4FromIpv6Hextets(value, pattern) {
123
+ const match = value.match(pattern);
124
+ if (!match)
125
+ return;
126
+ const high = Number.parseInt(match[1], 16);
127
+ const low = Number.parseInt(match[2], 16);
128
+ if (!Number.isFinite(high) || !Number.isFinite(low))
129
+ return;
130
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
131
+ }
132
+ var init_domains = () => {};
133
+
134
+ // src/core/options.ts
135
+ import { isIP as isIP2 } from "node:net";
136
+ function resolvePluginOptions(input) {
137
+ return {
138
+ search: resolveSearchOptions(input),
139
+ fetch: resolveFetchOptions(input),
140
+ auth: resolveAuthOptions(input),
141
+ retry: resolveRetryOptions(input)
142
+ };
143
+ }
144
+ function resolveSearchOptions(input) {
145
+ const count = clampInt(input?.count, DEFAULT_SEARCH_COUNT, 1, 50);
146
+ return {
147
+ count,
148
+ maxResults: clampInt(input?.maxResults, Number.isFinite(input?.count) ? count : DEFAULT_MAX_RESULTS, 0, 50),
149
+ minRerank: finiteNumber(input?.minRerank, DEFAULT_MIN_RERANK),
150
+ minAuthority: finiteNumber(input?.minAuthority, DEFAULT_MIN_AUTHORITY),
151
+ allowUnknownAuthority: input?.allowUnknownAuthority !== false,
152
+ blockedDomains: normalizeDomains(input?.blockedDomains),
153
+ includeDomains: normalizeDomains(input?.includeDomains),
154
+ language: optionalText(input?.language),
155
+ localization: localizationValue(input?.searchLocalization),
156
+ maxSummaryChars: clampInt(input?.maxSummaryChars, DEFAULT_MAX_SUMMARY_CHARS, 0, 1e6),
157
+ timeoutMs: clampInt(input?.searchTimeoutMs, DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS),
158
+ enabled: input?.searchEnabled !== false
159
+ };
160
+ }
161
+ function resolveFetchOptions(input) {
162
+ return {
163
+ maxChars: clampInt(input?.fetchMaxChars, DEFAULT_FETCH_MAX_CHARS, 0, 1e6),
164
+ allowedDomains: normalizeDomains(input?.fetchAllowedDomains),
165
+ blockedDomains: normalizeDomains(input?.fetchBlockedDomains),
166
+ timeoutMs: clampInt(input?.fetchTimeoutMs, DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS),
167
+ blockPrivateHosts: input?.fetchBlockPrivateHosts !== false,
168
+ enabled: input?.fetchEnabled !== false
169
+ };
170
+ }
171
+ function resolveAuthOptions(input) {
172
+ const value = input?.apiKeySource;
173
+ return {
174
+ source: value === "opencode" || value === "env" ? value : DEFAULT_API_KEY_SOURCE
175
+ };
176
+ }
177
+ function resolveRetryOptions(input) {
178
+ return {
179
+ maxRetries: clampInt(input?.maxRetries, DEFAULT_MAX_RETRIES, 0, MAX_RETRIES),
180
+ baseDelayMs: clampInt(input?.retryBaseDelayMs, DEFAULT_RETRY_BASE_DELAY_MS, 0, MAX_RETRY_DELAY_MS)
181
+ };
182
+ }
183
+ function optionalText(value) {
184
+ if (typeof value !== "string")
185
+ return;
186
+ const trimmed = value.trim();
187
+ return trimmed ? trimmed : undefined;
188
+ }
189
+ function localizationValue(value) {
190
+ const text = optionalText(value);
191
+ return text !== undefined && !text.includes("%") && isIP2(text) !== 0 ? text : undefined;
192
+ }
193
+ function finiteNumber(value, fallback) {
194
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
195
+ }
196
+ function clampInt(value, fallback, min, max) {
197
+ const number = typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : fallback;
198
+ return Math.min(max, Math.max(min, number));
199
+ }
200
+ var init_options = __esm(() => {
201
+ init_constants();
202
+ init_domains();
203
+ });
204
+
205
+ // src/core/config-summary.ts
206
+ function configDeviations(resolved) {
207
+ const defaults = configSummaryValues(resolvePluginOptions({}));
208
+ const effective = configSummaryValues(resolved);
209
+ const tokens = [];
210
+ for (const key of Object.keys(effective)) {
211
+ const value = effective[key];
212
+ if (sameValue(value, defaults[key]))
213
+ continue;
214
+ tokens.push(`${key}=${formatConfigValue(value, "length")}`);
215
+ }
216
+ return tokens.join(" ");
217
+ }
218
+ function configSummaryValues(options) {
219
+ const values = {};
220
+ for (const entry of VOCABULARY)
221
+ values[entry.key] = entry.read(options);
222
+ return values;
223
+ }
224
+ function formatConfigValue(value, arrays) {
225
+ if (Array.isArray(value)) {
226
+ if (arrays === "length")
227
+ return String(value.length);
228
+ return value.length > 0 ? value.join(", ") : "[]";
229
+ }
230
+ return value === undefined ? "unset" : String(value);
231
+ }
232
+ function sameValue(value, fallback) {
233
+ if (Array.isArray(value) && Array.isArray(fallback)) {
234
+ return value.length === fallback.length && value.every((entry, index) => entry === fallback[index]);
235
+ }
236
+ return value === fallback;
237
+ }
238
+ var VOCABULARY, CONFIG_KEYS;
239
+ var init_config_summary = __esm(() => {
240
+ init_options();
241
+ VOCABULARY = [
242
+ { key: "count", read: (o) => o.search.count },
243
+ { key: "maxResults", read: (o) => o.search.maxResults },
244
+ { key: "minRerank", read: (o) => o.search.minRerank },
245
+ { key: "minAuthority", read: (o) => o.search.minAuthority },
246
+ { key: "allowUnknownAuthority", read: (o) => o.search.allowUnknownAuthority },
247
+ { key: "blockedDomains", read: (o) => o.search.blockedDomains },
248
+ { key: "includeDomains", read: (o) => o.search.includeDomains },
249
+ { key: "language", read: (o) => o.search.language },
250
+ { key: "searchLocalization", read: (o) => o.search.localization },
251
+ { key: "maxSummaryChars", read: (o) => o.search.maxSummaryChars },
252
+ { key: "searchTimeoutMs", read: (o) => o.search.timeoutMs },
253
+ { key: "fetchMaxChars", read: (o) => o.fetch.maxChars },
254
+ { key: "fetchAllowedDomains", read: (o) => o.fetch.allowedDomains },
255
+ { key: "fetchBlockedDomains", read: (o) => o.fetch.blockedDomains },
256
+ { key: "fetchTimeoutMs", read: (o) => o.fetch.timeoutMs },
257
+ { key: "fetchBlockPrivateHosts", read: (o) => o.fetch.blockPrivateHosts },
258
+ { key: "maxRetries", read: (o) => o.retry.maxRetries },
259
+ { key: "retryBaseDelayMs", read: (o) => o.retry.baseDelayMs }
260
+ ];
261
+ CONFIG_KEYS = VOCABULARY.map((entry) => entry.key);
262
+ });
263
+
264
+ // src/core/object.ts
265
+ function isPlainObject(value) {
266
+ return typeof value === "object" && value !== null && !Array.isArray(value);
267
+ }
268
+
269
+ // src/core/config-file.ts
19
270
  import { readFileSync } from "node:fs";
271
+ import { homedir } from "node:os";
272
+ import { posix, win32 } from "node:path";
273
+ function joinFor(platform, ...parts) {
274
+ return (platform === "win32" ? win32 : posix).join(...parts);
275
+ }
276
+ function resolveContext(context = {}) {
277
+ return {
278
+ env: context.env ?? process.env,
279
+ home: context.home ?? homedir(),
280
+ platform: context.platform ?? process.platform
281
+ };
282
+ }
283
+ function userConfigHome(context) {
284
+ const { env, home, platform } = resolveContext(context);
285
+ const xdg = env.XDG_CONFIG_HOME;
286
+ if (xdg)
287
+ return xdg;
288
+ if (platform === "win32")
289
+ return env.APPDATA || joinFor(platform, home, "AppData", "Roaming");
290
+ return joinFor(platform, home, ".config");
291
+ }
292
+ function userConfigDir(context) {
293
+ const { env, home, platform } = resolveContext(context);
294
+ return joinFor(platform, userConfigHome({ env, home, platform }), SHARED_CONFIG_DIR);
295
+ }
296
+ function configFilePath(context) {
297
+ const { env, home, platform } = resolveContext(context);
298
+ return joinFor(platform, userConfigDir({ env, home, platform }), SHARED_CONFIG_FILE);
299
+ }
300
+ function readFileOptionsReport(file) {
301
+ let text;
302
+ try {
303
+ text = readFileSync(file, "utf8");
304
+ } catch (error) {
305
+ if (error.code === "ENOENT") {
306
+ return { options: {}, warnings: [], exists: false };
307
+ }
308
+ return { options: {}, warnings: [`cannot read ${file} — file ignored`], exists: true };
309
+ }
310
+ let parsed;
311
+ try {
312
+ parsed = JSON.parse(text);
313
+ } catch {
314
+ return { options: {}, warnings: [`${file} is not valid JSON — file ignored`], exists: true };
315
+ }
316
+ if (!isPlainObject(parsed)) {
317
+ return { options: {}, warnings: [`${file} is not a JSON object — file ignored`], exists: true };
318
+ }
319
+ const options = {};
320
+ const warnings = [];
321
+ for (const [key, value] of Object.entries(parsed)) {
322
+ if (SHARED_KEY_SET.has(key))
323
+ options[key] = value;
324
+ else if (HOST_INTEGRATION_KEYS.has(key))
325
+ warnings.push(`"${key}" is a host-integration key (host config only) — ignored`);
326
+ else
327
+ warnings.push(`unknown key "${key}" — ignored`);
328
+ }
329
+ return { options, warnings, exists: true };
330
+ }
331
+ function readFileOptions(file) {
332
+ const report = readFileOptionsReport(file);
333
+ for (const warning of report.warnings)
334
+ warn(warning);
335
+ return report.options;
336
+ }
337
+ function sharedFileOptions(context = {}) {
338
+ return readFileOptions(configFilePath(context));
339
+ }
340
+ function warn(line) {
341
+ console.error(`deepseek-web-retrieval config: ${line}`);
342
+ }
343
+ var SHARED_CONFIG_DIR = "deepseek-web-retrieval", SHARED_CONFIG_FILE = "config.json", SHARED_CONFIG_KEYS, SHARED_KEY_SET, HOST_INTEGRATION_KEYS;
344
+ var init_config_file = __esm(() => {
345
+ init_config_summary();
346
+ SHARED_CONFIG_KEYS = CONFIG_KEYS;
347
+ SHARED_KEY_SET = new Set(SHARED_CONFIG_KEYS);
348
+ HOST_INTEGRATION_KEYS = new Set([
349
+ "searchEnabled",
350
+ "fetchEnabled",
351
+ "setDefaultWebsearch",
352
+ "fetchOverrideWebfetch",
353
+ "fetchRegisterTool",
354
+ "apiKeySource"
355
+ ]);
356
+ });
357
+
358
+ // src/version.ts
359
+ import { readFileSync as readFileSync2 } from "node:fs";
20
360
  var TOOL_VERSION;
21
361
  var init_version = __esm(() => {
22
- TOOL_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
362
+ TOOL_VERSION = JSON.parse(readFileSync2(new URL("../package.json", import.meta.url), "utf8")).version;
23
363
  });
24
364
 
25
365
  // src/installer/persistence.ts
@@ -31,7 +371,7 @@ import {
31
371
  lstatSync,
32
372
  mkdirSync,
33
373
  openSync,
34
- readFileSync as readFileSync2,
374
+ readFileSync as readFileSync3,
35
375
  realpathSync,
36
376
  renameSync,
37
377
  rmSync,
@@ -65,7 +405,7 @@ function atomicWrite(file, text, mode) {
65
405
  try {
66
406
  fd = openSync(temporary, "wx", 384);
67
407
  writeFileSync(fd, text);
68
- if (readFileSync2(temporary, "utf8") !== text)
408
+ if (readFileSync3(temporary, "utf8") !== text)
69
409
  throw new Error(`Incomplete write to ${file}`);
70
410
  fchmodSync(fd, mode ?? existingMode ?? 438 & ~process.umask());
71
411
  fsyncSync(fd);
@@ -1447,11 +1787,6 @@ var init_jsonc = __esm(() => {
1447
1787
  init_main();
1448
1788
  });
1449
1789
 
1450
- // src/core/object.ts
1451
- function isPlainObject(value) {
1452
- return typeof value === "object" && value !== null && !Array.isArray(value);
1453
- }
1454
-
1455
1790
  // src/installer/formats/value.ts
1456
1791
  function deepEqual(a, b) {
1457
1792
  if (a === b)
@@ -1505,11 +1840,11 @@ function appendEntries(existing, entries, path) {
1505
1840
  var init_value = () => {};
1506
1841
 
1507
1842
  // src/installer/formats/json.ts
1508
- import { existsSync, readFileSync as readFileSync3 } from "node:fs";
1843
+ import { existsSync, readFileSync as readFileSync4 } from "node:fs";
1509
1844
  function loadJson(file) {
1510
1845
  if (!existsSync(file))
1511
1846
  return { exists: false, text: "", value: {}, lossy: false };
1512
- const text = readFileSync3(file, "utf8");
1847
+ const text = readFileSync4(file, "utf8");
1513
1848
  try {
1514
1849
  return { exists: true, text, value: parseJsonc(text), lossy: false };
1515
1850
  } catch (error) {
@@ -1641,7 +1976,7 @@ var init_json = __esm(() => {
1641
1976
  });
1642
1977
 
1643
1978
  // src/installer/formats/rules.ts
1644
- import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
1979
+ import { existsSync as existsSync2, readFileSync as readFileSync5 } from "node:fs";
1645
1980
  function rulesMarkers(host) {
1646
1981
  return {
1647
1982
  begin: `<!-- deepseek-web-retrieval:${host}:rules:begin -->`,
@@ -1696,7 +2031,7 @@ function rulesCodec(host) {
1696
2031
  format: "rules",
1697
2032
  load: (file) => {
1698
2033
  const exists = existsSync2(file);
1699
- const text = exists ? readFileSync4(file, "utf8") : "";
2034
+ const text = exists ? readFileSync5(file, "utf8") : "";
1700
2035
  try {
1701
2036
  blockRange(host, text);
1702
2037
  return { exists, text, value: {}, lossy: false };
@@ -2904,11 +3239,11 @@ var init_dist = __esm(() => {
2904
3239
  });
2905
3240
 
2906
3241
  // src/installer/formats/toml.ts
2907
- import { existsSync as existsSync3, readFileSync as readFileSync5 } from "node:fs";
3242
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
2908
3243
  function loadToml(file) {
2909
3244
  if (!existsSync3(file))
2910
3245
  return { exists: false, text: "", value: {}, lossy: false };
2911
- const text = readFileSync5(file, "utf8");
3246
+ const text = readFileSync6(file, "utf8");
2912
3247
  try {
2913
3248
  return { exists: true, text, value: parse3(text), lossy: hasTomlComment(text) };
2914
3249
  } catch (error) {
@@ -3081,7 +3416,7 @@ var init_formats = __esm(() => {
3081
3416
  });
3082
3417
 
3083
3418
  // src/installer/revert.ts
3084
- import { existsSync as existsSync4, readFileSync as readFileSync6, rmdirSync, unlinkSync } from "node:fs";
3419
+ import { existsSync as existsSync4, readFileSync as readFileSync7, rmdirSync, unlinkSync } from "node:fs";
3085
3420
  import { dirname as dirname2 } from "node:path";
3086
3421
  function pruneEmptyDir(dir) {
3087
3422
  try {
@@ -3095,7 +3430,7 @@ function revertRecordedFile(file, host, opts) {
3095
3430
  return lines;
3096
3431
  }
3097
3432
  const codec = codecFor(file.format, host);
3098
- const text = readFileSync6(file.file, "utf8");
3433
+ const text = readFileSync7(file.file, "utf8");
3099
3434
  if (file.format === "rules") {
3100
3435
  const edit2 = { file: file.file, format: "rules", block: file.blockApplied ?? "" };
3101
3436
  if (!codec.verify(text, edit2)) {
@@ -3144,16 +3479,29 @@ function stateDir(roots, scope) {
3144
3479
  var init_paths = () => {};
3145
3480
 
3146
3481
  // src/installer/state.ts
3147
- import { existsSync as existsSync5, lstatSync as lstatSync2, readdirSync, readFileSync as readFileSync7, rmSync as rmSync2 } from "node:fs";
3482
+ import { existsSync as existsSync5, lstatSync as lstatSync2, readdirSync, readFileSync as readFileSync8, rmSync as rmSync2 } from "node:fs";
3148
3483
  import { isAbsolute, join as join3 } from "node:path";
3149
3484
  import { z } from "zod/v4";
3150
3485
  function statePathFor(input) {
3151
3486
  return join3(stateDir(input, input.scope), `install.${input.host}.json`);
3152
3487
  }
3488
+ function platformOf(roots) {
3489
+ return roots.platform ?? process.platform;
3490
+ }
3491
+ function legacyGlobalStateDir(roots) {
3492
+ return join3(roots.home, ".config", "deepseek-web-retrieval");
3493
+ }
3494
+ function recordReadPath(input, platform = platformOf(input)) {
3495
+ const canonical = statePathFor(input);
3496
+ if (platform !== "win32" || input.scope !== "global" || existsSync5(canonical))
3497
+ return canonical;
3498
+ const legacy = join3(legacyGlobalStateDir(input), `install.${input.host}.json`);
3499
+ return existsSync5(legacy) ? legacy : canonical;
3500
+ }
3153
3501
  function readRecordFile(file, host, scope) {
3154
3502
  let text;
3155
3503
  try {
3156
- text = readFileSync7(file, "utf8");
3504
+ text = readFileSync8(file, "utf8");
3157
3505
  } catch (error) {
3158
3506
  if (error.code === "ENOENT") {
3159
3507
  try {
@@ -3181,7 +3529,7 @@ function readRecordFile(file, host, scope) {
3181
3529
  return result.data;
3182
3530
  }
3183
3531
  function readRecord(input) {
3184
- return readRecordFile(statePathFor(input), input.host, input.scope);
3532
+ return readRecordFile(recordReadPath(input), input.host, input.scope);
3185
3533
  }
3186
3534
  function claimedByOtherScope(input, files) {
3187
3535
  const other = input.scope === "global" ? "project" : "global";
@@ -3210,32 +3558,49 @@ function appendedByPrevious(record, path) {
3210
3558
  return entries;
3211
3559
  }
3212
3560
  function deleteRecord(input) {
3213
- const file = statePathFor(input);
3561
+ const file = recordReadPath(input);
3214
3562
  if (existsSync5(file))
3215
3563
  rmSync2(file);
3216
3564
  }
3217
- function listRecords(roots) {
3565
+ function readRecordsFromDir(dir, scope) {
3218
3566
  const records = [];
3219
- for (const scope of ["global", "project"]) {
3220
- const dir = stateDir(roots, scope);
3221
- let names;
3222
- try {
3223
- names = readdirSync(dir);
3224
- } catch (error) {
3225
- if (error.code === "ENOENT")
3226
- continue;
3227
- throw new InstallRecordError(dir, "unreadable", error.code ?? "list failed");
3228
- }
3229
- for (const name of names) {
3230
- if (!name.startsWith("install.") || !name.endsWith(".json"))
3231
- continue;
3232
- const record = readRecordFile(join3(dir, name), name.slice("install.".length, -".json".length), scope);
3233
- if (record !== undefined)
3234
- records.push(record);
3235
- }
3567
+ let names;
3568
+ try {
3569
+ names = readdirSync(dir);
3570
+ } catch (error) {
3571
+ if (error.code === "ENOENT")
3572
+ return records;
3573
+ throw new InstallRecordError(dir, "unreadable", error.code ?? "list failed");
3574
+ }
3575
+ for (const name of names) {
3576
+ if (!name.startsWith("install.") || !name.endsWith(".json"))
3577
+ continue;
3578
+ const record = readRecordFile(join3(dir, name), name.slice("install.".length, -".json".length), scope);
3579
+ if (record !== undefined)
3580
+ records.push(record);
3236
3581
  }
3237
3582
  return records;
3238
3583
  }
3584
+ function hasRecordFiles(dir) {
3585
+ try {
3586
+ return readdirSync(dir).some((name) => name.startsWith("install.") && name.endsWith(".json"));
3587
+ } catch {
3588
+ return false;
3589
+ }
3590
+ }
3591
+ function readingLegacyGlobalRecords(roots) {
3592
+ if (platformOf(roots) !== "win32")
3593
+ return false;
3594
+ if (hasRecordFiles(stateDir(roots, "global")))
3595
+ return false;
3596
+ return hasRecordFiles(legacyGlobalStateDir(roots));
3597
+ }
3598
+ function listRecords(roots) {
3599
+ const global = readRecordsFromDir(stateDir(roots, "global"), "global");
3600
+ const project = readRecordsFromDir(stateDir(roots, "project"), "project");
3601
+ const legacy = readingLegacyGlobalRecords(roots) ? readRecordsFromDir(legacyGlobalStateDir(roots), "global") : [];
3602
+ return [...global, ...legacy, ...project];
3603
+ }
3239
3604
  var keyPath, tier, operation, recordSchema, InstallRecordError;
3240
3605
  var init_state = __esm(() => {
3241
3606
  init_paths();
@@ -3281,8 +3646,25 @@ var init_state = __esm(() => {
3281
3646
  });
3282
3647
 
3283
3648
  // src/installer/ownership.ts
3284
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
3649
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
3285
3650
  import { basename as basename2, dirname as dirname3, join as join4, resolve } from "node:path";
3651
+ function hasVersionSuffix(ref) {
3652
+ const at = ref.lastIndexOf("@");
3653
+ return at > 0 && /^[0-9]/.test(ref.slice(at + 1));
3654
+ }
3655
+ function stripVersionSuffix(ref) {
3656
+ const at = ref.lastIndexOf("@");
3657
+ return hasVersionSuffix(ref) ? ref.slice(0, at) : ref;
3658
+ }
3659
+ function samePackageName(a, b) {
3660
+ return stripVersionSuffix(a) === stripVersionSuffix(b);
3661
+ }
3662
+ function lineageMatcher(refs) {
3663
+ return (candidate) => refs.some((ref) => samePackageName(ref, candidate));
3664
+ }
3665
+ function pinPackageRef(ref, version) {
3666
+ return hasVersionSuffix(ref) ? ref : `${ref}@${version}`;
3667
+ }
3286
3668
  function canonicalPath(file) {
3287
3669
  const absolute = resolve(file);
3288
3670
  if (existsSync6(absolute))
@@ -3304,7 +3686,7 @@ function readOwner(file) {
3304
3686
  if (!existsSync6(file))
3305
3687
  return;
3306
3688
  try {
3307
- const value = JSON.parse(readFileSync8(file, "utf8"));
3689
+ const value = JSON.parse(readFileSync9(file, "utf8"));
3308
3690
  if (isPlainObject(value) && typeof value.recordPath === "string" && typeof value.cwd === "string" && (value.scope === "project" || value.scope === "global")) {
3309
3691
  return { recordPath: value.recordPath, cwd: value.cwd, scope: value.scope };
3310
3692
  }
@@ -3315,6 +3697,8 @@ function assertOwner(input, claim) {
3315
3697
  const owner = readOwner(claim);
3316
3698
  if (owner === undefined || owner.recordPath === ownerOf(input).recordPath)
3317
3699
  return;
3700
+ if (owner.recordPath === canonicalPath(recordReadPath(input)))
3701
+ return;
3318
3702
  throw new Error(`A ${input.host} install is already recorded at the ${owner.scope} scope (${owner.recordPath}) and claims the same config file. ` + `Uninstall it first: deepseek-web-retrieval uninstall --host ${input.host} --scope ${owner.scope} --cwd ${JSON.stringify(owner.cwd)}. ` + "Two install records must not edit one file.");
3319
3703
  }
3320
3704
  function assertFileOwnership(input, files) {
@@ -3418,7 +3802,7 @@ var init_operation_lock = __esm(() => {
3418
3802
  });
3419
3803
 
3420
3804
  // src/installer/apply.ts
3421
- import { existsSync as existsSync7, readFileSync as readFileSync9, rmSync as rmSync5 } from "node:fs";
3805
+ import { existsSync as existsSync7, readFileSync as readFileSync10, rmSync as rmSync5 } from "node:fs";
3422
3806
  import { dirname as dirname5 } from "node:path";
3423
3807
  function applyPlan(plan, input) {
3424
3808
  if (plan.errors.length > 0) {
@@ -3516,7 +3900,7 @@ function snapshotTouchedFiles(plan) {
3516
3900
  const snapshots = new Map;
3517
3901
  const touched = [...plan.edits.map((edit2) => edit2.file), ...(plan.reverts ?? []).map((revert) => revert.file)];
3518
3902
  for (const file of new Set(touched)) {
3519
- snapshots.set(file, existsSync7(file) ? { exists: true, text: readFileSync9(file, "utf8") } : { exists: false, text: "" });
3903
+ snapshots.set(file, existsSync7(file) ? { exists: true, text: readFileSync10(file, "utf8") } : { exists: false, text: "" });
3520
3904
  }
3521
3905
  return snapshots;
3522
3906
  }
@@ -3526,10 +3910,10 @@ function rollbackApply(input, previous, snapshots) {
3526
3910
  for (const [file, snapshot] of [...snapshots.entries()].reverse()) {
3527
3911
  try {
3528
3912
  if (snapshot.exists) {
3529
- if (existsSync7(file) && readFileSync9(file, "utf8") === snapshot.text)
3913
+ if (existsSync7(file) && readFileSync10(file, "utf8") === snapshot.text)
3530
3914
  continue;
3531
3915
  writeConfig(file, snapshot.text);
3532
- if (readFileSync9(file, "utf8") !== snapshot.text)
3916
+ if (readFileSync10(file, "utf8") !== snapshot.text)
3533
3917
  throw new Error("restored contents differ from the snapshot");
3534
3918
  } else {
3535
3919
  if (!existsSync7(file))
@@ -3622,7 +4006,7 @@ function verifyEdits(edits, host) {
3622
4006
  continue;
3623
4007
  }
3624
4008
  const codec = codecFor(edit2.format, host);
3625
- const text = readFileSync9(edit2.file, "utf8");
4009
+ const text = readFileSync10(edit2.file, "utf8");
3626
4010
  if (edit2.format === "rules") {
3627
4011
  const good = codec.verify(text, edit2);
3628
4012
  lines.push(`${good ? "pass" : "FAIL"} ${edit2.file}: rules block ${good ? "present" : "missing"}`);
@@ -3661,1956 +4045,1940 @@ var init_apply = __esm(() => {
3661
4045
  };
3662
4046
  });
3663
4047
 
3664
- // src/core/constants.ts
3665
- var SEARCH_ENDPOINT = "https://api.deepseek.com/v1/tools/search", FETCH_ENDPOINT = "https://api.deepseek.com/v1/tools/fetch", DEFAULT_SEARCH_COUNT = 10, DEFAULT_MAX_RESULTS = 10, DEFAULT_MIN_RERANK = 0, DEFAULT_MIN_AUTHORITY = 0, DEFAULT_MAX_SUMMARY_CHARS = 1200, DEFAULT_FETCH_MAX_CHARS = 16000, DEFAULT_TIMEOUT_MS = 30000, MIN_TIMEOUT_MS = 1000, MAX_TIMEOUT_MS = 120000, MAX_QUERY_CHARS = 128, MAX_URL_CHARS = 8192, MAX_ERROR_BODY_CHARS = 2000, MAX_RESPONSE_BYTES, FETCH_TRUNCATION_MARKER = `
3666
-
3667
- [content truncated]`, DEFAULT_API_KEY_SOURCE = "auto", DEFAULT_MAX_RETRIES = 0, MAX_RETRIES = 5, DEFAULT_RETRY_BASE_DELAY_MS = 250, MAX_RETRY_DELAY_MS = 1e4, API_KEY_ENV = "DEEPSEEK_API_KEY", ENABLE_SEARCH_ENV = "DEEPSEEK_ENABLE_SEARCH", ENABLE_FETCH_ENV = "DEEPSEEK_ENABLE_FETCH";
3668
- var init_constants = __esm(() => {
3669
- MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
4048
+ // src/core/auth.ts
4049
+ function apiKeyFromEnv(env = process.env) {
4050
+ const key = env[API_KEY_ENV]?.trim();
4051
+ return key ? key : undefined;
4052
+ }
4053
+ var MISSING_API_KEY_MESSAGE;
4054
+ var init_auth = __esm(() => {
4055
+ init_constants();
4056
+ MISSING_API_KEY_MESSAGE = `DeepSeek API key not found. Set ${API_KEY_ENV} in the MCP server's env configuration.`;
3670
4057
  });
3671
4058
 
3672
- // src/installer/detect.ts
3673
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "node:fs";
3674
- function replacingExistingEntryNote(path) {
3675
- return `An existing ${path} entry is being replaced; its previous form is recorded for uninstall.`;
4059
+ // src/core/format.ts
4060
+ function truncate(value, maxChars) {
4061
+ if (maxChars <= 0)
4062
+ return "";
4063
+ if (value.length <= maxChars)
4064
+ return value;
4065
+ return Array.from(value).slice(0, maxChars).join("");
3676
4066
  }
3677
- function othersStayRegisteredNote(others) {
3678
- return `Other MCP servers stay registered (${others.join(", ")}); routing to DeepSeek is not exclusive while they offer web tools.`;
4067
+ function formatFetchedContent(title, content, maxChars) {
4068
+ const document = withTitle(title, content);
4069
+ const length = Array.from(document).length;
4070
+ if (maxChars <= 0)
4071
+ return { content: "", truncated: length > 0 };
4072
+ if (length <= maxChars)
4073
+ return { content: document, truncated: false };
4074
+ const markerLength = Array.from(FETCH_TRUNCATION_MARKER).length;
4075
+ if (maxChars <= markerLength) {
4076
+ return { content: truncate(document, maxChars), truncated: true };
4077
+ }
4078
+ return {
4079
+ content: `${truncate(document, maxChars - markerLength)}${FETCH_TRUNCATION_MARKER}`,
4080
+ truncated: true
4081
+ };
3679
4082
  }
3680
- function looksWebCapable(name, entry) {
3681
- if (WEB_TOOL_HINT.test(name))
3682
- return true;
3683
- if (!isPlainObject(entry))
3684
- return false;
3685
- const command = typeof entry.command === "string" ? entry.command : "";
3686
- const url = typeof entry.url === "string" ? entry.url : "";
3687
- const args = Array.isArray(entry.args) ? entry.args.filter((arg) => typeof arg === "string").join(" ") : "";
3688
- return WEB_TOOL_HINT.test(`${command} ${args} ${url}`);
4083
+ function withTitle(title, content) {
4084
+ const heading = title.trim();
4085
+ if (!heading)
4086
+ return content;
4087
+ const body = content.trimStart();
4088
+ const lines = body.split(/\r?\n/);
4089
+ const firstHeading = lines[0]?.match(/^\\?#\s+(.+?)\s*$/)?.[1];
4090
+ if (firstHeading && normalizeHeading(firstHeading) === normalizeHeading(heading)) {
4091
+ lines[0] = `# ${heading}`;
4092
+ return lines.join(`
4093
+ `);
4094
+ }
4095
+ return `# ${heading}
4096
+
4097
+ ${content}`;
3689
4098
  }
3690
- function looksLikeOwnPackage(source) {
3691
- return /(^|[/:@])deepseek-web-retrieval($|[@/]|-\d)/.test(source);
4099
+ function normalizeHeading(value) {
4100
+ return value.trim().replace(/\s+/g, " ").replace(/\s+#+\s*$/, "").toLowerCase();
3692
4101
  }
3693
- function findCompetitorSteering(host, file) {
3694
- if (!existsSync8(file))
3695
- return [];
3696
- let text;
3697
- try {
3698
- text = readFileSync10(file, "utf8");
3699
- } catch {
3700
- return [];
3701
- }
3702
- return removeBlock(host, text).split(`
3703
- `).map((line) => line.trim()).filter((line) => line.length > 0 && STEERING_HINT.test(line) && !line.includes("deepseek")).slice(0, 2);
4102
+ function redactSecrets(value) {
4103
+ return value.replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "sk-***").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, "Bearer ***");
3704
4104
  }
3705
- function competitorSteeringNote(file, lines) {
3706
- const quoted = lines.map((line) => `"${line}"`).join(", ");
3707
- return `Existing rules in ${file} steer toward other web tools (${quoted}); the plan surfaces this conflict — it does not resolve it.`;
4105
+ function formatApiError(operation2, status, body) {
4106
+ const detail = redactSecrets(body.trim());
4107
+ const detailChars = Array.from(detail);
4108
+ const text = detail ? detailChars.length > MAX_ERROR_BODY_CHARS ? `${detailChars.slice(0, MAX_ERROR_BODY_CHARS).join("")}…` : detail : "empty response body";
4109
+ const hint = status === 401 ? "invalid API key" : status === 402 ? "insufficient balance" : status === 403 ? "permission denied" : status === 429 ? "rate limited" : undefined;
4110
+ const label = hint ? `${operation2} failed (HTTP ${status}, ${hint})` : `${operation2} failed (HTTP ${status})`;
4111
+ return `${label}: ${text}`;
3708
4112
  }
3709
- function splitCompetitors(servers) {
3710
- const competitors = [];
3711
- const bystanders = [];
3712
- for (const [name, entry] of Object.entries(servers)) {
3713
- if (name === "deepseek")
3714
- continue;
3715
- (looksWebCapable(name, entry) ? competitors : bystanders).push(name);
3716
- }
3717
- return { competitors, bystanders };
4113
+ function formatTimeoutError(operation2, timeoutMs) {
4114
+ return `${operation2} timed out after ${timeoutMs} ms`;
3718
4115
  }
3719
- var BOTH_CAPABILITIES_OFF = "Both capabilities are off; nothing would be installed.", FORCED_COST_NOTE, WEB_TOOL_HINT, STEERING_HINT;
3720
- var init_detect = __esm(() => {
3721
- init_rules();
3722
- init_value();
3723
- FORCED_COST_NOTE = "Forced routing is deterministic, and Search and Fetch are billed per successful request — " + `see the README's "Privacy and cost" section before applying.`;
3724
- WEB_TOOL_HINT = /(web[_ -]?(search|fetch)|search|fetch|browse|scrape|crawl|tavily|brave|exa|perplexity|firecrawl|jina|serp|duckduckgo|reader)/i;
3725
- STEERING_HINT = /(web[_ ]?(search|fetch)|websearch|webfetch|tavily|exa|brave|perplexity|firecrawl|jina|serp|duckduckgo|google|bing)/i;
3726
- });
4116
+ function formatSearchResults(results) {
4117
+ if (results.length === 0)
4118
+ return "No results found.";
4119
+ return results.map((result, index) => {
4120
+ const title = result.title?.trim() || result.url;
4121
+ const marker = formatQualityMarker(result);
4122
+ const lines = [`${index + 1}. [${escapeBrackets(title)}](${result.url})${marker ? ` ${marker}` : ""}`];
4123
+ if (result.content) {
4124
+ lines.push(` ${result.content.replaceAll(`
4125
+ `, " ")}`);
4126
+ }
4127
+ if (result.published !== undefined) {
4128
+ lines.push(` Published: ${formatPublished(result.published)}`);
4129
+ }
4130
+ return lines.join(`
4131
+ `);
4132
+ }).join(`
3727
4133
 
3728
- // src/installer/rulesContent.ts
3729
- function rulesLines(ids, search, fetch) {
3730
- const lines = ["DeepSeek retrieval guidance:"];
3731
- if (search === "preferred") {
3732
- lines.push(`- Use ${ids.search} when the task needs fresh external information: current docs, version numbers,`, " changelogs, or anything you cannot know from the repository alone. Do not search for facts already", " present locally.");
3733
- }
3734
- if (fetch === "preferred") {
3735
- lines.push(`- Use ${ids.fetch} to read a specific public web page as Markdown when its content is needed.`);
3736
- }
3737
- lines.push("- Never send localhost or private-network URLs to the DeepSeek tools; use local tools for those (the", " server blocks private hosts by default).", "- DeepSeek requests are billed per successful call; retrieve only what the task needs.");
3738
- return lines;
4134
+ `);
3739
4135
  }
3740
- var MCP_TOOL_IDS, RAW_MCP_TOOL_IDS;
3741
- var init_rulesContent = __esm(() => {
3742
- MCP_TOOL_IDS = {
3743
- search: "mcp__deepseek__deepseek_web_search",
3744
- fetch: "mcp__deepseek__deepseek_fetch"
4136
+ function formatQualityMarker(result) {
4137
+ const parts = [];
4138
+ if (result.rerankScore !== undefined)
4139
+ parts.push(`rerank ${result.rerankScore}`);
4140
+ if (result.authority !== undefined && result.authority >= 0)
4141
+ parts.push(`authority ${result.authority}`);
4142
+ if (result.siteName)
4143
+ parts.push(result.siteName);
4144
+ return parts.length > 0 ? `[${parts.join(" · ")}]` : "";
4145
+ }
4146
+ function toStructuredResult(result) {
4147
+ return {
4148
+ url: result.url,
4149
+ ...result.title ? { title: result.title } : {},
4150
+ ...result.content ? { content: result.content } : {},
4151
+ ...result.published !== undefined ? { published: result.published } : {},
4152
+ ...result.rerankScore !== undefined ? { rerankScore: result.rerankScore } : {},
4153
+ ...result.authority !== undefined ? { authority: result.authority } : {},
4154
+ ...result.siteName ? { siteName: result.siteName } : {}
3745
4155
  };
3746
- RAW_MCP_TOOL_IDS = { search: "deepseek_web_search", fetch: "deepseek_fetch" };
4156
+ }
4157
+ function escapeBrackets(value) {
4158
+ return value.replaceAll("[", "\\[").replaceAll("]", "\\]");
4159
+ }
4160
+ function formatPublished(epochMs) {
4161
+ return new Date(epochMs).toISOString().slice(0, 10);
4162
+ }
4163
+ var init_format2 = __esm(() => {
4164
+ init_constants();
3747
4165
  });
3748
4166
 
3749
- // src/installer/hosts/shared.ts
3750
- function planHeader(input, paths, loaded, dialect) {
3751
- const notes = [];
3752
- const errors = [];
3753
- if (loaded.parseError) {
3754
- errors.push({ message: `${paths.config} exists but does not parse as ${dialect}: ${loaded.parseError}` });
3755
- return { notes, errors, abort: true };
4167
+ // src/core/url.ts
4168
+ function parseFetchUrl(value) {
4169
+ const input = value.trim();
4170
+ if (!input)
4171
+ throw new Error("URL must not be empty");
4172
+ if (input.length > MAX_URL_CHARS) {
4173
+ throw new Error(`URL must be ${MAX_URL_CHARS} characters or fewer`);
3756
4174
  }
3757
- if (input.search === "off" && input.fetch === "off") {
3758
- errors.push({ message: BOTH_CAPABILITIES_OFF });
4175
+ let url;
4176
+ try {
4177
+ url = new URL(input);
4178
+ } catch {
4179
+ throw new Error("URL must be an absolute http:// or https:// URL");
3759
4180
  }
3760
- const rules = codecFor("rules", input.host).load(paths.rules);
3761
- if (rules.parseError) {
3762
- errors.push({ message: `${paths.rules}: ${rules.parseError}` });
3763
- return { notes, errors, abort: true };
4181
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
4182
+ throw new Error("URL must use http:// or https://");
3764
4183
  }
3765
- const steering = findCompetitorSteering(input.host, paths.rules);
3766
- if (steering.length > 0)
3767
- notes.push(competitorSteeringNote(paths.rules, steering));
3768
- return { notes, errors, abort: false };
4184
+ if (!url.hostname || !normalizeHostname(url.hostname)) {
4185
+ throw new Error("URL must include a host");
4186
+ }
4187
+ if (url.username || url.password) {
4188
+ throw new Error("URL must not contain credentials");
4189
+ }
4190
+ return url;
3769
4191
  }
3770
- var init_shared = __esm(() => {
3771
- init_detect();
3772
- init_formats();
3773
- });
3774
-
3775
- // src/installer/hosts/codex.ts
3776
- import { spawnSync } from "node:child_process";
3777
- function probeCodexVersion(err) {
3778
- const result = spawnSync("codex", ["--version"], { timeout: 5000, encoding: "utf8", env: process.env });
3779
- const version = result.status === 0 ? parseCodexVersion(result.stdout ?? "") : undefined;
3780
- if (version === undefined) {
3781
- err("note: codex was not found on PATH or printed no version; the version-drift check was skipped");
4192
+ function normalizeResultUrl(value) {
4193
+ if (typeof value !== "string")
4194
+ return;
4195
+ const input = value.trim();
4196
+ if (!input || input.length > MAX_URL_CHARS)
4197
+ return;
4198
+ try {
4199
+ const url = new URL(input);
4200
+ if (url.protocol !== "http:" && url.protocol !== "https:")
4201
+ return;
4202
+ if (!url.hostname || url.username || url.password)
4203
+ return;
4204
+ return url.href;
4205
+ } catch {
4206
+ return;
3782
4207
  }
3783
- return version;
3784
4208
  }
3785
- function parseCodexVersion(output) {
3786
- return /\bcodex(?:-cli)?\s+(\d+\.\d+\.\d+)\b/.exec(output)?.[1];
4209
+ var init_url = __esm(() => {
4210
+ init_constants();
4211
+ init_domains();
4212
+ });
4213
+
4214
+ // src/core/search.ts
4215
+ function buildQuery(query, options) {
4216
+ const parts = [query.trim()];
4217
+ for (const domain of normalizeDomains(options.blockedDomains))
4218
+ parts.push(`-site:${domain}`);
4219
+ const include = normalizeDomains(options.includeDomains);
4220
+ if (include.length)
4221
+ parts.push(include.map((domain) => `site:${domain}`).join(" OR "));
4222
+ const language = options.language?.trim().replace(/^lang:/i, "");
4223
+ if (language)
4224
+ parts.push(`lang:${language}`);
4225
+ return parts.filter((part) => part.length > 0).join(" ");
3787
4226
  }
3788
- function codexPaths(input) {
3789
- return {
3790
- config: join2(input.home, ".codex/config.toml"),
3791
- rules: input.scope === "global" ? join2(input.home, ".codex/AGENTS.md") : join2(input.cwd, "AGENTS.md")
3792
- };
4227
+ function parsePublished(value) {
4228
+ if (typeof value !== "string" || !value.trim())
4229
+ return;
4230
+ const timestamp = Date.parse(value);
4231
+ return Number.isFinite(timestamp) ? timestamp : undefined;
3793
4232
  }
3794
- function planCodex(input, _previous) {
3795
- const paths = codexPaths(input);
3796
- const loaded = codecFor("toml", input.host).load(paths.config);
3797
- const tiers = { search: input.search, fetch: input.fetch };
3798
- const header = planHeader(input, paths, loaded, "TOML");
3799
- if (header.abort) {
3800
- return { host: "codex", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
3801
- }
3802
- const notes = [...header.notes];
3803
- const errors = [...header.errors];
3804
- const edits = [];
3805
- if (input.hostVersion !== undefined && input.hostVersion !== CODEX_TESTED_VERSION) {
3806
- notes.push(`Codex ${input.hostVersion} is installed, but this installer's Codex facts are verified against ` + `${CODEX_TESTED_VERSION} (the docs/hosts.jsonc lock). Kill-switch and trap behavior may have drifted ` + "between the two — re-verify the tiers if routing misbehaves.");
3807
- }
3808
- const tools = loaded.value.tools;
3809
- if (isPlainObject(tools) && "web_search" in tools) {
3810
- errors.push({
3811
- message: `${paths.config} sets [tools] web_search, which is a silent no-op at Codex 0.163.0 (only the top-level ` + "web_search key controls the tool). Remove it first so the config cannot mislead."
3812
- });
3813
- }
3814
- const servers = loaded.value.mcp_servers;
3815
- if (isPlainObject(servers)) {
3816
- if ("deepseek" in servers)
3817
- notes.push(replacingExistingEntryNote("mcp_servers.deepseek"));
3818
- const { competitors, bystanders } = splitCompetitors(servers);
3819
- if ((input.search === "forced" || input.fetch === "forced") && competitors.length > 0) {
3820
- errors.push({
3821
- message: `Forced cannot deliver exclusive routing: [mcp_servers.${competitors.join("], [mcp_servers.")}] look(s) web-capable, ` + "and Codex offers no per-server kill switch. Remove the server(s), disable their tools by hand via their " + "disabled_tools key, or choose a lower tier."
3822
- });
4233
+ function processResults(raw, options) {
4234
+ const results = [];
4235
+ const seen = new Set;
4236
+ for (const item of raw) {
4237
+ if (results.length >= options.maxResults)
4238
+ break;
4239
+ if (!item || typeof item !== "object")
4240
+ continue;
4241
+ const url = normalizeResultUrl(item.url);
4242
+ if (!url || seen.has(url))
4243
+ continue;
4244
+ const rerank = item.rerank_score;
4245
+ if (typeof rerank === "number" && Number.isFinite(rerank)) {
4246
+ if (rerank < options.minRerank)
4247
+ continue;
4248
+ } else if (options.minRerank > 0) {
4249
+ continue;
3823
4250
  }
3824
- const stayRegistered = input.search === "forced" || input.fetch === "forced" ? bystanders : [...competitors, ...bystanders];
3825
- if (stayRegistered.length > 0)
3826
- notes.push(othersStayRegisteredNote(stayRegistered));
3827
- }
3828
- const existingEntry = isPlainObject(servers) ? servers.deepseek : undefined;
3829
- const rawToolIds = Object.values(RAW_MCP_TOOL_IDS);
3830
- const keptDisabled = isPlainObject(existingEntry) && Array.isArray(existingEntry.disabled_tools) ? existingEntry.disabled_tools.filter((name) => typeof name === "string" && !rawToolIds.includes(name)) : [];
3831
- const offDisabled = [
3832
- ...input.search === "off" ? [RAW_MCP_TOOL_IDS.search] : [],
3833
- ...input.fetch === "off" ? [RAW_MCP_TOOL_IDS.fetch] : []
3834
- ];
3835
- const entry = {
3836
- command: "npx",
3837
- args: ["-y", input.packageRef],
3838
- ...keptDisabled.length > 0 || offDisabled.length > 0 ? { disabled_tools: [...keptDisabled, ...offDisabled] } : {},
3839
- env_vars: [API_KEY_ENV]
3840
- };
3841
- const ops = [{ op: "set", path: ["mcp_servers", "deepseek"], value: entry, previous: existingEntry }];
3842
- if (offDisabled.length > 0) {
3843
- notes.push(`Off capabilities use Codex's own disabled_tools key (${offDisabled.join(", ")}): the tools are removed from ` + "the model's context while the server keeps running and stays re-enableable by deleting the entries.");
3844
- }
3845
- if (input.search === "forced") {
3846
- const previous = typeof loaded.value.web_search === "string" ? loaded.value.web_search : undefined;
3847
- ops.push({ op: "set", path: ["web_search"], value: "disabled", previous });
3848
- notes.push(previous === undefined ? 'web_search is being set to "disabled" (no previous value existed; the default is "cached").' : `web_search is being set to "disabled"; the previous value "${previous}" is snapshotted for uninstall.`);
3849
- }
3850
- edits.push({ file: paths.config, format: "toml", shared: true, ops });
3851
- notes.push(`Codex stdio children do not inherit the parent environment, so the entry forwards ${API_KEY_ENV} explicitly ` + "via env_vars; the key must be set in the shell that launches Codex.");
3852
- if (input.scope === "project") {
3853
- notes.push("Codex config lives in ~/.codex/config.toml only (user level), so the server registration and kill switch are " + "written there even for a project-scope install; the rules file stays project-local.");
3854
- }
3855
- if (loaded.lossy) {
3856
- notes.push(`${paths.config} contains comments; the TOML rewrite will drop them.`);
3857
- }
3858
- if (input.search === "forced" || input.fetch === "forced") {
3859
- notes.push(`Forced search is exclusion: the built-in web_search tool is disabled ("disabled" mode). ${FORCED_COST_NOTE}`);
3860
- }
3861
- if (input.search === "optional" || input.fetch === "optional") {
3862
- notes.push('Note: Codex ships a built-in web_search tool (default "cached" mode, an OpenAI index) that stays available ' + "alongside the DeepSeek tools under the optional tier.");
3863
- }
3864
- if (input.search === "preferred" || input.fetch === "preferred") {
3865
- edits.push({
3866
- file: paths.rules,
3867
- format: "rules",
3868
- block: buildRulesBlock(input.host, rulesLines(MCP_TOOL_IDS, input.search, input.fetch))
4251
+ const authority = item.authority;
4252
+ const knownAuthority = typeof authority === "number" && Number.isFinite(authority) && authority >= 0;
4253
+ if (knownAuthority) {
4254
+ if (authority < options.minAuthority)
4255
+ continue;
4256
+ } else if (!options.allowUnknownAuthority) {
4257
+ continue;
4258
+ }
4259
+ seen.add(url);
4260
+ const content = truncate(optionalText2(item.summary) ?? optionalText2(item.snippet) ?? "", options.maxSummaryChars);
4261
+ const published = parsePublished(item.date);
4262
+ const title = optionalText2(item.title);
4263
+ const rerankScore = typeof rerank === "number" && Number.isFinite(rerank) ? rerank : undefined;
4264
+ const authorityScore = typeof authority === "number" && Number.isFinite(authority) ? authority : undefined;
4265
+ const siteName = optionalText2(item.site_name);
4266
+ results.push({
4267
+ url,
4268
+ ...title ? { title } : {},
4269
+ ...content ? { content } : {},
4270
+ ...published !== undefined ? { published } : {},
4271
+ ...rerankScore !== undefined ? { rerankScore } : {},
4272
+ ...authorityScore !== undefined ? { authority: authorityScore } : {},
4273
+ ...siteName ? { siteName } : {}
3869
4274
  });
3870
- notes.push(input.scope === "global" ? `Rules block upserted in ${paths.rules}; Codex reads ~/.codex/AGENTS.md plus every AGENTS.md from the project root to the cwd.` : `Rules block upserted in ${paths.rules}; Codex reads every AGENTS.md from the project root to the cwd.`);
3871
4275
  }
3872
- return { host: "codex", scope: input.scope, tiers, edits, notes, errors };
4276
+ return results;
3873
4277
  }
3874
- var CODEX_TESTED_VERSION = "0.163.0";
3875
- var init_codex = __esm(() => {
3876
- init_constants();
3877
- init_detect();
3878
- init_formats();
3879
- init_rules();
3880
- init_value();
3881
- init_paths();
3882
- init_rulesContent();
3883
- init_shared();
4278
+ function optionalText2(value) {
4279
+ if (typeof value !== "string")
4280
+ return;
4281
+ const trimmed = value.trim();
4282
+ return trimmed ? trimmed : undefined;
4283
+ }
4284
+ var init_search = __esm(() => {
4285
+ init_domains();
4286
+ init_format2();
4287
+ init_url();
3884
4288
  });
3885
4289
 
3886
- // src/installer/hosts/opencode.ts
3887
- function opencodePaths(input) {
3888
- return input.scope === "global" ? {
3889
- config: join2(configHome(input), "opencode/opencode.jsonc"),
3890
- rules: join2(configHome(input), "opencode/AGENTS.md")
3891
- } : { config: join2(input.cwd, "opencode.jsonc"), rules: join2(input.cwd, "AGENTS.md") };
3892
- }
3893
- function planOpenCode(input, previous) {
3894
- const paths = opencodePaths(input);
3895
- const loaded = codecFor("json", input.host).load(paths.config);
3896
- const tiers = { search: input.search, fetch: input.fetch };
3897
- const header = planHeader(input, paths, loaded, "JSONC");
3898
- if (header.abort) {
3899
- return { host: "opencode", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
3900
- }
3901
- const notes = [...header.notes];
3902
- const errors = [...header.errors];
3903
- const edits = [];
3904
- if (input.search === "preferred") {
3905
- errors.push({
3906
- message: "OpenCode search has no preferred tier: the websearch provider is host-level config, so the model never " + "chooses between engines. Use --search optional (provider registered, built-in stays default), " + "--search forced (replace the engine), or --search off."
3907
- });
3908
- }
3909
- const plugins = Array.isArray(loaded.value.plugins) ? loaded.value.plugins : [];
3910
- const trackedPackages = new Set(appendedByPrevious(previous, ["plugins"]).filter((entry) => isPlainObject(entry) && typeof entry.package === "string").map((entry) => entry.package));
3911
- const pluginPackages = plugins.filter((entry) => isPlainObject(entry) && typeof entry.package === "string");
3912
- const excused = previous === undefined ? new Set : new Set([...trackedPackages, input.packageRef]);
3913
- const foreignOwn = pluginPackages.filter((entry) => looksLikeOwnPackage(entry.package) && !excused.has(entry.package));
3914
- if (foreignOwn.length > 0) {
3915
- errors.push({
3916
- message: `${paths.config} already has a plugins entry referencing deepseek-web-retrieval that this installer did not ` + "write. Remove it (or run uninstall if it came from a previous init), then retry."
3917
- });
3918
- }
3919
- if (previous !== undefined && pluginPackages.some((entry) => excused.has(entry.package))) {
3920
- notes.push("A previous init wrote the plugins entry; re-applying keeps it the only entry (a changed package ref or tier " + "options replace it, an unchanged one is a no-op) and the original snapshots carry over.");
3921
- }
3922
- if (errors.length > 0) {
3923
- return { host: "opencode", scope: input.scope, tiers, edits, notes, errors };
3924
- }
3925
- const options = {};
3926
- if (input.search === "forced")
3927
- options.setDefaultWebsearch = true;
3928
- if (input.search === "off")
3929
- options.searchEnabled = false;
3930
- if (input.fetch === "forced")
3931
- options.fetchOverrideWebfetch = true;
3932
- if (input.fetch === "off")
3933
- options.fetchEnabled = false;
3934
- const ops = [
3935
- {
3936
- op: "append-array",
3937
- path: ["plugins"],
3938
- entries: [{ package: input.packageRef, options }],
3939
- existingCount: plugins.length
4290
+ // src/core/transport.ts
4291
+ async function postJson(endpoint, body, operation2, opts) {
4292
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
4293
+ const attempts = opts.retry.maxRetries + 1;
4294
+ let lastError;
4295
+ for (let attempt = 0;attempt < attempts; attempt++) {
4296
+ try {
4297
+ return await requestOnce(endpoint, body, operation2, opts, fetchImpl);
4298
+ } catch (error) {
4299
+ lastError = error;
4300
+ if (!(error instanceof DeepSeekApiError) || !error.retryable || attempt === attempts - 1) {
4301
+ throw error;
4302
+ }
4303
+ await sleep(retryDelay(error.retryAfterMs, opts.retry.baseDelayMs, attempt), opts.signal);
3940
4304
  }
3941
- ];
3942
- const permissions = [];
3943
- if (input.search !== "off")
3944
- permissions.push({ action: "websearch", resource: "*", effect: "allow" });
3945
- if (input.fetch !== "off")
3946
- permissions.push({ action: "deepseek_fetch", resource: "*", effect: "allow" });
3947
- if (input.fetch === "forced")
3948
- permissions.push({ action: "webfetch", resource: "*", effect: "allow" });
3949
- const existingPermissions = Array.isArray(loaded.value.permissions) ? loaded.value.permissions.length : 0;
3950
- if (permissions.length > 0) {
3951
- ops.push({ op: "append-array", path: ["permissions"], entries: permissions, existingCount: existingPermissions });
3952
- }
3953
- if (input.search === "forced") {
3954
- const currentProvider = isPlainObject(loaded.value.websearch) ? loaded.value.websearch.provider : undefined;
3955
- ops.push({ op: "set", path: ["websearch", "provider"], value: "deepseek", previous: currentProvider });
3956
- notes.push(currentProvider === undefined ? "websearch.provider is being set to deepseek (no previous value existed)." : `websearch.provider is being set to deepseek; the previous value "${String(currentProvider)}" is snapshotted for uninstall.`);
3957
- }
3958
- edits.push({ file: paths.config, format: "json", ops });
3959
- notes.push("The plugin entry uses the object form so options are honored; auto-discovered plugins cannot receive options.");
3960
- if (input.search === "optional") {
3961
- notes.push("Search tier optional: the deepseek provider is registered but the built-in provider stays the default engine; " + "set websearch.provider to deepseek (or rerun with --search forced) to route search through DeepSeek.");
3962
- }
3963
- if (input.search === "forced" || input.fetch === "forced") {
3964
- notes.push(`Forced tier replaces built-in routing. ${FORCED_COST_NOTE}`);
3965
- }
3966
- if (input.fetch === "preferred") {
3967
- edits.push({
3968
- file: paths.rules,
3969
- format: "rules",
3970
- block: buildRulesBlock(input.host, rulesLines(OPENCODE_TOOL_IDS, input.search, input.fetch))
3971
- });
3972
- notes.push(`Rules block upserted in ${paths.rules}; OpenCode loads AGENTS.md only (no CLAUDE.md fallback in v2).`);
3973
4305
  }
3974
- return { host: "opencode", scope: input.scope, tiers, edits, notes, errors };
3975
- }
3976
- var OPENCODE_TOOL_IDS;
3977
- var init_opencode = __esm(() => {
3978
- init_detect();
3979
- init_formats();
3980
- init_rules();
3981
- init_value();
3982
- init_paths();
3983
- init_rulesContent();
3984
- init_state();
3985
- init_shared();
3986
- OPENCODE_TOOL_IDS = { search: "websearch (provider deepseek)", fetch: "deepseek_fetch" };
3987
- });
3988
-
3989
- // src/pi/settings.ts
3990
- var SETTINGS_NAMESPACE = "deepseekWebRetrieval";
3991
- var init_settings = () => {};
3992
-
3993
- // src/installer/hosts/pi.ts
3994
- function piPaths(input) {
3995
- const mcp = input.scope === "global" ? join2(input.home, ".pi/agent/mcp.json") : join2(input.cwd, ".pi/mcp.json");
3996
- const settings = input.scope === "global" ? join2(input.home, ".pi/agent/settings.json") : join2(input.cwd, ".pi/settings.json");
3997
- const rules = input.scope === "global" ? join2(input.home, ".pi/agent/AGENTS.md") : join2(input.cwd, "AGENTS.md");
3998
- return { config: input.path === "mcp" ? mcp : settings, rules };
3999
- }
4000
- function piSourceRef(packageRef) {
4001
- return packageRef.startsWith("npm:") ? packageRef : `npm:${packageRef}`;
4002
- }
4003
- function planPi(input, previous) {
4004
- return input.path === "mcp" ? planPiMcp(input) : planPiExtension(input, previous);
4306
+ throw lastError;
4005
4307
  }
4006
- function planPiExtension(input, previous) {
4007
- const paths = piPaths(input);
4008
- const loaded = codecFor("json", input.host).load(paths.config);
4009
- const tiers = { search: input.search, fetch: input.fetch };
4010
- const header = planHeader(input, paths, loaded, "JSON");
4011
- if (header.abort) {
4012
- return { host: "pi", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
4013
- }
4014
- const notes = [...header.notes];
4015
- const errors = [...header.errors];
4016
- const edits = [];
4017
- const packages = Array.isArray(loaded.value.packages) ? loaded.value.packages : [];
4018
- const source = piSourceRef(input.packageRef);
4019
- const trackedSources = appendedByPrevious(previous, ["packages"]).filter((entry) => typeof entry === "string");
4020
- const excused = previous === undefined ? new Set : new Set([...trackedSources, source]);
4021
- const sources = packages.filter((entry) => typeof entry === "string");
4022
- const foreignOwn = sources.filter((entry) => looksLikeOwnPackage(entry) && !excused.has(entry));
4023
- if (foreignOwn.length > 0) {
4024
- errors.push({
4025
- message: `${paths.config} already lists ${foreignOwn.join(", ")} — this package (or a fork of it) that this installer did not ` + "write. Remove it (pi remove <source>, or uninstall if it came from a previous init), then retry."
4026
- });
4027
- }
4028
- if (previous !== undefined && sources.some((entry) => excused.has(entry))) {
4029
- notes.push("A previous init wrote the packages entry; re-applying reuses it (an unchanged source deduplicates, a changed " + "--package ref replaces the old source) and the original snapshots carry over.");
4030
- }
4031
- const forced = input.search === "forced" || input.fetch === "forced";
4032
- if (forced) {
4033
- const ownSources = new Set([...trackedSources, source]);
4034
- const unexcludable = [...collectSources(loaded.value.packages), ...collectSources(loaded.value.extensions)].filter((entry) => !ownSources.has(entry) && looksWebCapable(entry, undefined));
4035
- if (unexcludable.length > 0) {
4036
- errors.push({
4037
- message: `Forced cannot deliver exclusive routing: settings sources ${unexcludable.join(", ")} look web-capable, ` + "and Pi offers no per-package kill switch. Remove them (pi remove <source>) or choose a lower tier."
4308
+ async function requestOnce(endpoint, body, operation2, opts, fetchImpl) {
4309
+ return fetchWithTimeout(endpoint, {
4310
+ method: "POST",
4311
+ headers: {
4312
+ Authorization: `Bearer ${opts.auth.apiKey}`,
4313
+ "Content-Type": "application/json"
4314
+ },
4315
+ body: JSON.stringify(body)
4316
+ }, opts.signal, opts.timeoutMs, operation2, fetchImpl, async (response) => {
4317
+ if (!response.ok) {
4318
+ const text2 = await readBoundedText(response, MAX_ERROR_BODY_CHARS);
4319
+ throw new DeepSeekApiError({
4320
+ operation: operation2,
4321
+ status: response.status,
4322
+ body: text2,
4323
+ retryAfterMs: parseRetryAfter(response.headers.get("retry-after"))
4038
4324
  });
4039
4325
  }
4326
+ const text = await readResponseText(response, MAX_RESPONSE_BYTES, operation2);
4327
+ if (!text.trim())
4328
+ throw new Error(`${operation2} returned an empty response body`);
4329
+ try {
4330
+ return JSON.parse(text);
4331
+ } catch {
4332
+ throw new Error(`${operation2} returned invalid JSON: ${truncate(redactSecrets(text), 500)}`);
4333
+ }
4334
+ });
4335
+ }
4336
+ async function fetchWithTimeout(endpoint, init, signal, timeoutMs, operation2, fetchImpl, handleResponse) {
4337
+ const controller = new AbortController;
4338
+ let timedOut = false;
4339
+ const forwardAbort = () => controller.abort(signal.reason);
4340
+ if (signal.aborted)
4341
+ forwardAbort();
4342
+ else
4343
+ signal.addEventListener("abort", forwardAbort, { once: true });
4344
+ const timer = signal.aborted ? undefined : setTimeout(() => {
4345
+ timedOut = true;
4346
+ controller.abort(new Error("timeout"));
4347
+ }, timeoutMs);
4348
+ try {
4349
+ const response = await fetchImpl(endpoint, { ...init, signal: controller.signal });
4350
+ return await handleResponse(response);
4351
+ } catch (error) {
4352
+ if (timedOut)
4353
+ throw new Error(formatTimeoutError(operation2, timeoutMs));
4354
+ if (signal.aborted)
4355
+ throw abortReason(signal, operation2);
4356
+ throw error;
4357
+ } finally {
4358
+ if (timer !== undefined)
4359
+ clearTimeout(timer);
4360
+ signal.removeEventListener("abort", forwardAbort);
4040
4361
  }
4041
- if (errors.length > 0) {
4042
- return { host: "pi", scope: input.scope, tiers, edits: [], notes, errors };
4043
- }
4044
- const ops = [
4045
- { op: "append-array", path: ["packages"], entries: [source], existingCount: packages.length }
4046
- ];
4047
- const namespace = isPlainObject(loaded.value[SETTINGS_NAMESPACE]) ? loaded.value[SETTINGS_NAMESPACE] : {};
4048
- if (input.search === "off") {
4049
- ops.push({
4050
- op: "set",
4051
- path: [SETTINGS_NAMESPACE, "enableSearch"],
4052
- value: false,
4053
- previous: typeof namespace.enableSearch === "boolean" ? namespace.enableSearch : undefined
4054
- });
4055
- }
4056
- if (input.fetch === "off") {
4057
- ops.push({
4058
- op: "set",
4059
- path: [SETTINGS_NAMESPACE, "enableFetch"],
4060
- value: false,
4061
- previous: typeof namespace.enableFetch === "boolean" ? namespace.enableFetch : undefined
4062
- });
4063
- }
4064
- edits.push({ file: paths.config, format: "json", ops });
4065
- notes.push("Pi resolves the packages source at session start; the first launch after apply fetches the package from npm " + "(pi update --extensions refreshes it later).");
4066
- notes.push(`The extension reads ${API_KEY_ENV} from the Pi process environment; no env forwarding is needed. ` + "Set it in the shell that launches Pi.");
4067
- if (input.search === "off" || input.fetch === "off") {
4068
- notes.push(`Off capability switches are written into the "${SETTINGS_NAMESPACE}" settings namespace; the extension ` + "reads them at load (they outrank the DEEPSEEK_ENABLE_* environment variables).");
4069
- }
4070
- notes.push(`Extension tools are declared to the model with exposure "direct" by Pi's own default; no exposure key is needed.`);
4071
- if (forced) {
4072
- edits.push(...planMcpCompetitorDisables(input, notes, errors));
4073
- }
4074
- if (errors.length > 0) {
4075
- return { host: "pi", scope: input.scope, tiers, edits: [], notes, errors };
4076
- }
4077
- if (input.search === "preferred" || input.fetch === "preferred") {
4078
- edits.push({
4079
- file: paths.rules,
4080
- format: "rules",
4081
- block: buildRulesBlock(input.host, rulesLines(RAW_MCP_TOOL_IDS, input.search, input.fetch))
4082
- });
4083
- notes.push(`Rules block upserted in ${paths.rules}; Pi loads AGENTS.md context files from the working directory and its parents.`);
4084
- }
4085
- if (forced) {
4086
- notes.push("Forced tier: Pi 1.3.0 ships no built-in web tool, so the registered tools are the only web path (de-facto). " + FORCED_COST_NOTE);
4362
+ }
4363
+ function parseRetryAfter(value) {
4364
+ if (!value)
4365
+ return;
4366
+ const trimmed = value.trim();
4367
+ if (!trimmed)
4368
+ return;
4369
+ if (/^\d+$/.test(trimmed)) {
4370
+ return Math.min(MAX_RETRY_DELAY_MS, Number(trimmed) * 1000);
4087
4371
  }
4088
- return { host: "pi", scope: input.scope, tiers, edits, notes, errors };
4372
+ const timestamp = Date.parse(trimmed);
4373
+ if (!Number.isFinite(timestamp))
4374
+ return;
4375
+ return Math.min(MAX_RETRY_DELAY_MS, Math.max(0, timestamp - Date.now()));
4089
4376
  }
4090
- function planCompetitorDisables(servers, competitors, notes, errors) {
4091
- const ops = [];
4092
- const excluded = [];
4093
- const unexcludable = [];
4094
- for (const name of competitors) {
4095
- const current = servers[name];
4096
- if (!isPlainObject(current)) {
4097
- unexcludable.push(name);
4098
- continue;
4377
+ function retryDelay(retryAfterMs, baseDelayMs, attempt) {
4378
+ if (retryAfterMs !== undefined)
4379
+ return retryAfterMs;
4380
+ return Math.min(MAX_RETRY_DELAY_MS, baseDelayMs * 2 ** attempt);
4381
+ }
4382
+ function sleep(ms, signal) {
4383
+ if (ms <= 0)
4384
+ return Promise.resolve();
4385
+ return new Promise((resolve2, reject) => {
4386
+ const timer = setTimeout(() => {
4387
+ signal.removeEventListener("abort", onAbort);
4388
+ resolve2();
4389
+ }, ms);
4390
+ const onAbort = () => {
4391
+ clearTimeout(timer);
4392
+ reject(abortReason(signal, "DeepSeek request"));
4393
+ };
4394
+ if (signal.aborted) {
4395
+ clearTimeout(timer);
4396
+ reject(abortReason(signal, "DeepSeek request"));
4397
+ return;
4099
4398
  }
4100
- const previous = typeof current.enabled === "boolean" ? current.enabled : undefined;
4101
- ops.push({ op: "set", path: ["mcpServers", name, "enabled"], value: false, previous });
4102
- excluded.push(name);
4103
- }
4104
- if (excluded.length > 0) {
4105
- notes.push(`Forced tier: web-capable MCP servers are disabled so DeepSeek routing is exclusive (${excluded.join(", ")}; ` + "prior enabled values are snapshotted for uninstall).");
4106
- }
4107
- if (unexcludable.length > 0) {
4108
- errors.push({
4109
- message: `Forced cannot deliver exclusive routing: mcpServers entries ${unexcludable.join(", ")} look web-capable ` + "but are not objects, so the plan cannot set their enabled key. Fix or remove them, or choose a lower tier."
4399
+ signal.addEventListener("abort", onAbort, { once: true });
4400
+ });
4401
+ }
4402
+ function abortReason(signal, operation2) {
4403
+ return signal.reason instanceof Error ? signal.reason : new Error(`${operation2} request aborted`);
4404
+ }
4405
+ async function readBoundedText(response, maxChars) {
4406
+ if (!response.body)
4407
+ return truncate(await response.text(), maxChars + 1);
4408
+ const reader = response.body.getReader();
4409
+ const decoder = new TextDecoder;
4410
+ const limit = maxChars + 1;
4411
+ let text = "";
4412
+ let chars = 0;
4413
+ try {
4414
+ while (chars < limit) {
4415
+ const { done, value } = await reader.read();
4416
+ if (done)
4417
+ break;
4418
+ const chunk = decoder.decode(value, { stream: true });
4419
+ text += chunk;
4420
+ chars += Array.from(chunk).length;
4421
+ }
4422
+ text += decoder.decode();
4423
+ } finally {
4424
+ await reader.cancel().catch(() => {
4425
+ return;
4110
4426
  });
4427
+ reader.releaseLock();
4111
4428
  }
4112
- return ops;
4429
+ return truncate(text, limit);
4113
4430
  }
4114
- function planMcpCompetitorDisables(input, notes, errors) {
4115
- const mcpFile = input.scope === "global" ? join2(input.home, ".pi/agent/mcp.json") : join2(input.cwd, ".pi/mcp.json");
4116
- const loaded = codecFor("json", input.host).load(mcpFile);
4117
- if (loaded.parseError) {
4118
- errors.push({ message: `${mcpFile} does not parse: ${loaded.parseError}` });
4119
- return [];
4431
+ async function readResponseText(response, maxBytes, operation2) {
4432
+ if (!response.body) {
4433
+ const text2 = await response.text();
4434
+ if (new TextEncoder().encode(text2).byteLength > maxBytes) {
4435
+ throw new Error(`${operation2} response exceeded ${maxBytes} bytes`);
4436
+ }
4437
+ return text2;
4120
4438
  }
4121
- const servers = isPlainObject(loaded.value.mcpServers) ? loaded.value.mcpServers : undefined;
4122
- if (!isPlainObject(servers))
4123
- return [];
4124
- const { competitors, bystanders } = splitCompetitors(servers);
4125
- const edits = [];
4126
- if (competitors.length > 0) {
4127
- const ops = planCompetitorDisables(servers, competitors, notes, errors);
4128
- if (ops.length > 0)
4129
- edits.push({ file: mcpFile, format: "json", ops });
4439
+ const reader = response.body.getReader();
4440
+ const decoder = new TextDecoder;
4441
+ let text = "";
4442
+ let bytes = 0;
4443
+ try {
4444
+ while (true) {
4445
+ const { done, value } = await reader.read();
4446
+ if (done)
4447
+ break;
4448
+ bytes += value.byteLength;
4449
+ if (bytes > maxBytes) {
4450
+ throw new Error(`${operation2} response exceeded ${maxBytes} bytes`);
4451
+ }
4452
+ text += decoder.decode(value, { stream: true });
4453
+ }
4454
+ text += decoder.decode();
4455
+ } finally {
4456
+ await reader.cancel().catch(() => {
4457
+ return;
4458
+ });
4459
+ reader.releaseLock();
4130
4460
  }
4131
- if (bystanders.length > 0)
4132
- notes.push(othersStayRegisteredNote(bystanders));
4133
- return edits;
4461
+ return text;
4134
4462
  }
4135
- function planPiMcp(input) {
4136
- const paths = piPaths(input);
4137
- const loaded = codecFor("json", input.host).load(paths.config);
4138
- const tiers = { search: input.search, fetch: input.fetch };
4139
- const header = planHeader(input, paths, loaded, "JSON");
4140
- if (header.abort) {
4141
- return { host: "pi", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
4142
- }
4143
- const notes = [...header.notes];
4144
- const errors = [...header.errors];
4145
- const edits = [];
4146
- const env = { [API_KEY_ENV]: `\${${API_KEY_ENV}}` };
4147
- if (input.search === "off")
4148
- env[ENABLE_SEARCH_ENV] = "false";
4149
- if (input.fetch === "off")
4150
- env[ENABLE_FETCH_ENV] = "false";
4151
- const entry = {
4152
- command: "npx",
4153
- args: ["-y", input.packageRef],
4154
- env,
4155
- exposure: "direct",
4156
- enabled: true
4157
- };
4158
- const servers = loaded.value.mcpServers;
4159
- const existingEntry = isPlainObject(servers) ? servers.deepseek : undefined;
4160
- const ops = [{ op: "set", path: ["mcpServers", "deepseek"], value: entry, previous: existingEntry }];
4161
- edits.push({ file: paths.config, format: "json", ops });
4162
- if (isPlainObject(servers)) {
4163
- if (servers.deepseek !== undefined)
4164
- notes.push(replacingExistingEntryNote("mcpServers.deepseek"));
4165
- const { competitors, bystanders } = splitCompetitors(servers);
4166
- const forced = input.search === "forced" || input.fetch === "forced";
4167
- if (forced) {
4168
- ops.push(...planCompetitorDisables(servers, competitors, notes, errors));
4463
+ var DeepSeekApiError;
4464
+ var init_transport = __esm(() => {
4465
+ init_constants();
4466
+ init_format2();
4467
+ DeepSeekApiError = class DeepSeekApiError extends Error {
4468
+ operation;
4469
+ status;
4470
+ body;
4471
+ retryable;
4472
+ retryAfterMs;
4473
+ constructor(input) {
4474
+ const body = redactSecrets(input.body);
4475
+ super(formatApiError(input.operation, input.status, body));
4476
+ this.name = "DeepSeekApiError";
4477
+ this.operation = input.operation;
4478
+ this.status = input.status;
4479
+ this.body = body;
4480
+ this.retryable = input.status === 408 || input.status === 425 || input.status === 429 || input.status >= 500 && input.status <= 599;
4481
+ this.retryAfterMs = input.retryAfterMs;
4169
4482
  }
4170
- const stayRegistered = forced ? bystanders : [...competitors, ...bystanders];
4171
- if (stayRegistered.length > 0)
4172
- notes.push(othersStayRegisteredNote(stayRegistered));
4483
+ };
4484
+ });
4485
+
4486
+ // src/core/client.ts
4487
+ function effectiveTimeout(configuredMs, perCallMs) {
4488
+ return perCallMs === undefined ? configuredMs : Math.min(configuredMs, perCallMs);
4489
+ }
4490
+ function oriQuestionValue(oriQuestion) {
4491
+ const trimmed = oriQuestion?.trim();
4492
+ return trimmed ? truncate(trimmed, MAX_ORI_QUESTION_CHARS) : undefined;
4493
+ }
4494
+ async function searchWeb(query, options, request) {
4495
+ const trimmed = query.trim();
4496
+ if (!trimmed)
4497
+ throw new Error("DeepSeek search query must not be empty");
4498
+ if (Array.from(trimmed).length > MAX_QUERY_CHARS) {
4499
+ throw new Error(`DeepSeek search query must be ${MAX_QUERY_CHARS} characters or fewer`);
4173
4500
  }
4174
- notes.push('"exposure": "direct" is required: Pi 1.3.0 defaults MCP tools to codemode, which hides them from the model.');
4175
- notes.push(`\`${API_KEY_ENV}\` is written as "\${${API_KEY_ENV}}" so the key expands from the shell that launches Pi and stays out of the file.`);
4176
- if (input.search === "preferred" || input.fetch === "preferred") {
4177
- edits.push({
4178
- file: paths.rules,
4179
- format: "rules",
4180
- block: buildRulesBlock(input.host, rulesLines(MCP_TOOL_IDS, input.search, input.fetch))
4181
- });
4182
- notes.push(`Rules block upserted in ${paths.rules}; Pi loads AGENTS.md context files from the working directory and its parents.`);
4501
+ const builtQuery = buildQuery(trimmed, options);
4502
+ const builtQueryLength = Array.from(builtQuery).length;
4503
+ if (builtQueryLength > MAX_QUERY_CHARS) {
4504
+ throw new Error(`DeepSeek search query must be ${MAX_QUERY_CHARS} characters or fewer after applying ` + `blockedDomains, includeDomains, and language ` + `(built query is ${builtQueryLength} characters)`);
4183
4505
  }
4184
- if (input.search === "forced" || input.fetch === "forced") {
4185
- notes.push("Forced tier: Pi 1.3.0 ships no built-in web tool, so the registered tools are the only web path (de-facto). " + FORCED_COST_NOTE);
4506
+ const timeout = effectiveTimeout(options.timeoutMs, request.timeoutMs);
4507
+ const oriQuestion = oriQuestionValue(request.oriQuestion);
4508
+ const payload = await postJson(SEARCH_ENDPOINT, {
4509
+ query: builtQuery,
4510
+ count: options.count,
4511
+ need_content: false,
4512
+ ...oriQuestion === undefined ? {} : { ori_question: oriQuestion },
4513
+ ...options.localization === undefined ? {} : { localization: options.localization }
4514
+ }, "DeepSeek Search", { ...request, timeoutMs: timeout });
4515
+ if (!Array.isArray(payload.results)) {
4516
+ throw new Error("DeepSeek Search returned a response without a results array");
4186
4517
  }
4187
- return { host: "pi", scope: input.scope, tiers, edits, notes, errors };
4518
+ return processResults(payload.results, options);
4188
4519
  }
4189
- function collectSources(value) {
4190
- return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
4520
+ async function fetchPage(url, options, request) {
4521
+ const target = parseFetchUrl(url.href);
4522
+ assertFetchHostPolicy(target, options);
4523
+ const timeout = effectiveTimeout(options.timeoutMs, request.timeoutMs);
4524
+ const payload = await postJson(FETCH_ENDPOINT, { url: target.href }, "DeepSeek Fetch", {
4525
+ ...request,
4526
+ timeoutMs: timeout
4527
+ });
4528
+ const title = typeof payload.title === "string" ? payload.title.trim() : "";
4529
+ const content = typeof payload.content === "string" ? payload.content : "";
4530
+ if (!content.trim()) {
4531
+ throw new Error("DeepSeek Fetch returned no page content (the page may be empty or unavailable)");
4532
+ }
4533
+ return { url: target.href, title, content };
4191
4534
  }
4192
- var init_pi = __esm(() => {
4535
+ async function fetchDocument(url, options, request) {
4536
+ if (typeof url !== "string" && !(url instanceof URL))
4537
+ throw new Error('"url" must be a string or URL');
4538
+ const page = await fetchPage(url instanceof URL ? url : parseFetchUrl(url), options, request);
4539
+ const formatted = formatFetchedContent(page.title, page.content, options.maxChars);
4540
+ return {
4541
+ url: page.url,
4542
+ title: page.title,
4543
+ content: formatted.content,
4544
+ truncated: formatted.truncated
4545
+ };
4546
+ }
4547
+ function createRetrievalClient(dependencies = {}) {
4548
+ const bind = (request) => ({ ...request, ...dependencies });
4549
+ return {
4550
+ searchWeb: (query, options, request) => searchWeb(query, options, bind(request)),
4551
+ fetchPage: (url, options, request) => fetchPage(url, options, bind(request)),
4552
+ fetchDocument: (url, options, request) => fetchDocument(url, options, bind(request))
4553
+ };
4554
+ }
4555
+ var retrievalClient;
4556
+ var init_client = __esm(() => {
4193
4557
  init_constants();
4194
- init_settings();
4195
- init_detect();
4196
- init_formats();
4197
- init_rules();
4198
- init_value();
4199
- init_paths();
4200
- init_rulesContent();
4201
- init_state();
4202
- init_shared();
4558
+ init_domains();
4559
+ init_format2();
4560
+ init_search();
4561
+ init_transport();
4562
+ init_url();
4563
+ init_transport();
4564
+ retrievalClient = createRetrievalClient();
4203
4565
  });
4204
4566
 
4205
- // src/installer/hosts/index.ts
4206
- function planForHost(host, input) {
4207
- try {
4208
- const previous = readRecord(input);
4209
- const planned = withCrossScopeGuard(HOST_PLANNERS[host](input, previous), input);
4210
- return {
4211
- ...withSecretGuard(withOrphanReverts(withLegacySharedConfigGuard(planned, previous), previous)),
4212
- previousRecord: previous
4213
- };
4214
- } catch (error) {
4215
- if (!(error instanceof InstallRecordError))
4216
- throw error;
4217
- return {
4218
- host,
4219
- scope: input.scope,
4220
- tiers: { search: input.search, fetch: input.fetch },
4221
- edits: [],
4222
- notes: [],
4223
- errors: [{ message: error.message }]
4224
- };
4567
+ // src/core/env.ts
4568
+ function resolveEnvOptions(env = process.env, fileOptions) {
4569
+ return resolvePluginOptions({ ...fileOptions, ...pluginOptionsFromEnv(env) });
4570
+ }
4571
+ function envOptionsReport(env = process.env) {
4572
+ const options = {};
4573
+ const warnings = [];
4574
+ putNumber(options, "count", env, warnings);
4575
+ putNumber(options, "maxResults", env, warnings);
4576
+ putNumber(options, "minRerank", env, warnings);
4577
+ putNumber(options, "minAuthority", env, warnings);
4578
+ putFalseOnly(options, "allowUnknownAuthority", env, warnings);
4579
+ putDomains(options, "blockedDomains", env, warnings);
4580
+ putDomains(options, "includeDomains", env, warnings);
4581
+ putText(options, "language", env);
4582
+ putText(options, "searchLocalization", env);
4583
+ putNumber(options, "maxSummaryChars", env, warnings);
4584
+ putNumber(options, "searchTimeoutMs", env, warnings);
4585
+ putNumber(options, "fetchMaxChars", env, warnings);
4586
+ putDomains(options, "fetchAllowedDomains", env, warnings);
4587
+ putDomains(options, "fetchBlockedDomains", env, warnings);
4588
+ putNumber(options, "fetchTimeoutMs", env, warnings);
4589
+ putFalseOnly(options, "fetchBlockPrivateHosts", env, warnings);
4590
+ putFalseOnly(options, "searchEnabled", env, warnings);
4591
+ putFalseOnly(options, "fetchEnabled", env, warnings);
4592
+ putNumber(options, "maxRetries", env, warnings);
4593
+ putNumber(options, "retryBaseDelayMs", env, warnings);
4594
+ const known = new Set(OPTION_ENV_VARS);
4595
+ for (const key of Object.keys(env)) {
4596
+ if (!key.startsWith("DEEPSEEK_") || key === API_KEY_ENV || known.has(key))
4597
+ continue;
4598
+ if (!(env[key] ?? "").trim())
4599
+ continue;
4600
+ warnings.push(`unknown DEEPSEEK_* variable ${key} — ignored`);
4225
4601
  }
4602
+ return { options, warnings };
4226
4603
  }
4227
- function withCrossScopeGuard(plan, input) {
4228
- if (plan.errors.length > 0)
4229
- return plan;
4230
- try {
4231
- assertFileOwnership(input, plan.edits);
4232
- } catch (error) {
4233
- return { ...plan, edits: [], reverts: undefined, errors: [{ message: String(error) }] };
4604
+ function pluginOptionsFromEnv(env) {
4605
+ return envOptionsReport(env).options;
4606
+ }
4607
+ function putNumber(target, key, env, warnings) {
4608
+ const value = env[NUMBER_ENV[key]];
4609
+ if (value === undefined)
4610
+ return;
4611
+ const trimmed = value.trim();
4612
+ if (!trimmed)
4613
+ return;
4614
+ const parsed = Number(trimmed);
4615
+ if (Number.isFinite(parsed))
4616
+ target[key] = parsed;
4617
+ else
4618
+ warnings.push(`${NUMBER_ENV[key]} is not a number ("${trimmed}") — ignored`);
4619
+ }
4620
+ function putText(target, key, env) {
4621
+ const value = env[TEXT_ENV[key]];
4622
+ if (value === undefined)
4623
+ return;
4624
+ const trimmed = value.trim();
4625
+ if (trimmed)
4626
+ target[key] = trimmed;
4627
+ }
4628
+ function putFalseOnly(target, key, env, warnings) {
4629
+ const name = FALSE_ONLY_ENV[key];
4630
+ const value = env[name];
4631
+ if (value === undefined || !value.trim())
4632
+ return;
4633
+ if (isFalseValue(value)) {
4634
+ target[key] = false;
4635
+ return;
4234
4636
  }
4235
- const other = input.scope === "global" ? "project" : "global";
4236
- const overlap = claimedByOtherScope(input, plan.edits.map((edit2) => edit2.file));
4237
- if (overlap.length === 0)
4238
- return { ...plan, notes: [...plan.notes, ...fileOwnershipNotes(input, plan.edits)] };
4239
- return {
4240
- ...plan,
4241
- edits: [],
4242
- reverts: undefined,
4243
- errors: [
4244
- {
4245
- message: `A ${plan.host} install is already recorded at the ${other} scope and claims the same file(s): ${overlap.join(", ")}. ` + `Uninstall it first (deepseek-web-retrieval uninstall --host ${plan.host} --scope ${other}), ` + `or re-run with --scope ${other} to update it in place — two scopes must not edit one file.`
4246
- }
4247
- ]
4248
- };
4637
+ warnings.push(`${name}="${value.trim()}" changes nothing — only false/0/no/off turns the switch off`);
4249
4638
  }
4250
- function withLegacySharedConfigGuard(plan, previous) {
4251
- if (plan.errors.length > 0 || previous !== undefined)
4252
- return plan;
4253
- for (const edit2 of plan.edits) {
4254
- if (edit2.format === "rules" || !edit2.shared)
4255
- continue;
4256
- for (const op of edit2.ops) {
4257
- const old = op.previous;
4258
- if (op.op !== "set" || !isPlainObject(old) || old.command !== "npx" || !Array.isArray(old.args) || old.args[0] !== "-y" || !Array.isArray(old.env_vars) || !old.env_vars.includes(API_KEY_ENV))
4259
- continue;
4260
- return {
4261
- ...plan,
4262
- edits: [],
4263
- reverts: undefined,
4264
- errors: [
4265
- {
4266
- message: `${edit2.file} contains an installer-style registration without an install record for this location. ` + "It may belong to an older install in another project. Re-run init or uninstall from that original project and scope first; " + "if the registration was created manually, remove it before retrying. No existing registration was adopted."
4267
- }
4268
- ]
4269
- };
4639
+ function putDomains(target, key, env, warnings) {
4640
+ const name = DOMAINS_ENV[key];
4641
+ const value = env[name];
4642
+ if (value === undefined || !value.trim())
4643
+ return;
4644
+ const domains = value.split(",").map((domain) => domain.trim()).filter((domain) => domain.length > 0);
4645
+ for (const domain of domains) {
4646
+ if (normalizeDomain(domain) === undefined) {
4647
+ warnings.push(`${name} entry "${domain}" is not a domain — ignored`);
4270
4648
  }
4271
4649
  }
4272
- return plan;
4650
+ if (domains.length > 0)
4651
+ target[key] = domains;
4652
+ else
4653
+ warnings.push(`${name} contains no domains — ignored`);
4273
4654
  }
4274
- function withSecretGuard(plan) {
4275
- for (const edit2 of plan.edits) {
4276
- if (edit2.format === "rules")
4277
- continue;
4278
- for (const op of edit2.ops) {
4279
- if (op.op !== "set" || op.previous === undefined)
4280
- continue;
4281
- const offender = findSecretLike(op.previous, op.path.join("."));
4282
- if (offender !== undefined) {
4283
- return {
4284
- ...plan,
4285
- edits: [],
4286
- reverts: undefined,
4287
- errors: [
4288
- {
4289
- message: `${edit2.file}: the existing value at ${op.path.join(".")} contains a credential-looking key ` + `(${offender}). The installer refuses to snapshot secrets into its state file. Move the key to ` + `environment indirection ("\${${API_KEY_ENV}}" expansion or env_vars) and re-run.`
4290
- }
4291
- ]
4292
- };
4293
- }
4294
- }
4295
- }
4296
- return plan;
4297
- }
4298
- function findSecretLike(value, at) {
4299
- if (typeof value !== "object" || value === null)
4300
- return;
4301
- for (const [key, child] of Object.entries(value)) {
4302
- const path = `${at}.${key}`;
4303
- if (/(api[_-]?key|token|secret|password|credential)/i.test(key) && typeof child === "string" && child.length > 0 && !/^\$\{[^}]+\}$/.test(child)) {
4304
- return path;
4305
- }
4306
- const nested = findSecretLike(child, path);
4307
- if (nested !== undefined)
4308
- return nested;
4309
- }
4310
- return;
4311
- }
4312
- function withOrphanReverts(plan, previous) {
4313
- if (plan.errors.length > 0)
4314
- return plan;
4315
- if (previous === undefined)
4316
- return plan;
4317
- const reverts = [];
4318
- for (const file of previous.files) {
4319
- const edit2 = plan.edits.find((candidate) => candidate.file === file.file);
4320
- if (edit2 === undefined) {
4321
- reverts.push(file);
4322
- continue;
4323
- }
4324
- if (edit2.format === "rules" || file.format === "rules")
4325
- continue;
4326
- const orphanOps = file.ops.flatMap((op) => {
4327
- const claimed = edit2.ops.find((candidate) => candidate.op === op.op && candidate.path.join("\x00") === op.path.join("\x00"));
4328
- if (op.op !== "append-array" || claimed === undefined || claimed.op !== "append-array") {
4329
- return claimed === undefined ? [op] : [];
4330
- }
4331
- const dropped = (Array.isArray(op.applied) ? op.applied : []).filter((entry) => !(claimed.entries ?? []).some((wanted) => deepEqual(wanted, entry)));
4332
- return dropped.length > 0 ? [{ ...op, applied: dropped }] : [];
4333
- });
4334
- if (orphanOps.length > 0)
4335
- reverts.push({ ...file, ops: orphanOps });
4336
- }
4337
- if (reverts.length === 0)
4338
- return plan;
4339
- return { ...plan, reverts };
4655
+ function isFalseValue(value) {
4656
+ const trimmed = value?.trim().toLowerCase();
4657
+ return trimmed === "false" || trimmed === "0" || trimmed === "no" || trimmed === "off";
4340
4658
  }
4341
- var HOST_PLANNERS, HOST_VERSION_PROBES;
4342
- var init_hosts = __esm(() => {
4659
+ var NUMBER_ENV, TEXT_ENV, DOMAINS_ENV, FALSE_ONLY_ENV, OPTION_ENV_VARS;
4660
+ var init_env = __esm(() => {
4343
4661
  init_constants();
4344
- init_value();
4345
- init_ownership();
4346
- init_state();
4347
- init_codex();
4348
- init_opencode();
4349
- init_pi();
4350
- HOST_PLANNERS = {
4351
- opencode: planOpenCode,
4352
- pi: planPi,
4353
- codex: planCodex
4662
+ init_domains();
4663
+ init_options();
4664
+ NUMBER_ENV = {
4665
+ count: "DEEPSEEK_SEARCH_COUNT",
4666
+ maxResults: "DEEPSEEK_SEARCH_MAX_RESULTS",
4667
+ minRerank: "DEEPSEEK_SEARCH_MIN_RERANK",
4668
+ minAuthority: "DEEPSEEK_SEARCH_MIN_AUTHORITY",
4669
+ maxSummaryChars: "DEEPSEEK_SEARCH_MAX_SUMMARY_CHARS",
4670
+ searchTimeoutMs: "DEEPSEEK_SEARCH_TIMEOUT_MS",
4671
+ fetchMaxChars: "DEEPSEEK_FETCH_MAX_CHARS",
4672
+ fetchTimeoutMs: "DEEPSEEK_FETCH_TIMEOUT_MS",
4673
+ maxRetries: "DEEPSEEK_MAX_RETRIES",
4674
+ retryBaseDelayMs: "DEEPSEEK_RETRY_BASE_DELAY_MS"
4354
4675
  };
4355
- HOST_VERSION_PROBES = {
4356
- codex: probeCodexVersion
4676
+ TEXT_ENV = {
4677
+ language: "DEEPSEEK_SEARCH_LANGUAGE",
4678
+ searchLocalization: SEARCH_LOCALIZATION_ENV
4679
+ };
4680
+ DOMAINS_ENV = {
4681
+ blockedDomains: "DEEPSEEK_SEARCH_BLOCKED_DOMAINS",
4682
+ includeDomains: "DEEPSEEK_SEARCH_INCLUDE_DOMAINS",
4683
+ fetchAllowedDomains: "DEEPSEEK_FETCH_ALLOWED_DOMAINS",
4684
+ fetchBlockedDomains: "DEEPSEEK_FETCH_BLOCKED_DOMAINS"
4685
+ };
4686
+ FALSE_ONLY_ENV = {
4687
+ allowUnknownAuthority: "DEEPSEEK_SEARCH_ALLOW_UNKNOWN_AUTHORITY",
4688
+ fetchBlockPrivateHosts: "DEEPSEEK_FETCH_BLOCK_PRIVATE_HOSTS",
4689
+ searchEnabled: ENABLE_SEARCH_ENV,
4690
+ fetchEnabled: ENABLE_FETCH_ENV
4357
4691
  };
4692
+ OPTION_ENV_VARS = [
4693
+ ...Object.values(NUMBER_ENV),
4694
+ ...Object.values(TEXT_ENV),
4695
+ ...Object.values(DOMAINS_ENV),
4696
+ ...Object.values(FALSE_ONLY_ENV)
4697
+ ];
4358
4698
  });
4359
4699
 
4360
- // src/installer/render.ts
4361
- function renderPlan(plan) {
4362
- const lines = [];
4363
- lines.push(`Install plan: ${plan.host} (${plan.scope} scope)`);
4364
- lines.push(`Tiers: search=${plan.tiers.search}, fetch=${plan.tiers.fetch}`);
4365
- lines.push("");
4366
- lines.push("Files:");
4367
- for (const edit2 of plan.edits) {
4368
- lines.push(` ${edit2.file}`);
4369
- if (edit2.format === "rules") {
4370
- lines.push(" upsert marked rules block");
4371
- continue;
4372
- }
4373
- for (const op of edit2.ops) {
4374
- if (op.op === "set") {
4375
- const was = op.previous === undefined ? "(absent)" : preview(op.previous);
4376
- lines.push(` set ${op.path.join(".")} = ${preview(op.value)} (was ${was})`);
4377
- } else {
4378
- const count = (op.entries ?? []).length;
4379
- const kept = op.existingCount !== undefined ? ` (${op.existingCount} existing kept)` : "";
4380
- lines.push(` append ${count} entr${count === 1 ? "y" : "ies"} to ${op.path.join(".")}${kept}`);
4381
- for (const entry of op.entries ?? [])
4382
- lines.push(` + ${preview(entry)}`);
4383
- }
4384
- }
4700
+ // src/installer/config-command.ts
4701
+ async function runConfigCommand(query, io, deps = {}) {
4702
+ if (query !== undefined && !query.trim()) {
4703
+ io.err('error: --search requires a query (for example: config --search "deepseek mcp")');
4704
+ return EXIT_USAGE;
4385
4705
  }
4386
- if (plan.reverts && plan.reverts.length > 0) {
4387
- lines.push("");
4388
- lines.push("Reverts (artifacts from the previous init that this plan no longer wants):");
4389
- for (const revert of plan.reverts) {
4390
- lines.push(` ${revert.file}`);
4391
- if (revert.format === "rules") {
4392
- lines.push(" remove rules block");
4393
- continue;
4394
- }
4395
- for (const op of revert.ops) {
4396
- if (op.op === "set") {
4397
- lines.push(op.previous === undefined ? ` remove ${op.path.join(".")} (was not set before this install)` : ` restore ${op.path.join(".")} = ${preview(op.previous)}`);
4398
- } else {
4399
- const count = Array.isArray(op.applied) ? op.applied.length : 0;
4400
- lines.push(` remove ${count} appended entr${count === 1 ? "y" : "ies"} from ${op.path.join(".")}`);
4401
- }
4402
- }
4403
- }
4706
+ const env = deps.env ?? process.env;
4707
+ const file = configFilePath({ env });
4708
+ const report = readFileOptionsReport(file);
4709
+ for (const warning of report.warnings)
4710
+ io.err(`warning: ${warning}`);
4711
+ const envReport = envOptionsReport(env);
4712
+ for (const warning of envReport.warnings)
4713
+ io.err(`warning: ${warning}`);
4714
+ const resolved = resolveEnvOptions(env, report.options);
4715
+ if (query === undefined) {
4716
+ printConfigReport(file, report.exists, report.options, envReport.options, resolved, io);
4717
+ return report.warnings.length > 0 || envReport.warnings.length > 0 ? EXIT_CONFIG_PROBLEMS : 0;
4404
4718
  }
4405
- if (plan.notes.length > 0) {
4406
- lines.push("");
4407
- lines.push("Notes:");
4408
- for (const note of plan.notes)
4409
- lines.push(` - ${note}`);
4719
+ const apiKey = apiKeyFromEnv(env);
4720
+ if (!apiKey) {
4721
+ io.err(MISSING_API_KEY_MESSAGE);
4722
+ return EXIT_CONFIG_PROBLEMS;
4723
+ }
4724
+ const client = deps.client ?? createRetrievalClient();
4725
+ const startedAt = Date.now();
4726
+ try {
4727
+ const results = await client.searchWeb(query, resolved.search, {
4728
+ signal: new AbortController().signal,
4729
+ auth: { apiKey },
4730
+ retry: resolved.retry
4731
+ });
4732
+ const elapsedMs = Date.now() - startedAt;
4733
+ io.out(`search "${query.trim()}" — ${results.length} ${results.length === 1 ? "result" : "results"} in ${elapsedMs} ms`);
4734
+ io.out("");
4735
+ for (const line of formatSearchResults(results).split(`
4736
+ `))
4737
+ io.out(line);
4738
+ return 0;
4739
+ } catch (error) {
4740
+ io.err(error instanceof Error ? error.message : String(error));
4741
+ return EXIT_CONFIG_PROBLEMS;
4410
4742
  }
4411
- return lines.join(`
4412
- `);
4413
4743
  }
4414
- function preview(value) {
4415
- const text = JSON.stringify(value) ?? String(value);
4416
- return text.length > 100 ? `${text.slice(0, 97)}...` : text;
4744
+ function printConfigReport(file, exists, fileOptions, envOptions, resolved, io) {
4745
+ io.out(`Config file: ${file} (${exists ? "exists" : "missing"})`);
4746
+ io.out("");
4747
+ const effective = configSummaryValues(resolved);
4748
+ const fileKeys = new Set(Object.keys(fileOptions));
4749
+ const envKeys = new Set(Object.keys(envOptions));
4750
+ for (const name of Object.keys(effective)) {
4751
+ let source = envKeys.has(name) ? "env" : fileKeys.has(name) ? "file" : "default";
4752
+ if (name === "maxResults" && source === "default" && (envKeys.has("count") || fileKeys.has("count"))) {
4753
+ source = "count";
4754
+ }
4755
+ io.out(`${name} = ${formatConfigValue(effective[name], "join")} (${source})`);
4756
+ }
4757
+ io.out("");
4758
+ io.out(HOST_OVERRIDE_NOTE);
4417
4759
  }
4760
+ var EXIT_CONFIG_PROBLEMS = 1, EXIT_USAGE = 2, HOST_OVERRIDE_NOTE = "Host-native layers (OpenCode options, Pi settings) may override file and env values per host.";
4761
+ var init_config_command = __esm(() => {
4762
+ init_auth();
4763
+ init_client();
4764
+ init_config_file();
4765
+ init_config_summary();
4766
+ init_env();
4767
+ init_format2();
4768
+ });
4418
4769
 
4419
- // src/installer/uninstall.ts
4420
- function uninstall(input) {
4421
- return withOperationLock([statePathFor(input)], () => {
4422
- const record = readRecord(input);
4423
- if (record === undefined) {
4424
- throw new Error(`No ${input.host} install is recorded for the ${input.scope} scope.`);
4425
- }
4426
- return withOperationLock(record.files.map((file) => file.file), () => uninstallLocked(input, record));
4427
- });
4770
+ // src/installer/detect.ts
4771
+ import { existsSync as existsSync8, readFileSync as readFileSync11 } from "node:fs";
4772
+ function replacingExistingEntryNote(path) {
4773
+ return `An existing ${path} entry is being replaced; its previous form is recorded for uninstall.`;
4428
4774
  }
4429
- function uninstallLocked(input, record) {
4430
- assertFileOwnership(input, record.files);
4431
- const other = input.scope === "global" ? "project" : "global";
4432
- const overlap = claimedByOtherScope(input, record.files.map((file) => file.file));
4433
- if (overlap.length > 0) {
4434
- throw new Error(`A ${input.host} install is also recorded at the ${other} scope and claims the same file(s): ${overlap.join(", ")}. ` + `Uninstall the ${other}-scope install first so this rollback cannot clobber its entries.`);
4775
+ function othersStayRegisteredNote(others) {
4776
+ return `Other MCP servers stay registered (${others.join(", ")}); routing to DeepSeek is not exclusive while they offer web tools.`;
4777
+ }
4778
+ function looksWebCapable(name, entry) {
4779
+ if (WEB_TOOL_HINT.test(name))
4780
+ return true;
4781
+ if (!isPlainObject(entry))
4782
+ return false;
4783
+ const command = typeof entry.command === "string" ? entry.command : "";
4784
+ const url = typeof entry.url === "string" ? entry.url : "";
4785
+ const args = Array.isArray(entry.args) ? entry.args.filter((arg) => typeof arg === "string").join(" ") : "";
4786
+ return WEB_TOOL_HINT.test(`${command} ${args} ${url}`);
4787
+ }
4788
+ function looksLikeOwnPackage(source) {
4789
+ return /(^|[/:@])deepseek-web-retrieval($|[@/]|-\d)/.test(source);
4790
+ }
4791
+ function findCompetitorSteering(host, file) {
4792
+ if (!existsSync8(file))
4793
+ return [];
4794
+ let text;
4795
+ try {
4796
+ text = readFileSync11(file, "utf8");
4797
+ } catch {
4798
+ return [];
4435
4799
  }
4436
- const lines = [];
4437
- for (const file of record.files) {
4438
- if (file.format !== "rules")
4800
+ return removeBlock(host, text).split(`
4801
+ `).map((line) => line.trim()).filter((line) => line.length > 0 && STEERING_HINT.test(line) && !line.includes("deepseek")).slice(0, 2);
4802
+ }
4803
+ function competitorSteeringNote(file, lines) {
4804
+ const quoted = lines.map((line) => `"${line}"`).join(", ");
4805
+ return `Existing rules in ${file} steer toward other web tools (${quoted}); the plan surfaces this conflict — it does not resolve it.`;
4806
+ }
4807
+ function splitCompetitors(servers) {
4808
+ const competitors = [];
4809
+ const bystanders = [];
4810
+ for (const [name, entry] of Object.entries(servers)) {
4811
+ if (name === "deepseek")
4439
4812
  continue;
4440
- const loaded = codecFor("rules", record.host).load(file.file);
4441
- if (loaded.parseError)
4442
- throw new Error(`${file.file}: ${loaded.parseError}`);
4443
- }
4444
- for (const file of [...record.files].reverse()) {
4445
- lines.push(...revertRecordedFile(file, record.host, { label: "", whole: true }));
4813
+ (looksWebCapable(name, entry) ? competitors : bystanders).push(name);
4446
4814
  }
4447
- deleteRecord(input);
4448
- releaseFileOwnership(input, record.files);
4449
- pruneEmptyDir(stateDir(input, input.scope));
4450
- lines.push(`removed install record (${input.host}, ${input.scope})`);
4451
- return lines;
4815
+ return { competitors, bystanders };
4452
4816
  }
4453
- var init_uninstall = __esm(() => {
4454
- init_formats();
4455
- init_operation_lock();
4456
- init_ownership();
4457
- init_paths();
4458
- init_revert();
4459
- init_state();
4817
+ var BOTH_CAPABILITIES_OFF = "Both capabilities are off; nothing would be installed.", FORCED_COST_NOTE, WEB_TOOL_HINT, STEERING_HINT;
4818
+ var init_detect = __esm(() => {
4819
+ init_rules();
4820
+ init_value();
4821
+ FORCED_COST_NOTE = "Forced routing is deterministic, and Search and Fetch are billed per successful request — " + `see the README's "Privacy and cost" section before applying.`;
4822
+ WEB_TOOL_HINT = /(web[_ -]?(search|fetch)|search|fetch|browse|scrape|crawl|tavily|brave|exa|perplexity|firecrawl|jina|serp|duckduckgo|reader)/i;
4823
+ STEERING_HINT = /(web[_ ]?(search|fetch)|websearch|webfetch|tavily|exa|brave|perplexity|firecrawl|jina|serp|duckduckgo|google|bing)/i;
4460
4824
  });
4461
4825
 
4462
- // src/installer/cli.ts
4463
- var exports_cli = {};
4464
- __export(exports_cli, {
4465
- runInstallerCli: () => runInstallerCli,
4466
- exitCodeForError: () => exitCodeForError
4467
- });
4468
- import { homedir } from "node:os";
4469
- import { resolve as resolve2 } from "node:path";
4470
- function parseFlags(args) {
4471
- const values = new Map;
4472
- const booleans = new Set;
4473
- const problems = [];
4474
- for (let i = 0;i < args.length; i += 1) {
4475
- const arg = args[i];
4476
- if (!arg.startsWith("--")) {
4477
- problems.push(`unexpected argument "${arg}" (flags only)`);
4478
- continue;
4479
- }
4480
- const eq = arg.indexOf("=");
4481
- const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
4482
- if (BOOLEAN_FLAGS.has(name)) {
4483
- if (eq !== -1) {
4484
- problems.push(`--${name} does not accept a value; use --${name} to enable it or omit it`);
4485
- continue;
4486
- }
4487
- if (booleans.has(name)) {
4488
- problems.push(`--${name} was given more than once`);
4489
- continue;
4490
- }
4491
- booleans.add(name);
4492
- continue;
4493
- }
4494
- if (!VALUE_FLAGS.has(name)) {
4495
- problems.push(`unknown flag --${name}`);
4496
- continue;
4497
- }
4498
- if (values.has(name)) {
4499
- problems.push(`--${name} was given more than once`);
4500
- continue;
4501
- }
4502
- if (eq !== -1) {
4503
- values.set(name, arg.slice(eq + 1));
4504
- continue;
4505
- }
4506
- const next = args[i + 1];
4507
- if (next === undefined || next.startsWith("--")) {
4508
- problems.push(`--${name} requires a value`);
4509
- continue;
4510
- }
4511
- values.set(name, next);
4512
- i += 1;
4826
+ // src/installer/rulesContent.ts
4827
+ function rulesLines(ids, search, fetch) {
4828
+ const lines = ["DeepSeek retrieval guidance:"];
4829
+ if (search === "preferred") {
4830
+ lines.push(`- Use ${ids.search} when the task needs fresh external information: current docs, version numbers,`, " changelogs, or anything you cannot know from the repository alone. Do not search for facts already", " present locally.");
4513
4831
  }
4514
- return { values, booleans, problems };
4832
+ if (fetch === "preferred") {
4833
+ lines.push(`- Use ${ids.fetch} to read a specific public web page as Markdown when its content is needed.`);
4834
+ }
4835
+ lines.push("- Never send localhost or private-network URLs to the DeepSeek tools; use local tools for those (the", " server blocks private hosts by default).", "- DeepSeek requests are billed per successful call; retrieve only what the task needs.");
4836
+ return lines;
4515
4837
  }
4516
- async function runInstallerCli(argv, io = {}) {
4517
- const out = io.out ?? ((line) => console.log(line));
4518
- const err = io.err ?? ((line) => console.error(line));
4519
- const [command, ...rest] = argv;
4520
- if (command === "version" || command === "--version") {
4521
- out(TOOL_VERSION);
4522
- return 0;
4838
+ var MCP_TOOL_IDS, RAW_MCP_TOOL_IDS;
4839
+ var init_rulesContent = __esm(() => {
4840
+ MCP_TOOL_IDS = {
4841
+ search: "mcp__deepseek__deepseek_web_search",
4842
+ fetch: "mcp__deepseek__deepseek_fetch"
4843
+ };
4844
+ RAW_MCP_TOOL_IDS = { search: "deepseek_web_search", fetch: "deepseek_fetch" };
4845
+ });
4846
+
4847
+ // src/installer/hosts/shared.ts
4848
+ function planHeader(input, paths, loaded, dialect) {
4849
+ const notes = [];
4850
+ const errors = [];
4851
+ if (loaded.parseError) {
4852
+ errors.push({ message: `${paths.config} exists but does not parse as ${dialect}: ${loaded.parseError}` });
4853
+ return { notes, errors, abort: true };
4523
4854
  }
4524
- if (command === undefined) {
4525
- err(USAGE);
4526
- return EXIT_USAGE;
4855
+ if (input.search === "off" && input.fetch === "off") {
4856
+ errors.push({ message: BOTH_CAPABILITIES_OFF });
4527
4857
  }
4528
- if (command === "help" || command === "--help") {
4529
- out(USAGE);
4530
- return 0;
4858
+ const rules = codecFor("rules", input.host).load(paths.rules);
4859
+ if (rules.parseError) {
4860
+ errors.push({ message: `${paths.rules}: ${rules.parseError}` });
4861
+ return { notes, errors, abort: true };
4531
4862
  }
4532
- const flags = parseFlags(rest);
4533
- if (flags.problems.length > 0) {
4534
- for (const problem of flags.problems)
4535
- err(`error: ${problem}`);
4536
- err(`
4537
- ${USAGE}`);
4538
- return EXIT_USAGE;
4863
+ const steering = findCompetitorSteering(input.host, paths.rules);
4864
+ if (steering.length > 0)
4865
+ notes.push(competitorSteeringNote(paths.rules, steering));
4866
+ return { notes, errors, abort: false };
4867
+ }
4868
+ var init_shared = __esm(() => {
4869
+ init_detect();
4870
+ init_formats();
4871
+ });
4872
+
4873
+ // src/installer/hosts/codex.ts
4874
+ import { spawnSync } from "node:child_process";
4875
+ function probeCodexVersion(err) {
4876
+ const result = spawnSync("codex", ["--version"], { timeout: 5000, encoding: "utf8", env: process.env });
4877
+ const version = result.status === 0 ? parseCodexVersion(result.stdout ?? "") : undefined;
4878
+ if (version === undefined) {
4879
+ err("note: codex was not found on PATH or printed no version; the version-drift check was skipped");
4539
4880
  }
4540
- const cwd = resolve2(flags.values.get("cwd") ?? process.cwd());
4541
- const home = process.env.HOME ?? homedir();
4542
- const configHome2 = resolveConfigHome(home);
4543
- if (command === "list") {
4544
- let records;
4545
- try {
4546
- records = listRecords({ home, cwd, configHome: configHome2 });
4547
- } catch (error) {
4548
- err(error instanceof Error ? error.message : String(error));
4549
- return 1;
4550
- }
4551
- if (records.length === 0) {
4552
- out("No installs recorded.");
4553
- return 0;
4554
- }
4555
- for (const record of records) {
4556
- const by = record.installerVersion ? ` by v${record.installerVersion}` : "";
4557
- out(`${record.host} (${record.scope}) — search=${record.tiers.search}, fetch=${record.tiers.fetch}, installed ${record.createdAt}${by}`);
4558
- for (const file of record.files)
4559
- out(` ${file.created ? "created" : "modified"} ${file.file}`);
4560
- }
4561
- return 0;
4881
+ return version;
4882
+ }
4883
+ function parseCodexVersion(output) {
4884
+ return /\bcodex(?:-cli)?\s+(\d+\.\d+\.\d+)\b/.exec(output)?.[1];
4885
+ }
4886
+ function codexPaths(input) {
4887
+ return {
4888
+ config: join2(input.home, ".codex/config.toml"),
4889
+ rules: input.scope === "global" ? join2(input.home, ".codex/AGENTS.md") : join2(input.cwd, "AGENTS.md")
4890
+ };
4891
+ }
4892
+ function planCodex(input, _previous) {
4893
+ const paths = codexPaths(input);
4894
+ const loaded = codecFor("toml", input.host).load(paths.config);
4895
+ const tiers = { search: input.search, fetch: input.fetch };
4896
+ const header = planHeader(input, paths, loaded, "TOML");
4897
+ if (header.abort) {
4898
+ return { host: "codex", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
4562
4899
  }
4563
- if (command === "uninstall") {
4564
- const required2 = requireInput(flags, cwd, home, configHome2, false);
4565
- if (!required2.ok)
4566
- return usageError(required2.problems, err);
4567
- try {
4568
- for (const line of uninstall(required2.input))
4569
- out(line);
4570
- return 0;
4571
- } catch (error) {
4572
- err(error instanceof Error ? error.message : String(error));
4573
- return 1;
4900
+ const notes = [...header.notes];
4901
+ const errors = [...header.errors];
4902
+ const edits = [];
4903
+ if (input.hostVersion !== undefined && input.hostVersion !== CODEX_TESTED_VERSION) {
4904
+ notes.push(`Codex ${input.hostVersion} is installed, but this installer's Codex facts are verified against ` + `${CODEX_TESTED_VERSION} (the docs/hosts.jsonc lock). Kill-switch and trap behavior may have drifted ` + "between the two — re-verify the tiers if routing misbehaves.");
4905
+ }
4906
+ const tools = loaded.value.tools;
4907
+ if (isPlainObject(tools) && "web_search" in tools) {
4908
+ errors.push({
4909
+ message: `${paths.config} sets [tools] web_search, which is a silent no-op at Codex 0.163.0 (only the top-level ` + "web_search key controls the tool). Remove it first so the config cannot mislead."
4910
+ });
4911
+ }
4912
+ const servers = loaded.value.mcp_servers;
4913
+ if (isPlainObject(servers)) {
4914
+ if ("deepseek" in servers)
4915
+ notes.push(replacingExistingEntryNote("mcp_servers.deepseek"));
4916
+ const { competitors, bystanders } = splitCompetitors(servers);
4917
+ if ((input.search === "forced" || input.fetch === "forced") && competitors.length > 0) {
4918
+ errors.push({
4919
+ message: `Forced cannot deliver exclusive routing: [mcp_servers.${competitors.join("], [mcp_servers.")}] look(s) web-capable, ` + "and Codex offers no per-server kill switch. Remove the server(s), disable their tools by hand via their " + "disabled_tools key, or choose a lower tier."
4920
+ });
4574
4921
  }
4922
+ const stayRegistered = input.search === "forced" || input.fetch === "forced" ? bystanders : [...competitors, ...bystanders];
4923
+ if (stayRegistered.length > 0)
4924
+ notes.push(othersStayRegisteredNote(stayRegistered));
4575
4925
  }
4576
- if (command !== "init") {
4577
- err(`Unknown command "${command}".
4578
-
4579
- ${USAGE}`);
4580
- return EXIT_USAGE;
4926
+ const existingEntry = isPlainObject(servers) ? servers.deepseek : undefined;
4927
+ const rawToolIds = Object.values(RAW_MCP_TOOL_IDS);
4928
+ const keptDisabled = isPlainObject(existingEntry) && Array.isArray(existingEntry.disabled_tools) ? existingEntry.disabled_tools.filter((name) => typeof name === "string" && !rawToolIds.includes(name)) : [];
4929
+ const offDisabled = [
4930
+ ...input.search === "off" ? [RAW_MCP_TOOL_IDS.search] : [],
4931
+ ...input.fetch === "off" ? [RAW_MCP_TOOL_IDS.fetch] : []
4932
+ ];
4933
+ const entry = {
4934
+ command: "npx",
4935
+ args: ["-y", input.packageRef],
4936
+ ...keptDisabled.length > 0 || offDisabled.length > 0 ? { disabled_tools: [...keptDisabled, ...offDisabled] } : {},
4937
+ env_vars: [API_KEY_ENV, ...OPTION_ENV_VARS]
4938
+ };
4939
+ const ops = [{ op: "set", path: ["mcp_servers", "deepseek"], value: entry, previous: existingEntry }];
4940
+ if (offDisabled.length > 0) {
4941
+ notes.push(`Off capabilities use Codex's own disabled_tools key (${offDisabled.join(", ")}): the tools are removed from ` + "the model's context while the server keeps running and stays re-enableable by deleting the entries.");
4581
4942
  }
4582
- const required = requireInput(flags, cwd, home, configHome2, true);
4583
- if (!required.ok)
4584
- return usageError(required.problems, err);
4585
- const { input } = required;
4586
- const probe = HOST_VERSION_PROBES[input.host];
4587
- const hostVersion = probe?.(err);
4588
- const plan = planForHost(input.host, hostVersion === undefined ? input : { ...input, hostVersion });
4589
- if (plan.errors.length > 0) {
4590
- for (const error of plan.errors)
4591
- err(`error: ${error.message}`);
4592
- err("Nothing was written.");
4593
- return 1;
4943
+ if (input.search === "forced") {
4944
+ const previous = typeof loaded.value.web_search === "string" ? loaded.value.web_search : undefined;
4945
+ ops.push({ op: "set", path: ["web_search"], value: "disabled", previous });
4946
+ notes.push(previous === undefined ? 'web_search is being set to "disabled" (no previous value existed; the default is "cached").' : `web_search is being set to "disabled"; the previous value "${previous}" is snapshotted for uninstall.`);
4594
4947
  }
4595
- out(renderPlan(plan));
4596
- if (!flags.booleans.has("apply")) {
4597
- out(`
4598
- Plan only — re-run with --apply to write these changes.`);
4599
- return 0;
4948
+ edits.push({ file: paths.config, format: "toml", shared: true, ops });
4949
+ notes.push(`Codex stdio children do not inherit the parent environment, so the entry forwards ${API_KEY_ENV} and every ` + "DEEPSEEK_* option variable explicitly via env_vars; shell-set knobs reach the server without hand-editing " + "config.toml (the shared config file works without any forwarding).");
4950
+ if (input.scope === "project") {
4951
+ notes.push("Codex config lives in ~/.codex/config.toml only (user level), so the server registration and kill switch are " + "written there even for a project-scope install; the rules file stays project-local.");
4600
4952
  }
4601
- try {
4602
- const result = applyPlan(plan, input);
4603
- for (const line of result.lines)
4604
- out(line);
4605
- return 0;
4606
- } catch (error) {
4607
- err(error instanceof Error ? error.message : String(error));
4608
- return exitCodeForError(error);
4953
+ if (loaded.lossy) {
4954
+ notes.push(`${paths.config} contains comments; the TOML rewrite will drop them.`);
4609
4955
  }
4956
+ if (input.search === "forced" || input.fetch === "forced") {
4957
+ notes.push(`Forced search is exclusion: the built-in web_search tool is disabled ("disabled" mode). ${FORCED_COST_NOTE}`);
4958
+ }
4959
+ if (input.search === "optional" || input.fetch === "optional") {
4960
+ notes.push('Note: Codex ships a built-in web_search tool (default "cached" mode, an OpenAI index) that stays available ' + "alongside the DeepSeek tools under the optional tier.");
4961
+ }
4962
+ if (input.search === "preferred" || input.fetch === "preferred") {
4963
+ edits.push({
4964
+ file: paths.rules,
4965
+ format: "rules",
4966
+ block: buildRulesBlock(input.host, rulesLines(MCP_TOOL_IDS, input.search, input.fetch))
4967
+ });
4968
+ notes.push(input.scope === "global" ? `Rules block upserted in ${paths.rules}; Codex reads ~/.codex/AGENTS.md plus every AGENTS.md from the project root to the cwd.` : `Rules block upserted in ${paths.rules}; Codex reads every AGENTS.md from the project root to the cwd.`);
4969
+ }
4970
+ return { host: "codex", scope: input.scope, tiers, edits, notes, errors };
4610
4971
  }
4611
- function exitCodeForError(error) {
4612
- return error instanceof ApplyError && error.status === "recovery_required" ? EXIT_RECOVERY : EXIT_FAILURE;
4613
- }
4614
- function usageError(problems, err) {
4615
- for (const problem of problems)
4616
- err(`error: ${problem}`);
4617
- err(`
4618
- ${USAGE}`);
4619
- return EXIT_USAGE;
4620
- }
4621
- function resolveConfigHome(home) {
4622
- const xdg = process.env.XDG_CONFIG_HOME;
4623
- if (xdg && home === (process.env.HOME ?? ""))
4624
- return xdg;
4625
- return;
4972
+ var CODEX_TESTED_VERSION = "0.163.0";
4973
+ var init_codex = __esm(() => {
4974
+ init_constants();
4975
+ init_env();
4976
+ init_detect();
4977
+ init_formats();
4978
+ init_rules();
4979
+ init_value();
4980
+ init_paths();
4981
+ init_rulesContent();
4982
+ init_shared();
4983
+ });
4984
+
4985
+ // src/installer/hosts/opencode.ts
4986
+ function opencodePaths(input) {
4987
+ return input.scope === "global" ? {
4988
+ config: join2(configHome(input), "opencode/opencode.jsonc"),
4989
+ rules: join2(configHome(input), "opencode/AGENTS.md")
4990
+ } : { config: join2(input.cwd, "opencode.jsonc"), rules: join2(input.cwd, "AGENTS.md") };
4626
4991
  }
4627
- function requireInput(flags, cwd, home, configHome2, needsTiers) {
4628
- const problems = [];
4629
- const host = flags.values.get("host");
4630
- const scope = flags.values.get("scope");
4631
- const search = needsTiers ? flags.values.get("search") ?? "" : "optional";
4632
- const fetch = needsTiers ? flags.values.get("fetch") ?? "" : "optional";
4633
- const path = flags.values.get("path");
4634
- if (host === undefined)
4635
- problems.push(`--host is required (one of: ${HOSTS.join(", ")})`);
4636
- else if (!HOSTS.includes(host))
4637
- problems.push(`invalid --host value "${host}" (one of: ${HOSTS.join(", ")})`);
4638
- if (scope === undefined)
4639
- problems.push(`--scope is required (one of: ${SCOPES.join(", ")})`);
4640
- else if (!SCOPES.includes(scope))
4641
- problems.push(`invalid --scope value "${scope}" (one of: ${SCOPES.join(", ")})`);
4642
- if (path !== undefined) {
4643
- if (host !== "pi") {
4644
- problems.push(`--path is only supported for host pi (${host ?? "no host"} has a single integration path)`);
4645
- } else if (!PATH_CHOICES.includes(path)) {
4646
- problems.push(`invalid --path value "${path}" (one of: ${PATH_CHOICES.join(", ")})`);
4647
- }
4992
+ function planOpenCode(input, previous) {
4993
+ const paths = opencodePaths(input);
4994
+ const loaded = codecFor("json", input.host).load(paths.config);
4995
+ const tiers = { search: input.search, fetch: input.fetch };
4996
+ const header = planHeader(input, paths, loaded, "JSONC");
4997
+ if (header.abort) {
4998
+ return { host: "opencode", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
4648
4999
  }
4649
- if (needsTiers) {
4650
- if (!TIERS.includes(search)) {
4651
- problems.push(flags.values.has("search") ? `invalid --search value "${search}" (one of: ${TIERS.join(", ")})` : `--search is required (one of: ${TIERS.join(", ")})`);
4652
- }
4653
- if (!TIERS.includes(fetch)) {
4654
- problems.push(flags.values.has("fetch") ? `invalid --fetch value "${fetch}" (one of: ${TIERS.join(", ")})` : `--fetch is required (one of: ${TIERS.join(", ")})`);
4655
- }
5000
+ const notes = [...header.notes];
5001
+ const errors = [...header.errors];
5002
+ const edits = [];
5003
+ if (input.search === "preferred") {
5004
+ errors.push({
5005
+ message: "OpenCode search has no preferred tier: the websearch provider is host-level config, so the model never " + "chooses between engines. Use --search optional (provider registered, built-in stays default), " + "--search forced (replace the engine), or --search off."
5006
+ });
4656
5007
  }
4657
- if (home === "")
4658
- problems.push("HOME is not set and the user home cannot be resolved; cannot proceed");
4659
- if (problems.length > 0)
4660
- return { ok: false, problems };
4661
- return {
4662
- ok: true,
4663
- input: {
4664
- host,
4665
- scope,
4666
- search,
4667
- fetch,
4668
- packageRef: flags.values.get("package") ?? "deepseek-web-retrieval",
4669
- home,
4670
- cwd,
4671
- configHome: configHome2,
4672
- ...path !== undefined ? { path } : {}
5008
+ const plugins = Array.isArray(loaded.value.plugins) ? loaded.value.plugins : [];
5009
+ const trackedPackages = new Set(appendedByPrevious(previous, ["plugins"]).filter((entry) => isPlainObject(entry) && typeof entry.package === "string").map((entry) => entry.package));
5010
+ const pluginPackages = plugins.filter((entry) => isPlainObject(entry) && typeof entry.package === "string");
5011
+ const excusedRefs = previous === undefined ? [] : [...trackedPackages, input.packageRef];
5012
+ const isExcusedRef = lineageMatcher(excusedRefs);
5013
+ const foreignOwn = pluginPackages.filter((entry) => looksLikeOwnPackage(entry.package) && !isExcusedRef(entry.package));
5014
+ if (foreignOwn.length > 0) {
5015
+ errors.push({
5016
+ message: `${paths.config} already has a plugins entry referencing deepseek-web-retrieval that this installer did not ` + "write. Remove it (or run uninstall if it came from a previous init), then retry."
5017
+ });
5018
+ }
5019
+ if (previous !== undefined && pluginPackages.some((entry) => isExcusedRef(entry.package))) {
5020
+ notes.push("A previous init wrote the plugins entry; re-applying keeps it the only entry (a changed package ref or tier " + "options replace it, an unchanged one is a no-op) and the original snapshots carry over.");
5021
+ }
5022
+ if (errors.length > 0) {
5023
+ return { host: "opencode", scope: input.scope, tiers, edits, notes, errors };
5024
+ }
5025
+ const options = {};
5026
+ if (input.search === "forced")
5027
+ options.setDefaultWebsearch = true;
5028
+ if (input.search === "off")
5029
+ options.searchEnabled = false;
5030
+ if (input.fetch === "forced")
5031
+ options.fetchOverrideWebfetch = true;
5032
+ if (input.fetch === "off")
5033
+ options.fetchEnabled = false;
5034
+ const ops = [
5035
+ {
5036
+ op: "append-array",
5037
+ path: ["plugins"],
5038
+ entries: [{ package: input.packageRef, options }],
5039
+ existingCount: plugins.length
4673
5040
  }
4674
- };
5041
+ ];
5042
+ const permissions = [];
5043
+ if (input.search !== "off")
5044
+ permissions.push({ action: "websearch", resource: "*", effect: "allow" });
5045
+ if (input.fetch !== "off")
5046
+ permissions.push({ action: "deepseek_fetch", resource: "*", effect: "allow" });
5047
+ if (input.fetch === "forced")
5048
+ permissions.push({ action: "webfetch", resource: "*", effect: "allow" });
5049
+ const existingPermissions = Array.isArray(loaded.value.permissions) ? loaded.value.permissions.length : 0;
5050
+ if (permissions.length > 0) {
5051
+ ops.push({ op: "append-array", path: ["permissions"], entries: permissions, existingCount: existingPermissions });
5052
+ }
5053
+ if (input.search === "forced") {
5054
+ const currentProvider = isPlainObject(loaded.value.websearch) ? loaded.value.websearch.provider : undefined;
5055
+ ops.push({ op: "set", path: ["websearch", "provider"], value: "deepseek", previous: currentProvider });
5056
+ notes.push(currentProvider === undefined ? "websearch.provider is being set to deepseek (no previous value existed)." : `websearch.provider is being set to deepseek; the previous value "${String(currentProvider)}" is snapshotted for uninstall.`);
5057
+ }
5058
+ edits.push({ file: paths.config, format: "json", ops });
5059
+ notes.push("The plugin entry uses the object form so options are honored; auto-discovered plugins cannot receive options.");
5060
+ if (input.search === "optional") {
5061
+ notes.push("Search tier optional: the deepseek provider is registered but the built-in provider stays the default engine; " + "set websearch.provider to deepseek (or rerun with --search forced) to route search through DeepSeek.");
5062
+ }
5063
+ if (input.search === "forced" || input.fetch === "forced") {
5064
+ notes.push(`Forced tier replaces built-in routing. ${FORCED_COST_NOTE}`);
5065
+ }
5066
+ if (input.fetch === "preferred") {
5067
+ edits.push({
5068
+ file: paths.rules,
5069
+ format: "rules",
5070
+ block: buildRulesBlock(input.host, rulesLines(OPENCODE_TOOL_IDS, input.search, input.fetch))
5071
+ });
5072
+ notes.push(`Rules block upserted in ${paths.rules}; OpenCode loads AGENTS.md only (no CLAUDE.md fallback in v2).`);
5073
+ }
5074
+ return { host: "opencode", scope: input.scope, tiers, edits, notes, errors };
4675
5075
  }
4676
- var HOSTS, HOST_CHOICES, SCOPES, TIERS, EXIT_FAILURE = 1, EXIT_USAGE = 2, EXIT_RECOVERY = 3, USAGE, VALUE_FLAGS, BOOLEAN_FLAGS, PATH_CHOICES;
4677
- var init_cli = __esm(() => {
4678
- init_version();
4679
- init_apply();
4680
- init_hosts();
5076
+ var OPENCODE_TOOL_IDS;
5077
+ var init_opencode = __esm(() => {
5078
+ init_detect();
5079
+ init_formats();
5080
+ init_rules();
5081
+ init_value();
5082
+ init_ownership();
5083
+ init_paths();
5084
+ init_rulesContent();
4681
5085
  init_state();
4682
- init_uninstall();
4683
- HOSTS = Object.keys(HOST_PLANNERS);
4684
- HOST_CHOICES = `<${HOSTS.join("|")}>`;
4685
- SCOPES = ["project", "global"];
4686
- TIERS = ["optional", "preferred", "forced", "off"];
4687
- USAGE = `Usage:
4688
- deepseek-web-retrieval init --host ${HOST_CHOICES} --scope <project|global> --search <optional|preferred|forced|off> --fetch <optional|preferred|forced|off> [--path <extension|mcp>] [--package <npm ref>] [--cwd <dir>] [--apply]
4689
- deepseek-web-retrieval uninstall --host ${HOST_CHOICES} --scope <project|global> [--cwd <dir>]
4690
- deepseek-web-retrieval list [--cwd <dir>]
4691
- deepseek-web-retrieval version
4692
-
4693
- init prints the full plan (every file, old value → new value) and writes nothing
4694
- until --apply is passed. uninstall restores what the plan applied. --path picks
4695
- the integration mechanism for hosts with more than one (Pi: extension by
4696
- default, mcp for the stdio MCP server). --package overrides the package ref
4697
- written into host config; the Pi extension path turns it into the packages
4698
- source (a bare name is prefixed with npm:, a ref that already starts with npm:
4699
- is written as-is).
4700
-
4701
- Exit codes: 0 success; 1 refused or failed with nothing written (a failed apply
4702
- is fully rolled back); 2 invalid command line; 3 recovery required — a failed
4703
- apply could not roll back completely, follow the reported guidance before
4704
- re-running.`;
4705
- VALUE_FLAGS = new Set(["host", "scope", "search", "fetch", "path", "package", "cwd"]);
4706
- BOOLEAN_FLAGS = new Set(["apply"]);
4707
- PATH_CHOICES = ["extension", "mcp"];
5086
+ init_shared();
5087
+ OPENCODE_TOOL_IDS = { search: "websearch (provider deepseek)", fetch: "deepseek_fetch" };
4708
5088
  });
4709
5089
 
4710
- // src/core/auth.ts
4711
- function apiKeyFromEnv(env = process.env) {
4712
- const key = env[API_KEY_ENV]?.trim();
4713
- return key ? key : undefined;
4714
- }
4715
- var init_auth = __esm(() => {
4716
- init_constants();
4717
- });
5090
+ // src/pi/settings.ts
5091
+ var SETTINGS_NAMESPACE = "deepseekWebRetrieval";
5092
+ var init_settings = () => {};
4718
5093
 
4719
- // src/core/domains.ts
4720
- import { isIP } from "node:net";
4721
- function normalizeDomain(value) {
4722
- const trimmed = value.trim();
4723
- if (!trimmed || /\s/.test(trimmed))
4724
- return;
4725
- const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed);
4726
- if (hasScheme && !/^https?:\/\//i.test(trimmed))
4727
- return;
4728
- let hostname;
4729
- try {
4730
- hostname = new URL(hasScheme ? trimmed : `http://${trimmed}`).hostname;
4731
- } catch {
4732
- return;
4733
- }
4734
- return normalizeHostname(hostname);
4735
- }
4736
- function normalizeHostname(value) {
4737
- return value.trim().toLowerCase().replace(/^\[/, "").replace(/\]$/, "").replace(/\.+$/, "");
5094
+ // src/installer/hosts/pi.ts
5095
+ function piPaths(input) {
5096
+ const mcp = input.scope === "global" ? join2(input.home, ".pi/agent/mcp.json") : join2(input.cwd, ".pi/mcp.json");
5097
+ const settings = input.scope === "global" ? join2(input.home, ".pi/agent/settings.json") : join2(input.cwd, ".pi/settings.json");
5098
+ const rules = input.scope === "global" ? join2(input.home, ".pi/agent/AGENTS.md") : join2(input.cwd, "AGENTS.md");
5099
+ return { config: input.path === "mcp" ? mcp : settings, rules };
4738
5100
  }
4739
- function domainMatches(hostname, domain) {
4740
- const host = normalizeHostname(hostname);
4741
- const target = normalizeHostname(domain);
4742
- if (!host || !target)
4743
- return false;
4744
- return host === target || host.endsWith(`.${target}`);
5101
+ function piSourceRef(packageRef) {
5102
+ return packageRef.startsWith("npm:") ? packageRef : `npm:${packageRef}`;
4745
5103
  }
4746
- function normalizeDomains(values) {
4747
- if (!Array.isArray(values))
4748
- return [];
4749
- const domains = new Set;
4750
- for (const value of values) {
4751
- if (typeof value !== "string")
4752
- continue;
4753
- const domain = normalizeDomain(value);
4754
- if (domain)
4755
- domains.add(domain);
4756
- }
4757
- return [...domains];
5104
+ function planPi(input, previous) {
5105
+ return input.path === "mcp" ? planPiMcp(input) : planPiExtension(input, previous);
4758
5106
  }
4759
- function isPrivateHostname(value) {
4760
- const host = normalizeHostname(value);
4761
- if (!host)
4762
- return true;
4763
- if (host === "localhost" || host === "local")
4764
- return true;
4765
- if (host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan") || host.endsWith(".home.arpa")) {
4766
- return true;
5107
+ function planPiExtension(input, previous) {
5108
+ const paths = piPaths(input);
5109
+ const loaded = codecFor("json", input.host).load(paths.config);
5110
+ const tiers = { search: input.search, fetch: input.fetch };
5111
+ const header = planHeader(input, paths, loaded, "JSON");
5112
+ if (header.abort) {
5113
+ return { host: "pi", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
4767
5114
  }
4768
- const version = isIP(host);
4769
- if (version === 4)
4770
- return isPrivateIpv4(host);
4771
- if (version === 6)
4772
- return isPrivateIpv6(host);
4773
- return false;
4774
- }
4775
- function assertFetchHostPolicy(url, options) {
4776
- const host = normalizeHostname(url.hostname);
4777
- if (options.blockPrivateHosts && isPrivateHostname(host)) {
4778
- throw new Error(`Fetch blocked for ${host}: local/private addresses are not reachable by DeepSeek. ` + "Set fetchBlockPrivateHosts=false only if you really need to send the URL.");
5115
+ const notes = [...header.notes];
5116
+ const errors = [...header.errors];
5117
+ const edits = [];
5118
+ const packages = Array.isArray(loaded.value.packages) ? loaded.value.packages : [];
5119
+ const source = piSourceRef(input.packageRef);
5120
+ const trackedSources = appendedByPrevious(previous, ["packages"]).filter((entry) => typeof entry === "string");
5121
+ const sources = packages.filter((entry) => typeof entry === "string");
5122
+ const excusedSources = previous === undefined ? [] : [...trackedSources, source];
5123
+ const isExcusedSource = lineageMatcher(excusedSources);
5124
+ const foreignOwn = sources.filter((entry) => looksLikeOwnPackage(entry) && !isExcusedSource(entry));
5125
+ if (foreignOwn.length > 0) {
5126
+ errors.push({
5127
+ message: `${paths.config} already lists ${foreignOwn.join(", ")} — this package (or a fork of it) that this installer did not ` + "write. Remove it (pi remove <source>, or uninstall if it came from a previous init), then retry."
5128
+ });
4779
5129
  }
4780
- const blocked = options.blockedDomains.find((domain) => domainMatches(host, domain));
4781
- if (blocked) {
4782
- throw new Error(`Fetch blocked for ${host}: matched fetchBlockedDomains entry "${blocked}"`);
5130
+ if (previous !== undefined && sources.some((entry) => isExcusedSource(entry))) {
5131
+ notes.push("A previous init wrote the packages entry; re-applying reuses it (an unchanged source deduplicates, a changed " + "--package ref replaces the old source) and the original snapshots carry over.");
4783
5132
  }
4784
- if (options.allowedDomains.length > 0 && !options.allowedDomains.some((domain) => domainMatches(host, domain))) {
4785
- throw new Error(`Fetch not allowed for ${host}: add it to fetchAllowedDomains (exact host or subdomain)`);
5133
+ const forced = input.search === "forced" || input.fetch === "forced";
5134
+ if (forced) {
5135
+ const isOwnSource = lineageMatcher([...trackedSources, source]);
5136
+ const unexcludable = [...collectSources(loaded.value.packages), ...collectSources(loaded.value.extensions)].filter((entry) => !isOwnSource(entry) && looksWebCapable(entry, undefined));
5137
+ if (unexcludable.length > 0) {
5138
+ errors.push({
5139
+ message: `Forced cannot deliver exclusive routing: settings sources ${unexcludable.join(", ")} look web-capable, ` + "and Pi offers no per-package kill switch. Remove them (pi remove <source>) or choose a lower tier."
5140
+ });
5141
+ }
4786
5142
  }
4787
- }
4788
- function isPrivateIpv4(host) {
4789
- const parts = host.split(".").map((part) => Number(part));
4790
- if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
4791
- return true;
5143
+ if (errors.length > 0) {
5144
+ return { host: "pi", scope: input.scope, tiers, edits: [], notes, errors };
4792
5145
  }
4793
- const [a, b] = parts;
4794
- return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
4795
- }
4796
- function isPrivateIpv6(host) {
4797
- const value = host.toLowerCase();
4798
- if (value === "::" || value === "::1")
4799
- return true;
4800
- if (value.startsWith("fc") || value.startsWith("fd"))
4801
- return true;
4802
- if (/^fe[89ab]/.test(value))
4803
- return true;
4804
- const dottedMapped = value.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1];
4805
- if (dottedMapped)
4806
- return isPrivateIpv4(dottedMapped);
4807
- const mapped = ipv4FromIpv6Hextets(value, /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
4808
- if (mapped)
4809
- return isPrivateIpv4(mapped);
4810
- const compatible = ipv4FromIpv6Hextets(value, /^::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
4811
- if (compatible)
4812
- return isPrivateIpv4(compatible);
4813
- return false;
4814
- }
4815
- function ipv4FromIpv6Hextets(value, pattern) {
4816
- const match = value.match(pattern);
4817
- if (!match)
4818
- return;
4819
- const high = Number.parseInt(match[1], 16);
4820
- const low = Number.parseInt(match[2], 16);
4821
- if (!Number.isFinite(high) || !Number.isFinite(low))
4822
- return;
4823
- return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
4824
- }
4825
- var init_domains = () => {};
4826
-
4827
- // src/core/options.ts
4828
- function resolvePluginOptions(input) {
4829
- return {
4830
- search: resolveSearchOptions(input),
4831
- fetch: resolveFetchOptions(input),
4832
- auth: resolveAuthOptions(input),
4833
- retry: resolveRetryOptions(input)
4834
- };
4835
- }
4836
- function resolveSearchOptions(input) {
4837
- return {
4838
- count: clampInt(input?.count, DEFAULT_SEARCH_COUNT, 1, 50),
4839
- maxResults: clampInt(input?.maxResults, DEFAULT_MAX_RESULTS, 0, 50),
4840
- minRerank: finiteNumber(input?.minRerank, DEFAULT_MIN_RERANK),
4841
- minAuthority: finiteNumber(input?.minAuthority, DEFAULT_MIN_AUTHORITY),
4842
- allowUnknownAuthority: input?.allowUnknownAuthority !== false,
4843
- blockedDomains: normalizeDomains(input?.blockedDomains),
4844
- includeDomains: normalizeDomains(input?.includeDomains),
4845
- language: optionalText(input?.language),
4846
- maxSummaryChars: clampInt(input?.maxSummaryChars, DEFAULT_MAX_SUMMARY_CHARS, 0, 1e6),
4847
- timeoutMs: clampInt(input?.searchTimeoutMs, DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS),
4848
- enabled: input?.searchEnabled !== false
4849
- };
4850
- }
4851
- function resolveFetchOptions(input) {
4852
- return {
4853
- maxChars: clampInt(input?.fetchMaxChars, DEFAULT_FETCH_MAX_CHARS, 0, 1e6),
4854
- allowedDomains: normalizeDomains(input?.fetchAllowedDomains),
4855
- blockedDomains: normalizeDomains(input?.fetchBlockedDomains),
4856
- timeoutMs: clampInt(input?.fetchTimeoutMs, DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS),
4857
- blockPrivateHosts: input?.fetchBlockPrivateHosts !== false,
4858
- enabled: input?.fetchEnabled !== false
4859
- };
4860
- }
4861
- function resolveAuthOptions(input) {
4862
- const value = input?.apiKeySource;
4863
- return {
4864
- source: value === "opencode" || value === "env" ? value : DEFAULT_API_KEY_SOURCE
4865
- };
4866
- }
4867
- function resolveRetryOptions(input) {
4868
- return {
4869
- maxRetries: clampInt(input?.maxRetries, DEFAULT_MAX_RETRIES, 0, MAX_RETRIES),
4870
- baseDelayMs: clampInt(input?.retryBaseDelayMs, DEFAULT_RETRY_BASE_DELAY_MS, 0, MAX_RETRY_DELAY_MS)
4871
- };
4872
- }
4873
- function optionalText(value) {
4874
- if (typeof value !== "string")
4875
- return;
4876
- const trimmed = value.trim();
4877
- return trimmed ? trimmed : undefined;
4878
- }
4879
- function finiteNumber(value, fallback) {
4880
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
4881
- }
4882
- function clampInt(value, fallback, min, max) {
4883
- const number = typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : fallback;
4884
- return Math.min(max, Math.max(min, number));
4885
- }
4886
- var init_options = __esm(() => {
4887
- init_constants();
4888
- init_domains();
4889
- });
4890
-
4891
- // src/core/env.ts
4892
- function resolveEnvOptions(env = process.env) {
4893
- return resolvePluginOptions(pluginOptionsFromEnv(env));
4894
- }
4895
- function pluginOptionsFromEnv(env) {
4896
- const options = {};
4897
- putNumber(options, "count", env);
4898
- putNumber(options, "maxResults", env);
4899
- putNumber(options, "minRerank", env);
4900
- putNumber(options, "minAuthority", env);
4901
- putFalseOnly(options, "allowUnknownAuthority", env);
4902
- putDomains(options, "blockedDomains", env);
4903
- putDomains(options, "includeDomains", env);
4904
- putText(options, "language", env);
4905
- putNumber(options, "maxSummaryChars", env);
4906
- putNumber(options, "searchTimeoutMs", env);
4907
- putNumber(options, "fetchMaxChars", env);
4908
- putDomains(options, "fetchAllowedDomains", env);
4909
- putDomains(options, "fetchBlockedDomains", env);
4910
- putNumber(options, "fetchTimeoutMs", env);
4911
- putFalseOnly(options, "fetchBlockPrivateHosts", env);
4912
- putFalseOnly(options, "searchEnabled", env);
4913
- putFalseOnly(options, "fetchEnabled", env);
4914
- putNumber(options, "maxRetries", env);
4915
- putNumber(options, "retryBaseDelayMs", env);
4916
- return options;
4917
- }
4918
- function putNumber(target, key, env) {
4919
- const value = env[NUMBER_ENV[key]];
4920
- if (value === undefined)
4921
- return;
4922
- const trimmed = value.trim();
4923
- if (!trimmed)
4924
- return;
4925
- const parsed = Number(trimmed);
4926
- if (Number.isFinite(parsed))
4927
- target[key] = parsed;
4928
- }
4929
- function putText(target, key, env) {
4930
- const value = env[TEXT_ENV[key]];
4931
- if (value === undefined)
4932
- return;
4933
- const trimmed = value.trim();
4934
- if (trimmed)
4935
- target[key] = trimmed;
4936
- }
4937
- function putFalseOnly(target, key, env) {
4938
- if (isFalseValue(env[FALSE_ONLY_ENV[key]]))
4939
- target[key] = false;
4940
- }
4941
- function putDomains(target, key, env) {
4942
- const value = env[DOMAINS_ENV[key]];
4943
- if (value === undefined || !value.trim())
4944
- return;
4945
- const domains = value.split(",").map((domain) => domain.trim()).filter((domain) => domain.length > 0);
4946
- if (domains.length > 0)
4947
- target[key] = domains;
4948
- }
4949
- function isFalseValue(value) {
4950
- const trimmed = value?.trim().toLowerCase();
4951
- return trimmed === "false" || trimmed === "0" || trimmed === "no" || trimmed === "off";
4952
- }
4953
- var NUMBER_ENV, TEXT_ENV, DOMAINS_ENV, FALSE_ONLY_ENV;
4954
- var init_env = __esm(() => {
4955
- init_constants();
4956
- init_options();
4957
- NUMBER_ENV = {
4958
- count: "DEEPSEEK_SEARCH_COUNT",
4959
- maxResults: "DEEPSEEK_SEARCH_MAX_RESULTS",
4960
- minRerank: "DEEPSEEK_SEARCH_MIN_RERANK",
4961
- minAuthority: "DEEPSEEK_SEARCH_MIN_AUTHORITY",
4962
- maxSummaryChars: "DEEPSEEK_SEARCH_MAX_SUMMARY_CHARS",
4963
- searchTimeoutMs: "DEEPSEEK_SEARCH_TIMEOUT_MS",
4964
- fetchMaxChars: "DEEPSEEK_FETCH_MAX_CHARS",
4965
- fetchTimeoutMs: "DEEPSEEK_FETCH_TIMEOUT_MS",
4966
- maxRetries: "DEEPSEEK_MAX_RETRIES",
4967
- retryBaseDelayMs: "DEEPSEEK_RETRY_BASE_DELAY_MS"
4968
- };
4969
- TEXT_ENV = {
4970
- language: "DEEPSEEK_SEARCH_LANGUAGE"
4971
- };
4972
- DOMAINS_ENV = {
4973
- blockedDomains: "DEEPSEEK_SEARCH_BLOCKED_DOMAINS",
4974
- includeDomains: "DEEPSEEK_SEARCH_INCLUDE_DOMAINS",
4975
- fetchAllowedDomains: "DEEPSEEK_FETCH_ALLOWED_DOMAINS",
4976
- fetchBlockedDomains: "DEEPSEEK_FETCH_BLOCKED_DOMAINS"
4977
- };
4978
- FALSE_ONLY_ENV = {
4979
- allowUnknownAuthority: "DEEPSEEK_SEARCH_ALLOW_UNKNOWN_AUTHORITY",
4980
- fetchBlockPrivateHosts: "DEEPSEEK_FETCH_BLOCK_PRIVATE_HOSTS",
4981
- searchEnabled: ENABLE_SEARCH_ENV,
4982
- fetchEnabled: ENABLE_FETCH_ENV
4983
- };
4984
- });
4985
-
4986
- // src/mcp/auth.ts
4987
- function requireApiKey(env) {
4988
- const apiKey = apiKeyFromEnv(env);
4989
- if (!apiKey)
4990
- throw new Error(MISSING_API_KEY_MESSAGE);
4991
- return apiKey;
4992
- }
4993
- var MISSING_API_KEY_MESSAGE;
4994
- var init_auth2 = __esm(() => {
4995
- init_auth();
4996
- init_constants();
4997
- MISSING_API_KEY_MESSAGE = `DeepSeek API key not found. Set ${API_KEY_ENV} in the MCP server's env configuration.`;
4998
- });
4999
-
5000
- // src/mcp/client.ts
5001
- import { CLIENT_INFO_META_KEY } from "@modelcontextprotocol/server";
5002
- function clientNameOf(server, ctx) {
5003
- const envelope = ctx.mcpReq.envelope;
5004
- const name = envelope?.[CLIENT_INFO_META_KEY];
5005
- if (typeof name === "object" && name !== null && "name" in name && typeof name.name === "string") {
5006
- return name.name;
5146
+ const ops = [
5147
+ { op: "append-array", path: ["packages"], entries: [source], existingCount: packages.length }
5148
+ ];
5149
+ const namespace = isPlainObject(loaded.value[SETTINGS_NAMESPACE]) ? loaded.value[SETTINGS_NAMESPACE] : {};
5150
+ if (input.search === "off") {
5151
+ ops.push({
5152
+ op: "set",
5153
+ path: [SETTINGS_NAMESPACE, "enableSearch"],
5154
+ value: false,
5155
+ previous: typeof namespace.enableSearch === "boolean" ? namespace.enableSearch : undefined
5156
+ });
5007
5157
  }
5008
- return server.server.getClientVersion()?.name;
5158
+ if (input.fetch === "off") {
5159
+ ops.push({
5160
+ op: "set",
5161
+ path: [SETTINGS_NAMESPACE, "enableFetch"],
5162
+ value: false,
5163
+ previous: typeof namespace.enableFetch === "boolean" ? namespace.enableFetch : undefined
5164
+ });
5165
+ }
5166
+ edits.push({ file: paths.config, format: "json", ops });
5167
+ notes.push("Pi resolves the packages source at session start; the first launch after apply fetches the package from npm " + "(pi update --extensions refreshes it later).");
5168
+ notes.push(`The extension reads ${API_KEY_ENV} from the Pi process environment; no env forwarding is needed. ` + "Set it in the shell that launches Pi.");
5169
+ if (input.search === "off" || input.fetch === "off") {
5170
+ notes.push(`Off capability switches are written into the "${SETTINGS_NAMESPACE}" settings namespace; the extension ` + "reads them at load (they outrank the DEEPSEEK_ENABLE_* environment variables).");
5171
+ }
5172
+ notes.push(`Extension tools are declared to the model with exposure "direct" by Pi's own default; no exposure key is needed.`);
5173
+ if (forced) {
5174
+ edits.push(...planMcpCompetitorDisables(input, notes, errors));
5175
+ }
5176
+ if (errors.length > 0) {
5177
+ return { host: "pi", scope: input.scope, tiers, edits: [], notes, errors };
5178
+ }
5179
+ if (input.search === "preferred" || input.fetch === "preferred") {
5180
+ edits.push({
5181
+ file: paths.rules,
5182
+ format: "rules",
5183
+ block: buildRulesBlock(input.host, rulesLines(RAW_MCP_TOOL_IDS, input.search, input.fetch))
5184
+ });
5185
+ notes.push(`Rules block upserted in ${paths.rules}; Pi loads AGENTS.md context files from the working directory and its parents.`);
5186
+ }
5187
+ if (forced) {
5188
+ notes.push("Forced tier: Pi 1.3.0 ships no built-in web tool, so the registered tools are the only web path (de-facto). " + FORCED_COST_NOTE);
5189
+ }
5190
+ return { host: "pi", scope: input.scope, tiers, edits, notes, errors };
5009
5191
  }
5010
- function isJsonReplacingClient(name) {
5011
- return name !== undefined && JSON_REPLACING_CLIENT_NAMES.has(name);
5192
+ function planCompetitorDisables(servers, competitors, notes, errors) {
5193
+ const ops = [];
5194
+ const excluded = [];
5195
+ const unexcludable = [];
5196
+ for (const name of competitors) {
5197
+ const current = servers[name];
5198
+ if (!isPlainObject(current)) {
5199
+ unexcludable.push(name);
5200
+ continue;
5201
+ }
5202
+ const previous = typeof current.enabled === "boolean" ? current.enabled : undefined;
5203
+ ops.push({ op: "set", path: ["mcpServers", name, "enabled"], value: false, previous });
5204
+ excluded.push(name);
5205
+ }
5206
+ if (excluded.length > 0) {
5207
+ notes.push(`Forced tier: web-capable MCP servers are disabled so DeepSeek routing is exclusive (${excluded.join(", ")}; ` + "prior enabled values are snapshotted for uninstall).");
5208
+ }
5209
+ if (unexcludable.length > 0) {
5210
+ errors.push({
5211
+ message: `Forced cannot deliver exclusive routing: mcpServers entries ${unexcludable.join(", ")} look web-capable ` + "but are not objects, so the plan cannot set their enabled key. Fix or remove them, or choose a lower tier."
5212
+ });
5213
+ }
5214
+ return ops;
5012
5215
  }
5013
- function omitStructuredContent(server, ctx) {
5014
- return isJsonReplacingClient(clientNameOf(server, ctx));
5216
+ function planMcpCompetitorDisables(input, notes, errors) {
5217
+ const mcpFile = input.scope === "global" ? join2(input.home, ".pi/agent/mcp.json") : join2(input.cwd, ".pi/mcp.json");
5218
+ const loaded = codecFor("json", input.host).load(mcpFile);
5219
+ if (loaded.parseError) {
5220
+ errors.push({ message: `${mcpFile} does not parse: ${loaded.parseError}` });
5221
+ return [];
5222
+ }
5223
+ const servers = isPlainObject(loaded.value.mcpServers) ? loaded.value.mcpServers : undefined;
5224
+ if (!isPlainObject(servers))
5225
+ return [];
5226
+ const { competitors, bystanders } = splitCompetitors(servers);
5227
+ const edits = [];
5228
+ if (competitors.length > 0) {
5229
+ const ops = planCompetitorDisables(servers, competitors, notes, errors);
5230
+ if (ops.length > 0)
5231
+ edits.push({ file: mcpFile, format: "json", ops });
5232
+ }
5233
+ if (bystanders.length > 0)
5234
+ notes.push(othersStayRegisteredNote(bystanders));
5235
+ return edits;
5015
5236
  }
5016
- var JSON_REPLACING_CLIENT_NAMES;
5017
- var init_client = __esm(() => {
5018
- JSON_REPLACING_CLIENT_NAMES = new Set(["codex-mcp-client"]);
5019
- });
5020
-
5021
- // package.json
5022
- var package_default;
5023
- var init_package = __esm(() => {
5024
- package_default = {
5025
- $schema: "https://json.schemastore.org/package.json",
5026
- name: "deepseek-web-retrieval",
5027
- version: "0.6.0",
5028
- description: "Token-efficient DeepSeek Search and Fetch for coding agents, starting with OpenCode v2.",
5029
- type: "module",
5030
- license: "MIT",
5031
- repository: {
5032
- type: "git",
5033
- url: "git+https://github.com/gwokhou/deepseek-web-retrieval.git"
5034
- },
5035
- homepage: "https://github.com/gwokhou/deepseek-web-retrieval#readme",
5036
- bugs: "https://github.com/gwokhou/deepseek-web-retrieval/issues",
5037
- keywords: [
5038
- "opencode",
5039
- "opencode-plugin",
5040
- "pi",
5041
- "pi-extension",
5042
- "deepseek",
5043
- "websearch",
5044
- "webfetch",
5045
- "coding-agent",
5046
- "mcp"
5047
- ],
5048
- exports: {
5049
- ".": "./index.ts",
5050
- "./core": "./src/core/index.ts",
5051
- "./mcp": "./src/mcp/server.ts",
5052
- "./pi": "./src/pi/extension.ts"
5053
- },
5054
- pi: {
5055
- extensions: [
5056
- "./src/pi/extension.ts"
5057
- ]
5058
- },
5059
- bin: {
5060
- "deepseek-web-retrieval": "dist/cli.js"
5061
- },
5062
- files: [
5063
- "index.ts",
5064
- "src",
5065
- "dist",
5066
- "docs",
5067
- "README.md",
5068
- "LICENSE",
5069
- "CHANGELOG.md",
5070
- "examples"
5071
- ],
5072
- scripts: {
5073
- lint: "biome check --error-on-warnings .",
5074
- "lint:ci": "biome ci --error-on-warnings .",
5075
- "lint:fix": "biome check --write --error-on-warnings .",
5076
- format: "biome format --write .",
5077
- typecheck: "tsc --noEmit",
5078
- build: "bun build src/mcp/cli.ts --target=node --format=esm --outdir=dist --external @modelcontextprotocol/server --external @modelcontextprotocol/server/stdio --external zod --external zod/v4",
5079
- prepublishOnly: "bun run check:release",
5080
- test: "bun test",
5081
- "test:package": "node scripts/test-package.mjs",
5082
- "test:e2e:keyless": "bun run test:e2e pi pi-extension installer reinit upgrade pkg capability-off",
5083
- "check:release": "bun run check && bun run test:package && bun run test:e2e:keyless",
5084
- "test:e2e": "bun run test/e2e/run.ts",
5085
- "docs:matrix": "bun run scripts/render-matrix.ts",
5086
- "test:coverage": "bun test --coverage",
5087
- check: "bun run lint && bun run typecheck && bun run docs:matrix --check && bun run build && bun test"
5088
- },
5089
- peerDependencies: {
5090
- "@earendil-works/pi-ai": "^1.3.0",
5091
- "@earendil-works/pi-coding-agent": "^1.3.0",
5092
- "@opencode/plugin": "^2.0.32"
5093
- },
5094
- peerDependenciesMeta: {
5095
- "@earendil-works/pi-ai": {
5096
- optional: true
5097
- },
5098
- "@earendil-works/pi-coding-agent": {
5099
- optional: true
5100
- },
5101
- "@opencode/plugin": {
5102
- optional: true
5103
- }
5104
- },
5105
- devDependencies: {
5106
- "@biomejs/biome": "2.5.15",
5107
- "@earendil-works/pi-ai": "1.3.0",
5108
- "@earendil-works/pi-coding-agent": "1.3.0",
5109
- "@modelcontextprotocol/client": "^2.3.1",
5110
- "@opencode/plugin": "2.0.32",
5111
- "@types/bun": "1.4.0",
5112
- "@types/node": "^26.6.5",
5113
- typescript: "5.9.3"
5114
- },
5115
- engines: {
5116
- bun: ">=1.3.0",
5117
- node: ">=20"
5118
- },
5119
- dependencies: {
5120
- "@modelcontextprotocol/server": "^2.3.1",
5121
- "jsonc-parser": "^3.3.1",
5122
- "smol-toml": "^1.9.1",
5123
- zod: "^4"
5124
- }
5237
+ function planPiMcp(input) {
5238
+ const paths = piPaths(input);
5239
+ const loaded = codecFor("json", input.host).load(paths.config);
5240
+ const tiers = { search: input.search, fetch: input.fetch };
5241
+ const header = planHeader(input, paths, loaded, "JSON");
5242
+ if (header.abort) {
5243
+ return { host: "pi", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
5244
+ }
5245
+ const notes = [...header.notes];
5246
+ const errors = [...header.errors];
5247
+ const edits = [];
5248
+ const env = { [API_KEY_ENV]: `\${${API_KEY_ENV}}` };
5249
+ if (input.search === "off")
5250
+ env[ENABLE_SEARCH_ENV] = "false";
5251
+ if (input.fetch === "off")
5252
+ env[ENABLE_FETCH_ENV] = "false";
5253
+ const entry = {
5254
+ command: "npx",
5255
+ args: ["-y", input.packageRef],
5256
+ env,
5257
+ exposure: "direct",
5258
+ enabled: true
5125
5259
  };
5260
+ const servers = loaded.value.mcpServers;
5261
+ const existingEntry = isPlainObject(servers) ? servers.deepseek : undefined;
5262
+ const ops = [{ op: "set", path: ["mcpServers", "deepseek"], value: entry, previous: existingEntry }];
5263
+ edits.push({ file: paths.config, format: "json", ops });
5264
+ if (isPlainObject(servers)) {
5265
+ if (servers.deepseek !== undefined)
5266
+ notes.push(replacingExistingEntryNote("mcpServers.deepseek"));
5267
+ const { competitors, bystanders } = splitCompetitors(servers);
5268
+ const forced = input.search === "forced" || input.fetch === "forced";
5269
+ if (forced) {
5270
+ ops.push(...planCompetitorDisables(servers, competitors, notes, errors));
5271
+ }
5272
+ const stayRegistered = forced ? bystanders : [...competitors, ...bystanders];
5273
+ if (stayRegistered.length > 0)
5274
+ notes.push(othersStayRegisteredNote(stayRegistered));
5275
+ }
5276
+ notes.push('"exposure": "direct" is required: Pi 1.3.0 defaults MCP tools to codemode, which hides them from the model.');
5277
+ notes.push(`\`${API_KEY_ENV}\` is written as "\${${API_KEY_ENV}}" so the key expands from the shell that launches Pi and stays out of the file.`);
5278
+ if (input.search === "preferred" || input.fetch === "preferred") {
5279
+ edits.push({
5280
+ file: paths.rules,
5281
+ format: "rules",
5282
+ block: buildRulesBlock(input.host, rulesLines(MCP_TOOL_IDS, input.search, input.fetch))
5283
+ });
5284
+ notes.push(`Rules block upserted in ${paths.rules}; Pi loads AGENTS.md context files from the working directory and its parents.`);
5285
+ }
5286
+ if (input.search === "forced" || input.fetch === "forced") {
5287
+ notes.push("Forced tier: Pi 1.3.0 ships no built-in web tool, so the registered tools are the only web path (de-facto). " + FORCED_COST_NOTE);
5288
+ }
5289
+ return { host: "pi", scope: input.scope, tiers, edits, notes, errors };
5290
+ }
5291
+ function collectSources(value) {
5292
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
5293
+ }
5294
+ var init_pi = __esm(() => {
5295
+ init_constants();
5296
+ init_settings();
5297
+ init_detect();
5298
+ init_formats();
5299
+ init_rules();
5300
+ init_value();
5301
+ init_ownership();
5302
+ init_paths();
5303
+ init_rulesContent();
5304
+ init_state();
5305
+ init_shared();
5126
5306
  });
5127
5307
 
5128
- // src/core/format.ts
5129
- function truncate(value, maxChars) {
5130
- if (maxChars <= 0)
5131
- return "";
5132
- if (value.length <= maxChars)
5133
- return value;
5134
- return Array.from(value).slice(0, maxChars).join("");
5308
+ // src/installer/hosts/index.ts
5309
+ function planForHost(host, input) {
5310
+ try {
5311
+ const previous = readRecord(input);
5312
+ const planned = withCrossScopeGuard(HOST_PLANNERS[host](input, previous), input);
5313
+ return {
5314
+ ...withSecretGuard(withOrphanReverts(withLegacySharedConfigGuard(planned, previous), previous)),
5315
+ previousRecord: previous
5316
+ };
5317
+ } catch (error) {
5318
+ if (!(error instanceof InstallRecordError))
5319
+ throw error;
5320
+ return {
5321
+ host,
5322
+ scope: input.scope,
5323
+ tiers: { search: input.search, fetch: input.fetch },
5324
+ edits: [],
5325
+ notes: [],
5326
+ errors: [{ message: error.message }]
5327
+ };
5328
+ }
5135
5329
  }
5136
- function formatFetchedContent(title, content, maxChars) {
5137
- const document = withTitle(title, content);
5138
- const length = Array.from(document).length;
5139
- if (maxChars <= 0)
5140
- return { content: "", truncated: length > 0 };
5141
- if (length <= maxChars)
5142
- return { content: document, truncated: false };
5143
- const markerLength = Array.from(FETCH_TRUNCATION_MARKER).length;
5144
- if (maxChars <= markerLength) {
5145
- return { content: truncate(document, maxChars), truncated: true };
5330
+ function withCrossScopeGuard(plan, input) {
5331
+ if (plan.errors.length > 0)
5332
+ return plan;
5333
+ try {
5334
+ assertFileOwnership(input, plan.edits);
5335
+ } catch (error) {
5336
+ return { ...plan, edits: [], reverts: undefined, errors: [{ message: String(error) }] };
5146
5337
  }
5338
+ const other = input.scope === "global" ? "project" : "global";
5339
+ const overlap = claimedByOtherScope(input, plan.edits.map((edit2) => edit2.file));
5340
+ if (overlap.length === 0)
5341
+ return { ...plan, notes: [...plan.notes, ...fileOwnershipNotes(input, plan.edits)] };
5147
5342
  return {
5148
- content: `${truncate(document, maxChars - markerLength)}${FETCH_TRUNCATION_MARKER}`,
5149
- truncated: true
5343
+ ...plan,
5344
+ edits: [],
5345
+ reverts: undefined,
5346
+ errors: [
5347
+ {
5348
+ message: `A ${plan.host} install is already recorded at the ${other} scope and claims the same file(s): ${overlap.join(", ")}. ` + `Uninstall it first (deepseek-web-retrieval uninstall --host ${plan.host} --scope ${other}), ` + `or re-run with --scope ${other} to update it in place — two scopes must not edit one file.`
5349
+ }
5350
+ ]
5150
5351
  };
5151
5352
  }
5152
- function withTitle(title, content) {
5153
- const heading = title.trim();
5154
- if (!heading)
5155
- return content;
5156
- const body = content.trimStart();
5157
- const lines = body.split(/\r?\n/);
5158
- const firstHeading = lines[0]?.match(/^\\?#\s+(.+?)\s*$/)?.[1];
5159
- if (firstHeading && normalizeHeading(firstHeading) === normalizeHeading(heading)) {
5160
- lines[0] = `# ${heading}`;
5161
- return lines.join(`
5162
- `);
5353
+ function withLegacySharedConfigGuard(plan, previous) {
5354
+ if (plan.errors.length > 0 || previous !== undefined)
5355
+ return plan;
5356
+ for (const edit2 of plan.edits) {
5357
+ if (edit2.format === "rules" || !edit2.shared)
5358
+ continue;
5359
+ for (const op of edit2.ops) {
5360
+ const old = op.previous;
5361
+ if (op.op !== "set" || !isPlainObject(old) || old.command !== "npx" || !Array.isArray(old.args) || old.args[0] !== "-y" || !Array.isArray(old.env_vars) || !old.env_vars.includes(API_KEY_ENV))
5362
+ continue;
5363
+ return {
5364
+ ...plan,
5365
+ edits: [],
5366
+ reverts: undefined,
5367
+ errors: [
5368
+ {
5369
+ message: `${edit2.file} contains an installer-style registration without an install record for this location. ` + "It may belong to an older install in another project. Re-run init or uninstall from that original project and scope first; " + "if the registration was created manually, remove it before retrying. No existing registration was adopted."
5370
+ }
5371
+ ]
5372
+ };
5373
+ }
5163
5374
  }
5164
- return `# ${heading}
5165
-
5166
- ${content}`;
5167
- }
5168
- function normalizeHeading(value) {
5169
- return value.trim().replace(/\s+/g, " ").replace(/\s+#+\s*$/, "").toLowerCase();
5375
+ return plan;
5170
5376
  }
5171
- function redactSecrets(value) {
5172
- return value.replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "sk-***").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, "Bearer ***");
5377
+ function withSecretGuard(plan) {
5378
+ for (const edit2 of plan.edits) {
5379
+ if (edit2.format === "rules")
5380
+ continue;
5381
+ for (const op of edit2.ops) {
5382
+ if (op.op !== "set" || op.previous === undefined)
5383
+ continue;
5384
+ const offender = findSecretLike(op.previous, op.path.join("."));
5385
+ if (offender !== undefined) {
5386
+ return {
5387
+ ...plan,
5388
+ edits: [],
5389
+ reverts: undefined,
5390
+ errors: [
5391
+ {
5392
+ message: `${edit2.file}: the existing value at ${op.path.join(".")} contains a credential-looking key ` + `(${offender}). The installer refuses to snapshot secrets into its state file. Move the key to ` + `environment indirection ("\${${API_KEY_ENV}}" expansion or env_vars) and re-run.`
5393
+ }
5394
+ ]
5395
+ };
5396
+ }
5397
+ }
5398
+ }
5399
+ return plan;
5173
5400
  }
5174
- function formatApiError(operation2, status, body) {
5175
- const detail = redactSecrets(body.trim());
5176
- const detailChars = Array.from(detail);
5177
- const text = detail ? detailChars.length > MAX_ERROR_BODY_CHARS ? `${detailChars.slice(0, MAX_ERROR_BODY_CHARS).join("")}…` : detail : "empty response body";
5178
- const hint = status === 401 ? "invalid API key" : status === 402 ? "insufficient balance" : status === 403 ? "permission denied" : status === 429 ? "rate limited" : undefined;
5179
- const label = hint ? `${operation2} failed (HTTP ${status}, ${hint})` : `${operation2} failed (HTTP ${status})`;
5180
- return `${label}: ${text}`;
5401
+ function findSecretLike(value, at) {
5402
+ if (typeof value !== "object" || value === null)
5403
+ return;
5404
+ for (const [key, child] of Object.entries(value)) {
5405
+ const path = `${at}.${key}`;
5406
+ if (/(api[_-]?key|token|secret|password|credential)/i.test(key) && typeof child === "string" && child.length > 0 && !/^\$\{[^}]+\}$/.test(child)) {
5407
+ return path;
5408
+ }
5409
+ const nested = findSecretLike(child, path);
5410
+ if (nested !== undefined)
5411
+ return nested;
5412
+ }
5413
+ return;
5181
5414
  }
5182
- function formatTimeoutError(operation2, timeoutMs) {
5183
- return `${operation2} timed out after ${timeoutMs} ms`;
5415
+ function withOrphanReverts(plan, previous) {
5416
+ if (plan.errors.length > 0)
5417
+ return plan;
5418
+ if (previous === undefined)
5419
+ return plan;
5420
+ const reverts = [];
5421
+ for (const file of previous.files) {
5422
+ const edit2 = plan.edits.find((candidate) => candidate.file === file.file);
5423
+ if (edit2 === undefined) {
5424
+ reverts.push(file);
5425
+ continue;
5426
+ }
5427
+ if (edit2.format === "rules" || file.format === "rules")
5428
+ continue;
5429
+ const orphanOps = file.ops.flatMap((op) => {
5430
+ const claimed = edit2.ops.find((candidate) => candidate.op === op.op && candidate.path.join("\x00") === op.path.join("\x00"));
5431
+ if (op.op !== "append-array" || claimed === undefined || claimed.op !== "append-array") {
5432
+ return claimed === undefined ? [op] : [];
5433
+ }
5434
+ const dropped = (Array.isArray(op.applied) ? op.applied : []).filter((entry) => !(claimed.entries ?? []).some((wanted) => deepEqual(wanted, entry)));
5435
+ return dropped.length > 0 ? [{ ...op, applied: dropped }] : [];
5436
+ });
5437
+ if (orphanOps.length > 0)
5438
+ reverts.push({ ...file, ops: orphanOps });
5439
+ }
5440
+ if (reverts.length === 0)
5441
+ return plan;
5442
+ return { ...plan, reverts };
5184
5443
  }
5185
- function formatSearchResults(results) {
5186
- if (results.length === 0)
5187
- return "No results found.";
5188
- return results.map((result, index) => {
5189
- const title = result.title?.trim() || result.url;
5190
- const lines = [`${index + 1}. [${escapeBrackets(title)}](${result.url})`];
5191
- if (result.content) {
5192
- lines.push(` ${result.content.replaceAll(`
5193
- `, " ")}`);
5444
+ var HOST_PLANNERS, HOST_VERSION_PROBES;
5445
+ var init_hosts = __esm(() => {
5446
+ init_constants();
5447
+ init_value();
5448
+ init_ownership();
5449
+ init_state();
5450
+ init_codex();
5451
+ init_opencode();
5452
+ init_pi();
5453
+ HOST_PLANNERS = {
5454
+ opencode: planOpenCode,
5455
+ pi: planPi,
5456
+ codex: planCodex
5457
+ };
5458
+ HOST_VERSION_PROBES = {
5459
+ codex: probeCodexVersion
5460
+ };
5461
+ });
5462
+
5463
+ // src/installer/render.ts
5464
+ function renderPlan(plan) {
5465
+ const lines = [];
5466
+ lines.push(`Install plan: ${plan.host} (${plan.scope} scope)`);
5467
+ lines.push(`Tiers: search=${plan.tiers.search}, fetch=${plan.tiers.fetch}`);
5468
+ lines.push("");
5469
+ lines.push("Files:");
5470
+ for (const edit2 of plan.edits) {
5471
+ lines.push(` ${edit2.file}`);
5472
+ if (edit2.format === "rules") {
5473
+ lines.push(" upsert marked rules block");
5474
+ continue;
5194
5475
  }
5195
- if (result.published !== undefined) {
5196
- lines.push(` Published: ${formatPublished(result.published)}`);
5476
+ for (const op of edit2.ops) {
5477
+ if (op.op === "set") {
5478
+ const was = op.previous === undefined ? "(absent)" : preview(op.previous);
5479
+ lines.push(` set ${op.path.join(".")} = ${preview(op.value)} (was ${was})`);
5480
+ } else {
5481
+ const count = (op.entries ?? []).length;
5482
+ const kept = op.existingCount !== undefined ? ` (${op.existingCount} existing kept)` : "";
5483
+ lines.push(` append ${count} entr${count === 1 ? "y" : "ies"} to ${op.path.join(".")}${kept}`);
5484
+ for (const entry of op.entries ?? [])
5485
+ lines.push(` + ${preview(entry)}`);
5486
+ }
5487
+ }
5488
+ }
5489
+ if (plan.reverts && plan.reverts.length > 0) {
5490
+ lines.push("");
5491
+ lines.push("Reverts (artifacts from the previous init that this plan no longer wants):");
5492
+ for (const revert of plan.reverts) {
5493
+ lines.push(` ${revert.file}`);
5494
+ if (revert.format === "rules") {
5495
+ lines.push(" remove rules block");
5496
+ continue;
5497
+ }
5498
+ for (const op of revert.ops) {
5499
+ if (op.op === "set") {
5500
+ lines.push(op.previous === undefined ? ` remove ${op.path.join(".")} (was not set before this install)` : ` restore ${op.path.join(".")} = ${preview(op.previous)}`);
5501
+ } else {
5502
+ const count = Array.isArray(op.applied) ? op.applied.length : 0;
5503
+ lines.push(` remove ${count} appended entr${count === 1 ? "y" : "ies"} from ${op.path.join(".")}`);
5504
+ }
5505
+ }
5197
5506
  }
5198
- return lines.join(`
5199
- `);
5200
- }).join(`
5201
-
5507
+ }
5508
+ if (plan.notes.length > 0) {
5509
+ lines.push("");
5510
+ lines.push("Notes:");
5511
+ for (const note of plan.notes)
5512
+ lines.push(` - ${note}`);
5513
+ }
5514
+ return lines.join(`
5202
5515
  `);
5203
5516
  }
5204
- function toStructuredResult(result) {
5205
- return {
5206
- url: result.url,
5207
- ...result.title ? { title: result.title } : {},
5208
- ...result.content ? { content: result.content } : {},
5209
- ...result.published !== undefined ? { published: result.published } : {}
5210
- };
5211
- }
5212
- function escapeBrackets(value) {
5213
- return value.replaceAll("[", "\\[").replaceAll("]", "\\]");
5214
- }
5215
- function formatPublished(epochMs) {
5216
- return new Date(epochMs).toISOString().slice(0, 10);
5517
+ function preview(value) {
5518
+ const text = JSON.stringify(value) ?? String(value);
5519
+ return text.length > 100 ? `${text.slice(0, 97)}...` : text;
5217
5520
  }
5218
- var init_format2 = __esm(() => {
5219
- init_constants();
5220
- });
5221
5521
 
5222
- // src/core/url.ts
5223
- function parseFetchUrl(value) {
5224
- const input = value.trim();
5225
- if (!input)
5226
- throw new Error("URL must not be empty");
5227
- if (input.length > MAX_URL_CHARS) {
5228
- throw new Error(`URL must be ${MAX_URL_CHARS} characters or fewer`);
5229
- }
5230
- let url;
5231
- try {
5232
- url = new URL(input);
5233
- } catch {
5234
- throw new Error("URL must be an absolute http:// or https:// URL");
5235
- }
5236
- if (url.protocol !== "http:" && url.protocol !== "https:") {
5237
- throw new Error("URL must use http:// or https://");
5238
- }
5239
- if (!url.hostname || !normalizeHostname(url.hostname)) {
5240
- throw new Error("URL must include a host");
5522
+ // src/installer/uninstall.ts
5523
+ function uninstall(input) {
5524
+ return withOperationLock([statePathFor(input)], () => {
5525
+ const record = readRecord(input);
5526
+ if (record === undefined) {
5527
+ throw new Error(`No ${input.host} install is recorded for the ${input.scope} scope.`);
5528
+ }
5529
+ return withOperationLock(record.files.map((file) => file.file), () => uninstallLocked(input, record));
5530
+ });
5531
+ }
5532
+ function uninstallLocked(input, record) {
5533
+ assertFileOwnership(input, record.files);
5534
+ const other = input.scope === "global" ? "project" : "global";
5535
+ const overlap = claimedByOtherScope(input, record.files.map((file) => file.file));
5536
+ if (overlap.length > 0) {
5537
+ throw new Error(`A ${input.host} install is also recorded at the ${other} scope and claims the same file(s): ${overlap.join(", ")}. ` + `Uninstall the ${other}-scope install first so this rollback cannot clobber its entries.`);
5241
5538
  }
5242
- if (url.username || url.password) {
5243
- throw new Error("URL must not contain credentials");
5539
+ const lines = [];
5540
+ for (const file of record.files) {
5541
+ if (file.format !== "rules")
5542
+ continue;
5543
+ const loaded = codecFor("rules", record.host).load(file.file);
5544
+ if (loaded.parseError)
5545
+ throw new Error(`${file.file}: ${loaded.parseError}`);
5244
5546
  }
5245
- return url;
5246
- }
5247
- function normalizeResultUrl(value) {
5248
- if (typeof value !== "string")
5249
- return;
5250
- const input = value.trim();
5251
- if (!input || input.length > MAX_URL_CHARS)
5252
- return;
5253
- try {
5254
- const url = new URL(input);
5255
- if (url.protocol !== "http:" && url.protocol !== "https:")
5256
- return;
5257
- if (!url.hostname || url.username || url.password)
5258
- return;
5259
- return url.href;
5260
- } catch {
5261
- return;
5547
+ for (const file of [...record.files].reverse()) {
5548
+ lines.push(...revertRecordedFile(file, record.host, { label: "", whole: true }));
5262
5549
  }
5550
+ deleteRecord(input);
5551
+ releaseFileOwnership(input, record.files);
5552
+ pruneEmptyDir(stateDir(input, input.scope));
5553
+ lines.push(`removed install record (${input.host}, ${input.scope})`);
5554
+ return lines;
5263
5555
  }
5264
- var init_url = __esm(() => {
5265
- init_constants();
5266
- init_domains();
5556
+ var init_uninstall = __esm(() => {
5557
+ init_formats();
5558
+ init_operation_lock();
5559
+ init_ownership();
5560
+ init_paths();
5561
+ init_revert();
5562
+ init_state();
5267
5563
  });
5268
5564
 
5269
- // src/core/search.ts
5270
- function buildQuery(query, options) {
5271
- const parts = [query.trim()];
5272
- for (const domain of normalizeDomains(options.blockedDomains))
5273
- parts.push(`-site:${domain}`);
5274
- const include = normalizeDomains(options.includeDomains);
5275
- if (include.length)
5276
- parts.push(include.map((domain) => `site:${domain}`).join(" OR "));
5277
- const language = options.language?.trim().replace(/^lang:/i, "");
5278
- if (language)
5279
- parts.push(`lang:${language}`);
5280
- return parts.filter((part) => part.length > 0).join(" ");
5281
- }
5282
- function parsePublished(value) {
5283
- if (typeof value !== "string" || !value.trim())
5284
- return;
5285
- const timestamp = Date.parse(value);
5286
- return Number.isFinite(timestamp) ? timestamp : undefined;
5287
- }
5288
- function processResults(raw, options) {
5289
- const results = [];
5290
- const seen = new Set;
5291
- for (const item of raw) {
5292
- if (results.length >= options.maxResults)
5293
- break;
5294
- if (!item || typeof item !== "object")
5295
- continue;
5296
- const url = normalizeResultUrl(item.url);
5297
- if (!url || seen.has(url))
5565
+ // src/installer/cli.ts
5566
+ var exports_cli = {};
5567
+ __export(exports_cli, {
5568
+ runInstallerCli: () => runInstallerCli,
5569
+ resolveConfigHome: () => resolveConfigHome,
5570
+ exitCodeForError: () => exitCodeForError
5571
+ });
5572
+ import { homedir as homedir2 } from "node:os";
5573
+ import { resolve as resolve2 } from "node:path";
5574
+ function parseFlags(args) {
5575
+ const values = new Map;
5576
+ const booleans = new Set;
5577
+ const problems = [];
5578
+ for (let i = 0;i < args.length; i += 1) {
5579
+ const arg = args[i];
5580
+ if (!arg.startsWith("--")) {
5581
+ problems.push(`unexpected argument "${arg}" (flags only)`);
5298
5582
  continue;
5299
- const rerank = item.rerank_score;
5300
- if (typeof rerank === "number" && Number.isFinite(rerank)) {
5301
- if (rerank < options.minRerank)
5583
+ }
5584
+ const eq = arg.indexOf("=");
5585
+ const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
5586
+ if (BOOLEAN_FLAGS.has(name)) {
5587
+ if (eq !== -1) {
5588
+ problems.push(`--${name} does not accept a value; use --${name} to enable it or omit it`);
5302
5589
  continue;
5303
- } else if (options.minRerank > 0) {
5590
+ }
5591
+ if (booleans.has(name)) {
5592
+ problems.push(`--${name} was given more than once`);
5593
+ continue;
5594
+ }
5595
+ booleans.add(name);
5304
5596
  continue;
5305
5597
  }
5306
- const authority = item.authority;
5307
- const knownAuthority = typeof authority === "number" && Number.isFinite(authority) && authority >= 0;
5308
- if (knownAuthority) {
5309
- if (authority < options.minAuthority)
5310
- continue;
5311
- } else if (!options.allowUnknownAuthority) {
5598
+ if (!VALUE_FLAGS.has(name)) {
5599
+ problems.push(`unknown flag --${name}`);
5312
5600
  continue;
5313
5601
  }
5314
- seen.add(url);
5315
- const content = truncate(optionalText2(item.summary) ?? optionalText2(item.snippet) ?? "", options.maxSummaryChars);
5316
- const published = parsePublished(item.date);
5317
- const title = optionalText2(item.title);
5318
- results.push({
5319
- url,
5320
- ...title ? { title } : {},
5321
- ...content ? { content } : {},
5322
- ...published !== undefined ? { published } : {}
5323
- });
5602
+ if (values.has(name)) {
5603
+ problems.push(`--${name} was given more than once`);
5604
+ continue;
5605
+ }
5606
+ if (eq !== -1) {
5607
+ values.set(name, arg.slice(eq + 1));
5608
+ continue;
5609
+ }
5610
+ const next = args[i + 1];
5611
+ if (next === undefined || next.startsWith("--")) {
5612
+ problems.push(`--${name} requires a value`);
5613
+ continue;
5614
+ }
5615
+ values.set(name, next);
5616
+ i += 1;
5324
5617
  }
5325
- return results;
5326
- }
5327
- function optionalText2(value) {
5328
- if (typeof value !== "string")
5329
- return;
5330
- const trimmed = value.trim();
5331
- return trimmed ? trimmed : undefined;
5618
+ return { values, booleans, problems };
5332
5619
  }
5333
- var init_search = __esm(() => {
5334
- init_domains();
5335
- init_format2();
5336
- init_url();
5337
- });
5338
-
5339
- // src/core/transport.ts
5340
- async function postJson(endpoint, body, operation2, opts) {
5341
- const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
5342
- const attempts = opts.retry.maxRetries + 1;
5343
- let lastError;
5344
- for (let attempt = 0;attempt < attempts; attempt++) {
5620
+ async function runInstallerCli(argv, io = {}) {
5621
+ const out = io.out ?? ((line) => console.log(line));
5622
+ const err = io.err ?? ((line) => console.error(line));
5623
+ const [command, ...rest] = argv;
5624
+ if (command === "version" || command === "--version") {
5625
+ out(TOOL_VERSION);
5626
+ return 0;
5627
+ }
5628
+ if (command === undefined) {
5629
+ err(USAGE);
5630
+ return EXIT_USAGE2;
5631
+ }
5632
+ if (command === "help" || command === "--help") {
5633
+ out(USAGE);
5634
+ return 0;
5635
+ }
5636
+ const flags = parseFlags(rest);
5637
+ if (flags.problems.length > 0) {
5638
+ for (const problem of flags.problems)
5639
+ err(`error: ${problem}`);
5640
+ err(`
5641
+ ${USAGE}`);
5642
+ return EXIT_USAGE2;
5643
+ }
5644
+ const cwd = resolve2(flags.values.get("cwd") ?? process.cwd());
5645
+ const home = process.env.HOME ?? homedir2();
5646
+ const platform = io.platform ?? process.platform;
5647
+ const roots = { home, cwd, platform };
5648
+ const configHome2 = resolveConfigHome(process.env, home, platform);
5649
+ if (command === "list") {
5650
+ let records;
5345
5651
  try {
5346
- return await requestOnce(endpoint, body, operation2, opts, fetchImpl);
5652
+ records = listRecords({ ...roots, configHome: configHome2 });
5347
5653
  } catch (error) {
5348
- lastError = error;
5349
- if (!(error instanceof DeepSeekApiError) || !error.retryable || attempt === attempts - 1) {
5350
- throw error;
5351
- }
5352
- await sleep(retryDelay(error.retryAfterMs, opts.retry.baseDelayMs, attempt), opts.signal);
5654
+ err(error instanceof Error ? error.message : String(error));
5655
+ return 1;
5353
5656
  }
5354
- }
5355
- throw lastError;
5356
- }
5357
- async function requestOnce(endpoint, body, operation2, opts, fetchImpl) {
5358
- return fetchWithTimeout(endpoint, {
5359
- method: "POST",
5360
- headers: {
5361
- Authorization: `Bearer ${opts.auth.apiKey}`,
5362
- "Content-Type": "application/json"
5363
- },
5364
- body: JSON.stringify(body)
5365
- }, opts.signal, opts.timeoutMs, operation2, fetchImpl, async (response) => {
5366
- if (!response.ok) {
5367
- const text2 = await readBoundedText(response, MAX_ERROR_BODY_CHARS);
5368
- throw new DeepSeekApiError({
5369
- operation: operation2,
5370
- status: response.status,
5371
- body: text2,
5372
- retryAfterMs: parseRetryAfter(response.headers.get("retry-after"))
5373
- });
5657
+ if (records.length === 0) {
5658
+ out("No installs recorded.");
5659
+ return 0;
5374
5660
  }
5375
- const text = await readResponseText(response, MAX_RESPONSE_BYTES, operation2);
5376
- if (!text.trim())
5377
- throw new Error(`${operation2} returned an empty response body`);
5661
+ if (readingLegacyGlobalRecords({ ...roots, configHome: configHome2 })) {
5662
+ out(`Global install records are being read from the legacy ${legacyGlobalStateDir(roots)} ` + "(written before the Windows config home moved to %APPDATA%).");
5663
+ }
5664
+ for (const record of records) {
5665
+ const by = record.installerVersion ? ` by v${record.installerVersion}` : "";
5666
+ out(`${record.host} (${record.scope}) — search=${record.tiers.search}, fetch=${record.tiers.fetch}, installed ${record.createdAt}${by}`);
5667
+ for (const file of record.files)
5668
+ out(` ${file.created ? "created" : "modified"} ${file.file}`);
5669
+ }
5670
+ return 0;
5671
+ }
5672
+ if (command === "config") {
5673
+ return runConfigCommand(flags.values.get("search"), { out, err });
5674
+ }
5675
+ if (command === "uninstall") {
5676
+ const required2 = requireInput(flags, cwd, home, configHome2, platform, false);
5677
+ if (!required2.ok)
5678
+ return usageError(required2.problems, err);
5378
5679
  try {
5379
- return JSON.parse(text);
5380
- } catch {
5381
- throw new Error(`${operation2} returned invalid JSON: ${truncate(redactSecrets(text), 500)}`);
5680
+ for (const line of uninstall(required2.input))
5681
+ out(line);
5682
+ return 0;
5683
+ } catch (error) {
5684
+ err(error instanceof Error ? error.message : String(error));
5685
+ return 1;
5382
5686
  }
5383
- });
5384
- }
5385
- async function fetchWithTimeout(endpoint, init, signal, timeoutMs, operation2, fetchImpl, handleResponse) {
5386
- const controller = new AbortController;
5387
- let timedOut = false;
5388
- const forwardAbort = () => controller.abort(signal.reason);
5389
- if (signal.aborted)
5390
- forwardAbort();
5391
- else
5392
- signal.addEventListener("abort", forwardAbort, { once: true });
5393
- const timer = signal.aborted ? undefined : setTimeout(() => {
5394
- timedOut = true;
5395
- controller.abort(new Error("timeout"));
5396
- }, timeoutMs);
5687
+ }
5688
+ if (command !== "init") {
5689
+ err(`Unknown command "${command}".
5690
+
5691
+ ${USAGE}`);
5692
+ return EXIT_USAGE2;
5693
+ }
5694
+ const required = requireInput(flags, cwd, home, configHome2, platform, true);
5695
+ if (!required.ok)
5696
+ return usageError(required.problems, err);
5697
+ const { input } = required;
5698
+ const probe = HOST_VERSION_PROBES[input.host];
5699
+ const hostVersion = probe?.(err);
5700
+ const plan = planForHost(input.host, hostVersion === undefined ? input : { ...input, hostVersion });
5701
+ if (plan.errors.length > 0) {
5702
+ for (const error of plan.errors)
5703
+ err(`error: ${error.message}`);
5704
+ err("Nothing was written.");
5705
+ return 1;
5706
+ }
5707
+ out(renderPlan(plan));
5708
+ if (!flags.booleans.has("apply")) {
5709
+ out(`
5710
+ Plan only — re-run with --apply to write these changes.`);
5711
+ return 0;
5712
+ }
5397
5713
  try {
5398
- const response = await fetchImpl(endpoint, { ...init, signal: controller.signal });
5399
- return await handleResponse(response);
5714
+ const result = applyPlan(plan, input);
5715
+ for (const line of result.lines)
5716
+ out(line);
5717
+ return 0;
5400
5718
  } catch (error) {
5401
- if (timedOut)
5402
- throw new Error(formatTimeoutError(operation2, timeoutMs));
5403
- if (signal.aborted)
5404
- throw abortReason(signal, operation2);
5405
- throw error;
5406
- } finally {
5407
- if (timer !== undefined)
5408
- clearTimeout(timer);
5409
- signal.removeEventListener("abort", forwardAbort);
5410
- }
5411
- }
5412
- function parseRetryAfter(value) {
5413
- if (!value)
5414
- return;
5415
- const trimmed = value.trim();
5416
- if (!trimmed)
5417
- return;
5418
- if (/^\d+$/.test(trimmed)) {
5419
- return Math.min(MAX_RETRY_DELAY_MS, Number(trimmed) * 1000);
5719
+ err(error instanceof Error ? error.message : String(error));
5720
+ return exitCodeForError(error);
5420
5721
  }
5421
- const timestamp = Date.parse(trimmed);
5422
- if (!Number.isFinite(timestamp))
5423
- return;
5424
- return Math.min(MAX_RETRY_DELAY_MS, Math.max(0, timestamp - Date.now()));
5425
- }
5426
- function retryDelay(retryAfterMs, baseDelayMs, attempt) {
5427
- if (retryAfterMs !== undefined)
5428
- return retryAfterMs;
5429
- return Math.min(MAX_RETRY_DELAY_MS, baseDelayMs * 2 ** attempt);
5430
5722
  }
5431
- function sleep(ms, signal) {
5432
- if (ms <= 0)
5433
- return Promise.resolve();
5434
- return new Promise((resolve3, reject) => {
5435
- const timer = setTimeout(() => {
5436
- signal.removeEventListener("abort", onAbort);
5437
- resolve3();
5438
- }, ms);
5439
- const onAbort = () => {
5440
- clearTimeout(timer);
5441
- reject(abortReason(signal, "DeepSeek request"));
5442
- };
5443
- if (signal.aborted) {
5444
- clearTimeout(timer);
5445
- reject(abortReason(signal, "DeepSeek request"));
5446
- return;
5447
- }
5448
- signal.addEventListener("abort", onAbort, { once: true });
5449
- });
5723
+ function exitCodeForError(error) {
5724
+ return error instanceof ApplyError && error.status === "recovery_required" ? EXIT_RECOVERY : EXIT_FAILURE;
5450
5725
  }
5451
- function abortReason(signal, operation2) {
5452
- return signal.reason instanceof Error ? signal.reason : new Error(`${operation2} request aborted`);
5726
+ function usageError(problems, err) {
5727
+ for (const problem of problems)
5728
+ err(`error: ${problem}`);
5729
+ err(`
5730
+ ${USAGE}`);
5731
+ return EXIT_USAGE2;
5453
5732
  }
5454
- async function readBoundedText(response, maxChars) {
5455
- if (!response.body)
5456
- return truncate(await response.text(), maxChars + 1);
5457
- const reader = response.body.getReader();
5458
- const decoder = new TextDecoder;
5459
- const limit = maxChars + 1;
5460
- let text = "";
5461
- let chars = 0;
5462
- try {
5463
- while (chars < limit) {
5464
- const { done, value } = await reader.read();
5465
- if (done)
5466
- break;
5467
- const chunk = decoder.decode(value, { stream: true });
5468
- text += chunk;
5469
- chars += Array.from(chunk).length;
5470
- }
5471
- text += decoder.decode();
5472
- } finally {
5473
- await reader.cancel().catch(() => {
5474
- return;
5475
- });
5476
- reader.releaseLock();
5477
- }
5478
- return truncate(text, limit);
5733
+ function resolveConfigHome(env, home, platform = process.platform) {
5734
+ const xdgTrusted = env.XDG_CONFIG_HOME !== undefined && env.XDG_CONFIG_HOME !== "" && home === (env.HOME ?? "");
5735
+ return userConfigHome({ env: xdgTrusted ? env : { ...env, XDG_CONFIG_HOME: undefined }, home, platform });
5479
5736
  }
5480
- async function readResponseText(response, maxBytes, operation2) {
5481
- if (!response.body) {
5482
- const text2 = await response.text();
5483
- if (new TextEncoder().encode(text2).byteLength > maxBytes) {
5484
- throw new Error(`${operation2} response exceeded ${maxBytes} bytes`);
5485
- }
5486
- return text2;
5487
- }
5488
- const reader = response.body.getReader();
5489
- const decoder = new TextDecoder;
5490
- let text = "";
5491
- let bytes = 0;
5492
- try {
5493
- while (true) {
5494
- const { done, value } = await reader.read();
5495
- if (done)
5496
- break;
5497
- bytes += value.byteLength;
5498
- if (bytes > maxBytes) {
5499
- throw new Error(`${operation2} response exceeded ${maxBytes} bytes`);
5500
- }
5501
- text += decoder.decode(value, { stream: true });
5737
+ function requireInput(flags, cwd, home, configHome2, platform, needsTiers) {
5738
+ const problems = [];
5739
+ const host = flags.values.get("host");
5740
+ const scope = flags.values.get("scope");
5741
+ const search = needsTiers ? flags.values.get("search") ?? "" : "optional";
5742
+ const fetch = needsTiers ? flags.values.get("fetch") ?? "" : "optional";
5743
+ const path = flags.values.get("path");
5744
+ if (host === undefined)
5745
+ problems.push(`--host is required (one of: ${HOSTS.join(", ")})`);
5746
+ else if (!HOSTS.includes(host))
5747
+ problems.push(`invalid --host value "${host}" (one of: ${HOSTS.join(", ")})`);
5748
+ if (scope === undefined)
5749
+ problems.push(`--scope is required (one of: ${SCOPES.join(", ")})`);
5750
+ else if (!SCOPES.includes(scope))
5751
+ problems.push(`invalid --scope value "${scope}" (one of: ${SCOPES.join(", ")})`);
5752
+ if (path !== undefined) {
5753
+ if (host !== "pi") {
5754
+ problems.push(`--path is only supported for host pi (${host ?? "no host"} has a single integration path)`);
5755
+ } else if (!PATH_CHOICES.includes(path)) {
5756
+ problems.push(`invalid --path value "${path}" (one of: ${PATH_CHOICES.join(", ")})`);
5502
5757
  }
5503
- text += decoder.decode();
5504
- } finally {
5505
- await reader.cancel().catch(() => {
5506
- return;
5507
- });
5508
- reader.releaseLock();
5509
5758
  }
5510
- return text;
5511
- }
5512
- var DeepSeekApiError;
5513
- var init_transport = __esm(() => {
5514
- init_constants();
5515
- init_format2();
5516
- DeepSeekApiError = class DeepSeekApiError extends Error {
5517
- operation;
5518
- status;
5519
- body;
5520
- retryable;
5521
- retryAfterMs;
5522
- constructor(input) {
5523
- const body = redactSecrets(input.body);
5524
- super(formatApiError(input.operation, input.status, body));
5525
- this.name = "DeepSeekApiError";
5526
- this.operation = input.operation;
5527
- this.status = input.status;
5528
- this.body = body;
5529
- this.retryable = input.status === 408 || input.status === 425 || input.status === 429 || input.status >= 500 && input.status <= 599;
5530
- this.retryAfterMs = input.retryAfterMs;
5759
+ if (needsTiers) {
5760
+ if (!TIERS.includes(search)) {
5761
+ problems.push(flags.values.has("search") ? `invalid --search value "${search}" (one of: ${TIERS.join(", ")})` : `--search is required (one of: ${TIERS.join(", ")})`);
5762
+ }
5763
+ if (!TIERS.includes(fetch)) {
5764
+ problems.push(flags.values.has("fetch") ? `invalid --fetch value "${fetch}" (one of: ${TIERS.join(", ")})` : `--fetch is required (one of: ${TIERS.join(", ")})`);
5765
+ }
5766
+ }
5767
+ if (home === "")
5768
+ problems.push("HOME is not set and the user home cannot be resolved; cannot proceed");
5769
+ if (problems.length > 0)
5770
+ return { ok: false, problems };
5771
+ const packageRef = flags.values.get("package") ?? "deepseek-web-retrieval";
5772
+ return {
5773
+ ok: true,
5774
+ input: {
5775
+ host,
5776
+ scope,
5777
+ search,
5778
+ fetch,
5779
+ packageRef: flags.booleans.has("pin") ? pinPackageRef(packageRef, TOOL_VERSION) : packageRef,
5780
+ home,
5781
+ cwd,
5782
+ configHome: configHome2,
5783
+ platform,
5784
+ ...path !== undefined ? { path } : {}
5531
5785
  }
5532
5786
  };
5787
+ }
5788
+ var HOSTS, HOST_CHOICES, SCOPES, TIERS, EXIT_FAILURE = 1, EXIT_USAGE2 = 2, EXIT_RECOVERY = 3, USAGE, VALUE_FLAGS, BOOLEAN_FLAGS, PATH_CHOICES;
5789
+ var init_cli = __esm(() => {
5790
+ init_config_file();
5791
+ init_version();
5792
+ init_apply();
5793
+ init_config_command();
5794
+ init_hosts();
5795
+ init_ownership();
5796
+ init_state();
5797
+ init_uninstall();
5798
+ HOSTS = Object.keys(HOST_PLANNERS);
5799
+ HOST_CHOICES = `<${HOSTS.join("|")}>`;
5800
+ SCOPES = ["project", "global"];
5801
+ TIERS = ["optional", "preferred", "forced", "off"];
5802
+ USAGE = `Usage:
5803
+ deepseek-web-retrieval init --host ${HOST_CHOICES} --scope <project|global> --search <optional|preferred|forced|off> --fetch <optional|preferred|forced|off> [--path <extension|mcp>] [--package <npm ref>] [--pin] [--cwd <dir>] [--apply]
5804
+ deepseek-web-retrieval uninstall --host ${HOST_CHOICES} --scope <project|global> [--cwd <dir>]
5805
+ deepseek-web-retrieval list [--cwd <dir>]
5806
+ deepseek-web-retrieval config [--search <query>]
5807
+ deepseek-web-retrieval version
5808
+
5809
+ init prints the full plan (every file, old value → new value) and writes nothing
5810
+ until --apply is passed. uninstall restores what the plan applied. --path picks
5811
+ the integration mechanism for hosts with more than one (Pi: extension by
5812
+ default, mcp for the stdio MCP server). --package overrides the package ref
5813
+ written into host config; the Pi extension path turns it into the packages
5814
+ source (a bare name is prefixed with npm:, a ref that already starts with npm:
5815
+ is written as-is). --pin appends the running CLI's version to the package ref
5816
+ (a ref already ending in a version keeps it), so hosts resolve that exact
5817
+ release instead of the latest publish; re-run init --pin to move the pin.
5818
+
5819
+ config prints the effective configuration — every knob with its value and its
5820
+ source (default, shared file, or environment), resolved the way the MCP server
5821
+ resolves it — and exits 1 when the config file or the DEEPSEEK_* environment
5822
+ has problems (unknown or rejected keys, unparseable JSON, set-but-unusable
5823
+ variable values; a missing file is fine). config --search <query>
5824
+ runs one billed search through that configuration to verify the key, config,
5825
+ and network end to end; it exits 1 when the key is missing or the search fails.
5826
+
5827
+ Exit codes: 0 success; 1 refused or failed with nothing written (a failed apply
5828
+ is fully rolled back); 2 invalid command line; 3 recovery required — a failed
5829
+ apply could not roll back completely, follow the reported guidance before
5830
+ re-running.`;
5831
+ VALUE_FLAGS = new Set(["host", "scope", "search", "fetch", "path", "package", "cwd"]);
5832
+ BOOLEAN_FLAGS = new Set(["apply", "pin"]);
5833
+ PATH_CHOICES = ["extension", "mcp"];
5533
5834
  });
5534
5835
 
5535
- // src/core/client.ts
5536
- function effectiveTimeout(configuredMs, perCallMs) {
5537
- return perCallMs === undefined ? configuredMs : Math.min(configuredMs, perCallMs);
5538
- }
5539
- async function searchWeb(query, options, request) {
5540
- const trimmed = query.trim();
5541
- if (!trimmed)
5542
- throw new Error("DeepSeek search query must not be empty");
5543
- if (Array.from(trimmed).length > MAX_QUERY_CHARS) {
5544
- throw new Error(`DeepSeek search query must be ${MAX_QUERY_CHARS} characters or fewer`);
5545
- }
5546
- const builtQuery = buildQuery(trimmed, options);
5547
- const builtQueryLength = Array.from(builtQuery).length;
5548
- if (builtQueryLength > MAX_QUERY_CHARS) {
5549
- throw new Error(`DeepSeek search query must be ${MAX_QUERY_CHARS} characters or fewer after applying ` + `blockedDomains, includeDomains, and language ` + `(built query is ${builtQueryLength} characters)`);
5550
- }
5551
- const timeout = effectiveTimeout(options.timeoutMs, request.timeoutMs);
5552
- const payload = await postJson(SEARCH_ENDPOINT, {
5553
- query: builtQuery,
5554
- count: options.count,
5555
- need_content: false
5556
- }, "DeepSeek Search", { ...request, timeoutMs: timeout });
5557
- if (!Array.isArray(payload.results)) {
5558
- throw new Error("DeepSeek Search returned a response without a results array");
5559
- }
5560
- return processResults(payload.results, options);
5836
+ // src/mcp/auth.ts
5837
+ function requireApiKey(env) {
5838
+ const apiKey = apiKeyFromEnv(env);
5839
+ if (!apiKey)
5840
+ throw new Error(MISSING_API_KEY_MESSAGE);
5841
+ return apiKey;
5561
5842
  }
5562
- async function fetchPage(url, options, request) {
5563
- const target = parseFetchUrl(url.href);
5564
- assertFetchHostPolicy(target, options);
5565
- const timeout = effectiveTimeout(options.timeoutMs, request.timeoutMs);
5566
- const payload = await postJson(FETCH_ENDPOINT, { url: target.href }, "DeepSeek Fetch", {
5567
- ...request,
5568
- timeoutMs: timeout
5569
- });
5570
- const title = typeof payload.title === "string" ? payload.title.trim() : "";
5571
- const content = typeof payload.content === "string" ? payload.content : "";
5572
- if (!content.trim()) {
5573
- throw new Error("DeepSeek Fetch returned no page content (the page may be empty or unavailable)");
5843
+ var init_auth2 = __esm(() => {
5844
+ init_auth();
5845
+ });
5846
+
5847
+ // src/mcp/client.ts
5848
+ import { CLIENT_INFO_META_KEY } from "@modelcontextprotocol/server";
5849
+ function clientNameOf(server, ctx) {
5850
+ const envelope = ctx.mcpReq.envelope;
5851
+ const name = envelope?.[CLIENT_INFO_META_KEY];
5852
+ if (typeof name === "object" && name !== null && "name" in name && typeof name.name === "string") {
5853
+ return name.name;
5574
5854
  }
5575
- return { url: target.href, title, content };
5855
+ return server.server.getClientVersion()?.name;
5576
5856
  }
5577
- async function fetchDocument(url, options, request) {
5578
- if (typeof url !== "string" && !(url instanceof URL))
5579
- throw new Error('"url" must be a string or URL');
5580
- const page = await fetchPage(url instanceof URL ? url : parseFetchUrl(url), options, request);
5581
- const formatted = formatFetchedContent(page.title, page.content, options.maxChars);
5582
- return {
5583
- url: page.url,
5584
- title: page.title,
5585
- content: formatted.content,
5586
- truncated: formatted.truncated
5587
- };
5857
+ function isJsonReplacingClient(name) {
5858
+ return name !== undefined && JSON_REPLACING_CLIENT_NAMES.has(name);
5588
5859
  }
5589
- function createRetrievalClient(dependencies = {}) {
5590
- const bind = (request) => ({ ...request, ...dependencies });
5591
- return {
5592
- searchWeb: (query, options, request) => searchWeb(query, options, bind(request)),
5593
- fetchPage: (url, options, request) => fetchPage(url, options, bind(request)),
5594
- fetchDocument: (url, options, request) => fetchDocument(url, options, bind(request))
5595
- };
5860
+ function omitStructuredContent(server, ctx) {
5861
+ return isJsonReplacingClient(clientNameOf(server, ctx));
5596
5862
  }
5597
- var retrievalClient;
5863
+ var JSON_REPLACING_CLIENT_NAMES;
5598
5864
  var init_client2 = __esm(() => {
5599
- init_constants();
5600
- init_domains();
5601
- init_format2();
5602
- init_search();
5603
- init_transport();
5604
- init_url();
5605
- init_transport();
5606
- retrievalClient = createRetrievalClient();
5865
+ JSON_REPLACING_CLIENT_NAMES = new Set(["codex-mcp-client"]);
5866
+ });
5867
+
5868
+ // package.json
5869
+ var package_default;
5870
+ var init_package = __esm(() => {
5871
+ package_default = {
5872
+ $schema: "https://json.schemastore.org/package.json",
5873
+ name: "deepseek-web-retrieval",
5874
+ version: "0.7.0",
5875
+ description: "Token-efficient DeepSeek Search and Fetch for coding agents, starting with OpenCode v2.",
5876
+ type: "module",
5877
+ license: "MIT",
5878
+ repository: {
5879
+ type: "git",
5880
+ url: "git+https://github.com/gwokhou/deepseek-web-retrieval.git"
5881
+ },
5882
+ homepage: "https://github.com/gwokhou/deepseek-web-retrieval#readme",
5883
+ bugs: "https://github.com/gwokhou/deepseek-web-retrieval/issues",
5884
+ keywords: [
5885
+ "opencode",
5886
+ "opencode-plugin",
5887
+ "pi",
5888
+ "pi-extension",
5889
+ "deepseek",
5890
+ "websearch",
5891
+ "webfetch",
5892
+ "coding-agent",
5893
+ "mcp"
5894
+ ],
5895
+ exports: {
5896
+ ".": "./index.ts",
5897
+ "./core": "./src/core/index.ts",
5898
+ "./mcp": "./src/mcp/server.ts",
5899
+ "./pi": "./src/pi/extension.ts"
5900
+ },
5901
+ pi: {
5902
+ extensions: [
5903
+ "./src/pi/extension.ts"
5904
+ ]
5905
+ },
5906
+ bin: {
5907
+ "deepseek-web-retrieval": "dist/cli.js"
5908
+ },
5909
+ files: [
5910
+ "index.ts",
5911
+ "src",
5912
+ "dist",
5913
+ "docs",
5914
+ "README.md",
5915
+ "LICENSE",
5916
+ "CHANGELOG.md",
5917
+ "examples"
5918
+ ],
5919
+ scripts: {
5920
+ lint: "biome check --error-on-warnings .",
5921
+ clean: "bun run scripts/clean.ts",
5922
+ "lint:ci": "biome ci --error-on-warnings .",
5923
+ "lint:fix": "biome check --write --error-on-warnings .",
5924
+ format: "biome format --write .",
5925
+ typecheck: "tsc --noEmit",
5926
+ build: "bun build src/mcp/cli.ts --target=node --format=esm --outdir=dist --external @modelcontextprotocol/server --external @modelcontextprotocol/server/stdio --external zod --external zod/v4",
5927
+ prepublishOnly: "bun run check:release",
5928
+ test: "bun test",
5929
+ "test:package": "node scripts/test-package.mjs",
5930
+ "test:e2e:keyless": "bun run test:e2e pi pi-extension installer reinit upgrade pkg capability-off",
5931
+ "check:release": "bun run check && bun run test:package && bun run test:e2e:keyless",
5932
+ "test:e2e": "bun run test/e2e/run.ts",
5933
+ "docs:matrix": "bun run scripts/render-matrix.ts",
5934
+ "test:coverage": "bun test --coverage",
5935
+ check: "bun run lint && bun run typecheck && bun run docs:matrix --check && bun run build && bun test"
5936
+ },
5937
+ peerDependencies: {
5938
+ "@earendil-works/pi-ai": "^1.3.0",
5939
+ "@earendil-works/pi-coding-agent": "^1.3.0",
5940
+ "@opencode/plugin": "^2.0.32"
5941
+ },
5942
+ peerDependenciesMeta: {
5943
+ "@earendil-works/pi-ai": {
5944
+ optional: true
5945
+ },
5946
+ "@earendil-works/pi-coding-agent": {
5947
+ optional: true
5948
+ },
5949
+ "@opencode/plugin": {
5950
+ optional: true
5951
+ }
5952
+ },
5953
+ devDependencies: {
5954
+ "@biomejs/biome": "2.5.15",
5955
+ "@earendil-works/pi-ai": "1.3.0",
5956
+ "@earendil-works/pi-coding-agent": "1.3.0",
5957
+ "@modelcontextprotocol/client": "^2.3.1",
5958
+ "@opencode/plugin": "2.0.32",
5959
+ "@types/bun": "1.4.0",
5960
+ "@types/node": "^26.6.5",
5961
+ typescript: "5.9.3"
5962
+ },
5963
+ engines: {
5964
+ bun: ">=1.3.0",
5965
+ node: ">=20"
5966
+ },
5967
+ dependencies: {
5968
+ "@modelcontextprotocol/server": "^2.3.1",
5969
+ "jsonc-parser": "^3.3.1",
5970
+ "smol-toml": "^1.9.1",
5971
+ zod: "^4"
5972
+ }
5973
+ };
5607
5974
  });
5608
5975
 
5609
5976
  // src/core/descriptions.ts
5610
- var FETCH_SERVICE_LIMITS = "DeepSeek does not render JavaScript and cannot reach private networks; PDFs, images, and other binary files are unsupported.", FETCH_OUTPUT_TRUNCATED = "Output is truncated to the configured size.", SEARCH_RANKED_FILTERED = "Results are ranked by relevance and source authority, deduplicated by URL, and capped at the configured maximum.", SEARCH_EMPTY_IS_NORMAL = "An empty result list is normal, not an error.", SEARCH_QUERY_OPERATORS = "Use site:/-site: operators in the query to include or exclude domains; the full query must stay within 128 characters.", SEARCH_TOOL_DESCRIPTION, FETCH_TOOL_DESCRIPTION, SEARCH_QUERY_PARAMETER = "Search query, 128 characters or fewer including operators (site:, -site:, quoted phrases, lang:).", FETCH_URL_PARAMETER = "Absolute http:// or https:// URL to fetch. Credentials are rejected.";
5977
+ var FETCH_SERVICE_LIMITS = "DeepSeek does not render JavaScript and cannot reach private networks; PDFs, images, and other binary files are unsupported.", FETCH_OUTPUT_TRUNCATED = "Output is truncated to the configured size.", SEARCH_RANKED_FILTERED = "Results are ranked by relevance and source authority, deduplicated by URL, and capped at the configured maximum.", SEARCH_EMPTY_IS_NORMAL = "An empty result list is normal, not an error.", SEARCH_QUERY_OPERATORS = "Use site:/-site: operators in the query to include or exclude domains, and after:/before: with a year or date (e.g. after:2025-06-01) to filter by publish time; the full query must stay within 128 characters.", SEARCH_TOOL_DESCRIPTION, FETCH_TOOL_DESCRIPTION, SEARCH_QUERY_PARAMETER = "Search query, 128 characters or fewer including operators (site:, -site:, quoted phrases, lang:, after:, before:).", SEARCH_ORI_QUESTION_PARAMETER, FETCH_URL_PARAMETER = "Absolute http:// or https:// URL to fetch. Credentials are rejected.";
5611
5978
  var init_descriptions = __esm(() => {
5612
5979
  SEARCH_TOOL_DESCRIPTION = "Search the web with DeepSeek's in-house search engine and return a short, filtered result " + "list (title, URL, summary). " + `${SEARCH_RANKED_FILTERED} ` + `${SEARCH_EMPTY_IS_NORMAL} ` + `${SEARCH_QUERY_OPERATORS} ` + "To read a full page, pass a result URL to the deepseek_fetch tool.";
5613
5980
  FETCH_TOOL_DESCRIPTION = "Fetch one web page as clean Markdown through DeepSeek's Fetch API. " + `${FETCH_SERVICE_LIMITS} ` + `${FETCH_OUTPUT_TRUNCATED}`;
5981
+ SEARCH_ORI_QUESTION_PARAMETER = "The user's original question or task that triggered this search, in the user's own words rather than a " + "reformulated query. Optional; 1-128 characters, and longer values are truncated.";
5614
5982
  });
5615
5983
 
5616
5984
  // src/mcp/server.ts
@@ -5624,10 +5992,13 @@ function createDeepSeekServer(config, env = process.env, client = retrievalClien
5624
5992
  description: SEARCH_TOOL_DESCRIPTION,
5625
5993
  inputSchema: SEARCH_INPUT,
5626
5994
  annotations: { readOnlyHint: true }
5627
- }, async ({ query }, ctx) => {
5995
+ }, async ({ query, original_question }, ctx) => {
5628
5996
  try {
5629
5997
  const request = requestContext(config, env, ctx.mcpReq.signal);
5630
- const results = await client.searchWeb(query, config.search, request);
5998
+ const results = await client.searchWeb(query, config.search, {
5999
+ ...request,
6000
+ oriQuestion: original_question
6001
+ });
5631
6002
  return callResult(server, ctx, formatSearchResults(results), {
5632
6003
  results: results.map(toStructuredResult)
5633
6004
  });
@@ -5679,14 +6050,15 @@ function toErrorResult(error) {
5679
6050
  var MCP_SERVER_NAME = "deepseek-web-retrieval", SEARCH_INPUT, FETCH_INPUT;
5680
6051
  var init_server = __esm(() => {
5681
6052
  init_package();
5682
- init_client2();
6053
+ init_client();
5683
6054
  init_constants();
5684
6055
  init_descriptions();
5685
6056
  init_format2();
5686
6057
  init_auth2();
5687
- init_client();
6058
+ init_client2();
5688
6059
  SEARCH_INPUT = z2.object({
5689
- query: z2.string().min(1).describe(SEARCH_QUERY_PARAMETER)
6060
+ query: z2.string().min(1).describe(SEARCH_QUERY_PARAMETER),
6061
+ original_question: z2.string().optional().describe(SEARCH_ORI_QUESTION_PARAMETER)
5690
6062
  });
5691
6063
  FETCH_INPUT = z2.object({
5692
6064
  url: z2.string().min(1).describe(FETCH_URL_PARAMETER)
@@ -5705,7 +6077,7 @@ function serveMcp() {
5705
6077
  console.error(MISSING_API_KEY_MESSAGE);
5706
6078
  process.exit(1);
5707
6079
  }
5708
- const config = resolveEnvOptions(env);
6080
+ const config = resolveEnvOptions(env, sharedFileOptions({ env }));
5709
6081
  const precheck = servePrecheck(config);
5710
6082
  if (precheck) {
5711
6083
  console.error(precheck);
@@ -5726,14 +6098,19 @@ function serveMcp() {
5726
6098
  config.fetch.enabled ? `fetch (max ${config.fetch.maxChars} chars)` : null
5727
6099
  ].filter(Boolean).join(", ");
5728
6100
  console.error(`deepseek-web-retrieval MCP server on stdio (${tools})`);
6101
+ const deviations = configDeviations(config);
6102
+ if (deviations)
6103
+ console.error(`config: ${deviations}`);
5729
6104
  process.on("SIGINT", () => void handle.close());
5730
6105
  process.on("SIGTERM", () => void handle.close());
5731
6106
  }
5732
6107
  var init_serve = __esm(() => {
5733
6108
  init_auth();
6109
+ init_config_file();
6110
+ init_config_summary();
5734
6111
  init_env();
5735
6112
  init_auth2();
5736
- init_client();
6113
+ init_client2();
5737
6114
  init_server();
5738
6115
  });
5739
6116