agent-loft 0.2.97 → 0.2.99
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 +6 -6
- package/package.json +1 -1
- package/src/agents/claude/session.ts +57 -5
- 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/channels/feishu/cards.ts +9 -4
- package/src/channels/web/api.ts +8 -0
- package/src/channels/web/experts-api.ts +32 -5
- package/src/channels/web/skills-api.ts +42 -27
- package/src/channels/weixin/bot.ts +2 -1
- package/src/channels/weixin/format.ts +5 -5
- package/src/core/builtin-agents.ts +49 -8
- package/src/core/command-catalog.ts +2 -1
- package/src/core/commands.ts +11 -0
- package/src/core/experts.ts +18 -9
- package/src/core/hub.ts +62 -12
- package/src/core/interactions.ts +1 -1
- package/src/core/mcp.ts +121 -18
- package/src/core/permission.ts +20 -2
- package/src/core/skill-runtime.ts +5 -4
- package/src/core/skills-bridge.ts +95 -24
- package/src/core/skills.ts +184 -37
- package/src/core/store.ts +5 -0
- package/src/core/types.ts +14 -0
- package/src/mcp/tasks-server.ts +1 -1
- package/web/css/composer.css +15 -0
- package/web/lib/permission.js +23 -4
- package/web/settings/agents.js +15 -5
- package/web/settings/commands.js +1 -1
- package/web/settings/experts.js +63 -10
- package/web/settings/skills.js +38 -13
- package/web/state.js +4 -0
- package/web/views/composer.js +4 -3
- package/web/views/conv-actions.js +24 -4
- package/web/views/interaction.js +9 -5
- package/web/views/sidebar.js +1 -0
- package/web/views/tasks.js +2 -2
- package/web/views/topbar.js +15 -10
package/src/core/mcp.ts
CHANGED
|
@@ -6,6 +6,13 @@
|
|
|
6
6
|
// 环境变量和请求头可以标成密钥:网页上不回显,只说填没填。值只交给 MCP 进程 / 请求头,不进 agent 的提示词。
|
|
7
7
|
// 和技能一样是「信任型」的:能执行命令的专家读得到 data/ 下的文件,包括这里的值。
|
|
8
8
|
//
|
|
9
|
+
// stdio 会在服务器上直接执行命令,不受专家权限(只联网、只读……)的约束,所以只有管理员能添加;
|
|
10
|
+
// 成员以前建的 stdio 不再启动(可以删)。
|
|
11
|
+
//
|
|
12
|
+
// 共享:作者打开 shared,其他账号就能在专家 / 内置 Agent 里选它。共享的是「定义」(命令、地址、
|
|
13
|
+
// 普通的环境变量和请求头),标成密钥的那几项每个人填自己的值(data/mcp-values.json),作者的不会给出去。
|
|
14
|
+
// 用别人共享的 MCP,调用它的工具前一律先弹授权卡。
|
|
15
|
+
//
|
|
9
16
|
// 机器上原有的 MCP(Claude 的 ~/.claude.json、Codex 的 config.toml)只给管理员选,id 写成 machine:<名字>。
|
|
10
17
|
// 内置的 Claude Code / Codex 专家按 builtin-agents.ts 的个人默认选择加载;管理员默认沿用机器配置。
|
|
11
18
|
//
|
|
@@ -17,6 +24,7 @@ import { EventEmitter } from "node:events";
|
|
|
17
24
|
import { dataDir, readJson, writeJsonAtomic } from "../home.js";
|
|
18
25
|
import { MEMORY_MCP_NAME } from "./memory-mcp.js";
|
|
19
26
|
import { SKILLS_MCP_NAME, TASKS_MCP_NAME } from "./tasks-mcp.js";
|
|
27
|
+
import { getUser, listUsers } from "./users.js";
|
|
20
28
|
|
|
21
29
|
export type McpPair = { name: string; value: string; secret: boolean };
|
|
22
30
|
|
|
@@ -34,8 +42,10 @@ export type McpServer = {
|
|
|
34
42
|
env: McpPair[];
|
|
35
43
|
/** http 的请求头 */
|
|
36
44
|
headers: McpPair[];
|
|
37
|
-
/**
|
|
45
|
+
/** 调用这个服务的工具前先弹授权卡(默认不问:是用户自己给专家挂的)。别人用共享的一律要问 */
|
|
38
46
|
ask: boolean;
|
|
47
|
+
/** 共享给所有账号:别人能选它,密钥项填自己的值 */
|
|
48
|
+
shared?: boolean;
|
|
39
49
|
createdAt: number;
|
|
40
50
|
updatedAt: number;
|
|
41
51
|
};
|
|
@@ -53,9 +63,15 @@ export const MACHINE_PREFIX = "machine:";
|
|
|
53
63
|
export const MCP_LIMITS = { perUser: 50, description: 500, command: 1000, args: 50, arg: 2000, pairs: 30, value: 4000, url: 2000 };
|
|
54
64
|
|
|
55
65
|
const storePath = path.join(dataDir, "mcp.json");
|
|
66
|
+
/** 别人共享的 MCP,每个人自己填的密钥:用户 id → MCP id → 项名 → 值 */
|
|
67
|
+
const valuesPath = path.join(dataDir, "mcp-values.json");
|
|
68
|
+
|
|
69
|
+
/** 有变化。users:受影响的人(作者;共享的就是所有人),他们用着的会话空闲下来要换上新的 */
|
|
70
|
+
export const mcpEvents = new EventEmitter<{ changed: [users: string[], id: string] }>();
|
|
56
71
|
|
|
57
|
-
|
|
58
|
-
|
|
72
|
+
function touched(s: Pick<McpServer, "owner" | "shared">, wasShared = false): string[] {
|
|
73
|
+
return s.shared || wasShared ? [...new Set([s.owner, ...listUsers().map((u) => u.id)])] : [s.owner];
|
|
74
|
+
}
|
|
59
75
|
|
|
60
76
|
let cache: McpServer[] | null = null;
|
|
61
77
|
|
|
@@ -82,6 +98,74 @@ export function getMcp(id: string): McpServer | undefined {
|
|
|
82
98
|
return load().find((s) => s.id === id);
|
|
83
99
|
}
|
|
84
100
|
|
|
101
|
+
/** 这个服务能不能启动:stdio 要作者是管理员(成员以前建的不再启动) */
|
|
102
|
+
export function runnable(s: McpServer): boolean {
|
|
103
|
+
return s.type !== "stdio" || getUser(s.owner)?.role === "admin";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 这个人能不能用:自己的,或者别人共享出来的(作者账号还在、没被停用) */
|
|
107
|
+
export function canUseMcp(userId: string, s: McpServer | string | undefined): boolean {
|
|
108
|
+
const server = typeof s === "string" ? getMcp(s) : s;
|
|
109
|
+
if (!server || !runnable(server)) return false;
|
|
110
|
+
if (server.owner === userId) return true;
|
|
111
|
+
const author = getUser(server.owner);
|
|
112
|
+
const user = getUser(userId);
|
|
113
|
+
return server.shared === true && !!author && !author.disabled && !!user && !user.disabled;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 这个人能选的:自己的在前,别人共享的在后 */
|
|
117
|
+
export function listUsableMcp(userId: string): McpServer[] {
|
|
118
|
+
const others = load()
|
|
119
|
+
.filter((s) => s.owner !== userId && canUseMcp(userId, s))
|
|
120
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
121
|
+
return [...listMcp(userId), ...others];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function allValues(): Record<string, Record<string, Record<string, string>>> {
|
|
125
|
+
return readJson<Record<string, Record<string, Record<string, string>>>>(valuesPath, {});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 这个人给别人共享的 MCP 填的密钥 */
|
|
129
|
+
export function mcpUserValues(userId: string, id: string): Record<string, string> {
|
|
130
|
+
return allValues()[userId]?.[id] ?? {};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 填自己的密钥:只能填作者标成密钥的项;空字符串 / null = 清掉,没给的项不变 */
|
|
134
|
+
export function setMcpUserValues(userId: string, id: string, raw: unknown): void {
|
|
135
|
+
const s = getMcp(id);
|
|
136
|
+
if (!s || s.owner === userId || !canUseMcp(userId, s)) throw new Error("这个 MCP 不存在");
|
|
137
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("格式不对");
|
|
138
|
+
const secretNames = new Set([...s.env, ...s.headers].filter((p) => p.secret).map((p) => p.name));
|
|
139
|
+
const all = allValues();
|
|
140
|
+
const mine = { ...(all[userId]?.[id] ?? {}) };
|
|
141
|
+
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
142
|
+
if (!secretNames.has(k)) throw new Error(`「${k}」不是这个 MCP 要填的密钥`);
|
|
143
|
+
if (v === null || v === undefined || v === "") delete mine[k];
|
|
144
|
+
else {
|
|
145
|
+
const value = String(v);
|
|
146
|
+
if (value.length > MCP_LIMITS.value) throw new Error(`「${k}」的值太长`);
|
|
147
|
+
mine[k] = value;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
(all[userId] ??= {})[id] = mine;
|
|
151
|
+
writeJsonAtomic(valuesPath, all);
|
|
152
|
+
mcpEvents.emit("changed", [userId], id);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function dropValues(pred: (userId: string, id: string) => boolean): void {
|
|
156
|
+
const all = allValues();
|
|
157
|
+
let changed = false;
|
|
158
|
+
for (const [u, byId] of Object.entries(all)) {
|
|
159
|
+
for (const id of Object.keys(byId)) {
|
|
160
|
+
if (!pred(u, id)) continue;
|
|
161
|
+
delete byId[id];
|
|
162
|
+
changed = true;
|
|
163
|
+
}
|
|
164
|
+
if (!Object.keys(byId).length) delete all[u];
|
|
165
|
+
}
|
|
166
|
+
if (changed) writeJsonAtomic(valuesPath, all);
|
|
167
|
+
}
|
|
168
|
+
|
|
85
169
|
export type McpInput = {
|
|
86
170
|
name?: unknown;
|
|
87
171
|
description?: unknown;
|
|
@@ -92,6 +176,7 @@ export type McpInput = {
|
|
|
92
176
|
env?: unknown;
|
|
93
177
|
headers?: unknown;
|
|
94
178
|
ask?: unknown;
|
|
179
|
+
shared?: unknown;
|
|
95
180
|
};
|
|
96
181
|
|
|
97
182
|
const str = (v: unknown, max: number, what: string): string => {
|
|
@@ -134,7 +219,9 @@ function validate(owner: string, input: McpInput, prev?: McpServer): Omit<McpSer
|
|
|
134
219
|
if (!type) throw new Error("类型只能是 stdio 或 http");
|
|
135
220
|
const description = input.description === undefined && prev ? prev.description : str(input.description, MCP_LIMITS.description, "说明");
|
|
136
221
|
const ask = input.ask === undefined && prev ? prev.ask : input.ask === true;
|
|
222
|
+
const shared = input.shared === undefined && prev ? prev.shared === true : input.shared === true;
|
|
137
223
|
if (type === "stdio") {
|
|
224
|
+
if (getUser(owner)?.role !== "admin") throw new Error("本机进程(stdio)会在服务器上直接执行命令,只有管理员能添加或修改;可以改用 HTTP 地址");
|
|
138
225
|
const command = input.command === undefined && prev?.command ? prev.command : str(input.command, MCP_LIMITS.command, "命令");
|
|
139
226
|
if (!command) throw new Error("stdio 要填启动命令");
|
|
140
227
|
let args = prev?.args ?? [];
|
|
@@ -144,7 +231,7 @@ function validate(owner: string, input: McpInput, prev?: McpServer): Omit<McpSer
|
|
|
144
231
|
args = input.args.map((a) => String(a ?? ""));
|
|
145
232
|
if (args.some((a) => a.length > MCP_LIMITS.arg)) throw new Error("有个参数太长");
|
|
146
233
|
}
|
|
147
|
-
return { name, description, type, command, args, env: cleanPairs(input.env, prev?.env ?? [], "环境变量"), headers: [], ask };
|
|
234
|
+
return { name, description, type, command, args, env: cleanPairs(input.env, prev?.env ?? [], "环境变量"), headers: [], ask, shared };
|
|
148
235
|
}
|
|
149
236
|
const url = input.url === undefined && prev?.url ? prev.url : str(input.url, MCP_LIMITS.url, "地址");
|
|
150
237
|
let parsed: URL;
|
|
@@ -154,7 +241,7 @@ function validate(owner: string, input: McpInput, prev?: McpServer): Omit<McpSer
|
|
|
154
241
|
throw new Error("地址不对:要写完整的 http:// 或 https:// 地址");
|
|
155
242
|
}
|
|
156
243
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("地址只能是 http:// 或 https://");
|
|
157
|
-
return { name, description, type, url, env: [], headers: cleanPairs(input.headers, prev?.headers ?? [], "请求头"), ask };
|
|
244
|
+
return { name, description, type, url, env: [], headers: cleanPairs(input.headers, prev?.headers ?? [], "请求头"), ask, shared };
|
|
158
245
|
}
|
|
159
246
|
|
|
160
247
|
export function createMcp(owner: string, input: McpInput): McpServer {
|
|
@@ -163,7 +250,7 @@ export function createMcp(owner: string, input: McpInput): McpServer {
|
|
|
163
250
|
const server: McpServer = { id: `m_${crypto.randomBytes(6).toString("hex")}`, owner, ...validate(owner, input), createdAt: now, updatedAt: now };
|
|
164
251
|
load().push(server);
|
|
165
252
|
save();
|
|
166
|
-
mcpEvents.emit("changed",
|
|
253
|
+
mcpEvents.emit("changed", touched(server), server.id);
|
|
167
254
|
return server;
|
|
168
255
|
}
|
|
169
256
|
|
|
@@ -175,7 +262,9 @@ export function updateMcp(owner: string, id: string, input: McpInput): McpServer
|
|
|
175
262
|
const next: McpServer = { ...prev, ...validate(owner, input, prev), updatedAt: Date.now() };
|
|
176
263
|
list[idx] = next;
|
|
177
264
|
save();
|
|
178
|
-
|
|
265
|
+
// 取消共享:别人填的密钥也删掉
|
|
266
|
+
if (prev.shared && !next.shared) dropValues((_u, x) => x === id);
|
|
267
|
+
mcpEvents.emit("changed", touched(next, prev.shared), id);
|
|
179
268
|
return next;
|
|
180
269
|
}
|
|
181
270
|
|
|
@@ -183,22 +272,29 @@ export function deleteMcp(owner: string, id: string): void {
|
|
|
183
272
|
const list = load();
|
|
184
273
|
const idx = list.findIndex((s) => s.id === id && s.owner === owner);
|
|
185
274
|
if (idx < 0) throw new Error("这个 MCP 不存在");
|
|
186
|
-
list.splice(idx, 1);
|
|
275
|
+
const [gone] = list.splice(idx, 1);
|
|
187
276
|
save();
|
|
188
|
-
|
|
277
|
+
dropValues((_u, x) => x === id);
|
|
278
|
+
mcpEvents.emit("changed", touched(gone!), id);
|
|
189
279
|
}
|
|
190
280
|
|
|
191
281
|
export function purgeUserMcp(owner: string): void {
|
|
192
282
|
const list = load();
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
283
|
+
const mine = list.filter((s) => s.owner === owner);
|
|
284
|
+
const ids = new Set(mine.map((s) => s.id));
|
|
285
|
+
dropValues((u, id) => u === owner || ids.has(id));
|
|
286
|
+
if (!mine.length) return;
|
|
287
|
+
cache = list.filter((s) => s.owner !== owner);
|
|
196
288
|
save();
|
|
289
|
+
if (mine.some((s) => s.shared)) mcpEvents.emit("changed", touched({ owner, shared: true }), mine[0]!.id);
|
|
197
290
|
}
|
|
198
291
|
|
|
199
|
-
/**
|
|
200
|
-
export function mcpView(s: McpServer) {
|
|
201
|
-
const
|
|
292
|
+
/** 网页上看的样子:密钥不回显。viewer 不是作者时,密钥项说的是他自己填没填 */
|
|
293
|
+
export function mcpView(s: McpServer, viewer: string = s.owner) {
|
|
294
|
+
const mine = viewer === s.owner;
|
|
295
|
+
const own = mine ? {} : mcpUserValues(viewer, s.id);
|
|
296
|
+
const pairs = (list: McpPair[]) =>
|
|
297
|
+
list.map((p) => (p.secret ? { name: p.name, secret: true, set: mine ? p.value !== "" : !!own[p.name] } : { name: p.name, value: p.value, secret: false }));
|
|
202
298
|
return {
|
|
203
299
|
id: s.id,
|
|
204
300
|
name: s.name,
|
|
@@ -206,15 +302,22 @@ export function mcpView(s: McpServer) {
|
|
|
206
302
|
type: s.type,
|
|
207
303
|
...(s.type === "stdio" ? { command: s.command ?? "", args: s.args ?? [], env: pairs(s.env) } : { url: s.url ?? "", headers: pairs(s.headers) }),
|
|
208
304
|
ask: s.ask,
|
|
305
|
+
shared: s.shared === true,
|
|
306
|
+
mine,
|
|
307
|
+
...(mine ? {} : { ownerName: getUser(s.owner)?.name ?? "(已删除的用户)" }),
|
|
308
|
+
runnable: runnable(s),
|
|
209
309
|
createdAt: s.createdAt,
|
|
210
310
|
updatedAt: s.updatedAt,
|
|
211
311
|
};
|
|
212
312
|
}
|
|
213
313
|
|
|
214
|
-
|
|
314
|
+
/** 交给 agent 的启动参数。user 不是作者(用的是共享的):密钥项换成他自己填的,没填就不带 */
|
|
315
|
+
export function specOf(s: McpServer, user: string = s.owner): McpSpec {
|
|
316
|
+
const own = user === s.owner ? undefined : mcpUserValues(user, s.id);
|
|
317
|
+
const value = (p: McpPair) => (own && p.secret ? (own[p.name] ?? "") : p.value);
|
|
215
318
|
return s.type === "stdio"
|
|
216
|
-
? { type: "stdio", command: s.command ?? "", args: s.args ?? [], env: Object.fromEntries(s.env.map((p) => [p.name, p
|
|
217
|
-
: { type: "http", url: s.url ?? "", headers: Object.fromEntries(s.headers.filter((p) => p
|
|
319
|
+
? { type: "stdio", command: s.command ?? "", args: s.args ?? [], env: Object.fromEntries(s.env.filter((p) => !own || !p.secret || value(p) !== "").map((p) => [p.name, value(p)])) }
|
|
320
|
+
: { type: "http", url: s.url ?? "", headers: Object.fromEntries(s.headers.filter((p) => value(p) !== "").map((p) => [p.name, value(p)])) };
|
|
218
321
|
}
|
|
219
322
|
|
|
220
323
|
// ---------- 机器上原有的 ----------
|
package/src/core/permission.ts
CHANGED
|
@@ -2,27 +2,45 @@
|
|
|
2
2
|
//
|
|
3
3
|
// ask 逐次询问 Claude:default; Codex:只读沙箱(写文件要批准)
|
|
4
4
|
// edit 自动改文件 Claude:acceptEdits; Codex:工作区可写沙箱
|
|
5
|
+
// auto 自动判断 Claude:auto(分类器逐个判断,拿不准再问);Codex 没有,按自动改文件算
|
|
5
6
|
// full 完全允许 Claude:default + 全放行;Codex:无沙箱 + 全放行
|
|
6
7
|
//
|
|
7
|
-
// 不选级别(undefined)=
|
|
8
|
+
// 不选级别(undefined)= 按主人在设置里定的默认(见 builtin-agents.ts),没定就是老行为:
|
|
9
|
+
// Claude 逐次询问,Codex 按设置里的沙箱。老对话、老任务都不受影响。
|
|
8
10
|
//
|
|
9
11
|
// 完全允许不用 Claude 的 bypassPermissions:那会让 canUseTool 变成死代码,提问卡和「调用前询问」的 MCP 都走不到。
|
|
10
12
|
// Codex 也不用 approvalPolicy: never:实测 on-request 配无沙箱一样不弹审批,还留着 MCP 审批这条路。
|
|
13
|
+
//
|
|
14
|
+
// 计划模式(先出方案、批准了再动手)不是一个级别,是和级别叠加的开关,见 store.ts 的 Conversation.plan。
|
|
11
15
|
import type { ExpertAccess } from "./experts.js";
|
|
12
16
|
|
|
13
|
-
export const PERMISSION_LEVELS = ["ask", "edit", "full"] as const;
|
|
17
|
+
export const PERMISSION_LEVELS = ["ask", "edit", "auto", "full"] as const;
|
|
14
18
|
export type PermissionLevel = (typeof PERMISSION_LEVELS)[number];
|
|
15
19
|
|
|
16
20
|
export const PERMISSION_LABEL: Record<PermissionLevel, string> = {
|
|
17
21
|
ask: "逐次询问",
|
|
18
22
|
edit: "自动改文件",
|
|
23
|
+
auto: "自动判断",
|
|
19
24
|
full: "完全允许",
|
|
20
25
|
};
|
|
21
26
|
|
|
27
|
+
/** 能当默认权限的级别:完全允许是对一次任务说的,不能默认放开 */
|
|
28
|
+
export const DEFAULT_PERMISSION_LEVELS = ["ask", "edit", "auto"] as const;
|
|
29
|
+
|
|
22
30
|
export function isPermissionLevel(v: unknown): v is PermissionLevel {
|
|
23
31
|
return typeof v === "string" && (PERMISSION_LEVELS as readonly string[]).includes(v);
|
|
24
32
|
}
|
|
25
33
|
|
|
34
|
+
/** 这个引擎认不认这一级:自动判断只有 Claude 有 */
|
|
35
|
+
export function engineSupports(agent: string, level: PermissionLevel): boolean {
|
|
36
|
+
return level !== "auto" || agent === "claude";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 引擎不认的级别降到它认的最近一级(Codex 的自动判断按自动改文件算) */
|
|
40
|
+
export function forEngine(agent: string, level: PermissionLevel): PermissionLevel {
|
|
41
|
+
return engineSupports(agent, level) ? level : "edit";
|
|
42
|
+
}
|
|
43
|
+
|
|
26
44
|
export function minPermission(a: PermissionLevel, b: PermissionLevel): PermissionLevel {
|
|
27
45
|
return PERMISSION_LEVELS.indexOf(a) <= PERMISSION_LEVELS.indexOf(b) ? a : b;
|
|
28
46
|
}
|
|
@@ -14,7 +14,7 @@ import fs from "node:fs";
|
|
|
14
14
|
import os from "node:os";
|
|
15
15
|
import path from "node:path";
|
|
16
16
|
import { config } from "./config.js";
|
|
17
|
-
import { activeSkills, parseSkillMd, pluginsRoot,
|
|
17
|
+
import { activeSkills, allowedHosts, guardedNames, parseSkillMd, pluginsRoot, skillDir, skillEnv, userPrefs, type Skill } from "./skills.js";
|
|
18
18
|
import { SKILLS_MCP_NAME } from "./tasks-mcp.js";
|
|
19
19
|
import type { SessionSkills } from "./types.js";
|
|
20
20
|
import { getUser } from "./users.js";
|
|
@@ -152,11 +152,12 @@ export function syncPluginDir(userId: string, skills: Skill[], scope?: string):
|
|
|
152
152
|
/** 受保护的密钥怎么用:只能经 skill_request 代发。没有就是空 */
|
|
153
153
|
function protectedLines(skills: Skill[], userId: string): string[] {
|
|
154
154
|
const prefs = userPrefs(userId);
|
|
155
|
-
const
|
|
155
|
+
const declared = new Set(skills.flatMap((s) => s.vars.map((v) => v.name)));
|
|
156
|
+
const names = [...guardedNames(userId)].filter((n) => declared.has(n) && prefs.vars[n] !== undefined);
|
|
156
157
|
if (!names.length) return [];
|
|
157
158
|
return [
|
|
158
|
-
`这些密钥受保护,不在环境变量里,你也看不到值:${names.map((n) => `${n}(只能发往 ${(prefs
|
|
159
|
-
`要调用接口时用 ${SKILLS_MCP_NAME} 的 skill_request 工具,在
|
|
159
|
+
`这些密钥受保护,不在环境变量里,你也看不到值:${names.map((n) => `${n}(只能发往 ${allowedHosts(prefs, skills, n).join("、") || "用户还没确认的地址"})`).join(";")}。` +
|
|
160
|
+
`要调用接口时用 ${SKILLS_MCP_NAME} 的 skill_request 工具,在 headers 或 url 的查询参数(? 后面)里写 {{变量名}},agent-loft 发请求时才换成真值;受保护的密钥不能写进 body 和 url 的主机、路径。技能说明里写的是 curl $变量名 的,换成 skill_request 来发。`,
|
|
160
161
|
];
|
|
161
162
|
}
|
|
162
163
|
|
|
@@ -9,15 +9,19 @@ import { hub } from "./hub.js";
|
|
|
9
9
|
import { interactions } from "./interactions.js";
|
|
10
10
|
import { config } from "./config.js";
|
|
11
11
|
import { TASK_TOOL_TIMEOUT_SEC } from "./tasks-mcp.js";
|
|
12
|
+
import { builtinAgentDefaults } from "./builtin-agents.js";
|
|
13
|
+
import { expertTools, getExpert, isBuiltin } from "./experts.js";
|
|
14
|
+
import { getConversation } from "./store.js";
|
|
12
15
|
import {
|
|
13
16
|
activeSkills,
|
|
17
|
+
allowedHosts,
|
|
14
18
|
canSee,
|
|
15
19
|
cleanVars,
|
|
16
20
|
createSkill,
|
|
17
21
|
findSkillByName,
|
|
22
|
+
guardedNames,
|
|
18
23
|
hostAllowed,
|
|
19
24
|
isProtected,
|
|
20
|
-
protectedNames,
|
|
21
25
|
listFiles,
|
|
22
26
|
readSkillFile,
|
|
23
27
|
readSkillMd,
|
|
@@ -39,33 +43,91 @@ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"];
|
|
|
39
43
|
const RESPONSE_MAX = 256 * 1024;
|
|
40
44
|
const PLACEHOLDER = /\{\{\s*([A-Z][A-Z0-9_]{1,63})\s*\}\}/g;
|
|
41
45
|
|
|
42
|
-
/**
|
|
46
|
+
/** 响应里出现了密钥的值(接口回显、报错里带着):原文、URL 编码、base64 的都换掉,别让它回到模型手里 */
|
|
43
47
|
function redact(text: string, secrets: [string, string][]): string {
|
|
44
48
|
let out = text;
|
|
45
|
-
for (const [name, value] of secrets)
|
|
49
|
+
for (const [name, value] of secrets) {
|
|
50
|
+
const forms = new Set([value, encodeURIComponent(value), Buffer.from(value, "utf8").toString("base64"), Buffer.from(value, "utf8").toString("base64url")]);
|
|
51
|
+
for (const f of [...forms].sort((x, y) => y.length - x.length)) if (f.length >= 4) out = out.split(f).join(`[已隐藏 ${name}]`);
|
|
52
|
+
}
|
|
46
53
|
return out;
|
|
47
54
|
}
|
|
48
55
|
|
|
56
|
+
/** 局域网、本机的地址:受保护的密钥只有发往这些时才允许走明文 http */
|
|
57
|
+
function isPrivateHost(host: string): boolean {
|
|
58
|
+
const h = host.toLowerCase().replace(/^\[|\]$/g, "");
|
|
59
|
+
return (
|
|
60
|
+
h === "localhost" ||
|
|
61
|
+
h === "::1" ||
|
|
62
|
+
h.endsWith(".local") ||
|
|
63
|
+
h.endsWith(".lan") ||
|
|
64
|
+
/^127\./.test(h) ||
|
|
65
|
+
/^10\./.test(h) ||
|
|
66
|
+
/^192\.168\./.test(h) ||
|
|
67
|
+
/^172\.(1[6-9]|2\d|3[01])\./.test(h) ||
|
|
68
|
+
/^169\.254\./.test(h)
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
49
72
|
/**
|
|
50
|
-
*
|
|
51
|
-
*
|
|
73
|
+
* 这条对话的会话挂了哪些技能(和 hub 开会话时的算法一样):自定义专家选中的(连同子智能体的)、
|
|
74
|
+
* 内置 Agent 默认加载的。undefined = 全部启用着的。
|
|
75
|
+
*/
|
|
76
|
+
export function skillScope(userId: string, convKey: string): Set<string> | undefined {
|
|
77
|
+
const conv = getConversation(convKey);
|
|
78
|
+
if (!conv) return new Set();
|
|
79
|
+
try {
|
|
80
|
+
if (conv.expert) {
|
|
81
|
+
const e = getExpert(conv.expert);
|
|
82
|
+
if (!e) return new Set();
|
|
83
|
+
const ids = new Set(expertTools(userId, e).skills);
|
|
84
|
+
for (const subId of e.subagents) {
|
|
85
|
+
const sub = getExpert(subId);
|
|
86
|
+
if (!sub || sub.owner !== e.owner) continue;
|
|
87
|
+
try {
|
|
88
|
+
for (const id of expertTools(userId, sub).skills) ids.add(id);
|
|
89
|
+
} catch {
|
|
90
|
+
// 子智能体取消共享了:它的技能不算
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return ids;
|
|
94
|
+
}
|
|
95
|
+
if (isBuiltin(conv.agent)) {
|
|
96
|
+
const picked = builtinAgentDefaults(userId)[conv.agent].skills;
|
|
97
|
+
return picked ? new Set(picked) : undefined;
|
|
98
|
+
}
|
|
99
|
+
} catch {
|
|
100
|
+
return new Set();
|
|
101
|
+
}
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
type Where = "header" | "query" | "url" | "body";
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 按 agent 给的 url / headers / body 发一个 HTTP 请求,里面的 {{NAME}} 换成用户填的变量值。只认这条对话
|
|
109
|
+
* 挂着的技能(scope)声明过的变量。受保护的密钥:
|
|
110
|
+
* - 只能发往用户对这些技能确认过、技能现在还声明着的地址(按换完之后的地址查:塞进主机名里也逃不掉);
|
|
111
|
+
* - 只能写在请求头和 url 的查询参数里 —— 写进 body 就能借允许的服务本身发出去(比如建一个公开的 gist);
|
|
112
|
+
* - 只走 https,局域网、本机的地址才允许 http。
|
|
52
113
|
* 不跟随跳转(跳到别处会把带着密钥的请求带过去),响应里出现的变量值一律抹掉。
|
|
53
114
|
*/
|
|
54
|
-
export async function skillRequest(userId: string, args: Record<string, unknown>): Promise<Reply> {
|
|
115
|
+
export async function skillRequest(userId: string, args: Record<string, unknown>, scope?: Set<string>): Promise<Reply> {
|
|
55
116
|
const prefs = userPrefs(userId);
|
|
56
|
-
const skills = activeSkills(userId);
|
|
57
|
-
const guarded =
|
|
117
|
+
const skills = activeSkills(userId).filter((sk) => !scope || scope.has(sk.id));
|
|
118
|
+
const guarded = guardedNames(userId);
|
|
58
119
|
const declared = new Set(skills.flatMap((sk) => sk.vars.map((v) => v.name)));
|
|
59
120
|
const method = String(args.method ?? "GET").toUpperCase();
|
|
60
121
|
if (!METHODS.includes(method)) return fail(`method 只能是 ${METHODS.join("、")}`);
|
|
61
122
|
const rawHeaders = args.headers && typeof args.headers === "object" ? (args.headers as Record<string, unknown>) : {};
|
|
62
123
|
const body = args.body === undefined || args.body === null ? undefined : String(args.body);
|
|
63
124
|
|
|
64
|
-
const used = new Set<
|
|
125
|
+
const used = new Map<string, Set<Where>>();
|
|
65
126
|
const missing = new Set<string>();
|
|
66
|
-
const fillIn = (text: string, encode: boolean) =>
|
|
67
|
-
text.replace(PLACEHOLDER, (m, name: string) => {
|
|
68
|
-
used.
|
|
127
|
+
const fillIn = (text: string, where: (offset: number) => Where, encode: boolean) =>
|
|
128
|
+
text.replace(PLACEHOLDER, (m, name: string, offset: number) => {
|
|
129
|
+
if (!used.has(name)) used.set(name, new Set());
|
|
130
|
+
used.get(name)!.add(where(offset));
|
|
69
131
|
const value = declared.has(name) ? prefs.vars[name] : undefined;
|
|
70
132
|
if (value === undefined) {
|
|
71
133
|
missing.add(name);
|
|
@@ -73,22 +135,29 @@ export async function skillRequest(userId: string, args: Record<string, unknown>
|
|
|
73
135
|
}
|
|
74
136
|
return encode ? encodeURIComponent(value) : value;
|
|
75
137
|
});
|
|
138
|
+
const rawUrl = String(args.url ?? "");
|
|
139
|
+
const q = rawUrl.indexOf("?");
|
|
140
|
+
const hash = rawUrl.indexOf("#");
|
|
141
|
+
const inQuery = (offset: number): Where => (q >= 0 && offset > q && (hash < 0 || offset < hash) ? "query" : "url");
|
|
76
142
|
let url: URL;
|
|
77
143
|
try {
|
|
78
|
-
url = new URL(fillIn(
|
|
144
|
+
url = new URL(fillIn(rawUrl, inQuery, true));
|
|
79
145
|
} catch {
|
|
80
146
|
return fail("url 不是合法的地址。");
|
|
81
147
|
}
|
|
82
148
|
const headers: Record<string, string> = {};
|
|
83
|
-
for (const [k, v] of Object.entries(rawHeaders)) headers[k] = fillIn(String(v), false);
|
|
84
|
-
const filledBody = body === undefined ? undefined : fillIn(body, false);
|
|
149
|
+
for (const [k, v] of Object.entries(rawHeaders)) headers[k] = fillIn(String(v), () => "header", false);
|
|
150
|
+
const filledBody = body === undefined ? undefined : fillIn(body, () => "body", false);
|
|
85
151
|
if (missing.size) {
|
|
86
|
-
return fail(
|
|
152
|
+
return fail(`这些变量用户还没配(或者这个会话挂着的技能都没声明过):${[...missing].join("、")}。请用户去网页侧栏「技能」里填好,下一条消息起可用。`);
|
|
87
153
|
}
|
|
88
154
|
if (url.protocol !== "https:" && url.protocol !== "http:") return fail("只支持 http 和 https。");
|
|
89
|
-
for (const name of used) {
|
|
155
|
+
for (const [name, where] of used) {
|
|
90
156
|
if (!guarded.has(name)) continue;
|
|
91
|
-
|
|
157
|
+
if (where.has("body") || where.has("url")) {
|
|
158
|
+
return fail(`${name} 是受保护的密钥,只能写在 headers 或 url 的查询参数(? 后面)里,不能写进 body 或 url 的主机、路径。没有发出去。`);
|
|
159
|
+
}
|
|
160
|
+
const allowed = allowedHosts(prefs, skills, name);
|
|
92
161
|
if (!hostAllowed(allowed, url)) {
|
|
93
162
|
return fail(
|
|
94
163
|
allowed.length
|
|
@@ -96,9 +165,10 @@ export async function skillRequest(userId: string, args: Record<string, unknown>
|
|
|
96
165
|
: `${name} 允许发往的地址用户还没确认(技能作者可能改过),请用户去网页侧栏「技能」里确认一下。`,
|
|
97
166
|
);
|
|
98
167
|
}
|
|
168
|
+
if (url.protocol === "http:" && !isPrivateHost(url.hostname)) return fail(`${name} 是受保护的密钥,发往公网地址要用 https,没有发出去。`);
|
|
99
169
|
}
|
|
100
170
|
|
|
101
|
-
const secrets: [string, string][] = Object.entries(prefs.vars).filter(([k]) => declared.has(k));
|
|
171
|
+
const secrets: [string, string][] = Object.entries(prefs.vars).filter(([k]) => declared.has(k) || guarded.has(k));
|
|
102
172
|
let res: Response;
|
|
103
173
|
try {
|
|
104
174
|
res = await fetch(url, {
|
|
@@ -181,15 +251,16 @@ function cardOf(fields: { name: string; description?: string; body?: string; fil
|
|
|
181
251
|
function describe(s: Skill, userId: string): string {
|
|
182
252
|
const vars = userPrefs(userId).vars;
|
|
183
253
|
const v = s.vars.length
|
|
184
|
-
? ` · 变量 ${s.vars.map((x) => `${x.name}${vars[x.name] !== undefined ? "(已配)" : x.required ? "(未配,必填)" : "(未配)"}${isProtected(x) ? `(受保护,只能用 skill_request 发往 ${x.
|
|
254
|
+
? ` · 变量 ${s.vars.map((x) => `${x.name}${vars[x.name] !== undefined ? "(已配)" : x.required ? "(未配,必填)" : "(未配)"}${isProtected(x) ? `(受保护,只能用 skill_request 发往 ${allowedHosts(userPrefs(userId), [s], x.name).join("、") || "用户还没确认的地址"})` : ""}`).join("、")}`
|
|
185
255
|
: "";
|
|
186
256
|
return `- ${s.name}:${s.description}${s.owner === userId ? "(自己建的)" : `(${getUser(s.owner)?.name ?? "别人"}建的)`}${v}`;
|
|
187
257
|
}
|
|
188
258
|
|
|
189
259
|
export async function skillToolCall(userId: string, convKey: string, tool: string, args: Record<string, unknown>): Promise<Reply> {
|
|
190
|
-
if (tool === "skill_request") return skillRequest(userId, args);
|
|
260
|
+
if (tool === "skill_request") return skillRequest(userId, args, skillScope(userId, convKey));
|
|
191
261
|
if (tool === "list_skills") {
|
|
192
|
-
const
|
|
262
|
+
const scope = skillScope(userId, convKey);
|
|
263
|
+
const list = activeSkills(userId).filter((s) => !scope || scope.has(s.id));
|
|
193
264
|
if (!list.length) return { text: "用户在 agent-loft 里还没有启用任何技能。" };
|
|
194
265
|
return { text: `用户启用着的技能(${list.length} 个):\n${list.map((s) => describe(s, userId)).join("\n")}` };
|
|
195
266
|
}
|
|
@@ -230,7 +301,7 @@ export async function skillToolCall(userId: string, convKey: string, tool: strin
|
|
|
230
301
|
}
|
|
231
302
|
const description = String(args.description ?? "").trim();
|
|
232
303
|
const body = String(args.body ?? "").trim();
|
|
233
|
-
if (findSkillByName(name)) return fail(
|
|
304
|
+
if (findSkillByName(name)) return fail(`技能名 ${name} 已被占用,换个名字;要改自己的用 update_skill。`);
|
|
234
305
|
const ok = await confirm(convKey, `新建技能「${name}」`, `${cardOf({ name, description, body, files: [...files.keys()], vars })}\n\n建好后只有你自己看得到,可以在网页侧栏「技能」里修改、分享给别人。`);
|
|
235
306
|
if (!ok) return fail("用户没有同意,技能没有建。");
|
|
236
307
|
try {
|
|
@@ -269,7 +340,7 @@ export async function skillToolCall(userId: string, convKey: string, tool: strin
|
|
|
269
340
|
...(changes.write ? { files: [...changes.write.keys()] } : {}),
|
|
270
341
|
...(changes.remove ? { removed: changes.remove } : {}),
|
|
271
342
|
...(vars ? { vars } : {}),
|
|
272
|
-
})}${s.visibility !== "private" ? "\n\n
|
|
343
|
+
})}${s.visibility !== "private" ? "\n\n这个技能分享给了别人:内容有变化时,装了它的人要在网页上确认新版之后才会加载。" : ""}`,
|
|
273
344
|
);
|
|
274
345
|
if (!ok) return fail("用户没有同意,技能没有改。");
|
|
275
346
|
try {
|