Skip to content

fix(proxy): strip dsh-injected turns so L0 keeps the real user message - #2021

Open
showcodehk wants to merge 4 commits into
TencentCloud:feat/server_teamfrom
showcodehk:fix/dsh-runtime-notices-v2.0.4
Open

showcodehk wants to merge 4 commits into
TencentCloud:feat/server_teamfrom
showcodehk:fix/dsh-runtime-notices-v2.0.4

Conversation

@showcodehk

Copy link
Copy Markdown

本 PR 取代 #1734。原 PR 基于 ecc01a5(tag v2.0.3 之后 4 个提交);v2.0.4 已把响应 tap 从 body.tee() 重构为主链
pipeThrough,旧分支与 feat/server_team 冲突于 openai-chat.ts。此处以 v2.0.4 为基线重做,
原有三个缺陷的取证、测试用例与结论全部沿用,另补两类仍会顶掉真人输入的尾部注入。
原 PR 的讨论记录仍可查阅,没有任何结论被推翻。

另:取证时 dsh 侧把 provider 故意命名为 openrouter(原因见 #1733 的「接入方式补充」),
该借名做法现已由专用插件取代,详见下方 Background。

Description | 描述

修复 dsh(OpenAI Chat 通道)接入下 L0 的四个缺陷,详细取证见关联 issue。

共同后果不是"多记一条噪声",而是真人那一轮说的话被顶掉:dsh 把注入内容追加在真人消息之后,
而 extractLatestUserMessage() 从后往前扫、遇到第一条剥完非空的就返回。

1. 注入的运行时通知被当作用户提问(写脏)

time-context(每步三行)、working-directory(目录变化)、jobs(任务结算)都以 role=user 注入,
而提取器只认 Current runtime context. 前缀,三类全部落进 L0。

  • DSH_RUNTIME_NOTICE_LINE_PATTERNS 新增 5 条(行首锚定),按行剥
  • stripDshJobNotices() 整段剥 —— <label> 是命令原文、自带换行,按行剥会留残片

两类剥法的取舍:单行通知按行剥,Anthropic 通道把连续同 role block 合并成一条消息时只掉通知行、真问题保留;
jobs 这类把命令原文带进正文的通知只能整段剥 —— 按行剥会留下命令残片,比不剥更脏。

2. 表单答案不入库(漏写)

答案随工具结果回流,而 extractLatestUserMessage() 只扫 role === "user" ⇒ 弹过表单的轮次,
L0 记的是表单前那句,选项与自定义输入全丢。

  • 新增 form-answer-extractor.ts,渲染成 问:<题干>\n答:<选项;自定义输入>;题干已被压缩掉时只留 答:…
  • recorder.ts 改取第一条人类输入(真 user 文本或表单答案);session-init 表单按 callId 前缀
    (call_*session_init_ / toolu_cc_session_init_)排除

3. 客户端提前断开时整轮丢失

dsh 每轮结束会 consumer.abort(...);读端 cancel 不触发 flush(),而 L0 写入挂在收尾 ⇒ 每轮都可能丢,
短回复(尤其会话最后一句)最容易中。

v2.0.4 的 cancel() 只提交 session call,不跑 finalize():

// v2.0.4 原样
cancel() {
  try { submitSessionRecord(); }
  catch (err: unknown) { pipe.error("STREAM_CANCEL", err); }
}
  • 改成与 flush() 共用幂等的 finalizeOnce()(断开 / 中断 / 读完都收尾一次)
  • 顺带清掉残留的第二套 tap 实现,只留 createUsageTapTransform 一条路径

4. v2.0.4 基线上补充:其余 7 类注入源 + pi-ai 的图片占位(新增)

第 1 点只覆盖了当时已知的 3 类通知。按 dsh 0.2.2-rc.3 源码逐个核对 createUserMessage 的注入点后,
以 role=user 落在真人消息之后、且能用固定句式或容器识别的还有 7 类 —— 其中 repeat-tool-reminder
有两种措辞,分两行列出:

类型 固定文案 / 容器 修法
model-selection [model changed: …] 单行,整行锚定
repeat-tool-reminder(gentle) You are repeating the exact same tool call… 单行,行首锚定
repeat-tool-reminder(detailed) Repeated tool call detected: … evidence has been gathered. 整段剥
tmux-context tmux location (turn N): + 多行状态 整段剥
action-cards Latest status of action cards… + JSON 整段剥
session-reference ## Referenced sessions + <referenced-sessions> 整段剥(标题在标签外)
tool-skill(skill-catalog) <available_skills>…</available_skills> XML 标签
tool-goal <goal_complete> / <goal_blocked> XML 标签

上表 7 类之外还有一类,且不是 dsh 产生的:工具结果带图时,OpenAI Chat 协议表达不了"带图的 tool 消息",
pi-ai 会凭空造一条 role=user、正文只有 Attached image(s) from tool result: 的消息。它没有 source 字段,
只能按文案认,同样整行锚定。

整体看,dsh 侧以 role=user 进入对话流、且能用固定句式或容器识别的注入源共 12 类 —— runtime-context、
time-context、working-directory、tool-jobs、model-selection、repeat-tool-reminder、tool-goal、
action-cards、tmux-context、session-reference、agent-instructions、skill-catalog(技能目录);
本 PR 之后全部覆盖。

另有两类刻意不处理:webhook 的提示词是规则里配置的任意文本,无句式可锚;subagent 的 relay
是另一个 agent 发来的有效上下文,剥掉会丢信息。

Background | 背景:从借名 openrouter 到显式补头

#1733 的「接入方式补充」记录了取证时的形态:dsh 侧把 provider 故意命名为 openrouter(不是笔误)。
原因是 pi-ai 的兼容层按 provider 名 / baseURL 字面量探测,只有命中 isOpenRouter 才会打开会话亲和头:

const isOpenRouter = provider === "openrouter" || baseUrl.includes("openrouter.ai");
sendSessionAffinityHeaders: isOpenRouter,
sessionAffinityFormat: isOpenRouter ? "openrouter" : "openai",
if (sessionId && compat.sendSessionAffinityHeaders) headers["x-session-id"] = sessionId;

而这两个 compat 字段在 dsh 里是 withhold 的,profile 无法显式打开;baseURL 指向本地 proxy、不含
openrouter.ai,所以只有 provider 名字能命中。把名字写成 openrouter 是让 pi-ai 发出会话亲和头的唯一途径。

于是每轮请求都带 x-session-id: session-…,resolveConversationId()(session/session-key.ts)读它当 session key,
L0 记录与 session-init 绑定都落在正确会话上。这也说明本 PR 的三个缺陷从来不是"认不出是哪个会话",
而是"认不出什么算人类输入"
—— 与本 PR 的修复范围一致。

但这个做法脆弱,而且只覆盖了一半:

  • 它只换来 x-session-id;x-deepseek-harness-compact 仍然不发,压缩请求依旧被当作主对话记账
  • 它依赖一个供应商名字。provider 一改名(例如改成 tdai),isOpenRouter 不再命中、亲和头立刻消失,
    会话身份整条链路断掉。本项目后来正是在这次改名时,看到 dsh 往对话流里插入了
    [model changed: openrouter/… → tdai/…] —— 这正是本 PR 处理的第一类注入源

现已改为显式方案,取代借名做法:

  • provider 正名 tdai,五个兼容项全部写进 compat(路由级三项 + 模型级两项),不再依赖名字猜测
  • 请求头由一个零依赖插件补齐:https://github.com/showcodehk/dsh-llm-tdai

该插件只做一件事:挂 llm-pi-ai/request-headers,在有 sessionId 时补 x-deepseek-harness-session-id 与
x-session-id,在 purpose === 'compaction' 时补 x-deepseek-harness-compact: 1。它不再受供应商名字与
catalog withhold 的限制,解决的是"请求被打上正确身份"。

本 PR 的改动不依赖该插件。 即使维护者不安装它,抽取侧的修复同样生效;插件只影响会话归并与 auxiliary 判定,
不影响 user-query-extractor / recorder 的任何分支。两者可以独立评估、独立合并。

Related Issue | 关联 Issue

Fix #1733

Change Type | 修改类型

  • Bug fix | Bug 修复
  • New feature | 新功能
  • Documentation update | 文档更新
  • Code optimization | 代码优化

Self-test Checklist | 自测清单

  • Verified locally | 本地验证通过
  • No existing features affected | 无影响现有功能

测试 —— 4 份文件、60 例通过,载荷取自真实 dsh 会话文件与真实 L0 落库行:

测试文件 用例数
common/__tests__/user-query-extractor.test.ts 32
common/__tests__/form-answer-extractor.test.ts 14
tdai/__tests__/recorder.test.ts 9
injection/injectors/__tests__/tdai-l1-recall-injector.test.ts 5

其中两条是误伤防护:正文里引用 [model changed: …]、或正常提问中出现
Attached image(s) from tool result: 字样时,均原样保留。

类型检查 —— tsc --noEmit 错误数与基线一致(既有的 @context-proxy/cost-guard 缺类型声明),零新增。

图片占位规则 —— 在运行中的 v2.0.4 容器内、用实际加载的那份文件验证:

输入 输出
只有 Attached image(s) from tool result: ""
真问题 + 该占位 只留真问题
句中引用该句 原样保留

影响面 —— 改动集中在 L0 抽取与写入收尾,不触碰 L1/L2 的检索与注入。所有新增规则都锚定行首(单行)或
整段起始(多行块),未命中的文本原样通过;tdai-l1-recall-injector 只是把「取哪条 user 消息」换成跳过纯 harness 通知的实现,
注入内容与触发条件不变;客户端侧 SSE 字节流由 createCfqStripStream 原样输出,tap 只旁路读取。

Additional Notes | 其他说明

基线。 本 PR 基于 tag v2.0.4(db13b44)。feat/server_team 当前 HEAD 是 083c64b,比 v2.0.4 只多一个
README_CN.md 提交,与本分支合并无冲突。openai-chat.ts 在 v2.0.3 → v2.0.4 之间做了响应 tap 重构
(tee → 主链 pipeThrough,113 行变动),因此缺陷 3 按 v2.0.4 的结构编写,不能直接回移到 v2.0.3。

其余三个文件在两版之间的情况:recorder.ts 与 tdai-l1-recall-injector.ts 未变;user-query-extractor.ts
有一次 frontmatter 正则的性能改写(防 ReDoS,21 行改动),与本补丁新增的规则数组没有交集。

历史数据。 已落库的 harness 通知记录不会被本补丁自动清理(只影响新写入),需要显式
POST /v2/conversation/delete。

已知局限(仅 Anthropic 通道)。 tmux-context 与 action-cards 的块规则要求整条以首行开头才命中。
dsh 的 OpenAI Chat 通道下它们独立成条,正常剥除;若换成 Anthropic 通道、又与真问题合并成同一条消息
(真问题在前),这两类不会命中,内容会和人话一起留在 L0 —— 只多余,不丢写。

…ed stream

Three separate gaps in the L0 write path made dsh turns disappear or get
recorded with a stale user message.

1) dsh 0.2.1 injects runtime notices as role=user messages

