Skip to content

feat(opencode-plugin): support OpenCode v2 - #5341

Merged
t0saki merged 8 commits into
volcengine:mainfrom
t0saki:feat/opencode-v2
Sep 24, 2026
Merged

t0saki merged 8 commits into
volcengine:mainfrom
t0saki:feat/opencode-v2

Conversation

@t0saki

@t0saki t0saki commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

OpenCode v2 does not execute the v1 hook export, so the existing OpenViking plugin loads without providing memory integration. This change adds the v2 setup(ctx) API to the existing package while retaining the v1 server() entrypoint and installer configuration.

The same package now provides automatic recall, profile injection, conversation capture, lifecycle commits, MCP tools, and Viking URI guidance on OpenCode v1 (1.15.7+) and v2 (2.0.15+). Package version: 0.5.0.

Thanks to @ttelfer for the initial adapter in #5273; his original commit is kept in this branch.

Human Involvement

  • A human participated in the implementation or review loop
  • This PR was generated entirely by AI agents without human participation in the loop

Related Issue

Fixes #5226
Supersedes #5273

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • Test update

Changes Made

  • Keep the existing package, directory, harness identity and legacy plugin configuration. Export one definition with id openviking, v2 setup(ctx), and v1 server(input). OpenCode v2 normalizes the installer's "plugin" key and flat mcp.openviking entry, so the installer is unchanged.
  • Compute recall once per submitted prompt in the v2 prompt hook and persist it in user-message metadata. The context hook injects the stored text into that user message on every model step, so the system prompt and earlier turns stay stable across steps.
  • Capture real v2 user, assistant and tool messages through session.context() when each execution ends. Capture again before compaction removes the old transcript, then commit once on session.compaction.ended. Capture and lifecycle processing are serialized to avoid concurrent flushes.
  • Handle only sessions that belong to the plugin's own location. One v2 service runs a plugin instance per location, and the plugin event stream carries every location's events: the plugin's effect context has no Location.Service, so the bus does not filter, and execution events carry no envelope location. Ownership is resolved from session.created or ctx.session.get. Without this, every open project captured and committed every session, storing each message once per location.
  • Keep the capture cursor in plugin storage (ctx.storage) and remove it when the session is deleted. The session state file is shared by every location instance and rewritten by each, so its captured flags cannot prove what was already sent; an in-memory cursor alone made a reloaded or evicted instance resend the transcript since the last compaction.
  • Treat a failed v2 execution as the end of one turn: flush and check the commit threshold, keeping session state, instead of v1's session.error commit-and-delete path.
  • Drop reasoning blocks from capture, matching v1 parts and the shared capture filter, so chain-of-thought does not reach memory extraction.
  • Preserve structured tool inputs, outputs and errors. Support the v2 shell tool, return local-file URI guard errors to the model, and append notices without duplicating existing text blocks.
  • Register direct openviking_* MCP tools with codemode: false and v2 timeout settings; preserve an explicit disabled: true.
  • Defer startup health checks, pending replay and legacy migration so prompt admission is not blocked. Cleanup waits for event processing and initialization before its final flush.
  • Update English/Chinese integration and capability documentation.

Testing

  • I have added tests that prove my fix is effective or that my feature works

  • New and existing unit tests pass locally with my changes

  • I have tested this on the following platforms:

    • Linux
    • macOS
    • Windows
  • Plugin syntax checks and unit tests: 45 passed. The v2 event-loop tests cover location scoping (via session.created and the session.get fallback), failed executions keeping state, and a new instance resuming from the stored cursor; both event-loop tests fail against the adapter without these fixes.

  • Shared memory plugin tests: 467 passed. Plugin version gate (0.4.2 -> 0.5.0), git diff --check and npm pack --dry-run passed.

  • Real end-to-end tests on macOS, OpenCode 2.0.15 / 1.15.7 / 1.18.32, remote OpenViking v0.4.18.17, and DeepSeek V4.1 Flash through an Anthropic-compatible endpoint. Host configuration, data, state, and working directories were isolated. These runs used a single location; the location-scoping, stored-cursor, failed-execution and reasoning changes are covered by unit tests.

