opencode-dev-framework 0.1.29 → 0.2.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/logger.d.ts CHANGED
@@ -1,18 +1,28 @@
1
1
  /**
2
- * Structured logging wrapper around the OpenCode client's app.log API.
2
+ * Structured logging wrapper. Supports both V1 (client.app.log) and V2 (stderr/file).
3
3
  */
4
- import type { PluginInput } from "@opencode-ai/plugin";
5
4
  export type LogLevel = "debug" | "info" | "warn" | "error";
6
5
  export declare const LOG_SERVICE = "opencode-dev-framework";
7
6
  export type LogFn = (level: LogLevel, message: string, extra?: Record<string, unknown>) => Promise<void>;
7
+ type V1Client = {
8
+ app?: {
9
+ log?: (args: {
10
+ body: {
11
+ service: string;
12
+ level: LogLevel;
13
+ message: string;
14
+ extra?: Record<string, unknown>;
15
+ };
16
+ }) => Promise<unknown>;
17
+ };
18
+ };
8
19
  /**
9
- * Create a logger bound to the OpenCode client. Logging never throws:
10
- * `app.log` failures fall back to stderr so the failure stays visible
11
- * (a total swallow made production debugging painful during development),
12
- * and even stderr failures are ignored as a last resort.
13
- *
14
- * If the `OPENCODE_DEV_FRAMEWORK_LOG_FILE` environment variable is set, every
15
- * log line is also appended to that path as JSON, which is useful when
16
- * `app.log` is unavailable or when a persistent trace is needed.
20
+ * Create a logger. If a V1 client is provided, forwards to `client.app.log`
21
+ * (as tests expect). Otherwise logs to stderr/file (V2 runtime).
17
22
  */
18
- export declare function createLogger(client: PluginInput["client"]): LogFn;
23
+ export declare function createLogger(client?: V1Client | {
24
+ app: {
25
+ log: (...args: unknown[]) => Promise<unknown>;
26
+ };
27
+ }): LogFn;
28
+ export {};
package/dist/logger.js CHANGED
@@ -1,17 +1,11 @@
1
1
  /**
2
- * Structured logging wrapper around the OpenCode client's app.log API.
2
+ * Structured logging wrapper. Supports both V1 (client.app.log) and V2 (stderr/file).
3
3
  */
4
4
  import { appendFile } from "node:fs/promises";
5
5
  export const LOG_SERVICE = "opencode-dev-framework";
6
6
  /**
7
- * Create a logger bound to the OpenCode client. Logging never throws:
8
- * `app.log` failures fall back to stderr so the failure stays visible
9
- * (a total swallow made production debugging painful during development),
10
- * and even stderr failures are ignored as a last resort.
11
- *
12
- * If the `OPENCODE_DEV_FRAMEWORK_LOG_FILE` environment variable is set, every
13
- * log line is also appended to that path as JSON, which is useful when
14
- * `app.log` is unavailable or when a persistent trace is needed.
7
+ * Create a logger. If a V1 client is provided, forwards to `client.app.log`
8
+ * (as tests expect). Otherwise logs to stderr/file (V2 runtime).
15
9
  */
16
10
  export function createLogger(client) {
17
11
  const filePath = process.env.OPENCODE_DEV_FRAMEWORK_LOG_FILE;
@@ -23,23 +17,46 @@ export function createLogger(client) {
23
17
  message,
24
18
  extra,
25
19
  });
