惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tenable Blog
T
Tailwind CSS Blog
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
Webroot Blog
Webroot Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Cloudflare Blog
T
Threat Research - Cisco Blogs
V
Visual Studio Blog
Jina AI
Jina AI
V
V2EX
I
InfoQ
Latest news
Latest news
P
Proofpoint News Feed
T
Threatpost
Engineering at Meta
Engineering at Meta
P
Proofpoint News Feed
美团技术团队
The Register - Security
The Register - Security
L
LangChain Blog
Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
GbyAI
GbyAI
Cloudbric
Cloudbric
Microsoft Azure Blog
Microsoft Azure Blog
C
Cisco Blogs
U
Unit 42
Microsoft Security Blog
Microsoft Security Blog
MyScale Blog
MyScale Blog
V
Vulnerabilities – Threatpost
TaoSecurity Blog
TaoSecurity Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Recent Commits to openclaw:main
Recent Commits to openclaw:main
W
WeLiveSecurity
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
小众软件
小众软件
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园_首页
N
News and Events Feed by Topic

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
OpenCode Integration Practice: Architectural Evolution from Standalone Process to Shared Runtime
Hagicode · 2026-05-11 · via DEV Community

OpenCode Integration Practice: Architectural Evolution from Standalone Process to Shared Runtime

This article shares the complete practice of HagiCode integrating the OpenCode AI assistant, including key design decisions during the architectural evolution process, pitfalls encountered, and final solutions.

Background

OpenCode is an open-source AI coding assistant project hosted on GitHub. For a monorepo project like HagiCode, integrating OpenCode as a supported AI Provider means it can be used as a backend model for proposal generation, code editing, and workflow execution.

However, this integration process didn't go as smoothly as imagined. Early on, there were two separate proposals: one planned to create a C# SDK, which was later abandoned—not really a loss; another for repository-level integration did persist. As OpenCode entered the formal session pipeline, we encountered a series of issues like session management and error recovery—after all, what must come will come.

More troublesome was that the initially designed "standalone process per session" model exposed high resource overhead issues in actual operation, forcing a refactor to a "system-level shared runtime" model. We also stepped into the 400 BadRequest pit—reusing external endpoints lacking context causing request failures. It's all tears, really.

This article is just organizing these pitfalls and design decisions to provide reference for projects that need to integrate OpenCode in the future. After all, beautiful things or people don't necessarily need to be possessed—as long as she remains beautiful, just watching her beauty quietly is enough... Technical sharing is the same.

About HagiCode

The solution shared in this article comes from our practical experience in the HagiCode project. HagiCode is an AI-based code assistant project. During development, we needed to integrate multiple AI Providers, and OpenCode is one of them. The architectural evolution process shared below are all real experiences from our actual project—stepping in pits and optimizing them. No choice but to fill the pits we stepped in.

Technical Architecture

Overall Layered Design

HagiCode's OpenCode integration architecture is divided into five layers, each with clear responsibilities:

1. Repository Integration Layer

Register the OpenCode repository through the MonoSpecs configuration system (.hagicode/monospecs.yaml). There's a choice here: submodule or plain Git repository? We chose the latter, managing cloning and synchronization through a unified scripts/clone-repos.mjs script. This is more flexible and avoids the permission and collaboration issues brought by submodules—after all, no one wants to see that error screen, but no choice.

2. Provider Layer

OpenCodeCliProvider implements the IAIProvider interface, which is the standard abstraction layer for interfacing with external AI services. The initial proposal wanted "standalone process per session," but actual operation revealed resource overhead was too high, ultimately changing to shared runtime mode, managing system-level runtime lifecycle through OpenCodeRuntimeCoordinator. It's nothing, really—the idea was beautiful, reality is cruel.

3. Runtime Management Layer

OpenCodeRuntimeCoordinator is the core of the entire architecture, responsible for runtime startup, health checks, and失效重建. It uses HagiCode.Libs.Providers.OpenCode as the HTTP client foundation, encapsulating all interactions with the OpenCode runtime. Like that winter night, the bamboo outside the window remained the same as yesterday, lacking the response to her—she still liked looking out the window—runtime is the same, needing someone to silently guard it.

4. Session Persistence Layer

Using SQLite database (opencode-session-bindings-v2.db) to persist the mapping of CessionId to OpenCode SessionId. This design is critical, supporting session recovery and restart, avoiding creating new sessions each time. After all, memory—sometimes forgetting is better, but in the program world, having no memory really doesn't work.

5. Error Recovery Layer

