Skip to content

feat: OpenCode host support — official adapter for skills + session-start/pre-compact hooks (working bridge attached) #28

Open

Description

@lx-0

The problem

The operator works on the same ytstack-tracked projects (e.g. meinkontext, active .ytstack/ with M034 pointer) from four agents: Claude Code, Codex, Kimi Code and OpenCode (v2.2.6). ytstack installs cleanly on the first three through their plugin systems, but OpenCode cannot install Claude Code plugins: its plugin system is a TypeScript API with no marketplace for the Claude plugin format and no hooks.json execution. Result: every OpenCode session starts with zero ytstack context — no using-ytstack directive, no STATE.md snapshot, no greenfield routing — exactly the "remind me what we were working on" ritual the SessionStart hook exists to prevent.

Motivating session: 2026-11-09, OpenCode in a .ytstack/ project, no ytstack context present until a bridge was wired by hand.

Proposed change

Ship an official opencode/ adapter, analogous to codex/:

  • opencode/adapter.md — host conventions (how skills are addressed, how shell preambles run, what is not wired)
  • a small server plugin (the bridge) mapping OpenCode session events onto ytstack's existing hook scripts, unmodified
  • install docs: two entries in the global opencode.jsonc plus a pinned checkout

Working bridge (built and verified today, ytstack v0.4.2 + OpenCode v2.2.6, macOS)

  1. ytstack checkout at ~/.local/share/ytstack (tag v0.4.2, parity with the Claude marketplace install).
  2. Skills — OpenCode natively discovers SKILL.md directory trees via the config entry; all 31 skills load, hot-reload mid-session verified:
