@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.
Files changed (51) hide show
  1. package/agents/code-auditor.md +6 -0
  2. package/agents/code-designer.md +6 -0
  3. package/agents/document-organizer.md +6 -0
  4. package/agents/solution-designer.md +6 -0
  5. package/agents/super-pi-native-tools/index.ts +1 -0
  6. package/agents/super-pi-task/index.ts +7 -58
  7. package/agents/super-pi-task/workflow-schema.ts +34 -0
  8. package/dist/client/.super-pi-client-sources.json +11 -8
  9. package/dist/client/assets/{CodeMirrorEditor-B1T8wU12.js → CodeMirrorEditor-B3K0I0eS.js} +1 -1
  10. package/dist/client/assets/{GitDiffEditor-LCXbSvsh.js → GitDiffEditor-DYmMQWS8.js} +1 -1
  11. package/dist/client/assets/{index-DltiyYgr.css → index-DGpbsE3E.css} +1 -1
  12. package/dist/client/assets/index-Dx58PQcK.js +347 -0
  13. package/dist/client/index.html +2 -2
  14. package/dist/server/agents.js +4 -2
  15. package/dist/server/application/conversation-service.js +6 -1
  16. package/dist/server/application/group-chat-service.js +11 -2
  17. package/dist/server/application/workspace-service.js +15 -5
  18. package/dist/server/conversation-usage.d.ts +4 -1
  19. package/dist/server/conversation-usage.js +6 -3
  20. package/dist/server/http-server.d.ts +3 -1
  21. package/dist/server/http-server.js +99 -1
  22. package/dist/server/index.js +10 -2
  23. package/dist/server/native-tool-settings.d.ts +25 -0
  24. package/dist/server/native-tool-settings.js +41 -0
  25. package/dist/server/native-tools-extension.d.ts +2 -0
  26. package/dist/server/native-tools-extension.js +39 -0
  27. package/dist/server/native-tools-service.d.ts +39 -0
  28. package/dist/server/native-tools-service.js +240 -0
  29. package/dist/server/pi-native.d.ts +12 -0
  30. package/dist/server/pi-native.js +16 -0
  31. package/dist/server/pi-session-pool.d.ts +1 -0
  32. package/dist/server/pi-session-pool.js +14 -4
  33. package/dist/server/pi-session.d.ts +32 -1
  34. package/dist/server/pi-session.js +19 -4
  35. package/dist/server/runtime.d.ts +18 -0
  36. package/dist/server/runtime.js +167 -60
  37. package/dist/server/session-repository.d.ts +1 -0
  38. package/dist/server/session-repository.js +2 -1
  39. package/dist/server/store.d.ts +1 -0
  40. package/dist/server/store.js +10 -2
  41. package/dist/server/subagents.js +9 -22
  42. package/dist/server/thinking-level-discovery.js +25 -1
  43. package/dist/server/types.d.ts +2 -0
  44. package/dist/shared/group-chat.d.ts +3 -0
  45. package/dist/shared/group-chat.js +5 -0
  46. package/dist/shared/native-tools.d.ts +43 -0
  47. package/dist/shared/native-tools.js +1 -0
  48. package/dist/shared/pi-cache-warming.d.ts +9 -0
  49. package/dist/shared/pi-cache-warming.js +4 -0
  50. package/package.json +4 -2
  51. package/dist/client/assets/index-DDrbcKk9.js +0 -347
@@ -8,9 +8,9 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-DDrbcKk9.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-Dx58PQcK.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-DltiyYgr.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-DGpbsE3E.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -295,7 +295,8 @@ export function toolFlags(tools, options = {}) {
295
295
  if (!declared.length)
296
296
  return ["--no-tools"];
297
297
  const allow = [...declared, ...extra.filter((name) => !declared.includes(name) && !denied.has(name))];
298
- return ["--tools", allow.join(",")];
298
+ const excluded = [...new Set([...deny, ...denied])];
299
+ return ["--tools", allow.join(","), ...((allow.some(name => name.includes("*")) || excluded.some(name => name.includes("*"))) && excluded.length ? ["--exclude-tools", excluded.join(",")] : [])];
299
300
  }