Scenario Observed result
v2 prompt/context injection Metadata persisted. Two consecutive model requests contained session-start context and direct MCP tools; system/context hashes were unchanged, with one recall per prompt.
v2 URI guard and MCP Local read returned a model-visible guard error and execution continued. Shell output contained one notice without duplicated exit text. Direct openviking_list succeeded.
Compaction during execution Requested compaction during a tool call. The host dropped the earlier transcript; OV retained the user/assistant messages and both pre/post-compaction tool results. One compaction commit was observed.
v2 cleanup and remote archive With keep_recent_count=0, remote OV reported total_message_count=3 and commit_count=1; archive_001 and its summary were created.
Duplicate plugin identity Two local sources produced one active openviking instance and one Duplicate plugin ID error.
Explicit MCP disable Plugin remained active and MCP remained disabled.
v1 compatibility Both versions completed real model/tool turns. Persistent services captured user, assistant and tool messages verified by remote OV readback; 1.18.32 instance disposal committed successfully.

The commercial OV gateway blocks its dedicated archive-read endpoint (ApiBlocked), so raw archive contents were not read back. Live messages were inspected before archival, and archive existence, metadata and summary were verified separately.

Checklist

  • My code follows the project's coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Screenshots (if applicable)

N/A

Additional Notes

A short-lived v1 CLI run can exit before asynchronous idle capture finishes. This also reproduces with the main-branch plugin on 1.15.7, which does not invoke plugin disposal hooks. Persistent v1 services allow idle capture to complete, and 1.18.32 invokes disposal when its instance is disposed.

Known v2 follow-ups, not addressed here:

  • Parallel subagents can be mapped before their session.created is processed, so a child may land in a standalone oc-<child> session instead of oc-<parent>__subagent-<child>.
  • A heavily delayed execution-end capture can snapshot the next, still-running assistant message.
  • Cleanup force-commits every session in the state file, and v2 runs cleanup on each 60-minute location eviction and plugin reload.
  • A v1-style {"enabled": false} MCP override is dropped by v2 config normalization; the plugin's own hook-only switch still works.

OpenCode changes in #4988, #5179, #4989 and #4107 may need rebasing around the shared runtime extraction.

ttelfer and others added 3 commits September 23, 2026 21:52
OpenCode 2 does not run v1 hook plugins. Keep the existing server()
entrypoint and add setup() so one package serves both, adapting MCP,
recall, capture, and lifecycle events to the v2 shapes.

Refs volcengine#5226
Copilot AI lite review requested due to automatic review settings September 23, 2026 14:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@ktz03 ktz03 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First-pass review (Integration / opencode-plugin — focused)

Scope of this pass: packaging dual-entry (v1 server + v2 setup), memory-session/pending replay, docs capability matrix. Not a full line-by-line of all +900.

What looks solid

  • Keeping one package/id while exporting both host surfaces is the right compatibility shape for OpenCode v2 (v1 hooks no longer run).
  • v2 recall-once → user-message metadata → re-inject on later model steps avoids unstable system-prompt churn; matches how other hosts stabilize recall.
  • Capture at execution completion + pre-compaction, single commit on session.compaction.ended is consistent with the capability-reference matrix updates.
  • memory-session now catches replayPending failures during init (log + continue) — good hardening for hosts that must not abort startup on pending-queue/dynamic-import issues.
  • Version 0.5.0 + new v2 tests / docs EN+ZH look intentional for a host-API bump.
  • CI green on this head (plugin-tests / plugin-versions / docs / API).

Questions / nits (non-blocking)

  1. Confirm v2 cleanup / session.deleted|error forced-commit paths still honor the dispose time budget the docs warn about (v1 dispose 5s) — if v2 cleanup is similarly budgeted, a pending flush miss should stay documented.
  2. recall-session-wiring.test.mjs only shows a small touch in the diff summary — worth a one-line note in the PR if wiring expectations changed for opencode specifically.

Overall: direction looks mergeable; deferring final approval to Integration Primary Contact for a second look.

# Conflicts:
#	examples/opencode-plugin/package.json
…utions

v2 capture turned reasoning blocks into assistant text, so chain-of-thought
reached memory extraction and inflated pending tokens. v1 parts and the shared
capture filter drop reasoning; v2 now does the same.

