@evandu/super-pi 0.1.275 → 0.1.278
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-designer.md +1 -0
- package/agents/document-organizer.md +1 -0
- package/agents/group-rsi.md +44 -2
- package/agents/rsi-builder.md +58 -0
- package/agents/solution-designer.md +1 -0
- package/desktop/main.cjs +10 -5
- package/desktop/preload.cjs +2 -2
- package/desktop/shell-entries.cjs +14 -2
- package/desktop/window-state.cjs +59 -0
- package/dist/.super-pi-check-inputs.json +4 -0
- package/dist/client/.super-pi-client-sources.json +10 -9
- package/dist/client/assets/{CodeMirrorEditor-DJgZdigq.js → CodeMirrorEditor-CmfIAppR.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-lOnvlR42.js → GitDiffEditor-BZ2Kff1j.js} +3 -3
- package/dist/client/assets/{GitDiffEditor-DIRyUxnb.css → GitDiffEditor-DP0DQ9Y5.css} +1 -1
- package/dist/client/assets/index-B5TLGyEw.css +1 -0
- package/dist/client/assets/{index-BWm699nV.js → index-sXiJhOAC.js} +15 -15
- package/dist/client/index.html +2 -2
- package/dist/server/agents.d.ts +1 -1
- package/dist/server/agents.js +1 -1
- package/dist/server/application/group-chat-service.d.ts +18 -0
- package/dist/server/application/group-chat-service.js +42 -4
- package/dist/server/application/group-execution.js +4 -1
- package/dist/server/application/group-rsi.d.ts +1 -0
- package/dist/server/application/group-rsi.js +34 -6
- package/dist/server/application/rsi-service.d.ts +49 -0
- package/dist/server/application/rsi-service.js +372 -0
- package/dist/server/application/run-service.d.ts +4 -0
- package/dist/server/application/run-service.js +43 -8
- package/dist/server/http-server.js +4 -1
- package/dist/server/index.js +35 -1
- package/dist/server/length-continuation.d.ts +2 -9
- package/dist/server/length-continuation.js +10 -10
- package/dist/server/native-tools-extension.js +9 -4
- package/dist/server/pi-session-events.js +3 -1
- package/dist/server/rsi-evidence.d.ts +2 -0
- package/dist/server/rsi-evidence.js +7 -0
- package/dist/server/rsi-http.d.ts +3 -0
- package/dist/server/rsi-http.js +105 -0
- package/dist/server/runtime.d.ts +5 -1
- package/dist/server/runtime.js +15 -1
- package/dist/server/server-context.d.ts +2 -0
- package/dist/server/tool-runner.js +8 -3
- package/dist/server/turn-failure.d.ts +2 -0
- package/dist/server/turn-failure.js +15 -1
- package/dist/server/user-tools-extension.d.ts +5 -0
- package/dist/server/user-tools-extension.js +50 -0
- package/dist/server/user-tools.d.ts +86 -0
- package/dist/server/user-tools.js +259 -0
- package/dist/shared/group-chat.d.ts +18 -0
- package/dist/shared/output-recovery.d.ts +4 -0
- package/dist/shared/output-recovery.js +6 -0
- package/dist/shared/rsi.d.ts +44 -0
- package/dist/shared/rsi.js +1 -0
- package/package.json +5 -1
- package/skills/super-pi-capability-development/SKILL.md +32 -0
- package/dist/client/assets/index-CnNljc5p.css +0 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { MCP_RESOURCE_TOOLS, readNativeToolSettings } from "./native-tool-settings.js";
|
|
2
2
|
import { piNative, mcpCredentials } from "./pi-native.js";
|
|
3
|
+
import { registerUserTools } from "./user-tools-extension.js";
|
|
3
4
|
/** Loaded through Pi's resource loader in SDK sessions and isolated CLI workers alike. */
|
|
4
5
|
export default async function nativeToolsExtension(pi) {
|
|
5
6
|
const api = await piNative();
|
|
@@ -8,9 +9,13 @@ export default async function nativeToolsExtension(pi) {
|
|
|
8
9
|
const policy = JSON.parse(process.env.SUPER_PI_NATIVE_TOOL_POLICY ?? "{}");
|
|
9
10
|
const allowed = policy.tools;
|
|
10
11
|
const excluded = policy.excludeTools ?? [];
|
|
12
|
+
const canUse = (name) => !excluded.includes("*") && !excluded.includes(name) && (allowed === undefined || allowed.includes(name));
|
|
13
|
+
registerUserTools(pi, policy);
|
|
11
14
|
const agentDir = process.env.SUPER_PI_NATIVE_AGENT_DIR || api.sdk.getAgentDir();
|
|
12
|
-
|
|
13
|
-
|
|
15
|
+
if (canUse("codemode"))
|
|
16
|
+
api.sdk.createCodemodeExtension({ mode: settings.codemode ? "on" : "off", models: false })(pi);
|
|
17
|
+
if (settings.toolSearch && canUse("tool_search"))
|
|
18
|
+
api.sdk.createToolSearchExtension()(pi);
|
|
14
19
|
const resourcesAllowed = MCP_RESOURCE_TOOLS.some(name => !excluded.includes(name) && (allowed === undefined || allowed.includes(name)));
|
|
15
20
|
const mcpAllowed = settings.mcp && !excluded.includes("*") && (resourcesAllowed
|
|
16
21
|
|| !excluded.includes("mcp__*") && (allowed === undefined || allowed.some(name => name.startsWith("mcp__"))));
|
|
@@ -30,9 +35,9 @@ export default async function nativeToolsExtension(pi) {
|
|
|
30
35
|
})(pi);
|
|
31
36
|
pi.on("session_start", () => {
|
|
32
37
|
const tools = pi.getActiveTools();
|
|
33
|
-
if (settings.codemode)
|
|
38
|
+
if (settings.codemode && canUse("codemode"))
|
|
34
39
|
tools.push("codemode");
|
|
35
|
-
if (settings.toolSearch)
|
|
40
|
+
if (settings.toolSearch && canUse("tool_search"))
|
|
36
41
|
tools.push("tool_search");
|
|
37
42
|
pi.setActiveTools([...new Set(tools)]);
|
|
38
43
|
});
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { describeToolCall, describeToolCallArgs, extractPartialResultText, readQuestionCall } from "./tool-calls.js";
|
|
20
20
|
import { toolTargetPath } from "./file-changes.js";
|
|
21
|
-
import { LengthExceededError } from "./turn-failure.js";
|
|
21
|
+
import { LengthExceededError, isProviderQuotaError } from "./turn-failure.js";
|
|
22
22
|
/** Keeps only real strings, so a malformed queue snapshot cannot put objects into a broadcast. */
|
|
23
23
|
const textList = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;
|
|
24
24
|
/**
|
|
@@ -78,6 +78,8 @@ export function describeMessageFailure(record) {
|
|
|
78
78
|
if (!message || typeof message !== "object" || message.role !== "assistant")
|
|
79
79
|
return undefined;
|
|
80
80
|
const text = typeof message.errorMessage === "string" ? message.errorMessage.trim() : "";
|
|
81
|
+
if (text && isProviderQuotaError(text))
|
|
82
|
+
return { message: text, stopReason: "error" };
|
|
81
83
|
if (message.stopReason === "error") {
|
|
82
84
|
return { message: text || "Pi 报告模型或服务提供方错误。", stopReason: "error" };
|
|
83
85
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Redact common credentials before copying task evidence into observer records or prompts. */
|
|
2
|
+
export function rsiEvidence(text) {
|
|
3
|
+
return text.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, "[private key omitted]")
|
|
4
|
+
.replace(/\bBearer\s+[^\s"'<>]+/gi, "Bearer [redacted]")
|
|
5
|
+
.replace(/(["']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|capability)["']?\s*[:=]\s*)(["'])(.*?)\2/gi, "$1$2[redacted]$2")
|
|
6
|
+
.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/g, "$1[redacted]@");
|
|
7
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { verifyCapability } from "./capability.js";
|
|
2
|
+
import { toolSelection } from "./agents.js";
|
|
3
|
+
async function body(request, limit) {
|
|
4
|
+
const chunks = [];
|
|
5
|
+
let size = 0;
|
|
6
|
+
for await (const chunk of request) {
|
|
7
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
8
|
+
size += bytes.length;
|
|
9
|
+
if (size > limit)
|
|
10
|
+
throw new Error("请求内容过大。");
|
|
11
|
+
chunks.push(bytes);
|
|
12
|
+
}
|
|
13
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
14
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
15
|
+
throw new Error("请求须为 JSON 对象。");
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
export async function handleRsiHttp(context, request, response, url) {
|
|
19
|
+
if (url.pathname !== "/api/rsi" && url.pathname !== "/api/user-tools/tool")
|
|
20
|
+
return false;
|
|
21
|
+
const send = (status, data) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); response.end(JSON.stringify(data)); };
|
|
22
|
+
try {
|
|
23
|
+
if (url.pathname === "/api/user-tools/tool") {
|
|
24
|
+
if (request.method !== "POST" || !context.userTools) {
|
|
25
|
+
send(405, { error: "用户能力服务不可用。" });
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
const input = await body(request, 1100000), id = String(input.conversationId ?? "");
|
|
29
|
+
const conversation = context.store.conversation(id);
|
|
30
|
+
const groupCaller = context.groupChatService?.toolCaller(id);
|
|
31
|
+
const running = () => Boolean(conversation ? context.runService.isRunning(id) : context.groupChatService?.toolCaller(id));
|
|
32
|
+
if (!verifyCapability(id, request.headers["x-user-tool-capability"], { running: running() }).ok || !conversation && !groupCaller) {
|
|
33
|
+
send(403, { error: "用户能力调用没有当前执行授权。" });
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
const agentId = conversation?.agentId ?? groupCaller?.agentId;
|
|
37
|
+
const agent = await context.runtime.agentFor?.({ id, agentId });
|
|
38
|
+
if (agentId && !agent) {
|
|
39
|
+
send(403, { error: "当前执行角色已不可用。" });
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
const name = input.manage === true ? "user_tool_manage" : "user_tool";
|
|
43
|
+
const selection = agent ? toolSelection(agent.tools) : {};
|
|
44
|
+
if (selection.excludeTools?.includes("*") || selection.excludeTools?.includes(name) || selection.tools && !selection.tools.includes(name)) {
|
|
45
|
+
send(403, { error: "当前角色没有此用户能力权限。" });
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
const controller = new AbortController();
|
|
49
|
+
const timer = setInterval(() => { if (!running())
|
|
50
|
+
controller.abort(); }, 250);
|
|
51
|
+
timer.unref();
|
|
52
|
+
const disconnect = () => { if (!response.writableEnded)
|
|
53
|
+
controller.abort(); };
|
|
54
|
+
response.on("close", disconnect);
|
|
55
|
+
try {
|
|
56
|
+
const job = context.rsiService?.workerJob(id);
|
|
57
|
+
if (input.action === "register")
|
|
58
|
+
input.source = job?.id;
|
|
59
|
+
send(200, await context.userTools.action(input, id, input.manage === true, controller.signal));
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
clearInterval(timer);
|
|
63
|
+
response.off("close", disconnect);
|
|
64
|
+
}
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
if (!context.rsiService) {
|
|
68
|
+
send(503, { error: "RSI 服务不可用。" });
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
const source = { kind: url.searchParams.get("kind"), id: url.searchParams.get("id") ?? "", workspaceId: url.searchParams.get("workspaceId") ?? "" };
|
|
72
|
+
const group = source.kind === "group" ? context.groupChatService?.get(source.workspaceId, source.id) : undefined;
|
|
73
|
+
if (source.kind === "group" && !group)
|
|
74
|
+
throw new Error("群聊不存在。");
|
|
75
|
+
if (request.method === "GET") {
|
|
76
|
+
send(200, context.rsiService.snapshot(source, group?.rsi));
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
if (request.method !== "POST") {
|
|
80
|
+
send(405, { error: "请求方法无效。" });
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
const input = await body(request, 16000);
|
|
84
|
+
if ((group?.archivedAt || source.kind === "session" && context.store.conversation(source.id)?.archivedAt) && input.action !== "rsi.cancel")
|
|
85
|
+
throw new Error("已归档来源不能发起新的 RSI 工作。");
|
|
86
|
+
if (source.kind === "group" && input.action !== "rsi.cancel") {
|
|
87
|
+
if (input.action === "rsi.improve") {
|
|
88
|
+
const report = group?.rsi?.reports.find(report => report.id === input.reportId);
|
|
89
|
+
if (!report)
|
|
90
|
+
throw new Error("RSI 报告不存在。");
|
|
91
|
+
await context.rsiService.improve(source, report, input.findingId, context.groupChatService?.rsiContext(source.workspaceId, source.id));
|
|
92
|
+
}
|
|
93
|
+
else
|
|
94
|
+
await context.groupChatService.updateRsi(source.workspaceId, source.id, input);
|
|
95
|
+
}
|
|
96
|
+
else
|
|
97
|
+
await context.rsiService.update(source, input);
|
|
98
|
+
send(200, context.rsiService.snapshot(source, source.kind === "group" ? context.groupChatService?.get(source.workspaceId, source.id).rsi : undefined));
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (!response.headersSent)
|
|
102
|
+
send(400, { error: error instanceof Error ? error.message : String(error) });
|
|
103
|
+
}
|
|
104
|
+
return true;
|
|
105
|
+
}
|
package/dist/server/runtime.d.ts
CHANGED
|
@@ -260,9 +260,13 @@ export type IsolatedExecutionEvent = {
|
|
|
260
260
|
} | {
|
|
261
261
|
kind: "tool";
|
|
262
262
|
phase: "start" | "update" | "end";
|
|
263
|
-
call: Pick<ToolCallNotice, "id" | "name" | "detail" | "status" | "durationMs">;
|
|
263
|
+
call: Pick<ToolCallNotice, "id" | "name" | "detail" | "status" | "durationMs" | "result">;
|
|
264
264
|
};
|
|
265
265
|
export type IsolatedCompletionInput = {
|
|
266
|
+
userToolContext?: {
|
|
267
|
+
id: string;
|
|
268
|
+
workspaceId: string;
|
|
269
|
+
};
|
|
266
270
|
/** Internal group identity; absent for every stateless model helper. */
|
|
267
271
|
memberSession?: GroupMemberSession;
|
|
268
272
|
prompt: string;
|
package/dist/server/runtime.js
CHANGED
|
@@ -817,6 +817,7 @@ export class PiRpcRuntime {
|
|
|
817
817
|
SUPER_PI_ORCHESTRATOR_CONVERSATION: conversationId,
|
|
818
818
|
SUPER_PI_QUESTION_ENDPOINT: this.options.questionEndpoint ?? "",
|
|
819
819
|
SUPER_PI_TOOLS_ENDPOINT: this.options.toolsEndpoint ?? "",
|
|
820
|
+
SUPER_PI_USER_TOOLS_ID: conversationId,
|
|
820
821
|
// The document tools' endpoint and the conversation they act for. The CREDENTIAL is not here:
|
|
821
822
|
// it is the session's own capability, which the session pool adds to this environment when the
|
|
822
823
|
// session is born, and the document extension reads that same value. Minting a second
|
|
@@ -2673,6 +2674,8 @@ export class PiRpcRuntime {
|
|
|
2673
2674
|
const selection = nativeToolPolicy(toolSelection(input.agent.tools), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
|
|
2674
2675
|
args.push("--extension", nativeToolExtensionPath(), ...nativeToolArgs(selection));
|
|
2675
2676
|
nativeEnv = nativeToolEnv(this.sessionDir, selection);
|
|
2677
|
+
if (input.userToolContext)
|
|
2678
|
+
nativeEnv = { ...nativeEnv, SUPER_PI_USER_TOOLS_ID: input.userToolContext.id, SUPER_PI_USER_TOOLS_CAPABILITY: mintCapability(input.userToolContext.id) };
|
|
2676
2679
|
}
|
|
2677
2680
|
else
|
|
2678
2681
|
args.push("--no-tools", "--no-context-files");
|
|
@@ -2708,6 +2711,14 @@ export class PiRpcRuntime {
|
|
|
2708
2711
|
if (selected)
|
|
2709
2712
|
await input.onModel(selected);
|
|
2710
2713
|
}
|
|
2714
|
+
if (input.agent?.thinkingLevel) {
|
|
2715
|
+
try {
|
|
2716
|
+
const level = await channel.request({ id: "isolated_thinking", type: "set_thinking_level", level: input.agent.thinkingLevel }, Math.min(input.timeoutMs, 2000));
|
|
2717
|
+
if (level.success !== true && input.agent.thinkingLevel !== "off")
|
|
2718
|
+
await channel.request({ id: "isolated_thinking_fallback", type: "set_thinking_level", level: "off" }, Math.min(input.timeoutMs, 2000));
|
|
2719
|
+
}
|
|
2720
|
+
catch { /* Older worker protocols can retain their default; the wall-clock deadline still applies. */ }
|
|
2721
|
+
}
|
|
2711
2722
|
input.signal?.throwIfAborted();
|
|
2712
2723
|
channel.write({ id: "tool_llm", type: "prompt", message: input.prompt });
|
|
2713
2724
|
awaitingCompletion = true;
|
|
@@ -2743,12 +2754,13 @@ export class PiRpcRuntime {
|
|
|
2743
2754
|
if (input.onExecution && record.toolCallId && (record.type === "tool_execution_start" || record.type === "tool_execution_update" || record.type === "tool_execution_end")) {
|
|
2744
2755
|
const phase = record.type === "tool_execution_start" ? "start" : record.type === "tool_execution_update" ? "update" : "end";
|
|
2745
2756
|
const name = (record.toolName ?? "tool").slice(0, 64);
|
|
2746
|
-
// Keep file targets
|
|
2757
|
+
// Keep file targets, executable names and bounded result summaries for task-quality observation.
|
|
2747
2758
|
const detail = ["read", "write", "edit", "grep", "find", "ls"].includes(name)
|
|
2748
2759
|
? describeToolCall("read", record.args)
|
|
2749
2760
|
: name === "bash" || name === "powershell" ? describeToolCall(name, record.args)?.match(/^[a-z][a-z\d_.-]{0,31}(?=\s|$)/i)?.[0] : undefined;
|
|
2750
2761
|
input.onExecution({ kind: "tool", phase, call: {
|
|
2751
2762
|
id: record.toolCallId.slice(0, 160), name, detail,
|
|
2763
|
+
result: phase === "end" ? extractToolResultText(record.result) : undefined,
|
|
2752
2764
|
status: phase === "end" ? record.isError === true ? "error" : "ok" : undefined,
|
|
2753
2765
|
durationMs: typeof record.durationMs === "number" && Number.isFinite(record.durationMs) ? Math.max(0, Math.round(record.durationMs)) : undefined,
|
|
2754
2766
|
} });
|
|
@@ -2797,6 +2809,8 @@ export class PiRpcRuntime {
|
|
|
2797
2809
|
catch { /* Process shutdown remains the final backstop. */ }
|
|
2798
2810
|
}
|
|
2799
2811
|
await closePiWorker(child);
|
|
2812
|
+
if (input.userToolContext)
|
|
2813
|
+
releaseCapability(input.userToolContext.id);
|
|
2800
2814
|
}
|
|
2801
2815
|
}
|
|
2802
2816
|
/**
|
|
@@ -37,6 +37,8 @@ export interface EventBroadcaster {
|
|
|
37
37
|
* Central server context containing infrastructure dependencies and application services.
|
|
38
38
|
*/
|
|
39
39
|
export interface ServerContext {
|
|
40
|
+
rsiService?: import("./application/rsi-service.js").RsiService;
|
|
41
|
+
userTools?: import("./user-tools.js").UserTools;
|
|
40
42
|
managedServers?: import("./managed-servers.js").ManagedServers;
|
|
41
43
|
browserAccess?: import("./browser-access.js").BrowserAccess;
|
|
42
44
|
memory?: import("./active-memory.js").ActiveMemory;
|
|
@@ -152,10 +152,14 @@ export class ToolRunner {
|
|
|
152
152
|
const requirements = join(envDir, "requirements.txt");
|
|
153
153
|
await writeFile(requirements, `${requires.join("\n")}\n`, "utf8");
|
|
154
154
|
logLine(active, `正在准备 Python 虚拟环境(${requires.join("、")})…\n`);
|
|
155
|
-
const
|
|
155
|
+
const ownChild = (child) => { active.child = child; if (active.cancelled)
|
|
156
|
+
child.kill(); };
|
|
157
|
+
const created = await runCapture(base.path, ["-m", "venv", join(envDir, ".venv")], MAX_ENV_TIMEOUT_MS, (text) => logLine(active, text), ownChild);
|
|
156
158
|
if (!created.ok)
|
|
157
159
|
return { ok: false, error: `创建 Python 虚拟环境失败:${created.error || `解释器 ${base.path} 不可用`}` };
|
|
158
|
-
|
|
160
|
+
if (active.cancelled)
|
|
161
|
+
return { ok: false, error: "环境准备已取消。" };
|
|
162
|
+
const installed = await runCapture(envPython, ["-m", "pip", "install", "--disable-pip-version-check", "--no-input", "-r", requirements], MAX_ENV_TIMEOUT_MS, (text) => logLine(active, text), ownChild);
|
|
159
163
|
if (!installed.ok)
|
|
160
164
|
return { ok: false, error: `安装工具依赖失败:${installed.error || `pip 退出码 ${installed.code}`}(依赖:${requires.join("、")})` };
|
|
161
165
|
await writeFile(join(envDir, "installed.json"), JSON.stringify({ requires, python: base.path, builtAt: new Date().toISOString() }, null, 2), "utf8");
|
|
@@ -223,10 +227,11 @@ export class ToolRunner {
|
|
|
223
227
|
* Runs a Python process with NO SHELL - the same rule as a tool run, because what is being installed
|
|
224
228
|
* is code too. There is no command string anywhere on this path, only an argv.
|
|
225
229
|
*/
|
|
226
|
-
function runCapture(python, args, timeoutMs, onOutput) {
|
|
230
|
+
function runCapture(python, args, timeoutMs, onOutput, onChild) {
|
|
227
231
|
return new Promise((resolve) => {
|
|
228
232
|
let stdout = "", stderr = "", settled = false;
|
|
229
233
|
const child = spawn(python, args, { shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: pythonEnvironment() });
|
|
234
|
+
onChild?.(child);
|
|
230
235
|
const timer = setTimeout(() => { if (settled)
|
|
231
236
|
return; settled = true; try {
|
|
232
237
|
child.kill();
|
|
@@ -47,4 +47,6 @@ export declare class LengthExceededError extends Error {
|
|
|
47
47
|
* way up is exactly the case that used to kill a child session.
|
|
48
48
|
*/
|
|
49
49
|
export declare function isLengthExceededError(error: unknown): boolean;
|
|
50
|
+
/** An explicit provider limit overrides a contradictory output-length marker. */
|
|
51
|
+
export declare function isProviderQuotaError(error: unknown): boolean;
|
|
50
52
|
export declare function controllerAborted(error: unknown): boolean;
|
|
@@ -37,7 +37,9 @@ export function formatTurnFailure(error) {
|
|
|
37
37
|
// PROVIDER QUOTA / RATE LIMIT - the only reason the user is in this branch is because Pi was
|
|
38
38
|
// answering them a moment ago and now the model will not let it. The action is "wait or change
|
|
39
39
|
// model"; the wording has to make that obvious from the banner alone, without a tooltip.
|
|
40
|
-
if (
|
|
40
|
+
if (isProviderQuotaError(error)) {
|
|
41
|
+
if (/Token Plan.*用量上限|\(2056\)/i.test(raw))
|
|
42
|
+
return "模型额度已用完:供应商报告账户或套餐用量达到上限。请检查供应商控制台的用量,额度恢复后重试,或更换模型。";
|
|
41
43
|
return "模型额度已用完(5 小时限额或类似上限),Pi 已停止回答。可以等待重置后重试,或在会话里换一个模型再发。";
|
|
42
44
|
}
|
|
43
45
|
// RPC CHANNEL DEAD - Pi died without producing a `settled` event. Anything in the turn is now
|
|
@@ -142,6 +144,8 @@ export class LengthExceededError extends Error {
|
|
|
142
144
|
export function isLengthExceededError(error) {
|
|
143
145
|
if (!error)
|
|
144
146
|
return false;
|
|
147
|
+
if (isProviderQuotaError(error))
|
|
148
|
+
return false;
|
|
145
149
|
if (error instanceof LengthExceededError)
|
|
146
150
|
return true;
|
|
147
151
|
if (error?.stopReason === "length")
|
|
@@ -149,6 +153,16 @@ export function isLengthExceededError(error) {
|
|
|
149
153
|
const msg = error instanceof Error ? error.message : typeof error === "string" ? error : "";
|
|
150
154
|
return msg.includes("模型输出达到本轮长度上限") || msg.includes("达到本轮长度上限") || msg.includes("单次输出达到长度上限");
|
|
151
155
|
}
|
|
156
|
+
/** An explicit provider limit overrides a contradictory output-length marker. */
|
|
157
|
+
export function isProviderQuotaError(error) {
|
|
158
|
+
if (!error)
|
|
159
|
+
return false;
|
|
160
|
+
const record = error;
|
|
161
|
+
if (record.status === 429 || record.statusCode === 429)
|
|
162
|
+
return true;
|
|
163
|
+
const text = typeof error === "string" ? error : [record.message, record.errorMessage].filter(value => typeof value === "string").join("\n");
|
|
164
|
+
return /\b429\b|quota|rate[_ ]limit|usage limit|too many requests|5-hour|5h|resource_exhausted|resourc exhaust|hit your limit|usage cap|usage restrict|Token Plan.*(?:用量|上限)|用量上限|配额(?:耗尽|不足)|额度(?:已用完|耗尽|不足)|余额不足/i.test(text);
|
|
165
|
+
}
|
|
152
166
|
export function controllerAborted(error) {
|
|
153
167
|
if (!error)
|
|
154
168
|
return false;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Native user capability tools are shared by persistent sessions and group member workers. */
|
|
2
|
+
export function registerUserTools(pi, policy) {
|
|
3
|
+
const endpoint = process.env.SUPER_PI_USER_TOOLS_ENDPOINT;
|
|
4
|
+
const conversationId = process.env.SUPER_PI_USER_TOOLS_ID ?? process.env.SUPER_PI_TASK_CONVERSATION;
|
|
5
|
+
const token = process.env.SUPER_PI_USER_TOOLS_CAPABILITY ?? process.env.SUPER_PI_TASK_CAPABILITY;
|
|
6
|
+
if (!endpoint || !conversationId || !token)
|
|
7
|
+
return;
|
|
8
|
+
const allowed = (name) => !policy.excludeTools?.includes("*") && !policy.excludeTools?.includes(name) && (!policy.tools || policy.tools.includes(name));
|
|
9
|
+
const request = async (body, signal) => {
|
|
10
|
+
const response = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json", "x-user-tool-capability": token }, body: JSON.stringify({ ...body, conversationId }), signal });
|
|
11
|
+
const result = await response.json();
|
|
12
|
+
if (!response.ok)
|
|
13
|
+
throw new Error(result.error ?? "用户能力调用失败。");
|
|
14
|
+
return result;
|
|
15
|
+
};
|
|
16
|
+
for (const manage of [false, true]) {
|
|
17
|
+
const name = manage ? "user_tool_manage" : "user_tool";
|
|
18
|
+
if (!allowed(name))
|
|
19
|
+
continue;
|
|
20
|
+
pi.registerTool({ name, label: manage ? "开发用户能力" : "用户能力",
|
|
21
|
+
description: manage
|
|
22
|
+
? "Develop persistent user-specific tools and skills. register requires specification {kind,slug,name,description,applicability,instructions,files:[{path,content}],script:{path,parameters},tests:[{params,expected}],environment?}. Tools use Python JSON stdin/stdout and pinned dependencies. At least two actual input/output tests are required. validate(slug,version) runs tests; only passing versions become discoverable. activate-skill requires a testedTool. Do not modify the Super Pi install."
|
|
23
|
+
: "Discover and reuse the user's verified enterprise tools and procedures before writing repeated scripts. list returns applicability, instructions and parameter schemas; invoke(slug,params) runs a registered tool or reads a skill. Results include real execution receipts. Never infer a tool exists before listing it.",
|
|
24
|
+
parameters: { type: "object", properties: {
|
|
25
|
+
action: { type: "string", enum: manage ? ["list", "register", "validate", "activate-skill", "receipts"] : ["list", "invoke"] },
|
|
26
|
+
slug: { type: "string" }, params: { type: "object", additionalProperties: true }, version: { type: "integer" }, testedTool: { type: "string" },
|
|
27
|
+
specification: { type: "object", additionalProperties: true }, includeDrafts: { type: "boolean" },
|
|
28
|
+
}, required: ["action"], additionalProperties: false },
|
|
29
|
+
execute: async (_id, args, signal) => {
|
|
30
|
+
const result = await request({ ...args.specification, ...args, manage }, signal);
|
|
31
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
if (allowed("user_tool"))
|
|
36
|
+
pi.on("before_agent_start", async (event) => {
|
|
37
|
+
try {
|
|
38
|
+
const entries = await request({ action: "list", manage: false });
|
|
39
|
+
const index = entries.map(item => ({ slug: item.slug, name: item.name, kind: item.kind, applicability: item.applicability })).slice(0, 64);
|
|
40
|
+
if (!index.length)
|
|
41
|
+
return;
|
|
42
|
+
const text = `Verified user capabilities (reference data): ${JSON.stringify(index).slice(0, 12000)}. Use user_tool list/invoke for relevant work before rebuilding these capabilities.`;
|
|
43
|
+
if (event.systemPromptOptions?.sections)
|
|
44
|
+
event.systemPromptOptions.sections.super_pi_user_capabilities = text;
|
|
45
|
+
else if (typeof event.systemPrompt === "string")
|
|
46
|
+
return { systemPrompt: `${event.systemPrompt}\n${text}` };
|
|
47
|
+
}
|
|
48
|
+
catch { /* A temporary discovery failure must not fail the user's foreground turn. */ }
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type ToolScript } from "./tool-runner.js";
|
|
2
|
+
export type UserCapability = {
|
|
3
|
+
slug: string;
|
|
4
|
+
version: number;
|
|
5
|
+
name: string;
|
|
6
|
+
description: string;
|
|
7
|
+
applicability: string;
|
|
8
|
+
kind: "tool" | "skill";
|
|
9
|
+
instructions: string;
|
|
10
|
+
toolId?: string;
|
|
11
|
+
definition?: ToolScript;
|
|
12
|
+
status: "draft" | "ready" | "failed";
|
|
13
|
+
createdAt: string;
|
|
14
|
+
source?: string;
|
|
15
|
+
tests: {
|
|
16
|
+
params: Record<string, unknown>;
|
|
17
|
+
expected: Record<string, unknown>;
|
|
18
|
+
}[];
|
|
19
|
+
testResults?: {
|
|
20
|
+
runId: string;
|
|
21
|
+
passed: boolean;
|
|
22
|
+
error?: string;
|
|
23
|
+
}[];
|
|
24
|
+
validatedWith?: {
|
|
25
|
+
slug: string;
|
|
26
|
+
version: number;
|
|
27
|
+
};
|
|
28
|
+
sourceAssets?: {
|
|
29
|
+
path: string;
|
|
30
|
+
digest: string;
|
|
31
|
+
}[];
|
|
32
|
+
};
|
|
33
|
+
type Usage = {
|
|
34
|
+
slug: string;
|
|
35
|
+
version: number;
|
|
36
|
+
conversationId: string;
|
|
37
|
+
runId?: string;
|
|
38
|
+
status: string;
|
|
39
|
+
durationMs: number;
|
|
40
|
+
at: string;
|
|
41
|
+
};
|
|
42
|
+
/** User assets live outside the application installation; execution reuses the sidebar tool runner. */
|
|
43
|
+
export declare class UserTools {
|
|
44
|
+
private directory;
|
|
45
|
+
private registry;
|
|
46
|
+
private runner;
|
|
47
|
+
private entries;
|
|
48
|
+
private usage;
|
|
49
|
+
private lane;
|
|
50
|
+
private active;
|
|
51
|
+
private validations;
|
|
52
|
+
private constructor();
|
|
53
|
+
static open(directory: string): Promise<UserTools>;
|
|
54
|
+
private save;
|
|
55
|
+
private serial;
|
|
56
|
+
list(includeDrafts?: boolean): UserCapability[];
|
|
57
|
+
receipts(slug?: string): Usage[];
|
|
58
|
+
register(input: Record<string, unknown>): Promise<UserCapability>;
|
|
59
|
+
private execute;
|
|
60
|
+
validate(slug: string, version: number, owner: string, signal?: AbortSignal): Promise<UserCapability>;
|
|
61
|
+
activateSkill(slug: string, version: number, testedTool: string): Promise<UserCapability>;
|
|
62
|
+
invoke(slug: string, params: Record<string, unknown>, owner: string, signal?: AbortSignal, version?: number): Promise<{
|
|
63
|
+
instructions: string;
|
|
64
|
+
applicability: string;
|
|
65
|
+
validatedWith: {
|
|
66
|
+
slug: string;
|
|
67
|
+
version: number;
|
|
68
|
+
} | undefined;
|
|
69
|
+
result?: undefined;
|
|
70
|
+
receipt?: undefined;
|
|
71
|
+
} | {
|
|
72
|
+
instructions?: undefined;
|
|
73
|
+
applicability?: undefined;
|
|
74
|
+
validatedWith?: undefined;
|
|
75
|
+
result: Record<string, unknown> | undefined;
|
|
76
|
+
receipt: {
|
|
77
|
+
slug: string;
|
|
78
|
+
version: number;
|
|
79
|
+
runId: string;
|
|
80
|
+
durationMs: number;
|
|
81
|
+
};
|
|
82
|
+
}>;
|
|
83
|
+
action(body: Record<string, any>, owner: string, manage: boolean, signal?: AbortSignal): Promise<unknown>;
|
|
84
|
+
close(): void;
|
|
85
|
+
}
|
|
86
|
+
export {};
|