opencode-dev-framework 0.1.6 → 0.1.8

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/README.md CHANGED
@@ -9,16 +9,24 @@ reimplemented as an OpenCode-native plugin.
9
9
 
10
10
  - **Constitution injection.** Adds a project constitution (quality bar, test
11
11
  discipline, focus rules) to the system prompt at session start. Ships with a
12
- bundled default; point `constitution` at your own Markdown file to override.
12
+ bundled default split into numbered rule files; point `constitution` at your
13
+ own Markdown file to override.
13
14
  - **Guardrails.** Blocks or warns on edits to protected paths (`.env` files,
14
15
  `node_modules`, vendored code, your own globs) and on dangerous shell
15
16
  commands (`git push`, `rm -rf`, `git reset --hard`, ...).
16
17
  - **Per-edit lint.** Runs your configured linter on each file the agent edits
17
18
  and reports failures loudly.
18
19
  - **Completion gate.** When the session goes idle, runs typecheck, tests, and
19
- (optionally) lint on changed files, then reports the result.
20
- - **`/df-verify` command.** Lets the agent (or you) re-run the verification
21
- suite on demand.
20
+ (optionally) lint on changed files. In OpenCode versions with the
21
+ `experimental.session.stopping` hook, gate failures keep the session running
22
+ (up to `gate.max_blocks` times) so the agent must fix the failures. In older
23
+ versions the gate reports loudly via `session.idle`.
24
+ - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
25
+ skills, commands, and config; `dev_framework_set_profile` changes the profile
26
+ in-session without restarting.
27
+ - **Slash-command templates.** `/df-verify` and `/df-profile` are installed
28
+ into `.opencode/commands/` by `df init` or the `dev_framework_init` tool.
29
+ (OpenCode does not load slash commands from plugin packages automatically.)
22
30
 
23
31
  ## Profiles
24
32
 
@@ -43,6 +51,20 @@ Then add it to your project's `opencode.json`:
43
51
  }