`Time sampled while preparing turn N, step M: ...`, `The working directory
changed from ...`, and jobs completion notices such as `background job
pwsh-91 (...) finished [status: completed]` are all created by the harness,
not typed by the user. The extractor only recognised the older `Current
runtime context.` snapshot, so none of these anchors matched and the notice
itself became the user turn.

They are now stripped: time-context / working-directory lines line by line,
job notices as a whole block because the job label embeds newlines (stripping
only the first line leaves a fragment of the command behind, which is worse
than not stripping at all). Stripping by line instead of by message also
covers the Anthropic path, where consecutive same-role blocks are merged into
a single user message.

2) ask_user_question answers never reach role=user

Answers come back as an OpenAI role=tool message or an Anthropic tool_result
block, so any round that showed a form was recorded as the question asked
before the form -- what the user actually selected or typed was lost.

A new common/form-answer-extractor.ts parses `{"answers":[{id,selected,
custom}]}`, recovers the prompt text from the preceding tool call (both
OpenAI `tool_calls[]` and Anthropic `tool_use` blocks), and renders it as
`Q: <prompt>` / `A: <option text; custom text>`. recorder.ts now walks
backwards for the nearest human input -- real user text or a form answer --
instead of accepting only user text. session-init forms that the proxy
injects itself are skipped by call-id prefix.

