cline: reuse task ID per chat session for prompt caching (#69)
* cline: preserve ClinePass prompt cache across requests * cline: limit task ID omission to affected models * cline: reuse one task ID per chat session
This commit is contained in:
@@ -43,10 +43,14 @@ workos:<access token>` for a signed-in account or the raw API key, and the
|
||||
full client-identity header set Cline's own clients send (`HTTP-Referer`,
|
||||
`X-Title`, `User-Agent: Cline/<version>`, `X-CLIENT-TYPE: cline-cli`,
|
||||
`X-CLIENT-VERSION`, `X-PLATFORM`, `X-PLATFORM-VERSION`, `X-CORE-VERSION`,
|
||||
`X-IS-MULTIROOT`, and a per-task `X-Task-ID`) — pinned to Cline's current CLI
|
||||
release, which is also what the free models' gate reads; when Cline ships a
|
||||
new release, move the pinned numbers in `index.mjs` along. Auth and account
|
||||
requests carry the same identity. A finished non-streaming answer rides in a
|
||||
`X-IS-MULTIROOT`) — pinned to Cline's current CLI release, which is also
|
||||
what the free models' gate reads; when Cline ships a new release, move the
|
||||
pinned numbers in `index.mjs` along. All models use one `X-Task-ID` per
|
||||
named chat session, derived as a UUID from the session. With no named session
|
||||
(including magpie's synthetic id from the first user message), no task id
|
||||
is sent. The session crosses the plugin's hooks in a private header that is
|
||||
removed before the request goes to Cline. Auth and account requests carry
|
||||
the same identity. A finished non-streaming answer rides in a
|
||||
`{"data": …}` envelope the official clients take apart; the plugin takes it
|
||||
apart too. The model list is read from
|
||||
`/api/v1/ai/cline/recommended-models` and `/api/v1/ai/cline/models` (neither
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// and cloud-models feeds; usage reads the account's credit balance and, on
|
||||
// ClinePass, the plan's 5-hour, weekly and monthly limits.
|
||||
import { STATUS_CODES } from "node:http"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { createHash } from "node:crypto"
|
||||
|
||||
const PROVIDER = "cline"
|
||||
const API = "https://api.cline.bot/api/v1"
|
||||
@@ -37,9 +37,29 @@ const DEVICE_CAP = 600 // seconds the browser may take, however long the code li
|
||||
// only thing that has to match).
|
||||
const CLIENT = { type: "cline-cli", version: "3.0.68", platform: "cli", core: "0.0.90" }
|
||||
|
||||
// Pass the host's session through the chat.headers hook to the loader's
|
||||
// fetch. This private header never leaves the plugin.
|
||||
const SESSION = "x-magpie-cline-session"
|
||||
|
||||
// magpie's synthetic session from the first user message doesn't identify a
|
||||
// task: unrelated conversations can start with that same message.
|
||||
function sessionOf(input) {
|
||||
const s = String(input?.sessionID ?? "").trim()
|
||||
if (!s || /^magpie-[0-9a-f]{24}$/.test(s)) return ""
|
||||
return s.slice(0, 128)
|
||||
}
|
||||
|
||||
function taskIdOf(session) {
|
||||
const bytes = createHash("sha256").update("cline task\0").update(session).digest().subarray(0, 16)
|
||||
const b = Buffer.from(bytes)
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
const h = b.toString("hex")
|
||||
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`
|
||||
}
|
||||
|
||||
// clientHeaders is the header set resolveProviderRequestHeaders builds for a
|
||||
// client with that identity; a task id rides per chat request, as the
|
||||
// official clients ride one per task
|
||||
// client with that identity; official clients supply a task id per task.
|
||||
function clientHeaders(taskId) {
|
||||
return {
|
||||
"HTTP-Referer": "https://cline.bot",
|
||||
@@ -867,6 +887,11 @@ export const ClinePlugin = async ({ client } = {}, options = {}) => {
|
||||
}
|
||||
|
||||
return {
|
||||
async "chat.headers"(input, output) {
|
||||
if (input?.model?.providerID !== PROVIDER && input?.provider?.info?.id !== PROVIDER) return
|
||||
const session = sessionOf(input)
|
||||
if (session) output.headers[SESSION] = session
|
||||
},
|
||||
config: async (cfg) => {
|
||||
cfg.provider ??= {}
|
||||
const was = cfg.provider[PROVIDER] ?? {}
|
||||
@@ -945,10 +970,11 @@ export const ClinePlugin = async ({ client } = {}, options = {}) => {
|
||||
return signedInError(e)
|
||||
}
|
||||
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))
|
||||
const session = headers.get(SESSION)
|
||||
headers.delete(SESSION)
|
||||
headers.delete("X-Task-ID")
|
||||
headers.set("Authorization", `Bearer ${cred.bearer}`)
|
||||
// the request says who it comes from, headers down, exactly as
|
||||
// Cline's own client does — and rides its own task id
|
||||
for (const [k, v] of Object.entries(clientHeaders(randomUUID()))) headers.set(k, v)
|
||||
for (const [k, v] of Object.entries(clientHeaders(session ? taskIdOf(session) : undefined))) headers.set(k, v)
|
||||
headers.delete("content-length")
|
||||
headers.delete("host")
|
||||
let res
|
||||
|
||||
@@ -151,10 +151,38 @@ test("an API-key account signs requests with the raw key", async () => {
|
||||
expect(calls[0].init.headers.get("User-Agent")).toBe(`Cline/${CLIENT.version}`)
|
||||
expect(calls[0].init.headers.get("HTTP-Referer")).toBe("https://cline.bot")
|
||||
expect(calls[0].init.headers.get("X-Title")).toBe("Cline")
|
||||
expect(calls[0].init.headers.get("X-Task-ID")).toBeTruthy()
|
||||
expect(calls[0].init.headers.get("X-Task-ID")).toBeNull()
|
||||
expect(await res.json()).toEqual({ ok: true })
|
||||
})
|
||||
|
||||
test("one task id per named session, no task id without one, and no private header upstream", async () => {
|
||||
const { client: c } = client()
|
||||
const hooks = await ClinePlugin({ client: c })
|
||||
serve(Array.from({ length: 6 }, () => [chatUrl, () => Response.json({ ok: true })]))
|
||||
const l = await hooks.auth.loader(async () => ({ type: "api", key: "ck" }))
|
||||
const send = async (sessionID, model = "cline-pass/deepseek-v4.1-flash") => {
|
||||
const out = { headers: {} }
|
||||
await hooks["chat.headers"]({ sessionID, model: { providerID: "cline" }, provider: { info: { id: "cline" } } }, out)
|
||||
const headers = new Headers(out.headers)
|
||||
headers.set("X-Task-ID", "stale-id")
|
||||
const res = await l.fetch(chatUrl, { ...chatInit({ model }), headers })
|
||||
expect(res.status).toBe(200)
|
||||
const upstream = calls.at(-1).init.headers
|
||||
expect(upstream.get("x-magpie-cline-session")).toBeNull()
|
||||
return upstream.get("X-Task-ID")
|
||||
}
|
||||
const first = await send("session-one")
|
||||
expect(first).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
|
||||
expect(await send("session-one")).toBe(first)
|
||||
expect(await send("session-one", "moonshotai/kimi-k3")).toBe(first)
|
||||
expect(await send("session-two")).not.toBe(first)
|
||||
expect(await send("")).toBeNull()
|
||||
expect(await send("magpie-0123456789abcdef01234567")).toBeNull()
|
||||
const out = { headers: {} }
|
||||
await hooks["chat.headers"]({ sessionID: "session-one", model: { providerID: "other" }, provider: { info: { id: "other" } } }, out)
|
||||
expect(out.headers).toEqual({})
|
||||
})
|
||||
|
||||
test("clientHeaders is the official client's set, task id only when asked", () => {
|
||||
const h = clientHeaders()
|
||||
// the numbers are what has to match: the CLI release, and the @cline/core
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-cline-auth",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"description": "Cline (cline.bot) on your own account — usage billing, ClinePass and the free models — in OpenCode and magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user