devin 0.1.30: an opt-in cache keepalive, as the devin CLI's (#592)

Devin's prompt cache lasts 5 minutes and has no longer TTL to ask for.
A switch, "Keep the cache warm" (cache_keepalive, off by default, with
zh, zh-TW, ja and de labels), keeps it as the CLI's cache_keepalive.rs
does: after a reply that read or wrote the cache, whatever it stopped
for, the same GetChatMessage goes again every 285 s with one more user
prompt, "continue", and max_tokens 1. The request's bytes are encoded
once, and the ping is them with that prompt and field 8's max_tokens.

- A conversation is session + Claude Code agent id (when the headers
  reach the plugin) + a hash of the instructions, tool names and first
  user message; its next real request stops its pings, so a subagent
  never stops its lead's.
- Stops on 401, 402, 429, two pings in a row reading under half their
  prompt from the cache, the most pings (6), the switch going off, and
  process exit. Timers are unref'd. At most 32 conversations are kept.
- Options cacheKeepaliveInterval (30-299 s) and cacheKeepaliveMaxPings
  (1-50); OpenCode, which has no switch, takes cacheKeepalive: true.
- README says the cost (each ping is a cache read of the whole context,
  spent whether the user comes back or not) and why it is off.

Run (mote, HOME=$(mktemp -d)):
- bun test packages/devin: 170 pass, 0 fail (14 new in keepalive.test.mjs).
- Whole repo bun test: 4520 pass, 9 skip, 1 fail: gcp-ai's "a lock held
  by another process is waited for, then taken" (ENOENT in abandoned()'s
  stat, a race in lib/lock.mjs; passes 3 of 3 alone), filed as #594.
- bun scripts/check.mjs: ok.
- The new tests against the old index.mjs: 14 of 14 fail.

Broken by hand, each red in the test named for it: no cancel on the next
request, no agent id in the key, no prefix hash, no stop on 401/402/429,
no miss count, no cap, no unref, max_tokens kept, pings after a reply
that touched no cache.

Real account (the owner's Devin sign-in read, nothing written, sandbox
HOME, this Mac): claude-sonnet-5-5-low, an 11k-token prompt wrote 10,984
to the cache; one ping 287 s later read 10,984 from it (cacheWrite 3,
output 1) and, at max 1, stopped.

