agent-loft 0.2.99 → 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 +3 -2
- package/package.json +2 -1
- package/src/agents/claude/session.ts +1 -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/web/api.ts +32 -0
- package/src/channels/web/experts-api.ts +3 -1
- package/src/core/builtin-agents.ts +1 -1
- package/src/core/command-catalog.ts +2 -1
- package/src/core/commands.ts +2 -1
- package/src/core/config.ts +20 -3
- package/src/core/experts.ts +5 -3
- package/src/core/hub.ts +1 -1
- package/src/core/memory-curator.ts +2 -2
- package/src/core/memory.ts +2 -2
- package/src/core/permission.ts +1 -1
- package/src/core/users.ts +1 -1
- package/src/main.ts +6 -2
- package/web/lib/dom.js +2 -0
- package/web/settings/agents.js +93 -9
- package/web/settings/commands.js +1 -1
- package/web/settings/experts.js +1 -1
- package/web/settings/memory.js +2 -1
- package/web/views/composer.js +1 -1
- package/web/views/interaction.js +1 -1
- package/web/views/sidebar.js +1 -1
- package/web/views/topbar.js +1 -1
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
// 一条会话 ↔ 一个常驻的 WorkBuddy(CodeBuddy Code)CLI 进程。
|
|
2
|
+
//
|
|
3
|
+
// 用的是 SDK 的 V2 会话(unstable_v2_createSession / resumeSession),不是 query():
|
|
4
|
+
// 这个 SDK 的 query() 会先把 prompt 迭代器整个读完才开始收消息,而且收到第一个 result 就结束,
|
|
5
|
+
// 等于一次一轮,做不了常驻会话(实测,SDK 0.3.301)。V2 会话一个进程跑多轮:每轮 send() 再 stream(),
|
|
6
|
+
// stream() 收到这一轮的 result 就停;setModel / setPermissionMode / interrupt 都能在中途用。
|
|
7
|
+
//
|
|
8
|
+
// 消息先留在本地排队,上一轮出结果才交给 CLI —— 停止时排着的能一起丢掉(和 Claude 一样)。
|
|
9
|
+
// 出错时 SDK 不给 result,而是在 stream() 里抛 ExecutionError,当成这一轮出错处理。
|
|
10
|
+
//
|
|
11
|
+
// 只做内置专家:原装提示词和工具,后面追加 agent-loft 的回复格式、记忆、技能说明,挂上记忆 / 定时任务 / 技能 MCP。
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import type { McpServerConfig, Message, PermissionMode, PermissionResult, SessionOptions as SdkSessionOptions, UserMessage } from "@tencent-ai/agent-sdk";
|
|
14
|
+
import { RICH_REPLY_LINES } from "../../core/expert-prompt.js";
|
|
15
|
+
import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
|
|
16
|
+
import { SKILLS_MCP_NAME, skillsMcpSpawn, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
|
|
17
|
+
import type { PermissionLevel } from "../../core/permission.js";
|
|
18
|
+
import { codexSkillLines } from "../../core/skill-runtime.js";
|
|
19
|
+
import { describeAttachments } from "../../core/uploads.js";
|
|
20
|
+
import type {
|
|
21
|
+
AgentEvents,
|
|
22
|
+
AgentSession,
|
|
23
|
+
InteractionHost,
|
|
24
|
+
InterruptOptions,
|
|
25
|
+
ModelInfo,
|
|
26
|
+
RuntimeInfo,
|
|
27
|
+
SavedAttachment,
|
|
28
|
+
SessionOptions,
|
|
29
|
+
TokenUsage,
|
|
30
|
+
UserInput,
|
|
31
|
+
} from "../../core/types.js";
|
|
32
|
+
import { describeToolUse, summarize } from "../claude/session.js";
|
|
33
|
+
import { describeToolCall, isRememberable, parseQuestions } from "../claude/permissions.js";
|
|
34
|
+
import { feedTodos, TodoTracker } from "../claude/todos.js";
|
|
35
|
+
import { baseOptions, loadSdk, modelOf } from "./sdk.js";
|
|
36
|
+
|
|
37
|
+
/** 级别 + 计划模式 → permissionMode。「完全允许」也用 default,在 canUseTool 里全放行(和 Claude 一样,见 permission.ts) */
|
|
38
|
+
export function modeOf(level: PermissionLevel | undefined, plan: boolean | undefined): PermissionMode {
|
|
39
|
+
if (plan) return "plan";
|
|
40
|
+
return level === "edit" || level === "auto" ? "acceptEdits" : "default";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type ImageMedia = "image/jpeg" | "image/png" | "image/gif" | "image/webp";
|
|
44
|
+
type ContentBlock = { type: "text"; text: string } | { type: "image"; source: { type: "base64"; media_type: ImageMedia; data: string } };
|
|
45
|
+
|
|
46
|
+
/** 图片直接给模型看(和 Claude 一样限 3.75MB);PDF 等其余附件只给路径,让它自己读 */
|
|
47
|
+
const INLINE_IMAGE_MAX = 3.75 * 1024 * 1024;
|
|
48
|
+
function canInline(a: SavedAttachment): boolean {
|
|
49
|
+
return !!a.mediaType && /^image\/(png|jpeg|gif|webp)$/.test(a.mediaType) && a.size <= INLINE_IMAGE_MAX;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function buildContent(input: UserInput): string | ContentBlock[] {
|
|
53
|
+
if (input.attachments.length === 0) return input.text;
|
|
54
|
+
const note = describeAttachments(input.attachments, canInline, false);
|
|
55
|
+
const blocks: ContentBlock[] = [{ type: "text", text: [input.text, note].filter(Boolean).join("\n\n") }];
|
|
56
|
+
for (const a of input.attachments) {
|
|
57
|
+
if (!canInline(a)) continue;
|
|
58
|
+
blocks.push({ type: "image", source: { type: "base64", media_type: a.mediaType as ImageMedia, data: fs.readFileSync(a.path).toString("base64") } });
|
|
59
|
+
}
|
|
60
|
+
return blocks;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const MEMORY_TOOLS = new Set(["remember", "forget", "update_memory", "search_memory", "search_past_chats", "read_past_chat", "memory_timeline"].map((t) => `mcp__${MEMORY_MCP_NAME}__${t}`));
|
|
64
|
+
const TASK_TOOLS = new Set(["list_tasks", "create_task", "update_task", "delete_task"].map((t) => `mcp__${TASKS_MCP_NAME}__${t}`));
|
|
65
|
+
const SKILL_TOOLS = new Set(["list_skills", "get_skill", "create_skill", "update_skill", "skill_request"].map((t) => `mcp__${SKILLS_MCP_NAME}__${t}`));
|
|
66
|
+
|
|
67
|
+
/** 内置专家的会话选项:读不读本机 CodeBuddy 配置、挂哪些 MCP、系统提示后面追加什么 */
|
|
68
|
+
export function sessionOptions(opts: SessionOptions): Partial<SdkSessionOptions> {
|
|
69
|
+
const memory = opts.memory;
|
|
70
|
+
const skills = opts.skills;
|
|
71
|
+
const mcpServers: Record<string, McpServerConfig> = {
|
|
72
|
+
...(opts.builtinMcp?.mcp as Record<string, McpServerConfig> | undefined),
|
|
73
|
+
...(memory
|
|
74
|
+
? { [MEMORY_MCP_NAME]: { type: "stdio", ...memoryMcpSpawn(memory.userId, "workbuddy", { search: !!memory.search, ...(memory.convKey ? { convKey: memory.convKey } : {}) }) } }
|
|
75
|
+
: {}),
|
|
76
|
+
...(opts.tasks
|
|
77
|
+
? {
|
|
78
|
+
[TASKS_MCP_NAME]: { type: "stdio", ...tasksMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "workbuddy") },
|
|
79
|
+
[SKILLS_MCP_NAME]: { type: "stdio", ...skillsMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "workbuddy") },
|
|
80
|
+
}
|
|
81
|
+
: {}),
|
|
82
|
+
};
|
|
83
|
+
const append = [RICH_REPLY_LINES.join("\n"), memory?.prompt, codexSkillLines(skills).join("\n")].filter(Boolean).join("\n\n");
|
|
84
|
+
// SDK 默认什么本地配置都不读。管理员(或没主人的对话)读全部,和直接用 CLI 一样;
|
|
85
|
+
// 成员只读项目里的 —— 机器主人的 ~/.codebuddy 里的 MCP、技能、规则不给成员用(和 Claude 那边一致)
|
|
86
|
+
const machine = !skills || (skills.admin && skills.machineSkills !== false);
|
|
87
|
+
const strict = !!opts.builtinMcp && !opts.builtinMcp.inheritMachine;
|
|
88
|
+
return {
|
|
89
|
+
systemPrompt: { append },
|
|
90
|
+
settingSources: machine ? ["user", "project", "local"] : ["project"],
|
|
91
|
+
...(Object.keys(mcpServers).length ? { mcpServers } : {}),
|
|
92
|
+
...(strict || !machine ? { strictMcpConfig: true } : {}),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
type V2Session = ReturnType<Awaited<ReturnType<typeof loadSdk>>["unstable_v2_createSession"]>;
|
|
97
|
+
|
|
98
|
+
export class WorkBuddySession implements AgentSession {
|
|
99
|
+
private session: V2Session | null = null;
|
|
100
|
+
/** 正在拉起(SDK 按需 import) */
|
|
101
|
+
private starting: Promise<V2Session | null> | null = null;
|
|
102
|
+
private currentId: string | undefined;
|
|
103
|
+
/** 分叉已经生效(CLI 报了一个和原会话不同的 id),之后重拉就是接着新的这条,不再分叉 */
|
|
104
|
+
private forked = false;
|
|
105
|
+
private lastAssistantUuid: string | undefined;
|
|
106
|
+
private runtime: RuntimeInfo = {};
|
|
107
|
+
private disposed = false;
|
|
108
|
+
private turnBusy = false;
|
|
109
|
+
private pending: UserInput[] = [];
|
|
110
|
+
/** 「完全允许」或点过「本会话全部允许」 */
|
|
111
|
+
private allowAll = false;
|
|
112
|
+
private todos = new TodoTracker();
|
|
113
|
+
/** 这一轮的 send + stream,dispose 时等它收尾 */
|
|
114
|
+
private turn: Promise<void> | null = null;
|
|
115
|
+
/** 这一轮报过「开始」了:CLI 每轮会发两次 init,只报一次 */
|
|
116
|
+
private turnStarted = false;
|
|
117
|
+
|
|
118
|
+
constructor(
|
|
119
|
+
private readonly opts: SessionOptions,
|
|
120
|
+
private readonly events: AgentEvents,
|
|
121
|
+
private readonly host: InteractionHost,
|
|
122
|
+
) {
|
|
123
|
+
this.allowAll = opts.permission === "full";
|
|
124
|
+
if (opts.model) this.runtime = { model: opts.model };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
get sessionId(): string | undefined {
|
|
128
|
+
return this.currentId;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private start(): Promise<V2Session | null> {
|
|
132
|
+
if (this.session) return Promise.resolve(this.session);
|
|
133
|
+
if (this.disposed) return Promise.resolve(null);
|
|
134
|
+
this.starting ??= this.launch().finally(() => {
|
|
135
|
+
this.starting = null;
|
|
136
|
+
});
|
|
137
|
+
return this.starting;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private async launch(): Promise<V2Session | null> {
|
|
141
|
+
const sdk = await loadSdk();
|
|
142
|
+
if (this.disposed) return null;
|
|
143
|
+
// 重拉时接着最新的会话;分叉只在第一次
|
|
144
|
+
const fork = !!this.opts.fork && !this.forked;
|
|
145
|
+
const resume = fork ? this.opts.resumeId : (this.currentId ?? this.opts.resumeId);
|
|
146
|
+
const options: SdkSessionOptions = {
|
|
147
|
+
cwd: this.opts.cwd,
|
|
148
|
+
...baseOptions(this.opts.skills?.env ?? {}),
|
|
149
|
+
permissionMode: modeOf(this.opts.permission, this.opts.plan),
|
|
150
|
+
includePartialMessages: true,
|
|
151
|
+
...(this.opts.model ? { model: this.opts.model } : {}),
|
|
152
|
+
...sessionOptions(this.opts),
|
|
153
|
+
// V2 会话没有 additionalDirectories / forkSession 选项,直接给 CLI 参数
|
|
154
|
+
extraArgs: { "add-dir": this.opts.uploadsDir, ...(fork ? { "fork-session": null } : {}) },
|
|
155
|
+
canUseTool: async (toolName, toolInput) => this.canUseTool(toolName, toolInput as Record<string, unknown>),
|
|
156
|
+
};
|
|
157
|
+
const session = resume ? sdk.unstable_v2_resumeSession(resume, options) : sdk.unstable_v2_createSession(options);
|
|
158
|
+
this.session = session;
|
|
159
|
+
return session;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** CLI 退了、连接断了:扔掉这个会话对象,下一轮带着最新的 id 重新拉起 */
|
|
163
|
+
private drop(session: V2Session): void {
|
|
164
|
+
if (this.session !== session) return;
|
|
165
|
+
this.session = null;
|
|
166
|
+
try {
|
|
167
|
+
session.close();
|
|
168
|
+
} catch {
|
|
169
|
+
// 已经关了
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 跑一轮:发出去,收到这一轮的 result(或出错)为止 */
|
|
174
|
+
private async runTurn(content: string | ContentBlock[], input: UserInput): Promise<void> {
|
|
175
|
+
let sawResult = false;
|
|
176
|
+
let session: V2Session | null = null;
|
|
177
|
+
try {
|
|
178
|
+
session = await this.start();
|
|
179
|
+
if (!session) return;
|
|
180
|
+
await session.send({
|
|
181
|
+
type: "user",
|
|
182
|
+
...(input.id ? { uuid: input.id } : {}),
|
|
183
|
+
session_id: this.currentId ?? "",
|
|
184
|
+
message: { role: "user", content: content as never },
|
|
185
|
+
parent_tool_use_id: null,
|
|
186
|
+
} as UserMessage);
|
|
187
|
+
if (input.id) this.events.onUserAnchor?.(input, input.id);
|
|
188
|
+
for await (const message of session.stream()) {
|
|
189
|
+
if (message.type === "result") sawResult = true;
|
|
190
|
+
this.handle(message);
|
|
191
|
+
}
|
|
192
|
+
// 没等到 result 流就断了:CLI 多半退出了,下一轮重拉
|
|
193
|
+
if (!sawResult && !this.disposed) {
|
|
194
|
+
this.drop(session);
|
|
195
|
+
this.events.onError(new Error("WorkBuddy 进程意外退出了,这一轮没有完成"));
|
|
196
|
+
}
|
|
197
|
+
} catch (err) {
|
|
198
|
+
if (this.disposed) return;
|
|
199
|
+
const name = (err as { name?: string })?.name;
|
|
200
|
+
// ExecutionError:这一轮报错收场(未登录、额度用完…),进程还在;别的错误当进程坏了,重拉
|
|
201
|
+
if (name !== "ExecutionError" && session) this.drop(session);
|
|
202
|
+
this.events.onError(err);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private handle(message: Message): void {
|
|
207
|
+
const m = message as Message & { session_id?: string };
|
|
208
|
+
if (typeof m.session_id === "string" && m.session_id && m.session_id !== this.currentId) {
|
|
209
|
+
if (this.opts.fork && m.session_id !== this.opts.resumeId) this.forked = true;
|
|
210
|
+
this.currentId = m.session_id;
|
|
211
|
+
this.events.onSessionId(m.session_id);
|
|
212
|
+
}
|
|
213
|
+
if (message.type === "system" && message.subtype === "init") {
|
|
214
|
+
if (message.model) this.runtime = { ...this.runtime, model: message.model };
|
|
215
|
+
if (message.permissionMode) this.syncPlan(message.permissionMode === "plan");
|
|
216
|
+
if (!this.turnStarted) {
|
|
217
|
+
this.turnStarted = true;
|
|
218
|
+
this.events.onTurnStart?.();
|
|
219
|
+
}
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (message.type === "error") {
|
|
224
|
+
this.events.onError(new Error(message.error));
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (message.type === "stream_event") {
|
|
229
|
+
if (message.parent_tool_use_id) return;
|
|
230
|
+
const event = message.event as { type?: string; delta?: { type?: string; text?: string } };
|
|
231
|
+
if (event.type === "content_block_delta" && event.delta?.type === "text_delta" && event.delta.text) this.events.onTextDelta(event.delta.text);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (message.type === "assistant") {
|
|
236
|
+
const blocks = message.message?.content;
|
|
237
|
+
if (!Array.isArray(blocks)) return;
|
|
238
|
+
const sub = !!message.parent_tool_use_id;
|
|
239
|
+
if (!sub && message.uuid) this.lastAssistantUuid = message.uuid;
|
|
240
|
+
for (const block of blocks) {
|
|
241
|
+
if (block.type === "thinking") {
|
|
242
|
+
const thought = summarize(block.thinking);
|
|
243
|
+
if (thought) this.events.onStep("thinking", `💭 ${thought}`);
|
|
244
|
+
} else if (block.type === "tool_use") {
|
|
245
|
+
const todo = sub ? null : this.todos.use(block.name, block.input, block.id);
|
|
246
|
+
if (todo) {
|
|
247
|
+
this.events.onStep("tool", todo.step);
|
|
248
|
+
if (todo.changed) this.events.onTodos?.(this.todos.list);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
this.events.onStep("tool", `${sub ? " ↳ " : ""}🔧 ${describeToolUse(block.name, block.input)}`);
|
|
252
|
+
} else if (block.type === "text" && block.text.trim() && !sub) {
|
|
253
|
+
this.events.onText(block.text);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (message.error && !sub) this.events.onStep("warning", `⚠️ ${message.error}`);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (message.type === "user") {
|
|
261
|
+
if (!message.parent_tool_use_id && feedTodos(this.todos, message)) this.events.onTodos?.(this.todos.list);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (message.type === "result") {
|
|
266
|
+
const tokens = this.reportUsage(message.usage);
|
|
267
|
+
if (message.subtype === "success" && !message.is_error) {
|
|
268
|
+
this.events.onResult({
|
|
269
|
+
text: message.result,
|
|
270
|
+
...(tokens ? { tokens } : {}),
|
|
271
|
+
durationMs: message.duration_ms,
|
|
272
|
+
...(this.lastAssistantUuid ? { anchor: this.lastAssistantUuid } : {}),
|
|
273
|
+
});
|
|
274
|
+
} else {
|
|
275
|
+
const r = message as { result?: string; errors?: string[]; subtype: string };
|
|
276
|
+
const why = r.errors?.filter(Boolean).join(";") || (message.subtype === "success" ? r.result : "") || message.subtype;
|
|
277
|
+
this.events.onError(new Error(`运行结束但报错:${why}`));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* result 里的 usage 是这一轮的(新增量),由核心累加。
|
|
284
|
+
* 实测 WorkBuddy 的 input_tokens 已经含了缓存读写的部分(input = 读 + 写 + 没命中的),减掉才是没命中缓存的
|
|
285
|
+
*/
|
|
286
|
+
private reportUsage(usage: { input_tokens?: number; output_tokens?: number; cache_read_input_tokens?: number | null; cache_creation_input_tokens?: number | null } | undefined): number | undefined {
|
|
287
|
+
if (!usage) return undefined;
|
|
288
|
+
const cacheRead = usage.cache_read_input_tokens || 0;
|
|
289
|
+
const cacheWrite = usage.cache_creation_input_tokens || 0;
|
|
290
|
+
const input = usage.input_tokens || 0;
|
|
291
|
+
const u: TokenUsage = {
|
|
292
|
+
input: input >= cacheRead + cacheWrite ? input - cacheRead - cacheWrite : input,
|
|
293
|
+
cacheRead,
|
|
294
|
+
cacheWrite,
|
|
295
|
+
output: usage.output_tokens || 0,
|
|
296
|
+
};
|
|
297
|
+
const total = u.input + u.cacheRead + u.cacheWrite + u.output;
|
|
298
|
+
if (!(total > 0)) return undefined;
|
|
299
|
+
this.events.onUsage?.(u, false);
|
|
300
|
+
return total;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ---------- 授权 ----------
|
|
304
|
+
|
|
305
|
+
private async canUseTool(toolName: string, input: Record<string, unknown>): Promise<PermissionResult> {
|
|
306
|
+
if (MEMORY_TOOLS.has(toolName) && this.opts.memory) return { behavior: "allow", updatedInput: input };
|
|
307
|
+
if ((TASK_TOOLS.has(toolName) || SKILL_TOOLS.has(toolName)) && this.opts.tasks) return { behavior: "allow", updatedInput: input };
|
|
308
|
+
const mcp = /^mcp__(.+?)__/.exec(toolName)?.[1];
|
|
309
|
+
const builtin = this.opts.builtinMcp;
|
|
310
|
+
const configured = !!builtin && !!mcp && mcp in builtin.mcp;
|
|
311
|
+
const asksFirst = configured && builtin!.askMcp.includes(mcp!);
|
|
312
|
+
if (configured && !asksFirst) return { behavior: "allow", updatedInput: input };
|
|
313
|
+
|
|
314
|
+
if (toolName === "AskUserQuestion") {
|
|
315
|
+
const answered = await this.askQuestion(input);
|
|
316
|
+
if (answered) return answered;
|
|
317
|
+
}
|
|
318
|
+
if (toolName === "ExitPlanMode") return this.approvePlan(input);
|
|
319
|
+
|
|
320
|
+
const sessionable = isRememberable(toolName) && !asksFirst;
|
|
321
|
+
if (sessionable && this.allowAll && !this.opts.plan) return { behavior: "allow", updatedInput: input };
|
|
322
|
+
|
|
323
|
+
const outcome = await this.host({
|
|
324
|
+
kind: "approval",
|
|
325
|
+
title: `需要授权:${toolName}`,
|
|
326
|
+
detail: describeToolCall(toolName, input),
|
|
327
|
+
...(sessionable && !this.opts.noSessionGrant ? { allowSession: true } : {}),
|
|
328
|
+
});
|
|
329
|
+
if (outcome.settlement === "allow-session") {
|
|
330
|
+
if (!this.allowAll) this.events.onStep("warning", "🔓 本会话内后续操作不再询问(/new 或切换会话后恢复逐条确认)");
|
|
331
|
+
this.allowAll = true;
|
|
332
|
+
}
|
|
333
|
+
if (outcome.settlement === "allow-once" || outcome.settlement === "allow-always" || outcome.settlement === "allow-session") {
|
|
334
|
+
return { behavior: "allow", updatedInput: input };
|
|
335
|
+
}
|
|
336
|
+
const why =
|
|
337
|
+
outcome.settlement === "timeout"
|
|
338
|
+
? "用户长时间没有响应授权请求(已超时),按拒绝处理"
|
|
339
|
+
: outcome.settlement === "cancelled"
|
|
340
|
+
? "授权请求已被取消(用户中断了这一轮或切换了会话)"
|
|
341
|
+
: "用户拒绝了此操作";
|
|
342
|
+
return { behavior: "deny", message: why };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private async approvePlan(input: Record<string, unknown>): Promise<PermissionResult> {
|
|
346
|
+
const plan = typeof input.plan === "string" && input.plan.trim() ? input.plan : "(WorkBuddy 没有附上方案正文)";
|
|
347
|
+
const outcome = await this.host({ kind: "approval", title: "方案出好了,按这个开始做?", detail: plan, allowLabel: "开始执行", denyLabel: "继续改方案" });
|
|
348
|
+
if (outcome.settlement === "allow-once" || outcome.settlement === "allow-always") {
|
|
349
|
+
this.syncPlan(false);
|
|
350
|
+
const mode = modeOf(this.opts.permission, false);
|
|
351
|
+
// 有的 CLI 版本不认 updatedPermissions 里的 setMode:再显式切一次
|
|
352
|
+
setTimeout(() => void this.session?.setPermissionMode(mode).catch(() => {}), 0);
|
|
353
|
+
return { behavior: "allow", updatedInput: input, updatedPermissions: [{ type: "setMode", mode, destination: "session" }] };
|
|
354
|
+
}
|
|
355
|
+
const message =
|
|
356
|
+
outcome.settlement === "timeout"
|
|
357
|
+
? "用户长时间没有回应这个方案(已超时)。留在计划模式,不要动手,等用户回来。"
|
|
358
|
+
: outcome.settlement === "cancelled"
|
|
359
|
+
? "方案确认已被取消(用户中断了这一轮或切换了会话)。留在计划模式,不要动手。"
|
|
360
|
+
: "用户还不想按这个方案做。留在计划模式,不要动手;简短问一句要改哪里,等用户说明。";
|
|
361
|
+
return { behavior: "deny", message };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private syncPlan(on: boolean): void {
|
|
365
|
+
if (!!this.opts.plan === on) return;
|
|
366
|
+
this.opts.plan = on;
|
|
367
|
+
this.events.onPlanMode?.(on);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
private async askQuestion(input: Record<string, unknown>): Promise<PermissionResult | null> {
|
|
371
|
+
const questions = parseQuestions(input);
|
|
372
|
+
if (!questions) return null;
|
|
373
|
+
const outcome = await this.host({ kind: "question", title: "WorkBuddy 想确认一下", questions });
|
|
374
|
+
const answers: Record<string, string> = {};
|
|
375
|
+
for (const [id, picked] of Object.entries(outcome.answers)) answers[id] = picked.join(", ");
|
|
376
|
+
if (Object.keys(answers).length > 0) return { behavior: "allow", updatedInput: { ...input, answers } };
|
|
377
|
+
return { behavior: "deny", message: "用户没有作答(超时或主动跳过)。不要重复提同样的问题:按你认为合理的默认继续,并在回复里说明你替他选了什么。" };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ---------- 对外 ----------
|
|
381
|
+
|
|
382
|
+
send(input: UserInput): void {
|
|
383
|
+
if (this.disposed) return;
|
|
384
|
+
if (this.turnBusy) {
|
|
385
|
+
this.pending.push(input);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
this.deliver(input);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
cancelQueued(input: UserInput): boolean {
|
|
392
|
+
const index = this.pending.indexOf(input);
|
|
393
|
+
if (index < 0) return false;
|
|
394
|
+
this.pending.splice(index, 1);
|
|
395
|
+
return true;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
private onTurnEnd(): void {
|
|
399
|
+
this.turnBusy = false;
|
|
400
|
+
const next = this.pending.shift();
|
|
401
|
+
if (next && !this.disposed) this.deliver(next);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private deliver(input: UserInput): void {
|
|
405
|
+
let content: string | ContentBlock[];
|
|
406
|
+
try {
|
|
407
|
+
content = buildContent(input);
|
|
408
|
+
} catch (err) {
|
|
409
|
+
const why = (err as NodeJS.ErrnoException).code === "ENOENT" ? "附件文件已不存在,请重新上传" : String(err);
|
|
410
|
+
this.events.onError(new Error(`这条消息没能发出:${why}`));
|
|
411
|
+
const next = this.pending.shift();
|
|
412
|
+
if (next && !this.disposed) this.deliver(next);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
this.turnBusy = true;
|
|
416
|
+
this.turnStarted = false;
|
|
417
|
+
this.turn = this.runTurn(content, input).finally(() => {
|
|
418
|
+
this.turn = null;
|
|
419
|
+
if (this.turnBusy) this.onTurnEnd();
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async listModels(): Promise<ModelInfo[]> {
|
|
424
|
+
const session = await this.start();
|
|
425
|
+
if (!session) return [];
|
|
426
|
+
return (await session.getAvailableModels()).map(modelOf).filter((m): m is ModelInfo => !!m);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async setPermission(level: PermissionLevel | undefined): Promise<void> {
|
|
430
|
+
this.opts.permission = level;
|
|
431
|
+
this.allowAll = level === "full";
|
|
432
|
+
// 还没拉起就不用管:拉起时按 opts 来
|
|
433
|
+
if (this.session) await this.session.setPermissionMode(modeOf(level, this.opts.plan));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async setPlan(on: boolean): Promise<void> {
|
|
437
|
+
this.opts.plan = on;
|
|
438
|
+
if (this.session) await this.session.setPermissionMode(modeOf(this.opts.permission, on));
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** WorkBuddy 没有可在会话中途切换的思考程度,只认模型 */
|
|
442
|
+
async setModel(model?: string): Promise<void> {
|
|
443
|
+
if (model === undefined) return;
|
|
444
|
+
this.opts.model = model;
|
|
445
|
+
this.runtime = { ...this.runtime, model };
|
|
446
|
+
if (this.session) await this.session.setModel(model);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
peekRuntime(): RuntimeInfo {
|
|
450
|
+
return this.runtime;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
async describeRuntime(): Promise<RuntimeInfo> {
|
|
454
|
+
return this.runtime;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async interrupt(opts: InterruptOptions = {}): Promise<void> {
|
|
458
|
+
if (opts.keepQueue) {
|
|
459
|
+
const i = opts.first ? this.pending.indexOf(opts.first) : -1;
|
|
460
|
+
if (i > 0) this.pending.unshift(...this.pending.splice(i, 1));
|
|
461
|
+
} else {
|
|
462
|
+
const dropped = this.pending.length;
|
|
463
|
+
this.pending = [];
|
|
464
|
+
if (dropped > 0) this.events.onDropped?.(dropped);
|
|
465
|
+
}
|
|
466
|
+
if (!this.session || !this.turnBusy) return;
|
|
467
|
+
try {
|
|
468
|
+
await this.session.interrupt();
|
|
469
|
+
} catch (err) {
|
|
470
|
+
console.warn("[workbuddy] 中断失败:", err instanceof Error ? err.message : err);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async dispose(): Promise<void> {
|
|
475
|
+
this.disposed = true;
|
|
476
|
+
this.pending = [];
|
|
477
|
+
const session = this.session ?? (await this.starting?.catch(() => null)) ?? null;
|
|
478
|
+
if (session) {
|
|
479
|
+
if (this.turnBusy) await session.interrupt().catch(() => {});
|
|
480
|
+
this.drop(session);
|
|
481
|
+
}
|
|
482
|
+
await this.turn?.catch(() => {});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
@@ -102,7 +102,7 @@ export class FeishuBot {
|
|
|
102
102
|
const out: CommandEntry[] = [];
|
|
103
103
|
for (const agent of agents) {
|
|
104
104
|
if (!hub.driver(agent)) continue;
|
|
105
|
-
out.push(...(await hub.commandCatalog(agent, { allowedAgents: allowed, channel: "feishu" })).filter((c) => !["claude", "codex"].includes(c.name) || this.cfg.experts === undefined || this.cfg.experts.includes(c.name)));
|
|
105
|
+
out.push(...(await hub.commandCatalog(agent, { allowedAgents: allowed, channel: "feishu" })).filter((c) => !["claude", "codex", "workbuddy"].includes(c.name) || this.cfg.experts === undefined || this.cfg.experts.includes(c.name)));
|
|
106
106
|
}
|
|
107
107
|
return out;
|
|
108
108
|
}
|
package/src/channels/web/api.ts
CHANGED
|
@@ -64,6 +64,8 @@ import { curateNow, pendingCount } from "../../core/memory-curator.js";
|
|
|
64
64
|
import { listAllowlist, setAllowlist } from "../../agents/claude/permissions.js";
|
|
65
65
|
import { isPermissionLevel, type PermissionLevel } from "../../core/permission.js";
|
|
66
66
|
import { agentAvailability, agentHealth, invalidateHealth } from "../../agents/health.js";
|
|
67
|
+
import { loginState as workbuddyLoginState, logout as workbuddyLogout, startLogin as workbuddyLogin } from "../../agents/workbuddy/account.js";
|
|
68
|
+
import { WORKBUDDY_ENVIRONMENTS } from "../../agents/workbuddy/sdk.js";
|
|
67
69
|
import { installCodex, upgrade, useInstalledCodex, versionInfo } from "../../core/upgrade.js";
|
|
68
70
|
import { feishuBots } from "../feishu/index.js";
|
|
69
71
|
import { weixinStatus } from "../weixin/index.js";
|
|
@@ -342,6 +344,14 @@ function applyConfig(input: Partial<AppConfig>, selfOrigin?: string): void {
|
|
|
342
344
|
if (patch.models !== undefined) {
|
|
343
345
|
patch.models = Array.isArray(patch.models) ? [...new Set(patch.models.filter((m) => typeof m === "string" && m))] : [];
|
|
344
346
|
}
|
|
347
|
+
if (id === "workbuddy" && "environment" in patch && !(WORKBUDDY_ENVIRONMENTS as readonly unknown[]).includes(patch.environment)) {
|
|
348
|
+
throw new HttpError(400, "WorkBuddy 站点只能是 WorkBuddy、CodeBuddy 国内版、国际版或 iOA");
|
|
349
|
+
}
|
|
350
|
+
if (id === "workbuddy" && "cliPath" in patch) {
|
|
351
|
+
const cli = (patch as { cliPath?: unknown }).cliPath;
|
|
352
|
+
if (typeof cli !== "string" || cli.length > 500 || (cli.trim() && !path.isAbsolute(cli.trim()))) throw new HttpError(400, "CLI 路径要写绝对路径,留空自动找");
|
|
353
|
+
(patch as { cliPath: string }).cliPath = cli.trim();
|
|
354
|
+
}
|
|
345
355
|
Object.assign(next.agents[id], patch);
|
|
346
356
|
}
|
|
347
357
|
}
|
|
@@ -486,6 +496,7 @@ function adminOnly(p: string): boolean {
|
|
|
486
496
|
p === "/api/config" ||
|
|
487
497
|
p === "/api/server/upgrade" ||
|
|
488
498
|
p === "/api/agents/codex/install" ||
|
|
499
|
+
p.startsWith("/api/agents/workbuddy/") ||
|
|
489
500
|
p.startsWith("/api/pairing") ||
|
|
490
501
|
p.startsWith("/api/claude/") ||
|
|
491
502
|
p.startsWith("/api/feishu/") ||
|
|
@@ -1290,6 +1301,27 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1290
1301
|
sendJson(res, 200, result);
|
|
1291
1302
|
return;
|
|
1292
1303
|
}
|
|
1304
|
+
// WorkBuddy 网页登录:先拿登录链接(用户在自己的浏览器里打开),之后轮询状态
|
|
1305
|
+
if (p === "/api/agents/workbuddy/login" && method === "POST") {
|
|
1306
|
+
try {
|
|
1307
|
+
sendJson(res, 200, { url: await workbuddyLogin() });
|
|
1308
|
+
} catch (err) {
|
|
1309
|
+
throw new HttpError(400, `拿不到登录链接:${err instanceof Error ? err.message : String(err)}`);
|
|
1310
|
+
}
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
if (p === "/api/agents/workbuddy/login" && method === "GET") {
|
|
1314
|
+
sendJson(res, 200, workbuddyLoginState());
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
if (p === "/api/agents/workbuddy/logout" && method === "POST") {
|
|
1318
|
+
await workbuddyLogout().catch((err) => {
|
|
1319
|
+
throw new HttpError(400, err instanceof Error ? err.message : String(err));
|
|
1320
|
+
});
|
|
1321
|
+
invalidateHealth();
|
|
1322
|
+
sendJson(res, 200, { ok: true });
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1293
1325
|
if (p === "/api/agents/health" && method === "GET") {
|
|
1294
1326
|
sendJson(res, 200, { agents: await agentHealth(url.searchParams.get("refresh") === "1") });
|
|
1295
1327
|
return;
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
createExpert,
|
|
11
11
|
canUseExpert,
|
|
12
12
|
deleteExpert,
|
|
13
|
+
EXPERT_ENGINES,
|
|
13
14
|
EXPERT_LIMITS,
|
|
14
15
|
EXPERT_TEMPLATES,
|
|
15
16
|
getExpert,
|
|
@@ -131,7 +132,8 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
131
132
|
sendJson(res, 200, {
|
|
132
133
|
experts: availableExperts(user.id).map((e) => expertView(e, user.id)),
|
|
133
134
|
builtin: enabled.filter((id) => canUseExpert(user.id, id)).map((id) => ({ id, name: hub.label(id), engine: id })),
|
|
134
|
-
|
|
135
|
+
// 能建自定义专家的引擎(WorkBuddy 只有内置专家)
|
|
136
|
+
engines: enabled.filter((id) => (EXPERT_ENGINES as readonly string[]).includes(id)),
|
|
135
137
|
templates: EXPERT_TEMPLATES.map((t) => ({ id: t.id, label: t.label, expert: t.expert })),
|
|
136
138
|
access: ACCESS_LEVELS.map((id) => ({ id, label: ACCESS_LABEL[id] })),
|
|
137
139
|
skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
|
|
@@ -53,7 +53,7 @@ export function builtinAgentDefaults(owner: string): Defaults {
|
|
|
53
53
|
mcp: stored?.[engine]?.mcp ?? (admin ? null : []),
|
|
54
54
|
permission: storedPermission(stored?.[engine]?.permission, engine, admin),
|
|
55
55
|
});
|
|
56
|
-
return { claude: defaults("claude"), codex: defaults("codex") };
|
|
56
|
+
return { claude: defaults("claude"), codex: defaults("codex"), workbuddy: defaults("workbuddy") };
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
function selection(value: unknown, what: string): string[] | null {
|
|
@@ -37,6 +37,7 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
|
|
|
37
37
|
{ name: "expert", args: "[名称]", description: "查看 / 换专家(换了会开新会话)", chatOnly: true },
|
|
38
38
|
{ name: "claude", description: "换成 Claude Code 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
39
39
|
{ name: "codex", description: "换成 Codex 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
40
|
+
{ name: "workbuddy", description: "换成 WorkBuddy 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
40
41
|
{ name: "web", description: "接上一条 Web 会话,在飞书里查看和回复", feishuOnly: true },
|
|
41
42
|
{ name: "detach", description: "不再接着 Web 会话,回到这个聊天自己的会话", feishuOnly: true },
|
|
42
43
|
{ name: "bind", args: "<绑定码>", description: "把这个飞书账号绑定到你的 agent-loft 用户(绑定码在 Web 的「设置 → 账号」里生成)", feishuOnly: true },
|
|
@@ -164,7 +165,7 @@ export function buildCatalog(params: {
|
|
|
164
165
|
(!c.feishuOnly || params.channel === undefined || params.channel === "feishu") &&
|
|
165
166
|
(!c.chatOnly || params.channel !== "web") &&
|
|
166
167
|
// /claude /codex 只在这个渠道能用对应 agent 时才有意义
|
|
167
|
-
(!["claude", "codex"].includes(c.name) || params.allowedAgents.includes(c.name)),
|
|
168
|
+
(!["claude", "codex", "workbuddy"].includes(c.name) || params.allowedAgents.includes(c.name)),
|
|
168
169
|
).map((c) => ({
|
|
169
170
|
name: c.name,
|
|
170
171
|
...(c.args ? { args: c.args } : {}),
|
package/src/core/commands.ts
CHANGED
|
@@ -68,6 +68,7 @@ export function parseCommand(raw: string): ParsedCommand {
|
|
|
68
68
|
// 快捷切换到内置专家
|
|
69
69
|
case "claude":
|
|
70
70
|
case "codex":
|
|
71
|
+
case "workbuddy":
|
|
71
72
|
return arg ? { kind: "chat", text } : { kind: "agent", agent: head.toLowerCase() };
|
|
72
73
|
case "stop":
|
|
73
74
|
return { kind: "stop" };
|
|
@@ -126,7 +127,7 @@ export function helpText(agents: string[], channel?: string): string {
|
|
|
126
127
|
...BUILTIN_COMMANDS.filter((c) => !c.multiAgentOnly || multi)
|
|
127
128
|
.filter((c) => !c.feishuOnly || channel === "feishu")
|
|
128
129
|
.filter((c) => !c.chatOnly || channel === "feishu" || channel === "weixin")
|
|
129
|
-
.filter((c) => !["claude", "codex"].includes(c.name))
|
|
130
|
+
.filter((c) => !["claude", "codex", "workbuddy"].includes(c.name))
|
|
130
131
|
.map((c) =>
|
|
131
132
|
c.name === "expert"
|
|
132
133
|
? `\`${usageOf(c)}\` ${c.description}${multi ? `,也可以直接发 ${agents.map((a) => `\`/${a}\``).join(" ")}` : ""}`
|
package/src/core/config.ts
CHANGED
|
@@ -61,6 +61,21 @@ export type AppConfig = {
|
|
|
61
61
|
/** 生成会话名称用的模型,空 = Codex 默认模型 */
|
|
62
62
|
titleModel: string;
|
|
63
63
|
};
|
|
64
|
+
/** 腾讯 WorkBuddy(CodeBuddy Code):SDK 自带 CLI,登录在 设置 → Agent 里用浏览器完成 */
|
|
65
|
+
workbuddy: {
|
|
66
|
+
enabled: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* 账号所在站点:workbuddy 用本机 WorkBuddy 桌面版的 CLI(www.workbuddy.cn);
|
|
69
|
+
* internal / external / ioa 用 SDK 自带的 CLI 连 CodeBuddy 国内版、国际版、腾讯内网
|
|
70
|
+
*/
|
|
71
|
+
environment: "workbuddy" | "internal" | "external" | "ioa";
|
|
72
|
+
/** WorkBuddy 桌面版里 CLI 的路径,空 = 在常见位置自动找 */
|
|
73
|
+
cliPath: string;
|
|
74
|
+
defaultModel: string;
|
|
75
|
+
/** WorkBuddy 没有思考程度,留着和别的 agent 同形 */
|
|
76
|
+
defaultEffort: string;
|
|
77
|
+
models: string[];
|
|
78
|
+
};
|
|
64
79
|
};
|
|
65
80
|
web: {
|
|
66
81
|
enabled: boolean;
|
|
@@ -80,7 +95,7 @@ export type AppConfig = {
|
|
|
80
95
|
quotaEnabled: boolean;
|
|
81
96
|
};
|
|
82
97
|
/** 输入「/」时命令列表的顺序和隐藏项,按 agent 分开(设置 → 命令) */
|
|
83
|
-
commands: { claude: CommandPrefs; codex: CommandPrefs };
|
|
98
|
+
commands: { claude: CommandPrefs; codex: CommandPrefs; workbuddy: CommandPrefs };
|
|
84
99
|
/** 远程控制:网页终端和远程桌面。管理员能用;成员要在 设置 → 用户 里单独开(users.json 的 remote) */
|
|
85
100
|
remote: {
|
|
86
101
|
terminal: boolean;
|
|
@@ -117,7 +132,7 @@ export type AppConfig = {
|
|
|
117
132
|
};
|
|
118
133
|
};
|
|
119
134
|
|
|
120
|
-
export const AGENT_IDS = ["claude", "codex"] as const;
|
|
135
|
+
export const AGENT_IDS = ["claude", "codex", "workbuddy"] as const;
|
|
121
136
|
|
|
122
137
|
export function defaultConfig(): AppConfig {
|
|
123
138
|
return {
|
|
@@ -137,9 +152,11 @@ export function defaultConfig(): AppConfig {
|
|
|
137
152
|
autoTitle: false,
|
|
138
153
|
titleModel: "",
|
|
139
154
|
},
|
|
155
|
+
// 默认不开:要先在设置里登录
|
|
156
|
+
workbuddy: { enabled: false, environment: "workbuddy", cliPath: "", defaultModel: "", defaultEffort: "", models: [] },
|
|
140
157
|
},
|
|
141
158
|
web: { enabled: true, host: "0.0.0.0", port: 8800, passwordHash: "", trustedProxies: ["127.0.0.1", "::1"], quotaRefreshMin: 10, quotaEnabled: true },
|
|
142
|
-
commands: { claude: { order: [], hidden: [], custom: [] }, codex: { order: [], hidden: [], custom: [] } },
|
|
159
|
+
commands: { claude: { order: [], hidden: [], custom: [] }, codex: { order: [], hidden: [], custom: [] }, workbuddy: { order: [], hidden: [], custom: [] } },
|
|
143
160
|
remote: {
|
|
144
161
|
terminal: true,
|
|
145
162
|
desktop: true,
|