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
@@ -8,8 +8,8 @@
8
8
  import path from "node:path";
9
9
  import os from "node:os";
10
10
  import { existsSync, mkdirSync, rmSync, symlinkSync, } from "node:fs";
11
- import { execSync } from "node:child_process";
12
11
  import { DEFAULT_CONFIG } from "../../core/config.js";
12
+ import { installHint, resolveGlobalInstall } from "../../core/package-manager.js";
13
13
  import { c } from "../format.js";
14
14
  import { BEGIN_MARKER, END_MARKER, buildAgentsMdDirective } from "../../opencode/system-guidance.js";
15
15
  import { getStringRecord, readJsonObject, writeJsonFile, } from "../helpers.js";
@@ -247,6 +247,71 @@ export function generateSkillFile() {
247
247
  "",
248
248
  ].join("\n");
249
249
  }
250
+ /**
251
+ * Generate the content for `.opencode/skills/make-decision/SKILL.md`.
252
+ *
253
+ * Provides decision-model usage guidance for AI assistants: when to reach for
254
+ * `make_decision`, the three question types, prerequisites, and limits.
255
+ *
256
+ * @returns The full Markdown content of the decision skill file.
257
+ */
258
+ export function generateDecisionSkillFile() {
259
+ return [
260
+ "---",
261
+ "name: make-decision",
262
+ "description: Classify, route, or score short text with the local tev1 decision model via the make_decision tool (Ollama /v1/systemone)",
263
+ "---",
264
+ "",
265
+ "## Decision Model (`make_decision`)",
266
+ "",
267
+ "Use `make_decision(state, questions)` when a task reduces to a fast classification, routing choice, policy check, or rubric score over short text — e.g. \"which module owns this error?\", \"is this request within policy?\", \"rate the severity\". It calls a local decision model (tev1) that returns the chosen option with probabilities.",
268
+ "",
269
+ "### Prerequisites",
270
+ "",
271
+ "- `decision.enabled` must be `true` in `opencode-rag.json` (off by default).",
272
+ "- Requires Ollama >= 0.35 with a pulled tev1 model (`ollama pull tev1` or `ollama pull tev1:0.8b`).",
273
+ "- Keep `state` short — the effective context is ~2k tokens. Pass the relevant excerpt, not a whole file.",
274
+ "",
275
+ "### Questions",
276
+ "",
277
+ "Each question needs `id`, `type`, and `instructions`:",
278
+ "",
279
+ "- `choice` — pick one of 2-24 options. `criteria` maps option → description. Add a `none` option when no listed option may fit.",
280
+ "- `noul` — true/false probability. Optional criteria `{ \"true\": \"...\", \"false\": \"...\" }` describe each side.",
281
+ "- `score` — place the state on a rubric. `criteria` is an ordered array of 2-24 level descriptions, lowest first.",
282
+ "",
283
+ "### Example",
284
+ "",
285
+ "```json",
286
+ "{",
287
+ " \"state\": \"Customer says they were charged twice for the October subscription.\",",
288
+ " \"questions\": [",
289
+ " {",
290
+ " \"id\": \"intent\",",
291
+ " \"type\": \"choice\",",
292
+ " \"instructions\": \"Which support intent best matches the message?\",",
293
+ " \"criteria\": {",
294
+ " \"duplicate_charge\": \"Charged more than once.\",",
295
+ " \"cancel\": \"Wants to end the subscription.\",",
296
+ " \"none\": \"None of the listed intents matches.\"",
297
+ " }",
298
+ " }",
299
+ " ]",
300
+ "}",
301
+ "```",
302
+ "",
303
+ "### Optional: route decisions before asking the user",
304
+ "",
305
+ "- When `decision.routeBeforeAsking` is `true`, route option choices through `make_decision` before interrupting the user: proceed when the model is confident, and ask the user only when it is undecided (low `confidence`) or the choice depends on personal preference.",
306
+ "",
307
+ "### Limits",
308
+ "",
309
+ "- 1-64 questions per call; 2-24 options/levels per question.",
310
+ "- `confidence` is probability concentration, NOT the chance the answer is correct.",
311
+ "- Never rely on it as the only check for a high-stakes decision; treat low-confidence answers as undecided.",
312
+ "",
313
+ ].join("\n");
314
+ }
250
315
  /**
251
316
  * Merge required entries into an existing `.gitignore` content string.
252
317
  *
@@ -296,11 +361,19 @@ export function mergeGitignoreContent(existingContent) {
296
361
  *
297
362
  * @param existingContent - The current `AGENTS.md` content, or `undefined` if absent.
298
363
  * @param opts - Optional settings. `promptEnforcement` controls whether the
299
- * quirk-capture enforcement rules are included (default `true`).
364
+ * quirk-capture enforcement rules are included (default `true`);
365
+ * `decisionEnabled` controls whether the `make_decision` guidance section is
366
+ * included (default `false` — the tool is not registered when disabled);
367
+ * `routeBeforeAsking` adds the optional pre-ask decision-routing rule
368
+ * (default `false`).
300
369
  * @returns The merged `AGENTS.md` content with a trailing newline.
301
370
  */