26
- try {
27
- await client.app.log({ body: { service: LOG_SERVICE, level, message, extra } });
28
- }
29
- catch (error) {
20
+ if (client?.app?.log) {
30
21
  try {
31
- process.stderr.write(`[${LOG_SERVICE}] ${level} ${message} (app.log failed: ${String(error)})\n`);
22
+ // biome-ignore lint/style/noNonNullAssertion: guarded by if above
23
+ await client.app.log({
24
+ body: { service: LOG_SERVICE, level, message, extra },
25
+ });
32
26
  }
33
- catch {
34
- // Even stderr may be unavailable; truly ignore.
27
+ catch (error) {
28
+ try {
29
+ process.stderr.write(`[${LOG_SERVICE}] ${level} ${message} (app.log failed: ${String(error)})\n`);
30
+ }
31
+ catch {
32
+ // ignore
33
+ }
34
+ }
35
+ if (filePath) {
36
+ try {
37
+ await appendFile(filePath, `${line}\n`);
38
+ }
39
+ catch {
40
+ // best-effort
41
+ }
35
42
  }
43
+ return;
44
+ }
45
+ try {
46
+ process.stderr.write(`[${LOG_SERVICE}] ${level} ${message}\n`);
47
+ if (extra && Object.keys(extra).length > 0) {
48
+ process.stderr.write(` extra: ${JSON.stringify(extra)}\n`);
49
+ }
50
+ }
51
+ catch {
52
+ // ignore
36
53
  }
37
54
  if (filePath) {
38
55
  try {
39
56
  await appendFile(filePath, `${line}\n`);
40
57
  }
41
58
  catch {
42
- // File logging is best-effort.
59
+ // best-effort
43
60
  }
44
61
  }
45
62
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-dev-framework",
3
- "version": "0.1.29",
3
+ "version": "0.2.2",
4
4
  "description": "OpenCode plugin that enforces project-specific quality gates during AI coding sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -56,19 +56,20 @@
56
56
  "guardrails"
57
57
  ],
58
58
  "dependencies": {
59
+ "@opencode/plugin": "^2.0.11",
59
60
  "picomatch": "^4.0.5",
60
61
  "yaml": "^2.9.0",
61
62
  "zod": "^4.4.3"
62
63
  },
63
64
  "devDependencies": {
64
65
  "@biomejs/biome": "^2.5.8",
65
- "@opencode-ai/plugin": "^1.18.18",
66
- "@opentui/core": "^0.5.3",
67
- "@opentui/keymap": "^0.5.3",
68
- "@opentui/solid": "^0.5.3",
66
+ "@opentui/core": "^0.5.10",
67
+ "@opentui/keymap": "^0.5.11",
68
+ "@opentui/solid": "^0.5.11",
69
69
  "@types/node": "^26.2.0",
70
70
  "@types/picomatch": "^4.0.3",
71
71
  "markdownlint-cli2": "^0.23.2",
72
+ "solid-js": "^1.9.12",
72
73
  "typescript": "^7.0.2",
73
74
  "vitest": "^4.1.10"
74
75
  }
package/tui.tsx CHANGED
@@ -1,192 +1,140 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
 
3
- import type { TuiPluginModule } from "@opencode-ai/plugin/tui";
3
+ import { Plugin } from "@opencode/plugin/tui";
4
4
  import { changeProfile, verifyGate } from "./dist/commands.js";
5
5
  import { loadConfig } from "./dist/config.js";
6
6
  import { runCommand } from "./dist/host.js";
7
7
  import { renderConfigStatus, renderHelp } from "./dist/format-status.js";
8
8
  import type { Profile } from "./dist/types.js";
9
9
 
10
- type TuiApi = Parameters<TuiPluginModule["tui"]>[0];
11
-
12
- /**
13
- * OpenCode invokes a slash command's `run` with a keymap `CommandContext`.
14
- * The trailing slash text (e.g. `standard` in `/df-profile standard`) is
15
- * available on `ctx.input`. TUI commands are UI-only: they never insert text
16
- * into the chat stream, so they cannot leak into a model turn.
17
- */
18
- type CommandCtx = { input?: string };
19
-
20
- type DevFrameworkCommand = {
21
- title: string;
22
- name: string;
23
- description: string;
24
- slashName: string;
25
- run: (ctx?: CommandCtx) => void | Promise<void>;
26
- };
27
-
28
- /**
29
- * Register dev-framework slash commands.
30
- *
31
- * The current OpenCode API is `api.keymap.registerLayer` (a command-palette
32
- * layer that also wires up `/slash` invocations). This mirrors how DCP
33
- * registers its commands. The legacy `api.command` v1 API is kept as a
34
- * fallback (also like DCP). `slashName` makes OpenCode recognize the command
35
- * **with arguments** and pass the trailing text to `run` via `ctx.input`.
36
- *
37
- * All four commands are TUI commands (no server prompt command, which would
38
- * produce a model turn). Each `run` reads `ctx.input` so both the bare form
39
- * (e.g. `/df-profile` opens a picker) and the argument form (e.g.
40
- * `/df-profile standard` applies directly) work without feeding text to the
41
- * model.
42
- */
43
- function registerCommands(api: TuiApi, commands: DevFrameworkCommand[]): void {
44
- const keymap = (api as { keymap?: { registerLayer?: (layer: unknown) => void } }).keymap;
45
- if (keymap?.registerLayer) {
46
- keymap.registerLayer({
47
- commands: commands.map((command) => ({
48
- namespace: "palette",
49
- name: command.name,
50
- title: command.title,
51
- desc: command.description,
52
- category: "dev-framework",
53
- slashName: command.slashName,
54
- run: command.run,
55
- })),
56
- });
57
- return;
58
- }
59
-
60
- // Legacy v1 API fallback (used on runtimes where keymap.registerLayer is
61
- // unavailable). Mirrors how DCP registers its commands.
62
- const commandApi = (api as { command?: { register?: (fn: () => unknown) => void } }).command;
63
- commandApi?.register?.(() =>
64
- commands.map((command) => ({
65
- title: command.title,
66
- value: command.name,
67
- description: command.description,
68
- category: "dev-framework",
69
- slash: { name: command.slashName },
70
- onSelect: command.run,
71
- })),
72
- );
73
- }
74
-
75
10
  const PROFILES: Profile[] = ["off", "advisory", "standard", "strict"];
76
11
 
77
- const tui: TuiPluginModule["tui"] = async (api) => {
78
- const directory = api.state.path.directory;
79
-
80
- registerCommands(api, [
81
- {
82
- title: "dev-framework status",
83
- name: "df-status",
84
- description: "Show the current dev-framework configuration",
85
- slashName: "df-status",
86
- run: () => showStatusDialog(api, directory),
87
- },
88
- {
89
- title: "dev-framework help",
90
- name: "df-help",
91
- description: "List available dev-framework commands",
92
- slashName: "df-help",
93
- run: () => showHelpDialog(api),
94
- },
95
- {
96
- title: "dev-framework profile",
97
- name: "df-profile",
98
- description: "Change the active dev-framework profile",
99
- slashName: "df-profile",
100
- run: (ctx) => handleProfile(api, directory, ctx?.input),
101
- },
102
- {
103
- title: "dev-framework verify",
104
- name: "df-verify",
105
- description: "Run the dev-framework completion gate",
106
- slashName: "df-verify",
107
- run: () => handleVerify(api, directory),
108
- },
109
- ]);
110
- };
111
-
112
- function showStatusDialog(api: TuiApi, directory: string): void {
113
- const config = loadConfig(directory);
114
- const DialogAlert = api.ui.DialogAlert;
115
- api.ui.dialog.replace(() => (
116
- <DialogAlert
117
- title="opencode-dev-framework status"
118
- message={renderConfigStatus(config)}
119
- onConfirm={() => api.ui.dialog.clear()}
120
- />
121
- ));
122
- }
123
-
124
- function showHelpDialog(api: TuiApi): void {
125
- const DialogAlert = api.ui.DialogAlert;
126
- api.ui.dialog.replace(() => (
127
- <DialogAlert
128
- title="dev-framework commands"
129
- message={renderHelp()}
130
- onConfirm={() => api.ui.dialog.clear()}
131
- />
132
- ));
133
- }
12
+ export default Plugin.define({
13
+ id: "opencode-dev-framework",
14
+ setup(ctx) {
15
+ const getDirectory = (): string => {
16
+ const loc = ctx.location as unknown as { directory?: string } | undefined;
17
+ if (loc?.directory) return loc.directory;
18
+ try {
19
+ const def = (ctx.data as unknown as { location: { default: () => { directory: string } | undefined } }).location.default();
20
+ if (def?.directory) return def.directory;
21
+ } catch {
22
+ // ignore
23
+ }
24
+ return process.cwd();
25
+ };
134
26
 
135
- /** Bare `/df-profile` opens a picker; `/df-profile <name>` applies directly. */
136
- function handleProfile(api: TuiApi, directory: string, input?: string): void {
137
- // OpenCode passes the command name itself as `ctx.input` for a bare invocation
138
- // (e.g. "df-profile"), not an empty string. Normalize that back to "bare".
139
- const raw = (input ?? "").trim();
140
- const arg = raw === "df-profile" ? "" : raw;
141
- if (arg && PROFILES.includes(arg as Profile)) {
142
- void changeProfile(directory, arg as Profile).then((message) => {
143
- api.ui.toast?.({ message, variant: "success" });
144
- });
145
- api.ui.dialog.clear();
146
- return;
147
- }
148
- if (arg) {
149
- api.ui.toast?.({
150
- message: `Usage: /df-profile <${PROFILES.join("|")}>`,
151
- variant: "warning",
152
- });
153
- api.ui.dialog.clear();
154
- return;
155
- }
156
- showProfileDialog(api, directory);
157
- }
27
+ const register = () => {
28
+ try {
29
+ (ctx as unknown as { keymap?: { layer: (fn: () => unknown) => void } }).keymap?.layer?.(() => ({
30
+ mode: "global",
31
+ commands: [
32
+ {
33
+ id: "df-status",
34
+ title: "dev-framework status",
35
+ description: "Show the current dev-framework configuration",
36
+ group: "dev-framework",
37
+ palette: true,
38
+ slash: { name: "df-status" },
39
+ run: () => {
40
+ const dir = getDirectory();
41
+ const config = loadConfig(dir);
42
+ void ctx.ui.dialog.alert({
43
+ title: "opencode-dev-framework status",
44
+ message: renderConfigStatus(config),
45
+ });
46
+ },
47
+ },
48
+ {
49
+ id: "df-help",
50
+ title: "dev-framework help",
51
+ description: "List available dev-framework commands",
52
+ slash: { name: "df-help" },
53
+ group: "dev-framework",
54
+ palette: true,
55
+ run: () => {
56
+ void ctx.ui.dialog.alert({
57
+ title: "dev-framework commands",
58
+ message: renderHelp(),
59
+ });
60
+ },
61
+ },
62
+ {
63
+ id: "df-profile",
64
+ title: "dev-framework profile",
65
+ description: "Change the active dev-framework profile",
66
+ group: "dev-framework",
67
+ palette: true,
68
+ slash: { name: "df-profile", arguments: true },
69
+ run: async (input?: string) => {
70
+ const dir = getDirectory();
71
+ const raw = (input ?? "").trim();
72
+ const arg = raw === "df-profile" ? "" : raw;
73
+ if (arg && (PROFILES as string[]).includes(arg)) {
74
+ const message = await changeProfile(dir, arg as Profile);
75
+ ctx.ui.toast.show({ message, variant: "success" });
76
+ return;
77
+ }
78
+ if (arg) {
79
+ ctx.ui.toast.show({
80
+ message: `Usage: /df-profile <${PROFILES.join("|")}>`,
81
+ variant: "warning",
82
+ });
83
+ return;
84
+ }
85
+ const selected = await ctx.ui.dialog.select({
86
+ title: "dev-framework profile",
87
+ options: PROFILES.map((p) => ({ title: p, value: p })),
88
+ });
89
+ if (selected) {
90
+ const message = await changeProfile(dir, selected as Profile);
91
+ ctx.ui.toast.show({ message, variant: "success" });
92
+ }
93
+ },
94
+ },
95
+ {
96
+ id: "df-verify",
97
+ title: "dev-framework verify",
98
+ description: "Run the dev-framework completion gate",
99
+ group: "dev-framework",
100
+ palette: true,
101
+ slash: { name: "df-verify" },
102
+ run: async () => {
103
+ const dir = getDirectory();
104
+ const config = loadConfig(dir);
105
+ const { summary, report } = await verifyGate(runCommand, dir, config);
106
+ await ctx.ui.dialog.alert({
107
+ title: report.ok ? "dev-framework gate passed" : "dev-framework gate failed",
108
+ message: summary,
109
+ });
110
+ ctx.ui.toast.show({ message: summary, variant: report.ok ? "success" : "error" });
111
+ },
112
+ },
113
+ ],
114
+ }));
115
+ } catch (e) {
116
+ try {
117
+ console.warn("[opencode-dev-framework:tui] keymap registration failed:", String(e));
118
+ } catch {}
119
+ }
120
+ };
158
121
 
159
- function showProfileDialog(api: TuiApi, directory: string): void {
160
- const DialogSelect = api.ui.DialogSelect;
161
- api.ui.dialog.replace(() => (
162
- <DialogSelect
163
- title="dev-framework profile"
164
- options={PROFILES.map((p) => ({ title: p, value: p }))}
165
- onSelect={(option) => {
166
- api.ui.dialog.clear();
167
- void changeProfile(directory, option.value as Profile).then((message) => {
168
- api.ui.toast?.({ message, variant: "success" });
122
+ try {
123
+ const slot = (ctx.ui as unknown as { slot?: (claim: { append: string; render: () => unknown }) => void }).slot;
124
+ if (typeof slot === "function") {
125
+ slot({
126
+ append: "app",
127
+ render() {
128
+ register();
129
+ return null as unknown as null;
130
+ },
169
131
  });
170
- }}
171
- />
172
- ));
173
- }
132
+ return;
133
+ }
134
+ } catch {
135
+ // ignore, fallback below
136
+ }
174
137
 
175
- async function handleVerify(api: TuiApi, directory: string): Promise<void> {
176
- const config = loadConfig(directory);
177
- const { summary, report } = await verifyGate(runCommand, directory, config);
178
- const DialogAlert = api.ui.DialogAlert;
179
- api.ui.dialog.replace(() => (
180
- <DialogAlert
181
- title={report.ok ? "dev-framework gate passed" : "dev-framework gate failed"}
182
- message={summary}
183
- onConfirm={() => api.ui.dialog.clear()}
184
- />
185
- ));
186
- api.ui.toast?.({ message: summary, variant: report.ok ? "success" : "error" });
187
- }
188
-
189
- export default {
190
- id: "opencode-dev-framework",
191
- tui,
192
- } satisfies TuiPluginModule;
138
+ register();
139
+ },
140
+ });
package/dist/tools.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export declare function buildTools(_ctx: {
2
- directory: string;
3
- }): NonNullable<import("@opencode-ai/plugin").Hooks["tool"]>;
package/dist/tools.js DELETED
@@ -1,95 +0,0 @@
1
- import { tool } from "@opencode-ai/plugin";
2
- import { loadConfig, clearConfigCache } from "./config.js";
3
- import { installTemplates, writeDetectedConfig } from "./installer.js";
4
- import { getHookState, updateHookState } from "./registry.js";
5
- import { loadConstitution } from "./rules.js";
6
- import { renderStatus } from "./format-status.js";
7
- import { changeProfile } from "./commands.js";
8
- const PROFILES = ["off", "advisory", "standard", "strict"];
9
- function isProfile(value) {
10
- return PROFILES.includes(value);
11
- }
12
- export function buildTools(_ctx) {
13
- return {
14
- dev_framework_init: tool({
15
- description: "Scaffold opencode-dev-framework project files (agents, skills, commands, default config) into the current project. Missing files are created; existing files are skipped unless overwrite is true.",
16
- args: {
17
- directory: tool.schema
18
- .string()
19
- .optional()
20
- .describe("Target project directory (defaults to current project)"),
21
- overwrite: tool.schema
22
- .boolean()
23
- .optional()
24
- .describe("Overwrite existing files that differ from templates"),
25
- },
26
- async execute(args, context) {
27
- const targetDir = args.directory ?? context.directory;
28
- const result = await installTemplates(targetDir, {
29
- overwriteExisting: args.overwrite ?? false,
30
- skipExisting: !(args.overwrite ?? false),
31
- });
32
- const configResult = await writeDetectedConfig(targetDir, {
33
- overwriteExisting: args.overwrite ?? false,
34
- skipExisting: !(args.overwrite ?? false),
35
- });
36
- const lines = [
37
- `Installed opencode-dev-framework templates into ${targetDir}.`,
38
- `Created: ${result.created.length} file(s)`,
39
- `Overwritten: ${result.overwritten.length} file(s)`,
40
- `Skipped: ${result.skipped.length} file(s)`,
41
- `Config: ${configResult.action}`,
42
- ];
43
- if (result.created.length > 0) {
44
- lines.push("", "Created files:", ...result.created.map((file) => `- ${file}`));
45
- }
46
- if (result.overwritten.length > 0) {
47
- lines.push("", "Overwritten files:", ...result.overwritten.map((file) => `- ${file}`));
48
- }
49
- return lines.join("\n");
50
- },
51
- }),
52
- dev_framework_set_profile: tool({
53
- description: "Change the opencode-dev-framework profile (off, advisory, standard, strict) for the current project and apply it immediately without restarting OpenCode.",
54
- args: {
55
- profile: tool.schema.string().describe("New profile: off, advisory, standard, or strict"),
56
- directory: tool.schema
57
- .string()
58
- .optional()
59
- .describe("Project directory (defaults to current project)"),
60
- },
61
- async execute(args, context) {
62
- const targetDir = args.directory ?? context.directory;
63
- const profile = args.profile.trim().toLowerCase();
64
- if (!isProfile(profile)) {
65
- return `Invalid profile "${args.profile}". Valid values: ${PROFILES.join(", ")}.`;
66
- }
67
- const message = await changeProfile(targetDir, profile);
68
- // Reload config and constitution so the change takes effect immediately.
69
- clearConfigCache();
70
- const config = loadConfig(targetDir);
71
- const { constitution } = await loadConstitution(config, targetDir);
72
- const state = getHookState(targetDir);
73
- if (state) {
74
- updateHookState(targetDir, { config, constitution });
75
- }
76
- return `${message} Change applied immediately.`;
77
- },
78
- }),
79
- dev_framework_status: tool({
80
- description: "Show the current opencode-dev-framework state for the project: active profile, guardrails, completion gate, on-edit behavior, tracked changed files, and block counts.",
81
- args: {
82
- directory: tool.schema
83
- .string()
84
- .optional()
85
- .describe("Project directory (defaults to current project)"),
86
- },
87
- async execute(args, context) {
88
- const targetDir = args.directory ?? context.directory;
89
- const state = getHookState(targetDir);
90
- const config = state?.config ?? loadConfig(targetDir);
91
- return renderStatus(config, state);
92
- },
93
- }),
94
- };
95
- }