@magpie-community/opencode-factory-auth 0.1.19 → 0.1.21

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 (3) hide show
  1. package/README.md +13 -2
  2. package/index.mjs +92 -15
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -121,8 +121,11 @@ Claude Code's generated compaction summaries also have a fixed opening
121
121
  that Factory refuses. The adapter recognizes the two generated opening
122
122
  sentences and rephrases only the first in user strings and text blocks,
123
123
  including summaries without a `Summary:` label. The generated artifact
124
- provenance marker and note, summary body and continuation instructions stay
125
- verbatim.
124
+ provenance marker and note stay verbatim. If the summary itself quotes any
125
+ of the refused client phrases handled in tool output, the context after the
126
+ two opening sentences is encoded as a JSON string with explicit decoding
127
+ instructions. Decoding restores the exact summary, transcript path and
128
+ continuation instructions; context without those phrases stays verbatim.
126
129
  Complete generated reminders for restored Read calls and omitted files are
127
130
  adapted too. Read arguments and file paths are preserved; quoted or incomplete
128
131
  reminders are left alone.
@@ -154,6 +157,14 @@ The same lossless encoding applies to restored or `@`-attached Read file text
154
157
  after the exact `Result of calling the Read tool:` header, including complete
155
158
  reminder wrappers and announced runtime bundles. The generated header and
156
159
  wrapper stay intact. File text without a known refused phrase is unchanged.
160
+ Claude Code's complete changed-on-disk notifications receive the same handling:
161
+ only the numbered file snippet is encoded, retaining its TAB or colon line
162
+ separators, hunk separators and truncation notice. The path and instructions
163
+ about respecting the current file stay verbatim. This covers wrapped user
164
+ attachments and generated system bundles, including notifications before a
165
+ token marker. Changed-file text supplied by hooks, quoted or incomplete
166
+ notifications, and notices that omit the snippet are left alone. Model and
167
+ environment metadata after non-startup hooks retain their existing adaptation.
157
168
 
158
169
  Use magpie's Claude Code integration to select the Factory provider.
159
170
  magpie manages the provider-specific client settings, including capability
package/index.mjs CHANGED
@@ -286,20 +286,43 @@ function clientOpening(text) {
286
286
  return typeof text === "string" ? text.replace(PI_OPENING, (_, at) => at + PI_COMPAT) : text
287
287
  }
288
288
 
289
+ // pi turns a compaction, and a branch it came back from, into a user
290
+ // message of one text: a fixed sentence, then the summary in <summary> tags
291
+ // (pi-coding-agent 1.0.4 and 1.1.0, dist/core/messages.js:
292
+ // COMPACTION_SUMMARY_PREFIX and BRANCH_SUMMARY_PREFIX). Factory refuses the
293
+ // compaction sentence whole (yetone/magpie#1316): after a compaction every
294
+ // turn was 403, and the reporter's replays passed with the sentence removed,
295
+ // reworded or only half of it. The branch sentence is pi's other fixed
296
+ // summary opening and is reworded the same way. Only a text that is pi's
297
+ // whole summary, sentence first and </summary> last, changes; the summary
298
+ // itself goes on as it is.
299
+ const PI_SUMMARIES = [
300
+ ["The conversation history before this point was compacted into the following summary:\n\n<summary>\n", "Earlier conversation context is summarized below:\n\n<summary>\n"],
301
+ ["The following is a summary of a branch that this conversation came back from:\n\n<summary>\n", "Summary of an earlier conversation branch:\n\n<summary>\n"],
302
+ ]
303
+ function piSummary(text) {
304
+ if (typeof text !== "string" || !text.endsWith("</summary>")) return text
305
+ for (const [from, to] of PI_SUMMARIES) if (text.startsWith(from)) return to + text.slice(from.length)
306
+ return text
307
+ }
308
+
289
309
  // promptOpenings adapts clientOpening in the system and developer messages
