gateway: Factory's usage policy refusal reaches agents as a refused request, not a failed sign-in

sweanng (Discord #general, ZCode + Factory + GLM 5.3) got Factory's
usage policy refusal shown as "Provider authentication failed"
(reason=auth_failed status=403). The refusal is Factory's own; the label
was wrong. Factory refuses at 403 with code content_policy_rejected. The
Factory plugin (up to 0.1.39) handed it on as a 403 permission_error
with no code, magpie didn't know the code as a refusal, so the 403 went
through as is and the agent read it as an auth failure.

- policyRefusal knows content_policy_rejected (Factory's code, in its
  own top-level and error.code shapes and the plugin's), so the existing
  refusal path answers every protocol with 400 and its own request
  error: Anthropic invalid_request_error, OpenAI chat and Responses
  invalid_request_error, Gemini INVALID_ARGUMENT. Not asked again of the
  same account; other accounts/members follow the Refusal retries
  setting as for any refusal.
- restAfter leaves the account unrested for a policy refusal at 403 too,
  not only 400 (it rested "other by backoff" before).
- The refusal note keeps up to 1000 bytes of the vendor's message, not
  300: Factory's advice (start a new session or drop the quoted text)
  and OpenAI's Daybreak link were cut.
- Factory mover min 0.1.40 (plugins #494, on npm as latest): the plugin
  now answers this refusal as a 400 invalid_request_error carrying code
  content_policy_rejected; its other 403s stay permission_error.

Siblings checked: Devin's plugin maps its content policy to 400, Qoder's
sensitive codes and Zhipu's 1301 are request errors already; Factory was
the one content refusal sent as a 403.

Run (mote, rebased on origin/main 96a703a59, with the next commit):
  go test -timeout 45m -count=1 ./internal/provider: ok
  go test -timeout 45m -count=1 ./internal/gateway: ok (768s)
  (the first gateway run at this commit alone failed only
  TestUnroutedUnknownHoldAnsweredSooner's TempDir cleanup, a race in
  the test fixed in the next commit)
  gofmt -l internal/: clean
  plugins: HOME=$(mktemp -d) bun test packages/factory 178 pass;
  bun scripts/check.mjs ok.
Broken by hand: with fallback.go and routing.go reverted, all three new
tests fail (403 permission_error / PERMISSION_DENIED reaches every
protocol; policyRefusal false; rests "other by backoff"). With the note
cap back at 300, TestFactoryPolicyRejectedIsARefusal and
TestFactoryPolicyRefusalReachesAgentsAsARefusal fail (advice cut). With
the plugin's index.mjs reverted, content-policy.test.mjs fails 3 of 6.
Not tried: a real Factory content_policy_rejected (no way to trip it on
purpose), and ZCode itself reading the 400: its error mapping isn't in
any source I could find, so ZCode showing it as a refusal is expected
from the Anthropic invalid_request_error, not seen.
This commit is contained in:
yetone
2026-10-29 18:31:42 +08:00
parent fc43c69e53
commit 750bd1bb69
4 changed files with 134 additions and 11 deletions
+18 -9
View File
@@ -2907,17 +2907,23 @@ const refusedStatus = http.StatusBadRequest
// filterReasons are how a vendor says its safety filter stopped the reply:
// Anthropic's stop_reason, OpenAI's finish_reason and incomplete reason,
// an OpenAI or Azure error's code, and Gemini's finishReason and
// blockReason.
// an OpenAI or Azure error's code, Factory's error code, and Gemini's
// finishReason and blockReason.
var filterReasons = map[string]string{
"refusal": "refusal",
"content_filter": "content_filter",
"content_policy_violation": "content_filter",
"SAFETY": "safety",
"PROHIBITED_CONTENT": "safety",
"BLOCKLIST": "safety",
"SPII": "safety",
"IMAGE_SAFETY": "safety",
// Factory's usage policy check, a 403 whose code droid 0.245.0 tells
// apart from an account's 403 the same way (the Factory plugin keeps
// the code on the error it hands magpie): handed on as its 403, the
// agent took it for a failed sign-in (sweanng on Discord, ZCode:
// "Provider authentication failed", reason=auth_failed status=403)
"content_policy_rejected": "content_policy_rejected",
"SAFETY": "safety",
"PROHIBITED_CONTENT": "safety",
"BLOCKLIST": "safety",
"SPII": "safety",
"IMAGE_SAFETY": "safety",
}
// refusedNote is what a refusal is noted as: the vendor's own reason.
@@ -3345,8 +3351,11 @@ func policyRefusal(raw []byte) (string, bool) {
}
note := func(reason string) (string, bool) {
if msg = strings.TrimSpace(msg); msg != "" {
if len(msg) > 300 {
msg = msg[:300] + "…"
// long enough for the vendor's own advice after its words:
// Factory's "start a new session…" and OpenAI's Daybreak
// link were cut off at 300
if len(msg) > 1000 {
msg = msg[:1000] + "…"
}
return refusedNote(reason) + " — " + msg, true
}
+111
View File
@@ -0,0 +1,111 @@
package gateway
import (
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// factoryPolicyMsg is what the Factory plugin says of Factory's usage
// policy check refusing a request, as sweanng's ZCode showed it from magpie
// (Discord #general, 10-29), magpie's "Factory: " left off.
const factoryPolicyMsg = `This request was blocked by Factory's usage policy check. (upstream request id 8d1f0c2a3b4e5f60::LAX, code content_policy_rejected) — Factory's usage policy check reads the whole conversation, so this session's requests are refused again until the text that tripped it is gone: start a new session, or remove or reword what the conversation quotes (another agent's system prompt or instructions pasted in a message or a tool's output are the usual cause)`
// factoryPolicy403 is that refusal as the Factory plugin answers it, in
// the shape of the API the request was for: Anthropic's on /llm/a, OpenAI's
// on the others, the code kept on the error.
func factoryPolicy403(anthropic bool) string {
e := map[string]any{"type": "permission_error", "message": factoryPolicyMsg, "code": "content_policy_rejected"}
var v any = map[string]any{"error": e}
if anthropic {
v = map[string]any{"type": "error", "error": e, "request_id": "8d1f0c2a3b4e5f60::LAX"}
}
b, _ := json.Marshal(v)
return string(b)
}
// Factory's 403 content_policy_rejected is its usage policy check, not the
// account: in Factory's own two shapes and in the plugin's. Its other 403s
// (an org the user can't reach, a model the org's policy leaves out) are
// the account's still.
func TestFactoryPolicyRejectedIsARefusal(t *testing.T) {
for body, want := range map[string]bool{
`{"code":"content_policy_rejected","detail":"This request was blocked by Factory's usage policy check."}`: true,
`{"error":{"code":"content_policy_rejected","message":"This request was blocked by Factory's usage policy check."}}`: true,
factoryPolicy403(true): true,
factoryPolicy403(false): true,
`{"detail":"Requested active organization is not accessible by this user"}`: false,
`{"error":{"type":"permission_error","message":"Model not allowed by your organization's model policy"}}`: false,
`{"error":{"type":"permission_error","code":"org_policy_denied","message":"Model not allowed by your org"}}`: false,
} {
note, got := policyRefusal([]byte(body))
if got != want {
t.Errorf("%s: refusal %v, want %v", body, got, want)
}
if got && strings.Contains(body, "start a new session") && !strings.Contains(note, "are the usual cause") {
t.Errorf("the vendor's advice was cut from the note: %q", note)
}
}
}
// sweanng's ZCode, asking Factory through magpie, was handed Factory's
// usage policy refusal as the plugin's 403 permission_error, and showed
// "Provider authentication failed" (reason=auth_failed status=403). Each
// agent protocol is now told it as a refusal of the request: 400, the
// protocol's invalid-request error, Factory's words and advice kept, not
// asked again of the same account, and the account not rested.
func TestFactoryPolicyRefusalReachesAgentsAsARefusal(t *testing.T) {
asks := []struct{ name, path, body, inShape string }{
{"messages", "/v1/messages", `{"model":"f/m","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`, `"type":"invalid_request_error"`},
{"messages stream", "/v1/messages", `{"model":"f/m","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`, `"type":"invalid_request_error"`},
{"chat", "/v1/chat/completions", `{"model":"f/m","messages":[{"role":"user","content":"hi"}]}`, `"type":"invalid_request_error"`},
{"responses", "/v1/responses", `{"model":"f/m","input":"hi"}`, `"type":"invalid_request_error"`},
{"responses stream", "/v1/responses", `{"model":"f/m","stream":true,"input":"hi"}`, `"type":"invalid_request_error"`},
{"gemini", "/v1beta/models/f/m:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, `"status":"INVALID_ARGUMENT"`},
}
for _, up := range []provider.Protocol{provider.Anthropic, provider.Chat} {
for _, ask := range asks {
t.Run(string(up)+"/"+ask.name, func(t *testing.T) {
fresh(t)
f := &scripted{replies: []reply{{403, "application/json", factoryPolicy403(up == provider.Anthropic)}}}
scriptedOn(t, "f", up, f)
s := New()
code, out := sendTo(s, ask.path, ask.body)
if code != http.StatusBadRequest {
t.Fatalf("status %d, want 400: %s", code, out)
}
if !strings.Contains(out, ask.inShape) || strings.Contains(out, "permission_error") || strings.Contains(out, "PERMISSION_DENIED") {
t.Errorf("not the protocol's request error: %s", out)
}
if !strings.Contains(out, "content_policy_rejected") || !strings.Contains(out, "are the usual cause") {
t.Errorf("Factory's words or advice lost: %s", out)
}
if f.n != 1 {
t.Errorf("Factory asked %d times, want once", f.n)
}
r := lastRoute(s)
if n := len(r.Tries); n == 0 || r.Tries[n-1].Fail != failRefused || r.Tries[n-1].Rest != nil {
t.Errorf("tries: %+v", r.Tries)
}
if rests := liveRests(); len(rests) != 0 {
t.Errorf("rested for a refusal of the request: %v", rests)
}
})
}
}
}
// Any route that rests a candidate after a failure leaves it be for
// Factory's 403 refusal, as for a 400 one.
func TestFactoryPolicyRefusalRestsNobody(t *testing.T) {
fresh(t)
s := &Server{}
p := provider.Provider{ID: "f", Name: "Factory", Chat: "https://api.factory.ai/api/llm/o/v1", Key: "k"}
c := candidate{p: p, model: "glm-5.3", rest: p.ID}
if r := s.restAfter(c, 403, http.Header{}, []byte(factoryPolicy403(false))); r.Why != failRefused || r.By != "off" {
t.Errorf("rests as %s by %s, want %s by off", r.Why, r.By, failRefused)
}
}
+4 -1
View File
@@ -1042,7 +1042,10 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// as soon as the switch is off
return Rest{Why: why, Status: status, By: "off", Until: now}
}
if status == http.StatusBadRequest {
if status == http.StatusBadRequest || status == http.StatusForbidden {
// a 403 too: Factory's usage policy check refuses at 403
// (content_policy_rejected), which failureOf alone reads as the
// account's
if _, ok := policyRefusal(body); ok {
// the safety filter refused the request's content (#3274:
// Codex's 400 cyber_policy), read from the vendor's error
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func init() {
movers["factory"] = &mover{
pkg: "@magpie-community/opencode-factory-auth",
min: "0.1.39", // DeepSeek V4.1 Flash 1017, from droid 0.251.0, on its registry default upstream Fireworks (sweanng on Discord; plugins #480); 0.1.38: an account stops once its Standard window is used up when the Standard usage only option is on (plugins #349); 0.1.37: a billing header joined with instructions loses only its own line, so Claude Code auto mode keeps its policy (plugins #302); Claude Code 2.1.292's instructions re-read after compaction (changed: true), and a 403 that keeps Factory's request id (plugins #243); the update-config entry in a system prompt's configuration section, as claude-code-guide renders it with a slash, adapted the way Factory takes it (plugins #198); a model's token multiplier reaching magpie as its rate, with a running promotion's discount (plugins #158); an OpenAI model's request without temperature and top_p, which OpenAI's reasoning models turn away with 400 (sweanng424 on Discord, Nowledge Mem on gpt-6.1-sol); requests saying droid 0.242.0, the current release (sky杨 on Discord: every model 403 "Factory: Forbidden" from Claude Code); Claude Code on GLM and other /api/llm/o models without the phrases Factory refuses (Echoo on Discord); the Fast Mode models listed last, so GPT-5.3-Codex, Grok and GLM are in the first 24 again (plugins #119); droid's Fast Mode models (Opus 5.5/5/4.8, GPT-5.5/5.4/5.3-Codex), and fast asked of a base model sent to its Fast Mode model (plugins #119); Gemini 4 Argon and Gemini 3.x on Factory's Gemini route (#2080); a 413 asked once more with older images left out, then said as Factory's byte limit (#2082); Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker (JL); a session continued after Claude Code compaction, whose restored context opens with the invoked-skills reminder (plugins #66); Claude Code's streamed context_management left out, which Factory's streaming route refuses (plugins #71); Claude Code's skill list sent alone as a system message, as text blocks or a string, gets update-config's line Factory takes (plugins #72); Claude Code 2.1.280's restored-context turn after /compact (plugins #68); pi's compaction and branch summary openings reworded (#1316); hook notifications kept in Claude Code compaction context only stop changed-file quoting, summaries quoted like tool output, a cut after a hunk separator (plugins #42); Claude Code compaction/runtime metadata and quoted session summaries (#1132); pi's opening sentence cut to its first half (#952); DeepSeek V4.1 Flash, Kimi K3 and GLM-5.2 offering none, so reasoning turned off stops their thinking (#899); requests saying droid 0.233.0 (JL: every model 403); Claude Code 2.1.288's runtime context as a system message of text blocks (#658); a tool whose input_schema has anyOf/oneOf/allOf at its root (Codex's automation_update) wrapped for Claude models (#646); a failure's status and its sign-in mark as the built-in's; Claude 5's system-role metadata as Factory takes it; Claude Code's standalone model-switch system updates; tool results quoting Claude Code's fixed phrases, and Claude Code's directory updates carrying a model; the sign-in renewed ahead of time through auth.refresh; Claude Code with a global CLAUDE.md or a SessionStart hook, and Claude Desktop's model line (#634)
min: "0.1.40", // Factory's usage policy refusal (content_policy_rejected) is a 400 invalid_request_error with its code, not a 403 permission_error an agent reads as a failed sign-in (sweanng on Discord; plugins #494); 0.1.39: DeepSeek V4.1 Flash 1017, from droid 0.251.0, on its registry default upstream Fireworks (sweanng on Discord; plugins #480); 0.1.38: an account stops once its Standard window is used up when the Standard usage only option is on (plugins #349); 0.1.37: a billing header joined with instructions loses only its own line, so Claude Code auto mode keeps its policy (plugins #302); Claude Code 2.1.292's instructions re-read after compaction (changed: true), and a 403 that keeps Factory's request id (plugins #243); the update-config entry in a system prompt's configuration section, as claude-code-guide renders it with a slash, adapted the way Factory takes it (plugins #198); a model's token multiplier reaching magpie as its rate, with a running promotion's discount (plugins #158); an OpenAI model's request without temperature and top_p, which OpenAI's reasoning models turn away with 400 (sweanng424 on Discord, Nowledge Mem on gpt-6.1-sol); requests saying droid 0.242.0, the current release (sky杨 on Discord: every model 403 "Factory: Forbidden" from Claude Code); Claude Code on GLM and other /api/llm/o models without the phrases Factory refuses (Echoo on Discord); the Fast Mode models listed last, so GPT-5.3-Codex, Grok and GLM are in the first 24 again (plugins #119); droid's Fast Mode models (Opus 5.5/5/4.8, GPT-5.5/5.4/5.3-Codex), and fast asked of a base model sent to its Fast Mode model (plugins #119); Gemini 4 Argon and Gemini 3.x on Factory's Gemini route (#2080); a 413 asked once more with older images left out, then said as Factory's byte limit (#2082); Haiku 5.5 and Mistral Large 4, in droid 0.240.0's picker (JL); a session continued after Claude Code compaction, whose restored context opens with the invoked-skills reminder (plugins #66); Claude Code's streamed context_management left out, which Factory's streaming route refuses (plugins #71); Claude Code's skill list sent alone as a system message, as text blocks or a string, gets update-config's line Factory takes (plugins #72); Claude Code 2.1.280's restored-context turn after /compact (plugins #68); pi's compaction and branch summary openings reworded (#1316); hook notifications kept in Claude Code compaction context only stop changed-file quoting, summaries quoted like tool output, a cut after a hunk separator (plugins #42); Claude Code compaction/runtime metadata and quoted session summaries (#1132); pi's opening sentence cut to its first half (#952); DeepSeek V4.1 Flash, Kimi K3 and GLM-5.2 offering none, so reasoning turned off stops their thinking (#899); requests saying droid 0.233.0 (JL: every model 403); Claude Code 2.1.288's runtime context as a system message of text blocks (#658); a tool whose input_schema has anyOf/oneOf/allOf at its root (Codex's automation_update) wrapped for Claude models (#646); a failure's status and its sign-in mark as the built-in's; Claude 5's system-role metadata as Factory takes it; Claude Code's standalone model-switch system updates; tool results quoting Claude Code's fixed phrases, and Claude Code's directory updates carrying a model; the sign-in renewed ahead of time through auth.refresh; Claude Code with a global CLAUDE.md or a SessionStart hook, and Claude Desktop's model line (#634)
agents: []string{"factory"},
out: func() ([]Moving, error) {
ls := factoryLogins()