trae 0.2.32: a conversation keeps its session_id when the plugin restarts
baoguo on magpie's Discord: every call seemed to be a new Trae conversation, billed and cached as fresh; asked for one Trae session per agent session. The plugin already sends one session_id per conversation (0.2.6, #58): the session magpie names (the agent's own header, Claude Code's x-claude-code-session-id, Codex's session_id, DSH's x-deepseek-harness-session-id, OpenCode's session; else magpie's hash of how the conversation opens), with the account, hashed. But the hash's salt was new in each process, and magpie restarts its plugins on every update of magpie or of any plugin, so every conversation going on then went on under a session_id of its own from that point. Now the salt is made once, in ~/.config/magpie/trae-session-salt (MAGPIE_TRAE_SESSION_SALT names another file), written to a temp name and hard-linked into place so processes starting together all read the one that won. A file that can't be read or made, or holds anything else, is left as it is and the process has a salt of its own, as before. The id is derived, not cached, so there is nothing to bound or expire: the same agent session gives the same id for good. Tests now write their salt in a temp folder (nonet.mjs). Run: HOME=$(mktemp -d) bun test packages/trae on mote, 243 pass, 0 fail; bun scripts/check.mjs trae ok; conversation.test.mjs on Windows (xiaomi-gpu), 10 pass. Broken by hand: a salt new in each process makes "a conversation keeps its session_id when the plugin's process starts again" fail; overwriting the file on a race makes "processes starting at once on no salt yet all take the one that was made" fail. Not tried: a real Trae account (none in this magpie), so whether Trae's prompt cache follows session_id is not measured. dsh-connect-trae's probe (docs, 11-03) saw cache_read 0 on three same-prefix requests since 10-26, which no session id would change. Claude Code subagents still share their lead's session, as magpie names them. Reported-by: baoguo
This commit is contained in:
@@ -100,8 +100,13 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`:
|
||||
title. One conversation answered by two accounts (magpie failing over, or
|
||||
rotating, inside it) is named twice then, as two conversations, so Trae
|
||||
never reads one account's conversation as another's; that costs the two
|
||||
halves of such a conversation their single row. `request_id` is the
|
||||
request's own, fresh on every one.
|
||||
halves of such a conversation their single row. The id is a salted hash,
|
||||
so it says nothing of the words it was made from; the salt is this
|
||||
machine's own, made once in `~/.config/magpie/trae-session-salt`
|
||||
(`MAGPIE_TRAE_SESSION_SALT` names another file), so a conversation keeps
|
||||
its `session_id` when magpie restarts the plugin (on any update). If that
|
||||
file can't be read or made, each run of the plugin has a salt of its own,
|
||||
as before 0.2.32. `request_id` is the request's own, fresh on every one.
|
||||
- **Headers:** TRAE SOLO CN 0.1.69's (`x-ide-version`/`x-app-version`
|
||||
0.1.69, version code 20260917; Trae offers a model only to clients new
|
||||
enough for it): `Authorization: Cloud-IDE-JWT …`, `X-Cloudide-Token`,
|
||||
|
||||
@@ -118,3 +118,79 @@ test("the hook leaves other providers' requests alone", async () => {
|
||||
await hooks["chat.headers"]({ sessionID: "ses_1", model: { providerID: "trae-global" }, provider: { info: { id: "trae-global" } } }, out)
|
||||
expect(out.headers).toEqual({})
|
||||
})
|
||||
|
||||
// baoguo on magpie's Discord: a conversation's session_id is the same after
|
||||
// the plugin's process starts again (magpie restarts its plugins on every
|
||||
// update), so Trae goes on counting it as the one conversation. Each run
|
||||
// below is a process of its own, as a restarted plugin host is.
|
||||
const { mkdtempSync, readFileSync, writeFileSync, chmodSync, rmSync, statSync } = await import("node:fs")
|
||||
const { tmpdir } = await import("node:os")
|
||||
const { join } = await import("node:path")
|
||||
|
||||
function idIn(env) {
|
||||
const code = `const { _internal } = await import(${JSON.stringify(new URL("./index.mjs", import.meta.url).href)}); console.log(_internal.conversationID(null, "ses_1", "u-1"))`
|
||||
const r = Bun.spawnSync([process.execPath, "-e", code], { env: { ...process.env, ...env }, stderr: "pipe" })
|
||||
expect(r.exitCode).toBe(0)
|
||||
return r.stdout.toString().trim()
|
||||
}
|
||||
|
||||
test("a conversation keeps its session_id when the plugin's process starts again", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "trae-salt-"))
|
||||
try {
|
||||
const file = join(dir, "magpie", "trae-session-salt")
|
||||
const one = idIn({ MAGPIE_TRAE_SESSION_SALT: file })
|
||||
expect(one).toMatch(UUID)
|
||||
expect(idIn({ MAGPIE_TRAE_SESSION_SALT: file })).toBe(one)
|
||||
// the salt is this machine's own, unreadable to anyone else
|
||||
expect(readFileSync(file, "utf8").trim()).toMatch(/^[0-9a-f]{32}$/)
|
||||
if (process.platform !== "win32") expect(statSync(file).mode & 0o077).toBe(0)
|
||||
// another machine's (another file's) salt names it apart
|
||||
expect(idIn({ MAGPIE_TRAE_SESSION_SALT: join(dir, "other") })).not.toBe(one)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a salt file that isn't one is left alone, and each process has its own salt, as before", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "trae-salt-"))
|
||||
try {
|
||||
const file = join(dir, "trae-session-salt")
|
||||
writeFileSync(file, "not a salt\n")
|
||||
const one = idIn({ MAGPIE_TRAE_SESSION_SALT: file })
|
||||
expect(one).toMatch(UUID)
|
||||
expect(idIn({ MAGPIE_TRAE_SESSION_SALT: file })).not.toBe(one)
|
||||
expect(readFileSync(file, "utf8")).toBe("not a salt\n")
|
||||
// a file that can't be made: the folder it would go in is a file
|
||||
const blocked = idIn({ MAGPIE_TRAE_SESSION_SALT: join(file, "salt") })
|
||||
expect(blocked).toMatch(UUID)
|
||||
if (process.platform !== "win32" && process.getuid?.() !== 0) {
|
||||
// one that can't be read
|
||||
const shut = join(dir, "shut")
|
||||
writeFileSync(shut, "0".repeat(32) + "\n")
|
||||
chmodSync(shut, 0)
|
||||
const a = idIn({ MAGPIE_TRAE_SESSION_SALT: shut })
|
||||
expect(idIn({ MAGPIE_TRAE_SESSION_SALT: shut })).not.toBe(a)
|
||||
chmodSync(shut, 0o600)
|
||||
expect(readFileSync(shut, "utf8")).toBe("0".repeat(32) + "\n")
|
||||
}
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("processes starting at once on no salt yet all take the one that was made", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "trae-salt-"))
|
||||
try {
|
||||
const env = { ...process.env, MAGPIE_TRAE_SESSION_SALT: join(dir, "trae-session-salt") }
|
||||
const code = `const { _internal } = await import(${JSON.stringify(new URL("./index.mjs", import.meta.url).href)}); console.log(_internal.conversationID(null, "ses_1", "u-1"))`
|
||||
const runs = Array.from({ length: 8 }, () => Bun.spawn([process.execPath, "-e", code], { env, stdout: "pipe" }))
|
||||
const ids = await Promise.all(runs.map(async (p) => (await new Response(p.stdout).text()).trim()))
|
||||
expect(new Set(ids).size).toBe(1)
|
||||
expect(ids[0]).toMatch(UUID)
|
||||
// and no temp file is left beside it
|
||||
const { readdirSync } = await import("node:fs")
|
||||
expect(readdirSync(dir)).toEqual(["trae-session-salt"])
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
+52
-6
@@ -10,10 +10,11 @@
|
||||
// (/trae/api/…) as the account, for magpie's daily check-in (每日签到:
|
||||
// /trae/api/v2/ug/checkin_credits/status, then /claim).
|
||||
import { createDecipheriv, createHash, generateKeyPairSync, randomBytes, randomUUID, randomInt, sign } from "node:crypto"
|
||||
import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { createServer, STATUS_CODES } from "node:http"
|
||||
import { homedir, release, version as osVersion } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { dirname, join } from "node:path"
|
||||
|
||||
// SEES is a fallback model that takes images, as Trae's lists mark it
|
||||
// (multimodal: true)
|
||||
@@ -1388,10 +1389,55 @@ const nativeTools = (tools, moonshot = false) =>
|
||||
// from the chat.headers hook to the loader's fetch. It goes no further.
|
||||
const SESSION = "x-magpie-trae-session"
|
||||
|
||||
// SALT is what the id is derived with, so it says nothing of the words it was
|
||||
// made from. New in each process, as Trae's own session ids are one session's
|
||||
// own within a run.
|
||||
const SALT = randomBytes(16).toString("hex")
|
||||
// saltOf is what the id is derived with, so it says nothing to Trae of the
|
||||
// words it was made from. It is this machine's own, kept in a file of the
|
||||
// plugin's (saltFile) and made once, so a conversation keeps its session_id
|
||||
// when the plugin's process starts again: magpie restarts its plugins on an
|
||||
// update of magpie or of any plugin, and a salt new in each process gave
|
||||
// every conversation going on then a session of its new own — Trae counting
|
||||
// it as a conversation started anew, with nothing of the one before (baoguo
|
||||
// on magpie's Discord). The file is made under another name and linked into
|
||||
// place, so two processes starting at once both read the one that won, never
|
||||
// a half-written one. A file that can't be read or made, or holds anything
|
||||
// but a salt, is left as it is, and the process uses a salt of its own, as
|
||||
// every process did before.
|
||||
const saltFile = () => process.env.MAGPIE_TRAE_SESSION_SALT || join(homedir(), ".config", "magpie", "trae-session-salt")
|
||||
const SALT_SHAPE = /^[0-9a-f]{32}$/
|
||||
let salt = ""
|
||||
function saltOf() {
|
||||
if (salt) return salt
|
||||
const file = saltFile()
|
||||
const read = () => {
|
||||
try {
|
||||
const s = readFileSync(file, "utf8").trim()
|
||||
return SALT_SHAPE.test(s) ? s : null
|
||||
} catch (e) {
|
||||
return e?.code === "ENOENT" ? "" : null
|
||||
}
|
||||
}
|
||||
let s = read()
|
||||
if (s === "") {
|
||||
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`
|
||||
try {
|
||||
mkdirSync(dirname(file), { recursive: true })
|
||||
writeFileSync(tmp, randomBytes(16).toString("hex") + "\n", { mode: 0o600 })
|
||||
try {
|
||||
linkSync(tmp, file)
|
||||
} catch (e) {
|
||||
if (e?.code !== "EEXIST") throw e
|
||||
}
|
||||
s = read()
|
||||
} catch {
|
||||
s = null
|
||||
} finally {
|
||||
try {
|
||||
unlinkSync(tmp)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
salt = s || randomBytes(16).toString("hex")
|
||||
return salt
|
||||
}
|
||||
|
||||
// conversationID is the conversation a chat belongs to, as the UUID the
|
||||
// request's session_id wants: the session magpie or OpenCode names (its
|
||||
@@ -1419,7 +1465,7 @@ function conversationID(chat, session, who = "") {
|
||||
// uuidOf is a version 4 UUID made of a hash's first 16 bytes: the shape
|
||||
// randomUUID() returns, since that is what session_id carried before.
|
||||
function uuidOf(s) {
|
||||
const b = Buffer.from(createHash("sha256").update(SALT + "|" + s).digest().subarray(0, 16))
|
||||
const b = Buffer.from(createHash("sha256").update(saltOf() + "|" + s).digest().subarray(0, 16))
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
const h = b.toString("hex")
|
||||
|
||||
@@ -16,3 +16,9 @@ http2.connect = (origin, ...rest) => {
|
||||
if (!local(String(origin))) throw new Error("a test connected to " + origin)
|
||||
return connect(origin, ...rest)
|
||||
}
|
||||
// nor does a test write this machine's session salt (saltOf): the plugin's
|
||||
// salt goes in a folder of the test run's own
|
||||
import { mkdtempSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
process.env.MAGPIE_TRAE_SESSION_SALT = join(mkdtempSync(join(tmpdir(), "trae-test-salt-")), "trae-session-salt")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-trae-auth",
|
||||
"version": "0.2.31",
|
||||
"version": "0.2.32",
|
||||
"description": "OpenCode provider plugins for Trae: Trae CN (trae.cn) and Trae Global (trae.ai), free tier included, with Trae's own browser sign-in",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
Reference in New Issue
Block a user