agent-loft 0.2.98 → 0.2.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/package.json +2 -1
- package/src/agents/claude/session.ts +58 -6
- package/src/agents/codex/app-server.ts +2 -1
- package/src/agents/codex/protocol.ts +2 -1
- package/src/agents/codex/session.ts +65 -1
- package/src/agents/health.ts +73 -2
- package/src/agents/workbuddy/account.ts +98 -0
- package/src/agents/workbuddy/driver.ts +157 -0
- package/src/agents/workbuddy/errors.ts +34 -0
- package/src/agents/workbuddy/history.ts +237 -0
- package/src/agents/workbuddy/sdk.ts +156 -0
- package/src/agents/workbuddy/session.ts +484 -0
- package/src/channels/feishu/bot.ts +1 -1
- package/src/channels/feishu/cards.ts +9 -4
- package/src/channels/web/api.ts +40 -0
- package/src/channels/web/experts-api.ts +3 -1
- package/src/channels/weixin/bot.ts +2 -1
- package/src/channels/weixin/format.ts +5 -5
- package/src/core/builtin-agents.ts +48 -7
- package/src/core/command-catalog.ts +4 -2
- package/src/core/commands.ts +13 -1
- package/src/core/config.ts +20 -3
- package/src/core/experts.ts +5 -3
- package/src/core/hub.ts +62 -12
- package/src/core/interactions.ts +1 -1
- package/src/core/memory-curator.ts +2 -2
- package/src/core/memory.ts +2 -2
- package/src/core/permission.ts +20 -2
- package/src/core/store.ts +5 -0
- package/src/core/types.ts +14 -0
- package/src/core/users.ts +1 -1
- package/src/main.ts +6 -2
- package/web/css/composer.css +15 -0
- package/web/lib/dom.js +2 -0
- package/web/lib/permission.js +23 -4
- package/web/settings/agents.js +107 -13
- package/web/settings/commands.js +1 -1
- package/web/settings/experts.js +1 -1
- package/web/settings/memory.js +2 -1
- package/web/state.js +4 -0
- package/web/views/composer.js +5 -4
- package/web/views/conv-actions.js +24 -4
- package/web/views/interaction.js +9 -5
- package/web/views/sidebar.js +2 -1
- package/web/views/tasks.js +2 -2
- package/web/views/topbar.js +16 -11
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// WorkBuddy 驱动:腾讯 CodeBuddy Code 的官方 Agent SDK(@tencent-ai/agent-sdk,自带 CLI)。
|
|
2
|
+
//
|
|
3
|
+
// 会话怎么跑见 session.ts;会话列表 / 历史是读 CLI 的记录文件(history.ts),SDK 没提供这些接口。
|
|
4
|
+
// 分叉、回退暂不支持:CLI 的记录格式没有公开,自己拼一条新记录风险太大。
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import type { AgentCommand } from "../../core/command-catalog.js";
|
|
7
|
+
import { config } from "../../core/config.js";
|
|
8
|
+
import type {
|
|
9
|
+
AgentDriver,
|
|
10
|
+
AgentEvents,
|
|
11
|
+
AgentSession,
|
|
12
|
+
CompleteRequest,
|
|
13
|
+
HistoryMessage,
|
|
14
|
+
InteractionHost,
|
|
15
|
+
ModelInfo,
|
|
16
|
+
RuntimeInfo,
|
|
17
|
+
SessionOptions,
|
|
18
|
+
SessionSummary,
|
|
19
|
+
} from "../../core/types.js";
|
|
20
|
+
import { cachedProbe } from "../claude/probe.js";
|
|
21
|
+
import { diagnose } from "./errors.js";
|
|
22
|
+
import { listSessionFiles, readHistoryFile, SESSION_ID, sessionFile, sessionTitleOf } from "./history.js";
|
|
23
|
+
import { baseOptions, loadSdk, modelOf, withProbe } from "./sdk.js";
|
|
24
|
+
import { WorkBuddySession } from "./session.js";
|
|
25
|
+
|
|
26
|
+
const readCatalog = cachedProbe(10 * 60_000, "WorkBuddy 模型列表", () =>
|
|
27
|
+
withProbe(async (q) => (await q.supportedModels()).map(modelOf).filter((m): m is ModelInfo => !!m)),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
/** CLI 报的命令带着前导斜杠;这些是终端界面里才有意义的,网页 / 飞书里用不了 */
|
|
31
|
+
const TUI_ONLY = new Set(["add-dir", "agents", "background", "bg", "bashes", "config", "doctor", "exit", "export", "help", "ide", "login", "logout", "memory", "mcp", "permissions", "plugin", "plugins", "quit", "resume", "status", "statusline", "terminal-setup", "theme", "upgrade", "vim"]);
|
|
32
|
+
const commandReaders = new Map<string, () => Promise<AgentCommand[]>>();
|
|
33
|
+
function readCommands(cwd: string): Promise<AgentCommand[]> {
|
|
34
|
+
let reader = commandReaders.get(cwd);
|
|
35
|
+
if (!reader) {
|
|
36
|
+
if (commandReaders.size >= 50) commandReaders.delete(commandReaders.keys().next().value!);
|
|
37
|
+
reader = cachedProbe(
|
|
38
|
+
5 * 60_000,
|
|
39
|
+
"WorkBuddy 命令列表",
|
|
40
|
+
() =>
|
|
41
|
+
withProbe(
|
|
42
|
+
async (q) =>
|
|
43
|
+
(await q.supportedCommands())
|
|
44
|
+
.map((c) => ({ ...c, name: c.name.replace(/^\//, "") }))
|
|
45
|
+
.filter((c) => c.name && !TUI_ONLY.has(c.name))
|
|
46
|
+
.map((c) => ({ name: c.name, description: c.description || "", ...(c.argumentHint ? { args: c.argumentHint } : {}) })),
|
|
47
|
+
cwd,
|
|
48
|
+
),
|
|
49
|
+
[] as AgentCommand[],
|
|
50
|
+
);
|
|
51
|
+
commandReaders.set(cwd, reader);
|
|
52
|
+
}
|
|
53
|
+
return reader();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class WorkBuddyDriver implements AgentDriver {
|
|
57
|
+
readonly id = "workbuddy";
|
|
58
|
+
readonly label = "WorkBuddy";
|
|
59
|
+
readonly capabilities = { effort: false, fork: false, cost: false, streaming: true };
|
|
60
|
+
|
|
61
|
+
async start(): Promise<void> {
|
|
62
|
+
// 先把 SDK 加载好,第一条消息不用等 import
|
|
63
|
+
await loadSdk();
|
|
64
|
+
}
|
|
65
|
+
async stop(): Promise<void> {}
|
|
66
|
+
|
|
67
|
+
createSession(opts: SessionOptions, events: AgentEvents, host: InteractionHost): AgentSession {
|
|
68
|
+
if (opts.expert) throw new Error("WorkBuddy 暂不支持自定义专家,请用内置的 WorkBuddy");
|
|
69
|
+
return new WorkBuddySession(opts, events, host);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async listSessions(cwd: string | undefined, limit = 10): Promise<SessionSummary[]> {
|
|
73
|
+
try {
|
|
74
|
+
return listSessionFiles(cwd, limit);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
console.error("[workbuddy] 读取会话列表失败:", err);
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async sessionExists(id: string): Promise<boolean> {
|
|
82
|
+
return SESSION_ID.test(id) && !!sessionFile(id);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async sessionTitle(id: string): Promise<string | undefined> {
|
|
86
|
+
return sessionTitleOf(id);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async readHistory(id: string): Promise<HistoryMessage[]> {
|
|
90
|
+
return readHistoryFile(id);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async listModels(session: AgentSession): Promise<ModelInfo[]> {
|
|
94
|
+
const models = await (session as WorkBuddySession).listModels().catch(() => [] as ModelInfo[]);
|
|
95
|
+
return models.length ? models : readCatalog();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
catalog(): Promise<ModelInfo[]> {
|
|
99
|
+
return readCatalog();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
commands(cwd?: string): Promise<AgentCommand[]> {
|
|
103
|
+
return readCommands(cwd ?? os.homedir());
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async defaults(): Promise<RuntimeInfo> {
|
|
107
|
+
const c = config().agents.workbuddy;
|
|
108
|
+
return c.defaultModel ? { model: c.defaultModel } : {};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async statusLines(): Promise<string[]> {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 后台整理记忆:不读本地配置、不给工具、不落记录,按 schema 出 JSON */
|
|
116
|
+
async complete(req: CompleteRequest): Promise<unknown> {
|
|
117
|
+
const { query } = await loadSdk();
|
|
118
|
+
const abort = new AbortController();
|
|
119
|
+
const timer = setTimeout(() => abort.abort(), req.timeoutMs ?? 120_000);
|
|
120
|
+
try {
|
|
121
|
+
const q = query({
|
|
122
|
+
prompt: req.prompt,
|
|
123
|
+
options: {
|
|
124
|
+
cwd: os.tmpdir(),
|
|
125
|
+
...baseOptions(),
|
|
126
|
+
...(req.model ? { model: req.model } : {}),
|
|
127
|
+
systemPrompt: req.system,
|
|
128
|
+
tools: [],
|
|
129
|
+
settingSources: [],
|
|
130
|
+
strictMcpConfig: true,
|
|
131
|
+
mcpServers: {},
|
|
132
|
+
persistSession: false,
|
|
133
|
+
maxTurns: 3,
|
|
134
|
+
outputFormat: { type: "json_schema", schema: req.schema },
|
|
135
|
+
abortController: abort,
|
|
136
|
+
canUseTool: async () => ({ behavior: "deny", message: "后台整理不允许用工具" }),
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
for await (const m of q) {
|
|
140
|
+
if (m.type !== "result") continue;
|
|
141
|
+
if (m.subtype !== "success" || m.is_error) throw new Error(`后台调用失败:${m.subtype}`);
|
|
142
|
+
if (m.structured_output !== undefined) return m.structured_output;
|
|
143
|
+
// 没走结构化输出的:从正文里抠 JSON
|
|
144
|
+
const text = m.result.trim().replace(/^```(?:json)?\s*|\s*```$/g, "");
|
|
145
|
+
return JSON.parse(text);
|
|
146
|
+
}
|
|
147
|
+
throw new Error("后台调用没有结果");
|
|
148
|
+
} finally {
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
abort.abort();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
diagnose(err: unknown) {
|
|
155
|
+
return diagnose(err);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// WorkBuddy 的报错翻译成人话(口径同 claude/errors.ts)
|
|
2
|
+
import type { Diagnosis } from "../../core/types.js";
|
|
3
|
+
|
|
4
|
+
const LOGIN_HINT = "到 设置 → Agent → WorkBuddy 点「登录 WorkBuddy」,在浏览器里登录;或者给服务设 CODEBUDDY_API_KEY 环境变量。";
|
|
5
|
+
|
|
6
|
+
export function diagnose(err: unknown): Diagnosis {
|
|
7
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
8
|
+
const text = raw.toLowerCase();
|
|
9
|
+
if (text.includes("authentication required") || text.includes("/login") || text.includes("unauthorized") || text.includes("invalid api key") || text.includes("token expired")) {
|
|
10
|
+
return {
|
|
11
|
+
kind: "auth_missing",
|
|
12
|
+
chatMessage: "WorkBuddy 还没登录(或登录已过期),我暂时无法工作。\n请机器主人到 设置 → Agent → WorkBuddy 重新登录。",
|
|
13
|
+
consoleHint: `WorkBuddy 未登录:${LOGIN_HINT}`,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
if (text.includes("cannot find package") || text.includes("cli not found") || text.includes("err_module_not_found")) {
|
|
17
|
+
return {
|
|
18
|
+
kind: "cli_missing",
|
|
19
|
+
chatMessage: "WorkBuddy 的 SDK 没装好,我暂时无法工作。请机器主人在 agent-loft 目录里重新 npm install。",
|
|
20
|
+
consoleHint: "找不到 @tencent-ai/agent-sdk:在 agent-loft 目录里运行 npm install,再重启服务。",
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
if (text.includes("rate limit") || text.includes("429") || text.includes("quota") || text.includes("credit") || text.includes("额度") || text.includes("积分")) {
|
|
24
|
+
return {
|
|
25
|
+
kind: "rate_limit",
|
|
26
|
+
chatMessage: "WorkBuddy 的额度用完了或请求太频繁,稍后再试,或者换个模型。",
|
|
27
|
+
consoleHint: `WorkBuddy 额度 / 限流:${raw}`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
if (text.includes("aborted") || text.includes("interrupted")) {
|
|
31
|
+
return { kind: "turn_aborted", chatMessage: "这一轮已中断。", consoleHint: raw };
|
|
32
|
+
}
|
|
33
|
+
return { kind: "unknown", chatMessage: `WorkBuddy 出错了:${raw.slice(0, 300)}`, consoleHint: raw };
|
|
34
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// 读 WorkBuddy(CodeBuddy Code)的会话记录:~/.codebuddy/projects/<项目目录>/<会话 id>.jsonl。
|
|
2
|
+
//
|
|
3
|
+
// SDK 没有列会话、读历史的接口,只能读 CLI 落的盘。每行一条记录,常见的几种:
|
|
4
|
+
// { type: "message", role: "user" | "assistant", content: [{ type: "input_text" | "output_text", text }], id, timestamp, cwd }
|
|
5
|
+
// { type: "function_call", name, arguments: "<JSON 字符串>", callId }
|
|
6
|
+
// { type: "function_call_result", callId, output }
|
|
7
|
+
// { type: "reasoning", content: [{ type: "input_text", text }] }
|
|
8
|
+
// { type: "ai-title", aiTitle } / { type: "topic", topic }
|
|
9
|
+
// 这是 CLI 的内部格式,认不出的记录一律跳过,别因为它升级了就整段读不出来。
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { stripContext } from "../../core/expert-prompt.js";
|
|
13
|
+
import { splitAttachmentNote } from "../../core/uploads.js";
|
|
14
|
+
import type { HistoryMessage, SessionSummary } from "../../core/types.js";
|
|
15
|
+
import { describeToolUse, summarize } from "../claude/session.js";
|
|
16
|
+
import { resultText, TodoTracker } from "../claude/todos.js";
|
|
17
|
+
import { codebuddyHome } from "./sdk.js";
|
|
18
|
+
|
|
19
|
+
/** 会话 id 会拼进路径,先验形 */
|
|
20
|
+
export const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
21
|
+
|
|
22
|
+
type Record_ = {
|
|
23
|
+
type?: string;
|
|
24
|
+
role?: string;
|
|
25
|
+
id?: string;
|
|
26
|
+
timestamp?: number | string;
|
|
27
|
+
cwd?: string;
|
|
28
|
+
content?: unknown;
|
|
29
|
+
name?: string;
|
|
30
|
+
arguments?: unknown;
|
|
31
|
+
callId?: string;
|
|
32
|
+
output?: unknown;
|
|
33
|
+
aiTitle?: string;
|
|
34
|
+
topic?: string;
|
|
35
|
+
providerData?: { isSynthetic?: boolean; parentToolUseId?: string; agent?: string } | null;
|
|
36
|
+
isSidechain?: boolean;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function projectsDir(): string {
|
|
40
|
+
return path.join(codebuddyHome(), "projects");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 按会话 id 找记录文件。项目目录名是 CLI 按 cwd 编出来的,不去复刻规则,直接挨个目录找 */
|
|
44
|
+
export function sessionFile(id: string): string | undefined {
|
|
45
|
+
if (!SESSION_ID.test(id)) return undefined;
|
|
46
|
+
let dirs: string[];
|
|
47
|
+
try {
|
|
48
|
+
dirs = fs.readdirSync(projectsDir());
|
|
49
|
+
} catch {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
for (const d of dirs) {
|
|
53
|
+
const file = path.join(projectsDir(), d, `${id}.jsonl`);
|
|
54
|
+
if (fs.existsSync(file)) return file;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readRecords(file: string): Record_[] {
|
|
60
|
+
const out: Record_[] = [];
|
|
61
|
+
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
|
|
62
|
+
if (!line.trim()) continue;
|
|
63
|
+
try {
|
|
64
|
+
const r = JSON.parse(line) as unknown;
|
|
65
|
+
if (r && typeof r === "object") out.push(r as Record_);
|
|
66
|
+
} catch {
|
|
67
|
+
// 写到一半的最后一行
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function textOf(content: unknown): string {
|
|
74
|
+
if (typeof content === "string") return content;
|
|
75
|
+
if (!Array.isArray(content)) return "";
|
|
76
|
+
return content
|
|
77
|
+
.map((c) => (c && typeof c === "object" && typeof (c as { text?: unknown }).text === "string" ? (c as { text: string }).text : ""))
|
|
78
|
+
.filter((t) => t.trim())
|
|
79
|
+
.join("\n");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function tsOf(r: Record_): number | undefined {
|
|
83
|
+
const t = typeof r.timestamp === "number" ? r.timestamp : Date.parse(r.timestamp ?? "");
|
|
84
|
+
return Number.isFinite(t) ? t : undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function argsOf(raw: unknown): Record<string, unknown> {
|
|
88
|
+
if (raw && typeof raw === "object") return raw as Record<string, unknown>;
|
|
89
|
+
if (typeof raw !== "string") return {};
|
|
90
|
+
try {
|
|
91
|
+
const v = JSON.parse(raw) as unknown;
|
|
92
|
+
return v && typeof v === "object" ? (v as Record<string, unknown>) : {};
|
|
93
|
+
} catch {
|
|
94
|
+
return {};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 子 agent、系统塞进来的消息不算对话 */
|
|
99
|
+
function isSide(r: Record_): boolean {
|
|
100
|
+
return !!(r.isSidechain || r.providerData?.parentToolUseId);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function cleanTitle(raw: string): string | undefined {
|
|
104
|
+
const t = stripContext(raw).replace(/\s+/g, " ").trim();
|
|
105
|
+
if (!t) return undefined;
|
|
106
|
+
return t.length > 60 ? `${t.slice(0, 60)}…` : t;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** CLI 生成的标题(最后一次的为准);没有就返回 undefined */
|
|
110
|
+
function titleIn(records: Record_[]): string | undefined {
|
|
111
|
+
for (let i = records.length - 1; i >= 0; i--) {
|
|
112
|
+
const r = records[i]!;
|
|
113
|
+
if (r.type === "ai-title" && typeof r.aiTitle === "string" && r.aiTitle.trim()) return cleanTitle(r.aiTitle);
|
|
114
|
+
if (r.type === "topic" && typeof r.topic === "string" && r.topic.trim()) return cleanTitle(r.topic);
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function firstPrompt(records: Record_[]): string | undefined {
|
|
120
|
+
for (const r of records) {
|
|
121
|
+
if (r.type !== "message" || r.role !== "user" || isSide(r) || r.providerData?.isSynthetic) continue;
|
|
122
|
+
const t = splitAttachmentNote(stripContext(textOf(r.content))).text;
|
|
123
|
+
if (t && !t.startsWith("<")) return cleanTitle(t);
|
|
124
|
+
}
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function cwdIn(records: Record_[]): string | undefined {
|
|
129
|
+
return records.find((r) => typeof r.cwd === "string" && r.cwd)?.cwd;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function sessionTitleOf(id: string): string | undefined {
|
|
133
|
+
const file = sessionFile(id);
|
|
134
|
+
return file ? titleIn(readRecords(file)) : undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 最近的会话;cwd 给了就只要这个目录的 */
|
|
138
|
+
export function listSessionFiles(cwd: string | undefined, limit: number): SessionSummary[] {
|
|
139
|
+
let dirs: string[];
|
|
140
|
+
try {
|
|
141
|
+
dirs = fs.readdirSync(projectsDir());
|
|
142
|
+
} catch {
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
const files: { id: string; file: string; mtime: number }[] = [];
|
|
146
|
+
for (const d of dirs) {
|
|
147
|
+
let names: string[];
|
|
148
|
+
try {
|
|
149
|
+
names = fs.readdirSync(path.join(projectsDir(), d));
|
|
150
|
+
} catch {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
for (const n of names) {
|
|
154
|
+
if (!n.endsWith(".jsonl")) continue;
|
|
155
|
+
const id = n.slice(0, -6);
|
|
156
|
+
if (!SESSION_ID.test(id)) continue;
|
|
157
|
+
const file = path.join(projectsDir(), d, n);
|
|
158
|
+
try {
|
|
159
|
+
files.push({ id, file, mtime: fs.statSync(file).mtimeMs });
|
|
160
|
+
} catch {
|
|
161
|
+
// 刚被删
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
files.sort((a, b) => b.mtime - a.mtime);
|
|
166
|
+
const out: SessionSummary[] = [];
|
|
167
|
+
// 按目录筛要读文件内容才知道 cwd:最多看 200 个,别为了凑数把整个目录读一遍
|
|
168
|
+
for (const f of files.slice(0, 200)) {
|
|
169
|
+
if (out.length >= limit) break;
|
|
170
|
+
let records: Record_[];
|
|
171
|
+
try {
|
|
172
|
+
records = readRecords(f.file);
|
|
173
|
+
} catch {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const at = cwdIn(records);
|
|
177
|
+
if (cwd && at && path.resolve(at) !== path.resolve(cwd)) continue;
|
|
178
|
+
// 只有系统记录、没说过话的(比如没登录时的探测)不列
|
|
179
|
+
const prompt = firstPrompt(records);
|
|
180
|
+
if (!prompt) continue;
|
|
181
|
+
out.push({ id: f.id, title: titleIn(records) ?? prompt, ...(at ? { cwd: at } : {}), updatedAt: f.mtime });
|
|
182
|
+
}
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 整理成「一问一答」:用户一条,助手把这一轮的文字拼成一条,工具调用、思考挂成过程摘要。
|
|
188
|
+
* 和 Claude 的 readHistory 一个口径(见 claude/driver.ts)。
|
|
189
|
+
*/
|
|
190
|
+
export function readHistoryFile(id: string): HistoryMessage[] {
|
|
191
|
+
const file = sessionFile(id);
|
|
192
|
+
if (!file) return [];
|
|
193
|
+
const out: HistoryMessage[] = [];
|
|
194
|
+
let assistant: HistoryMessage | null = null;
|
|
195
|
+
const todos = new TodoTracker();
|
|
196
|
+
const flush = () => {
|
|
197
|
+
if (assistant && (assistant.text.trim() || assistant.steps?.length)) out.push(assistant);
|
|
198
|
+
assistant = null;
|
|
199
|
+
};
|
|
200
|
+
for (const r of readRecords(file)) {
|
|
201
|
+
if (isSide(r)) continue;
|
|
202
|
+
const ts = tsOf(r);
|
|
203
|
+
if (r.type === "message" && r.role === "user") {
|
|
204
|
+
if (r.providerData?.isSynthetic) continue;
|
|
205
|
+
const { text, attachments } = splitAttachmentNote(stripContext(textOf(r.content)));
|
|
206
|
+
if (!text && attachments.length === 0) continue;
|
|
207
|
+
if (text.startsWith("<command-") || text.startsWith("<local-command") || text.startsWith("<task-notification>") || text.startsWith("<system-reminder>")) {
|
|
208
|
+
flush();
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
flush();
|
|
212
|
+
out.push({ role: "user", text, ...(r.id ? { anchor: r.id } : {}), ...(attachments.length ? { attachments } : {}), ...(ts !== undefined ? { ts } : {}) });
|
|
213
|
+
} else if (r.type === "message" && r.role === "assistant") {
|
|
214
|
+
assistant ??= { role: "assistant", text: "", steps: [] };
|
|
215
|
+
if (r.id) assistant.anchor = r.id;
|
|
216
|
+
if (ts !== undefined) assistant.ts = ts;
|
|
217
|
+
const text = textOf(r.content);
|
|
218
|
+
if (text.trim()) assistant.text += (assistant.text ? "\n\n" : "") + text;
|
|
219
|
+
} else if (r.type === "function_call" && r.name) {
|
|
220
|
+
assistant ??= { role: "assistant", text: "", steps: [] };
|
|
221
|
+
const input = argsOf(r.arguments);
|
|
222
|
+
const todo = todos.use(r.name, input, r.callId);
|
|
223
|
+
if (todo?.changed) assistant.todos = todos.list;
|
|
224
|
+
assistant.steps!.push(todo ? todo.step : `🔧 ${describeToolUse(r.name, input)}`);
|
|
225
|
+
} else if (r.type === "function_call_result" && r.callId) {
|
|
226
|
+
if (todos.result(r.callId, resultText(r.output), undefined, false) && assistant) assistant.todos = todos.list;
|
|
227
|
+
} else if (r.type === "reasoning") {
|
|
228
|
+
const t = summarize(textOf(r.content));
|
|
229
|
+
if (t) {
|
|
230
|
+
assistant ??= { role: "assistant", text: "", steps: [] };
|
|
231
|
+
assistant.steps!.push(`💭 ${t}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
flush();
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// WorkBuddy(腾讯 CodeBuddy Code)官方 Agent SDK:@tencent-ai/agent-sdk。
|
|
2
|
+
//
|
|
3
|
+
// 两种用法,按「账号站点」选:
|
|
4
|
+
// workbuddy(默认):调本机 WorkBuddy 桌面版自带的 CLI。那份 CLI 带着 WorkBuddy 的产品配置
|
|
5
|
+
// (站点 www.workbuddy.cn、数据目录 ~/.workbuddy、WorkBuddy 的模型),账号就是 WorkBuddy 的账号。
|
|
6
|
+
// SDK 自带的那份是通用版 CodeBuddy,连的是 copilot.tencent.com / codebuddy.ai,和 WorkBuddy 账号不通。
|
|
7
|
+
// internal / external / ioa:用 SDK 自带的 CLI,连 CodeBuddy 国内版、国际版、腾讯 iOA。
|
|
8
|
+
//
|
|
9
|
+
// 桌面版的登录态由它的主进程保管,不会交给单独跑的 CLI,所以在 agent-loft 里还要再登一次(同一个账号)。
|
|
10
|
+
// SDK 的登录接口不替你存盘:令牌在返回值里(userinfo.token),由这边存起来(data/workbuddy-auth.json,0600),
|
|
11
|
+
// 每次起 CLI 时用 CODEBUDDY_AUTH_TOKEN 交给它(实测:不传的话刚登完也照样报未登录)。
|
|
12
|
+
//
|
|
13
|
+
// SDK 包很大(近 200MB),按需 import:没启用 WorkBuddy 的机器启动时不加载它。
|
|
14
|
+
// 接口和 Claude Agent SDK 几乎一样,但没有 listSessions、getSessionMessages,会话记录得自己读(见 history.ts)。
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import type { AuthEnvironment, Options, Query, UserMessage } from "@tencent-ai/agent-sdk";
|
|
19
|
+
import { agentEnvironment } from "../../core/agent-env.js";
|
|
20
|
+
import { config } from "../../core/config.js";
|
|
21
|
+
import { dataDir, readJson, writeJsonAtomic } from "../../home.js";
|
|
22
|
+
|
|
23
|
+
type Sdk = typeof import("@tencent-ai/agent-sdk");
|
|
24
|
+
let sdk: Promise<Sdk> | null = null;
|
|
25
|
+
|
|
26
|
+
export function loadSdk(): Promise<Sdk> {
|
|
27
|
+
sdk ??= import("@tencent-ai/agent-sdk").catch((err) => {
|
|
28
|
+
sdk = null;
|
|
29
|
+
throw err;
|
|
30
|
+
});
|
|
31
|
+
return sdk;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 账号在哪个站点:WorkBuddy(桌面版的 CLI)、CodeBuddy 国内版、国际版、腾讯 iOA */
|
|
35
|
+
export type WorkBuddyEnvironment = "workbuddy" | "internal" | "external" | "ioa";
|
|
36
|
+
export const WORKBUDDY_ENVIRONMENTS: readonly WorkBuddyEnvironment[] = ["workbuddy", "internal", "external", "ioa"];
|
|
37
|
+
export const ENVIRONMENT_LABEL: Record<WorkBuddyEnvironment, string> = {
|
|
38
|
+
workbuddy: "WorkBuddy(www.workbuddy.cn)",
|
|
39
|
+
internal: "CodeBuddy 国内版(copilot.tencent.com)",
|
|
40
|
+
external: "CodeBuddy 国际版(codebuddy.ai)",
|
|
41
|
+
ioa: "腾讯 iOA",
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export function environment(): WorkBuddyEnvironment {
|
|
45
|
+
const env = config().agents.workbuddy.environment;
|
|
46
|
+
return WORKBUDDY_ENVIRONMENTS.includes(env) ? env : "workbuddy";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** WorkBuddy 桌面版里 CLI 的常见位置(Linux deb / AppImage 解包、macOS、Windows) */
|
|
50
|
+
function desktopCandidates(): string[] {
|
|
51
|
+
const rel = ["resources", "app.asar.unpacked", "cli", "bin", "codebuddy"];
|
|
52
|
+
const local = process.env.LOCALAPPDATA;
|
|
53
|
+
return [
|
|
54
|
+
path.join("/opt/WorkBuddy", ...rel),
|
|
55
|
+
path.join("/usr/lib/workbuddy", ...rel),
|
|
56
|
+
path.join("/Applications/WorkBuddy.app/Contents", ...rel.map((p) => (p === "resources" ? "Resources" : p))),
|
|
57
|
+
path.join(os.homedir(), "Applications/WorkBuddy.app/Contents", ...rel.map((p) => (p === "resources" ? "Resources" : p))),
|
|
58
|
+
...(local ? [path.join(local, "Programs", "WorkBuddy", ...rel)] : []),
|
|
59
|
+
];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 桌面版的 CLI:设置里填了就用填的,否则在常见位置找。找不到返回 undefined */
|
|
63
|
+
export function desktopCli(): string | undefined {
|
|
64
|
+
const configured = config().agents.workbuddy.cliPath?.trim();
|
|
65
|
+
if (configured) return fs.existsSync(configured) ? configured : undefined;
|
|
66
|
+
return desktopCandidates().find((p) => fs.existsSync(p));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 用哪个 CLI:WorkBuddy 站点用桌面版的(找不到就报错,不悄悄换成 CodeBuddy 的),别的用 SDK 自带的 */
|
|
70
|
+
export function cliPath(): string | undefined {
|
|
71
|
+
if (environment() !== "workbuddy") return undefined;
|
|
72
|
+
const found = desktopCli();
|
|
73
|
+
if (!found) throw new Error("找不到 WorkBuddy 桌面版的 CLI:先装好 WorkBuddy 桌面版,或者在 设置 → Agent → WorkBuddy 里填 CLI 路径");
|
|
74
|
+
return found;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---------- 登录令牌 ----------
|
|
78
|
+
|
|
79
|
+
type SavedAuth = { token: string; user: string; at: number };
|
|
80
|
+
const authFile = path.join(dataDir, "workbuddy-auth.json");
|
|
81
|
+
|
|
82
|
+
/** 各站点的令牌分开存:换了站点就是另一个账号 */
|
|
83
|
+
export function savedAuth(env = environment()): SavedAuth | undefined {
|
|
84
|
+
const all = readJson<Record<string, SavedAuth>>(authFile, {});
|
|
85
|
+
const a = all[env];
|
|
86
|
+
return a && typeof a.token === "string" && a.token ? a : undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function saveAuth(env: WorkBuddyEnvironment, auth: SavedAuth | null): void {
|
|
90
|
+
const all = readJson<Record<string, SavedAuth>>(authFile, {});
|
|
91
|
+
if (auth) all[env] = auth;
|
|
92
|
+
else delete all[env];
|
|
93
|
+
writeJsonAtomic(authFile, all, 0o600);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 交给 CLI 的环境变量。CodeBuddy 的站点由 CODEBUDDY_INTERNET_ENVIRONMENT 决定:国际版不设,国内版 internal,iOA 是 ioa;
|
|
98
|
+
* WorkBuddy 的站点写在桌面版 CLI 自己的产品配置里,什么都不设。服务进程里设了 CODEBUDDY_API_KEY 的话 CLI 自己会用。
|
|
99
|
+
*/
|
|
100
|
+
export function workbuddyEnv(extra: Record<string, string> = {}): Record<string, string | undefined> {
|
|
101
|
+
const env = environment();
|
|
102
|
+
const base = agentEnvironment();
|
|
103
|
+
delete base.CODEBUDDY_INTERNET_ENVIRONMENT;
|
|
104
|
+
const site = env === "internal" || env === "ioa" ? { CODEBUDDY_INTERNET_ENVIRONMENT: env } : {};
|
|
105
|
+
// 服务进程自己设了 API Key / 令牌的,以它为准
|
|
106
|
+
const token = base.CODEBUDDY_API_KEY || base.CODEBUDDY_AUTH_TOKEN ? undefined : savedAuth(env)?.token;
|
|
107
|
+
return { ...base, ...site, ...(token ? { CODEBUDDY_AUTH_TOKEN: token } : {}), ...extra };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 每个 query / 会话都要带的:用哪个 CLI、站点、环境变量 */
|
|
111
|
+
export function baseOptions(extraEnv?: Record<string, string>): Pick<Options, "environment" | "env" | "pathToCodebuddyCode"> {
|
|
112
|
+
const env = environment();
|
|
113
|
+
const cli = cliPath();
|
|
114
|
+
return {
|
|
115
|
+
...(env === "workbuddy" ? {} : { environment: env as AuthEnvironment }),
|
|
116
|
+
...(cli ? { pathToCodebuddyCode: cli } : {}),
|
|
117
|
+
env: workbuddyEnv(extraEnv),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* CLI 的配置和会话记录目录。桌面版的 CLI 单独跑时也用 ~/.codebuddy(~/.workbuddy 是桌面版主程序给它另设的,
|
|
123
|
+
* 这边不设:不和桌面版抢同一份数据)
|
|
124
|
+
*/
|
|
125
|
+
export function codebuddyHome(): string {
|
|
126
|
+
return process.env.CODEBUDDY_CONFIG_DIR || path.join(os.homedir(), ".codebuddy");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 永远不产出消息的输入流:只问控制请求(模型列表、账号)用 */
|
|
130
|
+
async function* silence(): AsyncGenerator<UserMessage> {
|
|
131
|
+
await new Promise<never>(() => {});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 「探针」:拉一个不发消息的 CLI 进程,问完控制请求就关。不发消息就不耗额度 */
|
|
135
|
+
export async function withProbe<T>(fn: (q: Query) => Promise<T>, cwd = os.homedir()): Promise<T> {
|
|
136
|
+
const { query } = await loadSdk();
|
|
137
|
+
const abort = new AbortController();
|
|
138
|
+
const q = query({ prompt: silence(), options: { cwd, ...baseOptions(), abortController: abort } });
|
|
139
|
+
try {
|
|
140
|
+
return await fn(q);
|
|
141
|
+
} finally {
|
|
142
|
+
abort.abort();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* query 运行时报的模型是 { id, name },类型声明里写的是 { value, displayName },V2 会话给的是 { modelId, name }:都认
|
|
148
|
+
*/
|
|
149
|
+
export function modelOf(m: unknown): { id: string; label: string; description?: string } | null {
|
|
150
|
+
const r = (m ?? {}) as Record<string, unknown>;
|
|
151
|
+
const id = typeof r.id === "string" ? r.id : typeof r.modelId === "string" ? r.modelId : typeof r.value === "string" ? r.value : "";
|
|
152
|
+
if (!id) return null;
|
|
153
|
+
const label = typeof r.name === "string" && r.name ? r.name : typeof r.displayName === "string" && r.displayName ? r.displayName : id;
|
|
154
|
+
const description = typeof r.description === "string" && r.description ? r.description : undefined;
|
|
155
|
+
return { id, label, ...(description ? { description } : {}) };
|
|
156
|
+
}
|