opencode-dev-framework 0.1.6 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +64 -13
  2. package/bin/df +129 -0
  3. package/dist/config.js +16 -11
  4. package/dist/detect.d.ts +26 -0
  5. package/dist/detect.js +183 -0
  6. package/dist/gate.d.ts +6 -4
  7. package/dist/gate.js +6 -4
  8. package/dist/index.d.ts +20 -5
  9. package/dist/index.js +81 -34
  10. package/dist/installer.d.ts +50 -0
  11. package/dist/installer.js +287 -0
  12. package/dist/lint.d.ts +6 -0
  13. package/dist/lint.js +14 -1
  14. package/dist/logger.d.ts +4 -2
  15. package/dist/logger.js +11 -4
  16. package/dist/registry.d.ts +25 -0
  17. package/dist/registry.js +40 -0
  18. package/dist/rules.d.ts +24 -10
  19. package/dist/rules.js +140 -33
  20. package/dist/tools.d.ts +3 -0
  21. package/dist/tools.js +80 -0
  22. package/dist/types.d.ts +12 -5
  23. package/package.json +7 -3
  24. package/rules/00-activation.md +36 -0
  25. package/rules/10-quality-bar.md +34 -0
  26. package/rules/20-match-existing-patterns.md +41 -0
  27. package/rules/30-testing-discipline.md +41 -0
  28. package/rules/40-delegation.md +50 -0
  29. package/templates/.opencode/agents/pattern-guardian.md +78 -0
  30. package/templates/.opencode/agents/style-enforcer.md +75 -0
  31. package/templates/.opencode/agents/test-grounder.md +71 -0
  32. package/templates/.opencode/commands/df-profile.md +7 -0
  33. package/templates/.opencode/commands/df-verify.md +8 -0
  34. package/templates/.opencode/opencode-dev-framework/rules/.gitkeep +0 -0
  35. package/templates/.opencode/skills/ground-in-tests/SKILL.md +53 -0
  36. package/templates/.opencode/skills/match-patterns/SKILL.md +60 -0
  37. package/templates/.opencode/skills/peer-review/SKILL.md +56 -0
  38. package/commands/df-verify.md +0 -5
  39. package/rules/constitution.md +0 -23
package/README.md CHANGED
@@ -9,16 +9,29 @@ 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. Override it by dropping files
13
+ in `.opencode/opencode-dev-framework/rules/`, by setting explicit `rules`, or
14
+ by letting the plugin auto-discover `STYLE.md` / `CONTRIBUTING.md`.
13
15
  - **Guardrails.** Blocks or warns on edits to protected paths (`.env` files,
14
16
  `node_modules`, vendored code, your own globs) and on dangerous shell
15
17
  commands (`git push`, `rm -rf`, `git reset --hard`, ...).
16
18
  - **Per-edit lint.** Runs your configured linter on each file the agent edits
17
- and reports failures loudly.
19
+ and reports failures loudly. Optionally delegates per-file linting to
20
+ `pre-commit run --files` when `precommit: auto` is set.
18
21
  - **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.
22
+ (optionally) lint on changed files. In OpenCode versions with the
23
+ `experimental.session.stopping` hook, gate failures keep the session running
24
+ (up to `gate.max_blocks` times) so the agent must fix the failures. In older
25
+ versions the gate reports loudly via `session.idle`.
26
+ - **Custom tools.** `dev_framework_init` scaffolds project-level agents,
27
+ skills, commands, and config; `dev_framework_set_profile` changes the profile
28
+ in-session without restarting.
29
+ - **CLI installer.** `df init` auto-detects your language and writes a config
30
+ with sensible commands; `df profile <name>` changes the profile from the
31
+ shell; `df status` / `df version` report template state and the version.
32
+ - **Slash-command templates.** `/df-verify` and `/df-profile` are installed
33
+ into `.opencode/commands/` by `df init` or the `dev_framework_init` tool.
34
+ (OpenCode does not load slash commands from plugin packages automatically.)
22
35
 
23
36
  ## Profiles
24
37
 
@@ -43,6 +56,22 @@ Then add it to your project's `opencode.json`:
43
56
  }
