gongxiangp2/apps/detail-agent-pi/src/stream-presentation.mjs

162 lines
7.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { estimateTokens } from '@earendil-works/pi-coding-agent';
// Presentation only: the SDK's stored messages remain untouched.
export class StreamPresentation {
constructor() { this.text = ''; this.buffer = ''; this.inThought = false; this.code = ''; }
push(chunk) {
const data = this.buffer + chunk; this.buffer = '';
let text = '', thought = false, i = 0;
const append = value => { if (this.inThought) thought = true; else text += value; };
while (i < data.length) {
if (data[i] === '`') {
let j = i; while (j < data.length && data[j] === '`') j++;
if (j === data.length && j - i < 3) { this.buffer = data.slice(i); break; }
const ticks = data.slice(i, j);
if (!this.inThought) {
if (!this.code) this.code = ticks.length >= 3 ? 'fence' : 'inline';
else if ((this.code === 'fence' && ticks.length >= 3) || (this.code === 'inline' && ticks.length === 1)) this.code = '';
}
append(ticks); i = j; continue;
}
if (data[i] === '<' && !this.code) {
const tags = this.inThought ? ['</thinking>', '</think>'] : ['<thinking>', '<think>'];
const tail = data.slice(i, i + 11).toLowerCase();
const match = tags.find(tag => tail.startsWith(tag));
if (match) { this.inThought = !this.inThought; i += match.length; continue; }
if (data.length - i < 11 && tags.some(tag => tag.startsWith(tail))) { this.buffer = data.slice(i); break; }
}
let j = i + 1;
while (j < data.length && data[j] !== '`' && (this.code || data[j] !== '<')) j++;
append(data.slice(i, j)); i = j;
}
this.text += text;
return { text, thought };
}
endText() {
// A lone angle bracket is ordinary text; longer partial reasoning tags are withheld.
if (!this.inThought && (this.buffer === '<' || this.buffer.startsWith('`'))) {
this.text += this.buffer;
}
this.buffer = ''; this.inThought = false; this.code = '';
}
}
export function presentText(text) {
const view = new StreamPresentation(); view.push(text || ''); view.endText(); return view.text;
}
const receiptLabels = new Map(Object.entries({
detail: '详情页', main_images: '主图', sku_images: 'SKU 图',
completed: '已完成', exported: '已导出', pendingOutputs: '待交付成品',
deliveryStatus: '交付进度', partial_delivered: '部分成品已交付',
allOutputsCompleted: '整套成品完成情况', writeBlocked: '画布编辑状态',
true: '是', false: '否',
}));
/** Convert chat-only formatting and known receipt fragments at the presentation boundary. */
export function presentProductReply(text, streaming = false) {
const lines=text.split(/\r?\n/u);
const tableRule=/^\s*\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-{2,}:?\s*\|?\s*$/u;
let table=false;
const prose=lines.map((line,index)=>{
const startsWithPipe=/^\s*\|/u.test(line);
if(tableRule.test(line)){
table=true;
return '';
}
if(!line.includes('|'))table=false;
const row=startsWithPipe||table||line.includes(' |')||tableRule.test(lines[index+1]??'');
if(!row)return line;
if(streaming&&startsWithPipe&&index===lines.length-1&&!/\|\s*$/u.test(line.trim().slice(1)))return '';
const columns=line.trim().replace(/^\||\|$/gu,'').split('|').map(cell=>cell.trim()).filter(Boolean);
return columns.length?'- '+columns.join(','):'';
}).join('\n');
return prose
.replace(/\x60?\ballOutputsCompleted\s*[:=]\s*(true|false)\b\x60?/gu,(_match,value)=>value==='true'?'成品已全部完成':'成品还没全部完成')
.replace(/\x60?\bwriteBlocked\s*[:=]\s*(true|false)\b\x60?/gu,(_match,value)=>value==='true'?'画布暂不能编辑':'画布可以编辑')
.replace(/\x60?\bcompleted\s*[:=]\s*(true|false)\b\x60?/gu,(_match,value)=>value==='true'?'已完成':'尚未完成')
.replace(/\x60?\bpendingOutputs\s*(?:[:=]\s*\[\s*\]|为空)\x60?/gu,'没有待交付成品')
.replace(/(?:[A-Za-z]:)?(?:[/\\][^ \t\r\n"',。;、<>|\x60]+[/\\])?\bproduct-exports(?:[/\\][^ \t\r\n"',。;、<>|\x60]*)?/giu,'本机成品目录')
.replace(/\b(?:Pi(?: Agent)?|PhotoCraft)\b/gu,'小壹')
.replace(/\x60?\b(?:candidateId|generationId|operationId|requestId)\s*[:=]?\s*[\x60'"]?[a-f0-9-]{6,}\b[\x60'"]?/giu,'制作记录')
.replace(/(?:候选(?:图)?(?:编号|号|哈希)?|哈希)\s*[::]?\s*\x60?\b(?=[a-f0-9]*[a-f])[a-f0-9]{7,}(?:[.…]+[a-f0-9]+)?\b\x60?/giu,'候选图')
.replace(/\x60?\b(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?=[a-f0-9]*[a-f])[a-f0-9]{32,}|[a-f0-9]{8,}[.…]+[a-f0-9]{4,})\b\x60?/giu,'制作记录')
.replace(/\x60?\b(?:allOutputsCompleted|writeBlocked|deliveryStatus|pendingOutputs|main_images|sku_images|detail|partial_delivered|completed|exported|true|false)\b\x60?/gu,
match=>receiptLabels.get(match.replaceAll('\x60','')));
}
const productionToolText = /<tool_calls?\s*>[\s\S]*?(?:<\/tool_calls?\s*>|$)/giu;
export function stripProductionToolText(text, streaming = false) {
let visible = text.replace(productionToolText, '');
if (streaming) {
const start = visible.lastIndexOf('<');
if (start >= 0 && ['<tool_call>', '<tool_calls>'].some(tag => tag.startsWith(visible.slice(start).toLowerCase()))) {
visible = visible.slice(0, start);
}
}
return visible;
}
export class StreamOutputMeter {
sawThinking = false;
firstOutput = null;
lastOutput = null;
lastReport = -Infinity;
update(event, thinking, now = performance.now()) {
if (event.type === 'message_end') {
if (!this.sawThinking || event.message.role !== 'assistant') return;
const { usage, stopReason } = event.message;
const output = usage?.output;
const confirmed = stopReason !== 'error' && stopReason !== 'aborted'
&& Number.isSafeInteger(output) && output > 0;
return this.read(event.message, confirmed ? output : null);
}
const update = event.assistantMessageEvent;
if (event.type !== 'message_update' || !update) return;
this.sawThinking ||= thinking === true;
if (typeof update.delta === 'string' && update.delta.length > 0) {
this.firstOutput ??= now;
this.lastOutput = now;
}
if (!this.sawThinking || (thinking !== true && update.type !== 'thinking_end')
|| this.firstOutput === null || now - this.lastReport < 500) return;
const report = this.read(update.partial, null);
if (report) this.lastReport = now;
return report;
}
read(message, confirmedOutput) {
if (message?.role !== 'assistant') return;
const tokens = confirmedOutput ?? estimateTokens(message);
if (!Number.isSafeInteger(tokens) || tokens <= 0) return;
const duration = this.lastOutput - this.firstOutput;
const tokensPerSecond = duration >= 500 ? Math.round(tokens * 10_000 / duration) / 10 : null;
return { tokens, tokensPerSecond, estimated: confirmedOutput === null };
}
}
/** Deliver the newest presentation state with at most one delivery in flight. */
export class PresentationBatch {
constructor(deliver, merge = (_pending, next) => next) {
this.deliver = deliver;
this.merge = merge;
}
push(value) {
this.pending = this.pending === undefined ? value : this.merge(this.pending, value);
this.running ??= new Promise(resolve => setImmediate(resolve)).then(async () => {
try {
while (this.pending !== undefined) {
const next = this.pending;
this.pending = undefined;
await this.deliver(next).catch(() => {});
}
} finally {
this.running = undefined;
}
});
}
flush() { return this.running; }
}