opencode-rag-plugin 2.2.2 → 2.3.1

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 (58) hide show
  1. package/ReadMe.md +2 -0
  2. package/dist/api.js +2 -0
  3. package/dist/chunker/factory.js +48 -18
  4. package/dist/chunker/image.js +6 -0
  5. package/dist/cli/commands/clear.js +21 -1
  6. package/dist/cli/commands/init-helpers.d.ts +4 -1
  7. package/dist/cli/commands/init-helpers.js +55 -20
  8. package/dist/cli/commands/init.js +13 -1
  9. package/dist/cli/commands/query.js +6 -0
  10. package/dist/cli/commands/setup.js +43 -12
  11. package/dist/cli/commands/status.js +4 -0
  12. package/dist/cli/commands/update.d.ts +3 -2
  13. package/dist/cli/commands/update.js +7 -3
  14. package/dist/core/bootstrap.d.ts +3 -1
  15. package/dist/core/bootstrap.js +5 -0
  16. package/dist/core/config.d.ts +74 -1
  17. package/dist/core/config.js +63 -1
  18. package/dist/core/interfaces.d.ts +34 -0
  19. package/dist/core/package-manager.d.ts +69 -0
  20. package/dist/core/package-manager.js +250 -0
  21. package/dist/core/setup-runtime.d.ts +7 -4
  22. package/dist/core/setup-runtime.js +33 -31
  23. package/dist/core/version-check.d.ts +19 -11
  24. package/dist/core/version-check.js +30 -11
  25. package/dist/describer/describer.js +9 -1
  26. package/dist/embedder/factory.d.ts +5 -1
  27. package/dist/embedder/factory.js +76 -6
  28. package/dist/embedder/health.d.ts +1 -1
  29. package/dist/embedder/health.js +43 -0
  30. package/dist/eval/rerank-eval.d.ts +45 -0
  31. package/dist/eval/rerank-eval.js +581 -0
  32. package/dist/indexer/pipeline.d.ts +17 -0
  33. package/dist/indexer/pipeline.js +123 -3
  34. package/dist/indexer/stats.d.ts +7 -0
  35. package/dist/mcp/handlers.js +3 -0
  36. package/dist/opencode/create-read-tool.js +5 -2
  37. package/dist/plugin.js +67 -6
  38. package/dist/quirks/quirk-store.d.ts +1 -0
  39. package/dist/quirks/quirk-store.js +1 -1
  40. package/dist/quirks/tool-error-recall.d.ts +112 -0
  41. package/dist/quirks/tool-error-recall.js +144 -0
  42. package/dist/reranker/base.d.ts +47 -0
  43. package/dist/reranker/base.js +73 -0
  44. package/dist/reranker/factory.d.ts +16 -0
  45. package/dist/reranker/factory.js +47 -0
  46. package/dist/reranker/llama-server.d.ts +33 -0
  47. package/dist/reranker/llama-server.js +101 -0
  48. package/dist/retriever/keyword-index.d.ts +1 -0
  49. package/dist/retriever/keyword-index.js +1 -1
  50. package/dist/retriever/retriever.d.ts +24 -1
  51. package/dist/retriever/retriever.js +69 -5
  52. package/dist/types/opencode-plugin.d.ts +2 -2
  53. package/dist/v2/v2-adapter.d.ts +6 -1
  54. package/dist/v2/v2-adapter.js +52 -8
  55. package/dist/vectorstore/lancedb.d.ts +1 -1
  56. package/dist/vectorstore/lancedb.js +43 -7
  57. package/dist/web/api.js +5 -0
  58. package/package.json +1 -1