44
57
  ```
45
58
 
59
+ Finally, scaffold the project-level files (agents, skills, commands, default
60
+ config) into your repo with the bundled `df` CLI:
61
+
62
+ ```bash
63
+ npx df init # if installed locally as a project dependency
64
+ # or, after npm i -g opencode-dev-framework:
65
+ df init
66
+ ```
67
+
68
+ `df init` is interactive by default: it asks before overwriting existing files.
69
+ Use `--skip-existing` or `--overwrite-existing` for non-interactive runs.
70
+ `df init` auto-detects your project's language and writes a matching
71
+ `.opencode-dev-framework.yml` with sensible commands. `df status` shows what is
72
+ and isn't scaffolded; `df profile off|advisory|standard|strict` changes the
73
+ profile from the shell; `df version` prints the plugin version.
74
+
46
75
  ## Local development and testing
47
76
 
48
77
  To test the plugin from source without publishing to npm, point OpenCode at the
@@ -78,7 +107,9 @@ npm run build
78
107
 
79
108
  ## Configuration
80
109
 
81
- Create `.opencode-dev-framework.yml` in your project root:
110
+ Create `.opencode-dev-framework.yml` in your project root. The easiest way to
111
+ override the bundled constitution is to run `df init` and then add Markdown
112
+ files to `.opencode/opencode-dev-framework/rules/`.
82
113
 
83
114
  ```yaml
84
115
  profile: standard
@@ -101,7 +132,16 @@ gate:
101
132
  on_edit:
102
133
  lint: true
103
134
 
