Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/en/agent-integrations/10-opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ Restart OpenCode after installation. In an OpenCode session, the plugin should e
- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`
- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`

OpenCode 2 captures the current turn's user message, assistant response, and tool results when each execution ends, and captures the transcript before compaction discards it. It commits at the token threshold, and forces a commit on compaction, session deletion, and plugin cleanup. OpenCode 2 runs cleanup after 60 minutes of inactivity, when the service stops, and when a local plugin is hot-reloaded.
OpenCode 2 captures the current turn's user message, assistant response, and tool results when each execution ends, and captures the transcript before compaction discards it. It commits at the token threshold, and forces a commit on compaction and session deletion. Plugin cleanup commits every session that has new messages since its last commit. OpenCode 2 runs cleanup after 60 minutes of inactivity, when the service stops, and when a local plugin is hot-reloaded.

Tool calls and results are captured as dedicated `tool` parts, and `tool_output` is reported verbatim. Truncation is the server's job: output larger than `tool_output_externalization.threshold_chars` (default `20000`) is written to the session's tool-result store, and the part keeps a synopsis stub plus `tool_output_ref`, so the original stays readable through [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read-tool-result).

Expand Down
2 changes: 1 addition & 1 deletion docs/zh/agent-integrations/10-opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`
- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`
- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`

OpenCode 2 在每次 execution 结束时抓取本轮用户消息、助手回复和工具结果,并在压缩前补齐即将移出上下文的对话;达到 token 阈值时提交,compaction、session 删除和插件 cleanup 会强制提交。OpenCode 2 会在无活动 60 分钟、服务停止或本地插件热重载时执行 cleanup。
OpenCode 2 在每次 execution 结束时抓取本轮用户消息、助手回复和工具结果,并在压缩前补齐即将移出上下文的对话;达到 token 阈值时提交,compaction 和 session 删除会强制提交;插件 cleanup 会提交自上次提交以来有新消息的所有 session。OpenCode 2 会在无活动 60 分钟、服务停止或本地插件热重载时执行 cleanup。

工具调用和结果会作为独立的 `tool` part 捕获,`tool_output` 原样上报。截断由服务端负责:超过 `tool_output_externalization.threshold_chars`(默认 `20000`)的输出会写入 session 的 tool-result 存储,part 中只保留 synopsis stub 和 `tool_output_ref`,原文仍可通过 [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read-tool-result) 读回。

Expand Down
2 changes: 1 addition & 1 deletion examples/opencode-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ call and points it to the OpenViking MCP tools. A `bash` command that contains a
an HTTP payload); the command runs and the plugin appends a notice naming the
MCP tools to its output.

OpenCode v2 has no plugin toast API. Service availability and other non-fatal notices are written to `openviking-memory.log`. The plugin captures the transcript before compaction discards it, checks the commit threshold after every execution (succeeded, failed, or interrupted), and forces a commit after completed compaction, session deletion, and cleanup. Each plugin instance handles only the sessions of its own location, and keeps its capture cursor in OpenCode plugin storage so a reloaded instance does not resend earlier turns.
OpenCode v2 has no plugin toast API. Service availability and other non-fatal notices are written to `openviking-memory.log`. The plugin captures the transcript before compaction discards it, checks the commit threshold after every execution (succeeded, failed, or interrupted), and forces a commit after completed compaction and session deletion. Cleanup commits every session with new messages since its last commit. Each plugin instance handles only the sessions of its own location, and keeps its capture cursor in OpenCode plugin storage so a reloaded instance does not resend earlier turns.

## MCP Tools

Expand Down
43 changes: 40 additions & 3 deletions examples/opencode-plugin/lib/memory-session.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ export function createMemorySessionManager({ config, pluginRoot }) {
createdAt: state.createdAt,
lastActivityAt: state.lastActivityAt,
lastCommitTime: state.lastCommitTime,
captureSeq: state.captureSeq,
committedSeq: state.committedSeq,
compactedAt: state.compactedAt,
messages: Array.from(state.messages.entries()).map(([messageId, message]) => ([
messageId,
Expand Down Expand Up @@ -156,6 +158,11 @@ export function createMemorySessionManager({ config, pluginRoot }) {
createdAt: persisted.createdAt,
lastActivityAt: persisted.lastActivityAt,
lastCommitTime: persisted.lastCommitTime,
// State written before the watermark existed: treat activity after the
// last commit as one uncommitted capture.
captureSeq: persisted.captureSeq ??
((persisted.lastActivityAt ?? 0) > (persisted.lastCommitTime ?? 0) ? 1 : 0),
committedSeq: persisted.committedSeq ?? 0,
compactedAt: persisted.compactedAt,
messages: new Map((persisted.messages ?? []).map(([messageId, message]) => ([
messageId,
Expand Down Expand Up @@ -296,7 +303,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {
debouncedSaveState()
}

async function flushAll({ commit = false } = {}) {
async function flushAll({ commit = false, onlyIfUncommitted = false, includesSession } = {}) {
if (saveTimer) {
clearTimeout(saveTimer)
saveTimer = null
Expand All @@ -306,7 +313,8 @@ export function createMemorySessionManager({ config, pluginRoot }) {
// See https://github.com/volcengine/OpenViking/issues/4490
for (const sessionId of sessions.keys()) {
try {
await flushSession(sessionId, { commit, reason: "flushAll" })
if (includesSession && !await includesSession(sessionId)) continue
await flushSession(sessionId, { commit, onlyIfUncommitted, reason: "flushAll" })
} catch (err) {
console.warn(
`[opencode-plugin] flushAll skipped session ${sessionId}:`,
Expand All @@ -317,7 +325,12 @@ export function createMemorySessionManager({ config, pluginRoot }) {
await enqueueSave()
}

async function flushSession(opencodeSessionId, { commit = false, reason = "manual" } = {}) {
// onlyIfUncommitted skips the commit when nothing arrived since the last one.
async function flushSession(opencodeSessionId, {
commit = false,
reason = "manual",
onlyIfUncommitted = false,
} = {}) {
if (!opencodeSessionId) return false
const state = sessions.get(opencodeSessionId)
if (!state) return false
Expand All @@ -326,6 +339,10 @@ export function createMemorySessionManager({ config, pluginRoot }) {
// not send the same pending messages twice.
const run = (state.flushChain ?? Promise.resolve()).then(async () => {
const added = await flushPendingMessages(opencodeSessionId, state)
if (commit && onlyIfUncommitted && !hasUncommittedActivity(state)) {
await enqueueSave()
return true
}
if (commit && isCaptureEnabled(config) && !shouldSkipSubagentSession(state)) {
const result = await commitOvSession(state.ovSessionId, { force: true, reason })
// Server lost the session (reset/reinstall); drop the stale mapping.
Expand Down Expand Up @@ -377,6 +394,8 @@ export function createMemorySessionManager({ config, pluginRoot }) {
createdAt: Date.now(),
lastActivityAt: Date.now(),
lastCommitTime: undefined,
captureSeq: 0,
committedSeq: 0,
compactedAt: undefined,
messages: new Map(),
}
Expand Down Expand Up @@ -496,6 +515,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {
}
if (added > 0) {
state.lastActivityAt = Date.now()
state.captureSeq = (state.captureSeq ?? 0) + 1
debouncedSaveState()
}
return added
Expand All @@ -516,9 +536,21 @@ export function createMemorySessionManager({ config, pluginRoot }) {
return commitOvSession(state.ovSessionId, { force: true, reason: "threshold" })
}

// captureSeq advances on every successful capture. A commit snapshots it
// when the request is sent, so a capture that lands while the commit is in
// flight stays uncommitted.
function hasUncommittedActivity(state) {
if (state.messages.size === 0) return false
return (state.captureSeq ?? 0) > (state.committedSeq ?? 0)
}

async function commitOvSession(ovSessionId, { force = false, reason = "manual", abortSignal } = {}) {
if (!force && config.commitTokenThreshold <= 0) return { status: "skipped" }
const body = { keep_recent_count: 0 }
const watermarks = new Map()
for (const state of sessions.values()) {
if (state.ovSessionId === ovSessionId) watermarks.set(state, state.captureSeq ?? 0)
}
const res = await fetchJSON(config, `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`, {
method: "POST",
body: JSON.stringify(body),
Expand All @@ -528,10 +560,15 @@ export function createMemorySessionManager({ config, pluginRoot }) {
for (const state of sessions.values()) {
if (state.ovSessionId === ovSessionId) state.lastCommitTime = Date.now()
}
for (const [state, seq] of watermarks) {
state.committedSeq = Math.max(state.committedSeq ?? 0, seq)
}
const traceId = res.traceId || res.result?.trace_id
log("INFO", "session", "Committed OpenViking session", {
openviking_session: ovSessionId,
reason,
status: res.result?.status,
archived: res.result?.archived,
trace_id: traceId,
})
return { status: "accepted", result: res.result, traceId }
Expand Down
8 changes: 7 additions & 1 deletion examples/opencode-plugin/lib/v2-plugin.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,13 @@ export async function startV2Plugin(ctx, runtime, { pluginRoot }) {
await runtime.ready
await runtime.background
await sessionManager.waitForBackground?.()
await sessionManager.flushAll({ commit: true })
// Cleanup ends every session this process was serving. Sessions with
// nothing new since their last commit are left alone.
await sessionManager.flushAll({ commit: true, onlyIfUncommitted: true, includesSession: async (sessionID) => {
const result = await ctx.session?.get?.({ sessionID })
const location = (result?.data ?? result)?.location
return Boolean(ctx.location?.directory && location?.directory && sameLocation(location, ctx.location))
} })
} catch (error) {
logHookError("plugin.cleanup", error)
}
Expand Down
2 changes: 1 addition & 1 deletion examples/opencode-plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
"version": "0.5.28",
"version": "0.5.29",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
Expand Down
120 changes: 119 additions & 1 deletion examples/opencode-plugin/tests/memory-session.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ async function withTempDir(prefix, fn) {
}
}

async function withCaptureServer(fn) {
async function withCaptureServer(fn, { beforeRespond } = {}) {
const requests = []
const server = createServer(async (req, res) => {
let body = ""
req.setEncoding("utf8")
for await (const chunk of req) body += chunk
requests.push({ method: req.method, url: req.url, body })
await beforeRespond?.(req)

res.setHeader("Content-Type", "application/json")
if (req.url === "/health") {
Expand Down Expand Up @@ -876,3 +877,120 @@ test("commit of a session the server no longer has drops the stale local mapping
await new Promise((resolve) => server.close(resolve))
}
})

test("a session is not committed again with nothing new since its last commit", async () => {
await withCaptureServer(async ({ endpoint, requests }) => {
await withTempDir("ov-oc-session-", async (dir) => {
const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })
const commitIfNew = { commit: true, onlyIfUncommitted: true, reason: "cleanup" }

await manager.init()
await manager.handleEvent({ type: "session.created", properties: { info: { id: "oc-short" } } })
await manager.handleEvent({
type: "message.updated",
properties: { info: { id: "msg-short", sessionID: "oc-short", role: "user" } },
})
await manager.handleEvent({
type: "message.part.updated",
properties: {
part: { id: "part-short", messageID: "msg-short", sessionID: "oc-short", type: "text", text: "A short session." },
},
})

await manager.flushSession("oc-short", commitIfNew)
await manager.flushSession("oc-short", commitIfNew)
await manager.flushAll({ commit: true, onlyIfUncommitted: true })

const commits = requests.filter((request) => request.method === "POST" && request.url?.endsWith("/commit"))
assert.deepEqual(commits.map((request) => request.url), ["/api/v1/sessions/oc-oc-short/commit"])
})
})
})

test("cleanup does not commit a session with no transcript", async () => {
await withCaptureServer(async ({ endpoint, requests }) => {
await withTempDir("ov-oc-session-", async (dir) => {
const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })

await manager.init()
await manager.handleEvent({ type: "session.created", properties: { info: { id: "oc-empty" } } })
await manager.flushAll({ commit: true, onlyIfUncommitted: true })

assert.equal(requests.some((request) => request.url?.endsWith("/commit")), false)
})
})
})

async function addUserMessage(manager, sessionId, messageId, text) {
await manager.handleEvent({
type: "message.updated",
properties: { info: { id: messageId, sessionID: sessionId, role: "user" } },
})
await manager.handleEvent({
type: "message.part.updated",
properties: {
part: { id: `${messageId}-part`, messageID: messageId, sessionID: sessionId, type: "text", text },
},
})
}

test("a message captured in the same millisecond as a commit is still committed", async (t) => {
t.mock.method(Date, "now", () => 1000)
await withCaptureServer(async ({ endpoint, requests }) => {
await withTempDir("ov-oc-session-", async (dir) => {
const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })
const commitIfNew = { commit: true, onlyIfUncommitted: true, reason: "cleanup" }

await manager.init()
await manager.handleEvent({ type: "session.created", properties: { info: { id: "oc-same-ms" } } })
await addUserMessage(manager, "oc-same-ms", "msg-first", "First message.")
await manager.flushSession("oc-same-ms", commitIfNew)
await addUserMessage(manager, "oc-same-ms", "msg-second", "Second message.")
await manager.flushSession("oc-same-ms", { reason: "session.idle" })
await manager.flushAll({ commit: true, onlyIfUncommitted: true })

const commits = requests.filter((request) => request.method === "POST" && request.url?.endsWith("/commit"))
assert.equal(commits.length, 2)
})
})
})

test("a message captured while a commit is in flight is not marked committed by its response", async () => {
let markCommitStarted
let releaseCommit
const commitStarted = new Promise((resolve) => { markCommitStarted = resolve })
const commitGate = new Promise((resolve) => { releaseCommit = resolve })
let commitCount = 0
const beforeRespond = async (req) => {
if (!req.url?.endsWith("/commit")) return
commitCount += 1
if (commitCount === 1) {
markCommitStarted()
await commitGate
}
}

await withCaptureServer(async ({ endpoint, requests }) => {
await withTempDir("ov-oc-session-", async (dir) => {
const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })
const commitIfNew = { commit: true, onlyIfUncommitted: true, reason: "cleanup" }

await manager.init()
await manager.handleEvent({ type: "session.created", properties: { info: { id: "oc-in-flight" } } })
await addUserMessage(manager, "oc-in-flight", "msg-first", "First message.")
const firstCommit = manager.flushSession("oc-in-flight", commitIfNew)
await commitStarted

await addUserMessage(manager, "oc-in-flight", "msg-second", "Second message.")
// Upstream serializes flushes: queue the second one without waiting
// for it before releasing the first commit response.
const secondFlush = manager.flushSession("oc-in-flight", { reason: "session.idle" })
releaseCommit()
await Promise.all([firstCommit, secondFlush])
await manager.flushAll({ commit: true, onlyIfUncommitted: true })

const commits = requests.filter((request) => request.method === "POST" && request.url?.endsWith("/commit"))
assert.equal(commits.length, 2)
})
}, { beforeRespond })
})
15 changes: 15 additions & 0 deletions examples/opencode-plugin/tests/v2-plugin.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,21 @@ test("prompt starts session context and recall together and keeps block order",
assert.deepEqual(event.metadata.openviking.context, ["<profile/>", "<recall/>"])
})

test("cleanup commits only sessions with new messages in its own location", async () => {
const flushes = []
const { runtime } = runtimeFixture()
runtime.sessionManager.flushAll = async (options) => { flushes.push(options) }
const { ctx } = contextFixture()
ctx.session.get = async ({ sessionID }) => ({ location: sessionID === "local" ? ctx.location : sessionID === "foreign" ? { directory: "/elsewhere" } : undefined })
await (await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" }))()
assert.equal(flushes.length, 1)
const { includesSession, ...options } = flushes[0]
assert.deepEqual(options, { commit: true, onlyIfUncommitted: true })
assert.equal(await includesSession("local"), true)
assert.equal(await includesSession("foreign"), false)
assert.equal(await includesSession("unknown"), false)
})

test("prompt metadata is persisted and context injection is stable across model steps", async () => {
let recallCalls = 0
const event = {
Expand Down