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(teammates): bound tool discovery and checkpoint recurring checks (#7463)

Chris Zhang45ce712179ab
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index 181ab078f9..61382e20a3 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -113,6 +113,23 @@ it('dispatches into the routine lane and records its task for inspection', async
expect(mock.ensureRoutineSession).toHaveBeenCalledWith(expect.objectContaining({ botId: 'bot', routineId: routine.id }));
});
+it('rebinds a stored canonical backing schedule to its independent lane before running', async () => {
+ const routine = await routineTools.save('bot', { name: 'Legacy review', prompt: 'Keep original instructions', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }] });
+ mock.storage.get.mockResolvedValueOnce({
+ id: `routine-${routine.id}`, name: 'Legacy review', prompt: 'Keep original instructions',
+ source: 'bot', kind: 'cron', cronExpr: '* * * * *', timezone: 'UTC',
+ recurring: true, manual: true, agentKind: 'pi', workspaceKind: 'dialogue', useWorktree: false,
+ targetSessionId: 'canonical-task', notify: { desktop: false, feishu: false },
+ status: 'active', createdAt: 123, updatedAt: 123,
+ });
+ await routineTools.runNow('bot', routine.id);
+ await vi.waitFor(async () => expect((await routineTools.history('bot', routine.id))[0]?.status).toBe('success'));
+ expect(mock.storage.update).toHaveBeenCalledWith(`routine-${routine.id}`, expect.objectContaining({
+ targetSessionId: `lane-${routine.id}`, createdAt: 123, prompt: expect.stringContaining('Keep original instructions'),
+ }));
+});
+
it('creates and closes an isolated lane for each fresh routine trigger', async () => {
const routine = await routineTools.save('bot', {
name: 'Fresh review', prompt: 'Check only this trigger', enabled: true,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
index 5e0a9817d6..67e2c207c0 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
@@ -196,6 +196,18 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active' });
});
+ it.each([true, false])('adds the checkpoint guidance only to recurring teammate work (%s)', async (recurring) => {
+ const h = createSessionHarness(acceptingSend());
+ const { runner } = createRunnerHarness(h.session, { silenced: true });
+ const promise = runner.fire(baseSchedule({ source: 'bot', recurring }), createFireContext());
+ await vi.waitFor(() => expect(h.session.send).toHaveBeenCalled());
+ const sent = JSON.stringify(vi.mocked(h.session.send).mock.calls[0][0]);
+ expect(sent.includes('[Routine checkpoint]')).toBe(recurring);
+ expect(sent).toContain('check the PR status');
+ h.emit({ type: 'done', data: { result: '' } });
+ await promise;
+ });
+
it('passes successful precheck output only to model input, keeping stored instructions intact', async () => {
mocks.executePreRunHook.mockResolvedValue({
decision: 'pass',
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index a61d625b43..9921b737df 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -3777,7 +3777,10 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
function buildScheduledRunPrompt(schedule: Schedule, ctx: FireContext, checkOutput = ''): string {
- return `${schedule.prompt}${checkOutput}${buildScheduledRunContextInstruction(schedule, ctx)}${
+ const routineWait = schedule.source === 'bot' && schedule.recurring
+ ? '\n\n[Routine checkpoint] For recurring checks with another trigger scheduled, inspect the current state and finish this run once actionable work is handled. If only external progress is pending, leave a concise checkpoint (identifiers, current state and next check) in the final result; do not keep this run alive with repeated sleep/poll calls. A later trigger may start with fresh context: when prior progress is needed, retrieve the previous result from the existing routine or schedule run history instead of assuming it is in this conversation. Complete one-time assignments and preserve explicit instructions requiring continuous observation or a delivery deadline.'
+ : '';
+ return `${schedule.prompt}${checkOutput}${buildScheduledRunContextInstruction(schedule, ctx)}${routineWait}${
schedule.silentWhenIdle ? buildSilentRunInstruction(schedule.source === 'bot') : ''
}`;
}
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index d6d5d86944..d78528ace9 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -56,7 +56,9 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
`initialize + tools/list` 总预算为 10s(低于 Pi RPC 30s ready 门槛);探测完成后实际工具
调用保留 600s 长预算。SSE response 按 event 增量消费,不等待 server 关闭持续流。Pi 模型侧
始终只注册 `cindy_mcp_list_tools` 与 `cindy_mcp_call_tool` 两个稳定网关 schema;完整工具目录与
- input schema 留在 bridge 内部。先发现名称/描述,再按具体 server + tool 取单个 schema,
+ input schema 留在 bridge 内部。名称/描述发现每页最多 50 项,说明预览最多 240 字符;
+ 可按 server 或 query 检索完整说明,并用 nextOffset 翻页,工具不会因分页丢失。
+ 再按具体 server + tool 取完整说明及单个 schema,
未检查 schema 的调用在 bridge 内 fail closed,不会触达 MCP 或弹权限框。门按会话与
当前工具 schema 指纹记账:Pi 升级不再作废未变 schema 的披露,schema 真变动时门重新武装。
首次未披露的调用在**发起权限询问之前**被拦下——不弹权限框、不触达 MCP,回执指名该查的
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts
index ae5117e69f..813b9bc027 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts
@@ -6,13 +6,14 @@ import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
// Execute the generated extension's actual client and registered gateway. Pi
// loads this standalone source, so importing a parallel client would miss bugs.
+const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+const compiled = ts.transpileModule(
+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))
+ + '\nglobalThis.Client = McpHttpClient; globalThis.Gateway = CindyMcpGateway;',
+ { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
+).outputText;
+
function gatewayWithFetch(fetchImpl: typeof fetch) {
- const source = CINDY_BRIDGE_EXTENSION_SOURCE;
- const compiled = ts.transpileModule(
- source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))
- + '\nglobalThis.Client = McpHttpClient; globalThis.Gateway = CindyMcpGateway;',
- { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
- ).outputText;
const context: Record<string, any> = {
fetch: fetchImpl, URL, Headers, AbortController, TextDecoder, process: { env: {} },
// 沙箱没有模块系统:bridge 顶部的 node:crypto import 在切片后丢失,
@@ -31,12 +32,39 @@ function gatewayWithFetch(fetchImpl: typeof fetch) {
registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', { server: 'cindy', tool: 'ghost_call' });
const call = (signal?: AbortSignal) => registered.find(t => t.name === 'cindy_mcp_call_tool')
.execute('call', { server: 'cindy', tool: 'ghost_call', args: { ghost_id: 'demo' } }, signal);
- return { call };
+ return { call, gateway, client, list: (params: unknown = {}) => registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', params) };
}
afterEach(() => vi.useRealTimers());
describe('Pi MCP request lifecycle', () => {
+ it('bounds broad discovery, pages all tools, and inspects the full searchable description', async () => {
+ const h = gatewayWithFetch(vi.fn());
+ const description = 'Documentation '.repeat(200) + 'needle';
+ h.gateway.add('catalog', h.client, Array.from({ length: 117 }, (_, i) => ({
+ name: 'tool_' + String(i).padStart(3, '0'), description,
+ inputSchema: { type: 'object', properties: { value: { type: 'string' } } },
+ })));
+ const first = (await h.list()).details;
+ expect(first.tools).toHaveLength(50);
+ expect(first.total).toBe(118);
+ expect(JSON.stringify(first).length).toBeLessThan(18000);
+ const names = [...first.tools];
+ let next = first.nextOffset;
+ while (next !== undefined) {
+ const page = (await h.list({ offset: next })).details;
+ names.push(...page.tools);
+ next = page.nextOffset;
+ }
+ expect(new Set(names.map(tool => tool.server + ':' + tool.name)).size).toBe(118);
+ const search = (await h.list({ query: 'NEEDLE', server: 'catalog', offset: 100 })).details;
+ expect(search.total).toBe(117);
+ expect(search.tools).toHaveLength(17);
+ const exact = (await h.list({ server: 'catalog', tool: 'tool_116' })).details;
+ expect(exact.tools[0].description).toBe(description);
+ expect(exact.tools[0].inputSchema.properties.value.type).toBe('string');
+ });
+
it('waits for card interaction beyond five minutes with one explicit deadline', async () => {
vi.useFakeTimers();
let complete!: (response: Response) => void;
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 3993a1bd5d..f914131e7a 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -3374,9 +3374,21 @@ class CindyMcpGateway {
unavailableServers,
};
} else {
+ const query = typeof input.query === 'string' ? input.query.trim().toLowerCase() : '';
+ const offset = Number.isSafeInteger(input.offset) && Number(input.offset) >= 0 ? Number(input.offset) : 0;
+ const limit = Number.isSafeInteger(input.limit) && Number(input.limit) > 0 ? Math.min(Number(input.limit), 50) : 50;
+ const matches = query ? tools.filter((tool) =>
+ [tool.server, tool.name, tool.description].some((value) => value.toLowerCase().includes(query))) : tools;
+ const page = matches.slice(offset, offset + limit);
payload = {
ok: true,
- tools,
+ tools: page.map((tool) => ({ ...tool, description: tool.description.length > 240
+ ? tool.description.slice(0, 240) + '…' : tool.description })),
+ total: matches.length,
+ offset,
+ ...(offset + page.length < matches.length ? { nextOffset: offset + page.length } : {}),
+ availableServers: this.availableServers(),
+ hint: 'Use query or server to narrow results; follow nextOffset for more. Inspect an exact server and tool for the complete description and input schema.',
...(unavailableServers.length > 0 ? { unavailableServers } : {}),
};
}
@@ -3808,16 +3820,19 @@ class CindyMcpGateway {
name: CINDY_MCP_LIST_TOOLS,
label: 'Discover Cindy MCP tools',
description:
- 'List every connected Cindy/MCP capability without loading their parameter schemas into startup context. ' +
- 'Omit arguments to discover names and descriptions. Before invoking a tool, pass its exact server and tool ' +
+ 'Discover connected Cindy/MCP tools in pages of at most 50 short descriptions. Use query or server to narrow ' +
+ 'results, or offset=nextOffset for more. Before invoking a tool, pass its exact server and tool ' +
'names here once to inspect that single input schema, then use cindy_mcp_call_tool.',
parameters: {
type: 'object',
properties: {
server: {
type: 'string',
- description: 'Optional exact server name. Omit to list tools from every connected server.',
+ description: 'Optional exact server name. Omit to search across connected servers.',
},
+ query: { type: 'string', description: 'Search tool names and full descriptions, case-insensitively.' },
+ offset: { type: 'integer', minimum: 0, description: 'Use the previous nextOffset to continue browsing.' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Page size; default 50.' },
tool: {
type: 'string',
description: 'Optional exact tool name. Requires server and returns that tool\'s input schema.',