@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,17 +8,19 @@ import { FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME } from "./feishu-cli.js";
8
8
  import { WEB_FETCH_TOOL_NAME, WEB_SEARCH_TOOL_NAME } from "./web.js";
9
9
  import { existsSync } from "node:fs";
10
10
  import { ConversationUsageCollector } from "./conversation-usage.js";
11
- import { defaultAgentDir } from "./pi-session.js";
11
+ import { defaultAgentDir, piCacheWarmingMode } from "./pi-session.js";
12
+ import { isPiCacheWarmingMode } from "../shared/pi-cache-warming.js";
12
13
  import { readProviderProxyEnv } from "./provider-proxy.js";
13
14
  import { withArbitratedWindows } from "./model-context-window.js";
14
15
  import { mkdir, stat } from "node:fs/promises";
15
16
  import { forkSessionFile, truncateSessionFile } from "./session-repository.js";
16
17
  export { forkSessionFile, truncateSessionFile } from "./session-repository.js";
17
- import { resolve, join } from "node:path";
18
+ import { resolve, join, basename } from "node:path";
18
19
  import { agentSpawnArgs, readAgents, toolSelection, writeAgentPrompt } from "./agents.js";
19
20
  import { TASK_CAPABILITY_ENV, mintCapability, releaseCapability } from "./capability.js";
20
21
  import { resolvePiCommand, shellQuote } from "./pi-command.js";
21
22
  import { PiSessionPool, repositoryRootFrom } from "./pi-session-pool.js";
23
+ import { nativeToolArgs, nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, nativeToolExtensionPath, readNativeToolSettings } from "./native-tool-settings.js";
22
24
  import { describeDeliveredUserMessage, describePiQueue, handleSessionEvent, TurnQueue } from "./pi-session-events.js";
23
25
  import { LengthExceededError } from "./turn-failure.js";
24
26
  // The queue/steer recognisers live in pi-session-events.ts, where the SESSION path's bridge can use
@@ -166,6 +168,34 @@ export function killTree(pid) {
166
168
  killer.once("error", () => resolve());
167
169
  });
168
170
  }
171
+ /** Let Pi flush its extension shutdown hooks before using the process-tree backstop. */
172
+ export async function closePiWorker(child) {
173
+ const exited = () => child.exitCode !== null || child.signalCode !== null;
174
+ if (exited())
175
+ return;
176
+ const wait = (ms) => new Promise(resolve => {
177
+ const finish = () => { clearTimeout(timer); child.off("exit", finish); resolve(); };
178
+ const timer = setTimeout(finish, ms);
179
+ child.once("exit", finish);
180
+ if (exited())
181
+ finish();
182
+ });
183
+ child.stdin.end();
184
+ await wait(2000);
185
+ if (!exited() && child.pid !== undefined) {
186
+ if (process.platform === "win32")
187
+ await killTree(child.pid);
188
+ else {
189
+ try {
190
+ process.kill(-child.pid, "SIGKILL");
191
+ }
192
+ catch {
193
+ child.kill("SIGKILL");
194
+ }
195
+ }
196
+ await wait(2000);
197
+ }
198
+ }
169
199
  // Session-file mutation and validation live behind this boundary; runtime only locates Pi sessions.
170
200
  /** How long one command may take before the turn is failed rather than left hanging. */
171
201
  const SESSION_COMMAND_TIMEOUT_MS = 10_000;
