opencode-rag-plugin 2.3.0 → 2.4.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 (71) hide show
  1. package/ReadMe.md +73 -8
  2. package/dist/chunker/skeleton.js +1 -1
  3. package/dist/cli/commands/decide.d.ts +25 -0
  4. package/dist/cli/commands/decide.js +160 -0
  5. package/dist/cli/commands/eval.d.ts +23 -0
  6. package/dist/cli/commands/eval.js +331 -1
  7. package/dist/cli/commands/index-command.js +28 -10
  8. package/dist/cli/commands/index.d.ts +2 -1
  9. package/dist/cli/commands/index.js +2 -1
  10. package/dist/cli/commands/init-helpers.d.ts +20 -2
  11. package/dist/cli/commands/init-helpers.js +139 -22
  12. package/dist/cli/commands/init.js +42 -5
  13. package/dist/cli/commands/setup.js +43 -12
  14. package/dist/cli/commands/status.js +14 -8
  15. package/dist/cli/commands/update.d.ts +3 -2
  16. package/dist/cli/commands/update.js +7 -3
  17. package/dist/cli/format.d.ts +50 -0
  18. package/dist/cli/format.js +122 -0
  19. package/dist/cli/index.js +4 -1
  20. package/dist/cli/types.d.ts +2 -0
  21. package/dist/core/bootstrap.js +1 -0
  22. package/dist/core/config.d.ts +54 -2
  23. package/dist/core/config.js +36 -3
  24. package/dist/core/interfaces.d.ts +69 -0
  25. package/dist/core/package-manager.d.ts +69 -0
  26. package/dist/core/package-manager.js +250 -0
  27. package/dist/core/setup-runtime.d.ts +7 -4
  28. package/dist/core/setup-runtime.js +33 -31
  29. package/dist/core/version-check.d.ts +19 -11
  30. package/dist/core/version-check.js +30 -11
  31. package/dist/decision/factory.d.ts +17 -0
  32. package/dist/decision/factory.js +17 -0
  33. package/dist/decision/format.d.ts +14 -0
  34. package/dist/decision/format.js +53 -0
  35. package/dist/decision/systemone.d.ts +76 -0
  36. package/dist/decision/systemone.js +234 -0
  37. package/dist/decision/validate.d.ts +26 -0
  38. package/dist/decision/validate.js +74 -0
  39. package/dist/eval/decide-calibration.d.ts +112 -0
  40. package/dist/eval/decide-calibration.js +185 -0
  41. package/dist/eval/golden-gate.d.ts +65 -0
  42. package/dist/eval/golden-gate.js +61 -0
  43. package/dist/eval/golden-set.d.ts +81 -0
  44. package/dist/eval/golden-set.js +155 -0
  45. package/dist/eval/rerank-eval.js +10 -125
  46. package/dist/index.d.ts +6 -2
  47. package/dist/index.js +4 -0
  48. package/dist/indexer/pipeline.d.ts +0 -10
  49. package/dist/indexer/pipeline.js +1 -0
  50. package/dist/mcp/handlers.d.ts +17 -1
  51. package/dist/mcp/handlers.js +30 -0
  52. package/dist/mcp/server.d.ts +9 -1
  53. package/dist/mcp/server.js +47 -3
  54. package/dist/opencode/system-guidance.d.ts +11 -0
  55. package/dist/opencode/system-guidance.js +53 -0
  56. package/dist/opencode/tools.d.ts +24 -1
  57. package/dist/opencode/tools.js +101 -0
  58. package/dist/plugin.js +21 -3
  59. package/dist/quirks/quirk-store.d.ts +2 -0
  60. package/dist/quirks/quirk-store.js +33 -4
  61. package/dist/tui.js +21 -2
  62. package/dist/v2/v2-adapter.d.ts +20 -0
  63. package/dist/v2/v2-adapter.js +36 -8
  64. package/dist/vectorstore/lancedb.js +54 -5
  65. package/dist/watcher.d.ts +26 -1
  66. package/dist/watcher.js +71 -9
  67. package/dist/web/ui/assets/index-CWcp0jNf.css +2 -0
  68. package/dist/web/ui/index.html +2 -2
  69. package/package.json +5 -2
  70. package/dist/web/ui/assets/index-Dp009QCQ.css +0 -1
  71. /package/dist/web/ui/assets/{index-C0QXKA-b.js → index-DbXFrn53.js} +0 -0
