opencode-rag-plugin 2.9.0 → 2.9.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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * @fileoverview Selective auto-injection of quirks.
3
+ *
4
+ * Both injection surfaces (`experimental.chat.system.transform` and
5
+ * `chat.message`) used to carry a copy of the same gates. They drifted, and
6
+ * neither logged what it decided, so a "quirk did not show up" report could
7
+ * not be answered without reading the plugin source. This module is the one
8
+ * implementation both call:
9
+ *
10
+ * 1. recall at the auto-inject semantic bar (raw vector similarity),
11
+ * 2. drop quirks already injected in this session,
12
+ * 3. apply the lexical gate against the user's CURRENT message,
13
+ * 4. rank the survivors by *content-word* overlap, then similarity,
14
+ * 5. cut to `topK`.
15
+ *
16
+ * Two deliberate differences from the previous inline copies:
17
+ *
18
+ * - **Over-fetch before gating.** Recall asks for several candidates, not
19
+ * `topK` of one. Before, a blocked top-1 produced an empty turn *and* stayed
20
+ * eligible for the next turn (it was never added to the injected set), so the
21
+ * same ineligible quirk was re-considered every turn while nothing was shown.
22
+ * - **The gate needs one content word.** `sharedWords` counts tokens >= 3
23
+ * chars including filler ("the", "and", "does", "work"), so four shared
24
+ * tokens can be four stopwords. The gate now also requires at least one
25
+ * non-stopword token, and ranking prefers content-word overlap.
26
+ *
27
+ * No user text means no injection: a quirk must earn its place against what the
28
+ * user actually asked, never against the assistant's previous message.
29
+ */
30
+ import type { SearchResult } from "../core/interfaces.js";
31
+ /**
32
+ * Filler tokens that must not satisfy the lexical gate on their own.
33
+ *
34
+ * Deliberately small and English-only: this is not a linguistics project, just
35
+ * a guard against "the/and/does/this" style overlaps. Technical vocabulary is
36
+ * never listed here — dropping a real identifier would weaken genuine matches.
37
+ */
38
+ export declare const AUTO_INJECT_STOPWORDS: ReadonlySet<string>;
39
+ /** Split a text into lowercased word tokens of at least `minTokenLen` chars. */
40
+ export declare function tokenize(text: string, minTokenLen?: number): string[];
41
+ /** Distinct tokens shared by both texts (filler included). */
42
+ export declare function sharedTokenCount(a: string, b: string, minTokenLen?: number): number;
43
+ /**
44
+ * Distinct *content* tokens shared by both texts — the same overlap with
45
+ * `AUTO_INJECT_STOPWORDS` removed. This is the signal that decides whether a
46
+ * quirk is actually about the user's request rather than about the word "work".
47
+ */
48
+ export declare function contentOverlap(a: string, b: string, minTokenLen?: number): number;
49
+ /** A quirk selected for injection, with the evidence that selected it. */
50
+ export interface AutoInjectHit {
51
+ id: string;
52
+ content: string;
53
+ quirkType?: string;
54
+ /** Confidence-weighted similarity as reported by `recallQuirks`. */
55
+ score: number;
56
+ /** Raw vector similarity (`(cosine + 1) / 2`), the auto-inject bar's domain. */
57
+ rawSimilarity: number;
58
+ /** Shared tokens including filler — the number the config threshold counts. */
59
+ overlap: number;
60
+ /** Shared non-filler tokens — the number ranking uses first. */
61
+ contentOverlap: number;
62
+ }
63
+ /** Why a selection produced the hits it did (logged, never shown to the model). */
64
+ export type AutoInjectReason = "ok" | "no-user-text" | "no-candidates" | "gate" | "already-injected" | "budget" | "recall-error";
65
+ /** The full outcome of one auto-inject attempt. */
66
+ export interface AutoInjectSelection {
67
+ hits: AutoInjectHit[];
68
+ /** Recall results before any gate (0..n). */
69
+ considered: number;
70
+ droppedByGate: number;
71
+ droppedAlreadyInjected: number;
72
+ reason: AutoInjectReason;
73
+ }
74
+ /** Recall function shape — `recallQuirks` bound to its deps and tag filter. */
75
+ export type AutoInjectRecall = (query: string, options: {
76
+ topK: number;
77
+ minScore: number;
78
+ explain: true;
79
+ }) => Promise<SearchResult[]>;
80
+ export interface AutoInjectOptions {
81
+ topK: number;
82
+ /** Minimum shared tokens (filler included) — `memory.autoInjectMinTokenOverlap`. */
83
+ minTokenOverlap: number;
84
+ /** Semantic bar — `memory.autoInjectMinScore`. */
85
+ minScore: number;
86
+ /** Quirks already injected in this session. */
87
+ injectedIds?: ReadonlySet<string>;
88
+ /** Extra recall candidates per injected slot (default 4, floor 8). */
89
+ candidateMultiplier?: number;
90
+ }
91
+ /**
92
+ * Select the quirks to auto-inject for one turn.
93
+ *
94
+ * @param recall - Bound recall (`recallQuirks` with `excludeTags` applied).
95
+ * @param args.query - Combined assistant + user text used for retrieval.
96
+ * @param args.userText - The user's CURRENT message; the lexical gate runs on it.
97
+ * @param args.options - Bars, topK, and the session's injected set.
98
+ */
99
+ export declare function selectAutoInjectQuirks(recall: AutoInjectRecall, args: {
100
+ query: string;
101
+ userText: string;
102
+ options: AutoInjectOptions;
103
+ }): Promise<AutoInjectSelection>;
104
+ /**
105
+ * `selectAutoInjectQuirks` under a latency budget.
106
+ *
107
+ * Auto-injection runs inside a model request; an embedding provider that is
108
+ * slow (or down) must cost at most `budgetMs`. On timeout the result is an
109
+ * empty selection with reason `"budget"` — the pending promise is NOT
110
+ * cancelled, but nothing awaits it, so the request proceeds.
111
+ */
112
+ export declare function selectAutoInjectQuirksWithinBudget(recall: AutoInjectRecall, args: {
113
+ query: string;
114
+ userText: string;
115
+ options: AutoInjectOptions;
116
+ }, budgetMs: number): Promise<AutoInjectSelection>;
117
+ /** Render the block appended to the user message / prepended to the system prompt. */
118
+ export declare function formatAutoInjectBlock(hits: readonly AutoInjectHit[], options?: {
119
+ heading?: string;
120
+ separator?: boolean;
121
+ }): string;
122
+ /**
123
+ * One-line, greppable description of a selection for the plugin log.
124
+ *
125
+ * Format: `injected=2 [quirk:a overlap=5 content=3 raw=0.81] found=6 gate=2 dup=1`
126
+ */
127
+ export declare function describeAutoInjectSelection(selection: AutoInjectSelection): string;
@@ -0,0 +1,240 @@
1
+ /**
2
+ * @fileoverview Selective auto-injection of quirks.
3
+ *
4
+ * Both injection surfaces (`experimental.chat.system.transform` and
5
+ * `chat.message`) used to carry a copy of the same gates. They drifted, and
6
+ * neither logged what it decided, so a "quirk did not show up" report could
7
+ * not be answered without reading the plugin source. This module is the one
8
+ * implementation both call:
9
+ *
10
+ * 1. recall at the auto-inject semantic bar (raw vector similarity),
11
+ * 2. drop quirks already injected in this session,
12
+ * 3. apply the lexical gate against the user's CURRENT message,
13
+ * 4. rank the survivors by *content-word* overlap, then similarity,
14
+ * 5. cut to `topK`.
15
+ *
16
+ * Two deliberate differences from the previous inline copies:
17
+ *
18
+ * - **Over-fetch before gating.** Recall asks for several candidates, not
19
+ * `topK` of one. Before, a blocked top-1 produced an empty turn *and* stayed
20
+ * eligible for the next turn (it was never added to the injected set), so the
21
+ * same ineligible quirk was re-considered every turn while nothing was shown.
22
+ * - **The gate needs one content word.** `sharedWords` counts tokens >= 3
23
+ * chars including filler ("the", "and", "does", "work"), so four shared
24
+ * tokens can be four stopwords. The gate now also requires at least one
25
+ * non-stopword token, and ranking prefers content-word overlap.
26
+ *
27
+ * No user text means no injection: a quirk must earn its place against what the
28
+ * user actually asked, never against the assistant's previous message.
29
+ */
30
+ /**
31
+ * Filler tokens that must not satisfy the lexical gate on their own.
32
+ *
33
+ * Deliberately small and English-only: this is not a linguistics project, just
34
+ * a guard against "the/and/does/this" style overlaps. Technical vocabulary is
35
+ * never listed here — dropping a real identifier would weaken genuine matches.
36
+ */
37
+ export const AUTO_INJECT_STOPWORDS = new Set([
38
+ "the", "and", "but", "for", "nor", "not", "yet", "you", "your", "yours",
39
+ "with", "without", "from", "into", "onto", "over", "under", "about",
40
+ "this", "that", "these", "those", "there", "their", "them", "they", "its",
41
+ "are", "was", "were", "been", "being", "has", "have", "had", "does", "did",
42
+ "doing", "done", "can", "could", "will", "would", "shall", "should", "may",
43
+ "might", "must", "what", "when", "where", "which", "who", "whom", "whose",
44
+ "why", "how", "all", "any", "some", "more", "most", "such", "only", "also",
45
+ "just", "than", "then", "too", "very", "each", "every", "both", "few",
46
+ "other", "same", "own", "out", "off", "again", "once", "here", "now",
47
+ "after", "before", "during", "while", "because", "since", "until", "per",
48
+ "via", "use", "uses", "used", "using", "get", "gets", "got", "make", "made",
49
+ "does", "doing", "one", "two", "way", "want", "wants", "wanted", "need",
50
+ "needs", "needed", "like", "works", "working",
51
+ ]);
52
+ /** Split a text into lowercased word tokens of at least `minTokenLen` chars. */
53
+ export function tokenize(text, minTokenLen = 3) {
54
+ return text
55
+ .toLowerCase()
56
+ .split(/\W+/)
57
+ .filter((w) => w.length >= minTokenLen);
58
+ }
59
+ /** Distinct tokens shared by both texts (filler included). */
60
+ export function sharedTokenCount(a, b, minTokenLen = 3) {
61
+ const wordsA = new Set(tokenize(a, minTokenLen));
62
+ const wordsB = new Set(tokenize(b, minTokenLen));
63
+ let count = 0;
64
+ for (const tok of wordsA) {
65
+ if (wordsB.has(tok))
66
+ count++;
67
+ }
68
+ return count;
69
+ }
70
+ /**
71
+ * Distinct *content* tokens shared by both texts — the same overlap with
72
+ * `AUTO_INJECT_STOPWORDS` removed. This is the signal that decides whether a
73
+ * quirk is actually about the user's request rather than about the word "work".
74
+ */
75
+ export function contentOverlap(a, b, minTokenLen = 3) {
76
+ const wordsA = new Set(tokenize(a, minTokenLen));
77
+ const wordsB = new Set(tokenize(b, minTokenLen));
78
+ let count = 0;
79
+ for (const tok of wordsA) {
80
+ if (wordsB.has(tok) && !AUTO_INJECT_STOPWORDS.has(tok))
81
+ count++;
82
+ }
83
+ return count;
84
+ }
85
+ /** Raw similarity of a recall result (falls back to the reported score). */
86
+ function rawSimilarityOf(r) {
87
+ return r.explanation?.scoreBreakdown?.rawVectorScore ?? r.score;
88
+ }
89
+ /**
90
+ * Select the quirks to auto-inject for one turn.
91
+ *
92
+ * @param recall - Bound recall (`recallQuirks` with `excludeTags` applied).
93
+ * @param args.query - Combined assistant + user text used for retrieval.
94
+ * @param args.userText - The user's CURRENT message; the lexical gate runs on it.
95
+ * @param args.options - Bars, topK, and the session's injected set.
96
+ */
97
+ export async function selectAutoInjectQuirks(recall, args) {
98
+ const { query, userText, options } = args;
99
+ const empty = (reason, extra = {}) => ({
100
+ hits: [],
101
+ considered: 0,
102
+ droppedByGate: 0,
103
+ droppedAlreadyInjected: 0,
104
+ reason,
105
+ ...extra,
106
+ });
107
+ if (userText.trim().length === 0)
108
+ return empty("no-user-text");
109
+ if (query.trim().length === 0)
110
+ return empty("no-candidates");
111
+ const topK = Math.max(1, Math.floor(options.topK));
112
+ const candidateK = Math.max(topK * (options.candidateMultiplier ?? 4), 8);
113
+ let raw;
114
+ try {
115
+ raw = await recall(query, { topK: candidateK, minScore: options.minScore, explain: true });
116
+ }
117
+ catch {
118
+ return empty("recall-error");
119
+ }
120
+ if (raw.length === 0)
121
+ return empty("no-candidates");
122
+ const injected = options.injectedIds;
123
+ let droppedAlreadyInjected = 0;
124
+ let droppedByGate = 0;
125
+ const eligible = [];
126
+ for (const r of raw) {
127
+ const id = r.chunk.id;
128
+ if (injected?.has(id)) {
129
+ droppedAlreadyInjected++;
130
+ continue;
131
+ }
132
+ const content = r.chunk.content;
133
+ const overlap = sharedTokenCount(content, userText);
134
+ const contentWords = contentOverlap(content, userText);
135
+ // The threshold is the calibrated one; the content-word requirement is the
136
+ // fix for filler-only matches ("the ... and ... does ... work").
137
+ if (options.minTokenOverlap > 0 && (overlap < options.minTokenOverlap || contentWords < 1)) {
138
+ droppedByGate++;
139
+ continue;
140
+ }
141
+ eligible.push({
142
+ id,
143
+ content,
144
+ quirkType: r.chunk.metadata?.quirkType,
145
+ score: r.score,
146
+ rawSimilarity: rawSimilarityOf(r),
147
+ overlap,
148
+ contentOverlap: contentWords,
149
+ });
150
+ }
151
+ if (eligible.length === 0) {
152
+ if (droppedAlreadyInjected > 0 && droppedByGate === 0)
153
+ return empty("already-injected", { considered: raw.length, droppedAlreadyInjected });
154
+ if (droppedByGate > 0)
155
+ return empty("gate", { considered: raw.length, droppedByGate, droppedAlreadyInjected });
156
+ return empty("no-candidates");
157
+ }
158
+ // Rank by what actually makes a quirk relevant to this turn: the number of
159
+ // meaningful tokens it shares with the user's message, then the (also
160
+ // overlap-based) total, then semantic similarity as the tie-breaker.
161
+ eligible.sort((a, b) => b.contentOverlap - a.contentOverlap ||
162
+ b.overlap - a.overlap ||
163
+ b.rawSimilarity - a.rawSimilarity ||
164
+ b.score - a.score);
165
+ return {
166
+ hits: eligible.slice(0, topK),
167
+ considered: raw.length,
168
+ droppedByGate,
169
+ droppedAlreadyInjected,
170
+ reason: "ok",
171
+ };
172
+ }
173
+ /**
174
+ * `selectAutoInjectQuirks` under a latency budget.
175
+ *
176
+ * Auto-injection runs inside a model request; an embedding provider that is
177
+ * slow (or down) must cost at most `budgetMs`. On timeout the result is an
178
+ * empty selection with reason `"budget"` — the pending promise is NOT
179
+ * cancelled, but nothing awaits it, so the request proceeds.
180
+ */
181
+ export async function selectAutoInjectQuirksWithinBudget(recall, args, budgetMs) {
182
+ if (!Number.isFinite(budgetMs) || budgetMs <= 0) {
183
+ return selectAutoInjectQuirks(recall, args);
184
+ }
185
+ let timer;
186
+ const timeout = new Promise((resolve) => {
187
+ timer = setTimeout(() => resolve({
188
+ hits: [],
189
+ considered: 0,
190
+ droppedByGate: 0,
191
+ droppedAlreadyInjected: 0,
192
+ reason: "budget",
193
+ }), budgetMs);
194
+ });
195
+ try {
196
+ return await Promise.race([selectAutoInjectQuirks(recall, args), timeout]);
197
+ }
198
+ finally {
199
+ if (timer)
200
+ clearTimeout(timer);
201
+ }
202
+ }
203
+ /** Render the block appended to the user message / prepended to the system prompt. */
204
+ export function formatAutoInjectBlock(hits, options = {}) {
205
+ const heading = options.heading ?? "⚠ **Quirk memory**";
206
+ const separator = options.separator ?? true;
207
+ const lines = [""];
208
+ if (separator)
209
+ lines.push("---");
210
+ lines.push(heading, "");
211
+ for (const h of hits) {
212
+ const badge = h.quirkType ? `[\`${h.quirkType}\`] ` : "";
213
+ lines.push(`- ${badge}${h.content}`);
214
+ }
215
+ return lines.join("\n");
216
+ }
217
+ /**
218
+ * One-line, greppable description of a selection for the plugin log.
219
+ *
220
+ * Format: `injected=2 [quirk:a overlap=5 content=3 raw=0.81] found=6 gate=2 dup=1`
221
+ */
222
+ export function describeAutoInjectSelection(selection) {
223
+ const parts = [];
224
+ if (selection.hits.length > 0) {
225
+ const hits = selection.hits
226
+ .map((h) => `${h.id} overlap=${h.overlap} content=${h.contentOverlap} raw=${h.rawSimilarity.toFixed(3)}`)
227
+ .join("; ");
228
+ parts.push(`injected=${selection.hits.length} [${hits}]`);
229
+ }
230
+ else {
231
+ parts.push(`injected=0 reason=${selection.reason}`);
232
+ }
233
+ parts.push(`found=${selection.considered}`);
234
+ if (selection.droppedByGate > 0)
235
+ parts.push(`gate=${selection.droppedByGate}`);
236
+ if (selection.droppedAlreadyInjected > 0)
237
+ parts.push(`dup=${selection.droppedAlreadyInjected}`);
238
+ return parts.join(" ");
239
+ }
240
+ //# sourceMappingURL=auto-inject.js.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @fileoverview Detection of failures on the surfaces OpenCode does NOT
3
+ * report as tool errors.
4
+ *
5
+ * The host only flags a tool call as an error when it rejects the call itself
6
+ * (schema/argument validation). Everything else arrives as a COMPLETED tool
7
+ * call whose output merely mentions the failure: a command that exits
8
+ * non-zero, a script that raises, a file that cannot be read. The quirk path
9
+ * was blind to all of them, so the most common real failure in an agent
10
+ * session was never learned from and never answered from memory.
11
+ *
12
+ * This module turns such an output into a `DetectedError`. It is deliberately
13
+ * conservative: every rule matches a marker that a real failure produces.
14
+ * A false positive is not free — it costs a recall, a possible quirk write,
15
+ * and an injected block in the next model request — so the generic
16
+ * `Error:`-anywhere and localized "not found" heuristics are deliberately
17
+ * NOT here.
18
+ *
19
+ * Pure and dependency-free, so it is cheap to unit-test.
20
+ */
21
+ /** Which surface an error was detected on. */
22
+ export type ErrorSource = "host" | "output" | "session";
23
+ /** A failure detected on a surface the host does not report as an error. */
24
+ export interface DetectedError {
25
+ /**
26
+ * Normalized text used for the recall query and for the quirk content.
27
+ * Deliberately short: it is the failure's own message plus the marker that
28
+ * identified it, never the whole (possibly huge) tool output.
29
+ */
30
+ text: string;
31
+ /** The tool the failure came from; absent for session-level errors. */
32
+ tool?: string;
33
+ /** The surface that produced the signal. */
34
+ source: ErrorSource;
35
+ /**
36
+ * A stable cause class, used as the `cause:<class>` tag when the generic
37
+ * classifier cannot derive one. Stable per failure KIND, which is what
38
+ * keeps the exact duplicate check working across sessions.
39
+ */
40
+ causeClass?: string;
41
+ }
42
+ /** Tunables for the output scanner. */
43
+ export interface OutputErrorOptions {
44
+ /** Only the tail of the output is scanned (default 20000 chars). */
45
+ maxScanChars?: number;
46
+ /** Max characters of the failure message kept in the error text (default 200). */
47
+ maxMessageChars?: number;
48
+ /**
49
+ * The tool's structured exit code, when it reports one. A non-zero code is
50
+ * DEFINITIVE — no text marker is needed, and none is looked for. Measured
51
+ * live 2026-10-21: OpenCode's shell tool reports `{ status, truncated, exit }`
52
+ * in the result metadata.
53
+ */
54
+ exitCode?: number;
55
+ }
56
+ /** Strip ANSI colour codes. */
57
+ export declare function stripAnsi(text: string): string;
58
+ /**
59
+ * Detect a failure in a tool's output.
60
+ *
61
+ * Returns `undefined` when the output carries no failure marker. A tool that
62
+ * succeeded produces no match, so the common case costs one regex pass over
63
+ * the (capped) output.
64
+ */
65
+ export declare function detectOutputError(tool: string, output: string, options?: OutputErrorOptions): DetectedError | undefined;
66
+ /**
67
+ * Read a tool result's structured exit code.
68
+ *
69
+ * The shell tool reports `{ status, truncated, exit }` in its result metadata
70
+ * (measured live 2026-10-21). A non-zero code means the command failed.
71
+ */
72
+ export declare function extractExitCode(metadata: unknown): number | undefined;
73
+ /**
74
+ * Detect a session-level error (a failed model call, a provider error).
75
+ *
76
+ * The `session.error` event carries an `error` object whose shape differs
77
+ * between OpenCode versions, so the message is dug out defensively.
78
+ */
79
+ export declare function detectSessionError(error: unknown): DetectedError | undefined;
80
+ /** Dig a human-readable message out of an error payload of unknown shape. */
81
+ export declare function extractErrorMessage(error: unknown): string | undefined;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * @fileoverview Detection of failures on the surfaces OpenCode does NOT
3
+ * report as tool errors.
4
+ *
5
+ * The host only flags a tool call as an error when it rejects the call itself
6
+ * (schema/argument validation). Everything else arrives as a COMPLETED tool
7
+ * call whose output merely mentions the failure: a command that exits
8
+ * non-zero, a script that raises, a file that cannot be read. The quirk path
9
+ * was blind to all of them, so the most common real failure in an agent
10
+ * session was never learned from and never answered from memory.
11
+ *
12
+ * This module turns such an output into a `DetectedError`. It is deliberately
13
+ * conservative: every rule matches a marker that a real failure produces.
14
+ * A false positive is not free — it costs a recall, a possible quirk write,
15
+ * and an injected block in the next model request — so the generic
16
+ * `Error:`-anywhere and localized "not found" heuristics are deliberately
17
+ * NOT here.
18
+ *
19
+ * Pure and dependency-free, so it is cheap to unit-test.
20
+ */
21
+ /** ANSI escape sequences — stripped before matching. */
22
+ const ANSI_PATTERN = /\u001b\[[0-9;]*m/g;
23
+ /**
24
+ * OpenCode's shell tool appends `Exited with code N` to the output when the
25
+ * command exits non-zero. Measured live 2026-10-21: this marker is the ONLY
26
+ * machine-readable failure signal in a command's output — the exit code is
27
+ * not reported anywhere else, and the host still reports the call as
28
+ * `status=completed`. The marker is emitted in red, hence the ANSI strip.
29
+ */
30
+ const EXIT_CODE_PATTERN = /(?:^|\n)\s*(?:Error:\s*)?Exited with code\s+(\d+)/i;
31
+ /** Node errno codes — a precise "this operation failed" signal. */
32
+ const ERRNO_PATTERN = /\b(ENOENT|ENOTFOUND|EISDIR|ENOTDIR|EEXIST|ELOOP|ENOTEMPTY|ENAMETOOLONG)\b/;
33
+ /** Python's uncaught-exception marker. */
34
+ const TRACEBACK_PATTERN = /Traceback \(most recent call last\)/;
35
+ /** Node/JS uncaught exception types, anchored to the start of a line. */
36
+ const JS_EXCEPTION_PATTERN = /^(?:Type|Reference|Syntax|Range|URI)Error:/m;
37
+ /** npm's own failure marker. */
38
+ const NPM_ERROR_PATTERN = /^npm ERR!/m;
39
+ /** Process-level crashes. */
40
+ const CRASH_PATTERN = /Segmentation fault|core dumped|panic:|Killed$/m;
41
+ /** OpenCode's shell tool reports some failures as "Command failed". */
42
+ const COMMAND_FAILED_PATTERN = /Command failed/i;
43
+ /** The RAG read override's own failure message. */
44
+ const READ_FALLBACK_PATTERN = /^Could not read file:/i;
45
+ /**
46
+ * Tools whose output is a COMMAND's stdout/stderr.
47
+ *
48
+ * The text rules describe a failed command. Applying them to a tool that
49
+ * returns FILE CONTENT produces false positives: measured live 2026-10-21, a
50
+ * `grep` whose match mentioned "EACCES" and a `read` of a file documenting
51
+ * "EACCES / EPERM" were both reported as failures — and each wrote a quirk.
52
+ * The structured exit code (below) is the reliable signal; the text rules are
53
+ * the fallback for tools that report no exit code.
54
+ */
55
+ const COMMAND_TOOLS = new Set([
56
+ "shell",
57
+ "bash",
58
+ "sh",
59
+ "run",
60
+ "exec",
61
+ "command",
62
+ ]);
63
+ /** Rules that apply to tools which are NOT command runners. */
64
+ const NON_COMMAND_RULES = [
65
+ { cause: "path", pattern: READ_FALLBACK_PATTERN },
66
+ ];
67
+ /**
68
+ * Rules in priority order: the first match wins. Order matters — a
69
+ * `ENOENT` in a command's output is a more actionable cause than "the
70
+ * command exited non-zero", so it is checked first.
71
+ */
72
+ const OUTPUT_RULES = [
73
+ { cause: "permissions", pattern: /\b(EACCES|EPERM)\b/ },
74
+ { cause: "path", pattern: ERRNO_PATTERN },
75
+ { cause: "runtime", pattern: TRACEBACK_PATTERN },
76
+ { cause: "runtime", pattern: JS_EXCEPTION_PATTERN },
77
+ { cause: "tooling", pattern: NPM_ERROR_PATTERN },
78
+ { cause: "crash", pattern: CRASH_PATTERN },
79
+ { cause: "exit-code", pattern: COMMAND_FAILED_PATTERN },
80
+ { cause: "path", pattern: READ_FALLBACK_PATTERN },
81
+ {
82
+ cause: "exit-code",
83
+ pattern: EXIT_CODE_PATTERN,
84
+ accept: (match) => Number(match[1]) !== 0,
85
+ markerIsNotMessage: true,
86
+ },
87
+ ];
88
+ /** Strip ANSI colour codes. */
89
+ export function stripAnsi(text) {
90
+ return text.replace(ANSI_PATTERN, "");
91
+ }
92
+ /** Split into trimmed, non-empty lines. */
93
+ function toLines(text) {
94
+ return text
95
+ .split("\n")
96
+ .map((line) => line.trim())
97
+ .filter((line) => line.length > 0);
98
+ }
99
+ /**
100
+ * The line that carries the most information about the failure: the first
101
+ * line matching the rule. Falls back to the first non-empty line.
102
+ */
103
+ function pickMessageLine(lines, pattern, maxChars) {
104
+ for (const line of lines) {
105
+ if (pattern.test(line))
106
+ return line.slice(0, maxChars);
107
+ }
108
+ return lines[0]?.slice(0, maxChars) ?? "";
109
+ }
110
+ /**
111
+ * Detect a failure in a tool's output.
112
+ *
113
+ * Returns `undefined` when the output carries no failure marker. A tool that
114
+ * succeeded produces no match, so the common case costs one regex pass over
115
+ * the (capped) output.
116
+ */
117
+ export function detectOutputError(tool, output, options) {
118
+ if (!output || output.trim().length === 0)
119
+ return undefined;
120
+ const maxScanChars = options?.maxScanChars ?? 20_000;
121
+ const maxMessageChars = options?.maxMessageChars ?? 200;
122
+ // Errors are reported at the END of a command's output, so scan the tail.
123
+ const scanned = stripAnsi(output.length > maxScanChars ? output.slice(-maxScanChars) : output);
124
+ const lines = toLines(scanned);
125
+ // A structured exit code is AUTHORITATIVE when the tool reports one: a
126
+ // non-zero code means the command failed (no marker required, and none is
127
+ // looked for), and a zero code means it SUCCEEDED — so a marker-looking
128
+ // string in its output (a doc example mentioning ENOENT, a grep for
129
+ // "Error:") is not a failure. This is the strongest signal available and
130
+ // it beats the text rules below, which can misread a localized message.
131
+ const exitCode = options?.exitCode;
132
+ if (typeof exitCode === "number") {
133
+ if (exitCode === 0)
134
+ return undefined;
135
+ const own = lines.filter((line) => !/^Exited with code/i.test(line));
136
+ const message = (own[own.length - 1] ?? "").slice(0, maxMessageChars);
137
+ const marker = `Exited with code ${exitCode}`;
138
+ const text = [message, marker].filter((part) => part.length > 0).join("\n").slice(0, 400);
139
+ return { text, tool, source: "output", causeClass: "exit-code" };
140
+ }
141
+ if (lines.length === 0)
142
+ return undefined;
143
+ // Only a command's output can carry a command-failure marker. A tool that
144
+ // returns file content is exempt — except for the plugin's own read
145
+ // failure message, which is the whole output when it happens.
146
+ const rules = COMMAND_TOOLS.has(tool.toLowerCase()) ? OUTPUT_RULES : NON_COMMAND_RULES;
147
+ for (const rule of rules) {
148
+ const match = scanned.match(rule.pattern);
149
+ if (!match)
150
+ continue;
151
+ if (rule.accept && !rule.accept(match))
152
+ continue;
153
+ let message;
154
+ if (rule.markerIsNotMessage) {
155
+ // The marker is OpenCode's own annotation — the useful text is the
156
+ // command's own error output, which sits just above it.
157
+ const markerIndex = lines.findIndex((line) => rule.pattern.test(line));
158
+ const before = markerIndex > 0 ? lines.slice(0, markerIndex) : lines;
159
+ const own = before.filter((line) => !/^Exited with code/i.test(line));
160
+ message = own[own.length - 1]?.slice(0, maxMessageChars) ?? "";
161
+ }
162
+ else {
163
+ message = pickMessageLine(lines, rule.pattern, maxMessageChars);
164
+ }
165
+ // The marker is always part of the text: it is the stable part of the
166
+ // failure and it is what makes the cause class (and therefore the
167
+ // duplicate check) stable across occurrences. It is omitted when the
168
+ // message already carries it.
169
+ const marker = match[0].trim().replace(/^(?:Error:\s*)?/i, "").slice(0, 80);
170
+ const parts = message.includes(marker) ? [message] : [message, marker];
171
+ const text = parts.filter((part) => part.length > 0).join("\n").slice(0, 400);
172
+ return { text, tool, source: "output", causeClass: rule.cause };
173
+ }
174
+ return undefined;
175
+ }
176
+ /**
177
+ * Read a tool result's structured exit code.
178
+ *
179
+ * The shell tool reports `{ status, truncated, exit }` in its result metadata
180
+ * (measured live 2026-10-21). A non-zero code means the command failed.
181
+ */
182
+ export function extractExitCode(metadata) {
183
+ if (!metadata || typeof metadata !== "object")
184
+ return undefined;
185
+ const record = metadata;
186
+ for (const key of ["exit", "exitCode"]) {
187
+ const value = record[key];
188
+ if (typeof value === "number" && Number.isFinite(value))
189
+ return value;
190
+ }
191
+ return undefined;
192
+ }
193
+ /**
194
+ * Detect a session-level error (a failed model call, a provider error).
195
+ *
196
+ * The `session.error` event carries an `error` object whose shape differs
197
+ * between OpenCode versions, so the message is dug out defensively.
198
+ */
199
+ export function detectSessionError(error) {
200
+ const message = extractErrorMessage(error);
201
+ if (!message || message.length < 10)
202
+ return undefined;
203
+ return { text: message.slice(0, 400), source: "session" };
204
+ }
205
+ /** Dig a human-readable message out of an error payload of unknown shape. */
206
+ export function extractErrorMessage(error) {
207
+ if (typeof error === "string")
208
+ return error.trim() || undefined;
209
+ if (!error || typeof error !== "object")
210
+ return undefined;
211
+ const record = error;
212
+ for (const key of ["message", "error", "reason", "detail", "stack"]) {
213
+ const value = record[key];
214
+ if (typeof value === "string" && value.trim().length > 0)
215
+ return value.trim();
216
+ if (value && typeof value === "object") {
217
+ const nested = extractErrorMessage(value);
218
+ if (nested)
219
+ return nested;
220
+ }
221
+ }
222
+ const name = typeof record["name"] === "string" ? record["name"] : undefined;
223
+ return name;
224
+ }
225
+ //# sourceMappingURL=error-signals.js.map