@magpie-community/opencode-factory-auth 0.1.33 → 0.1.35

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 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, or the compaction opening embedded in a historical session JSONL
213
- record. Those text results are represented as JSON strings with explicit
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
@@ -229,6 +230,24 @@ token marker. Changed-file text supplied by hooks, quoted or incomplete
229
230
  notifications, and notices that omit the snippet are left alone. Model and
230
231
  environment metadata after non-startup hooks retain their existing adaptation.
231
232
 
233
+ Claude Code's instructions reminder names `~/.claude/CLAUDE.md` "(user's
234
+ private global instructions for all projects)", which Factory refuses; in
235
+ the generated reminder it becomes "(global instructions)". Claude Code
236
+ renders that reminder two ways: the first copy opens with "Codebase and user
237
+ instructions are shown below", and a copy re-read after the files changed
238
+ (after compaction, a settings sync and the like) opens with "Instruction
239
+ files were re-read …; these differ from their earlier copies" or "These
240
+ instruction files changed". Both are adapted, in text blocks, string user
241
+ turns and chat completions' joined user text; text after the reminder and
242
+ a user's own mention of the phrase stay as written. A tool result that
243
+ quotes the phrase (reading Claude Code's renderer, say) gets the lossless
244
+ JSON encoding above.
245
+
246
+ When Factory still answers 403, the error magpie and the agent see keeps
247
+ Factory's request id (from `x-request-id`, `request-id` or `cf-ray`, or the
248
+ body) and its error code and type, and the Anthropic-route body carries
249
+ `request_id`, so the refusal can be named to Factory.
250
+
232
251
  Use magpie's Claude Code integration to select the Factory provider.
233
252
  magpie manages the provider-specific client settings, including capability
234
253
  and permission configuration. Fields such as `safeguards` and
@@ -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"
@@ -410,6 +411,28 @@ function explain(status, text) {
410
411
  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
412
  }
412
413
 
414
+ // upstreamIds are what Factory's refusal says to tell it apart when asking
415
+ // Factory about it (plugins#243): the request id from its headers or body,
416
+ // and the error's own code and type. The headers go back as they came too.
417
+ const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-amzn-requestid", "cf-ray"]
418
+ function upstreamIds(text, headers) {
419
+ let v
420
+ try {
421
+ v = JSON.parse(text)
422
+ } catch {}
423
+ const err = v && typeof v === "object" && v.error && typeof v.error === "object" ? v.error : {}
424
+ const str = (x) => (typeof x === "string" && /^[\x21-\x7e]{1,128}$/.test(x) ? x : undefined)
425
+ const id = str(v?.request_id) ?? str(v?.requestId) ?? str(err.request_id) ?? str(err.requestId) ??
426
+ REQUEST_ID_HEADERS.map((h) => str(headers?.get?.(h) ?? undefined)).find(Boolean)
427
+ const parts = []
428
+ if (id) parts.push("request id " + id)
429
+ const code = str(err.code) ?? str(v?.code)
430
+ if (code) parts.push("code " + code)
431
+ const type = str(err.type)
432
+ if (type) parts.push("type " + type)
433
+ return { id, said: parts.length ? " (upstream " + parts.join(", ") + ")" : "" }
434
+ }
435
+
413
436
  // ---- opening as droid ---------------------------------------------------------
414
437
  //
415
438
  // Factory takes a subscription's model requests only from Droid (magpie
@@ -459,6 +482,48 @@ function piSummary(text) {
459
482
  return text
460
483
  }
461
484
 