@@ -6,6 +6,7 @@
6
6
  * and result formatting functions shared across all CLI command modules.
7
7
  */
8
8
  import pc from "picocolors";
9
+ import path from "node:path";
9
10
  import { resolveRagContext } from "../core/bootstrap.js";
10
11
  import { destroyAllPooledConnections } from "../embedder/http.js";
11
12
  import { appendDebugLog } from "../core/fileLogger.js";
@@ -139,6 +140,118 @@ export function formatTimestamp(timestamp) {
139
140
  return "never";
140
141
  return new Date(timestamp).toLocaleString();
141
142
  }
143
+ /**
144
+ * Format a Unix timestamp as a compact "time since" label (e.g. `"5m ago"`).
145
+ *
146
+ * @param timestamp - Unix timestamp in milliseconds, or `undefined` for "never".
147
+ * @param now - Reference time in ms (defaults to `Date.now()`, injectable for tests).
148
+ * @returns A human-readable age such as `"just now"`, `"2h ago"`, or `"3d ago"`.
149
+ */
150
+ export function formatRelativeAge(timestamp, now = Date.now()) {
151
+ if (!timestamp)
152
+ return "never";
153
+ const diffMinutes = Math.floor(Math.max(0, now - timestamp) / 60_000);
154
+ if (diffMinutes < 1)
155
+ return "just now";
156
+ if (diffMinutes < 60)
157
+ return `${diffMinutes}m ago`;
158
+ const diffHours = Math.floor(diffMinutes / 60);
159
+ if (diffHours < 48)
160
+ return `${diffHours}h ago`;
161
+ return `${Math.floor(diffHours / 24)}d ago`;
162
+ }
163
+ /**
164
+ * Classify an index pass from its stats. Mirrors the messages printed by the `index`
165
+ * command and the exit-code mapping: 0 = ok, 3 = partial, 1 = incomplete/interrupted.
166
+ *
167
+ * @param stats - Statistics from a single indexing pass.
168
+ * @returns The pass status.
169
+ */
170
+ export function classifyIndexRun(stats) {
171
+ if (stats.embeddingUnavailable)
172
+ return "incomplete";
173
+ if (stats.totalChunks === 0 && stats.newFiles + stats.modifiedFiles > 0)
174
+ return "incomplete";
175
+ if (stats.extractionFailures > 0 || stats.descriptionFailedFiles > 0 || stats.embeddingFailures > 0) {
176
+ return "partial";
177
+ }
178
+ return "ok";
179
+ }
180
+ /**
181
+ * Build short human-readable descriptions of a partial pass's problems.
182
+ *
183
+ * @param stats - Statistics from a single indexing pass.
184
+ * @returns One string per problem category; empty when the pass was clean.
185
+ */
186
+ export function describeIndexProblems(stats) {
187
+ const parts = [];
188
+ if (stats.extractionFailures > 0)
189
+ parts.push(`${stats.extractionFailures} file(s) failed content extraction`);
190
+ if (stats.descriptionFailedFiles > 0)
191
+ parts.push(`${stats.descriptionFailedFiles} file(s) had description failures`);
192
+ if (stats.embeddingFailures > 0)
193
+ parts.push(`${stats.embeddingFailures} chunk(s) had no vectors`);
194
+ return parts;
195
+ }
196
+ /** Extraction error paths shown in the human summary before truncating. */
197
+ const MAX_SHOWN_EXTRACTION_ERRORS = 5;
198
+ /** Extraction errors included in the JSON summary before truncating. */
199
+ const MAX_JSON_EXTRACTION_ERRORS = 20;
200
+ /** Longest error text rendered before truncation. */
201
+ const MAX_ERROR_CHARS = 160;
202
+ /** Collapse whitespace and truncate an error message for one-line display. */
203
+ function truncateError(error) {
204
+ const oneLine = error.replace(/\s+/g, " ").trim();
205
+ return oneLine.length > MAX_ERROR_CHARS ? `${oneLine.slice(0, MAX_ERROR_CHARS - 1)}…` : oneLine;
206
+ }
207
+ /** Make a path workspace-relative when it is inside the workspace; keep it otherwise. */
208
+ function toWorkspaceRelative(cwd, filePath) {
209
+ try {
210
+ const rel = path.relative(cwd, filePath);
211
+ return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel : filePath;
212
+ }
213
+ catch {
214
+ return filePath;
215
+ }
216
+ }
217
+ /**
218
+ * Build the machine-readable `index --json` summary. The CLI prints this object as a
219
+ * single line of JSON so agents can parse the outcome without scraping log text.
220
+ *
221
+ * @param stats - Statistics from a single indexing pass.
222
+ * @param opts - Workspace, timing, and interrupt information.
223
+ * @returns A plain JSON-serializable object (schema version 1).
224
+ */
225
+ export function buildIndexSummaryJson(stats, opts) {
226
+ const extractionErrors = stats.extractionErrors
227
+ .slice(0, MAX_JSON_EXTRACTION_ERRORS)
228
+ .map((entry) => ({
229
+ file: toWorkspaceRelative(opts.cwd, entry.filePath),
230
+ error: truncateError(entry.error),
231
+ }));
232
+ return {
233
+ schema: 1,
234
+ status: opts.interrupted ? "interrupted" : classifyIndexRun(stats),
235
+ startedAt: new Date(opts.startedAt).toISOString(),
236
+ durationMs: opts.durationMs,
237
+ totalFiles: stats.totalFiles,
238
+ newFiles: stats.newFiles,
239
+ modifiedFiles: stats.modifiedFiles,
240
+ unchangedFiles: stats.unchangedFiles,
241
+ deletedFiles: stats.deletedFiles,
242
+ removedFiles: stats.removedFiles,
243
+ skippedEmptyFiles: stats.skippedEmptyFiles,
244
+ skippedSmallFiles: stats.skippedSmallFiles,
245
+ totalChunks: stats.totalChunks,
246
+ finalCount: stats.finalCount,
247
+ extractionFailures: stats.extractionFailures,
248
+ descriptionFailedFiles: stats.descriptionFailedFiles,
249
+ embeddingFailures: stats.embeddingFailures,
250
+ embeddingUnavailable: stats.embeddingUnavailable,
251
+ extractionErrors,
252
+ extractionErrorsTruncated: stats.extractionErrors.length > extractionErrors.length,
253
+ };
254
+ }
142
255
  /**
143
256
  * Print an indexing pass summary to stdout.
144
257
  *
@@ -153,6 +266,15 @@ export function logIndexSummary(logFilePath, stats) {
153
266
  logCliInfo(logFilePath, "index", ` ${c.label("Removed:")} ${c.num(stats.removedFiles)}`);
154
267
  logCliInfo(logFilePath, "index", ` ${c.label("Empty skipped:")} ${c.num(stats.skippedEmptyFiles)}`);
155
268
  logCliInfo(logFilePath, "index", ` ${c.label("Small skipped:")} ${c.num(stats.skippedSmallFiles)}`);
269
+ if (stats.extractionFailures > 0) {
270
+ logCliInfo(logFilePath, "index", ` ${c.label("Extract failed:")} ${c.num(stats.extractionFailures)} file(s)`);
271
+ for (const entry of stats.extractionErrors.slice(0, MAX_SHOWN_EXTRACTION_ERRORS)) {
272
+ logCliInfo(logFilePath, "index", ` ${c.file(entry.filePath)} — ${c.dim(truncateError(entry.error))}`);
273
+ }
274
+ if (stats.extractionErrors.length > MAX_SHOWN_EXTRACTION_ERRORS) {
275
+ logCliInfo(logFilePath, "index", ` ${c.dim(`… and ${stats.extractionErrors.length - MAX_SHOWN_EXTRACTION_ERRORS} more (see log)`)}`);
276
+ }
277
+ }
156
278
  if (stats.descriptionFailedFiles > 0) {
157
279
  logCliInfo(logFilePath, "index", ` ${c.label("Desc failed:")} ${c.num(stats.descriptionFailedFiles)}`);
158
280
  }
package/dist/cli/index.js CHANGED
@@ -15,7 +15,7 @@ import { realpathSync } from "node:fs";
15
15
  import { basename, dirname } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { getPackageMetadata } from "./helpers.js";
18
- import { registerIndexCommand, registerQueryCommand, registerClearCommand, registerStatusCommand, registerListCommand, registerShowCommand, registerDumpCommand, registerInitCommand, registerUiCommand, registerMcpCommand, registerSetupCommand, registerUpdateCommand, registerEvalSessionsCommand, registerEvalAnalyzeCommand, registerEvalCompareCommand, registerDescribeImageCommand, registerQuirkCommand, } from "./commands/index.js";
18
+ import { registerIndexCommand, registerQueryCommand, registerClearCommand, registerStatusCommand, registerListCommand, registerShowCommand, registerDumpCommand, registerInitCommand, registerUiCommand, registerMcpCommand, registerSetupCommand, registerUpdateCommand, registerEvalSessionsCommand, registerEvalAnalyzeCommand, registerEvalCompareCommand, registerEvalGateCommand, registerEvalDecideCommand, registerDescribeImageCommand, registerDecideCommand, registerQuirkCommand, } from "./commands/index.js";
19
19
  /**
20
20
  * The top-level Commander program instance that defines the `opencode-rag` CLI.
21
21
  *
@@ -37,6 +37,7 @@ registerListCommand(program);
37
37
  registerShowCommand(program);
38
38
  registerDumpCommand(program);
39
39
  registerDescribeImageCommand(program);
40
+ registerDecideCommand(program);
40
41
  registerUiCommand(program);
41
42
  registerMcpCommand(program);
42
43
  registerSetupCommand(program);
@@ -44,6 +45,8 @@ registerUpdateCommand(program);
44
45
  registerEvalSessionsCommand(program);
45
46
  registerEvalAnalyzeCommand(program);
46
47
  registerEvalCompareCommand(program);
48
+ registerEvalGateCommand(program);
49
+ registerEvalDecideCommand(program);
47
50
  registerInitCommand(program);
48
51
  registerQuirkCommand(program);
49
52
  // ── Auto-run detection ──────────────────────────────────────────
@@ -20,6 +20,8 @@ export interface CliOptions {
20
20
  explain?: boolean;
21
21
  /** Skip confirmation prompts for destructive operations. */
