feat(agent): 接入有界只读运维查询

- 使用真实模型工具调用查询项目、部署与 Jenkins 构建和日志,返回可信来源。

- 限制并发、调用轮次、日志及响应大小,隔离个人历史并脱敏审计。

- 增加只读查询和协议回归,不新增依赖、进程或数据库迁移。
This commit is contained in:
湛兮
2026-10-27 23:54:01 +08:00
parent 23a75207c6
commit bf9a229804
20 changed files with 1888 additions and 45 deletions
+450
View File
@@ -0,0 +1,450 @@
import { Injectable } from '@nestjs/common';
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: '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;
};
@Injectable()
export class AgentToolsService {
constructor(
private readonly projectsService: ProjectsService,
private readonly repository: DeployRunRepository,
private readonly auth: AuthService,
private readonly jenkins: JenkinsClient,
) {}
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: [],
};
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 === '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)]),
);
result = {
checkedAt: new Date().toISOString(),
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 };
}),
};
} 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:
(
{
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;
}
}