3) A closed client connection dropped the whole turn

The streaming write hung off `flush()` on a TransformStream produced by
`pipeThrough()`. `flush()` is not called when the client cancels the stream,
and there was no `cancel()` handler, so neither the user nor the assistant
message reached L0. This is not limited to explicit interrupts: dsh aborts
the request once its consumer is done, so the last turn of an ordinary
conversation has the same window, and short replies hit it most often.

The OpenAI-chat path now mirrors anthropic.ts: `body.tee()` the upstream
response, consume one branch independently of the client, and finalize once
behind an idempotent guard. Partial content is still written rather than
discarding the turn, matching the existing recorder behaviour of omitting
the assistant message when it is empty.

Tests: 47 cases across user-query extraction, form-answer extraction,
recorder, and the L1 recall injector. Payloads are taken from real dsh
session traces rather than hand-written fixtures.

Signed-off-by: SHOW-AGENT <show-agent@agent.com>
The extractor recognised time-context, working-directory and job notices, but
several other kinds of harness-injected role=user content still reached L0 — and
because dsh appends its injections after the human turn, the reverse scan
returned the notice itself and never saw the real question.

Added, matched against dsh 0.2.2-rc.3 source text:

  pattern  [model changed: ...]              model-selection
  pattern  You are repeating the exact ...   repeat-tool-reminder (gentle)
  block    Repeated tool call detected ...   repeat-tool-reminder (detailed)
  block    tmux location (turn N):           tmux-context
  block    Latest status of action cards     action-cards
  xml      <available_skills>                tool-skill
  xml      <goal_complete|goal_blocked>      tool-goal
  block    ## Referenced sessions ...        session-reference

