@evandu/super-pi 0.1.280 → 0.1.282
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/rsi-discussion.md +21 -0
- package/agents/rsi-repair.md +33 -0
- package/agents/super-pi-model-policy/index.ts +1 -0
- package/desktop/preload.cjs +1 -1
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +25 -16
- package/dist/client/assets/{CodeMirrorEditor-D-UuYizz.js → CodeMirrorEditor-Y4BbFnPe.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-Bt1n2la-.js → GitDiffEditor-BhUOinn3.js} +1 -1
- package/dist/client/assets/index-CMb8f0dS.css +1 -0
- package/dist/client/assets/index-DGnOud6x.js +350 -0
- package/dist/client/index.html +2 -2
- package/dist/server/application/conversation-service.js +4 -0
- package/dist/server/application/group-chat-service.d.ts +8 -0
- package/dist/server/application/group-chat-service.js +13 -4
- package/dist/server/application/group-execution.d.ts +1 -0
- package/dist/server/application/group-execution.js +18 -0
- package/dist/server/application/group-rsi.d.ts +9 -0
- package/dist/server/application/group-rsi.js +19 -6
- package/dist/server/application/provider-service.d.ts +27 -11
- package/dist/server/application/provider-service.js +78 -10
- package/dist/server/application/rsi-repairs.d.ts +27 -0
- package/dist/server/application/rsi-repairs.js +201 -0
- package/dist/server/application/rsi-service.d.ts +6 -0
- package/dist/server/application/rsi-service.js +105 -17
- package/dist/server/application/run-service.d.ts +3 -0
- package/dist/server/application/run-service.js +79 -5
- package/dist/server/bounded-compaction.d.ts +12 -0
- package/dist/server/bounded-compaction.js +34 -0
- package/dist/server/command-handler.js +10 -0
- package/dist/server/conversation-usage.d.ts +6 -1
- package/dist/server/conversation-usage.js +2 -2
- package/dist/server/hierarchical-compaction.d.ts +1 -0
- package/dist/server/hierarchical-compaction.js +115 -0
- package/dist/server/http-server.js +23 -0
- package/dist/server/index.js +39 -0
- package/dist/server/length-continuation.js +1 -1
- package/dist/server/model-capabilities.d.ts +6 -0
- package/dist/server/model-capabilities.js +57 -0
- package/dist/server/model-discovery.d.ts +44 -0
- package/dist/server/model-discovery.js +139 -0
- package/dist/server/model-policy-extension.d.ts +3 -0
- package/dist/server/model-policy-extension.js +82 -0
- package/dist/server/model-request-policy.d.ts +2 -0
- package/dist/server/model-request-policy.js +30 -0
- package/dist/server/pi-session-events.d.ts +2 -0
- package/dist/server/pi-session-events.js +10 -0
- package/dist/server/pi-session.d.ts +39 -2
- package/dist/server/pi-session.js +39 -1
- package/dist/server/provider-proxy.d.ts +2 -0
- package/dist/server/provider-proxy.js +8 -3
- package/dist/server/providers.d.ts +6 -0
- package/dist/server/providers.js +76 -10
- package/dist/server/rsi-http.js +6 -3
- package/dist/server/runtime.d.ts +13 -0
- package/dist/server/runtime.js +201 -13
- package/dist/server/store.d.ts +2 -0
- package/dist/server/store.js +17 -1
- package/dist/server/subagents.js +2 -1
- package/dist/server/thinking-level-discovery.d.ts +6 -0
- package/dist/server/thinking-level-discovery.js +10 -3
- package/dist/server/turn-failure.js +3 -1
- package/dist/server/types.d.ts +13 -0
- package/dist/server/ws-server.js +1 -1
- package/dist/shared/context-compaction.d.ts +15 -0
- package/dist/shared/context-compaction.js +14 -0
- package/dist/shared/context-meter.d.ts +22 -0
- package/dist/shared/context-meter.js +9 -0
- package/dist/shared/group-chat.d.ts +8 -0
- package/dist/shared/model-discovery.d.ts +15 -0
- package/dist/shared/model-discovery.js +1 -0
- package/dist/shared/rsi.d.ts +33 -0
- package/dist/shared/tab-layout.d.ts +12 -0
- package/dist/shared/tab-layout.js +28 -0
- package/package.json +11 -1
- package/dist/client/assets/index-B5TLGyEw.css +0 -1
- package/dist/client/assets/index-rWE1xu-t.js +0 -350
package/dist/server/providers.js
CHANGED
|
@@ -283,6 +283,8 @@ export class ProviderRegistry {
|
|
|
283
283
|
this.dataDir = dataDir;
|
|
284
284
|
this.piDir = piDir;
|
|
285
285
|
}
|
|
286
|
+
get discoveryPath() { return join(this.dataDir, "model-discovery.json"); }
|
|
287
|
+
get agentDir() { return this.piDir; }
|
|
286
288
|
networkQueue = Promise.resolve();
|
|
287
289
|
async sharedNetworkRecord(known) {
|
|
288
290
|
const saved = await readSharedProviderProxy(this.piDir);
|
|
@@ -671,6 +673,23 @@ export class ProviderRegistry {
|
|
|
671
673
|
await writeJsonAtomic(modelsPath, { ...existing, providers: mergedProviders });
|
|
672
674
|
await this.applyKeysToPi(previous, next);
|
|
673
675
|
}
|
|
676
|
+
/** Append discovery results without normalizing any existing model or touching auth.json. */
|
|
677
|
+
async appendDiscovered(provider, models) {
|
|
678
|
+
const path = piModelsPath(this.piDir);
|
|
679
|
+
const existing = await readJsonFile(path);
|
|
680
|
+
const entry = existing?.providers?.[provider.id];
|
|
681
|
+
if (!entry || typeof entry !== "object")
|
|
682
|
+
throw new Error("供应商配置已改变,放弃本次自动导入。");
|
|
683
|
+
const additions = toPiProvider({ ...provider, models }).models;
|
|
684
|
+
const updated = { ...entry, models: [...(Array.isArray(entry.models) ? entry.models : []), ...additions] };
|
|
685
|
+
await writeJsonAtomic(path, { ...existing, providers: { ...existing?.providers, [provider.id]: updated } });
|
|
686
|
+
return async () => {
|
|
687
|
+
const current = await readJsonFile(path);
|
|
688
|
+
if (JSON.stringify(current.providers?.[provider.id]) !== JSON.stringify(updated))
|
|
689
|
+
throw new Error("模型配置已被外部修改,拒绝覆盖。");
|
|
690
|
+
await writeJsonAtomic(path, { ...current, providers: { ...current.providers, [provider.id]: entry } });
|
|
691
|
+
};
|
|
692
|
+
}
|
|
674
693
|
/**
|
|
675
694
|
* Writes the keys into Pi's `auth.json`.
|
|
676
695
|
*/
|
|
@@ -851,18 +870,31 @@ export async function fetchRemoteModels(input) {
|
|
|
851
870
|
const cleanBase = rawBase.replace(/\/+$/, "");
|
|
852
871
|
const headers = {
|
|
853
872
|
accept: "application/json",
|
|
873
|
+
...input.headers,
|
|
854
874
|
};
|
|
855
875
|
if (input.apiKey && input.apiKey.trim()) {
|
|
856
876
|
headers.authorization = `Bearer ${input.apiKey.trim()}`;
|
|
877
|
+
if (input.api === "anthropic-messages") {
|
|
878
|
+
headers["x-api-key"] = input.apiKey.trim();
|
|
879
|
+
headers["anthropic-version"] ??= "2023-06-01";
|
|
880
|
+
delete headers.authorization;
|
|
881
|
+
}
|
|
882
|
+
else if (input.api === "google-generative-ai") {
|
|
883
|
+
headers["x-goog-api-key"] = input.apiKey.trim();
|
|
884
|
+
delete headers.authorization;
|
|
885
|
+
}
|
|
857
886
|
}
|
|
858
887
|
const isOllama = input.api === "ollama" || cleanBase.includes(":11434");
|
|
859
888
|
const candidates = [];
|
|
860
889
|
if (isOllama) {
|
|
861
890
|
candidates.push(`${cleanBase}/api/tags`, `${cleanBase}/v1/models`, `${cleanBase}/models`);
|
|
862
891
|
}
|
|
863
|
-
else if (
|
|
892
|
+
else if (/\/(v1|v1beta|v1alpha)$/.test(cleanBase)) {
|
|
864
893
|
candidates.push(`${cleanBase}/models`);
|
|
865
894
|
}
|
|
895
|
+
else if (input.api === "google-generative-ai") {
|
|
896
|
+
candidates.push(`${cleanBase}/v1beta/models`);
|
|
897
|
+
}
|
|
866
898
|
else {
|
|
867
899
|
candidates.push(`${cleanBase}/v1/models`, `${cleanBase}/models`);
|
|
868
900
|
}
|
|
@@ -878,7 +910,9 @@ export async function fetchRemoteModels(input) {
|
|
|
878
910
|
try {
|
|
879
911
|
const response = await (providerProxyFetch(input.proxyEnv) ?? fetch)(candidate, {
|
|
880
912
|
headers,
|
|
881
|
-
|
|
913
|
+
// Fetch only strips standard Authorization on cross-origin redirects, not vendor key headers.
|
|
914
|
+
redirect: input.api === "anthropic-messages" || input.api === "google-generative-ai" ? "error" : "follow",
|
|
915
|
+
signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000),
|
|
882
916
|
});
|
|
883
917
|
if (!response.ok) {
|
|
884
918
|
lastError = `HTTP ${response.status} ${response.statusText}`;
|
|
@@ -903,9 +937,32 @@ export async function fetchRemoteModels(input) {
|
|
|
903
937
|
const cause = lastCause instanceof Error
|
|
904
938
|
? (lastCause.cause instanceof Error ? lastCause.cause.message : lastCause.cause instanceof Object && lastCause.cause !== null ? String(lastCause.cause.code ?? "") : undefined)
|
|
905
939
|
: undefined;
|
|
906
|
-
|
|
940
|
+
const error = new Error(`无法从远程服务获取模型列表 (${lastError || "请求超时或无法连接"}${cause ? `:${cause}` : ""})`);
|
|
941
|
+
if (/HTTP (404|405|501)/.test(lastError))
|
|
942
|
+
Object.assign(error, { code: "DISCOVERY_UNSUPPORTED" });
|
|
943
|
+
throw error;
|
|
907
944
|
}
|
|
908
|
-
|
|
945
|
+
// Follow only same-origin continuation URLs that we construct; never forward keys to payload URLs.
|
|
946
|
+
const first = payload;
|
|
947
|
+
const combined = Array.isArray(payload) ? [...payload] : [...(first.data ?? first.models ?? [])];
|
|
948
|
+
let page = first;
|
|
949
|
+
const seenPages = new Set();
|
|
950
|
+
for (let index = 1; page.has_more || page.nextPageToken; index++) {
|
|
951
|
+
if (index >= 100 || combined.length >= 20_000)
|
|
952
|
+
throw new Error("模型目录分页超过安全上限,请缩小供应商范围。");
|
|
953
|
+
const token = page.nextPageToken ?? page.last_id;
|
|
954
|
+
if (!token || seenPages.has(token))
|
|
955
|
+
throw new Error("供应商模型分页无效,已保留原目录。");
|
|
956
|
+
seenPages.add(token);
|
|
957
|
+
const next = new URL(answeredUrl);
|
|
958
|
+
next.searchParams.set(page.nextPageToken ? "pageToken" : "after", token);
|
|
959
|
+
const response = await (providerProxyFetch(input.proxyEnv) ?? fetch)(next, { headers, redirect: "error", signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000) });
|
|
960
|
+
if (!response.ok)
|
|
961
|
+
throw new Error("供应商模型分页读取失败,已保留原目录。");
|
|
962
|
+
page = await response.json();
|
|
963
|
+
combined.push(...(page.data ?? page.models ?? []));
|
|
964
|
+
}
|
|
965
|
+
return parseRemoteModels(combined, { baseUrl: answeredUrl, api: input.api });
|
|
909
966
|
}
|
|
910
967
|
/**
|
|
911
968
|
* THE ANSWER, READ.
|
|
@@ -941,7 +998,11 @@ export function parseRemoteModels(payload, context) {
|
|
|
941
998
|
if (!item || typeof item !== "object")
|
|
942
999
|
continue;
|
|
943
1000
|
const rec = item;
|
|
944
|
-
|
|
1001
|
+
if (Array.isArray(rec.supportedGenerationMethods) && !rec.supportedGenerationMethods.includes("generateContent"))
|
|
1002
|
+
continue;
|
|
1003
|
+
let id = typeof rec.id === "string" ? rec.id.trim() : typeof rec.name === "string" ? rec.name.trim() : typeof rec.model === "string" ? rec.model.trim() : "";
|
|
1004
|
+
if (context?.api === "google-generative-ai")
|
|
1005
|
+
id = id.replace(/^models\//, "");
|
|
945
1006
|
if (!id || seen.has(id))
|
|
946
1007
|
continue;
|
|
947
1008
|
seen.add(id);
|
|
@@ -960,24 +1021,29 @@ export function parseRemoteModels(payload, context) {
|
|
|
960
1021
|
const reasoning = typeof rec.reasoning === "boolean"
|
|
961
1022
|
? rec.reasoning
|
|
962
1023
|
: (Boolean(thinkingLevelMap) || /r1|reason|o1|o3|thinking|qwq|deepseek-r1/i.test(lower));
|
|
963
|
-
const imageInput =
|
|
1024
|
+
const imageInput = typeof rec.imageInput === "boolean" ? rec.imageInput
|
|
1025
|
+
: Array.isArray(rec.input) ? rec.input.includes("image")
|
|
1026
|
+
: /vision|vl|4o|gemini|claude-3|flash|pixtral/i.test(lower);
|
|
964
1027
|
// THE CATALOGUE IS ASKED BEFORE THE DEFAULT IS GUESSED. A model the provider did not describe
|
|
965
1028
|
// used to fall straight to the placeholder 128000/16384, and that stamp was later read back as
|
|
966
1029
|
// if a person had chosen it - which is how MiniMax-M3 (a 1,000,000-token model) came to believe
|
|
967
1030
|
// it had 128,000. Only a model with NO catalogue entry takes the default.
|
|
968
1031
|
const catalogue = storeWindowFor(readModelStore(piAgentDir()), id);
|
|
969
|
-
const
|
|
970
|
-
|
|
1032
|
+
const reportedWindow = rec.context_window ?? rec.contextWindow ?? rec.context_length ?? rec.inputTokenLimit;
|
|
1033
|
+
const contextWindow = typeof reportedWindow === "number" && Number.isFinite(reportedWindow) && reportedWindow > 0
|
|
1034
|
+
? reportedWindow
|
|
971
1035
|
: catalogue?.contextWindow ?? DEFAULT_CONTEXT_WINDOW;
|
|
972
1036
|
// THE CATALOGUE OUTRANKS THE REASONING GUESS, AND THE ORDER IS THE WHOLE POINT. A reasoning
|
|
973
1037
|
// model used to be stamped with 32768 BEFORE the catalogue was consulted, so a model whose
|
|
974
1038
|
// provider publishes a bigger answer limit got a smaller one - the same hole as the window
|
|
975
1039
|
// one number over, with the same consequence: the limit Super Pi invented is the limit the
|
|
976
1040
|
// session runs on. The guess is what is left when nobody knows better.
|
|
977
|
-
const
|
|
1041
|
+
const reportedOutput = rec.max_output_tokens ?? rec.maxTokens ?? rec.outputTokenLimit;
|
|
1042
|
+
const maxTokens = typeof reportedOutput === "number" && Number.isFinite(reportedOutput) && reportedOutput > 0 ? reportedOutput
|
|
1043
|
+
: catalogue?.maxTokens ?? (reasoning ? GUESSED_MAX_TOKENS : DEFAULT_MAX_TOKENS);
|
|
978
1044
|
discovered.push({
|
|
979
1045
|
id,
|
|
980
|
-
name: id,
|
|
1046
|
+
name: typeof rec.display_name === "string" ? rec.display_name : typeof rec.displayName === "string" ? rec.displayName : id,
|
|
981
1047
|
reasoning,
|
|
982
1048
|
imageInput,
|
|
983
1049
|
contextWindow,
|
package/dist/server/rsi-http.js
CHANGED
|
@@ -80,10 +80,13 @@ export async function handleRsiHttp(context, request, response, url) {
|
|
|
80
80
|
send(405, { error: "请求方法无效。" });
|
|
81
81
|
return true;
|
|
82
82
|
}
|
|
83
|
-
const input = await body(request,
|
|
84
|
-
if ((group?.archivedAt || source.kind === "session" && context.store.conversation(source.id)?.archivedAt) &&
|
|
83
|
+
const input = await body(request, 96000);
|
|
84
|
+
if ((group?.archivedAt || source.kind === "session" && context.store.conversation(source.id)?.archivedAt) && !["rsi.cancel", "rsi.repair.cancel"].includes(input.action))
|
|
85
85
|
throw new Error("已归档来源不能发起新的 RSI 工作。");
|
|
86
|
-
if (
|
|
86
|
+
if (String(input.action).startsWith("rsi.repair.")) {
|
|
87
|
+
await context.rsiService.repairAction(source, input, group?.rsi, group && context.groupChatService?.rsiContext(source.workspaceId, source.id));
|
|
88
|
+
}
|
|
89
|
+
else if (source.kind === "group" && input.action !== "rsi.cancel") {
|
|
87
90
|
if (input.action === "rsi.improve") {
|
|
88
91
|
const report = group?.rsi?.reports.find(report => report.id === input.reportId);
|
|
89
92
|
if (!report)
|
package/dist/server/runtime.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { type KnowledgeBase } from "./knowledge.js";
|
|
|
6
6
|
import { type TurnUsageReadout } from "./conversation-usage.js";
|
|
7
7
|
import { type PiCacheWarmingMode, type PiCacheWarmingSettings } from "../shared/pi-cache-warming.js";
|
|
8
8
|
export { forkSessionFile, truncateSessionFile } from "./session-repository.js";
|
|
9
|
+
import { type ContextCompactionEvent } from "../shared/context-compaction.js";
|
|
9
10
|
export { describeDeliveredUserMessage, describePiQueue } from "./pi-session-events.js";
|
|
10
11
|
import { type PiSessionFactory } from "./pi-session.js";
|
|
11
12
|
import { type AgentDefinition, type Conversation, type ExtensionUiAnswer, type ExtensionUiRequest, type MessageImage, type ModelCatalog, type ModelOption, type ModelSelection, type PiQueueSnapshot, type ToolCallNotice, type ToolCallPreparing } from "./types.js";
|
|
@@ -24,6 +25,7 @@ export interface ExtensionUiHost {
|
|
|
24
25
|
notify(request: ExtensionUiRequest): void;
|
|
25
26
|
}
|
|
26
27
|
export interface AnswerInput {
|
|
28
|
+
onCompaction?(event: ContextCompactionEvent): void | Promise<void>;
|
|
27
29
|
/** Internal isolated review: no built-in tools, delegation or user-session writes. */
|
|
28
30
|
memoryReview?: boolean;
|
|
29
31
|
memorySourceConversationId?: string;
|
|
@@ -254,6 +256,9 @@ export type ForkOutcome = {
|
|
|
254
256
|
inheritedUsageEntryIds?: string[];
|
|
255
257
|
};
|
|
256
258
|
export type IsolatedExecutionEvent = {
|
|
259
|
+
kind: "compaction";
|
|
260
|
+
event: ContextCompactionEvent;
|
|
261
|
+
} | {
|
|
257
262
|
kind: "thinking";
|
|
258
263
|
phase: "start" | "delta" | "end";
|
|
259
264
|
delta?: string;
|
|
@@ -272,6 +277,8 @@ export type IsolatedCompletionInput = {
|
|
|
272
277
|
prompt: string;
|
|
273
278
|
timeoutMs: number;
|
|
274
279
|
cwd: string;
|
|
280
|
+
/** Structured consumers need the last assistant answer, without pre-tool commentary. */
|
|
281
|
+
finalResponseOnly?: boolean;
|
|
275
282
|
signal?: AbortSignal;
|
|
276
283
|
model?: ModelSelection;
|
|
277
284
|
agent?: AgentDefinition;
|
|
@@ -281,6 +288,7 @@ export type IsolatedCompletionInput = {
|
|
|
281
288
|
onModel?: (model: ModelSelection) => void | Promise<void>;
|
|
282
289
|
};
|
|
283
290
|
export interface AgentRuntime {
|
|
291
|
+
compactContext?(input: Pick<AnswerInput, "conversation" | "cwd" | "signal" | "onCompaction" | "onUsage" | "onSessionFile">): Promise<void>;
|
|
284
292
|
answer(input: AnswerInput): AsyncIterable<string>;
|
|
285
293
|
cacheWarmingSettings?(): Promise<PiCacheWarmingSettings>;
|
|
286
294
|
setCacheWarming?(mode: PiCacheWarmingMode): Promise<PiCacheWarmingSettings>;
|
|
@@ -393,6 +401,7 @@ export interface AgentRuntime {
|
|
|
393
401
|
* selected model silently clamps away.
|
|
394
402
|
*/
|
|
395
403
|
catalog(selection?: ModelSelection): Promise<ModelCatalog>;
|
|
404
|
+
readonly supportsModelDiscovery?: boolean;
|
|
396
405
|
oauthProviders?(): Promise<{
|
|
397
406
|
id: string;
|
|
398
407
|
name: string;
|
|
@@ -641,6 +650,7 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
641
650
|
* is on the session RIGHT NOW - that is what an abort targets, and what a steer is delivered into.
|
|
642
651
|
*/
|
|
643
652
|
private readonly activeTurns;
|
|
653
|
+
private readonly manualCompactions;
|
|
644
654
|
/**
|
|
645
655
|
* THE CURRENT TURN'S EXTENSION-UI HOST, per conversation.
|
|
646
656
|
*
|
|
@@ -857,6 +867,8 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
857
867
|
* the old context in memory would keep answering from history the user has withdrawn.
|
|
858
868
|
*/
|
|
859
869
|
disposeSessions(conversationId?: string): Promise<void>;
|
|
870
|
+
compactContext(input: Pick<AnswerInput, "conversation" | "cwd" | "signal" | "onCompaction" | "onUsage" | "onSessionFile">): Promise<void>;
|
|
871
|
+
private compactRpcContext;
|
|
860
872
|
cacheWarmingSettings(): Promise<PiCacheWarmingSettings>;
|
|
861
873
|
reloadNativeTools(): void;
|
|
862
874
|
setCacheWarming(mode: PiCacheWarmingMode): Promise<PiCacheWarmingSettings>;
|
|
@@ -1304,6 +1316,7 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
1304
1316
|
loginLabel?: string;
|
|
1305
1317
|
authenticated: boolean;
|
|
1306
1318
|
}[]>;
|
|
1319
|
+
get supportsModelDiscovery(): boolean;
|
|
1307
1320
|
loginOAuth(providerId: string, interaction: {
|
|
1308
1321
|
signal: AbortSignal;
|
|
1309
1322
|
prompt(prompt: any): Promise<string>;
|
package/dist/server/runtime.js
CHANGED
|
@@ -23,13 +23,15 @@ import { resolvePiCommand, shellQuote } from "./pi-command.js";
|
|
|
23
23
|
import { PiSessionPool, repositoryRootFrom } from "./pi-session-pool.js";
|
|
24
24
|
import { nativeToolArgs, nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, nativeToolExtensionPath, readNativeToolSettings } from "./native-tool-settings.js";
|
|
25
25
|
import { describeDeliveredUserMessage, describePiQueue, handleSessionEvent, TurnQueue } from "./pi-session-events.js";
|
|
26
|
-
import { LengthExceededError } from "./turn-failure.js";
|
|
26
|
+
import { LengthExceededError, formatTurnFailure } from "./turn-failure.js";
|
|
27
|
+
import { modelPolicyExtensionPath } from "./model-policy-extension.js";
|
|
28
|
+
import { readCompactionEvent } from "../shared/context-compaction.js";
|
|
27
29
|
import { CONVERSATION_TITLE_CONTEXT_MAX_CHARS, CONVERSATION_TITLE_TIMEOUT_MS } from "../shared/conversation-title.js";
|
|
28
30
|
// The queue/steer recognisers live in pi-session-events.ts, where the SESSION path's bridge can use
|
|
29
31
|
// them; the one-shot drain loop below reads the same records through the same two functions, so both
|
|
30
32
|
// paths recognise a delivery identically. Re-exported because they were part of this module's surface.
|
|
31
33
|
export { describeDeliveredUserMessage, describePiQueue } from "./pi-session-events.js";
|
|
32
|
-
import { createPiSession, createSdkCatalog, piSdkAvailable, resolveTranscriptFile, superPiExtensionPaths } from "./pi-session.js";
|
|
34
|
+
import { createPiSession, createSdkCatalog, piSdkAvailable, readTranscriptHeader, resolveTranscriptFile, superPiExtensionPaths } from "./pi-session.js";
|
|
33
35
|
import { TASK_CONVERSATION_ENV, PARENT_CONVERSATION_ENV, TASK_DEPTH_ENV, TASK_ENDPOINT_ENV, TASK_EXEC_ENDPOINT_ENV, TASK_ROSTER_ENV, TASK_TOOL_NAME, TODO_ENDPOINT_ENV, TODO_TOOL_NAME, PROJECT_TOOL_NAME, PROJECT_ENDPOINT_ENV, SCHEDULED_TASK_ENDPOINT_ENV, SCHEDULED_TASK_TOOL_NAME, WORKFLOW_ENDPOINT_ENV, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, ORCHESTRATOR_ENDPOINT_ENV, ORCHESTRATOR_WORKSPACE_ENV, WORKTREE_TOOL_NAME, SESSION_SPAWN_TOOL_NAME, SESSION_STATUS_TOOL_NAME, SESSION_DISPATCH_TOOL_NAME, SESSION_STOP_TOOL_NAME, SESSION_REPORT_TOOL_NAME, SESSION_STOP_SUBTREE_TOOL_NAME, SESSION_REMOVE_TOOL_NAME, SESSION_REMINDER_TOOL_NAME, rosterPayload, } from "./task-tool.js";
|
|
34
36
|
import { BLOCKING_UI_METHODS, EXTENSION_UI_METHODS, } from "./types.js";
|
|
35
37
|
import { loadConversationImages } from "./upload.js";
|
|
@@ -357,6 +359,7 @@ export class PiRpcRuntime {
|
|
|
357
359
|
* is on the session RIGHT NOW - that is what an abort targets, and what a steer is delivered into.
|
|
358
360
|
*/
|
|
359
361
|
activeTurns = new Map();
|
|
362
|
+
manualCompactions = new Map();
|
|
360
363
|
/**
|
|
361
364
|
* THE CURRENT TURN'S EXTENSION-UI HOST, per conversation.
|
|
362
365
|
*
|
|
@@ -594,6 +597,134 @@ export class PiRpcRuntime {
|
|
|
594
597
|
await this.sessionPool.disposeAll();
|
|
595
598
|
await this.backgroundUsageWrites;
|
|
596
599
|
}
|
|
600
|
+
async compactContext(input) {
|
|
601
|
+
if (this.sessionMode !== "sdk")
|
|
602
|
+
return this.compactRpcContext(input);
|
|
603
|
+
input.signal.throwIfAborted();
|
|
604
|
+
const { conversation, cwd } = input;
|
|
605
|
+
const configuration = await this.sessionConfiguration(conversation, cwd);
|
|
606
|
+
let file = conversation.piSessionFile;
|
|
607
|
+
if (!this.sessionPool.get(conversation.id)) {
|
|
608
|
+
const header = file ? await readTranscriptHeader(file) : undefined;
|
|
609
|
+
if (!header || header.id !== conversation.id || typeof header.cwd !== "string" || resolve(header.cwd) !== resolve(cwd))
|
|
610
|
+
file = await resolveTranscriptFile(cwd, conversation.id, this.sessionDir);
|
|
611
|
+
if (!file)
|
|
612
|
+
throw new Error("没有找到属于当前工作区和会话的 Pi 历史,无法压缩;请先发送一条消息建立会话。");
|
|
613
|
+
}
|
|
614
|
+
const session = await this.sessionPool.acquire({ ...configuration, conversationId: conversation.id, cwd: resolve(cwd), agentId: conversation.agentId ?? null, ...(file ? { sessionFile: file } : {}) });
|
|
615
|
+
if (!session.compact)
|
|
616
|
+
throw new Error("当前 Pi 会话不支持主动压缩,请更新内置运行时。");
|
|
617
|
+
this.observeBackgroundUsage(conversation.id, session);
|
|
618
|
+
const operation = { abort: () => session.abort() };
|
|
619
|
+
this.manualCompactions.set(conversation.id, operation);
|
|
620
|
+
const abort = () => { void session.abort().catch(() => { }); };
|
|
621
|
+
if (input.signal.aborted)
|
|
622
|
+
abort();
|
|
623
|
+
else
|
|
624
|
+
input.signal.addEventListener("abort", abort, { once: true });
|
|
625
|
+
let pending = Promise.resolve();
|
|
626
|
+
const off = session.subscribe(record => { const event = readCompactionEvent(record); if (event)
|
|
627
|
+
pending = pending.then(async () => { await input.onCompaction?.(event); }).catch(error => { operation.error = error; }); });
|
|
628
|
+
try {
|
|
629
|
+
input.signal.throwIfAborted();
|
|
630
|
+
if (!this.uiBoundSessions.has(session)) {
|
|
631
|
+
await session.bindExtensions?.({ mode: "rpc", uiContext: this.extensionUiBridge(conversation.id), onError: error => {
|
|
632
|
+
const policy = error.extensionPath.replace(/\\/g, "/").includes("/super-pi-model-policy/");
|
|
633
|
+
const failure = new Error(policy ? `上下文压缩失败:${formatTurnFailure(error.error)}` : `Pi 扩展在 ${error.event} 中执行失败。`);
|
|
634
|
+
const maintenance = this.manualCompactions.get(conversation.id);
|
|
635
|
+
if (maintenance)
|
|
636
|
+
maintenance.error = failure;
|
|
637
|
+
this.activeTurns.get(conversation.id)?.queue.fail(failure);
|
|
638
|
+
void session.abort().catch(() => { });
|
|
639
|
+
} });
|
|
640
|
+
this.uiBoundSessions.add(session);
|
|
641
|
+
}
|
|
642
|
+
if (operation.error)
|
|
643
|
+
throw operation.error;
|
|
644
|
+
input.signal.throwIfAborted();
|
|
645
|
+
if (session.sessionFile)
|
|
646
|
+
await input.onSessionFile?.(session.sessionFile);
|
|
647
|
+
await session.compact();
|
|
648
|
+
await pending;
|
|
649
|
+
if (operation.error)
|
|
650
|
+
throw operation.error;
|
|
651
|
+
}
|
|
652
|
+
catch (error) {
|
|
653
|
+
await pending;
|
|
654
|
+
throw operation.error ?? error;
|
|
655
|
+
}
|
|
656
|
+
finally {
|
|
657
|
+
off();
|
|
658
|
+
input.signal.removeEventListener("abort", abort);
|
|
659
|
+
this.manualCompactions.delete(conversation.id);
|
|
660
|
+
await this.backgroundUsageWrites;
|
|
661
|
+
await input.onUsage?.(new ConversationUsageCollector().readout(session.getContextUsage?.(), session.model, defaultAgentDir(), session.getContextPolicy?.()));
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async compactRpcContext(input) {
|
|
665
|
+
if (!this.pi.found)
|
|
666
|
+
throw new Error(this.pi.reason);
|
|
667
|
+
const { conversation, cwd, signal } = input;
|
|
668
|
+
let file = conversation.piSessionFile;
|
|
669
|
+
const header = file ? await readTranscriptHeader(file) : undefined;
|
|
670
|
+
if (!header || header.id !== conversation.id || typeof header.cwd !== "string" || resolve(header.cwd) !== resolve(cwd))
|
|
671
|
+
file = await resolveTranscriptFile(cwd, conversation.id, this.sessionDir);
|
|
672
|
+
if (!file)
|
|
673
|
+
throw new Error("没有找到属于当前工作区和会话的 Pi 历史,无法压缩;请先发送一条消息建立会话。");
|
|
674
|
+
const configuration = await this.sessionConfiguration(conversation, cwd);
|
|
675
|
+
const args = ["--mode", "rpc", "--session", file, "--no-extensions", "--no-mcp", ...configuration.extensionPaths.flatMap(path => ["--extension", path]), ...(configuration.model ? ["--provider", configuration.model.provider, "--model", configuration.model.modelId] : []), ...(configuration.systemPromptFile ? [configuration.systemPromptMode === "replace" ? "--system-prompt" : "--append-system-prompt", configuration.systemPromptFile] : []), ...(configuration.tools ? ["--tools", configuration.tools.join(",")] : []), ...(configuration.excludeTools ? ["--exclude-tools", configuration.excludeTools.join(",")] : [])];
|
|
676
|
+
signal.throwIfAborted();
|
|
677
|
+
const child = spawn(shellQuote(this.pi.command), args.map(arg => shellQuote(arg)), { cwd: resolve(cwd), env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir(), conversation.model?.provider), ...configuration.extensionEnv }, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32", windowsHide: true });
|
|
678
|
+
const channel = new RpcChannel(child);
|
|
679
|
+
const abort = () => { try {
|
|
680
|
+
channel.write({ id: "compact-abort", type: "abort" });
|
|
681
|
+
}
|
|
682
|
+
catch { } };
|
|
683
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
684
|
+
const usage = new ConversationUsageCollector();
|
|
685
|
+
try {
|
|
686
|
+
if (signal.aborted)
|
|
687
|
+
abort();
|
|
688
|
+
await input.onSessionFile?.(file);
|
|
689
|
+
channel.write({ id: "manual-context-compact", type: "compact" });
|
|
690
|
+
const deadline = Date.now() + 600000;
|
|
691
|
+
let result;
|
|
692
|
+
while (Date.now() < deadline) {
|
|
693
|
+
signal.throwIfAborted();
|
|
694
|
+
const record = await channel.next(250);
|
|
695
|
+
if (!record) {
|
|
696
|
+
if (child.exitCode !== null)
|
|
697
|
+
throw new Error("Pi 在上下文压缩结束前退出。");
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
const event = readCompactionEvent(record);
|
|
701
|
+
if (event) {
|
|
702
|
+
await input.onCompaction?.(event);
|
|
703
|
+
if (event.phase === "end")
|
|
704
|
+
result = event;
|
|
705
|
+
}
|
|
706
|
+
if (record.type === "extension_error" && typeof record.extensionPath === "string" && record.extensionPath.replace(/\\/g, "/").includes("/super-pi-model-policy/"))
|
|
707
|
+
throw new Error(`上下文压缩失败:${formatTurnFailure(record.error)}`);
|
|
708
|
+
if (record.type === "response" && record.id === "manual-context-compact") {
|
|
709
|
+
if (record.success !== true)
|
|
710
|
+
throw new Error(record.error || "Pi 未能压缩上下文。");
|
|
711
|
+
const value = record.data;
|
|
712
|
+
usage.add(value?.usage, false);
|
|
713
|
+
const catalog = await this.catalog(conversation.model);
|
|
714
|
+
const selected = catalog.models.find(model => model.provider === conversation.model?.provider && model.modelId === conversation.model.modelId);
|
|
715
|
+
await input.onUsage?.(usage.readout({ tokens: null, contextWindow: selected?.contextWindow ?? conversation.contextUsage?.contextWindow ?? 0 }, undefined, defaultAgentDir()));
|
|
716
|
+
if (!result)
|
|
717
|
+
throw new Error("Pi 没有提供上下文压缩结果。");
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
throw new Error("上下文压缩超过十分钟,已停止;原始历史保留。");
|
|
722
|
+
}
|
|
723
|
+
finally {
|
|
724
|
+
signal.removeEventListener("abort", abort);
|
|
725
|
+
await closePiWorker(child);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
597
728
|
async cacheWarmingSettings() {
|
|
598
729
|
const mode = await piCacheWarmingMode();
|
|
599
730
|
const sessions = this.sessionPool.conversationIds.map(id => this.sessionPool.get(id)).filter(Boolean);
|
|
@@ -628,10 +759,11 @@ export class PiRpcRuntime {
|
|
|
628
759
|
if (!value || typeof value !== "object")
|
|
629
760
|
return;
|
|
630
761
|
const entry = value;
|
|
631
|
-
|
|
762
|
+
const failedSummary = entry.type === "custom" && entry.customType === "super_pi_compaction_usage";
|
|
763
|
+
if (!entry.id || !(entry.type === "usage" && entry.kind === "cache_warm" || entry.type === "compaction" || entry.type === "branch_summary" || failedSummary))
|
|
632
764
|
return;
|
|
633
765
|
const collector = new ConversationUsageCollector();
|
|
634
|
-
collector.add(entry.usage, false);
|
|
766
|
+
collector.add(failedSummary ? entry.data?.usage : entry.usage, false);
|
|
635
767
|
const readout = { ...collector.readout(undefined, session.model, defaultAgentDir()), sourceEntryId: entry.id };
|
|
636
768
|
if (!readout.usage)
|
|
637
769
|
return;
|
|
@@ -979,7 +1111,14 @@ export class PiRpcRuntime {
|
|
|
979
1111
|
const queue = new TurnQueue();
|
|
980
1112
|
const deferred = (handler) => (...args) => { if (handler)
|
|
981
1113
|
queue.push({ kind: "callback", run: () => handler(...args) }); };
|
|
1114
|
+
let compactionActive = false;
|
|
1115
|
+
let compactionReason = "threshold";
|
|
982
1116
|
const handlers = {
|
|
1117
|
+
onCompaction: deferred(async (event) => {
|
|
1118
|
+
compactionActive = event.phase === "start";
|
|
1119
|
+
compactionReason = event.reason;
|
|
1120
|
+
await input.onCompaction?.(event);
|
|
1121
|
+
}),
|
|
983
1122
|
onToolCall: deferred(input.onToolCall),
|
|
984
1123
|
onFileWrite: input.onFileWrite,
|
|
985
1124
|
onToolUpdate: deferred(input.onToolUpdate),
|
|
@@ -1069,12 +1208,17 @@ export class PiRpcRuntime {
|
|
|
1069
1208
|
let startupFailure;
|
|
1070
1209
|
try {
|
|
1071
1210
|
await session.bindExtensions({ uiContext, mode: "rpc", onError: error => {
|
|
1072
|
-
const
|
|
1211
|
+
const policy = error.extensionPath.replace(/\\/g, "/").includes("/super-pi-model-policy/");
|
|
1212
|
+
const detail = error.error;
|
|
1213
|
+
const failure = new Error(policy && error.event === "session_before_compact" ? `上下文压缩失败:${formatTurnFailure(detail)}` : `Pi 扩展 ${basename(error.extensionPath)} 在 ${error.event} 中执行失败,请检查扩展配置。`);
|
|
1073
1214
|
console.warn(failure.message);
|
|
1074
1215
|
if (binding) {
|
|
1075
1216
|
startupFailure = failure;
|
|
1076
1217
|
return;
|
|
1077
1218
|
}
|
|
1219
|
+
const maintenance = this.manualCompactions.get(conversation.id);
|
|
1220
|
+
if (maintenance)
|
|
1221
|
+
maintenance.error = failure;
|
|
1078
1222
|
if (this.sessionPool.get(conversation.id) !== session)
|
|
1079
1223
|
return;
|
|
1080
1224
|
this.activeTurns.get(conversation.id)?.queue.fail(failure);
|
|
@@ -1228,13 +1372,15 @@ export class PiRpcRuntime {
|
|
|
1228
1372
|
if (input.host)
|
|
1229
1373
|
this.sessionHosts.delete(conversation.id);
|
|
1230
1374
|
await finished.catch(() => undefined);
|
|
1375
|
+
if (compactionActive)
|
|
1376
|
+
await input.onCompaction?.({ phase: "end", reason: compactionReason, aborted: signal.aborted, error: signal.aborted ? undefined : "本轮执行已结束,但没有收到上下文压缩结果。" });
|
|
1231
1377
|
if (input.onUsage) {
|
|
1232
1378
|
let context;
|
|
1233
1379
|
try {
|
|
1234
1380
|
context = session.getContextUsage?.();
|
|
1235
1381
|
}
|
|
1236
1382
|
catch { /* Unavailable context must not discard usage or keep a stale occupancy. */ }
|
|
1237
|
-
await input.onUsage(usage.readout(context, session.model, defaultAgentDir()));
|
|
1383
|
+
await input.onUsage(usage.readout(context, session.model, defaultAgentDir(), session.getContextPolicy?.()));
|
|
1238
1384
|
}
|
|
1239
1385
|
}
|
|
1240
1386
|
}
|
|
@@ -1538,7 +1684,7 @@ export class PiRpcRuntime {
|
|
|
1538
1684
|
* Still used for the memory review, the knowledge reranker, and as the fallback when Pi's SDK is not
|
|
1539
1685
|
* installed. The main conversation path does NOT come here - see `answer`.
|
|
1540
1686
|
*/
|
|
1541
|
-
async *answerOneShot({ conversation, prompt, signal, cwd, host, onPiQueue, onSteerDelivered, onUserEntry, onSessionFile, onToolCall, onFileWrite, onToolUpdate, onToolPreparing, onToolEnd, onThinking, onThinkingEnd, images, memoryReview, memorySourceConversationId, knowledgeRerank }) {
|
|
1687
|
+
async *answerOneShot({ conversation, prompt, signal, cwd, host, onPiQueue, onSteerDelivered, onUserEntry, onSessionFile, onToolCall, onFileWrite, onToolUpdate, onToolPreparing, onToolEnd, onThinking, onThinkingEnd, onCompaction, images, memoryReview, memorySourceConversationId, knowledgeRerank }) {
|
|
1542
1688
|
const latencyStartedAt = performance.now();
|
|
1543
1689
|
traceLatency(conversation.id, "answer.begin", latencyStartedAt);
|
|
1544
1690
|
await mkdir(this.sessionDir, { recursive: true });
|
|
@@ -1630,7 +1776,7 @@ export class PiRpcRuntime {
|
|
|
1630
1776
|
if (useNativeTools && nativePolicy.excludeTools?.length)
|
|
1631
1777
|
agentArgs.push("--exclude-tools", nativePolicy.excludeTools.join(","));
|
|
1632
1778
|
const providerProxyEnv = { ...await readProviderProxyEnv(defaultAgentDir(), conversation.model?.provider), ...(useNativeTools ? nativeToolEnv(this.sessionDir, nativePolicy) : {}) };
|
|
1633
|
-
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], {
|
|
1779
|
+
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, "--extension", shellQuote(modelPolicyExtensionPath())], {
|
|
1634
1780
|
cwd: childCwd,
|
|
1635
1781
|
detached: process.platform !== "win32",
|
|
1636
1782
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -1822,6 +1968,15 @@ export class PiRpcRuntime {
|
|
|
1822
1968
|
// the "looks wired up but nothing happens" failure - it is the only signal that a steer was
|
|
1823
1969
|
// really picked up, and Pi emits it before the delivered message on the same stdout stream.
|
|
1824
1970
|
const piQueue = describePiQueue(record);
|
|
1971
|
+
if (record.type === "extension_error" && typeof record.extensionPath === "string" && record.extensionPath.replace(/\\/g, "/").includes("/super-pi-model-policy/") && record.event === "session_before_compact")
|
|
1972
|
+
throw new Error(`上下文压缩失败:${formatTurnFailure(record.error)}`);
|
|
1973
|
+
const compaction = readCompactionEvent(record);
|
|
1974
|
+
if (compaction) {
|
|
1975
|
+
await onCompaction?.(compaction);
|
|
1976
|
+
if (compaction.phase === "end" && compaction.reason === "overflow" && compaction.error && !compaction.aborted)
|
|
1977
|
+
finalAgentOutcome = { stopReason: "error", errorMessage: `上下文自动压缩失败,尚未恢复回答:${compaction.error}` };
|
|
1978
|
+
continue;
|
|
1979
|
+
}
|
|
1825
1980
|
if (piQueue) {
|
|
1826
1981
|
try {
|
|
1827
1982
|
onPiQueue?.(piQueue);
|
|
@@ -2481,6 +2636,11 @@ export class PiRpcRuntime {
|
|
|
2481
2636
|
reply(buildExtensionUiResponse(request, answer));
|
|
2482
2637
|
}
|
|
2483
2638
|
async stop(conversationId) {
|
|
2639
|
+
const maintenance = this.manualCompactions.get(conversationId);
|
|
2640
|
+
if (maintenance) {
|
|
2641
|
+
await maintenance.abort();
|
|
2642
|
+
return;
|
|
2643
|
+
}
|
|
2484
2644
|
// A turn on a persistent session is stopped by aborting THAT SESSION, and the session survives - it
|
|
2485
2645
|
// is the next turn's session. This is the whole reason an interrupt no longer costs a process
|
|
2486
2646
|
// teardown and a process startup: there is no process to tear down.
|
|
@@ -2554,7 +2714,7 @@ export class PiRpcRuntime {
|
|
|
2554
2714
|
// The selected model is carried over, but the current conversation transcript and its live cache are
|
|
2555
2715
|
// deliberately not: title generation is an isolated, bounded one-shot request.
|
|
2556
2716
|
const selectedModel = conversation.model;
|
|
2557
|
-
const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates"], {
|
|
2717
|
+
const child = spawn(shellQuote(this.pi.command), ["--mode", "rpc", "--no-session", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-context-files", "--no-prompt-templates", "--extension", shellQuote(modelPolicyExtensionPath())], {
|
|
2558
2718
|
cwd: resolve(cwd),
|
|
2559
2719
|
env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir(), selectedModel?.provider) },
|
|
2560
2720
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -2668,7 +2828,7 @@ export class PiRpcRuntime {
|
|
|
2668
2828
|
async completeOnce(input, sessionFile) {
|
|
2669
2829
|
if (!this.pi.found)
|
|
2670
2830
|
throw new Error(this.pi.reason);
|
|
2671
|
-
const args = ["--mode", "rpc", ...(sessionFile ? ["--session", sessionFile] : ["--no-session"]), "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-mcp"];
|
|
2831
|
+
const args = ["--mode", "rpc", ...(sessionFile ? ["--session", sessionFile] : ["--no-session"]), "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-mcp", "--extension", modelPolicyExtensionPath()];
|
|
2672
2832
|
let nativeEnv = {};
|
|
2673
2833
|
if (input.agent && input.onToolStart) {
|
|
2674
2834
|
const selection = nativeToolPolicy(toolSelection(input.agent.tools), readNativeToolSettings(nativeToolSettingsPath(this.sessionDir)));
|
|
@@ -2723,7 +2883,9 @@ export class PiRpcRuntime {
|
|
|
2723
2883
|
channel.write({ id: "tool_llm", type: "prompt", message: input.prompt });
|
|
2724
2884
|
awaitingCompletion = true;
|
|
2725
2885
|
let settled = false, text = "";
|
|
2726
|
-
let failure;
|
|
2886
|
+
let failure, finalText;
|
|
2887
|
+
let compactionFailure;
|
|
2888
|
+
const executionCalls = new Map();
|
|
2727
2889
|
const splitter = new InlineThinkingSplitter();
|
|
2728
2890
|
const append = (parts) => {
|
|
2729
2891
|
for (const part of parts) {
|
|
@@ -2739,6 +2901,12 @@ export class PiRpcRuntime {
|
|
|
2739
2901
|
input.onText?.(delta);
|
|
2740
2902
|
};
|
|
2741
2903
|
const noteOutcome = (message, reason) => {
|
|
2904
|
+
if (input.finalResponseOnly && message?.content !== undefined) {
|
|
2905
|
+
const content = typeof message.content === "string" ? message.content : Array.isArray(message.content)
|
|
2906
|
+
? message.content.filter((part) => part?.type === "text" && typeof part.text === "string").map(part => part.text).join("") : "";
|
|
2907
|
+
const finalSplitter = new InlineThinkingSplitter();
|
|
2908
|
+
finalText = [...finalSplitter.push(content), ...finalSplitter.flush()].filter(part => part.kind === "text").map(part => part.text).join("");
|
|
2909
|
+
}
|
|
2742
2910
|
const stop = message?.stopReason ?? reason;
|
|
2743
2911
|
if (stop)
|
|
2744
2912
|
failure = ["error", "aborted", "length"].includes(stop) ? message?.errorMessage || `模型未完成回答(${stop})` : undefined;
|
|
@@ -2751,13 +2919,28 @@ export class PiRpcRuntime {
|
|
|
2751
2919
|
continue;
|
|
2752
2920
|
if (record.type === "tool_execution_start")
|
|
2753
2921
|
input.onToolStart?.();
|
|
2922
|
+
if (record.type === "extension_error" && typeof record.extensionPath === "string" && record.extensionPath.replace(/\\/g, "/").includes("/super-pi-model-policy/") && record.event === "session_before_compact")
|
|
2923
|
+
throw new Error(`上下文压缩失败:${formatTurnFailure(record.error)}`);
|
|
2924
|
+
const compaction = readCompactionEvent(record);
|
|
2925
|
+
if (compaction) {
|
|
2926
|
+
input.onExecution?.({ kind: "compaction", event: compaction });
|
|
2927
|
+
if (compaction.phase === "end" && compaction.reason === "overflow" && compaction.error && !compaction.aborted)
|
|
2928
|
+
compactionFailure = `上下文自动压缩失败:${compaction.error}`;
|
|
2929
|
+
}
|
|
2930
|
+
if (record.type === "message_start" && record.message?.role === "assistant")
|
|
2931
|
+
compactionFailure = undefined;
|
|
2754
2932
|
if (input.onExecution && record.toolCallId && (record.type === "tool_execution_start" || record.type === "tool_execution_update" || record.type === "tool_execution_end")) {
|
|
2755
2933
|
const phase = record.type === "tool_execution_start" ? "start" : record.type === "tool_execution_update" ? "update" : "end";
|
|
2756
|
-
const
|
|
2934
|
+
const previous = executionCalls.get(record.toolCallId);
|
|
2935
|
+
const name = (record.toolName ?? previous?.name ?? "tool").slice(0, 64);
|
|
2757
2936
|
// Keep file targets, executable names and bounded result summaries for task-quality observation.
|
|
2758
|
-
const detail = ["read", "write", "edit", "grep", "find", "ls"].includes(name)
|
|
2937
|
+
const detail = record.args === undefined ? previous?.detail : ["read", "write", "edit", "grep", "find", "ls"].includes(name)
|
|
2759
2938
|
? describeToolCall("read", record.args)
|
|
2760
2939
|
: name === "bash" || name === "powershell" ? describeToolCall(name, record.args)?.match(/^[a-z][a-z\d_.-]{0,31}(?=\s|$)/i)?.[0] : undefined;
|
|
2940
|
+
if (phase === "end")
|
|
2941
|
+
executionCalls.delete(record.toolCallId);
|
|
2942
|
+
else
|
|
2943
|
+
executionCalls.set(record.toolCallId, { name, detail });
|
|
2761
2944
|
input.onExecution({ kind: "tool", phase, call: {
|
|
2762
2945
|
id: record.toolCallId.slice(0, 160), name, detail,
|
|
2763
2946
|
result: phase === "end" ? extractToolResultText(record.result) : undefined,
|
|
@@ -2795,8 +2978,12 @@ export class PiRpcRuntime {
|
|
|
2795
2978
|
// would otherwise hand the caller a `<think>`-prefixed string, and the caller - a tool, a
|
|
2796
2979
|
// title, a card - would store the reasoning trace as its result.
|
|
2797
2980
|
append(splitter.flush());
|
|
2981
|
+
if (compactionFailure)
|
|
2982
|
+
throw new Error(compactionFailure);
|
|
2798
2983
|
if (failure)
|
|
2799
2984
|
throw new Error(failure);
|
|
2985
|
+
if (input.finalResponseOnly && finalText !== undefined)
|
|
2986
|
+
text = finalText;
|
|
2800
2987
|
if (!text.trim())
|
|
2801
2988
|
throw new Error("模型没有返回任何内容");
|
|
2802
2989
|
return text;
|
|
@@ -2976,6 +3163,7 @@ export class PiRpcRuntime {
|
|
|
2976
3163
|
this.sdkCatalogPromise = undefined;
|
|
2977
3164
|
}
|
|
2978
3165
|
async oauthProviders() { return (await this.sdkCatalog())?.oauthProviders() ?? []; }
|
|
3166
|
+
get supportsModelDiscovery() { return this.pi.explicit !== true && this.sessionMode !== "oneshot"; }
|
|
2979
3167
|
async loginOAuth(providerId, interaction) {
|
|
2980
3168
|
const catalog = await this.sdkCatalog();
|
|
2981
3169
|
if (!catalog)
|
package/dist/server/store.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type SessionSearchResult } from "../shared/session-search.js";
|
|
2
|
+
import type { ContextCompactionEvent } from "../shared/context-compaction.js";
|
|
2
3
|
import type { AppStateRepository } from "./persistence/app-state-repository.js";
|
|
3
4
|
import { defaultJsonStatePath } from "./persistence/json-state-repository.js";
|
|
4
5
|
import type { ScheduledTask } from "./scheduled-tasks.js";
|
|
@@ -713,6 +714,7 @@ export declare class Store {
|
|
|
713
714
|
*
|
|
714
715
|
* Set to `undefined` to clear, which the next `addUserMessage` does anyway.
|
|
715
716
|
*/
|
|
717
|
+
recordCompaction(conversationId: string, event: ContextCompactionEvent): Promise<void>;
|
|
716
718
|
setWarningReason(conversationId: string, reason: string | undefined): Promise<void>;
|
|
717
719
|
/** The plan a revert would carry out, without carrying it out. The server reads this to stop children first. */
|
|
718
720
|
planRevert(conversationId: string, messageId: string, withdraw?: boolean): RevertPlan;
|