@magpie-community/opencode-factory-auth 0.1.11 → 0.1.13
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 +17 -0
- package/anthropic-tools.mjs +181 -0
- package/index.mjs +53 -5
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -131,3 +131,20 @@ organization region and upstream API. Connectivity has been verified with
|
|
|
131
131
|
Sonnet 4.6, Sonnet 5.5 and Opus 5.5. Two-turn Read tool calls with Claude
|
|
132
132
|
Code's default tool set have been verified with Sonnet 4.6 and Sonnet 5.5,
|
|
133
133
|
including Sonnet 5.5 selected through a routing group.
|
|
134
|
+
|
|
135
|
+
## Tool schema compatibility
|
|
136
|
+
|
|
137
|
+
Factory's Anthropic route rejects tool schemas with root-level `anyOf`,
|
|
138
|
+
`oneOf` or `allOf`. The plugin nests those schemas under an internal
|
|
139
|
+
`arguments` property instead of removing their branch constraints. It
|
|
140
|
+
wraps examples and previous tool inputs too, then unwraps tool replies
|
|
141
|
+
before returning them to OpenCode or magpie. Ordinary object schemas and
|
|
142
|
+
OpenAI routes keep their existing behavior.
|
|
143
|
+
|
|
144
|
+
Local schema pointers are rebased to the nested schema; `$id` resources
|
|
145
|
+
and anchors retain their resolution scope, and literal data is unchanged.
|
|
146
|
+
Recursive schema resources
|
|
147
|
+
without `$id` fail explicitly because nesting would change their scope.
|
|
148
|
+
Affected streaming tool arguments are buffered until their content block
|
|
149
|
+
is complete. Other events, tool ids, usage and upstream errors pass through;
|
|
150
|
+
an incomplete or invalid argument envelope fails instead of being executed.
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Factory rejects composition keywords at the tool schema's root. Keep the
|
|
2
|
+
// original schema under one argument, and hide that wire-only envelope from
|
|
3
|
+
// the caller in both replies and the next turn's history.
|
|
4
|
+
const argument = "arguments"
|
|
5
|
+
const compositions = ["anyOf", "oneOf", "allOf"]
|
|
6
|
+
const schemaMaps = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]
|
|
7
|
+
const schemaLists = ["anyOf", "oneOf", "allOf", "prefixItems"]
|
|
8
|
+
const schemaValues = ["additionalProperties", "unevaluatedProperties", "propertyNames", "contains", "items", "additionalItems", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]
|
|
9
|
+
const isObject = (v) => v != null && typeof v === "object" && !Array.isArray(v)
|
|
10
|
+
|
|
11
|
+
export function parseToolJSON(text) {
|
|
12
|
+
return JSON.parse(text, (_key, value, context) => {
|
|
13
|
+
if (typeof value !== "number" || Number.isSafeInteger(value)) return value
|
|
14
|
+
if (context?.source && typeof JSON.rawJSON === "function") return JSON.rawJSON(context.source)
|
|
15
|
+
// Never round a tool's large integer into a different argument on an old
|
|
16
|
+
// runtime that cannot retain JSON number tokens.
|
|
17
|
+
if (!Number.isFinite(value) || Number.isInteger(value)) throw new Error("Factory: this runtime cannot preserve the tool's JSON number")
|
|
18
|
+
return value
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function rebaseSchema(schema, rebase = true, legacy = false) {
|
|
23
|
+
if (!isObject(schema)) return
|
|
24
|
+
const id = schema.$id ?? (legacy ? schema.id : undefined)
|
|
25
|
+
if (typeof id === "string" && id.split("#")[0]) rebase = false
|
|
26
|
+
if (rebase) {
|
|
27
|
+
// Draft 2019-09's recursive anchor must remain a resource root. Refuse
|
|
28
|
+
// this unsupported relocation instead of changing its resolution scope.
|
|
29
|
+
if (schema.$recursiveAnchor === true || Object.hasOwn(schema, "$recursiveRef")) throw new Error("Factory: a recursive tool schema needs $id before it can be wrapped")
|
|
30
|
+
for (const key of ["$ref", "$dynamicRef"]) {
|
|
31
|
+
const ref = schema[key]
|
|
32
|
+
if (typeof ref !== "string" || !ref.startsWith("#")) continue
|
|
33
|
+
const pointer = decodeURIComponent(ref.slice(1))
|
|
34
|
+
if (pointer === "" || pointer.startsWith("/")) schema[key] = "#/properties/" + argument + ref.slice(1)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// Visit schema positions only: const/default/examples may contain ordinary
|
|
38
|
+
// data named $ref, properties or anyOf and must not be rewritten.
|
|
39
|
+
for (const key of schemaMaps) {
|
|
40
|
+
if (isObject(schema[key])) for (const child of Object.values(schema[key])) rebaseSchema(child, rebase, legacy)
|
|
41
|
+
}
|
|
42
|
+
for (const key of schemaLists) {
|
|
43
|
+
if (Array.isArray(schema[key])) for (const child of schema[key]) rebaseSchema(child, rebase, legacy)
|
|
44
|
+
}
|
|
45
|
+
for (const key of schemaValues) {
|
|
46
|
+
if (Array.isArray(schema[key])) for (const child of schema[key]) rebaseSchema(child, rebase, legacy)
|
|
47
|
+
else rebaseSchema(schema[key], rebase, legacy)
|
|
48
|
+
}
|
|
49
|
+
if (isObject(schema.dependencies)) for (const child of Object.values(schema.dependencies)) rebaseSchema(child, rebase, legacy)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function wrapAnthropicTools(body) {
|
|
53
|
+
const names = new Set()
|
|
54
|
+
const text = typeof body === "string" ? body
|
|
55
|
+
: body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8")
|
|
56
|
+
: ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : ""
|
|
57
|
+
let request
|
|
58
|
+
try { request = parseToolJSON(text) } catch (e) {
|
|
59
|
+
if (!(e instanceof SyntaxError)) throw e
|
|
60
|
+
return { body, names }
|
|
61
|
+
}
|
|
62
|
+
if (!Array.isArray(request?.tools) || !Array.isArray(request.messages)) return { body, names }
|
|
63
|
+
for (const tool of request.tools) {
|
|
64
|
+
const schema = tool?.input_schema
|
|
65
|
+
if (typeof tool?.name !== "string" || !isObject(schema) || !compositions.some((key) => Object.hasOwn(schema, key))) continue
|
|
66
|
+
rebaseSchema(schema, true, /draft-0[34]/.test(schema.$schema ?? ""))
|
|
67
|
+
tool.input_schema = { type: "object", properties: { [argument]: schema }, required: [argument], additionalProperties: false }
|
|
68
|
+
if (schema.$schema) tool.input_schema.$schema = schema.$schema
|
|
69
|
+
if (Array.isArray(tool.input_examples)) tool.input_examples = tool.input_examples.map((input) => ({ [argument]: input }))
|
|
70
|
+
names.add(tool.name)
|
|
71
|
+
}
|
|
72
|
+
if (!names.size) return { body, names }
|
|
73
|
+
for (const message of request.messages) {
|
|
74
|
+
if (message?.role !== "assistant" || !Array.isArray(message.content)) continue
|
|
75
|
+
for (const block of message.content) {
|
|
76
|
+
if (block?.type === "tool_use" && names.has(block.name) && Object.hasOwn(block, "input")) block.input = { [argument]: block.input }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { body: JSON.stringify(request), names }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function unwrap(input, name) {
|
|
83
|
+
if (!isObject(input) || !Object.hasOwn(input, argument) || Object.keys(input).length !== 1) throw new Error(`Factory: tool ${name} returned invalid wrapped arguments`)
|
|
84
|
+
return input[argument]
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function responseHeaders(res) {
|
|
88
|
+
const headers = new Headers(res.headers)
|
|
89
|
+
headers.delete("content-length")
|
|
90
|
+
headers.delete("content-encoding")
|
|
91
|
+
return { status: res.status, statusText: res.statusText, headers }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function toolStream(body, names) {
|
|
95
|
+
const reader = body.getReader()
|
|
96
|
+
const decoder = new TextDecoder("utf-8", { fatal: true })
|
|
97
|
+
const encoder = new TextEncoder()
|
|
98
|
+
const blocks = new Map()
|
|
99
|
+
let pending = "", ended = false
|
|
100
|
+
const incomplete = () => {
|
|
101
|
+
if (blocks.size) throw new Error("Factory: incomplete wrapped tool arguments")
|
|
102
|
+
}
|
|
103
|
+
const frame = (raw, ending) => {
|
|
104
|
+
const lines = raw.split(/\r\n|\n|\r/)
|
|
105
|
+
const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n")
|
|
106
|
+
if (!data) return [raw + ending]
|
|
107
|
+
if (data === "[DONE]") { incomplete(); return [raw + ending] }
|
|
108
|
+
const event = parseToolJSON(data)
|
|
109
|
+
const replace = (value) => {
|
|
110
|
+
let first = true
|
|
111
|
+
const next = []
|
|
112
|
+
for (const line of lines) {
|
|
113
|
+
if (!line.startsWith("data:")) next.push(line)
|
|
114
|
+
else if (first) { next.push("data: " + JSON.stringify(value)); first = false }
|
|
115
|
+
}
|
|
116
|
+
return next.join(raw.includes("\r\n") ? "\r\n" : "\n") + ending
|
|
117
|
+
}
|
|
118
|
+
if (event.type === "content_block_start" && event.content_block?.type === "tool_use" && names.has(event.content_block.name)) {
|
|
119
|
+
if (blocks.has(event.index)) throw new Error("Factory: duplicate wrapped tool block")
|
|
120
|
+
blocks.set(event.index, { name: event.content_block.name, json: "", initial: event.content_block.input })
|
|
121
|
+
event.content_block.input = {}
|
|
122
|
+
return [replace(event)]
|
|
123
|
+
}
|
|
124
|
+
const block = blocks.get(event.index)
|
|
125
|
+
if (block && event.type === "content_block_delta" && event.delta?.type === "input_json_delta") {
|
|
126
|
+
if (typeof event.delta.partial_json !== "string") throw new Error("Factory: invalid tool argument delta")
|
|
127
|
+
block.json += event.delta.partial_json
|
|
128
|
+
return []
|
|
129
|
+
}
|
|
130
|
+
if (block && event.type === "content_block_stop") {
|
|
131
|
+
const input = unwrap(block.json ? parseToolJSON(block.json) : block.initial, block.name)
|
|
132
|
+
blocks.delete(event.index)
|
|
133
|
+
const delta = { type: "content_block_delta", index: event.index, delta: { type: "input_json_delta", partial_json: JSON.stringify(input) } }
|
|
134
|
+
return ["event: content_block_delta\ndata: " + JSON.stringify(delta) + "\n\n", raw + ending]
|
|
135
|
+
}
|
|
136
|
+
if (event.type === "error") blocks.clear() // preserve the upstream error
|
|
137
|
+
if (event.type === "message_stop") incomplete()
|
|
138
|
+
return [raw + ending]
|
|
139
|
+
}
|
|
140
|
+
return new ReadableStream({
|
|
141
|
+
async pull(controller) {
|
|
142
|
+
try {
|
|
143
|
+
while (true) {
|
|
144
|
+
const boundary = /\r\n\r\n|\r\n\n|\n\r\n|\n\n|\r\r/.exec(pending)
|
|
145
|
+
if (boundary || (ended && pending)) {
|
|
146
|
+
const raw = boundary ? pending.slice(0, boundary.index) : pending
|
|
147
|
+
const ending = boundary?.[0] ?? ""
|
|
148
|
+
pending = boundary ? pending.slice(boundary.index + ending.length) : ""
|
|
149
|
+
const out = frame(raw, ending)
|
|
150
|
+
for (const value of out) controller.enqueue(encoder.encode(value))
|
|
151
|
+
if (out.length) return
|
|
152
|
+
continue
|
|
153
|
+
}
|
|
154
|
+
if (ended) { incomplete(); controller.close(); return }
|
|
155
|
+
const chunk = await reader.read()
|
|
156
|
+
pending += decoder.decode(chunk.value, { stream: !chunk.done })
|
|
157
|
+
ended = chunk.done
|
|
158
|
+
}
|
|
159
|
+
} catch (e) {
|
|
160
|
+
controller.error(e)
|
|
161
|
+
await reader.cancel(e).catch(() => {})
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
cancel(reason) { return reader.cancel(reason) },
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function unwrapAnthropicTools(res, names) {
|
|
169
|
+
if (!names.size || !res.ok || !res.body) return res
|
|
170
|
+
if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) return new Response(toolStream(res.body, names), responseHeaders(res))
|
|
171
|
+
if (!(res.headers.get("content-type") ?? "").includes("json")) return res
|
|
172
|
+
const text = await res.text()
|
|
173
|
+
const message = parseToolJSON(text)
|
|
174
|
+
let changed = false
|
|
175
|
+
for (const block of Array.isArray(message?.content) ? message.content : []) {
|
|
176
|
+
if (block?.type !== "tool_use" || !names.has(block.name)) continue
|
|
177
|
+
block.input = unwrap(block.input, block.name)
|
|
178
|
+
changed = true
|
|
179
|
+
}
|
|
180
|
+
return new Response(changed ? JSON.stringify(message) : text, responseHeaders(res))
|
|
181
|
+
}
|
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 { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs"
|
|
7
8
|
|
|
8
9
|
const PROVIDER = "factory"
|
|
9
10
|
|
|
@@ -604,7 +605,20 @@ const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^
|
|
|
604
605
|
const SYSTEM_MODEL_UPDATE = /^You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/
|
|
605
606
|
const SYSTEM_ENV_UPDATE = /^# Environment update\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
|
|
606
607
|
const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_tokens>(?=\n\n|$)/
|
|
608
|
+
// A SessionStart hook's output comes ahead of the generated context in the
|
|
609
|
+
// same message (Claude Code 2.1.288 with a hook installed, #634): the
|
|
610
|
+
// context after it is adapted as it would be on its own, the hook's output
|
|
611
|
+
// is left as it is.
|
|
612
|
+
const HOOK_OUTPUT = /^SessionStart:[^\n]* hook success:/
|
|
613
|
+
const HOOK_CONTEXT = "\n# Environment\nYou have been invoked in the following environment:"
|
|
607
614
|
function systemContext(text) {
|
|
615
|
+
if (HOOK_OUTPUT.test(text)) {
|
|
616
|
+
const at = text.indexOf(HOOK_CONTEXT)
|
|
617
|
+
return at < 0 ? text : text.slice(0, at + 1) + generatedContext(text.slice(at + 1))
|
|
618
|
+
}
|
|
619
|
+
return generatedContext(text)
|
|
620
|
+
}
|
|
621
|
+
function generatedContext(text) {
|
|
608
622
|
const environment = SYSTEM_ENV_CONTEXT.test(text)
|
|
609
623
|
if (!environment && !((SYSTEM_MODEL_UPDATE.test(text) || SYSTEM_ENV_UPDATE.test(text)) && SYSTEM_TOKEN_CONTEXT.test(text))) return text
|
|
610
624
|
let out = text.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
|
|
@@ -624,6 +638,22 @@ function systemContext(text) {
|
|
|
624
638
|
return out
|
|
625
639
|
}
|
|
626
640
|
|
|
641
|
+
// The model line inside a system prompt (Claude Desktop's, #634) is the
|
|
642
|
+
// same generated sentence as in a reminder; only that line changes.
|
|
643
|
+
const SYSTEM_MODEL_LINE = /(^|\n)You are powered by the model [^\n<>]+/g
|
|
644
|
+
function systemModelLine(text) {
|
|
645
|
+
return text.replace(SYSTEM_MODEL_LINE, (line) => line
|
|
646
|
+
.replace("You are powered by the model named", "Current model name:")
|
|
647
|
+
.replace("You are powered by the model", "Current model:")
|
|
648
|
+
.replace("The exact model ID is", "Model ID:")
|
|
649
|
+
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:"))
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// The reminder carrying CLAUDE.md files names the global one with a phrase
|
|
653
|
+
// Factory refuses; only that phrase in the generated reminder changes.
|
|
654
|
+
const INSTRUCTIONS_REMINDER = "<system-reminder>\nCodebase and user instructions are shown below"
|
|
655
|
+
const GLOBAL_INSTRUCTIONS = "(user's private global instructions for all projects)"
|
|
656
|
+
|
|
627
657
|
// Factory also refuses these fixed client phrases when they are quoted in
|
|
628
658
|
// tool output, e.g. while reading this adapter's source. Keep the original
|
|
629
659
|
// text recoverable: a JSON string with explicit decoding instructions,
|
|
@@ -647,7 +677,7 @@ function anthropicBody(body) {
|
|
|
647
677
|
const text = typeof body === "string" ? body
|
|
648
678
|
: body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8")
|
|
649
679
|
: ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : ""
|
|
650
|
-
request =
|
|
680
|
+
request = parseToolJSON(text)
|
|
651
681
|
} catch {
|
|
652
682
|
return body
|
|
653
683
|
}
|
|
@@ -676,6 +706,12 @@ function anthropicBody(body) {
|
|
|
676
706
|
if (block?.type === "text" && CLAUDE_IDENTITIES.has(block.text)) {
|
|
677
707
|
block.text = DROID_LINE
|
|
678
708
|
changed = true
|
|
709
|
+
} else if (block?.type === "text") {
|
|
710
|
+
const adapted = systemModelLine(block.text)
|
|
711
|
+
if (adapted !== block.text) {
|
|
712
|
+
block.text = adapted
|
|
713
|
+
changed = true
|
|
714
|
+
}
|
|
679
715
|
}
|
|
680
716
|
kept.push(block)
|
|
681
717
|
}
|
|
@@ -728,7 +764,17 @@ function anthropicBody(body) {
|
|
|
728
764
|
continue
|
|
729
765
|
}
|
|
730
766
|
if (block?.type !== "text" || typeof block.text !== "string") continue
|
|
731
|
-
if (
|
|
767
|
+
if (block.text.startsWith(INSTRUCTIONS_REMINDER) && block.text.includes(GLOBAL_INSTRUCTIONS)) {
|
|
768
|
+
block.text = block.text.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)")
|
|
769
|
+
changed = true
|
|
770
|
+
} else if (HOOK_OUTPUT.test(block.text)) {
|
|
771
|
+
// a system message folded into the user's turn on its way here
|
|
772
|
+
const adapted = systemContext(block.text)
|
|
773
|
+
if (adapted !== block.text) {
|
|
774
|
+
block.text = adapted
|
|
775
|
+
changed = true
|
|
776
|
+
}
|
|
777
|
+
} else if (ENV_REMINDER.test(block.text)) {
|
|
732
778
|
block.text = block.text.replace("# Environment", "# Runtime context")
|
|
733
779
|
.replace("You have been invoked in the following environment:", "The session environment is:")
|
|
734
780
|
changed = true
|
|
@@ -1050,10 +1096,12 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
1050
1096
|
// which Anthropic's SDK sends beside the bearer token
|
|
1051
1097
|
if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
|
|
1052
1098
|
// another agent's request opens as droid's does (droidBody)
|
|
1053
|
-
const
|
|
1054
|
-
|
|
1099
|
+
const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
|
|
1100
|
+
const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() }
|
|
1101
|
+
const out = adapted.body
|
|
1055
1102
|
if (out !== body) h.delete("content-length")
|
|
1056
|
-
|
|
1103
|
+
const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
|
|
1104
|
+
return path.endsWith("/messages") ? unwrapAnthropicTools(res, adapted.names) : res
|
|
1057
1105
|
}
|
|
1058
1106
|
|
|
1059
1107
|
return {
|
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.13",
|
|
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", "README.md"],
|
|
7
|
+
"files": ["index.mjs", "anthropic-tools.mjs", "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" }
|