A failed v2 execution ends one turn, not the session. Mapping it to v1's
session.error committed and deleted the session state, so a later capture
without a cursor resent every earlier turn. Failed executions now take the
same idle path as succeeded and interrupted ones.
…sist its cursor

One OpenCode v2 service runs a plugin instance per location, and the plugin
event stream carries every location's events. Each instance therefore
captured and committed every session, storing each message once per open
project. Handle only lifecycle events whose session belongs to this
location, resolved from session.created or ctx.session.get because execution
events carry no envelope location.

The capture cursor lived only in memory, and the shared session state file
is rewritten by every instance, so a reloaded or evicted instance could
resend the transcript since the last compaction. Keep the cursor in plugin
storage and remove it when the session is deleted.
@t0saki
t0saki merged commit 1207638 into volcengine:main Sep 24, 2026
5 of 6 checks passed
@github-project-automation github-project-automation Bot moved this from Backlog to Done in OpenViking project Sep 24, 2026
frankyang2008-eng added a commit to frankyang2008-eng/OpenViking that referenced this pull request Oct 9, 2026
…I plugin, account-scoped embedding/VLM providers, resource permission management, ls/tree pagination)

Upstream: 7b07c4a -> 3949b51 (57 commits, 518 files, +29307/-7524), post-v0.4.21.

