@evandu/super-pi 0.1.281 → 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 +21 -14
- package/dist/client/assets/{CodeMirrorEditor-xxJP_tVy.js → CodeMirrorEditor-Y4BbFnPe.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-X8eCsha9.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/rsi-repairs.d.ts +27 -0
- package/dist/server/application/rsi-repairs.js +201 -0
- package/dist/server/application/rsi-service.d.ts +4 -0
- package/dist/server/application/rsi-service.js +29 -9
- 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/index.js +35 -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-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 +14 -0
- package/dist/server/pi-session.js +9 -0
- package/dist/server/provider-proxy.js +7 -2
- package/dist/server/rsi-http.js +6 -3
- package/dist/server/runtime.d.ts +11 -0
- package/dist/server/runtime.js +200 -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 +6 -0
- package/dist/shared/rsi.d.ts +33 -0
- package/package.json +7 -1
- package/dist/client/assets/index-DaKloC7K.css +0 -1
- package/dist/client/assets/index-sWsdT0fC.js +0 -350
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import { describeToolCall, describeToolCallArgs, extractPartialResultText, readQuestionCall } from "./tool-calls.js";
|
|
20
20
|
import { toolTargetPath } from "./file-changes.js";
|
|
21
21
|
import { LengthExceededError, isProviderQuotaError } from "./turn-failure.js";
|
|
22
|
+
import { readCompactionEvent } from "../shared/context-compaction.js";
|
|
22
23
|
/** Keeps only real strings, so a malformed queue snapshot cannot put objects into a broadcast. */
|
|
23
24
|
const textList = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;
|
|
24
25
|
/**
|
|
@@ -183,6 +184,15 @@ export function handleSessionEvent(event, queue, handlers, report, failure) {
|
|
|
183
184
|
if (!record || typeof record.type !== "string")
|
|
184
185
|
return false;
|
|
185
186
|
switch (record.type) {
|
|
187
|
+
case "compaction_start":
|
|
188
|
+
case "compaction_end": {
|
|
189
|
+
const event = readCompactionEvent(record);
|
|
190
|
+
handlers.onCompaction?.(event);
|
|
191
|
+
if (event.phase === "end" && event.reason === "overflow" && event.error && !event.aborted && failure) {
|
|
192
|
+
failure.current = { stopReason: "error", message: `上下文自动压缩失败,尚未恢复回答:${event.error}` };
|
|
193
|
+
}
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
186
196
|
case "message_end": {
|
|
187
197
|
// THE AUTHORITATIVE END OF AN ASSISTANT MESSAGE. `message_end` is the completed message, and its
|
|
188
198
|
// `stopReason` is the only place Pi says whether the model actually answered. The bridge used to
|
|
@@ -137,6 +137,11 @@ interface PiSdk {
|
|
|
137
137
|
getDefaultProvider?: () => string | undefined;
|
|
138
138
|
getDefaultModel?: () => string | undefined;
|
|
139
139
|
getDefaultThinkingLevel?: () => string | undefined;
|
|
140
|
+
getCompactionSettings?(model: unknown): {
|
|
141
|
+
enabled: boolean;
|
|
142
|
+
reserveTokens: number;
|
|
143
|
+
keepRecentTokens: number;
|
|
144
|
+
};
|
|
140
145
|
getCacheWarmingMode(): PiCacheWarmingMode;
|
|
141
146
|
setCacheWarmingMode(mode: PiCacheWarmingMode): void;
|
|
142
147
|
flush(): Promise<void>;
|
|
@@ -459,6 +464,15 @@ export interface PiSessionLike {
|
|
|
459
464
|
readonly model?: {
|
|
460
465
|
provider?: string;
|
|
461
466
|
id?: string;
|
|
467
|
+
contextWindow?: number;
|
|
468
|
+
maxTokens?: number;
|
|
469
|
+
} | undefined;
|
|
470
|
+
compact?(instructions?: string): Promise<unknown>;
|
|
471
|
+
getContextPolicy?(): {
|
|
472
|
+
autoCompact: boolean;
|
|
473
|
+
reserveTokens: number;
|
|
474
|
+
keepRecentTokens: number;
|
|
475
|
+
outputReserveTokens: number;
|
|
462
476
|
} | undefined;
|
|
463
477
|
/** Pi's estimate for the current context, including its post-compaction unknown state. */
|
|
464
478
|
getContextUsage?(): {
|
|
@@ -413,6 +413,7 @@ export async function createPiSession(creation) {
|
|
|
413
413
|
traceSession(creation.sessionId, "sdk.transcript.ready", startedAt, `bytes=${transcriptBytes(sessionManager)}`);
|
|
414
414
|
const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(agentDir, "auth.json"))) : undefined;
|
|
415
415
|
const modelRuntime = await sdk.ModelRuntime.create(credentials ? { credentials } : undefined);
|
|
416
|
+
const settingsManager = sdk.SettingsManager.create(creation.cwd, agentDir);
|
|
416
417
|
await installProviderProxy(modelRuntime, agentDir);
|
|
417
418
|
traceSession(creation.sessionId, "sdk.model-runtime", startedAt);
|
|
418
419
|
// THE MODEL IS RESOLVED, NOT PASSED THROUGH. Pi's SDK takes a whole Model object - the provider's
|
|
@@ -433,6 +434,7 @@ export async function createPiSession(creation) {
|
|
|
433
434
|
modelRuntime,
|
|
434
435
|
resourceLoader: loader,
|
|
435
436
|
sessionManager,
|
|
437
|
+
settingsManager,
|
|
436
438
|
...(nativePolicy.tools ? { tools: nativePolicy.tools } : {}),
|
|
437
439
|
...(nativePolicy.excludeTools ? { excludeTools: nativePolicy.excludeTools } : {}),
|
|
438
440
|
...(model ? { model } : {}),
|
|
@@ -454,6 +456,12 @@ export async function createPiSession(creation) {
|
|
|
454
456
|
// The window the model REALLY has is arbitrated inside the resolver - see
|
|
455
457
|
// `model-context-window.ts` for the whole reasoning and for the tests that hold it in place.
|
|
456
458
|
live.resolveModel = createModelResolver({ agentDir, modelRuntime });
|
|
459
|
+
live.getContextPolicy = () => {
|
|
460
|
+
const policy = settingsManager.getCompactionSettings?.(live.model);
|
|
461
|
+
if (!policy)
|
|
462
|
+
return;
|
|
463
|
+
return { autoCompact: policy.enabled, reserveTokens: policy.reserveTokens, keepRecentTokens: policy.keepRecentTokens, outputReserveTokens: Math.min(live.model?.maxTokens ?? 8192, Math.max(1024, Math.min(8192, Math.floor((live.model?.contextWindow ?? 128000) / 8)))) };
|
|
464
|
+
};
|
|
457
465
|
return live;
|
|
458
466
|
})();
|
|
459
467
|
}
|
|
@@ -655,6 +663,7 @@ export async function loadPromptTemplateSummaries(cwd) {
|
|
|
655
663
|
}
|
|
656
664
|
export function superPiExtensionPaths(repositoryRoot) {
|
|
657
665
|
const paths = [
|
|
666
|
+
join(repositoryRoot, "agents", "super-pi-model-policy", "index.ts"),
|
|
658
667
|
join(repositoryRoot, "agents", "super-pi-native-tools", "index.ts"),
|
|
659
668
|
join(repositoryRoot, "agents", "super-pi-task", "index.ts"),
|
|
660
669
|
join(repositoryRoot, "agents", "super-pi-memory", "index.ts"),
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { installManagedModels } from "./managed-model-adapter.js";
|
|
2
|
+
import { installModelCapabilities } from "./model-capabilities.js";
|
|
3
|
+
import { withModelRequestPolicy } from "./model-request-policy.js";
|
|
2
4
|
import { EnvHttpProxyAgent } from "undici";
|
|
3
5
|
import { readFile } from "node:fs/promises";
|
|
4
6
|
import { join } from "node:path";
|
|
@@ -140,6 +142,7 @@ export function proxyCredentialStore(store) {
|
|
|
140
142
|
/** Read provider routing independently of Pi's auth result: OAuth resolution omits credential.env. */
|
|
141
143
|
export async function installProviderProxy(runtime, agentDir) {
|
|
142
144
|
await installManagedModels(runtime);
|
|
145
|
+
const normalizeModel = installModelCapabilities(runtime, agentDir);
|
|
143
146
|
const target = runtime;
|
|
144
147
|
if (typeof target.getAuth !== "function")
|
|
145
148
|
return;
|
|
@@ -175,6 +178,7 @@ export async function installProviderProxy(runtime, agentDir) {
|
|
|
175
178
|
if (typeof original !== "function")
|
|
176
179
|
continue;
|
|
177
180
|
target[method] = function (model, context, options) {
|
|
181
|
+
model = normalizeModel(model);
|
|
178
182
|
// These SDK adapters reject injected fetch implementations; preserve their native transport.
|
|
179
183
|
if (["bedrock-converse-stream", "google-generative-ai", "google-vertex"].includes(model?.api ?? ""))
|
|
180
184
|
return original.call(target, model, context, options);
|
|
@@ -186,15 +190,16 @@ export async function installProviderProxy(runtime, agentDir) {
|
|
|
186
190
|
throw new Error("Codex 配置代理时当前仅支持 SSE 传输,请将 transport 设为 sse 或 auto");
|
|
187
191
|
routed.transport = "sse";
|
|
188
192
|
}
|
|
193
|
+
const start = (selectedOptions) => withModelRequestPolicy(model, selectedOptions, value => original.call(target, model, context, value));
|
|
189
194
|
if (options?.fetch)
|
|
190
|
-
return
|
|
195
|
+
return start(routed);
|
|
191
196
|
const requestFetch = async (input, init) => {
|
|
192
197
|
const auth = await target.getAuth(model, { env });
|
|
193
198
|
// Provider requests select their own routing, even when launched inside another auth callback.
|
|
194
199
|
const transport = globalThis.fetch === scopedFetch ? baseAuthFetch : globalThis.fetch;
|
|
195
200
|
return (providerProxyFetch(mergeEnv(auth?.env, env), transport) ?? transport)(input, init);
|
|
196
201
|
};
|
|
197
|
-
return
|
|
202
|
+
return start({ ...routed, fetch: requestFetch });
|
|
198
203
|
};
|
|
199
204
|
}
|
|
200
205
|
}
|
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>;
|
|
@@ -642,6 +650,7 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
642
650
|
* is on the session RIGHT NOW - that is what an abort targets, and what a steer is delivered into.
|
|
643
651
|
*/
|
|
644
652
|
private readonly activeTurns;
|
|
653
|
+
private readonly manualCompactions;
|
|
645
654
|
/**
|
|
646
655
|
* THE CURRENT TURN'S EXTENSION-UI HOST, per conversation.
|
|
647
656
|
*
|
|
@@ -858,6 +867,8 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
858
867
|
* the old context in memory would keep answering from history the user has withdrawn.
|
|
859
868
|
*/
|
|
860
869
|
disposeSessions(conversationId?: string): Promise<void>;
|
|
870
|
+
compactContext(input: Pick<AnswerInput, "conversation" | "cwd" | "signal" | "onCompaction" | "onUsage" | "onSessionFile">): Promise<void>;
|
|
871
|
+
private compactRpcContext;
|
|
861
872
|
cacheWarmingSettings(): Promise<PiCacheWarmingSettings>;
|
|
862
873
|
reloadNativeTools(): void;
|
|
863
874
|
setCacheWarming(mode: PiCacheWarmingMode): Promise<PiCacheWarmingSettings>;
|
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;
|
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;
|
package/dist/server/store.js
CHANGED
|
@@ -218,12 +218,20 @@ function reconcileConversations(state) {
|
|
|
218
218
|
state.conversations = conversations;
|
|
219
219
|
const orphaned = [];
|
|
220
220
|
for (const conversation of conversations) {
|
|
221
|
+
if (!conversation)
|
|
222
|
+
continue;
|
|
223
|
+
const compactionInterrupted = conversation.compaction?.status === "running";
|
|
224
|
+
if (compactionInterrupted && conversation.compaction)
|
|
225
|
+
conversation.compaction = { ...conversation.compaction, status: "cancelled", finishedAt: now(), error: "服务已重启,上一次上下文压缩已中断。" };
|
|
221
226
|
// `waiting` joins the orphan set for the same reason `running` does: the turn was opened (a prompt
|
|
222
227
|
// was sent) and the server died before any settled state was recorded. A conversation that was in
|
|
223
228
|
// either of those two states when the process went away has a half-open turn whose outcome nobody
|
|
224
229
|
// can determine from the file alone - exactly the situation this sweep exists to remove.
|
|
225
|
-
if (
|
|
230
|
+
if (conversation.status !== "running" && conversation.status !== "waiting" && conversation.status !== "awaiting_background") {
|
|
231
|
+
if (compactionInterrupted)
|
|
232
|
+
orphaned.push(conversation);
|
|
226
233
|
continue;
|
|
234
|
+
}
|
|
227
235
|
conversation.status = "failed";
|
|
228
236
|
conversation.error = ORPHANED_CONVERSATION_ERROR;
|
|
229
237
|
orphaned.push(conversation);
|
|
@@ -2584,6 +2592,14 @@ export class Store {
|
|
|
2584
2592
|
*
|
|
2585
2593
|
* Set to `undefined` to clear, which the next `addUserMessage` does anyway.
|
|
2586
2594
|
*/
|
|
2595
|
+
async recordCompaction(conversationId, event) {
|
|
2596
|
+
const conversation = this.requireConversation(conversationId);
|
|
2597
|
+
const stamp = now();
|
|
2598
|
+
conversation.compaction = event.phase === "start"
|
|
2599
|
+
? { reason: event.reason, status: "running", startedAt: stamp }
|
|
2600
|
+
: { ...event, status: event.aborted ? "cancelled" : event.error ? "failed" : "completed", startedAt: conversation.compaction?.startedAt ?? stamp, finishedAt: stamp };
|
|
2601
|
+
await this.persistMetadata(conversationId);
|
|
2602
|
+
}
|
|
2587
2603
|
async setWarningReason(conversationId, reason) {
|
|
2588
2604
|
const conversation = this.requireConversation(conversationId);
|
|
2589
2605
|
if (reason === undefined)
|
package/dist/server/subagents.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { modelPolicyExtensionPath } from "./model-policy-extension.js";
|
|
3
4
|
import { mkdir, stat } from "node:fs/promises";
|
|
4
5
|
import { join, resolve } from "node:path";
|
|
5
6
|
import { agentSpawnArgs, readAgents, toolSelection } from "./agents.js";
|
|
@@ -277,7 +278,7 @@ export class SubagentSupervisor {
|
|
|
277
278
|
throw new SubagentCancelled(id);
|
|
278
279
|
}
|
|
279
280
|
// npm exposes global CLIs as .cmd shims on Windows; Node requires a shell to launch those shims.
|
|
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" } : {}) } });
|
|
281
|
+
const child = spawn(shellQuote(this.pi.command), [...args, "--extension", shellQuote(modelPolicyExtensionPath())], { 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" } : {}) } });
|
|
281
282
|
if (memoryToken)
|
|
282
283
|
child.once("close", () => this.memory?.release(memoryToken));
|
|
283
284
|
this.children.set(id, { conversationId, child });
|