485
+ // Factory refuses pi's opening and its compaction opening wherever they
486
+ // appear, not only as the system prompt or the whole summary: a tool result
487
+ // that prints pi's system prompt, or a historical session record, carries
488
+ // them too, and every later turn of that conversation is 403.
489
+ //
490
+ // The list lives in client-phrases.json so the guard and the sanitizer read
491
+ // the same one. Its entries are written with a \uXXXX first character, so the
492
+ // file is safe to read from a Droid session; JSON.parse here yields the real
493
+ // phrase. "anywhere" is refused in any text (pi turns a compaction into one
494
+ // user text), "toolOnly" is refused in tool output while the prompt adapters
495
+ // keep them.
496
+ const FALLBACK_PHRASES = {
497
+ anywhere: [
498
+ "You are an expert coding assistant operating inside pi, a coding agent harness.",
499
+ PI_SUMMARIES[0][0].split("\n\n")[0],
500
+ ],
501
+ toolOnly: [
502
+ "You are Claude Code, Anthropic's official CLI for Claude.",
503
+ "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
504
+ "You are a Claude agent, built on Anthropic's Claude Agent SDK.",
505
+ "You have been invoked in the following environment:",
506
+ "x-anthropic-billing-header: cc_version=",
507
+ "This session is being continued from a previous conversation that ran out of context.",
508
+ "(user's private global instructions for all projects)",
509
+ ],
510
+ }
511
+ function loadClientPhrases() {
512
+ try {
513
+ const parsed = JSON.parse(readFileSync(new URL("./client-phrases.json", import.meta.url), "utf8"))
514
+ const anywhere = Array.isArray(parsed?.anywhere) ? parsed.anywhere.filter((p) => typeof p === "string" && p) : []
515
+ const toolOnly = Array.isArray(parsed?.toolOnly) ? parsed.toolOnly.filter((p) => typeof p === "string" && p) : []
516
+ // either group missing would silently drop protection, so use the
517
+ // built-in list instead
518
+ if (anywhere.length === 0 || toolOnly.length === 0) throw new Error("client-phrases.json needs both groups")
519
+ return { anywhere, toolOnly }
520
+ } catch {
521
+ return FALLBACK_PHRASES
522
+ }
523
+ }
524
+ const CLIENT_PHRASES = loadClientPhrases()
525
+ const PI_QUOTED_IN_TOOL = CLIENT_PHRASES.anywhere
526
+
462
527
  // promptOpenings adapts the messages of msgs (chat completions' messages,
463
528
  // Responses' input) as anthropicBody adapts a Messages request's: pi's
464
529
  // opening and Claude Code's fixed phrases in the system and developer
@@ -610,6 +675,9 @@ function geminiBody(model, body) {
610
675
  si.parts = [{ text: joined.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + joined }, ...rest]
611
676
  }
612
677
  m.systemInstruction = si
678
+ // Gemini's route has no tool-output adaptation: escape every refused
679
+ // phrase in its parts (functionResponse, systemInstruction) here.
680
+ escapeDeep(m, REFUSED_PHRASES)
613
681
  return JSON.stringify(m)
614
682
  }
615
683
 
