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
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// 读 pi 的会话记录:data/pi/sessions/<时间>_<会话 id>.jsonl(格式见 pi 文档 session-format.md)。
|
|
2
|
+
//
|
|
3
|
+
// 第一行是头 { type: "session", id, cwd, timestamp },后面每行一条记录,靠 id / parentId 连成一棵树:
|
|
4
|
+
// 分叉、回退不删旧记录,只是从更早的一条接着往下写。当前分支 = 从最后一条往上找到根(pi 打开文件时也这么定)。
|
|
5
|
+
// { type: "message", id, parentId, message: { role: "user" | "assistant" | "toolResult" | "system", content, timestamp } }
|
|
6
|
+
// { type: "session_info", name } 会话名称
|
|
7
|
+
// { type: "compaction", summary } 上下文压缩
|
|
8
|
+
// 自己读文件,不用 SDK:列会话、读历史不必为此加载 pi。认不出的记录一律跳过。
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { stripContext } from "../../core/expert-prompt.js";
|
|
12
|
+
import { splitAttachmentNote } from "../../core/uploads.js";
|
|
13
|
+
import type { HistoryMessage, SessionSummary } from "../../core/types.js";
|
|
14
|
+
import { summarize } from "../claude/session.js";
|
|
15
|
+
import { SESSIONS_DIR } from "./sdk.js";
|
|
16
|
+
import { describePiStep } from "./steps.js";
|
|
17
|
+
|
|
18
|
+
/** 会话 id 会拼进路径,先验形(pi 自己的规则,见 assertValidSessionId) */
|
|
19
|
+
export const SESSION_ID = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,126}[A-Za-z0-9])?$/;
|
|
20
|
+
|
|
21
|
+
type Entry = {
|
|
22
|
+
type?: string;
|
|
23
|
+
id?: string;
|
|
24
|
+
parentId?: string | null;
|
|
25
|
+
timestamp?: string;
|
|
26
|
+
cwd?: string;
|
|
27
|
+
name?: string;
|
|
28
|
+
message?: { role?: string; content?: unknown; timestamp?: number };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function sessionsDir(): string {
|
|
32
|
+
return SESSIONS_DIR;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 按会话 id 找记录文件:文件名是「时间_id.jsonl」 */
|
|
36
|
+
export function sessionFile(id: string): string | undefined {
|
|
37
|
+
if (!SESSION_ID.test(id)) return undefined;
|
|
38
|
+
let names: string[];
|
|
39
|
+
try {
|
|
40
|
+
names = fs.readdirSync(sessionsDir());
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const hit = names.filter((n) => n.endsWith(`_${id}.jsonl`)).sort().pop();
|
|
45
|
+
return hit ? path.join(sessionsDir(), hit) : undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function readEntries(file: string): Entry[] {
|
|
49
|
+
const out: Entry[] = [];
|
|
50
|
+
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
|
|
51
|
+
if (!line.trim()) continue;
|
|
52
|
+
try {
|
|
53
|
+
const v = JSON.parse(line) as Entry;
|
|
54
|
+
if (v && typeof v === "object") out.push(v);
|
|
55
|
+
} catch {
|
|
56
|
+
// 写到一半的最后一行
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 当前分支:从最后一条往上走到根,再倒过来 */
|
|
63
|
+
export function activeBranch(entries: Entry[]): Entry[] {
|
|
64
|
+
const body = entries.filter((e) => e.type !== "session" && typeof e.id === "string");
|
|
65
|
+
const byId = new Map(body.map((e) => [e.id!, e]));
|
|
66
|
+
const out: Entry[] = [];
|
|
67
|
+
const seen = new Set<string>();
|
|
68
|
+
for (let e = body[body.length - 1]; e && !seen.has(e.id!); e = e.parentId ? byId.get(e.parentId) : undefined) {
|
|
69
|
+
seen.add(e.id!);
|
|
70
|
+
out.push(e);
|
|
71
|
+
}
|
|
72
|
+
return out.reverse();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function textOf(content: unknown): string {
|
|
76
|
+
if (typeof content === "string") return content;
|
|
77
|
+
if (!Array.isArray(content)) return "";
|
|
78
|
+
return content
|
|
79
|
+
.filter((b): b is { type: "text"; text: string } => !!b && typeof b === "object" && (b as { type?: unknown }).type === "text" && typeof (b as { text?: unknown }).text === "string")
|
|
80
|
+
.map((b) => b.text)
|
|
81
|
+
.join("\n");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function userText(e: Entry): string {
|
|
85
|
+
return splitAttachmentNote(stripContext(textOf(e.message?.content))).text;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function tsOf(e: Entry): number | undefined {
|
|
89
|
+
if (typeof e.message?.timestamp === "number") return e.message.timestamp;
|
|
90
|
+
const t = e.timestamp ? Date.parse(e.timestamp) : NaN;
|
|
91
|
+
return Number.isFinite(t) ? t : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function nameOf(entries: Entry[]): string | undefined {
|
|
95
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
96
|
+
const e = entries[i]!;
|
|
97
|
+
if (e.type === "session_info") return e.name?.trim() || undefined;
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function sessionTitleOf(id: string): string | undefined {
|
|
103
|
+
const file = sessionFile(id);
|
|
104
|
+
if (!file) return undefined;
|
|
105
|
+
try {
|
|
106
|
+
return nameOf(readEntries(file));
|
|
107
|
+
} catch {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function sessionCwd(id: string): string | undefined {
|
|
113
|
+
const file = sessionFile(id);
|
|
114
|
+
if (!file) return undefined;
|
|
115
|
+
try {
|
|
116
|
+
return readEntries(file).find((e) => e.type === "session")?.cwd;
|
|
117
|
+
} catch {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** cwd 为 undefined 时列全部。没说过话的不列 */
|
|
123
|
+
export function listSessionFiles(cwd: string | undefined, limit: number): SessionSummary[] {
|
|
124
|
+
let names: string[];
|
|
125
|
+
try {
|
|
126
|
+
names = fs.readdirSync(sessionsDir());
|
|
127
|
+
} catch {
|
|
128
|
+
return [];
|
|
129
|
+
}
|
|
130
|
+
const files: { id: string; file: string; mtime: number }[] = [];
|
|
131
|
+
for (const n of names) {
|
|
132
|
+
const m = /_([^_]+)\.jsonl$/.exec(n);
|
|
133
|
+
if (!m || !SESSION_ID.test(m[1]!)) continue;
|
|
134
|
+
const file = path.join(sessionsDir(), n);
|
|
135
|
+
try {
|
|
136
|
+
files.push({ id: m[1]!, file, mtime: fs.statSync(file).mtimeMs });
|
|
137
|
+
} catch {
|
|
138
|
+
// 刚被删
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
files.sort((a, b) => b.mtime - a.mtime);
|
|
142
|
+
const out: SessionSummary[] = [];
|
|
143
|
+
for (const f of files.slice(0, 300)) {
|
|
144
|
+
if (out.length >= limit) break;
|
|
145
|
+
let entries: Entry[];
|
|
146
|
+
try {
|
|
147
|
+
entries = readEntries(f.file);
|
|
148
|
+
} catch {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const at = entries.find((e) => e.type === "session")?.cwd;
|
|
152
|
+
if (cwd && at && path.resolve(at) !== path.resolve(cwd)) continue;
|
|
153
|
+
const first = entries.find((e) => e.type === "message" && e.message?.role === "user" && userText(e));
|
|
154
|
+
if (!first) continue;
|
|
155
|
+
out.push({ id: f.id, title: nameOf(entries) ?? summarize(userText(first), 60), ...(at ? { cwd: at } : {}), updatedAt: f.mtime });
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 整理成「一问一答」:用户一条,助手把这一轮的文字拼成一条,工具调用、思考挂成过程摘要 */
|
|
161
|
+
export function readHistoryFile(id: string): HistoryMessage[] {
|
|
162
|
+
const file = sessionFile(id);
|
|
163
|
+
if (!file) return [];
|
|
164
|
+
const out: HistoryMessage[] = [];
|
|
165
|
+
let assistant: HistoryMessage | null = null;
|
|
166
|
+
const flush = () => {
|
|
167
|
+
if (assistant && (assistant.text.trim() || assistant.steps?.length)) out.push(assistant);
|
|
168
|
+
assistant = null;
|
|
169
|
+
};
|
|
170
|
+
for (const e of activeBranch(readEntries(file))) {
|
|
171
|
+
if (e.type === "compaction") {
|
|
172
|
+
assistant ??= { role: "assistant", text: "", steps: [] };
|
|
173
|
+
assistant.steps!.push("🗜️ 上下文已压缩");
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (e.type !== "message" || !e.message) continue;
|
|
177
|
+
const role = e.message.role;
|
|
178
|
+
const ts = tsOf(e);
|
|
179
|
+
if (role === "user") {
|
|
180
|
+
const { text, attachments } = splitAttachmentNote(stripContext(textOf(e.message.content)));
|
|
181
|
+
if (!text && attachments.length === 0) continue;
|
|
182
|
+
flush();
|
|
183
|
+
out.push({ role: "user", text, anchor: e.id!, ...(attachments.length ? { attachments } : {}), ...(ts !== undefined ? { ts } : {}) });
|
|
184
|
+
} else if (role === "assistant") {
|
|
185
|
+
assistant ??= { role: "assistant", text: "", steps: [] };
|
|
186
|
+
assistant.anchor = e.id!;
|
|
187
|
+
if (ts !== undefined) assistant.ts = ts;
|
|
188
|
+
const blocks = Array.isArray(e.message.content) ? (e.message.content as { type?: string; text?: string; thinking?: string; redacted?: boolean; name?: string; arguments?: unknown }[]) : [];
|
|
189
|
+
for (const b of blocks) {
|
|
190
|
+
if (b.type === "text" && b.text?.trim()) assistant.text += (assistant.text ? "\n\n" : "") + b.text;
|
|
191
|
+
else if (b.type === "thinking" && !b.redacted) {
|
|
192
|
+
const t = summarize(b.thinking ?? "");
|
|
193
|
+
if (t) assistant.steps!.push(`💭 ${t}`);
|
|
194
|
+
} else if (b.type === "toolCall" && b.name) {
|
|
195
|
+
assistant.steps!.push(`🔧 ${describePiStep(b.name, b.arguments)}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
flush();
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 回退:要保留到哪条记录(指定的用户消息的上一条);是第一条用户消息就返回 null */
|
|
205
|
+
export function rewindParent(id: string, userAnchor: string): string | null | undefined {
|
|
206
|
+
const file = sessionFile(id);
|
|
207
|
+
if (!file) return undefined;
|
|
208
|
+
const branch = activeBranch(readEntries(file));
|
|
209
|
+
const i = branch.findIndex((e) => e.id === userAnchor);
|
|
210
|
+
if (i < 0) return undefined;
|
|
211
|
+
// 往前找最近的一条对话消息:前面只有模型、思考程度这类设置记录的,就算第一条
|
|
212
|
+
for (let j = i - 1; j >= 0; j--) {
|
|
213
|
+
const e = branch[j]!;
|
|
214
|
+
if (e.type === "message" && (e.message?.role === "user" || e.message?.role === "assistant" || e.message?.role === "toolResult")) return e.id!;
|
|
215
|
+
}
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// pi 的订阅账号登录(OAuth)搬到网页上:后台跑 ModelRuntime.login(provider, "oauth"),
|
|
2
|
+
// 它要的交互(选登录方式、填企业域名、粘贴回调地址)和给的提示(登录链接、设备码、进度)都记成一份状态,
|
|
3
|
+
// 网页轮询这份状态、把用户的回答交回来。整台服务器同一时间只有一个登录在跑。
|
|
4
|
+
//
|
|
5
|
+
// 服务器上通常没有浏览器:「浏览器登录」时 pi 在服务器的 127.0.0.1 上等回调,用户的浏览器在别的机器上回调不到,
|
|
6
|
+
// 这时 pi 会让人把浏览器最后跳到的地址(或授权码)粘贴回来 —— 网页上就是一个输入框。设备码方式不受影响。
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { AGENT_DIR, modelRuntime } from "./sdk.js";
|
|
11
|
+
|
|
12
|
+
export type OAuthPrompt = {
|
|
13
|
+
id: string;
|
|
14
|
+
type: "text" | "secret" | "select" | "manual_code";
|
|
15
|
+
message: string;
|
|
16
|
+
placeholder?: string;
|
|
17
|
+
options?: { id: string; label: string; description?: string }[];
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type OAuthNotice =
|
|
21
|
+
| { type: "info"; message: string; links?: { url: string; label?: string }[] }
|
|
22
|
+
| { type: "auth_url"; url: string; instructions?: string }
|
|
23
|
+
| { type: "device_code"; userCode: string; verificationUri: string }
|
|
24
|
+
| { type: "progress"; message: string };
|
|
25
|
+
|
|
26
|
+
export type OAuthState = {
|
|
27
|
+
provider: string;
|
|
28
|
+
status: "running" | "done" | "error" | "cancelled";
|
|
29
|
+
notices: OAuthNotice[];
|
|
30
|
+
prompt?: OAuthPrompt;
|
|
31
|
+
error?: string;
|
|
32
|
+
startedAt: number;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type Job = {
|
|
36
|
+
state: OAuthState;
|
|
37
|
+
abort: AbortController;
|
|
38
|
+
answer?: { id: string; resolve: (v: string) => void; reject: (e: Error) => void };
|
|
39
|
+
timer: NodeJS.Timeout;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** 登录最多等这么久(设备码一般 15 分钟过期) */
|
|
43
|
+
const LOGIN_TIMEOUT_MS = 15 * 60_000;
|
|
44
|
+
let job: Job | null = null;
|
|
45
|
+
const listeners = new Set<() => void>();
|
|
46
|
+
|
|
47
|
+
/** 登录成功了(体检缓存要作废、模型列表要刷新) */
|
|
48
|
+
export function onOAuthDone(fn: () => void): void {
|
|
49
|
+
listeners.add(fn);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 只给网页看的那部分:别把 OAuth 返回的东西带出去(这里本来也没有) */
|
|
53
|
+
export function oauthState(): OAuthState | null {
|
|
54
|
+
return job ? structuredClone(job.state) : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 有的服务商(OpenAI)登录要一个固定的「这台安装」的 id:第一次用时生成,存在 data/pi/device-id */
|
|
58
|
+
function deviceId(): string {
|
|
59
|
+
const file = path.join(AGENT_DIR, "device-id");
|
|
60
|
+
try {
|
|
61
|
+
const v = fs.readFileSync(file, "utf8").trim();
|
|
62
|
+
if (/^[0-9a-f-]{36}$/i.test(v)) return v;
|
|
63
|
+
} catch {
|
|
64
|
+
// 第一次
|
|
65
|
+
}
|
|
66
|
+
const id = randomUUID();
|
|
67
|
+
fs.mkdirSync(AGENT_DIR, { recursive: true, mode: 0o700 });
|
|
68
|
+
fs.writeFileSync(file, `${id}\n`, { mode: 0o600 });
|
|
69
|
+
return id;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 只放行 http(s) 链接:网页上会直接做成可点的链接 */
|
|
73
|
+
function safeUrl(url: string): string | undefined {
|
|
74
|
+
return /^https?:\/\//i.test(url) ? url : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function finish(j: Job, status: OAuthState["status"], error?: string): void {
|
|
78
|
+
if (j.state.status !== "running") return;
|
|
79
|
+
clearTimeout(j.timer);
|
|
80
|
+
j.state.status = status;
|
|
81
|
+
delete j.state.prompt;
|
|
82
|
+
if (error) j.state.error = error;
|
|
83
|
+
j.answer?.reject(new Error(status === "cancelled" ? "已取消" : (error ?? "已结束")));
|
|
84
|
+
j.answer = undefined;
|
|
85
|
+
if (status === "done") for (const fn of listeners) fn();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function startOAuth(providerId: string): Promise<OAuthState> {
|
|
89
|
+
const rt = await modelRuntime();
|
|
90
|
+
const provider = rt.getProvider(providerId);
|
|
91
|
+
const oauth = (provider as { auth?: { oauth?: unknown } } | undefined)?.auth?.oauth;
|
|
92
|
+
if (!provider || !oauth) throw new Error(`${provider?.name ?? providerId} 不支持订阅账号登录`);
|
|
93
|
+
if (job) cancelOAuth();
|
|
94
|
+
const abort = new AbortController();
|
|
95
|
+
const j: Job = {
|
|
96
|
+
state: { provider: providerId, status: "running", notices: [], startedAt: Date.now() },
|
|
97
|
+
abort,
|
|
98
|
+
timer: setTimeout(() => {
|
|
99
|
+
abort.abort();
|
|
100
|
+
finish(j, "error", "登录超时了,重新开始");
|
|
101
|
+
}, LOGIN_TIMEOUT_MS),
|
|
102
|
+
};
|
|
103
|
+
j.timer.unref?.();
|
|
104
|
+
job = j;
|
|
105
|
+
void rt
|
|
106
|
+
.login(
|
|
107
|
+
providerId,
|
|
108
|
+
"oauth",
|
|
109
|
+
{
|
|
110
|
+
signal: abort.signal,
|
|
111
|
+
prompt: (p) =>
|
|
112
|
+
new Promise<string>((resolve, reject) => {
|
|
113
|
+
if (j.state.status !== "running") return reject(new Error("已结束"));
|
|
114
|
+
const id = randomUUID();
|
|
115
|
+
j.state.prompt = {
|
|
116
|
+
id,
|
|
117
|
+
type: p.type,
|
|
118
|
+
message: p.message,
|
|
119
|
+
...("placeholder" in p && p.placeholder ? { placeholder: p.placeholder } : {}),
|
|
120
|
+
...(p.type === "select" ? { options: p.options.map((o) => ({ id: o.id, label: o.label, ...(o.description ? { description: o.description } : {}) })) } : {}),
|
|
121
|
+
};
|
|
122
|
+
const clear = () => {
|
|
123
|
+
if (j.state.prompt?.id === id) delete j.state.prompt;
|
|
124
|
+
if (j.answer?.id === id) j.answer = undefined;
|
|
125
|
+
};
|
|
126
|
+
j.answer = {
|
|
127
|
+
id,
|
|
128
|
+
resolve: (v) => {
|
|
129
|
+
clear();
|
|
130
|
+
resolve(v);
|
|
131
|
+
},
|
|
132
|
+
reject: (e) => {
|
|
133
|
+
clear();
|
|
134
|
+
reject(e);
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
// pi 自己撤掉这个问题(比如回调先到了,粘贴框就不用了)
|
|
138
|
+
p.signal?.addEventListener("abort", () => j.answer?.id === id && j.answer.reject(new Error("aborted")), { once: true });
|
|
139
|
+
}),
|
|
140
|
+
notify: (e) => {
|
|
141
|
+
if (j.state.status !== "running") return;
|
|
142
|
+
const links = e.type === "info" ? (e.links ?? []).filter((l) => safeUrl(l.url)).map((l) => ({ url: l.url, ...(l.label ? { label: l.label } : {}) })) : [];
|
|
143
|
+
const n: OAuthNotice | null =
|
|
144
|
+
e.type === "auth_url"
|
|
145
|
+
? safeUrl(e.url)
|
|
146
|
+
? { type: "auth_url", url: e.url, ...(e.instructions ? { instructions: e.instructions } : {}) }
|
|
147
|
+
: null
|
|
148
|
+
: e.type === "device_code"
|
|
149
|
+
? safeUrl(e.verificationUri)
|
|
150
|
+
? { type: "device_code", userCode: e.userCode, verificationUri: e.verificationUri }
|
|
151
|
+
: null
|
|
152
|
+
: e.type === "info"
|
|
153
|
+
? { type: "info", message: e.message, ...(links.length ? { links } : {}) }
|
|
154
|
+
: e.type === "progress"
|
|
155
|
+
? { type: "progress", message: e.message }
|
|
156
|
+
: null;
|
|
157
|
+
if (!n) return;
|
|
158
|
+
// 进度只留最新一条,别越积越长
|
|
159
|
+
if (n.type === "progress") j.state.notices = j.state.notices.filter((x) => x.type !== "progress");
|
|
160
|
+
j.state.notices.push(n);
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
{ getDeviceId: deviceId, agentName: "agent-loft" },
|
|
164
|
+
)
|
|
165
|
+
.then(() => finish(j, "done"))
|
|
166
|
+
.catch((err) => finish(j, abort.signal.aborted ? "cancelled" : "error", err instanceof Error ? err.message : String(err)));
|
|
167
|
+
return oauthState()!;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 网页交回的回答:要对得上当前这个问题(id),对不上说明问题已经换了 */
|
|
171
|
+
export function answerOAuth(promptId: string, value: string): void {
|
|
172
|
+
const a = job?.answer;
|
|
173
|
+
if (!job || job.state.status !== "running" || !a || a.id !== promptId) throw new Error("这个问题已经过期了,刷新一下");
|
|
174
|
+
const p = job.state.prompt;
|
|
175
|
+
if (p?.type === "select" && !p.options?.some((o) => o.id === value)) throw new Error("选项不对");
|
|
176
|
+
a.resolve(value);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function cancelOAuth(): void {
|
|
180
|
+
if (!job) return;
|
|
181
|
+
const j = job;
|
|
182
|
+
j.abort.abort();
|
|
183
|
+
finish(j, "cancelled");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 测试用 */
|
|
187
|
+
export function resetOAuth(): void {
|
|
188
|
+
if (job) cancelOAuth();
|
|
189
|
+
job = null;
|
|
190
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// pi(earendil-works/pi,原 @mariozechner/pi-coding-agent)的官方 TypeScript SDK,进程内运行。
|
|
2
|
+
//
|
|
3
|
+
// pi 不是账号制,是「模型服务商」制:每家服务商一份凭据(API Key 或 OAuth),由 ModelRuntime 统一管。
|
|
4
|
+
// agent-loft 自己管这些凭据:所有东西都放在 data/pi/ 下,不读也不写机器上的 ~/.pi:
|
|
5
|
+
// data/pi/auth.json 各服务商的凭据(pi 自己写,0600)
|
|
6
|
+
// data/pi/models.json 自定义服务商 / 模型(可选,比如本地的 llama.cpp、OpenAI 兼容的网关)
|
|
7
|
+
// data/pi/sessions/ 会话记录(JSONL,一个会话一个文件,文件名以会话 id 结尾)
|
|
8
|
+
// 也认 agent-loft 服务进程的环境变量(DEEPSEEK_API_KEY 之类,pi 的规则)。
|
|
9
|
+
//
|
|
10
|
+
// SDK 依赖不少(TUI、wasm 图片处理……),按需 import:没启用 pi 的机器启动时不加载它。
|
|
11
|
+
// pi 1.x 要求 Node ≥ 22.19,比 agent-loft 本身的要求高,版本不够时体检里报出来。
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
15
|
+
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { dataDir } from "../../home.js";
|
|
17
|
+
import type { ModelInfo } from "../../core/types.js";
|
|
18
|
+
|
|
19
|
+
export const AGENT_DIR = path.join(dataDir, "pi");
|
|
20
|
+
export const AUTH_FILE = path.join(AGENT_DIR, "auth.json");
|
|
21
|
+
export const MODELS_FILE = path.join(AGENT_DIR, "models.json");
|
|
22
|
+
export const SESSIONS_DIR = path.join(AGENT_DIR, "sessions");
|
|
23
|
+
|
|
24
|
+
export const MIN_NODE = [22, 19] as const;
|
|
25
|
+
export function nodeOk(version = process.versions.node): boolean {
|
|
26
|
+
const [major = 0, minor = 0] = version.split(".").map(Number);
|
|
27
|
+
return major > MIN_NODE[0] || (major === MIN_NODE[0] && minor >= MIN_NODE[1]);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type Sdk = typeof import("@earendil-works/pi-coding-agent");
|
|
31
|
+
type Ai = typeof import("@earendil-works/pi-ai");
|
|
32
|
+
let sdk: Promise<{ pi: Sdk; ai: Ai }> | null = null;
|
|
33
|
+
|
|
34
|
+
export function loadSdk(): Promise<{ pi: Sdk; ai: Ai }> {
|
|
35
|
+
sdk ??= (async () => {
|
|
36
|
+
if (!nodeOk()) throw new Error(`pi 需要 Node ${MIN_NODE.join(".")} 以上,现在是 ${process.versions.node}`);
|
|
37
|
+
const [pi, ai] = await Promise.all([import("@earendil-works/pi-coding-agent"), import("@earendil-works/pi-ai")]);
|
|
38
|
+
return { pi, ai };
|
|
39
|
+
})().catch((err) => {
|
|
40
|
+
sdk = null;
|
|
41
|
+
throw err;
|
|
42
|
+
});
|
|
43
|
+
return sdk;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let runtime: Promise<ModelRuntime> | null = null;
|
|
47
|
+
|
|
48
|
+
/** 整个进程共用一个 ModelRuntime:凭据、模型目录、可用性都在这里 */
|
|
49
|
+
export function modelRuntime(): Promise<ModelRuntime> {
|
|
50
|
+
runtime ??= (async () => {
|
|
51
|
+
const { pi } = await loadSdk();
|
|
52
|
+
fs.mkdirSync(AGENT_DIR, { recursive: true, mode: 0o700 });
|
|
53
|
+
fs.mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 });
|
|
54
|
+
return pi.ModelRuntime.create({ authPath: AUTH_FILE, modelsPath: MODELS_FILE });
|
|
55
|
+
})().catch((err) => {
|
|
56
|
+
runtime = null;
|
|
57
|
+
throw err;
|
|
58
|
+
});
|
|
59
|
+
return runtime;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 测试用:换一个 runtime(比如注册了假服务商的) */
|
|
63
|
+
export function setModelRuntime(rt: ModelRuntime | null): void {
|
|
64
|
+
runtime = rt ? Promise.resolve(rt) : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---------- 模型 ----------
|
|
68
|
+
|
|
69
|
+
/** agent-loft 里的模型 id 是「服务商/模型」(模型 id 自己也可能带斜杠,比如 OpenRouter 的) */
|
|
70
|
+
export function modelKey(m: Pick<Model<Api>, "provider" | "id">): string {
|
|
71
|
+
return `${m.provider}/${m.id}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function splitModelKey(key: string): { provider: string; id: string } | null {
|
|
75
|
+
const i = key.indexOf("/");
|
|
76
|
+
if (i <= 0 || i === key.length - 1) return null;
|
|
77
|
+
return { provider: key.slice(0, i), id: key.slice(i + 1) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function findModel(key: string): Promise<Model<Api> | undefined> {
|
|
81
|
+
const parts = splitModelKey(key);
|
|
82
|
+
if (!parts) return undefined;
|
|
83
|
+
return (await modelRuntime()).getModel(parts.provider, parts.id);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 模型支持的思考程度(不支持思考的模型没有) */
|
|
87
|
+
export async function effortsOf(model: Model<Api>): Promise<string[]> {
|
|
88
|
+
if (!model.reasoning) return [];
|
|
89
|
+
const { ai } = await loadSdk();
|
|
90
|
+
return ai.getSupportedThinkingLevels(model).filter((l) => l !== "off");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function modelInfo(model: Model<Api>, providerName?: string): Promise<ModelInfo> {
|
|
94
|
+
const efforts = await effortsOf(model);
|
|
95
|
+
return {
|
|
96
|
+
id: modelKey(model),
|
|
97
|
+
label: model.name || model.id,
|
|
98
|
+
...(providerName ? { description: providerName } : {}),
|
|
99
|
+
...(efforts.length ? { efforts } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 配好了凭据的服务商下的所有模型 */
|
|
104
|
+
export async function availableModels(): Promise<ModelInfo[]> {
|
|
105
|
+
const rt = await modelRuntime();
|
|
106
|
+
const models = await rt.getAvailable();
|
|
107
|
+
const names = new Map(rt.getProviders().map((p) => [p.id, p.name]));
|
|
108
|
+
return Promise.all(models.map((m) => modelInfo(m, names.get(m.provider))));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 没指定模型时用哪个:设置里的默认 → 能用的里面按常见的顺序挑一个。
|
|
113
|
+
* 都没有(一家服务商都没配)返回 undefined,由调用方报「先配服务商」
|
|
114
|
+
*/
|
|
115
|
+
const PREFERRED_PROVIDERS = ["deepseek", "zai-coding-cn", "kimi-coding", "moonshotai-cn", "qwen-token-plan-cn", "minimax-cn", "anthropic", "openai", "openrouter"];
|
|
116
|
+
export async function pickModel(preferred?: string): Promise<Model<Api> | undefined> {
|
|
117
|
+
if (preferred) {
|
|
118
|
+
const m = await findModel(preferred);
|
|
119
|
+
if (m) return m;
|
|
120
|
+
}
|
|
121
|
+
const rt = await modelRuntime();
|
|
122
|
+
const models = await rt.getAvailable();
|
|
123
|
+
if (!models.length) return undefined;
|
|
124
|
+
for (const p of PREFERRED_PROVIDERS) {
|
|
125
|
+
const hit = models.find((m) => m.provider === p);
|
|
126
|
+
if (hit) return hit;
|
|
127
|
+
}
|
|
128
|
+
return models[0];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------- 服务商凭据 ----------
|
|
132
|
+
|
|
133
|
+
export type ProviderView = {
|
|
134
|
+
id: string;
|
|
135
|
+
name: string;
|
|
136
|
+
/** 能填 API Key */
|
|
137
|
+
apiKey: boolean;
|
|
138
|
+
/** 能用 OAuth 登录(订阅账号):登录方式的名字,如「Anthropic (Claude Pro/Max)」 */
|
|
139
|
+
oauth?: string;
|
|
140
|
+
/** OAuth 是订阅账号(Claude Pro、ChatGPT Plus、Copilot……) */
|
|
141
|
+
subscription?: boolean;
|
|
142
|
+
/** 能用了(存了凭据,或者服务进程有对应的环境变量 / 云凭据) */
|
|
143
|
+
configured: boolean;
|
|
144
|
+
/** 凭据在 data/pi/auth.json 里(能在网页上删) */
|
|
145
|
+
stored?: "api_key" | "oauth";
|
|
146
|
+
models: number;
|
|
147
|
+
/** 在 data/pi/models.json 里自定义的(网页上「自定义服务商」那一块管) */
|
|
148
|
+
custom?: boolean;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export async function listProviders(): Promise<ProviderView[]> {
|
|
152
|
+
const rt = await modelRuntime();
|
|
153
|
+
const stored = new Map((await rt.listCredentials()).map((c) => [c.providerId, c.type]));
|
|
154
|
+
let custom = new Set<string>();
|
|
155
|
+
try {
|
|
156
|
+
custom = new Set(Object.keys((JSON.parse(fs.readFileSync(MODELS_FILE, "utf8")) as { providers?: object }).providers ?? {}));
|
|
157
|
+
} catch {
|
|
158
|
+
// 没有 models.json
|
|
159
|
+
}
|
|
160
|
+
return rt
|
|
161
|
+
.getProviders()
|
|
162
|
+
.map((p) => {
|
|
163
|
+
const auth = (p as { auth?: { apiKey?: { login?: unknown }; oauth?: { name?: string; isSubscription?: boolean } } }).auth ?? {};
|
|
164
|
+
const kind = stored.get(p.id);
|
|
165
|
+
return {
|
|
166
|
+
id: p.id,
|
|
167
|
+
name: p.name,
|
|
168
|
+
apiKey: !!auth.apiKey?.login,
|
|
169
|
+
...(auth.oauth ? { oauth: auth.oauth.name || p.name, ...(auth.oauth.isSubscription ? { subscription: true } : {}) } : {}),
|
|
170
|
+
configured: rt.hasConfiguredAuth(p.id),
|
|
171
|
+
...(kind ? { stored: kind } : {}),
|
|
172
|
+
models: rt.getModels(p.id).length,
|
|
173
|
+
...(custom.has(p.id) ? { custom: true } : {}),
|
|
174
|
+
};
|
|
175
|
+
})
|
|
176
|
+
.filter((p) => p.models > 0 && (p.apiKey || p.oauth || p.configured));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 存一家服务商的 API Key:走 pi 自己的登录流程(它负责格式、落盘、刷新可用模型)。
|
|
181
|
+
* 有的服务商除了 Key 还要别的(Cloudflare 的账号 id 之类),网页上暂不支持,直接报错
|
|
182
|
+
*/
|
|
183
|
+
export async function setApiKey(providerId: string, key: string): Promise<void> {
|
|
184
|
+
const rt = await modelRuntime();
|
|
185
|
+
const provider = rt.getProvider(providerId);
|
|
186
|
+
if (!provider) throw new Error(`没有这个服务商:${providerId}`);
|
|
187
|
+
let asked = 0;
|
|
188
|
+
await rt.login(providerId, "api_key", {
|
|
189
|
+
prompt: async (p) => {
|
|
190
|
+
asked++;
|
|
191
|
+
if (p.type === "secret" && asked === 1) return key;
|
|
192
|
+
throw new Error(`${provider.name} 除了 API Key 还要填别的信息(${p.message}),网页上暂不支持;可以给 agent-loft 服务设环境变量`);
|
|
193
|
+
},
|
|
194
|
+
notify: () => {},
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function removeCredential(providerId: string): Promise<void> {
|
|
199
|
+
const rt = await modelRuntime();
|
|
200
|
+
await rt.logout(providerId);
|
|
201
|
+
}
|