Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot-import): companion_import 工具 schema 改为 2020-12 兼容的定长整数数组 (#5321)
FicoWang24e5e80009b7
diff --git a/apps/desktop/src/main/bot-import/__tests__/importProviderSchema.test.ts b/apps/desktop/src/main/bot-import/__tests__/importProviderSchema.test.tsnew file mode 100644index 0000000000..dab0234f8c--- /dev/null+++ b/apps/desktop/src/main/bot-import/__tests__/importProviderSchema.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { z } from 'zod';+import { companionImportEntryRangeSchema, companionImportToolArgs } from '../importProviderSchema.js';++type JsonSchema = { type?: string; items?: unknown; prefixItems?: unknown; minItems?: number; maxItems?: number; properties?: Record<string, JsonSchema> };++/** Every `items` keyword in the published schema must be a single schema (2020-12 compatible), never a tuple array. */+function tupleItemPaths(schema: unknown, path = '$'): string[] {+ if (!schema || typeof schema !== 'object') return [];+ const found: string[] = [];+ for (const [key, value] of Object.entries(schema as Record<string, unknown>)) {+ if (key === 'items' && Array.isArray(value)) found.push(`${path}.items`);+ found.push(...tupleItemPaths(value, `${path}.${key}`));+ }+ return found;+}++async function publishedInputSchema(args: Record<string, z.ZodType>): Promise<JsonSchema> {+ const server = new McpServer({ name: 'companion_import', version: '1.0.0' });+ server.tool('import_agent', 'test', args, async () => ({ content: [] }));+ const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ const client = new Client({ name: 'test', version: '1.0.0' });+ await client.connect(clientTransport);+ try {+ const { tools } = await client.listTools();+ return tools[0]!.inputSchema as JsonSchema;+ } finally { await client.close(); await server.close(); }+}++describe('companion_import tool schema (#5317)', () => {+ it('publishes entryRanges without draft-07 tuple items, as xAI validates tool schemas against 2020-12', async () => {+ const schema = await publishedInputSchema(companionImportToolArgs);+ expect(tupleItemPaths(schema)).toEqual([]);+ const ranges = schema.properties!.selection!.properties!.entryRanges!;+ expect(ranges.type).toBe('array');+ const range = ranges.items as JsonSchema;+ expect(range).toMatchObject({ type: 'array', minItems: 2, maxItems: 2 });+ expect(range.items).toMatchObject({ type: 'integer', minimum: 0 });+ expect(range.prefixItems).toBeUndefined();+ });++ it('counter-evidence: the former z.tuple definition is what produced the rejected tuple items', async () => {+ const legacy = { ...companionImportToolArgs, selection: z.object({ entryRanges: z.array(z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()])).optional() }).optional() };+ const schema = await publishedInputSchema(legacy);+ expect(tupleItemPaths(schema)).toEqual(['$.properties.selection.properties.entryRanges.items.items']);+ });++ it('still only accepts [first, last] pairs of non-negative integers at the wire boundary', () => {+ expect(companionImportEntryRangeSchema.safeParse([0, 4]).success).toBe(true);+ expect(companionImportEntryRangeSchema.safeParse([3]).success).toBe(false);+ expect(companionImportEntryRangeSchema.safeParse([1, 2, 3]).success).toBe(false);+ expect(companionImportEntryRangeSchema.safeParse([-1, 2]).success).toBe(false);+ expect(companionImportEntryRangeSchema.safeParse([0.5, 2]).success).toBe(false);+ });+});diff --git a/apps/desktop/src/main/bot-import/importProvider.ts b/apps/desktop/src/main/bot-import/importProvider.tsindex 5f7adb86a7..c1ceee7f58 100644--- a/apps/desktop/src/main/bot-import/importProvider.ts+++ b/apps/desktop/src/main/bot-import/importProvider.ts@@ -1,5 +1,4 @@import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { z } from 'zod';import type { McpProvider } from '@cindy/maker-core';import { resolveLiziMcpSessionContext } from '@cindy/mcps';import { listCompanionImportSources, previewCompanionImport, startCompanionImport, getCompanionImportResult } from './host.js';@@ -8,16 +7,14 @@ import { getDbClient } from '../localDb/client/current.js';import { sessions, sharedTaskEvents } from '../localDb/schema.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';import { CompanionImportError } from './types.js';+import { companionImportToolArgs } from './importProviderSchema.js';+import type { CompanionImportSelection } from '@cindy/maker-shared/companion-import';/** Commands and the GUI share the same selection, durable receipt and takeover transaction. */export function createCompanionImportProvider(): McpProvider {return { name: 'companion_import', toClaudeSdkConfig(context) {const server = new McpServer({ name: 'companion_import', version: '1.0.0' });- server.tool('import_agent', 'Import a selected local Hermes/OpenClaw agent into a teammate. Discover sources, preview selectable metadata, then import only IDs explicitly selected by the user. Secrets remain on the host. For takeover, the user must request taking over the automations. Poll status by the same requestId; never invent a new requestId after a lost reply.', {- operation: z.enum(['sources', 'preview', 'start', 'status']), sourceId: z.string().optional(),- selection: z.object({ previewId: z.string(), requestId: z.string(), name: z.string(), avatarImageBase64: z.string().min(1).max(2_000_000).optional(), entryIds: z.array(z.string()), takeover: z.boolean(), deferSetup: z.boolean().default(true), entryRanges: z.array(z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()])).optional() }).optional(),- requestId: z.string().optional(),- }, async input => {+ server.tool('import_agent', 'Import a selected local Hermes/OpenClaw agent into a teammate. Discover sources, preview selectable metadata, then import only IDs explicitly selected by the user. Secrets remain on the host. For takeover, the user must request taking over the automations. Poll status by the same requestId; never invent a new requestId after a lost reply.', companionImportToolArgs, async input => {const session = resolveLiziMcpSessionContext(context);if (!session.sessionId) return { isError: true, content: [{ type: 'text', text: 'IMPORT_CALLER_UNAVAILABLE' }] };const controller = `command:${session.sessionId}`;@@ -31,7 +28,8 @@ export function createCompanionImportProvider(): McpProvider {if (!task || task.source !== 'desktop' || task.status !== 'active' || task.remoteHostId || shared || isAppSessionBoundaryPending() || owner !== activeOwnerScopeKey()) throw new CompanionImportError('IMPORT_CALLER_UNAVAILABLE');const result = input.operation === 'sources' ? await listCompanionImportSources(controller): input.operation === 'preview' && input.sourceId ? await previewCompanionImport(input.sourceId, controller)- : input.operation === 'start' && input.selection ? await startCompanionImport(input.selection, controller)+ // Length-2 arrays are re-checked as [first, last] pairs by validateImportSelection.+ : input.operation === 'start' && input.selection ? await startCompanionImport(input.selection as CompanionImportSelection, controller): input.operation === 'status' && input.requestId ? await getCompanionImportResult(input.requestId) : undefined;if (result === undefined && input.operation !== 'status') throw new CompanionImportError('INVALID_REQUEST');return { content: [{ type: 'text', text: JSON.stringify(result ?? null) }] };diff --git a/apps/desktop/src/main/bot-import/importProviderSchema.ts b/apps/desktop/src/main/bot-import/importProviderSchema.tsnew file mode 100644index 0000000000..014206ebfa--- /dev/null+++ b/apps/desktop/src/main/bot-import/importProviderSchema.ts@@ -0,0 +1,21 @@+import { z } from 'zod';++/**+ * Argument schema of the `companion_import.import_agent` MCP tool.+ *+ * Kept free of host dependencies so the exact JSON Schema handed to model+ * providers can be asserted in tests. Upstream providers (xAI Grok among them)+ * validate tool definitions against JSON Schema 2020-12, where tuple-style+ * `items: [...]` arrays are rejected outright; the MCP SDK emits that form for+ * `z.tuple` because it targets draft-07. `entryRanges` therefore uses a plain+ * fixed-length integer array (#5317). `validateImportSelection` still enforces+ * ordering, non-overlap and `[first, last]` pairing on the business side.+ */+const sourceIndex = z.number().int().nonnegative();+export const companionImportEntryRangeSchema = z.array(sourceIndex).length(2);++export const companionImportToolArgs = {+ operation: z.enum(['sources', 'preview', 'start', 'status']), sourceId: z.string().optional(),+ selection: z.object({ previewId: z.string(), requestId: z.string(), name: z.string(), avatarImageBase64: z.string().min(1).max(2_000_000).optional(), entryIds: z.array(z.string()), takeover: z.boolean(), deferSetup: z.boolean().default(true), entryRanges: z.array(companionImportEntryRangeSchema).optional() }).optional(),+ requestId: z.string().optional(),+};