opencode-dev-framework 0.1.2

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.
package/dist/gate.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Completion gate: run typecheck / test / lint-changed commands when the
3
+ * session goes idle, plus the changed-file tracking that feeds it.
4
+ *
5
+ * Architectural note: OpenCode has no agentStop hook, so the gate runs on
6
+ * `session.idle` — after the agent's turn has already finished. The gate is
7
+ * therefore advisory: it reports failures loudly but cannot block completion.
8
+ */
9
+ import type { CommandResult, RunCommand } from "./host.js";
10
+ import type { ResolvedConfig } from "./types.js";
11
+ /** Fallback per-command timeout (seconds) when `gate.timeout` is unset. */
12
+ export declare const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
13
+ /** Tracks files edited during a session so the gate can scope work. */
14
+ export interface ChangedFileTracker {
15
+ add: (filePath: string, directory?: string) => void;
16
+ getChangedFiles: () => string[];
17
+ clearChangedFiles: () => void;
18
+ }
19
+ /**
20
+ * Create a changed-file tracker. Paths are deduplicated and stored relative
21
+ * to the project directory when one is provided.
22
+ */
23
+ export declare function createChangedFileTracker(): ChangedFileTracker;
24
+ export interface GateStep {
25
+ /** `typecheck`, `test`, or `lint:<file>`. */
26
+ name: string;
27
+ command?: string[];
28
+ skipped: boolean;
29
+ reason?: string;
30
+ result?: CommandResult;
31
+ }
32
+ export interface GateReport {
33
+ /** False when the gate did not run (unchanged project, nothing configured). */
34
+ ran: boolean;
35
+ reason?: string;
36
+ steps: GateStep[];
37
+ /** True when every executed step passed (vacuously true when nothing ran). */
38
+ ok: boolean;
39
+ failedSteps: GateStep[];
40
+ }
41
+ /**
42
+ * Substitute the `{files}` token with the changed-file list. A token that is
43
+ * exactly `{files}` expands to multiple argv entries (the commands run
44
+ * without a shell); an embedded token is replaced inline.
45
+ */
46
+ export declare function substituteFiles(template: string, files: string[]): string[];
47
+ /**
48
+ * Run the completion gate. Steps run sequentially and all results are
49
+ * aggregated — a failing step does not abort the remaining steps.
50
+ */
51
+ export declare function runGate(run: RunCommand, config: ResolvedConfig, changedFiles: string[], options?: {
52
+ cwd?: string;
53
+ }): Promise<GateReport>;
54
+ /** One-line-per-step summary of a gate report for logging. */
55
+ export declare function summarizeGate(report: GateReport): string;
package/dist/gate.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Completion gate: run typecheck / test / lint-changed commands when the
3
+ * session goes idle, plus the changed-file tracking that feeds it.
4
+ *
5
+ * Architectural note: OpenCode has no agentStop hook, so the gate runs on
6
+ * `session.idle` — after the agent's turn has already finished. The gate is
7
+ * therefore advisory: it reports failures loudly but cannot block completion.
8
+ */
9
+ import { isAbsolute, relative } from "node:path";
10
+ import { splitCommand } from "./config-to-opencode.js";
11
+ import { lintFile } from "./lint.js";
12
+ /** Fallback per-command timeout (seconds) when `gate.timeout` is unset. */
13
+ export const DEFAULT_GATE_TIMEOUT_SECONDS = 300;
14
+ /**
15
+ * Create a changed-file tracker. Paths are deduplicated and stored relative
16
+ * to the project directory when one is provided.
17
+ */
18
+ export function createChangedFileTracker() {
19
+ const files = new Set();
20
+ return {
21
+ add(filePath, directory) {
22
+ let candidate = filePath;
23
+ if (directory !== undefined && isAbsolute(filePath)) {
24
+ candidate = relative(directory, filePath);
25
+ }
26
+ files.add(candidate.replace(/^\.\//, ""));
27
+ },
28
+ getChangedFiles() {
29
+ return [...files];
30
+ },
31
+ clearChangedFiles() {
32
+ files.clear();
33
+ },
34
+ };
35
+ }
36
+ function isFailure(result) {
37
+ return result.timedOut || result.exitCode !== 0;
38
+ }
39
+ /**
40
+ * Substitute the `{files}` token with the changed-file list. A token that is
41
+ * exactly `{files}` expands to multiple argv entries (the commands run
42
+ * without a shell); an embedded token is replaced inline.
43
+ */
44
+ export function substituteFiles(template, files) {
45
+ return splitCommand(template).flatMap((token) => token === "{files}" ? files : [token.replaceAll("{files}", files.join(" "))]);
46
+ }
47
+ /**
48
+ * Run the completion gate. Steps run sequentially and all results are
49
+ * aggregated — a failing step does not abort the remaining steps.
50
+ */
51
+ export async function runGate(run, config, changedFiles, options) {
52
+ if (config.gate.skip_unchanged && changedFiles.length === 0) {
53
+ return { ran: false, reason: "no changed files", steps: [], ok: true, failedSteps: [] };
54
+ }
55
+ const timeout = config.gate.timeout ?? DEFAULT_GATE_TIMEOUT_SECONDS;
56
+ const runOptions = { cwd: options?.cwd, timeout };
57
+ const steps = [];
58
+ if (config.gate.run_typecheck) {
59
+ if (config.commands.typecheck !== undefined) {
60
+ const command = splitCommand(config.commands.typecheck);
61
+ steps.push({
62
+ name: "typecheck",
63
+ command,
64
+ skipped: false,
65
+ result: await run(command, runOptions),
66
+ });
67
+ }
68
+ else {
69
+ steps.push({ name: "typecheck", skipped: true, reason: "no typecheck command configured" });
70
+ }
71
+ }
72
+ if (config.gate.run_tests) {
73
+ const template = config.gate.scope === "changed" ? config.commands.test_changed : config.commands.test;
74
+ if (template !== undefined) {
75
+ const command = substituteFiles(template, changedFiles);
76
+ steps.push({ name: "test", command, skipped: false, result: await run(command, runOptions) });
77
+ }
78
+ else {
79
+ const reason = config.gate.scope === "changed"
80
+ ? "no test_changed command configured"
81
+ : "no test command configured";
82
+ steps.push({ name: "test", skipped: true, reason });
83
+ }
84
+ }
85
+ if (config.gate.lint_changed) {
86
+ for (const file of changedFiles) {
87
+ const outcome = await lintFile(run, config, file, runOptions);
88
+ steps.push({
89
+ name: `lint:${file}`,
90
+ command: outcome.command,
91
+ skipped: outcome.skipped,
92
+ reason: outcome.reason,
93
+ result: outcome.result,
94
+ });
95
+ }
96
+ }
97
+ const ran = steps.some((step) => !step.skipped);
98
+ const failedSteps = steps.filter((step) => !step.skipped && step.result !== undefined && isFailure(step.result));
99
+ return {
100
+ ran,
101
+ reason: ran ? undefined : "no gate commands configured",
102
+ steps,
103
+ ok: failedSteps.length === 0,
104
+ failedSteps,
105
+ };
106
+ }
107
+ /** One-line-per-step summary of a gate report for logging. */
108
+ export function summarizeGate(report) {
109
+ if (!report.ran) {
110
+ return `completion gate skipped: ${report.reason ?? "unknown reason"}`;
111
+ }
112
+ const lines = report.steps.map((step) => {
113
+ if (step.skipped) {
114
+ return `${step.name}: skipped (${step.reason ?? "unknown reason"})`;
115
+ }
116
+ const result = step.result;
117
+ if (result === undefined) {
118
+ return `${step.name}: no result`;
119
+ }
120
+ if (result.timedOut) {
121
+ return `${step.name}: timed out`;
122
+ }
123
+ return result.exitCode === 0
124
+ ? `${step.name}: passed`
125
+ : `${step.name}: failed (exit ${result.exitCode})`;
126
+ });
127
+ const verdict = report.ok ? "passed" : "FAILED";
128
+ return `completion gate ${verdict}\n${lines.join("\n")}`;
129
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Host abstraction: how the plugin executes external commands.
3
+ *
4
+ * Unit tests inject a stubbed `RunCommand`; production wiring uses the
5
+ * `runCommand` implementation below, which is compatible with both Node.js
6
+ * and Bun (OpenCode loads plugins under Bun).
7
+ */
8
+ export interface CommandResult {
9
+ stdout: string;
10
+ stderr: string;
11
+ exitCode: number;
12
+ /** True when the process was killed because it exceeded the timeout. */
13
+ timedOut: boolean;
14
+ }
15
+ export interface RunCommandOptions {
16
+ cwd?: string;
17
+ /** Timeout in seconds. The process is killed (SIGTERM) when exceeded. */
18
+ timeout?: number;
19
+ }
20
+ export type RunCommand = (command: string[], options?: RunCommandOptions) => Promise<CommandResult>;
21
+ /**
22
+ * Execute a command without a shell, capturing stdout/stderr.
23
+ *
24
+ * Never rejects: spawn failures resolve with exitCode 127 so callers can
25
+ * treat "tool missing" like any other command failure.
26
+ */
27
+ export declare const runCommand: RunCommand;
package/dist/host.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Host abstraction: how the plugin executes external commands.
3
+ *
4
+ * Unit tests inject a stubbed `RunCommand`; production wiring uses the
5
+ * `runCommand` implementation below, which is compatible with both Node.js
6
+ * and Bun (OpenCode loads plugins under Bun).
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ /**
10
+ * Execute a command without a shell, capturing stdout/stderr.
11
+ *
12
+ * Never rejects: spawn failures resolve with exitCode 127 so callers can
13
+ * treat "tool missing" like any other command failure.
14
+ */
15
+ export const runCommand = (command, options = {}) => new Promise((resolve) => {
16
+ const [cmd, ...args] = command;
17
+ let settled = false;
18
+ let stdout = "";
19
+ let stderr = "";
20
+ let timedOut = false;
21
+ const finish = (result) => {
22
+ if (settled) {
23
+ return;
24
+ }
25
+ settled = true;
26
+ if (timer !== undefined) {
27
+ clearTimeout(timer);
28
+ }
29
+ resolve(result);
30
+ };
31
+ let timer;
32
+ let child;
33
+ try {
34
+ child = spawn(cmd, args, { cwd: options.cwd });
35
+ }
36
+ catch (error) {
37
+ finish({ stdout, stderr: String(error), exitCode: 127, timedOut });
38
+ return;
39
+ }
40
+ if (options.timeout !== undefined && options.timeout > 0) {
41
+ timer = setTimeout(() => {
42
+ timedOut = true;
43
+ child.kill("SIGTERM");
44
+ }, options.timeout * 1000);
45
+ }
46
+ child.stdout?.on("data", (chunk) => {
47
+ stdout += chunk.toString();
48
+ });
49
+ child.stderr?.on("data", (chunk) => {
50
+ stderr += chunk.toString();
51
+ });
52
+ child.on("error", (error) => {
53
+ finish({ stdout, stderr: stderr + String(error), exitCode: 127, timedOut });
54
+ });
55
+ child.on("close", (code) => {
56
+ finish({ stdout, stderr, exitCode: code ?? 1, timedOut });
57
+ });
58
+ });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * opencode-dev-framework plugin entry point.
3
+ *
4
+ * Wired so far:
5
+ * - tool.execute.before -> protected-path / dangerous-command guardrails
6
+ * - event (file.edited) -> per-edit lint + changed-file tracking
7
+ * - event (session.idle) -> completion gate (advisory: reports loudly, cannot block)
8
+ * - experimental.chat.system.transform -> constitution injection
9
+ */
10
+ import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
11
+ import { type ChangedFileTracker } from "./gate.js";
12
+ import { type RunCommand } from "./host.js";
13
+ import { type LogFn } from "./logger.js";
14
+ import type { ResolvedConfig } from "./types.js";
15
+ /**
16
+ * Build the plugin's hooks. Exported (rather than inlined in the plugin) so
17
+ * tests can inject a stubbed command runner and tracker.
18
+ */
19
+ export declare function buildHooks(ctx: PluginInput, config: ResolvedConfig, log: LogFn, run?: RunCommand, tracker?: ChangedFileTracker, constitution?: string | null): Hooks;
20
+ export declare const devFramework: Plugin;
21
+ export default devFramework;
package/dist/index.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * opencode-dev-framework plugin entry point.
3
+ *
4
+ * Wired so far:
5
+ * - tool.execute.before -> protected-path / dangerous-command guardrails
6
+ * - event (file.edited) -> per-edit lint + changed-file tracking
7
+ * - event (session.idle) -> completion gate (advisory: reports loudly, cannot block)
8
+ * - experimental.chat.system.transform -> constitution injection
9
+ */
10
+ import { loadConfig } from "./config.js";
11
+ import { createChangedFileTracker, runGate, summarizeGate, } from "./gate.js";
12
+ import { runCommand } from "./host.js";
13
+ import { isLintFailure, lintFile, summarizeLint } from "./lint.js";
14
+ import { createLogger } from "./logger.js";
15
+ import { checkToolCall } from "./protect.js";
16
+ import { injectConstitution, loadConstitution } from "./rules.js";
17
+ /**
18
+ * Build the plugin's hooks. Exported (rather than inlined in the plugin) so
19
+ * tests can inject a stubbed command runner and tracker.
20
+ */
21
+ export function buildHooks(ctx, config, log, run = runCommand, tracker = createChangedFileTracker(), constitution = null) {
22
+ const onFileEdited = async (filePath) => {
23
+ tracker.add(filePath, ctx.directory);
24
+ if (!config.on_edit.lint) {
25
+ return;
26
+ }
27
+ const outcome = await lintFile(run, config, filePath, {
28
+ cwd: ctx.directory,
29
+ timeout: config.gate.timeout,
30
+ });
31
+ if (outcome.skipped) {
32
+ await log("debug", summarizeLint(outcome), { filePath, reason: outcome.reason });
33
+ return;
34
+ }
35
+ if (!isLintFailure(outcome)) {
36
+ await log("info", summarizeLint(outcome), { filePath });
37
+ return;
38
+ }
39
+ const summary = summarizeLint(outcome);
40
+ await log("error", summary, {
41
+ filePath,
42
+ command: outcome.command?.join(" "),
43
+ stdout: outcome.result?.stdout,
44
+ stderr: outcome.result?.stderr,
45
+ });
46
+ // In strict mode lint failures throw. Note: file.edited is an event
47
+ // notification (the edit already happened), so this cannot undo the
48
+ // edit — it surfaces the failure loudly to the session.
49
+ if (config.profile === "strict") {
50
+ throw new Error(`[opencode-dev-framework] ${summary}`);
51
+ }
52
+ };
53
+ const onSessionIdle = async () => {
54
+ const changedFiles = tracker.getChangedFiles();
55
+ const report = await runGate(run, config, changedFiles, { cwd: ctx.directory });
56
+ tracker.clearChangedFiles();
57
+ const summary = summarizeGate(report);
58
+ if (!report.ran) {
59
+ await log("debug", summary);
60
+ return;
61
+ }
62
+ if (report.ok) {
63
+ await log("info", summary);
64
+ return;
65
+ }
66
+ // The gate cannot physically block (session.idle fires after the turn
67
+ // ends), so failure visibility is the enforcement mechanism.
68
+ const level = config.gate.block_on_failure ? "error" : "warn";
69
+ await log(level, summary, {
70
+ failedSteps: report.failedSteps.map((step) => ({
71
+ name: step.name,
72
+ command: step.command?.join(" "),
73
+ exitCode: step.result?.exitCode,
74
+ timedOut: step.result?.timedOut,
75
+ stderr: step.result?.stderr,
76
+ })),
77
+ });
78
+ };
79
+ return {
80
+ "experimental.chat.system.transform": async (_input, output) => {
81
+ const next = injectConstitution(output.system, constitution);
82
+ if (next !== output.system) {
83
+ await log("info", "constitution injected into system prompt");
84
+ output.system = next;
85
+ }
86
+ },
87
+ "tool.execute.before": async (input, output) => {
88
+ const result = checkToolCall(config, input.tool, output.args, ctx.directory);
89
+ if (result.decision === "allow") {
90
+ return;
91
+ }
92
+ const message = result.reason ?? "blocked by guardrails";
93
+ const extra = {
94
+ tool: input.tool,
95
+ sessionID: input.sessionID,
96
+ pattern: result.matchedPattern,
97
+ };
98
+ if (result.decision === "warn") {
99
+ await log("warn", message, extra);
100
+ return;
101
+ }
102
+ await log("error", message, extra);
103
+ throw new Error(`[opencode-dev-framework] ${message}`);
104
+ },
105
+ event: async ({ event }) => {
106
+ if (event.type === "file.edited") {
107
+ await onFileEdited(event.properties.file);
108
+ return;
109
+ }
110
+ if (event.type === "session.idle") {
111
+ await onSessionIdle();
112
+ }
113
+ },
114
+ };
115
+ }
116
+ export const devFramework = async (ctx) => {
117
+ const config = loadConfig(ctx.directory);
118
+ // The off profile registers no hooks at all.
119
+ if (config.profile === "off") {
120
+ return {};
121
+ }
122
+ const log = createLogger(ctx.client);
123
+ const { constitution, warning } = await loadConstitution(config, ctx.directory);
124
+ if (warning) {
125
+ await log("warn", warning);
126
+ }
127
+ return buildHooks(ctx, config, log, runCommand, createChangedFileTracker(), constitution);
128
+ };
129
+ export default devFramework;
package/dist/lint.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Per-edit lint: resolve the linter command for a changed file and run it
3
+ * through an injectable command runner. Pure orchestration — the OpenCode
4
+ * hook wiring lives in src/index.ts.
5
+ */
6
+ import type { CommandResult, RunCommand } from "./host.js";
7
+ import type { ResolvedConfig } from "./types.js";
8
+ /** Fallback per-lint timeout (seconds) when the config sets none. */
9
+ export declare const DEFAULT_LINT_TIMEOUT_SECONDS = 60;
10
+ export interface LintOutcome {
11
+ /** True when no linter ran (file excluded or no command configured). */
12
+ skipped: boolean;
13
+ /** Why the file was skipped, when it was. */
14
+ reason?: string;
15
+ filePath: string;
16
+ /** The argv that was executed, when a linter ran. */
17
+ command?: string[];
18
+ result?: CommandResult;
19
+ }
20
+ /**
21
+ * Match a file path against the config `exclude` globs. Returns the matching
22
+ * pattern, or undefined. Patterns without a slash also match basenames at
23
+ * any depth, mirroring protected-path semantics.
24
+ */
25
+ export declare function matchExclude(config: ResolvedConfig, filePath: string, directory?: string): string | undefined;
26
+ /**
27
+ * Resolve the lint command for a file: the per-extension override wins over
28
+ * the default command. The `{file}` token is replaced with the file path;
29
+ * commands without the token run as-is. Returns undefined when no lint
30
+ * command is configured at all.
31
+ */
32
+ export declare function resolveLintCommand(config: ResolvedConfig, filePath: string): string[] | undefined;
33
+ /**
34
+ * Lint a single file. Excluded files and file types without a configured
35
+ * linter are skipped; everything else runs through the injected runner.
36
+ */
37
+ export declare function lintFile(run: RunCommand, config: ResolvedConfig, filePath: string, options?: {
38
+ cwd?: string;
39
+ timeout?: number;
40
+ }): Promise<LintOutcome>;
41
+ /** True when a lint outcome represents a failure (non-zero exit or timeout). */
42
+ export declare function isLintFailure(outcome: LintOutcome): boolean;
43
+ /** One-line summary of a lint outcome for logging. */
44
+ export declare function summarizeLint(outcome: LintOutcome): string;
package/dist/lint.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Per-edit lint: resolve the linter command for a changed file and run it
3
+ * through an injectable command runner. Pure orchestration — the OpenCode
4
+ * hook wiring lives in src/index.ts.
5
+ */
6
+ import { basename, extname, isAbsolute, relative } from "node:path";
7
+ import picomatch from "picomatch";
8
+ import { normalizeCommandMap, splitCommand } from "./config-to-opencode.js";
9
+ /** Fallback per-lint timeout (seconds) when the config sets none. */
10
+ export const DEFAULT_LINT_TIMEOUT_SECONDS = 60;
11
+ /**
12
+ * Match a file path against the config `exclude` globs. Returns the matching
13
+ * pattern, or undefined. Patterns without a slash also match basenames at
14
+ * any depth, mirroring protected-path semantics.
15
+ */
16
+ export function matchExclude(config, filePath, directory) {
17
+ let candidate = filePath;
18
+ if (directory !== undefined && isAbsolute(filePath)) {
19
+ candidate = relative(directory, filePath);
20
+ }
21
+ candidate = candidate.replace(/^\.\//, "");
22
+ const name = basename(candidate);
23
+ for (const pattern of config.exclude) {
24
+ const isMatch = picomatch(pattern, { dot: true });
25
+ if (isMatch(candidate)) {
26
+ return pattern;
27
+ }
28
+ if (!pattern.includes("/") && isMatch(name)) {
29
+ return pattern;
30
+ }
31
+ }
32
+ return undefined;
33
+ }
34
+ /**
35
+ * Resolve the lint command for a file: the per-extension override wins over
36
+ * the default command. The `{file}` token is replaced with the file path;
37
+ * commands without the token run as-is. Returns undefined when no lint
38
+ * command is configured at all.
39
+ */
40
+ export function resolveLintCommand(config, filePath) {
41
+ const { default: defaultCommand, byExtension } = normalizeCommandMap(config.commands.lint);
42
+ const template = byExtension[extname(filePath)] ?? defaultCommand;
43
+ if (template === undefined) {
44
+ return undefined;
45
+ }
46
+ return splitCommand(template).map((token) => token.replaceAll("{file}", filePath));
47
+ }
48
+ /**
49
+ * Lint a single file. Excluded files and file types without a configured
50
+ * linter are skipped; everything else runs through the injected runner.
51
+ */
52
+ export async function lintFile(run, config, filePath, options) {
53
+ const excluded = matchExclude(config, filePath, options?.cwd);
54
+ if (excluded !== undefined) {
55
+ return { skipped: true, reason: `excluded by "${excluded}"`, filePath };
56
+ }
57
+ const command = resolveLintCommand(config, filePath);
58
+ if (command === undefined) {
59
+ return { skipped: true, reason: "no lint command configured for this file type", filePath };
60
+ }
61
+ const result = await run(command, {
62
+ cwd: options?.cwd,
63
+ timeout: options?.timeout ?? DEFAULT_LINT_TIMEOUT_SECONDS,
64
+ });
65
+ return { skipped: false, filePath, command, result };
66
+ }
67
+ /** True when a lint outcome represents a failure (non-zero exit or timeout). */
68
+ export function isLintFailure(outcome) {
69
+ if (outcome.skipped || outcome.result === undefined) {
70
+ return false;
71
+ }
72
+ return outcome.result.timedOut || outcome.result.exitCode !== 0;
73
+ }
74
+ /** One-line summary of a lint outcome for logging. */
75
+ export function summarizeLint(outcome) {
76
+ if (outcome.skipped) {
77
+ return `lint skipped for ${outcome.filePath}: ${outcome.reason ?? "unknown reason"}`;
78
+ }
79
+ const result = outcome.result;
80
+ if (result === undefined) {
81
+ return `lint produced no result for ${outcome.filePath}`;
82
+ }
83
+ if (result.timedOut) {
84
+ return `lint timed out for ${outcome.filePath}`;
85
+ }
86
+ if (result.exitCode !== 0) {
87
+ return `lint failed for ${outcome.filePath} (exit ${result.exitCode})`;
88
+ }
89
+ return `lint passed for ${outcome.filePath}`;
90
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Structured logging wrapper around the OpenCode client's app.log API.
3
+ */
4
+ import type { PluginInput } from "@opencode-ai/plugin";
5
+ export type LogLevel = "debug" | "info" | "warn" | "error";
6
+ export declare const LOG_SERVICE = "opencode-dev-framework";
7
+ export type LogFn = (level: LogLevel, message: string, extra?: Record<string, unknown>) => Promise<void>;
8
+ /**
9
+ * Create a logger bound to the OpenCode client. Logging failures are
10
+ * swallowed — logging must never break the plugin or a tool call.
11
+ */
12
+ export declare function createLogger(client: PluginInput["client"]): LogFn;
package/dist/logger.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Structured logging wrapper around the OpenCode client's app.log API.
3
+ */
4
+ export const LOG_SERVICE = "opencode-dev-framework";
5
+ /**
6
+ * Create a logger bound to the OpenCode client. Logging failures are
7
+ * swallowed — logging must never break the plugin or a tool call.
8
+ */
9
+ export function createLogger(client) {
10
+ return async (level, message, extra) => {
11
+ try {
12
+ await client.app.log({ body: { service: LOG_SERVICE, level, message, extra } });
13
+ }
14
+ catch {
15
+ // Intentionally ignored: logging is best-effort.
16
+ }
17
+ };
18
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Guardrail logic: match tool calls against protected paths and dangerous
3
+ * shell commands. Pure functions — the OpenCode hook wiring lives in
4
+ * src/index.ts.
5
+ */
6
+ import type { ResolvedConfig } from "./types.js";
7
+ export type GuardDecision = "allow" | "warn" | "deny";
8
+ export interface GuardResult {
9
+ decision: GuardDecision;
10
+ reason?: string;
11
+ /** The config glob or command pattern that matched, if any. */
12
+ matchedPattern?: string;
13
+ }
14
+ /** Tools whose args carry a target file path. */
15
+ export declare const FILE_TOOLS: ReadonlySet<string>;
16
+ /** Tools whose args carry a shell command. */
17
+ export declare const SHELL_TOOLS: ReadonlySet<string>;
18
+ export interface DangerousCommand {
19
+ pattern: RegExp;
20
+ reason: string;
21
+ }
22
+ /** Dangerous shell commands that guardrails flag. */
23
+ export declare const DANGEROUS_COMMANDS: DangerousCommand[];
24
+ /** Extract the target file path from tool args, if present. */
25
+ export declare function extractFilePath(args: unknown): string | undefined;
26
+ /** Extract the shell command from tool args, if present. */
27
+ export declare function extractCommand(args: unknown): string | undefined;
28
+ /**
29
+ * Check a file path against the protected globs. Returns the matching
30
+ * pattern, or undefined. Patterns without a slash also match basenames at
31
+ * any depth (so `.env*` protects `config/.env.local` too).
32
+ */
33
+ export declare function matchProtectedPath(config: ResolvedConfig, filePath: string, directory?: string): string | undefined;
34
+ /** Check a shell command against the dangerous-command list. */
35
+ export declare function matchDangerousCommand(command: string): DangerousCommand | undefined;
36
+ /**
37
+ * Evaluate a tool call against the guardrail config.
38
+ *
39
+ * Returns `allow` when protection is disabled (`off` profile or
40
+ * `protect_off: true`), when the tool is not guarded, or when nothing
41
+ * matched. Otherwise returns `deny` or `warn` per `protect_mode`.
42
+ */
43
+ export declare function checkToolCall(config: ResolvedConfig, tool: string, args: unknown, directory?: string): GuardResult;