104
- constitution: "TEAM_RULES.md" # optional; bundled default if omitted
135
+ # Optional: delegate per-file linting to pre-commit when available
136
+ # precommit: auto
137
+
138
+ # Optional: explicit rule files (replace bundled; use mode: append to extend)
139
+ # rules:
140
+ # - docs/team-rules.md
141
+
142
+ # Optional: project style guide appended to the constitution.
143
+ # Auto-discovers STYLE.md / CONTRIBUTING.md / docs/STYLE.md when not set.
144
+ # style_guide: STYLE.md
105
145
  ```
106
146
 
107
147
  The legacy `.dev-framework.yml` flat-key format is read as a fallback for
@@ -110,17 +150,28 @@ compatibility, but the native format above is preferred. See
110
150
  config reference and [`examples/go-service/`](examples/go-service/) for a
111
151
  complete example.
112
152
 
153
+ ## Slash command
154
+
155
+ The `/df-verify` and `/df-profile` commands are installed by `df init` (or the
156
+ `dev_framework_init` tool) into `.opencode/commands/`. Inside an OpenCode
157
+ session, type `/df-verify` to ask the agent to run the configured verification
158
+ suite manually, or `/df-profile strict` to change the profile.
159
+
113
160
  ## Limitations
114
161
 
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.
162
+ - **The completion gate blocks only in newer OpenCode versions.** The
163
+ `experimental.session.stopping` hook (PR #41811) lets the plugin keep the
164
+ session running until checks pass. In older OpenCode versions the gate runs
165
+ on `session.idle` and reports failures loudly but cannot force the agent to
166
+ keep working.
119
167
  - **Guardrails run inside OpenCode.** The `tool.execute.before` hook runs
120
168
  after OpenCode's own permission system; it adds project rules on top, it
121
169
  does not replace OpenCode permissions.
122
- - **Formatting is delegated.** Formatter config is contributed to OpenCode's
123
- native formatter system rather than reimplemented.
170
+ - **Formatting and linting are delegated.** The plugin does not reimplement
171
+ formatters or linters; you declare your formatter and linter commands in
172
+ `.opencode-dev-framework.yml` and the plugin runs them on edited files and
173
+ at the completion gate. It does not automatically rewrite `opencode.json`
174
+ formatter/permission fragments.
124
175
 
125
176
  ## Development
126
177
 
package/bin/df ADDED
@@ -0,0 +1,129 @@
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 {
9
+ installTemplates,
10
+ resolveTargetDir,
11
+ setProfileInFile,
12
+ statusTemplates,
13
+ writeDetectedConfig,
14
+ } from "../dist/installer.js";
15
+
16
+ async function getVersion() {
17
+ const packagePath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
18
+ const pkg = JSON.parse(await readFile(packagePath, "utf8"));
19
+ return pkg.version ?? "unknown";
20
+ }
21
+
22
+ function printHelp() {
23
+ console.log(`df — opencode-dev-framework project installer
24
+
25
+ Usage:
26
+ df init [dir] Scaffold templates into a project (default: cwd)
27
+ df profile <name> [dir] Set profile to off, advisory, standard, or strict
28
+ df status [dir] Show which template files are missing/present/different
29
+ df version Print the plugin version
30
+ df help Show this help
31
+
32
+ Options:
33
+ --overwrite-existing Overwrite files that already exist (non-interactive)
34
+ --skip-existing Skip files that already exist (non-interactive)
35
+ `);
36
+ }
37
+
38
+ function formatList(label, files) {
39
+ if (files.length === 0) {
40
+ return [`${label}: (none)`];
41
+ }
42
+ return [`${label}:`, ...files.map((file) => ` - ${file}`)];
43
+ }
44
+
45
+ async function main() {
46
+ const args = process.argv.slice(2);
47
+ const command = args[0];
48
+
49
+ if (!command || command === "help" || command === "--help" || command === "-h") {
50
+ printHelp();
51
+ return;
52
+ }
53
+
54
+ if (command === "version" || command === "--version" || command === "-v") {
55
+ console.log(await getVersion());
56
+ return;
57
+ }
58
+
59
+ if (command === "profile") {
60
+ const profile = positional[0];
61
+ const profileDir = resolveTargetDir(positional[1]);
62
+ const valid = ["off", "advisory", "standard", "strict"];
63
+ if (!profile || !valid.includes(profile)) {
64
+ console.error(`Invalid profile: ${profile ?? "(missing)"}`);
65
+ console.error(`Valid profiles: ${valid.join(", ")}`);
66
+ process.exitCode = 1;
67
+ return;
68
+ }
69
+ const configPath = join(profileDir, ".opencode-dev-framework.yml");
70
+ await setProfileInFile(configPath, profile);
71
+ console.log(`Profile set to "${profile}" in ${configPath}`);
72
+ return;
73
+ }
74
+
75
+ if (command !== "init" && command !== "status") {
76
+ console.error(`Unknown command: ${command}`);
77
+ printHelp();
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+
82
+ const flags = new Set(args.slice(1).filter((arg) => arg.startsWith("--")));
83
+ const positional = args.slice(1).filter((arg) => !arg.startsWith("--"));
84
+ const targetDir = resolveTargetDir(positional[0]);
85
+
86
+ if (command === "init" && flags.has("--skip-existing") && flags.has("--overwrite-existing")) {
87
+ console.error("Cannot use both --skip-existing and --overwrite-existing");
88
+ process.exitCode = 1;
89
+ return;
90
+ }
91
+
92
+ if (command === "status") {
93
+ const status = await statusTemplates(targetDir);
94
+ console.log(`Template status for ${targetDir}:`);
95
+ for (const line of [
96
+ ...formatList("Missing", status.missing),
97
+ ...formatList("Present", status.present),
98
+ ...formatList("Different", status.different),
99
+ ]) {
100
+ console.log(line);
101
+ }
102
+ return;
103
+ }
104
+
105
+ const result = await installTemplates(targetDir, {
106
+ overwriteExisting: flags.has("--overwrite-existing"),
107
+ skipExisting: flags.has("--skip-existing"),
108
+ });
109
+
110
+ const configResult = await writeDetectedConfig(targetDir, {
111
+ overwriteExisting: flags.has("--overwrite-existing"),
112
+ skipExisting: flags.has("--skip-existing"),
113
+ });
114
+
115
+ console.log(`Installed templates into ${targetDir}:`);
116
+ for (const line of [
117
+ ...formatList("Created", result.created),
118
+ ...formatList("Overwritten", result.overwritten),
119
+ ...formatList("Skipped", result.skipped),
120
+ ]) {
121
+ console.log(line);
122
+ }
123
+ console.log(`\nConfig: ${configResult.action}`);
124
+ }
125
+
126
+ main().catch((error) => {
127
+ console.error(error instanceof Error ? error.message : String(error));
128
+ process.exitCode = 1;
129
+ });
package/dist/config.js CHANGED
@@ -60,9 +60,17 @@ const configSchema = z.object({
60
60
  })
61
61
  .optional(),
62
62
  exclude: z.array(z.string()).optional(),
63
- constitution: z.string().optional(),
64
- rules: z.array(z.string()).optional(),
63
+ rules: z
64
+ .union([
65
+ z.array(z.string()),
66
+ z.object({
67
+ mode: z.enum(["replace", "append"]),
68
+ files: z.array(z.string()),
69
+ }),
70
+ ])
71
+ .optional(),
65
72
  style_guide: z.string().optional(),
73
+ precommit: z.enum(["auto", "off"]).optional(),
66
74
  });
67
75
  /** Find the highest-precedence config file in a directory, if any. */
68
76
  export function findConfigFile(directory) {
@@ -164,9 +172,6 @@ export function mapFlatConfig(flat) {
164
172
  case "test_changed":
165
173
  commands.test_changed = String(value);
166
174
  break;
167
- case "precommit":
168
- // Ignored in MVP.
169
- break;
170
175
  case "format_on_edit":
171
176
  onEdit.format = toBoolean(value);
172
177
  break;
@@ -209,15 +214,15 @@ export function mapFlatConfig(flat) {
209
214
  case "exclude":
210
215
  config.exclude = splitGlobs(value);
211
216
  break;
212
- case "constitution":
213
- config.constitution = String(value);
214
- break;
215
217
  case "rules":
216
- config.rules = splitGlobs(value);
218
+ config.rules = { mode: "replace", files: splitGlobs(value) };
217
219
  break;
218
220
  case "style_guide":
219
221
  config.style_guide = String(value);
220
222
  break;
223
+ case "precommit":
224
+ config.precommit = value === "auto" || value === true ? "auto" : "off";
225
+ break;
221
226
  default:
222
227
  // Unknown flat keys are ignored for forward compatibility.
223
228
  break;
@@ -278,9 +283,9 @@ export function resolveConfig(raw, configPath) {
278
283
  lint: raw.on_edit?.lint ?? defaults.on_edit_lint,
279
284
  },
280
285
  exclude: raw.exclude ?? [],
281
- constitution: raw.constitution,
282
- rules: raw.rules,
286
+ rules: Array.isArray(raw.rules) ? { mode: "replace", files: raw.rules } : raw.rules,
283
287
  style_guide: raw.style_guide,
288
+ precommit: raw.precommit ?? "off",
284
289
  };
285
290
  }
286
291
  function validateConfig(data, configPath) {
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Project auto-detection for `df init`.
3
+ *
4
+ * Detects the dominant language, test/typecheck/format/lint commands, and
5
+ * pre-commit availability by inspecting files in the project root. All
6
+ * detection is synchronous and side-effect free; callers decide what to do
7
+ * with the result.
8
+ */
9
+ import type { CommandsConfig } from "./types.js";
10
+ export interface DetectionResult {
11
+ /** Dominant language or framework detected from root files. */
12
+ language: string | null;
13
+ /** Suggested commands config for the project. */
14
+ commands: CommandsConfig;
15
+ /** True when a `.pre-commit-config.yaml` file is present. */
16
+ hasPreCommitConfig: boolean;
17
+ }
18
+ /**
19
+ * Detect project tooling by scanning the directory root.
20
+ */
21
+ export declare function detectProject(directory: string): DetectionResult;
22
+ /**
23
+ * Build a YAML config string from a detection result. Only includes keys that
24
+ * have a detected value.
25
+ */
26
+ export declare function detectedConfigYaml(language: string | null, commands: CommandsConfig): string;
package/dist/detect.js ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Project auto-detection for `df init`.
3
+ *
4
+ * Detects the dominant language, test/typecheck/format/lint commands, and
5
+ * pre-commit availability by inspecting files in the project root. All
6
+ * detection is synchronous and side-effect free; callers decide what to do
7
+ * with the result.
8
+ */
9
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ function fileExists(path) {
12
+ try {
13
+ return existsSync(path);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ function readJsonSafe(path) {
20
+ try {
21
+ return JSON.parse(readFileSync(path, "utf8"));
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ function hasAny(files, names) {
28
+ return names.some((name) => files.includes(name));
29
+ }
30
+ /**
31
+ * Detect project tooling by scanning the directory root.
32
+ */
33
+ export function detectProject(directory) {
34
+ const files = readdirSync(directory);
35
+ const has = {
36
+ packageJson: fileExists(join(directory, "package.json")),
37
+ goMod: fileExists(join(directory, "go.mod")),
38
+ cargoToml: fileExists(join(directory, "Cargo.toml")),
39
+ pyProject: fileExists(join(directory, "pyproject.toml")),
40
+ requirements: fileExists(join(directory, "requirements.txt")),
41
+ gemfile: fileExists(join(directory, "Gemfile")),
42
+ composerJson: fileExists(join(directory, "composer.json")),
43
+ pomXml: fileExists(join(directory, "pom.xml")),
44
+ gradle: hasAny(files, ["build.gradle", "build.gradle.kts"]),
45
+ mavenWrapper: fileExists(join(directory, "mvnw")),
46
+ gradleWrapper: fileExists(join(directory, "gradlew")),
47
+ tsConfig: fileExists(join(directory, "tsconfig.json")),
48
+ };
49
+ const result = {
50
+ language: null,
51
+ commands: {},
52
+ hasPreCommitConfig: fileExists(join(directory, ".pre-commit-config.yaml")),
53
+ };
54
+ if (has.packageJson) {
55
+ result.language = "node";
56
+ const pkg = readJsonSafe(join(directory, "package.json"));
57
+ const scripts = pkg?.scripts ?? {};
58
+ if (typeof scripts.test === "string") {
59
+ result.commands.test = "npm test";
60
+ }
61
+ if (has.tsConfig) {
62
+ result.commands.typecheck = "npx tsc --noEmit";
63
+ }
64
+ const devDeps = {
65
+ ...(pkg?.devDependencies ?? {}),
66
+ ...(pkg?.dependencies ?? {}),
67
+ };
68
+ if ("prettier" in devDeps) {
69
+ result.commands.format = "npx prettier --write {file}";
70
+ }
71
+ if ("eslint" in devDeps) {
72
+ result.commands.lint = "npx eslint {file}";
73
+ }
74
+ else if ("biome" in devDeps) {
75
+ result.commands.lint = "npx biome lint {file}";
76
+ }
77
+ return result;
78
+ }
79
+ if (has.goMod) {
80
+ result.language = "go";
81
+ result.commands.test = "go test ./...";
82
+ result.commands.typecheck = "go build ./...";
83
+ result.commands.format = "gofumpt -w {file}";
84
+ result.commands.lint = "golangci-lint run {file}";
85
+ return result;
86
+ }
87
+ if (has.pyProject || has.requirements) {
88
+ result.language = "python";
89
+ result.commands.test = "pytest";
90
+ if (has.pyProject) {
91
+ result.commands.typecheck = "mypy .";
92
+ }
93
+ result.commands.format = "black {file}";
94
+ result.commands.lint = "flake8 {file}";
95
+ return result;
96
+ }
97
+ if (has.cargoToml) {
98
+ result.language = "rust";
99
+ result.commands.test = "cargo test";
100
+ result.commands.typecheck = "cargo check";
101
+ result.commands.format = "cargo fmt";
102
+ result.commands.lint = "cargo clippy";
103
+ return result;
104
+ }
105
+ if (has.gemfile) {
106
+ result.language = "ruby";
107
+ result.commands.test = "bundle exec rake test";
108
+ result.commands.format = "rubocop -A {file}";
109
+ result.commands.lint = "rubocop {file}";
110
+ return result;
111
+ }
112
+ if (has.composerJson) {
113
+ result.language = "php";
114
+ result.commands.test = "composer test";
115
+ result.commands.format = "php-cs-fixer fix {file}";
116
+ result.commands.lint = "phpstan analyse {file}";
117
+ return result;
118
+ }
119
+ if (has.pomXml || has.gradle) {
120
+ result.language = "java";
121
+ if (has.mavenWrapper) {
122
+ result.commands.test = "./mvnw test";
123
+ result.commands.typecheck = "./mvnw compile";
124
+ }
125
+ else if (has.gradleWrapper) {
126
+ result.commands.test = "./gradlew test";
127
+ result.commands.typecheck = "./gradlew compileJava";
128
+ }
129
+ else if (has.pomXml) {
130
+ result.commands.test = "mvn test";
131
+ result.commands.typecheck = "mvn compile";
132
+ }
133
+ else {
134
+ result.commands.test = "gradle test";
135
+ result.commands.typecheck = "gradle compileJava";
136
+ }
137
+ return result;
138
+ }
139
+ return result;
140
+ }
141
+ /**
142
+ * Build a YAML config string from a detection result. Only includes keys that
143
+ * have a detected value.
144
+ */
145
+ export function detectedConfigYaml(language, commands) {
146
+ const lines = [];
147
+ lines.push("profile: standard");
148
+ if (language !== null) {
149
+ lines.push(`# Detected language: ${language}`);
150
+ }
151
+ if (Object.keys(commands).length > 0) {
152
+ lines.push("commands:");
153
+ if (commands.test !== undefined)
154
+ lines.push(` test: ${commands.test}`);
155
+ if (commands.typecheck !== undefined)
156
+ lines.push(` typecheck: ${commands.typecheck}`);
157
+ if (commands.format !== undefined) {
158
+ if (typeof commands.format === "string") {
159
+ lines.push(` format: ${commands.format}`);
160
+ }
161
+ else {
162
+ lines.push(" format:");
163
+ for (const [ext, cmd] of Object.entries(commands.format)) {
164
+ lines.push(` ${ext}: ${cmd}`);
165
+ }
166
+ }
167
+ }
168
+ if (commands.lint !== undefined) {
169
+ if (typeof commands.lint === "string") {
170
+ lines.push(` lint: ${commands.lint}`);
171
+ }
172
+ else {
173
+ lines.push(" lint:");
174
+ for (const [ext, cmd] of Object.entries(commands.lint)) {
175
+ lines.push(` ${ext}: ${cmd}`);
176
+ }
177
+ }
178
+ }
179
+ if (commands.test_changed !== undefined)
180
+ lines.push(` test_changed: ${commands.test_changed}`);
181
+ }
182
+ return lines.join("\n");
183
+ }
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;