Import packages/plugin/src/compact-history.ts

This commit is contained in:
QQ 2026-11-17 08:46:46 +08:00
parent de9744db95
commit 1b07c25a60
1 changed files with 17 additions and 4 deletions

View File

@ -9,6 +9,9 @@ const MARKER = '\n[Compact history: output omitted]'
* follow stream has no transfer fallback, so growth has to stay far below it.
*/
const ROUND_BUDGET = 128 * 1024
/** Tools whose result the client renders as an in-chat card: the component tree lives in
* `arguments`, and `meta` decides whether the card is rendered at all. */
const UI_TOOL_NAMES = new Set(['ui_render', 'ui_patch', 'ui_render_widget', 'ui_compose'])
const object = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)
type Budget = { remaining: number }
@ -28,13 +31,23 @@ function summary(value: unknown, budget: Budget): string {
return preservedRound(text, budget) ?? text.slice(0, LIMIT) + MARKER
}
function toolValue(value: unknown, budget: Budget): unknown {
if (Array.isArray(value)) return value.map(item => toolValue(item, budget))
function toolValue(value: unknown, budget: Budget, keepUiPayload = false): unknown {
if (Array.isArray(value)) return value.map(item => toolValue(item, budget, keepUiPayload))
if (!object(value)) return value
const result: Record<string, unknown> = { ...value }
const toolName = typeof value.name === 'string' ? value.name
: typeof value.toolName === 'string' ? value.toolName : undefined
const keepUi = keepUiPayload || (toolName !== undefined && UI_TOOL_NAMES.has(toolName))
for (const [key, child] of Object.entries(value)) {
if (['input', 'arguments', 'output', 'result', 'rawInput', 'rawOutput', 'uiResultMeta', 'meta', 'argumentsDelta'].includes(key)) {
result[key] = typeof child === 'string' ? summary(child, budget) : { summary: summary(child, budget) }
if (key === 'meta' || key === 'uiResultMeta') {
// The client renders an in-chat card only when `meta.ok` / `meta.ui` survive intact;
// wrapping this object in `{ summary }` silently drops the whole card.
result[key] = child
} else if (['input', 'arguments', 'output', 'result', 'rawInput', 'rawOutput', 'argumentsDelta'].includes(key)) {
// A UI tool's component tree is its arguments: truncating or wrapping them makes the
// client's JSON.parse fail, so keep them byte-exact for those tools only.
if (keepUi && (key === 'arguments' || key === 'argumentsDelta' || key === 'input')) result[key] = child
else result[key] = typeof child === 'string' ? summary(child, budget) : { summary: summary(child, budget) }
} else if (key === 'content' && Array.isArray(child)) {
let previews = 0
const blocks = child.flatMap(block => {