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,orca): 协同 token 卫生——提示词规则 + 压缩后一次性重申已披露工具 (#7110)

Yunjin Zhangf32002f8b0fd
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 0baa183a0b..d6d5d86944 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -61,7 +61,9 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
当前工具 schema 指纹记账:Pi 升级不再作废未变 schema 的披露,schema 真变动时门重新武装。
首次未披露的调用在**发起权限询问之前**被拦下——不弹权限框、不触达 MCP,回执指名该查的
server/tool 并说明重发即可放行(模型补完 `cindy_mcp_list_tools` 后重发即通过,重发那次
- 正常过一次权限)。Host 审批、策略与变更捕获仍使用真实
+ 正常过一次权限)。上下文压缩成功后,bridge 会在下一次运行开始前注入一条一次性的已披露
+ 工具清单提醒(display:false 常驻上下文,只列仍存在且指纹仍匹配的工具),避免模型因压缩
+ 失忆而重跑 `cindy_mcp_list_tools`;这是提示卫生,不改变门的任何判定。Host 审批、策略与变更捕获仍使用真实
`mcp__<server>__<tool>` identity 和真实参数,不能退化成对网关包装器授权。Claude Code 与
Codex 保持各自的直接 MCP 注册方式,不经过此 Pi 专属网关。配置新增、修改、禁用或删除对
下一新建/重启会话生效;旧活动会话保留启动时 generation 快照至 close。
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index fb6769879f..22a3495c91 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -1624,6 +1624,13 @@ describe('cindy-bridge extension source', () => {
);
expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("qualifiedName: 'mcp__' + serverName + '__' + toolName");
expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('private readonly disclosedSchemas');
+ // Post-compaction amnesia drives voluntary re-inspection: the persisted
+ // disclosure set is re-surfaced as a one-shot custom message on the first run
+ // after each successful compaction, never as a per-run system-prompt edit.
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("pi.on?.('session_compact'");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("pi.on?.('before_agent_start'");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("customType: 'cindy-mcp-disclosure-state'");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('disclosedKeysForPrompt');
// 披露按 schema 指纹持有 + 自愈放行(2026-10-13 pi 升级后整片失效、模型反复
// 撞墙后放弃的真机事故);权限/采集分类只认“解析成功”,不再按披露状态。
expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('private schemaFingerprint(');
@@ -2314,6 +2321,68 @@ describe('cindy-bridge extension source', () => {
);
});
+it('re-surfaces the disclosure set once after compaction instead of editing every run prompt', () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const compiled = ts.transpileModule(
+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))
+ + '\n(globalThis as any).Gateway = CindyMcpGateway;',
+ { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ const context: Record<string, any> = {
+ recordInput: (value: unknown) => value && typeof value === 'object' ? value : {},
+ mcpContentToPi: (content: unknown) => content,
+ createHash,
+ };
+ runInNewContext(compiled, context);
+ const handlers = new Map<string, (event: any) => any>();
+ const gateway = new context.Gateway();
+ gateway.register({ registerTool: () => {}, on: (event: string, cb: (event: any) => any) => handlers.set(event, cb) });
+ expect(handlers.has('session_compact')).toBe(true);
+ expect(handlers.has('before_agent_start')).toBe(true);
+
+ // No compaction yet: the run prompt stays untouched (zero per-run token cost).
+ expect(handlers.get('before_agent_start')!({ systemPrompt: 'base' })).toBeUndefined();
+
+ // A successful compaction arms exactly one reminder with the current keys.
+ const client = { request: async () => ({ content: [] }) };
+ const callTool = { name: 'call_tool', description: 'd', inputSchema: { type: 'object' } };
+ const sendWorker = { name: 'send_to_worker', description: 'd', inputSchema: { type: 'object' } };
+ gateway.add('cindy_memory', client, [callTool]);
+ gateway.add('cindy_orca', client, [sendWorker]);
+ gateway.disclosedSchemas.set('cindy_memory\u0000call_tool', gateway.schemaFingerprint(callTool));
+ gateway.disclosedSchemas.set('cindy_orca\u0000send_to_worker', gateway.schemaFingerprint(sendWorker));
+ handlers.get('session_compact')!({ reason: 'threshold' });
+ const note = handlers.get('before_agent_start')!({ systemPrompt: 'base' });
+ expect(note?.message?.customType).toBe('cindy-mcp-disclosure-state');
+ expect(note?.message?.display).toBe(false);
+ const text = note?.message?.content?.[0]?.text ?? '';
+ expect(text).toContain('cindy_memory/call_tool');
+ expect(text).toContain('cindy_orca/send_to_worker');
+ // 压缩可能模糊参数细节:提醒软化为「参数记得就直接调,模糊了按需重查」,
+ // 不再绝对化禁止重查(Greptile P2:否则模型只能猜参数或违背提醒)。
+ expect(text).toContain('Call them directly while you still remember their parameter shapes');
+ expect(text).toContain('re-inspect just the tools you need via cindy_mcp_list_tools instead of guessing');
+ // One-shot: the second run after the same compaction stays clean.
+ expect(handlers.get('before_agent_start')!({ systemPrompt: 'base' })).toBeUndefined();
+
+ // A removed tool or a drifted schema must not be advertised as safe to call:
+ // only keys whose tool still exists with a matching fingerprint are listed.
+ gateway.disclosedSchemas.set('cindy_ghosts\u0000gone_tool', gateway.schemaFingerprint(callTool));
+ gateway.disclosedSchemas.set('cindy_memory\u0000call_tool', 'stale-fingerprint');
+ handlers.get('session_compact')!({ reason: 'manual' });
+ const filtered = handlers.get('before_agent_start')!({ systemPrompt: 'base' });
+ const filteredText = filtered?.message?.content?.[0]?.text ?? '';
+ expect(filteredText).toContain('cindy_orca/send_to_worker');
+ expect(filteredText).not.toContain('gone_tool');
+ expect(filteredText).not.toContain('cindy_memory/call_tool');
+
+ // An empty disclosure set consumes the flag without emitting an empty note.
+ gateway.disclosedSchemas.clear();
+ handlers.get('session_compact')!({ reason: 'manual' });
+ expect(handlers.get('before_agent_start')!({ systemPrompt: 'base' })).toBeUndefined();
+ expect(handlers.get('before_agent_start')!({ systemPrompt: 'base' })).toBeUndefined();
+});
+
it('routes Bot shortcuts through the scoped helper entry without exposing them to ordinary Pi tasks', async () => {
const source = CINDY_BRIDGE_EXTENSION_SOURCE;
const compiled = ts.transpileModule(
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 2d10b42063..8254c6b0fa 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -2962,6 +2962,7 @@ class CindyMcpGateway {
private readonly disclosedSchemas = new Map<string, string>();
/** 本次调用跳过了权限询问(hook 未披露即放行):按 toolCallId 记账,execute 见此标记一律回路标。 */
private readonly permissionSkippedCalls = new Set<string>();
+ private disclosureNotePending = false;
private botMemoryFacadeEnabled = false;
private botHelperFacadeEnabled = false;
@@ -3235,6 +3236,26 @@ class CindyMcpGateway {
return this.disclosedSchemas.get(key) === this.schemaFingerprint(call.tool);
}
+ /**
+ * Sorted, prompt-ready server/tool names worth re-surfacing after compaction:
+ * only tools that still exist AND whose stored fingerprint still matches the
+ * live schema — a removed or schema-drifted tool must not be advertised as
+ * safe to call directly (the gate would re-close on it and waste a round-trip).
+ */
+ disclosedKeysForPrompt(limit = 48): string {
+ const all: string[] = [];
+ for (const [key, fingerprint] of this.disclosedSchemas) {
+ const tool = this.tools.get(key);
+ if (!tool || this.schemaFingerprint(tool) !== fingerprint) continue;
+ const sep = key.indexOf('\u0000');
+ all.push(sep === -1 ? key : key.slice(0, sep) + '/' + key.slice(sep + 1));
+ }
+ all.sort();
+ const shown = all.slice(0, limit);
+ if (all.length > limit) shown.push('… +' + (all.length - limit) + ' more');
+ return shown.join(', ');
+ }
+
/**
* 按当前 schema 记一次披露并落盘。披露判定按 schema 指纹而非 Pi 版本:Pi 升级不会
* 作废未变 schema 的披露;schema 真变动时指纹失配,门重新武装。
@@ -3498,6 +3519,32 @@ class CindyMcpGateway {
this.botHelperFacadeEnabled = options.botMemoryFacade === true;
this.botMemoryFacadeEnabled = options.botMemoryFacade === true
&& this.tools.has(mcpGatewayKey('cindy_memory', 'call_tool'));
+ // Token hygiene: post-compaction the model loses the memory of which MCP tools
+ // it already inspected and re-runs cindy_mcp_list_tools "to be safe". Inject a
+ // one-shot custom message into the first run after each successful compaction
+ // instead of editing the system prompt every run; the message then lives in
+ // context like any other turn until the next compaction summarizes it away.
+ this.disclosureNotePending = false;
+ pi.on?.('session_compact', () => { this.disclosureNotePending = true; });
+ pi.on?.('before_agent_start', () => {
+ if (!this.disclosureNotePending) return undefined;
+ this.disclosureNotePending = false;
+ const keys = this.disclosedKeysForPrompt();
+ if (!keys) return undefined;
+ return {
+ message: {
+ customType: 'cindy-mcp-disclosure-state',
+ content: [{
+ type: 'text',
+ text: 'MCP tools whose schemas you already inspected for this session (persisted across restarts): '
+ + keys + '. Call them directly while you still remember their parameter shapes. If compaction '
+ + 'blurred the details, re-inspect just the tools you need via cindy_mcp_list_tools instead of '
+ + 'guessing parameters. (One-shot reminder after context compaction.)',
+ }],
+ display: false,
+ },
+ };
+ });
if (this.botMemoryFacadeEnabled) {
pi.registerTool({
diff --git a/packages/orca-workflow/src/__tests__/orca-bridge-prompt.test.ts b/packages/orca-workflow/src/__tests__/orca-bridge-prompt.test.ts
index 1d1d29db96..4cf49324af 100644
--- a/packages/orca-workflow/src/__tests__/orca-bridge-prompt.test.ts
+++ b/packages/orca-workflow/src/__tests__/orca-bridge-prompt.test.ts
@@ -223,6 +223,21 @@ describe('renderOrcaWorkerSystemPrompt', () => {
expect(prompt).toContain(subagentHint);
});
+ it('teaches token hygiene to both lead and workers', () => {
+ // Orca worker 会话反复冷启、门禁类命令输出巨大:不复读已知 schema、
+ // 不重复发起仍然新鲜的调用、验证类命令只回摘要行,是协同模式 token 浪费的主要止血点。
+ // 措辞必须保留“结果已过期/改码后重验/失败重试”的豁免,否则会挡住合法的状态刷新。
+ const leadPrompt = renderOrcaLeadSystemPrompt(null);
+ expect(leadPrompt).toContain('10. Token hygiene: do not re-issue a tool call just to re-fetch a result you already have and that is still current');
+ expect(leadPrompt).toContain('Re-running a state read after something changed, re-running verification after new edits, and retrying a failed call are not repetition.');
+ expect(leadPrompt).toContain('require gate/verification commands (build/test/smoke/LSP/md5/git) to be answered with a one-line pass/fail summary naming the command, the outcome and the log file path');
+
+ const workerPrompt = renderOrcaWorkerSystemPrompt(workerMeta);
+ expect(workerPrompt).toContain('12. Token hygiene: do not re-issue a tool call just to re-fetch a result you already have and that is still current');
+ expect(workerPrompt).toContain('Re-running a state read after something changed, re-running verification (build/test/smoke/LSP) after new edits, and retrying a failed call are not repetition.');
+ expect(workerPrompt).toContain('report only a one-line pass/fail summary to the lead — command, outcome and the log file path');
+ });
+
it('keeps the Worker rule concise without the unreachable fallback', () => {
const prompt = renderOrcaWorkerSystemPrompt(workerMeta);
diff --git a/packages/orca-workflow/src/orca-bridge-prompt.ts b/packages/orca-workflow/src/orca-bridge-prompt.ts
index 3ace448b79..afbb170034 100644
--- a/packages/orca-workflow/src/orca-bridge-prompt.ts
+++ b/packages/orca-workflow/src/orca-bridge-prompt.ts
@@ -66,7 +66,7 @@ export function renderOrcaLeadSystemPrompt(initialWorker?: OrcaInitialWorkerRef
'Rules:',
'1. Discuss task breakdown with the user before dispatching.',
'2. Before any dispatch, call get_workspace_info. For a multi-role request, resolve every requested role or label before dispatching any task; if any target is missing or its creation approval is unresolved, dispatch nothing, report all missing targets, and ask first. Use send_to_worker only for an existing worker that already matches the requested worker/session/role/label — messages queue automatically, so a running worker can take a new task too. Use create_worker only when the user explicitly asks to open one new worker, and use create_workers only when the user explicitly asks to open multiple new workers. If no existing worker matches a requested role or label, say so and ask whether to create one; do not silently substitute another worker or a native subagent. If the user assigns a task to a generic Orca Worker but no worker exists, say so and ask whether to create one; the assignment itself is not authorization to create it.',
- '3. Dispatches must include Intent, Decisions, Boundaries, and Task; quote critical constraints and flag assumptions so workers can act independently.',
+ '3. Dispatches must include Intent, Decisions, Boundaries, and Task; quote critical constraints and flag assumptions so workers can act independently. In the Task, require gate/verification commands (build/test/smoke/LSP/md5/git) to be answered with a one-line pass/fail summary naming the command, the outcome and the log file path — full output goes to that file, not the conversation; on failure append the single most relevant error line.',
'4. If a worker explicitly asks you to reply via send_to_worker, do so. The worker cannot see your conversation output — send_to_worker is the only way to reach it.',
'Use interrupt_worker only when the active task must not continue and the new instruction must replace it; for additional context or later work, use send_to_worker.',
'If get_workspace_info shows queued_count > 0 or queue_paused=true, call get_worker_queue_status first, then revise or withdraw one pending message, merge related messages, or send a separate task.',
@@ -76,6 +76,7 @@ export function renderOrcaLeadSystemPrompt(initialWorker?: OrcaInitialWorkerRef
'7. If you see "[Auto-bridged: ...]" in a worker message, the system forwarded its result automatically. Treat it the same as a normal worker report; this does not imply a missed tool call.',
'8. Before saying that all tasks are complete, verify every task from the terminal state reported by the same execution channel that ran it. A native subagent result is not evidence that an Orca Worker ran or completed.',
'9. In the final summary, label every delegated task with its actual execution channel: Orca Worker or native subagent.',
+ '10. Token hygiene: do not re-issue a tool call just to re-fetch a result you already have and that is still current — reuse that result instead. Re-running a state read after something changed, re-running verification after new edits, and retrying a failed call are not repetition. For verification commands (build/test/smoke/LSP/md5/git) you run yourself, keep full output in a file and surface only a one-line pass/fail summary that names the command, the outcome and the log file path; on failure append the single most relevant error line.',
];
if (initialWorker) {
@@ -112,6 +113,7 @@ export function renderOrcaWorkerSystemPrompt(meta: OrcaWorkerPromptMeta): string
'9. When first created, wait for the lead to assign a task. Do not proactively message the lead.',
'10. If the user asks for a "subagent" / "子代理", use your own native subagent mechanism (for example Codex spawn_agent, or the Claude Code Agent/Task tool) to handle it yourself — do NOT escalate to the lead for it, and do NOT call start_team / create_worker (you cannot create Orca workers). An Orca Worker is never a substitute for a subagent.',
'11. An [Orca UI Assignment] may include a Lead session id and snapshot_before_ms because the Lead did not compose the assignment. If the task depends on current work, continuing work, this PR, or other relative context, use read_lead_history to inspect the owning Lead transcript before acting; pass snapshot_before_ms as from_ms when present. This read is scoped to your Lead and does not wake it. If the task is self-contained, proceed without reading history.',
+ '12. Token hygiene: do not re-issue a tool call just to re-fetch a result you already have and that is still current — reuse that result instead. Re-running a state read after something changed, re-running verification (build/test/smoke/LSP) after new edits, and retrying a failed call are not repetition. For gate/verification commands, keep full output in a file and report only a one-line pass/fail summary to the lead — command, outcome and the log file path; on failure append the single most relevant error line.',
];
return lines.join('\n');