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): 子代理支持显式指定 provider

Zhang Yunjinf6023219ed55
diff --git a/docs/research/pi-subagent-delegation.md b/docs/research/pi-subagent-delegation.md
index a7f64f4024..aabe618444 100644
--- a/docs/research/pi-subagent-delegation.md
+++ b/docs/research/pi-subagent-delegation.md
@@ -24,7 +24,7 @@
| 环节 | 原有缺口 | 本次实现 |
| --- | --- | --- |
-| 能力发现 | 角色名在工具说明里,模型难以系统查询 | `capabilities` 返回角色、工具、可选型号与并发限制 |
+| 能力发现 | 角色名在工具说明里,模型难以系统查询 | `capabilities` 返回角色、工具、可选型号(含各自可用的 provider)与并发限制 |
| 启动 | runId 仅在 details,模型收到笼统启动回执 | 文本回执带 runId/taskId |
| 控制 | 模型只能针对整个 run;写入邮箱就宣称成功 | `childId` 定向,等待 runner receipt,拒绝与不确定分别报告 |
| 等待 | 只能反复 get | `wait` 最长 60 秒,超时不终止子代理 |
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts
index 8321c61fcc..5a49e004f9 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts
@@ -9,7 +9,7 @@ import { CINDY_SUBAGENT_EXTENSION_SOURCE } from '../cindy-subagent-source.js';
// Execute the exact staged extension, including its filesystem mailbox and
// lifecycle handlers. Export helpers only in this test's in-memory module.
-const compiled = ts.transpileModule(CINDY_SUBAGENT_EXTENSION_SOURCE + '\nexport { parentContextSnapshot, createResultDelivery };', {
+const compiled = ts.transpileModule(CINDY_SUBAGENT_EXTENSION_SOURCE + '\nexport { parentContextSnapshot, createResultDelivery, resolveTaskModelRoutes, normalizeInvocation };', {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText;
const nativeRequire = createRequire(import.meta.url);
@@ -48,7 +48,7 @@ async function fixture(fsOverrides: Record<string, unknown> = {}) {
const ctx = { ui: { input: vi.fn(async (_title: string, _payload: string) => JSON.stringify({ ok: true })) },
sessionManager: { getBranch: () => [] }, hasPendingMessages: () => false };
const execute = (params: any, signal = new AbortController().signal) => tool.execute('control-id', params, signal, undefined, ctx);
- return { root, runId, dir, status, publish, hooks, pi, ctx, execute };
+ return { root, runId, dir, status, publish, hooks, pi, ctx, execute, tool };
}
const boundary = { outcome: 'completed', context: { pendingMessages: [] } };
function restorePending(f: Awaited<ReturnType<typeof fixture>>) {
@@ -302,3 +302,79 @@ describe('Pi delegation behavior', () => {
expect((await operation).entries[0].content).toContain('CHILD_RESULT');
});
});
+
+describe('Pi subagent provider selection', () => {
+ // 同一裸模型 id 在两个真实连接下重名(ex: 智谱 Coding Plan 与 OpenCode Go 都有 glm-5.3-flash),
+ // 父会话在第三个 provider 上时,只有调用方显式点名的 provider 能消歧。
+ const runtime = {
+ model: 'parent-model',
+ provider: 'parent',
+ modelRoutes: {
+ 'parent-model': [{ provider: 'parent', model: 'parent-model' }],
+ 'glm-5.3-flash': [
+ { provider: 'opencode-go', model: 'glm-5.3-flash', sourceProviderId: 'opencode-go' },
+ { provider: 'glm-coding-plan', model: 'glm-5.3-flash', sourceProviderId: 'glm-coding-plan' },
+ ],
+ 'gateway-model': [
+ { provider: 'cindy', model: 'gateway-model', sourceProviderId: 'cindy-gateway', proxySessionAuth: true },
+ { provider: 'commandcode', model: 'gateway-model', sourceProviderId: 'commandcode' },
+ ],
+ },
+ };
+ const route = (task: { model?: string; provider?: string }) => {
+ const tasks = [task];
+ extension.resolveTaskModelRoutes(tasks, runtime);
+ return tasks[0] as Record<string, unknown>;
+ };
+
+ it('routes a child to the provider the caller names for an ambiguous model', () => {
+ expect(route({ model: 'glm-5.3-flash', provider: 'glm-coding-plan' })).toMatchObject({
+ routeProvider: 'glm-coding-plan',
+ routeModel: 'glm-5.3-flash',
+ routeSourceProviderId: 'glm-coding-plan',
+ routeProxySessionAuth: false,
+ });
+ });
+
+ it('accepts the Cindy source id even when the runtime provider name differs', () => {
+ expect(route({ model: 'gateway-model', provider: 'cindy-gateway' })).toMatchObject({
+ routeProvider: 'cindy',
+ routeProxySessionAuth: true,
+ });
+ });
+
+ it('keeps the parent model when only a provider is given', () => {
+ expect(route({ provider: 'parent' })).toMatchObject({
+ routeProvider: 'parent',
+ routeModel: 'parent-model',
+ });
+ });
+
+ it('rejects a provider that does not offer the model and lists the ones that do', () => {
+ expect(() => route({ model: 'glm-5.3-flash', provider: 'commandcode' })).toThrow(
+ 'provider "commandcode" does not offer model "glm-5.3-flash" in this session. '
+ + 'Providers for this model: opencode-go, glm-coding-plan.',
+ );
+ });
+
+ it('points an unqualified ambiguous model at the provider knob', () => {
+ expect(() => route({ model: 'glm-5.3-flash' })).toThrow(
+ 'is available from multiple providers: opencode-go, glm-coding-plan. Pass provider',
+ );
+ });
+
+ it('accepts provider at call level and per task, and exposes it in the tool schema', async () => {
+ const callLevel = extension.normalizeInvocation({ agent: 'worker', task: 'x', provider: 'glm-coding-plan' });
+ expect(callLevel.tasks[0].provider).toBe('glm-coding-plan');
+ const perTask = extension.normalizeInvocation({
+ agent: 'worker', task: 'x', provider: 'call-level',
+ tasks: [{ agent: 'worker', task: 'a' }, { agent: 'reviewer', task: 'b', provider: 'task-level' }],
+ });
+ expect(perTask.tasks.map((task: { provider: string }) => task.provider))
+ .toEqual(['call-level', 'task-level']);
+ expect(extension.normalizeInvocation({ agent: 'worker', task: 'x' }).tasks[0].provider).toBe('');
+ const f = await fixture();
+ expect(f.tool.parameters.properties.provider.type).toBe('string');
+ expect(f.tool.parameters.properties.tasks.items.properties.provider.type).toBe('string');
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
index 6fabf8bab4..d1f7dd51ee 100644
--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
@@ -350,6 +350,30 @@ function parentContextSnapshot(ctx) {
.map(function (entry) { return entry[1]; }).join('\n\n');
}
+function routeMatchesProvider(route, provider) {
+ // Cindy 的来源 id 与 pi 的 runtime provider 名可以不同(cindy-gateway / cindy,
+ // openai / openai-codex),调用方拿到的通常是前者,两个都认。
+ return route.provider === provider || route.sourceProviderId === provider;
+}
+
+function routeProviders(candidates) {
+ const providers = [];
+ for (const route of candidates) {
+ const label = route.sourceProviderId || route.provider;
+ if (providers.indexOf(label) < 0) providers.push(label);
+ }
+ return providers;
+}
+
+function modelProviderMap(runtime) {
+ const map = {};
+ for (const [id, routes] of Object.entries(runtime.modelRoutes || {})) {
+ const providers = routeProviders(routes);
+ if (providers.length > 0) map[id] = providers;
+ }
+ return map;
+}
+
function resolveTaskModelRoutes(tasks, runtime) {
const availableModels = Object.keys(runtime.modelRoutes || {}).sort();
const availableModelHint = availableModels.length > 0
@@ -357,7 +381,7 @@ function resolveTaskModelRoutes(tasks, runtime) {
+ (availableModels.length > 24 ? ', ...' : '') + '.'
: ' No models are available in this session.';
for (const task of tasks) {
- if (!task.model) {
+ if (!task.model && !task.provider) {
const currentRoutes = runtime.modelRoutes && Array.isArray(runtime.modelRoutes[runtime.model])
? runtime.modelRoutes[runtime.model]
: [];
@@ -370,9 +394,45 @@ function resolveTaskModelRoutes(tasks, runtime) {
task.routeProxySessionAuth = !!(currentRoute && currentRoute.proxySessionAuth === true);
continue;
}
- const candidates = runtime.modelRoutes && Array.isArray(runtime.modelRoutes[task.model])
- ? runtime.modelRoutes[task.model]
+ const modelId = task.model || runtime.model;
+ const candidates = runtime.modelRoutes && Array.isArray(runtime.modelRoutes[modelId])
+ ? runtime.modelRoutes[modelId]
: [];
+ if (task.provider) {
+ // 显式 provider 压过父 provider 与下面的 id 前缀推断:裸 id 在两个真实连接下重名时,
+ // 只有调用方知道要哪一条。仍然只认快照里存在的路由 —— 不按名字拼 endpoint。
+ const matching = candidates.filter(function (route) {
+ return routeMatchesProvider(route, task.provider);
+ });
+ const exact = matching.filter(function (route) { return route.model === modelId; });
+ const route = matching.length === 1
+ ? matching[0]
+ : exact.length === 1
+ ? exact[0]
+ : null;
+ if (!route) {
+ if (candidates.length === 0) {
+ throw new Error(
+ 'subagent: model "' + modelId + '" is not available in this session.' + availableModelHint,
+ );
+ }
+ if (matching.length > 1) {
+ throw new Error(
+ 'subagent: provider "' + task.provider + '" has several routes for model "' + modelId + '": '
+ + matching.map(function (route) { return route.model; }).join(', ') + '.',
+ );
+ }
+ throw new Error(
+ 'subagent: provider "' + task.provider + '" does not offer model "' + modelId + '" in this session. '
+ + 'Providers for this model: ' + routeProviders(candidates).join(', ') + '.',
+ );
+ }
+ task.routeProvider = route.provider;
+ task.routeModel = route.model;
+ task.routeSourceProviderId = route.sourceProviderId;
+ task.routeProxySessionAuth = route.proxySessionAuth === true;
+ continue;
+ }
const explicitSource = task.model.startsWith('xai/')
? 'xai'
: task.model.startsWith('chatgpt/')
@@ -396,8 +456,9 @@ function resolveTaskModelRoutes(tasks, runtime) {
if (!route) {
if (candidates.length > 1) {
throw new Error(
- 'subagent: model "' + task.model + '" is available from multiple providers; '
- + 'switch the parent to the intended provider before delegating.',
+ 'subagent: model "' + task.model + '" is available from multiple providers: '
+ + routeProviders(candidates).join(', ') + '. Pass provider to choose one, or switch the parent '
+ + 'to the intended provider before delegating.',
);
}
throw new Error(
@@ -616,9 +677,11 @@ async function writeDurableControl(status, action, message, childId, signal) {
async function managementResult(params, ctx, signal, delivery) {
const action = params.action;
if (action === 'capabilities') {
+ const runtime = readRuntimeSnapshot();
return JSON.stringify({ roles: Object.keys(PROFILES).map(function (agent) {
return { agent: agent, tools: toolsFor(agent).split(',') };
- }), models: Object.keys(readRuntimeSnapshot().modelRoutes || {}),
+ }), models: Object.keys(runtime.modelRoutes || {}),
+ modelProviders: modelProviderMap(runtime),
maxTasks: MAX_TASKS, concurrency: MAX_CONCURRENCY, context: ['fresh', 'fork'],
actions: ['run', 'list', 'get', 'wait', 'stop', 'steer', 'follow_up', 'resume'] });
}
@@ -1231,6 +1294,14 @@ function normalizeInvocation(params) {
if (model.length > MAX_MODEL_CHARS) {
throw new Error('subagent: model id exceeds ' + MAX_MODEL_CHARS + ' characters');
}
+ const provider = typeof item.provider === 'string' && item.provider.trim()
+ ? item.provider.trim()
+ : typeof input.provider === 'string' && input.provider.trim()
+ ? input.provider.trim()
+ : '';
+ if (provider.length > MAX_MODEL_CHARS) {
+ throw new Error('subagent: provider id exceeds ' + MAX_MODEL_CHARS + ' characters');
+ }
const thinking = typeof item.thinking === 'string' && item.thinking.trim()
? item.thinking.trim()
: typeof input.thinking === 'string' && input.thinking.trim()
@@ -1246,6 +1317,7 @@ function normalizeInvocation(params) {
title: title,
task: task,
model: model,
+ provider: provider,
thinking: thinking,
customProfile: false,
customTools: 'read',
@@ -1419,7 +1491,8 @@ export default async function cindySubagent(pi: any) {
description: 'Delegate work to a PI child with its own context and durable session. '
+ 'Available roles: ' + profileNames() + '. Read-only roles cannot edit. worker uses the parent '
+ 'permission mode; Ask/Auto requests are forwarded to Cindy approval. Pass model/thinking to override the '
- + 'parent model for a child. Pass async:true for a detached background run that survives parent navigation. '
+ + 'parent model for a child, and provider to choose which provider serves that model (see capabilities '
+ + 'modelProviders). Pass async:true for a detached background run that survives parent navigation. '
+ 'Results are collected before this parent turn settles; notify:false leaves collection explicit. '
+ 'Pass {agent, task} for one, or {tasks:[{agent, task}, ...]} to fan out in parallel. '
+ 'Use action:capabilities/list/get/wait/stop/steer/follow_up/resume for durable runs. Select childId to control one child. Children cannot spawn further subagents.',
@@ -1442,6 +1515,10 @@ export default async function cindySubagent(pi: any) {
},
title: { type: 'string', description: 'Optional user-facing name describing the task value.' },
model: { type: 'string', description: 'Optional exact child model id.' },
+ provider: {
+ type: 'string',
+ description: 'Optional provider id for the child (from capabilities modelProviders). Must serve the chosen model; defaults to the parent provider.',
+ },
thinking: { type: 'string', description: 'Optional thinking level: ' + THINKING_LEVELS },
async: { type: 'boolean', description: 'Run in Cindy durable background mode.' },
notify: { type: 'boolean', description: 'Default true: collect async/resume results before the parent finishes. false: use wait/get explicitly.' },
@@ -1471,6 +1548,7 @@ export default async function cindySubagent(pi: any) {
title: { type: 'string', description: 'Optional user-facing name for this task.' },
task: { type: 'string' },
model: { type: 'string' },
+ provider: { type: 'string' },
thinking: { type: 'string' },
},
required: ['agent', 'task'],