diff --git a/app/AGENTS.md b/app/AGENTS.md index c35e9b6..f17b9bf 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -211,6 +211,11 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插” `{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}`;正文开头混入的 `` 块会被 `splitInlineThinking` 剥离到 reasoning。 +增量上下文(模型配了 `store: true` 且带 `opts.context_id`):只发上次之后新增的消息,带 +`X-Context-Id` / `X-Context-Hash`;relay 回 409 说明缓存对不上(压缩、relay 重启、TTL 过期), +改发全量重试**一次**。指针存 `ctxState`(进程内存,只存 hash + 条数),进程重启即失效 → +下一轮自动全量。上游仍然是全量,语义不变。 + ## 工具层 - 工具全集 = `definitions.json`(14 个内置)+ MCP 发现结果;再依次叠 profile 的 `tools_allow` diff --git a/app/server/config.js b/app/server/config.js index a91843b..7cd8a51 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -236,6 +236,9 @@ function normalizePlatforms(rawPlatforms, profileNames) { // 非空时发请求前给历史 assistant 行挂该字段;空(缺省)= 不回传。纯发送侧旋钮, // 与接收解析无关(接收早已兼容 reasoning/reasoning_content 双名)。 reasoning_ack_field: typeof m.reasoning_ack_field === 'string' ? m.reasoning_ack_field.trim() : '', + // 选填:该模型的请求走增量上下文(context relay),只有配合 relay 生效。 + // 不配 = 每轮重传全量,和以前完全一样。 + store: m.store === true, // 选填:自动压缩阈值(用户自定义的「上下文用量线」,**不是**模型真实窗口)。 // 回合内 In token 峰值达到它即自动压缩上下文(见 engine.runLoopInner 循环顶部);0/未配 = 不启用。 max_context: Math.max(0, parseInt(m.max_context, 10) || 0), @@ -363,6 +366,7 @@ function parseAndValidate(rawText, configPath) { extra_params: m.extra_params, thinking_params: m.thinking_params, reasoning_ack_field: m.reasoning_ack_field, max_context: m.max_context, + store: m.store, profile: m.profile, url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency, platform_index: pi, key_index: ki, model_index: mi, diff --git a/app/server/engine.js b/app/server/engine.js index a57af77..648471e 100644 --- a/app/server/engine.js +++ b/app/server/engine.js @@ -3,6 +3,7 @@ const fs = require('fs'); const path = require('path'); const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts, patchImageReceipt } = require('./llm'); +const { instanceId } = require('./instance'); const { executeTool, resolveInTask } = require('./tools/executor'); const publicFiles = require('./public-files'); const mcp = require('./mcp'); @@ -1159,6 +1160,9 @@ async function streamAssistant(sessionId, run, session, messages, tools) { // key_slot 定位会话占用的具体 key 副本(model_id 只到「平台/模型」) const result = await callModel(cfg, session.model_id, messages, tools, { key_slot: session.model_slot, + // 增量上下文用:::,三层保证跨 core / 跨用户 / 跨会话都不撞。 + // 只有带 store: true 的模型才会真的用它(llm.js 判断)。 + context_id: instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id, signal: run.abortController.signal, shouldCancel: () => run.cancelled, onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }), diff --git a/app/server/instance.js b/app/server/instance.js new file mode 100644 index 0000000..33e506f --- /dev/null +++ b/app/server/instance.js @@ -0,0 +1,29 @@ +'use strict'; +// 实例标识:跨 core 隔离用,作 relay 的 X-Context-Id 前缀。 +// 首次启动生成并落盘到 /instance-id,之后只读同一个值。 +// 删了数据目录会换新 id —— 旧缓存成孤儿,由 relay 的 TTL 自行清理,不影响正确性。 +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); + +const cache = new Map(); // dataRoot -> id + +function instanceId(dataRoot) { + const root = path.resolve(String(dataRoot || '.')); + if (cache.has(root)) return cache.get(root); + const file = path.join(root, 'instance-id'); + let id = ''; + try { + id = fs.readFileSync(file, 'utf8').trim(); + } catch (_) {} + if (!/^[0-9a-f]{12}$/.test(id)) { + id = crypto.randomBytes(6).toString('hex'); + try { + fs.writeFileSync(file, id + '\n'); + } catch (_) {} + } + cache.set(root, id); + return id; +} + +module.exports = { instanceId }; diff --git a/app/server/llm.js b/app/server/llm.js index f96bfc9..b212959 100644 --- a/app/server/llm.js +++ b/app/server/llm.js @@ -2,6 +2,14 @@ // 累积 content 与 tool_calls 分片;支持 abort。 const fs = require('fs'); const path = require('path'); +const crypto = require('node:crypto'); + +// 增量上下文:context_id -> { hash, len }(本进程认为 relay 已存到哪一段)。 +// 只存指针不存正文;进程重启即清空 → 下一轮发全量,relay 整段替换,行为正确。 +const ctxState = new Map(); +function ctxHash(messages) { + return crypto.createHash('sha256').update(JSON.stringify(messages)).digest('hex'); +} const SYSTEM_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'profile-default.txt'), 'utf8'); @@ -714,18 +722,53 @@ async function callModel(cfg, modelId, messages, tools, options) { opts.onFetchParams(logBody); } - const res = await fetch(modelCfg.url + '/chat/completions', { + // ---- 增量上下文(context relay)---- + // 仅对显式 store: true 的模型生效,且必须带 opts.context_id。 + // 不做前缀比对:压缩/改写/relay 重启一律靠 409 回退全量,客户端只负责“接着上次发”。 + const cid = opts.context_id; + const storeOn = !!(modelCfg.store && cid); + const fullBody = JSON.stringify(body); + if (storeOn) { + const st = ctxState.get(cid); + headers['X-Context-Id'] = cid; + if (st && messages.length > st.len) { + body.messages = messages.slice(st.len); // 只发新增 + headers['X-Context-Hash'] = st.hash; + } else { + headers['X-Context-Hash'] = ''; // 首轮 / 压缩后:全量替换 + } + } + + let res = await fetch(modelCfg.url + '/chat/completions', { method: 'POST', headers, - body: JSON.stringify(body), + body: storeOn ? JSON.stringify(body) : fullBody, signal: controller.signal, }); + + // relay 说 hash 对不上(缓存没了 / 历史被改写):改发全量重试一次。 + // 只重试一次:hash="" 对 relay 是“整段替换”,重发后不可能再 409。 + if (storeOn && res.status === 409) { + body.messages = messages; + headers['X-Context-Hash'] = ''; + res = await fetch(modelCfg.url + '/chat/completions', { + method: 'POST', + headers, + body: JSON.stringify(body), + signal: controller.signal, + }); + } + if (!res.ok) { const text = await res.text().catch(() => ''); const err = new Error('上游返回 ' + res.status + ': ' + text.slice(0, 500)); err.upstream_status = res.status; throw err; } + // 成功才更新“relay 已存到哪”:失败下一轮自然重发全量。 + if (storeOn) { + ctxState.set(cid, { hash: ctxHash(messages), len: messages.length }); + } let content = ''; let reasoning = '';