22
22
  yes?: boolean;
23
+ /** Print a machine-readable JSON summary as the last line of the `index` command. */
24
+ json?: boolean;
23
25
  /** Optional system prompt to steer an image description toward specific features. */
24
26
  systemPrompt?: string;
25
27
  }
@@ -109,6 +109,7 @@ export async function resolveRagContext(opts = {}) {
109
109
  // Surface only store-level drift (the split-brain symptom). Keyword-index
110
110
  // healing is routine (addQuirk never persisted the index) and stays silent.
111
111
  console.warn(`[bootstrap] Quirk reconcile: restored ${rec.restoredToStore} to store, ` +
112
+ `deduplicated ${rec.deduplicated}, ` +
112
113
  `removed ${rec.removedOrphans} orphans (keyword index: +${rec.addedToKeywordIndex})`);
113
114
  }
114
115
  }
@@ -154,6 +154,51 @@ export interface ImageDescriptionConfig {
154
154
  */
155
155
  onDemand?: ImageDescriptionOnDemandConfig;
156
156
  }
157
+ /**
158
+ * Configuration for decision-model (tev1) calls via Ollama's
159
+ * `/v1/systemone` endpoint — classification, routing, policy checks, and
160
+ * rubrics.
161
+ */
162
+ export interface DecisionConfig {
163
+ /**
164
+ * Whether the `make_decision` tool is available. Default false: tev1
165
+ * requires Ollama >= 0.35 and an explicitly pulled model (`ollama pull tev1`).
166
+ */
167
+ enabled: boolean;
168
+ /** Decision provider name. Only "ollama" is supported for now. */
169
+ provider: string;
170
+ /**
171
+ * Base URL of the Ollama server. Both root URLs (`http://127.0.0.1:11434`)
172
+ * and the `/api`-suffixed convention used by the other sections are
173
+ * accepted — `/api` is stripped because decision models are served at
174
+ * `/v1/systemone`.
175
+ */
176
+ baseUrl: string;
177
+ /** Decision model name (`tev1`/`tev1:4b` or `tev1:0.8b`). */
178
+ model: string;
179
+ /** Request timeout in milliseconds. The first call may load the model. */
180
+ timeoutMs: number;
181
+ /** Ollama keep_alive value (e.g. "30m", "-1" for keep-in-memory). */
182
+ keepAlive?: string;
183
+ /** Proxy configuration. */
184
+ proxy?: ProxyConfig;
185
+ /**
186
+ * When enabled, agent guidance instructs the agent to route choices through
187
+ * `make_decision` before asking the user (proceed on a confident answer;
188
+ * ask only when the model is undecided or the choice is preference-based).
189
+ * Default false — asking the user stays the default behavior.
190
+ */
191
+ routeBeforeAsking?: boolean;
192
+ /**
193
+ * Maximum characters accepted for `state`. The decision context is small
194
+ * (~2k tokens), so oversized states are rejected instead of truncated.
195
+ */
196
+ maxStateChars?: number;
197
+ /** Maximum retry attempts on retryable failures. */
198
+ retryMax?: number;
199
+ /** Base delay in ms between retries (exponential backoff). */
200
+ retryBaseDelayMs?: number;
201
+ }
157
202
  export interface UiConfig {
158
203
  /** HTTP port for the UI server. */
159
204
  port: number;
@@ -306,7 +351,7 @@ export interface RerankingConfig {
306
351
  maxDocChars?: number;
307
352
  /** Additional gate on the rerank score itself (0 = pure reorder, default). NOT comparable to retrieval.minScore — rerank scores are provider-scaled, not calibrated. */
308
353
  minScore?: number;
309
- /** Per-call timeout in ms; on expiry the fusion order is kept. @default 1500 */
354
+ /** Per-call timeout in ms; on expiry the fusion order is kept. @default 4000 */
310
355
  timeoutMs?: number;
311
356
  /**
312
357
  * Query template applied before scoring. With a `{query}` placeholder the
@@ -315,7 +360,12 @@ export interface RerankingConfig {
315
360
  * reuse embedding.queryPrefix here. @default ""
316
361
  */
317
362
  queryTemplate?: string;
318
- /** Document text: raw content, or description + content. @default "content" */
363
+ /**
364
+ * Document text: raw content, or description + content.
365
+ * `"content+description"` was the best arm in the 2026-10-02 eval (Hit@1 29.2 % vs 22.9 %,
366
+ * MRR 0.466 vs 0.414) — descriptions carry signal the raw code text misses.
367
+ * @default "content+description"
368
+ */
319
369
  docField?: "content" | "content+description";
320
370
  /** Proxy configuration for the rerank endpoint. */
321
371
  proxy?: ProxyConfig;
@@ -516,6 +566,8 @@ export interface RagConfig {
516
566
  description?: DescriptionConfig;
517
567
  /** Vision-model-based image description config. */
518
568
  imageDescription?: ImageDescriptionConfig;
569
+ /** Decision-model (tev1) config for the `make_decision` tool. */
570
+ decision?: DecisionConfig;
519
571
  /** Automated documentation mode config. */
520
572
  documentationMode?: DocumentationModeConfig;
521
573
  /** Wiki mode config that instructs the AI agent to maintain a persistent knowledge wiki. */
@@ -155,9 +155,9 @@ export const DEFAULT_CONFIG = {
155
155
  candidates: 20,
156
156
  maxDocChars: 1200,
157
157
  minScore: 0,
158
- timeoutMs: 1500,
158
+ timeoutMs: 4000,
159
159
  queryTemplate: "",
160
- docField: "content",
160
+ docField: "content+description",
161
161
  },
162
162
  openCode: {
163
163
  enabled: true,
@@ -182,6 +182,18 @@ export const DEFAULT_CONFIG = {
182
182
  numCtx: 2048,
183
183
  resizeMaxDimension: 1024,
184
184
  },
185
+ decision: {
186
+ enabled: false,
187
+ provider: "ollama",
188
+ baseUrl: "http://127.0.0.1:11434/api",
189
+ model: "tev1:4b",
190
+ timeoutMs: 120000,
191
+ keepAlive: "30m",
192
+ maxStateChars: 8000,
193
+ routeBeforeAsking: false,
194
+ retryMax: 2,
195
+ retryBaseDelayMs: 500,
196
+ },
185
197
  description: {
186
198
  enabled: true,
187
199
  provider: "ollama",
@@ -341,7 +353,7 @@ export function validateConfig(config) {
341
353
  const KNOWN_TOP_KEYS = new Set([
342
354
  "embedding", "indexing", "vectorStore", "retrieval", "reranking",
343
355
  "openCode", "chunkers", "chunking", "description",
344
- "imageDescription", "documentationMode", "wikiMode", "mcp", "autoUpdate", "memory", "ui", "tui", "logging",
356
+ "imageDescription", "decision", "documentationMode", "wikiMode", "mcp", "autoUpdate", "memory", "ui", "tui", "logging",
345
357
  ]);
346
358
  const topKeys = new Set(Object.keys(config));
347
359
  for (const key of topKeys) {
@@ -508,6 +520,23 @@ export function validateConfig(config) {
508
520
  warnings.push("imageDescription.onDemand.timeoutMs must be > 0");
509
521
  }
510
522
  }
523
+ if (config.decision) {
524
+ if (config.decision.provider !== "ollama") {
525
+ warnings.push(`decision.provider "${config.decision.provider}" is not supported yet — only "ollama" (tev1 via /v1/systemone)`);
526
+ }
527
+ if (config.decision.timeoutMs != null && config.decision.timeoutMs <= 0) {
528
+ warnings.push("decision.timeoutMs must be > 0");
529
+ }
530
+ if (config.decision.maxStateChars != null && config.decision.maxStateChars <= 0) {
531
+ warnings.push("decision.maxStateChars must be > 0");
532
+ }
533
+ try {
534
+ new URL(config.decision.baseUrl);
535
+ }
536
+ catch {
537
+ warnings.push(`decision.baseUrl "${config.decision.baseUrl}" is not a valid URL`);
538
+ }
539
+ }
511
540
  if (config.reranking?.enabled) {
512
541
  const rr = config.reranking;
513
542
  if (!rr.baseUrl)
@@ -632,6 +661,10 @@ export function loadConfig(filePath, validate = true) {
632
661
  ...DEFAULT_CONFIG.imageDescription,
633
662
  ...(safeObj(parsed.imageDescription) ?? {}),
634
663
  },
664
+ decision: {
665
+ ...DEFAULT_CONFIG.decision,
666
+ ...(safeObj(parsed.decision) ?? {}),
667
+ },
635
668
  documentationMode: {
636
669
  ...DEFAULT_CONFIG.documentationMode,
637
670
  ...(safeObj(parsed.documentationMode) ?? {}),
@@ -63,6 +63,75 @@ export interface DescriptionProvider {
63
63
  timeoutMs?: number;
64
64
  }): Promise<string>;
65
65
  }
66
+ /** Question types supported by the decision model. */
67
+ export type DecisionQuestionType = "choice" | "noul" | "score";
68
+ /**
69
+ * A single question asked of the decision model.
70
+ *
71
+ * - `choice`: `criteria` maps option name → description (2-24 options);
72
+ * add a `none` option when no listed option may fit.
73
+ * - `noul`: true/false probability; optional `criteria` describes each side.
74
+ * - `score`: `criteria` is an ordered array of level descriptions, lowest first.
75
+ */
76
+ export interface DecisionQuestion {
77
+ /** Unique name for the question; answers are keyed by it. */
78
+ id: string;
79
+ /** Question type. */
80
+ type: DecisionQuestionType;
81
+ /** Natural-language instruction describing what to decide. */
82
+ instructions: string;
83
+ /** Answer criteria — shape depends on `type` (see interface docs). */
84
+ criteria?: Record<string, string> | string[] | {
85
+ true?: string;
86
+ false?: string;
87
+ };
88
+ }
89
+ /** The model's answer to a single question. */
90
+ export interface DecisionAnswer {
91
+ /** Question id this answer belongs to. */
92
+ id: string;
93
+ /** Question type this answer belongs to. */
94
+ type: DecisionQuestionType;
95
+ /** Chosen option for `choice` questions. */
96
+ choice?: string;
97
+ /** Probability that a `noul` question is true (0-1). */
98
+ noul?: number;
99
+ /** Probability-weighted level for `score` questions (0-based). */
100
+ score?: number;
101
+ /** Level labels for `score` answers, lowest first. */
102
+ legend?: string[];
103
+ /** Probability distribution over options (choice) or levels (score). */
104
+ probabilities?: Record<string, number> | number[];
105
+ /**
106
+ * How concentrated the probability mass is (0-1). This is NOT the chance
107
+ * the answer is correct — use it to detect an undecided model.
108
+ */
109
+ confidence?: number;
110
+ }
111
+ /** Request payload for a decision-model call. */
112
+ export interface DecisionRequest {
113
+ /** Text (or JSON string) the questions are judged against. Keep it short. */
114
+ state: string;
115
+ /** 1-64 named questions. */
116
+ questions: DecisionQuestion[];
117
+ }
118
+ /** Result of a decision-model call. */
119
+ export interface DecisionResult {
120
+ /** One answer per requested question, in request order. */
121
+ answers: DecisionAnswer[];
122
+ /** Raw provider response, retained for diagnostics. */
123
+ raw?: unknown;
124
+ }
125
+ /**
126
+ * Answers classification/decision questions against a text using a decision
127
+ * model (tev1 via Ollama's `/v1/systemone`).
128
+ */
129
+ export interface DecisionProvider {
130
+ /** Provider name (e.g. "ollama"). */
131
+ readonly name: string;
132
+ /** Run a decision request; one answer is returned per question. */
133
+ decide(request: DecisionRequest, abort?: AbortSignal): Promise<DecisionResult>;
134
+ }
66
135
  /** Explains how a search result score was computed, including vector and keyword contributions. */
67
136
  export interface SearchExplanation {
68
137
  /** Breakdown of the fused score components. */
@@ -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;