fix: complete HoloLake Agent and Forgejo desktop runtime
This commit is contained in:
parent
28f68fa9ac
commit
46bdd0ca73
15 changed files with 1217 additions and 638 deletions
|
|
@ -59,6 +59,15 @@ export interface DiffResult {
|
|||
hunks: { oldStart: number; newStart: number; lines: string[] }[];
|
||||
}
|
||||
|
||||
export interface RepositoryStatus {
|
||||
branch: string;
|
||||
head: string;
|
||||
clean: boolean;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
remote: { name: string; url: string } | null;
|
||||
}
|
||||
|
||||
// ─── Git 引擎 ───
|
||||
|
||||
export class GitEngine {
|
||||
|
|
@ -94,6 +103,69 @@ export class GitEngine {
|
|||
await fs.mkdir(this.docsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// ─── Forgejo 远端仓库 ───
|
||||
|
||||
/** 返回本地 Git 与 Forgejo 远端的真实连接状态,不探测或修改网络。 */
|
||||
async getRepositoryStatus(remoteName = 'origin'): Promise<RepositoryStatus> {
|
||||
this.assertRemoteName(remoteName);
|
||||
const [status, remotes, head] = await Promise.all([
|
||||
this.git.status(),
|
||||
this.git.getRemotes(true),
|
||||
this.git.revparse(['HEAD']).catch(() => ''),
|
||||
]);
|
||||
const remote = remotes.find(item => item.name === remoteName);
|
||||
return {
|
||||
branch: status.current || '未命名分支',
|
||||
head: head.trim(),
|
||||
clean: status.isClean(),
|
||||
ahead: status.ahead,
|
||||
behind: status.behind,
|
||||
remote: remote ? { name: remote.name, url: this.redactRemoteUrl(remote.refs.fetch) } : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 配置 Forgejo Git 远端。认证交给系统钥匙串或 SSH,不保存凭据。 */
|
||||
async configureRemote(url: string, remoteName = 'origin'): Promise<RepositoryStatus> {
|
||||
this.assertRemoteName(remoteName);
|
||||
const safeUrl = this.validateRemoteUrl(url);
|
||||
const remotes = await this.git.getRemotes(true);
|
||||
if (remotes.some(item => item.name === remoteName)) {
|
||||
await this.git.remote(['set-url', remoteName, safeUrl]);
|
||||
} else {
|
||||
await this.git.addRemote(remoteName, safeUrl);
|
||||
}
|
||||
return this.getRepositoryStatus(remoteName);
|
||||
}
|
||||
|
||||
async fetchRemote(remoteName = 'origin'): Promise<RepositoryStatus> {
|
||||
this.assertRemoteName(remoteName);
|
||||
await this.requireRemote(remoteName);
|
||||
await this.git.fetch(remoteName, ['--prune']);
|
||||
return this.getRepositoryStatus(remoteName);
|
||||
}
|
||||
|
||||
/** 只允许快进拉取,避免客户端静默制造合并提交。 */
|
||||
async pullRemote(remoteName = 'origin'): Promise<RepositoryStatus> {
|
||||
this.assertRemoteName(remoteName);
|
||||
await this.requireRemote(remoteName);
|
||||
const status = await this.git.status();
|
||||
if (!status.current) throw new Error('当前没有可拉取的分支');
|
||||
if (!status.isClean()) throw new Error('本地有未提交变更,请先保存或提交后再拉取');
|
||||
await this.git.pull(remoteName, status.current, { '--ff-only': null });
|
||||
return this.getRepositoryStatus(remoteName);
|
||||
}
|
||||
|
||||
/** 推送只能由显式 UI 操作调用,Agent 不注册此写操作。 */
|
||||
async pushRemote(remoteName = 'origin'): Promise<RepositoryStatus> {
|
||||
this.assertRemoteName(remoteName);
|
||||
await this.requireRemote(remoteName);
|
||||
const status = await this.git.status();
|
||||
if (!status.current) throw new Error('当前没有可推送的分支');
|
||||
if (!status.isClean()) throw new Error('本地有未提交变更,请先保存后再推送');
|
||||
await this.git.push(remoteName, status.current, ['--set-upstream']);
|
||||
return this.getRepositoryStatus(remoteName);
|
||||
}
|
||||
|
||||
// ─── 文档 CRUD ───
|
||||
|
||||
/** 读取文档 */
|
||||
|
|
@ -360,8 +432,44 @@ export class GitEngine {
|
|||
// ─── 辅助 ───
|
||||
|
||||
private resolvePath(docPath: string): string {
|
||||
// 安全检查:防止路径穿越
|
||||
const normalized = path.normalize(docPath).replace(/^(\.\.\/?)+/, '');
|
||||
return path.join(this.docsDir, normalized);
|
||||
const normalized = path.normalize(docPath);
|
||||
const resolved = path.resolve(this.docsDir, normalized);
|
||||
const prefix = `${path.resolve(this.docsDir)}${path.sep}`;
|
||||
if (!resolved.startsWith(prefix) || !normalized.endsWith('.md')) {
|
||||
throw new Error('文档路径无效,只允许知识库 docs 目录内的 Markdown 文件');
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private assertRemoteName(name: string): void {
|
||||
if (!/^[A-Za-z0-9._-]{1,64}$/.test(name)) throw new Error('远端名称无效');
|
||||
}
|
||||
|
||||
private validateRemoteUrl(value: string): string {
|
||||
const url = value.trim();
|
||||
if (!url) throw new Error('Forgejo 仓库地址不能为空');
|
||||
if (/^https?:\/\//i.test(url)) {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.username || parsed.password) throw new Error('仓库地址不能包含账号或密钥,请使用系统钥匙串');
|
||||
return parsed.toString().replace(/\/$/, '');
|
||||
}
|
||||
if (/^(ssh:\/\/|git@)[^\s]+$/i.test(url)) return url;
|
||||
throw new Error('仅支持 HTTPS 或 SSH Forgejo 仓库地址');
|
||||
}
|
||||
|
||||
private redactRemoteUrl(value: string): string {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return parsed.toString().replace(/\/$/, '');
|
||||
} catch {
|
||||
return value.replace(/\/\/[^/@]+@/, '//***@');
|
||||
}
|
||||
}
|
||||
|
||||
private async requireRemote(name: string): Promise<void> {
|
||||
const remotes = await this.git.getRemotes();
|
||||
if (!remotes.includes(name)) throw new Error('尚未配置 Forgejo 仓库地址');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,12 @@ const REPO_PATH = process.env.KB_REPO_PATH || path.resolve(_dirname, '../kb-data
|
|||
const app = express();
|
||||
const engine = new GitEngine(REPO_PATH);
|
||||
|
||||
app.use(cors());
|
||||
app.use(cors({
|
||||
origin(origin, callback) {
|
||||
const allowed = !origin || origin === 'null' || /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin);
|
||||
callback(allowed ? null : new Error('仅允许 HoloLake 本机界面访问'), allowed);
|
||||
},
|
||||
}));
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
|
||||
// Express v5 的 {*param} 返回数组,工具函数统一转字符串
|
||||
|
|
@ -178,6 +183,55 @@ app.get('/api/search', async (req, res) => {
|
|||
}
|
||||
});
|
||||
|
||||
// ─── Forgejo(Git 远端引擎) ───
|
||||
|
||||
app.get('/api/forgejo/status', async (_req, res) => {
|
||||
try {
|
||||
res.json({ ok: true, status: await engine.getRepositoryStatus() });
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ ok: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/forgejo/remote', async (req, res) => {
|
||||
try {
|
||||
const { url } = req.body;
|
||||
if (!url || typeof url !== 'string') {
|
||||
return res.status(400).json({ ok: false, error: 'url 必填且为字符串' });
|
||||
}
|
||||
res.json({ ok: true, status: await engine.configureRemote(url) });
|
||||
} catch (err: any) {
|
||||
res.status(400).json({ ok: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/forgejo/fetch', async (_req, res) => {
|
||||
try {
|
||||
res.json({ ok: true, status: await engine.fetchRemote() });
|
||||
} catch (err: any) {
|
||||
res.status(502).json({ ok: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/forgejo/pull', async (_req, res) => {
|
||||
try {
|
||||
res.json({ ok: true, status: await engine.pullRemote() });
|
||||
} catch (err: any) {
|
||||
res.status(409).json({ ok: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/forgejo/push', async (req, res) => {
|
||||
try {
|
||||
if (req.body?.confirm !== true) {
|
||||
return res.status(428).json({ ok: false, error: '推送需要用户明确确认' });
|
||||
}
|
||||
res.json({ ok: true, status: await engine.pushRemote() });
|
||||
} catch (err: any) {
|
||||
res.status(409).json({ ok: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Agent(人格体) ───
|
||||
|
||||
let personaAgent: PersonaAgent | null = null;
|
||||
|
|
@ -194,6 +248,7 @@ function getAgent(): PersonaAgent {
|
|||
app.get('/api/agent/status', (_req, res) => {
|
||||
const agent = getAgent();
|
||||
const def = agent.getDefinition();
|
||||
const runtime = agent.getRuntimeStatus();
|
||||
res.json({
|
||||
ok: true,
|
||||
persona: {
|
||||
|
|
@ -204,6 +259,9 @@ app.get('/api/agent/status', (_req, res) => {
|
|||
permissionMode: def.permissionMode,
|
||||
},
|
||||
conversationLength: agent.getConversation().length,
|
||||
configured: runtime.configured,
|
||||
operational: runtime.operational,
|
||||
tools: runtime.toolNames,
|
||||
engine: 'git',
|
||||
repo: REPO_PATH,
|
||||
});
|
||||
|
|
@ -247,9 +305,10 @@ async function start() {
|
|||
await engine.init();
|
||||
// 初始化人格体
|
||||
getAgent();
|
||||
app.listen(PORT, () => {
|
||||
app.listen(PORT, '127.0.0.1', () => {
|
||||
console.log(`光湖知识库 API 已启动: http://localhost:${PORT}`);
|
||||
console.log(`人格体已激活: ${personaAgent?.getDefinition().name}`);
|
||||
const runtime = personaAgent?.getRuntimeStatus();
|
||||
console.log(`人格体运行状态: ${runtime?.operational ? '已接入模型' : '等待模型配置'}`);
|
||||
console.log(`仓库路径: ${REPO_PATH}`);
|
||||
});
|
||||
}
|
||||
|
|
@ -260,4 +319,3 @@ start().catch(err => {
|
|||
});
|
||||
|
||||
export default app;
|
||||
|
||||
|
|
|
|||
|
|
@ -141,6 +141,14 @@ export class PersonaAgent {
|
|||
// ─── 内置工具注册 ───
|
||||
|
||||
private registerBuiltinTools(): void {
|
||||
// 读取 Git/Forgejo 状态;同步写操作必须由用户在界面中明确确认。
|
||||
this.tools.register({
|
||||
name: 'inspect_repository',
|
||||
description: '查看知识库本地 Git 与 Forgejo 远端的连接和同步状态(只读)',
|
||||
parameters: {},
|
||||
execute: async () => JSON.stringify(await this.git.getRepositoryStatus(), null, 2),
|
||||
});
|
||||
|
||||
// 读取知识库文档
|
||||
this.tools.register({
|
||||
name: 'read_document',
|
||||
|
|
@ -366,13 +374,10 @@ ${toolsList}
|
|||
private async callLLM(messages: Message[]): Promise<{ content: string; toolCalls?: ToolCall[] }> {
|
||||
const apiKey = process.env.OPENAI_API_KEY || process.env.HOLOLAKE_LLM_KEY || '';
|
||||
const baseUrl = process.env.HOLOLAKE_LLM_BASE || 'https://api.openai.com/v1';
|
||||
const model = this.definition.model || 'gpt-4o';
|
||||
const model = process.env.HOLOLAKE_LLM_MODEL || this.definition.model || 'gpt-4o';
|
||||
|
||||
if (!apiKey) {
|
||||
// 没有 API Key 时返回模拟回复(开发模式)
|
||||
return {
|
||||
content: `[${this.definition.name}] 收到你的消息。当前为离线模式,请配置 HOLOLAKE_LLM_KEY 环境变量启用 AI 能力。\n\n你说的: "${messages[messages.length - 1]?.content}"`,
|
||||
};
|
||||
throw new Error('Agent 尚未配置模型。请先在运行环境中设置 HOLOLAKE_LLM_KEY;当前不会伪装成已运行。');
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -384,11 +389,28 @@ ${toolsList}
|
|||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: messages.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
...(m.toolCalls ? { tool_calls: m.toolCalls } : {}),
|
||||
})),
|
||||
messages: messages.map(m => {
|
||||
if (m.role === 'assistant' && m.toolCalls?.length) {
|
||||
return {
|
||||
role: 'assistant',
|
||||
content: m.content || null,
|
||||
tool_calls: m.toolCalls.map(call => ({
|
||||
id: call.id,
|
||||
type: 'function',
|
||||
function: { name: call.name, arguments: JSON.stringify(call.arguments) },
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (m.role === 'tool' && m.toolResults?.[0]) {
|
||||
return {
|
||||
role: 'tool',
|
||||
content: m.content,
|
||||
tool_call_id: m.toolResults[0].id,
|
||||
name: m.toolResults[0].name,
|
||||
};
|
||||
}
|
||||
return { role: m.role, content: m.content };
|
||||
}),
|
||||
tools: this.tools.toSchema(),
|
||||
temperature: this.definition.temperature,
|
||||
max_tokens: this.definition.maxTokens,
|
||||
|
|
@ -396,6 +418,9 @@ ${toolsList}
|
|||
});
|
||||
|
||||
const data = await res.json() as any;
|
||||
if (!res.ok) {
|
||||
throw new Error(data?.error?.message || `模型服务返回 HTTP ${res.status}`);
|
||||
}
|
||||
const choice = data.choices?.[0]?.message;
|
||||
|
||||
if (!choice) {
|
||||
|
|
@ -413,7 +438,7 @@ ${toolsList}
|
|||
toolCalls,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return { content: `AI 调用失败: ${err.message}` };
|
||||
throw new Error(`AI 调用失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -428,7 +453,19 @@ ${toolsList}
|
|||
}
|
||||
|
||||
getDefinition(): PersonaDefinition {
|
||||
return { ...this.definition };
|
||||
return {
|
||||
...this.definition,
|
||||
model: process.env.HOLOLAKE_LLM_MODEL || this.definition.model,
|
||||
};
|
||||
}
|
||||
|
||||
getRuntimeStatus(): { configured: boolean; operational: boolean; toolNames: string[] } {
|
||||
const configured = Boolean(process.env.OPENAI_API_KEY || process.env.HOLOLAKE_LLM_KEY);
|
||||
return {
|
||||
configured,
|
||||
operational: configured,
|
||||
toolNames: this.tools.list().map(tool => tool.name),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -442,6 +479,7 @@ export function createDefaultPersona(git: GitEngine): PersonaAgent {
|
|||
role: '知识库管理者 — 负责文档的创建、整理、搜索和版本管理',
|
||||
systemPromptBase: '你是光湖知识库的人格体,一个活的知识管理 AI Agent。',
|
||||
tools: [
|
||||
'inspect_repository',
|
||||
'read_document',
|
||||
'create_document',
|
||||
'update_document',
|
||||
|
|
@ -458,4 +496,3 @@ export function createDefaultPersona(git: GitEngine): PersonaAgent {
|
|||
git
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue