agent-loft 0.2.96 → 0.2.98
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 -4
- package/package.json +1 -1
- package/src/channels/web/api.ts +7 -5
- package/src/channels/web/experts-api.ts +32 -5
- package/src/channels/web/skills-api.ts +42 -27
- package/src/channels/web/workspace-api.ts +14 -1
- package/src/core/builtin-agents.ts +2 -2
- package/src/core/experts.ts +18 -9
- package/src/core/git.ts +192 -2
- package/src/core/hub.ts +1 -1
- package/src/core/mcp.ts +121 -18
- 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/users.ts +15 -2
- package/src/mcp/tasks-server.ts +1 -1
- package/web/css/workspace.css +24 -0
- package/web/settings/experts.js +63 -10
- package/web/settings/skills.js +38 -13
- package/web/settings/users.js +29 -2
- package/web/views/workspace.js +38 -1
package/src/core/git.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// - 去掉继承来的 GIT_* 环境变量,从 git 钩子里启动服务时也不会指到别的仓库;
|
|
10
10
|
// - 本服务自己的凭据不传下去(和 agent 子进程一样,见 agent-env.ts):用户勾选了运行钩子时,钩子也拿不到;
|
|
11
11
|
// - 不连网(GIT_ALLOW_PROTOCOL、GIT_NO_LAZY_FETCH):部分克隆缺对象时 git 会去远程地址拿,
|
|
12
|
-
// 而地址是配置里写的,ext::
|
|
12
|
+
// 而地址是配置里写的,ext:: 这种地址就是一条命令。只有用户点的获取、拉取、推送例外,见 networkEnv;
|
|
13
13
|
// - 不抢索引锁(GIT_OPTIONAL_LOCKS=0):面板在后台刷新,不能和正在干活的 agent 抢。
|
|
14
14
|
//
|
|
15
15
|
// 路径都相对仓库根目录。
|
|
@@ -39,7 +39,7 @@ function gitEnv(): NodeJS.ProcessEnv {
|
|
|
39
39
|
for (const [k, v] of Object.entries(agentEnvironment())) if (!k.startsWith("GIT_")) env[k] = v;
|
|
40
40
|
env.GIT_OPTIONAL_LOCKS = "0";
|
|
41
41
|
env.GIT_NO_LAZY_FETCH = "1";
|
|
42
|
-
//
|
|
42
|
+
// 除了获取、拉取、推送(见 networkEnv),这里用到的命令都不需要连网。没有哪个协议叫这个名字,所以都不允许
|
|
43
43
|
env.GIT_ALLOW_PROTOCOL = "none";
|
|
44
44
|
env.GIT_TERMINAL_PROMPT = "0";
|
|
45
45
|
env.GIT_PAGER = "cat";
|
|
@@ -208,6 +208,8 @@ export type GitStatus = {
|
|
|
208
208
|
upstream?: string;
|
|
209
209
|
ahead: number;
|
|
210
210
|
behind: number;
|
|
211
|
+
/** 推送会连到的地址(去掉了里面的账号密码)。只在要 stats 时给;没有远程时没有 */
|
|
212
|
+
pushUrl?: string;
|
|
211
213
|
files: GitFileChange[];
|
|
212
214
|
truncated: boolean;
|
|
213
215
|
/** 工作区相对 HEAD 的总行数变化(含未跟踪文件,不含敏感文件、二进制)。 */
|
|
@@ -279,6 +281,10 @@ export async function gitStatus(root: string, options: { stats?: boolean } = {})
|
|
|
279
281
|
if (isSensitivePath(path.join(root, f.path)) || (f.oldPath && isSensitivePath(path.join(root, f.oldPath)))) f.sensitive = true;
|
|
280
282
|
}
|
|
281
283
|
if (options.stats && !status.truncated) status.stats = await workingTreeStats(root, status, safe).catch(() => undefined);
|
|
284
|
+
if (options.stats) {
|
|
285
|
+
const url = await currentPushUrl(root, status.branch).catch(() => undefined);
|
|
286
|
+
if (url) status.pushUrl = url;
|
|
287
|
+
}
|
|
282
288
|
return status;
|
|
283
289
|
}
|
|
284
290
|
|
|
@@ -796,6 +802,190 @@ export async function gitCreateBranch(root: string, name: unknown): Promise<void
|
|
|
796
802
|
await write(root, ["checkout", "-q", "-b", branch], "新建分支失败");
|
|
797
803
|
}
|
|
798
804
|
|
|
805
|
+
// ---------- 和远程同步 ----------
|
|
806
|
+
//
|
|
807
|
+
// 用的是这台机器全局配置里的凭据,地址和其他设置却可能来自不可信的 .git/config,所以:
|
|
808
|
+
// - 只放行 https、http、ssh,ext:: 这种能跑命令的地址和本地路径都不行;
|
|
809
|
+
// - 仓库配置里有能跑程序、能改去向的项就不操作,让用户去终端(assertNetworkSafe);
|
|
810
|
+
// - 钩子照旧不跑(推送可以勾选),不碰子模块;
|
|
811
|
+
// - 只做快进拉取和不强制的推送:不会产生冲突,也不会覆盖别人的提交。
|
|
812
|
+
|
|
813
|
+
const NETWORK_TIMEOUT_MS = 5 * 60_000;
|
|
814
|
+
const NETWORK_MAX_BYTES = 8 * 1024 * 1024;
|
|
815
|
+
|
|
816
|
+
/** 仓库自己的配置里连网时不能信的项(键名是小写的,http 的单独看,见 unsafeNetworkKey) */
|
|
817
|
+
const UNSAFE_NETWORK_CONFIG =
|
|
818
|
+
/^(credential\.|protocol\.|ssh\.|url\.|core\.(sshcommand|gitproxy|askpass|alternaterefscommand)$|remote\..*\.(uploadpack|receivepack|proxy|vcs)$|merge\..*\.driver$|gpg\.(.*\.)?program$|gpg\.ssh\.defaultkeycommand$|lfs\.(url$|pushurl$|standalonetransferagent$|customtransfer\.|extension\.))/;
|
|
819
|
+
|
|
820
|
+
function unsafeNetworkKey(key: string): boolean {
|
|
821
|
+
const k = key.toLowerCase();
|
|
822
|
+
// 代理、自定义请求头、证书校验都能把请求或凭据转走。只调传输参数的放行
|
|
823
|
+
if (k.startsWith("http.")) return !/\.(postbuffer|lowspeedlimit|lowspeedtime|version)$/.test(k);
|
|
824
|
+
return UNSAFE_NETWORK_CONFIG.test(k);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** 地址里可能带着账号密码(https://user:token@host/…),不能出现在页面上 */
|
|
828
|
+
function redactUrls(text: string): string {
|
|
829
|
+
return text.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi, "$1");
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async function assertNetworkSafe(root: string): Promise<void> {
|
|
833
|
+
const unsafe = (await repoConfig(root, ".")).find((c) => unsafeNetworkKey(c.key));
|
|
834
|
+
if (unsafe) throw new GitError(409, `这个仓库的配置里有「${redactUrls(unsafe.key)}」,它能运行程序或改变连接的去向,面板不会带着凭据去连。确认没问题的话请在终端里操作`);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** 连网命令的环境,换掉 gitEnv 里禁止连网的设置。assertNetworkSafe 之后才能调:这里读到的 core.sshCommand 是全局配置的 */
|
|
838
|
+
async function networkEnv(root: string): Promise<NodeJS.ProcessEnv> {
|
|
839
|
+
const ssh = await configValue(root, "core.sshCommand");
|
|
840
|
+
return {
|
|
841
|
+
GIT_ALLOW_PROTOCOL: "https:http:ssh",
|
|
842
|
+
// 部分克隆拉取后检出时要按需下载对象
|
|
843
|
+
GIT_NO_LAZY_FETCH: undefined,
|
|
844
|
+
// 没人能回答提示:要输密码、确认主机指纹的直接失败,不要等到超时
|
|
845
|
+
GIT_SSH_COMMAND: `${ssh || "ssh"} -o BatchMode=yes`,
|
|
846
|
+
SSH_ASKPASS: undefined,
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function explainNetwork(stderr: string, fallback: string): string {
|
|
851
|
+
const text = redactUrls(stderr);
|
|
852
|
+
if (/transport '.*' not allowed/i.test(text)) return "面板只连 https、http、ssh 地址的远程,这个地址请在终端里操作";
|
|
853
|
+
if (/authentication failed|could not read (username|password)|terminal prompts disabled|permission denied \(|host key verification failed|invalid username or|returned error: 40[13]/i.test(text)) {
|
|
854
|
+
return "远程的认证没通过:服务器上的 git 没有这个仓库的凭据,或者没有权限。先在服务器终端里配置好(比如 gh auth login、SSH 密钥、known_hosts)";
|
|
855
|
+
}
|
|
856
|
+
if (/not possible to fast-forward/i.test(text)) return "本地和远程已经分叉,面板只支持快进拉取。请在终端里合并,或者交给 agent";
|
|
857
|
+
if (/\[rejected\]|non-fast-forward|fetch first/i.test(text)) return "远程有本地没有的提交,先拉取再推送";
|
|
858
|
+
if (/could not resolve host|could not connect|failed to connect|connection (timed out|refused)|network is unreachable/i.test(text)) return "连不上远程,检查一下这台服务器的网络和远程地址";
|
|
859
|
+
return explain(text, fallback);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
async function network(root: string, args: string[], fallback: string, opts: { hooks?: boolean } = {}): Promise<void> {
|
|
863
|
+
const hookArgs = opts.hooks ? ["-c", `core.hooksPath=${await hooksDir(root)}`] : [];
|
|
864
|
+
const prefix = [...(await safeArgs(root)), "-c", "submodule.recurse=false", ...hookArgs];
|
|
865
|
+
let out: RunResult;
|
|
866
|
+
try {
|
|
867
|
+
out = await run(root, [...prefix, ...args], NETWORK_MAX_BYTES, { env: await networkEnv(root), timeoutMs: NETWORK_TIMEOUT_MS });
|
|
868
|
+
} catch (err) {
|
|
869
|
+
throw new GitError(504, redactUrls(err instanceof Error ? err.message : String(err)));
|
|
870
|
+
}
|
|
871
|
+
// 超过缓冲区时 git 被杀掉了,run 报的 code 0 不代表成功
|
|
872
|
+
if (out.truncated) throw new GitError(502, "git 的输出太多,操作被中断了。请刷新确认结果,或者在终端里操作");
|
|
873
|
+
if (out.code !== 0) throw new GitError(409, explainNetwork(out.stderr, fallback));
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
async function configValue(root: string, key: string): Promise<string | undefined> {
|
|
877
|
+
const out = await run(root, ["config", "--get", key], 64 * 1024);
|
|
878
|
+
return out.code === 0 ? out.stdout.trim() || undefined : undefined;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
async function remoteNames(root: string): Promise<string[]> {
|
|
882
|
+
const out = await run(root, ["remote"], 256 * 1024);
|
|
883
|
+
// 不会用「-」开头的名字:放到命令行上就成了选项
|
|
884
|
+
const names = out.code === 0 ? out.stdout.split("\n").filter((n) => n && !n.startsWith("-")) : [];
|
|
885
|
+
if (!names.length) throw new GitError(409, "这个仓库还没有配置远程");
|
|
886
|
+
return names;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** 当前分支跟踪的远程,没有就是 origin,再没有就是唯一的那个 */
|
|
890
|
+
async function fetchRemote(root: string, branch: string | null, remotes: string[]): Promise<string> {
|
|
891
|
+
const tracked = branch ? await configValue(root, `branch.${branch}.remote`) : undefined;
|
|
892
|
+
if (tracked && remotes.includes(tracked)) return tracked;
|
|
893
|
+
if (remotes.includes("origin")) return "origin";
|
|
894
|
+
if (remotes.length === 1) return remotes[0]!;
|
|
895
|
+
throw new GitError(409, "这个仓库有多个远程,不知道该连哪个。请先给当前分支设置上游,或者在终端里操作");
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** 推送的目标和 git 自己的优先级一样:branch.<名字>.pushRemote、remote.pushDefault,然后才是跟踪的远程 */
|
|
899
|
+
async function pushRemote(root: string, branch: string | null, remotes: string[]): Promise<string> {
|
|
900
|
+
const explicit = (branch ? await configValue(root, `branch.${branch}.pushRemote`) : undefined) ?? (await configValue(root, "remote.pushDefault"));
|
|
901
|
+
if (explicit && remotes.includes(explicit)) return explicit;
|
|
902
|
+
return fetchRemote(root, branch, remotes);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
async function currentPushUrl(root: string, branch: string | null): Promise<string | undefined> {
|
|
906
|
+
const remote = await pushRemote(root, branch, await remoteNames(root));
|
|
907
|
+
const out = await run(root, ["remote", "get-url", "--push", remote], 64 * 1024);
|
|
908
|
+
return out.code === 0 ? redactUrls(out.stdout.trim()) || undefined : undefined;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** 更新远程分支的引用,不动工作区和本地分支 */
|
|
912
|
+
export async function gitFetch(root: string): Promise<{ remote: string; ahead: number; behind: number }> {
|
|
913
|
+
await assertNetworkSafe(root);
|
|
914
|
+
const { branch } = await gitStatus(root);
|
|
915
|
+
const remote = await fetchRemote(root, branch, await remoteNames(root));
|
|
916
|
+
await network(root, ["fetch", "--no-recurse-submodules", remote], "获取失败");
|
|
917
|
+
const { ahead, behind } = await gitStatus(root);
|
|
918
|
+
return { remote, ahead, behind };
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** 拉取,只做快进:本地也有新提交(分叉)时不合并,不会把工作区弄成冲突状态 */
|
|
922
|
+
export async function gitPull(root: string): Promise<{ updated: boolean; short: string | null }> {
|
|
923
|
+
await assertWritable(root);
|
|
924
|
+
await assertNetworkSafe(root);
|
|
925
|
+
const before = await gitStatus(root);
|
|
926
|
+
if (!before.branch) throw new GitError(409, "现在不在任何分支上(分离头指针),没法拉取");
|
|
927
|
+
if (!before.upstream) throw new GitError(409, `分支「${before.branch}」还没有上游,没有可以拉取的地方`);
|
|
928
|
+
const tracked = await configValue(root, `branch.${before.branch}.remote`);
|
|
929
|
+
// 「.」是跟踪本地分支,不用连网
|
|
930
|
+
if (tracked && tracked !== ".") {
|
|
931
|
+
if (!(await remoteNames(root)).includes(tracked)) throw new GitError(409, `上游的远程「${redactUrls(tracked)}」不是这个仓库配置的远程,请在终端里操作`);
|
|
932
|
+
await network(root, ["fetch", "--no-recurse-submodules", tracked], "获取失败");
|
|
933
|
+
}
|
|
934
|
+
const after = await gitStatus(root);
|
|
935
|
+
if (!after.behind) return { updated: false, short: after.head };
|
|
936
|
+
if (after.ahead) throw new GitError(409, `本地和远程已经分叉(领先 ${after.ahead},落后 ${after.behind}),面板只支持快进拉取。请在终端里合并,或者交给 agent`);
|
|
937
|
+
await network(root, ["merge", "--ff-only", "--no-stat", "--no-edit", "@{upstream}"], "拉取失败");
|
|
938
|
+
return { updated: true, short: (await gitStatus(root)).head };
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/** 用了 Git LFS 的仓库:大文件靠 pre-push 钩子上传,钩子不跑的话远程只收到指针 */
|
|
942
|
+
async function usesLfs(root: string): Promise<boolean> {
|
|
943
|
+
const dir = await run(root, ["rev-parse", "--git-path", "lfs"], 4096);
|
|
944
|
+
if (dir.code === 0 && fs.existsSync(path.resolve(root, dir.stdout.trim()))) return true;
|
|
945
|
+
const attributes = await run(root, ["cat-file", "blob", "HEAD:.gitattributes"], 1024 * 1024);
|
|
946
|
+
return attributes.code === 0 && /\bfilter=lfs\b/.test(attributes.stdout);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* 面板不让提交敏感文件,它们可能是 agent 或终端提交的;推出去就收不回来了,所以也拦一道。
|
|
951
|
+
* 文件太多看不完时同样拒绝:不能在没看完的情况下放行
|
|
952
|
+
*/
|
|
953
|
+
async function assertNoSensitiveOutgoing(root: string, remote: string): Promise<void> {
|
|
954
|
+
const out = await run(root, [...(await safeArgs(root)), "log", "-z", "--name-only", "--no-renames", "--diff-filter=d", "--format=", "HEAD", "--not", `--remotes=${remote}`], STATUS_MAX_BYTES);
|
|
955
|
+
if (out.code !== 0) throw new GitError(409, redactUrls(out.stderr.trim()) || "读取要推送的提交失败");
|
|
956
|
+
if (out.truncated) throw new GitError(409, "要推送的提交涉及的文件太多,没法检查里面有没有敏感文件,请在终端里推送");
|
|
957
|
+
const secret = out.stdout.split("\0").map((f) => f.trim()).find((f) => f && isSensitivePath(path.join(root, f)));
|
|
958
|
+
if (secret) throw new GitError(403, `要推送的提交里有「${secret}」,是密钥一类的敏感文件,不能在面板里推送。确认没问题的话请在终端里操作`);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/**
|
|
962
|
+
* 推送当前分支到同名的远程分支,从不强制。还没有上游时顺手设置。
|
|
963
|
+
* 写明 refspec:不受仓库配置里的 push.default、remote.*.push 影响,点一次只动这一个分支
|
|
964
|
+
*/
|
|
965
|
+
export async function gitPush(root: string, opts: { hooks?: boolean } = {}): Promise<{ remote: string; branch: string; published: boolean }> {
|
|
966
|
+
await assertNetworkSafe(root);
|
|
967
|
+
const status = await gitStatus(root);
|
|
968
|
+
const branch = status.branch;
|
|
969
|
+
if (!branch) throw new GitError(409, "现在不在任何分支上(分离头指针),没法推送");
|
|
970
|
+
if (!status.head) throw new GitError(409, "这个分支还没有提交,没有可以推送的内容");
|
|
971
|
+
const remote = await pushRemote(root, branch, await remoteNames(root));
|
|
972
|
+
// 和 git 默认的 push.default=simple 一样:跟踪的分支名字不同(比如 feature 跟踪 origin/main)时不猜
|
|
973
|
+
if (status.upstream && (await configValue(root, `branch.${branch}.remote`)) === remote) {
|
|
974
|
+
const merge = await configValue(root, `branch.${branch}.merge`);
|
|
975
|
+
if (merge !== `refs/heads/${branch}`) throw new GitError(409, `分支「${branch}」跟踪的是「${status.upstream}」,名字不一样。为了不推错地方,请在终端里操作`);
|
|
976
|
+
}
|
|
977
|
+
if (!opts.hooks && (await usesLfs(root))) throw new GitError(409, "这个仓库用了 Git LFS,不跑钩子时大文件传不上去。请勾选「运行 Git 钩子」,或者在终端里推送");
|
|
978
|
+
await assertNoSensitiveOutgoing(root, remote);
|
|
979
|
+
const published = !status.upstream;
|
|
980
|
+
await network(
|
|
981
|
+
root,
|
|
982
|
+
["push", "--recurse-submodules=no", "--no-signed", ...(published ? ["--set-upstream"] : []), remote, `refs/heads/${branch}:refs/heads/${branch}`],
|
|
983
|
+
"推送失败",
|
|
984
|
+
opts,
|
|
985
|
+
);
|
|
986
|
+
return { remote, branch, published };
|
|
987
|
+
}
|
|
988
|
+
|
|
799
989
|
// ---------- 撤销一轮 ----------
|
|
800
990
|
|
|
801
991
|
/** 两棵 tree 里内容不一样的文件。不做重命名检测:撤销时重命名就是一删一增 */
|
package/src/core/hub.ts
CHANGED
|
@@ -364,7 +364,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
|
|
|
364
364
|
this.dropIfStale(key);
|
|
365
365
|
}
|
|
366
366
|
});
|
|
367
|
-
mcpEvents.on("changed", (
|
|
367
|
+
mcpEvents.on("changed", (users) => this.personalChanged(new Set(users)));
|
|
368
368
|
builtinAgentEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
|
|
369
369
|
// workspaceRoot 改了:store 会把没显式 /cd 过的会话目录重置,正在跑的旧目录会话要作废
|
|
370
370
|
onConfigChange((next, prev) => {
|
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
|
// ---------- 机器上原有的 ----------
|
|
@@ -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
|
|