Install
Install with PiG
pig install npm:pi-ds-session-guardInstall with Pi
pi install npm:pi-ds-session-guardPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"extensions": [
"./index.ts"
]
}README
Written by the package's publisher, shown as published in version 0.3.0 (README.md). PiG does not review it.
pi-ds-session-guard
English | 简体中文
Strips DeepSeek DSML markers that leak into assistant text, and auto-continues a turn that produced nothing.
Six kinds of dead turn are covered:
- DSML markers leak into the assistant text (the gateway wrote tool-call syntax into
content); - The model writes only reasoning and stops, with no text and no tool call (
stopReasonis stillstop, so pi does not retry); - The gateway writes the reasoning into both
contentandreasoning_content, so the "text" is just a copy of the reasoning and the model actually delivered nothing; - With a large context the model volunteers an
<analysis>…</analysis><summary>…</summary>compaction summary and treats it as the answer to the current task; - The model wraps its reasoning in
<thinking>…,<thought>…, or<think>…inside the text and stops once the whole text is thinking; - The model writes the "tool it wants to call" as pseudo-tags in the text:
<existing-code>wrapping<bash>command</invoke>,<tool_search">followed by<query>…. The syntax looks like a call, but no tool is ever sent.
Why this is needed
On some gateways DeepSeek writes tool-call syntax into the text:
我先看下项目结构。
<||DSML|| calls>
<||DSML|| invoke name="bash">
<||DSML|| parameter name="command" string="true">ls -la</||DSML|| parameter>
</||DSML|| invoke>
</||DSML|| calls>
For that turn pi receives stopReason === "stop", while pi's automatic retry only handles stopReason === "error". So pi neither retries nor reports an error — it just stops. The dirty markers are persisted with the assistant message and sent back upstream on the next turn.
What it does
message_end: strips markers fromtextandthinking, drops text blocks that are byte-identical to the reasoning, drops compaction summaries and text that is entirely pseudo-tag thinking, then replaces the message. Pi replaces in place at this layer, and the replacement happens before persistence, so the screen and the history are both clean.turn_end: decides whether the turn produced nothing, and if so appends adisplay: falsecustom_messageand asks to continue. The continue request has to carry a message, because whether the boundary can continue depends on the last LLM message not having the assistant role.registerMarkdownTransformer: renders markers as⟨tool call⟩while streaming.
There are six continue trigger paths, each with its own continue text:
| Shape | Criterion | Continue bucket |
|---|---|---|
| Leak | Text is shorter than minVisibleChars after stripping | leak |
| Empty turn | No non-empty text block, no tool call, no image (usually a stop after reasoning only, or a stated intent to call a tool that was never sent) | empty |
| Duplicate | Text is byte-identical to the reasoning, and the text block is dropped | deduped |
| Compaction summary | Text starts with <analysis> or ends with </summary>, and is at least 500 characters; the whole text is dropped | summary |
| Pseudo-tag thinking | The whole turn's text sits inside <thinking> / <thought> / <think> (unclosed, or closed with only repeated closing tags left); with a tool call, at least 200 visible characters are also required | thinking |
| Pseudo call | The whole text is pseudo tool-call tags (a tag borrowing a tool name wrapping a command, with the outer tag unclosed); the structurally broken form may also be followed by a short "already done" narrative | leak |
The last five all fall back to "this turn has no text", but the texts stay separate. The leak case needs the model to re-issue the tool call. The empty-turn, duplicate, summary, and pseudo-thinking cases never had a tool call at all, and saying "the markers were corrupted" again only sends the model looking for something that does not exist. Pseudo-call shares leak with the leak case because the required action is the same — re-issue the tool call — even though the reason differs: in one case the markers were broken, in the other nothing was ever sent.
Except for leak, the texts are deliberately vague: they do not name the anomaly and do not prescribe the next step. That trade-off is intentional — precise directions such as "do not output analysis/summary envelopes" or "write the conclusion into the text" tend to pull the model's attention toward those shapes and make it reproduce them. A vague "please continue the current task" is enough to move it forward without reminding it of the specific failure mode.
The duplicate check is exact equality, not fuzzy matching. When it hits, that text block is also removed from the persisted message, leaving only the thinking — otherwise the history records "the model mistook its own reasoning for an answer", and the next turn feeds it back upstream as completed output.
The compaction-summary check looks at either end of the envelope, because a truncated leftover has only one side; the length floor avoids false positives on replies that genuinely discuss those two tags. When it hits, the whole text is dropped, for two reasons: it is only a summary of the session history and does not constitute an answer inside the message, and at ten to twenty thousand characters it would grow an already large context another notch.
The continue messages for these two dead shapes come from continueTexts.summary and continueTexts.thinking, separately from the leak case, because "please re-issue the tool call" does not fit a situation where no answer was ever written.
Pseudo-tag thinking does not have fixed tag names: the same gateway writes <thinking>, <thought>, and <think>, which are written and meant the same way. The plugin accepts all three, case-insensitively, and also accepts a closing tag whose name does not match the opening one. After closing, a repeated-closing leftover is common (</thought></thought>, </thought> \n</thought>), and those are treated as "all thinking" too.
With a tool call, length decides: under 200 visible characters is kept as a short preface (the <thinking>**Verifying yt-dlp installation**</thinking> kind), and 200 or more is the whole reasoning and is dropped as before. That threshold comes from measurement: a genuine short preface is only a few dozen characters, while reasoning that leaks into the text runs three to seven thousand characters, gets persisted with the message, and is sent back upstream next turn. Without a tool call there is no length check — it is always dropped. If there is still text after the tag (<thinking>what next</thinking> followed by an answer), nothing is touched; that is not a dead turn.
The pseudo-call check does not enumerate syntax the way markers do, because the tag names keep changing. It looks at three things: first it erases fenced code blocks and inline code (replies discussing these tags must not be hit), then it requires the remaining text to start with a pseudo-call tag, and finally it erases the tool body wrapped in the tool-name tag (up to the matching closing tag) and measures how many visible characters remain. Requiring the text to start with the tag avoids killing a normal reply that writes a paragraph and then shows a command as an example.
Tool bodies are split into two kinds by length and structure. A structurally complete one (<bash>…</bash>) counts as a pseudo call only when it occupies the whole text; otherwise it is treated as an example. A structurally broken one (an outer <parameter> / <existing-code> present, a closing tag with the wrong name, no closing at all) may be followed by a short "already done" narrative, because that execution never happened and keeping the narrative would persist fabricated results.
This criterion was regressed against 11,004 real text blocks. It hit 3, all genuinely dead: the one with <existing-code> wrapping <bash> stalled a session for 16 hours, and <tool_search"> and <parameter name="bash"> hit once each.
No continue happens when stopReason is neither stop nor length (error is left to pi's own retry, aborted means you stopped it). A turn with a tool call, with an image, or with a normal short answer also does not continue, so "Done." is not misread as a dead turn and the consecutive counter resets on that turn.
Marker syntax variants and leftovers: a complete call block is removed whole; isolated trailing closing tags, unclosed outer wrapper fragments, and bare markers are removed too. The pipe variants cover ||DSML||, |DSML|, ||DSML||, |DSML|, and DSML|. Markers inside fenced code blocks and inline code are never touched.
Install
pi install npm:pi-ds-session-guard
To load a local checkout while developing:
pi -e ./index.ts
Configuration
Optional. It lives in <agent-dir>/extensions/pi-ds-session-guard.json (by default ~/.pi/agent/extensions/pi-ds-session-guard.json):
{
"enabled": true,
"sanitize": true,
"autoContinue": true,
"continueTexts": {
"leak": "上一条回复里的工具调用标记已损坏并被丢弃,请重新发起工具调用。"
},
"minVisibleChars": 80,
"maxConsecutive": 5,
"hideWhileStreaming": true,
"debug": false,
"logFile": ""
}
| Key | Default | Meaning |
|---|---|---|
enabled | true | Master switch |
sanitize | true | Strip markers; when off, only the continue decision runs |
autoContinue | true | Whether to auto-continue |
continueTexts | see below | The five continue texts; write only the buckets you want to change, the rest fall back to defaults |
minVisibleChars | 80 | Leak criterion: fewer visible characters than this after stripping counts as "nothing produced" |
maxConsecutive | 5 | Cap on consecutive continues in one session |
hideWhileStreaming | true | Show ⟨tool call⟩ in place of markers while streaming |
debug | false | Write decision logs to a file; also PI_DS_SESSION_GUARD_DEBUG=1 |
logFile | "" | Log path; empty means <agent-dir>/logs/pi-ds-session-guard-{date}.log |
The five continueTexts buckets cover the six shapes above (pseudo call shares leak). The defaults ship in Chinese, because they are prompt text sent to the model:
| Bucket | Default |
|---|---|
leak | 上一条回复里的工具调用标记已损坏并被丢弃,请重新发起工具调用。 |
empty | 上一轮推理结束后的正文意外丢失,请继续当前任务。 |
deduped | 上一轮的正文意外变成推理内容的副本,已被丢弃。请继续当前任务。 |
summary | 上一轮交付的是会话历史总结,已被丢弃。请继续推进当前任务本身,不要自动总结会话。 |
thinking | 上一轮的正文都是推理内容,没有实际回答。请继续当前任务,避免把推理内容混入正文。 |
When you change these texts, keep the trade-off above in mind: the more specific they get, the more they hint the failure shape back to the model.
The old continueText and noAnswerContinueText keys still work: the former feeds leak, the latter feeds summary and thinking; if a bucket is also present in continueTexts, the new map wins.
debug can also be turned on with the PI_DS_SESSION_GUARD_DEBUG=1 environment variable.
The /pi-ds-session-guard command shows the current configuration, the consecutive-continue counter, and the log path.
Logging
Nothing is logged by default. With debug on, every strip and every continue decision writes one line to
<agent-dir>/logs/pi-ds-session-guard-YYYY-MM-DD.log (one file per day, so no extra rotation is needed):
21:04:07.412 摘除标记:412 字符,剩余正文 1 字符
21:04:07.418 续跑第 1 次:空回合:没有正文、没有工具调用
21:04:31.902 摘除标记:37 字符,剩余正文 755 字符
21:04:31.903 不续跑:正文完整(755 字符)
21:12:40.118 丢弃与 reasoning 完全相同的正文块,这一轮正文计 0 字符
21:12:40.119 续跑第 1 次:正文只是 reasoning 的副本:本轮没有实际回复
21:20:52.004 丢弃上下文总结 16771 字符,这一轮正文计 0 字符
21:20:52.005 续跑第 1 次:上下文总结已丢弃:本轮没有实际回复
21:24:33.207 丢弃伪标签思考 584 字符,这一轮正文计 0 字符
21:24:33.208 续跑第 1 次:正文只是一段伪标签思考:本轮没有实际回复
21:31:02.905 丢弃伪工具调用 219 字符,这一轮正文计 0 字符
21:31:02.906 续跑第 1 次:正文只是伪工具调用:本轮没有实际执行
Only decisions and character counts are recorded, never model text, so no session content ends up in the logs. Write failures (read-only directory, invalid path) are skipped silently and never affect stripping or continuing.
{date} in logFile is replaced with today's date; a fixed path without the placeholder turns per-day splitting off. If the config file itself fails to parse, one line is written even with debug off, so the problem is easy to locate.
Upgrading from the old name
This package used to be called dsml-guard. After the rename these places changed:
| Item | Old | New |
|---|---|---|
| Package and directory | dsml-guard | pi-ds-session-guard |
| Config file | extensions/dsml-guard.json | extensions/pi-ds-session-guard.json |
| Command | /dsml-guard | /pi-ds-session-guard |
| Log file | logs/dsml-guard-*.log | logs/pi-ds-session-guard-*.log |
| Debug variable | PI_DSML_GUARD_DEBUG | PI_DS_SESSION_GUARD_DEBUG |
The dsml-guard:resume entries already in old sessions are left as they are and do not affect continuing; new entries use pi-ds-session-guard:resume.
Tests
npm install
npm run check
check runs tsc --noEmit first, then the regression tests in test.mjs.
License
MIT