@evandu/super-pi 0.1.244 → 0.1.246
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/agents/code-auditor.md +6 -0
- package/agents/code-designer.md +6 -0
- package/agents/document-organizer.md +6 -0
- package/agents/solution-designer.md +6 -0
- package/agents/super-pi-native-tools/index.ts +1 -0
- package/agents/super-pi-task/index.ts +7 -58
- package/agents/super-pi-task/workflow-schema.ts +34 -0
- package/dist/client/.super-pi-client-sources.json +11 -8
- package/dist/client/assets/{CodeMirrorEditor-B1T8wU12.js → CodeMirrorEditor-B3K0I0eS.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-LCXbSvsh.js → GitDiffEditor-DYmMQWS8.js} +1 -1
- package/dist/client/assets/{index-DltiyYgr.css → index-DGpbsE3E.css} +1 -1
- package/dist/client/assets/index-Dx58PQcK.js +347 -0
- package/dist/client/index.html +2 -2
- package/dist/server/agents.js +4 -2
- package/dist/server/application/conversation-service.js +6 -1
- package/dist/server/application/group-chat-service.js +11 -2
- package/dist/server/application/workspace-service.js +15 -5
- package/dist/server/conversation-usage.d.ts +4 -1
- package/dist/server/conversation-usage.js +6 -3
- package/dist/server/http-server.d.ts +3 -1
- package/dist/server/http-server.js +99 -1
- package/dist/server/index.js +10 -2
- package/dist/server/native-tool-settings.d.ts +25 -0
- package/dist/server/native-tool-settings.js +41 -0
- package/dist/server/native-tools-extension.d.ts +2 -0
- package/dist/server/native-tools-extension.js +39 -0
- package/dist/server/native-tools-service.d.ts +39 -0
- package/dist/server/native-tools-service.js +240 -0
- package/dist/server/pi-native.d.ts +12 -0
- package/dist/server/pi-native.js +16 -0
- package/dist/server/pi-session-pool.d.ts +1 -0
- package/dist/server/pi-session-pool.js +14 -4
- package/dist/server/pi-session.d.ts +32 -1
- package/dist/server/pi-session.js +19 -4
- package/dist/server/runtime.d.ts +18 -0
- package/dist/server/runtime.js +167 -60
- package/dist/server/session-repository.d.ts +1 -0
- package/dist/server/session-repository.js +2 -1
- package/dist/server/store.d.ts +1 -0
- package/dist/server/store.js +10 -2
- package/dist/server/subagents.js +9 -22
- package/dist/server/thinking-level-discovery.js +25 -1
- package/dist/server/types.d.ts +2 -0
- package/dist/shared/group-chat.d.ts +3 -0
- package/dist/shared/group-chat.js +5 -0
- package/dist/shared/native-tools.d.ts +43 -0
- package/dist/shared/native-tools.js +1 -0
- package/dist/shared/pi-cache-warming.d.ts +9 -0
- package/dist/shared/pi-cache-warming.js +4 -0
- package/package.json +4 -2
- package/dist/client/assets/index-DDrbcKk9.js +0 -347
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, mkdir, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { defaultAgentDir } from "./pi-session.js";
|
|
5
|
+
import { piNative, mcpCredentials } from "./pi-native.js";
|
|
6
|
+
import { readNativeToolSettings } from "./native-tool-settings.js";
|
|
7
|
+
const exposures = ["deferred", "direct", "codemode", "hidden"];
|
|
8
|
+
export class NativeToolsError extends Error {
|
|
9
|
+
}
|
|
10
|
+
/** Web management reuses Pi's validated configuration, native connection and OAuth implementation. */
|
|
11
|
+
export class NativeToolsService {
|
|
12
|
+
dataDir;
|
|
13
|
+
changed;
|
|
14
|
+
agentDir;
|
|
15
|
+
configPath;
|
|
16
|
+
settingsPath;
|
|
17
|
+
logins = new Map();
|
|
18
|
+
connections = new Set();
|
|
19
|
+
jobs = new Set();
|
|
20
|
+
diagnostics;
|
|
21
|
+
generation = 0;
|
|
22
|
+
closed = false;
|
|
23
|
+
configurationWarning;
|
|
24
|
+
track(job) { this.jobs.add(job); void job.finally(() => this.jobs.delete(job)).catch(() => undefined); }
|
|
25
|
+
invalidate() { this.generation++; this.diagnostics = undefined; this.changed(); }
|
|
26
|
+
constructor(dataDir, changed, agentDir = defaultAgentDir()) {
|
|
27
|
+
this.dataDir = dataDir;
|
|
28
|
+
this.changed = changed;
|
|
29
|
+
this.agentDir = agentDir;
|
|
30
|
+
this.configPath = join(agentDir, "mcp.json");
|
|
31
|
+
this.settingsPath = join(dataDir, "native-tools.json");
|
|
32
|
+
}
|
|
33
|
+
async entries() {
|
|
34
|
+
const api = await piNative();
|
|
35
|
+
const loaded = api.config.loadMcpConfig({ agentDir: this.agentDir, cwd: this.agentDir, projectTrusted: false });
|
|
36
|
+
this.configurationWarning = loaded.errors.length ? "部分 MCP 配置无法读取,请检查 Pi 配置目录中的 mcp.json。有效服务仍可管理。" : undefined;
|
|
37
|
+
return loaded.servers;
|
|
38
|
+
}
|
|
39
|
+
async snapshot() {
|
|
40
|
+
const api = await piNative();
|
|
41
|
+
const credentials = mcpCredentials(api, this.agentDir);
|
|
42
|
+
const entries = await this.entries();
|
|
43
|
+
return { settings: readNativeToolSettings(this.settingsPath), configurationWarning: this.configurationWarning,
|
|
44
|
+
servers: entries.map(entry => ({ name: entry.name, transport: entry.config.url ? "http" : "stdio",
|
|
45
|
+
enabled: entry.config.enabled !== false, exposure: entry.config.exposure ?? "codemode", description: entry.config.description,
|
|
46
|
+
hasCredentials: Boolean(entry.config.env && Object.keys(entry.config.env).length || entry.config.headers && Object.keys(entry.config.headers).length
|
|
47
|
+
|| entry.config.oauth?.clientSecret || entry.config.auth || entry.config.url && credentials.tokens(entry.name, entry.config.url)),
|
|
48
|
+
authenticated: Boolean(entry.config.url && credentials.tokens(entry.name, entry.config.url)),
|
|
49
|
+
supportsLogin: Boolean(entry.config.url && !entry.config.auth && !Object.keys(entry.config.headers ?? {}).some(key => key.toLowerCase() === "authorization")) })),
|
|
50
|
+
logins: [...this.logins.values()].map(item => ({ ...item.public })),
|
|
51
|
+
...(this.diagnostics ? { diagnostics: structuredClone(this.diagnostics) } : {}) };
|
|
52
|
+
}
|
|
53
|
+
async entry(name) {
|
|
54
|
+
if (typeof name !== "string")
|
|
55
|
+
throw new NativeToolsError("请选择 MCP 服务。");
|
|
56
|
+
const entry = (await this.entries()).find(item => item.name === name);
|
|
57
|
+
if (!entry)
|
|
58
|
+
throw new NativeToolsError("MCP 服务不存在。");
|
|
59
|
+
return entry;
|
|
60
|
+
}
|
|
61
|
+
async settings(value) {
|
|
62
|
+
if (!value || typeof value !== "object" || Object.keys(value).some(key => !["mcp", "toolSearch", "codemode"].includes(key))
|
|
63
|
+
|| Object.values(value).some(item => typeof item !== "boolean"))
|
|
64
|
+
throw new NativeToolsError("工具开关格式不正确。");
|
|
65
|
+
const next = { ...readNativeToolSettings(this.settingsPath), ...value };
|
|
66
|
+
await mkdir(this.dataDir, { recursive: true });
|
|
67
|
+
const temporary = `${this.settingsPath}.${randomUUID()}.tmp`;
|
|
68
|
+
await writeFile(temporary, JSON.stringify(next, null, 2), { mode: 0o600 });
|
|
69
|
+
await rename(temporary, this.settingsPath);
|
|
70
|
+
this.changed();
|
|
71
|
+
}
|
|
72
|
+
async save(name, config) {
|
|
73
|
+
const api = await piNative();
|
|
74
|
+
if (typeof name !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/.test(name))
|
|
75
|
+
throw new NativeToolsError("服务名请使用字母、数字、点、短横线或下划线。");
|
|
76
|
+
const validated = api.core.validateMcpServerConfig(name, config);
|
|
77
|
+
if (typeof validated === "string")
|
|
78
|
+
throw new NativeToolsError("MCP 配置格式不正确,请检查 command / args 或 url,以及 env、headers 和 exposure。");
|
|
79
|
+
await mkdir(this.agentDir, { recursive: true, mode: 0o700 });
|
|
80
|
+
this.cancelName(name);
|
|
81
|
+
try {
|
|
82
|
+
api.config.addMcpServerConfig(this.configPath, name, validated);
|
|
83
|
+
await chmod(this.configPath, 0o600);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
throw new NativeToolsError("MCP 配置保存失败,请检查服务端目录权限。");
|
|
87
|
+
}
|
|
88
|
+
this.invalidate();
|
|
89
|
+
}
|
|
90
|
+
async patch(name, patch) {
|
|
91
|
+
const entry = await this.entry(name);
|
|
92
|
+
if (patch.enabled !== undefined && typeof patch.enabled !== "boolean" || patch.exposure !== undefined && !exposures.includes(String(patch.exposure)))
|
|
93
|
+
throw new NativeToolsError("服务设置格式不正确。");
|
|
94
|
+
const api = await piNative();
|
|
95
|
+
api.config.updateMcpServerConfig(this.configPath, entry.name, patch);
|
|
96
|
+
this.cancelName(entry.name);
|
|
97
|
+
this.invalidate();
|
|
98
|
+
}
|
|
99
|
+
async remove(name) {
|
|
100
|
+
const entry = await this.entry(name);
|
|
101
|
+
this.cancelName(entry.name);
|
|
102
|
+
const api = await piNative();
|
|
103
|
+
api.config.removeMcpServerConfig(this.configPath, entry.name);
|
|
104
|
+
this.invalidate();
|
|
105
|
+
}
|
|
106
|
+
cancelName(name) {
|
|
107
|
+
for (const login of this.logins.values())
|
|
108
|
+
if (login.public.name === name && ["starting", "authorizing"].includes(login.public.state)) {
|
|
109
|
+
login.public.state = "cancelled";
|
|
110
|
+
login.abort.abort();
|
|
111
|
+
login.redirect?.();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async connection(entry, cwd) {
|
|
115
|
+
const api = await piNative();
|
|
116
|
+
if (this.closed)
|
|
117
|
+
throw new NativeToolsError("服务已停止。");
|
|
118
|
+
let modelRuntime;
|
|
119
|
+
const connection = new api.runtime.McpServerConnection({ entry: { ...entry, config: { ...entry.config, timeout: Math.min(entry.config.timeout ?? 15, 15) } }, cwd,
|
|
120
|
+
createTransport: api.runtime.createDefaultTransport, credentials: mcpCredentials(api, this.agentDir), onTools() { },
|
|
121
|
+
providerToken: async (provider) => {
|
|
122
|
+
modelRuntime ??= api.sdk.ModelRuntime.create({ authPath: join(this.agentDir, "auth.json"), modelsPath: join(this.agentDir, "models.json") });
|
|
123
|
+
return (await (await modelRuntime).getAuth(provider))?.auth?.apiKey;
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
this.connections.add(connection);
|
|
127
|
+
return connection;
|
|
128
|
+
}
|
|
129
|
+
async diagnose(cwd) {
|
|
130
|
+
if (this.diagnostics?.running)
|
|
131
|
+
return;
|
|
132
|
+
const entries = await this.entries();
|
|
133
|
+
const generation = ++this.generation;
|
|
134
|
+
const report = this.diagnostics = { running: true, total: entries.length, servers: [] };
|
|
135
|
+
this.track((async () => {
|
|
136
|
+
for (let i = 0; i < entries.length && generation === this.generation && !this.closed; i += 4)
|
|
137
|
+
await Promise.all(entries.slice(i, i + 4).map(async (entry) => {
|
|
138
|
+
if (entry.config.enabled === false) {
|
|
139
|
+
report.servers.push({ name: entry.name, scope: entry.scope, state: "disabled", tools: [] });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const connection = await this.connection(entry, cwd);
|
|
143
|
+
try {
|
|
144
|
+
await connection.getClient().catch(() => undefined);
|
|
145
|
+
report.servers.push({ name: entry.name, scope: entry.scope, state: connection.state,
|
|
146
|
+
tools: connection.tools.map((tool) => tool.name),
|
|
147
|
+
...(connection.error ? { error: connection.state === "needs-auth" ? "需要登录授权。" : "连接失败,请检查地址、命令与服务端日志。" } : {}) });
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
await connection.close();
|
|
151
|
+
this.connections.delete(connection);
|
|
152
|
+
}
|
|
153
|
+
}));
|
|
154
|
+
})().catch(() => { report.error = "连接测试失败,请检查服务配置。"; }).finally(() => { report.running = false; }));
|
|
155
|
+
}
|
|
156
|
+
async login(name, cwd) {
|
|
157
|
+
const entry = await this.entry(name);
|
|
158
|
+
if (!entry.config.url || entry.config.auth || Object.keys(entry.config.headers ?? {}).some(key => key.toLowerCase() === "authorization"))
|
|
159
|
+
throw new NativeToolsError("这个服务使用命令或预设凭据,无需 MCP 网页登录。");
|
|
160
|
+
this.cancelName(entry.name);
|
|
161
|
+
if (this.logins.size >= 20)
|
|
162
|
+
for (const [id, job] of this.logins)
|
|
163
|
+
if (!["starting", "authorizing"].includes(job.public.state)) {
|
|
164
|
+
this.logins.delete(id);
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
const job = { public: { id: randomUUID(), name: entry.name, state: "starting" }, abort: new AbortController() };
|
|
168
|
+
this.logins.set(job.public.id, job);
|
|
169
|
+
const timer = setTimeout(() => job.abort.abort(), 10 * 60_000).unref();
|
|
170
|
+
this.track((async () => {
|
|
171
|
+
const api = await piNative();
|
|
172
|
+
const connection = await this.connection(entry, cwd);
|
|
173
|
+
const abort = () => { void connection.close(); };
|
|
174
|
+
job.abort.signal.addEventListener("abort", abort, { once: true });
|
|
175
|
+
if (job.abort.signal.aborted)
|
|
176
|
+
abort();
|
|
177
|
+
let settings, challenge, state;
|
|
178
|
+
try {
|
|
179
|
+
await connection.getClient().catch(() => undefined);
|
|
180
|
+
settings = connection.oauthSettings();
|
|
181
|
+
challenge = connection.challenge;
|
|
182
|
+
state = connection.state;
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
job.abort.signal.removeEventListener("abort", abort);
|
|
186
|
+
await connection.close();
|
|
187
|
+
this.connections.delete(connection);
|
|
188
|
+
}
|
|
189
|
+
job.abort.signal.throwIfAborted();
|
|
190
|
+
if (state === "connected") {
|
|
191
|
+
job.public.state = "completed";
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (state !== "needs-auth")
|
|
195
|
+
throw new NativeToolsError("服务连接失败。");
|
|
196
|
+
await api.oauth.signInMcpServer({ serverUrl: entry.config.url, store: mcpCredentials(api, this.agentDir).forServer(entry.name, entry.config.url), settings, challenge,
|
|
197
|
+
signal: job.abort.signal, prompt: {
|
|
198
|
+
showAuthorizationUrl(url) { if (!["http:", "https:"].includes(url.protocol))
|
|
199
|
+
throw new NativeToolsError("Invalid authorization URL"); job.public.url = url.href; job.public.state = "authorizing"; },
|
|
200
|
+
promptForRedirectUrl: (signal) => new Promise(resolve => {
|
|
201
|
+
job.redirect = resolve;
|
|
202
|
+
signal.addEventListener("abort", () => resolve(undefined), { once: true });
|
|
203
|
+
if (signal.aborted)
|
|
204
|
+
resolve(undefined);
|
|
205
|
+
}),
|
|
206
|
+
} });
|
|
207
|
+
job.abort.signal.throwIfAborted();
|
|
208
|
+
const verification = await this.connection(entry, cwd);
|
|
209
|
+
try {
|
|
210
|
+
await verification.getClient();
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
await verification.close();
|
|
214
|
+
this.connections.delete(verification);
|
|
215
|
+
}
|
|
216
|
+
job.abort.signal.throwIfAborted();
|
|
217
|
+
job.public.state = "completed";
|
|
218
|
+
delete job.public.url;
|
|
219
|
+
this.changed();
|
|
220
|
+
})().catch(() => { job.public.state = job.abort.signal.aborted ? "cancelled" : "failed"; job.public.error = job.abort.signal.aborted ? "登录已取消或过期。" : "登录未完成,请核对服务的授权设置后重试。"; })
|
|
221
|
+
.finally(() => { clearTimeout(timer); job.redirect = undefined; delete job.public.url; }));
|
|
222
|
+
return job.public.id;
|
|
223
|
+
}
|
|
224
|
+
redirect(id, url) {
|
|
225
|
+
const job = this.logins.get(String(id));
|
|
226
|
+
if (!job || job.public.state !== "authorizing" || !job.redirect)
|
|
227
|
+
throw new NativeToolsError("登录已结束,请重新发起登录。");
|
|
228
|
+
if (typeof url !== "string" || url.length > 16000 || !/^https?:\/\//.test(url))
|
|
229
|
+
throw new NativeToolsError("请粘贴完整的 HTTP / HTTPS 回调地址。");
|
|
230
|
+
job.redirect(url);
|
|
231
|
+
}
|
|
232
|
+
cancelLogin(id) { const job = this.logins.get(String(id)); if (job)
|
|
233
|
+
this.cancelName(job.public.name); }
|
|
234
|
+
async logout(name) { const entry = await this.entry(name); const api = await piNative(); this.cancelName(entry.name); if (entry.config.url)
|
|
235
|
+
mcpCredentials(api, this.agentDir).remove(entry.name, entry.config.url); this.changed(); }
|
|
236
|
+
async close() { this.closed = true; this.generation++; for (const job of this.logins.values()) {
|
|
237
|
+
job.abort.abort();
|
|
238
|
+
job.redirect?.();
|
|
239
|
+
} await Promise.allSettled([...this.connections].map(connection => connection.close())); await Promise.allSettled([...this.jobs]); }
|
|
240
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
type Module = Record<string, any>;
|
|
2
|
+
export declare function piNative(): Promise<{
|
|
3
|
+
sdk: any;
|
|
4
|
+
config: Module;
|
|
5
|
+
cli: Module;
|
|
6
|
+
oauth: Module;
|
|
7
|
+
auth: Module;
|
|
8
|
+
core: Module;
|
|
9
|
+
runtime: Module;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function mcpCredentials(api: Awaited<ReturnType<typeof piNative>>, agentDir: string): any;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
let modules;
|
|
2
|
+
export function piNative() {
|
|
3
|
+
return modules ??= (async () => {
|
|
4
|
+
const name = "@earendil-works/pi-coding-agent";
|
|
5
|
+
const base = import.meta.resolve(name);
|
|
6
|
+
const read = (path) => import(new URL(path, base).href);
|
|
7
|
+
const [sdk, config, cli, oauth, auth, core, runtime] = await Promise.all([
|
|
8
|
+
import(name), read("./extensions/mcp/config.js"), read("./extensions/mcp/cli.js"),
|
|
9
|
+
read("./extensions/mcp/oauth.js"), read("./core/auth-storage.js"), read("./core/mcp-servers.js"), read("./extensions/mcp/runtime.js"),
|
|
10
|
+
]);
|
|
11
|
+
return { sdk, config, cli, oauth, auth, core, runtime };
|
|
12
|
+
})();
|
|
13
|
+
}
|
|
14
|
+
export function mcpCredentials(api, agentDir) {
|
|
15
|
+
return new api.oauth.McpOAuthCredentialStore(new api.auth.FileAuthStorageBackend(`${agentDir}/mcp-auth.json`), agentDir);
|
|
16
|
+
}
|
|
@@ -214,6 +214,7 @@ export declare class PiSessionPool {
|
|
|
214
214
|
evictIdle(now?: number): Promise<void>;
|
|
215
215
|
/** Throws away every session. Used at shutdown. */
|
|
216
216
|
disposeAll(): Promise<void>;
|
|
217
|
+
private closeSession;
|
|
217
218
|
/** The conversations with a live session. */
|
|
218
219
|
get conversationIds(): string[];
|
|
219
220
|
}
|
|
@@ -189,7 +189,7 @@ export class PiSessionPool {
|
|
|
189
189
|
if (this.sessions.size < MAX_LIVE_SESSIONS)
|
|
190
190
|
return;
|
|
191
191
|
const candidates = [...this.sessions.entries()]
|
|
192
|
-
.filter(([id, entry]) => id !== exceptConversationId && !entry.building)
|
|
192
|
+
.filter(([id, entry]) => id !== exceptConversationId && !entry.building && entry.session?.isIdle !== false)
|
|
193
193
|
.sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt);
|
|
194
194
|
while (this.sessions.size >= MAX_LIVE_SESSIONS && candidates.length) {
|
|
195
195
|
const [conversationId] = candidates.shift();
|
|
@@ -318,11 +318,13 @@ export class PiSessionPool {
|
|
|
318
318
|
// actually released rather than leaked - a session that finishes building after the eviction has
|
|
319
319
|
// no owner left to dispose it.
|
|
320
320
|
const session = await entry.building.catch(() => undefined);
|
|
321
|
-
session
|
|
321
|
+
if (session)
|
|
322
|
+
await this.closeSession(session);
|
|
322
323
|
return;
|
|
323
324
|
}
|
|
324
325
|
try {
|
|
325
|
-
entry.session
|
|
326
|
+
if (entry.session)
|
|
327
|
+
await this.closeSession(entry.session);
|
|
326
328
|
}
|
|
327
329
|
catch (error) {
|
|
328
330
|
console.warn(`Super Pi: disposing the Pi session of ${conversationId} threw: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
@@ -337,7 +339,7 @@ export class PiSessionPool {
|
|
|
337
339
|
*/
|
|
338
340
|
async evictIdle(now = Date.now()) {
|
|
339
341
|
for (const [conversationId, entry] of [...this.sessions]) {
|
|
340
|
-
if (now - entry.lastUsedAt >= IDLE_EVICTION_MS)
|
|
342
|
+
if (entry.session?.isIdle !== false && now - entry.lastUsedAt >= IDLE_EVICTION_MS)
|
|
341
343
|
await this.evict(conversationId);
|
|
342
344
|
}
|
|
343
345
|
}
|
|
@@ -346,6 +348,14 @@ export class PiSessionPool {
|
|
|
346
348
|
for (const conversationId of [...this.sessions.keys()])
|
|
347
349
|
await this.evict(conversationId);
|
|
348
350
|
}
|
|
351
|
+
async closeSession(session) {
|
|
352
|
+
try {
|
|
353
|
+
await session.extensionRunner?.emit?.({ type: "session_shutdown", reason: "quit" });
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
session.dispose();
|
|
357
|
+
}
|
|
358
|
+
}
|
|
349
359
|
/** The conversations with a live session. */
|
|
350
360
|
get conversationIds() {
|
|
351
361
|
return [...this.sessions.keys()];
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* would notice the difference.
|
|
25
25
|
*/
|
|
26
26
|
import type { PiImageContent } from "./types.js";
|
|
27
|
+
import type { PiCacheWarmingMode } from "../shared/pi-cache-warming.js";
|
|
27
28
|
/**
|
|
28
29
|
* The Pi SDK, imported lazily.
|
|
29
30
|
*
|
|
@@ -100,6 +101,12 @@ interface PiSdk {
|
|
|
100
101
|
getDefaultProvider?: () => string | undefined;
|
|
101
102
|
getDefaultModel?: () => string | undefined;
|
|
102
103
|
getDefaultThinkingLevel?: () => string | undefined;
|
|
104
|
+
getCacheWarmingMode(): PiCacheWarmingMode;
|
|
105
|
+
setCacheWarmingMode(mode: PiCacheWarmingMode): void;
|
|
106
|
+
flush(): Promise<void>;
|
|
107
|
+
drainErrors(): Array<{
|
|
108
|
+
error: Error;
|
|
109
|
+
}>;
|
|
103
110
|
};
|
|
104
111
|
};
|
|
105
112
|
createAgentSession(options: Record<string, unknown>): Promise<{
|
|
@@ -117,6 +124,7 @@ interface PiSdk {
|
|
|
117
124
|
* module and returns, and the caller decides what to do with a failure.
|
|
118
125
|
*/
|
|
119
126
|
export declare function warmPiSdk(): Promise<boolean>;
|
|
127
|
+
export declare function piCacheWarmingMode(mode?: PiCacheWarmingMode): Promise<PiCacheWarmingMode>;
|
|
120
128
|
/**
|
|
121
129
|
* A model catalog read from Pi's SDK, with NO PROCESS.
|
|
122
130
|
*
|
|
@@ -307,8 +315,26 @@ export interface PiSessionLike {
|
|
|
307
315
|
prompt(message: string, options?: {
|
|
308
316
|
images?: PiImageContent[];
|
|
309
317
|
streamingBehavior?: "steer" | "followUp";
|
|
310
|
-
preflightResult?: (
|
|
318
|
+
preflightResult?: (result: "handled" | "started" | "queued") => void;
|
|
319
|
+
}): Promise<void>;
|
|
320
|
+
bindExtensions?(bindings: {
|
|
321
|
+
uiContext: unknown;
|
|
322
|
+
mode: "rpc";
|
|
323
|
+
onError: (error: {
|
|
324
|
+
extensionPath: string;
|
|
325
|
+
event: string;
|
|
326
|
+
}) => void;
|
|
311
327
|
}): Promise<void>;
|
|
328
|
+
setCacheWarmingMode?(mode: PiCacheWarmingMode): void;
|
|
329
|
+
readonly settingsManager?: {
|
|
330
|
+
flush(): Promise<void>;
|
|
331
|
+
drainErrors?(): unknown[];
|
|
332
|
+
};
|
|
333
|
+
readonly cacheWarmingStatus?: {
|
|
334
|
+
state: "inactive" | "scheduled" | "refreshing";
|
|
335
|
+
reason?: string;
|
|
336
|
+
nextWarmAt?: number;
|
|
337
|
+
};
|
|
312
338
|
/** True when no agent run or compaction remains; also true when an input hook handled the prompt. */
|
|
313
339
|
readonly isIdle?: boolean;
|
|
314
340
|
/**
|
|
@@ -433,6 +459,7 @@ export interface PiSessionLike {
|
|
|
433
459
|
getLeafId(): string | null;
|
|
434
460
|
/** The entries from the root to `fromId` (or the current leaf), in path order. */
|
|
435
461
|
getBranch(fromId?: string): unknown[];
|
|
462
|
+
getEntries?(): unknown[];
|
|
436
463
|
};
|
|
437
464
|
/**
|
|
438
465
|
* The session's extension runner, for binding a UI context AFTER creation.
|
|
@@ -444,6 +471,10 @@ export interface PiSessionLike {
|
|
|
444
471
|
*/
|
|
445
472
|
readonly extensionRunner?: {
|
|
446
473
|
setUIContext(uiContext: unknown, mode?: string): void;
|
|
474
|
+
emit?(event: {
|
|
475
|
+
type: "session_shutdown";
|
|
476
|
+
reason: "quit";
|
|
477
|
+
}): Promise<unknown>;
|
|
447
478
|
};
|
|
448
479
|
}
|
|
449
480
|
/** How a session should be built. Everything here is decided once, at creation. */
|
|
@@ -30,6 +30,7 @@ import { dirname, join, resolve } from "node:path";
|
|
|
30
30
|
import { createModelResolver } from "./model-context-window.js";
|
|
31
31
|
import { installProviderProxy, proxyCredentialStore } from "./provider-proxy.js";
|
|
32
32
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
33
|
+
import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, readNativeToolSettings } from "./native-tool-settings.js";
|
|
33
34
|
const traceSession = (conversationId, phase, startedAt, extra = "") => {
|
|
34
35
|
if (process.env.SUPER_PI_TRACE_LATENCY !== "1")
|
|
35
36
|
return;
|
|
@@ -56,6 +57,18 @@ export async function warmPiSdk() {
|
|
|
56
57
|
}
|
|
57
58
|
let sdkPromise;
|
|
58
59
|
let sdkFailure;
|
|
60
|
+
export async function piCacheWarmingMode(mode) {
|
|
61
|
+
const sdk = await loadSdk();
|
|
62
|
+
const settings = sdk.SettingsManager.create(process.cwd(), defaultAgentDir());
|
|
63
|
+
if (mode !== undefined) {
|
|
64
|
+
settings.setCacheWarmingMode(mode);
|
|
65
|
+
await settings.flush();
|
|
66
|
+
}
|
|
67
|
+
const errors = settings.drainErrors();
|
|
68
|
+
if (errors.length)
|
|
69
|
+
throw new Error("Pi 设置读写失败,请检查服务端设置文件和目录权限。");
|
|
70
|
+
return settings.getCacheWarmingMode();
|
|
71
|
+
}
|
|
59
72
|
async function loadSdk() {
|
|
60
73
|
if (sdkFailure)
|
|
61
74
|
throw new Error(sdkFailure);
|
|
@@ -344,7 +357,8 @@ export async function createPiSession(creation) {
|
|
|
344
357
|
// The extension factories run inside `reload()` and capture this session's env values into their
|
|
345
358
|
// closures; the window is serialized (`withIsolatedSessionEnv`) so a concurrent creation cannot
|
|
346
359
|
// land its own capability in the middle.
|
|
347
|
-
|
|
360
|
+
const nativePolicy = nativeToolPolicy(creation, readNativeToolSettings(nativeToolSettingsPath(creation.sessionDir)));
|
|
361
|
+
await withIsolatedSessionEnv({ ...creation.extensionEnv, ...nativeToolEnv(creation.sessionDir, nativePolicy), SUPER_PI_NATIVE_AGENT_DIR: agentDir }, () => loader.reload());
|
|
348
362
|
traceSession(creation.sessionId, "sdk.loader.reload", startedAt, `extensions=${creation.extensionPaths.length}`);
|
|
349
363
|
const sessionManager = creation.persist === false
|
|
350
364
|
? sdk.SessionManager.inMemory(creation.cwd, { id: creation.sessionId })
|
|
@@ -372,8 +386,8 @@ export async function createPiSession(creation) {
|
|
|
372
386
|
modelRuntime,
|
|
373
387
|
resourceLoader: loader,
|
|
374
388
|
sessionManager,
|
|
375
|
-
...(
|
|
376
|
-
...(
|
|
389
|
+
...(nativePolicy.tools ? { tools: nativePolicy.tools } : {}),
|
|
390
|
+
...(nativePolicy.excludeTools ? { excludeTools: nativePolicy.excludeTools } : {}),
|
|
377
391
|
...(model ? { model } : {}),
|
|
378
392
|
...(creation.thinkingLevel ? { thinkingLevel: creation.thinkingLevel } : {}),
|
|
379
393
|
};
|
|
@@ -587,13 +601,14 @@ async function loadPromptTemplateLoader() {
|
|
|
587
601
|
}
|
|
588
602
|
export async function loadPromptTemplateSummaries(cwd) {
|
|
589
603
|
const loadPromptTemplates = await loadPromptTemplateLoader();
|
|
590
|
-
const templates = loadPromptTemplates({ cwd, agentDir: defaultAgentDir(), promptPaths: [], includeDefaults: true });
|
|
604
|
+
const { templates } = loadPromptTemplates({ cwd, agentDir: defaultAgentDir(), promptPaths: [], includeDefaults: true });
|
|
591
605
|
return templates
|
|
592
606
|
.filter((template) => template.sourceInfo.scope === "user" || template.sourceInfo.scope === "project")
|
|
593
607
|
.map((template) => ({ name: template.name, description: template.description, ...(template.argumentHint ? { argumentHint: template.argumentHint } : {}), scope: template.sourceInfo.scope }));
|
|
594
608
|
}
|
|
595
609
|
export function superPiExtensionPaths(repositoryRoot) {
|
|
596
610
|
const paths = [
|
|
611
|
+
join(repositoryRoot, "agents", "super-pi-native-tools", "index.ts"),
|
|
597
612
|
join(repositoryRoot, "agents", "super-pi-task", "index.ts"),
|
|
598
613
|
join(repositoryRoot, "agents", "super-pi-memory", "index.ts"),
|
|
599
614
|
join(repositoryRoot, "agents", "super-pi-knowledge", "index.ts"),
|
package/dist/server/runtime.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
1
2
|
import { type RpcRecord } from "./rpc-channel.js";
|
|
2
3
|
export { RpcChannel, type RpcRecord } from "./rpc-channel.js";
|
|
3
4
|
import type { ActiveMemory } from "./active-memory.js";
|
|
4
5
|
import { type KnowledgeBase } from "./knowledge.js";
|
|
5
6
|
import { type TurnUsageReadout } from "./conversation-usage.js";
|
|
7
|
+
import { type PiCacheWarmingMode, type PiCacheWarmingSettings } from "../shared/pi-cache-warming.js";
|
|
6
8
|
export { forkSessionFile, truncateSessionFile } from "./session-repository.js";
|
|
7
9
|
export { describeDeliveredUserMessage, describePiQueue } from "./pi-session-events.js";
|
|
8
10
|
import { type PiSessionFactory } from "./pi-session.js";
|
|
@@ -248,6 +250,7 @@ export type ForkOutcome = {
|
|
|
248
250
|
sessionFile?: string;
|
|
249
251
|
/** Entry lines copied, header excluded. */
|
|
250
252
|
entriesCopied: number;
|
|
253
|
+
inheritedUsageEntryIds?: string[];
|
|
251
254
|
};
|
|
252
255
|
export type IsolatedExecutionEvent = {
|
|
253
256
|
kind: "thinking";
|
|
@@ -271,6 +274,9 @@ export type IsolatedCompletionInput = {
|
|
|
271
274
|
};
|
|
272
275
|
export interface AgentRuntime {
|
|
273
276
|
answer(input: AnswerInput): AsyncIterable<string>;
|
|
277
|
+
cacheWarmingSettings?(): Promise<PiCacheWarmingSettings>;
|
|
278
|
+
setCacheWarming?(mode: PiCacheWarmingMode): Promise<PiCacheWarmingSettings>;
|
|
279
|
+
reloadNativeTools?(): void;
|
|
274
280
|
stop?(conversationId: string): Promise<void>;
|
|
275
281
|
/**
|
|
276
282
|
* Hands one message to the Pi process that is running RIGHT NOW, to be injected at its next turn
|
|
@@ -483,6 +489,8 @@ export declare function sessionCommands(conversation: Pick<Conversation, "model"
|
|
|
483
489
|
* only the shim, which is the exact failure this function exists to prevent.
|
|
484
490
|
*/
|
|
485
491
|
export declare function killTree(pid: number): Promise<void>;
|
|
492
|
+
/** Let Pi flush its extension shutdown hooks before using the process-tree backstop. */
|
|
493
|
+
export declare function closePiWorker(child: ChildProcessWithoutNullStreams): Promise<void>;
|
|
486
494
|
/**
|
|
487
495
|
* Reads Pi's `steer` disposition out of its response payload.
|
|
488
496
|
*
|
|
@@ -623,6 +631,11 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
623
631
|
private readonly sessionHosts;
|
|
624
632
|
/** The sessions whose extension runner already has the UI bridge bound. */
|
|
625
633
|
private readonly uiBoundSessions;
|
|
634
|
+
private readonly backgroundUsageObservers;
|
|
635
|
+
private backgroundUsageWrites;
|
|
636
|
+
private cacheWarmingWrites;
|
|
637
|
+
private cacheWarmingOverride?;
|
|
638
|
+
private cacheWarmingEpoch;
|
|
626
639
|
/**
|
|
627
640
|
* The session-file path last reported for a conversation, so `onSessionFile` fires when it CHANGES
|
|
628
641
|
* rather than once per turn. The path is stable for the life of a session; what changes it is a
|
|
@@ -764,6 +777,7 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
764
777
|
uploadsDir?: string;
|
|
765
778
|
sessionFactory?: PiSessionFactory;
|
|
766
779
|
sessionMode?: "sdk" | "oneshot";
|
|
780
|
+
onBackgroundUsage?: (conversationId: string, readout: TurnUsageReadout) => Promise<void>;
|
|
767
781
|
});
|
|
768
782
|
/**
|
|
769
783
|
* The configuration of the session that was built for a conversation, for tests to inspect.
|
|
@@ -820,6 +834,10 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
820
834
|
* the old context in memory would keep answering from history the user has withdrawn.
|
|
821
835
|
*/
|
|
822
836
|
disposeSessions(conversationId?: string): Promise<void>;
|
|
837
|
+
cacheWarmingSettings(): Promise<PiCacheWarmingSettings>;
|
|
838
|
+
reloadNativeTools(): void;
|
|
839
|
+
setCacheWarming(mode: PiCacheWarmingMode): Promise<PiCacheWarmingSettings>;
|
|
840
|
+
private observeBackgroundUsage;
|
|
823
841
|
/** Throws away the sessions that have been idle for a while. */
|
|
824
842
|
evictIdleSessions(): Promise<void>;
|
|
825
843
|
/**
|