Skip to content

Commit 835531c

Browse files
1056674754claude
andcommitted
chore: port the sscity fork delta onto v2.0.21
Upstream re-rooted the repository on 2026-07-24 and shipped the Effect-v2 architecture as the v2 line (v2.0.0..v2.0.21) while v1.18.x moved to maintenance on the old root. The two lines share no merge base, so the fork cannot merge v2 in place; this commit re-applies the sscity delta on a fresh branch cut from v2.0.21 (8a8bd62). Port audit of the 13 substantive fork commits against v2.0.21: Superseded natively (verified, no code carried): - b75e846 (revert scoping) — v2 restore is per-file by construction (core/src/session/revert.ts + snapshot.restore({files})). - 5dab0a8 (empty provider streams) — route-level requireTerminalEvent (packages/ai/src/route/client.ts) + step-level unknownFinish retry + runner drain loop cover the failure class with bounded retries. - 81c7736 (overlapping async prompts) — v2 prompts are durably admitted (steer/queue); double admission is structurally impossible and conflicts map to 409 PromptConflictError. - d97d232 (concurrent prompt join + idle ensure) — the run coordinator joins executions and settles exactly one outcome per busy period. - 9203bd3 / 5aa972b / 9f114bf (hot-reload cluster) — v2 ConfigWatch + config plugins reload skills/MCP/tools/providers on config and filesystem events (core/src/config.ts reconcileWatches, config/plugin/*). - 4b0b8d5 (deferred provider snapshot) — v2 resolves providers lazily from a bundled models.dev catalog; eager bootstrap init no longer exists. - 9f114bf rider ("our servers are currently overloaded" retryable) — v2 SERVER_ERROR_TEXT already matches overloaded phrasing. Ported: - da40edc (GLM/ZhiPu normalization, error 1210) → packages/ai/src/ protocols/openai-chat.ts: zai/glm toolCallID charset sanitization for all zai/glm routes; a legacy-model post-pass drops empty assistant messages, merges consecutive assistant turns and strips replayed reasoning fields. Scoped to pre-4.6 models (glm-4.5-era): v2's recorded GLM 5.3 traffic requires reasoning replay through tool loops, so modern models keep it. - e4d26b6 (GLM retry classification) → "cyber_policy" joins CONTENT_POLICY_CODES (packages/ai/src/provider-error.ts) and the session runner treats ContentPolicy failures as soft-retryable with a 3-attempt cap (core/src/session/runner/{retry,step}.ts). - 0e07d91 (small_model_fallback) → generalized as agents.<id>.fallbacks (schema/src/config/agent.ts, schema/src/agent.ts); legacy small_model_fallback migrates into agents.title.fallbacks (core/src/config/normalize.ts, core/src/v1/config/*); title generation walks selected -> fallbacks -> session model (core/src/session/ {context,title}.ts). Project naming has no v2 call site — omitted. - 0bef5e5 (branding) → all 37 workspace package.json versions rebranded 2.0.21-sscity; bun.lock regenerated. Build note: the v2 build script (packages/cli/script/build.ts) hard-requires bun ^1.4.2 and emits packages/cli/dist/cli-darwin-arm64/bin/opencode; the OpenChamber embedded-packaging runbook needs its paths and bun version updated. Tests: zai route scrub/merge/preserve-reasoning cases, glm-compatible route sanitization + non-glm negative, cyber_policy classification, content-policy retry cap (session-error), legacy small_model_fallback migration + title fallback chain (config/normalization, session-title). Formatter test failures in packages/core are pre-existing on pristine v2.0.21 (verified by stash probe) and unrelated to this port. Co-Authored-By: Claude Sonnet 5 <[email protected]>
1 parent 8a8bd62 commit 835531c

57 files changed

Lines changed: 4305 additions & 3960 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎bun.lock‎

Lines changed: 3896 additions & 3896 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"$schema": "https://json.schemastore.org/package.json",
33
"name": "opencode",
44
"description": "AI-powered development tool",
5-
"version": "2.0.21",
5+
"version": "2.0.21-sscity",
66
"private": true,
77
"type": "module",
88
"packageManager": "[email protected]",

‎packages/ai/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"$schema": "https://json.schemastore.org/package.json",
3-
"version": "2.0.21",
3+
"version": "2.0.21-sscity",
44
"name": "@opencode/ai",
55
"type": "module",
66
"license": "MIT",

‎packages/ai/src/protocols/openai-chat.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,16 @@ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request:
575575
modelID.includes("deepseek"))
576576
const reasoningField = request.model.compatibility?.reasoningField
577577
const mistral = ["mistral", "devstral", "codestral", "pixtral", "mixtral"].some((family) => modelID.includes(family))
578+
const baseURL = request.model.route.endpoint.baseURL?.toLowerCase()
579+
const zaiGlm =
580+
["zai", "zai-coding-plan", "zhipuai", "zhipuai-coding-plan"].includes(request.model.provider.toLowerCase()) ||
581+
baseURL?.includes("api.z.ai") === true ||
582+
baseURL?.includes("open.bigmodel.cn") === true ||
583+
modelID.includes("glm")
584+
// GLM 4.6+ and 5.x accept replayed reasoning and tool streaming; older
585+
// coding-plan endpoints reject reasoning replay with error 1210
586+
// (https://github.com/sst/opencode/issues/22209).
587+
const zaiGlmLegacy = zaiGlm && !/^glm-(?:4\.[67]|5(?:[.-]|$))/i.test(request.model.id)
578588
const lowering = {
579589
...options,
580590
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
@@ -584,6 +594,7 @@ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request:
584594
.replace(/[^a-zA-Z0-9]/g, "")
585595
.slice(0, 9)
586596
.padEnd(9, "0")
597+
if (zaiGlm) return id.replace(/[^a-zA-Z0-9_-]/g, "") || "call0"
587598
if (modelID.includes("claude")) return id.replace(/[^a-zA-Z0-9_-]/g, "_")
588599
if (request.model.provider === "openai" || request.model.provider === "azure" || modelID.startsWith("openai/"))
589600
return id.slice(0, 40)
@@ -661,7 +672,42 @@ const lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request:
661672
messages.push(...(yield* lowerMessage(message, reasoningField, requireReasoning, lowering)))
662673
}
663674
flushAttachments()
664-
return messages
675+
if (!zaiGlmLegacy) return messages
676+
// Legacy GLM (ZhiPu AI) — pre-4.6 open.bigmodel.cn coding-plan and related
677+
// endpoints — is stricter than the OpenAI Chat Completions spec and rejects
678+
// several lowered message shapes with error 1210 ("API 调用参数有误"):
679+
// • empty content on any message
680+
// • consecutive assistant turns
681+
// • replayed reasoning fields on assistant messages
682+
// (tool_call_ids are already sanitized through lowering.toolCallID for all
683+
// zai/glm models.)
684+
// See: https://github.com/sst/opencode/issues/22209
685+
const scrubbed: OpenAIChatMessage[] = []
686+
for (const message of messages) {
687+
if (message.role === "assistant") {
688+
const { reasoning_content: _rc, reasoning: _r, reasoning_text: _rt, reasoning_details: _rd, ...wire } = message
689+
if ((wire.content === null || wire.content === "") && wire.tool_calls === undefined) continue
690+
const previous = scrubbed.at(-1)
691+
if (previous?.role === "assistant") {
692+
const toParts = (content: typeof wire.content): ReadonlyArray<OpenAIChatTextContent> => {
693+
if (typeof content === "string") return content === "" ? [] : [{ type: "text", text: content }]
694+
return content ?? []
695+
}
696+
const toolCalls = [...(previous.tool_calls ?? []), ...(wire.tool_calls ?? [])]
697+
scrubbed[scrubbed.length - 1] = {
698+
...previous,
699+
content: [...toParts(previous.content), ...toParts(wire.content)],
700+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
701+
}
702+
continue
703+
}
704+
scrubbed.push(wire)
705+
continue
706+
}
707+
if (message.role !== "tool" && typeof message.content === "string" && message.content === "") continue
708+
scrubbed.push(message)
709+
}
710+
return scrubbed
665711
})
666712

667713
// Anthropic via LiteLLM and Amazon Bedrock require `tools` to be present

‎packages/ai/src/provider-error.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,10 @@ const CONTENT_POLICY_CODES = new Set([
143143
"content_policy_violation",
144144
"image_content_policy_violation",
145145
"refusal",
146+
// GLM (ZhiPu) reports overzealous safety rejections as `cyber_policy`; they
147+
// clear when the model redraws a sample, so the session runner retries them
148+
// a bounded number of times instead of failing the turn immediately.
149+
"cyber_policy",
146150
])
147151
// OpenCode Zen replaces upstream codes outside its allow-list but keeps the original
148152
// as a `[code]` label at the start of the rewritten message.

‎packages/ai/test/provider-error.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,4 +462,14 @@ describe("provider error messages", () => {
462462
].map(providerErrorMessage),
463463
).toEqual([undefined, undefined, undefined, undefined])
464464
})
465+
466+
test("classifies GLM cyber_policy rejections as content policy", () => {
467+
expect(
468+
classifyProviderFailure({
469+
message: "cyber_policy: your request has been rejected by the safety system",
470+
rawBody: '{"error":{"code":"cyber_policy","message":"your request has been rejected by the safety system"}}',
471+
status: 400,
472+
}),
473+
).toMatchObject({ _tag: "ContentPolicy" })
474+
})
465475
})

‎packages/ai/test/provider/openai-compatible-chat.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,3 +606,51 @@ describe("OpenAI-compatible Chat route", () => {
606606
}),
607607
)
608608
})
609+
610+
describe("GLM scrub", () => {
611+
const glmModel = OpenAICompatibleChat.route
612+
.with({
613+
provider: "zhipu",
614+
endpoint: { baseURL: "https://open.bigmodel.cn/api/paas/v4/" },
615+
auth: Auth.bearer("test-key"),
616+
})
617+
.model({ id: "glm-5.3" })
618+
619+
it.effect("sanitizes tool call ids for glm-compatible routes", () =>
620+
Effect.gen(function* () {
621+
const prepared = yield* compileRequest(
622+
LLM.request({
623+
model: glmModel,
624+
messages: [
625+
Message.user("Plan the work"),
626+
Message.assistant([
627+
ToolCallPart.make({ id: "call 1 weird", name: "lookup", input: { city: "Paris" } }),
628+
]),
629+
Message.tool({ id: "call 1 weird", name: "lookup", result: "Sunny" }),
630+
],
631+
}),
632+
)
633+
const assistant = prepared.body.messages[1]
634+
expect(assistant?.role === "assistant" ? assistant.tool_calls?.[0]?.id : undefined).toBe("call1weird")
635+
const tool = prepared.body.messages[2]
636+
expect(tool?.role === "tool" ? tool.tool_call_id : undefined).toBe("call1weird")
637+
}),
638+
)
639+
640+
it.effect("leaves non-glm tool call ids untouched", () =>
641+
Effect.gen(function* () {
642+
const prepared = yield* compileRequest(
643+
LLM.request({
644+
model,
645+
messages: [
646+
Message.user("Plan the work"),
647+
Message.assistant([ToolCallPart.make({ id: "call 1", name: "lookup", input: { city: "Paris" } })]),
648+
Message.tool({ id: "call 1", name: "lookup", result: "Sunny" }),
649+
],
650+
}),
651+
)
652+
const assistant = prepared.body.messages[1]
653+
expect(assistant?.role === "assistant" ? assistant.tool_calls?.[0]?.id : undefined).toBe("call 1")
654+
}),
655+
)
656+
})

‎packages/ai/test/provider/zai.test.ts‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { expect } from "bun:test"
22
import { ConfigProvider, Effect } from "effect"
33
import { Headers } from "effect/unstable/http"
4-
import { Auth, LLM, LLMClient, Message, ReasoningPart, ToolDefinition } from "../../src/index.js"
4+
import { Auth, LLM, LLMClient, Message, ReasoningPart, ToolCallPart, ToolDefinition } from "../../src/index.js"
55
import { ZAI, ZAICodingPlan } from "../../src/providers.js"
66
import { compileRequest } from "../../src/route/client.js"
77
import { Endpoint } from "../../src/route/endpoint.js"
@@ -331,3 +331,77 @@ it.effect("ZAI Coding Messages serializes enabled thinking without a token budge
331331
),
332332
),
333333
)
334+
335+
it.effect("scrubs GLM-hostile message shapes for legacy zai routes", () =>
336+
Effect.gen(function* () {
337+
for (const model of [ZAI.chat("glm-4.5-air"), ZAICodingPlan.chat("glm-4.5-air")]) {
338+
const prepared = yield* compileRequest(
339+
LLM.request({
340+
model,
341+
messages: [
342+
Message.user("Plan the work"),
343+
Message.assistant([
344+
{ type: "reasoning", text: "hidden chain of thought" },
345+
ToolCallPart.make({ id: "call 1 weird", name: "lookup", input: { city: "Paris" } }),
346+
]),
347+
Message.tool({ id: "call 1 weird", name: "lookup", result: "Sunny" }),
348+
Message.assistant([{ type: "text", text: "Working on it." }]),
349+
],
350+
}),
351+
)
352+
const messages = prepared.body.messages
353+
const first = messages[1]
354+
expect(first?.role === "assistant" ? first.reasoning_content : undefined).toBeUndefined()
355+
expect(first?.role === "assistant" ? first.reasoning_details : undefined).toBeUndefined()
356+
expect(first?.role === "assistant" ? first.tool_calls?.[0]?.id : undefined).toBe("call1weird")
357+
const tool = messages[2]
358+
expect(tool?.role === "tool" ? tool.tool_call_id : undefined).toBe("call1weird")
359+
const last = messages.at(-1)
360+
expect(last?.role === "assistant" && typeof last.content === "string" ? last.content : undefined).toBe(
361+
"Working on it.",
362+
)
363+
}
364+
}).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: { ZAI_API_KEY: "fixture" } })))),
365+
)
366+
367+
it.effect("merges consecutive assistant turns for legacy zai routes", () =>
368+
Effect.gen(function* () {
369+
const prepared = yield* compileRequest(
370+
LLM.request({
371+
model: ZAI.chat("glm-4.5-air"),
372+
messages: [
373+
Message.user("Plan the work"),
374+
Message.assistant([{ type: "text", text: "Working" }]),
375+
Message.assistant([{ type: "text", text: "on it." }]),
376+
Message.assistant([{ type: "reasoning", text: "forgotten" }]),
377+
],
378+
}),
379+
)
380+
const messages = prepared.body.messages
381+
expect(messages).toHaveLength(2)
382+
const merged = messages[1]
383+
expect(merged?.role === "assistant" ? Array.isArray(merged.content) : false).toBe(true)
384+
expect(merged?.role === "assistant" ? merged.reasoning_content : undefined).toBeUndefined()
385+
}).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: { ZAI_API_KEY: "fixture" } })))),
386+
)
387+
388+
it.effect("preserves replayed reasoning for modern GLM models", () =>
389+
Effect.gen(function* () {
390+
const prepared = yield* compileRequest(
391+
LLM.request({
392+
model: ZAI.chat("glm-5.3"),
393+
messages: [
394+
Message.user("Plan the work"),
395+
Message.assistant([
396+
{ type: "reasoning", text: "chain of thought" },
397+
ToolCallPart.make({ id: "call_1", name: "lookup", input: { city: "Paris" } }),
398+
]),
399+
Message.tool({ id: "call_1", name: "lookup", result: "Sunny" }),
400+
],
401+
}),
402+
)
403+
const assistant = prepared.body.messages[1]
404+
expect(assistant?.role === "assistant" ? assistant.reasoning_content : undefined).toBe("chain of thought")
405+
expect(assistant?.role === "assistant" ? assistant.tool_calls?.[0]?.id : undefined).toBe("call_1")
406+
}).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: { ZAI_API_KEY: "fixture" } })))),
407+
)

‎packages/app/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@opencode/app",
3-
"version": "2.0.21",
3+
"version": "2.0.21-sscity",
44
"description": "",
55
"type": "module",
66
"exports": {

‎packages/cli/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"$schema": "https://json.schemastore.org/package.json",
33
"name": "@opencode/cli",
4-
"version": "2.0.21",
4+
"version": "2.0.21-sscity",
55
"type": "module",
66
"license": "MIT",
77
"bin": {

0 commit comments

Comments
 (0)