@magpie-community/opencode-factory-auth 0.1.34 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/client-phrases.json +16 -0
- package/index.mjs +145 -11
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -209,8 +209,9 @@ incomplete and hook-owned forms are left alone.
|
|
|
209
209
|
|
|
210
210
|
Factory can also refuse fixed client phrases quoted in tool results, such as
|
|
211
211
|
the identity/environment definitions printed when inspecting this plugin's
|
|
212
|
-
source,
|
|
213
|
-
record
|
|
212
|
+
source, the compaction opening embedded in a historical session JSONL
|
|
213
|
+
record, or pi's opening sentence in a model snapshot of its own system
|
|
214
|
+
prompt. Those text results are represented as JSON strings with explicit
|
|
214
215
|
decoding instructions and Unicode escapes for the fixed phrases. Decoding
|
|
215
216
|
the string recovers the exact original output, including quotes, backslashes
|
|
216
217
|
and Unicode; the plugin does not delete the output or replace its identities
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"//": "Fixed client phrases Factory refuses in a request body. Each phrase's first character is a JSON \\uXXXX escape: the file is safe to read (a Droid session reading it does not 403), and JSON.parse yields the real phrase. anywhere: refused in any text (system, user, assistant, tool_use). toolOnly: refused in tool output; the prompt adapters keep them.",
|
|
3
|
+
"anywhere": [
|
|
4
|
+
"\u0059ou are an expert coding assistant operating inside pi, a coding agent harness.",
|
|
5
|
+
"\u0054he conversation history before this point was compacted into the following summary:"
|
|
6
|
+
],
|
|
7
|
+
"toolOnly": [
|
|
8
|
+
"\u0059ou are Claude Code, Anthropic's official CLI for Claude.",
|
|
9
|
+
"\u0059ou are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
|
|
10
|
+
"\u0059ou are a Claude agent, built on Anthropic's Claude Agent SDK.",
|
|
11
|
+
"\u0059ou have been invoked in the following environment:",
|
|
12
|
+
"\u0078-anthropic-billing-header: cc_version=",
|
|
13
|
+
"\u0054his session is being continued from a previous conversation that ran out of context.",
|
|
14
|
+
"\u0028user's private global instructions for all projects)"
|
|
15
|
+
]
|
|
16
|
+
}
|
package/index.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// built-in Factory account (internal/provider/factory*.go).
|
|
5
5
|
|
|
6
6
|
import { STATUS_CODES } from "node:http"
|
|
7
|
+
import { readFileSync } from "node:fs"
|
|
7
8
|
import { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs"
|
|
8
9
|
|
|
9
10
|
const PROVIDER = "factory"
|
|
@@ -402,10 +403,28 @@ async function reconcile(c) {
|
|
|
402
403
|
// "Requested active organization is not accessible by this user".
|
|
403
404
|
const orgRefused = (status, text) => status === 403 && text.toLowerCase().includes("active organization is not accessible")
|
|
404
405
|
|
|
406
|
+
// contentRefused is Factory's usage policy check refusing what the request
|
|
407
|
+
// says, not who sent it: a 403 with code "content_policy_rejected" (droid
|
|
408
|
+
// 0.245.0 tells it apart the same way, and only when Factory sent no
|
|
409
|
+
// x-factory-upstream-error header). Its check reads the whole conversation,
|
|
410
|
+
// so sending the request again, under any org, is refused again.
|
|
411
|
+
function contentRefused(status, text, headers) {
|
|
412
|
+
if (status !== 403 || headers?.get?.("x-factory-upstream-error")) return false
|
|
413
|
+
let v
|
|
414
|
+
try {
|
|
415
|
+
v = JSON.parse(text)
|
|
416
|
+
} catch {
|
|
417
|
+
return false
|
|
418
|
+
}
|
|
419
|
+
const err = v && typeof v === "object" && v.error && typeof v.error === "object" ? v.error : {}
|
|
420
|
+
return v?.code === "content_policy_rejected" || err.code === "content_policy_rejected"
|
|
421
|
+
}
|
|
422
|
+
|
|
405
423
|
// explain is what the user can do about a 403 Factory still answers once
|
|
406
424
|
// the request carries what droid sends.
|
|
407
|
-
function explain(status, text) {
|
|
425
|
+
function explain(status, text, headers) {
|
|
408
426
|
if (status !== 403) return ""
|
|
427
|
+
if (contentRefused(status, text, headers)) return "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)"
|
|
409
428
|
if (orgRefused(status, text)) return "the Factory account's organization changed; remove the account in magpie and sign in to it again"
|
|
410
429
|
return "Factory refused the request. magpie adapts fixed client metadata on both OpenAI and Anthropic routes. Factory may still refuse unsupported fields or wrappers; check the upstream error, the organization's model policy, plan and regional provider availability, and compare the same model in Droid"
|
|
411
430
|
}
|
|
@@ -481,6 +500,48 @@ function piSummary(text) {
|
|
|
481
500
|
return text
|
|
482
501
|
}
|
|
483
502
|
|
|
503
|
+
// Factory refuses pi's opening and its compaction opening wherever they
|
|
504
|
+
// appear, not only as the system prompt or the whole summary: a tool result
|
|
505
|
+
// that prints pi's system prompt, or a historical session record, carries
|
|
506
|
+
// them too, and every later turn of that conversation is 403.
|
|
507
|
+
//
|
|
508
|
+
// The list lives in client-phrases.json so the guard and the sanitizer read
|
|
509
|
+
// the same one. Its entries are written with a \uXXXX first character, so the
|
|
510
|
+
// file is safe to read from a Droid session; JSON.parse here yields the real
|
|
511
|
+
// phrase. "anywhere" is refused in any text (pi turns a compaction into one
|
|
512
|
+
// user text), "toolOnly" is refused in tool output while the prompt adapters
|
|
513
|
+
// keep them.
|
|
514
|
+
const FALLBACK_PHRASES = {
|
|
515
|
+
anywhere: [
|
|
516
|
+
"You are an expert coding assistant operating inside pi, a coding agent harness.",
|
|
517
|
+
PI_SUMMARIES[0][0].split("\n\n")[0],
|
|
518
|
+
],
|
|
519
|
+
toolOnly: [
|
|
520
|
+
"You are Claude Code, Anthropic's official CLI for Claude.",
|
|
521
|
+
"You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
|
|
522
|
+
"You are a Claude agent, built on Anthropic's Claude Agent SDK.",
|
|
523
|
+
"You have been invoked in the following environment:",
|
|
524
|
+
"x-anthropic-billing-header: cc_version=",
|
|
525
|
+
"This session is being continued from a previous conversation that ran out of context.",
|
|
526
|
+
"(user's private global instructions for all projects)",
|
|
527
|
+
],
|
|
528
|
+
}
|
|
529
|
+
function loadClientPhrases() {
|
|
530
|
+
try {
|
|
531
|
+
const parsed = JSON.parse(readFileSync(new URL("./client-phrases.json", import.meta.url), "utf8"))
|
|
532
|
+
const anywhere = Array.isArray(parsed?.anywhere) ? parsed.anywhere.filter((p) => typeof p === "string" && p) : []
|
|
533
|
+
const toolOnly = Array.isArray(parsed?.toolOnly) ? parsed.toolOnly.filter((p) => typeof p === "string" && p) : []
|
|
534
|
+
// either group missing would silently drop protection, so use the
|
|
535
|
+
// built-in list instead
|
|
536
|
+
if (anywhere.length === 0 || toolOnly.length === 0) throw new Error("client-phrases.json needs both groups")
|
|
537
|
+
return { anywhere, toolOnly }
|
|
538
|
+
} catch {
|
|
539
|
+
return FALLBACK_PHRASES
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const CLIENT_PHRASES = loadClientPhrases()
|
|
543
|
+
const PI_QUOTED_IN_TOOL = CLIENT_PHRASES.anywhere
|
|
544
|
+
|
|
484
545
|
// promptOpenings adapts the messages of msgs (chat completions' messages,
|
|
485
546
|
// Responses' input) as anthropicBody adapts a Messages request's: pi's
|
|
486
547
|
// opening and Claude Code's fixed phrases in the system and developer
|
|
@@ -632,6 +693,9 @@ function geminiBody(model, body) {
|
|
|
632
693
|
si.parts = [{ text: joined.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + joined }, ...rest]
|
|
633
694
|
}
|
|
634
695
|
m.systemInstruction = si
|
|
696
|
+
// Gemini's route has no tool-output adaptation: escape every refused
|
|
697
|
+
// phrase in its parts (functionResponse, systemInstruction) here.
|
|
698
|
+
escapeDeep(m, REFUSED_PHRASES)
|
|
635
699
|
return JSON.stringify(m)
|
|
636
700
|
}
|
|
637
701
|
|
|
@@ -1332,19 +1396,89 @@ function changedFileContext(text) {
|
|
|
1332
1396
|
// rather than deleting or rewriting the file's contents. Other output and
|
|
1333
1397
|
// the tool's id, error/cache markers and non-text blocks stay untouched.
|
|
1334
1398
|
const QUOTED_TOOL_PREFIX = "Tool output encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n"
|
|
1399
|
+
// the phrases Factory refuses wherever they appear
|
|
1400
|
+
const REFUSED_PHRASES = [
|
|
1401
|
+
...CLIENT_PHRASES.anywhere,
|
|
1402
|
+
...CLIENT_PHRASES.toolOnly,
|
|
1403
|
+
]
|
|
1404
|
+
// The substrings whose first character is escaped in tool output: every
|
|
1405
|
+
// refused phrase from the list, plus the shorter prefixes the old loop
|
|
1406
|
+
// escaped and the reminder marker. Longest first, so a full sentence is
|
|
1407
|
+
// escaped before its own prefix (escaping the prefix first would hide it).
|
|
1408
|
+
const ESCAPE_IN_TOOL = [...new Set([...REFUSED_PHRASES, COMPACT_OPENING, GLOBAL_INSTRUCTIONS, "system-reminder", "You have", "You are", "x-anthropic-billing-header"])]
|
|
1409
|
+
.sort((a, b) => b.length - a.length)
|
|
1335
1410
|
function quotedToolText(text, prefix = QUOTED_TOOL_PREFIX) {
|
|
1336
|
-
if (!
|
|
1337
|
-
!text.includes("You have been invoked in the following environment:") &&
|
|
1338
|
-
!text.includes("x-anthropic-billing-header: cc_version=") &&
|
|
1339
|
-
!text.includes(COMPACT_OPENING) &&
|
|
1340
|
-
!text.includes(GLOBAL_INSTRUCTIONS)) return text
|
|
1411
|
+
if (!REFUSED_PHRASES.some((phrase) => text.includes(phrase))) return text
|
|
1341
1412
|
let encoded = JSON.stringify(text)
|
|
1342
|
-
for (const phrase of
|
|
1413
|
+
for (const phrase of ESCAPE_IN_TOOL) {
|
|
1343
1414
|
encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
|
|
1344
1415
|
}
|
|
1345
1416
|
return prefix + encoded
|
|
1346
1417
|
}
|
|
1347
1418
|
|
|
1419
|
+
// Factory refuses these phrases anywhere in the body, not only in tool
|
|
1420
|
+
// output: pi turns a compaction into one user text, and an assistant
|
|
1421
|
+
// message or a tool_use argument can quote a file too. escapePhrases
|
|
1422
|
+
// rewrites the first character of each phrase as \uXXXX without wrapping the
|
|
1423
|
+
// text, so a poisoned conversation can still be compacted or replayed.
|
|
1424
|
+
// Tool output keeps the JSON-wrapped, lossless form above.
|
|
1425
|
+
function escapePhrases(text, phrases = PI_QUOTED_IN_TOOL) {
|
|
1426
|
+
let out = text
|
|
1427
|
+
// By default only the phrases proven to be refused outside tool output
|
|
1428
|
+
// (pi's opening and its compaction opening): escaping generated reminders
|
|
1429
|
+
// such as GLOBAL_INSTRUCTIONS or Claude Code's environment line would
|
|
1430
|
+
// rewrite text the adapters deliberately keep. Gemini's route passes the
|
|
1431
|
+
// full list, because its tool output has no quotedToolText of its own.
|
|
1432
|
+
for (const phrase of phrases) {
|
|
1433
|
+
if (out.includes(phrase)) out = out.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
|
|
1434
|
+
}
|
|
1435
|
+
return out
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// escapeDeep applies escapePhrases to every string in a JSON body, in place.
|
|
1439
|
+
// true when something changed. Tool results are already escaped, so a
|
|
1440
|
+
// second pass changes nothing.
|
|
1441
|
+
function escapeDeep(value, phrases = PI_QUOTED_IN_TOOL) {
|
|
1442
|
+
if (typeof value === "string") return false // strings are replaced by their parent
|
|
1443
|
+
if (Array.isArray(value)) {
|
|
1444
|
+
let changed = false
|
|
1445
|
+
for (let i = 0; i < value.length; i++) {
|
|
1446
|
+
if (typeof value[i] === "string") {
|
|
1447
|
+
const out = escapePhrases(value[i], phrases)
|
|
1448
|
+
if (out !== value[i]) (value[i] = out), (changed = true)
|
|
1449
|
+
} else if (escapeDeep(value[i], phrases)) changed = true
|
|
1450
|
+
}
|
|
1451
|
+
return changed
|
|
1452
|
+
}
|
|
1453
|
+
if (value && typeof value === "object") {
|
|
1454
|
+
let changed = false
|
|
1455
|
+
for (const key of Object.keys(value)) {
|
|
1456
|
+
const v = value[key]
|
|
1457
|
+
if (typeof v === "string") {
|
|
1458
|
+
const out = escapePhrases(v, phrases)
|
|
1459
|
+
if (out !== v) (value[key] = out), (changed = true)
|
|
1460
|
+
} else if (escapeDeep(v, phrases)) changed = true
|
|
1461
|
+
}
|
|
1462
|
+
return changed
|
|
1463
|
+
}
|
|
1464
|
+
return false
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// sanitizeBody is the last pass before a request leaves: every string in the
|
|
1468
|
+
// body gets escapePhrases. Handles Messages, Responses, chat and Gemini.
|
|
1469
|
+
function sanitizeBody(body) {
|
|
1470
|
+
const text = bodyText(body)
|
|
1471
|
+
if (text == null) return body
|
|
1472
|
+
let parsed
|
|
1473
|
+
try {
|
|
1474
|
+
parsed = JSON.parse(text)
|
|
1475
|
+
} catch {
|
|
1476
|
+
return body
|
|
1477
|
+
}
|
|
1478
|
+
if (!escapeDeep(parsed)) return body
|
|
1479
|
+
return JSON.stringify(parsed)
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1348
1482
|
// The adapters below are shared by both of Factory's routes. Claude Code's
|
|
1349
1483
|
// request reaches /api/llm/a as Messages, but a model Factory serves on
|
|
1350
1484
|
// /api/llm/o (GLM, Kimi and other chat models) gets it translated by magpie
|
|
@@ -1864,7 +1998,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
1864
1998
|
// another agent's request opens as droid's does (droidBody)
|
|
1865
1999
|
const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
|
|
1866
2000
|
const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() }
|
|
1867
|
-
const out = adapted.body
|
|
2001
|
+
const out = sanitizeBody(adapted.body)
|
|
1868
2002
|
// the caller's length is of the body it sent, not of this one
|
|
1869
2003
|
if (out !== init?.body) h.delete("content-length")
|
|
1870
2004
|
const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
|
|
@@ -1904,12 +2038,12 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
1904
2038
|
if (res.status === 413) return answer(await smaller(res))
|
|
1905
2039
|
if (res.status !== 403) return answer(res)
|
|
1906
2040
|
let text = await res.text()
|
|
1907
|
-
if (await mendOrg(res.status, text, onRenew).catch(() => false)) {
|
|
2041
|
+
if (!contentRefused(res.status, text, res.headers) && (await mendOrg(res.status, text, onRenew).catch(() => false))) {
|
|
1908
2042
|
res = await send(input, init, body, onRenew)
|
|
1909
2043
|
if (res.status !== 403) return answer(res)
|
|
1910
2044
|
text = await res.text()
|
|
1911
2045
|
}
|
|
1912
|
-
const why = explain(res.status, text)
|
|
2046
|
+
const why = explain(res.status, text, res.headers)
|
|
1913
2047
|
// the refusal, then what to do about it, as provider.Explain joins them
|
|
1914
2048
|
const ids = upstreamIds(text, res.headers)
|
|
1915
2049
|
const msg = `${vendorError(text, statusLine(res.status))}${ids.said} — ${why}`
|
|
@@ -1928,4 +2062,4 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
1928
2062
|
}
|
|
1929
2063
|
|
|
1930
2064
|
// for tests
|
|
1931
|
-
export const _internal = { fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
|
|
2065
|
+
export const _internal = { 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 }
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-factory-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.36",
|
|
4
4
|
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
7
|
-
"files": ["index.mjs", "anthropic-tools.mjs", "README.md"],
|
|
7
|
+
"files": ["index.mjs", "anthropic-tools.mjs", "client-phrases.json", "README.md"],
|
|
8
8
|
"keywords": ["opencode", "opencode-plugin", "magpie", "factory", "droid"],
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/factory" }
|