300
301
  // A map with no allowlist is Pi's defaults, so a denied name has to become an explicit exclusion
301
302
  // rather than being dropped - there is nothing to drop it FROM.
@@ -348,7 +349,8 @@ export function toolSelection(tools, options = {}) {
348
349
  if (!declared.length)
349
350
  return { tools: [] };
350
351
  const allow = [...declared, ...extra.filter((name) => !declared.includes(name) && !denied.has(name))];
351
- return { tools: allow };
352
+ const excluded = [...new Set([...deny, ...denied])];
353
+ return { tools: allow, ...((allow.some(name => name.includes("*")) || excluded.some(name => name.includes("*"))) && excluded.length ? { excludeTools: excluded } : {}) };
352
354
  }
353
355
  const excluded = [...new Set([...deny, ...[...denied].filter((name) => !deny.includes(name))])];
354
356
  return excluded.length ? { excludeTools: excluded } : {};
@@ -309,6 +309,7 @@ export class ConversationService {
309
309
  * Sets the active model on a conversation, validating against Pi's catalog.
310
310
  */
311
311
  async setModel(conversationId, provider, modelId) {
312
+ const previous = this.store.conversation(conversationId);
312
313
  const catalog = await this.runtime.catalog();
313
314
  const option = catalog.source === "pi"
314
315
  ? catalog.models.find((model) => model.provider === provider && model.modelId === modelId)
@@ -324,6 +325,10 @@ export class ConversationService {
324
325
  throw new Error("找不到这个工作区。");
325
326
  assertModelAllowed(this.store.modelFilterRules(), workspace, selection);
326
327
  await this.store.setConversationModel(conversationId, selection);
328
+ const thinking = await this.runtime.catalog(selection);
329
+ if (thinking.source === "pi" && previous?.thinkingLevel && !thinking.levels.includes(previous.thinkingLevel)) {
330
+ await this.store.setConversationThinking(conversationId, undefined);
331
+ }
327
332
  this.broadcaster.broadcastState();
328
333
  await this.catalogService.broadcastCatalog(selection, conversationId);
329
334
  }
@@ -601,7 +606,7 @@ export class ConversationService {
601
606
  || latest.archivedAt !== conversation.archivedAt || JSON.stringify(latest.messages) !== JSON.stringify(conversation.messages)) {
602
607
  throw new Error("来源会话在复制时发生变化,请等当前操作结束后重试");
603
608
  }
604
- const forked = await this.store.forkConversation(conversationId, forkedId, { parentConversationId: parent, warmTitle, piSessionFile: copiedFile });
609
+ const forked = await this.store.forkConversation(conversationId, forkedId, { parentConversationId: parent, warmTitle, piSessionFile: copiedFile, inheritedUsageEntryIds: outcome.inheritedUsageEntryIds });
605
610
  copiedFile = undefined;
606
611
  copiedUploads = undefined;
607
612
  console.log(`Super Pi: forked conversation ${conversation.id} into ${forked.id}: ` +
@@ -46,7 +46,15 @@ function activityStatus(messages) {
46
46
  return "idle";
47
47
  }
48
48
  function groupActivity(room) {
49
- return { status: activityStatus(room.messages), revision: room.revision };
49
+ let lastReplyAt;
50
+ for (const post of room.messages) {
51
+ if (post.role !== "assistant" || (!post.content && !post.error))
52
+ continue;
53
+ const at = post.settledAt ?? post.createdAt;
54
+ if (!lastReplyAt || at > lastReplyAt)
55
+ lastReplyAt = at;
56
+ }
57
+ return { status: activityStatus(room.messages), revision: room.revision, ...(lastReplyAt ? { lastReplyAt } : {}) };
50
58
  }
51
59
  function summary(room) {
52
60
  const { id, workspaceId, title, updatedAt, archivedAt } = room;
@@ -223,7 +231,8 @@ export class GroupChatService {
223
231
  if (!workspace || workspace.closedAt)
224
232
  continue;
225
233
  const activity = groupActivity(room);
226
- if (activity.status !== activityStatus(before.messages))
234
+ const priorActivity = groupActivity(before);
235
+ if (activity.status !== priorActivity.status || activity.lastReplyAt !== priorActivity.lastReplyAt)
227
236
  this.onActivity({ id: room.id, workspaceId: room.workspaceId, activity });
228
237
  }
229
238
  }
@@ -80,10 +80,20 @@ export class WorkspaceService {
80
80
  ? { provider: option.provider, modelId: option.modelId, label: option.label }
81
81
  : { provider: requested.provider, modelId: requested.modelId, label: requested.modelId };
82
82
  }
83
- if (settings.thinkingLevel) {
84
- const catalog = await this.runtime.catalog(selection ?? workspace.defaultModel);
85
- if (catalog.source === "pi" && !catalog.levels.includes(settings.thinkingLevel)) {
86
- throw this.catalogService.notOffered(`思考等级 ${settings.thinkingLevel}`, catalog);
83
+ let thinkingLevel = settings.thinkingLevel ?? undefined;
84
+ if (thinkingLevel) {
85
+ const modelChanged = settings.model !== undefined && (selection?.provider !== workspace.defaultModel?.provider ||
86
+ selection?.modelId !== workspace.defaultModel?.modelId);
87
+ const targetModel = settings.model === null ? undefined : selection ?? workspace.defaultModel;
88
+ const catalog = await this.runtime.catalog(targetModel);
89
+ if (catalog.source === "pi" && !catalog.levels.includes(thinkingLevel)) {
90
+ if (modelChanged) {
91
+ // A saved thinking level belongs to its model; switching models follows Pi's own default.
92
+ thinkingLevel = undefined;
93
+ }
94
+ else {
95
+ throw this.catalogService.notOffered(`思考等级 ${thinkingLevel}`, catalog);
96
+ }
87
97
  }
88
98
  }
89
99
  let agentToStore;
@@ -126,7 +136,7 @@ export class WorkspaceService {
126
136
  assertModelAllowed(this.store.modelFilterRules(), workspace, selection);
127
137
  await this.store.setWorkspaceDefaults(workspaceId, {
128
138
  model: selection,
129
- thinkingLevel: settings.thinkingLevel ?? undefined,
139
+ thinkingLevel,
130
140
  agentId: agentToStore,
131
141
  });
132
142
  this.broadcaster.broadcastState();
@@ -3,12 +3,15 @@ export type TurnUsageReadout = {
3
3
  usage?: SubagentUsage;
4
4
  costKnown: boolean;
5
5
  contextUsage?: ConversationContextUsage;
6
+ /** Persisted Pi usage entries are accounted independently from foreground turns. */
7
+ sourceEntryId?: string;
6
8
  };
7
9
  /** Collect only completed assistant messages, never the repeated usage on streaming deltas. */
8
10
  export declare class ConversationUsageCollector {
9
11
  private readonly total;
10
12
  private costKnown;
11
- add(value: unknown): void;
13
+ private hasUsage;
14
+ add(value: unknown, countTurn?: boolean): void;
12
15
  readout(context: {
13
16
  tokens: number | null;
14
17
  contextWindow: number;
@@ -4,7 +4,8 @@ const nonnegative = (value) => typeof value === "number" && Number.isFinite(valu
4
4
  export class ConversationUsageCollector {
5
5
  total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
6
6
  costKnown = true;
7
- add(value) {
7
+ hasUsage = false;
8
+ add(value, countTurn = true) {
8
9
  if (!value || typeof value !== "object") {
9
10
  this.costKnown = false;
10
11
  return;
@@ -16,12 +17,14 @@ export class ConversationUsageCollector {
16
17
  this.costKnown = false;
17
18
  if (!keys.some(key => nonnegative(usage[key])) && !nonnegative(cost))
18
19
  return;
20
+ this.hasUsage = true;
19
21
  for (const key of keys)
20
22
  if (nonnegative(usage[key]))
21
23
  this.total[key] += usage[key];
22
24
  if (nonnegative(cost))
23
25
  this.total.cost += cost;
24
- this.total.turns++;
26
+ if (countTurn)
27
+ this.total.turns++;
25
28
  }
26
29
  readout(context, model, agentDir) {
27
30
  let contextUsage;
@@ -35,6 +38,6 @@ export class ConversationUsageCollector {
35
38
  contextUsage = { tokens, contextWindow, percent: tokens === null ? null : tokens / contextWindow * 100 };
36
39
  }
37
40
  }
38
- return { ...(this.total.turns ? { usage: { ...this.total } } : {}), costKnown: this.costKnown, ...(contextUsage ? { contextUsage } : {}) };
41
+ return { ...(this.hasUsage ? { usage: { ...this.total } } : {}), costKnown: this.costKnown, ...(contextUsage ? { contextUsage } : {}) };
39
42
  }
40
43
  }
@@ -40,4 +40,6 @@ export interface HttpServerOptions {
40
40
  port?: number;
41
41
  host?: string;
42
42
  }
43
- export declare function createHttpServer(options: HttpServerOptions): NodeHttpServer;
43
+ export declare function createHttpServer(options: HttpServerOptions): NodeHttpServer & {
44
+ closeNativeTools(): Promise<void>;
45
+ };
@@ -2,6 +2,7 @@ import { createReadStream, existsSync } from "node:fs";
2
2
  import { matchPathMentions } from "../shared/file-mentions.js";
3
3
  import { spawn } from "node:child_process";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { NativeToolsService, NativeToolsError } from "./native-tools-service.js";
5
6
  import { once } from "node:events";
6
7
  import { readdir, realpath, rm, stat } from "node:fs/promises";
7
8
  import { createServer } from "node:http";
@@ -361,6 +362,7 @@ export function createHttpServer(options) {
361
362
  const gitDrafts = new Set();
362
363
  const manageWorktree = createWorktreeService(context);
363
364
  const explicitFileOpen = createExplicitFileOpen();
365
+ const nativeTools = new NativeToolsService(paths.dataDir, () => context.runtime?.reloadNativeTools?.());
364
366
  let tracker;
365
367
  const getUpdateTracker = () => tracker ??= new UpdateTracker(join(paths.dataDir ?? rootDir, "update-status.json"), rootDir);
366
368
  const updateStatus = () => {
@@ -370,7 +372,7 @@ export function createHttpServer(options) {
370
372
  ? { ok: operation.phase === "completed", code: operation.failure?.code, at: operation.changedAt } : null;
371
373
  return { ...status, updating: updateIsActive(operation), lastUpdate };
372
374
  };
373
- return createServer(async (request, response) => {
375
+ const server = createServer(async (request, response) => {
374
376
  // Every HTTP request gets one stable id. It is returned to the browser and
375
377
  // included in the server log, so a report containing a status code or a
376
378
  // timeout can be joined to the exact failing request without guessing from
@@ -892,6 +894,100 @@ export function createHttpServer(options) {
892
894
  }
893
895
  return;
894
896
  }
897
+ if (url.pathname === "/api/native-tools") {
898
+ const remote = request.socket.remoteAddress;
899
+ const origin = request.headers.origin;
900
+ const fetchSite = request.headers["sec-fetch-site"];
901
+ if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
902
+ json(403, { error: "外部工具管理只允许本机或局域网的同源请求。" });
903
+ return;
904
+ }
905
+ try {
906
+ if (request.method === "GET") {
907
+ json(200, await nativeTools.snapshot());
908
+ return;
909
+ }
910
+ if (request.method !== "POST") {
911
+ json(405, { error: "外部工具设置仅支持 GET / POST" });
912
+ return;
913
+ }
914
+ const asked = await readRequestText(request, 262144);
915
+ if (asked.tooLarge) {
916
+ json(413, { error: "配置内容过大" });
917
+ return;
918
+ }
919
+ const body = JSON.parse(asked.text || "{}");
920
+ const workspace = context.store.workspace(body.workspaceId);
921
+ const requireWorkspace = () => { if (!workspace || workspace.closedAt)
922
+ throw new NativeToolsError("请选择有效的工作区。"); return workspace.path; };
923
+ switch (body.action) {
924
+ case "settings":
925
+ await nativeTools.settings(body.settings);
926
+ break;
927
+ case "save":
928
+ await nativeTools.save(body.name, body.config);
929
+ break;
930
+ case "patch":
931
+ await nativeTools.patch(body.name, { enabled: body.enabled, exposure: body.exposure });
932
+ break;
933
+ case "delete":
934
+ await nativeTools.remove(body.name);
935
+ break;
936
+ case "diagnose":
937
+ await nativeTools.diagnose(requireWorkspace());
938
+ break;
939
+ case "login":
940
+ await nativeTools.login(body.name, requireWorkspace());
941
+ break;
942
+ case "redirect":
943
+ nativeTools.redirect(body.id, body.url);
944
+ break;
945
+ case "cancel-login":
946
+ nativeTools.cancelLogin(body.id);
947
+ break;
948
+ case "logout":
949
+ await nativeTools.logout(body.name);
950
+ break;
951
+ default: throw new NativeToolsError("未知的外部工具操作。");
952
+ }
953
+ json(200, await nativeTools.snapshot());
954
+ }
955
+ catch (error) {
956
+ json(400, { error: error instanceof NativeToolsError ? error.message : error instanceof SyntaxError ? "配置 JSON 格式不正确。" : "外部工具处理失败,请检查服务端配置与目录权限。" });
957
+ }
958
+ return;
959
+ }
960
+ if (url.pathname === "/api/pi/cache-warming") {
961
+ if (!context.runtime.cacheWarmingSettings || !context.runtime.setCacheWarming) {
962
+ json(503, { error: "当前运行模式不支持 Pi 缓存预热设置。" });
963
+ return;
964
+ }
965
+ try {
966
+ if (request.method === "GET") {
967
+ json(200, await context.runtime.cacheWarmingSettings());
968
+ return;
969
+ }
970
+ if (request.method !== "PATCH") {
971
+ json(405, { error: "缓存设置仅支持 GET / PATCH" });
972
+ return;
973
+ }
974
+ const asked = await readRequestText(request, 4096);
975
+ if (asked.tooLarge) {
976
+ json(413, { error: "缓存设置过大" });
977
+ return;
978
+ }
979
+ const body = JSON.parse(asked.text || "{}");
980
+ if (!body || !["off", "streaming", "idle"].includes(body.mode)) {
981
+ json(400, { error: "请选择有效的缓存预热模式。" });
982
+ return;
983
+ }
984
+ json(200, await context.runtime.setCacheWarming(body.mode));
985
+ }
986
+ catch (error) {
987
+ json(400, { error: error instanceof SyntaxError ? "缓存设置格式不正确" : error instanceof Error ? error.message : "缓存设置保存失败" });
988
+ }
989
+ return;
990
+ }
895
991
  if (url.pathname === "/api/providers/network") {
896
992
  try {
897
993
  if (request.method === "GET") {
@@ -3448,4 +3544,6 @@ export function createHttpServer(options) {
3448
3544
  }
3449
3545
  }
3450
3546
  });
3547
+ server.once("close", () => { void nativeTools.close(); });
3548
+ return Object.assign(server, { closeNativeTools: () => nativeTools.close() });
3451
3549
  }
@@ -161,7 +161,14 @@ const paths = {
161
161
  };
162
162
  const runtime = process.env.SUPER_PI_RUNTIME === "welcome"
163
163
  ? new WelcomeRuntime()
164
- : new PiRpcRuntime(join(dataDir, "pi-sessions"), undefined, { dir: initialAgentDirs, promptDir: agentPromptDir }, { endpoint: taskEndpoint, execEndpoint, todoEndpoint, workflowEndpoint, questionEndpoint, toolsEndpoint, documentsEndpoint, scheduledTaskEndpoint, orchestratorEndpoint, uploadsDir });
164
+ : new PiRpcRuntime(join(dataDir, "pi-sessions"), undefined, { dir: initialAgentDirs, promptDir: agentPromptDir }, { endpoint: taskEndpoint, execEndpoint, todoEndpoint, workflowEndpoint, questionEndpoint, toolsEndpoint, documentsEndpoint, scheduledTaskEndpoint, orchestratorEndpoint, uploadsDir,
165
+ onBackgroundUsage: async (conversationId, readout) => {
166
+ if (!store.conversation(conversationId))
167
+ return;
168
+ await store.recordConversationUsage(conversationId, readout);
169
+ broadcaster.broadcastState();
170
+ },
171
+ });
165
172
  // Closed workspaces stay in the store for reopening. Focused sockets receive all visible sidebar
166
173
  // summaries and only their selected transcript; legacy sockets retain the complete visible state.
167
174
  let projectRuntime = (state) => state;
@@ -395,6 +402,7 @@ async function shutdown(reason) {
395
402
  // Stop accepting new connections first. Existing clients stay connected until
396
403
  // their cancelled work has recorded its terminal state.
397
404
  const httpClosed = closeHttpServer();
405
+ const nativeToolsClosed = httpServer.closeNativeTools();
398
406
  // Kill every shell BEFORE the sockets close, so a PTY is never outlived by the server that owns it.
399
407
  terminalService.closeAll();
400
408
  const execClosed = execService.closeAll();
@@ -424,7 +432,7 @@ async function shutdown(reason) {
424
432
  await store.flush();
425
433
  wsServer.close();
426
434
  httpServer.closeAllConnections();
427
- await httpClosed;
435
+ await Promise.all([httpClosed, nativeToolsClosed]);
428
436
  await store.close();
429
437
  })();
430
438
  return shutdownPromise;
@@ -0,0 +1,25 @@
1
+ import { type NativeToolSettings } from "../shared/native-tools.js";
2
+ export declare const MCP_RESOURCE_TOOLS: string[];
3
+ export declare const nativeToolSettingsPath: (sessionDir: string) => string;
4
+ export declare const nativeToolExtensionPath: () => string;
5
+ export declare function readNativeToolSettings(path: string): NativeToolSettings;
6
+ export declare function nativeToolExclusions(settings: NativeToolSettings): string[];
7
+ export declare function nativeToolEnv(sessionDir: string, selection: {
8
+ tools?: string[];
9
+ excludeTools?: string[];
10
+ }): {
11
+ SUPER_PI_NATIVE_TOOLS_CONFIG_PATH: string;
12
+ SUPER_PI_NATIVE_TOOL_POLICY: string;
13
+ SUPER_PI_NATIVE_AGENT_DIR: string;
14
+ };
15
+ export declare function nativeToolPolicy(selection: {
16
+ tools?: string[];
17
+ excludeTools?: string[];
18
+ }, settings: NativeToolSettings): {
19
+ tools?: string[];
20
+ excludeTools?: string[];
21
+ };
22
+ export declare function nativeToolArgs(selection: {
23
+ tools?: string[];
24
+ excludeTools?: string[];
25
+ }): string[];
@@ -0,0 +1,41 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { DEFAULT_NATIVE_TOOLS } from "../shared/native-tools.js";
5
+ export const MCP_RESOURCE_TOOLS = ["list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"];
6
+ export const nativeToolSettingsPath = (sessionDir) => join(dirname(sessionDir), "native-tools.json");
7
+ export const nativeToolExtensionPath = () => resolve(import.meta.dirname, "../../agents/super-pi-native-tools/index.ts");
8
+ export function readNativeToolSettings(path) {
9
+ let value;
10
+ try {
11
+ value = JSON.parse(readFileSync(path, "utf8"));
12
+ }
13
+ catch (error) {
14
+ if (error.code === "ENOENT")
15
+ return { ...DEFAULT_NATIVE_TOOLS };
16
+ throw new Error("外部工具设置无法读取,请检查服务端配置文件。");
17
+ }
18
+ if (!value || typeof value !== "object" || Object.keys(value).some(key => !["mcp", "toolSearch", "codemode"].includes(key)) || Object.values(value).some(item => typeof item !== "boolean"))
19
+ throw new Error("外部工具设置格式不正确。");
20
+ return { ...DEFAULT_NATIVE_TOOLS, ...value };
21
+ }
22
+ export function nativeToolExclusions(settings) {
23
+ return [...(!settings.mcp ? ["mcp__*", ...MCP_RESOURCE_TOOLS] : []), ...(!settings.toolSearch ? ["tool_search"] : []), ...(!settings.codemode ? ["codemode"] : [])];
24
+ }
25
+ export function nativeToolEnv(sessionDir, selection) {
26
+ return { SUPER_PI_NATIVE_TOOLS_CONFIG_PATH: nativeToolSettingsPath(sessionDir), SUPER_PI_NATIVE_TOOL_POLICY: JSON.stringify(selection), SUPER_PI_NATIVE_AGENT_DIR: process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent") };
27
+ }
28
+ export function nativeToolPolicy(selection, settings) {
29
+ const denied = [...(selection.excludeTools ?? []), ...nativeToolExclusions(settings)];
30
+ if (selection.tools && !selection.tools.some(name => name.startsWith("mcp__")))
31
+ denied.push("mcp__*");
32
+ if (selection.tools)
33
+ denied.push(...MCP_RESOURCE_TOOLS.filter(name => !selection.tools.includes(name)));
34
+ if (selection.tools?.length === 0)
35
+ denied.push("*");
36
+ return { ...selection, ...(denied.length ? { excludeTools: [...new Set(denied)] } : {}) };
37
+ }
38
+ export function nativeToolArgs(selection) {
39
+ return [...(selection.tools ? selection.tools.length ? ["--tools", selection.tools.join(",")] : ["--no-tools"] : []),
40
+ ...(selection.excludeTools?.length ? ["--exclude-tools", selection.excludeTools.join(",")] : [])];
41
+ }
@@ -0,0 +1,2 @@
1
+ /** Loaded through Pi's resource loader in SDK sessions and isolated CLI workers alike. */
2
+ export default function nativeToolsExtension(pi: any): Promise<void>;
@@ -0,0 +1,39 @@
1
+ import { MCP_RESOURCE_TOOLS, readNativeToolSettings } from "./native-tool-settings.js";
2
+ import { piNative, mcpCredentials } from "./pi-native.js";
3
+ /** Loaded through Pi's resource loader in SDK sessions and isolated CLI workers alike. */
4
+ export default async function nativeToolsExtension(pi) {
5
+ const api = await piNative();
6
+ const path = process.env.SUPER_PI_NATIVE_TOOLS_CONFIG_PATH;
7
+ const settings = path ? readNativeToolSettings(path) : { mcp: true, codemode: true, toolSearch: true };
8
+ const policy = JSON.parse(process.env.SUPER_PI_NATIVE_TOOL_POLICY ?? "{}");
9
+ const allowed = policy.tools;
10
+ const excluded = policy.excludeTools ?? [];
11
+ const agentDir = process.env.SUPER_PI_NATIVE_AGENT_DIR || api.sdk.getAgentDir();
12
+ api.sdk.createCodemodeExtension({ mode: settings.codemode ? "on" : "off", models: false })(pi);
13
+ api.sdk.createToolSearchExtension()(pi);
14
+ const resourcesAllowed = MCP_RESOURCE_TOOLS.some(name => !excluded.includes(name) && (allowed === undefined || allowed.includes(name)));
15
+ const mcpAllowed = settings.mcp && !excluded.includes("*") && (resourcesAllowed
16
+ || !excluded.includes("mcp__*") && (allowed === undefined || allowed.some(name => name.startsWith("mcp__"))));
17
+ if (mcpAllowed)
18
+ api.sdk.createMcpExtension({
19
+ credentials: mcpCredentials(api, agentDir),
20
+ logPath: `${agentDir}/mcp.log`,
21
+ loadConfig(ctx) {
22
+ const loaded = api.config.loadMcpConfig({ agentDir, cwd: ctx.cwd, projectTrusted: ctx.isProjectTrusted?.() === true });
23
+ if (allowed && !resourcesAllowed)
24
+ loaded.servers = loaded.servers.filter((server) => {
25
+ const prefix = `mcp__${server.name}__`.replace(/[^A-Za-z0-9_]/g, "_");
26
+ return allowed.some(pattern => pattern.startsWith("mcp__") && (pattern.startsWith(prefix) || prefix.startsWith(pattern.split("*")[0])));
27
+ });
28
+ return { ...loaded, autoEnableCodemode: settings.codemode && loaded.autoEnableCodemode !== false };
29
+ },
30
+ })(pi);
31
+ pi.on("session_start", () => {
32
+ const tools = pi.getActiveTools();
33
+ if (settings.codemode)
34
+ tools.push("codemode");
35
+ if (settings.toolSearch)
36
+ tools.push("tool_search");
37
+ pi.setActiveTools([...new Set(tools)]);
38
+ });
39
+ }
@@ -0,0 +1,39 @@
1
+ import type { NativeToolsSnapshot } from "../shared/native-tools.js";
2
+ export declare class NativeToolsError extends Error {
3
+ }
4
+ /** Web management reuses Pi's validated configuration, native connection and OAuth implementation. */
5
+ export declare class NativeToolsService {
6
+ private readonly dataDir;
7
+ private readonly changed;
8
+ private readonly agentDir;
9
+ private readonly configPath;
10
+ private readonly settingsPath;
11
+ private readonly logins;
12
+ private readonly connections;
13
+ private readonly jobs;
14
+ private diagnostics?;
15
+ private generation;
16
+ private closed;
17
+ private configurationWarning?;
18
+ private track;
19
+ private invalidate;
20
+ constructor(dataDir: string, changed: () => void, agentDir?: string);
21
+ private entries;
22
+ snapshot(): Promise<NativeToolsSnapshot>;
23
+ private entry;
24
+ settings(value: unknown): Promise<void>;
25
+ save(name: unknown, config: unknown): Promise<void>;
26
+ patch(name: unknown, patch: {
27
+ enabled?: unknown;
28
+ exposure?: unknown;
29
+ }): Promise<void>;
30
+ remove(name: unknown): Promise<void>;
31
+ private cancelName;
32
+ private connection;
33
+ diagnose(cwd: string): Promise<void>;
34
+ login(name: unknown, cwd: string): Promise<string>;
35
+ redirect(id: unknown, url: unknown): void;
36
+ cancelLogin(id: unknown): void;
37
+ logout(name: unknown): Promise<void>;
38
+ close(): Promise<void>;
39
+ }