@magpie-community/opencode-factory-auth 0.1.12 → 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 +7 -4
- 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
|
|
|
@@ -676,7 +677,7 @@ function anthropicBody(body) {
|
|
|
676
677
|
const text = typeof body === "string" ? body
|
|
677
678
|
: body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8")
|
|
678
679
|
: ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : ""
|
|
679
|
-
request =
|
|
680
|
+
request = parseToolJSON(text)
|
|
680
681
|
} catch {
|
|
681
682
|
return body
|
|
682
683
|
}
|
|
@@ -1095,10 +1096,12 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
1095
1096
|
// which Anthropic's SDK sends beside the bearer token
|
|
1096
1097
|
if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
|
|
1097
1098
|
// another agent's request opens as droid's does (droidBody)
|
|
1098
|
-
const
|
|
1099
|
-
|
|
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
|
|
1100
1102
|
if (out !== body) h.delete("content-length")
|
|
1101
|
-
|
|
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
|
|
1102
1105
|
}
|
|
1103
1106
|
|
|
1104
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" }
|