@@ -698,12 +766,14 @@ function tooLarge(text, left) {
698
766
 
699
767
  // errorReply is an error as the API the request was for words one:
700
768
  // Anthropic's on /llm/a/, OpenAI's on the others.
701
- function errorReply(url, status, type, message, headers = new Headers()) {
769
+ function errorReply(url, status, type, message, headers = new Headers(), requestId) {
702
770
  headers.set("content-type", "application/json")
703
771
  headers.delete("content-length")
704
772
  headers.delete("content-encoding")
705
773
  const anthropic = new URL(url).pathname.includes("/llm/a/")
706
774
  const body = anthropic ? { type: "error", error: { type, message } } : { error: { message, type, code: null } }
775
+ // Anthropic's error body carries the request id beside the error
776
+ if (anthropic && requestId) body.request_id = requestId
707
777
  return new Response(JSON.stringify(body), { status, headers })
708
778
  }
709
779
 
@@ -1159,8 +1229,24 @@ function systemModelLine(text) {
1159
1229
 
1160
1230
  // The reminder carrying CLAUDE.md files names the global one with a phrase
1161
1231
  // Factory refuses; only that phrase in the generated reminder changes.
1162
- const INSTRUCTIONS_REMINDER = "<system-reminder>\nCodebase and user instructions are shown below"
1232
+ // Claude Code renders the instructions attachment two ways (n_t in
1233
+ // 2.1.292/2.1.303): the first copy opens with the preamble, and a copy
1234
+ // re-read after the files changed (changed: true, with or without a
1235
+ // reason such as "compaction") opens with its own sentence before the same
1236
+ // "Contents of … (user's private global instructions for all projects):"
1237
+ // lines (plugins#243).
1238
+ const INSTRUCTIONS_REMINDER = /^<system-reminder>\n(?:Codebase and user instructions are shown below|(?:Instruction files were re-read [^\n]+; these differ from their earlier copies|These instruction files changed) \u2014 each replaces its earlier copy, and the instructions preamble above still applies:\nContents of )/
1163
1239
  const GLOBAL_INSTRUCTIONS = "(user's private global instructions for all projects)"
1240
+ // Only the reminder itself changes: text joined after its close (a chat
1241
+ // user message is a turn's blocks joined) stays as the user wrote it.
1242
+ function instructionsText(text) {
1243
+ if (!INSTRUCTIONS_REMINDER.test(text)) return text
1244
+ const close = text.indexOf("\n</system-reminder>")
1245
+ const end = close < 0 ? text.length : close + "\n</system-reminder>".length
1246
+ const reminder = text.slice(0, end)
1247
+ if (!reminder.includes(GLOBAL_INSTRUCTIONS)) return text
1248
+ return reminder.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)") + text.slice(end)
1249
+ }
1164
1250
 
1165
1251
  // Claude Code (2.1.291 and later) restores skills invoked before compaction
1166
1252
  // as one generated reminder. Factory refuses that fixed opening, and the restored
@@ -1292,18 +1378,89 @@ function changedFileContext(text) {
1292
1378
  // rather than deleting or rewriting the file's contents. Other output and
1293
1379
  // the tool's id, error/cache markers and non-text blocks stay untouched.
1294
1380
  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"
1381
+ // the phrases Factory refuses wherever they appear
1382
+ const REFUSED_PHRASES = [
1383
+ ...CLIENT_PHRASES.anywhere,
1384
+ ...CLIENT_PHRASES.toolOnly,
1385
+ ]
1386
+ // The substrings whose first character is escaped in tool output: every
1387
+ // refused phrase from the list, plus the shorter prefixes the old loop
1388
+ // escaped and the reminder marker. Longest first, so a full sentence is
1389
+ // escaped before its own prefix (escaping the prefix first would hide it).
1390
+ const ESCAPE_IN_TOOL = [...new Set([...REFUSED_PHRASES, COMPACT_OPENING, GLOBAL_INSTRUCTIONS, "system-reminder", "You have", "You are", "x-anthropic-billing-header"])]
1391
+ .sort((a, b) => b.length - a.length)
1295
1392
  function quotedToolText(text, prefix = QUOTED_TOOL_PREFIX) {
1296
- if (![...CLAUDE_IDENTITIES].some((identity) => text.includes(identity)) &&
1297
- !text.includes("You have been invoked in the following environment:") &&
1298
- !text.includes("x-anthropic-billing-header: cc_version=") &&
1299
- !text.includes(COMPACT_OPENING)) return text
1393
+ if (!REFUSED_PHRASES.some((phrase) => text.includes(phrase))) return text
1300
1394
  let encoded = JSON.stringify(text)
1301
- for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder", COMPACT_OPENING]) {
1395
+ for (const phrase of ESCAPE_IN_TOOL) {
1302
1396
  encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
1303
1397
  }
1304
1398
  return prefix + encoded
1305
1399
  }
1306
1400
 
1401
+ // Factory refuses these phrases anywhere in the body, not only in tool
1402
+ // output: pi turns a compaction into one user text, and an assistant
1403
+ // message or a tool_use argument can quote a file too. escapePhrases
1404
+ // rewrites the first character of each phrase as \uXXXX without wrapping the
1405
+ // text, so a poisoned conversation can still be compacted or replayed.
1406
+ // Tool output keeps the JSON-wrapped, lossless form above.
1407
+ function escapePhrases(text, phrases = PI_QUOTED_IN_TOOL) {
1408
+ let out = text
1409
+ // By default only the phrases proven to be refused outside tool output
1410
+ // (pi's opening and its compaction opening): escaping generated reminders
1411
+ // such as GLOBAL_INSTRUCTIONS or Claude Code's environment line would
1412
+ // rewrite text the adapters deliberately keep. Gemini's route passes the
1413
+ // full list, because its tool output has no quotedToolText of its own.
1414
+ for (const phrase of phrases) {
1415
+ if (out.includes(phrase)) out = out.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
1416
+ }
1417
+ return out
1418
+ }
1419
+
1420
+ // escapeDeep applies escapePhrases to every string in a JSON body, in place.
1421
+ // true when something changed. Tool results are already escaped, so a
1422
+ // second pass changes nothing.
1423
+ function escapeDeep(value, phrases = PI_QUOTED_IN_TOOL) {
1424
+ if (typeof value === "string") return false // strings are replaced by their parent
1425
+ if (Array.isArray(value)) {
1426
+ let changed = false
1427
+ for (let i = 0; i < value.length; i++) {
1428
+ if (typeof value[i] === "string") {
1429
+ const out = escapePhrases(value[i], phrases)
1430
+ if (out !== value[i]) (value[i] = out), (changed = true)
1431
+ } else if (escapeDeep(value[i], phrases)) changed = true
1432
+ }
1433
+ return changed
1434
+ }
1435
+ if (value && typeof value === "object") {
1436
+ let changed = false
1437
+ for (const key of Object.keys(value)) {
1438
+ const v = value[key]
1439
+ if (typeof v === "string") {
1440
+ const out = escapePhrases(v, phrases)
1441
+ if (out !== v) (value[key] = out), (changed = true)
1442
+ } else if (escapeDeep(v, phrases)) changed = true
1443
+ }
1444
+ return changed
1445
+ }
1446
+ return false
1447
+ }
1448
+
1449
+ // sanitizeBody is the last pass before a request leaves: every string in the
1450
+ // body gets escapePhrases. Handles Messages, Responses, chat and Gemini.
1451
+ function sanitizeBody(body) {
1452
+ const text = bodyText(body)
1453
+ if (text == null) return body
1454
+ let parsed
1455
+ try {
1456
+ parsed = JSON.parse(text)
1457
+ } catch {
1458
+ return body
1459
+ }
1460
+ if (!escapeDeep(parsed)) return body
1461
+ return JSON.stringify(parsed)
1462
+ }
1463
+
1307
1464
  // The adapters below are shared by both of Factory's routes. Claude Code's
1308
1465
  // request reaches /api/llm/a as Messages, but a model Factory serves on
1309
1466
  // /api/llm/o (GLM, Kimi and other chat models) gets it translated by magpie
@@ -1332,7 +1489,8 @@ function systemMessageText(text) {
1332
1489
  function userBlockText(text) {
1333
1490
  const compacted = compactContext(text)
1334
1491
  if (compacted !== text) return compacted
1335
- if (text.startsWith(INSTRUCTIONS_REMINDER) && text.includes(GLOBAL_INSTRUCTIONS)) return text.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)")
1492
+ const instructions = instructionsText(text)
1493
+ if (instructions !== text) return instructions
1336
1494
  // a system message folded into the user's turn on its way here
1337
1495
  if (HOOK_OUTPUT.test(text) || SYSTEM_ENV_CONTEXT.test(text)) return systemContext(text)
1338
1496
  if (ENV_REMINDER.test(text)) {
@@ -1446,7 +1604,8 @@ function anthropicBody(body) {
1446
1604
  }
1447
1605
  if (message?.role !== "user") continue
1448
1606
  if (typeof message.content === "string") {
1449
- const adapted = compactContext(message.content)
1607
+ const compacted = compactContext(message.content)
1608
+ const adapted = compacted !== message.content ? compacted : instructionsText(message.content)
1450
1609
  if (adapted !== message.content) {
1451
1610
  message.content = adapted
1452
1611
  changed = true
@@ -1821,7 +1980,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
1821
1980
  // another agent's request opens as droid's does (droidBody)
1822
1981
  const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
1823
1982
  const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() }
1824
- const out = adapted.body
1983
+ const out = sanitizeBody(adapted.body)
1825
1984
  // the caller's length is of the body it sent, not of this one
1826
1985
  if (out !== init?.body) h.delete("content-length")
1827
1986
  const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
@@ -1868,8 +2027,9 @@ export const FactoryAuthPlugin = async ({ client }) => {
1868
2027
  }
1869
2028
  const why = explain(res.status, text)
1870
2029
  // the refusal, then what to do about it, as provider.Explain joins them
1871
- const msg = `${vendorError(text, statusLine(res.status))} — ${why}`
1872
- return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers)))
2030
+ const ids = upstreamIds(text, res.headers)
2031
+ const msg = `${vendorError(text, statusLine(res.status))}${ids.said} — ${why}`
2032
+ return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers), ids.id))
1873
2033
  } catch (e) {
1874
2034
  // Factory refused to renew the sign-in: the built-in failed the
1875
2035
  // request (magpie's 502) and marked the account lapsed
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.33",
3
+ "version": "0.1.35",
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" }