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。

feat(pi): measure preparation time and add runtime health check

Chrisc3c9b7e92a97
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 71eb395aef..6d35e7d4c1 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -104,7 +104,7 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
本机 Pi bridge 在原生 `before_provider_request` 处理后,通过既有单向通知发送白名单
请求摘要。宿主以 `startupTraceId + requestSequence` 记录 debug 级 `pi request stage`:
-`provider-request-prepared`(本桥处理后的工具数、消息数、wire effort)、`first-output`
+`provider-request-prepared`(本桥处理后的工具数、消息数、wire effort、`preparationMs`)、`first-output`
(首个文本/推理增量或工具调用开始/增量)、`agent-settled`(原生整轮终态,不能用 `agent_end` 替代)。
请求阶段时长用宿主单调时钟,`elapsedMs` 从最近一次请求摘要到达起算;终态另有
`turnElapsedMs`,从本轮第一次请求摘要到达起算,包含重试/工具等后续处理。
@@ -115,6 +115,15 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
只记录有界计数和已知档位名,无法识别的请求字段省略,不把未知工具数当成零。
不记录请求正文、工具定义、模型 ID、凭据或任意上游字符串;
诊断失败不能阻止发送,也不出现在聊天里,不增加需要宿主应答的 RPC。
+`preparationMs` 单独记录本桥 `before_provider_request` 的单调时钟耗时,包含 Fast 偏好
+查询的等待;它不包含此前 Pi 构造上下文及此后网络传输,也不改变既有 `elapsedMs` 起点。
+
+升级官方 Pi 后可运行 `node scripts/pi-healthcheck.mjs --binary /absolute/path/to/pi`。
+省略参数使用仓库分发二进制;脚本不安装或替换运行时、不读取正式任务或配置、不启用扩展。
+它启动临时 PiAgent 与本机协议端点,逐项检查 Fast、窗口与恢复、线上请求档位投影、图片与
+历史、MCP 批准/拒绝、多服务、结构化结果、SSE 和分页。JSON 报告输出到 stdout,测试输出
+到 stderr;任一必需项失败、跳过或未发现都返回非零。它验证接线兼容性,不证明在线模型
+质量、上游服务可用性或真实网络速度。
Gateway 的档位成员仍以供应商实报为准。目录支持 low 时,Cindy 能传 low;不支持时,
启动选择按现有默认档收敛,不能把直接调用 SDK 的 low→medium 结果冒充完整宿主路径。
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index 0ea822c3db..c133143969 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -1046,7 +1046,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
try {
writeFileSync(path.join(workingDir, 'proof.txt'), 'GROK47_TOOL_OK');
const imagePath = path.join(workingDir, 'pixel.png');
- writeFileSync(imagePath, Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64'));
+ writeFileSync(imagePath, Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGP4DwQACfsD/fteaysAAAAASUVORK5CYII=', 'base64'));
handle = await agent.startSession({ sessionId: 'grok47-native', workingDir,
model: row.id, providerId: 'xai', effort: 'high', permissionMode: 'bypassPermissions' });
const send = async (image = false) => {
@@ -1362,9 +1362,10 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
'forwards an image attachment through pi to the gateway (multimodal image)',
{ timeout: 60_000 },
async () => {
- // 合法 1x1 透明 PNG —— pi 不会因非法图片拒收;其 base64 应原样出现在网关请求体。
+ // Valid 1x1 RGBA PNG, including chunk CRCs. Pi 1.4 rejects the old corrupt
+ // fixture during image normalization; intact bytes must reach the model.
const PNG_1x1_B64 =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGP4DwQACfsD/fteaysAAAAASUVORK5CYII=';
const agent = new PiAgent(buildDeps());
const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-img-cwd-'));
let handle: AgentSessionHandle | null = null;
@@ -1406,7 +1407,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
{ timeout: 60_000 },
async () => {
const pngBase64 =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGP4DwQACfsD/fteaysAAAAASUVORK5CYII=';
const agent = new PiAgent(buildDeps());
const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-review-formats-'));
const markdownPath = path.join(workingDir, 'launch.md');
@@ -2154,7 +2155,9 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
expect(body.thinking).toEqual({ type: 'enabled' });
const stages = debug.mock.calls.filter(([message]) => message === 'pi request stage').map(([, fields]) => fields);
expect(stages.map(row => row.stage)).toEqual(['provider-request-prepared', 'first-output', 'agent-settled']);
- expect(stages[0]).toMatchObject({ wireEffort: wire, toolCount: body.tools.length, messageCount: body.messages.length });
+ expect(stages[0]).toMatchObject({ wireEffort: wire, toolCount: body.tools.length, messageCount: body.messages.length,
+ preparationMs: expect.any(Number) });
+ expect(stages[0].preparationMs).toBeGreaterThanOrEqual(0);
expect(JSON.stringify(stages)).not.toContain('private translation fixture');
expect(JSON.stringify(stages)).not.toContain('test-key-123');
} finally {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 43b5cc8b9e..07eaf2f63f 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -3372,7 +3372,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
notify('wrong-instance:{"wireEffort":"low"}');
notify(`${token}:invalid-json`);
expect(debug.mock.calls.filter(([message]) => message === 'pi request stage')).toEqual([]);
- notify(`${token}:${JSON.stringify({ toolCount: 2, messageCount: 3, wireEffort: 'medium', secret: 'private-content' })}`);
+ notify(`${token}:${JSON.stringify({ toolCount: 2, messageCount: 3, preparationMs: 5012.4, wireEffort: 'medium', secret: 'private-content' })}`);
const delta = { type: 'message_update', assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'private-output' } };
knobs.onEvent?.(delta);
knobs.onEvent?.(delta);
@@ -3382,9 +3382,9 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
knobs.onEvent?.({ type: 'agent_settled' });
stages = debug.mock.calls.filter(([message]) => message === 'pi request stage').map(([, fields]) => fields);
expect(stages.map(row => row.stage)).toEqual(['provider-request-prepared', 'first-output', 'agent-settled']);
- expect(stages[0]).toMatchObject({ toolCount: 2, messageCount: 3, wireEffort: 'medium', requestSequence: 1 });
+ expect(stages[0]).toMatchObject({ toolCount: 2, messageCount: 3, preparationMs: 5012, wireEffort: 'medium', requestSequence: 1 });
expect(stages[2]).toMatchObject({ requestSequence: 1, elapsedMs: expect.any(Number), turnElapsedMs: expect.any(Number) });
- notify(`${token}:${JSON.stringify({ toolCount: -1, messageCount: 'secret', wireEffort: 'private-effort' })}`);
+ notify(`${token}:${JSON.stringify({ toolCount: -1, messageCount: 'secret', preparationMs: 60001, wireEffort: 'private-effort' })}`);
const last = debug.mock.calls.filter(([message]) => message === 'pi request stage').at(-1)?.[1];
expect(last).toEqual({ startupTraceId: resolverOptions?.startupTraceId, requestSequence: 2,
stage: 'provider-request-prepared', wireEffort: null });
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index af79af9590..06d13d8eac 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -66,6 +66,8 @@ export function projectPiRequestDiagnostics(value: unknown): Record<string, numb
const count = row[key];
if (typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 && count <= 1_000_000) result[key] = count;
}
+ if (typeof row.preparationMs === 'number' && Number.isFinite(row.preparationMs)
+ && row.preparationMs >= 0 && row.preparationMs <= 60_000) result.preparationMs = Math.round(row.preparationMs);
result.wireEffort = typeof row.wireEffort === 'string' &&
['none', 'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(row.wireEffort)
? row.wireEffort : null;
@@ -4520,6 +4522,7 @@ export default async function cindyBridge(piApi: any) {
} catch { return payload; }
}
pi.on('before_provider_request', async (event, ctx) => {
+ const preparationStarted = performance.now();
const payload = astraResponsesPayload(event.payload, ctx.model) ?? event.payload;
const next = learnedCachePayload((await nativeFastPayload(payload, ctx.model, ctx)) ?? payload, ctx.model);
// A one-way native notification adds no host round trip. This is the payload
@@ -4530,6 +4533,7 @@ export default async function cindyBridge(piApi: any) {
const messages = next?.messages ?? next?.input ?? next?.contents;
ctx.ui.notify(${JSON.stringify(CINDY_PI_REQUEST_DIAGNOSTICS_PREFIX)} + token + ':' + JSON.stringify(
projectPiRequestDiagnostics({
+ preparationMs: performance.now() - preparationStarted,
toolCount: Array.isArray(next?.tools) ? next.tools.length : undefined,
messageCount: Array.isArray(messages) ? messages.length : undefined,
wireEffort: next?.reasoning_effort ?? next?.reasoning?.effort ?? next?.output_config?.effort,
diff --git a/scripts/pi-healthcheck.mjs b/scripts/pi-healthcheck.mjs
new file mode 100644
index 0000000000..7fb1149f95
--- /dev/null
+++ b/scripts/pi-healthcheck.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+// Exercise Cindy's production PiAgent with an official binary and local fixture
+// servers. No account, extension installation, or Desktop restart is needed.
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const args = process.argv.slice(2);
+if (args.length === 1 && args[0] === '--help') {
+ console.log('Usage: node scripts/pi-healthcheck.mjs [--binary /absolute/path/to/pi]\n'
+ + 'Defaults to the repository Pi binary. JSON report on stdout; local test progress on stderr.\n'
+ + 'Runs isolated PiAgent protocol checks, not an online model quality or speed benchmark.');
+ process.exit(0);
+}
+if (args.length && (args.length !== 2 || args[0] !== '--binary' || !path.isAbsolute(args[1]))) {
+ console.error('Expected --binary /absolute/path/to/pi, or --help.');
+ process.exit(2);
+}
+const binary = args[1] ?? path.join(root, 'apps/pi-bin', `${process.platform}-${process.arch}`,
+ process.platform === 'win32' ? 'pi.exe' : 'pi');
+const groups = [
+ { name: 'fast-preferences', pattern: 'reads native Fast from host RPC' },
+ { name: 'window-and-resume', pattern: 'applies configured windows on creation' },
+ { name: 'wire-effort-and-timing', pattern: 'sends catalog effort' },
+ { name: 'images-and-history', pattern: 'runs Grok 4.7 with all efforts, image input' },
+ { name: 'image-attachment', pattern: 'forwards an image attachment through pi to the gateway' },
+ { name: 'mcp-allow', pattern: 'ask \\+ allow:' },
+ { name: 'mcp-deny', pattern: 'ask \\+ deny:' },
+ { name: 'mcp-multiple-servers', pattern: 'executes five real tools across two MCP servers' },
+ { name: 'mcp-structured-success', pattern: 'preserves MCP structured success data' },
+ { name: 'mcp-structured-error', pattern: 'preserves MCP structured failure data' },
+ { name: 'mcp-sse', pattern: 'persistent SSE: registers' },
+ { name: 'mcp-pagination', pattern: 'paginated tools/list: follows' },
+];
+const started = performance.now();
+let temporary;
+let report = { ok: false, binary, mode: 'isolated-local-protocol', groups: [] };
+try {
+ if (!existsSync(binary)) throw new Error('Pi binary is missing; pass --binary pointing to the installed official runtime.');
+ const version = spawnSync(binary, ['--version'], { encoding: 'utf8', timeout: 10_000 });
+ if (version.error || version.status !== 0) throw new Error('Pi --version failed; verify the binary can run on this computer.');
+ report.version = version.stdout.trim().slice(0, 120);
+ const vitest = path.join(root, 'node_modules/vitest/vitest.mjs');
+ if (!existsSync(vitest)) throw new Error('Repository test dependencies are missing; install them before running the health check.');
+ temporary = mkdtempSync(path.join(tmpdir(), 'cindy-pi-health-'));
+ const home = path.join(temporary, 'home');
+ mkdirSync(home);
+ const output = path.join(temporary, 'results.json');
+ const run = spawnSync(process.execPath, [vitest, 'run',
+ 'src/agents/pi/__tests__/pi-agent.integration.test.ts',
+ 'src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts',
+ '--maxWorkers=1', '--no-file-parallelism', '-t', groups.map(group => group.pattern).join('|'),
+ '--reporter=json', '--outputFile', output,
+ ], {
+ cwd: path.join(root, 'packages/maker-core'), encoding: 'utf8', timeout: 180_000, maxBuffer: 4 * 1024 * 1024,
+ env: { ...process.env, HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: path.join(home, '.config'),
+ PI_CODING_AGENT_DIR: path.join(home, '.pi/agent'),
+ CINDY_TEST_PI_BINARY: binary, CINDY_PI_MCP_TEST_BINARY: binary },
+ });
+ if (run.stdout) process.stderr.write(run.stdout);
+ if (run.stderr) process.stderr.write(run.stderr);
+ if (run.error) throw new Error('Health check process failed or exceeded 180 seconds; inspect the test output.');
+ if (!existsSync(output)) throw new Error('Test report is missing; health could not be verified.');
+ const results = JSON.parse(readFileSync(output, 'utf8'));
+ const assertions = results.testResults.flatMap(file => file.assertionResults);
+ for (const test of assertions.filter(test => test.status === 'failed')) {
+ console.error(test.fullName + '\n' + (test.failureMessages ?? []).join('\n').slice(0, 2000));
+ }
+ report.groups = groups.map(group => {
+ const selected = assertions.filter(test => new RegExp(group.pattern).test(test.fullName));
+ return { name: group.name, passed: selected.filter(test => test.status === 'passed').length,
+ total: selected.length, ok: selected.length > 0 && selected.every(test => test.status === 'passed') };
+ });
+ report.ok = run.status === 0 && results.success === true && report.groups.every(group => group.ok);
+ if (!report.ok) report.error = 'At least one required check failed, was skipped, or was not discovered. See group results and stderr.';
+} catch (error) {
+ report.error = error instanceof Error ? error.message : 'Health check failed.';
+} finally {
+ if (temporary) rmSync(temporary, { recursive: true, force: true });
+}
+report.elapsedMs = Math.round(performance.now() - started);
+console.log(JSON.stringify(report, null, 2));
+process.exitCode = report.ok ? 0 : 1;