Multi-line injections are stripped as whole blocks: removing only the first line
left their bodies (window 0 pane 1, the JSON payload, - tool: ...) behind, which
is dirtier than not stripping at all.

Ten cases added to the extractor suite, including two false-positive guards.

Signed-off-by: SHOW-AGENT <show-agent@agent.com>
Rebasing onto v2.0.4 left two tap implementations stacked: v2.0.4 pipes
createUsageTapTransform into the main chain, while the older fix teed the stream
and consumed a branch with consumeOpenAiTapStream. The conflict resolution kept
both the new call and the old function, so the file referenced a name that no
longer existed and returned a TransformStream from a void signature.

There is now one path. createUsageTapTransform returns the TransformStream, and
its cancel() runs the same finalize as flush() — which is the piece v2.0.4 still
lacks: upstream cancel() only calls submitSessionRecord, so a client abort would
still drop the turn's L0 record.

Type check is back to the one pre-existing error in storage/factory.ts
(@context-proxy/cost-guard is referenced but is no longer a dependency upstream).

Signed-off-by: SHOW-AGENT <show-agent@agent.com>
On the OpenAI Chat channel a tool message can only carry string content, so
pi-ai moves a tool result's images into a synthetic user message whose only text
is 'Attached image(s) from tool result:'. That message has no source field at
all - it is produced by the adapter, not by dsh - and it is appended after the
human turn, so the reverse scan returned the placeholder and never reached the
real question.

Matched whole-line: the string is fixed, and a question that merely quotes it
keeps its line.

Three cases added: the placeholder alone, the placeholder below a real question
(the shape extractContentText produces), and a sentence that quotes it.

Signed-off-by: SHOW-AGENT <show-agent@agent.com>
@github-actions

Copy link
Copy Markdown
Contributor

Thank you for your contribution! This is an automated acknowledgment. We'll review it internally soon and share all feedback in the discussion below.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] MemoryProxy L0 在 Deepseek Harness 0.2.1 上的接入问题:运行时通知入账、表单答案丢失、断流丢整轮

1 participant