44
52
  ```
45
53
 
54
+ Finally, scaffold the project-level files (agents, skills, commands, default
55
+ config) into your repo with the bundled `df` CLI:
56
+
57
+ ```bash
58
+ npx df init # if installed locally as a project dependency
59
+ # or, after npm i -g opencode-dev-framework:
60
+ df init
61
+ ```
62
+
63
+ `df init` is interactive by default: it asks before overwriting existing files.
64
+ Use `--skip-existing` or `--overwrite-existing` for non-interactive runs.
65
+ `df status` shows what is and isn't scaffolded; `df version` prints the plugin
66
+ version.
67
+
46
68
  ## Local development and testing
47
69
 
48
70
  To test the plugin from source without publishing to npm, point OpenCode at the
@@ -110,12 +132,20 @@ compatibility, but the native format above is preferred. See
110
132
  config reference and [`examples/go-service/`](examples/go-service/) for a
111
133
  complete example.
112
134
 
135
+ ## Slash command
136
+
137
+ The `/df-verify` and `/df-profile` commands are installed by `df init` (or the
138
+ `dev_framework_init` tool) into `.opencode/commands/`. Inside an OpenCode
139
+ session, type `/df-verify` to ask the agent to run the configured verification
140
+ suite manually, or `/df-profile strict` to change the profile.
141
+
113
142
  ## Limitations
114
143
 
115
- - **The completion gate is advisory, not a hard block.** OpenCode has no
116
- `agentStop` hook, so the gate runs on `session.idle` and reports failures
117
- loudly (error-level log) but cannot physically prevent the agent from
118
- stopping. This is an architectural limitation of the plugin API.
144
+ - **The completion gate blocks only in newer OpenCode versions.** The
145
+ `experimental.session.stopping` hook (PR #41811) lets the plugin keep the
146
+ session running until checks pass. In older OpenCode versions the gate runs
147
+ on `session.idle` and reports failures loudly but cannot force the agent to
148
+ keep working.
119
149
  - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
120
150
  after OpenCode's own permission system; it adds project rules on top, it
121
151
  does not replace OpenCode permissions.
package/bin/df ADDED
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ // df — opencode-dev-framework CLI installer.
3
+ // Scaffold project-level agents, skills, commands, and config into a repo.
4
+
5
+ import { readFile } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { installTemplates, resolveTargetDir, statusTemplates } from "../dist/installer.js";
9
+
10
+ async function getVersion() {
11
+ const packagePath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
12
+ const pkg = JSON.parse(await readFile(packagePath, "utf8"));
13
+ return pkg.version ?? "unknown";
14
+ }
15
+
16
+ function printHelp() {
17
+ console.log(`df — opencode-dev-framework project installer
18
+
19
+ Usage:
20
+ df init [dir] Scaffold templates into a project (default: cwd)
21
+ df status [dir] Show which template files are missing/present/different
22
+ df version Print the plugin version
23
+ df help Show this help
24
+
25
+ Options:
26
+ --overwrite-existing Overwrite files that already exist (non-interactive)
27
+ --skip-existing Skip files that already exist (non-interactive)
28
+ `);
29
+ }
30
+
31
+ function formatList(label, files) {
32
+ if (files.length === 0) {
33
+ return [`${label}: (none)`];
34
+ }
35
+ return [`${label}:`, ...files.map((file) => ` - ${file}`)];
36
+ }
37
+
38
+ async function main() {
39
+ const args = process.argv.slice(2);
40
+ const command = args[0];
41
+
42
+ if (!command || command === "help" || command === "--help" || command === "-h") {
43
+ printHelp();
44
+ return;
45
+ }
46
+
47
+ if (command === "version" || command === "--version" || command === "-v") {
48
+ console.log(await getVersion());
49
+ return;
50
+ }
51
+
52
+ if (command !== "init" && command !== "status") {
53
+ console.error(`Unknown command: ${command}`);
54
+ printHelp();
55
+ process.exitCode = 1;
56
+ return;
57
+ }
58
+
59
+ const flags = new Set(args.slice(1).filter((arg) => arg.startsWith("--")));
60
+ const positional = args.slice(1).filter((arg) => !arg.startsWith("--"));
61
+ const targetDir = resolveTargetDir(positional[0]);
62
+
63
+ if (command === "status") {
64
+ const status = await statusTemplates(targetDir);
65
+ console.log(`Template status for ${targetDir}:`);
66
+ for (const line of [
67
+ ...formatList("Missing", status.missing),
68
+ ...formatList("Present", status.present),
69
+ ...formatList("Different", status.different),
70
+ ]) {
71
+ console.log(line);
72
+ }
73
+ return;
74
+ }
75
+
76
+ const result = await installTemplates(targetDir, {
77
+ overwriteExisting: flags.has("--overwrite-existing"),
78
+ skipExisting: flags.has("--skip-existing"),
79
+ });
80
+
81
+ console.log(`Installed templates into ${targetDir}:`);
82
+ for (const line of [
83
+ ...formatList("Created", result.created),
84
+ ...formatList("Overwritten", result.overwritten),
85
+ ...formatList("Skipped", result.skipped),
86
+ ]) {
87
+ console.log(line);
88
+ }
89
+ }
90
+
91
+ main().catch((error) => {
92
+ console.error(error instanceof Error ? error.message : String(error));
93
+ process.exitCode = 1;
94
+ });
package/dist/gate.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * Completion gate: run typecheck / test / lint-changed commands when the
3
- * session goes idle, plus the changed-file tracking that feeds it.
3
+ * session tries to stop, plus the changed-file tracking that feeds it.
4
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.
5
+ * The gate runs from two call sites:
6
+ * - `experimental.session.stopping` (OpenCode PR #41811): on failure, a
7
+ * synthetic user message keeps the session running, up to `gate.max_blocks`.
8
+ * - `session.idle` (fallback on older OpenCode): advisory logging only — by
9
+ * then the agent's turn has already finished, so failures cannot block.
8
10
  */
9
11
  import type { CommandResult, RunCommand } from "./host.js";
10
12
  import type { ResolvedConfig } from "./types.js";
package/dist/gate.js CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * Completion gate: run typecheck / test / lint-changed commands when the
3
- * session goes idle, plus the changed-file tracking that feeds it.
3
+ * session tries to stop, plus the changed-file tracking that feeds it.
4
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.
5
+ * The gate runs from two call sites:
6
+ * - `experimental.session.stopping` (OpenCode PR #41811): on failure, a
7
+ * synthetic user message keeps the session running, up to `gate.max_blocks`.
8
+ * - `session.idle` (fallback on older OpenCode): advisory logging only — by
9
+ * then the agent's turn has already finished, so failures cannot block.
8
10
  */
9
11
  import { isAbsolute, relative } from "node:path";
10
12
  import { splitCommand } from "./config-to-opencode.js";
package/dist/index.d.ts CHANGED
@@ -4,8 +4,10 @@
4
4
  * Wired so far:
5
5
  * - tool.execute.before -> protected-path / dangerous-command guardrails
6
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
7
+ * - event (session.idle) -> completion gate fallback (advisory logging)
8
+ * - experimental.chat.system.transform -> constitution injection + session mapping
9
+ * - experimental.session.stopping -> blocking completion gate (OpenCode >= PR #41811)
10
+ * - tool -> dev_framework_init / dev_framework_set_profile custom tools
9
11
  */
10
12
  import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
11
13
  import { type ChangedFileTracker } from "./gate.js";
@@ -13,9 +15,22 @@ import { type RunCommand } from "./host.js";
13
15
  import { type LogFn } from "./logger.js";
14
16
  import type { ResolvedConfig } from "./types.js";
15
17
  /**
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
+ * The `experimental.session.stopping` hook was added in OpenCode PR #41811
19
+ * and is not yet in the published `@opencode-ai/plugin` types. We define it
20
+ * locally so the plugin compiles and automatically uses the hook when the
21
+ * runtime supports it.
18
22
  */
19
- export declare function buildHooks(ctx: PluginInput, config: ResolvedConfig, log: LogFn, run?: RunCommand, tracker?: ChangedFileTracker, constitution?: string | null): Hooks;
23
+ export interface HooksWithStopping extends Hooks {
24
+ "experimental.session.stopping"?: (input: {
25
+ sessionID: string;
26
+ }, output: {
27
+ context: string[];
28
+ }) => Promise<void>;
29
+ }
30
+ /**
31
+ * Build the plugin's hooks and custom tools. Exported (rather than inlined in
32
+ * the plugin) so tests can inject a stubbed command runner and tracker.
33
+ */
34
+ export declare function buildHooks(ctx: PluginInput, config: ResolvedConfig, log: LogFn, run?: RunCommand, tracker?: ChangedFileTracker, constitution?: string | null): HooksWithStopping;
20
35
  export declare const devFramework: Plugin;
21
36
  export default devFramework;
package/dist/index.js CHANGED
@@ -4,8 +4,10 @@
4
4
  * Wired so far:
5
5
  * - tool.execute.before -> protected-path / dangerous-command guardrails
6
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
7
+ * - event (session.idle) -> completion gate fallback (advisory logging)
8
+ * - experimental.chat.system.transform -> constitution injection + session mapping
9
+ * - experimental.session.stopping -> blocking completion gate (OpenCode >= PR #41811)
10
+ * - tool -> dev_framework_init / dev_framework_set_profile custom tools
9
11
  */
10
12
  import { loadConfig } from "./config.js";
11
13
  import { createChangedFileTracker, runGate, summarizeGate, } from "./gate.js";
@@ -13,35 +15,37 @@ import { runCommand } from "./host.js";
13
15
  import { isLintFailure, lintFile, summarizeLint } from "./lint.js";
14
16
  import { createLogger } from "./logger.js";
15
17
  import { checkToolCall } from "./protect.js";
18
+ import { clearSessionDirectory, getDirectoryForSession, getHookState, setHookState, setSessionDirectory, } from "./registry.js";
16
19
  import { injectConstitution, loadConstitution } from "./rules.js";
20
+ import { buildTools } from "./tools.js";
17
21
  /**
18
- * Per-directory hook state registry. OpenCode's effect runtime can strip
19
- * closure variables when invoking hooks asynchronously, so we store the state
20
- * in module-level maps and look it up at call time.
21
- */
22
- const hookRegistry = new Map();
23
- let activeDirectory = null;
24
- function getHookState(directoryHint) {
25
- const directory = directoryHint ?? activeDirectory;
26
- if (!directory) {
27
- return null;
28
- }
29
- return hookRegistry.get(directory) ?? null;
30
- }
31
- /**
32
- * Build the plugin's hooks. Exported (rather than inlined in the plugin) so
33
- * tests can inject a stubbed command runner and tracker.
22
+ * Build the plugin's hooks and custom tools. Exported (rather than inlined in
23
+ * the plugin) so tests can inject a stubbed command runner and tracker.
34
24
  */
35
25
  export function buildHooks(ctx, config, log, run = runCommand, tracker = createChangedFileTracker(), constitution = null) {
36
- const directory = ctx.directory;
37
- hookRegistry.set(directory, { config, log, run, tracker, constitution });
38
- activeDirectory = directory;
26
+ // All hook state — including the project directory — lives in the registry
27
+ // and is looked up at call time. OpenCode's Effect runtime stripped closure
28
+ // captures in production (config/log/run came back undefined), so hooks must
29
+ // not rely on variables from this scope.
30
+ setHookState(ctx.directory, {
31
+ directory: ctx.directory,
32
+ config,
33
+ log,
34
+ run,
35
+ tracker,
36
+ constitution,
37
+ blockCounts: new Map(),
38
+ });
39
39
  return {
40
- "experimental.chat.system.transform": async (_input, output) => {
40
+ tool: buildTools(ctx),
41
+ "experimental.chat.system.transform": async (input, output) => {
41
42
  const state = getHookState();
42
43
  if (!state) {
43
44
  return;
44
45
  }
46
+ if (input.sessionID) {
47
+ setSessionDirectory(input.sessionID, state.directory);
48
+ }
45
49
  const next = injectConstitution(output.system, state.constitution);
46
50
  if (next !== output.system) {
47
51
  await state.log("info", "constitution injected into system prompt");
@@ -53,7 +57,7 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
53
57
  if (!state) {
54
58
  return;
55
59
  }
56
- const result = checkToolCall(state.config, input.tool, output.args, activeDirectory ?? undefined);
60
+ const result = checkToolCall(state.config, input.tool, output.args, state.directory);
57
61
  if (result.decision === "allow") {
58
62
  return;
59
63
  }
@@ -70,19 +74,55 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
70
74
  await state.log("error", message, extra);
71
75
  throw new Error(`[opencode-dev-framework] ${message}`);
72
76
  },
77
+ "experimental.session.stopping": async (input, output) => {
78
+ const state = getHookState(getDirectoryForSession(input.sessionID) ?? undefined);
79
+ if (!state?.config.gate || state.config.profile === "off") {
80
+ return;
81
+ }
82
+ const changedFiles = state.tracker.getChangedFiles();
83
+ const report = await runGate(state.run, state.config, changedFiles, { cwd: state.directory });
84
+ if (!report.ran || report.ok) {
85
+ state.tracker.clearChangedFiles();
86
+ state.blockCounts.delete(input.sessionID);
87
+ return;
88
+ }
89
+ const maxBlocks = state.config.gate.max_blocks ?? 3;
90
+ const blockCount = (state.blockCounts.get(input.sessionID) ?? 0) + 1;
91
+ state.blockCounts.set(input.sessionID, blockCount);
92
+ if (blockCount > maxBlocks) {
93
+ // Standing down: clear the tracker so the session.idle fallback does
94
+ // not re-run the same failing gate commands a second time.
95
+ state.tracker.clearChangedFiles();
96
+ await state.log("warn", `completion gate has blocked ${maxBlocks} times; standing down but checks are still failing`, { failedSteps: report.failedSteps.map((step) => step.name) });
97
+ return;
98
+ }
99
+ const summary = summarizeGate(report);
100
+ await state.log("error", summary, {
101
+ failedSteps: report.failedSteps.map((step) => step.name),
102
+ });
103
+ output.context.push(`opencode-dev-framework completion gate blocked you from finishing (block ${blockCount}/${maxBlocks}). ` +
104
+ `The following checks failed:\n\n${summary}\n\n` +
105
+ `Fix the underlying cause and continue. Do NOT disable, skip, or weaken these checks to make them pass.`);
106
+ },
73
107
  event: async ({ event }) => {
108
+ // session.deleted must run even without hook state so the session map
109
+ // does not grow unboundedly.
110
+ if (event.type === "session.deleted") {
111
+ clearSessionDirectory(event.properties.info.id);
112
+ return;
113
+ }
74
114
  const state = getHookState();
75
115
  if (!state) {
76
116
  return;
77
117
  }
78
118
  if (event.type === "file.edited") {
79
119
  const filePath = event.properties.file;
80
- state.tracker.add(filePath, activeDirectory ?? undefined);
120
+ state.tracker.add(filePath, state.directory);
81
121
  if (!state.config.on_edit.lint) {
82
122
  return;
83
123
  }
84
124
  const outcome = await lintFile(state.run, state.config, filePath, {
85
- cwd: activeDirectory ?? undefined,
125
+ cwd: state.directory,
86
126
  timeout: state.config.gate?.timeout,
87
127
  });
88
128
  if (outcome.skipped) {
@@ -109,15 +149,16 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
109
149
  return;
110
150
  }
111
151
  if (event.type === "session.idle") {
152
+ if (state.config.profile === "off") {
153
+ return;
154
+ }
112
155
  if (!state.config.gate) {
113
- await state.log("warn", "plugin config is incomplete (missing gate section), skipping completion gate", {
114
- directory: activeDirectory ?? undefined,
115
- });
156
+ await state.log("warn", "plugin config is incomplete (missing gate section), skipping completion gate", { directory: state.directory });
116
157
  return;
117
158
  }
118
159
  const changedFiles = state.tracker.getChangedFiles();
119
160
  const report = await runGate(state.run, state.config, changedFiles, {
120
- cwd: activeDirectory ?? undefined,
161
+ cwd: state.directory,
121
162
  });
122
163
  state.tracker.clearChangedFiles();
123
164
  const summary = summarizeGate(report);
@@ -129,8 +170,8 @@ export function buildHooks(ctx, config, log, run = runCommand, tracker = createC
129
170
  await state.log("info", summary);
130
171
  return;
131
172
  }
132
- // The gate cannot physically block (session.idle fires after the turn
133
- // ends), so failure visibility is the enforcement mechanism.
173
+ // The gate cannot physically block on session.idle (the turn already
174
+ // ended), so failure visibility is the enforcement mechanism.
134
175
  const level = state.config.gate.block_on_failure ? "error" : "warn";
135
176
  await state.log(level, summary, {
136
177
  failedSteps: report.failedSteps.map((step) => ({
@@ -0,0 +1,35 @@
1
+ /** Directory containing the project templates shipped with the package. */
2
+ export declare const TEMPLATES_DIR: string;
3
+ export type OverwriteDecision = "overwrite" | "skip" | "overwrite-all" | "skip-all";
4
+ export type PromptFn = (relativePath: string) => Promise<OverwriteDecision>;
5
+ export interface InstallOptions {
6
+ /** How to handle files that already exist with different content. */
7
+ overwriteExisting?: boolean;
8
+ /** Non-interactive mode: never prompt. Defaults to skip when false. */
9
+ skipExisting?: boolean;
10
+ /** Custom prompt function for interactive installs. */
11
+ prompt?: PromptFn;
12
+ }
13
+ export interface InstallResult {
14
+ created: string[];
15
+ skipped: string[];
16
+ overwritten: string[];
17
+ }
18
+ export interface TemplateStatus {
19
+ missing: string[];
20
+ present: string[];
21
+ different: string[];
22
+ }
23
+ /** List all template files relative to TEMPLATES_DIR. */
24
+ export declare function listTemplateFiles(): Promise<string[]>;
25
+ /**
26
+ * Install all bundled templates into a target project directory.
27
+ * Returns lists of created, skipped, and overwritten files (relative paths).
28
+ */
29
+ export declare function installTemplates(targetDir: string, options?: InstallOptions): Promise<InstallResult>;
30
+ /**
31
+ * Compare the target project against the bundled templates.
32
+ */
33
+ export declare function statusTemplates(targetDir: string): Promise<TemplateStatus>;
34
+ /** Resolve a user-supplied directory (default cwd) to an absolute path. */
35
+ export declare function resolveTargetDir(dir?: string): string;
@@ -0,0 +1,155 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createInterface } from "node:readline";
5
+ /** Directory containing the project templates shipped with the package. */
6
+ export const TEMPLATES_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "templates");
7
+ /** List all template files relative to TEMPLATES_DIR. */
8
+ export async function listTemplateFiles() {
9
+ const files = [];
10
+ async function walk(dir, prefix) {
11
+ const entries = await fs.readdir(dir, { withFileTypes: true });
12
+ for (const entry of entries) {
13
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
14
+ if (entry.isDirectory()) {
15
+ await walk(join(dir, entry.name), relative);
16
+ }
17
+ else if (entry.isFile()) {
18
+ files.push(relative);
19
+ }
20
+ }
21
+ }
22
+ await walk(TEMPLATES_DIR, "");
23
+ return files.sort();
24
+ }
25
+ async function fileExists(path) {
26
+ try {
27
+ await fs.access(path);
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ async function readFileSafe(path) {
35
+ try {
36
+ return await fs.readFile(path, "utf8");
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ async function defaultPrompt(relativePath) {
43
+ if (!process.stdin.isTTY) {
44
+ return "skip";
45
+ }
46
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
47
+ try {
48
+ const answer = await new Promise((resolve) => {
49
+ rl.question(`File exists with different content: ${relativePath}\nOverwrite? [o]verwrite / [s]kip / [a]ll / [n]one: `, resolve);
50
+ });
51
+ const normalized = answer.trim().toLowerCase();
52
+ if (normalized === "o" || normalized === "overwrite") {
53
+ return "overwrite";
54
+ }
55
+ if (normalized === "s" || normalized === "skip") {
56
+ return "skip";
57
+ }
58
+ if (normalized === "a" || normalized === "all") {
59
+ return "overwrite-all";
60
+ }
61
+ if (normalized === "n" || normalized === "none") {
62
+ return "skip-all";
63
+ }
64
+ return "skip";
65
+ }
66
+ finally {
67
+ rl.close();
68
+ }
69
+ }
70
+ /**
71
+ * Install all bundled templates into a target project directory.
72
+ * Returns lists of created, skipped, and overwritten files (relative paths).
73
+ */
74
+ export async function installTemplates(targetDir, options = {}) {
75
+ const result = { created: [], skipped: [], overwritten: [] };
76
+ const files = await listTemplateFiles();
77
+ const prompt = options.prompt ?? defaultPrompt;
78
+ /** Sticky decision set when the user answers "all" or "none". */
79
+ let stickyDecision = null;
80
+ for (const relative of files) {
81
+ const source = join(TEMPLATES_DIR, relative);
82
+ const destination = join(targetDir, relative);
83
+ const sourceContent = await readFileSafe(source);
84
+ if (sourceContent === null) {
85
+ continue;
86
+ }
87
+ if (!(await fileExists(destination))) {
88
+ await fs.mkdir(dirname(destination), { recursive: true });
89
+ await fs.writeFile(destination, sourceContent, "utf8");
90
+ result.created.push(relative);
91
+ continue;
92
+ }
93
+ const existing = await readFileSafe(destination);
94
+ if (existing === sourceContent) {
95
+ result.skipped.push(relative);
96
+ continue;
97
+ }
98
+ let decision;
99
+ if (stickyDecision !== null) {
100
+ decision = stickyDecision;
101
+ }
102
+ else if (options.skipExisting) {
103
+ decision = "skip";
104
+ }
105
+ else if (options.overwriteExisting) {
106
+ decision = "overwrite";
107
+ }
108
+ else {
109
+ decision = await prompt(relative);
110
+ }
111
+ if (decision === "overwrite-all") {
112
+ stickyDecision = "overwrite";
113
+ decision = "overwrite";
114
+ }
115
+ else if (decision === "skip-all") {
116
+ stickyDecision = "skip";
117
+ decision = "skip";
118
+ }
119
+ if (decision === "overwrite") {
120
+ await fs.writeFile(destination, sourceContent, "utf8");
121
+ result.overwritten.push(relative);
122
+ }
123
+ else {
124
+ result.skipped.push(relative);
125
+ }
126
+ }
127
+ return result;
128
+ }
129
+ /**
130
+ * Compare the target project against the bundled templates.
131
+ */
132
+ export async function statusTemplates(targetDir) {
133
+ const files = await listTemplateFiles();
134
+ const status = { missing: [], present: [], different: [] };
135
+ for (const relative of files) {
136
+ const source = join(TEMPLATES_DIR, relative);
137
+ const destination = join(targetDir, relative);
138
+ const sourceContent = await readFileSafe(source);
139
+ const existing = await readFileSafe(destination);
140
+ if (existing === null) {
141
+ status.missing.push(relative);
142
+ }
143
+ else if (existing === sourceContent) {
144
+ status.present.push(relative);
145
+ }
146
+ else {
147
+ status.different.push(relative);
148
+ }
149
+ }
150
+ return status;
151
+ }
152
+ /** Resolve a user-supplied directory (default cwd) to an absolute path. */
153
+ export function resolveTargetDir(dir) {
154
+ return resolve(dir ?? process.cwd());
155
+ }
package/dist/logger.d.ts CHANGED
@@ -6,7 +6,9 @@ export type LogLevel = "debug" | "info" | "warn" | "error";
6
6
  export declare const LOG_SERVICE = "opencode-dev-framework";
7
7
  export type LogFn = (level: LogLevel, message: string, extra?: Record<string, unknown>) => Promise<void>;
8
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.
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.
11
13
  */
12
14
  export declare function createLogger(client: PluginInput["client"]): LogFn;
package/dist/logger.js CHANGED
@@ -3,16 +3,23 @@
3
3
  */
4
4
  export const LOG_SERVICE = "opencode-dev-framework";
5
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.
6
+ * Create a logger bound to the OpenCode client. Logging never throws:
7
+ * `app.log` failures fall back to stderr so the failure stays visible
8
+ * (a total swallow made production debugging painful during development),
9
+ * and even stderr failures are ignored as a last resort.
8
10
  */
9
11
  export function createLogger(client) {
10
12
  return async (level, message, extra) => {
11
13
  try {
12
14
  await client.app.log({ body: { service: LOG_SERVICE, level, message, extra } });
13
15
  }
14
- catch {
15
- // Intentionally ignored: logging is best-effort.
16
+ catch (error) {
17
+ try {
18
+ process.stderr.write(`[${LOG_SERVICE}] ${level} ${message} (app.log failed: ${String(error)})\n`);
19
+ }
20
+ catch {
21
+ // Even stderr may be unavailable; truly ignore.
22
+ }
16
23
  }
17
24
  };
18
25
  }