agent-loft 0.2.103 → 0.2.105
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 +58 -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 +4 -2
- 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/web/workbuddy.png +0 -0
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
// 一条会话 ↔ 一个进程内的 pi AgentSession(SDK 的 createAgentSession)。
|
|
2
|
+
//
|
|
3
|
+
// pi 自己没有权限系统(官方说明:不逐次审批、没有沙箱),授权卡是这边做的:
|
|
4
|
+
// 挂一个内联扩展,在 tool_call 钩子里按权限级别放行 / 弹卡 / 拦下({ block: true })。
|
|
5
|
+
// 计划模式、提问卡 pi 也没有,用两个自定义工具补上:exit_plan_mode(交方案给用户批)、ask_user(问用户)。
|
|
6
|
+
//
|
|
7
|
+
// 消息先留在本地排队,上一轮跑完才交给 pi(prompt() 跑完一整轮才返回)—— 停止时排着的能一起丢掉。
|
|
8
|
+
// 记忆 / 定时任务 / 技能 MCP 和个人 MCP 交给 pi 自带的 MCP 扩展连(stdio / HTTP),工具直接给模型。
|
|
9
|
+
// 凭据、会话记录都在 data/pi/ 下(见 sdk.ts),不读机器上的 ~/.pi;项目里的 .pi/ 扩展一律不加载(会执行代码)。
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import type { ImageContent } from "@earendil-works/pi-ai";
|
|
13
|
+
import type { AgentSession as PiAgentSession, AgentSessionEvent, ExtensionAPI, ToolCallEventResult, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { config } from "../../core/config.js";
|
|
15
|
+
import { expertAppend, expertSystemPrompt, RICH_REPLY_LINES, wrapContext } from "../../core/expert-prompt.js";
|
|
16
|
+
import { ACCESS_LEVELS, type ExpertAccess } from "../../core/experts.js";
|
|
17
|
+
import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
|
|
18
|
+
import type { PermissionLevel } from "../../core/permission.js";
|
|
19
|
+
import { codexSkillLines } from "../../core/skill-runtime.js";
|
|
20
|
+
import { SKILLS_MCP_NAME, skillsMcpSpawn, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
|
|
21
|
+
import { describeAttachments, inlineTextBlocks, readTextAttachments } from "../../core/uploads.js";
|
|
22
|
+
import type {
|
|
23
|
+
AgentEvents,
|
|
24
|
+
AgentSession,
|
|
25
|
+
InteractionHost,
|
|
26
|
+
InterruptOptions,
|
|
27
|
+
ModelInfo,
|
|
28
|
+
RuntimeInfo,
|
|
29
|
+
SavedAttachment,
|
|
30
|
+
SessionOptions,
|
|
31
|
+
TokenUsage,
|
|
32
|
+
UserInput,
|
|
33
|
+
} from "../../core/types.js";
|
|
34
|
+
import { summarize } from "../claude/session.js";
|
|
35
|
+
import { parseQuestions } from "../claude/permissions.js";
|
|
36
|
+
import { NO_PROVIDER } from "./constants.js";
|
|
37
|
+
import { sessionFile } from "./history.js";
|
|
38
|
+
import { ASK_TOOL, describePiStep, PLAN_TOOL } from "./steps.js";
|
|
39
|
+
import { AGENT_DIR, availableModels, findModel, loadSdk, modelKey, modelRuntime, pickModel, SESSIONS_DIR } from "./sdk.js";
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
/** 只读、不会改东西的内置工具:任何级别都直接放行 */
|
|
43
|
+
const READ_TOOLS = new Set(["read", "grep", "find", "ls"]);
|
|
44
|
+
/** 改文件的内置工具:「自动改文件」级别下,改的是工作目录(或附件目录)里的文件就不问 */
|
|
45
|
+
const EDIT_TOOLS = new Set(["edit", "write"]);
|
|
46
|
+
/**
|
|
47
|
+
* 给 pi 的工具白名单:内置的 7 个(按专家的文件权限给)、两个补上的、所有 MCP 工具。
|
|
48
|
+
* 不给 access(内置的 pi)就是全部:能跑命令
|
|
49
|
+
*/
|
|
50
|
+
export function toolsFor(access?: ExpertAccess): string[] {
|
|
51
|
+
const rank = access ? ACCESS_LEVELS.indexOf(access) : ACCESS_LEVELS.length - 1;
|
|
52
|
+
return [...(rank >= 1 ? ["read", "grep", "find", "ls"] : []), ...(rank >= 2 ? ["edit", "write"] : []), ...(rank >= 3 ? ["bash"] : []), ASK_TOOL, PLAN_TOOL, "mcp__*"];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 这个会话的个人 MCP:自定义专家用专家选的,内置的 pi 用设置 → Agent 里选的 */
|
|
56
|
+
export function userMcp(opts: Pick<SessionOptions, "expert" | "builtinMcp">): { mcp: Record<string, object>; askMcp: string[] } | undefined {
|
|
57
|
+
if (opts.expert) return { mcp: opts.expert.mcp, askMcp: opts.expert.askMcp };
|
|
58
|
+
return opts.builtinMcp ? { mcp: opts.builtinMcp.mcp, askMcp: opts.builtinMcp.askMcp } : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const AGENT_LOFT_MCP = new Set([MEMORY_MCP_NAME, TASKS_MCP_NAME, SKILLS_MCP_NAME]);
|
|
62
|
+
|
|
63
|
+
const PLAN_LINES = [
|
|
64
|
+
"## 计划模式",
|
|
65
|
+
"",
|
|
66
|
+
"用户开着计划模式:这一轮只读、只出方案,不要改文件、不要跑会改东西的命令(bash / edit / write 会被拦下)。",
|
|
67
|
+
"把代码看清楚后,调用 exit_plan_mode 工具,把完整方案(markdown)放进 plan 参数交给用户批准;批准了才按方案动手。",
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
export type Gate = { allow: true } | { allow: false; reason: string } | { ask: true; sessionable: boolean };
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 不弹卡就能定下来的部分(纯函数,便于测试):放行 / 拦下 / 要问用户。
|
|
74
|
+
* 「完全允许」和「本会话全部允许」由调用方在 ask 之后处理(调用前询问的 MCP 不受它们影响)
|
|
75
|
+
*/
|
|
76
|
+
export function gateOf(
|
|
77
|
+
toolName: string,
|
|
78
|
+
input: Record<string, unknown>,
|
|
79
|
+
ctx: { level: PermissionLevel | undefined; plan: boolean; cwd: string; uploadsDir: string; mcp?: { mcp: Record<string, object>; askMcp: string[] }; agentLoftMcp: boolean },
|
|
80
|
+
): Gate {
|
|
81
|
+
if (READ_TOOLS.has(toolName) || toolName === ASK_TOOL || toolName === PLAN_TOOL) return { allow: true };
|
|
82
|
+
const mcp = /^mcp__(.+?)__/.exec(toolName)?.[1];
|
|
83
|
+
if (mcp) {
|
|
84
|
+
if (AGENT_LOFT_MCP.has(mcp) && ctx.agentLoftMcp) return { allow: true };
|
|
85
|
+
const picked = ctx.mcp;
|
|
86
|
+
const configured = !!picked && mcp in picked.mcp;
|
|
87
|
+
const asksFirst = configured && picked!.askMcp.includes(mcp);
|
|
88
|
+
if (configured && !asksFirst) return { allow: true };
|
|
89
|
+
return { ask: true, sessionable: !asksFirst };
|
|
90
|
+
}
|
|
91
|
+
if (ctx.plan && (toolName === "bash" || EDIT_TOOLS.has(toolName))) {
|
|
92
|
+
return { allow: false, reason: "现在是计划模式:只读、出方案,不能改文件或跑命令。方案想好了就调用 exit_plan_mode 交给用户批准。" };
|
|
93
|
+
}
|
|
94
|
+
if (EDIT_TOOLS.has(toolName) && (ctx.level === "edit" || ctx.level === "auto") && typeof input.path === "string") {
|
|
95
|
+
const file = path.resolve(ctx.cwd, input.path);
|
|
96
|
+
if (inside(file, ctx.cwd) || inside(file, ctx.uploadsDir)) return { allow: true };
|
|
97
|
+
}
|
|
98
|
+
return { ask: true, sessionable: true };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function inside(file: string, dir: string): boolean {
|
|
102
|
+
const rel = path.relative(path.resolve(dir), file);
|
|
103
|
+
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 授权卡上的说明:pi 的工具参数是 path / command / edits / content */
|
|
107
|
+
export function describePiTool(toolName: string, input: Record<string, unknown>): string {
|
|
108
|
+
if (toolName === "bash") return `\`\`\`bash\n${String(input.command ?? "")}\n\`\`\``;
|
|
109
|
+
if (toolName === "write") {
|
|
110
|
+
const content = String(input.content ?? "");
|
|
111
|
+
const preview = content.length > 1500 ? `${content.slice(0, 1500)}\n…(共 ${content.length} 字)` : content;
|
|
112
|
+
return `**写入文件**:\`${String(input.path ?? "")}\`\n\n\`\`\`\n${preview}\n\`\`\``;
|
|
113
|
+
}
|
|
114
|
+
if (toolName === "edit") {
|
|
115
|
+
const edits = Array.isArray(input.edits) ? (input.edits as { oldText?: unknown; newText?: unknown }[]) : [];
|
|
116
|
+
const body = edits
|
|
117
|
+
.slice(0, 5)
|
|
118
|
+
.map((e) => `\`\`\`diff\n${diffLines(String(e.oldText ?? ""), "-")}\n${diffLines(String(e.newText ?? ""), "+")}\n\`\`\``)
|
|
119
|
+
.join("\n\n");
|
|
120
|
+
return `**修改文件**:\`${String(input.path ?? "")}\`(${edits.length} 处)${body ? `\n\n${body}` : ""}${edits.length > 5 ? "\n\n…" : ""}`;
|
|
121
|
+
}
|
|
122
|
+
return `\`\`\`json\n${JSON.stringify(input, null, 2)}\n\`\`\``;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function diffLines(text: string, mark: string): string {
|
|
126
|
+
const lines = text.split("\n");
|
|
127
|
+
const shown = lines.slice(0, 20).map((l) => `${mark} ${l}`);
|
|
128
|
+
if (lines.length > 20) shown.push(`${mark} …(共 ${lines.length} 行)`);
|
|
129
|
+
return shown.join("\n");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 图片直接给模型看(模型要支持图片输入);其余附件只给路径,让它自己读 */
|
|
133
|
+
const INLINE_IMAGE_MAX = 3.75 * 1024 * 1024;
|
|
134
|
+
function canInline(a: SavedAttachment, images: boolean): boolean {
|
|
135
|
+
return images && !!a.mediaType && /^image\/(png|jpeg|gif|webp)$/.test(a.mediaType) && a.size <= INLINE_IMAGE_MAX;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** noRead:只能联网的专家没有读文件的工具,文本附件的内容直接放进消息 */
|
|
139
|
+
export function buildPrompt(input: UserInput, images: boolean, plan: boolean, noRead = false): { text: string; images: ImageContent[] } {
|
|
140
|
+
const texts = noRead ? readTextAttachments(input.attachments) : new Map<string, string>();
|
|
141
|
+
const inlined = (a: SavedAttachment) => canInline(a, images) || texts.has(a.path);
|
|
142
|
+
const note = input.attachments.length ? describeAttachments(input.attachments, inlined, noRead) : "";
|
|
143
|
+
const blocks = noRead ? inlineTextBlocks(input.attachments, texts) : "";
|
|
144
|
+
const text = [input.text, note, blocks, plan ? wrapContext(PLAN_LINES) : ""].filter(Boolean).join("\n\n");
|
|
145
|
+
const out: ImageContent[] = [];
|
|
146
|
+
for (const a of input.attachments) {
|
|
147
|
+
if (!canInline(a, images)) continue;
|
|
148
|
+
out.push({ type: "image", data: fs.readFileSync(a.path).toString("base64"), mimeType: a.mediaType! });
|
|
149
|
+
}
|
|
150
|
+
return { text, images: out };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 系统提示:内置的 pi 用原装的,后面追加回复格式、记忆、技能清单。
|
|
155
|
+
* 自定义专家「只用专家的提示词」:换掉 pi 原装的开头(身份、工具说明、规则),追加、项目说明、工作目录照旧;
|
|
156
|
+
* 「追加在原装后面」:原装的不动,专家的人设和能力说明追加在后面
|
|
157
|
+
*/
|
|
158
|
+
export function promptParts(opts: SessionOptions): { system?: string; append: string } {
|
|
159
|
+
const e = opts.expert;
|
|
160
|
+
const skills = codexSkillLines(opts.skills).join("\n");
|
|
161
|
+
const join = (parts: (string | undefined)[]) => parts.filter(Boolean).join("\n\n");
|
|
162
|
+
if (!e) return { append: join([RICH_REPLY_LINES.join("\n"), opts.memory?.prompt, skills]) };
|
|
163
|
+
// pi 没有联网搜索 / 读网页的工具(要联网就给专家挂 MCP)
|
|
164
|
+
if (e.basePrompt === "lean") return { system: expertSystemPrompt(e, undefined, opts.cwd, opts.memory?.prompt), append: skills };
|
|
165
|
+
return { append: join([expertAppend(e, undefined, opts.cwd), opts.memory?.prompt, skills]) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function appendPrompt(opts: SessionOptions): string {
|
|
169
|
+
return promptParts(opts).append;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type McpEntry = { name: string; config: Record<string, unknown>; source: string; scope: "extension" };
|
|
173
|
+
|
|
174
|
+
/** 要挂的 MCP:个人 MCP + 记忆 / 定时任务 / 技能。工具都直接声明给模型(exposure: direct) */
|
|
175
|
+
export function mcpServers(opts: SessionOptions): McpEntry[] {
|
|
176
|
+
const out: McpEntry[] = [];
|
|
177
|
+
const add = (name: string, spec: object) => out.push({ name, config: { ...spec, exposure: "direct" }, source: "agent-loft", scope: "extension" });
|
|
178
|
+
for (const [name, spec] of Object.entries(userMcp(opts)?.mcp ?? {})) add(name, spec);
|
|
179
|
+
const memory = opts.memory;
|
|
180
|
+
if (memory) add(MEMORY_MCP_NAME, { type: "stdio", ...memoryMcpSpawn(memory.userId, "pi", { search: !!memory.search, ...(memory.convKey ? { convKey: memory.convKey } : {}) }) });
|
|
181
|
+
if (opts.tasks) {
|
|
182
|
+
add(TASKS_MCP_NAME, { type: "stdio", ...tasksMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "pi") });
|
|
183
|
+
add(SKILLS_MCP_NAME, { type: "stdio", ...skillsMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "pi") });
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** pi 的 usage 每条助手消息一份,是这次请求的量 */
|
|
189
|
+
function usageOf(u: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; reasoning?: number; cost?: { total?: number } } | undefined): TokenUsage | undefined {
|
|
190
|
+
if (!u) return undefined;
|
|
191
|
+
const usage: TokenUsage = { input: u.input || 0, cacheRead: u.cacheRead || 0, cacheWrite: u.cacheWrite || 0, output: u.output || 0 };
|
|
192
|
+
if (u.reasoning) usage.reasoning = u.reasoning;
|
|
193
|
+
if (u.cost?.total) usage.costUsd = u.cost.total;
|
|
194
|
+
return usage.input + usage.cacheRead + usage.cacheWrite + usage.output > 0 ? usage : undefined;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
type Assistant = { role: "assistant"; content: { type: string; text?: string; thinking?: string; redacted?: boolean }[]; stopReason?: string; errorMessage?: string; usage?: Parameters<typeof usageOf>[0] };
|
|
198
|
+
|
|
199
|
+
export class PiSession implements AgentSession {
|
|
200
|
+
private session: PiAgentSession | null = null;
|
|
201
|
+
private starting: Promise<PiAgentSession | null> | null = null;
|
|
202
|
+
private currentId: string | undefined;
|
|
203
|
+
/** 分叉已经生效:之后重建就接着新的这条 */
|
|
204
|
+
private forked = false;
|
|
205
|
+
private runtime: RuntimeInfo = {};
|
|
206
|
+
private disposed = false;
|
|
207
|
+
private turnBusy = false;
|
|
208
|
+
private pending: UserInput[] = [];
|
|
209
|
+
/** 「完全允许」或点过「本会话全部允许」 */
|
|
210
|
+
private allowAll = false;
|
|
211
|
+
private turn: Promise<void> | null = null;
|
|
212
|
+
private aborting = false;
|
|
213
|
+
/** 这一轮的 token 合计、最后一次报错 */
|
|
214
|
+
private turnTokens = 0;
|
|
215
|
+
private turnCost = 0;
|
|
216
|
+
private turnError: string | undefined;
|
|
217
|
+
|
|
218
|
+
constructor(
|
|
219
|
+
private readonly opts: SessionOptions,
|
|
220
|
+
private readonly events: AgentEvents,
|
|
221
|
+
private readonly host: InteractionHost,
|
|
222
|
+
) {
|
|
223
|
+
this.allowAll = opts.permission === "full";
|
|
224
|
+
if (opts.model) this.runtime.model = opts.model;
|
|
225
|
+
if (opts.effort) this.runtime.effort = opts.effort;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
get sessionId(): string | undefined {
|
|
229
|
+
return this.currentId;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private start(): Promise<PiAgentSession | null> {
|
|
233
|
+
if (this.session) return Promise.resolve(this.session);
|
|
234
|
+
if (this.disposed) return Promise.resolve(null);
|
|
235
|
+
this.starting ??= this.launch().finally(() => {
|
|
236
|
+
this.starting = null;
|
|
237
|
+
});
|
|
238
|
+
return this.starting;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private async launch(): Promise<PiAgentSession | null> {
|
|
242
|
+
const { pi } = await loadSdk();
|
|
243
|
+
const rt = await modelRuntime();
|
|
244
|
+
if (this.disposed) return null;
|
|
245
|
+
const cfg = config().agents.pi;
|
|
246
|
+
const model = await pickModel(this.opts.model || cfg.defaultModel || undefined);
|
|
247
|
+
if (!model) throw new Error(NO_PROVIDER);
|
|
248
|
+
const cwd = this.opts.cwd;
|
|
249
|
+
|
|
250
|
+
// 会话记录:新建 / 接着以前的 / 从以前的分叉一条新的
|
|
251
|
+
const fork = !!this.opts.fork && !this.forked;
|
|
252
|
+
const resume = fork ? this.opts.resumeId : (this.currentId ?? this.opts.resumeId);
|
|
253
|
+
let sessionManager;
|
|
254
|
+
if (resume) {
|
|
255
|
+
const file = sessionFile(resume);
|
|
256
|
+
if (!file) throw new Error(`找不到 pi 的会话记录 ${resume}`);
|
|
257
|
+
sessionManager = fork ? pi.SessionManager.forkFrom(file, cwd, SESSIONS_DIR) : pi.SessionManager.open(file, SESSIONS_DIR, cwd);
|
|
258
|
+
} else {
|
|
259
|
+
sessionManager = pi.SessionManager.create(cwd, SESSIONS_DIR);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// 设置全在内存里:不读机器上的 ~/.pi/agent/settings.json;项目里的 .pi/ 一律不信任(扩展会执行代码)
|
|
263
|
+
const settingsManager = pi.SettingsManager.inMemory({ defaultProjectTrust: "never" });
|
|
264
|
+
const expert = this.opts.expert;
|
|
265
|
+
// data/pi/skills 里的技能当「机器上的技能」:成员和自定义专家不给
|
|
266
|
+
const machine = !expert && (!this.opts.skills || (this.opts.skills.admin && this.opts.skills.machineSkills !== false));
|
|
267
|
+
const prompt = promptParts(this.opts);
|
|
268
|
+
const servers = mcpServers(this.opts);
|
|
269
|
+
const resourceLoader = new pi.DefaultResourceLoader({
|
|
270
|
+
cwd,
|
|
271
|
+
agentDir: AGENT_DIR,
|
|
272
|
+
settingsManager,
|
|
273
|
+
extensionFactories: [
|
|
274
|
+
{ name: "agent-loft-gate", factory: (api: ExtensionAPI) => {
|
|
275
|
+
api.on("tool_call", (e) => this.onToolCall(e.toolName, e.input as Record<string, unknown>));
|
|
276
|
+
} },
|
|
277
|
+
...(servers.length ? [{ name: "mcp", factory: pi.createMcpExtension({ loadConfig: () => ({ servers: servers as never, errors: [] }), logPath: path.join(AGENT_DIR, "mcp.log") }) }] : []),
|
|
278
|
+
],
|
|
279
|
+
noSkills: !machine,
|
|
280
|
+
noThemes: true,
|
|
281
|
+
// 只能联网的专家碰不了文件,项目里的 AGENTS.md / CLAUDE.md 也不读
|
|
282
|
+
...(expert?.access === "web" ? { noContextFiles: true } : {}),
|
|
283
|
+
...(prompt.system ? { systemPrompt: prompt.system } : {}),
|
|
284
|
+
...(prompt.append ? { appendSystemPrompt: [prompt.append] } : {}),
|
|
285
|
+
});
|
|
286
|
+
await resourceLoader.reload();
|
|
287
|
+
|
|
288
|
+
const env = this.opts.skills?.env ?? {};
|
|
289
|
+
const customTools: ToolDefinition[] = [this.askTool(), this.planTool()] as unknown as ToolDefinition[];
|
|
290
|
+
// 技能声明的环境变量交给 bash(pi 进程内运行,不能改 process.env)
|
|
291
|
+
if (Object.keys(env).length && (!expert || expert.access === "exec")) customTools.push(pi.createBashToolDefinition(cwd, { spawnHook: (c) => ({ ...c, env: { ...c.env, ...env } }) }) as unknown as ToolDefinition);
|
|
292
|
+
|
|
293
|
+
const thinking = this.opts.effort || cfg.defaultEffort || undefined;
|
|
294
|
+
const { session } = await pi.createAgentSession({
|
|
295
|
+
cwd,
|
|
296
|
+
agentDir: AGENT_DIR,
|
|
297
|
+
modelRuntime: rt,
|
|
298
|
+
model,
|
|
299
|
+
...(thinking ? { thinkingLevel: thinking as never } : {}),
|
|
300
|
+
settingsManager,
|
|
301
|
+
resourceLoader,
|
|
302
|
+
sessionManager,
|
|
303
|
+
tools: toolsFor(expert?.access),
|
|
304
|
+
customTools,
|
|
305
|
+
});
|
|
306
|
+
if (this.disposed) {
|
|
307
|
+
session.dispose();
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
// 发出 session_start:MCP 扩展这时才开始连
|
|
311
|
+
await session.bindExtensions({});
|
|
312
|
+
session.subscribe((e) => this.handle(e));
|
|
313
|
+
this.syncPlanTool(session);
|
|
314
|
+
if (fork) this.forked = true;
|
|
315
|
+
this.session = session;
|
|
316
|
+
this.runtime = { model: modelKey(model), ...(session.supportsThinking() ? { effort: session.thinkingLevel } : {}) };
|
|
317
|
+
return session;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---------- 自定义工具:提问、交方案 ----------
|
|
321
|
+
|
|
322
|
+
private askTool(): object {
|
|
323
|
+
return {
|
|
324
|
+
name: ASK_TOOL,
|
|
325
|
+
label: "Ask user",
|
|
326
|
+
description:
|
|
327
|
+
"Ask the user one or more multiple-choice questions when a decision is genuinely theirs to make. Each question has 2-4 options; the user can also answer in free text. Returns the user's answers.",
|
|
328
|
+
parameters: {
|
|
329
|
+
type: "object",
|
|
330
|
+
properties: {
|
|
331
|
+
questions: {
|
|
332
|
+
type: "array",
|
|
333
|
+
minItems: 1,
|
|
334
|
+
maxItems: 4,
|
|
335
|
+
items: {
|
|
336
|
+
type: "object",
|
|
337
|
+
properties: {
|
|
338
|
+
question: { type: "string", description: "The full question" },
|
|
339
|
+
header: { type: "string", description: "Very short label (max 12 chars)" },
|
|
340
|
+
options: {
|
|
341
|
+
type: "array",
|
|
342
|
+
minItems: 2,
|
|
343
|
+
maxItems: 4,
|
|
344
|
+
items: { type: "object", properties: { label: { type: "string" }, description: { type: "string" } }, required: ["label"] },
|
|
345
|
+
},
|
|
346
|
+
multiSelect: { type: "boolean" },
|
|
347
|
+
},
|
|
348
|
+
required: ["question", "options"],
|
|
349
|
+
},
|
|
350
|
+
},
|
|
351
|
+
},
|
|
352
|
+
required: ["questions"],
|
|
353
|
+
},
|
|
354
|
+
execute: async (_id: string, params: Record<string, unknown>) => {
|
|
355
|
+
const questions = parseQuestions(params);
|
|
356
|
+
if (!questions) return text("问题格式不对:每个问题要有 question 和至少两个带 label 的 options。");
|
|
357
|
+
const outcome = await this.host({ kind: "question", title: "pi 想确认一下", questions });
|
|
358
|
+
const lines = Object.entries(outcome.answers).map(([q, picked]) => `- ${q}:${picked.join("、")}`);
|
|
359
|
+
if (lines.length) return text(`用户的回答:\n${lines.join("\n")}`);
|
|
360
|
+
return text("用户没有作答(超时或主动跳过)。不要重复提同样的问题:按你认为合理的默认继续,并在回复里说明你替他选了什么。");
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
private planTool(): object {
|
|
366
|
+
return {
|
|
367
|
+
name: PLAN_TOOL,
|
|
368
|
+
label: "Exit plan mode",
|
|
369
|
+
description: "Plan mode only: submit your complete plan (markdown) to the user for approval. Only after approval may you edit files or run commands.",
|
|
370
|
+
parameters: { type: "object", properties: { plan: { type: "string", description: "The complete plan in markdown" } }, required: ["plan"] },
|
|
371
|
+
execute: async (_id: string, params: Record<string, unknown>) => {
|
|
372
|
+
if (!this.opts.plan) return text("现在不在计划模式,直接动手就行。");
|
|
373
|
+
const plan = typeof params.plan === "string" && params.plan.trim() ? params.plan : "(pi 没有附上方案正文)";
|
|
374
|
+
const outcome = await this.host({ kind: "approval", title: "方案出好了,按这个开始做?", detail: plan, allowLabel: "开始执行", denyLabel: "继续改方案" });
|
|
375
|
+
if (outcome.settlement === "allow-once" || outcome.settlement === "allow-always") {
|
|
376
|
+
this.syncPlan(false);
|
|
377
|
+
return text("用户批准了这个方案。计划模式已关闭,现在按方案动手。");
|
|
378
|
+
}
|
|
379
|
+
return text(
|
|
380
|
+
outcome.settlement === "timeout"
|
|
381
|
+
? "用户长时间没有回应这个方案(已超时)。留在计划模式,不要动手,等用户回来。"
|
|
382
|
+
: outcome.settlement === "cancelled"
|
|
383
|
+
? "方案确认已被取消(用户中断了这一轮或切换了会话)。留在计划模式,不要动手。"
|
|
384
|
+
: "用户还不想按这个方案做。留在计划模式,不要动手;简短问一句要改哪里,等用户说明。",
|
|
385
|
+
);
|
|
386
|
+
},
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** 交方案的工具只在计划模式下给模型看 */
|
|
391
|
+
private syncPlanTool(session: PiAgentSession): void {
|
|
392
|
+
const active = session.getActiveToolNames().filter((n) => n !== PLAN_TOOL);
|
|
393
|
+
session.setActiveToolsByName(this.opts.plan ? [...active, PLAN_TOOL] : active);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private syncPlan(on: boolean): void {
|
|
397
|
+
if (!!this.opts.plan === on) return;
|
|
398
|
+
this.opts.plan = on;
|
|
399
|
+
if (this.session) this.syncPlanTool(this.session);
|
|
400
|
+
this.events.onPlanMode?.(on);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// ---------- 授权 ----------
|
|
404
|
+
|
|
405
|
+
private async onToolCall(toolName: string, input: Record<string, unknown>): Promise<ToolCallEventResult | undefined> {
|
|
406
|
+
const gate = gateOf(toolName, input, {
|
|
407
|
+
level: this.opts.permission,
|
|
408
|
+
plan: !!this.opts.plan,
|
|
409
|
+
cwd: this.opts.cwd,
|
|
410
|
+
uploadsDir: this.opts.uploadsDir,
|
|
411
|
+
mcp: userMcp(this.opts),
|
|
412
|
+
agentLoftMcp: !!(this.opts.memory || this.opts.tasks),
|
|
413
|
+
});
|
|
414
|
+
if ("allow" in gate) return gate.allow ? undefined : { block: true, reason: gate.reason };
|
|
415
|
+
if (gate.sessionable && this.allowAll) return undefined;
|
|
416
|
+
const outcome = await this.host({
|
|
417
|
+
kind: "approval",
|
|
418
|
+
title: `需要授权:${toolName}`,
|
|
419
|
+
detail: describePiTool(toolName, input),
|
|
420
|
+
...(gate.sessionable && !this.opts.noSessionGrant ? { allowSession: true } : {}),
|
|
421
|
+
});
|
|
422
|
+
if (outcome.settlement === "allow-session") {
|
|
423
|
+
if (!this.allowAll) this.events.onStep("warning", "🔓 本会话内后续操作不再询问(/new 或切换会话后恢复逐条确认)");
|
|
424
|
+
this.allowAll = true;
|
|
425
|
+
}
|
|
426
|
+
if (outcome.settlement === "allow-once" || outcome.settlement === "allow-always" || outcome.settlement === "allow-session") return undefined;
|
|
427
|
+
const reason =
|
|
428
|
+
outcome.settlement === "timeout"
|
|
429
|
+
? "用户长时间没有响应授权请求(已超时),按拒绝处理"
|
|
430
|
+
: outcome.settlement === "cancelled"
|
|
431
|
+
? "授权请求已被取消(用户中断了这一轮或切换了会话)"
|
|
432
|
+
: "用户拒绝了此操作";
|
|
433
|
+
return { block: true, reason };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// ---------- 事件 ----------
|
|
437
|
+
|
|
438
|
+
private handle(e: AgentSessionEvent): void {
|
|
439
|
+
if (this.disposed) return;
|
|
440
|
+
switch (e.type) {
|
|
441
|
+
case "message_update": {
|
|
442
|
+
const ev = e.assistantMessageEvent;
|
|
443
|
+
if (ev.type === "text_delta" && ev.delta) this.events.onTextDelta(ev.delta);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
case "message_end": {
|
|
447
|
+
const m = e.message as unknown as Assistant;
|
|
448
|
+
if (m.role !== "assistant") return;
|
|
449
|
+
for (const block of m.content ?? []) {
|
|
450
|
+
if (block.type === "thinking" && !block.redacted) {
|
|
451
|
+
const thought = summarize(block.thinking ?? "");
|
|
452
|
+
if (thought) this.events.onStep("thinking", `💭 ${thought}`);
|
|
453
|
+
} else if (block.type === "text" && block.text?.trim()) {
|
|
454
|
+
this.events.onText(block.text);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
const usage = usageOf(m.usage);
|
|
458
|
+
if (usage) {
|
|
459
|
+
this.turnTokens += usage.input + usage.cacheRead + usage.cacheWrite + usage.output;
|
|
460
|
+
this.turnCost += usage.costUsd ?? 0;
|
|
461
|
+
this.events.onUsage?.(usage, false);
|
|
462
|
+
}
|
|
463
|
+
if (m.stopReason === "error") this.turnError = m.errorMessage || "模型请求失败";
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
case "tool_execution_start": {
|
|
467
|
+
if (e.toolName === ASK_TOOL || e.toolName === PLAN_TOOL) return;
|
|
468
|
+
this.events.onStep("tool", `${e.parentToolCallId ? " ↳ " : ""}🔧 ${describePiStep(e.toolName, e.args)}`);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
case "auto_retry_start":
|
|
472
|
+
this.events.onStep("warning", `⚠️ 请求失败,${Math.round(e.delayMs / 1000)} 秒后重试(第 ${e.attempt}/${e.maxAttempts} 次):${summarize(e.errorMessage, 80)}`);
|
|
473
|
+
return;
|
|
474
|
+
case "auto_retry_end":
|
|
475
|
+
if (e.success) this.turnError = undefined;
|
|
476
|
+
return;
|
|
477
|
+
case "compaction_start":
|
|
478
|
+
this.events.onStep("note", "🗜️ 上下文快满了,正在压缩");
|
|
479
|
+
return;
|
|
480
|
+
case "thinking_level_changed":
|
|
481
|
+
this.runtime = { ...this.runtime, effort: e.level };
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** 跑一轮:prompt() 返回时这一轮(含自动重试)就结束了 */
|
|
487
|
+
private async runTurn(input: UserInput): Promise<void> {
|
|
488
|
+
const started = Date.now();
|
|
489
|
+
this.turnTokens = 0;
|
|
490
|
+
this.turnCost = 0;
|
|
491
|
+
this.turnError = undefined;
|
|
492
|
+
this.aborting = false;
|
|
493
|
+
let session: PiAgentSession | null = null;
|
|
494
|
+
try {
|
|
495
|
+
session = await this.start();
|
|
496
|
+
if (!session) return;
|
|
497
|
+
this.events.onTurnStart?.();
|
|
498
|
+
const raw = input.text.trim();
|
|
499
|
+
if (raw === "/compact" || raw.startsWith("/compact ")) {
|
|
500
|
+
await this.compact(session, raw.slice("/compact".length).trim());
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
const images = (session.model?.input ?? []).includes("image");
|
|
504
|
+
const prompt = buildPrompt(input, images, !!this.opts.plan, this.opts.expert?.access === "web");
|
|
505
|
+
await session.prompt(prompt.text, { ...(prompt.images.length ? { images: prompt.images } : {}), expandPromptTemplates: false });
|
|
506
|
+
if (this.disposed) return;
|
|
507
|
+
this.reportIds(session, input);
|
|
508
|
+
const usage = session.getContextUsage();
|
|
509
|
+
if (usage && usage.tokens !== null) this.events.onContext?.({ used: usage.tokens, window: usage.contextWindow, percent: Math.round(usage.percent ?? (usage.tokens / usage.contextWindow) * 100) });
|
|
510
|
+
const text = session.getLastAssistantText() ?? "";
|
|
511
|
+
const anchor = lastEntryId(session, "assistant");
|
|
512
|
+
if (this.aborting) {
|
|
513
|
+
this.events.onResult({ text: text || "(已中断)", durationMs: Date.now() - started, ...(anchor ? { anchor } : {}) });
|
|
514
|
+
} else if (this.turnError) {
|
|
515
|
+
this.events.onError(new Error(this.turnError));
|
|
516
|
+
} else {
|
|
517
|
+
this.events.onResult({
|
|
518
|
+
text,
|
|
519
|
+
durationMs: Date.now() - started,
|
|
520
|
+
...(this.turnTokens ? { tokens: this.turnTokens } : {}),
|
|
521
|
+
...(this.turnCost ? { costUsd: this.turnCost } : {}),
|
|
522
|
+
...(anchor ? { anchor } : {}),
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
} catch (err) {
|
|
526
|
+
if (this.disposed) return;
|
|
527
|
+
if (this.aborting) {
|
|
528
|
+
// 用户消息已经落盘了:id 照样报,下次接着这条会话
|
|
529
|
+
if (session) this.reportIds(session, input);
|
|
530
|
+
this.events.onResult({ text: "(已中断)", durationMs: Date.now() - started });
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
// 会话对象坏了(模型没了、记录读不出来……):扔掉,下一轮重建
|
|
534
|
+
if (session) this.drop(session);
|
|
535
|
+
this.events.onError(err);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private async compact(session: PiAgentSession, instructions: string): Promise<void> {
|
|
540
|
+
const started = Date.now();
|
|
541
|
+
const before = session.getContextUsage();
|
|
542
|
+
await session.compact(instructions || undefined);
|
|
543
|
+
const after = session.getContextUsage();
|
|
544
|
+
const fmt = (n: number | null | undefined) => (n == null ? "?" : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));
|
|
545
|
+
this.reportIds(session);
|
|
546
|
+
this.events.onResult({ text: `上下文已压缩(${fmt(before?.tokens)} → ${fmt(after?.tokens)} tokens)`, durationMs: Date.now() - started });
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
private reportIds(session: PiAgentSession, input?: UserInput): void {
|
|
550
|
+
if (session.sessionId !== this.currentId) {
|
|
551
|
+
this.currentId = session.sessionId;
|
|
552
|
+
this.events.onSessionId(session.sessionId);
|
|
553
|
+
}
|
|
554
|
+
if (input) {
|
|
555
|
+
const user = lastEntryId(session, "user");
|
|
556
|
+
if (user) this.events.onUserAnchor?.(input, user);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
private drop(session: PiAgentSession): void {
|
|
561
|
+
if (this.session !== session) return;
|
|
562
|
+
this.session = null;
|
|
563
|
+
try {
|
|
564
|
+
session.dispose();
|
|
565
|
+
} catch {
|
|
566
|
+
// 已经关了
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// ---------- 对外 ----------
|
|
571
|
+
|
|
572
|
+
send(input: UserInput): void {
|
|
573
|
+
if (this.disposed) return;
|
|
574
|
+
if (this.turnBusy) {
|
|
575
|
+
this.pending.push(input);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
this.deliver(input);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
cancelQueued(input: UserInput): boolean {
|
|
582
|
+
const index = this.pending.indexOf(input);
|
|
583
|
+
if (index < 0) return false;
|
|
584
|
+
this.pending.splice(index, 1);
|
|
585
|
+
return true;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
private deliver(input: UserInput): void {
|
|
589
|
+
this.turnBusy = true;
|
|
590
|
+
this.turn = this.runTurn(input).finally(() => {
|
|
591
|
+
this.turn = null;
|
|
592
|
+
this.turnBusy = false;
|
|
593
|
+
const next = this.pending.shift();
|
|
594
|
+
if (next && !this.disposed) this.deliver(next);
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async listModels(): Promise<ModelInfo[]> {
|
|
599
|
+
return availableModels();
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
async setPermission(level: PermissionLevel | undefined): Promise<void> {
|
|
603
|
+
this.opts.permission = level;
|
|
604
|
+
this.allowAll = level === "full";
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
async setPlan(on: boolean): Promise<void> {
|
|
608
|
+
this.opts.plan = on;
|
|
609
|
+
if (this.session) this.syncPlanTool(this.session);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async setModel(model?: string, effort?: string): Promise<void> {
|
|
613
|
+
if (model !== undefined && model) {
|
|
614
|
+
const m = await findModel(model);
|
|
615
|
+
if (!m) throw new Error(`pi 里没有这个模型:${model}`);
|
|
616
|
+
this.opts.model = model;
|
|
617
|
+
this.runtime = { ...this.runtime, model };
|
|
618
|
+
if (this.session) await this.session.setModel(m);
|
|
619
|
+
}
|
|
620
|
+
if (effort !== undefined && effort) {
|
|
621
|
+
this.opts.effort = effort;
|
|
622
|
+
this.runtime = { ...this.runtime, effort };
|
|
623
|
+
this.session?.setThinkingLevel(effort as never);
|
|
624
|
+
if (this.session) this.runtime.effort = this.session.thinkingLevel;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
peekRuntime(): RuntimeInfo {
|
|
629
|
+
return this.runtime;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
async describeRuntime(): Promise<RuntimeInfo> {
|
|
633
|
+
const s = this.session;
|
|
634
|
+
if (!s?.model) return this.runtime;
|
|
635
|
+
return { model: modelKey(s.model), ...(s.supportsThinking() ? { effort: s.thinkingLevel } : {}) };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async interrupt(opts: InterruptOptions = {}): Promise<void> {
|
|
639
|
+
if (opts.keepQueue) {
|
|
640
|
+
const i = opts.first ? this.pending.indexOf(opts.first) : -1;
|
|
641
|
+
if (i > 0) this.pending.unshift(...this.pending.splice(i, 1));
|
|
642
|
+
} else {
|
|
643
|
+
const dropped = this.pending.length;
|
|
644
|
+
this.pending = [];
|
|
645
|
+
if (dropped > 0) this.events.onDropped?.(dropped);
|
|
646
|
+
}
|
|
647
|
+
if (!this.session || !this.turnBusy) return;
|
|
648
|
+
this.aborting = true;
|
|
649
|
+
try {
|
|
650
|
+
if (this.session.isCompacting) this.session.abortCompaction();
|
|
651
|
+
await this.session.abort();
|
|
652
|
+
} catch (err) {
|
|
653
|
+
console.warn("[pi] 中断失败:", err instanceof Error ? err.message : err);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async dispose(): Promise<void> {
|
|
658
|
+
this.disposed = true;
|
|
659
|
+
this.pending = [];
|
|
660
|
+
const session = this.session ?? (await this.starting?.catch(() => null)) ?? null;
|
|
661
|
+
if (session) {
|
|
662
|
+
if (this.turnBusy) await session.abort().catch(() => {});
|
|
663
|
+
this.drop(session);
|
|
664
|
+
}
|
|
665
|
+
await this.turn?.catch(() => {});
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function text(t: string) {
|
|
670
|
+
return { content: [{ type: "text" as const, text: t }], details: undefined };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** 当前分支上最后一条 user / assistant 消息的记录 id:用户消息用来回退,助手消息用来分叉 */
|
|
674
|
+
function lastEntryId(session: PiAgentSession, role: "user" | "assistant"): string | undefined {
|
|
675
|
+
const branch = session.sessionManager.getBranch();
|
|
676
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
677
|
+
const e = branch[i]!;
|
|
678
|
+
if (e.type === "message" && (e as { message?: { role?: string } }).message?.role === role) return e.id;
|
|
679
|
+
}
|
|
680
|
+
return undefined;
|
|
681
|
+
}
|