ProviderErrorAutoRetryCoordinator provides automatic retry mechanism,配合 OpenCodeRetryableTerminalFailureClassifier to classify errors—which can be retried, which should fail directly. This layer greatly improves system robustness. Actually nothing much, just letting the system be like a person—fall down and get up again.

Key Data Flow

When an AI request comes in, the data flow goes like this:

  1. Request first reaches OpenCodeCliProvider
  2. Provider requests runtime from OpenCodeRuntimeCoordinator
  3. Coordinator checks if there's an available runtime, if not starts a new one
  4. Query or create session binding through CessionId
  5. Use bound SessionId to call OpenCode API
  6. If error occurs, decide whether to retry based on error type

This process looks simple, but every step has had pitfalls. Does this have meaning? Perhaps, but we've stepped in them all... Also figured it out, stepping in pits is itself part of growth.

Key Design Decisions

From Standalone Process to Shared Runtime

The initial opencode-csharp-sdk proposal adopted a "standalone process per session" model. The idea was beautiful: good isolation, one process crash doesn't affect other sessions. But reality is cruel:

  • High resource overhead: each process needs to load runtime, memory usage rises straight up
  • Slow startup: frequent creation and destruction of processes, overhead can't be ignored
  • Complex management: process lifecycle management is itself a troublesome matter

Ultimately we changed to "system-level shared runtime" mode. All sessions reuse the same runtime process, distinguishing different sessions through session id. This change reduced resource usage by an order of magnitude and significantly improved response speed. Actually nothing much, just changing "one person enjoying alone" to "everyone using together."

Self-Managed Endpoint vs External BaseUri

Early on we encountered a weird 400 BadRequest problem. Investigation revealed it was because we reused an external BaseUrl but lacked necessary context information. OpenCode's runtime is stateful—directly using an external endpoint is equivalent to context loss—like a person without memory, at a loss.

The solution is simple: maintain self-managed runtime, don't depend on external endpoints. Leave BaseUri empty in configuration file, let the system manage runtime lifecycle itself.

AI:
  OpenCode:
    Enabled: true
    ExecutablePath: "opencode"
    BaseUri: null  # Leave empty, use self-managed runtime
    Model: "anthropic/claude-sonnet-4-20250514"

Enter fullscreen mode Exit fullscreen mode

This configuration change looks inconspicuous, but solved the most headache-inducing problem at the time. After all, sometimes the answer is right before our eyes, we just took too many detours.

Session Binding Strategy

Session binding is another key design. We use CessionId as binding key, supporting three modes:

  • started: New session, create new OpenCode SessionId
  • resumed: Resume existing session, read binding from database
  • restarted: Restart session, create new SessionId but preserve history

This design makes session management very flexible—users can resume previous conversations at any time, and the system can automatically rebuild bindings after runtime restart. After all, memory—sometimes want to forget but can't, sometimes want to remember but can't... Memory in the program world is quite reliable.

Implementation Plan

1. Repository Integration

Register OpenCode repository in .hagicode/monospecs.yaml:

repositories:
  - path: "repos/opencode"
    url: "https://github.com/anomalyco/opencode.git"
    displayName: "OpenCode"
    icon: "⌨️"

Enter fullscreen mode Exit fullscreen mode

Then run the clone script:

node scripts/clone-repos.mjs

Enter fullscreen mode Exit fullscreen mode

This pulls the OpenCode source code locally, and it can be updated at any time later. Actually quite simple, as long as there are no errors...

2. Provider Configuration

Configure OpenCode provider in appsettings.yml:

AI:
  OpenCode:
    Enabled: true
    ExecutablePath: "opencode"
    BaseUri: null
    Model: "anthropic/claude-sonnet-4-20250514"
    RequestTimeoutSeconds: 300
    StartupTimeoutSeconds: 60

Enter fullscreen mode Exit fullscreen mode

Several key parameters:

  • RequestTimeoutSeconds: Timeout for single request, default 5 minutes—after all, waiting too long is quite torturous
  • StartupTimeoutSeconds: Runtime startup timeout, giving a full 1 minute

3. Provider Restoration

Bring OpenCode back into the AI Provider system:

  • Restore OpenCodeCli in AIProviderType enum
  • Restore creation logic in AIProviderFactory
  • ExecutorGrainFactory routes OpenCodeCli to dedicated grain

These changes make OpenCode an equally-treated AI Provider, not a special case. Actually everyone is the same, nothing special or not special.

4. Runtime Management Code Example

// Get runtime through OpenCodeRuntimeCoordinator
var runtime = await _runtimeCoordinator.GetRuntimeAsync(
    _settings,
    request.WorkingDirectory,
    cancellationToken);

