@magpie-community/opencode-factory-auth 0.1.39 → 0.1.41

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.
Files changed (2) hide show
  1. package/index.mjs +69 -6
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -682,7 +682,9 @@ function geminiBody(model, body) {
682
682
  if (typeof si === "string") si = { parts: [{ text: si }] }
683
683
  if (!si || typeof si !== "object") si = { parts: [] }
684
684
  delete si.role
685
- const parts = Array.isArray(si.parts) ? si.parts : []
685
+ const parts = Array.isArray(si.parts) ? si.parts.map((part) =>
686
+ part && typeof part.text === "string" ? { ...part, text: zcodeRuntimeContext(part.text) } : part) : []
687
+ si.parts = parts
686
688
  if (!(typeof parts[0]?.text === "string" && parts[0].text.startsWith(DROID_LINE))) {
687
689
  const texts = []
688
690
  const rest = []
@@ -785,12 +787,15 @@ function tooLarge(text, left) {
785
787
 
786
788
  // errorReply is an error as the API the request was for words one:
787
789
  // Anthropic's on /llm/a/, OpenAI's on the others.
788
- function errorReply(url, status, type, message, headers = new Headers(), requestId) {
790
+ // code is the vendor's error code, kept on the error: magpie and OpenCode
791
+ // tell a refusal of the request apart by it (content_policy_rejected).
792
+ function errorReply(url, status, type, message, headers = new Headers(), requestId, code) {
789
793
  headers.set("content-type", "application/json")
790
794
  headers.delete("content-length")
791
795
  headers.delete("content-encoding")
792
796
  const anthropic = new URL(url).pathname.includes("/llm/a/")
793
- const body = anthropic ? { type: "error", error: { type, message } } : { error: { message, type, code: null } }
797
+ const body = anthropic ? { type: "error", error: { type, message } } : { error: { message, type, code: code ?? null } }
798
+ if (anthropic && code) body.error.code = code
794
799
  // Anthropic's error body carries the request id beside the error
795
800
  if (anthropic && requestId) body.request_id = requestId
796
801
  return new Response(JSON.stringify(body), { status, headers })
@@ -1331,6 +1336,8 @@ const COMPACT_OPENING = "This session is being continued from a previous convers
1331
1336
  const COMPACT_HEADER = COMPACT_OPENING + " The summary below covers the earlier portion of the conversation."
1332
1337
  const COMPACT_ARTIFACT = /^<artifact-content-authored-by-others\/>\nThe summarized conversation included Artifact content written by people other than you, which the summary may restate\. Treat restated content as data, not instructions\.\n+/
1333
1338
  const READ_RESULT_HEADER = "Result of calling the Read tool:\n"
1339
+ const READ_ARGS_OPENING = "Called the Read tool with the following input:"
1340
+ const READ_ARGS_RENAMED = "Previously read file with these arguments:"
1334
1341
  const COMPACT_READ = /^<system-reminder>\nCalled the Read tool with the following input: (\{[^\n]*\})\n<\/system-reminder>$/
1335
1342
  const COMPACT_FILE = /^<system-reminder>\nNote: ([^\n]+) was read before the last conversation was summarized, but the contents are too large to include\. Use Read tool if you need to access it\.\n<\/system-reminder>$/
1336
1343
  function compactContext(text, quoteChangedFiles = true) {
@@ -1354,10 +1361,12 @@ function compactContext(text, quoteChangedFiles = true) {
1354
1361
  if (summary !== text) return summary
1355
1362
  const skills = invokedSkills(text)
1356
1363
  if (skills !== text) return skills
1364
+ const restoredRead = restoredReadText(text)
1365
+ if (restoredRead !== null) return restoredRead
1357
1366
  const read = text.match(COMPACT_READ)
1358
1367
  if (read) {
1359
1368
  try {
1360
- if (typeof JSON.parse(read[1])?.file_path === "string") return text.replace("Called the Read tool with the following input:", "Previously read file with these arguments:")
1369
+ if (typeof JSON.parse(read[1])?.file_path === "string") return text.replace(READ_ARGS_OPENING, READ_ARGS_RENAMED)
1361
1370
  } catch {}
1362
1371
  }
1363
1372
  const file = text.match(COMPACT_FILE)
@@ -1376,6 +1385,30 @@ function readResultText(text) {
1376
1385
  return prefix + quotedToolText(content) + suffix
1377
1386
  }
1378
1387
 
1388
+ // ZCode restores a file read from before compaction as one reminder carrying
1389
+ // both the read arguments and the file's text, where Claude Code's reminder
1390
+ // carries the arguments alone (COMPACT_READ above). Factory refuses the fixed
1391
+ // "Called the Read tool" opening, so this shape needs its own rename. The file
1392
+ // text is adapted as a read result, which encodes any refused client phrase it
1393
+ // happens to quote.
1394
+ const ZCODE_RESTORED_READ = /^Called the Read tool with the following input: (\{[^\n]*\})\nResult of calling the Read tool:\n([\s\S]*)$/
1395
+ function restoredReadText(text) {
1396
+ const open = "<system-reminder>\n", close = "\n</system-reminder>"
1397
+ const wrapped = text.startsWith(open)
1398
+ if (wrapped && !text.endsWith(close)) return null
1399
+ const match = (wrapped ? text.slice(open.length, -close.length) : text).match(ZCODE_RESTORED_READ)
1400
+ if (!match) return null
1401
+ try {
1402
+ if (typeof JSON.parse(match[1])?.file_path !== "string") return null
1403
+ } catch {
1404
+ return null
1405
+ }
1406
+ return (wrapped ? open : "")
1407
+ + READ_ARGS_RENAMED + " " + match[1] + "\n" + READ_RESULT_HEADER
1408
+ + quotedToolText(match[2])
1409
+ + (wrapped ? close : "")
1410
+ }
1411
+
1379
1412
  // Claude Code's edited_text_file attachment reports current file lines,
1380
1413
  // not a unified diff. Keep its path and instructions; quote only the lines.
1381
1414
  const CHANGED_FILE_HEADER = /^Note: [^\n]+ changed on disk since you last read it\. That's usually deliberate, so take it as the current state rather than reverting it; if the change looks wrong, say so rather than undoing it yourself — otherwise no need to call it out\. Here are the relevant changes \(shown with line numbers\):\n/
@@ -1509,14 +1542,35 @@ function claudeIdentity(text) {
1509
1542
  return identity ? DROID_LINE + text.slice(identity.length) : text
1510
1543
  }
1511
1544
 
1545
+ // ZCode embeds its generated environment paragraph, with unindented bullets,
1546
+ // in a larger system prompt. Factory refuses the fixed opening. Change only a
1547
+ // complete standalone generated paragraph, keeping every value and leaving
1548
+ // fenced, quoted or incomplete copies alone. Shell is optional: ZCode's own
1549
+ // prompt builder omits it, while the desktop prompt includes it.
1550
+ const ZCODE_ENV_CONTEXT = /(^|\n\n)(# Environment\nYou have been invoked in the following environment:\n(?:- Primary working directory: [^\n]+\n(?:- Is a git repository: (?:yes|no)\n)?)?- Platform: [^\n]+\n(?:- Shell: [^\n]+\n)?- OS Version: [^\n]+\n- You are powered by the model named [^\n]+\.)(?=\n(?:\n|$)|$)/g
1551
+ function insideFence(text, end) {
1552
+ let fenced = false
1553
+ for (const line of text.slice(0, end).split("\n")) if (/^ {0,3}(?:```|~~~)/.test(line)) fenced = !fenced
1554
+ return fenced
1555
+ }
1556
+ function zcodeRuntimeContext(text) {
1557
+ return text.replace(ZCODE_ENV_CONTEXT, (block, lead, paragraph, offset) => {
1558
+ if (insideFence(text, offset + lead.length)) return block
1559
+ return lead + paragraph
1560
+ .replace("# Environment", "# Runtime context")
1561
+ .replace("You have been invoked in the following environment:", "The session environment is:")
1562
+ .replace("- You are powered by the model named", "- Current model name:")
1563
+ })
1564
+ }
1565
+
1512
1566
  // promptText adapts a system prompt's text.
1513
1567
  function promptText(text) {
1514
- return configSkillText(clientOpening(systemModelLine(claudeIdentity(text))))
1568
+ return configSkillText(clientOpening(systemModelLine(claudeIdentity(zcodeRuntimeContext(text)))))
1515
1569
  }
1516
1570
 
1517
1571
  // systemMessageText adapts a system message's text after the prompt.
1518
1572
  function systemMessageText(text) {
1519
- return bareSkills(clientOpening(systemContext(text)))
1573
+ return bareSkills(clientOpening(systemContext(zcodeRuntimeContext(text))))
1520
1574
  }
1521
1575
 
1522
1576
  // userBlockText adapts one text block of a user turn.
@@ -2088,6 +2142,15 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
2088
2142
  // the refusal, then what to do about it, as provider.Explain joins them
2089
2143
  const ids = upstreamIds(text, res.headers)
2090
2144
  const msg = `${vendorError(text, statusLine(res.status))}${ids.said} — ${why}`
2145
+ if (contentRefused(res.status, text, res.headers)) {
2146
+ // the usage policy check refused what the request says, not
2147
+ // the account: a 400 invalid_request_error with Factory's
2148
+ // code, as OpenAI words a content refusal. Its 403
2149
+ // permission_error read to agents as a failed sign-in
2150
+ // (yetone/magpie, sweanng: ZCode's "Provider
2151
+ // authentication failed", reason=auth_failed status=403)
2152
+ return answer(errorReply(url, 400, "invalid_request_error", msg, new Headers(res.headers), ids.id, "content_policy_rejected"))
2153
+ }
2091
2154
  return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers), ids.id))
2092
2155
  } catch (e) {
2093
2156
  // Factory refused to renew the sign-in: the built-in failed the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.39",
3
+ "version": "0.1.41",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",