Not tried: more than one ping or a long Claude Code session; the OpenCode
2 (v2) path, which has no keepalive. magpie doesn't pass
x-claude-code-session-id / x-claude-code-agent-id to a plugin's fetch, so
under magpie the key rests on the prefix hash (a lead and a subagent
differ there; two sessions with the same prefix share one keepalive).
This commit is contained in:
yetone
2026-11-01 14:12:06 +08:00
parent 85019888d7
commit b797476f6b
4 changed files with 583 additions and 22 deletions
+39
View File
@@ -81,6 +81,45 @@ The plugin's `fetch` handles this:
were counted. The plugin waits for actual content before opening a
successful stream, so the gateway can try another channel.
## Keeping the cache warm
Devin keeps a prompt cache for 5 minutes, and has no longer TTL to ask
for (`PromptCacheOptions` has only `type: EPHEMERAL`; Claude Code's
`ttl: "1h"` has nowhere to go). After 5 minutes without a request, the
next turn writes the whole context again.
**Keep the cache warm** (`cache_keepalive`), a switch in the provider's
editor in magpie, **off by default** (#592), keeps it as the devin CLI
does (`cache_keepalive.rs`, 3000.11.205): after a reply that read or wrote
the cache, whatever it stopped for (a tool call waiting too), the same
`GetChatMessage` is sent again every 285 seconds, byte for byte, with one
more user prompt, `continue`, and `max_tokens` 1. Each one reads the cache
and renews it. Unlike the CLI's, it also runs while the user is reading
the reply, not only while a tool or subagent works.
- The conversation's next real request stops its pings; its own reply
starts them again. A conversation is the session the agent names, the
Claude Code subagent (`x-claude-code-agent-id`) and a hash of the
instructions, the tools' names and the first user message, so a
subagent's requests never stop its lead's pings.
- They stop on a 401, 402 or 429, after two pings in a row that read less
than half their prompt from the cache, at the most pings (6), when the
switch goes off, and with the plugin host's process. The timers never
keep a process running.
- The plugin's options change the interval and the most pings:
`cacheKeepaliveInterval` (seconds, 30–299, default 285) and
`cacheKeepaliveMaxPings` (1–50, default 6), in magpie's `plugins.json`
entry or OpenCode's `["@magpie-community/opencode-devin-auth", {…}]`.
In OpenCode, which has no switch, `cacheKeepalive: true` turns it on.
**The cost.** Each ping is billed as a cache read of the whole context, plus
a token or two. That is about a tenth of writing it again, but it is
spent whether or not the conversation goes on: six pings of a 300k-token
context read 1.8M cached tokens over 28 minutes, and if the user never
comes back, all of it is lost. It pays when the next turn comes after 5
minutes and within half an hour; a user who leaves a conversation for good
pays for nothing. So it is off until turned on.
## Models
Devin's models are families: `swe-2`, `claude-opus-5-5`, `gpt-6-sol`, …
+246 -21
View File
@@ -1577,33 +1577,50 @@ function build(chat, uid, key) {
}
// encodeRequest is the GetChatMessage request of msgs, with tools offered
// and the sampling asked, to the model uid.
// and the sampling asked, to the model uid. Its cache keepalive ping
// (keepalivePing) is the same request, byte for byte, with one more user
// prompt, "continue", and max_tokens 1, as the devin CLI pings
// (plugins#592): each prompt is encoded once, so both carry the same bytes.
function encodeRequest(msgs, tools, chat, uid, key) {
const out = new PB().bytes(1, metadata(key))
for (const m of msgs) out.bytes(3, encodeMsg(m))
out.varint(7, 5)
const max = chat.max || 128000 // the server holds it to the model's own
const head = metadata(key).done()
const prompts = msgs.map(encodeMsg)
// Devin answers "an internal error occurred" to a temperature or top_p of
// exactly 0 (on every model: its Claude ones and swe-2), where 1e-6 goes
// through; a 0 is sent as the smallest step above it, as near greedy
const above0 = (v) => (v === 0 ? 1e-6 : v)
const temp = above0(typeof chat.temperature === "number" ? chat.temperature : 1)
const topP = above0(typeof chat.top_p === "number" ? chat.top_p : 0.95)
out.bytes(8, new PB().varint(1, 1).varint(2, max).varint(3, 400).double(5, temp).varint(7, 40).double(8, topP))
const sampling = (max) => new PB().varint(1, 1).varint(2, max).varint(3, 400).double(5, temp).varint(7, 40).double(8, topP)
// the caller's tools, and any the conversation used that it no longer
// offers
const offered = new Set()
const toolParts = []
const tool = (name, desc, schema) => {
if (!schema || typeof schema !== "object") schema = { type: "object", properties: {} }
offered.add(name)
out.bytes(10, new PB().str(1, name).str(2, desc || name).bytes(3, JSON.stringify(schema)))
toolParts.push(new PB().str(1, name).str(2, desc || name).bytes(3, JSON.stringify(schema)).done())
}
for (const t of tools) tool(t.name, t.description ? `Described under <tool name="${t.name}"> in <tool_descriptions>, in the instructions.` : "", t.schema)
for (const m of msgs) for (const c of m.calls ?? []) if (!offered.has(c.name)) tool(c.name, "Tool")
return out.str(21, uid).done()
const assemble = (more, max) => {
const out = new PB().bytes(1, head)
for (const p of [...prompts, ...more]) out.bytes(3, p)
out.varint(7, 5)
out.bytes(8, sampling(max))
for (const t of toolParts) out.bytes(10, t)
return out.str(21, uid).done()
}
const bytes = assemble([], chat.max || 128000) // the server holds max to the model's own
pingOf.set(bytes, () => assemble([encodeMsg({ role: USER, text: "continue" })], 1))
return bytes
}
// pingOf is each request's keepalive ping, made when one is first sent
const pingOf = new WeakMap()
const keepalivePing = (bytes) => pingOf.get(bytes)?.()
function encodeMsg(m) {
const b = new PB().str(1, randomUUID()).varint(2, m.role)
if (m.text) b.str(3, m.text)
@@ -1747,14 +1764,20 @@ async function* prepend(first, rest) {
const CHAT_WIRE = { effort: (chat) => effortOf(chat.reasoning_effort), build }
const MESSAGES = { effort: anthropicEffort, build: buildMessages }
async function roundtrip({ key, server, families }, chat, signal, wire = CHAT_WIRE) {
// rpcHeaders are a GetChatMessage's headers for a framed body.
const rpcHeaders = (key, body) => ({ "Content-Type": "application/connect+proto", "Connect-Protocol-Version": "1", ...(body[0] & 1 ? { "Connect-Content-Encoding": "gzip" } : {}), Authorization: "Basic " + key })
// keep, when given, is the conversation's cache keepalive (keepaliveFor):
// once the reply has finished, its pings are scheduled.
async function roundtrip({ key, server, families, keep }, chat, signal, wire = CHAT_WIRE) {
const uid = variantFor(families, chat.model, wire.effort(chat))
const body = frame(wire.build(chat, uid, key))
const msg = wire.build(chat, uid, key)
const body = frame(msg)
let res
try {
res = await fetch(server + CHAT_RPC, {
method: "POST",
headers: { "Content-Type": "application/connect+proto", "Connect-Protocol-Version": "1", ...(body[0] & 1 ? { "Connect-Content-Encoding": "gzip" } : {}), Authorization: "Basic " + key },
headers: rpcHeaders(key, body),
body,
signal,
})
@@ -1784,12 +1807,13 @@ async function roundtrip({ key, server, families }, chat, signal, wire = CHAT_WI
await fr.return?.()
return head.value.error
}
return { it: prepend(head.value, source) }
const it = prepend(head.value, source)
return { it: keep ? keptAfter(it, keep, { key, server, msg }) : it }
}
// complete answers a chat completion through GetChatMessage.
async function complete({ key, server, families }, chat, signal) {
const rt = await roundtrip({ key, server, families }, chat, signal)
async function complete({ key, server, families, keep }, chat, signal) {
const rt = await roundtrip({ key, server, families, keep }, chat, signal)
if (!rt.it) return errorResponse(rt)
const it = rt.it
const id = "chatcmpl-" + randomBytes(12).toString("hex")
@@ -2016,8 +2040,8 @@ const anthropicUsage = (t = {}) => ({ input_tokens: t.input ?? 0, output_tokens:
// completeMessages answers a Messages request through GetChatMessage, as
// Anthropic would: the reply's blocks, its stop reason and the usage with
// what was read from the cache and written to it.
async function completeMessages({ key, server, families }, req, signal) {
const rt = await roundtrip({ key, server, families }, req, signal, MESSAGES)
async function completeMessages({ key, server, families, keep }, req, signal) {
const rt = await roundtrip({ key, server, families, keep }, req, signal, MESSAGES)
if (!rt.it) return anthropicError(rt)
const it = rt.it
const id = "msg_" + randomBytes(12).toString("hex")
@@ -2105,6 +2129,179 @@ async function completeMessages({ key, server, families }, req, signal) {
return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Magpie-Sign-In": "kept" } })
}
// ---- cache keepalive (plugins#592) -----------------------------------------------
// Devin's prompt cache lasts 5 minutes, and has no longer TTL to ask for
// (PromptCacheOptions has only type EPHEMERAL). The devin CLI keeps it warm
// (3000.11.205, cache_keepalive.rs): after a reply it sends the same
// GetChatMessage again every 285 s, with "continue" at the end and
// max_tokens 1, which reads the cache and renews it. This is the same,
// off by default (each ping is billed as a read of the whole context):
// after any reply that read or wrote the cache, up to max pings, until the
// conversation's next real request, a refusal (401, 402, 429) or two
// pings in a row that read less than half their prompt from the cache.
// Unlike the CLI's, it also runs while the user is reading, not only while
// a tool or subagent works: magpie can't tell those apart, and the issue's
// reporter wants both. The CLI's ping carries query_label
// "cache_keepalive" in its trace; this plugin labels no request, so its
// ping doesn't either.
const KEEPALIVE = "cache_keepalive"
const KEEPALIVE_INTERVAL = 285 // seconds
const KEEPALIVE_MAX = 6
const KEEPALIVE_KEPT = 32 // conversations kept warm at once; past it the oldest stops
const KEEPALIVE_STOP = new Set([401, 402, 429])
// timers are what the pings wait on; tests hand in their own. A timer is
// unref'd: it never keeps a process or a test running.
const realTimers = { set: (fn, ms) => setTimeout(fn, ms), clear: (t) => clearTimeout(t) }
let timers = realTimers
const keeps = new Map() // conversation → {n, misses, timer, ctl}
// keepaliveSettings are the interval (ms) and the most pings, from the
// plugin's options (cacheKeepaliveInterval in seconds, 30–299;
// cacheKeepaliveMaxPings, 1–50), else the CLI's interval and 6.
function keepaliveSettings(options = {}) {
const sec = Number(options?.cacheKeepaliveInterval)
const max = Number(options?.cacheKeepaliveMaxPings)
return {
interval: (Number.isFinite(sec) && sec >= 30 && sec <= 299 ? sec : KEEPALIVE_INTERVAL) * 1000,
max: Number.isInteger(max) && max >= 1 && max <= 50 ? max : KEEPALIVE_MAX,
}
}
// the headers an agent names its session in, as magpie's gateway reads them
const SESSION_HEADERS = ["x-claude-code-session-id", "x-session-id", "session_id", "session-id", "x-opencode-session", "x-session-affinity", "x-conversation-id"]
// textsOf is a message's or system's words, without the cache marks a
// client moves forward as the history grows
const textsOf = (c) => (typeof c === "string" ? [c] : Array.isArray(c) ? c.map((b) => (typeof b === "string" ? b : typeof b?.text === "string" ? b.text : b?.type ?? "")) : [])
// keepaliveKey is the conversation a request is of: the session the agent
// names, the Claude Code subagent it is of (x-claude-code-agent-id, never
// sent for the lead's own turns), and a hash of the prefix every turn
// shares: the instructions, the tools' names and the first user message.
// A subagent's prefix is its own, so its requests never stop its lead's
// pings, nor the lead's its.
function keepaliveKey(req, messages, headers) {
let h
try {
h = new Headers(headers ?? {})
} catch {
h = new Headers()
}
const session = SESSION_HEADERS.map((k) => h.get(k)?.trim()).find(Boolean) ?? ""
const agent = h.get("x-claude-code-agent-id")?.trim() ?? ""
let prefix
if (messages) {
const system = textsOf(req.system).map((t) => t.replace(BILLING_LINE, ""))
prefix = [system, (req.tools ?? []).map((t) => t?.name ?? ""), textsOf(req.messages?.[0]?.content)]
} else {
const ms = req.messages ?? []
const system = ms.filter((m) => m?.role === "system" || m?.role === "developer").map((m) => textsOf(m.content))
prefix = [system, (req.tools ?? []).map((t) => t?.function?.name ?? ""), textsOf(ms.find((m) => m?.role === "user")?.content)]
}
return [session, agent, createHash("sha256").update(JSON.stringify(prefix)).digest("hex").slice(0, 32)].join("\n")
}
// stopKeepalive stops a conversation's pings, one in flight too.
function stopKeepalive(id) {
const k = keeps.get(id)
if (!k) return
keeps.delete(id)
if (k.timer) timers.clear(k.timer)
k.ctl?.abort()
}
function stopAllKeepalive() {
for (const id of [...keeps.keys()]) stopKeepalive(id)
}
// the pings stop with the process that sends them (the plugin host)
let exitHooked = false
function hookExit() {
if (exitHooked) return
exitHooked = true
process.once?.("exit", stopAllKeepalive)
}
// pingOnce sends a ping and reads its status and usage.
async function pingOnce(server, key, body, signal) {
let res
try {
res = await fetch(server + CHAT_RPC, { method: "POST", headers: rpcHeaders(key, body), body, signal })
} catch {
return { status: 0 }
}
if (!res.ok) return { status: failure(res.status, (await res.text().catch(() => "")).slice(0, 1 << 16)).status }
const tokens = { input: 0, cacheRead: 0, cacheWrite: 0 }
try {
for await (const f of frames(res.body)) {
if (f.end) {
const e = failure(200, dec.decode(f.data))
if (e.status >= 300) return { status: e.status }
break
}
for (const x of fields(f.data)) {
if (x.num !== 7 || x.wire !== 2) continue
for (const g of fields(x.data)) {
if (g.wire !== 0) continue
if (g.num === 2) tokens.input = g.n
else if (g.num === 4) tokens.cacheWrite = g.n
else if (g.num === 5) tokens.cacheRead = g.n
}
}
}
} catch {
return { status: 0 }
}
return { status: 200, tokens }
}
// scheduleKeepalive starts a conversation's pings for the request msg
// just answered, in place of any it had.
function scheduleKeepalive({ id, interval, max }, key, server, msg) {
const ping = keepalivePing(msg)
if (!ping) return
stopKeepalive(id)
while (keeps.size >= KEEPALIVE_KEPT) stopKeepalive(keeps.keys().next().value)
const body = frame(ping)
const k = { n: 0, misses: 0, timer: null, ctl: null }
keeps.set(id, k)
hookExit()
const next = () => {
k.timer = timers.set(run, interval)
k.timer?.unref?.()
}
const run = async () => {
k.timer = null
if (keeps.get(id) !== k) return
k.n++
k.ctl = new AbortController()
const r = await pingOnce(server, key, body, k.ctl.signal)
k.ctl = null
if (keeps.get(id) !== k) return // a real request came, or the switch went off
if (KEEPALIVE_STOP.has(r.status)) return stopKeepalive(id)
const t = r.tokens
const hit = r.status === 200 && t.cacheRead > 0 && t.cacheRead * 2 >= t.input + t.cacheRead + t.cacheWrite
k.misses = hit ? 0 : k.misses + 1
if (k.misses >= 2 || k.n >= max) return stopKeepalive(id)
next()
}
next()
}
// keptAfter passes a reply's events on, and once it has finished (any stop:
// a tool call waiting too) schedules the conversation's pings, when the
// reply read or wrote the cache: a request with nothing cached has nothing
// to keep.
async function* keptAfter(it, keep, { key, server, msg }) {
for await (const e of it) {
if (e.stop && (e.tokens?.cacheRead || e.tokens?.cacheWrite)) scheduleKeepalive(keep, key, server, msg)
yield e
}
}
// ---- OpenCode 2 ----------------------------------------------------------------------
// OpenCode 2 asks for a default export with an id and a setup(ctx). The
@@ -2579,8 +2776,8 @@ export default {
async setup(ctx) {
await v2Setup(ctx)
},
async server(input) {
return DevinAuthPlugin(input)
async server(input, options) {
return DevinAuthPlugin(input, options)
},
}
@@ -2692,7 +2889,10 @@ async function live(auth) {
return { key: auth?.key, server: serverOf(auth) }
}
export async function DevinAuthPlugin({ client } = {}) {
export async function DevinAuthPlugin({ client, magpie } = {}, options = {}) {
// the cache keepalive: magpie's switch, or in OpenCode the plugin's
// option cacheKeepalive: true
const keepOn = () => magpie?.option?.(ID, KEEPALIVE) === true || options?.cacheKeepalive === true
return {
auth: {
provider: ID,
@@ -2719,9 +2919,19 @@ export async function DevinAuthPlugin({ client } = {}) {
} catch {
return (messages ? anthropicError : errorResponse)({ status: 400, message: "a request that isn't JSON" })
}
// a real request for a conversation stops its pings; its own
// reply starts them again
let keep
const on = keepOn()
if (!on) stopAllKeepalive()
else {
const id = keepaliveKey(chat, messages, init.headers ?? (input instanceof Request ? input.headers : undefined))
stopKeepalive(id)
keep = { id, ...keepaliveSettings(options) }
}
const { key, server } = await live(now)
const families = await familiesFor(key, server)
return (messages ? completeMessages : complete)({ key, server, families }, chat, init.signal)
return (messages ? completeMessages : complete)({ key, server, families, keep }, chat, init.signal)
},
}
},
@@ -2729,6 +2939,21 @@ export async function DevinAuthPlugin({ client } = {}) {
{ type: "oauth", label: "Devin (browser)", authorize: browserSignIn },
{ type: "oauth", label: "Devin CLI's sign-in", authorize: cliSignIn },
],
// magpie's own switches (OpenCode never reads auth.options)
options: [
{
key: KEEPALIVE,
label: "Keep the cache warm",
description: "Devin keeps a prompt cache for 5 minutes. When on, after a reply the conversation is sent again with max_tokens 1 every 285 s, up to 6 times, so a later turn reads the cache instead of writing it again. Each ping is billed as a cache read of the whole context.",
labels: { zh: "缓存保活", "zh-TW": "快取保活", ja: "キャッシュを保持", de: "Cache warm halten" },
descriptions: {
zh: "Devin 的提示词缓存只保留 5 分钟。开启后,每次回复结束会每 285 秒以 max_tokens 1 重发一次对话,最多 6 次,让之后的回合读取缓存而不是重写。每次保活都按整段上下文的缓存读取计费。",
"zh-TW": "Devin 的提示詞快取只保留 5 分鐘。開啟後,每次回覆結束會每 285 秒以 max_tokens 1 重送一次對話,最多 6 次,讓之後的回合讀取快取而不是重寫。每次保活都以整段上下文的快取讀取計費。",
ja: "Devin のプロンプトキャッシュは 5 分しか保持されません。オンにすると、返信のあと 285 秒ごとに会話を max_tokens 1 で再送し(最大 6 回)、次のターンがキャッシュを書き直さずに読めるようにします。各 ping はコンテキスト全体のキャッシュ読み取りとして課金されます。",
de: "Devin hält einen Prompt-Cache nur 5 Minuten. Ist dies an, wird das Gespräch nach einer Antwort alle 285 s mit max_tokens 1 erneut gesendet, bis zu 6-mal, damit eine spätere Runde den Cache liest, statt ihn neu zu schreiben. Jeder Ping wird als Cache-Lesen des ganzen Kontexts berechnet.",
},
},
],
// magpie's: the plan and how much of its quota is gone. The built-in
// read none, so no read marks the account or clears it, not even a
// key Devin turned away.
@@ -2798,4 +3023,4 @@ export async function DevinAuthPlugin({ client } = {}) {
}
// for tests
export const _internal = { buildMessages, completeMessages, anthropicEffort, encodeMsg, parseFree, parsePrices, geminiSchema, freeIDs, outID, inID, objectRoot, seesImages, imagesFor, forgetSaid: () => said.clear(), parseModelConfigs, parseConfigFamilies, SNAPSHOT_IMAGES, withImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoOfStatus, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames, v2Chat, v2ToolParts, v2FileData, v2Effort, v2ResponseFormat, v2Usage, v2Auth, v2Credential, v2Models, devinLanguage, v2Setup, connKey }
export const _internal = { keepaliveKey, keepaliveSettings, keepalivePing, scheduleKeepalive, stopKeepalive, stopAllKeepalive, keeping: () => [...keeps.keys()], useTimers: (t) => (timers = t ?? realTimers), KEEPALIVE, buildMessages, completeMessages, anthropicEffort, encodeMsg, parseFree, parsePrices, geminiSchema, freeIDs, outID, inID, objectRoot, seesImages, imagesFor, forgetSaid: () => said.clear(), parseModelConfigs, parseConfigFamilies, SNAPSHOT_IMAGES, withImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoOfStatus, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames, v2Chat, v2ToolParts, v2FileData, v2Effort, v2ResponseFormat, v2Usage, v2Auth, v2Credential, v2Models, devinLanguage, v2Setup, connKey }
+297
View File
@@ -0,0 +1,297 @@
// Devin's prompt cache lasts 5 minutes, with no longer TTL to ask for. The
// devin CLI keeps it warm (cache_keepalive.rs): after a reply it sends the
// same GetChatMessage again every 285 s with "continue" at the end and
// max_tokens 1. The plugin does the same when its switch is on (off by
// default), and stops on the conversation's next request, a refusal, two
// misses in a row or its most pings (plugins#592, zelong77).
import { afterEach, beforeEach, expect, test } from "bun:test"
import { readFileSync } from "node:fs"
import { join } from "node:path"
import { gunzipSync } from "node:zlib"
import { DevinAuthPlugin, _internal } from "./index.mjs"
const { PB, frame, fields, buildMessages, build, keepalivePing, keepaliveKey, KEEPALIVE } = _internal
const dec = new TextDecoder()
const enc = new TextEncoder()
const hex = (b) => Buffer.from(b ?? []).toString("hex")
const realFetch = globalThis.fetch
const configs = new Uint8Array(readFileSync(join(import.meta.dir, "testdata", "model-configs.bin")))
// fake timers: each set is held until the test fires it
let clock
const fakeTimers = () => {
const q = []
return {
q,
set(fn, ms) {
const t = { fn, ms, cleared: false, fired: false, unrefd: false, unref: () => (t.unrefd = true) }
q.push(t)
return t
},
clear(t) {
t.cleared = true
},
live: () => q.filter((t) => !t.cleared && !t.fired),
async fire() {
const [t] = q.filter((t) => !t.cleared && !t.fired)
if (!t) throw new Error("no timer to fire")
t.fired = true
await t.fn()
},
}
}
beforeEach(() => {
clock = fakeTimers()
_internal.useTimers(clock)
})
afterEach(() => {
_internal.stopAllKeepalive()
_internal.useTimers()
globalThis.fetch = realFetch
})
// unframe is a request's one message, gunzipped when it was
const unframe = (b) => {
const d = b.subarray(5)
return b[0] & 1 ? new Uint8Array(gunzipSync(d)) : d
}
const prompts = (msg) => fields(msg).filter((f) => f.num === 3)
const textOf = (p) => dec.decode(fields(p.data).find((g) => g.num === 3)?.data ?? new Uint8Array())
const isPing = (msg) => textOf(prompts(msg).at(-1)) === "continue"
const endFrame = (obj = {}) => {
const b = enc.encode(JSON.stringify(obj))
const out = new Uint8Array(5 + b.length)
out[0] = 2
new DataView(out.buffer).setUint32(1, b.length)
out.set(b, 5)
return out
}
// a reply of a word and its usage: input, cache write, cache read
const answer = ({ input = 10, write = 0, read = 0 } = {}) =>
new Response(new Blob([frame(new PB().str(3, "ok").varint(5, 1).bytes(7, new PB().varint(2, input).varint(3, 1).varint(4, write).varint(5, read)).done()), endFrame()]))
// devin fakes Devin: the model configs, each real request's answer (a cache
// write and read by default) and each ping's from pings, in turn
let sent, pings, real
const devin = () => {
sent = []
pings = []
real = () => answer({ write: 200, read: 9000 })
globalThis.fetch = async (url, init) => {
const u = String(url)
if (u.endsWith("/GetCliModelConfigs")) return new Response(configs)
if (!u.endsWith("/GetChatMessage")) return new Response("", { status: 404 })
const msg = unframe(init.body)
const ping = isPing(msg)
sent.push({ ping, msg })
if (!ping) return real()
const next = pings.shift() ?? (() => answer({ input: 3, read: 9200 }))
return next()
}
}
const pingsSent = () => sent.filter((s) => s.ping).length
const SERVER = "https://devin.test"
const auth = { type: "api", key: "k", metadata: { server: SERVER } }
// plugin is the loader's fetch with the switch on or off, and the plugin's
// options
const plugin = async (on, options) => {
const hooks = await DevinAuthPlugin({ magpie: { option: (p, k) => on && p === "devin" && k === KEEPALIVE } }, options)
const { fetch } = await hooks.auth.loader(async () => auth)
return async (chat, headers = {}) => {
const res = await fetch("https://server.codeium.com/devin/v1/chat/completions", { method: "POST", headers, body: JSON.stringify({ model: "swe-2", ...chat }) })
expect(res.status).toBe(200)
await res.text()
}
}
const lead = (...more) => ({ messages: [{ role: "system", content: "You are the lead." }, { role: "user", content: "fix the build" }, ...more] })
const sub = { messages: [{ role: "system", content: "You are an explore subagent." }, { role: "user", content: "find the test files" }] }
test("a ping is the request, byte for byte, with \"continue\" at the end and max_tokens 1", () => {
const mark = { type: "ephemeral" }
const req = {
model: "claude-haiku-5-5",
max_tokens: 32000,
system: [{ type: "text", text: "You are Claude Code.", cache_control: mark }],
tools: [{ name: "Read", description: "Reads a file.", input_schema: { type: "object", properties: { path: { type: "string" } } } }],
messages: [
{ role: "user", content: [{ type: "text", text: "read a", cache_control: mark }] },
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "Read", input: { path: "a" } }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "A", cache_control: mark }] },
],
}
for (const msg of [buildMessages(req, "claude-haiku-5-5", "k"), build({ model: "swe-2", max_tokens: 500, messages: [{ role: "user", content: "hi" }] }, "swe-2", "k")]) {
const ping = keepalivePing(msg)
const was = fields(msg)
const now = fields(ping)
const last = was.findLastIndex((f) => f.num === 3)
// every field as it was, the extra prompt after the last, field 8 apart
const shape = (fs) => fs.map((f) => [f.num, f.wire, f.num === 8 ? "" : f.wire === 0 ? f.n : hex(f.data)])
expect(shape(now)).toEqual(shape([...was.slice(0, last + 1), now[last + 1], ...was.slice(last + 1)]))
// the extra prompt is the user's "continue", unmarked
const extra = fields(now[last + 1].data)
expect(extra.find((g) => g.num === 2).n).toBe(1)
expect(dec.decode(extra.find((g) => g.num === 3).data)).toBe("continue")
expect(extra.some((g) => g.num === 8)).toBe(false)
// the sampling is the same but for max_tokens (field 2), now 1
const sampling = (fs) => fields(fs.find((f) => f.num === 8).data).map((g) => [g.num, g.wire === 0 ? g.n : hex(g.data)])
expect(sampling(now)).toEqual(sampling(was).map(([n, v]) => [n, n === 2 ? 1 : v]))
expect(sampling(now).find(([n]) => n === 2)[1]).toBe(1)
}
})
test("off by default: a reply schedules nothing", async () => {
devin()
const ask = await plugin(false)
await ask(lead())
expect(clock.q).toEqual([])
expect(_internal.keeping()).toEqual([])
})
test("after a reply, pings every 285 s on unref'd timers, up to 6, each the request again", async () => {
devin()
const ask = await plugin(true)
await ask(lead())
expect(clock.live().map((t) => [t.ms, t.unrefd])).toEqual([[285_000, true]])
// and they stop with the plugin host's process
expect(process.listeners("exit").some((fn) => fn.name === "stopAllKeepalive")).toBe(true)
for (let i = 1; i <= 6; i++) {
await clock.fire()
expect(pingsSent()).toBe(i)
}
// the sixth was the last
expect(clock.live()).toEqual([])
expect(_internal.keeping()).toEqual([])
// each ping is the real request's prompts and one more
const first = sent[0].msg
for (const s of sent.slice(1)) {
expect(prompts(s.msg).length).toBe(prompts(first).length + 1)
expect(prompts(s.msg).slice(0, -1).map((p) => hex(p.data))).toEqual(prompts(first).map((p) => hex(p.data)))
}
})
test("the interval and the most pings are the plugin's options", async () => {
devin()
const ask = await plugin(true, { cacheKeepaliveInterval: 120, cacheKeepaliveMaxPings: 2 })
await ask(lead())
expect(clock.live().map((t) => t.ms)).toEqual([120_000])
await clock.fire()
await clock.fire()
expect(pingsSent()).toBe(2)
expect(clock.live()).toEqual([])
// out of range is the default
expect(_internal.keepaliveSettings({ cacheKeepaliveInterval: 600, cacheKeepaliveMaxPings: 0 })).toEqual({ interval: 285_000, max: 6 })
})
test("the conversation's next request stops its pings, and its reply starts them again", async () => {
devin()
const ask = await plugin(true)
await ask(lead())
const [t1] = clock.live()
// stopped when the request comes, not only when its reply starts new ones
let stoppedBefore
real = () => ((stoppedBefore = t1.cleared), answer({ write: 300, read: 9000 }))
await ask(lead({ role: "assistant", content: "done" }, { role: "user", content: "thanks, now run the tests" }))
expect(stoppedBefore).toBe(true)
expect(t1.cleared).toBe(true)
expect(clock.live().length).toBe(1)
expect(_internal.keeping().length).toBe(1)
expect(pingsSent()).toBe(0)
})
test("a subagent's request doesn't stop its lead's pings, nor the lead's its", async () => {
devin()
const ask = await plugin(true)
const session = { "x-claude-code-session-id": "s1" }
await ask(lead(), session)
const [leadTimer] = clock.live()
await ask(sub, { ...session, "x-claude-code-agent-id": "a1" })
expect(leadTimer.cleared).toBe(false)
expect(clock.live().length).toBe(2)
const [, subTimer] = clock.live()
await ask(lead({ role: "assistant", content: "done" }, { role: "user", content: "next" }), session)
expect(leadTimer.cleared).toBe(true)
expect(subTimer.cleared).toBe(false)
// the same prefix under another agent id or session is another conversation
const chat = lead()
expect(keepaliveKey(chat, false, { "x-claude-code-agent-id": "a1" })).not.toBe(keepaliveKey(chat, false, { "x-claude-code-agent-id": "a2" }))
expect(keepaliveKey(chat, false, { "x-claude-code-session-id": "s1" })).not.toBe(keepaliveKey(chat, false, { "x-claude-code-session-id": "s2" }))
// and a turn's growing history, or a cache mark moving on, is the same one
const req = (mark) => ({ system: [{ type: "text", text: "S", cache_control: mark }], messages: [{ role: "user", content: [{ type: "text", text: "hi", cache_control: mark }] }] })
expect(keepaliveKey(req({ type: "ephemeral" }), true, {})).toBe(keepaliveKey({ ...req(undefined), messages: [...req(undefined).messages, { role: "assistant", content: "x" }] }, true, {}))
})
for (const [name, reply] of [
["a usage limit (429)", () => new Response(endFrame({ error: { code: "resource_exhausted", message: "rate limit" } }))],
["a refused key (401)", () => new Response(JSON.stringify({ code: "unauthenticated", message: "bad key" }), { status: 401 })],
["no credit (402)", () => new Response("", { status: 402 })],
]) {
test(`${name} stops the pings`, async () => {
devin()
const ask = await plugin(true)
await ask(lead())
pings.push(reply)
await clock.fire()
expect(pingsSent()).toBe(1)
expect(clock.live()).toEqual([])
expect(_internal.keeping()).toEqual([])
})
}
test("two pings in a row that read under half their prompt from the cache stop them; a hit between keeps them going", async () => {
devin()
const ask = await plugin(true)
await ask(lead())
const miss = () => answer({ input: 9000, write: 9000, read: 200 })
const hit = () => answer({ input: 3, read: 9200 })
pings.push(miss, hit, miss, miss)
await clock.fire() // miss
await clock.fire() // hit
await clock.fire() // miss
expect(clock.live().length).toBe(1)
await clock.fire() // miss again: stop
expect(pingsSent()).toBe(4)
expect(clock.live()).toEqual([])
expect(_internal.keeping()).toEqual([])
})
test("a reply that read and wrote nothing of the cache has nothing to keep", async () => {
devin()
real = () => answer({ input: 500 })
const ask = await plugin(true)
await ask(lead())
expect(clock.q).toEqual([])
})
test("turning the switch off stops every conversation's pings", async () => {
devin()
let on = true
const hooks = await DevinAuthPlugin({ magpie: { option: () => on } })
const { fetch } = await hooks.auth.loader(async () => auth)
const ask = (chat) => fetch("https://server.codeium.com/devin/v1/chat/completions", { method: "POST", body: JSON.stringify({ model: "swe-2", ...chat }) }).then((r) => r.text())
await ask(lead())
await ask(sub)
expect(clock.live().length).toBe(2)
on = false
await ask({ messages: [{ role: "user", content: "another conversation" }] })
expect(clock.live()).toEqual([])
expect(_internal.keeping()).toEqual([])
})
test("in OpenCode, the plugin's option cacheKeepalive turns it on", async () => {
devin()
const hooks = await DevinAuthPlugin({}, { cacheKeepalive: true })
const { fetch } = await hooks.auth.loader(async () => auth)
await (await fetch("https://server.codeium.com/devin/v1/chat/completions", { method: "POST", body: JSON.stringify({ model: "swe-2", ...lead() }) })).text()
expect(clock.live().length).toBe(1)
})
test("the switch says its words in magpie's languages, off by default", async () => {
const hooks = await DevinAuthPlugin({})
const o = hooks.auth.options.find((x) => x.key === KEEPALIVE)
expect(o.default).toBeUndefined()
expect(Object.keys(o.labels)).toEqual(["zh", "zh-TW", "ja", "de"])
expect(Object.keys(o.descriptions)).toEqual(["zh", "zh-TW", "ja", "de"])
for (const d of [o.description, ...Object.values(o.descriptions)]) expect(d.length).toBeLessThanOrEqual(300)
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-devin-auth",
"version": "0.1.29",
"version": "0.1.30",
"description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie",
"type": "module",
"main": "./index.mjs",