fix: complete HoloLake Agent and Forgejo desktop runtime

This commit is contained in:
冰朔 2026-08-08 10:39:18 +08:00
commit 46bdd0ca73
15 changed files with 1217 additions and 638 deletions

View file

@ -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 仓库地址');
}
}

View file

@ -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) => {
}
});
// ─── ForgejoGit 远端引擎) ───
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;

View file

@ -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
);
}

View file

@ -9,6 +9,7 @@ import AgentChat from './components/AgentChat';
type View = 'editor' | 'history';
export default function App() {
const agentApiBase = window.location.protocol === 'file:' ? 'http://127.0.0.1:3890' : '';
const [tree, setTree] = useState<DocTreeNode[]>([]);
const [currentDoc, setCurrentDoc] = useState<DocContent | null>(null);
const [currentPath, setCurrentPath] = useState<string>('');
@ -181,7 +182,7 @@ export default function App() {
{/* Agent 面板 */}
{agentPanelOpen && (
<aside className="kb-agent-panel">
<AgentChat apiBase="" onDocSelect={openDoc} />
<AgentChat apiBase={agentApiBase} onDocSelect={openDoc} />
</aside>
)}
</div>

View file

@ -3,7 +3,9 @@
* Agent UI
*/
const BASE = '/api';
const BASE = typeof window !== 'undefined' && window.location.protocol === 'file:'
? 'http://127.0.0.1:3890/api'
: '/api';
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, {

View file

@ -21,6 +21,18 @@ interface AgentStatus {
role: string;
model: string;
conversationLength: number;
configured: boolean;
operational: boolean;
tools: string[];
}
interface RepositoryStatus {
branch: string;
head: string;
clean: boolean;
ahead: number;
behind: number;
remote: { name: string; url: string } | null;
}
interface Props {
@ -33,11 +45,22 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const [status, setStatus] = useState<AgentStatus | null>(null);
const [repoStatus, setRepoStatus] = useState<RepositoryStatus | null>(null);
const [remoteUrl, setRemoteUrl] = useState('');
const [syncMessage, setSyncMessage] = useState('');
const [syncing, setSyncing] = useState(false);
const [configOpen, setConfigOpen] = useState(false);
const [modelBaseUrl, setModelBaseUrl] = useState('https://api.openai.com/v1');
const [modelName, setModelName] = useState('gpt-4o');
const [modelKey, setModelKey] = useState('');
const [configMessage, setConfigMessage] = useState('');
const bottomRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
fetchStatus();
fetchRepositoryStatus();
loadModelConfig();
}, []);
useEffect(() => {
@ -54,11 +77,74 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
role: data.persona.role,
model: data.persona.model,
conversationLength: data.conversationLength,
configured: data.configured,
operational: data.operational,
tools: data.tools || [],
});
}
} catch {}
}
async function loadModelConfig() {
const bridge = (window as any).hololake?.agent;
if (!bridge) return;
try {
const config = await bridge.getConfig();
setModelBaseUrl(config.baseUrl || 'https://api.openai.com/v1');
setModelName(config.model || 'gpt-4o');
} catch {}
}
async function saveModelConfig() {
const bridge = (window as any).hololake?.agent;
if (!bridge) {
setConfigMessage('模型安全配置只在桌面 App 中提供');
return;
}
try {
await bridge.saveConfig({ baseUrl: modelBaseUrl, model: modelName, apiKey: modelKey || undefined });
setModelKey('');
setConfigMessage('已保存到 macOS 加密存储');
await fetchStatus();
} catch (err: any) {
setConfigMessage(err.message);
}
}
async function fetchRepositoryStatus() {
try {
const res = await fetch(`${apiBase}/api/forgejo/status`);
const data = await res.json();
if (data.ok) {
setRepoStatus(data.status);
if (data.status.remote?.url) setRemoteUrl(data.status.remote.url);
}
} catch {}
}
async function runForgejoAction(action: 'configure' | 'fetch' | 'pull' | 'push') {
if (syncing) return;
if (action === 'push' && !confirm('确认把当前知识库提交推送到已配置的 Forgejo 仓库?')) return;
setSyncing(true);
setSyncMessage('');
try {
const endpoint = action === 'configure' ? 'remote' : action;
const res = await fetch(`${apiBase}/api/forgejo/${endpoint}`, {
method: action === 'configure' ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(action === 'configure' ? { url: remoteUrl } : { confirm: action === 'push' }),
});
const data = await res.json();
if (!data.ok) throw new Error(data.error || '操作失败');
setRepoStatus(data.status);
setSyncMessage(action === 'configure' ? 'Forgejo 已连接' : `${action} 已完成`);
} catch (err: any) {
setSyncMessage(err.message);
} finally {
setSyncing(false);
}
}
async function sendMessage() {
const text = input.trim();
if (!text || sending) return;
@ -135,19 +221,61 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
</div>
<div className="agent-actions">
<span className="agent-model">{status?.model || 'offline'}</span>
<button className="btn-config" onClick={() => setConfigOpen(!configOpen)} title="配置模型"></button>
<button className="btn-clear" onClick={clearConversation} title="清空对话">
</button>
</div>
</div>
<div className="runtime-status">
<div className="runtime-row">
<span className={`runtime-dot ${status?.operational ? 'online' : 'waiting'}`} />
<span>{status?.operational ? 'Agent 已接入模型' : 'Agent 等待模型配置'}</span>
<span className="runtime-tools">{status?.tools?.length || 0} </span>
</div>
{configOpen && (
<div className="model-config">
<input value={modelBaseUrl} onChange={e => setModelBaseUrl(e.target.value)} placeholder="模型服务地址" />
<input value={modelName} onChange={e => setModelName(e.target.value)} placeholder="模型名称" />
<input type="password" value={modelKey} onChange={e => setModelKey(e.target.value)} placeholder={status?.configured ? '留空则保留现有密钥' : '模型密钥'} />
<button onClick={saveModelConfig}></button>
{configMessage && <div className="forgejo-message">{configMessage}</div>}
</div>
)}
<div className="forgejo-status">
<div className="forgejo-title">
<strong>Forgejo </strong>
<span>{repoStatus?.remote ? `${repoStatus.branch} · ${repoStatus.head.slice(0, 7)}` : '尚未连接远端'}</span>
</div>
<input
className="forgejo-url"
value={remoteUrl}
onChange={e => setRemoteUrl(e.target.value)}
placeholder="HTTPS 或 SSH Forgejo 仓库地址"
/>
<div className="forgejo-actions">
<button onClick={() => runForgejoAction('configure')} disabled={syncing || !remoteUrl.trim()}></button>
<button onClick={() => runForgejoAction('fetch')} disabled={syncing || !repoStatus?.remote}></button>
<button onClick={() => runForgejoAction('pull')} disabled={syncing || !repoStatus?.remote}></button>
<button onClick={() => runForgejoAction('push')} disabled={syncing || !repoStatus?.remote}></button>
</div>
{repoStatus?.remote && (
<div className="forgejo-detail">
{repoStatus.clean ? '本地已提交' : '本地有未提交内容'} · {repoStatus.ahead} / {repoStatus.behind}
</div>
)}
{syncMessage && <div className="forgejo-message">{syncMessage}</div>}
</div>
</div>
{/* 对话区域 */}
<div className="agent-messages">
{messages.length === 0 && (
<div className="agent-welcome">
<div className="welcome-icon">🌊</div>
<h2></h2>
<p> AI Agent Git </p>
<p>{status?.operational ? '我是知识库的 AI Agent可以调用工具管理文档。' : '知识库功能已运行Agent 需要配置模型后才会回应,不会用模拟回复冒充。'}</p>
<p className="welcome-hint"></p>
<div className="welcome-suggestions">
<button onClick={() => { setInput('帮我列出所有文档'); inputRef.current?.focus(); }}>
@ -232,18 +360,18 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
rows={1}
disabled={sending}
disabled={sending || !status?.operational}
/>
<button
className="btn-send"
onClick={sendMessage}
disabled={sending || !input.trim()}
disabled={sending || !input.trim() || !status?.operational}
>
{sending ? '⏳' : '↑'}
</button>
</div>
<div className="agent-hint">
Enter · Shift+Enter · Agent
{status?.operational ? 'Enter 发送 · 写操作由本地 Git 留痕 · Forgejo 推送需确认' : 'Agent 尚未接入模型;知识库与 Forgejo 功能仍可独立使用'}
</div>
</div>
</div>

View file

@ -45,6 +45,7 @@ body {
}
.kb-header {
-webkit-app-region: drag;
height: var(--kb-header-height);
display: flex;
align-items: center;
@ -55,6 +56,12 @@ body {
flex-shrink: 0;
}
.kb-header button,
.kb-header input,
.kb-header a {
-webkit-app-region: no-drag;
}
.kb-header-left {
display: flex;
align-items: center;
@ -838,7 +845,8 @@ body {
font-family: var(--kb-font-mono);
}
.btn-clear {
.btn-clear,
.btn-config {
background: none;
border: none;
color: var(--kb-text-muted);
@ -849,11 +857,108 @@ body {
transition: all 0.15s;
}
.btn-clear:hover {
.btn-clear:hover,
.btn-config:hover {
background: var(--kb-bg-tertiary);
color: var(--kb-danger);
}
.model-config {
display: grid;
grid-template-columns: 1fr 92px;
gap: 6px;
margin-top: 9px;
padding: 9px;
border: 1px solid var(--kb-border);
border-radius: 8px;
background: var(--kb-bg);
}
.model-config input {
min-width: 0;
border: 1px solid var(--kb-border);
border-radius: 5px;
padding: 6px 7px;
background: var(--kb-bg-secondary);
color: var(--kb-text);
font-size: 10px;
}
.model-config input:first-child,
.model-config input[type="password"],
.model-config .forgejo-message { grid-column: 1 / -1; }
.model-config button {
border: 1px solid var(--kb-accent);
border-radius: 5px;
background: rgba(88, 166, 255, .12);
color: var(--kb-text);
cursor: pointer;
}
.runtime-status {
padding: 10px 14px;
border-bottom: 1px solid var(--kb-border);
background: var(--kb-bg-secondary);
font-size: 11px;
}
.runtime-row,
.forgejo-title,
.forgejo-actions {
display: flex;
align-items: center;
gap: 7px;
}
.runtime-dot {
width: 7px;
height: 7px;
border-radius: 50%;
}
.runtime-dot.online { background: #3fb950; box-shadow: 0 0 7px rgba(63, 185, 80, .55); }
.runtime-dot.waiting { background: #d29922; }
.runtime-tools { margin-left: auto; color: var(--kb-text-muted); }
.forgejo-status {
margin-top: 9px;
padding: 9px;
border: 1px solid var(--kb-border);
border-radius: 8px;
background: var(--kb-bg);
}
.forgejo-title { justify-content: space-between; margin-bottom: 7px; }
.forgejo-title span,
.forgejo-detail { color: var(--kb-text-muted); }
.forgejo-url {
width: 100%;
box-sizing: border-box;
border: 1px solid var(--kb-border);
border-radius: 6px;
padding: 7px 8px;
background: var(--kb-bg-secondary);
color: var(--kb-text);
font-size: 11px;
}
.forgejo-actions { margin-top: 7px; }
.forgejo-actions button {
flex: 1;
border: 1px solid var(--kb-border);
border-radius: 5px;
padding: 5px 3px;
background: var(--kb-bg-tertiary);
color: var(--kb-text);
cursor: pointer;
font-size: 10px;
}
.forgejo-actions button:disabled { opacity: .4; cursor: not-allowed; }
.forgejo-detail { margin-top: 6px; }
.forgejo-message { margin-top: 5px; color: var(--kb-accent); word-break: break-word; }
/* ─── 对话区域 ─── */
.agent-messages {