@@ -335,6 +365,11 @@ export class PiRpcRuntime {
335
365
  sessionHosts = new Map();
336
366
  /** The sessions whose extension runner already has the UI bridge bound. */
337
367
  uiBoundSessions = new WeakSet();
368
+ backgroundUsageObservers = new Map();
369
+ backgroundUsageWrites = Promise.resolve();
370
+ cacheWarmingWrites = Promise.resolve();
371
+ cacheWarmingOverride;
372
+ cacheWarmingEpoch = 0;
338
373
  /**
339
374
  * The session-file path last reported for a conversation, so `onSessionFile` fires when it CHANGES
340
375
  * rather than once per turn. The path is stable for the life of a session; what changes it is a
@@ -491,6 +526,8 @@ export class PiRpcRuntime {
491
526
  // ABOUT that session and stop being true with it.
492
527
  this.sessionHosts.delete(conversationId);
493
528
  this.reportedSessionFiles.delete(conversationId);
529
+ this.backgroundUsageObservers.get(conversationId)?.();
530
+ this.backgroundUsageObservers.delete(conversationId);
494
531
  // The session held these credentials too, so they die with it.
495
532
  const tokens = this.sessionExtensionTokens.get(conversationId);
496
533
  if (tokens) {
@@ -550,6 +587,60 @@ export class PiRpcRuntime {
550
587
  await this.sessionPool.evict(conversationId);
551
588
  else
552
589
  await this.sessionPool.disposeAll();
590
+ await this.backgroundUsageWrites;
591
+ }
592
+ async cacheWarmingSettings() {
593
+ const mode = await piCacheWarmingMode();
594
+ const sessions = this.sessionPool.conversationIds.map(id => this.sessionPool.get(id)).filter(Boolean);
595
+ return { mode, liveSessions: sessions.length,
596
+ scheduled: sessions.filter(session => session?.cacheWarmingStatus?.state === "scheduled").length,
597
+ refreshing: sessions.filter(session => session?.cacheWarmingStatus?.state === "refreshing").length };
598
+ }
599
+ reloadNativeTools() { this.modelEpoch++; }
600
+ async setCacheWarming(mode) {
601
+ if (!isPiCacheWarmingMode(mode))
602
+ throw new Error("请选择有效的缓存预热模式。");
603
+ const update = this.cacheWarmingWrites.then(async () => {
604
+ await piCacheWarmingMode(mode);
605
+ this.cacheWarmingOverride = mode;
606
+ this.cacheWarmingEpoch++;
607
+ for (const id of this.sessionPool.conversationIds) {
608
+ const session = this.sessionPool.get(id);
609
+ session?.setCacheWarmingMode?.(mode);
610
+ await session?.settingsManager?.flush();
611
+ if (session?.settingsManager?.drainErrors?.().length)
612
+ throw new Error("Pi 会话缓存设置同步失败,请检查服务端目录权限。");
613
+ }
614
+ return this.cacheWarmingSettings();
615
+ });
616
+ this.cacheWarmingWrites = update.catch(() => undefined);
617
+ return update;
618
+ }
619
+ observeBackgroundUsage(conversationId, session) {
620
+ if (!this.options.onBackgroundUsage || this.backgroundUsageObservers.has(conversationId))
621
+ return;
622
+ const record = (value) => {
623
+ if (!value || typeof value !== "object")
624
+ return;
625
+ const entry = value;
626
+ if (entry.type !== "usage" || entry.kind !== "cache_warm" || !entry.id)
627
+ return;
628
+ const collector = new ConversationUsageCollector();
629
+ collector.add(entry.usage, false);
630
+ const readout = { ...collector.readout(undefined, session.model, defaultAgentDir()), sourceEntryId: entry.id };
631
+ if (!readout.usage)
632
+ return;
633
+ this.backgroundUsageWrites = this.backgroundUsageWrites.then(() => this.options.onBackgroundUsage(conversationId, readout))
634
+ .catch(() => { console.warn(`PiRpcRuntime: could not persist cache-warming usage for conversation ${conversationId}. It will be retried when the transcript is reopened.`); });
635
+ };
636
+ this.backgroundUsageObservers.set(conversationId, session.subscribe(event => {
637
+ const item = event;
638
+ if (item?.type === "entry_appended")
639
+ record(item.entry);
640
+ }));
641
+ // Reconcile persisted entries after restart or eviction. The store deduplicates by entry id.
642
+ for (const entry of session.sessionManager?.getEntries?.() ?? [])
643
+ record(entry);
553
644
  }
554
645
  /** Throws away the sessions that have been idle for a while. */
555
646
  async evictIdleSessions() {
@@ -798,9 +889,9 @@ export class PiRpcRuntime {
798
889
  // form the SDK takes. `toolSelection` is the shared translation, so an agent that declares
799
890
  // `tools: {"*": false, "read": true}` gets exactly the same tools here as it used to get on the
800
891
  // command line - including the empty allowlist that means "this agent talks and does not act".
801
- const selection = agent
892
+ const selection = nativeToolPolicy(agent
802
893
  ? toolSelection(agent.tools, { extraAllowedTools: this.extensionToolNames() })
803
- : {};
894
+ : {}, readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
804
895
  const systemPromptFile = agent ? await writeAgentPrompt(this.agents.promptDir, agent) : undefined;
805
896
  return {
806
897
  ...(selection.tools ? { tools: selection.tools } : {}),
@@ -822,6 +913,7 @@ export class PiRpcRuntime {
822
913
  // exists even when the build fails - a test that wants to know what Super Pi INTENDED to give Pi
823
914
  // must be able to ask after a failure too.
824
915
  this.builtSessions.set(conversation.id, configuration);
916
+ const cacheWarmingEpoch = this.cacheWarmingEpoch;
825
917
  const session = await this.sessionPool.acquire({
826
918
  conversationId: conversation.id,
827
919
  cwd: resolve(cwd),
@@ -836,6 +928,10 @@ export class PiRpcRuntime {
836
928
  ...(configuration.thinkingLevel ? { thinkingLevel: configuration.thinkingLevel } : {}),
837
929
  });
838
930
  traceLatency(conversation.id, "session.acquired", latencyStartedAt);
931
+ // A session may finish building while a settings update is visiting the pool.
932
+ if (this.cacheWarmingOverride && cacheWarmingEpoch !== this.cacheWarmingEpoch)
933
+ session.setCacheWarmingMode?.(this.cacheWarmingOverride);
934
+ this.observeBackgroundUsage(conversation.id, session);
839
935
  // THE SESSION-FILE LOCATOR. `revert` and `fork` open the conversation's transcript by PATH, and the
840
936
  // path is a fact the session already knows: its SessionManager resolves it at creation, before any
841
937
  // byte is written. Reported when it CHANGES rather than once per turn - the path is stable for the
@@ -857,15 +953,6 @@ export class PiRpcRuntime {
857
953
  // `undefined`/`false` - and for `confirm` a silent `false` is a fabricated "no" the user never gave.
858
954
  // The bridge forwards to the host of whichever turn is running RIGHT NOW (registered below), and
859
955
  // answers `cancelled` when there is none - the same rule the RPC path's no-host branch follows.
860
- if (session.extensionRunner && !this.uiBoundSessions.has(session)) {
861
- this.uiBoundSessions.add(session);
862
- try {
863
- session.extensionRunner.setUIContext(this.extensionUiBridge(conversation.id), "rpc");
864
- }
865
- catch (error) {
866
- console.warn(`PiRpcRuntime: could not bind the extension UI bridge for conversation ${conversation.id}: ${error instanceof Error ? error.message : "unknown error"}. Pi extensions that ask questions will get cancelled answers.`);
867
- }
868
- }
869
956
  if (input.host)
870
957
  this.sessionHosts.set(conversation.id, input.host);
871
958
  // WHERE THIS TURN STARTS in Pi's own transcript, captured BEFORE the prompt. The one-shot path asked
@@ -913,6 +1000,8 @@ export class PiRpcRuntime {
913
1000
  const unsubscribe = session.subscribe((event) => {
914
1001
  try {
915
1002
  const record = event;
1003
+ if (record?.type === "entry_appended")
1004
+ return; // Persisted background usage has its own lifecycle observer.
916
1005
  if (record?.type === "message_end" && record.message?.role === "assistant")
917
1006
  usage.add(record.message.usage);
918
1007
  handleSessionEvent(event, queue, handlers, report, failure);
@@ -967,16 +1056,49 @@ export class PiRpcRuntime {
967
1056
  const promptFinished = new Promise((resolvePromise) => { markPromptFinished = resolvePromise; });
968
1057
  const finished = (async () => {
969
1058
  try {
970
- let promptAccepted = false;
1059
+ if (!this.uiBoundSessions.has(session)) {
1060
+ const uiContext = this.extensionUiBridge(conversation.id);
1061
+ if (session.bindExtensions) {
1062
+ let binding = true;
1063
+ let startupFailure;
1064
+ try {
1065
+ await session.bindExtensions({ uiContext, mode: "rpc", onError: error => {
1066
+ const failure = new Error(`Pi 扩展 ${basename(error.extensionPath)} 在 ${error.event} 中执行失败,请检查扩展配置。`);
1067
+ console.warn(failure.message);
1068
+ if (binding) {
1069
+ startupFailure = failure;
1070
+ return;
1071
+ }
1072
+ if (this.sessionPool.get(conversation.id) !== session)
1073
+ return;
1074
+ this.activeTurns.get(conversation.id)?.queue.fail(failure);
1075
+ void session.abort().catch(() => undefined);
1076
+ } });
1077
+ if (startupFailure)
1078
+ throw startupFailure;
1079
+ }
1080
+ catch (error) {
1081
+ await this.disposeSessions(conversation.id);
1082
+ throw error;
1083
+ }
1084
+ finally {
1085
+ binding = false;
1086
+ }
1087
+ }
1088
+ else
1089
+ session.extensionRunner?.setUIContext(uiContext, "rpc");
1090
+ this.uiBoundSessions.add(session);
1091
+ }
1092
+ let preflight;
971
1093
  const imagePayloads = this.options.uploadsDir && images?.length
972
1094
  ? await loadConversationImages(this.options.uploadsDir, conversation.id, images)
973
1095
  : undefined;
974
1096
  const promptOptions = {
975
1097
  ...(imagePayloads?.length ? { images: imagePayloads } : {}),
976
- preflightResult: (success) => {
977
- if (!success)
1098
+ preflightResult: (result) => {
1099
+ preflight = result;
1100
+ if (result !== "started")
978
1101
  return;
979
- promptAccepted = true;
980
1102
  traceLatency(conversation.id, "session.prompt.accepted", latencyStartedAt, promptSize());
981
1103
  // Pi calls this hook immediately BEFORE _runAgentPrompt synchronously marks the run
982
1104
  // active. An abort during before_agent_start can have returned while Pi was idle. Repeat
@@ -1011,11 +1133,11 @@ export class PiRpcRuntime {
1011
1133
  }
1012
1134
  await session.prompt(prompt, promptOptions);
1013
1135
  markPromptFinished();
1014
- // Pi 0.86's prompt() awaits the whole agent run. Input hooks and extension commands can also
1136
+ // Pi's prompt() awaits the whole agent run. Input hooks and extension commands can also
1015
1137
  // handle it without starting a run, in which case no agent_settled event is emitted. Pi's idle
1016
1138
  // flag distinguishes that legitimate completion from an asynchronous session adapter whose
1017
1139
  // prompt promise returns before its stream finishes.
1018
- if (promptAccepted && session.isIdle === true && !queue.isSettled)
1140
+ if ((preflight === "handled" || (preflight === "started" && session.isIdle === true)) && !queue.isSettled)
1019
1141
  queue.push({ kind: "end" });
1020
1142
  // Drain every queued callback and delta before releasing this turn, even if Pi already went
1021
1143
  // idle. An adapter that returns early must still provide the authoritative settled event.
@@ -1497,9 +1619,14 @@ export class PiRpcRuntime {
1497
1619
  if (!this.pi.found)
1498
1620
  throw new Error(this.pi.reason);
1499
1621
  // npm exposes global CLIs as .cmd shims on Windows; Node requires a shell to launch those shims.
1500
- const providerProxyEnv = await readProviderProxyEnv(defaultAgentDir(), conversation.model?.provider);
1501
- const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", this.sessionDir, "--session-id", conversation.id, ...extensionArgs, ...memoryArgs, ...knowledgeArgs, ...documentArgs, ...webArgs, ...feishuArgs, ...agentArgs], {
1622
+ const nativePolicy = nativeToolPolicy(toolSelection(agent?.tools), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
1623
+ const useNativeTools = !memoryReview && !knowledgeRerank;
1624
+ if (useNativeTools && nativePolicy.excludeTools?.length)
1625
+ agentArgs.push("--exclude-tools", nativePolicy.excludeTools.join(","));
1626
+ const providerProxyEnv = { ...await readProviderProxyEnv(defaultAgentDir(), conversation.model?.provider), ...(useNativeTools ? nativeToolEnv(this.sessionDir, nativePolicy) : {}) };
1627
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", this.sessionDir, "--session-id", conversation.id, ...(useNativeTools ? ["--no-mcp", "--extension", nativeToolExtensionPath()] : []), ...extensionArgs, ...memoryArgs, ...knowledgeArgs, ...documentArgs, ...webArgs, ...feishuArgs, ...agentArgs], {
1502
1628
  cwd: childCwd,
1629
+ detached: process.platform !== "win32",
1503
1630
  stdio: ["pipe", "pipe", "pipe"],
1504
1631
  shell: process.platform === "win32",
1505
1632
  // `env` is passed ONLY when the extension is mounted, because passing `{ ...process.env }` on
@@ -1980,16 +2107,7 @@ export class PiRpcRuntime {
1980
2107
  // precedes the `exit` subscription, so an exit that lands between them is dropped and the promise
1981
2108
  // never settles. Unbounded, that hangs the turn that asked for it. See readCatalog() for the
1982
2109
  // measurement.
1983
- if (child.exitCode === null && child.pid !== undefined) {
1984
- if (!child.killed) {
1985
- if (process.platform === "win32")
1986
- await killTree(child.pid);
1987
- else
1988
- child.kill();
1989
- }
1990
- if (child.exitCode === null)
1991
- await new Promise((resolve) => { child.once("exit", resolve); setTimeout(resolve, 5000); });
1992
- }
2110
+ await closePiWorker(child);
1993
2111
  }
1994
2112
  }
1995
2113
  /**
@@ -2100,6 +2218,8 @@ export class PiRpcRuntime {
2100
2218
  async revert({ conversation, cwd, boundaryEntryId, beforeBoundary }) {
2101
2219
  if (this.runs.has(conversation.id) || this.activeTurns.has(conversation.id))
2102
2220
  throw new Error("这个会话还有一轮任务在跑,先停止它再回退");
2221
+ // Stop idle cache writes and finish accounting before rewriting the transcript.
2222
+ await this.disposeSessions(conversation.id);
2103
2223
  if (!this.pi.found)
2104
2224
  throw new Error(this.pi.reason);
2105
2225
  // Normal path: this exact worker already asked Pi for get_state before its prompt was sent, so reuse
@@ -2144,7 +2264,7 @@ export class PiRpcRuntime {
2144
2264
  // `SessionManager._persist` only creates a file once a session holds a message
2145
2265
  // (`session-manager.ts:1160-1170`), so an answer to `get_state` cannot write anything. Adding the
2146
2266
  // task extension here would mount a tool whose every call fails, since no endpoint is wired up.
2147
- const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", this.sessionDir, "--session-id", conversation.id], {
2267
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", this.sessionDir, "--session-id", conversation.id], {
2148
2268
  cwd: childCwd,
2149
2269
  stdio: ["pipe", "pipe", "pipe"],
2150
2270
  shell: process.platform === "win32",
@@ -2226,8 +2346,9 @@ export class PiRpcRuntime {
2226
2346
  * and copying that into a second conversation would make the disagreement permanent and multiply it.
2227
2347
  */
2228
2348
  async fork({ conversation, cwd, forkedConversationId }) {
2229
- if (this.runs.has(conversation.id))
2349
+ if (this.runs.has(conversation.id) || this.activeTurns.has(conversation.id))
2230
2350
  throw new Error("这个会话还有一轮任务在跑,先停止它再分叉");
2351
+ await this.disposeSessions(conversation.id);
2231
2352
  if (!conversation.messages.length)
2232
2353
  return { entriesCopied: 0 };
2233
2354
  if (!this.pi.found)
@@ -2237,7 +2358,7 @@ export class PiRpcRuntime {
2237
2358
  const cached = conversation.piSessionFile;
2238
2359
  if (cached && (await stat(cached).catch(() => undefined))?.isFile()) {
2239
2360
  const result = await forkSessionFile(cached, target, conversation.id, forkedConversationId);
2240
- return { sessionFile: target, entriesCopied: result.entriesCopied };
2361
+ return { sessionFile: target, ...result };
2241
2362
  }
2242
2363
  const childCwd = resolve(cwd);
2243
2364
  const info = await stat(childCwd).catch(() => undefined);
@@ -2252,11 +2373,11 @@ export class PiRpcRuntime {
2252
2373
  if (!found?.isFile())
2253
2374
  return { entriesCopied: 0 };
2254
2375
  const copied = await forkSessionFile(resolved, target, conversation.id, forkedConversationId);
2255
- return { sessionFile: target, entriesCopied: copied.entriesCopied };
2376
+ return { sessionFile: target, ...copied };
2256
2377
  }
2257
2378
  // The same lookup spawn as `revert`, and the same reason for leaving the agent flags off: this child
2258
2379
  // sends no prompt and must leave nothing behind.
2259
- const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", this.sessionDir, "--session-id", conversation.id], {
2380
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", this.sessionDir, "--session-id", conversation.id], {
2260
2381
  cwd: childCwd,
2261
2382
  stdio: ["pipe", "pipe", "pipe"],
2262
2383
  shell: process.platform === "win32",
@@ -2297,7 +2418,7 @@ export class PiRpcRuntime {
2297
2418
  // while the filename carries when this copy was made, which is what makes the ordering of a directory
2298
2419
  // full of forks mean anything.
2299
2420
  const result = await forkSessionFile(sessionFile, target, conversation.id, forkedConversationId);
2300
- return { sessionFile: target, entriesCopied: result.entriesCopied };
2421
+ return { sessionFile: target, ...result };
2301
2422
  }
2302
2423
  /**
2303
2424
  * Delivers one Extension UI request. One-way methods are pushed to the host and never replied to
@@ -2424,7 +2545,7 @@ export class PiRpcRuntime {
2424
2545
  const MAX_TITLE_CHARS = 18;
2425
2546
  // A throwaway session id, not the conversation's: this child reads nothing else and its history must
2426
2547
  // not be filed under the conversation whose title it is producing.
2427
- const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", this.sessionDir, "--session-id", `autotitle-${randomUUID()}`], {
2548
+ const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", this.sessionDir, "--session-id", `autotitle-${randomUUID()}`], {
2428
2549
  cwd: resolve(cwd),
2429
2550
  env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir()) },
2430
2551
  stdio: ["pipe", "pipe", "pipe"],
@@ -2501,12 +2622,12 @@ export class PiRpcRuntime {
2501
2622
  async askOnce(input) {
2502
2623
  if (!this.pi.found)
2503
2624
  throw new Error(this.pi.reason);
2504
- const args = ["--mode", "rpc", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates"];
2625
+ const args = ["--mode", "rpc", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-mcp"];
2626
+ let nativeEnv = {};
2505
2627
  if (input.agent && input.onToolStart) {
2506
- const nativeTools = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
2507
- const selection = toolSelection(input.agent.tools);
2508
- const allowed = nativeTools.filter(name => (selection.tools ?? nativeTools).includes(name) && !selection.excludeTools?.includes(name));
2509
- args.push(...(allowed.length ? ["--tools", allowed.join(",")] : ["--no-tools"]));
2628
+ const selection = nativeToolPolicy(toolSelection(input.agent.tools), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
2629
+ args.push("--extension", nativeToolExtensionPath(), ...nativeToolArgs(selection));
2630
+ nativeEnv = nativeToolEnv(this.sessionDir, selection);
2510
2631
  }
2511
2632
  else
2512
2633
  args.push("--no-tools", "--no-context-files");
@@ -2516,7 +2637,7 @@ export class PiRpcRuntime {
2516
2637
  input.signal?.throwIfAborted();
2517
2638
  const child = spawn(shellQuote(this.pi.command), args.map(arg => shellQuote(arg)), {
2518
2639
  cwd: resolve(input.cwd),
2519
- env: { ...process.env, ...proxyEnv },
2640
+ env: { ...process.env, ...proxyEnv, ...nativeEnv },
2520
2641
  stdio: ["pipe", "pipe", "pipe"],
2521
2642
  shell: process.platform === "win32",
2522
2643
  detached: process.platform !== "win32",
@@ -2608,21 +2729,7 @@ export class PiRpcRuntime {
2608
2729
  return text;
2609
2730
  }
2610
2731
  finally {
2611
- if (child.pid !== undefined) {
2612
- if (process.platform === "win32") {
2613
- if (child.exitCode === null)
2614
- await killTree(child.pid);
2615
- }
2616
- else {
2617
- try {
2618
- process.kill(-child.pid, "SIGKILL");
2619
- }
2620
- catch (error) {
2621
- if (error.code !== "ESRCH")
2622
- throw error;
2623
- }
2624
- }
2625
- }
2732
+ await closePiWorker(child);
2626
2733
  }
2627
2734
  }
2628
2735
  /**
@@ -3008,7 +3115,7 @@ export class PiRpcRuntime {
3008
3115
  return unavailable(this.pi.reason);
3009
3116
  let child;
3010
3117
  try {
3011
- child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--session-dir", directory, "--session-id", "catalog"], { cwd: directory, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32" });
3118
+ child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--session-dir", directory, "--session-id", "catalog"], { cwd: directory, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32" });
3012
3119
  if (process.env.SUPER_PI_TRACE_LATENCY === "1")
3013
3120
  console.warn(`[super-pi latency] catalog key=${key} phase=catalog.spawned pid=${child.pid ?? "unknown"}`);
3014
3121
  }
@@ -96,4 +96,5 @@ export declare function truncateSessionFile(path: string, boundaryEntryId: strin
96
96
  */
97
97
  export declare function forkSessionFile(sourcePath: string, targetPath: string, expectedSessionId: string, targetSessionId: string): Promise<{
98
98
  entriesCopied: number;
99
+ inheritedUsageEntryIds?: string[];
99
100
  }>;
@@ -241,5 +241,6 @@ export async function forkSessionFile(sourcePath, targetPath, expectedSessionId,
241
241
  if (verified.length !== lines.length || verifiedHeader?.id !== targetSessionId) {
242
242
  throw new Error(`写入后的 Pi 会话文件不是预期的样子(写到 ${verified.length} 行,期望 ${lines.length} 行,header id=${JSON.stringify(verifiedHeader?.id ?? null)},期望 ${JSON.stringify(targetSessionId)})。已放弃,没有创建任何会话。`);
243
243
  }
244
- return { entriesCopied: lines.length - 1 };
244
+ const inheritedUsageEntryIds = parsed.flatMap(entry => entry?.type === "usage" && entry.kind === "cache_warm" && typeof entry.id === "string" ? [entry.id] : []);
245
+ return { entriesCopied: lines.length - 1, ...(inheritedUsageEntryIds.length ? { inheritedUsageEntryIds } : {}) };
245
246
  }
@@ -389,6 +389,7 @@ export declare class Store {
389
389
  parentConversationId?: string;
390
390
  warmTitle?: string;
391
391
  piSessionFile?: string;
392
+ inheritedUsageEntryIds?: string[];
392
393
  }): Promise<Conversation>;
393
394
  /**
394
395
  * Archive is a marker, not a move: the conversation keeps its id, workspace, messages and position.
@@ -1310,7 +1310,7 @@ export class Store {
1310
1310
  const closed = new Set(this.state.workspaces.filter((item) => item.closedAt).map((item) => item.id));
1311
1311
  const workspaces = this.state.workspaces.filter((item) => !closed.has(item.id));
1312
1312
  const visible = this.state.conversations.filter((item) => !closed.has(item.workspaceId) && !item.warmSession)
1313
- .map(({ acceptedSendIds: _accepted, ...conversation }) => conversation);
1313
+ .map(({ acceptedSendIds: _accepted, accountedPiUsageEntries: _piUsage, ...conversation }) => conversation);
1314
1314
  const warmSessions = workspaces.flatMap((workspace) => this.listWarmSessions(workspace.id));
1315
1315
  const presets = warmSessions.length ? { warmSessions } : {};
1316
1316
  const openEscalations = this.openEscalationAudiences();
@@ -1591,6 +1591,7 @@ export class Store {
1591
1591
  ...(parent ? { parentConversationId: parent.id, origin: "orchestrator" } : {}),
1592
1592
  ...(options.warmTitle ? { warmSession: true, archivedAt: now() } : {}),
1593
1593
  ...(options.piSessionFile ? { piSessionFile: options.piSessionFile } : {}),
1594
+ ...(options.inheritedUsageEntryIds?.length ? { accountedPiUsageEntries: [...new Set(options.inheritedUsageEntryIds)] } : {}),
1594
1595
  title: options.warmTitle ?? source.title,
1595
1596
  workspaceId: source.workspaceId,
1596
1597
  updatedAt: now(),
@@ -2484,6 +2485,13 @@ export class Store {
2484
2485
  /** Commit once at turn end; metadata transactions work for both JSON and SQLite repositories. */
2485
2486
  async recordConversationUsage(conversationId, readout) {
2486
2487
  const conversation = this.requireConversation(conversationId);
2488
+ if (readout.sourceEntryId) {
2489
+ if (conversation.accountedPiUsageEntries?.includes(readout.sourceEntryId))
2490
+ return;
2491
+ if (!readout.usage)
2492
+ return;
2493
+ (conversation.accountedPiUsageEntries ??= []).push(readout.sourceEntryId);
2494
+ }
2487
2495
  if (readout.usage) {
2488
2496
  const previous = conversation.usage;
2489
2497
  const total = { ...readout.usage };
@@ -2495,7 +2503,7 @@ export class Store {
2495
2503
  }
2496
2504
  if (readout.contextUsage)
2497
2505
  conversation.contextUsage = { ...readout.contextUsage };
2498
- else
2506
+ else if (!readout.sourceEntryId)
2499
2507
  delete conversation.contextUsage;
2500
2508
  if (readout.usage || readout.contextUsage)
2501
2509
  conversation.usageUpdatedAt = now();
@@ -2,9 +2,10 @@ import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { mkdir, stat } from "node:fs/promises";
4
4
  import { join, resolve } from "node:path";
5
- import { agentSpawnArgs, readAgents } from "./agents.js";
5
+ import { agentSpawnArgs, readAgents, toolSelection } from "./agents.js";
6
+ import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, nativeToolExtensionPath, readNativeToolSettings } from "./native-tool-settings.js";
6
7
  import { resolvePiCommand, shellQuote } from "./pi-command.js";
7
- import { buildExtensionUiResponse, describeExtensionUiRequest, killTree, } from "./runtime.js";
8
+ import { buildExtensionUiResponse, describeExtensionUiRequest, closePiWorker, } from "./runtime.js";
8
9
  import { RpcChannel } from "./rpc-channel.js";
9
10
  import { InlineThinkingSplitter, stripInlineThinking } from "./inline-thinking.js";
10
11
  import { describeToolCall, extractPartialResultText, TOOL_DETAIL_CAP } from "./tool-calls.js";
@@ -250,10 +251,13 @@ export class SubagentSupervisor {
250
251
  // ALLOWLIST - see `SubagentRunInput.denyTools` for why that asymmetry is the reference's too.
251
252
  const memoryEnabled = this.memory ? (await this.memory.configuration()).enabled : false;
252
253
  const agentArgs = await agentSpawnArgs(this.agents.promptDir, agent, { denyTools: input.denyTools ?? [], extraAllowedTools: memoryEnabled ? ["memory", "skill_manage", "session_search"] : [] });
254
+ const nativePolicy = nativeToolPolicy(toolSelection(agent.tools, { denyTools: input.denyTools ?? [], extraAllowedTools: memoryEnabled ? ["memory", "skill_manage", "session_search"] : [] }), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
255
+ if (nativePolicy.excludeTools?.length)
256
+ agentArgs.push("--exclude-tools", nativePolicy.excludeTools.join(","));
253
257
  const sessionDirectory = join(this.sessionDir, "subagents");
254
258
  await mkdir(sessionDirectory, { recursive: true });
255
259
  const memoryToken = memoryEnabled ? this.memory.issue(conversationId, { readOnly: true, agentId }) : undefined;
256
- const args = ["--mode", "rpc", "--session-dir", sessionDirectory, "--session-id", id, ...(memoryToken ? ["--extension", resolve(import.meta.dirname, "../../agents/super-pi-memory/index.ts")] : []), ...agentArgs];
260
+ const args = ["--mode", "rpc", "--no-mcp", "--extension", nativeToolExtensionPath(), "--session-dir", sessionDirectory, "--session-id", id, ...(memoryToken ? ["--extension", resolve(import.meta.dirname, "../../agents/super-pi-memory/index.ts")] : []), ...agentArgs];
257
261
  // Model inheritance: the definition wins, otherwise the parent's current model, otherwise Pi's own
258
262
  // default. "Omit the model and get what the parent is running on" is the default worth having, and it
259
263
  // is a spawn-time flag because there is no RPC command to change it later.
@@ -273,7 +277,7 @@ export class SubagentSupervisor {
273
277
  throw new SubagentCancelled(id);
274
278
  }
275
279
  // npm exposes global CLIs as .cmd shims on Windows; Node requires a shell to launch those shims.
276
- const child = spawn(shellQuote(this.pi.command), args, { cwd: childCwd, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32", ...(memoryToken ? { env: { ...process.env, SUPER_PI_MEMORY_ENDPOINT: process.env.SUPER_PI_MEMORY_ENDPOINT, SUPER_PI_MEMORY_TOKEN: memoryToken, SUPER_PI_MEMORY_READ_ONLY: "1" } } : {}) });
280
+ const child = spawn(shellQuote(this.pi.command), args, { cwd: childCwd, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32", env: { ...process.env, ...nativeToolEnv(this.sessionDir, nativePolicy), ...(memoryToken ? { SUPER_PI_MEMORY_ENDPOINT: process.env.SUPER_PI_MEMORY_ENDPOINT, SUPER_PI_MEMORY_TOKEN: memoryToken, SUPER_PI_MEMORY_READ_ONLY: "1" } : {}) } });
277
281
  if (memoryToken)
278
282
  child.once("close", () => this.memory?.release(memoryToken));
279
283
  this.children.set(id, { conversationId, child });
@@ -594,24 +598,7 @@ export class SubagentSupervisor {
594
598
  // The run is not over until the child is actually gone: a process still tearing down still holds a
595
599
  // lock on its working directory, so a caller that removes that directory the moment run() settles
596
600
  // would hit EBUSY on Windows.
597
- if (child.exitCode === null && child.pid !== undefined) {
598
- if (!child.killed) {
599
- // The TREE, never the shim: Super Pi spawns pi.cmd through a .cmd shim with shell:true, so the
600
- // direct child is cmd.exe and the real Pi is its grandchild. Killing only the shim leaks a Pi
601
- // that keeps holding the workspace directory, which is the failure this exact call already had
602
- // to be written for on the primary agent's side.
603
- if (process.platform === "win32")
604
- await killTree(child.pid);
605
- else
606
- child.kill();
607
- }
608
- if (child.exitCode === null) {
609
- // The 5s backstop matches the primary agent's side (runtime.ts answer() / readCatalog()): the
610
- // kill precedes this subscription, so an exit landing in between is dropped and the promise
611
- // would never settle - hanging the sub-agent run instead of ending it.
612
- await new Promise((resolve) => { child.once("exit", resolve); setTimeout(resolve, 5000); });
613
- }
614
- }
601
+ await closePiWorker(child);
615
602
  }
616
603
  }
617
604
  /**
@@ -70,6 +70,18 @@ const MINIMAX_FLASH_LEVELS = {
70
70
  xhigh: "xhigh",
71
71
  max: "max",
72
72
  };
73
+ const KIMI_K31_PRO_MODEL = "kimi-k3.1-pro";
74
+ const KIMI_API_ORIGINS = new Set(["https://api.moonshot.ai", "https://api.moonshot.cn"]);
75
+ const KIMI_API_PATHS = new Set(["", "/v1", "/v1/models"]);
76
+ const KIMI_K31_PRO_LEVELS = {
77
+ off: null,
78
+ minimal: null,
79
+ low: "low",
80
+ medium: null,
81
+ high: "high",
82
+ xhigh: null,
83
+ max: "max",
84
+ };
73
85
  /**
74
86
  * The official endpoint, or undefined.
75
87
  *
@@ -89,6 +101,15 @@ function officialMinimaxEndpoint(baseUrl) {
89
101
  return false;
90
102
  }
91
103
  }
104
+ function officialKimiEndpoint(baseUrl) {
105
+ try {
106
+ const parsed = new URL(baseUrl.trim());
107
+ return KIMI_API_ORIGINS.has(parsed.origin) && KIMI_API_PATHS.has(parsed.pathname.replace(/\/+$/, ""));
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
92
113
  /**
93
114
  * The levels a provider DECLARED for a model, when it declared them properly.
94
115
  *
@@ -148,11 +169,14 @@ export function discoverThinkingLevels(entry, context) {
148
169
  const declared = declaredLevels(entry);
149
170
  if (declared)
150
171
  return declared;
172
+ const id = typeof entry.id === "string" ? entry.id.trim().toLowerCase() : "";
173
+ if (id === KIMI_K31_PRO_MODEL && officialKimiEndpoint(context.baseUrl)) {
174
+ return { ...KIMI_K31_PRO_LEVELS };
175
+ }
151
176
  // THE OFFICIAL MINIMAX ENDPOINT, AND ONLY THAT ONE - the origin and the path both, because a map
152
177
  // is only true of the endpoint it was learned from.
153
178
  if (!officialMinimaxEndpoint(context.baseUrl))
154
179
  return undefined;
155
- const id = typeof entry.id === "string" ? entry.id.trim().toLowerCase() : "";
156
180
  if (id !== MINIMAX_FLASH_MODEL)
157
181
  return undefined;
158
182
  return { ...MINIMAX_FLASH_LEVELS };
@@ -509,6 +509,8 @@ export type Conversation = {
509
509
  usage?: SubagentUsage;
510
510
  /** False means cost is only a sum of reported costs, not a complete price (zero is not "free"). */
511
511
  usageCostKnown?: boolean;
512
+ /** Persisted Pi cache-warming entry ids, for replay-safe background accounting. */
513
+ accountedPiUsageEntries?: string[];
512
514
  contextUsage?: ConversationContextUsage;
513
515
  usageUpdatedAt?: string;
514
516
  /** Transport projection only: false means messages were omitted, rather than an empty transcript. */
@@ -1,3 +1,4 @@
1
+ import { type SessionDisplayState } from "./session-reporting.js";
1
2
  export type GroupModel = {
2
3
  provider: string;
3
4
  modelId: string;
@@ -83,7 +84,9 @@ export type GroupMessage = GroupUserPost | GroupReply;
83
84
  export type GroupActivity = {
84
85
  status: "idle" | "running" | "awaiting_background" | "completed" | "failed";
85
86
  revision: number;
87
+ lastReplyAt?: string;
86
88
  };
89
+ export declare function groupDisplayState(activity: GroupActivity, readAt?: string): SessionDisplayState;
87
90
  export type GroupActivityUpdate = {
88
91
  id: string;
89
92
  workspaceId: string;
@@ -1 +1,6 @@
1
+ import { deriveSessionState } from "./session-reporting.js";
1
2
  export const DEFAULT_GROUP_MEMBER_IDS = ["solution-designer", "code-designer", "code-auditor", "document-organizer"];
3
+ export function groupDisplayState(activity, readAt) {
4
+ return deriveSessionState({ status: activity.status, quietWhenRead: true,
5
+ reportingState: activity.lastReplyAt && activity.lastReplyAt > (readAt ?? "") ? "unread" : null });
6
+ }