Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(maker-core): 修复 Agent 测试类型与 Pi 资源来源判断

DavidShen8192fb885c4a
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts
index 2872476631..8a988d03dd 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts
@@ -772,7 +772,8 @@ describe('normalizeClaudeJsonlToolIdsText', () => {
// content_block.id(子调用)→ 独立解析匹配第二个 Task_1 → Task_1_dup2,
// 不复用父映射
const evt = (entries[0] as Record<string, unknown>).event as Record<string, unknown>;
- expect((evt.content_block).id).toBe('Task_1_dup2');
+ const contentBlock = evt.content_block as Record<string, unknown>;
+ expect(contentBlock.id).toBe('Task_1_dup2');
});
it('child content_block_start 在 assistant 后且父同 id 时匹配子 occurrence(P1: Map post-assistant stream starts to the child occurrence)', () => {
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
index 9d3ded90de..83a8125c70 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
@@ -13,7 +13,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { AgentDeps } from '../../base-agent.js';
+import type { AgentDeps, RemoteClaudeRoute } from '../../base-agent.js';
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { PermissionMode } from '../../../types/common.js';
import type { AgentEvent, InteractionDecision, InteractionRequest } from '../../../types/events.js';
@@ -568,7 +568,7 @@ describe('ClaudeCodeAgent plan mode', () => {
imagePath,
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
);
- const remoteSend = vi.fn(async () => {});
+ const remoteSend = vi.fn(async (_message: unknown) => {});
const fakeQuery = { ...createFakeQuery(), send: remoteSend };
const remoteCcQueryFactory: NonNullable<AgentDeps['remoteCcQueryFactory']> = async () =>
fakeQuery as never;
@@ -607,7 +607,7 @@ describe('ClaudeCodeAgent plan mode', () => {
process.env.CLAUDE_CONFIG_DIR = configDir;
const workingDir = await makeTempDir();
const imagePath = path.join(workingDir, 'desktop.png');
- const remoteSend = vi.fn(async () => {});
+ const remoteSend = vi.fn(async (_message: unknown) => {});
const fakeQuery = { ...createFakeQuery(), send: remoteSend };
const remoteCcQueryFactory: NonNullable<AgentDeps['remoteCcQueryFactory']> = async () =>
fakeQuery as never;
@@ -660,7 +660,7 @@ describe('ClaudeCodeAgent plan mode', () => {
process.env.CLAUDE_CONFIG_DIR = configDir;
const workingDir = await makeTempDir();
const imagePath = path.join(workingDir, 'desktop-steer.png');
- const remoteSend = vi.fn(async () => {});
+ const remoteSend = vi.fn(async (_message: unknown) => {});
const fakeQuery = { ...createFakeQuery(), send: remoteSend };
const remoteCcQueryFactory: NonNullable<AgentDeps['remoteCcQueryFactory']> = async () =>
fakeQuery as never;
@@ -862,7 +862,7 @@ describe('ClaudeCodeAgent plan mode', () => {
return { authenticated: true };
},
async logout() {},
- async getAuthEnv(options) {
+ async getAuthEnv(options): Promise<Record<string, string>> {
return options?.credentialMode === 'gateway-key'
? { ANTHROPIC_API_KEY: 'gw-key' }
: { CLAUDE_CODE_OAUTH_TOKEN: 'tok-sub' }; // 本地 fallback: 订阅已连
@@ -1304,7 +1304,7 @@ describe('ClaudeCodeAgent plan mode', () => {
// 后台刷新后 nextRoute.env 是新 token,但 remoteEnv(远端 daemon)还是旧值 ——
// token 值轮换不算路由变化,同路由放行(codex P2 三轮)。
let callCount = 0;
- const resolveRemoteClaudeRoute = vi.fn(async () => {
+ const resolveRemoteClaudeRoute = vi.fn(async (): Promise<RemoteClaudeRoute> => {
callCount += 1;
return {
endpoint: 'https://api.anthropic.com',
@@ -1340,7 +1340,7 @@ describe('ClaudeCodeAgent plan mode', () => {
// 登录后 backfill 补齐 subscriptionType/rateLimitTier(用户零操作)—— 与 token 同组
// 按存在性比对,不按值,不误拒(Fable 5 评估 B1)。
let callCount = 0;
- const resolveRemoteClaudeRoute = vi.fn(async () => {
+ const resolveRemoteClaudeRoute = vi.fn(async (): Promise<RemoteClaudeRoute> => {
callCount += 1;
return {
endpoint: 'https://api.anthropic.com',
@@ -1419,7 +1419,7 @@ describe('ClaudeCodeAgent plan mode', () => {
// 初次解析带 x-tenant 定制头;切模时目标路由把它删了 —— 远端 daemon 仍烤着旧头,
// 必须拒绝(Greptile review #1035:只取 nextRoute 的 key 会把删除误判成一致)。
let callCount = 0;
- const resolveRemoteClaudeRoute = vi.fn(async () => {
+ const resolveRemoteClaudeRoute = vi.fn(async (): Promise<RemoteClaudeRoute> => {
callCount += 1;
return callCount === 1
? {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index ebd35eed81..700605f893 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -14,8 +14,14 @@ import {
type TurnPermissionPolicy,
} from '../base-agent.js';
import type { AuthAdapter } from '../../interfaces/auth-adapter.js';
-import type { AgentEvent, InteractionDecision, InteractionRequest } from '../../types/events.js';
+import type { AgentEvent as CoreAgentEvent, InteractionDecision, InteractionRequest } from '../../types/events.js';
import type { Logger } from '../../interfaces/logger.js';
+import type { AutoReviewDelegate } from '../shared/auto-review-decision.js';
+
+type AgentEvent = Omit<CoreAgentEvent, 'data'> & { data: any };
+type LooseThreadEventHandlers = {
+ [K in keyof ThreadEventHandlers]?: (...args: any[]) => any;
+};
const { MockCodexTransport, createdTransports, createdStdioOptions } = vi.hoisted(() => {
type LineHandler = (line: string) => void;
@@ -369,7 +375,7 @@ function installFakeHost(
userAgent: opts.userAgent ?? 'mock-codex/0.144.6',
...(opts.codexHome ? { codexHome: opts.codexHome } : {}),
}));
- let threadHandlers: ThreadEventHandlers | null = null;
+ let threadHandlers: LooseThreadEventHandlers | null = null;
const request = vi.fn(async (method: string, params: unknown): Promise<unknown> => {
if (requestImpl) {
const response = await requestImpl(method, params);
@@ -744,7 +750,7 @@ describe('CodexAgent permissions', () => {
forceConfirmToolCall: (_toolName, input) =>
JSON.stringify(input).includes('rm -rf'),
};
- const resolver = vi.fn(async () => ({
+ const resolver = vi.fn(async (_request: InteractionRequest): Promise<InteractionDecision> => ({
kind: 'permission' as const,
behavior: 'allow' as const,
}));
@@ -1703,7 +1709,7 @@ describe('CodexAgent capability routing', () => {
},
message: 'Allow tool call',
requestedSchema: {},
- }).then((result) => {
+ }).then((result: unknown) => {
elicitationSettled = true;
return result;
});
@@ -1797,7 +1803,7 @@ describe('CodexAgent capability routing', () => {
},
message: 'Allow tool call',
requestedSchema: {},
- }).then((result) => {
+ }).then((result: unknown) => {
elicitationSettled = true;
return result;
});
@@ -4856,10 +4862,10 @@ describe('CodexAgent MCP thread context hooks', () => {
const idleEvents: Array<Record<string, unknown>> = [];
const busyEvents: Array<Record<string, unknown>> = [];
const collectIdle = (async () => {
- for await (const event of idleHandle.events()) idleEvents.push(event as Record<string, unknown>);
+ for await (const event of idleHandle.events()) idleEvents.push(event as unknown as Record<string, unknown>);
})();
const collectBusy = (async () => {
- for await (const event of busyHandle.events()) busyEvents.push(event as Record<string, unknown>);
+ for await (const event of busyHandle.events()) busyEvents.push(event as unknown as Record<string, unknown>);
})();
// busy 会话先进入 in-flight turn;idle 会话保持空闲。
@@ -10584,7 +10590,7 @@ describe('CodexAgent MCP thread context hooks', () => {
const retryCall = host.request.mock.calls
.filter(([method]) => method === Method.TurnStart)
- .at(-1);
+ .at(-1) as unknown as [string, unknown, { timeoutMs?: number }];
expect(retryCall?.[2]).toMatchObject({ timeoutMs: expect.any(Number) });
await handle.close();
@@ -11038,7 +11044,7 @@ describe('CodexAgent MCP thread context hooks', () => {
workingDir: '/repo',
permissionMode: 'auto',
});
- const resolver = vi.fn(async () => ({
+ const resolver = vi.fn(async (_request: InteractionRequest): Promise<InteractionDecision> => ({
kind: 'permission' as const,
behavior: 'deny' as const,
}));
@@ -11451,7 +11457,7 @@ describe('CodexAgent MCP thread context hooks', () => {
});
it('keeps third-party routes on the user protocol and reviews with the current session model', async () => {
- const reviewAutoPermissionAction = vi.fn(async () => ({ verdict: 'allow' as const }));
+ const reviewAutoPermissionAction: ReturnType<typeof vi.fn<AutoReviewDelegate>> = vi.fn(async () => ({ verdict: 'allow' as const }));
const agent = new CodexAgent(createDeps({}, { reviewAutoPermissionAction }));
const host = installFakeHost(agent, (method) => {
if (method === Method.TurnStart) {
@@ -11618,7 +11624,7 @@ describe('CodexAgent MCP thread context hooks', () => {
});
it('opens the approval UI only when the lightweight reviewer explicitly returns ask', async () => {
- const reviewAutoPermissionAction = vi.fn(async () => ({
+ const reviewAutoPermissionAction = vi.fn<AutoReviewDelegate>(async (_request) => ({
verdict: 'ask' as const,
reason: 'This action crosses a high-impact boundary.',
}));
@@ -11651,7 +11657,7 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(result).toEqual({ decision: 'accept' });
expect(reviewAutoPermissionAction).toHaveBeenCalledOnce();
expect(resolver).toHaveBeenCalledOnce();
- const request = resolver.mock.calls[0]?.[0];
+ const request = (resolver.mock.calls as unknown as Array<[InteractionRequest]>)[0]?.[0];
expect(request?.kind).toBe('permission');
if (request?.kind !== 'permission') throw new Error('expected permission request');
expect(request.suggestions).toBeUndefined();
@@ -11712,7 +11718,7 @@ describe('CodexAgent MCP thread context hooks', () => {
});
it('auto-approves safe fallback commands via the Cindy auto-review core without prompting', async () => {
- const reviewAutoPermissionAction = vi.fn(async () => ({ verdict: 'allow' as const }));
+ const reviewAutoPermissionAction = vi.fn<AutoReviewDelegate>(async (_request) => ({ verdict: 'allow' as const }));
const agent = new CodexAgent(createDeps({}, { reviewAutoPermissionAction }));
const host = installFakeHost(agent);
const handle = await agent.startSession({
@@ -11755,7 +11761,7 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(resolver).toHaveBeenCalledOnce();
// prompt-each-time 必须剥离会话级 suggestion —— 否则用户点一次"总是允许"就把高风险 action 永久放行
// (与 Claude Code 侧等价断言对齐)。
- const request = resolver.mock.calls[0]?.[0];
+ const request = (resolver.mock.calls as unknown as Array<[InteractionRequest]>)[0]?.[0];
expect(request?.kind).toBe('permission');
if (request?.kind !== 'permission') throw new Error('expected permission request');
expect(request.suggestions).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.ts
index 343a36c06a..12a4e1cc54 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
@@ -89,6 +89,10 @@ import { PiAgent } from '../index.js';
import type { AgentDeps, AgentSessionHandle } from '../../base-agent.js';
import type { Logger } from '../../../interfaces/logger.js';
+type PiTestSessionHandle = AgentSessionHandle & {
+ setModel: NonNullable<AgentSessionHandle['setModel']>;
+};
+
const noopLogger: Logger = {
trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},
child: () => noopLogger,
@@ -157,7 +161,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
...(mcp?.serverNames
? {
preparePiExtraSpawnConfig: async (_providers, context) => {
- captured.mcpVendorOptions = context.vendorOptions;
+ captured.mcpVendorOptions = context?.vendorOptions;
return {
mcpBridge: {
token: 'bridge-token',
@@ -220,14 +224,14 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
reviewAutoPermissionAction?: AgentDeps['reviewAutoPermissionAction'],
includeNextModel = false,
mcp?: McpSetup,
- ): Promise<AgentSessionHandle> {
+ ): Promise<PiTestSessionHandle> {
const agent = new PiAgent(buildDeps(reviewAutoPermissionAction, includeNextModel, mcp));
return agent.startSession({
sessionId: 's1',
workingDir: cwd,
model: 'm',
...(permissionMode ? { permissionMode: permissionMode as never } : {}),
- });
+ }) as Promise<PiTestSessionHandle>;
}
/**
@@ -1203,7 +1207,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
});
const events: Array<Record<string, unknown>> = [];
void (async () => {
- for await (const e of handle.events()) events.push(e as Record<string, unknown>);
+ for await (const e of handle.events()) {
+ events.push(e as unknown as Record<string, unknown>);
+ }
})();
let cardShown = false;
handle.setInteractionResolver?.(async () => {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
index 5993b648d4..d801d9547b 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
@@ -868,7 +868,7 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
sourceInfo: expect.objectContaining({
path: path.join(explicitSkill, 'SKILL.md'),
source: 'local',
- scope: 'temporary',
+ scope: 'project',
}),
}),
]));
@@ -901,7 +901,7 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
baseDir: snapshotSkill,
path: path.join(snapshotSkill, 'SKILL.md'),
source: 'local',
- scope: 'temporary',
+ scope: 'project',
}),
}),
]));
@@ -932,7 +932,7 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
baseDir: path.dirname(explicitSkill),
path: explicitSkill,
source: 'local',
- scope: 'temporary',
+ scope: 'project',
}),
}),
]));
@@ -962,7 +962,7 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
expect(duplicates).toHaveLength(1);
expect(duplicates[0]).toMatchObject({
source: 'skill',
- sourceInfo: { baseDir: first, source: 'local', scope: 'temporary' },
+ sourceInfo: { baseDir: first, source: 'local', scope: 'project' },
});
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
index 5d34e643c5..5e0c080c68 100644
--- a/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
@@ -704,7 +704,7 @@ describe('Pi approved project resource assembly', () => {
name: 'skill:demo',
source: 'skill',
sourceInfo: {
- scope: 'temporary',
+ scope: 'project',
source: 'local',
baseDir: skillPath,
path: `${skillPath}/SKILL.md`,
diff --git a/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts b/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
index 729272d35d..b29ad13ab1 100644
--- a/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
+++ b/packages/maker-core/src/agents/pi/skill-runtime-provenance.ts
@@ -4,15 +4,17 @@ import type { PiRuntimeCommand } from '../../types/pi-runtime-capabilities.js';
/**
* Return the exact explicit --skill directory proven by pinned Pi provenance.
- * Both fields must agree; accepting either independently lets malformed runtime
- * data mark the wrong discovered project skill loaded.
+ * Pi v0.83 reports explicit local skills as either `temporary` (staged launch
+ * snapshots) or `project` (paths passed directly on the CLI). Both fields must
+ * agree; accepting either independently lets malformed runtime data mark the
+ * wrong discovered project skill loaded.
*/
export function piExplicitSkillRuntimePath(command: PiRuntimeCommand): string | null {
const baseDir = command.sourceInfo.baseDir;
const skillFile = command.sourceInfo.path;
if (
command.source !== 'skill'
- || command.sourceInfo.scope !== 'temporary'
+ || (command.sourceInfo.scope !== 'temporary' && command.sourceInfo.scope !== 'project')
|| command.sourceInfo.source !== 'local'
|| typeof baseDir !== 'string'
|| typeof skillFile !== 'string'