factory: adapt Claude Code's standalone model-switch system updates (#9)

After /model, Claude Code 2.1.287 sends a separate string-content system message that opens with the new model paragraph and carries <total_tokens> metadata but no environment block; Factory refused it with 403, so continuing a conversation after a model switch failed. systemContext now also adapts that shape: only when the message starts with the model paragraph and has a complete generated <total_tokens>N tokens left</total_tokens> paragraph, it rewrites each whole model paragraph (named or not, routing-group ids, accumulated switches) to Current model / Model ID / Model knowledge cutoff, leaving every other byte, role and order as sent; inference and count_tokens share it, and a second pass is byte-identical. Tests cover accumulated switches across both endpoints with idempotence, and pass-through for incomplete markers, quoted text, array content and non-system roles. Factory bumped to 0.1.9.
This commit is contained in:
XIQI
2026-10-02 23:22:21 +08:00
committed by GitHub
parent ef81d34320
commit d7d8d61c42
4 changed files with 80 additions and 9 deletions
+5
View File
@@ -90,6 +90,11 @@ Claude 5 can send runtime metadata in string-content `system` messages
instead of user-message reminders. The plugin adapts the known environment,
model and configuration-skill metadata in that shape too, preserving the
message role, environment values and session instructions.
After `/model` switches, Claude Code can send model-only system updates
without the initial environment paragraph. Updates beginning with the known
model paragraph and containing complete generated token metadata are
adapted too, including accumulated switches when resuming a conversation.
Token budgets, permission instructions and conversation history are preserved.
Use magpie's Claude Code integration to select the Factory provider.
magpie manages the provider-specific client settings, including capability
+14 -8
View File
@@ -591,18 +591,24 @@ const CONFIG_SKILL_COMPAT = CONFIG_SKILL_METADATA.replace("not Claude", "not the
// Claude 5 also sends its runtime metadata as a string-content system
// message, instead of user-message reminders. Preserve that role and all
// instructions; only the known environment paragraph opens this adapter.
// instructions. A model switch sends a separate update without the
// environment paragraph; require its opening model paragraph and complete
// generated token context before adapting that shape.
const SYSTEM_ENV_CONTEXT = /^# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/g
const SYSTEM_MODEL_UPDATE = /^You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/
const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_tokens>(?=\n\n|$)/
function systemContext(text) {
if (!SYSTEM_ENV_CONTEXT.test(text)) return text
let out = text.replace("# Environment", "# Runtime context")
const environment = SYSTEM_ENV_CONTEXT.test(text)
if (!environment && !(SYSTEM_MODEL_UPDATE.test(text) && SYSTEM_TOKEN_CONTEXT.test(text))) return text
let out = text.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
.replace("You are powered by the model named", "Current model name:")
.replace("You are powered by the model", "Current model:")
.replace("The exact model ID is", "Model ID:")
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:"))
if (!environment) return out
out = out.replace("# Environment", "# Runtime context")
.replace("You have been invoked in the following environment:", "The session environment is:")
.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
.replace("You are powered by the model named", "Current model name:")
.replace("You are powered by the model", "Current model:")
.replace("The exact model ID is", "Model ID:")
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:"))
const skillHeader = "\n\nThe following skills are available for use with the Skill tool:\n\n"
const skills = out.indexOf(skillHeader)
if (skills >= 0) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-factory-auth",
"version": "0.1.8",
"version": "0.1.9",
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
"type": "module",
"main": "./index.mjs",
+60
View File
@@ -299,3 +299,63 @@ test("system-role context adaptation is idempotent and preserves non-metadata pa
await l.fetch(url, { method: "POST", body: seen[0].body })
expect(seen[1].body).toBe(seen[0].body)
})
test("adapts accumulated model-switch updates when continuing a Claude 5 session", async () => {
const { l, seen } = await loaded()
const tokenContext = "<total_tokens>15000000 tokens left</total_tokens>"
const instructions = "## Auto Mode Active\n\nKeep all permission instructions verbatim.\n\nUser quoted: You are powered by the model custom-model."
const update = [
"You are powered by the model named Sonnet 5.5. The exact model ID is factory/claude-sonnet-5-5. Assistant knowledge cutoff is June 2026.",
tokenContext,
"You are powered by the model group/claude-default.",
instructions,
tokenContext,
"You are powered by the model named Opus 5.5. The exact model ID is factory/claude-opus-5-5. Assistant knowledge cutoff is June 2026.",
"The following agent types are no longer available:\n- claude-code-guide",
tokenContext,
"USD budget: $0/$0.4; $0.4 remaining",
].join("\n\n")
const messages = [
{ role: "user", content: "Continue the existing conversation." },
{ role: "system", content: "# Environment update\n - Primary working directory: /tmp/project (was /tmp/old)\n\n" + tokenContext },
{ role: "assistant", content: [{ type: "tool_use", id: "read_1", name: "Read", input: { path: "/tmp/project/proof" } }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "read_1", content: update, cache_control: { type: "ephemeral" } }] },
{ role: "system", content: update },
]
const request = { system: droid, messages, tools: [{ name: "Read", input_schema: { type: "object" } }], stream: true }
const adapted = update.replaceAll("\n\nYou are powered by the model named", "\n\nCurrent model name:")
.replace(/^You are powered by the model named/, "Current model name:")
.replace("\n\nYou are powered by the model group/", "\n\nCurrent model: group/")
.replaceAll("The exact model ID is", "Model ID:")
.replaceAll("Assistant knowledge cutoff is", "Model knowledge cutoff:")
for (const endpoint of [url, url + "/count_tokens"]) {
await l.fetch(endpoint, { method: "POST", body: JSON.stringify(request) })
expect(JSON.parse(seen.at(-1).body)).toEqual({ ...request, messages: [...messages.slice(0, -1), { role: "system", content: adapted }] })
const once = seen.at(-1).body
await l.fetch(endpoint, { method: "POST", body: once })
expect(seen.at(-1).body).toBe(once)
}
})
test("requires a model-update preamble and complete token metadata before adapting standalone system text", async () => {
const { l, seen } = await loaded()
const model = "You are powered by the model group/claude-default."
const update = model + "\n\n<total_tokens>15000000 tokens left</total_tokens>"
for (const content of [
model,
update.replace("</total_tokens>", ""),
update.replace("15000000", "unknown"),
"Explain this quoted metadata:\n\n" + update,
model + "\n\nQuoted token marker: <total_tokens>15000000 tokens left</total_tokens>",
[{ type: "text", text: update }],
]) {
const body = JSON.stringify({ system: droid, messages: [{ role: "system", content }] })
await l.fetch(url, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
}
for (const role of ["user", "assistant"]) {
const body = JSON.stringify({ system: droid, messages: [{ role, content: update }] })
await l.fetch(url, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
}
})