Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797

Daniel23b76ca32de6
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts
index 8f6d69a65a..7daaf85aa4 100644
--- a/app/src/layout/dock/AgentChat.ts
+++ b/app/src/layout/dock/AgentChat.ts
@@ -203,7 +203,7 @@ export class AgentChat extends Model {
this.sessionCreatedAt = session.createdAt || Date.now();
this.sessionTitle = session.title;
this.entries = (session.entries && session.entries.length > 0) ? session.entries as any as SessionEntry[] : [];
- this.hasTitled = true;
+ this.hasTitled = session.titled !== false;
this.sessionPromptTokens = session.promptTokens || 0;
this.sessionCompletionTokens = session.completionTokens || 0;
this.sessionTotalDuration = session.totalDuration || 0;
@@ -350,6 +350,7 @@ export class AgentChat extends Model {
const session: AgentSession = {
id: this.sessionId,
title: this.sessionTitle,
+ titled: this.hasTitled,
entries: this.entries.slice(),
promptTokens: this.sessionPromptTokens,
completionTokens: this.sessionCompletionTokens,
@@ -376,7 +377,7 @@ export class AgentChat extends Model {
this.sessionCreatedAt = session.createdAt || Date.now();
this.sessionTitle = session.title;
this.entries = (session.entries && session.entries.length > 0) ? session.entries as any as SessionEntry[] : [];
- this.hasTitled = true;
+ this.hasTitled = session.titled !== false;
this.currentAIElement = null;
this.currentContent = "";
this.fullContent = "";
diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.ts
index 23a475a077..6a0792fcec 100644
--- a/app/src/layout/dock/SessionStore.ts
+++ b/app/src/layout/dock/SessionStore.ts
@@ -1,7 +1,6 @@
import {fetchSyncPost} from "../../util/fetch";
const SESSIONS_DIR = "data/storage/ai/agent/sessions/";
-const SESSIONS_INDEX = SESSIONS_DIR + "index.json";
interface SessionIndexItem {
id: string;
@@ -14,6 +13,7 @@ interface SessionIndexItem {
export interface AgentSession {
id: string;
title: string;
+ titled?: boolean;
model?: string;
entries?: Array<{
type: "user" | "thinking" | "assistant";
@@ -38,7 +38,6 @@ function newSessionId(): string {
async function readJsonFile(path: string): Promise<any | null> {
try {
const r = await fetchSyncPost("/api/file/getFile", {path: path}) as any;
- // getFile 返回的是文件内容本身,不是 {code, data} 包装
if (!r) { return null; }
return r;
} catch (e) {
@@ -47,7 +46,7 @@ async function readJsonFile(path: string): Promise<any | null> {
}
async function writeJsonFile(path: string, data: any): Promise<void> {
- const content = JSON.stringify(data, null, 2);
+ const content = JSON.stringify(data, null, "\t");
const fileName = path.split("/").pop() || "file.json";
const file = new File([new Blob([content], {type: "application/json"})], fileName);
const formData = new FormData();
@@ -57,100 +56,57 @@ async function writeJsonFile(path: string, data: any): Promise<void> {
await fetchSyncPost("/api/file/putFile", formData);
}
-async function ensureDir(): Promise<SessionIndexItem[]> {
- const idx = await readJsonFile(SESSIONS_INDEX);
- if (idx && Array.isArray(idx)) { return idx; }
-
+async function readDir(path: string): Promise<Array<{name: string; isDir: boolean; updated: number}> | null> {
try {
- const r = await fetchSyncPost("/api/file/readDir", {path: SESSIONS_DIR}) as any;
- if (r && r.code === 0) {
- await rebuildIndex();
- const newIdx = await readJsonFile(SESSIONS_INDEX);
- return Array.isArray(newIdx) ? newIdx : [];
- }
- } catch (e) {
- // readDir 失败,继续尝试创建
- }
+ const r = await fetchSyncPost("/api/file/readDir", {path}) as any;
+ if (r && r.code === 0 && r.data) { return r.data; }
+ } catch (e) { /* readDir failed, directory may not exist */ }
+ return null;
+}
- await writeJsonFile(SESSIONS_INDEX, []);
- return [];
+function getSessionFilePath(id: string): string {
+ return SESSIONS_DIR + id + "/session.json";
}
-async function rebuildIndex(): Promise<void> {
- try {
- const r = await fetchSyncPost("/api/file/readDir", {path: SESSIONS_DIR}) as any;
- if (!r || r.code !== 0 || !r.data) {
- await writeJsonFile(SESSIONS_INDEX, []);
- return;
- }
- const entries = r.data as Array<{name: string; updated: number}>;
+export const SessionStore = {
+ async init(): Promise<SessionIndexItem[]> {
+ return await this.list();
+ },
+
+ async list(): Promise<SessionIndexItem[]> {
+ const entries = await readDir(SESSIONS_DIR);
+ if (!entries) { return []; }
+
const list: SessionIndexItem[] = [];
for (let i = 0; i < entries.length; i++) {
- const name = entries[i].name;
- if (name === "index.json" || !name.endsWith(".json")) { continue; }
- const id = name.replace(".json", "");
- const session = await readJsonFile(SESSIONS_DIR + name);
- if (session && session.id && (session.entries || session.messages)) {
+ const entry = entries[i];
+ if (!entry.isDir) { continue; }
+ const session = await readJsonFile(getSessionFilePath(entry.name));
+ if (session && session.id) {
list.push({
- id: id,
+ id: session.id,
title: session.title || "AI Agent",
model: session.model || "",
- createdAt: session.createdAt || entries[i].updated || Date.now(),
- updatedAt: session.updatedAt || entries[i].updated || Date.now(),
+ createdAt: session.createdAt || entry.updated || Date.now(),
+ updatedAt: session.updatedAt || entry.updated || Date.now(),
});
}
}
- await writeJsonFile(SESSIONS_INDEX, list);
- } catch (e) {
- console.warn("[SessionStore] rebuildIndex failed:", e);
- await writeJsonFile(SESSIONS_INDEX, []);
- }
-}
-
-async function writeIndex(list: SessionIndexItem[]): Promise<void> {
- await writeJsonFile(SESSIONS_INDEX, list);
-}
-
-export const SessionStore = {
- async init(): Promise<SessionIndexItem[]> {
- return await ensureDir();
- },
-
- async list(): Promise<SessionIndexItem[]> {
- const idx = await readJsonFile(SESSIONS_INDEX);
- return Array.isArray(idx) ? idx : [];
+ list.sort((a, b) => b.updatedAt - a.updatedAt);
+ return list;
},
async load(id: string): Promise<AgentSession | null> {
- return await readJsonFile(SESSIONS_DIR + id + ".json");
+ return await readJsonFile(getSessionFilePath(id));
},
async save(session: AgentSession): Promise<void> {
session.updatedAt = Date.now();
- await writeJsonFile(SESSIONS_DIR + session.id + ".json", session);
-
- const list = await this.list();
- let foundIdx = -1;
- for (let i = 0; i < list.length; i++) {
- if (list[i].id === session.id) {
- list[i].title = session.title;
- list[i].updatedAt = session.updatedAt;
- list[i].model = session.model;
- foundIdx = i;
- break;
- }
- }
- if (foundIdx < 0) {
- list.unshift({id: session.id, title: session.title, model: session.model, createdAt: session.createdAt, updatedAt: session.updatedAt});
- }
- await writeIndex(list);
+ await writeJsonFile(getSessionFilePath(session.id), session);
},
async remove(id: string): Promise<void> {
- await fetchSyncPost("/api/file/removeFile", {path: SESSIONS_DIR + id + ".json"});
- let list = await this.list();
- list = list.filter(function (item: any) { return item.id !== id; });
- await writeIndex(list);
+ await fetchSyncPost("/api/file/removeFile", {path: SESSIONS_DIR + id + "/"});
},
async rename(id: string, newTitle: string): Promise<void> {
@@ -160,5 +116,5 @@ export const SessionStore = {
await this.save(session);
},
- newSessionId: newSessionId,
+ newSessionId,
};
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 9231508c1b..f9ff8a5576 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -24,11 +24,14 @@ import (
"io"
"math/rand/v2"
"os"
+
"path/filepath"
"strings"
"sync"
"time"
+ "github.com/88250/gulu"
+
"github.com/sashabaranov/go-openai"
"github.com/siyuan-note/filelock"
mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client"
@@ -160,29 +163,30 @@ type Reference struct {
}
type checkpointThinkingStep struct {
- Reasoning string `json:"reasoning"`
- Text string `json:"text"`
- ToolCalls []checkpointBriefTC `json:"toolCalls"`
- ReasoningContent string `json:"reasoningContent"`
+ Reasoning string `json:"reasoning"`
+ Text string `json:"text"`
+ ToolCalls []checkpointBriefTC `json:"toolCalls"`
+ ReasoningContent string `json:"reasoningContent"`
}
type checkpointBriefTC struct {
- Name string `json:"name"`
- Result string `json:"result,omitempty"`
+ Name string `json:"name"`
+ Result string `json:"result,omitempty"`
}
type agentCheckpoint struct {
- ID string `json:"id"`
- Title string `json:"title"`
- Messages []AgentMessage `json:"messages"`
- Entries []json.RawMessage `json:"entries,omitempty"`
- PromptTokens int `json:"promptTokens"`
- CompletionTokens int `json:"completionTokens"`
- TotalDuration int64 `json:"totalDuration"`
- CreatedAt int64 `json:"createdAt"`
- UpdatedAt int64 `json:"updatedAt"`
- MessageHistory []string `json:"messageHistory,omitempty"`
- ThinkingSteps []checkpointThinkingStep `json:"thinkingSteps,omitempty"`
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Titled bool `json:"titled"`
+ Messages []AgentMessage `json:"messages"`
+ Entries []json.RawMessage `json:"entries,omitempty"`
+ PromptTokens int `json:"promptTokens"`
+ CompletionTokens int `json:"completionTokens"`
+ TotalDuration int64 `json:"totalDuration"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+ MessageHistory []string `json:"messageHistory,omitempty"`
+ ThinkingSteps []checkpointThinkingStep `json:"thinkingSteps,omitempty"`
}
func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, history []UserMessage, language string, references []Reference, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {
@@ -660,15 +664,18 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,
UpdatedAt: time.Now().UnixMilli(),
}
- dir := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions")
+ dir := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", sessionID)
_ = os.MkdirAll(dir, 0755)
- path := filepath.Join(dir, sessionID+".json")
+ path := filepath.Join(dir, "session.json")
existing, err := os.ReadFile(path)
if err == nil {
var old agentCheckpoint
- if json.Unmarshal(existing, &old) == nil && old.Title != "" && old.Title != "AI Agent" {
- cp.Title = old.Title
+ if gulu.JSON.UnmarshalJSON(existing, &old) == nil {
+ if old.Titled {
+ cp.Title = old.Title
+ cp.Titled = true
+ }
}
if old.CreatedAt > 0 {
cp.CreatedAt = old.CreatedAt
@@ -684,7 +691,7 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,
}
}
- data, err := json.MarshalIndent(cp, "", " ")
+ data, err := gulu.JSON.MarshalIndentJSON(cp, "", "\t")
if err != nil {
return
}
@@ -779,6 +786,6 @@ func backoffDuration(attempt int) time.Duration {
if base <= 1*time.Second {
return base
}
- jitter := time.Duration(rand.Int64N(int64(base) * 40 / 100)) - time.Duration(base*20/100)
+ jitter := time.Duration(rand.Int64N(int64(base)*40/100)) - time.Duration(base*20/100)
return base + jitter
}