@evandu/super-pi 0.1.276 → 0.1.279
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 +15 -6
- package/desktop/preload.cjs +2 -2
- package/desktop/window-state.cjs +59 -0
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +11 -10
- package/dist/client/assets/{CodeMirrorEditor-WFfkDO6N.js → CodeMirrorEditor-D-UuYizz.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-PPULzRIU.js → GitDiffEditor-Bt1n2la-.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-DOFVNrEW.css → GitDiffEditor-DP0DQ9Y5.css} +1 -1
- package/dist/client/assets/index-B5TLGyEw.css +1 -0
- package/dist/client/assets/{index-BjauxoWZ.js → index-rWE1xu-t.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 +385 -0
- package/dist/server/application/run-service.d.ts +3 -0
- package/dist/server/application/run-service.js +10 -1
- package/dist/server/http-server.js +4 -1
- package/dist/server/index.js +35 -1
- package/dist/server/native-tools-extension.js +9 -4
- 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/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/rsi.d.ts +44 -0
- package/dist/shared/rsi.js +1 -0
- package/package.json +4 -1
- package/skills/super-pi-capability-development/SKILL.md +32 -0
- package/dist/client/assets/index-CnNljc5p.css +0 -1
|
@@ -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();
|
|
@@ -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 {};
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { ToolRegistry } from "./tool-registry.js";
|
|
6
|
+
import { ToolRunner } from "./tool-runner.js";
|
|
7
|
+
const slugPattern = /^[a-z0-9][a-z0-9-]{0,47}$/;
|
|
8
|
+
class UserToolArtifactError extends Error {
|
|
9
|
+
}
|
|
10
|
+
function required(value, max, label) {
|
|
11
|
+
if (typeof value !== "string" || !value.trim() || value.length > max)
|
|
12
|
+
throw new Error(`${label}不能为空且不得超过 ${max} 字符。`);
|
|
13
|
+
return value.trim();
|
|
14
|
+
}
|
|
15
|
+
/** User assets live outside the application installation; execution reuses the sidebar tool runner. */
|
|
16
|
+
export class UserTools {
|
|
17
|
+
directory;
|
|
18
|
+
registry;
|
|
19
|
+
runner;
|
|
20
|
+
entries = [];
|
|
21
|
+
usage = [];
|
|
22
|
+
lane = Promise.resolve();
|
|
23
|
+
active = new Set();
|
|
24
|
+
validations = new Map();
|
|
25
|
+
constructor(directory) {
|
|
26
|
+
this.directory = directory;
|
|
27
|
+
this.registry = new ToolRegistry(directory);
|
|
28
|
+
this.runner = new ToolRunner(directory);
|
|
29
|
+
}
|
|
30
|
+
static async open(directory) {
|
|
31
|
+
const service = new UserTools(directory);
|
|
32
|
+
try {
|
|
33
|
+
const saved = JSON.parse(await readFile(join(directory, "capabilities.json"), "utf8"));
|
|
34
|
+
service.entries = saved.entries ?? [];
|
|
35
|
+
service.usage = saved.usage ?? [];
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error.code !== "ENOENT")
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
for (const entry of service.entries)
|
|
42
|
+
if (entry.status === "draft") {
|
|
43
|
+
entry.status = "failed";
|
|
44
|
+
entry.testResults = [{ runId: "", passed: false, error: "服务重启,验证中断;请重新验证。" }];
|
|
45
|
+
}
|
|
46
|
+
await service.save();
|
|
47
|
+
return service;
|
|
48
|
+
}
|
|
49
|
+
async save() {
|
|
50
|
+
await mkdir(this.directory, { recursive: true });
|
|
51
|
+
const temporary = join(this.directory, `capabilities.${randomUUID()}.tmp`);
|
|
52
|
+
await writeFile(temporary, JSON.stringify({ entries: this.entries, usage: this.usage }, null, 2), { mode: 0o600 });
|
|
53
|
+
await rename(temporary, join(this.directory, "capabilities.json"));
|
|
54
|
+
}
|
|
55
|
+
serial(work) {
|
|
56
|
+
const job = this.lane.then(work);
|
|
57
|
+
this.lane = job.catch(() => { });
|
|
58
|
+
return job;
|
|
59
|
+
}
|
|
60
|
+
list(includeDrafts = false) {
|
|
61
|
+
const latest = new Map();
|
|
62
|
+
for (const entry of this.entries)
|
|
63
|
+
if (includeDrafts || entry.status === "ready")
|
|
64
|
+
latest.set(entry.slug, entry);
|
|
65
|
+
return structuredClone([...latest.values()]);
|
|
66
|
+
}
|
|
67
|
+
receipts(slug) { return structuredClone(this.usage.filter(item => !slug || item.slug === slug).slice(-100)); }
|
|
68
|
+
async register(input) {
|
|
69
|
+
return this.serial(async () => {
|
|
70
|
+
const slug = required(input.slug, 48, "能力标识");
|
|
71
|
+
if (!slugPattern.test(slug))
|
|
72
|
+
throw new Error("能力标识只能包含小写字母、数字和连字符。");
|
|
73
|
+
if (this.entries.length >= 512)
|
|
74
|
+
throw new Error("用户能力版本数量达到上限,请整理已有版本。");
|
|
75
|
+
const kind = input.kind === "skill" ? "skill" : input.kind === "tool" ? "tool" : undefined;
|
|
76
|
+
if (!kind)
|
|
77
|
+
throw new Error("能力类型须为 tool 或 skill。");
|
|
78
|
+
if (this.entries.some(entry => entry.slug === slug && entry.kind !== kind))
|
|
79
|
+
throw new Error("同名能力不能改变 tool/skill 类型,请使用独立标识。");
|
|
80
|
+
const version = Math.max(0, ...this.entries.filter(item => item.slug === slug).map(item => item.version)) + 1;
|
|
81
|
+
const entry = {
|
|
82
|
+
slug, version, kind, name: required(input.name, 120, "名称"), description: required(input.description, 1600, "说明"),
|
|
83
|
+
applicability: required(input.applicability, 1600, "适用范围"), instructions: required(input.instructions, 16000, "使用说明"),
|
|
84
|
+
status: "draft", createdAt: new Date().toISOString(), source: typeof input.source === "string" ? input.source.slice(0, 160) : undefined, tests: [],
|
|
85
|
+
};
|
|
86
|
+
if (kind === "tool") {
|
|
87
|
+
if (!Array.isArray(input.tests) || input.tests.length < 2 || input.tests.length > 8)
|
|
88
|
+
throw new Error("至少提供两个真实输入/预期 JSON 输出用例,最多八个。");
|
|
89
|
+
entry.tests = input.tests.map((test) => {
|
|
90
|
+
if (!test || typeof test.params !== "object" || !test.params || Array.isArray(test.params) || !test.expected || typeof test.expected !== "object" || Array.isArray(test.expected))
|
|
91
|
+
throw new Error("测试必须包含 params 和 expected JSON 对象。");
|
|
92
|
+
return { params: test.params, expected: test.expected };
|
|
93
|
+
});
|
|
94
|
+
if (entry.tests.some((test, index) => entry.tests.slice(0, index).some(other => isDeepStrictEqual(other.params, test.params))))
|
|
95
|
+
throw new Error("测试用例必须包含不同输入,不能重复同一个用例。");
|
|
96
|
+
if (JSON.stringify(entry.tests).length > 64000)
|
|
97
|
+
throw new Error("测试数据过大,请保留最小复现输入。");
|
|
98
|
+
const script = input.script;
|
|
99
|
+
if (!script || typeof script !== "object" || !Array.isArray(input.files))
|
|
100
|
+
throw new Error("工具须提供完整 files 和 Python script 声明。");
|
|
101
|
+
const tool = await this.registry.register({ slug: `${slug}-v${version}`, name: entry.name, description: entry.description,
|
|
102
|
+
files: [...input.files.filter(file => file.path !== "index.html"), { path: "index.html", content: "<!doctype html><meta charset=utf-8><title>User capability</title><p>Agent callable capability</p>" }],
|
|
103
|
+
script, environment: input.environment });
|
|
104
|
+
entry.toolId = tool.id;
|
|
105
|
+
entry.definition = tool.script;
|
|
106
|
+
entry.sourceAssets = await Promise.all(input.files.filter(file => file.path !== "index.html").map(async (file) => ({ path: file.path, digest: createHash("sha256").update(file.content, "utf8").digest("hex") })));
|
|
107
|
+
}
|
|
108
|
+
this.entries.push(entry);
|
|
109
|
+
await this.save();
|
|
110
|
+
return structuredClone(entry);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
async execute(entry, params, owner, signal) {
|
|
114
|
+
if (!entry.toolId || !entry.definition)
|
|
115
|
+
throw new Error("这项能力没有可执行脚本。");
|
|
116
|
+
signal?.throwIfAborted();
|
|
117
|
+
const resolved = await this.registry.resolve(entry.toolId, entry.definition.path);
|
|
118
|
+
if (!resolved)
|
|
119
|
+
throw new UserToolArtifactError("能力文件不存在。");
|
|
120
|
+
for (const asset of entry.sourceAssets ?? []) {
|
|
121
|
+
const source = await this.registry.resolve(entry.toolId, asset.path);
|
|
122
|
+
if (!source || createHash("sha256").update(await readFile(source.file)).digest("hex") !== asset.digest)
|
|
123
|
+
throw new UserToolArtifactError("已注册版本的源文件发生变化,请注册并验证新版本。");
|
|
124
|
+
}
|
|
125
|
+
const run = this.runner.start({ toolId: entry.toolId, script: resolved.file, cwd: resolved.root, definition: entry.definition, params, environment: resolved.tool.environment, ownerId: owner });
|
|
126
|
+
const active = { id: run.id, toolId: entry.toolId };
|
|
127
|
+
this.active.add(active);
|
|
128
|
+
const cancel = () => this.runner.cancel(run.id, entry.toolId);
|
|
129
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
130
|
+
try {
|
|
131
|
+
for (;;) {
|
|
132
|
+
if (signal?.aborted)
|
|
133
|
+
cancel();
|
|
134
|
+
const latest = this.runner.get(run.id, entry.toolId);
|
|
135
|
+
if (!latest)
|
|
136
|
+
throw new Error("工具执行记录丢失。");
|
|
137
|
+
if (latest.status !== "running")
|
|
138
|
+
return latest;
|
|
139
|
+
await new Promise(resolve => setTimeout(resolve, 40));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
signal?.removeEventListener("abort", cancel);
|
|
144
|
+
this.active.delete(active);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async validate(slug, version, owner, signal) {
|
|
148
|
+
const key = `${slug}:${version}`;
|
|
149
|
+
if (this.validations.has(key))
|
|
150
|
+
return this.validations.get(key);
|
|
151
|
+
const work = (async () => {
|
|
152
|
+
const entry = await this.serial(async () => {
|
|
153
|
+
const entry = this.entries.find(item => item.slug === slug && item.version === version);
|
|
154
|
+
if (!entry)
|
|
155
|
+
throw new Error("能力版本不存在。");
|
|
156
|
+
if (entry.kind === "skill")
|
|
157
|
+
throw new Error("Skill 必须关联已经实测通过的工具才能激活;请使用 activate-skill 并指定工具。");
|
|
158
|
+
entry.status = "draft";
|
|
159
|
+
entry.testResults = [];
|
|
160
|
+
await this.save();
|
|
161
|
+
return entry;
|
|
162
|
+
});
|
|
163
|
+
if (!entry)
|
|
164
|
+
throw new Error("能力版本不存在。");
|
|
165
|
+
const results = [];
|
|
166
|
+
for (const test of entry.tests) {
|
|
167
|
+
try {
|
|
168
|
+
const run = await this.execute(entry, test.params, owner, signal);
|
|
169
|
+
const passed = run.status === "succeeded" && isDeepStrictEqual(run.result, test.expected);
|
|
170
|
+
results.push({ runId: run.id, passed, ...(passed ? {} : { error: run.error ?? "实际输出与预期输出不一致。" }) });
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
results.push({ runId: "", passed: false, error: error instanceof Error ? error.message : String(error) });
|
|
174
|
+
}
|
|
175
|
+
if (signal?.aborted)
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
return this.serial(async () => {
|
|
179
|
+
entry.testResults = results;
|
|
180
|
+
entry.status = results.length === entry.tests.length && results.every(item => item.passed) ? "ready" : "failed";
|
|
181
|
+
await this.save();
|
|
182
|
+
return structuredClone(entry);
|
|
183
|
+
});
|
|
184
|
+
})();
|
|
185
|
+
this.validations.set(key, work);
|
|
186
|
+
try {
|
|
187
|
+
return await work;
|
|
188
|
+
}
|
|
189
|
+
finally {
|
|
190
|
+
this.validations.delete(key);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async activateSkill(slug, version, testedTool) {
|
|
194
|
+
return this.serial(async () => {
|
|
195
|
+
const entry = this.entries.find(item => item.slug === slug && item.version === version && item.kind === "skill");
|
|
196
|
+
if (!entry || !this.list().some(item => item.slug === testedTool && item.kind === "tool"))
|
|
197
|
+
throw new Error("Skill 需要关联一项已验证可用的用户工具。");
|
|
198
|
+
if (entry.status === "ready") {
|
|
199
|
+
if (entry.validatedWith?.slug !== testedTool)
|
|
200
|
+
throw new Error("已激活的 Skill 不可更改关联,请注册新版本。");
|
|
201
|
+
return structuredClone(entry);
|
|
202
|
+
}
|
|
203
|
+
const tool = this.list().find(item => item.slug === testedTool && item.kind === "tool");
|
|
204
|
+
entry.validatedWith = { slug: tool.slug, version: tool.version };
|
|
205
|
+
entry.status = "ready";
|
|
206
|
+
await this.save();
|
|
207
|
+
return structuredClone(entry);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
async invoke(slug, params, owner, signal, version) {
|
|
211
|
+
if (version !== undefined && (!Number.isInteger(version) || version < 1))
|
|
212
|
+
throw new Error("工具版本须为正整数。");
|
|
213
|
+
const entry = version === undefined ? this.list().find(item => item.slug === slug) : structuredClone(this.entries.find(item => item.slug === slug && item.version === version && item.status === 'ready'));
|
|
214
|
+
if (!entry)
|
|
215
|
+
throw new Error("找不到已通过验证的用户能力。");
|
|
216
|
+
if (entry.kind === "skill")
|
|
217
|
+
return { instructions: entry.instructions, applicability: entry.applicability, validatedWith: entry.validatedWith };
|
|
218
|
+
const began = Date.now();
|
|
219
|
+
let run;
|
|
220
|
+
try {
|
|
221
|
+
run = await this.execute(entry, params, owner, signal);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
await this.serial(async () => {
|
|
225
|
+
if (error instanceof UserToolArtifactError) {
|
|
226
|
+
const actual = this.entries.find(item => item.slug === entry.slug && item.version === entry.version);
|
|
227
|
+
if (actual)
|
|
228
|
+
actual.status = "failed";
|
|
229
|
+
}
|
|
230
|
+
this.usage = [...this.usage.slice(-999), { slug, version: entry.version, conversationId: owner, status: "rejected", durationMs: Date.now() - began, at: new Date().toISOString() }];
|
|
231
|
+
await this.save();
|
|
232
|
+
});
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
await this.serial(async () => { this.usage = [...this.usage.slice(-999), { slug, version: entry.version, conversationId: owner, runId: run.id, status: run.status, durationMs: Date.now() - began, at: new Date().toISOString() }]; await this.save(); });
|
|
236
|
+
if (run.status !== "succeeded")
|
|
237
|
+
throw new Error(run.error ?? `工具执行 ${run.status}`);
|
|
238
|
+
return { result: run.result, receipt: { slug, version: entry.version, runId: run.id, durationMs: Date.now() - began } };
|
|
239
|
+
}
|
|
240
|
+
async action(body, owner, manage, signal) {
|
|
241
|
+
if (body.action === "list")
|
|
242
|
+
return this.list(manage && body.includeDrafts === true);
|
|
243
|
+
if (body.action === "invoke")
|
|
244
|
+
return this.invoke(required(body.slug, 48, "能力标识"), body.params ?? {}, owner, signal, body.version);
|
|
245
|
+
if (!manage)
|
|
246
|
+
throw new Error("当前角色没有用户能力管理权限。");
|
|
247
|
+
if (body.action === "register")
|
|
248
|
+
return this.register(body);
|
|
249
|
+
if (body.action === "validate")
|
|
250
|
+
return this.validate(body.slug, body.version, owner, signal);
|
|
251
|
+
if (body.action === "activate-skill")
|
|
252
|
+
return this.activateSkill(body.slug, body.version, body.testedTool);
|
|
253
|
+
if (body.action === "receipts")
|
|
254
|
+
return this.receipts(body.slug);
|
|
255
|
+
throw new Error("用户能力操作无效。");
|
|
256
|
+
}
|
|
257
|
+
close() { for (const active of this.active)
|
|
258
|
+
this.runner.cancel(active.id, active.toolId); }
|
|
259
|
+
}
|