// Create or resume session
var session = await ResolveSessionAsync(runtime, request, cancellationToken);

// Send prompt
var response = await session.Runtime.Client.PromptAsync(
    session.SessionId,
    promptRequest,
    cancellationToken);

Enter fullscreen mode Exit fullscreen mode

This code looks very concise, but behind it does a lot of work: runtime startup, health checks, session binding query and creation. Like many things,表面上看不出什么,behind it all are stories.

5. Error Recovery Mechanism

// Detect retryable errors and rebuild runtime
if (ShouldRetryWithFreshRuntime(ex, cancellationToken))
{
    await _runtimeCoordinator.InvalidateAsync(runtime, ...);
    var recoveredRuntime = await ResolveRuntimeAsync(request, cancellationToken);
    // Retry with new runtime
}

Enter fullscreen mode Exit fullscreen mode

Automatic retry mechanism greatly improves system robustness—network jitter, runtime occasional crashes can all automatically recover. Actually life is the same, fall down and get up, nothing big... Programs are much stronger than people.

Practice Guide

Key Configuration Quick Reference

Configuration Default Description
Enabled true Whether to enable OpenCode provider
ExecutablePath "opencode" OpenCode executable path
BaseUri null External endpoint (recommended to leave empty)
Model - Default model
RequestTimeoutSeconds 300 Request timeout
StartupTimeoutSeconds 60 Runtime startup timeout

Session Binding Database Structure

CREATE TABLE IF NOT EXISTS OpenCodeSessionBindings (
    BindingKey TEXT NOT NULL PRIMARY KEY,
    OpenCodeSessionId TEXT NOT NULL,
    CreatedAtUtc TEXT NOT NULL,
    UpdatedAtUtc TEXT NOT NULL
);

Enter fullscreen mode Exit fullscreen mode

Bindings are retained for 30 days, automatically cleaned after expiration. This design both ensures session recovery capability and avoids unlimited data growth. After all, everything has an expiration, expired then clean up, it's also a form of letting go...

Common Issues and Solutions

1. 400 BadRequest Error

Check BaseUri configuration, recommend leaving empty to use self-managed runtime. If must use external endpoint, ensure context is complete. Actually most times, the problem lies in "taking for granted."

2. Session Cannot Resume

Confirm whether CessionId is correctly passed, check if corresponding binding record exists in database. Like searching for memory, there must be clues.

3. Model Selection Issue

Supports two formats: provider/model (like anthropic/claude-sonnet-4) and no-provider format (like claude-sonnet-4). All roads lead to Rome, just some roads are easier to walk, some roads slightly more winding.

4. Tool Name Mismatch

Tool names are automatically normalized, removing content after parentheses and colons. For example read(path) becomes read, pay attention when calling. These details aren't much, just easily overlooked.

5. Auto Retry Not Working

Check if error classifier correctly identifies retryable errors. By default, network errors, runtime failures etc. automatically retry up to 3 times. After all, trying a few more times doesn't hurt, might just work.

Related Code Paths

  • Provider: repos/hagicode-core/src/PCode.ClaudeHelper/AI/Providers/OpenCodeCliProvider.cs
  • Runtime Coordinator: repos/hagicode-core/src/PCode.ClaudeHelper/AI/Providers/OpenCodeRuntimeCoordinator.cs
  • Configuration: repos/hagicode-core/src/PCode.ClaudeHelper/AI/Configuration/OpenCodeSettings.cs
  • Proposal Archive: openspec/changes/archive/2026-03-*opencode*/

Summary

HagiCode's process of integrating OpenCode is actually a continuous process of stepping in pits and optimizing. From the initial standalone process mode to shared runtime, from reusing external endpoints to self-managed runtime, every architecture adjustment is driven by actual needs. Actually nothing much, just didn't miss any pit that should be stepped in.

There are three core experiences:

  1. Resource sharing is important: Don't blindly pursue isolation, shared runtime can significantly reduce resource overhead—sometimes one person enjoying alone isn't as good as everyone using together
  2. Be careful with state management: Stateful services should be self-managed, don't depend on external endpoints—after all, your own affairs are best done yourself
  3. Error recovery is essential: Automatic retry mechanism can take system robustness up a level—fall down and get up, nothing big

This solution now runs stably in HagiCode, supporting session recovery, automatic retry, runtime rebuild and other functions. If your project also needs to integrate OpenCode, hope these experiences can help you walk fewer detours. After all... only after walking detours do you know where the shortcut is, sometimes knowing it is of no use.

References