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(pi): reclaim idle plugin runtimes and clarify request diagnostics

Dash8fd7953687a1
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index 44b532ef7e..c7fbe65746 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
refresh: vi.fn(),
invalidateSession: vi.fn(),
logger: {
+ debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
@@ -25,17 +26,43 @@ vi.mock('../authManager', () => ({
vi.mock('../i18n.js', () => ({
getResolvedMainLocale: () => 'zh-CN',
}));
+vi.mock('../clientEndpointsService.js', () => ({
+ getClientEndpoint: () => 'https://models.example.test',
+}));
vi.mock('../logger', () => ({
createLogger: () => mocks.logger,
}));
import { serverApiFetch } from '../serverApiClient';
+import { readOrganizationAccountUsage } from '../usage/organizationAccountUsage';
describe('serverApiFetch', () => {
beforeEach(() => {
vi.clearAllMocks();
});
+ // Unit: exercise the real quota reader through the HTTP client. Previously its
+ // mocked client hid recurring warnings for a successful legacy fallback.
+ it.each([
+ { status: 404, code: 'NOT_FOUND', fallback: true },
+ { status: 501, code: 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED', fallback: true },
+ { status: 501, code: 'OTHER_FAILURE', fallback: false },
+ { status: 503, code: 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED', fallback: false },
+ { status: 403, code: 'FORBIDDEN', fallback: false },
+ { status: 401, code: 'ACCOUNT_UNAVAILABLE', fallback: false },
+ ])('only downgrades expected quota fallback logs: $status $code', async ({ status, code, fallback }) => {
+ mocks.netFetch.mockResolvedValueOnce(new Response(JSON.stringify({
+ error: { code, message: 'private upstream message' },
+ }), { status }));
+ const result = await readOrganizationAccountUsage();
+ expect(result).toBe(fallback ? undefined : null);
+ expect(mocks.logger.warn).toHaveBeenCalledTimes(fallback ? 0 : 1);
+ expect(mocks.logger.debug).toHaveBeenCalledTimes(fallback ? 1 : 0);
+ expect(JSON.stringify([...mocks.logger.warn.mock.calls, ...mocks.logger.debug.mock.calls]))
+ .not.toContain('private upstream message');
+ if (status === 401) expect(mocks.invalidateSession).toHaveBeenCalledWith('account-unavailable');
+ });
+
it('keeps an unfamiliar original error and its cause while redacting secrets before logging', async () => {
const cause = Object.assign(new Error('proxy refused tunnel https://api.example.invalid/account/private-account#private-fragment'),
{ code: 'NEW_PROXY_FAILURE' });
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts
index 08164fb14c..6e695fed15 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts
@@ -1,7 +1,13 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { and, eq, sql } from 'drizzle-orm';
+import { sessions } from '../../localDb/schema.js';
import {
createPiIdleReleaseWatcher,
+ piIdleReleaseCandidateWhere,
+ piIdleReleaseIdleSince,
type PiIdleReleaseCandidate,
type PiIdleReleaseWatcherDeps,
} from '../piIdleReleaseWatcher';
@@ -45,6 +51,52 @@ afterEach(() => {
});
describe('createPiIdleReleaseWatcher', () => {
+ // Unit regression: the real scan/recheck SQL excluded hidden plugin tasks.
+ // Existing tests injected preselected candidates and could not catch that leak.
+ // Minimal input: one idle hidden Pi plugin task; use in-memory SQLite, no user DB.
+ it.each(['active', 'archived'])('releases idle %s plugin runtimes through the database filter', async (status) => {
+ const sqlite = new Database(':memory:');
+ try {
+ sqlite.exec(`CREATE TABLE sessions (
+ id TEXT PRIMARY KEY, agent_kind TEXT, status TEXT, source TEXT, orca_role TEXT,
+ hidden_at INTEGER, remote_host_id TEXT, agent_device_id TEXT,
+ updated_at INTEGER, last_turn_ended_at INTEGER, user_send_at INTEGER
+ )`);
+ const insert = sqlite.prepare('INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
+ insert.run('plugin', 'pi', status, 'plugin', null, 1, null, null, 0, 0, 0);
+ insert.run('desktop', 'pi', status, 'desktop', null, null, null, null, 0, 0, 0);
+ insert.run('hidden-desktop', 'pi', status, 'desktop', null, 1, null, null, 0, 0, 0);
+ insert.run('worker', 'pi', status, 'plugin', 'worker', 1, null, null, 0, 0, 0);
+ insert.run('ssh', 'pi', status, 'plugin', null, 1, 'ssh', null, 0, 0, 0);
+ insert.run('device', 'pi', status, 'plugin', null, 1, null, 'device', 0, 0, 0);
+ insert.run('bot', 'pi', status, 'bot', null, null, null, null, 0, 0, 0);
+ insert.run('codex', 'codex', status, 'plugin', null, 1, null, null, 0, 0, 0);
+ insert.run('deleted', 'pi', 'deleted', 'plugin', null, 1, null, null, 0, 0, 0);
+ insert.run('recent', 'pi', status, 'plugin', null, 1, null, null, 0, 90_000, 0);
+ const db = drizzle(sqlite);
+ const idleSince = piIdleReleaseIdleSince();
+ const { deps, session, watcher } = createDeps({
+ listCandidates: async before => db.select({ id: sessions.id, idleSinceMs: idleSince }).from(sessions)
+ .where(and(piIdleReleaseCandidateWhere(), sql`${idleSince} < ${before}`)).all(),
+ readIdleSinceMs: async id => db.select({ idleSinceMs: idleSince }).from(sessions)
+ .where(and(eq(sessions.id, id), piIdleReleaseCandidateWhere())).get()?.idleSinceMs ?? null,
+ });
+ await watcher.scanNow();
+ expect(vi.mocked(deps.getSession).mock.calls.map(([id]) => id).sort()).toEqual(['desktop', 'plugin']);
+ expect(session.closeIfIdle).toHaveBeenCalledTimes(2);
+ // The lock recheck must also see plugin activity that arrived after selection.
+ vi.mocked(deps.withSessionLock).mockImplementation(async (id, task) => {
+ if (id === 'plugin') sqlite.prepare('UPDATE sessions SET user_send_at = 100000 WHERE id = ?').run(id);
+ return task();
+ });
+ session.closeIfIdle.mockClear();
+ await watcher.scanNow();
+ expect(session.closeIfIdle).toHaveBeenCalledOnce();
+ } finally {
+ sqlite.close();
+ }
+ });
+
it('does not scan when idle release is disabled', async () => {
const { deps, watcher } = createDeps({
readIdleReleaseMinutes: vi.fn(() => 0),
diff --git a/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts b/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts
index dddd5cd04a..00feddde38 100644
--- a/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts
+++ b/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts
@@ -1,10 +1,10 @@
/**
- * piIdleReleaseWatcher —— 桌面普通 pi 会话的空闲运行时回收。
+ * piIdleReleaseWatcher —— 桌面普通及插件 pi 会话的空闲运行时回收。
*
* 背景(2026-10 实测 + upstream #5830):`pi --mode rpc` 子进程每个约 150~300MB,
* 普通会话此前没有任何 Idle TTL/LRU —— 只有退出应用、切换 Agent 或 Orca 工人
* 走各自路径才会回收,长时间使用后进程数与内存持续累积、整机变卡、重启才恢复。
- * 这里为「本机、桌面来源、非 Orca/bot」的 pi 会话补一个与
+ * 这里为「本机、桌面普通或插件来源、非 Orca/bot」的 pi 会话补一个与
* `orcaIdleReleaseWatcher` 同构的 watcher。
*
* 候选由 SQL 给出(闲置起点取 max(updated_at, last_turn_ended_at, user_send_at)),
@@ -18,6 +18,25 @@
* 与冷启动语义一致,见 docs/dev-rules/pi-harness.md。
*/
+import { and, eq, inArray, isNull, or, sql } from 'drizzle-orm';
+import { sessions } from '../localDb/schema.js';
+
+/** Shared by the initial scan and the lock-protected recheck. */
+export const piIdleReleaseIdleSince = () =>
+ sql<number>`max(${sessions.updatedAt}, coalesce(${sessions.lastTurnEndedAt}, 0), coalesce(${sessions.userSendAt}, 0))`;
+
+export const piIdleReleaseCandidateWhere = () =>
+ and(
+ eq(sessions.agentKind, 'pi'),
+ inArray(sessions.status, ['active', 'archived']),
+ // Plugin tasks are intentionally hidden, but their processes are host-owned.
+ // Keep other hidden tasks and specialized lifecycle owners out of this scan.
+ or(and(eq(sessions.source, 'desktop'), isNull(sessions.hiddenAt)), eq(sessions.source, 'plugin')),
+ isNull(sessions.orcaRole),
+ isNull(sessions.remoteHostId),
+ isNull(sessions.agentDeviceId),
+ );
+
/** 普通 pi 会话进入空闲回收前的闲置时长(分钟)。与远端 pi daemon 的 30min 口径一致。 */
export const DEFAULT_PI_IDLE_RELEASE_MINUTES = 30;
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 5dff75f0e0..0a7d616e3f 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -755,6 +755,8 @@ import {
import { createOrcaWorkerResumeScheduler } from './orcaWorkerResumeScheduler.js';
import {
createPiIdleReleaseWatcher,
+ piIdleReleaseCandidateWhere,
+ piIdleReleaseIdleSince,
DEFAULT_PI_IDLE_RELEASE_MINUTES,
type PiIdleReleaseWatcher,
} from './piIdleReleaseWatcher.js';
@@ -16385,23 +16387,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
idleReleaseWatcher.start();
- // ─── pi 普通会话 idle watcher ────────────────────────────────────────────
- // 只回收本机桌面来源的普通 pi 会话:Orca 角色/远程/插件隐藏任务/bot 与 IM
- // 来源都有各自的生命周期。归档会话也纳入(归档不关运行时),其余安全闸门见
+ // ─── pi 普通与插件会话 idle watcher ──────────────────────────────────────
+ // 插件隐藏任务也由宿主回收;Orca 角色/远程/bot 与 IM 沿用各自生命周期。
+ // 归档会话也纳入(归档不关运行时),其余安全闸门见
// piIdleReleaseWatcher;释放后下一次发送走 lazy create-session 透明重建。
- const PI_IDLE_RELEASE_SESSION_STATUSES = ['active', 'archived'] as const;
- const piIdleReleaseIdleSince = () =>
- sql<number>`max(${sessions.updatedAt}, coalesce(${sessions.lastTurnEndedAt}, 0), coalesce(${sessions.userSendAt}, 0))`;
- const piIdleReleaseCandidateWhere = () =>
- and(
- eq(sessions.agentKind, 'pi'),
- inArray(sessions.status, PI_IDLE_RELEASE_SESSION_STATUSES),
- eq(sessions.source, 'desktop'),
- isNull(sessions.orcaRole),
- isNull(sessions.hiddenAt),
- isNull(sessions.remoteHostId),
- isNull(sessions.agentDeviceId),
- );
piIdleReleaseWatcher?.stop();
piIdleReleaseWatcher = createPiIdleReleaseWatcher({
readIdleReleaseMinutes: () => DEFAULT_PI_IDLE_RELEASE_MINUTES,
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index a09f3e2cfa..86e0bc903d 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -71,6 +71,8 @@ export interface ApiFetchOptions {
* by the caller. These codes are also safe to include in redacted logs.
*/
allowedRedactedErrorCodes?: readonly string[];
+ /** Expected compatibility responses still throw, but log at debug instead of warn. */
+ expectedErrors?: readonly { status: number; code?: string }[];
}
interface RawResponse<T> {
@@ -172,8 +174,11 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
}
// 网络异常 rawFetch 已 log;这里补 not-ok 响应(401/5xx 等)的日志,
// 否则上层 catch 一吞,排查调用链时完全看不到原因。
+ const expected = opts.expectedErrors?.some(({ status, code }) =>
+ result.status === status && (code === undefined || code === errCode));
+ const logNotOk = expected ? log.debug.bind(log) : log.warn.bind(log);
if (opts.redactErrorDetails) {
- log.warn(
+ logNotOk(
'serverApiFetch.redacted_not_ok',
'path=' + (opts.logLabel ?? redactedLogPath(apiPath)),
'method=' + (opts.method ?? 'GET'),
@@ -192,7 +197,7 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
'code=' + errCode,
];
if (!opts.logLabel) fields.push('msg=' + errMsg);
- log.warn(...fields);
+ logNotOk(...fields);
}
throw new ServerApiError(
publicCode,
diff --git a/apps/desktop/src/main/usage/organizationAccountUsage.ts b/apps/desktop/src/main/usage/organizationAccountUsage.ts
index 43ac4318f9..0ad2727758 100644
--- a/apps/desktop/src/main/usage/organizationAccountUsage.ts
+++ b/apps/desktop/src/main/usage/organizationAccountUsage.ts
@@ -9,6 +9,7 @@ export async function readOrganizationAccountUsage(): Promise<ClaudeAccountUsage
baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
timeoutMs: 8000, redactErrorDetails: true,
allowedRedactedErrorCodes: ['MODEL_ACCESS_QUOTA_NOT_SUPPORTED'],
+ expectedErrors: [{ status: 404 }, { status: 501, code: 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED' }],
});
if (!data || typeof data !== 'object') return null;
const row = data as Record<string, unknown>;
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 138ce3dcdb..0fc2684367 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -97,6 +97,34 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
## 2. 配置面:Cindy 显式设置 vs 放任 pi 默认
+### 请求计时与档位核验
+
+`pi startup stage` 的 `first-prompt-rpc` 只测第一次 prompt RPC 发出至回执/失败,
+不再使用容易误解的 `first-model-request` 名称。RPC 接受不等于 HTTP 已发送或整轮完成。
+
+本机 Pi bridge 在原生 `before_provider_request` 处理后,通过既有单向通知发送白名单
+请求摘要。宿主以 `startupTraceId + requestSequence` 记录 debug 级 `pi request stage`:
+`provider-request-prepared`(本桥处理后的工具数、消息数、wire effort)、`first-output`
+(首个文本/推理/工具增量)、`agent-settled`(原生整轮终态,不能用 `agent_end` 替代)。
+请求阶段时长用宿主单调时钟,`elapsedMs` 从最近一次请求摘要到达起算;终态另有
+`turnElapsedMs`,从本轮第一次请求摘要到达起算,包含重试/工具等后续处理。
+这是请求构造钩子的观测时间,不是 socket 发出时间、上游接收时间或插件收到答复时间;
+后加载的用户扩展仍可能改写请求。没有测点的 SSH/旧运行时不编造该阶段。
+只记录有界计数和已知档位名,无法识别的请求字段省略,不把未知工具数当成零。
+不记录请求正文、工具定义、模型 ID、凭据或任意上游字符串;
+诊断失败不能阻止发送,也不出现在聊天里,不增加需要宿主应答的 RPC。
+
+Gateway 的档位成员仍以供应商实报为准。目录支持 low 时,Cindy 能传 low;不支持时,
+启动选择按现有默认档收敛,不能把直接调用 SDK 的 low→medium 结果冒充完整宿主路径。
+bundled map 对已支持档位的 remap 保留,medium 可能映射为 high,因此不能仅凭档位名称
+声称推理强度降低。`pi-agent.integration.test.ts` 用真实 Pi 和 loopback 假网关验证
+low→low、声明的 medium→high,以及不支持 low→默认 high;它验证客户端传输,
+不代表 XD 线上目录已开放 low 或已完成真实模型质量/速度评测。
+
+主干已有 `SendOptions.toolsDisabled`,通过 host-owned 输入标记阻止本轮工具执行;
+它不是移除请求工具 schema 的优化,不能描述成“只给模型两个工具”或“无工具请求”。
+是否精简工具与 system prompt 需实际请求单变量对照;不借诊断改动删掉 Pi 原生能力。
+
图片能力未声明时,Pi 的模型配置与发送校验默认允许图片输入,不因新型号缺少能力资料而
提前拦截。目录、原生模型资料或用户配置明确声明 `supportsImageInput: false` / `input: ['text']`
时仍保持仅文本;此默认值不写回用户配置,也不代表上游接口保证支持图片。活动任务沿用启动时
@@ -443,7 +471,8 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见
才回收(Orca 工人另有 `workerIdleReleaseMinutes`,默认关闭),长时间使用进程与内存
持续累积(upstream #5830)。
- **实现**:`apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts`(30min TTL /
- 5min 扫描)。候选只取本机桌面来源、无 Orca 角色、非远程、未隐藏的 pi 会话
+ 5min 扫描)。候选只取本机桌面普通任务或插件任务、无 Orca 角色、非远程的 pi 会话;
+ 插件任务包含隐藏任务,其余隐藏任务仍排除
(归档也纳入——归档不会关运行时);释放前在发送锁内复查回合/后台任务/silent-stop
续跑/自动续跑/排队输入,并重读最新活动时间复核阈值;最后由
`Session.closeIfIdle()` 做同步的检查+关闭预约——它同时拒绝关闭宿主独占 RPC 操作
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 db312c4649..0ea822c3db 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
@@ -2113,6 +2113,56 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
}
}
+ // Integration: the real Pi request builder must preserve declared low and
+ // upstream remaps, while an unavailable low must follow the catalog default.
+ // The former offline SDK probe never exercised Cindy startup reconciliation.
+ it.each([
+ { efforts: ['low', 'medium', 'high', 'max'] as const, requested: 'low' as const, wire: 'low' },
+ { efforts: ['low', 'medium', 'high', 'max'] as const, requested: 'medium' as const, wire: 'high' },
+ { efforts: ['medium', 'high', 'max'] as const, requested: 'low' as const, wire: 'high' },
+ ])('sends catalog effort $requested as $wire and records the real payload boundary', { timeout: 30_000 }, async ({ efforts, requested, wire }) => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-effort-wire-'));
+ const deps = buildDeps();
+ const debug = vi.fn();
+ deps.logger = { ...noopLogger, debug };
+ const model = 'deepseek/deepseek-v4-flash';
+ deps.capabilityAdditions = { availableModels: [{
+ id: model, displayName: 'DeepSeek test route', contextWindow: 200_000,
+ efforts: [...efforts], defaultEffort: 'high',
+ }] };
+ deps.resolvePiGatewayModelApi = () => 'openai-completions';
+ deps.resolvePiGatewayModelSpec = () => ({
+ api: 'openai-completions',
+ compat: { thinkingFormat: 'deepseek', maxTokensField: 'max_tokens',
+ requiresReasoningContentOnAssistantMessages: true },
+ thinkingLevelMap: { low: 'low', medium: 'high', high: 'high', max: 'max' },
+ });
+ let handle: AgentSessionHandle | undefined;
+ try {
+ handle = await new PiAgent(deps).startSession({ sessionId: `effort-${requested}-${efforts.length}`,
+ workingDir, model, providerId: 'xd', effort: requested });
+ const before = seenRequests.length;
+ const done = (async () => {
+ for await (const event of handle!.events()) if (event.type === 'done') return;
+ })();
+ await handle.send({ type: 'user', content: 'private translation fixture' });
+ await done;
+ const requests = seenRequests.slice(before);
+ expect(requests).toHaveLength(1);
+ const body = JSON.parse(requests[0]!.body);
+ expect(body.reasoning_effort).toBe(wire);
+ 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(JSON.stringify(stages)).not.toContain('private translation fixture');
+ expect(JSON.stringify(stages)).not.toContain('test-key-123');
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ });
+
it.each(['ask', 'auto', 'bypassPermissions'] as const)(
'host text-only turn blocks tools in %s and restores the next ordinary turn',
{ timeout: 60_000 },
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 4cc9ae08e8..924d4911ba 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
@@ -3313,11 +3313,13 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
}
});
- it('correlates redacted MCP, spawn, RPC-ready, and first-model-request timings', async () => {
+ it('correlates redacted MCP, spawn, RPC-ready, and first-prompt-rpc timings', async () => {
const info = vi.fn();
+ const debug = vi.fn();
const timingLogger: Logger = {
...noopLogger,
info,
+ debug,
child: () => timingLogger,
};
const resolvePiManagedPackageResources = vi.fn<NonNullable<AgentDeps['resolvePiManagedPackageResources']>>(async () => ({
@@ -3345,7 +3347,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
'mcp-ready',
'pi-spawn',
'rpc-ready',
- 'first-model-request',
+ 'first-prompt-rpc',
]);
for (const event of events) {
expect(event).toMatchObject({
@@ -3359,6 +3361,34 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(serialized).not.toContain('timing-session-secret');
expect(serialized).not.toContain('timing-prompt-secret');
expect(serialized).not.toContain(cwd);
+ // The RPC receipt is not a model request. Only a native preparation hook
+ // may start request timings; test unknown metadata cannot leak into logs.
+ expect(debug.mock.calls.filter(([message]) => message === 'pi request stage')).toEqual([]);
+ const token = knobs.spawnedEnvs.at(-1)?.CINDY_PI_TURN_TOOL_POLICY;
+ const notify = (suffix: string) => knobs.onEvent?.({
+ type: 'extension_ui_request', method: 'notify',
+ message: `cindy:provider-request:${suffix}`,
+ });
+ 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' })}`);
+ const delta = { type: 'message_update', assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'private-output' } };
+ knobs.onEvent?.(delta);
+ knobs.onEvent?.(delta);
+ knobs.onEvent?.({ type: 'agent_end' });
+ let 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']);
+ 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[2]).toMatchObject({ requestSequence: 1, elapsedMs: expect.any(Number), turnElapsedMs: expect.any(Number) });
+ notify(`${token}:${JSON.stringify({ toolCount: -1, messageCount: 'secret', 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 });
+ expect(JSON.stringify(debug.mock.calls.filter(([message]) => message === 'pi request stage'))).not.toContain('private');
} finally {
await handle.close();
}
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 2330159113..9d773c8475 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -56,6 +56,21 @@ export const CINDY_BRIDGE_EXTENSION_FILENAME = "cindy-bridge.ts";
export const CINDY_PI_TEXT_ONLY_INPUT_PREFIX = '[CINDY_TEXT_ONLY_INPUT]:';
export const CINDY_PI_TEXT_ONLY_READY_PREFIX = 'cindy:text-only-ready:';
export const CINDY_PI_TEXT_ONLY_CLOSED_PREFIX = 'cindy:text-only-unavailable:';
+export const CINDY_PI_REQUEST_DIAGNOSTICS_PREFIX = 'cindy:provider-request:';
+
+/** Shared with the generated bridge: only bounded counts and known effort names may enter logs. */
+export function projectPiRequestDiagnostics(value: unknown): Record<string, number | string | null> {
+ const row = value && typeof value === 'object' ? value as Record<string, unknown> : {};
+ const result: Record<string, number | string | null> = {};
+ for (const key of ['toolCount', 'messageCount']) {
+ const count = row[key];
+ if (typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 && count <= 1_000_000) result[key] = count;
+ }
+ result.wireEffort = typeof row.wireEffort === 'string' &&
+ ['none', 'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(row.wireEffort)
+ ? row.wireEffort : null;
+ return result;
+}
/** Cindy-enforced bash bound when the model omits timeout or passes a non-positive number. */
export const CINDY_PI_BASH_DEFAULT_TIMEOUT_SECONDS = 300;
@@ -155,6 +170,7 @@ const PI_PACKAGE_MANAGEMENT_TITLE = 'cindy:pi-package';
const MAX_PI_PACKAGE_SOURCE_LENGTH = 2_048;
const projectPiPackageCommandDiagnostic = ${projectPiPackageCommandDiagnostic.toString()};
const projectPiManagedCommandFailure = ${projectPiManagedCommandFailure.toString()};
+const projectPiRequestDiagnostics = ${projectPiRequestDiagnostics.toString()};
// Pi 的模型鉴权、localhost proxy 与 MCP bearer 需要留在父进程 env 供 runtime
// 按请求解析,但绝不能继承进 LLM 可调用的 bash 子进程。名单由 host 按本次会话
@@ -4327,7 +4343,23 @@ export default async function cindyBridge(piApi: any) {
}
pi.on('before_provider_request', async (event, ctx) => {
const payload = astraResponsesPayload(event.payload, ctx.model) ?? event.payload;
- return learnedCachePayload((await nativeFastPayload(payload, ctx.model, ctx)) ?? payload, ctx.model);
+ 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
+ // preparation hook, not proof that HTTP was sent or accepted upstream.
+ const token = process.env.CINDY_PI_TURN_TOOL_POLICY;
+ if (token) {
+ try {
+ const messages = next?.messages ?? next?.input ?? next?.contents;
+ ctx.ui.notify(${JSON.stringify(CINDY_PI_REQUEST_DIAGNOSTICS_PREFIX)} + token + ':' + JSON.stringify(
+ projectPiRequestDiagnostics({
+ 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,
+ }),
+ ), 'info');
+ } catch { /* Diagnostics must never block a model request. */ }
+ }
+ return next;
});
const mcpGateway = new CindyMcpGateway();
// bash 隔离 home 经 resolveBashPackageHome 解析(首次加载读删 + 防篡改 stash,
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 876dc44537..63d7b00a75 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -102,6 +102,8 @@ import {
CINDY_PI_TEXT_ONLY_INPUT_PREFIX,
CINDY_PI_TEXT_ONLY_READY_PREFIX,
CINDY_PI_TEXT_ONLY_CLOSED_PREFIX,
+ CINDY_PI_REQUEST_DIAGNOSTICS_PREFIX,
+ projectPiRequestDiagnostics,
CINDY_BRIDGE_EXTENSION_SOURCE } from './cindy-bridge-source.js';
import { nativeProviderAdapterAliases } from './native-provider-adapter-source.js';
import { parsePiNativeRuntimeSettings, resolvePiNativeReserve, type PiNativeRuntimeSettings } from './native-runtime-settings.js';
@@ -608,7 +610,7 @@ interface ConfigHomeCleanupLogger {
debug(message: string, fields?: Record<string, unknown>): void;
}
-type PiStartupStage = 'mcp-ready' | 'pi-spawn' | 'rpc-ready' | 'first-model-request';
+type PiStartupStage = 'mcp-ready' | 'pi-spawn' | 'rpc-ready' | 'first-prompt-rpc';
function logPiStartupStage(
logger: AgentDeps['logger'],
@@ -3541,6 +3543,10 @@ export class PiAgent extends BaseAgent {
};
let activeToolsDisabled = false;
let textOnlyPolicyReady = false;
+ let providerRequestSequence = 0;
+ let providerRequestObservedAt: number | undefined;
+ let providerTurnObservedAt: number | undefined;
+ let providerFirstOutputLogged = false;
const textOnlyInput = (text: string): string => {
if (!activeToolsDisabled) return text;
if (!textOnlyPolicyReady) throw new Error('Pi text-only input policy is unavailable.');
@@ -5753,6 +5759,44 @@ export class PiAgent extends BaseAgent {
transport,
logger: this.deps.logger,
onEvent: (event: PiRpcEvent) => {
+ if (!remote && event.type === 'extension_ui_request' && event.method === 'notify' &&
+ typeof event.message === 'string' && event.message.startsWith(CINDY_PI_REQUEST_DIAGNOSTICS_PREFIX)) {
+ const prefix = `${CINDY_PI_REQUEST_DIAGNOSTICS_PREFIX}${runtimeInstanceId}:`;
+ if (event.message.startsWith(prefix) && event.message.length <= prefix.length + 1024) {
+ try {
+ const metadata = projectPiRequestDiagnostics(JSON.parse(event.message.slice(prefix.length)));
+ providerRequestObservedAt = performance.now();
+ providerTurnObservedAt ??= providerRequestObservedAt;
+ providerFirstOutputLogged = false;
+ providerRequestSequence++;
+ this.deps.logger.debug('pi request stage', {
+ startupTraceId, requestSequence: providerRequestSequence,
+ stage: 'provider-request-prepared', ...metadata,
+ });
+ } catch { /* Invalid diagnostic frames never enter logs or user UI. */ }
+ }
+ return;
+ }
+ if (providerRequestObservedAt !== undefined) {
+ const update = event.assistantMessageEvent as { type?: unknown } | undefined;
+ if (!providerFirstOutputLogged && event.type === 'message_update' &&
+ ['text_delta', 'thinking_delta', 'toolcall_delta'].includes(String(update?.type))) {
+ providerFirstOutputLogged = true;
+ this.deps.logger.debug('pi request stage', {
+ startupTraceId, requestSequence: providerRequestSequence, stage: 'first-output',
+ elapsedMs: Math.max(0, performance.now() - providerRequestObservedAt),
+ });
+ }
+ if (event.type === 'agent_settled') {
+ this.deps.logger.debug('pi request stage', {
+ startupTraceId, requestSequence: providerRequestSequence, stage: 'agent-settled',
+ elapsedMs: Math.max(0, performance.now() - providerRequestObservedAt),
+ turnElapsedMs: Math.max(0, performance.now() - providerTurnObservedAt!),
+ });
+ providerRequestObservedAt = undefined;
+ providerTurnObservedAt = undefined;
+ }
+ }
if (event.type === 'agent_start' && !ctx.pendingHostTurnStartToken) {
syncNativePlanMode?.();
}
@@ -6643,7 +6687,7 @@ export class PiAgent extends BaseAgent {
const deps = this.deps;
const agentKind = this.kind;
- let firstModelRequestLogged = false;
+ let firstPromptRpcLogged = false;
// 取消边界:main 的队列协调器在 Stop/close 抢占时会 abort 传入的 signal 并撤下
// steer 标记。send/steer 必须在**构建 prompt(读附件是 async)前后、投递 RPC 前**
@@ -7797,9 +7841,6 @@ export class PiAgent extends BaseAgent {
? await readPiUserEntryIds()
: null;
if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'send');
- const firstModelRequestStartedAt = firstModelRequestLogged ? undefined : Date.now();
- if (firstModelRequestStartedAt !== undefined) firstModelRequestLogged = true;
- let firstModelRequestStatus: 'ok' | 'degraded' = 'degraded';
try {
doctorCommandActivity.enter(isDoctorCommand);
const { resp, pendingTurnStartToken } = await runExclusivePiRpc(async () => {
@@ -7821,6 +7862,14 @@ export class PiAgent extends BaseAgent {
}
const pendingTurnStartToken = markPiHostTurnStartPending(ctx);
promptRequestStarted = true;
+ const firstPromptRpcStartedAt = firstPromptRpcLogged ? undefined : Date.now();
+ firstPromptRpcLogged = true;
+ const logPromptResponse = (success: boolean) => {
+ if (firstPromptRpcStartedAt !== undefined) logPiStartupStage(
+ deps.logger, startupTraceId, 'first-prompt-rpc', firstPromptRpcStartedAt,
+ success ? 'ok' : 'degraded',
+ );
+ };
const resp = await proc.request(command, {
timeoutMs: PI_PROMPT_ACCEPTANCE_TIMEOUT_MS,
// Prompt acceptance may legitimately span multiple compaction
@@ -7828,6 +7877,12 @@ export class PiAgent extends BaseAgent {
// preflight, so a healthy long compaction is not killed at 10m.
refreshTimeoutOnEvent: (event) =>
PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS.has(event.type),
+ }).then(response => {
+ logPromptResponse(response.success);
+ return response;
+ }, error => {
+ logPromptResponse(false);
+ throw error;
});
// Only consume the one-shot choice after acceptance. A confirmed
// rejection must preserve it for a retry without a message snapshot.
@@ -7839,7 +7894,6 @@ export class PiAgent extends BaseAgent {
}
return { resp, pendingTurnStartToken };
});
- firstModelRequestStatus = resp.success ? 'ok' : 'degraded';
if (!resp.success) {
rollbackPiHostTurnStart(ctx, pendingTurnStartToken);
if (managedPackageRoute.accepted) {
@@ -7965,15 +8019,6 @@ export class PiAgent extends BaseAgent {
}
}
} finally {
- if (firstModelRequestStartedAt !== undefined) {
- logPiStartupStage(
- deps.logger,
- startupTraceId,
- 'first-model-request',
- firstModelRequestStartedAt,
- firstModelRequestStatus,
- );
- }
if (activeExtensionCommandNotifications === capturedExtensionNotifications) {
activeExtensionCommandNotifications = null;
}