// ~/.config/opencode/opencode.jsonc (global)
{
  "skills": ["~/.local/share/ytstack/skills"],
  "plugins": ["<path to>/~/.config/opencode/plugins/ytstack"]
}
  1. Hooks — plugin at ~/.config/opencode/plugins/ytstack/index.ts (loaded from the global config's plugins array; OpenCode does not auto-load ~/.config/opencode/plugins/ in v2):
  • ctx.session.hook("context") → runs hooks/session-start once per session (cached), parses hookSpecificOutput.additionalContext, pushes it into event.system on every model call (OpenCode rebuilds the system prompt per call, so the text must be re-pushed; the script itself still runs only once).
  • ctx.session.hook("compaction") → runs hooks/pre-compact: writes HANDOFF.auto.md out-of-tree as designed and injects the compaction guidance into the summary request (capped at 10,000 chars).
  • Synthesizes the Claude hook payload {session_id, cwd, hook_event_name} on stdin and sets CLAUDE_PLUGIN_ROOT; resolves cwd from the session → project canonical.
  • Skips child sessions via session.parentID, matching the Claude matcher startup|resume|clear|compact|fork (no subagent injection).
  • Fail-open on every error, mirroring ytstack's own hook contract.
index.ts (as tested)
import { execFile } from "node:child_process"
import { homedir } from "node:os"
import path from "node:path"

const ROOT =
  process.env.YTSTACK_OPENCODE_ROOT ?? path.join(homedir(), ".local", "share", "ytstack")
const TIMEOUT_MS = 10_000

function runHook(hook: string, cwd: string, sessionID: string, extra: Record<string, unknown> = {}) {
  return new Promise<string>((resolve) => {
    const payload = JSON.stringify({
      session_id: sessionID,
      cwd,
      hook_event_name: hook === "pre-compact" ? "PreCompact" : "SessionStart",
      ...extra,
    })
    const child = execFile(
      "bash",
      [path.join(ROOT, "hooks", hook)],
      { cwd, timeout: TIMEOUT_MS, maxBuffer: 2 * 1024 * 1024,
        env: { ...process.env, CLAUDE_PLUGIN_ROOT: ROOT } },
      (error, stdout) => {
        if (error) { console.error(`[ytstack] ${hook} failed: ${error.message}`); resolve(""); return }
        resolve(stdout)
      },
    )
    child.stdin?.end(payload)
  })
}

async function sessionContext(ctx: any, sessionID: string) {
  try {
    const session = await ctx.session.get({ sessionID })
    if (ctx.project?.get && session?.projectID) {
      const project = await ctx.project.get({ projectID: session.projectID })
      const dir = project?.directory ?? project?.canonical
      if (dir) return { cwd: dir, child: Boolean(session?.parentID) }
    }
    return { cwd: ctx.location?.directory ?? process.cwd(), child: Boolean(session?.parentID) }
  } catch {
    return { cwd: ctx.location?.directory ?? process.cwd(), child: false }
  }
}

export default {
  id: "ytstack",
  async setup(ctx: any) {
    const startCache = new Map<string, Promise<string>>()

    const startContext = (sessionID: string, cwd: string) => {
      const cached = startCache.get(sessionID)
      if (cached) return cached
      const promise = runHook("session-start", cwd, sessionID, { source: "startup" }).then(
        (stdout) => {
          try {
            const text = JSON.parse(stdout)?.hookSpecificOutput?.additionalContext
            return typeof text === "string" ? text : ""
          } catch { return "" }
        },
      )
      startCache.set(sessionID, promise)
      if (startCache.size > 256) {
        for (const key of startCache.keys()) {
          startCache.delete(key)
          if (startCache.size <= 200) break
        }
      }
      return promise
    }

    await ctx.session.hook("context", async (event: any) => {
      const { cwd, child } = await sessionContext(ctx, event.sessionID)
      if (child) return
      const text = await startContext(event.sessionID, cwd)
      if (text) event.system.push({ type: "text", text })
    })

    await ctx.session.hook("compaction", async (event: any) => {
      const { cwd, child } = await sessionContext(ctx, event.sessionID)
      if (child) return
      const guidance = await runHook("pre-compact", cwd, event.sessionID, { trigger: "auto" })
      if (guidance) event.system.push({ type: "text", text: guidance.slice(0, 10_000) })
    })
  },
}

Verification: plugin active via /api/plugin, no server-log errors, skills watcher subscribed, and a fresh headless opencode run session in a .ytstack/ repo confirmed the directive was injected. Both hook scripts ran unmodified against a synthesized payload.

Findings an official adapter should decide

  • Namespace: skill IDs lose the ytstack: prefix (OpenCode IDs = directory names). /ytstack:<name> steering becomes an @<name> mention; adapter.md should say so.
  • CLAUDE_SKILL_DIR: OpenCode does not set it when loading a skill, so every preamble falls into the existing "Codex adapter: project scope only" fallback — works, but user-scope ~/.ytstack/projects/ resolution is unreachable. A bin/ytstack-opencode helper (analogous to bin/ytstack-codex) would close that.
  • gstack layering: OpenCode auto-discovers ~/.claude/skills as a compatibility source, so gstack's originals are visible there; the explicit skills config entry wins precedence, which keeps the ytstack wrappers on top — worth documenting as the supported shape.
  • Not wired, no OpenCode equivalent: SessionEnd journal, Stop, TaskCreated/TaskCompleted, TeammateIdle, PreToolUse-Edit, PostToolUse-Bash (commit-ref task linking). Edit/Bash could be approximated via ctx.tool.hook("execute.before"/"execute.after") — needs an explicit decision.
  • spawn-milestone-team references Claude-native subagent/worktree mechanics; OpenCode has subagent and worktree tools with different flags — like the Codex docs, adapter.md should prescribe the sequential flow.
  • Updates: no marketplace — the checkout is updated by hand (git fetch && git checkout <tag>); an install/update helper would help.

Scope check

  • It does not replicate a vendored superpowers / gstack skill. (Host plumbing; no skill content touched — hook scripts reused unmodified.)
  • It is not domain-specific functionality (that belongs in a separate plugin that depends on ytstack).
  • If it is a new skill, it needs .ytstack/ state to make sense — n/a, no new skill.
  • It preserves the UX contracts in docs/ux/ (no skill files modified; semantic selection via description: unchanged).

Alternatives considered

  • OpenCode plugin marketplace install: does not exist for the Claude plugin format; plugins are TS packages.
  • skills entry alone, no plugin: skill bodies load, but the session-start directive + STATE injection (the core "open tomorrow and it knows where you are" UX) and greenfield routing never fire.
  • instructions config pointing at .ytstack/STATE.md: static, per-project manual wiring, no worktree/repo resolution, no greenfield routing, no compaction handoff.

Activity

  1. added
    enhancement
    on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions