factory: each conversation is a Factory session of its own (0.1.48)
marovole on X: on Factory, Gemini 4 Argon, Hydrogen and Carbon answer
400 "Factory: Invalid model ID in request body" now and then. Success
and failure take turns within one conversation (Droid, v0.1.4404).
The plugin sent one x-session-id, a random UUID made when the plugin
loaded, on every request of its process. So every conversation, every
model and every subagent shared one Factory session. droid makes its
x-session-id per conversation (createProxyHeaders' sessionId in droid
1.14), and a subagent's Task gets a session of its own. Gemini is the
one route where droid locks the provider itself (getNextProvider with
lockedProvider "google"). A session that a Claude or GPT request opened
and that a Gemini request then joins is a state droid never sends.
x-session-id is now a v4 UUID hashed from the conversation magpie
names. A chat.headers hook is told the conversation (its session, else
the hash of its first message). If no hook runs (OpenCode 2), the
x-magpie-session or x-opencode-session header names it. Each subagent
(x-magpie-subagent) gets its own id. A request that names no
conversation keeps the process's id, as before. The header that carries
the conversation, x-magpie-factory-conversation, is taken off before the
request leaves.
Not proven: there is no Factory account here, so the refusal was not
reproduced against Factory itself. session.test.mjs reproduces it with a
fake Factory that holds a session to the provider it was opened with.
That is the hypothesis, not Factory's code. The feature flags droid's
registry puts on exactly these three models (Gemini4Argon/Hydrogen/
Carbon) are the other candidate. Nothing on magpie's side can change
those.
Run (mica, HOME=$(mktemp -d)):
- bun test packages/factory/session.test.mjs gemini.test.mjs: green.
- With session.test.mjs on the old index.mjs: all red. The fake answers
the Gemini conversation's requests 400 and the ids are shared.
- The root bun test and scripts/check.mjs: 9055 pass, 20 skip, 0 fail (9075 tests, 636 files); check.mjs ok.
Not changed: commandcode keeps one x-session-id for each process ("as
one CLI session has"); filed as plugins#1313. minimax already names
its session per conversation.
This commit is contained in:
@@ -4,6 +4,7 @@
|
|||||||
// built-in Factory account (internal/provider/factory*.go).
|
// built-in Factory account (internal/provider/factory*.go).
|
||||||
|
|
||||||
import { STATUS_CODES } from "node:http"
|
import { STATUS_CODES } from "node:http"
|
||||||
|
import { createHash } from "node:crypto"
|
||||||
import { readFileSync } from "node:fs"
|
import { readFileSync } from "node:fs"
|
||||||
import { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs"
|
import { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs"
|
||||||
|
|
||||||
@@ -1797,6 +1798,32 @@ function anthropicBody(body) {
|
|||||||
return changed ? JSON.stringify(request) : body
|
return changed ? JSON.stringify(request) : body
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CONVERSATION is the header the chat.headers hook below names the
|
||||||
|
// conversation in, for the loader's fetch to read and take off: it never
|
||||||
|
// reaches Factory.
|
||||||
|
const CONVERSATION = "x-magpie-factory-conversation"
|
||||||
|
|
||||||
|
// sessionId is the x-session-id droid sends for a conversation: droid opens
|
||||||
|
// one session per conversation, and a subagent's Task its own, so every
|
||||||
|
// request of one conversation says the same id and no two conversations
|
||||||
|
// share one. A UUID, as droid's are, made of a hash of the conversation
|
||||||
|
// magpie names (its session, else its first message's hash) and the
|
||||||
|
// subagent; fallback, this process's own, when magpie names none.
|
||||||
|
// One id for every request of the process put every conversation, model
|
||||||
|
// and subagent in one Factory session, which droid never does, and
|
||||||
|
// Factory's Gemini route answered a Gemini 4 model in such a session now
|
||||||
|
// and then with 400 "Invalid model ID in request body" (marovole on X).
|
||||||
|
function sessionId(conversation, subagent, fallback) {
|
||||||
|
conversation = String(conversation ?? "").trim().slice(0, 128)
|
||||||
|
if (!conversation) return fallback
|
||||||
|
subagent = String(subagent ?? "").trim().slice(0, 128)
|
||||||
|
const b = createHash("sha256").update("factory-session\0" + conversation + "\0" + subagent).digest().subarray(0, 16)
|
||||||
|
b[6] = (b[6] & 0x0f) | 0x40
|
||||||
|
b[8] = (b[8] & 0x3f) | 0x80
|
||||||
|
const x = b.toString("hex")
|
||||||
|
return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`
|
||||||
|
}
|
||||||
|
|
||||||
export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
||||||
// standardOnly is the user's STANDARD_ONLY as magpie has it now, read at
|
// standardOnly is the user's STANDARD_ONLY as magpie has it now, read at
|
||||||
// each usage reading so a change needs no restart; false outside magpie
|
// each usage reading so a change needs no restart; false outside magpie
|
||||||
@@ -1815,7 +1842,7 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
|||||||
}
|
}
|
||||||
return models
|
return models
|
||||||
}
|
}
|
||||||
// the session id this process's requests carry
|
// the session id a request that names no conversation carries
|
||||||
const session = crypto.randomUUID()
|
const session = crypto.randomUUID()
|
||||||
// serializes checking, rotating and saving tokens: WorkOS rotates the
|
// serializes checking, rotating and saving tokens: WorkOS rotates the
|
||||||
// refresh token, so two refreshes would spend it twice
|
// refresh token, so two refreshes would spend it twice
|
||||||
@@ -2031,6 +2058,15 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
// the conversation a request is of, as magpie tells the hook (its
|
||||||
|
// session, else its first message's hash), for the loader's fetch to
|
||||||
|
// name its x-session-id by (sessionId). Every plugin's hook sees every
|
||||||
|
// provider's requests, so it goes on Factory's alone.
|
||||||
|
"chat.headers": async (input, output) => {
|
||||||
|
const id = input?.model?.providerID ?? input?.provider?.info?.id
|
||||||
|
if (id !== PROVIDER || !input?.sessionID || !output?.headers) return
|
||||||
|
output.headers[CONVERSATION] = String(input.sessionID).slice(0, 128)
|
||||||
|
},
|
||||||
// magpie's list for this provider: the same models configModels gives
|
// magpie's list for this provider: the same models configModels gives
|
||||||
// OpenCode, each with the token multiplier droid shows it by, which
|
// OpenCode, each with the token multiplier droid shows it by, which
|
||||||
// magpie shows beside the model as its rate
|
// magpie shows beside the model as its rate
|
||||||
@@ -2134,6 +2170,10 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
|||||||
const to = llmBase(c)
|
const to = llmBase(c)
|
||||||
if (to !== API && url.startsWith(API)) url = to + url.slice(API.length)
|
if (to !== API && url.startsWith(API)) url = to + url.slice(API.length)
|
||||||
const h = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))
|
const h = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))
|
||||||
|
// the conversation the hook named, else the session magpie or
|
||||||
|
// OpenCode 2 (which has no chat.headers) names on the request
|
||||||
|
const conversation = h.get(CONVERSATION) || h.get("x-magpie-session") || h.get("x-opencode-session")
|
||||||
|
h.delete(CONVERSATION)
|
||||||
h.delete("x-api-key")
|
h.delete("x-api-key")
|
||||||
// the AI SDK's Google package's, with OpenCode's placeholder key
|
// the AI SDK's Google package's, with OpenCode's placeholder key
|
||||||
h.delete("x-goog-api-key")
|
h.delete("x-goog-api-key")
|
||||||
@@ -2148,7 +2188,7 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
|||||||
const model = byId.get(bodyModel(body))
|
const model = byId.get(bodyModel(body))
|
||||||
const upstream = model ? model.upstream : path.includes("/llm/o/") ? "openai" : "anthropic"
|
const upstream = model ? model.upstream : path.includes("/llm/o/") ? "openai" : "anthropic"
|
||||||
h.set("x-api-provider", upstream)
|
h.set("x-api-provider", upstream)
|
||||||
h.set("x-session-id", session)
|
h.set("x-session-id", sessionId(conversation, h.get("x-magpie-subagent"), session))
|
||||||
h.set("x-assistant-message-id", crypto.randomUUID())
|
h.set("x-assistant-message-id", crypto.randomUUID())
|
||||||
h.set("x-provider-routing-source", "registry_default")
|
h.set("x-provider-routing-source", "registry_default")
|
||||||
if (upstream === "openai") h.set("OpenAI-Platform", "org-bHuLtG1fGmYk5YaOihAAXFBw")
|
if (upstream === "openai") h.set("OpenAI-Platform", "org-bHuLtG1fGmYk5YaOihAAXFBw")
|
||||||
@@ -2231,4 +2271,4 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// for tests
|
// for tests
|
||||||
export const _internal = { STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
|
export const _internal = { CONVERSATION, sessionId, STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@magpie-community/opencode-factory-auth",
|
"name": "@magpie-community/opencode-factory-auth",
|
||||||
"version": "0.1.47",
|
"version": "0.1.48",
|
||||||
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./opencode.mjs",
|
"main": "./opencode.mjs",
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
// marovole on X: Gemini 4 models on Factory 400 "Invalid model ID in request
|
||||||
|
// body" now and then, success and failure taking turns in one conversation.
|
||||||
|
// The plugin said one x-session-id for every request of its process, so
|
||||||
|
// every conversation, model and subagent shared one Factory session. droid
|
||||||
|
// opens a session per conversation (createProxyHeaders' sessionId), and
|
||||||
|
// Factory's routing keeps a session on the provider it was opened with.
|
||||||
|
import { afterEach, expect, test } from "bun:test"
|
||||||
|
import { FactoryAuthPlugin, _internal } from "./index.mjs"
|
||||||
|
|
||||||
|
const real = globalThis.fetch
|
||||||
|
afterEach(() => (globalThis.fetch = real))
|
||||||
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
|
||||||
|
|
||||||
|
// a fake Factory that, as a session lock would, keeps each x-session-id on
|
||||||
|
// the provider its first request named and refuses a model of another one
|
||||||
|
async function loaded() {
|
||||||
|
const seen = []
|
||||||
|
const locked = new Map()
|
||||||
|
globalThis.fetch = async (url, init) => {
|
||||||
|
const h = new Headers(init.headers)
|
||||||
|
seen.push({ url: String(url), headers: h, body: init.body })
|
||||||
|
const s = h.get("x-session-id")
|
||||||
|
const p = h.get("x-api-provider")
|
||||||
|
if (!locked.has(s)) locked.set(s, p)
|
||||||
|
if (locked.get(s) !== p)
|
||||||
|
return new Response(JSON.stringify({ error: { message: "Factory: Invalid model ID in request body" } }), { status: 400, headers: { "content-type": "application/json" } })
|
||||||
|
return new Response('data: {"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]}}]}\n\n', { headers: { "content-type": "text/event-stream" } })
|
||||||
|
}
|
||||||
|
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||||
|
const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "factory-token", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A" }))
|
||||||
|
// what magpie's host does for a request: the chat.headers hooks are told
|
||||||
|
// the conversation, and the headers they set reach the loader's fetch
|
||||||
|
const ask = async (conversation, url, body, extra = {}, providerID = "factory") => {
|
||||||
|
const out = { headers: {} }
|
||||||
|
await hooks["chat.headers"]?.({ sessionID: conversation, model: { providerID } }, out)
|
||||||
|
return l.fetch(url, { method: "POST", headers: { "content-type": "application/json", ...out.headers, ...extra }, body: JSON.stringify(body) })
|
||||||
|
}
|
||||||
|
return { ask, seen, hooks }
|
||||||
|
}
|
||||||
|
|
||||||
|
const gemini = "https://api.factory.ai/api/llm/g/v1/models/gemini-4-argon:streamGenerateContent?alt=sse"
|
||||||
|
const claude = "https://api.factory.ai/api/llm/a/v1/messages"
|
||||||
|
const gBody = { contents: [{ role: "user", parts: [{ text: "hi" }] }] }
|
||||||
|
const cBody = { model: "claude-opus-5-5", max_tokens: 16, messages: [{ role: "user", content: "hi" }] }
|
||||||
|
|
||||||
|
test("a Gemini conversation beside a Claude one isn't refused: each conversation is its own Factory session", async () => {
|
||||||
|
const { ask, seen } = await loaded()
|
||||||
|
const results = []
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
results.push((await ask("magpie-aaaaaaaaaaaaaaaaaaaaaaaa", claude, cBody)).status)
|
||||||
|
results.push((await ask("magpie-bbbbbbbbbbbbbbbbbbbbbbbb", gemini, gBody)).status)
|
||||||
|
}
|
||||||
|
expect(results).toEqual([200, 200, 200, 200, 200, 200])
|
||||||
|
const ids = seen.map((s) => s.headers.get("x-session-id"))
|
||||||
|
for (const id of ids) expect(id).toMatch(UUID)
|
||||||
|
// one conversation keeps its id, two never share one
|
||||||
|
expect(new Set(ids.filter((_, i) => i % 2 === 0)).size).toBe(1)
|
||||||
|
expect(new Set(ids.filter((_, i) => i % 2 === 1)).size).toBe(1)
|
||||||
|
expect(ids[0]).not.toBe(ids[1])
|
||||||
|
// the header that carried the conversation never reaches Factory
|
||||||
|
for (const s of seen) expect(s.headers.get(_internal.CONVERSATION)).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
test("a subagent is a session of its own, the same one on each of its requests", async () => {
|
||||||
|
const { ask, seen } = await loaded()
|
||||||
|
await ask("s1", gemini, gBody)
|
||||||
|
await ask("s1", gemini, gBody, { "x-magpie-subagent": "agent-1" })
|
||||||
|
await ask("s1", gemini, gBody, { "x-magpie-subagent": "agent-1" })
|
||||||
|
const ids = seen.map((s) => s.headers.get("x-session-id"))
|
||||||
|
expect(ids[0]).not.toBe(ids[1])
|
||||||
|
expect(ids[1]).toBe(ids[2])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("another provider's request names no conversation, and one with none keeps the process's session", async () => {
|
||||||
|
const { hooks, ask, seen } = await loaded()
|
||||||
|
const out = { headers: {} }
|
||||||
|
await hooks["chat.headers"]({ sessionID: "s1", model: { providerID: "cursor" } }, out)
|
||||||
|
expect(out.headers).toEqual({})
|
||||||
|
await ask("", gemini, gBody)
|
||||||
|
await ask("", gemini, gBody)
|
||||||
|
const ids = seen.map((s) => s.headers.get("x-session-id"))
|
||||||
|
expect(ids[0]).toMatch(UUID)
|
||||||
|
expect(ids[0]).toBe(ids[1])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("sessionId is a stable v4 UUID of the conversation and subagent", () => {
|
||||||
|
const { sessionId } = _internal
|
||||||
|
expect(sessionId("s1", "", "fb")).toMatch(UUID)
|
||||||
|
expect(sessionId("s1", "", "fb")).toBe(sessionId("s1", undefined, "fb"))
|
||||||
|
expect(sessionId("s1", "", "fb")).not.toBe(sessionId("s2", "", "fb"))
|
||||||
|
expect(sessionId("s1", "a", "fb")).not.toBe(sessionId("s1", "", "fb"))
|
||||||
|
expect(sessionId("", "a", "fb")).toBe("fb")
|
||||||
|
expect(sessionId(" ", "", "fb")).toBe("fb")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("with no hook (OpenCode 2), the session magpie or OpenCode names on the request names the Factory session", async () => {
|
||||||
|
const { l, seen } = await (async () => {
|
||||||
|
const seen = []
|
||||||
|
globalThis.fetch = async (url, init) => (seen.push(new Headers(init.headers)), new Response("data: {}\n\n", { headers: { "content-type": "text/event-stream" } }))
|
||||||
|
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||||
|
return { l: await hooks.auth.loader(async () => ({ type: "oauth", access: "t", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A" })), seen }
|
||||||
|
})()
|
||||||
|
const go = (headers) => l.fetch(gemini, { method: "POST", headers, body: JSON.stringify(gBody) })
|
||||||
|
await go({ "x-magpie-session": "s1" })
|
||||||
|
await go({ "x-opencode-session": "s1" })
|
||||||
|
await go({ "x-magpie-session": "s2" })
|
||||||
|
const ids = seen.map((h) => h.get("x-session-id"))
|
||||||
|
expect(ids[0]).toBe(_internal.sessionId("s1", "", ""))
|
||||||
|
expect(ids[1]).toBe(ids[0])
|
||||||
|
expect(ids[2]).not.toBe(ids[0])
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user