Files
devops-platform-api/src/agent/agent-tools.service.ts
T
湛兮 a29066f343 feat: 接入精确回滚与确认后执行的运维操作
- 生成绑定操作者与 SHA 的签名计划,确认后复用发布、取消和重试服务,限制过期、并发与重复提交。

- 从真实历史构建核实回滚目标,升级纳管 Jenkins 任务以锁定提交并保留原参数选择器。

- Agent 只准备操作卡片,不直接执行;补充权限、回放、历史令牌与实际部署参数回归。
2026-10-28 10:18:01 +08:00

549 lines
19 KiB
TypeScript

import { Injectable, Optional } from '@nestjs/common';
import { OperationsService } from '../operations/operations.service';
import {
OperationPlan,
prepareOperationSchema,
} from '../operations/operation.dto';
import { z } from 'zod';
import { AuthService } from '../auth/auth.service';
import { AuthenticatedUser } from '../auth/auth.types';
import { AppError } from '../common/errors/app-error';
import { redactSensitive } from '../common/security/redact-sensitive';
import { DeployRunRepository } from '../deploy-runs/deploy-run.repository';
import { DeployRunSummary } from '../deploy-runs/deploy-run.types';
import { JenkinsClient } from '../integrations/jenkins/jenkins.client';
import { ProjectsService } from '../projects/projects.service';
import { ProjectSummary } from '../projects/project.types';
import {
AGENT_LIMITS,
AgentSource,
AgentToolDefinition,
AgentToolTrace,
} from './agent-question.types';
const listSchema = z
.object({
projectKey: z.string().max(80).optional(),
environment: z.enum(['test', 'production']).optional(),
status: z
.enum(['pending', 'queued', 'running', 'success', 'failed', 'canceled'])
.optional(),
since: z.string().datetime({ offset: true }).optional(),
until: z.string().datetime({ offset: true }).optional(),
limit: z.number().int().min(1).max(10).default(8),
offset: z.number().int().min(0).max(200).default(0),
})
.strict()
.refine(
(input) =>
!input.since ||
!input.until ||
Date.parse(input.since) < Date.parse(input.until),
'开始时间必须早于结束时间',
);
const runSchema = z.object({ runId: z.string().min(1).max(120) }).strict();
const logSchema = runSchema
.extend({ start: z.number().int().min(0).max(100_000_000).default(0) })
.strict();
const buildSchema = z
.object({
projectKey: z.string().min(1).max(80),
environment: z.enum(['test', 'production']),
})
.strict();
const projectSchema = z
.object({ keyword: z.string().max(80).optional() })
.strict();
const object = (
properties: Record<string, unknown>,
required: string[] = [],
) => ({ type: 'object', properties, required, additionalProperties: false });
const string = { type: 'string' };
export const agentToolDefinitions: AgentToolDefinition[] = [
{
type: 'function',
function: {
name: 'prepare_operation',
description:
'用户明确要求发布、回滚、取消、重试时,生成待确认的操作计划。仅准备,不执行。用户必须在界面点确认执行。部署/默认回滚必须明确项目与环境,不得猜测环境;指定历史发布可用 runId。生产操作也只生成计划。没有返回计划就不能声称已准备或已执行。',
parameters: object(
{
kind: {
type: 'string',
enum: ['deploy', 'rollback', 'cancel', 'retry'],
},
projectKey: string,
environment: { type: 'string', enum: ['test', 'production'] },
ref: string,
runId: string,
},
['kind'],
),
},
},
{
type: 'function',
function: {
name: 'recent_builds',
description:
'按指定项目和环境直接只读查询 Jenkins 最近5次真实构建,适用于确认实时构建或平台只连接本地开发数据。构建成功不等于线上服务健康。',
parameters: object(
{
projectKey: string,
environment: { type: 'string', enum: ['test', 'production'] },
},
['projectKey', 'environment'],
),
},
},
{
type: 'function',
function: {
name: 'list_projects',
description:
'查询当前账号可访问的真实项目、分支与环境。主要项目如无重要性标记应说明当前纳管项目,不得虚构优先级。最多返回30项。',
parameters: object({ keyword: string }),
},
},
{
type: 'function',
function: {
name: 'list_deployments',
description:
'按项目、环境、状态与创建时间筛选真实部署记录,按创建时间倒序。每页最多10条;返回 hasMore 和 nextOffset,不能把一页当作全部历史。since/until 必须是带时区 ISO8601。',
parameters: object({
projectKey: string,
environment: { type: 'string', enum: ['test', 'production'] },
status: {
type: 'string',
enum: [
'pending',
'queued',
'running',
'success',
'failed',
'canceled',
],
},
since: string,
until: string,
limit: { type: 'integer', minimum: 1, maximum: 10 },
offset: { type: 'integer', minimum: 0, maximum: 200 },
}),
},
},
{
type: 'function',
function: {
name: 'get_deployment',
description:
'查询指定部署的真实状态、失败原因和步骤。不会同步或改变部署状态。runId 必须来自已查询的记录或用户明确提供。',
parameters: object({ runId: string }, ['runId']),
},
},
{
type: 'function',
function: {
name: 'read_deployment_log',
description:
'仅在失败排查确需日志时读取指定构建的有界日志片段,最多16KiB,默认从头读取,可指定字节 start。不等于完整日志或尾部。不能用于发布、取消或重试。',
parameters: object(
{ runId: string, start: { type: 'integer', minimum: 0 } },
['runId'],
),
},
},
];
export type AgentToolSession = {
operator: AuthenticatedUser;
projects: ProjectSummary[];
sources: Map<string, AgentSource>;
traces: AgentToolTrace[];
signal: AbortSignal;
plans: OperationPlan[];
};
@Injectable()
export class AgentToolsService {
constructor(
private readonly projectsService: ProjectsService,
private readonly repository: DeployRunRepository,
private readonly auth: AuthService,
private readonly jenkins: JenkinsClient,
@Optional() private readonly operations?: OperationsService,
) {}
dataSource() {
return this.repository.agentDataSource();
}
async createSession(
operator: AuthenticatedUser,
signal: AbortSignal,
projectKey?: string,
runId?: string,
): Promise<AgentToolSession> {
let projects = await this.projectsService.listProjects(operator);
if (projectKey) {
await this.auth.requireProjectPermission(operator, projectKey, 'read');
projects = projects.filter((project) => project.key === projectKey);
if (!projects.length)
throw new AppError(
'RESOURCE_NOT_FOUND',
'指定项目不存在或不可访问',
404,
);
}
if (projects.length > 100)
throw new AppError(
'VALIDATION_FAILED',
'项目范围过大,请选择一个具体项目',
400,
);
const session: AgentToolSession = {
operator,
projects,
signal,
sources: new Map(),
traces: [],
plans: [],
};
if (runId) await this.requireRun(session, runId);
return session;
}
async execute(
session: AgentToolSession,
name: string,
argumentsText: string,
): Promise<string> {
try {
session.signal.throwIfAborted();
const args: unknown = JSON.parse(argumentsText);
let result: unknown;
if (name === 'prepare_operation') {
if (!this.operations)
throw new AppError('CONFIG_MISSING', '操作服务未启用', 503);
if (session.plans.length >= 2)
throw new AppError(
'VALIDATION_FAILED',
'一次提问最多准备两个操作计划',
400,
);
const input = prepareOperationSchema.parse(args);
if (
'projectKey' in input &&
input.projectKey &&
!session.projects.some((project) => project.key === input.projectKey)
)
throw new AppError('FORBIDDEN', '项目不在当前查询范围', 403);
if ('runId' in input && input.runId)
await this.requireRun(session, input.runId);
const plan = await this.operations.prepare(input, session.operator);
if (
!session.projects.some((project) => project.key === plan.projectKey)
)
throw new AppError('FORBIDDEN', '项目不在当前查询范围', 403);
session.plans.push(plan);
result = {
planId: plan.id,
kind: plan.kind,
projectKey: plan.projectKey,
environment: plan.environment,
ref: plan.ref,
commit: plan.commit,
expiresAt: plan.expiresAt,
status: 'awaiting-user-confirmation',
message: '计划已准备,尚未执行;请用户点击操作卡片的确认执行按钮。',
};
} else if (name === 'list_projects') {
const input = projectSchema.parse(args);
const filtered = session.projects.filter(
(project) =>
!input.keyword ||
`${project.key} ${project.name}`
.toLowerCase()
.includes(input.keyword.toLowerCase()),
);
result = {
checkedAt: new Date().toISOString(),
totalAccessible: filtered.length,
truncated: filtered.length > 30,
projects: filtered.slice(0, 30).map((project) => ({
sourceId: this.source(
session,
'project',
project.key,
project.name,
),
key: project.key,
name: project.name.slice(0, 120),
defaultBranch: project.defaultBranch,
status: project.status,
environments: project.environments
.slice(0, 5)
.map((environment) => ({
name: environment.name,
releasePolicy: environment.releasePolicy,
})),
})),
};
} else if (name === 'list_deployments') {
const input = listSchema.parse(args);
const keys = session.projects.map((project) => project.key);
if (input.projectKey && !keys.includes(input.projectKey))
throw new AppError('FORBIDDEN', '项目不在当前授权范围内', 403);
const page = await this.repository.findAgentRuns({
...input,
projectKeys: input.projectKey ? [input.projectKey] : keys,
});
result = {
checkedAt: new Date().toISOString(),
since: input.since,
until: input.until,
hasMore: page.hasMore,
nextOffset: page.hasMore ? input.offset + page.runs.length : null,
coverage:
'平台已记录的部署;状态为最后同步结果,不等于服务实时可用性。',
runs: page.runs.map((run) => this.runSummary(session, run)),
};
} else if (name === 'recent_builds') {
const input = buildSchema.parse(args);
const project = session.projects.find(
(project) => project.key === input.projectKey,
);
if (!project)
throw new AppError('FORBIDDEN', '项目不在当前授权范围内', 403);
await this.auth.requireProjectPermission(
session.operator,
project.key,
'read',
);
const environment = project.environments.find(
(environment) => environment.name === input.environment,
);
if (!environment)
throw new AppError('RESOURCE_NOT_FOUND', '项目没有该发布环境', 404);
const builds = await this.jenkins.getBoundedRecentBuilds(
environment.jenkinsJobPath,
AbortSignal.any([session.signal, AbortSignal.timeout(8000)]),
);
const localTime = (value: string) =>
new Intl.DateTimeFormat('sv-SE', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(new Date(value));
const todayInShanghai = localTime(new Date().toISOString()).slice(
0,
10,
);
result = {
checkedAt: new Date().toISOString(),
timeZone: 'Asia/Shanghai',
todayInShanghai,
startedTodayInReturnedBuilds: builds.filter(
(build) =>
build.startedAt &&
localTime(build.startedAt).slice(0, 10) === todayInShanghai,
).length,
source: 'jenkins-live',
projectKey: project.key,
environment: environment.name,
coverage:
'该任务最近5次构建;今日数量仅指返回样本,不等于今日总量;不代表所有项目或服务健康。',
builds: builds.map((build) => {
const key = `build:${project.key}:${environment.name}:${build.number}`;
const id = `S${session.sources.size + 1}`;
if (
!session.sources.has(key) &&
session.sources.size < AGENT_LIMITS.sources
)
session.sources.set(key, {
id,
kind: 'build',
projectKey: project.key,
label: `${project.key} · ${environment.name} · #${build.number}`,
checkedAt: new Date().toISOString(),
url: build.url,
});
return {
sourceId: session.sources.get(key)?.id,
...build,
startedAtLocal: build.startedAt
? localTime(build.startedAt)
: undefined,
startedToday: Boolean(
build.startedAt &&
localTime(build.startedAt).slice(0, 10) === todayInShanghai,
),
};
}),
};
} else if (name === 'get_deployment' || name === 'read_deployment_log') {
const input =
name === 'get_deployment'
? runSchema.parse(args)
: logSchema.parse(args);
const run = await this.requireRun(session, input.runId);
if (name === 'get_deployment')
result = {
...this.runSummary(session, run),
steps: run.steps.slice(0, 12).map((step) => ({
name: step.name,
status: step.status,
message: step.message,
errorSummary: step.errorSummary,
})),
};
else {
if (run.jenkinsBuildNumber === undefined)
throw new AppError(
'VALIDATION_FAILED',
'该部署尚未关联构建,无法读取日志',
400,
);
const project = session.projects.find(
(project) => project.key === run.projectKey,
)!;
const environment = project.environments.find(
(environment) => environment.name === run.environment,
);
if (!environment)
throw new AppError('RESOURCE_NOT_FOUND', '发布环境不存在', 404);
const start = 'start' in input ? Number(input.start) : 0;
const log = await this.jenkins.getBoundedLog(
environment.jenkinsJobPath,
run.jenkinsBuildNumber,
start,
AGENT_LIMITS.logBytes,
AbortSignal.any([session.signal, AbortSignal.timeout(8000)]),
);
const cleanText = log.text.replace(
new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, 'g'),
'',
);
result = {
...this.runSummary(session, run),
start,
truncated: log.truncated,
hasMore: log.hasMore,
text: redactSensitive({ text: cleanText }).text.slice(0, 5000),
coverage: '仅当前构建的日志片段,不保证完整或包含根因。',
};
}
} else
throw new AppError(
'VALIDATION_FAILED',
'未知工具;仅提供查询和准备待确认的操作计划',
400,
);
const text = redactSensitive({ text: JSON.stringify(result) }).text;
if (text.length > AGENT_LIMITS.toolChars)
throw new AppError(
'VALIDATION_FAILED',
'查询结果过长,请减少 limit 或缩小项目范围',
400,
);
session.traces.push({
name,
status: 'success',
summary:
(
{
prepare_operation: '准备待确认的操作计划(尚未执行)',
list_projects: '查询项目清单',
list_deployments: '查询部署记录',
get_deployment: '读取部署详情',
read_deployment_log: '读取构建日志片段',
recent_builds: '查询 Jenkins 实时构建',
} as Record<string, string>
)[name] || '只读查询',
});
return text;
} catch (error) {
const message =
error instanceof z.ZodError || error instanceof SyntaxError
? '工具参数不合法,请按定义重新查询'
: error instanceof AppError
? error.message
: session.signal.aborted
? '查询超时'
: '查询失败,暂时无法确认数据';
session.traces.push({
name: name.slice(0, 80),
status: 'failed',
summary: message,
});
return JSON.stringify({ error: message });
}
}
private async requireRun(
session: AgentToolSession,
id: string,
): Promise<DeployRunSummary> {
const run = await this.repository.findAgentRun(id);
if (
!run ||
!session.projects.some((project) => project.key === run.projectKey)
)
throw new AppError('FORBIDDEN', '部署不存在或不在当前授权范围内', 403);
await this.auth.requireProjectPermission(
session.operator,
run.projectKey,
'read',
);
return run;
}
private runSummary(session: AgentToolSession, run: DeployRunSummary) {
return {
sourceId: this.source(
session,
'deployment',
run.projectKey,
`${run.projectKey} · ${run.environment} · ${run.ref}`,
run.id,
),
id: run.id,
projectKey: run.projectKey,
environment: run.environment,
ref: run.ref,
status: run.status,
operator: run.operator,
createdAt: run.createdAt,
startedAt: run.startedAt,
finishedAt: run.finishedAt,
failureSummary: run.failureSummary,
};
}
private source(
session: AgentToolSession,
kind: AgentSource['kind'],
projectKey: string,
label: string,
runId?: string,
): string {
const key = `${kind}:${runId ?? projectKey}`;
const existing = session.sources.get(key);
if (existing) return existing.id;
if (session.sources.size >= AGENT_LIMITS.sources)
return '来源数量达到上限,请在发布记录中继续查看';
const source: AgentSource = {
id: `S${session.sources.size + 1}`,
kind,
projectKey,
runId,
label: redactSensitive({ text: label }).text.slice(0, 180),
checkedAt: new Date().toISOString(),
};
session.sources.set(key, source);
return source.id;
}
}