Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(maker-core): pi RPC 帧级定界诊断,锁定成功轮正文单帧丢失(#3696) (#3742)

fico-hubae2945c1fa9d
diff --git a/packages/maker-core/src/agents/pi/rpc-client.test.ts b/packages/maker-core/src/agents/pi/rpc-client.test.ts
index 2e4a4ef28a..0b210e3620 100644
--- a/packages/maker-core/src/agents/pi/rpc-client.test.ts
+++ b/packages/maker-core/src/agents/pi/rpc-client.test.ts
@@ -58,6 +58,142 @@ beforeEach(() => {
mocks.spawn.mockReset();
});
+describe('PiRpcProcess frame diagnostics (#3696)', () => {
+ function createProcessWithMocks() {
+ const child = makeChild();
+ mocks.spawn.mockReturnValue(child);
+ const logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: vi.fn(),
+ };
+ logger.child.mockReturnValue(logger);
+ const transport = createPiStdioTransport({
+ binaryPath: '/pi',
+ args: ['--mode', 'rpc'],
+ cwd: '/work',
+ env: {},
+ logger,
+ });
+ const onEvent = vi.fn();
+ const proc = new PiRpcProcess({ transport, logger, onEvent, onExit: vi.fn() });
+ const feed = (frame: Record<string, unknown>): void => {
+ child.stdout.emit('data', Buffer.from(`${JSON.stringify(frame)}\n`));
+ };
+ return { proc, logger, onEvent, feed };
+ }
+
+ it('logs message_end frame metadata (block types + char counts) without message content', () => {
+ const { logger, onEvent, feed } = createProcessWithMocks();
+ feed({
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ stopReason: 'stop',
+ content: [
+ { type: 'thinking', thinking: '思考中' },
+ { type: 'text', text: 'hello world' },
+ ],
+ },
+ });
+
+ expect(logger.info).toHaveBeenCalledWith('pi rpc message_end frame', {
+ role: 'assistant',
+ stopReason: 'stop',
+ blockTypes: ['thinking', 'text'],
+ textChars: 'hello world'.length,
+ thinkingChars: '思考中'.length,
+ });
+ // 事件仍照常透传,诊断不改变协议行为。
+ expect(onEvent).toHaveBeenCalledTimes(1);
+ // 隐私:任何日志载荷里不得出现消息正文。
+ const serializedLogs = JSON.stringify([
+ logger.info.mock.calls,
+ logger.warn.mock.calls,
+ logger.debug.mock.calls,
+ ]);
+ expect(serializedLogs).not.toContain('hello world');
+ expect(serializedLogs).not.toContain('思考中');
+ });
+
+ it('flushes an unsettled turn histogram at the next agent_start (no cross-turn bleed)', () => {
+ const { logger, feed } = createProcessWithMocks();
+ // 第一轮:abort 类结束,收不到 agent_settled。
+ feed({ type: 'agent_start' });
+ feed({ type: 'message_update', assistantMessageEvent: { type: 'text_delta' } });
+ // 第二轮开始:先冲刷上一轮直方图并清零。
+ feed({ type: 'agent_start' });
+ expect(logger.info).toHaveBeenCalledWith('pi rpc turn frame histogram (no agent_settled)', {
+ frames: { agent_start: 1, message_update: 1 },
+ });
+ feed({ type: 'agent_settled' });
+ // 第二轮直方图不含第一轮的 message_update 计数。
+ expect(logger.info).toHaveBeenCalledWith('pi rpc turn frame histogram', {
+ frames: { agent_start: 1, agent_settled: 1 },
+ });
+ });
+
+ it('normalizes non-identifier labels to (other) so hostile fields never reach logs', () => {
+ const { logger, feed } = createProcessWithMocks();
+ const smuggled = 'secret token value with spaces';
+ feed({
+ type: smuggled,
+ });
+ feed({
+ type: 'message_end',
+ message: {
+ role: smuggled,
+ stopReason: smuggled,
+ content: [{ type: smuggled, text: 'x' }],
+ },
+ });
+ feed({ type: 'agent_settled' });
+ expect(logger.info).toHaveBeenCalledWith('pi rpc message_end frame', {
+ role: '(other)',
+ stopReason: '(other)',
+ blockTypes: ['(other)'],
+ textChars: 0,
+ thinkingChars: 0,
+ });
+ const serializedLogs = JSON.stringify([logger.info.mock.calls, logger.warn.mock.calls]);
+ expect(serializedLogs).not.toContain(smuggled);
+ // 直方图键同样被归一化。
+ expect(logger.info).toHaveBeenCalledWith('pi rpc turn frame histogram', {
+ frames: { '(other)': 1, message_end: 1, agent_settled: 1 },
+ });
+ });
+
+ it('logs a per-turn frame histogram at agent_settled and resets counts', () => {
+ const { logger, feed } = createProcessWithMocks();
+ feed({ type: 'agent_start' });
+ feed({ type: 'message_update', assistantMessageEvent: { type: 'text_delta' } });
+ feed({ type: 'message_update', assistantMessageEvent: { type: 'text_delta' } });
+ feed({ type: 'message_end', message: { role: 'assistant', stopReason: 'stop', content: [] } });
+ feed({ type: 'agent_settled' });
+
+ expect(logger.info).toHaveBeenCalledWith('pi rpc turn frame histogram', {
+ frames: {
+ agent_start: 1,
+ message_update: 2,
+ message_end: 1,
+ agent_settled: 1,
+ },
+ });
+
+ logger.info.mockClear();
+ feed({ type: 'agent_start' });
+ feed({ type: 'agent_settled' });
+ // 第二轮直方图不包含第一轮计数(settled 后已清零)。
+ expect(logger.info).toHaveBeenCalledWith('pi rpc turn frame histogram', {
+ frames: { agent_start: 1, agent_settled: 1 },
+ });
+ });
+});
+
describe('PiRpcProcess process observer', () => {
it('registers the concrete PID and disposes that generation once on close', () => {
const child = makeChild();
diff --git a/packages/maker-core/src/agents/pi/rpc-client.ts b/packages/maker-core/src/agents/pi/rpc-client.ts
index f1e2033abd..3e55558ca8 100644
--- a/packages/maker-core/src/agents/pi/rpc-client.ts
+++ b/packages/maker-core/src/agents/pi/rpc-client.ts
@@ -85,6 +85,18 @@ function redactCredentialText(text: string): string {
return out;
}
+/**
+ * 帧诊断日志的标签白名单:pi 协议的事件类型 / role / stopReason / 块类型都是短
+ * 标识符。扩展或畸形事件可能把任意正文塞进这些字段 —— 不符合标识符形态的一律
+ * 归一为 '(other)',落实「不落消息内容」的白名单方向(不是靠脱敏兜底)。
+ */
+const FRAME_LABEL_RE = /^[A-Za-z0-9_.:-]{1,64}$/;
+
+function sanitizeFrameLabel(value: unknown): string {
+ if (typeof value !== 'string' || value.length === 0) return '(untyped)';
+ return FRAME_LABEL_RE.test(value) ? value : '(other)';
+}
+
export class PiRpcProcess {
private readonly transport: PiTransport;
private nextRequestId = 1;
@@ -105,6 +117,13 @@ export class PiRpcProcess {
*/
private closePromise: Promise<void> | null = null;
private readonly logger: Logger;
+ /**
+ * #3696 定界诊断:成功轮的正文可能整帧消失(jsonl 有正文、DB/UI 均无),离线
+ * 无法复现。这里按事件类型计数、在 message_end/agent_settled 落两行元数据日志
+ * (块类型与字符数,不含任何消息内容),让下一次复现能区分「pi 未发出该帧」
+ * 与「Cindy 收到后在下游丢失」。
+ */
+ private readonly eventFrameCounts = new Map<string, number>();
constructor(private readonly opts: PiRpcSpawnOptions) {
this.logger = opts.logger;
@@ -292,6 +311,7 @@ export class PiRpcProcess {
}
const event = obj as PiRpcEvent;
+ this.recordEventFrameDiagnostics(event);
for (const [id, entry] of this.pending) {
if (!entry.refreshTimeoutOnEvent?.(event)) continue;
clearTimeout(entry.timer);
@@ -304,6 +324,60 @@ export class PiRpcProcess {
this.opts.onEvent(event);
}
+ /** 只记帧元数据(类型 / 块类型 / 字符数),绝不落消息正文 —— 日志白名单方向。 */
+ private recordEventFrameDiagnostics(event: PiRpcEvent): void {
+ const type = sanitizeFrameLabel(event.type);
+ // abort / 重试失败 / 进程异常的轮次收不到 agent_settled:计数留到下一轮会把
+ // 「message_end 是否到达」污染成不可归属。新轮 agent_start 先冲刷再清零 ——
+ // 既保住未收口轮的证据,又保证每份直方图只属于一轮。
+ if (type === 'agent_start' && this.eventFrameCounts.size > 0) {
+ this.logger.info('pi rpc turn frame histogram (no agent_settled)', {
+ frames: Object.fromEntries(this.eventFrameCounts),
+ });
+ this.eventFrameCounts.clear();
+ }
+ this.eventFrameCounts.set(type, (this.eventFrameCounts.get(type) ?? 0) + 1);
+ if (type === 'message_end') {
+ const message = event.message as
+ | { role?: unknown; stopReason?: unknown; content?: unknown }
+ | undefined;
+ const blocks = Array.isArray(message?.content) ? message.content : [];
+ const blockTypes: string[] = [];
+ let textChars = 0;
+ let thinkingChars = 0;
+ for (const block of blocks) {
+ if (!block || typeof block !== 'object') {
+ blockTypes.push('(invalid)');
+ continue;
+ }
+ const rec = block as Record<string, unknown>;
+ const blockType = sanitizeFrameLabel(rec.type);
+ blockTypes.push(blockType);
+ if (rec.type === 'text' && typeof rec.text === 'string') textChars += rec.text.length;
+ if (rec.type === 'thinking' && typeof rec.thinking === 'string') {
+ thinkingChars += rec.thinking.length;
+ }
+ }
+ this.logger.info('pi rpc message_end frame', {
+ role: sanitizeFrameLabel(message?.role),
+ stopReason:
+ message?.stopReason === undefined || message?.stopReason === null
+ ? null
+ : sanitizeFrameLabel(message.stopReason),
+ blockTypes,
+ textChars,
+ thinkingChars,
+ });
+ return;
+ }
+ if (type === 'agent_settled') {
+ this.logger.info('pi rpc turn frame histogram', {
+ frames: Object.fromEntries(this.eventFrameCounts),
+ });
+ this.eventFrameCounts.clear();
+ }
+ }
+
private failAllPending(err: Error): void {
for (const [, entry] of this.pending) {
clearTimeout(entry.timer);