Themes
- plugins: Kimi Code CLI memory plugin (volcengine#4787) with manifest alignment (volcengine#5376);
  shared capture filtering across adapters (volcengine#5359, volcengine#5375); find the installer
  runtime in the fetched checkout (volcengine#5280); dsh bundle/plugin card (volcengine#5390, volcengine#5362),
  producer-owned source kind (volcengine#5318), broad MCP recall scope (volcengine#5346), per-session
  workspace peer settings (volcengine#5380); OpenCode v2 support (volcengine#5341), parallel
  session-inject and recall (volcengine#5149)
- config: isolate account runtime resources (volcengine#5323) - RuntimeConfigManager plus
  account-scoped embedding/VLM providers, which is what the embedding_provider /
  vlm_resolver plumbing in this merge serves
- acl: inherit full-management permissions by default with create-time
  authorization (volcengine#5266); web-studio resource permission management (volcengine#5329)
- fs: pagination state for ls and tree (volcengine#5330), unified URI normalization with
  Chinese path support (volcengine#5328), serialize mkdir abstract creation (volcengine#5183)
- grep: propagate later-page ACL denials (volcengine#5289); drop the ripgrep invoke
  (volcengine#5369)
- queue: requeue on semantic directory lock conflicts (volcengine#5340), fix the missing
  downstream index task on write-wait (volcengine#5357)
- metrics: queue processing latency (volcengine#5365), persisted HTTP retrieval result
  counts (volcengine#5294); observer JSON status format (volcengine#5316)
- openclaw: stop offering the legacy person peer role at install time (volcengine#5355),
  widen to unscoped recall when peer_role=sender has no sender (volcengine#5347)
- session: split session.py into sub-modules (volcengine#5363)
- hermes: gateway memory presets and sender attribution (volcengine#5293), rotate
  read-only session state (volcengine#5372), mirror native memory replacements/removals
  (volcengine#5281), bind settings to the initialized profile (volcengine#5374), skip writes for
  non-primary agent contexts (volcengine#5353)
- docs: enterprise deployment guides (volcengine#5361, volcengine#5388), browser-language docs
  preferences (volcengine#5351); feishu project auth refresh (volcengine#5350)

Conflicts (15) and resolutions - full analysis in
plans/upstream-sync-14-conflict-analysis.md

- openviking/models/vlm/token_usage.py - took upstream. The fork made
  TokenUsageTracker thread-safe with an RLock and hand-written locks; upstream
  shipped the same intent more completely (a @_locked decorator, _add_usage()
  that also merges last_updated, and a merge() that iterates a to_dict()
  snapshot instead of a live model map). Upstream is a superset, so the fork's
  version carries no information the merge would lose.
- examples/agent-hook-plugin/hosts/zcode-capture.mjs,
  examples/dsh-memory-plugin/index.mjs,
  examples/openclaw-plugin/tests/ut/identity-routing.test.ts,
  docs/en/agent-integrations/17-dsh.md,
  docs/zh/agent-integrations/17-dsh.md, docs/en/api/03-filesystem.md - took
  upstream. Every fork change on these files is Prettier/markdown noise
  (re-wrapping, table pipes, arrow parens); verified by comparing base to the
  fork tip with whitespace, commas and semicolons stripped. The repository has
  no prettier/markdownlint/yamllint config and CI does not run them, so keeping
  the formatting only re-conflicts on every sync. identity-routing.test.ts also
  had to take upstream on semantics: the fork still asserted a throw for a
  sender-scoped call without a sender, which upstream replaced with a warning
  plus unscoped fallback.
- openviking/service/core.py - union of three hunks. Kept the fork's
  _init_shared_rerank_runtime() call and the shared rerank client/executor, and
  took upstream's _init_runtime_config_manager() plus the VLM resolver check.
  Upstream's removal of the process-level embedder check is taken as-is: the
  attribute is no longer assigned anywhere upstream, so keeping the check would
  raise on every boot. The rerank runtime is initialized after the config
  manager, matching upstream's use of the same config reference for
  init_viking_fs(rerank_config=...).
- openviking/service/debug_service.py - the constructor and set_dependencies now
  accept rerank_client together with upstream's embedding_provider and
  vlm_resolver, in that positional order. The models-status path reuses the
  service-shared rerank client and only falls back to building one. The fork's
  "if self._config.embedding: embedding_instance = get_embedder()" block is
  dropped: upstream replaced the process-level embedder with the token-tracker
  namespace, so keeping it would resurrect the deleted embedder.
- openviking/storage/queuefs/queue_manager.py - union. The fork's shared
  "qfs-agfs" ThreadPoolExecutor and _agfs_call_timeout survive next to
  upstream's optional VLMResolver plus the TYPE_CHECKING import.
- openviking/session/memory/patch_merge_context_provider.py - union of imports;
  the fork's consumer="patch_merge" attribution survives.
- examples/pi-coding-agent-extension/index.ts - took upstream on both hunks
  (comment plus Prettier wrapping). The fork's omp getBranch() fallback and the
  WeakMap identity map live in non-conflicting regions and are preserved.
- examples/openclaw-plugin/commands/setup.ts, setup-helper/install.js - took
  upstream's peer-role semantics. Upstream added normalizePeerRoleInput(), which
  rejects "person" for setup input while still reading it from existing configs;
  the fork side of the setup.ts hunk lacks that definition while other code
  calls it, so taking the fork would break at runtime. All five install.js
  conflicts are the same change plus Prettier wrapping.
- examples/memory-plugin-shared/install.sh (20 hunks) - union. Upstream adds the
  kimicode harness, the fork adds qoder, codebuddy, omp and agy; both extend the
  same lists, so every hunk keeps both, in the order zcode, kimicode, qoder,
  codebuddy, omp, agy. copy_agent_integration() keeps upstream's explicit
  destination argument and the fork's host-specific source lookup side by side.
  This also fixes a fork bug found while resolving tui_item_at(): the missing
  i=$((i + 1)) between zcode and qoder left qoder without an index of its own
  (the row was unreachable and "add" was rendered twice), and
  tui_selectable_count() now says 12.
- docs/maintenance: plans/upstream-sync-14-conflict-analysis.md records the
  per-file evidence, the TUI index/count self-check, and the report-only
  convention for upstream-owned lint/type debt.

Not touched
- No file that is byte-identical to upstream/main was modified; upstream-owned
  lint/type debt stays report-only per the convention established in the 12th
  and 13th syncs (plans/upstream-type-debt-20260917.md).

Verified
- git grep for conflict markers: clean
- bash -n install.sh, node --check on every merged .js/.mjs, ast.parse on every
  merged .py: pass
- local work still present on top of main: core.py +49, debug_service.py 14,
  queue_manager.py 125, install.sh +682, install.js 1588, setup.ts 530,
  pi-coding-agent-extension 95
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[Feature] Support OpenCode v2

5 participants