feat: 初始化DevOps平台后端
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { Body, Controller, Get, Post } from '@nestjs/common';
|
||||
import {
|
||||
ApiBody,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { ZodValidationPipe } from '../common/pipes/zod-validation.pipe';
|
||||
import { AgentInvocation } from './agent.types';
|
||||
import { AgentService } from './agent.service';
|
||||
import {
|
||||
CreateAgentInvocationDto,
|
||||
CreateAgentInvocationInput,
|
||||
createAgentInvocationSchema,
|
||||
} from './create-agent-invocation.dto';
|
||||
|
||||
@ApiTags('agent')
|
||||
@Controller('agent/invocations')
|
||||
export class AgentController {
|
||||
constructor(private readonly agentService: AgentService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOkResponse({ description: 'Agent invocation audit list.' })
|
||||
listInvocations(): AgentInvocation[] {
|
||||
return this.agentService.listInvocations();
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiBody({ type: CreateAgentInvocationDto })
|
||||
@ApiCreatedResponse({ description: 'Create a DevOps-scoped agent invocation.' })
|
||||
async createInvocation(
|
||||
@Body(new ZodValidationPipe(createAgentInvocationSchema))
|
||||
body: CreateAgentInvocationInput,
|
||||
): Promise<AgentInvocation> {
|
||||
return this.agentService.createInvocation(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { AgentController } from './agent.controller';
|
||||
import { AgentService } from './agent.service';
|
||||
import { LlmClient } from './llm.client';
|
||||
|
||||
@Module({
|
||||
imports: [AuditModule],
|
||||
controllers: [AgentController],
|
||||
providers: [AgentService, LlmClient],
|
||||
exports: [AgentService, LlmClient],
|
||||
})
|
||||
export class AgentModule {}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { AgentService } from './agent.service';
|
||||
import { CreateAgentInvocationInput } from './create-agent-invocation.dto';
|
||||
import { LlmClient } from './llm.client';
|
||||
|
||||
/**
|
||||
* 锁定 Agent 入口只服务 DevOps 场景,避免后续误扩成泛聊天接口。
|
||||
*/
|
||||
describe('AgentService', () => {
|
||||
function createService(options?: {
|
||||
llmConfigured?: boolean;
|
||||
llmText?: string;
|
||||
}) {
|
||||
const audit = {
|
||||
record: jest.fn(),
|
||||
} satisfies Pick<AuditService, 'record'>;
|
||||
const llm = {
|
||||
healthSummary: jest.fn(() =>
|
||||
options?.llmConfigured
|
||||
? { status: 'ok' as const }
|
||||
: { status: 'not_configured' as const, message: 'Missing LLM_API_KEY' },
|
||||
),
|
||||
complete: jest.fn(() =>
|
||||
Promise.resolve({
|
||||
text: options?.llmText ?? 'LLM generated DevOps answer',
|
||||
model: 'test-model',
|
||||
}),
|
||||
),
|
||||
} satisfies Pick<LlmClient, 'healthSummary' | 'complete'>;
|
||||
|
||||
return {
|
||||
audit,
|
||||
llm,
|
||||
service: new AgentService(
|
||||
audit as unknown as AuditService,
|
||||
llm as unknown as LlmClient,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
it('creates a DevOps-scoped mock invocation when LLM is not configured', async () => {
|
||||
const { audit, llm, service } = createService();
|
||||
|
||||
const invocation = await service.createInvocation({
|
||||
type: 'failure-diagnosis',
|
||||
runId: 'run_001',
|
||||
projectKey: 'role-user',
|
||||
promptSummary: 'Analyze latest failed Jenkins log excerpt.',
|
||||
});
|
||||
|
||||
expect(invocation.status).toBe('success');
|
||||
expect(invocation.resultMarkdown).toContain('失败诊断摘要');
|
||||
expect(llm.complete).not.toHaveBeenCalled();
|
||||
expect(audit.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'AGENT_INVOCATION_CREATED',
|
||||
resourceType: 'agent_invocation',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('creates a DevOps-scoped LLM invocation when configured', async () => {
|
||||
const { audit, llm, service } = createService({
|
||||
llmConfigured: true,
|
||||
llmText: '真实 LLM 运维分析结果',
|
||||
});
|
||||
|
||||
const invocation = await service.createInvocation({
|
||||
type: 'release-risk',
|
||||
projectKey: 'access-manage',
|
||||
promptSummary: 'Analyze production tag risk.',
|
||||
});
|
||||
|
||||
expect(invocation.status).toBe('success');
|
||||
expect(invocation.resultMarkdown).toBe('真实 LLM 运维分析结果');
|
||||
expect(llm.complete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
purpose: 'release-risk',
|
||||
promptVersion: 'devops-agent-v1',
|
||||
}),
|
||||
);
|
||||
expect(audit.record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
after: expect.objectContaining({
|
||||
mode: 'llm',
|
||||
model: 'test-model',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects non-DevOps invocation types', async () => {
|
||||
const { service } = createService();
|
||||
|
||||
await expect(
|
||||
service.createInvocation({
|
||||
type: 'general-chat',
|
||||
promptSummary: 'Tell me anything.',
|
||||
} as unknown as CreateAgentInvocationInput),
|
||||
).rejects.toBeInstanceOf(AppError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { redactSensitive } from '../common/security/redact-sensitive';
|
||||
import { AgentInvocation, AgentPurpose } from './agent.types';
|
||||
import { CreateAgentInvocationInput } from './create-agent-invocation.dto';
|
||||
import { LlmClient } from './llm.client';
|
||||
|
||||
const allowedTypes: AgentPurpose[] = [
|
||||
'release-risk',
|
||||
'failure-diagnosis',
|
||||
'runbook-qa',
|
||||
'release-note',
|
||||
'incident-review',
|
||||
];
|
||||
|
||||
const mockResults: Record<AgentPurpose, string> = {
|
||||
'release-risk':
|
||||
'发布风险摘要:当前为第一阶段 mock 分析。真实接入后会读取 Gitea ref diff、历史失败记录和项目部署策略。',
|
||||
'failure-diagnosis':
|
||||
'失败诊断摘要:当前为第一阶段 mock 分析。真实接入后会基于 Jenkins progressiveText 日志和 run steps 生成建议。',
|
||||
'runbook-qa':
|
||||
'Runbook 回答:当前仅允许围绕 DevOps 平台文档、项目 README 和白名单运维资料回答。',
|
||||
'release-note':
|
||||
'发布说明草稿:当前为 mock 草稿。真实接入后会根据 commit、PR 和 tag 信息生成。',
|
||||
'incident-review':
|
||||
'事故复盘草稿:当前为 mock 草稿。真实接入后会汇总失败 run、耗时、日志摘要和人工处理记录。',
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AgentService {
|
||||
private readonly invocations: AgentInvocation[] = [];
|
||||
|
||||
constructor(
|
||||
private readonly auditService: AuditService,
|
||||
private readonly llmClient: LlmClient,
|
||||
) {}
|
||||
|
||||
listInvocations(): AgentInvocation[] {
|
||||
return [...this.invocations].sort((left, right) =>
|
||||
right.createdAt.localeCompare(left.createdAt),
|
||||
);
|
||||
}
|
||||
|
||||
async createInvocation(input: CreateAgentInvocationInput): Promise<AgentInvocation> {
|
||||
if (!allowedTypes.includes(input.type)) {
|
||||
throw new AppError('VALIDATION_FAILED', 'Unsupported agent invocation type', 400, {
|
||||
type: input.type,
|
||||
});
|
||||
}
|
||||
|
||||
const llmHealth = this.llmClient.healthSummary();
|
||||
const baseInvocation = {
|
||||
id: `agent_${Date.now()}_${this.invocations.length + 1}`,
|
||||
runId: input.runId,
|
||||
projectKey: input.projectKey,
|
||||
type: input.type,
|
||||
promptSummary: input.promptSummary,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
let invocation: AgentInvocation;
|
||||
|
||||
if (llmHealth.status === 'ok') {
|
||||
try {
|
||||
const completion = await this.llmClient.complete({
|
||||
purpose: input.type,
|
||||
promptVersion: 'devops-agent-v1',
|
||||
systemPrompt: this.systemPromptFor(input.type),
|
||||
userPrompt: this.userPromptFor(input),
|
||||
});
|
||||
|
||||
invocation = {
|
||||
...baseInvocation,
|
||||
status: 'success',
|
||||
resultMarkdown: completion.text || mockResults[input.type],
|
||||
};
|
||||
this.recordInvocationAudit(invocation, 'llm', completion.model);
|
||||
} catch (error) {
|
||||
invocation = {
|
||||
...baseInvocation,
|
||||
status: 'failed',
|
||||
resultMarkdown:
|
||||
error instanceof Error
|
||||
? redactSensitive({ message: error.message }).message
|
||||
: 'LLM invocation failed',
|
||||
};
|
||||
this.recordInvocationAudit(invocation, 'llm_failed');
|
||||
}
|
||||
} else {
|
||||
invocation = {
|
||||
...baseInvocation,
|
||||
status: 'success',
|
||||
resultMarkdown: mockResults[input.type],
|
||||
};
|
||||
this.recordInvocationAudit(invocation, 'mock', undefined, llmHealth.message);
|
||||
}
|
||||
|
||||
this.invocations.unshift(invocation);
|
||||
return invocation;
|
||||
}
|
||||
|
||||
private recordInvocationAudit(
|
||||
invocation: AgentInvocation,
|
||||
mode: 'mock' | 'llm' | 'llm_failed',
|
||||
model?: string,
|
||||
reason?: string,
|
||||
): void {
|
||||
const action =
|
||||
invocation.status === 'failed'
|
||||
? 'AGENT_INVOCATION_FAILED'
|
||||
: 'AGENT_INVOCATION_CREATED';
|
||||
|
||||
this.auditService.record({
|
||||
action,
|
||||
resourceType: 'agent_invocation',
|
||||
resourceId: invocation.id,
|
||||
after: {
|
||||
type: invocation.type,
|
||||
runId: invocation.runId,
|
||||
projectKey: invocation.projectKey,
|
||||
mode,
|
||||
model,
|
||||
reason,
|
||||
},
|
||||
parameterDigest: {
|
||||
promptSummary: invocation.promptSummary,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private systemPromptFor(type: AgentPurpose): string {
|
||||
return [
|
||||
'你是 DevOps 运维平台内的受限 Agent,只能围绕发布、构建、Jenkins、Gitea、通知平台、BPMN 流程、回滚和运行记录回答。',
|
||||
'不要输出或猜测任何密钥、token、webhook、cookie、私钥、环境变量原文。',
|
||||
'只给出与当前项目运维目标有关的结论、风险、排查步骤或草稿。',
|
||||
`当前任务类型:${type}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
private userPromptFor(input: CreateAgentInvocationInput): string {
|
||||
return [
|
||||
`项目:${input.projectKey ?? '未指定'}`,
|
||||
`Run:${input.runId ?? '未指定'}`,
|
||||
`用户输入:${input.promptSummary}`,
|
||||
].join('\n');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export type AgentPurpose =
|
||||
| 'release-risk'
|
||||
| 'failure-diagnosis'
|
||||
| 'runbook-qa'
|
||||
| 'release-note'
|
||||
| 'incident-review';
|
||||
|
||||
export type LlmCompletionInput = {
|
||||
purpose: AgentPurpose;
|
||||
promptVersion: string;
|
||||
systemPrompt: string;
|
||||
userPrompt: string;
|
||||
operator?: string;
|
||||
};
|
||||
|
||||
export type LlmCompletionResult = {
|
||||
text: string;
|
||||
model: string;
|
||||
};
|
||||
|
||||
export type AgentInvocationStatus = 'pending' | 'running' | 'success' | 'failed';
|
||||
|
||||
export type AgentInvocation = {
|
||||
id: string;
|
||||
runId?: string;
|
||||
projectKey?: string;
|
||||
type: AgentPurpose;
|
||||
status: AgentInvocationStatus;
|
||||
promptSummary: string;
|
||||
resultMarkdown?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { z } from 'zod';
|
||||
import { AgentPurpose } from './agent.types';
|
||||
|
||||
const agentPurposeSchema = z.enum([
|
||||
'release-risk',
|
||||
'failure-diagnosis',
|
||||
'runbook-qa',
|
||||
'release-note',
|
||||
'incident-review',
|
||||
]);
|
||||
|
||||
const optionalTrimmedString = (maxLength: number) =>
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.max(maxLength)
|
||||
.optional()
|
||||
.or(z.literal('').transform(() => undefined));
|
||||
|
||||
/**
|
||||
* Agent 入口只接受 DevOps 场景参数,防止演变成通用聊天代理。
|
||||
*/
|
||||
export const createAgentInvocationSchema = z.object({
|
||||
type: agentPurposeSchema,
|
||||
runId: optionalTrimmedString(120),
|
||||
projectKey: optionalTrimmedString(80),
|
||||
promptSummary: z.string().trim().min(1).max(2000),
|
||||
});
|
||||
|
||||
export type CreateAgentInvocationInput = z.infer<
|
||||
typeof createAgentInvocationSchema
|
||||
>;
|
||||
|
||||
export class CreateAgentInvocationDto {
|
||||
@ApiProperty({
|
||||
enum: [
|
||||
'release-risk',
|
||||
'failure-diagnosis',
|
||||
'runbook-qa',
|
||||
'release-note',
|
||||
'incident-review',
|
||||
],
|
||||
example: 'failure-diagnosis',
|
||||
})
|
||||
type!: AgentPurpose;
|
||||
|
||||
@ApiPropertyOptional({ example: 'run-1052' })
|
||||
runId?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'access-manage' })
|
||||
projectKey?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'Analyze latest failed Jenkins log excerpt for access-manage test.',
|
||||
})
|
||||
promptSummary!: string;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { IntegrationRequestError, IntegrationUnavailableError } from '../common/errors/integration-error';
|
||||
import { redactSensitive } from '../common/security/redact-sensitive';
|
||||
import { EnvConfig } from '../config/env.schema';
|
||||
import { LlmCompletionInput, LlmCompletionResult } from './agent.types';
|
||||
|
||||
@Injectable()
|
||||
export class LlmClient {
|
||||
constructor(private readonly config: ConfigService<EnvConfig, true>) {}
|
||||
|
||||
healthSummary(): { status: 'ok' | 'not_configured'; message?: string } {
|
||||
const missing = this.missingConfig();
|
||||
return missing.length === 0
|
||||
? { status: 'ok' }
|
||||
: { status: 'not_configured', message: `Missing ${missing.join(', ')}` };
|
||||
}
|
||||
|
||||
async complete(input: LlmCompletionInput): Promise<LlmCompletionResult> {
|
||||
this.assertConfigured();
|
||||
const baseUrl = this.config.get('LLM_BASE_URL', { infer: true }) ?? '';
|
||||
const apiKey = this.config.get('LLM_API_KEY', { infer: true }) ?? '';
|
||||
const model = this.config.get('LLM_MODEL', { infer: true }) ?? '';
|
||||
const response = await fetch(`${baseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${apiKey}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: [
|
||||
{ role: 'system', content: input.systemPrompt },
|
||||
{ role: 'user', content: input.userPrompt },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new IntegrationRequestError('llm', 'LLM request failed', {
|
||||
status: response.status,
|
||||
purpose: input.purpose,
|
||||
request: redactSensitive(input),
|
||||
});
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as {
|
||||
choices?: Array<{ message?: { content?: string } }>;
|
||||
model?: string;
|
||||
};
|
||||
|
||||
return {
|
||||
text: payload.choices?.[0]?.message?.content ?? '',
|
||||
model: payload.model ?? model,
|
||||
};
|
||||
}
|
||||
|
||||
private assertConfigured(): void {
|
||||
const missing = this.missingConfig();
|
||||
|
||||
if (missing.length > 0) {
|
||||
throw new IntegrationUnavailableError('llm', missing);
|
||||
}
|
||||
}
|
||||
|
||||
private missingConfig(): string[] {
|
||||
const entries: Array<[string, string | undefined]> = [
|
||||
['LLM_BASE_URL', this.config.get('LLM_BASE_URL', { infer: true })],
|
||||
['LLM_API_KEY', this.config.get('LLM_API_KEY', { infer: true })],
|
||||
['LLM_MODEL', this.config.get('LLM_MODEL', { infer: true })],
|
||||
];
|
||||
|
||||
return entries.filter(([, value]) => !value).map(([key]) => key);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user