Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): rewrite context-mode doctor path to Cindy managed package (#3085)
Chris Zhangb4b324e9605f
diff --git a/packages/maker-core/src/agents/pi/__tests__/context-mode-doctor-path.test.ts b/packages/maker-core/src/agents/pi/__tests__/context-mode-doctor-path.test.tsnew file mode 100644index 0000000000..e7de346d0b--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/context-mode-doctor-path.test.ts@@ -0,0 +1,148 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import {+ CONTEXT_MODE_STALE_EXTENSION_PATH,+ findContextModePackageRoot,+ isContextModeDoctorNotifyMessage,+ isContextModeDoctorUiEvent,+ rewriteContextModeDoctorPath,+ shouldRewriteContextModeDoctorNotification,+ DoctorCommandActivity,+} from '../context-mode-doctor-path.js';++const DOCTOR = [+ 'context-mode doctor',+ '',+ `[OK] Hook support: Pi hooks are wired via the context-mode Pi extension (${CONTEXT_MODE_STALE_EXTENSION_PATH}/), not via JSON-stdio.`,+].join('\n');++describe('rewriteContextModeDoctorPath', () => {+ it('replaces the stale extension path with the managed package root', () => {+ const root = '/tmp/cindy/managed-packages/0/node_modules/context-mode';+ expect(rewriteContextModeDoctorPath(DOCTOR, root)).toBe(+ [+ 'context-mode doctor',+ '',+ `[OK] Hook support: Pi hooks are wired via the context-mode Pi extension (${root}/), not via JSON-stdio.`,+ ].join('\n'),+ );+ });++ it('leaves text unchanged when context-mode is not loaded', () => {+ expect(rewriteContextModeDoctorPath(DOCTOR, undefined)).toBe(DOCTOR);+ expect(rewriteContextModeDoctorPath(DOCTOR, '')).toBe(DOCTOR);+ });++ it('does not rewrite unrelated ~/.pi mentions', () => {+ const other = 'sessions live under ~/.pi/context-mode/sessions';+ expect(rewriteContextModeDoctorPath(other, '/tmp/context-mode')).toBe(other);+ });++ it('inserts dollar sequences in the managed root as literals', () => {+ const root = '/tmp/cindy/$&/$1/user-dir/node_modules/context-mode';+ const rewritten = rewriteContextModeDoctorPath(DOCTOR, root);+ expect(rewritten).toContain(`(${root}/)`);+ expect(rewritten).not.toContain(CONTEXT_MODE_STALE_EXTENSION_PATH);+ });+});++describe('isContextModeDoctorUiEvent', () => {+ it('matches command or tool identity on the event itself', () => {+ expect(isContextModeDoctorUiEvent({ commandName: 'ctx-doctor' })).toBe(true);+ expect(isContextModeDoctorUiEvent({ command: '/ctx-doctor' })).toBe(true);+ expect(isContextModeDoctorUiEvent({ toolName: 'ctx_doctor' })).toBe(true);+ expect(isContextModeDoctorUiEvent({ name: 'ctx-doctor' })).toBe(true);+ });++ it('rejects unidentified notify events even if the message mentions the stale path', () => {+ expect(isContextModeDoctorUiEvent({+ method: 'notify',+ message: `[OK] Hook support: (${CONTEXT_MODE_STALE_EXTENSION_PATH}/)`,+ })).toBe(false);+ expect(isContextModeDoctorUiEvent({ source: 'extension' })).toBe(false);+ expect(isContextModeDoctorUiEvent(undefined)).toBe(false);+ });+});++describe('shouldRewriteContextModeDoctorNotification', () => {+ const doctorBody = [+ 'context-mode doctor',+ '',+ `[OK] Hook support: Pi hooks are wired via the context-mode Pi extension (${CONTEXT_MODE_STALE_EXTENSION_PATH}/), not via JSON-stdio.`,+ ].join('\n');+ const realNotify = { id: 'uuid-5', method: 'notify', message: doctorBody, notifyType: 'info' };+ const otherNotify = {+ id: 'uuid-6',+ method: 'notify',+ message: `other-ext: (${CONTEXT_MODE_STALE_EXTENSION_PATH}/)`,+ notifyType: 'warning',+ };++ it('rewrites a real notify payload while /ctx-doctor is active', () => {+ expect(shouldRewriteContextModeDoctorNotification(doctorBody, realNotify, true)).toBe(true);+ expect(isContextModeDoctorNotifyMessage(doctorBody)).toBe(true);+ });++ it('does not rewrite concurrent ordinary notify payloads', () => {+ expect(shouldRewriteContextModeDoctorNotification(otherNotify.message, otherNotify, true)).toBe(false);+ expect(shouldRewriteContextModeDoctorNotification(doctorBody, realNotify, false)).toBe(false);+ });+});++describe('DoctorCommandActivity', () => {+ it('stays active when a non-doctor command overlaps a doctor command', () => {+ const activity = new DoctorCommandActivity();+ activity.enter(true);+ activity.enter(false);+ expect(activity.active).toBe(true);+ expect(shouldRewriteContextModeDoctorNotification(+ 'context-mode doctor\nHook support: Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/)',+ { id: 'n1', method: 'notify' },+ activity.active,+ )).toBe(true);+ activity.leave(false);+ expect(activity.active).toBe(true);+ activity.leave(true);+ expect(activity.active).toBe(false);+ });++ it('keeps nested doctor commands active until the last leave', () => {+ const activity = new DoctorCommandActivity();+ activity.enter(true);+ activity.enter(true);+ activity.leave(true);+ expect(activity.active).toBe(true);+ activity.leave(true);+ expect(activity.active).toBe(false);+ });+});++describe('findContextModePackageRoot', () => {+ it('finds a direct package root and a node_modules snapshot', () => {+ const tmp = path.join(os.tmpdir(), `cm-doctor-${process.pid}-${Date.now()}`);+ const direct = path.join(tmp, 'direct');+ const snapshot = path.join(tmp, 'snapshot');+ const nested = path.join(snapshot, 'node_modules', 'context-mode');+ mkdirSync(direct, { recursive: true });+ mkdirSync(nested, { recursive: true });+ writeFileSync(path.join(direct, 'package.json'), JSON.stringify({ name: 'context-mode' }));+ writeFileSync(path.join(nested, 'package.json'), JSON.stringify({ name: 'context-mode' }));+ writeFileSync(+ path.join(snapshot, 'package.json'),+ JSON.stringify({ name: 'pi-extensions', private: true }),+ );++ expect(findContextModePackageRoot([direct])).toBe(direct);+ expect(findContextModePackageRoot([snapshot])).toBe(nested);+ expect(findContextModePackageRoot(['/no/such/root', snapshot])).toBe(nested);+ });++ it('returns undefined when no context-mode package is present', () => {+ expect(findContextModePackageRoot([])).toBeUndefined();+ expect(findContextModePackageRoot(['/definitely/missing'])).toBeUndefined();+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 8da8a7879d..4fced77013 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -780,6 +780,140 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {}});+ it('rewrites context-mode doctor notify paths to the managed package root', async () => {+ const packageRoot = path.join(agentHome, 'managed-context-mode');+ const extensionPath = path.join(packageRoot, 'extension.js');+ mkdirSync(packageRoot, { recursive: true });+ writeFileSync(extensionPath, '// extension');+ writeFileSync(path.join(packageRoot, 'package.json'), JSON.stringify({ name: 'context-mode' }));+ captured.commandCatalog = [+ {+ name: 'ctx-doctor',+ description: 'Run context-mode diagnostics',+ source: 'extension',+ sourceInfo: { path: extensionPath, source: 'extension' },+ },+ ];+ captured.onPrompt = (command) => {+ if (command.message !== '/ctx-doctor') return;+ captured.onEvent!({+ type: 'extension_ui_request',+ id: 'other-ext-notify',+ method: 'notify',+ notifyType: 'warning',+ message: 'other-ext: (~/.pi/extensions/context-mode/), not via JSON-stdio.',+ });+ captured.onEvent!({+ type: 'extension_ui_request',+ id: 'ctx-doctor-notify',+ method: 'notify',+ notifyType: 'info',+ message: [+ 'context-mode doctor',+ '',+ '[OK] Hook support: Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio.',+ ].join('\n'),+ });+ };+ const deps = buildDeps();+ deps.resolvePiManagedPackageResources = async () => ({+ extensions: [extensionPath],+ skills: [],+ promptTemplates: [],+ packageRoots: [packageRoot],+ });+ const handle = await new PiAgent(deps).startSession({+ sessionId: 'managed-doctor-path-session',+ workingDir: cwd,+ model: 'm',+ });+ const events: Array<Record<string, unknown>> = [];+ void (async () => {+ for await (const event of handle.events()) {+ events.push(event as unknown as Record<string, unknown>);+ }+ })();+ try {+ const deadline = Date.now() + 2_000;+ while (handle.getRuntimeCapabilities?.()?.status !== 'loaded') {+ if (Date.now() > deadline) throw new Error('managed command catalog did not load');+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ await handle.send({ type: 'user', content: '/ctx-doctor' });+ await new Promise((resolve) => setImmediate(resolve));+ await flush();+ const texts = events+ .filter((event) => event.type === 'text')+ .map((event) => (event.data as { text?: string }).text ?? '');+ expect(texts.some((text) => text.includes('other-ext') && text.includes('~/.pi/extensions/context-mode'))).toBe(true);+ expect(texts.some((text) => text.includes('Hook support') && text.includes(packageRoot))).toBe(true);+ expect(texts.some((text) => text.includes('Hook support') && text.includes('~/.pi/extensions/context-mode'))).toBe(false);+ } finally {+ await handle.close();+ }+ });++ it('leaves non-doctor extension notify text containing the stale path unchanged', async () => {+ const packageRoot = path.join(agentHome, 'managed-context-mode');+ const extensionPath = path.join(packageRoot, 'extension.js');+ mkdirSync(packageRoot, { recursive: true });+ writeFileSync(extensionPath, '// extension');+ writeFileSync(path.join(packageRoot, 'package.json'), JSON.stringify({ name: 'context-mode' }));+ captured.commandCatalog = [+ {+ name: 'ctx-stats',+ description: 'Show context-mode stats',+ source: 'extension',+ sourceInfo: { path: extensionPath, source: 'extension' },+ },+ ];+ const stale = '[OK] Hook support: (~/.pi/extensions/context-mode/), not via JSON-stdio.';+ captured.onPrompt = (command) => {+ if (command.message !== '/ctx-stats') return;+ captured.onEvent!({+ type: 'extension_ui_request',+ id: 'ctx-stats-notify',+ method: 'notify',+ message: stale,+ });+ };+ const deps = buildDeps();+ deps.resolvePiManagedPackageResources = async () => ({+ extensions: [extensionPath],+ skills: [],+ promptTemplates: [],+ packageRoots: [packageRoot],+ });+ const handle = await new PiAgent(deps).startSession({+ sessionId: 'managed-stats-path-unchanged-session',+ workingDir: cwd,+ model: 'm',+ });+ const events: Array<Record<string, unknown>> = [];+ void (async () => {+ for await (const event of handle.events()) {+ events.push(event as unknown as Record<string, unknown>);+ }+ })();+ try {+ const deadline = Date.now() + 2_000;+ while (handle.getRuntimeCapabilities?.()?.status !== 'loaded') {+ if (Date.now() > deadline) throw new Error('managed command catalog did not load');+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ await handle.send({ type: 'user', content: '/ctx-stats' });+ await new Promise((resolve) => setImmediate(resolve));+ await flush();+ const texts = events+ .filter((event) => event.type === 'text')+ .map((event) => (event.data as { text?: string }).text ?? '');+ expect(texts).toContain(stale);+ expect(texts.some((text) => text.includes(packageRoot) && text.includes('Hook support'))).toBe(false);+ } finally {+ await handle.close();+ }+ });+it('keeps an accepted extension command alive when the idle-state probe fails', async () => {const packageRoot = path.join(agentHome, 'managed-context-mode-probe-failure');const extensionPath = path.join(packageRoot, 'extension.js');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex 0fba48762c..641b4b6840 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -5,6 +5,7 @@import { describe, expect, it, vi } from 'vitest';+import { rewriteContextModeDoctorPath } from '../context-mode-doctor-path.js';import {createPiTranslateContext,disposePiTranslateContext,@@ -570,6 +571,60 @@ describe('pi translator', () => {expect(JSON.parse((full!.data as { fullText: string }).fullText).content).toBe(content);});+ it('rewrites context-mode doctor tool results to the Cindy-managed package path', () => {+ const root = '/tmp/cindy/managed-packages/0/node_modules/context-mode';+ const ctx = createPiTranslateContext(noopLogger);+ ctx.rewriteToolResultText = (text) => rewriteContextModeDoctorPath(text, root);+ const { queue, events } = makeQueue();+ translatePiEvent(+ ev({+ type: 'tool_execution_end',+ toolCallId: 'doctor-1',+ toolName: 'ctx_doctor',+ result: {+ content: [+ {+ type: 'text',+ text: '[OK] Hook support: (~/.pi/extensions/context-mode/), not via JSON-stdio.',+ },+ ],+ },+ }),+ queue,+ ctx,+ );+ const full = events.find((event) => event.type === 'tool_result_full');+ expect(full).toMatchObject({+ data: {+ fullText: `[OK] Hook support: (${root}/), not via JSON-stdio.`,+ },+ });+ });++ it('leaves non-doctor tool results containing the stale path unchanged', () => {+ const root = '/tmp/cindy/managed-packages/0/node_modules/context-mode';+ const stale = '[OK] Hook support: (~/.pi/extensions/context-mode/), not via JSON-stdio.';+ const ctx = createPiTranslateContext(noopLogger);+ ctx.rewriteToolResultText = (text) => rewriteContextModeDoctorPath(text, root);+ const { queue, events } = makeQueue();+ translatePiEvent(+ ev({ type: 'tool_execution_start', toolCallId: 'read-1', toolName: 'read', args: {} }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({+ type: 'tool_execution_end',+ toolCallId: 'read-1',+ result: { content: [{ type: 'text', text: stale }] },+ }),+ queue,+ ctx,+ );+ const full = events.find((event) => event.type === 'tool_result_full');+ expect(full).toMatchObject({ data: { fullText: stale } });+ });+it('maps compaction_end (threshold) → compact_boundary with token deltas + updates contextTokens', () => {const ctx = createPiTranslateContext(noopLogger);const { queue, events } = makeQueue();diff --git a/packages/maker-core/src/agents/pi/context-mode-doctor-path.ts b/packages/maker-core/src/agents/pi/context-mode-doctor-path.tsnew file mode 100644index 0000000000..10cc3505cb--- /dev/null+++ b/packages/maker-core/src/agents/pi/context-mode-doctor-path.ts@@ -0,0 +1,111 @@+/**+ * context-mode's Pi doctor still claims hooks live at+ * ~/.pi/extensions/context-mode/. Cindy never installs there — packages are+ * snapshotted into the session managed-packages tree and passed as explicit+ * --extension/--skill args. Rewrite that stale path in user-visible doctor+ * output so Cindy users are not sent looking at a directory that does not exist.+ */+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';++export const CONTEXT_MODE_STALE_EXTENSION_PATH = '~/.pi/extensions/context-mode';+export const CONTEXT_MODE_DOCTOR_TOOL_NAME = 'ctx_doctor';+export const CONTEXT_MODE_DOCTOR_COMMAND_NAME = 'ctx-doctor';++export function isContextModeDoctorToolName(toolName: string): boolean {+ return toolName === CONTEXT_MODE_DOCTOR_TOOL_NAME;+}++export function isContextModeDoctorCommandName(commandName: string | null | undefined): boolean {+ return commandName === CONTEXT_MODE_DOCTOR_COMMAND_NAME;+}++const DOCTOR_UI_EVENT_KEYS = ['command', 'commandName', 'name', 'toolName'] as const;++/** True when a Pi extension UI event itself identifies ctx_doctor / ctx-doctor. */+export function isContextModeDoctorUiEvent(event: Record<string, unknown> | undefined): boolean {+ if (!event) return false;+ for (const key of DOCTOR_UI_EVENT_KEYS) {+ const value = event[key];+ if (typeof value !== 'string') continue;+ const name = value.trim().replace(/^\//, '');+ if (isContextModeDoctorCommandName(name) || isContextModeDoctorToolName(name)) return true;+ }+ return false;+}++/** Real /ctx-doctor notify text from context-mode, not a generic stale-path mention. */+export function isContextModeDoctorNotifyMessage(message: string): boolean {+ if (!message.includes(CONTEXT_MODE_STALE_EXTENSION_PATH)) return false;+ return /(?:^|\n)## ctx-doctor\b/.test(message)+ || /(?:^|\n)context-mode doctor\b/.test(message)+ || /Hook support:\s+Pi hooks are wired via the context-mode Pi extension/.test(message);+}++/** Rewrite doctor notify when the event is identified, or when /ctx-doctor is active and the body is doctor output. */+export function shouldRewriteContextModeDoctorNotification(+ message: string,+ event: Record<string, unknown> | undefined,+ doctorCommandActive: boolean,+): boolean {+ if (isContextModeDoctorUiEvent(event)) return true;+ return doctorCommandActive && isContextModeDoctorNotifyMessage(message);+}++/** Refcount of in-flight /ctx-doctor commands so overlapping send/steer cannot clobber a boolean. */+export class DoctorCommandActivity {+ #count = 0;++ get active(): boolean {+ return this.#count > 0;+ }++ enter(isDoctor: boolean): void {+ if (isDoctor) this.#count += 1;+ }++ leave(isDoctor: boolean): void {+ if (isDoctor && this.#count > 0) this.#count -= 1;+ }+}++function isContextModePackageRoot(dir: string): boolean {+ try {+ const raw = readFileSync(path.join(dir, 'package.json'), 'utf8');+ const parsed: unknown = JSON.parse(raw);+ return typeof parsed === 'object'+ && parsed !== null+ && 'name' in parsed+ && (parsed as { name?: unknown }).name === 'context-mode';+ } catch {+ return false;+ }+}++/** Resolve the context-mode package directory from Cindy-owned package roots. */+export function findContextModePackageRoot(packageRoots: readonly string[]): string | undefined {+ for (const root of packageRoots) {+ if (!root) continue;+ if (isContextModePackageRoot(root)) return root;+ const nested = path.join(root, 'node_modules', 'context-mode');+ if (existsSync(nested) && isContextModePackageRoot(nested)) return nested;+ }+ return undefined;+}++/**+ * Replace context-mode's hardcoded ~/.pi/extensions/context-mode path with the+ * Cindy-managed package root. No-op when the stale path is absent or Cindy+ * did not load context-mode — never invent a path.+ */+export function rewriteContextModeDoctorPath(+ text: string,+ actualRoot: string | undefined,+): string {+ if (!actualRoot || !text.includes(CONTEXT_MODE_STALE_EXTENSION_PATH)) return text;+ const replacement = actualRoot.replace(/[/\\]+$/, '');+ // Function replacement keeps dollar sequences in custom data dirs literal.+ return text+ .replaceAll(`${CONTEXT_MODE_STALE_EXTENSION_PATH}/`, () => `${replacement}/`)+ .replaceAll(CONTEXT_MODE_STALE_EXTENSION_PATH, () => replacement);+}diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 017c46b98c..4877c4c145 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -113,6 +113,13 @@ import type { AgentKind, Effort, UserMessage, UserContentBlock } from '../../typimport type { ListAgentSkillsOptions, ListAgentSkillsResult } from '../../types/palette.js';import type { ListCustomizationsOptions, ListCustomizationsResult } from '../../types/customizations.js';import { scanPiCustomizations } from './customization-scanner.js';+import {+ DoctorCommandActivity,+ findContextModePackageRoot,+ isContextModeDoctorCommandName,+ rewriteContextModeDoctorPath,+ shouldRewriteContextModeDoctorNotification,+} from './context-mode-doctor-path.js';import { AutoCompactController } from '../shared/auto-compact-controller.js';import { createAsyncQueue, type AsyncQueue } from '../shared/async-queue.js';import { formatManagedImageReferences } from '../shared/managed-image-reference.js';@@ -413,11 +420,17 @@ function isExecutablePiSlashCommand(text: string, manifest: PiRuntimeCapabilityMreturn manifest?.status === 'loaded' && manifest.managedPackageCommandNames?.includes(match[1]) === true;}-function isManagedPiExtensionSlashCommand(text: string, manifest: PiRuntimeCapabilityManifest | undefined): boolean {+function managedExtensionSlashCommandName(+ text: string,+ manifest: PiRuntimeCapabilityManifest | undefined,+): string | undefined {const match = text.trimStart().match(/^\/([^\s]+)(?:\s|$)/);- if (!match?.[1] || manifest?.status !== 'loaded') return false;- if (manifest.managedPackageCommandNames?.includes(match[1]) !== true) return false;- return manifest.commands.some((command) => command.name === match[1] && command.source === 'extension');+ if (!match?.[1] || manifest?.status !== 'loaded') return undefined;+ if (manifest.managedPackageCommandNames?.includes(match[1]) !== true) return undefined;+ if (!manifest.commands.some((command) => command.name === match[1] && command.source === 'extension')) {+ return undefined;+ }+ return match[1];}function escapeLeadingSlashCommand(text: string, manifest: PiRuntimeCapabilityManifest | undefined): string {@@ -2162,6 +2175,8 @@ export class PiAgent extends BaseAgent {const queue: AsyncQueue<AgentEvent> = createAsyncQueue<AgentEvent>();const ctx: PiTranslateContext = createPiTranslateContext(this.deps.logger);+ const contextModeRoot = findContextModePackageRoot(managedPackageResources.packageRoots);+ ctx.rewriteToolResultText = (text) => rewriteContextModeDoctorPath(text, contextModeRoot);let interactionResolver: InteractionResolver | null = null;// Host 每轮权限策略(个人微信 / Telegram 群)。刻意保留在 send 之外的闭包里:// pi 的内部续跑(plan 审批后的实施轮、自动继续)不再经 handle.send,却必须继续@@ -2351,6 +2366,7 @@ export class PiAgent extends BaseAgent {let runtimeCapabilityGeneration = 0;let piAgentLifecycleSequence = 0;let activeExtensionCommandNotifications: string[] | null = null;+ const doctorCommandActivity = new DoctorCommandActivity();const unsupportedExtensionUiMethods = new Set<string>();const runtimeCapabilityListeners = new Set<(manifest: PiRuntimeCapabilityManifest | undefined) => void>();const notifyRuntimeCapabilityListener = (@@ -2549,13 +2565,20 @@ export class PiAgent extends BaseAgent {remote: Boolean(opts.remoteHostId),allowPiPackageManagement,piPackageManagementToken,- emitExtensionNotification: (message) => {+ emitExtensionNotification: (message, event) => {+ const text = shouldRewriteContextModeDoctorNotification(+ message,+ event,+ doctorCommandActivity.active,+ )+ ? rewriteContextModeDoctorPath(message, contextModeRoot)+ : message;if (activeExtensionCommandNotifications) {- activeExtensionCommandNotifications.push(message);+ activeExtensionCommandNotifications.push(text);}queue.push({type: 'text',- data: { text: message, isFinal: false },+ data: { text, isFinal: false },source: 'pi',});},@@ -3596,9 +3619,14 @@ export class PiAgent extends BaseAgent {// setExtraDirs 是热更新;Pi 没有独立的 mid-session system-prompt RPC,所以在// 后续 user turn 前附上短引用目录段(但 /skill: 起始时不前置,见 composePiPromptText)。const promptText = composePiPromptText(text, piExtraDirsPrompt(mutableExtraDirs), runtimeCapabilityManifest);- const managedExtensionCommand = isManagedPiExtensionSlashCommand(promptText, runtimeCapabilityManifest);+ const managedExtensionCommandName = managedExtensionSlashCommandName(+ promptText,+ runtimeCapabilityManifest,+ );+ const managedExtensionCommand = managedExtensionCommandName !== undefined;const lifecycleSequenceBeforePrompt = piAgentLifecycleSequence;const capturedExtensionNotifications: string[] | null = managedExtensionCommand ? [] : null;+ const isDoctorCommand = isContextModeDoctorCommandName(managedExtensionCommandName);if (capturedExtensionNotifications) {activeExtensionCommandNotifications = capturedExtensionNotifications;}@@ -3615,6 +3643,7 @@ export class PiAgent extends BaseAgent {if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'send');promptRequestStarted = true;try {+ doctorCommandActivity.enter(isDoctorCommand);const resp = await runExclusivePiRpc(() => proc.request(command, {timeoutMs: PI_PROMPT_ACCEPTANCE_TIMEOUT_MS,// Prompt acceptance may legitimately span multiple compaction@@ -3749,6 +3778,7 @@ export class PiAgent extends BaseAgent {if (activeExtensionCommandNotifications === capturedExtensionNotifications) {activeExtensionCommandNotifications = null;}+ doctorCommandActivity.leave(isDoctorCommand);}} catch (err) {// 只在 Provider 尚未接受本轮时回滚。接受后的 transcript 回调失败不代表@@ -3795,7 +3825,11 @@ export class PiAgent extends BaseAgent {if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'steer');// /skill: 起始时不前置 Extra Dir 引用段(否则命令退化成文本),与 send 同口径。const promptText = composePiPromptText(text, piExtraDirsPrompt(mutableExtraDirs), runtimeCapabilityManifest);- const managedExtensionCommand = isManagedPiExtensionSlashCommand(promptText, runtimeCapabilityManifest);+ const managedExtensionCommandName = managedExtensionSlashCommandName(+ promptText,+ runtimeCapabilityManifest,+ );+ const managedExtensionCommand = managedExtensionCommandName !== undefined;const command: Record<string, unknown> = {// Pi rejects extension commands on the steer RPC. Its prompt RPC// explicitly executes extension commands immediately while another@@ -3804,7 +3838,14 @@ export class PiAgent extends BaseAgent {message: escapeLeadingSlashCommand(promptText, runtimeCapabilityManifest),};if (images.length > 0) command.images = images;- const resp = await runExclusivePiRpc(() => proc.request(command));+ const isDoctorCommand = isContextModeDoctorCommandName(managedExtensionCommandName);+ doctorCommandActivity.enter(isDoctorCommand);+ let resp: Awaited<ReturnType<typeof proc.request>>;+ try {+ resp = await runExclusivePiRpc(() => proc.request(command));+ } finally {+ doctorCommandActivity.leave(isDoctorCommand);+ }if (!resp.success) {if (managedPackageRoute.accepted) {// The host-owned mutation already completed and its deterministic@@ -4508,7 +4549,7 @@ export class PiAgent extends BaseAgent {remote: boolean;allowPiPackageManagement: boolean;piPackageManagementToken?: string;- emitExtensionNotification: (message: string) => void;+ emitExtensionNotification: (message: string, event?: PiRpcEvent) => void;notifyUnsupportedExtensionUi: (method: string, reason: 'unsupported-ui' | 'timed-dialog') => void;/*** 把一张挂起的权限卡登记进会话级表,返回注销函数。档位切换 / 关闭会话时由@@ -4540,7 +4581,10 @@ export class PiAgent extends BaseAgent {// Pi RPC has no toast surface. Preserve the extension's only visible// output as transcript text instead of silently dropping it (for example// context-mode's /ctx-stats and /ctx-doctor commands).- getPermissionCtx().emitExtensionNotification(message.slice(0, MAX_PI_EXTENSION_NOTIFICATION_LENGTH));+ getPermissionCtx().emitExtensionNotification(+ message.slice(0, MAX_PI_EXTENSION_NOTIFICATION_LENGTH),+ event,+ );return;}diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex c84c1afa36..19b4140797 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -42,6 +42,7 @@ import {UPSTREAM_STREAM_INTERRUPTED_REASON,isStreamInterruptedErrorMessage,} from '../shared/stream-interrupt-error.js';+import { isContextModeDoctorToolName } from './context-mode-doctor-path.js';import type { PiRpcEvent } from './rpc-client.js';import { parsePiSubagentProgress, type PiSubagentUsage } from './subagent-progress.js';@@ -143,6 +144,10 @@ export interface PiTranslateContext {subagentToolCalls: Map<string, AgentTaskUpdateEventData>;/** Host 百分比闸发起的 compact RPC 在途;Pi 仍会报 reason=manual。 */hostAutoCompactInFlight: boolean;+ /** Optional rewrite for ctx_doctor tool result text (Cindy-managed package paths). */+ rewriteToolResultText?: (text: string) => string;+ /** toolCallId → toolName for the in-flight Pi tool, so end events can gate rewrites. */+ toolNamesByCallId: Map<string, string>;/*** compaction_start 锁存的 turnScope。end/boundary 必须复用,不能按结束时的* isStreaming 重判——idle compact 期间用户开了新 turn 时,重判会把后台边界@@ -176,6 +181,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {generationHeartbeatReliable: true,delegatedUsage: new Map(),subagentToolCalls: new Map(),+ toolNamesByCallId: new Map(),pendingAssistantError: null,hostAutoCompactInFlight: false,compactTurnScope: null,@@ -199,6 +205,7 @@ export function disposePiTranslateContext(ctx: PiTranslateContext): void {ctx.pendingAssistantError = null;ctx.compactTurnScope = null;ctx.subagentToolCalls.clear();+ ctx.toolNamesByCallId.clear();}function samplePiGenerationHeartbeat(ctx: PiTranslateContext, now = Date.now()): void {@@ -447,6 +454,7 @@ export function translatePiEvent(// 也避免长会话里 taskId 条目无界堆积。ctx.delegatedUsage.clear();ctx.subagentToolCalls.clear();+ ctx.toolNamesByCallId.clear();ctx.streamStopTokenByIndex.clear();pushStatus(queue, ctx, 'Working…', true);return;@@ -528,6 +536,7 @@ export function translatePiEvent(const toolUseId = String(event.toolCallId ?? '');const toolName = String(event.toolName ?? 'tool');const toolArgs = (event.args as Record<string, unknown>) ?? {};+ if (toolUseId) ctx.toolNamesByCallId.set(toolUseId, toolName);queue.push({type: 'tool_use',data: {@@ -586,7 +595,16 @@ export function translatePiEvent(case 'tool_execution_end': {const toolUseId = String(event.toolCallId ?? '');const isError = event.isError === true;- const fullText = toolResultFullText(event.result);+ const rawText = toolResultFullText(event.result);+ const toolName = String(+ event.toolName+ ?? (toolUseId ? ctx.toolNamesByCallId.get(toolUseId) : undefined)+ ?? '',+ );+ if (toolUseId) ctx.toolNamesByCallId.delete(toolUseId);+ const fullText = isContextModeDoctorToolName(toolName) && ctx.rewriteToolResultText+ ? ctx.rewriteToolResultText(rawText)+ : rawText;queue.push({type: 'tool_result_full',data: { toolUseId, fullText, isError },