deepseek-web-retrieval 0.7.0 → 0.8.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.
@@ -0,0 +1,325 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { API_KEY_ENV } from "../../core/constants";
4
+ import { FORCED_COST_NOTE, othersStayRegisteredNote, replacingExistingEntryNote, splitCompetitors } from "../detect";
5
+ import { codecFor, type LoadedConfig } from "../formats";
6
+ import { buildRulesBlock } from "../formats/rules";
7
+ import { isPlainObject } from "../formats/value";
8
+ import { join } from "../paths";
9
+ import { MCP_TOOL_IDS, rulesLines } from "../rulesContent";
10
+ import type { ConfigOp, FileEdit, HostPaths, InstallerInput, InstallPlan, InstallRecord } from "../types";
11
+ import { planHeader } from "./shared";
12
+
13
+ /**
14
+ * The Claude Code release this installer's facts are verified against — the lock in
15
+ * docs/hosts.jsonc; the drift note fires when the probed CLI differs.
16
+ */
17
+ export const CLAUDE_CODE_TESTED_VERSION = "2.1.303";
18
+
19
+ /** The built-in web tools the forced tier denies; bare names remove them from context. */
20
+ const BUILTIN_TOOL_IDS = { search: "WebSearch", fetch: "WebFetch" } as const;
21
+
22
+ /** Human name for a wrong-typed config value in plan errors ("an array", "a string"). */
23
+ function valueKind(value: unknown): string {
24
+ return Array.isArray(value) ? "an array" : `a ${typeof value}`;
25
+ }
26
+
27
+ /**
28
+ * The one subprocess the installer runs: `claude --version`, probed for the
29
+ * version-drift note. A missing binary or unreadable output skips the check with
30
+ * a stderr note and never blocks the plan — honor or report.
31
+ */
32
+ export function probeClaudeCodeVersion(err: (line: string) => void): string | undefined {
33
+ // env passed explicitly: runtime PATH edits (tests) must reach the lookup.
34
+ // shell: npm's global install on Windows provides only a claude.cmd shim,
35
+ // which spawnSync cannot launch without a shell; the command and args are
36
+ // hardcoded, so the shell hop is safe.
37
+ const result = spawnSync("claude", ["--version"], { timeout: 5000, encoding: "utf8", env: process.env, shell: true });
38
+ const version = result.status === 0 ? parseClaudeCodeVersion(result.stdout ?? "") : undefined;
39
+ if (version === undefined) {
40
+ err("note: claude was not found on PATH or printed no version; the version-drift check was skipped");
41
+ }
42
+ return version;
43
+ }
44
+
45
+ /**
46
+ * Parses `claude --version` output (`2.1.303 (Claude Code)`) into the bare version.
47
+ * The last semver wins: an update banner advertising a newer release must not
48
+ * anchor the drift note on the wrong number.
49
+ */
50
+ export function parseClaudeCodeVersion(output: string): string | undefined {
51
+ return [...output.matchAll(/\b\d+\.\d+\.\d+\b/g)].map((match) => match[0]).at(-1);
52
+ }
53
+
54
+ /**
55
+ * Claude Code config, settings, and rules files per scope; the host module owns
56
+ * this mapping. MCP registration and the settings file are disjoint per scope
57
+ * (project: `.mcp.json` + `.claude/settings.json`; global: `~/.claude.json` +
58
+ * `~/.claude/settings.json`), so the two scopes can coexist unlike Codex's.
59
+ */
60
+ function claudeCodePaths(input: InstallerInput): HostPaths & { readonly settings: string } {
61
+ return input.scope === "global"
62
+ ? {
63
+ config: join(input.home, ".claude.json"),
64
+ settings: join(input.home, ".claude", "settings.json"),
65
+ rules: join(input.home, ".claude", "CLAUDE.md"),
66
+ }
67
+ : {
68
+ config: join(input.cwd, ".mcp.json"),
69
+ settings: join(input.cwd, ".claude", "settings.json"),
70
+ rules: join(input.cwd, "CLAUDE.md"),
71
+ };
72
+ }
73
+
74
+ /**
75
+ * The managed-policy layer, the one settings layer above the user. Its existence
76
+ * (never its contents) is reported: deny and allow rules there outrank anything
77
+ * this plan writes at either scope.
78
+ */
79
+ function managedSettingsPath(input: InstallerInput): string {
80
+ const platform = input.platform ?? process.platform;
81
+ if (platform === "darwin") return "/Library/Application Support/ClaudeCode/managed-settings.json";
82
+ if (platform === "win32") return "C:\\Program Files\\ClaudeCode\\managed-settings.json";
83
+ return "/etc/claude-code/managed-settings.json";
84
+ }
85
+
86
+ export function planClaudeCode(input: InstallerInput, _previous: InstallRecord | undefined): InstallPlan {
87
+ const paths = claudeCodePaths(input);
88
+ const loaded = codecFor("json", input.host).load(paths.config);
89
+ const tiers = { search: input.search, fetch: input.fetch };
90
+ const header = planHeader(input, paths, loaded, "JSON");
91
+ if (header.abort) {
92
+ return { host: "claude-code", scope: input.scope, tiers, edits: [], notes: header.notes, errors: header.errors };
93
+ }
94
+ const notes = [...header.notes];
95
+ const errors = [...header.errors];
96
+ const edits: FileEdit[] = [];
97
+
98
+ if (input.hostVersion !== undefined && input.hostVersion !== CLAUDE_CODE_TESTED_VERSION) {
99
+ notes.push(
100
+ `Claude Code ${input.hostVersion} is installed, but this installer's Claude Code facts are verified against ` +
101
+ `${CLAUDE_CODE_TESTED_VERSION} (the docs/hosts.jsonc lock). Deny-rule and tool-visibility behavior may have ` +
102
+ "drifted between the two — re-verify the tiers if routing misbehaves.",
103
+ );
104
+ }
105
+ const managed = managedSettingsPath(input);
106
+ if (existsSync(managed)) {
107
+ notes.push(
108
+ `${managed} exists: the managed policy layer outranks every settings file this plan writes, so a deny or allow ` +
109
+ "there overrides these changes. Check with your administrator if routing does not take effect.",
110
+ );
111
+ }
112
+
113
+ // The server registration. `${VAR}` expansion is Claude Code's own mechanism, so
114
+ // the key expands from the environment that launches Claude Code and never sits
115
+ // in the file.
116
+ const servers = loaded.value.mcpServers;
117
+ if (servers !== undefined && !isPlainObject(servers)) {
118
+ errors.push({
119
+ message: `${paths.config}: mcpServers is ${valueKind(servers)}, not an object; fix it before installing.`,
120
+ });
121
+ }
122
+ const existingEntry = isPlainObject(servers) ? servers.deepseek : undefined;
123
+ const entry = {
124
+ command: "npx",
125
+ args: ["-y", input.packageRef],
126
+ env: { [API_KEY_ENV]: `\${${API_KEY_ENV}}` },
127
+ };
128
+ const ops: ConfigOp[] = [{ op: "set", path: ["mcpServers", "deepseek"], value: entry, previous: existingEntry }];
129
+ edits.push({
130
+ file: paths.config,
131
+ format: "json",
132
+ // Global-scope files live outside the install record's config home, so they
133
+ // need the owner sidecar that stops a second install (another project or
134
+ // XDG_CONFIG_HOME) from claiming them — the codex topology.
135
+ ...(input.scope === "global" ? { shared: true as const } : {}),
136
+ ops,
137
+ });
138
+
139
+ if (isPlainObject(servers)) {
140
+ if ("deepseek" in servers) notes.push(replacingExistingEntryNote("mcpServers.deepseek"));
141
+ }
142
+ notes.push(
143
+ `\`${API_KEY_ENV}\` is written as "\${${API_KEY_ENV}}" in the server's env block, so the key expands from the ` +
144
+ "environment that launches Claude Code and stays out of the file.",
145
+ );
146
+ if (input.scope === "project") {
147
+ notes.push(
148
+ "Claude Code asks once per project whether to use servers from .mcp.json; approve the deepseek server when " +
149
+ "prompted (or via the /mcp menu), or its tools will not load in that project.",
150
+ );
151
+ } else {
152
+ notes.push(
153
+ `User-scope servers live in the mcpServers key of ${paths.config} — Claude Code's own user-level store, where ` +
154
+ "`claude mcp add --scope user` writes too; every other key in the file is left untouched.",
155
+ );
156
+ }
157
+
158
+ // Forced-tier competitor detection also scans the other stack's file — a project
159
+ // install sees user-scope servers and a global install runs inside a cwd — since
160
+ // a server-level deny rule in this scope's settings file excludes either origin.
161
+ const forced = input.search === "forced" || input.fetch === "forced";
162
+ const scanned: Record<string, unknown> = {};
163
+ if (isPlainObject(servers)) Object.assign(scanned, servers);
164
+ const otherFile = input.scope === "project" ? join(input.home, ".claude.json") : join(input.cwd, ".mcp.json");
165
+ if (forced && existsSync(otherFile)) {
166
+ let otherLoaded: LoadedConfig | undefined;
167
+ try {
168
+ otherLoaded = codecFor("json", input.host).load(otherFile);
169
+ } catch (error) {
170
+ // A directory or unreadable file (EISDIR/EACCES) must refuse the tier —
171
+ // honor or report — instead of crashing on a file we never edit.
172
+ errors.push({
173
+ message: `${otherFile} exists but cannot be read (${error instanceof Error ? error.message : String(error)}); the forced-tier competitor scan requires it. Fix the file or its permissions, or choose a lower tier.`,
174
+ });
175
+ }
176
+ if (otherLoaded?.parseError) {
177
+ errors.push({ message: `${otherFile} exists but does not parse as JSON: ${otherLoaded.parseError}` });
178
+ } else if (
179
+ otherLoaded !== undefined &&
180
+ otherLoaded.value.mcpServers !== undefined &&
181
+ !isPlainObject(otherLoaded.value.mcpServers)
182
+ ) {
183
+ errors.push({
184
+ message: `${otherFile}: mcpServers is ${valueKind(otherLoaded.value.mcpServers)}, not an object; the forced-tier competitor scan cannot read it. Fix the file or choose a lower tier.`,
185
+ });
186
+ } else if (otherLoaded !== undefined && isPlainObject(otherLoaded.value.mcpServers)) {
187
+ const otherServers = otherLoaded.value.mcpServers;
188
+ Object.assign(scanned, otherServers);
189
+ if ("deepseek" in otherServers) {
190
+ notes.push(
191
+ `A deepseek server is also registered in ${otherFile}; Claude Code resolves the name local first, then ` +
192
+ "project, then user scope, so consider uninstalling the other scope to keep one registration.",
193
+ );
194
+ }
195
+ }
196
+ }
197
+
198
+ const denyEntries: string[] = [];
199
+ const { competitors, bystanders } = splitCompetitors(scanned);
200
+ if (forced && competitors.length > 0) {
201
+ // Claude Code has a per-server kill switch: a bare `mcp__<server>` deny rule
202
+ // denies every tool of that server, so detected web-capable competitors are
203
+ // excluded instead of refusing the tier (unlike Codex).
204
+ const rules = competitors.map((name) => `mcp__${name}`);
205
+ denyEntries.push(...rules);
206
+ notes.push(
207
+ `Forced tier: web-capable MCP servers are denied by server-level rules (${rules.join(", ")}), so DeepSeek ` +
208
+ "routing is exclusive while the entries stay." +
209
+ (input.scope === "global"
210
+ ? " These denies apply in every project on this machine and match by server name, so a same-named server in another project is denied too."
211
+ : ""),
212
+ );
213
+ }
214
+ const stayRegistered = forced ? bystanders : [...competitors, ...bystanders];
215
+ if (stayRegistered.length > 0) notes.push(othersStayRegisteredNote(stayRegistered));
216
+
217
+ if (input.search === "forced") denyEntries.push(BUILTIN_TOOL_IDS.search);
218
+ if (input.fetch === "forced") denyEntries.push(BUILTIN_TOOL_IDS.fetch);
219
+ if (input.search === "off") denyEntries.push(MCP_TOOL_IDS.search);
220
+ if (input.fetch === "off") denyEntries.push(MCP_TOOL_IDS.fetch);
221
+
222
+ if (denyEntries.length > 0) {
223
+ const settingsLoaded = codecFor("json", input.host).load(paths.settings);
224
+ if (settingsLoaded.parseError) {
225
+ errors.push({ message: `${paths.settings} exists but does not parse as JSON: ${settingsLoaded.parseError}` });
226
+ } else {
227
+ const permissions = settingsLoaded.value.permissions;
228
+ const deny = isPlainObject(permissions) ? permissions.deny : undefined;
229
+ if (permissions !== undefined && !isPlainObject(permissions)) {
230
+ errors.push({
231
+ message: `${paths.settings}: the permissions key is ${valueKind(permissions)}, not an object; fix it before installing.`,
232
+ });
233
+ } else if (deny !== undefined && !Array.isArray(deny)) {
234
+ errors.push({
235
+ message: `${paths.settings}: permissions.deny is ${valueKind(deny)}, not an array; fix it before installing.`,
236
+ });
237
+ } else {
238
+ const existingCount = Array.isArray(deny) ? deny.length : 0;
239
+ const existingDeny = Array.isArray(deny) ? deny.filter((item): item is string => typeof item === "string") : [];
240
+ const denyOps: ConfigOp[] = [
241
+ {
242
+ op: "append-array",
243
+ path: ["permissions", "deny"],
244
+ entries: denyEntries,
245
+ existingCount,
246
+ },
247
+ ];
248
+ edits.push({
249
+ file: paths.settings,
250
+ format: "json",
251
+ ...(input.scope === "global" ? { shared: true as const } : {}),
252
+ ops: denyOps,
253
+ });
254
+ if (existingCount > 0) {
255
+ notes.push(
256
+ `permissions.deny already holds ${existingCount} ${existingCount === 1 ? "entry" : "entries"}; ` +
257
+ "the plan appends only its own and never removes yours.",
258
+ );
259
+ }
260
+ const preexisting = denyEntries.filter((name) => existingDeny.includes(name));
261
+ if (preexisting.length > 0) {
262
+ notes.push(
263
+ `${preexisting.join(", ")} ${preexisting.length === 1 ? "is" : "are"} already present in permissions.deny — present entries are not duplicated.`,
264
+ );
265
+ }
266
+ }
267
+ }
268
+ }
269
+ if (errors.length > 0) {
270
+ return { host: "claude-code", scope: input.scope, tiers, edits: [], notes, errors };
271
+ }
272
+
273
+ const forcedIds = [
274
+ ...(input.search === "forced" ? [BUILTIN_TOOL_IDS.search] : []),
275
+ ...(input.fetch === "forced" ? [BUILTIN_TOOL_IDS.fetch] : []),
276
+ ];
277
+ if (forcedIds.length > 0) {
278
+ notes.push(
279
+ `Forced is exclusion: bare deny rules (${forcedIds.join(", ")}) in permissions.deny remove the built-in tool ` +
280
+ "from the model's context entirely — deny outranks allow at every settings level and cannot be carved out, so " +
281
+ `the exclusion also applies to every other workflow that relied on the tool ${
282
+ input.scope === "global" ? "in every project on this machine" : "in this project"
283
+ }. ` +
284
+ FORCED_COST_NOTE,
285
+ );
286
+ }
287
+ const offIds = [
288
+ ...(input.search === "off" ? [MCP_TOOL_IDS.search] : []),
289
+ ...(input.fetch === "off" ? [MCP_TOOL_IDS.fetch] : []),
290
+ ];
291
+ if (offIds.length > 0) {
292
+ notes.push(
293
+ `Off capabilities are written as their full tool ids (${offIds.join(", ")}) in permissions.deny: the tool ` +
294
+ "leaves the model's context while the server keeps running; delete the entry to re-enable it.",
295
+ );
296
+ }
297
+ if (input.search === "optional" || input.fetch === "optional") {
298
+ notes.push(
299
+ "Claude Code ships built-in WebSearch and WebFetch tools; under the optional tier they stay available " +
300
+ "alongside the DeepSeek tools.",
301
+ );
302
+ }
303
+
304
+ if (input.search === "preferred" || input.fetch === "preferred") {
305
+ if (input.scope === "project" && !existsSync(paths.rules) && existsSync(join(input.cwd, "AGENTS.md"))) {
306
+ notes.push(
307
+ `This plan creates ${paths.rules} where none exists, and ${join(input.cwd, "AGENTS.md")} is present: Claude ` +
308
+ "Code reads AGENTS.md only when no CLAUDE.md exists above the cwd, so the new CLAUDE.md takes precedence — " +
309
+ "merge anything you rely on from AGENTS.md before applying.",
310
+ );
311
+ }
312
+ edits.push({
313
+ file: paths.rules,
314
+ format: "rules",
315
+ block: buildRulesBlock(input.host, rulesLines(MCP_TOOL_IDS, input.search, input.fetch)),
316
+ });
317
+ notes.push(
318
+ input.scope === "global"
319
+ ? `Rules block upserted in ${paths.rules}; Claude Code loads the user CLAUDE.md plus every CLAUDE.md from the cwd up the directory tree, concatenating the levels.`
320
+ : `Rules block upserted in ${paths.rules}; Claude Code loads every CLAUDE.md from the cwd up the directory tree, concatenating the levels.`,
321
+ );
322
+ }
323
+
324
+ return { host: "claude-code", scope: input.scope, tiers, edits, notes, errors };
325
+ }
@@ -23,7 +23,10 @@ export const CODEX_TESTED_VERSION = "0.163.0";
23
23
  */
