agent-loft 0.2.104 → 0.2.106
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/package.json +3 -1
- package/src/agents/health.ts +60 -3
- package/src/agents/pi/constants.ts +2 -0
- package/src/agents/pi/custom.ts +146 -0
- package/src/agents/pi/driver.ts +150 -0
- package/src/agents/pi/errors.ts +37 -0
- package/src/agents/pi/history.ts +217 -0
- package/src/agents/pi/oauth.ts +190 -0
- package/src/agents/pi/sdk.ts +201 -0
- package/src/agents/pi/session.ts +681 -0
- package/src/agents/pi/steps.ts +21 -0
- package/src/channels/feishu/bot.ts +1 -1
- package/src/channels/web/api.ts +109 -0
- package/src/channels/web/experts-api.ts +1 -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 +17 -3
- package/src/core/experts.ts +11 -9
- 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 +279 -3
- package/web/settings/commands.js +1 -1
- package/web/settings/experts.js +11 -4
- package/web/settings/memory.js +2 -1
- package/web/views/composer.js +1 -1
- package/web/views/sidebar.js +1 -1
- package/web/views/topbar.js +1 -1
package/README.md
CHANGED
|
@@ -36,8 +36,9 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
36
36
|
|
|
37
37
|
## 能做什么
|
|
38
38
|
|
|
39
|
-
- **多个 agent**:Claude Code、Codex、WorkBuddy。几个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
|
|
39
|
+
- **多个 agent**:Claude Code、Codex、WorkBuddy、pi。几个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
|
|
40
40
|
- **WorkBuddy(腾讯)**:默认不启用。调用这台服务器上 **WorkBuddy 桌面版自带的 CLI**(官方 Agent SDK `@tencent-ai/agent-sdk` 驱动,账号站点 www.workbuddy.cn),也可以改用 CodeBuddy 国内版 / 国际版 / 腾讯 iOA 的账号(用 SDK 自带的 CLI,不用装桌面版)。到 设置 → Agent → WorkBuddy 勾上「启用」、选账号站点后保存,再在「运行环境」里点「登录 WorkBuddy」:在你自己的浏览器里打开登录页,**1 分钟内**登录完(CLI 只等这么久,超时重新点),整台服务器登一次就行,所有人共用。桌面版里登录过也要在这里再登一次(同一个账号):桌面版的登录由它自己保管,不交给单独跑的 CLI;这边的令牌存在 `data/workbuddy-auth.json`(0600),不碰桌面版的数据。也可以给服务设 `CODEBUDDY_API_KEY`。支持流式回复、授权卡(逐次询问 / 自动改文件 / 完全允许)、提问卡、计划模式、中途换模型、图片附件、`/sessions` 恢复以前的会话、记忆和定时任务工具、个人技能和 MCP;管理员的会话读机器上的 `~/.codebuddy` 配置,成员只读项目里的。暂不支持自定义专家、分叉 / 回退、思考程度和额度显示;令牌过期后要回设置页重新登录。
|
|
41
|
+
- **pi**:默认不启用。开源编程 agent [pi](https://pi.dev),用官方 TypeScript SDK(`@earendil-works/pi-coding-agent`)在 agent-loft 进程里运行(需要 Node 22.19 以上)。按**模型服务商**配凭据,整台服务器共用:到 设置 → Agent → pi 勾上「启用」,在「模型服务商」里选一家(DeepSeek、智谱 Coding Plan、Kimi、通义 Token Plan、MiniMax、OpenRouter、Anthropic、OpenAI……)粘贴 API Key 保存;或者点「登录」用**订阅账号**(Claude Pro/Max、ChatGPT Plus/Pro、GitHub Copilot、Kimi Code、xAI……),在你自己的浏览器里完成,设备码直接显示在页面上,浏览器登录完跳到打不开的 127.0.0.1 地址时把地址栏整个粘贴回来即可(订阅能否用在第三方工具里以各家条款为准);也可以给服务设对应的环境变量(如 `DEEPSEEK_API_KEY`)。本地模型和 OpenAI 兼容网关在「自定义服务商」里加(Ollama、LM Studio、vLLM、llama.cpp、one-api……,填地址、接口类型、Key,能「从服务读取模型列表」),写在 `data/pi/models.json`(0600,Key 按字面值保存,不会被当成环境变量或命令)。凭据、会话记录都存在 `data/pi/` 下(`auth.json` 0600、`sessions/`),不读也不写机器上的 `~/.pi`;项目里的 `.pi/` 扩展不加载。pi 自己没有权限系统,授权卡(逐次询问 / 自动改文件 / 完全允许)、计划模式、提问卡由 agent-loft 补上,「自动改文件」只放行工作目录和附件目录里的文件;跑命令(bash)没有沙箱。支持流式回复、中途换模型和思考程度、图片附件(模型支持时)、`/compact` 压缩上下文、`/sessions` 恢复、分叉 / 回退、费用显示、记忆和定时任务工具、个人技能和 MCP,记忆整理也可选 pi。可以建 pi 引擎的自定义专家(见下面「专家」)。
|
|
41
42
|
- **多个飞书机器人**:设置 → 飞书 →「可用专家」直接勾选内置或共享专家,并选择「默认专家」。只勾一个共享专家即可专用,不用再勾选底层 Agent;每个人绑定自己的账号后,直接私聊就是这个专家,使用各自的记忆和工具。机器人能在 Web 上扫码创建(Lark 国际版用「手动添加」),改完配置立即生效,不用重启。
|
|
42
43
|
- 群聊里要 @ 机器人;不同话题是各自独立的会话;支持文字、富文本、图片、文件、语音和视频。
|
|
43
44
|
- 思考和工具调用显示在实时刷新的过程卡片里,最终回复是普通消息。
|
|
@@ -80,9 +81,9 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
80
81
|
- **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。权限级别(输入框左下角或 `/permission`):逐次询问 / 自动改文件 / 自动判断(仅 Claude Code,由 Claude 逐个判断安不安全)/ 完全允许,定时任务也可以单独设,自动判断和完全允许只给管理员;默认级别在 设置 → Agent 里按引擎设。同一个弹窗里还有**计划模式**开关(或 `/planmode on`):agent 先只读、出方案,你点「开始执行」后再按权限级别动手。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
|
|
81
82
|
- **设置都在网页上**,按用途分组:**我的**(账号、飞书和微信绑定、自己的登录设备、记忆、专家、技能、MCP、用量);**Agent**(运行环境置顶,各 agent 卡片分别配置默认模型、思考程度、可选模型、个人默认技能和 MCP,Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户标题旁添加用户,用户的「管理 → 登录设备」查看和下线各自设备;系统页管理服务端版本和升级、重启、局域网访问和端口,网络访问下方是系统通知;成员也可在系统页设置自己的通知)。账号页通过「修改名称」「修改密码」按需展开表单;飞书和微信绑定操作位于卡片右上角。设置、新建 / 编辑专家、重命名等编辑弹窗不会因点击外部或按 Esc 关闭;通过关闭、取消或保存 / 完成按钮退出。改了没保存就切页或关掉设置会先提醒。
|
|
82
83
|
- **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知;个人设置各自管理,服务器设置由管理员修改,见下面「安全」。
|
|
83
|
-
- **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex`、`/workbuddy` 换专家会开新会话)。**内置专家**:Claude Code、Codex,保留原装提示词和所有工具,默认技能与 MCP 在「设置 → Agent」中按账号、按引擎分别选择。**自定义专家**由创建者管理,可以勾选「共享给所有账号」。共享后,其他人能在网页、绑定账号后的飞书私聊和定时任务中选择它;只有创建者能修改设定。每个人在该专家的「我的工具」里选择自己的技能和 MCP,使用各自的变量、凭据、记忆和聊天记录;创建者沿用原有工具选择;其他人没配置过时,沿用创建者选的里面自己能用的(自己装了的技能、创建者共享出来的 MCP),创建者私有的 MCP 和机器 MCP 不会带给别人。取消共享后,其他人的历史对话保留,后续消息不能继续调用该专家,相关定时任务在下次运行时暂停。可以配:
|
|
84
|
-
- 头像(点头像区域的加号上传;未上传时,会话中用引擎的图标)、引擎(Claude / Codex
|
|
85
|
-
- 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
|
|
84
|
+
- **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex`、`/workbuddy`、`/pi` 换专家会开新会话)。**内置专家**:Claude Code、Codex,保留原装提示词和所有工具,默认技能与 MCP 在「设置 → Agent」中按账号、按引擎分别选择。**自定义专家**由创建者管理,可以勾选「共享给所有账号」。共享后,其他人能在网页、绑定账号后的飞书私聊和定时任务中选择它;只有创建者能修改设定。每个人在该专家的「我的工具」里选择自己的技能和 MCP,使用各自的变量、凭据、记忆和聊天记录;创建者沿用原有工具选择;其他人没配置过时,沿用创建者选的里面自己能用的(自己装了的技能、创建者共享出来的 MCP),创建者私有的 MCP 和机器 MCP 不会带给别人。取消共享后,其他人的历史对话保留,后续消息不能继续调用该专家,相关定时任务在下次运行时暂停。可以配:
|
|
85
|
+
- 头像(点头像区域的加号上传;未上传时,会话中用引擎的图标)、引擎(Claude / Codex / pi,建好后不能换;pi 专家没有自带的联网搜索和读网页,要联网就给它挂搜索 MCP,也没有子智能体)、默认模型和思考程度(从模型列表里选);
|
|
86
|
+
- 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);pi 专家同样默认只用这段,也可以追加在 pi 原装提示词后面(每轮多约 600 token);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
|
|
86
87
|
- 权限,勾选:联网搜索、读网页,以及文件权限(一级包含一级):都不勾就是**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
|
|
87
88
|
- 带不带个人记忆,默认工作目录,新对话页上的欢迎语和快捷提问;
|
|
88
89
|
- 技能:只给选中的(Claude 用技能白名单,没选的调不了;没选技能就不挂 Skill 工具,省 token);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-loft",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.106",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
|
|
6
6
|
"keywords": [
|
|
@@ -46,6 +46,8 @@
|
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@anthropic-ai/claude-agent-sdk": "^0.3.302",
|
|
49
|
+
"@earendil-works/pi-ai": "1.5.0",
|
|
50
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
49
51
|
"@highlightjs/cdn-assets": "^11.12.0",
|
|
50
52
|
"@larksuiteoapi/node-sdk": "^1.73.0",
|
|
51
53
|
"@novnc/novnc": "^1.7.0",
|
package/src/agents/health.ts
CHANGED
|
@@ -5,11 +5,14 @@
|
|
|
5
5
|
import { spawn, spawnSync } from "node:child_process";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
7
|
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
8
9
|
import { agentEnvironment } from "../core/agent-env.js";
|
|
9
10
|
import { config } from "../core/config.js";
|
|
10
11
|
import { withProbe } from "./claude/probe.js";
|
|
11
12
|
import { onLoginDone, readAccount } from "./workbuddy/account.js";
|
|
12
13
|
import { desktopCli, ENVIRONMENT_LABEL, environment } from "./workbuddy/sdk.js";
|
|
14
|
+
import { listProviders, MIN_NODE, nodeOk } from "./pi/sdk.js";
|
|
15
|
+
import { onOAuthDone } from "./pi/oauth.js";
|
|
13
16
|
|
|
14
17
|
const require = createRequire(import.meta.url);
|
|
15
18
|
|
|
@@ -24,7 +27,7 @@ export type AgentFix = {
|
|
|
24
27
|
};
|
|
25
28
|
|
|
26
29
|
export type AgentHealth = {
|
|
27
|
-
id: "claude" | "codex" | "workbuddy";
|
|
30
|
+
id: "claude" | "codex" | "workbuddy" | "pi";
|
|
28
31
|
label: string;
|
|
29
32
|
enabled: boolean;
|
|
30
33
|
installed: boolean;
|
|
@@ -194,11 +197,62 @@ async function workbuddyHealth(): Promise<AgentHealth> {
|
|
|
194
197
|
}
|
|
195
198
|
}
|
|
196
199
|
|
|
200
|
+
/** pi:SDK 跟着 agent-loft 装好;「登录」= 至少一家模型服务商配了凭据 */
|
|
201
|
+
async function piHealth(): Promise<AgentHealth> {
|
|
202
|
+
const base = { id: "pi" as const, label: "pi", enabled: config().agents.pi.enabled };
|
|
203
|
+
if (!nodeOk()) {
|
|
204
|
+
return {
|
|
205
|
+
...base,
|
|
206
|
+
installed: false,
|
|
207
|
+
loggedIn: null,
|
|
208
|
+
problem: `pi 需要 Node ${MIN_NODE.join(".")} 以上,现在是 ${process.versions.node}`,
|
|
209
|
+
fix: { action: "install", title: "升级 Node.js", commands: [], note: `把运行 agent-loft 的 Node 升级到 ${MIN_NODE.join(".")} 以上,再重启服务。` },
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
let version: string | undefined;
|
|
213
|
+
try {
|
|
214
|
+
// SDK 只有 import 导出,require.resolve 解不到,得走 import.meta.resolve
|
|
215
|
+
const v = (require(path.join(path.dirname(fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent"))), "..", "package.json")) as { version?: string }).version;
|
|
216
|
+
version = v ? `SDK ${v}` : undefined;
|
|
217
|
+
} catch {
|
|
218
|
+
return {
|
|
219
|
+
...base,
|
|
220
|
+
installed: false,
|
|
221
|
+
loggedIn: null,
|
|
222
|
+
problem: "找不到 @earendil-works/pi-coding-agent",
|
|
223
|
+
fix: { action: "install", title: "安装 pi SDK", commands: ["npm install"], note: "在 agent-loft 的目录里运行,装好后重启服务。" },
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
const keyFix: AgentFix = {
|
|
227
|
+
action: "login",
|
|
228
|
+
web: true,
|
|
229
|
+
title: "填模型服务商的 API Key",
|
|
230
|
+
commands: [],
|
|
231
|
+
note: "在下面 pi 卡片的「模型服务商」里选一家(DeepSeek、智谱、Kimi、通义、OpenRouter……)填 API Key,保存后点「重新检查」。也可以给 agent-loft 服务设对应的环境变量(如 DEEPSEEK_API_KEY)。",
|
|
232
|
+
};
|
|
233
|
+
try {
|
|
234
|
+
const providers = await Promise.race([listProviders(), timeout<never>(25_000, "读取 pi 服务商")]);
|
|
235
|
+
const ready = providers.filter((p) => p.configured);
|
|
236
|
+
return {
|
|
237
|
+
...base,
|
|
238
|
+
installed: true,
|
|
239
|
+
...(version ? { version } : {}),
|
|
240
|
+
loggedIn: ready.length > 0,
|
|
241
|
+
...(ready.length ? { account: ready.map((p) => p.name).join("、") } : { fix: keyFix }),
|
|
242
|
+
};
|
|
243
|
+
} catch (err) {
|
|
244
|
+
return { ...base, installed: true, ...(version ? { version } : {}), loggedIn: null, problem: err instanceof Error ? err.message : String(err), fix: keyFix };
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
197
248
|
let cache: { at: number; value: AgentHealth[] } | null = null;
|
|
198
249
|
// 网页上登录完:下次体检别用缓存
|
|
199
250
|
onLoginDone(() => {
|
|
200
251
|
cache = null;
|
|
201
252
|
});
|
|
253
|
+
onOAuthDone(() => {
|
|
254
|
+
cache = null;
|
|
255
|
+
});
|
|
202
256
|
|
|
203
257
|
/**
|
|
204
258
|
* 不等体检、立刻给出的「这个 agent 能不能用」:用最近一次体检的结果(多旧都算),
|
|
@@ -220,7 +274,7 @@ export function invalidateHealth(): void {
|
|
|
220
274
|
}
|
|
221
275
|
let inflight: Promise<AgentHealth[]> | null = null;
|
|
222
276
|
|
|
223
|
-
/**
|
|
277
|
+
/** 几个 agent 一起查,结果缓存一分钟;refresh 跳过缓存(点了「重新检查」) */
|
|
224
278
|
export function agentHealth(refresh = false): Promise<AgentHealth[]> {
|
|
225
279
|
if (!refresh && cache && Date.now() - cache.at < 60_000) return Promise.resolve(cache.value);
|
|
226
280
|
// WorkBuddy 没启用就不去起它的 CLI(包很大,拉起要几秒)
|
|
@@ -228,7 +282,10 @@ export function agentHealth(refresh = false): Promise<AgentHealth[]> {
|
|
|
228
282
|
config().agents.workbuddy.enabled
|
|
229
283
|
? workbuddyHealth()
|
|
230
284
|
: Promise.resolve<AgentHealth>({ id: "workbuddy", label: "WorkBuddy", enabled: false, installed: true, loggedIn: null });
|
|
231
|
-
|
|
285
|
+
// pi 没启用就不加载它的 SDK
|
|
286
|
+
const pi = () =>
|
|
287
|
+
config().agents.pi.enabled ? piHealth() : Promise.resolve<AgentHealth>({ id: "pi", label: "pi", enabled: false, installed: true, loggedIn: null });
|
|
288
|
+
inflight ??= Promise.all([claudeHealth(), codexHealth(), workbuddy(), pi()])
|
|
232
289
|
.then((value) => {
|
|
233
290
|
cache = { at: Date.now(), value };
|
|
234
291
|
return value;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// pi 的自定义服务商:data/pi/models.json 里的 providers(本地的 Ollama / LM Studio / vLLM / llama.cpp、
|
|
2
|
+
// one-api 之类的 OpenAI 兼容网关、自己部署的 Anthropic 兼容代理……)。格式见 pi 文档 models-configuration.md。
|
|
3
|
+
//
|
|
4
|
+
// 这份文件归 agent-loft 管(网页上增删改),0600。Key 按字面值写进去:pi 会把 apiKey 里的 $NAME 当环境变量、
|
|
5
|
+
// 开头的 ! 当 shell 命令执行,所以写之前转义($ → $$,开头的 ! → $!),网页上填什么就是什么。
|
|
6
|
+
// 网页上不回显 Key,只告诉有没有。
|
|
7
|
+
import { modelRuntime, MODELS_FILE } from "./sdk.js";
|
|
8
|
+
import { readJson, writeJsonAtomic } from "../../home.js";
|
|
9
|
+
|
|
10
|
+
export const CUSTOM_APIS = ["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai"] as const;
|
|
11
|
+
export type CustomApi = (typeof CUSTOM_APIS)[number];
|
|
12
|
+
|
|
13
|
+
export type CustomModel = { id: string; name?: string; reasoning?: boolean; input?: ("text" | "image")[]; contextWindow?: number; maxTokens?: number };
|
|
14
|
+
|
|
15
|
+
export type CustomProviderView = {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
api: string;
|
|
20
|
+
hasKey: boolean;
|
|
21
|
+
models: CustomModel[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type CustomProviderInput = {
|
|
25
|
+
id: string;
|
|
26
|
+
name?: string;
|
|
27
|
+
baseUrl: string;
|
|
28
|
+
api: string;
|
|
29
|
+
/** 不给 = 沿用原来的;空字符串 = 不用 Key(本地服务) */
|
|
30
|
+
apiKey?: string;
|
|
31
|
+
models: CustomModel[];
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type FileProvider = { name?: string; baseUrl?: string; api?: string; apiKey?: string; models?: CustomModel[]; [k: string]: unknown };
|
|
35
|
+
type ModelsFile = { providers?: Record<string, FileProvider>; [k: string]: unknown };
|
|
36
|
+
|
|
37
|
+
/** 不需要 Key 的本地服务也得填个值,pi 才认为这个服务商「能用」 */
|
|
38
|
+
const NO_KEY = "agent-loft-no-key";
|
|
39
|
+
|
|
40
|
+
/** 字面值 → pi 配置值:不让 $ 变成环境变量、开头的 ! 变成命令 */
|
|
41
|
+
export function escapeConfigValue(value: string): string {
|
|
42
|
+
const v = value.replace(/\$/g, "$$$$");
|
|
43
|
+
return v.startsWith("!") ? `$${v}` : v;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function readFile(): ModelsFile {
|
|
47
|
+
const v = readJson<ModelsFile>(MODELS_FILE, {});
|
|
48
|
+
return v && typeof v === "object" ? v : {};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function listCustom(): CustomProviderView[] {
|
|
52
|
+
return Object.entries(readFile().providers ?? {})
|
|
53
|
+
.filter(([, p]) => p && typeof p === "object" && typeof p.baseUrl === "string" && Array.isArray(p.models))
|
|
54
|
+
.map(([id, p]) => ({
|
|
55
|
+
id,
|
|
56
|
+
name: p.name || id,
|
|
57
|
+
baseUrl: p.baseUrl!,
|
|
58
|
+
api: p.api ?? "",
|
|
59
|
+
hasKey: typeof p.apiKey === "string" && p.apiKey !== NO_KEY && p.apiKey !== "",
|
|
60
|
+
models: (p.models ?? []).filter((m) => m && typeof m.id === "string"),
|
|
61
|
+
}));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function cleanModels(models: unknown): CustomModel[] {
|
|
65
|
+
if (!Array.isArray(models) || models.length === 0) throw new Error("至少填一个模型");
|
|
66
|
+
if (models.length > 200) throw new Error("模型最多 200 个");
|
|
67
|
+
const seen = new Set<string>();
|
|
68
|
+
const out: CustomModel[] = [];
|
|
69
|
+
for (const raw of models as Record<string, unknown>[]) {
|
|
70
|
+
const id = typeof raw?.id === "string" ? raw.id.trim() : "";
|
|
71
|
+
if (!id || id.length > 200 || /\s/.test(id)) throw new Error(`模型 id 不对:${String(raw?.id ?? "")}`);
|
|
72
|
+
if (seen.has(id)) continue;
|
|
73
|
+
seen.add(id);
|
|
74
|
+
const m: CustomModel = { id };
|
|
75
|
+
if (typeof raw.name === "string" && raw.name.trim()) m.name = raw.name.trim().slice(0, 100);
|
|
76
|
+
if (raw.reasoning === true) m.reasoning = true;
|
|
77
|
+
if (raw.image === true || (Array.isArray(raw.input) && raw.input.includes("image"))) m.input = ["text", "image"];
|
|
78
|
+
const ctx = Number(raw.contextWindow);
|
|
79
|
+
if (Number.isFinite(ctx) && ctx >= 1024 && ctx <= 10_000_000) m.contextWindow = Math.round(ctx);
|
|
80
|
+
const max = Number(raw.maxTokens);
|
|
81
|
+
if (Number.isFinite(max) && max >= 256 && max <= 1_000_000) m.maxTokens = Math.round(max);
|
|
82
|
+
out.push(m);
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function saveCustom(input: CustomProviderInput): Promise<void> {
|
|
88
|
+
const id = typeof input.id === "string" ? input.id.trim() : "";
|
|
89
|
+
if (!/^[a-z0-9][a-z0-9-]{0,40}$/.test(id)) throw new Error("id 只能用小写字母、数字和 -,最长 41 个字符");
|
|
90
|
+
const rt = await modelRuntime();
|
|
91
|
+
const file = readFile();
|
|
92
|
+
const providers = { ...(file.providers ?? {}) };
|
|
93
|
+
const prev = providers[id];
|
|
94
|
+
// 内置服务商不能在这里改(改了会盖掉它的模型目录)
|
|
95
|
+
if (!prev && rt.getProvider(id)) throw new Error(`${id} 是 pi 内置的服务商,换个 id`);
|
|
96
|
+
const baseUrl = typeof input.baseUrl === "string" ? input.baseUrl.trim().replace(/\/+$/, "") : "";
|
|
97
|
+
if (!/^https?:\/\/[^\s]+$/i.test(baseUrl) || baseUrl.length > 500) throw new Error("地址要以 http:// 或 https:// 开头");
|
|
98
|
+
if (!(CUSTOM_APIS as readonly string[]).includes(input.api)) throw new Error("接口类型不对");
|
|
99
|
+
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim().slice(0, 60) : id;
|
|
100
|
+
let apiKey: string;
|
|
101
|
+
if (input.apiKey === undefined) apiKey = prev?.apiKey ?? NO_KEY;
|
|
102
|
+
else if (typeof input.apiKey !== "string" || input.apiKey.length > 4096 || /\s/.test(input.apiKey.trim())) throw new Error("API Key 不能带空格");
|
|
103
|
+
else apiKey = input.apiKey.trim() ? escapeConfigValue(input.apiKey.trim()) : NO_KEY;
|
|
104
|
+
providers[id] = { name, baseUrl, api: input.api, apiKey, models: cleanModels(input.models) };
|
|
105
|
+
writeJsonAtomic(MODELS_FILE, { ...file, providers });
|
|
106
|
+
await rt.refresh({ allowNetwork: false });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function deleteCustom(id: string): Promise<void> {
|
|
110
|
+
const file = readFile();
|
|
111
|
+
if (!file.providers?.[id]) throw new Error("没有这个自定义服务商");
|
|
112
|
+
const providers = { ...file.providers };
|
|
113
|
+
delete providers[id];
|
|
114
|
+
writeJsonAtomic(MODELS_FILE, { ...file, providers });
|
|
115
|
+
await (await modelRuntime()).refresh({ allowNetwork: false });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 问服务要模型列表(OpenAI 兼容的 GET /models,Ollama、LM Studio、vLLM、one-api 都有)。
|
|
120
|
+
* key 不给就用已保存的(编辑时不用重新填)。只有管理员能调
|
|
121
|
+
*/
|
|
122
|
+
export async function discoverModels(baseUrl: string, api: string, key?: string, savedId?: string): Promise<string[]> {
|
|
123
|
+
const url = baseUrl.trim().replace(/\/+$/, "");
|
|
124
|
+
if (!/^https?:\/\/[^\s]+$/i.test(url)) throw new Error("地址要以 http:// 或 https:// 开头");
|
|
125
|
+
let secret = key?.trim() || "";
|
|
126
|
+
if (!secret && savedId) {
|
|
127
|
+
const saved = readFile().providers?.[savedId]?.apiKey;
|
|
128
|
+
// 存的是转义过的字面值:还原(只有 agent-loft 写的这种格式)
|
|
129
|
+
if (saved && saved !== NO_KEY) secret = saved.replace(/^\$!/, "!").replace(/\$\$/g, "$");
|
|
130
|
+
}
|
|
131
|
+
const headers: Record<string, string> = { accept: "application/json" };
|
|
132
|
+
if (api === "anthropic-messages") {
|
|
133
|
+
if (secret) headers["x-api-key"] = secret;
|
|
134
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
135
|
+
} else if (api === "google-generative-ai") {
|
|
136
|
+
if (secret) headers["x-goog-api-key"] = secret;
|
|
137
|
+
} else if (secret) headers.authorization = `Bearer ${secret}`;
|
|
138
|
+
const res = await fetch(`${url}/models`, { headers, signal: AbortSignal.timeout(10_000), redirect: "error" });
|
|
139
|
+
if (!res.ok) throw new Error(`服务返回 ${res.status}`);
|
|
140
|
+
const body = (await res.json()) as { data?: { id?: unknown }[]; models?: { id?: unknown; name?: unknown }[] };
|
|
141
|
+
const ids = [
|
|
142
|
+
...(body.data ?? []).map((m) => m?.id),
|
|
143
|
+
...(body.models ?? []).map((m) => (typeof m?.id === "string" ? m.id : typeof m?.name === "string" ? m.name.replace(/^models\//, "") : undefined)),
|
|
144
|
+
].filter((v): v is string => typeof v === "string" && !!v.trim());
|
|
145
|
+
return [...new Set(ids)].slice(0, 200);
|
|
146
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// pi 驱动:官方 TypeScript SDK(@earendil-works/pi-coding-agent),进程内运行。
|
|
2
|
+
//
|
|
3
|
+
// 会话怎么跑见 session.ts;会话列表 / 历史自己读 data/pi/sessions 下的 JSONL(history.ts)。
|
|
4
|
+
// 记录是树结构(id / parentId),分叉、回退都用 SDK 的 SessionManager 另存一条新会话,原会话不动。
|
|
5
|
+
import type { AgentCommand } from "../../core/command-catalog.js";
|
|
6
|
+
import { config } from "../../core/config.js";
|
|
7
|
+
import type {
|
|
8
|
+
AgentDriver,
|
|
9
|
+
AgentEvents,
|
|
10
|
+
AgentSession,
|
|
11
|
+
CompleteRequest,
|
|
12
|
+
HistoryMessage,
|
|
13
|
+
InteractionHost,
|
|
14
|
+
ModelInfo,
|
|
15
|
+
RuntimeInfo,
|
|
16
|
+
SessionOptions,
|
|
17
|
+
SessionSummary,
|
|
18
|
+
} from "../../core/types.js";
|
|
19
|
+
import { cachedProbe } from "../claude/probe.js";
|
|
20
|
+
import { NO_PROVIDER } from "./constants.js";
|
|
21
|
+
import { diagnose } from "./errors.js";
|
|
22
|
+
import { listSessionFiles, readHistoryFile, rewindParent, SESSION_ID, sessionFile, sessionTitleOf } from "./history.js";
|
|
23
|
+
import { availableModels, loadSdk, modelKey, modelRuntime, pickModel, SESSIONS_DIR } from "./sdk.js";
|
|
24
|
+
import { PiSession } from "./session.js";
|
|
25
|
+
|
|
26
|
+
const readCatalog = cachedProbe(60_000, "pi 模型列表", () => availableModels(), [] as ModelInfo[]);
|
|
27
|
+
|
|
28
|
+
const COMMANDS: AgentCommand[] = [{ name: "compact", args: "[说明]", description: "压缩上下文(可以附一句要保留什么)", builtin: true }];
|
|
29
|
+
|
|
30
|
+
export class PiDriver implements AgentDriver {
|
|
31
|
+
readonly id = "pi";
|
|
32
|
+
readonly label = "pi";
|
|
33
|
+
readonly capabilities = { effort: true, fork: true, cost: true, streaming: true };
|
|
34
|
+
|
|
35
|
+
async start(): Promise<void> {
|
|
36
|
+
// 先把 SDK 和模型目录加载好,第一条消息不用等
|
|
37
|
+
await modelRuntime();
|
|
38
|
+
}
|
|
39
|
+
async stop(): Promise<void> {}
|
|
40
|
+
|
|
41
|
+
createSession(opts: SessionOptions, events: AgentEvents, host: InteractionHost): AgentSession {
|
|
42
|
+
return new PiSession(opts, events, host);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async listSessions(cwd: string | undefined, limit = 10): Promise<SessionSummary[]> {
|
|
46
|
+
try {
|
|
47
|
+
return listSessionFiles(cwd, limit);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
console.error("[pi] 读取会话列表失败:", err);
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async sessionExists(id: string): Promise<boolean> {
|
|
55
|
+
return SESSION_ID.test(id) && !!sessionFile(id);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async sessionTitle(id: string): Promise<string | undefined> {
|
|
59
|
+
return sessionTitleOf(id);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async readHistory(id: string): Promise<HistoryMessage[]> {
|
|
63
|
+
return readHistoryFile(id);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async forkAt(id: string, cwd: string, anchor?: string): Promise<string> {
|
|
67
|
+
const file = sessionFile(id);
|
|
68
|
+
if (!file) throw new Error("找不到这条 pi 会话的记录");
|
|
69
|
+
const { pi } = await loadSdk();
|
|
70
|
+
if (!anchor) return pi.SessionManager.forkFrom(file, cwd, SESSIONS_DIR).getSessionId();
|
|
71
|
+
const sm = pi.SessionManager.open(file, SESSIONS_DIR, cwd);
|
|
72
|
+
if (!sm.getEntry(anchor)) throw new Error("找不到要分叉的那条回复");
|
|
73
|
+
sm.createBranchedSession(anchor);
|
|
74
|
+
return sm.getSessionId();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async rewindTo(id: string, cwd: string, anchor: string): Promise<string | undefined> {
|
|
78
|
+
const parent = rewindParent(id, anchor);
|
|
79
|
+
if (parent === undefined) throw new Error("找不到要回退到的那条消息");
|
|
80
|
+
if (parent === null) return undefined;
|
|
81
|
+
const { pi } = await loadSdk();
|
|
82
|
+
const sm = pi.SessionManager.open(sessionFile(id)!, SESSIONS_DIR, cwd);
|
|
83
|
+
sm.createBranchedSession(parent);
|
|
84
|
+
return sm.getSessionId();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async listModels(): Promise<ModelInfo[]> {
|
|
88
|
+
return availableModels().catch(() => readCatalog());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
catalog(): Promise<ModelInfo[]> {
|
|
92
|
+
return readCatalog();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async commands(): Promise<AgentCommand[]> {
|
|
96
|
+
return COMMANDS;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async defaults(): Promise<RuntimeInfo> {
|
|
100
|
+
const c = config().agents.pi;
|
|
101
|
+
return { ...(c.defaultModel ? { model: c.defaultModel } : {}), ...(c.defaultEffort ? { effort: c.defaultEffort } : {}) };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async statusLines(): Promise<string[]> {
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 后台整理记忆:直接调模型,不建会话、不给工具、不落记录 */
|
|
109
|
+
async complete(req: CompleteRequest): Promise<unknown> {
|
|
110
|
+
const rt = await modelRuntime();
|
|
111
|
+
const model = await pickModel(req.model || config().agents.pi.defaultModel || undefined);
|
|
112
|
+
if (!model) throw new Error(NO_PROVIDER);
|
|
113
|
+
const abort = new AbortController();
|
|
114
|
+
const timer = setTimeout(() => abort.abort(), req.timeoutMs ?? 120_000);
|
|
115
|
+
try {
|
|
116
|
+
const prompt = `${req.prompt}\n\n只输出一个 JSON 对象(不要代码块、不要解释),符合这个 JSON Schema:\n${JSON.stringify(req.schema)}`;
|
|
117
|
+
const msg = await rt.completeSimple(
|
|
118
|
+
model,
|
|
119
|
+
{ systemPrompt: req.system, messages: [{ role: "user", content: prompt, timestamp: Date.now() }] },
|
|
120
|
+
{ signal: abort.signal, ...(model.reasoning ? { reasoning: "minimal" as const } : {}) },
|
|
121
|
+
);
|
|
122
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted") throw new Error(`后台调用失败(${modelKey(model)}):${msg.errorMessage ?? msg.stopReason}`);
|
|
123
|
+
const text = msg.content
|
|
124
|
+
.filter((b): b is { type: "text"; text: string } => b.type === "text")
|
|
125
|
+
.map((b) => b.text)
|
|
126
|
+
.join("")
|
|
127
|
+
.trim();
|
|
128
|
+
return parseJson(text);
|
|
129
|
+
} finally {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
diagnose(err: unknown) {
|
|
135
|
+
return diagnose(err);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 模型偶尔会套一层代码块、前后加几句话:抠出第一个完整的 JSON 对象 */
|
|
140
|
+
export function parseJson(text: string): unknown {
|
|
141
|
+
const bare = text.replace(/^```(?:json)?\s*|\s*```$/g, "").trim();
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(bare);
|
|
144
|
+
} catch {
|
|
145
|
+
const start = bare.indexOf("{");
|
|
146
|
+
const end = bare.lastIndexOf("}");
|
|
147
|
+
if (start >= 0 && end > start) return JSON.parse(bare.slice(start, end + 1));
|
|
148
|
+
throw new Error(`后台调用没有返回 JSON:${bare.slice(0, 120)}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// pi 的报错翻译成人话(口径同 claude/errors.ts)
|
|
2
|
+
import type { Diagnosis } from "../../core/types.js";
|
|
3
|
+
import { NO_PROVIDER } from "./constants.js";
|
|
4
|
+
|
|
5
|
+
const KEY_HINT = "到 设置 → Agent → pi 的「模型服务商」里填 API Key(凭据存在 agent-loft 的 data/pi/auth.json)。";
|
|
6
|
+
|
|
7
|
+
export function diagnose(err: unknown): Diagnosis {
|
|
8
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
9
|
+
const text = raw.toLowerCase();
|
|
10
|
+
if (raw.includes(NO_PROVIDER) || text.includes("no api key") || text.includes("no model") || text.includes("not configured")) {
|
|
11
|
+
return { kind: "auth_missing", chatMessage: `${NO_PROVIDER}。`, consoleHint: `pi 没有可用的模型:${KEY_HINT}` };
|
|
12
|
+
}
|
|
13
|
+
if (text.includes("401") || text.includes("unauthorized") || text.includes("invalid api key") || text.includes("invalid_api_key") || text.includes("authentication") || text.includes("incorrect api key")) {
|
|
14
|
+
return {
|
|
15
|
+
kind: "auth_missing",
|
|
16
|
+
chatMessage: "pi 用的这家模型服务商不认这个 API Key(填错了或已失效)。\n请机器主人到 设置 → Agent → pi 重新填。",
|
|
17
|
+
consoleHint: `pi 服务商鉴权失败:${raw}。${KEY_HINT}`,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
if (text.includes("cannot find package") || text.includes("err_module_not_found") || text.includes("需要 node")) {
|
|
21
|
+
return {
|
|
22
|
+
kind: "cli_missing",
|
|
23
|
+
chatMessage: `pi 的 SDK 没法加载,我暂时无法工作:${raw.slice(0, 200)}`,
|
|
24
|
+
consoleHint: "在 agent-loft 目录里运行 npm install(pi 需要 Node 22.19 以上),再重启服务。",
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
if (text.includes("rate limit") || text.includes("429") || text.includes("quota") || text.includes("insufficient") || text.includes("balance") || text.includes("余额") || text.includes("额度")) {
|
|
28
|
+
return { kind: "rate_limit", chatMessage: "pi 用的模型服务商额度用完了、余额不足或请求太频繁,稍后再试,或者换个模型。", consoleHint: `pi 额度 / 限流:${raw}` };
|
|
29
|
+
}
|
|
30
|
+
if (text.includes("context") && (text.includes("too long") || text.includes("overflow") || text.includes("maximum"))) {
|
|
31
|
+
return { kind: "context_overflow", chatMessage: "上下文太长了,发 /compact 压缩一下,或者 /new 开新会话。", consoleHint: raw };
|
|
32
|
+
}
|
|
33
|
+
if (text.includes("aborted") || text.includes("interrupted")) {
|
|
34
|
+
return { kind: "turn_aborted", chatMessage: "这一轮已中断。", consoleHint: raw };
|
|
35
|
+
}
|
|
36
|
+
return { kind: "unknown", chatMessage: `pi 出错了:${raw.slice(0, 300)}`, consoleHint: raw };
|
|
37
|
+
}
|