302
371
  export function mergeAgentsMdContent(existingContent, opts) {
303
- const section = buildAgentsMdDirective({ promptEnforcement: opts?.promptEnforcement ?? true });
372
+ const section = buildAgentsMdDirective({
373
+ promptEnforcement: opts?.promptEnforcement ?? true,
374
+ decisionEnabled: opts?.decisionEnabled ?? false,
375
+ routeBeforeAsking: opts?.routeBeforeAsking ?? false,
376
+ });
304
377
  if (!existingContent) {
305
378
  return `${section}\n`;
306
379
  }
@@ -359,28 +432,22 @@ export async function installPluginFromGlobal(opencodeDir, packageName, skipInst
359
432
  const globalPluginDir = path.join(runtimeDir, "node_modules", packageName);
360
433
  const workspaceTarget = path.join(opencodeDir, "node_modules", packageName);
361
434
  if (!existsSync(globalPluginDir)) {
362
- // Fallback: try the global npm prefix
363
- let globalRoot;
364
- try {
365
- globalRoot = execSync("npm root -g", { encoding: "utf-8", timeout: 10_000 }).trim();
366
- }
367
- catch {
368
- throw new Error(`Global plugin cache not found at ${globalPluginDir}. ` +
369
- "Run 'opencode-rag setup' or install globally with 'npm install -g opencode-rag-plugin' first.");
370
- }
371
- const globalNpmPluginDir = path.join(globalRoot, packageName);
372
- if (existsSync(globalNpmPluginDir) && existsSync(path.join(globalNpmPluginDir, "dist", "cli.js"))) {
373
- console.log(` ${c.created("Found:")} ${packageName} in global npm prefix, linking...`);
435
+ // Fallback: locate a global install via any package manager (issue #34:
436
+ // npm may be absent — pnpm/yarn/bun installs must resolve too).
437
+ const install = resolveGlobalInstall(packageName);
438
+ if (install && existsSync(path.join(install.packageDir, "dist", "cli.js"))) {
439
+ const pmLabel = install.pm ? `global ${install.pm} install` : "global install";
440
+ console.log(` ${c.created("Found:")} ${packageName} in ${pmLabel}, linking...`);
374
441
  if (existsSync(workspaceTarget)) {
375
442
  rmSync(workspaceTarget, { recursive: true, force: true });
376
443
  }
377
444
  mkdirSync(path.dirname(workspaceTarget), { recursive: true });
378
- createJunction(globalNpmPluginDir, workspaceTarget);
445
+ createJunction(install.packageDir, workspaceTarget);
379
446
  const cliEntry = path.join(workspaceTarget, "dist", "cli.js");
380
447
  if (existsSync(cliEntry)) {
381
- console.log(` ${c.success("Linked:")} ${packageName} from global npm`);
382
- // Also link @opencode-ai/plugin from global npm
383
- const globalSdkDir = path.join(globalRoot, "@opencode-ai", "plugin");
448
+ console.log(` ${c.success("Linked:")} ${packageName} from the global install`);
449
+ // Also link @opencode-ai/plugin from the same global node_modules
450
+ const globalSdkDir = path.join(install.globalRoot, "@opencode-ai", "plugin");
384
451
  const workspaceSdkDir = path.join(opencodeDir, "node_modules", "@opencode-ai", "plugin");
385
452
  if (existsSync(globalSdkDir) && !existsSync(workspaceSdkDir)) {
386
453
  mkdirSync(path.dirname(workspaceSdkDir), { recursive: true });
@@ -392,14 +459,14 @@ export async function installPluginFromGlobal(opencodeDir, packageName, skipInst
392
459
  cpSync(globalSdkDir, workspaceSdkDir, { recursive: true });
393
460
  }
394
461
  }
395
- console.log(` ${c.success("Linked:")} @opencode-ai/plugin from global npm`);
462
+ console.log(` ${c.success("Linked:")} @opencode-ai/plugin from the global install`);
396
463
  return;
397
464
  }
398
465
  // Junction failed or incomplete — fall through to error
399
466
  rmSync(workspaceTarget, { recursive: true, force: true });
400
467
  }
401
468
  throw new Error(`Global plugin cache not found at ${globalPluginDir}. ` +
402
- "Run 'opencode-rag setup' or install globally with 'npm install -g opencode-rag-plugin' first.");
469
+ `Run 'opencode-rag setup' or install globally first (${installHint(packageName)}).`);
403
470
  }
404
471
  // Remove any stale copy (e.g. from a previous 'npm install' run)
405
472
  if (existsSync(workspaceTarget)) {
@@ -437,20 +504,61 @@ export async function installPluginFromGlobal(opencodeDir, packageName, skipInst
437
504
  "Run 'install.sh compile' / 'install.ps1 compile' to install it.");
438
505
  }
439
506
  }
507
+ /**
508
+ * `embedding` keys that the default template does not model but that MUST
509
+ * survive a rewrite. Losing `vectorDimension` makes the next run fall back to
510
+ * the 384 default (and corrupts a rebuild against a store whose schema is
511
+ * 4096), and `apiKey` is provider auth the template never carries — both are
512
+ * invisible data loss when a user confirms "Overwrite with default config?".
513
+ */
514
+ const PRESERVED_EMBEDDING_KEYS = ["apiKey", "vectorDimension"];
515
+ /**
516
+ * Pick the identity-critical `embedding` keys out of an existing config file so
517
+ * the generated defaults can re-apply them. Malformed input simply yields an
518
+ * empty set (the pure default template).
519
+ */
520
+ function preservedEmbeddingKeys(existingConfigRaw) {
521
+ if (!existingConfigRaw)
522
+ return {};
523
+ try {
524
+ const raw = existingConfigRaw.charCodeAt(0) === 0xfeff
525
+ ? existingConfigRaw.slice(1)
526
+ : existingConfigRaw;
527
+ const parsed = JSON.parse(raw);
528
+ const embedding = parsed?.embedding;
529
+ if (!embedding || typeof embedding !== "object")
530
+ return {};
531
+ const preserved = {};
532
+ for (const key of PRESERVED_EMBEDDING_KEYS) {
533
+ const value = embedding[key];
534
+ if (value !== undefined && value !== null && value !== "") {
535
+ preserved[key] = value;
536
+ }
537
+ }
538
+ return preserved;
539
+ }
540
+ catch {
541
+ return {};
542
+ }
543
+ }
440
544
  /**
441
545
  * Generate the default `opencode-rag.json` configuration content.
442
546
  *
443
547
  * @param tuning - Optional embedding batch tuning (auto-detected from the
444
548
  * Ollama backend). Falls back to `DEFAULT_CONFIG` for any omitted field.
549
+ * @param existingConfigRaw - Optional raw text of the config file that is about
550
+ * to be replaced. Its `apiKey` and `vectorDimension` are carried over: a
551
+ * reset must not silently change the store schema or drop provider auth.
445
552
  * @returns A pretty-printed JSON string with all default configuration values.
446
553
  */
447
- export function generateDefaultConfigJson(tuning) {
554
+ export function generateDefaultConfigJson(tuning, existingConfigRaw) {
448
555
  return JSON.stringify({
449
556
  embedding: {
450
557
  provider: DEFAULT_CONFIG.embedding.provider,
451
558
  baseUrl: DEFAULT_CONFIG.embedding.baseUrl,
452
559
  model: DEFAULT_CONFIG.embedding.model,
453
560
  timeoutMs: DEFAULT_CONFIG.embedding.timeoutMs,
561
+ ...preservedEmbeddingKeys(existingConfigRaw),
454
562
  },
455
563
  indexing: {
456
564
  includeExtensions: DEFAULT_CONFIG.indexing.includeExtensions,
@@ -493,6 +601,15 @@ export function generateDefaultConfigJson(tuning) {
493
601
  think: DEFAULT_CONFIG.imageDescription.think,
494
602
  numCtx: DEFAULT_CONFIG.imageDescription.numCtx,
495
603
  },
604
+ decision: {
605
+ enabled: DEFAULT_CONFIG.decision.enabled,
606
+ provider: DEFAULT_CONFIG.decision.provider,
607
+ baseUrl: DEFAULT_CONFIG.decision.baseUrl,
608
+ model: DEFAULT_CONFIG.decision.model,
609
+ timeoutMs: DEFAULT_CONFIG.decision.timeoutMs,
610
+ keepAlive: DEFAULT_CONFIG.decision.keepAlive,
611
+ routeBeforeAsking: DEFAULT_CONFIG.decision.routeBeforeAsking,
612
+ },
496
613
  description: {
497
614
  enabled: DEFAULT_CONFIG.description.enabled,
498
615
  provider: DEFAULT_CONFIG.description.provider,
@@ -16,7 +16,7 @@ import { checkProviderHealth, pullOllamaModels } from "../../embedder/health.js"
16
16
  import { destroyAllPooledConnections } from "../../embedder/http.js";
17
17
  import { c } from "../format.js";
18
18
  import { getPackageMetadata, readJsonObject, writeJsonFile } from "../helpers.js";
19
- import { buildOpencodeConfig, buildWorkspacePackageJson, generateDefaultConfigJson, generateSkillFile, generateWorkspacePluginFile, generateWorkspaceTuiPluginFile, installPluginFromGlobal, mergeAgentsMdContent, mergeGitignoreContent, } from "./init-helpers.js";
19
+ import { buildOpencodeConfig, buildWorkspacePackageJson, generateDefaultConfigJson, generateSkillFile, generateDecisionSkillFile, generateWorkspacePluginFile, generateWorkspaceTuiPluginFile, installPluginFromGlobal, mergeAgentsMdContent, mergeGitignoreContent, } from "./init-helpers.js";
20
20
  import { detectOllamaBackend } from "./backend-detect.js";
21
21
  /**
22
22
  * Register the `init` command on the given Commander program.
@@ -170,20 +170,45 @@ export async function runWorkspaceInit(options = {}) {
170
170
  else {
171
171
  console.log(` ${c.exists("Exists:")} .opencode/skills/opencode-rag/SKILL.md`);
172
172
  }
173
+ // Separate decision-model skill — loaded on demand when a task needs
174
+ // classification/routing/scoring via `make_decision`.
175
+ const decisionSkillDir = path.join(skillsDir, "make-decision");
176
+ const decisionSkillPath = path.join(decisionSkillDir, "SKILL.md");
177
+ if (!existsSync(decisionSkillDir)) {
178
+ mkdirSync(decisionSkillDir, { recursive: true });
179
+ console.log(` ${c.created("Created:")} .opencode/skills/make-decision/`);
180
+ }
181
+ const decisionSkillContent = generateDecisionSkillFile();
182
+ const decisionSkillExists = existsSync(decisionSkillPath);
183
+ if (!decisionSkillExists || options.force) {
184
+ writeFileSync(decisionSkillPath, decisionSkillContent, "utf-8");
185
+ console.log(` ${decisionSkillExists ? c.updated("Updated:") : c.created("Created:")} .opencode/skills/make-decision/SKILL.md`);
186
+ }
187
+ else if (readFileSync(decisionSkillPath, "utf-8") !== decisionSkillContent) {
188
+ writeFileSync(decisionSkillPath, decisionSkillContent, "utf-8");
189
+ console.log(` ${c.updated("Updated:")} .opencode/skills/make-decision/SKILL.md`);
190
+ }
191
+ else {
192
+ console.log(` ${c.exists("Exists:")} .opencode/skills/make-decision/SKILL.md`);
193
+ }
173
194
  const agentsMdPath = path.join(cwd, "AGENTS.md");
174
195
  const agentsMdExists = existsSync(agentsMdPath);
175
- // Read effective promptEnforcement from existing config (if present)
196
+ // Read effective memory/decision flags from existing config (if present)
176
197
  let promptEnforcement = true;
198
+ let decisionEnabled = false;
199
+ let routeBeforeAsking = false;
177
200
  try {
178
201
  if (existsSync(configPath)) {
179
202
  const existingCfg = loadConfig(configPath, false);
180
203
  promptEnforcement = existingCfg.memory?.promptEnforcement ?? true;
204
+ decisionEnabled = existingCfg.decision?.enabled ?? false;
205
+ routeBeforeAsking = existingCfg.decision?.routeBeforeAsking ?? false;
181
206
  }
182
207
  }
183
208
  catch {
184
- // Malformed or missing config — use default
209
+ // Malformed or missing config — use defaults
185
210
  }
186
- const nextAgentsMd = mergeAgentsMdContent(agentsMdExists ? readFileSync(agentsMdPath, "utf-8") : undefined, { promptEnforcement });
211
+ const nextAgentsMd = mergeAgentsMdContent(agentsMdExists ? readFileSync(agentsMdPath, "utf-8") : undefined, { promptEnforcement, decisionEnabled, routeBeforeAsking });
187
212
  if (!agentsMdExists || options.force) {
188
213
  writeFileSync(agentsMdPath, nextAgentsMd, "utf-8");
189
214
  console.log(` ${agentsMdExists ? c.updated("Updated:") : c.created("Created:")} AGENTS.md`);
@@ -226,7 +251,19 @@ export async function runWorkspaceInit(options = {}) {
226
251
  detectedTuning = undefined;
227
252
  }
228
253
  }
229
- return generateDefaultConfigJson(detectedTuning);
254
+ // Carry the identity-critical embedding keys (apiKey, vectorDimension)
255
+ // over from the file being replaced: a reset must never downgrade the
256
+ // store schema to the 384 default or drop provider auth.
257
+ let existingRaw;
258
+ if (configExists) {
259
+ try {
260
+ existingRaw = readFileSync(configPath, "utf-8");
261
+ }
262
+ catch {
263
+ existingRaw = undefined;
264
+ }
265
+ }
266
+ return generateDefaultConfigJson(detectedTuning, existingRaw);
230
267
  };
231
268
  if (!configExists) {
232
269
  writeFileSync(configPath, await configContent(), "utf-8");
@@ -5,6 +5,7 @@ import { c } from "../format.js";
5
5
  import { getPackageMetadata } from "../helpers.js";
6
6
  import { getRuntimeDir, getVersionFile, readVersionFile, setupRuntime, } from "../../core/setup-runtime.js";
7
7
  import { compareVersions, getCurrentVersion, installLatestUpdate } from "../../core/version-check.js";
8
+ import { bestAvailablePackageManager, globalUninstallCommand } from "../../core/package-manager.js";
8
9
  import { isLikelyProjectRoot, isWorkspaceInitialized, runWorkspaceInit } from "./init.js";
9
10
  const PLUGIN_NAME = "opencode-rag-plugin";
10
11
  function removeIfExists(targetPath) {
@@ -98,7 +99,8 @@ export function registerSetupCommand(program) {
98
99
  removeIfExists(versionFile);
99
100
  console.log(` ${c.updated("Removed:")} ${c.file(runtimePluginDir)}`);
100
101
  console.log(` ${c.updated("Removed:")} ${c.file(runtimeSdkPluginDir)}`);
101
- console.log(`\n ${c.success("Done.")} Run ${c.file("npm uninstall -g opencode-rag-plugin")} to remove the global package.\n`);
102
+ const uninstallPm = bestAvailablePackageManager() ?? "npm";
103
+ console.log(`\n ${c.success("Done.")} Run ${c.file(globalUninstallCommand(uninstallPm, PLUGIN_NAME))} to remove the global package.\n`);
102
104
  return;
103
105
  }
104
106
  // --- install ---
@@ -161,9 +163,9 @@ export function registerSetupCommand(program) {
161
163
  */
162
164
  async function ensureUpToDate() {
163
165
  const current = getCurrentVersion();
164
- const latest = getLatestNpmVersion();
166
+ const latest = await getLatestNpmVersion();
165
167
  if (!latest) {
166
- console.log(` ${c.dim("Could not check npm for the latest version (offline?).")}`);
168
+ console.log(` ${c.dim("Could not check the npm registry for the latest version (offline?).")}`);
167
169
  console.log(` ${c.dim("Run `opencode-rag update` later to upgrade.\n")}`);
168
170
  return;
169
171
  }
@@ -184,20 +186,49 @@ async function ensureUpToDate() {
184
186
  /**
185
187
  * Query the npm registry for the latest published version of the plugin.
186
188
  *
187
- * Best-effort: returns `null` when npm is unavailable or the lookup fails.
189
+ * Fetches the registry over HTTPS directly so the check works no matter which
190
+ * package manager installed this CLI — the npm binary may not even exist on
191
+ * machines set up via pnpm/yarn/bun (GitHub issue #34). Honors
192
+ * `npm_config_registry` (set by all four managers) for private mirrors.
193
+ *
194
+ * Best-effort: returns `null` when every endpoint lookup fails (offline,
195
+ * mirror without the endpoint, malformed response).
188
196
  *
189
197
  * @returns The latest version string, or `null` on failure.
190
198
  */
191
- function getLatestNpmVersion() {
199
+ async function getLatestNpmVersion() {
200
+ const registry = (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
201
+ const pkgPath = PLUGIN_NAME.includes("/") ? PLUGIN_NAME.replace("/", "%2F") : PLUGIN_NAME;
202
+ // Prefer the lightweight dist-tags endpoint; fall back to the version
203
+ // document for mirrors that do not implement it.
204
+ const urls = [
205
+ `${registry}/-/package/${pkgPath}/dist-tags`,
206
+ `${registry}/${pkgPath}/latest`,
207
+ ];
208
+ const controller = new AbortController();
209
+ const timeout = setTimeout(() => controller.abort(), 15_000);
192
210
  try {
193
- const out = execSync(`npm view ${PLUGIN_NAME} dist-tags.latest`, {
194
- encoding: "utf-8",
195
- timeout: 15_000,
196
- }).trim();
197
- return out || null;
198
- }
199
- catch {
211
+ for (const url of urls) {
212
+ try {
213
+ const response = await fetch(url, {
214
+ headers: { Accept: "application/json" },
215
+ signal: controller.signal,
216
+ });
217
+ if (!response.ok)
218
+ continue;
219
+ const data = (await response.json());
220
+ const version = data.latest ?? data.version;
221
+ if (typeof version === "string" && version)
222
+ return version;
223
+ }
224
+ catch {
225
+ // Try the next endpoint.
226
+ }
227
+ }
200
228
  return null;
201
229
  }
230
+ finally {
231
+ clearTimeout(timeout);
232
+ }
202
233
  }
203
234
  //# sourceMappingURL=setup.js.map
@@ -7,8 +7,9 @@
7
7
  import path from "node:path";
8
8
  import os from "node:os";
9
9
  import fs from "node:fs";
10
- import { c, resolveCliContext, logCliError, logCliInfo, formatTimestamp } from "../format.js";
10
+ import { c, resolveCliContext, logCliError, logCliInfo, formatTimestamp, formatRelativeAge } from "../format.js";
11
11
  import { getIndexStatusSummary } from "../../indexer.js";
12
+ import { deriveWatcherHealth } from "../../watcher.js";
12
13
  import { getPackageMetadata } from "../helpers.js";
13
14
  import { checkForUpdate } from "../../core/version-check.js";
14
15
  /**
@@ -107,19 +108,21 @@ export function registerStatusCommand(program) {
107
108
  // Read watcher status from the background auto-indexer
108
109
  const watcherStatusPath = path.join(storePath, "watcher-status.json");
109
110
  let watchModeDisplay;
111
+ let watcherWarning;
110
112
  if (fs.existsSync(watcherStatusPath)) {
111
113
  try {
112
- const raw = fs.readFileSync(watcherStatusPath, "utf-8");
113
- const ws = JSON.parse(raw);
114
- if (ws.lastRunAt) {
115
- const lastRun = formatTimestamp(ws.lastRunAt);
116
- watchModeDisplay = ws.running
117
- ? c.enabled("active") + c.dim(" (last run: " + lastRun + ")")
118
- : c.enabled("on") + c.dim(" (last run: " + lastRun + ")");
114
+ const ws = JSON.parse(fs.readFileSync(watcherStatusPath, "utf-8"));
115
+ const lastRun = ws.lastSuccessAt ?? ws.lastRunAt;
116
+ if (lastRun) {
117
+ const runLabel = ws.lastSuccessAt ? "last successful run" : "last run";
118
+ watchModeDisplay = `${ws.running ? c.enabled("active") : c.enabled("on")} ${c.dim(`(${runLabel}: ${formatTimestamp(lastRun)}, ${formatRelativeAge(lastRun)})`)}`;
119
119
  }
120
120
  else {
121
121
  watchModeDisplay = c.enabled("on");
122
122
  }
123
+ const health = deriveWatcherHealth(ws);
124
+ if (health.stale)
125
+ watcherWarning = health.reason;
123
126
  }
124
127
  catch {
125
128
  watchModeDisplay = c.enabled("on") + c.dim(" (status unknown)");
@@ -132,6 +135,9 @@ export function registerStatusCommand(program) {
132
135
  watchModeDisplay = c.dim("off");
133
136
  }
134
137
  logCliInfo(logFilePath, "status", `${c.label("Watch mode:")} ${watchModeDisplay}`);
138
+ if (watcherWarning) {
139
+ logCliInfo(logFilePath, "status", `${c.label("Watcher health:")} ${c.warn(`stale — ${watcherWarning}`)} ${c.dim("(run 'opencode-rag index' or check .opencode/opencode-rag.log)")}`);
140
+ }
135
141
  const kiCount = config.retrieval.hybridSearch?.enabled
136
142
  ? keywordIndex?.count() ?? 0
137
143
  : 0;
@@ -3,8 +3,9 @@
3
3
  */
4
4
  /**
5
5
  * `update` command — checks for a newer published version of OpenCodeRAG and,
6
- * by default, installs it (via `npm install -g ...@latest`) then re-syncs the
7
- * OpenCode runtime junctions so the new build is picked up on next restart.
6
+ * by default, installs it via the package manager that owns the global install
7
+ * (npm/pnpm/yarn/bun, `<pkg>@latest`) then re-syncs the OpenCode runtime
8
+ * junctions so the new build is picked up on next restart.
8
9
  */
9
10
  import type { Command } from "commander";
10
11
  /**
@@ -3,11 +3,14 @@
3
3
  */
4
4
  /**
5
5
  * `update` command — checks for a newer published version of OpenCodeRAG and,
6
- * by default, installs it (via `npm install -g ...@latest`) then re-syncs the
7
- * OpenCode runtime junctions so the new build is picked up on next restart.
6
+ * by default, installs it via the package manager that owns the global install
7
+ * (npm/pnpm/yarn/bun, `<pkg>@latest`) then re-syncs the OpenCode runtime
8
+ * junctions so the new build is picked up on next restart.
8
9
  */
9
10
  import { c } from "../format.js";
10
11
  import { checkForUpdate, getCurrentVersion, installLatestUpdate } from "../../core/version-check.js";
12
+ import { bestAvailablePackageManager, globalInstallCommand } from "../../core/package-manager.js";
13
+ const PLUGIN_NAME = "opencode-rag-plugin";
11
14
  /**
12
15
  * Register the `update` command on the given Commander program.
13
16
  *
@@ -56,7 +59,8 @@ export function registerUpdateCommand(program) {
56
59
  else {
57
60
  console.error(` ${c.error("✗")} ${result.message}`);
58
61
  console.error(`\n ${c.error("Update failed. You can retry with `opencode-rag update` or install manually:")}\n`);
59
- console.error(` ${c.dim(" npm install -g opencode-rag-plugin@latest && opencode-rag setup")}\n`);
62
+ const hintPm = bestAvailablePackageManager() ?? "npm";
63
+ console.error(` ${c.dim(` ${globalInstallCommand(hintPm, `${PLUGIN_NAME}@latest`)} && opencode-rag setup`)}\n`);
60
64
  process.exit(1);
61
65
  }
62
66
  });
@@ -95,6 +95,56 @@ export declare function cleanupContext(ctx: RagContext): Promise<void>;
95
95
  * @returns A localized date string, or `"never"` if the timestamp is falsy.
96
96
  */
97
97
  export declare function formatTimestamp(timestamp?: number): string;
98
+ /**
99
+ * Format a Unix timestamp as a compact "time since" label (e.g. `"5m ago"`).
100
+ *
101
+ * @param timestamp - Unix timestamp in milliseconds, or `undefined` for "never".
102
+ * @param now - Reference time in ms (defaults to `Date.now()`, injectable for tests).
103
+ * @returns A human-readable age such as `"just now"`, `"2h ago"`, or `"3d ago"`.
104
+ */
105
+ export declare function formatRelativeAge(timestamp?: number, now?: number): string;
106
+ /**
107
+ * Overall outcome of an index pass — drives the CLI exit code and the machine-readable
108
+ * summary. `"ok"` = everything that was found got indexed; `"partial"` = the pass did real
109
+ * work but some files/chunks failed and will be retried; `"incomplete"` = nothing usable
110
+ * was stored (embedding provider down or zero chunks).
111
+ */
112
+ export type IndexRunStatus = "ok" | "partial" | "incomplete";
113
+ /**
114
+ * Classify an index pass from its stats. Mirrors the messages printed by the `index`
115
+ * command and the exit-code mapping: 0 = ok, 3 = partial, 1 = incomplete/interrupted.
116
+ *
117
+ * @param stats - Statistics from a single indexing pass.
118
+ * @returns The pass status.
119
+ */
120
+ export declare function classifyIndexRun(stats: IndexRunStats): IndexRunStatus;
121
+ /**
122
+ * Build short human-readable descriptions of a partial pass's problems.
123
+ *
124
+ * @param stats - Statistics from a single indexing pass.
125
+ * @returns One string per problem category; empty when the pass was clean.
126
+ */
127
+ export declare function describeIndexProblems(stats: IndexRunStats): string[];
128
+ /** Options for {@link buildIndexSummaryJson}. */
129
+ export interface IndexSummaryJsonOptions {
130
+ /** Workspace root used to relativize extraction error paths. */
131
+ cwd: string;
132
+ /** Pass start time (ms since epoch). */
133
+ startedAt: number;
134
+ /** Pass duration in milliseconds. */
135
+ durationMs: number;
136
+ /** True when the run was interrupted (Ctrl+C) — reported instead of the pass status. */
137
+ interrupted?: boolean;
138
+ }
139
+ /**
140
+ * Build the machine-readable `index --json` summary. The CLI prints this object as a
141
+ * single line of JSON so agents can parse the outcome without scraping log text.
142
+ *
143
+ * @param stats - Statistics from a single indexing pass.
144
+ * @param opts - Workspace, timing, and interrupt information.
145
+ * @returns A plain JSON-serializable object (schema version 1).
146
+ */
147
+ export declare function buildIndexSummaryJson(stats: IndexRunStats, opts: IndexSummaryJsonOptions): Record<string, unknown>;
98
148
  /**
99
149
  * Print an indexing pass summary to stdout.
100
150
  *