24
24
  export function probeCodexVersion(err: (line: string) => void): string | undefined {
25
25
  // env passed explicitly: runtime PATH edits (tests) must reach the lookup.
26
- const result = spawnSync("codex", ["--version"], { timeout: 5000, encoding: "utf8", env: process.env });
26
+ // shell: npm's global install on Windows provides only a codex.cmd shim,
27
+ // which spawnSync cannot launch without a shell; the command and args are
28
+ // hardcoded, so the shell hop is safe.
29
+ const result = spawnSync("codex", ["--version"], { timeout: 5000, encoding: "utf8", env: process.env, shell: true });
27
30
  const version = result.status === 0 ? parseCodexVersion(result.stdout ?? "") : undefined;
28
31
  if (version === undefined) {
29
32
  err("note: codex was not found on PATH or printed no version; the version-drift check was skipped");
@@ -3,6 +3,7 @@ import { deepEqual, isPlainObject } from "../formats/value";
3
3
  import { assertFileOwnership, fileOwnershipNotes } from "../ownership";
4
4
  import { claimedByOtherScope, InstallRecordError, readRecord } from "../state";
5
5
  import type { HostName, InstallerInput, InstallPlan, InstallRecord, RecordedFile } from "../types";
6
+ import { planClaudeCode, probeClaudeCodeVersion } from "./claude-code";
6
7
  import { planCodex, probeCodexVersion } from "./codex";
7
8
  import { planOpenCode } from "./opencode";
8
9
  import { planPi } from "./pi";
@@ -23,6 +24,7 @@ export const HOST_PLANNERS: Readonly<Record<HostName, HostPlanner>> = {
23
24
  opencode: planOpenCode,
24
25
  pi: planPi,
25
26
  codex: planCodex,
27
+ "claude-code": planClaudeCode,
26
28
  };
27
29
 
28
30
  /**
@@ -32,6 +34,7 @@ export const HOST_PLANNERS: Readonly<Record<HostName, HostPlanner>> = {
32
34
  */
33
35
  export const HOST_VERSION_PROBES: Partial<Record<HostName, (err: (line: string) => void) => string | undefined>> = {
34
36
  codex: probeCodexVersion,
37
+ "claude-code": probeClaudeCodeVersion,
35
38
  };
36
39
 
37
40
  export function planForHost(host: HostName, input: InstallerInput): InstallPlan {
@@ -128,7 +128,15 @@ function planPiExtension(input: InstallerInput, previous: InstallRecord | undefi
128
128
  previous: typeof namespace.enableFetch === "boolean" ? namespace.enableFetch : undefined,
129
129
  });
130
130
  }
131
- edits.push({ file: paths.config, format: "json", ops });
131
+ edits.push({
132
+ file: paths.config,
133
+ format: "json",
134
+ // Global-scope files live outside the install record's config home, so they
135
+ // need the owner sidecar that stops a second install (another project or
136
+ // XDG_CONFIG_HOME) from claiming them — the codex topology.
137
+ ...(input.scope === "global" ? { shared: true as const } : {}),
138
+ ops,
139
+ });
132
140
 
133
141
  notes.push(
134
142
  "Pi resolves the packages source at session start; the first launch after apply fetches the package from npm " +
@@ -234,7 +242,14 @@ function planMcpCompetitorDisables(input: InstallerInput, notes: string[], error
234
242
  const edits: FileEdit[] = [];
235
243
  if (competitors.length > 0) {
236
244
  const ops = planCompetitorDisables(servers, competitors, notes, errors);
237
- if (ops.length > 0) edits.push({ file: mcpFile, format: "json", ops });
245
+ if (ops.length > 0) {
246
+ edits.push({
247
+ file: mcpFile,
248
+ format: "json",
249
+ ...(input.scope === "global" ? { shared: true as const } : {}),
250
+ ops,
251
+ });
252
+ }
238
253
  }
239
254
  if (bystanders.length > 0) notes.push(othersStayRegisteredNote(bystanders));
240
255
  return edits;
@@ -267,7 +282,13 @@ function planPiMcp(input: InstallerInput): InstallPlan {
267
282
  const servers = loaded.value.mcpServers;
268
283
  const existingEntry = isPlainObject(servers) ? servers.deepseek : undefined;
269
284
  const ops: ConfigOp[] = [{ op: "set", path: ["mcpServers", "deepseek"], value: entry, previous: existingEntry }];
270
- edits.push({ file: paths.config, format: "json", ops });
285
+ edits.push({
286
+ file: paths.config,
287
+ format: "json",
288
+ // Same shared-file reason as the extension path's settings.json above.
289
+ ...(input.scope === "global" ? { shared: true as const } : {}),
290
+ ops,
291
+ });
271
292
 
272
293
  if (isPlainObject(servers)) {
273
294
  if (servers.deepseek !== undefined) notes.push(replacingExistingEntryNote("mcpServers.deepseek"));
@@ -49,7 +49,7 @@ const operation = z.discriminatedUnion("op", [
49
49
  const recordSchema = z.object({
50
50
  version: z.literal(1),
51
51
  installerVersion: z.string().optional(),
52
- host: z.enum(["opencode", "pi", "codex"]),
52
+ host: z.enum(["opencode", "pi", "codex", "claude-code"]),
53
53
  scope: z.enum(["global", "project"]),
54
54
  tiers: z.object({ search: tier, fetch: tier }),
55
55
  createdAt: z.string().refine((value) => Number.isFinite(Date.parse(value))),
@@ -1,5 +1,5 @@
1
1
  /** Hosts the installer supports. */
2
- export type HostName = "opencode" | "pi" | "codex";
2
+ export type HostName = "opencode" | "pi" | "codex" | "claude-code";
3
3
 
4
4
  /** Install scope, a first-class user choice. */
5
5
  export type Scope = "project" | "global";
@@ -48,8 +48,11 @@ function uninstallLocked(input: InstallerInput, record: InstallRecord): string[]
48
48
  for (const file of [...record.files].reverse()) {
49
49
  lines.push(...revertRecordedFile(file, record.host, { label: "", whole: true }));
50
50
  }
51
- deleteRecord(input);
51
+ // Release claims before deleting the record: releaseClaim re-asserts lineage
52
+ // through recordReadPath, whose legacy win32 fallback needs the record file
53
+ // to still exist on disk.
52
54
  releaseFileOwnership(input, record.files);
55
+ deleteRecord(input);
53
56
  pruneEmptyDir(stateDir(input, input.scope));
54
57
  lines.push(`removed install record (${input.host}, ${input.scope})`);
55
58
  return lines;