290
- // of msgs (chat completions' messages, Responses' input), their string
291
- // content or text parts: false when nothing changed.
310
+ // of msgs (chat completions' messages, Responses' input), and piSummary in
311
+ // their user messages, their string content or text parts: false when
312
+ // nothing changed.
292
313
  function promptOpenings(msgs) {
293
314
  let changed = false
294
315
  for (const m of Array.isArray(msgs) ? msgs : []) {
295
- if (!m || typeof m !== "object" || (m.role !== "system" && m.role !== "developer")) continue
316
+ if (!m || typeof m !== "object") continue
317
+ const adapt = m.role === "system" || m.role === "developer" ? clientOpening : m.role === "user" ? piSummary : null
318
+ if (!adapt) continue
296
319
  if (typeof m.content === "string") {
297
- const adapted = clientOpening(m.content)
320
+ const adapted = adapt(m.content)
298
321
  if (adapted !== m.content) (m.content = adapted), (changed = true)
299
322
  } else if (Array.isArray(m.content)) {
300
323
  for (const p of m.content) {
301
324
  if (!p || typeof p !== "object" || typeof p.text !== "string") continue
302
- const adapted = clientOpening(p.text)
325
+ const adapted = adapt(p.text)
303
326
  if (adapted !== p.text) (p.text = adapted), (changed = true)
304
327
  }
305
328
  }
@@ -650,6 +673,9 @@ const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_to
650
673
  // context in the same message (#634 and subagent startup). Adapt only the
651
674
  // environment suffix; keep the hook output and tool announcement verbatim.
652
675
  const HOOK_OUTPUT = /^(?:SessionStart|SubagentStart)(?::[^\n]* hook success:| hook additional context:)/
676
+ // Other hook events can also own additional context inside a notification
677
+ // bundle. This guard only stops rewriting; it does not adapt their output.
678
+ const HOOK_NOTIFICATION = /^[A-Z][A-Za-z]*(?::[^\n]* hook success:| hook additional context:)/
653
679
  const DEFERRED_TOOLS_OPENING = 'The following deferred tools are now available via ToolSearch. Their schemas are NOT loaded — calling them directly will fail with InputValidationError. Use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas before calling them:\n'
654
680
  const HOOK_CONTEXT = "\n# Environment\nYou have been invoked in the following environment:"
655
681
  const SYSTEM_TOKEN_OPENING = /^<total_tokens>\d+ tokens left<\/total_tokens>\n\n/
@@ -657,6 +683,7 @@ const SYSTEM_TOKEN_OPENING = /^<total_tokens>\d+ tokens left<\/total_tokens>\n\n
657
683
  // auto mode). Require the generated list opening and a complete token tail.
658
684
  const SYSTEM_SKILL_CONTEXT = /^The following skills are available for use with the Skill tool:\n\n- [\s\S]*\n\n<total_tokens>\d+ tokens left<\/total_tokens>$/
659
685
  function systemContext(text) {
686
+ text = changedFileContext(text)
660
687
  text = announcedSkills(text)
661
688
  if (SYSTEM_TOKEN_OPENING.test(text) || SYSTEM_SKILL_CONTEXT.test(text)) return announcedContext(text)
662
689
  if (HOOK_OUTPUT.test(text) || text.startsWith(DEFERRED_TOOLS_OPENING)) {
@@ -688,15 +715,25 @@ function announcedSkills(text) {
688
715
  // token context and no system-reminder wrappers. Only known metadata
689
716
  // paragraphs change; numbered file contents and the hook's own output stay.
690
717
  function announcedContext(text) {
691
- const parts = text.split("\n\n")
718
+ const parts = changedFileContext(text).split(/\n\n(?!\.\.\. \[)/)
692
719
  const open = "<system-reminder>\n", close = "\n</system-reminder>"
720
+ let quoteChangedFiles = true
693
721
  for (let i = 1; i < parts.length; i++) {
694
722
  const part = parts[i]
695
- if (HOOK_OUTPUT.test(part)) break
723
+ const hook = part.replace(/^<system-reminder>\n/, "")
724
+ if (HOOK_OUTPUT.test(hook)) break
725
+ // Any hook owns its file snippets. Non-startup hooks do not stop the
726
+ // existing adaptation of model/environment metadata that follows them.
727
+ if (HOOK_NOTIFICATION.test(hook)) quoteChangedFiles = false
728
+ const changedFile = quoteChangedFiles ? changedFileText(part) : null
729
+ if (changedFile !== null) {
730
+ parts[i] = changedFile
731
+ continue
732
+ }
696
733
  const result = part.indexOf("\n" + READ_RESULT_HEADER)
697
734
  const heading = result < 0 ? part : part.slice(0, result)
698
735
  const wrapped = open + heading + close
699
- const compacted = compactContext(wrapped)
736
+ const compacted = compactContext(wrapped, quoteChangedFiles)
700
737
  if (compacted !== wrapped) {
701
738
  parts[i] = compacted.slice(open.length, -close.length) + (result < 0 ? "" : "\n" + readResultText(part.slice(result + 1)))
702
739
  } else if (SYSTEM_ENV_CONTEXT.test(part + "\n")) {
@@ -749,9 +786,10 @@ const GLOBAL_INSTRUCTIONS = "(user's private global instructions for all project
749
786
  // Factory returns 403 for Claude Code's fixed compaction opening, even
750
787
  // without tools or other history. Match the two generated opening sentences,
751
788
  // including the provenance prefix, without requiring a Summary label. Keep
752
- // the provenance, summary and continuation instructions verbatim. File
753
- // reminders restored after compaction need the same narrow adaptation;
754
- // their paths and read arguments stay intact; refused file text is quoted
789
+ // the provenance verbatim. A summary that quotes refused client metadata
790
+ // needs lossless encoding too, including its transcript path and continuation
791
+ // instructions. File reminders restored after compaction need the same narrow
792
+ // adaptation; their paths and read arguments stay intact; refused file text is quoted
755
793
  // losslessly below.
756
794
  const COMPACT_OPENING = "This session is being continued from a previous conversation that ran out of context."
757
795
  const COMPACT_HEADER = COMPACT_OPENING + " The summary below covers the earlier portion of the conversation."
@@ -759,14 +797,23 @@ const COMPACT_ARTIFACT = /^<artifact-content-authored-by-others\/>\nThe summariz
759
797
  const READ_RESULT_HEADER = "Result of calling the Read tool:\n"
760
798
  const COMPACT_READ = /^<system-reminder>\nCalled the Read tool with the following input: (\{[^\n]*\})\n<\/system-reminder>$/
761
799
  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>$/
762
- function compactContext(text) {
800
+ function compactContext(text, quoteChangedFiles = true) {
763
801
  // A translating gateway can fold an announced system turn into user text.
764
802
  if (SYSTEM_TOKEN_OPENING.test(text) || SYSTEM_SKILL_CONTEXT.test(text)) return announcedContext(text)
765
803
  if (HOOK_OUTPUT.test(text) || text.startsWith(DEFERRED_TOOLS_OPENING)) return systemContext(text)
766
804
  const result = readResultText(text)
767
805
  if (result !== null) return result
806
+ const changedFile = quoteChangedFiles && text.startsWith("<system-reminder>\n") ? changedFileText(text) : null
807
+ if (changedFile !== null) return changedFile
768
808
  const prefix = text.match(COMPACT_ARTIFACT)?.[0] ?? ""
769
- if (text.startsWith(COMPACT_HEADER, prefix.length)) return prefix + "Earlier conversation context is summarized below." + text.slice(prefix.length + COMPACT_OPENING.length)
809
+ if (text.startsWith(COMPACT_HEADER, prefix.length)) {
810
+ const context = text.slice(prefix.length + COMPACT_HEADER.length)
811
+ const header = prefix + COMPACT_HEADER.replace(COMPACT_OPENING, "Earlier conversation context is summarized below.")
812
+ const quoted = quotedToolText(context, "Conversation context encoded as a JSON string. Decode the JSON string to recover the exact original context before continuing:\n")
813
+ return header + (quoted === context ? context : "\n\n" + quoted)
814
+ }
815
+ const summary = piSummary(text)
816
+ if (summary !== text) return summary
770
817
  const read = text.match(COMPACT_READ)
771
818
  if (read) {
772
819
  try {
@@ -789,13 +836,43 @@ function readResultText(text) {
789
836
  return prefix + quotedToolText(content) + suffix
790
837
  }
791
838
 
839
+ // Claude Code's edited_text_file attachment reports current file lines,
840
+ // not a unified diff. Keep its path and instructions; quote only the lines.
841
+ 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/
842
+ function changedFileText(text) {
843
+ const open = "<system-reminder>\n", close = "\n</system-reminder>"
844
+ const wrapped = text.startsWith(open)
845
+ if (wrapped && !text.endsWith(close)) return null
846
+ const content = wrapped ? text.slice(open.length, -close.length) : text
847
+ const header = content.match(CHANGED_FILE_HEADER)?.[0]
848
+ if (!header) return null
849
+ const lines = content.slice(header.length)
850
+ if (!/^\d+[\t:][^\n]*(?:\n(?:\.\.\.\n)?\d+[\t:][^\n]*)*(?:(?:\n\.\.\.)?\n\n\.\.\. \[\d+ lines truncated\] \.\.\.)?$/.test(lines)) return null
851
+ return (wrapped ? open : "") + header + quotedToolText(lines) + (wrapped ? close : "")
852
+ }
853
+
854
+ // System-turn notifications may start with the changed file, or put it
855
+ // among other notifications before the final token marker. Hook output is
856
+ // owned by the hook, even when it quotes a complete generated notification.
857
+ function changedFileContext(text) {
858
+ // Keep even an incomplete truncation tail with its snippet, so the
859
+ // complete-notification check can reject it rather than encode a fragment.
860
+ const parts = text.split(/\n\n(?!\.\.\. \[)/)
861
+ if (changedFileText(parts[0]) === null && !SYSTEM_TOKEN_OPENING.test(text) && !/(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_tokens>$/.test(text)) return text
862
+ for (let i = 0; i < parts.length; i++) {
863
+ if (HOOK_NOTIFICATION.test(parts[i].replace(/^<system-reminder>\n/, ""))) break
864
+ parts[i] = changedFileText(parts[i]) ?? parts[i]
865
+ }
866
+ return parts.join("\n\n")
867
+ }
868
+
792
869
  // Factory also refuses these fixed client phrases when they are quoted in
793
870
  // tool output, e.g. while reading this adapter's source. Keep the original
794
871
  // text recoverable: a JSON string with explicit decoding instructions,
795
872
  // rather than deleting or rewriting the file's contents. Other output and
796
873
  // the tool's id, error/cache markers and non-text blocks stay untouched.
797
874
  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"
798
- function quotedToolText(text) {
875
+ function quotedToolText(text, prefix = QUOTED_TOOL_PREFIX) {
799
876
  if (![...CLAUDE_IDENTITIES].some((identity) => text.includes(identity)) &&
800
877
  !text.includes("You have been invoked in the following environment:") &&
801
878
  !text.includes("x-anthropic-billing-header: cc_version=") &&
@@ -804,7 +881,7 @@ function quotedToolText(text) {
804
881
  for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder", COMPACT_OPENING]) {
805
882
  encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
806
883
  }
807
- return QUOTED_TOOL_PREFIX + encoded
884
+ return prefix + encoded
808
885
  }
809
886
 
810
887
  function anthropicBody(body) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",