@@ -75,7 +75,14 @@ export interface DescriptionConfig {
75
75
  retryMax?: number;
76
76
  /** Base delay in ms between retries (exponential backoff). */
77
77
  retryBaseDelayMs?: number;
78
- /** Whether to include chain-of-thought tokens in the response. */
78
+ /**
79
+ * Whether the model may emit chain-of-thought tokens before the answer.
80
+ * For the Ollama provider this sets the `think` request field. For
81
+ * OpenAI-compatible providers `false` forwards
82
+ * `chat_template_kwargs.enable_thinking=false` (llama.cpp / vLLM
83
+ * convention); without it, reasoning models spend thousands of extra
84
+ * tokens per description and indexing runs ~50x slower.
85
+ */
79
86
  think?: boolean;
80
87
  /** Context window size for the LLM. */
81
88
  numCtx?: number;
@@ -208,6 +215,24 @@ export interface MemoryConfig {
208
215
  autoCaptureMaxPerTurn: number;
209
216
  /** Lexical similarity threshold (0-1) above which a candidate is considered a duplicate and skipped. */
210
217
  autoCaptureDedupThreshold: number;
218
+ /**
219
+ * Inject matching quirks into the next model request after a FAILED tool call
220
+ * (default true). Failed calls are also appended to the auto-capture pipeline,
221
+ * so recurring errors can become quirks.
222
+ */
223
+ injectOnToolError: boolean;
224
+ /** Minimum relevance score (0-1) for a quirk to be injected after a tool error (default 0.7). */
225
+ toolErrorMinScore: number;
226
+ /** Max quirks injected per tool error (default 2). */
227
+ toolErrorTopK: number;
228
+ /** Minimum shared word tokens (>=3 chars) between a quirk and the error text; 0 disables (default 1). */
229
+ toolErrorMinTokenOverlap: number;
230
+ /** Cooldown per normalized tool-error signature in ms (default 60000). */
231
+ toolErrorCooldownMs: number;
232
+ /** Max tool-error quirk injections per session (default 3). */
233
+ toolErrorMaxPerSession: number;
234
+ /** Latency budget (ms) for tool-error quirk recall; exceeded -> no injection (default 1500). */
235
+ toolErrorLatencyBudgetMs: number;
211
236
  /** Decay settings for aging quirks. */
212
237
  decay: {
213
238
  /** Whether confidence decays over time. */
@@ -254,6 +279,52 @@ export interface ContextOptimizationConfig {
254
279
  /** Jaccard similarity threshold (0-1) for same-file dedup. */
255
280
  similarityThreshold: number;
256
281
  }
282
+ /**
283
+ * Optional cross-encoder rerank stage (opt-in, default OFF).
284
+ *
285
+ * After hybrid fusion the top candidates are re-scored by a cross-encoder
286
+ * (e.g. Qwen3-Reranker served by llama-server's `/v1/rerank`). The stage is a
287
+ * pure reorder (+ optional gate); the fusion `minScore` gate runs unchanged
288
+ * BEFORE reranking, so disabling reranking reproduces today's behavior
289
+ * exactly. Provider errors/timeouts always degrade to the fusion order —
290
+ * retrieval never fails because of the reranker.
291
+ */
292
+ export interface RerankingConfig {
293
+ /** Master switch — when false (default) no reranker is created. */
294
+ enabled: boolean;
295
+ /** Rerank provider implementation. @default "llama-server" */
296
+ provider?: "llama-server";
297
+ /** Base URL of the rerank endpoint (e.g. http://127.0.0.1:8080/v1). The stage POSTs to {baseUrl}/rerank. */
298
+ baseUrl: string;
299
+ /** Optional bearer token (e.g. llama-swap auth). */
300
+ apiKey?: string;
301
+ /** Reranker model name passed to the server. */
302
+ model: string;
303
+ /** How many fused candidates to send per query (after the fusion minScore gate). @default 20 */
304
+ candidates?: number;
305
+ /** Each candidate's document text is truncated to this many characters. @default 1200 */
306
+ maxDocChars?: number;
307
+ /** Additional gate on the rerank score itself (0 = pure reorder, default). NOT comparable to retrieval.minScore — rerank scores are provider-scaled, not calibrated. */
308
+ minScore?: number;
309
+ /** Per-call timeout in ms; on expiry the fusion order is kept. @default 4000 */
310
+ timeoutMs?: number;
311
+ /**
312
+ * Query template applied before scoring. With a `{query}` placeholder the
313
+ * query is substituted, otherwise the template is used as a prefix.
314
+ * Use this for instruct-style rerankers (e.g. Qwen3-Reranker) — do NOT
315
+ * reuse embedding.queryPrefix here. @default ""
316
+ */
317
+ queryTemplate?: string;
318
+ /**
319
+ * Document text: raw content, or description + content.
320
+ * `"content+description"` was the best arm in the 2026-10-02 eval (Hit@1 29.2 % vs 22.9 %,
321
+ * MRR 0.466 vs 0.414) — descriptions carry signal the raw code text misses.
322
+ * @default "content+description"
323
+ */
324
+ docField?: "content" | "content+description";
325
+ /** Proxy configuration for the rerank endpoint. */
326
+ proxy?: ProxyConfig;
327
+ }
257
328
  /** Complete configuration for the OpenCodeRAG pipeline. */
258
329
  export interface RagConfig {
259
330
  /** Embedding provider settings (model, endpoint, prefixes). */
@@ -398,6 +469,8 @@ export interface RagConfig {
398
469
  /** Context window optimization settings for post-retrieval quality filtering. */
399
470
  contextOptimization?: ContextOptimizationConfig;
400
471
  };
472
+ /** Optional cross-encoder rerank stage (opt-in; absent = disabled). */
473
+ reranking?: RerankingConfig;
401
474
  /** OpenCode plugin integration settings. */
402
475
  openCode: {
403
476
  /** Whether the OpenCode plugin is active. */
@@ -145,6 +145,20 @@ export const DEFAULT_CONFIG = {
145
145
  similarityThreshold: 0.8,
146
146
  },
147
147
  },
148
+ reranking: {
149
+ enabled: false,
150
+ provider: "llama-server",
151
+ // llama-server's default port; llama-swap users typically point this at
152
+ // their swap proxy (which routes v1/rerank) instead.
153
+ baseUrl: "http://127.0.0.1:8080/v1",
154
+ model: "qwen3-reranker-0.6b",
155
+ candidates: 20,
156
+ maxDocChars: 1200,
157
+ minScore: 0,
158
+ timeoutMs: 4000,
159
+ queryTemplate: "",
160
+ docField: "content+description",
161
+ },
148
162
  openCode: {
149
163
  enabled: true,
150
164
  maxContextChunks: 10,
@@ -288,6 +302,13 @@ export const DEFAULT_CONFIG = {
288
302
  sessionEndExtraction: true,
289
303
  autoCaptureMaxPerTurn: 2,
290
304
  autoCaptureDedupThreshold: 0.85,
305
+ injectOnToolError: true,
306
+ toolErrorMinScore: 0.7,
307
+ toolErrorTopK: 2,
308
+ toolErrorMinTokenOverlap: 1,
309
+ toolErrorCooldownMs: 60_000,
310
+ toolErrorMaxPerSession: 3,
311
+ toolErrorLatencyBudgetMs: 1500,
291
312
  decay: {
292
313
  enabled: false,
293
314
  halfLifeDays: 30,
@@ -318,7 +339,7 @@ export function resolveLogConfig(config) {
318
339
  export function validateConfig(config) {
319
340
  const warnings = [];
320
341
  const KNOWN_TOP_KEYS = new Set([
321
- "embedding", "indexing", "vectorStore", "retrieval",
342
+ "embedding", "indexing", "vectorStore", "retrieval", "reranking",
322
343
  "openCode", "chunkers", "chunking", "description",
323
344
  "imageDescription", "documentationMode", "wikiMode", "mcp", "autoUpdate", "memory", "ui", "tui", "logging",
324
345
  ]);
@@ -416,6 +437,23 @@ export function validateConfig(config) {
416
437
  if (t < 0 || t > 1)
417
438
  warnings.push("memory.autoCaptureDedupThreshold must be between 0 and 1");
418
439
  }
440
+ if (config.memory?.toolErrorMinScore != null) {
441
+ const r = config.memory.toolErrorMinScore;
442
+ if (r < 0 || r > 1)
443
+ warnings.push("memory.toolErrorMinScore must be between 0 and 1");
444
+ }
445
+ if (config.memory?.toolErrorTopK != null && config.memory.toolErrorTopK < 1) {
446
+ warnings.push("memory.toolErrorTopK must be >= 1");
447
+ }
448
+ if (config.memory?.toolErrorCooldownMs != null && config.memory.toolErrorCooldownMs < 0) {
449
+ warnings.push("memory.toolErrorCooldownMs must be >= 0");
450
+ }
451
+ if (config.memory?.toolErrorMaxPerSession != null && config.memory.toolErrorMaxPerSession < 0) {
452
+ warnings.push("memory.toolErrorMaxPerSession must be >= 0");
453
+ }
454
+ if (config.memory?.toolErrorLatencyBudgetMs != null && config.memory.toolErrorLatencyBudgetMs < 0) {
455
+ warnings.push("memory.toolErrorLatencyBudgetMs must be >= 0");
456
+ }
419
457
  if (config.memory?.decay && config.memory.decay.halfLifeDays <= 0) {
420
458
  warnings.push("memory.decay.halfLifeDays must be > 0");
421
459
  }
@@ -470,6 +508,25 @@ export function validateConfig(config) {
470
508
  warnings.push("imageDescription.onDemand.timeoutMs must be > 0");
471
509
  }
472
510
  }
511
+ if (config.reranking?.enabled) {
512
+ const rr = config.reranking;
513
+ if (!rr.baseUrl)
514
+ warnings.push("reranking.baseUrl must be set when reranking.enabled is true");
515
+ if (!rr.model)
516
+ warnings.push("reranking.model must be set when reranking.enabled is true");
517
+ if (rr.candidates !== undefined && (rr.candidates < 1 || rr.candidates > 100)) {
518
+ warnings.push("reranking.candidates should be between 1 and 100 (latency scales linearly with document count)");
519
+ }
520
+ if (rr.minScore !== undefined && (rr.minScore < 0 || rr.minScore > 1)) {
521
+ warnings.push("reranking.minScore must be between 0 and 1");
522
+ }
523
+ if (rr.timeoutMs !== undefined && rr.timeoutMs <= 0) {
524
+ warnings.push("reranking.timeoutMs must be > 0");
525
+ }
526
+ if (rr.maxDocChars !== undefined && rr.maxDocChars <= 0) {
527
+ warnings.push("reranking.maxDocChars must be > 0");
528
+ }
529
+ }
473
530
  return { valid: warnings.length === 0, warnings };
474
531
  }
475
532
  /** Config file locations to search, in order of precedence. */
@@ -541,6 +598,11 @@ export function loadConfig(filePath, validate = true) {
541
598
  ...(safeObj(parsed.retrieval?.contextOptimization) ?? {}),
542
599
  },
543
600
  },
601
+ // Flat section — no nested objects, a shallow spread merge is safe.
602
+ reranking: {
603
+ ...DEFAULT_CONFIG.reranking,
604
+ ...(safeObj(parsed.reranking) ?? {}),
605
+ },
544
606
  openCode: (() => {
545
607
  const base = DEFAULT_CONFIG.openCode;
546
608
  const user = parsed.openCode ?? {};
@@ -81,6 +81,11 @@ export interface SearchExplanation {
81
81
  vectorRank?: number;
82
82
  /** Rank (0-indexed) in the keyword index results. */
83
83
  keywordRank?: number;
84
+ /** Cross-encoder relevance from the optional rerank stage. Higher means more
85
+ * relevant. NOT a calibrated probability (provider-dependent, llama-server
86
+ * semantics) and NOT comparable to the RRF-normalized fused components.
87
+ * Set only when the rerank stage actually ran for this result. */
88
+ rerankScore?: number;
84
89
  };
85
90
  /** Calibrated relevance in [0,1] derived from the raw vector-score spread of the
86
91
  * candidate set — unlike the fused `score` (RRF-normalized so rank 0 is always
@@ -128,6 +133,35 @@ export interface EmbeddingProvider {
128
133
  /** Embed one or more text strings. `purpose` may apply a prefix for query vs. document embeddings. */
129
134
  embed(texts: string[], purpose?: "query" | "document"): Promise<number[][]>;
130
135
  }
136
+ /**
137
+ * Cross-encoder reranker: scores (query, document) pairs for relevance.
138
+ *
139
+ * Deliberately narrow so a decision model (typed classifier) can implement the
140
+ * same contract later. Providers never throw into retrieval hot paths by
141
+ * design: callers catch `rerank()` rejections, degrade to the original order,
142
+ * and feed the failure into `noteFailure()` so repeated outages trip an
143
+ * automatic cooldown (`available() === false`).
144
+ */
145
+ export interface RerankProvider {
146
+ /** Provider name (e.g. "llama-server"). */
147
+ readonly name: string;
148
+ /** Model identifier used for scoring (cache/log attribution). */
149
+ readonly model: string;
150
+ /** False while a failure cooldown is active — callers must skip reranking. */
151
+ available(): boolean;
152
+ /**
153
+ * Score every document against the query; the returned array is index-aligned
154
+ * with `documents` (higher = more relevant). May reject — the caller then
155
+ * keeps the pre-rerank order and calls `noteFailure()`.
156
+ */
157
+ rerank(query: string, documents: string[], opts?: {
158
+ timeoutMs?: number;
159
+ }): Promise<number[]>;
160
+ /** Record a failed call (counts toward the cooldown). */
161
+ noteFailure(): void;
162
+ /** Record a successful call (resets the failure streak). */
163
+ noteSuccess(): void;
164
+ }
131
165
  /** In-memory TF-IDF inverted index for keyword-based search alongside vector search. */
132
166
  export interface KeywordIndex {
133
167
  /** Release resources and free memory. */
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @fileoverview Package-manager detection for the setup and self-update flows.
3
+ *
4
+ * OpenCodeRAG is usually installed globally with npm, but users also install it
5
+ * via pnpm, yarn, or bun. Earlier releases shelled out to `npm` directly and
6
+ * failed with "/bin/sh: 1: npm: not found" on machines where npm is not on
7
+ * PATH (GitHub issue #34). Every global-package operation now goes through
8
+ * this module: it finds the package manager that actually owns the global
9
+ * install and renders the equivalent commands for it
10
+ * (`npm root -g` / `pnpm root -g` / `yarn global dir` / bun's fixed layout).
11
+ */
12
+ /** Package managers with a working global-install mechanism that OpenCodeRAG supports. */
13
+ export type PackageManagerName = "npm" | "pnpm" | "yarn" | "bun";
14
+ /** Location of a global package install, independent of how it was installed. */
15
+ export interface GlobalInstall {
16
+ /** Package manager that owns the install, or `null` when only the directory could be located. */
17
+ pm: PackageManagerName | null;
18
+ /** Absolute path of the global `node_modules` directory that contains the package. */
19
+ globalRoot: string;
20
+ /** Absolute path of the package directory itself (the one containing `dist/`). */
21
+ packageDir: string;
22
+ }
23
+ /** Injectable seams so detection can be unit-tested without real package managers. */
24
+ export interface PackageManagerDeps {
25
+ /** Command runner (defaults to `execSync` with utf-8 output). */
26
+ exec?: (command: string, timeoutMs: number) => string;
27
+ /** Existence check (defaults to `fs.existsSync`). */
28
+ exists?: (filePath: string) => boolean;
29
+ /** JSON file reader (defaults to read + JSON.parse). */
30
+ readJson?: (filePath: string) => unknown;
31
+ /** Environment to detect from (defaults to `process.env`). */
32
+ env?: Record<string, string | undefined>;
33
+ /** Module path to derive a fallback install location from (defaults to this file). */
34
+ selfPath?: string;
35
+ }
36
+ /**
37
+ * Candidate package managers, best guess first.
38
+ *
39
+ * Detection order: the manager that launched this process (user-agent), then
40
+ * the manager implied by where this module is installed, then the default
41
+ * probe order (npm, pnpm, bun, yarn).
42
+ */
43
+ export declare function candidatePackageManagerOrder(deps?: PackageManagerDeps): PackageManagerName[];
44
+ /** The first package manager whose global root can be resolved (availability probe). */
45
+ export declare function bestAvailablePackageManager(deps?: PackageManagerDeps): PackageManagerName | null;
46
+ /** Shell command that globally installs `pkg` with the given manager. */
47
+ export declare function globalInstallCommand(pm: PackageManagerName, pkg: string): string;
48
+ /** Shell command that globally removes `pkg` with the given manager. */
49
+ export declare function globalUninstallCommand(pm: PackageManagerName, pkg: string): string;
50
+ /**
51
+ * Human-friendly install hint using the most likely manager for this machine
52
+ * (falls back to npm when nothing can be detected, e.g. npm-less CI probes).
53
+ */
54
+ export declare function installHint(pkg: string, deps?: PackageManagerDeps): string;
55
+ /**
56
+ * Locate the global install of `pluginName` and the package manager that owns it.
57
+ *
58
+ * Strategy: ask each candidate manager for its global root and check whether
59
+ * the package sits there. When no package-manager CLI works at all (the
60
+ * issue-#34 case: pnpm install, npm missing), fall back to deriving the
61
+ * location from this module's own resolved path — the running CLI *is* the
62
+ * installed package, so its real path identifies the install even without any
63
+ * package manager on PATH.
64
+ *
65
+ * @param pluginName - npm package name to look for (e.g. `opencode-rag-plugin`).
66
+ * @param deps - Test seams; leave empty in production.
67
+ * @returns The resolved install, or `null` when the package is not globally installed.
68
+ */
69
+ export declare function resolveGlobalInstall(pluginName: string, deps?: PackageManagerDeps): GlobalInstall | null;
@@ -0,0 +1,250 @@
1
+ /**
2
+ * @fileoverview Package-manager detection for the setup and self-update flows.
3
+ *
4
+ * OpenCodeRAG is usually installed globally with npm, but users also install it
5
+ * via pnpm, yarn, or bun. Earlier releases shelled out to `npm` directly and
6
+ * failed with "/bin/sh: 1: npm: not found" on machines where npm is not on
7
+ * PATH (GitHub issue #34). Every global-package operation now goes through
8
+ * this module: it finds the package manager that actually owns the global
9
+ * install and renders the equivalent commands for it
10
+ * (`npm root -g` / `pnpm root -g` / `yarn global dir` / bun's fixed layout).
11
+ */
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
15
+ import { execSync } from "node:child_process";
16
+ import { fileURLToPath } from "node:url";
17
+ /** Default probe order when no signal identifies the owning package manager. */
18
+ const DEFAULT_ORDER = ["npm", "pnpm", "bun", "yarn"];
19
+ const EXEC_TIMEOUT_MS = 15_000;
20
+ /** Run a command and return trimmed stdout, or `null` on any failure. */
21
+ function tryRun(command, deps) {
22
+ try {
23
+ const out = deps.exec
24
+ ? deps.exec(command, EXEC_TIMEOUT_MS)
25
+ : execSync(command, { encoding: "utf-8", timeout: EXEC_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"] });
26
+ const trimmed = out.trim();
27
+ return trimmed || null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ const SPECS = {
34
+ npm: {
35
+ name: "npm",
36
+ globalRoot(deps) {
37
+ return tryRun("npm root -g", deps);
38
+ },
39
+ installCommand(pkg) {
40
+ return `npm install -g ${pkg} --no-fund --no-audit`;
41
+ },
42
+ uninstallCommand(pkg) {
43
+ return `npm uninstall -g ${pkg}`;
44
+ },
45
+ },
46
+ pnpm: {
47
+ name: "pnpm",
48
+ globalRoot(deps) {
49
+ // Returns e.g. `~/.local/share/pnpm/global/v10/node_modules` on Linux or
50
+ // `%LOCALAPPDATA%\pnpm\global\v10\node_modules` on Windows. Installed
51
+ // packages are symlinks/junctions inside it, so existence checks follow.
52
+ return tryRun("pnpm root -g", deps);
53
+ },
54
+ installCommand(pkg) {
55
+ return `pnpm add -g ${pkg}`;
56
+ },
57
+ uninstallCommand(pkg) {
58
+ return `pnpm remove -g ${pkg}`;
59
+ },
60
+ },
61
+ yarn: {
62
+ name: "yarn",
63
+ globalRoot(deps) {
64
+ // Yarn 1 ("classic") keeps globals in `<yarn global dir>/node_modules`.
65
+ // Yarn Berry has no global installs and errors on `global` — the null
66
+ // return makes callers skip it.
67
+ const dir = tryRun("yarn global dir", deps);
68
+ return dir ? path.join(dir, "node_modules") : null;
69
+ },
70
+ installCommand(pkg) {
71
+ return `yarn global add ${pkg}`;
72
+ },
73
+ uninstallCommand(pkg) {
74
+ return `yarn global remove ${pkg}`;
75
+ },
76
+ },
77
+ bun: {
78
+ name: "bun",
79
+ globalRoot(deps) {
80
+ // `bun pm` has no root query; the global layout is fixed at
81
+ // `$BUN_INSTALL/install/global/node_modules` (default `~/.bun`).
82
+ if (tryRun("bun --version", deps) === null)
83
+ return null;
84
+ const base = (deps.env ?? process.env).BUN_INSTALL || path.join(os.homedir(), ".bun");
85
+ return path.join(base, "install", "global", "node_modules");
86
+ },
87
+ installCommand(pkg) {
88
+ return `bun add -g ${pkg}`;
89
+ },
90
+ uninstallCommand(pkg) {
91
+ return `bun remove -g ${pkg}`;
92
+ },
93
+ },
94
+ };
95
+ /** Package manager that started this process, from `npm_config_user_agent` (set by all four). */
96
+ function preferredFromEnv(deps) {
97
+ const ua = (deps.env ?? process.env).npm_config_user_agent ?? "";
98
+ for (const name of DEFAULT_ORDER) {
99
+ if (ua.startsWith(`${name}/`))
100
+ return name;
101
+ }
102
+ return null;
103
+ }
104
+ /**
105
+ * Package manager implied by the running module's own path.
106
+ *
107
+ * A pnpm-global install lives under `…/pnpm/global/…/node_modules/.pnpm/…`,
108
+ * a bun-global one under `~/.bun/install/global/…`, a Yarn classic global one
109
+ * under `~/.config/yarn/global/…`. npm's global roots carry no such marker.
110
+ */
111
+ function preferredFromSelfLocation(deps) {
112
+ let self;
113
+ try {
114
+ self = deps.selfPath ?? fileURLToPath(import.meta.url);
115
+ }
116
+ catch {
117
+ return null;
118
+ }
119
+ const segments = self.toLowerCase().split(/[\\/]+/);
120
+ if (segments.includes(".pnpm"))
121
+ return "pnpm";
122
+ for (const segment of segments) {
123
+ if (segment === "pnpm")
124
+ return "pnpm";
125
+ if (segment === ".bun")
126
+ return "bun";
127
+ if (segment === "yarn")
128
+ return "yarn";
129
+ }
130
+ return null;
131
+ }
132
+ /**
133
+ * Candidate package managers, best guess first.
134
+ *
135
+ * Detection order: the manager that launched this process (user-agent), then
136
+ * the manager implied by where this module is installed, then the default
137
+ * probe order (npm, pnpm, bun, yarn).
138
+ */
139
+ export function candidatePackageManagerOrder(deps = {}) {
140
+ const preferred = preferredFromEnv(deps) ?? preferredFromSelfLocation(deps);
141
+ if (!preferred)
142
+ return [...DEFAULT_ORDER];
143
+ return [preferred, ...DEFAULT_ORDER.filter((name) => name !== preferred)];
144
+ }
145
+ /** The first package manager whose global root can be resolved (availability probe). */
146
+ export function bestAvailablePackageManager(deps = {}) {
147
+ for (const name of candidatePackageManagerOrder(deps)) {
148
+ if (SPECS[name].globalRoot(deps) !== null)
149
+ return name;
150
+ }
151
+ return null;
152
+ }
153
+ /** Shell command that globally installs `pkg` with the given manager. */
154
+ export function globalInstallCommand(pm, pkg) {
155
+ return SPECS[pm].installCommand(pkg);
156
+ }
157
+ /** Shell command that globally removes `pkg` with the given manager. */
158
+ export function globalUninstallCommand(pm, pkg) {
159
+ return SPECS[pm].uninstallCommand(pkg);
160
+ }
161
+ /**
162
+ * Human-friendly install hint using the most likely manager for this machine
163
+ * (falls back to npm when nothing can be detected, e.g. npm-less CI probes).
164
+ */
165
+ export function installHint(pkg, deps = {}) {
166
+ const preferred = preferredFromEnv(deps) ?? preferredFromSelfLocation(deps) ?? bestAvailablePackageManager(deps);
167
+ return SPECS[preferred ?? "npm"].installCommand(pkg);
168
+ }
169
+ /**
170
+ * Locate the global install of `pluginName` and the package manager that owns it.
171
+ *
172
+ * Strategy: ask each candidate manager for its global root and check whether
173
+ * the package sits there. When no package-manager CLI works at all (the
174
+ * issue-#34 case: pnpm install, npm missing), fall back to deriving the
175
+ * location from this module's own resolved path — the running CLI *is* the
176
+ * installed package, so its real path identifies the install even without any
177
+ * package manager on PATH.
178
+ *
179
+ * @param pluginName - npm package name to look for (e.g. `opencode-rag-plugin`).
180
+ * @param deps - Test seams; leave empty in production.
181
+ * @returns The resolved install, or `null` when the package is not globally installed.
182
+ */
183
+ export function resolveGlobalInstall(pluginName, deps = {}) {
184
+ for (const name of candidatePackageManagerOrder(deps)) {
185
+ const root = SPECS[name].globalRoot(deps);
186
+ if (!root)
187
+ continue;
188
+ const packageDir = path.join(root, pluginName);
189
+ if ((deps.exists ?? existsSync)(packageDir)) {
190
+ return { pm: name, globalRoot: root, packageDir };
191
+ }
192
+ }
193
+ return deriveFromSelfLocation(pluginName, deps);
194
+ }
195
+ /**
196
+ * Derive `{ globalRoot, packageDir }` by walking up from this module's path to
197
+ * the package.json that names `pluginName`, then to the shallowest
198
+ * `node_modules` ancestor that still contains the package (for pnpm that is
199
+ * the outer global root, not the `.pnpm` store directory).
200
+ */
201
+ function deriveFromSelfLocation(pluginName, deps) {
202
+ const exists = deps.exists ?? existsSync;
203
+ const readJson = deps.readJson ?? ((filePath) => JSON.parse(readFileSync(filePath, "utf-8")));
204
+ let self;
205
+ try {
206
+ self = deps.selfPath ?? fileURLToPath(import.meta.url);
207
+ // Resolve junctions/symlinks so a runtime-dir junction points at the real
208
+ // global install instead of back at `~/.opencode/node_modules`.
209
+ if (!deps.selfPath)
210
+ self = realpathSync(self);
211
+ }
212
+ catch {
213
+ return null;
214
+ }
215
+ let dir = path.dirname(self);
216
+ for (let depth = 0; depth < 24; depth++) {
217
+ const pkgJson = path.join(dir, "package.json");
218
+ if (exists(pkgJson)) {
219
+ let name;
220
+ try {
221
+ name = readJson(pkgJson).name;
222
+ }
223
+ catch {
224
+ name = undefined;
225
+ }
226
+ if (name === pluginName) {
227
+ let globalRoot = null;
228
+ let probe = dir;
229
+ let parent = path.dirname(probe);
230
+ while (parent !== probe) {
231
+ if (path.basename(probe) === "node_modules" && exists(path.join(probe, pluginName))) {
232
+ globalRoot = probe;
233
+ }
234
+ probe = parent;
235
+ parent = path.dirname(probe);
236
+ }
237
+ if (globalRoot) {
238
+ return { pm: null, globalRoot, packageDir: dir };
239
+ }
240
+ return null;
241
+ }
242
+ }
243
+ const parent = path.dirname(dir);
244
+ if (parent === dir)
245
+ break;
246
+ dir = parent;
247
+ }
248
+ return null;
249
+ }
250
+ //# sourceMappingURL=package-manager.js.map
@@ -1,9 +1,9 @@
1
+ import { type GlobalInstall } from "./package-manager.js";
1
2
  export interface SetupResult {
2
3
  success: boolean;
3
4
  errors: string[];
4
5
  }
5
6
  export declare function getRuntimeDir(): string;
6
- export declare function getNpmGlobalRoot(): string;
7
7
  export declare function getVersionFile(runtimeDir: string): string;
8
8
  export declare function readVersionFile(versionFile: string): string | null;
9
9
  /**
@@ -12,10 +12,13 @@ export declare function readVersionFile(versionFile: string): string | null;
12
12
  * (e.g. Notepad++) instead of Node.js, the CLI opens the editor instead of
13
13
  * running. This function patches the wrappers to call `node` explicitly.
14
14
  *
15
- * Runs only on Windows. Safe to call on every setup — detects already-patched
16
- * wrappers by checking for the `node` prefix.
15
+ * npm only: pnpm/bun/yarn shims already invoke `node` explicitly, and their
16
+ * global bin directories are not laid out relative to the global root the way
17
+ * npm's are (`<prefix>\node_modules` next to `<prefix>`). Runs only on
18
+ * Windows; safe to call on every setup — detects already-patched wrappers by
19
+ * checking for the `node` prefix.
17
20
  */
18
- export declare function patchWindowsWrappers(npmGlobalRoot: string): void;
21
+ export declare function patchWindowsWrappers(install: GlobalInstall): void;
19
22
  export declare function setupRuntime(options?: {
20
23
  force?: boolean;
21
24
  silent?: boolean;