@magpie-community/opencode-zcode-auth 0.1.30 → 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.
Files changed (3) hide show
  1. package/README.md +10 -1
  2. package/index.mjs +131 -14
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -30,7 +30,8 @@ over Anthropic's Messages API. Provider id: `zcode`.
30
30
  request, and the plan's endpoint keeps a prompt cache on the machine it
31
31
  picks by it, so without it the cache is mostly missed (#387). An
32
32
  account known only by its key gets a device id made from the key, the
33
- same on every start. zcode.z.ai also
33
+ same on every start. Every request also carries the `x-session-id`
34
+ header below. zcode.z.ai also
34
35
  answers 405 code 3012 to every request of an account its risk control
35
36
  blocked, ZCode's own app's included (plugins#348). That answer comes
36
37
  back as ZCode's words, then "ZCode's risk control blocked this account
@@ -40,6 +41,14 @@ over Anthropic's Messages API. Provider id: `zcode`.
40
41
  firewall says this network's address was blocked instead.
41
42
  - The Start Plan's token can't be refreshed. When it runs out, sign in
42
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.
43
52
  - **ZCode: a team's GLM Coding Plan**
44
53
  - For an account with a plan of its own and a seat on a team's plan
45
54
  (#285). The sign-ins above take the account's own plan, as ZCode does
package/index.mjs CHANGED
@@ -50,12 +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
- // keyDevice is a device id for an account known only by its key: the same
54
- // key gives the same id on every start, as a sign-in's saved device does
55
- const keyDevice = (key) => {
56
- const h = createHash("sha256").update("zcode-device\0" + key).digest("hex")
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
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
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)
59
62
  const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? ""
60
63
 
61
64
  // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
@@ -1197,6 +1200,86 @@ function configKey(key) {
1197
1200
  return null
1198
1201
  }
1199
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
+
1200
1283
  // ownSignIn is what ZCode is signed in to now: the account, its coding
1201
1284
  // plan key, ZCode's session token (the Start Plan's key) and the team plan
1202
1285
  // it is switched to; null when it has none of them.
@@ -1217,6 +1300,8 @@ function ownSignIn() {
1217
1300
  // ZCode 3.15 keeps no plan key in its credentials; the one it uses sits
1218
1301
  // in config.json, the provider's options.apiKey (yetone/magpie#2130)
1219
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
1220
1305
  const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
1221
1306
  const team = ownTeam(store, key)
1222
1307
  if (team) s = { ...team, jwt }
@@ -1732,7 +1817,7 @@ function contextPrefix() {
1732
1817
  // sign-in's device. site names the powered-by line's provider, place where
1733
1818
  // the agent works (workPlace). A body that isn't a Messages request goes as
1734
1819
  // it is.
1735
- function dress(text, site, device, place) {
1820
+ function dress(text, site, device, place, session) {
1736
1821
  if (typeof text !== "string" || !text.includes("messages")) return text
1737
1822
  let b
1738
1823
  try {
@@ -1772,7 +1857,7 @@ function dress(text, site, device, place) {
1772
1857
  }
1773
1858
  if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control
1774
1859
  const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {}
1775
- b.metadata = { ...meta, user_id: userIdOf(device) }
1860
+ b.metadata = { ...meta, user_id: userIdOf(device, session) }
1776
1861
  return JSON.stringify(b)
1777
1862
  }
1778
1863
 
@@ -1780,13 +1865,14 @@ function dress(text, site, device, place) {
1780
1865
  // MLs and vWr) puts it on every Anthropic-format request, a coding plan's
1781
1866
  // too: the machine's device id, no account uuid. The plan's endpoint keeps
1782
1867
  // a prompt cache on the machine it picks by it, so a request without it
1783
- // lands anywhere and its cache is mostly missed (#387).
1784
- const userIdOf = (device) => JSON.stringify({ device_id: device, account_uuid: "", session_id: "" })
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 })
1785
1871
 
1786
1872
  // marked is a coding plan's Messages request body with metadata.user_id
1787
1873
  // as ZCode sends it, when the agent sent none of its own. Anything else,
1788
1874
  // a body that isn't a Messages request among them, goes as it is.
1789
- function marked(text, device) {
1875
+ function marked(text, device, session) {
1790
1876
  if (typeof text !== "string" || !device || !text.includes("messages")) return text
1791
1877
  let b
1792
1878
  try {
@@ -1797,10 +1883,25 @@ function marked(text, device) {
1797
1883
  if (!b || typeof b !== "object" || Array.isArray(b) || !Array.isArray(b.messages)) return text
1798
1884
  const meta = b.metadata && typeof b.metadata === "object" && !Array.isArray(b.metadata) ? b.metadata : {}
1799
1885
  if (typeof meta.user_id === "string" && meta.user_id.trim()) return text
1800
- b.metadata = { ...meta, user_id: userIdOf(device) }
1886
+ b.metadata = { ...meta, user_id: userIdOf(device, session) }
1801
1887
  return JSON.stringify(b)
1802
1888
  }
1803
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
+
1804
1905
  // ---- the plugin ------------------------------------------------------------------
1805
1906
 
1806
1907
  export async function ZCodeAuthPlugin({ client }) {
@@ -1815,6 +1916,14 @@ export async function ZCodeAuthPlugin({ client }) {
1815
1916
  authorize: () => authorize(site, log),
1816
1917
  })
1817
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
+ },
1818
1927
  config: async (cfg) => {
1819
1928
  cfg.provider ??= {}
1820
1929
  const was = cfg.provider[PROVIDER] ?? {}
@@ -1879,7 +1988,7 @@ export async function ZCodeAuthPlugin({ client }) {
1879
1988
  apiKey: s0.key || "zcode", // the fetch below puts the real one on
1880
1989
  async fetch(input, init) {
1881
1990
  const auth = await getAuth()
1882
- const s = stateOf(auth)
1991
+ const s = await located(stateOf(auth))
1883
1992
  if (!s) throw new Error("not signed in to ZCode")
1884
1993
  let url = input instanceof Request ? input.url : String(input)
1885
1994
  const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
@@ -1934,6 +2043,7 @@ export async function ZCodeAuthPlugin({ client }) {
1934
2043
  }
1935
2044
  let h = new Headers(opts.headers)
1936
2045
  const place = workPlace(h)
2046
+ const sid = sessionOf(h.get("x-session-id"), s.device)
1937
2047
  if (start) {
1938
2048
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
1939
2049
  if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
@@ -1941,9 +2051,10 @@ export async function ZCodeAuthPlugin({ client }) {
1941
2051
  // the Start Plan is served only to what looks like ZCode's own request
1942
2052
  url = startURL(url)
1943
2053
  h = startHeaders(h, s.jwt)
2054
+ h.set("x-session-id", sid)
1944
2055
  if (opts.body != null) {
1945
2056
  const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
1946
- opts.body = dress(text, s.site, s.device, place)
2057
+ opts.body = dress(text, s.site, s.device, place, sid)
1947
2058
  delete opts.duplex
1948
2059
  h.delete("content-length")
1949
2060
  }
@@ -1954,12 +2065,13 @@ export async function ZCodeAuthPlugin({ client }) {
1954
2065
  // count_tokens and other paths ZCode never sends go as they are
1955
2066
  if (opts.body != null && /\/v1\/messages$/.test(new URL(url).pathname)) {
1956
2067
  const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
1957
- const next = marked(text, s.device)
2068
+ const next = marked(text, s.device, sid)
1958
2069
  if (next !== text) h.delete("content-length")
1959
2070
  opts.body = next
1960
2071
  delete opts.duplex
1961
2072
  }
1962
2073
  if (renamed) h.delete("content-length")
2074
+ h.set("x-session-id", sid)
1963
2075
  h.delete("authorization")
1964
2076
  h.set("x-api-key", key)
1965
2077
  h.set("Authorization", "Bearer " + key)
@@ -2018,6 +2130,11 @@ export async function ZCodeAuthPlugin({ client }) {
2018
2130
  const auth = await getAuth()
2019
2131
  const s = stateOf(auth)
2020
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
+ }
2021
2138
  // every card starts from the plan the sign-in saved, as magpie's
2022
2139
  // built-in did: a reply without a level, a team detail that
2023
2140
  // failed or an error keeps it
@@ -2112,4 +2229,4 @@ export async function ZCodeAuthPlugin({ client }) {
2112
2229
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2113
2230
  // out of reach, undefined forgets it
2114
2231
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2115
- export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT, marked, keyDevice }
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.30",
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",