@magpie-community/opencode-zcode-auth 0.1.29 → 0.1.31
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 +15 -1
- package/index.mjs +166 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,7 +25,13 @@ over Anthropic's Messages API. Provider id: `zcode`.
|
|
|
25
25
|
agent's system prompt at the end of the third (a fourth block is
|
|
26
26
|
refused, #343), the day in a `<system-reminder>` turn before the agent's
|
|
27
27
|
turns, and the sign-in's device id in `metadata.user_id`. GLM Coding
|
|
28
|
-
Plan and team requests go as the agent sent them
|
|
28
|
+
Plan and team requests go as the agent sent them, but for that same
|
|
29
|
+
`metadata.user_id` when the agent sent none: ZCode puts it on every
|
|
30
|
+
request, and the plan's endpoint keeps a prompt cache on the machine it
|
|
31
|
+
picks by it, so without it the cache is mostly missed (#387). An
|
|
32
|
+
account known only by its key gets a device id made from the key, the
|
|
33
|
+
same on every start. Every request also carries the `x-session-id`
|
|
34
|
+
header below. zcode.z.ai also
|
|
29
35
|
answers 405 code 3012 to every request of an account its risk control
|
|
30
36
|
blocked, ZCode's own app's included (plugins#348). That answer comes
|
|
31
37
|
back as ZCode's words, then "ZCode's risk control blocked this account
|
|
@@ -35,6 +41,14 @@ over Anthropic's Messages API. Provider id: `zcode`.
|
|
|
35
41
|
firewall says this network's address was blocked instead.
|
|
36
42
|
- The Start Plan's token can't be refreshed. When it runs out, sign in
|
|
37
43
|
again.
|
|
44
|
+
- Every request, on any plan, names its conversation in `x-session-id`,
|
|
45
|
+
as ZCode does: a bare UUID, the same on each turn. BigModel's prompt
|
|
46
|
+
cache follows it: without it a long conversation's turns hit the cache
|
|
47
|
+
about one time in twenty, with it nearly every turn (#387). The
|
|
48
|
+
agent's own session id (magpie tells it to the plugin) goes as it is
|
|
49
|
+
when it is a UUID, else as a UUID made from it, so the vendor sees
|
|
50
|
+
only ZCode's format; with none, a UUID made from the device. The same
|
|
51
|
+
id is `metadata.user_id`'s `session_id`, as in ZCode's requests.
|
|
38
52
|
- **ZCode: a team's GLM Coding Plan**
|
|
39
53
|
- For an account with a plan of its own and a seat on a team's plan
|
|
40
54
|
(#285). The sign-ins above take the account's own plan, as ZCode does
|
package/index.mjs
CHANGED
|
@@ -50,6 +50,15 @@ const siteOf = (s) => (s === "bigmodel" ? "bigmodel" : "zai")
|
|
|
50
50
|
const platform = () => `${process.platform}-${process.arch}` // darwin-arm64, win32-x64, linux-x64, as ZCode names them
|
|
51
51
|
const uuid = () => crypto.randomUUID()
|
|
52
52
|
const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list)
|
|
53
|
+
// uuidOf is a version 4 shaped UUID made from a seed: the same seed gives
|
|
54
|
+
// the same UUID every time
|
|
55
|
+
const uuidOf = (seed) => {
|
|
56
|
+
const h = createHash("sha256").update(seed).digest("hex")
|
|
57
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16], 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`
|
|
58
|
+
}
|
|
59
|
+
// keyDevice is a device id for an account known only by its key: the same
|
|
60
|
+
// key gives the same id on every start, as a sign-in's saved device does
|
|
61
|
+
const keyDevice = (key) => uuidOf("zcode-device\0" + key)
|
|
53
62
|
const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? ""
|
|
54
63
|
|
|
55
64
|
// STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
|
|
@@ -1191,6 +1200,86 @@ function configKey(key) {
|
|
|
1191
1200
|
return null
|
|
1192
1201
|
}
|
|
1193
1202
|
|
|
1203
|
+
// ownLocation is where ZCode 3.16 finds the account's own coding plan key
|
|
1204
|
+
// when it keeps none: credentials.json's
|
|
1205
|
+
// project-key-location:v1:<[origin, family, accountId, team, 1, selection]>,
|
|
1206
|
+
// URI-encoded JSON, holds { organizationId, projectId, apiKeyId } (its
|
|
1207
|
+
// ProjectAccessTokenClient). ZCode trades that key for a short-lived
|
|
1208
|
+
// project token each time; here its secret is read (located), as a sign-in
|
|
1209
|
+
// here reads its own key's. The account's own (team null), of the family
|
|
1210
|
+
// ZCode is on first, else Z.ai's, as ZCode lists them; one of another
|
|
1211
|
+
// account the profile names is left alone (meraki7304, #410).
|
|
1212
|
+
const LOCATION = "project-key-location:v1:"
|
|
1213
|
+
function ownLocation(store, key) {
|
|
1214
|
+
const set = readJSON(join(settingDir(), "setting.json"))
|
|
1215
|
+
const fams = set?.providerFamilyDomain === "bigmodel" ? ["bigmodel", "zai"] : ["zai", "bigmodel"]
|
|
1216
|
+
const found = []
|
|
1217
|
+
for (const [name, v] of Object.entries(store)) {
|
|
1218
|
+
if (!name.startsWith(LOCATION)) continue
|
|
1219
|
+
let at
|
|
1220
|
+
try {
|
|
1221
|
+
at = JSON.parse(decodeURIComponent(name.slice(LOCATION.length)))
|
|
1222
|
+
} catch {
|
|
1223
|
+
continue
|
|
1224
|
+
}
|
|
1225
|
+
if (!Array.isArray(at) || at[3] !== null || String(at[4]) !== "1" || !fams.includes(at[1])) continue
|
|
1226
|
+
let loc
|
|
1227
|
+
try {
|
|
1228
|
+
loc = JSON.parse(decrypt(key, v) ?? "")
|
|
1229
|
+
} catch {}
|
|
1230
|
+
const org = first(loc?.organizationId), project = first(loc?.projectId), apiKeyId = first(loc?.apiKeyId)
|
|
1231
|
+
if (!org || !project || !apiKeyId) continue
|
|
1232
|
+
found.push({ site: at[1], origin: typeof at[0] === "string" ? at[0] : "", account: String(at[2] ?? ""), org, project, apiKeyId })
|
|
1233
|
+
}
|
|
1234
|
+
for (const site of fams) {
|
|
1235
|
+
const token = first(decrypt(key, store[`oauth:${site}:access_token`]))
|
|
1236
|
+
if (!token) continue
|
|
1237
|
+
let me = ""
|
|
1238
|
+
try {
|
|
1239
|
+
me = String(JSON.parse(decrypt(key, store[`oauth:${site}:user_info`]) ?? "{}")?.id ?? "")
|
|
1240
|
+
} catch {}
|
|
1241
|
+
const mine = found.filter((l) => l.site === site && (!me || l.account === me))
|
|
1242
|
+
if (!mine.length) continue
|
|
1243
|
+
const l = mine[0]
|
|
1244
|
+
// the origin ZCode asked, when it is the site's own; else the site's API
|
|
1245
|
+
let origin = SITES[site].api
|
|
1246
|
+
try {
|
|
1247
|
+
const u = new URL(l.origin)
|
|
1248
|
+
const h = u.host.toLowerCase()
|
|
1249
|
+
if (u.protocol === "https:" && (site === "zai" ? h === "z.ai" || h.endsWith(".z.ai") : h === "bigmodel.cn" || h.endsWith(".bigmodel.cn"))) origin = u.origin
|
|
1250
|
+
} catch {}
|
|
1251
|
+
return { site, base: SITES[site].base, token, loc: { origin, org: l.org, project: l.project, apiKeyId: l.apiKeyId } }
|
|
1252
|
+
}
|
|
1253
|
+
return null
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// located gives a sign-in that has only ZCode's key location (ownLocation)
|
|
1257
|
+
// its key: the secret of the key it names, read as ZCode lists the
|
|
1258
|
+
// project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is
|
|
1259
|
+
// made: a location whose key is gone (404) leaves the sign-in keyless, as
|
|
1260
|
+
// before; any other failure is said. A key read is kept for the token.
|
|
1261
|
+
const locatedKeys = new Map()
|
|
1262
|
+
async function located(s) {
|
|
1263
|
+
if (!s || s.key || !s.loc || !s.token) return s
|
|
1264
|
+
const l = s.loc
|
|
1265
|
+
const id = [s.token, l.origin, l.org, l.project, l.apiKeyId].join("\0")
|
|
1266
|
+
let got = locatedKeys.get(id)
|
|
1267
|
+
if (!got || (got.err && Date.now() - got.at >= 60_000)) {
|
|
1268
|
+
const auth = s.site === "zai" ? "Bearer " + s.token : s.token
|
|
1269
|
+
try {
|
|
1270
|
+
const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth }))?.secretKey)
|
|
1271
|
+
got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") }
|
|
1272
|
+
} catch (e) {
|
|
1273
|
+
got = e?.status === 404 ? { key: "" } : { err: e }
|
|
1274
|
+
}
|
|
1275
|
+
got.at = Date.now()
|
|
1276
|
+
locatedKeys.set(id, got)
|
|
1277
|
+
}
|
|
1278
|
+
if (got.err) throw new Error(`ZCode's ${SITES[s.site].name} coding plan key: ${got.err.message} — sign in to ZCode again`)
|
|
1279
|
+
if (got.key) s.key = got.key
|
|
1280
|
+
return s
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1194
1283
|
// ownSignIn is what ZCode is signed in to now: the account, its coding
|
|
1195
1284
|
// plan key, ZCode's session token (the Start Plan's key) and the team plan
|
|
1196
1285
|
// it is switched to; null when it has none of them.
|
|
@@ -1211,6 +1300,8 @@ function ownSignIn() {
|
|
|
1211
1300
|
// ZCode 3.15 keeps no plan key in its credentials; the one it uses sits
|
|
1212
1301
|
// in config.json, the provider's options.apiKey (yetone/magpie#2130)
|
|
1213
1302
|
if (!s.key) s = configKey(key) || s
|
|
1303
|
+
// ZCode 3.16 keeps neither: only where the key is (#410)
|
|
1304
|
+
if (!s.key) s = ownLocation(store, key) || s
|
|
1214
1305
|
const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
|
|
1215
1306
|
const team = ownTeam(store, key)
|
|
1216
1307
|
if (team) s = { ...team, jwt }
|
|
@@ -1265,11 +1356,13 @@ function stateOf(auth) {
|
|
|
1265
1356
|
}
|
|
1266
1357
|
}
|
|
1267
1358
|
const site = siteOf(s.site)
|
|
1268
|
-
|
|
1359
|
+
const key = s.key ?? (s.jwt ? "" : auth.access)
|
|
1360
|
+
return { ...s, site, base: s.base || SITES[site].base, key, device: s.device || (key ? keyDevice(key) : anyDevice) }
|
|
1269
1361
|
}
|
|
1270
1362
|
if (auth?.type === "api") {
|
|
1271
1363
|
const site = siteOf(auth.metadata?.site)
|
|
1272
|
-
|
|
1364
|
+
const key = String(auth.key ?? "").trim()
|
|
1365
|
+
return { site, base: SITES[site].base, key, device: key ? keyDevice(key) : anyDevice }
|
|
1273
1366
|
}
|
|
1274
1367
|
return null
|
|
1275
1368
|
}
|
|
@@ -1724,7 +1817,7 @@ function contextPrefix() {
|
|
|
1724
1817
|
// sign-in's device. site names the powered-by line's provider, place where
|
|
1725
1818
|
// the agent works (workPlace). A body that isn't a Messages request goes as
|
|
1726
1819
|
// it is.
|
|
1727
|
-
function dress(text, site, device, place) {
|
|
1820
|
+
function dress(text, site, device, place, session) {
|
|
1728
1821
|
if (typeof text !== "string" || !text.includes("messages")) return text
|
|
1729
1822
|
let b
|
|
1730
1823
|
try {
|
|
@@ -1764,10 +1857,51 @@ function dress(text, site, device, place) {
|
|
|
1764
1857
|
}
|
|
1765
1858
|
if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control
|
|
1766
1859
|
const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {}
|
|
1767
|
-
b.metadata = { ...meta, user_id:
|
|
1860
|
+
b.metadata = { ...meta, user_id: userIdOf(device, session) }
|
|
1861
|
+
return JSON.stringify(b)
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
// userIdOf is metadata.user_id as ZCode's client (3.14.3, glm/zcode.cjs
|
|
1865
|
+
// MLs and vWr) puts it on every Anthropic-format request, a coding plan's
|
|
1866
|
+
// too: the machine's device id, no account uuid. The plan's endpoint keeps
|
|
1867
|
+
// a prompt cache on the machine it picks by it, so a request without it
|
|
1868
|
+
// lands anywhere and its cache is mostly missed (#387). Its session_id is
|
|
1869
|
+
// the request's x-session-id (sessionOf), as ZCode's is.
|
|
1870
|
+
const userIdOf = (device, session = "") => JSON.stringify({ device_id: device, account_uuid: "", session_id: session })
|
|
1871
|
+
|
|
1872
|
+
// marked is a coding plan's Messages request body with metadata.user_id
|
|
1873
|
+
// as ZCode sends it, when the agent sent none of its own. Anything else,
|
|
1874
|
+
// a body that isn't a Messages request among them, goes as it is.
|
|
1875
|
+
function marked(text, device, session) {
|
|
1876
|
+
if (typeof text !== "string" || !device || !text.includes("messages")) return text
|
|
1877
|
+
let b
|
|
1878
|
+
try {
|
|
1879
|
+
b = JSON.parse(text)
|
|
1880
|
+
} catch {
|
|
1881
|
+
return text
|
|
1882
|
+
}
|
|
1883
|
+
if (!b || typeof b !== "object" || Array.isArray(b) || !Array.isArray(b.messages)) return text
|
|
1884
|
+
const meta = b.metadata && typeof b.metadata === "object" && !Array.isArray(b.metadata) ? b.metadata : {}
|
|
1885
|
+
if (typeof meta.user_id === "string" && meta.user_id.trim()) return text
|
|
1886
|
+
b.metadata = { ...meta, user_id: userIdOf(device, session) }
|
|
1768
1887
|
return JSON.stringify(b)
|
|
1769
1888
|
}
|
|
1770
1889
|
|
|
1890
|
+
// sessionOf is the x-session-id a request goes with, as ZCode's client
|
|
1891
|
+
// (3.14.3, glm/zcode.cjs xst and Tst) sends it: a bare UUID, the same on
|
|
1892
|
+
// every turn of a conversation. BigModel keeps a prompt's cache for the
|
|
1893
|
+
// requests that name the same session and seldom for those that name none
|
|
1894
|
+
// (#387). The agent's session (chat.headers below) goes as it is when it is
|
|
1895
|
+
// a UUID, else as a UUID made from it, so the vendor sees only ZCode's
|
|
1896
|
+
// format, never magpie's or another agent's; with none, a UUID made from
|
|
1897
|
+
// the device.
|
|
1898
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
1899
|
+
function sessionOf(id, device) {
|
|
1900
|
+
const own = typeof id === "string" ? id.trim() : ""
|
|
1901
|
+
if (UUID.test(own)) return own.toLowerCase()
|
|
1902
|
+
return uuidOf(own ? "zcode-session\0" + own : "zcode-session-device\0" + (device ?? ""))
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1771
1905
|
// ---- the plugin ------------------------------------------------------------------
|
|
1772
1906
|
|
|
1773
1907
|
export async function ZCodeAuthPlugin({ client }) {
|
|
@@ -1782,6 +1916,14 @@ export async function ZCodeAuthPlugin({ client }) {
|
|
|
1782
1916
|
authorize: () => authorize(site, log),
|
|
1783
1917
|
})
|
|
1784
1918
|
return {
|
|
1919
|
+
// the agent's session, which magpie tells the plugins here and not
|
|
1920
|
+
// in the request, goes on as x-session-id (sessionOf)
|
|
1921
|
+
"chat.headers": async (input, output) => {
|
|
1922
|
+
const provider = input?.model?.providerID ?? input?.provider?.info?.id
|
|
1923
|
+
if (provider !== PROVIDER) return
|
|
1924
|
+
const id = input?.sessionID
|
|
1925
|
+
if (typeof id === "string" && id.trim()) output.headers["x-session-id"] = sessionOf(id)
|
|
1926
|
+
},
|
|
1785
1927
|
config: async (cfg) => {
|
|
1786
1928
|
cfg.provider ??= {}
|
|
1787
1929
|
const was = cfg.provider[PROVIDER] ?? {}
|
|
@@ -1846,7 +1988,7 @@ export async function ZCodeAuthPlugin({ client }) {
|
|
|
1846
1988
|
apiKey: s0.key || "zcode", // the fetch below puts the real one on
|
|
1847
1989
|
async fetch(input, init) {
|
|
1848
1990
|
const auth = await getAuth()
|
|
1849
|
-
const s = stateOf(auth)
|
|
1991
|
+
const s = await located(stateOf(auth))
|
|
1850
1992
|
if (!s) throw new Error("not signed in to ZCode")
|
|
1851
1993
|
let url = input instanceof Request ? input.url : String(input)
|
|
1852
1994
|
const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
|
|
@@ -1901,6 +2043,7 @@ export async function ZCodeAuthPlugin({ client }) {
|
|
|
1901
2043
|
}
|
|
1902
2044
|
let h = new Headers(opts.headers)
|
|
1903
2045
|
const place = workPlace(h)
|
|
2046
|
+
const sid = sessionOf(h.get("x-session-id"), s.device)
|
|
1904
2047
|
if (start) {
|
|
1905
2048
|
if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
|
|
1906
2049
|
if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
|
|
@@ -1908,16 +2051,27 @@ export async function ZCodeAuthPlugin({ client }) {
|
|
|
1908
2051
|
// the Start Plan is served only to what looks like ZCode's own request
|
|
1909
2052
|
url = startURL(url)
|
|
1910
2053
|
h = startHeaders(h, s.jwt)
|
|
2054
|
+
h.set("x-session-id", sid)
|
|
1911
2055
|
if (opts.body != null) {
|
|
1912
2056
|
const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
|
|
1913
|
-
opts.body = dress(text, s.site, s.device, place)
|
|
2057
|
+
opts.body = dress(text, s.site, s.device, place, sid)
|
|
1914
2058
|
delete opts.duplex
|
|
1915
2059
|
h.delete("content-length")
|
|
1916
2060
|
}
|
|
1917
2061
|
} else {
|
|
1918
2062
|
if (!key) throw new Error("ZCode's sign-in has no key; sign in again")
|
|
1919
2063
|
swap(s.base)
|
|
2064
|
+
// a Messages request names the device, as ZCode's does (#387);
|
|
2065
|
+
// count_tokens and other paths ZCode never sends go as they are
|
|
2066
|
+
if (opts.body != null && /\/v1\/messages$/.test(new URL(url).pathname)) {
|
|
2067
|
+
const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
|
|
2068
|
+
const next = marked(text, s.device, sid)
|
|
2069
|
+
if (next !== text) h.delete("content-length")
|
|
2070
|
+
opts.body = next
|
|
2071
|
+
delete opts.duplex
|
|
2072
|
+
}
|
|
1920
2073
|
if (renamed) h.delete("content-length")
|
|
2074
|
+
h.set("x-session-id", sid)
|
|
1921
2075
|
h.delete("authorization")
|
|
1922
2076
|
h.set("x-api-key", key)
|
|
1923
2077
|
h.set("Authorization", "Bearer " + key)
|
|
@@ -1976,6 +2130,11 @@ export async function ZCodeAuthPlugin({ client }) {
|
|
|
1976
2130
|
const auth = await getAuth()
|
|
1977
2131
|
const s = stateOf(auth)
|
|
1978
2132
|
if (!s) return { error: "not signed in", signIn: "kept" }
|
|
2133
|
+
try {
|
|
2134
|
+
await located(s)
|
|
2135
|
+
} catch (e) {
|
|
2136
|
+
return { error: e.message, signIn: "kept" }
|
|
2137
|
+
}
|
|
1979
2138
|
// every card starts from the plan the sign-in saved, as magpie's
|
|
1980
2139
|
// built-in did: a reply without a level, a team detail that
|
|
1981
2140
|
// failed or an error keeps it
|
|
@@ -2070,4 +2229,4 @@ export async function ZCodeAuthPlugin({ client }) {
|
|
|
2070
2229
|
// config sets what zcodeConfig has read, for tests: null is ZCode's config
|
|
2071
2230
|
// out of reach, undefined forgets it
|
|
2072
2231
|
const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
|
|
2073
|
-
export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT }
|
|
2232
|
+
export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-zcode-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.31",
|
|
4
4
|
"description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|