diff --git a/packages/zed/README.md b/packages/zed/README.md index 2fd3ed9..57d5bc4 100644 --- a/packages/zed/README.md +++ b/packages/zed/README.md @@ -64,6 +64,13 @@ GitHub login. | x_ai | `@ai-sdk/openai-compatible` | chat completions | | google | `@ai-sdk/google` | generateContent | +- **Thread and prompt:** like Zed's editor, each request names its + `thread_id` and `prompt_id`. The thread comes from the conversation's + session (or, without one, its first user message), so every turn of one + conversation is one thread. The prompt changes with each message the user + sends and stays the same through the tool calls that answer it. Both are + UUIDs hashed with a per-process salt, so they name nothing they were made + from. - **Request changes, as magpie makes them:** - Anthropic: the request loses `stream`, since the cloud always streams. Every `tool_result` gets `is_error` (Zed's cloud refuses one without it). diff --git a/packages/zed/index.mjs b/packages/zed/index.mjs index afa6f24..a10008d 100644 --- a/packages/zed/index.mjs +++ b/packages/zed/index.mjs @@ -546,6 +546,86 @@ async function bodyText(body) { return await new Response(body).text() } +// ---- the thread a request belongs to ---------------------------------------------- +// +// Zed's editor names every completion's thread and prompt: CompletionBody's +// thread_id is the agent thread's id (a UUID made once per thread) and +// prompt_id one made again for each message the user sends, the same +// through the tool calls that answer it (zed crates/cloud_llm_client +// CompletionBody, crates/agent thread.rs build_completion_request and +// advance_prompt_id). The plugin sent neither, so to Zed's cloud every +// request was a thread of its own; a Gemini 4 Argon conversation of 180k to +// 230k tokens read no cache on any of 11 requests (plugins#731), where Zed +// bills Argon's implicit cache hits for its own editor's threads. +// +// SESSION carries the conversation magpie (or OpenCode) names a request by, +// from the chat.headers hook to the loader's fetch. It goes no further. +const SESSION = "x-magpie-zed-session" + +// SALT is what the ids are derived with, so they say nothing of the session +// or the words they were made from. New in each process. +const SALT = crypto.randomBytes(16).toString("hex") + +// uuidOf is a version 4 UUID made of a hash's first 16 bytes: the shape of +// the ids Zed's editor sends. +function uuidOf(s) { + const b = Buffer.from(crypto.createHash("sha256").update(SALT + "|" + s).digest().subarray(0, 16)) + 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)}` +} + +// textOf is the words a message's content says: a string, or its text parts +// (Anthropic's and Chat's text blocks, Responses' input_text, Gemini's +// parts). Tool results, images and calls say none. +function textOf(content) { + if (typeof content === "string") return content + if (!Array.isArray(content)) return "" + return content + .map((p) => (p && typeof p === "object" && typeof p.text === "string" && !p.thought && p.type !== "tool_result" ? p.text : "")) + .join("") +} + +// prompts is what each message the user wrote says, in order, in the +// request's own API: a turn carrying only tool results (Anthropic's user +// turn of tool_result blocks, Gemini's functionResponse parts, Chat's tool +// role, Responses' function_call_output) is the answer to a call, not a +// message the user sent. +function prompts(wire, req) { + let turns = [] + if (wire === "gemini") turns = (Array.isArray(req.contents) ? req.contents : []).filter((c) => (c?.role ?? "user") === "user").map((c) => textOf(c.parts)) + else if (wire === "responses") { + if (typeof req.input === "string") turns = [req.input] + else turns = (Array.isArray(req.input) ? req.input : []).filter((m) => m?.role === "user" && (m.type ?? "message") === "message").map((m) => textOf(m.content)) + } else turns = (Array.isArray(req.messages) ? req.messages : []).filter((m) => m?.role === "user").map((m) => textOf(m.content)) + return turns.filter((t) => t.trim()) +} + +// threadOf is the request's thread_id and prompt_id, as Zed's editor sends +// them: the thread from the session magpie (or OpenCode) names, else from the +// conversation's first user message, which every later turn repeats; the +// prompt from the thread and how many messages the user has sent in it, so +// the tool calls answering one message share its prompt_id and the next +// message gets a new one. The account (its user id) is part of both, so one +// conversation two accounts answer is a thread of each's own. {} when the +// request names neither a session nor a user message. +function threadOf(wire, req, session, who) { + const said = prompts(wire, req) + const key = session ? "session|" + session : said.length ? "first|" + said[0] : "" + if (!key) return {} + const thread = uuidOf("zed-thread|" + who + "|" + key) + return { thread_id: thread, prompt_id: uuidOf("zed-prompt|" + thread + "|" + said.length) } +} + +// sessionOf takes the session a chat.headers hook named off the headers, +// with the header: it goes no further than here. +function sessionOf(headers) { + if (!headers) return "" + const h = new Headers(headers) + return String(h.get(SESSION) ?? "").trim().slice(0, 128) +} + // wireOf is the API a request was written in, from the path the AI SDK // sent it to, and the model named in a Gemini path. function wireOf(url) { @@ -1122,8 +1202,10 @@ async function complete(s, url, init) { if (!req || typeof req !== "object") return errorResponse(w.wire, 400, "an unreadable request") const id = w.model ?? String(req.model ?? "") const vendor = vendors.get(id) ?? WIRE_VENDOR[w.wire] + // read before providerRequest moves anything: the turns as the caller wrote them + const ids = threadOf(w.wire, req, sessionOf(init?.headers), s.userId ?? "") const { req: pr, stream = w.stream } = providerRequest(w.wire, req, id) - const body = JSON.stringify({ provider: vendor, model: id, provider_request: pr }) + const body = JSON.stringify({ ...ids, provider: vendor, model: id, provider_request: pr }) let res let renewed = false let moved = false @@ -1252,6 +1334,13 @@ export async function ZedAuthPlugin({ client } = {}) { models: { ...Object.fromEntries(MODELS.map((m) => [m.id, entry(m)])), ...(was.models ?? {}) }, } }, + // the conversation a request belongs to, for the fetch below to name + // its thread by as Zed's editor does (threadOf). Zed's requests only. + "chat.headers": async (input, output) => { + const id = input?.model?.providerID ?? input?.provider?.info?.id + if (id !== PROVIDER || !input?.sessionID || !output?.headers) return + output.headers[SESSION] = String(input.sessionID).slice(0, 128) + }, provider: { id: PROVIDER, // the models the account may call, as Zed's /models lists them now @@ -1299,7 +1388,7 @@ export async function ZedAuthPlugin({ client } = {}) { if (!s) throw new Error("not signed in to Zed") s.save = save const url = input instanceof Request ? input.url : String(input) - if (input instanceof Request) init = { method: input.method, body: await input.text(), signal: input.signal, ...init } + if (input instanceof Request) init = { method: input.method, headers: input.headers, body: await input.text(), signal: input.signal, ...init } return complete(s, url, init) }, } @@ -1313,4 +1402,4 @@ export async function ZedAuthPlugin({ client } = {}) { } // for tests -export const _internal = { said, eventError, stateOf, parseModels, entry, model, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, planOf, picked, who, planName, usage } +export const _internal = { said, eventError, stateOf, parseModels, entry, model, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, planOf, picked, who, planName, usage, threadOf, prompts, SESSION } diff --git a/packages/zed/package.json b/packages/zed/package.json index efb23fc..ecf4ef1 100644 --- a/packages/zed/package.json +++ b/packages/zed/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zed-auth", - "version": "0.1.17", + "version": "0.1.18", "description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie", "type": "module", "main": "./opencode.mjs", diff --git a/packages/zed/thread-id.test.mjs b/packages/zed/thread-id.test.mjs new file mode 100644 index 0000000..42a832d --- /dev/null +++ b/packages/zed/thread-id.test.mjs @@ -0,0 +1,158 @@ +// Zed's editor names each completion's thread and prompt in CompletionBody: +// thread_id once per agent thread, prompt_id again for each message the +// user sends (zed crates/cloud_llm_client CompletionBody; crates/agent +// thread.rs). The plugin sent neither, so every request was a thread of its +// own to Zed's cloud, and a Gemini 4 Argon conversation read no cache on 11 +// requests of 180k to 230k tokens (plugins#731). +import { afterEach, expect, test } from "bun:test" +import { ZedAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.tokens.clear() +}) + +const s = { userId: "4242", access: "plain-access", systemId: "", org: "org-me", plan: "zed_pro", who: "octo" } +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +// sent is the CompletionBody the plugin hands Zed for a request to path. +async function sent(path, body, headers, who = s) { + let got + globalThis.fetch = async (url, init) => { + const p = new URL(String(url)).pathname + if (p === "/client/llm_tokens") return Response.json({ token: "llm-token" }) + if (p === "/completions") { + got = JSON.parse(init.body) + return new Response(JSON.stringify({ status: "stream_ended" }) + "\n", { headers: { "x-zed-server-supports-status-messages": "true" } }) + } + return new Response("", { status: 404 }) + } + const res = await _internal.complete(who, "https://cloud.zed.dev" + path, { method: "POST", headers, body: JSON.stringify(body) }) + await res.text().catch(() => {}) + return got +} + +const ARGON = "/v1beta/models/gemini-4-argon:streamGenerateContent" +const call = { functionCall: { name: "read", args: { path: "a.go" } } } +const answer = { functionResponse: { name: "read", response: { content: "package a" } } } +const turns = { + first: [{ role: "user", parts: [{ text: "read a.go" }] }], + toolRound: [{ role: "user", parts: [{ text: "read a.go" }] }, { role: "model", parts: [call] }, { role: "user", parts: [answer] }], + next: [{ role: "user", parts: [{ text: "read a.go" }] }, { role: "model", parts: [call] }, { role: "user", parts: [answer] }, { role: "model", parts: [{ text: "done" }] }, { role: "user", parts: [{ text: "now b.go" }] }], +} +const gemini = (contents) => ({ contents, systemInstruction: { parts: [{ text: "You are a coding agent." }] } }) + +test("a Gemini conversation keeps one thread_id, and a new prompt_id only for a message the user sends", async () => { + const h = { [_internal.SESSION]: "ses_abc" } + const a = await sent(ARGON, gemini(turns.first), h) + const b = await sent(ARGON, gemini(turns.toolRound), h) + const c = await sent(ARGON, gemini(turns.next), h) + expect(a.thread_id).toMatch(UUID) + expect(a.prompt_id).toMatch(UUID) + expect(b.thread_id).toBe(a.thread_id) + expect(c.thread_id).toBe(a.thread_id) + // the tool call's answer is the same prompt, as in Zed's editor + expect(b.prompt_id).toBe(a.prompt_id) + expect(c.prompt_id).not.toBe(a.prompt_id) + expect(c.provider).toBe("google") + expect(c.model).toBe("gemini-4-argon") +}) + +test("the session header goes no further than the plugin, and names nothing it was made from", async () => { + const got = await sent(ARGON, gemini(turns.first), { [_internal.SESSION]: "ses_abc" }) + const text = JSON.stringify(got) + expect(text).not.toContain("ses_abc") + expect(text).not.toContain(_internal.SESSION) + expect(text).not.toContain("4242") +}) + +test("two sessions, or two accounts, are two threads", async () => { + const a = await sent(ARGON, gemini(turns.first), { [_internal.SESSION]: "ses_abc" }) + const b = await sent(ARGON, gemini(turns.first), { [_internal.SESSION]: "ses_xyz" }) + const c = await sent(ARGON, gemini(turns.first), { [_internal.SESSION]: "ses_abc" }, { ...s, userId: "777" }) + expect(b.thread_id).not.toBe(a.thread_id) + expect(c.thread_id).not.toBe(a.thread_id) +}) + +test("with no session, the first message the user sent names the thread", async () => { + const a = await sent(ARGON, gemini(turns.first)) + const c = await sent(ARGON, gemini(turns.next)) + expect(a.thread_id).toMatch(UUID) + expect(c.thread_id).toBe(a.thread_id) + expect(c.prompt_id).not.toBe(a.prompt_id) +}) + +test("every API's tool round shares its prompt, and the next message gets a new one", async () => { + const anthropic = (m) => ({ model: "claude-sonnet-5", max_tokens: 100, stream: true, messages: m }) + const chat = (m) => ({ model: "gpt-5", stream: true, messages: m }) + const responses = (m) => ({ model: "gpt-5", stream: true, input: m }) + const cases = [ + [ + "/v1/messages", + anthropic([{ role: "user", content: "read a.go" }]), + anthropic([{ role: "user", content: "read a.go" }, { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Read", input: {} }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: [{ type: "text", text: "package a" }] }] }]), + anthropic([{ role: "user", content: "read a.go" }, { role: "assistant", content: "ok" }, { role: "user", content: [{ type: "text", text: "now b.go" }] }]), + ], + [ + "/v1/chat/completions", + chat([{ role: "user", content: "read a.go" }]), + chat([{ role: "user", content: "read a.go" }, { role: "assistant", tool_calls: [{ id: "t1", type: "function", function: { name: "read", arguments: "{}" } }] }, { role: "tool", tool_call_id: "t1", content: "package a" }]), + chat([{ role: "user", content: "read a.go" }, { role: "assistant", content: "ok" }, { role: "user", content: [{ type: "text", text: "now b.go" }] }]), + ], + [ + "/v1/responses", + responses([{ role: "user", content: [{ type: "input_text", text: "read a.go" }] }]), + responses([{ role: "user", content: [{ type: "input_text", text: "read a.go" }] }, { type: "function_call", call_id: "t1", name: "read", arguments: "{}" }, { type: "function_call_output", call_id: "t1", output: "package a" }]), + responses([{ role: "user", content: [{ type: "input_text", text: "read a.go" }] }, { role: "assistant", content: [{ type: "output_text", text: "ok" }] }, { role: "user", content: [{ type: "input_text", text: "now b.go" }] }]), + ], + ] + for (const [path, first, round, next] of cases) { + const h = { [_internal.SESSION]: "ses_" + path } + const a = await sent(path, first, h) + const b = await sent(path, round, h) + const c = await sent(path, next, h) + expect([path, a.thread_id]).toEqual([path, expect.stringMatching(UUID)]) + expect([path, b.thread_id, c.thread_id]).toEqual([path, a.thread_id, a.thread_id]) + expect([path, b.prompt_id]).toEqual([path, a.prompt_id]) + expect([path, c.prompt_id === a.prompt_id]).toEqual([path, false]) + } +}) + +test("chat.headers names Zed's requests' session, and no other provider's", async () => { + const p = await ZedAuthPlugin({}) + const out = { headers: {} } + await p["chat.headers"]({ sessionID: "ses_abc", model: { providerID: "zed", id: "gemini-4-argon" } }, out) + expect(out.headers[_internal.SESSION]).toBe("ses_abc") + const other = { headers: {} } + await p["chat.headers"]({ sessionID: "ses_abc", model: { providerID: "anthropic", id: "claude-sonnet-5" } }, other) + expect(other.headers).toEqual({}) +}) + +test("the loader's fetch keeps a Request's headers, the session among them", async () => { + let got + globalThis.fetch = async (url, init) => { + const p = new URL(String(url)).pathname + if (p === "/client/llm_tokens") return Response.json({ token: "llm-token" }) + if (p === "/completions") { + got = JSON.parse(init.body) + return new Response(JSON.stringify({ status: "stream_ended" }) + "\n", { headers: { "x-zed-server-supports-status-messages": "true" } }) + } + return new Response("", { status: 404 }) + } + const auth = { type: "oauth", refresh: JSON.stringify({ userId: "4242", access: "plain-access" }), access: "plain-access", expires: Date.now() + 3600e3 } + const p = await ZedAuthPlugin({}) + const sdk = await p.auth.loader(async () => auth) + expect(typeof sdk.fetch).toBe("function") + const one = async (contents) => { + const req = new Request("https://cloud.zed.dev" + ARGON, { method: "POST", headers: { [_internal.SESSION]: "ses_abc" }, body: JSON.stringify(gemini(contents)) }) + const res = await sdk.fetch(req) + await res.text().catch(() => {}) + return got + } + const a = await one(turns.first) + const b = await one([{ role: "user", parts: [{ text: "something else entirely" }] }]) + // the same session, though the first message differs: the header was read + expect(a.thread_id).toMatch(UUID) + expect(b.thread_id).toBe(a.thread_id) +})