@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.
Files changed (76) hide show
  1. package/agents/rsi-discussion.md +21 -0
  2. package/agents/rsi-repair.md +33 -0
  3. package/agents/super-pi-model-policy/index.ts +1 -0
  4. package/desktop/preload.cjs +1 -1
  5. package/dist/.super-pi-check-inputs.json +2 -2
  6. package/dist/client/.super-pi-client-sources.json +25 -16
  7. package/dist/client/assets/{CodeMirrorEditor-D-UuYizz.js → CodeMirrorEditor-Y4BbFnPe.js} +1 -1
  8. package/dist/client/assets/{GitDiffEditor-Bt1n2la-.js → GitDiffEditor-BhUOinn3.js} +1 -1
  9. package/dist/client/assets/index-CMb8f0dS.css +1 -0
  10. package/dist/client/assets/index-DGnOud6x.js +350 -0
  11. package/dist/client/index.html +2 -2
  12. package/dist/server/application/conversation-service.js +4 -0
  13. package/dist/server/application/group-chat-service.d.ts +8 -0
  14. package/dist/server/application/group-chat-service.js +13 -4
  15. package/dist/server/application/group-execution.d.ts +1 -0
  16. package/dist/server/application/group-execution.js +18 -0
  17. package/dist/server/application/group-rsi.d.ts +9 -0
  18. package/dist/server/application/group-rsi.js +19 -6
  19. package/dist/server/application/provider-service.d.ts +27 -11
  20. package/dist/server/application/provider-service.js +78 -10
  21. package/dist/server/application/rsi-repairs.d.ts +27 -0
  22. package/dist/server/application/rsi-repairs.js +201 -0
  23. package/dist/server/application/rsi-service.d.ts +6 -0
  24. package/dist/server/application/rsi-service.js +105 -17
  25. package/dist/server/application/run-service.d.ts +3 -0
  26. package/dist/server/application/run-service.js +79 -5
  27. package/dist/server/bounded-compaction.d.ts +12 -0
  28. package/dist/server/bounded-compaction.js +34 -0
  29. package/dist/server/command-handler.js +10 -0
  30. package/dist/server/conversation-usage.d.ts +6 -1
  31. package/dist/server/conversation-usage.js +2 -2
  32. package/dist/server/hierarchical-compaction.d.ts +1 -0
  33. package/dist/server/hierarchical-compaction.js +115 -0
  34. package/dist/server/http-server.js +23 -0
  35. package/dist/server/index.js +39 -0
  36. package/dist/server/length-continuation.js +1 -1
  37. package/dist/server/model-capabilities.d.ts +6 -0
  38. package/dist/server/model-capabilities.js +57 -0
  39. package/dist/server/model-discovery.d.ts +44 -0
  40. package/dist/server/model-discovery.js +139 -0
  41. package/dist/server/model-policy-extension.d.ts +3 -0
  42. package/dist/server/model-policy-extension.js +82 -0
  43. package/dist/server/model-request-policy.d.ts +2 -0
  44. package/dist/server/model-request-policy.js +30 -0
  45. package/dist/server/pi-session-events.d.ts +2 -0
  46. package/dist/server/pi-session-events.js +10 -0
  47. package/dist/server/pi-session.d.ts +39 -2
  48. package/dist/server/pi-session.js +39 -1
  49. package/dist/server/provider-proxy.d.ts +2 -0
  50. package/dist/server/provider-proxy.js +8 -3
  51. package/dist/server/providers.d.ts +6 -0
  52. package/dist/server/providers.js +76 -10
  53. package/dist/server/rsi-http.js +6 -3
  54. package/dist/server/runtime.d.ts +13 -0
  55. package/dist/server/runtime.js +201 -13
  56. package/dist/server/store.d.ts +2 -0
  57. package/dist/server/store.js +17 -1
  58. package/dist/server/subagents.js +2 -1
  59. package/dist/server/thinking-level-discovery.d.ts +6 -0
  60. package/dist/server/thinking-level-discovery.js +10 -3
  61. package/dist/server/turn-failure.js +3 -1
  62. package/dist/server/types.d.ts +13 -0
  63. package/dist/server/ws-server.js +1 -1
  64. package/dist/shared/context-compaction.d.ts +15 -0
  65. package/dist/shared/context-compaction.js +14 -0
  66. package/dist/shared/context-meter.d.ts +22 -0
  67. package/dist/shared/context-meter.js +9 -0
  68. package/dist/shared/group-chat.d.ts +8 -0
  69. package/dist/shared/model-discovery.d.ts +15 -0
  70. package/dist/shared/model-discovery.js +1 -0
  71. package/dist/shared/rsi.d.ts +33 -0
  72. package/dist/shared/tab-layout.d.ts +12 -0
  73. package/dist/shared/tab-layout.js +28 -0
  74. package/package.json +11 -1
  75. package/dist/client/assets/index-B5TLGyEw.css +0 -1
  76. package/dist/client/assets/index-rWE1xu-t.js +0 -350
@@ -0,0 +1,139 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ /** Server-owned discovery; network work never runs in a picker read or on a model turn. */
5
+ export class ModelDiscovery {
6
+ path;
7
+ hooks;
8
+ intervalMs;
9
+ saved = { states: {}, excluded: {} };
10
+ loaded;
11
+ writes = Promise.resolve();
12
+ pending;
13
+ timer;
14
+ wake;
15
+ controller;
16
+ closed = false;
17
+ started = false;
18
+ constructor(path, hooks, intervalMs = 4 * 60 * 60_000) {
19
+ this.path = path;
20
+ this.hooks = hooks;
21
+ this.intervalMs = intervalMs;
22
+ }
23
+ load() {
24
+ return this.loaded ??= (async () => {
25
+ try {
26
+ const raw = JSON.parse(await readFile(this.path, "utf8"));
27
+ if (!raw?.states || typeof raw.states !== "object" || Array.isArray(raw.states)
28
+ || !raw?.excluded || typeof raw.excluded !== "object" || Array.isArray(raw.excluded)
29
+ || !Object.values(raw.states).every((value) => value && typeof value.providerId === "string" && ["checking", "ready", "failed", "unsupported"].includes(value.state))
30
+ || !Object.values(raw.excluded).every(value => Array.isArray(value) && value.every(id => typeof id === "string")))
31
+ throw new Error("Invalid discovery state");
32
+ this.saved = raw;
33
+ for (const state of Object.values(this.saved.states))
34
+ if (state.state === "checking") {
35
+ state.state = "failed";
36
+ state.detail = "上次检查被服务重启中断,稍后自动重试。";
37
+ }
38
+ }
39
+ catch (error) {
40
+ if (error.code !== "ENOENT") {
41
+ this.loaded = undefined;
42
+ throw new Error("模型发现缓存无法读取;为保护已删除模型记录,暂不自动导入。");
43
+ }
44
+ }
45
+ })();
46
+ }
47
+ save() {
48
+ const task = this.writes.catch(() => undefined).then(async () => {
49
+ await mkdir(dirname(this.path), { recursive: true });
50
+ const temporary = `${this.path}.${randomUUID()}.tmp`;
51
+ await writeFile(temporary, JSON.stringify(this.saved), { mode: 0o600 });
52
+ await rename(temporary, this.path);
53
+ });
54
+ this.writes = task;
55
+ return task;
56
+ }
57
+ async snapshot() {
58
+ await this.load();
59
+ const targets = await this.hooks.targets();
60
+ return { intervalHours: this.intervalMs / 3_600_000, automatic: this.started && !this.closed, running: Boolean(this.pending), providers: targets.map(target => structuredClone({ ...(this.saved.states[target.scope] ?? { providerId: target.id, state: "ready", added: 0, detail: "等待后台首次检查。" }), name: target.name })) };
61
+ }
62
+ async exclude(scope, modelId) {
63
+ await this.load();
64
+ this.saved.excluded[scope] = [...new Set([...(this.saved.excluded[scope] ?? []), modelId])];
65
+ await this.save();
66
+ }
67
+ async include(scope, modelIds) {
68
+ await this.load();
69
+ if (!this.saved.excluded[scope]?.some(id => modelIds.includes(id)))
70
+ return;
71
+ this.saved.excluded[scope] = this.saved.excluded[scope].filter(id => !modelIds.includes(id));
72
+ await this.save();
73
+ }
74
+ start() {
75
+ if (this.closed)
76
+ return;
77
+ this.started = true;
78
+ this.request(false);
79
+ this.timer ??= setInterval(() => { void this.refresh().catch(() => undefined); }, 60_000);
80
+ this.timer.unref();
81
+ }
82
+ request(force = true) {
83
+ if (this.closed || !this.started)
84
+ return;
85
+ clearTimeout(this.wake);
86
+ this.wake = setTimeout(() => { void this.refresh(force).catch(() => undefined); }, 2000);
87
+ this.wake.unref();
88
+ }
89
+ refresh(force = false) {
90
+ if (this.closed)
91
+ return Promise.resolve();
92
+ if (this.pending)
93
+ return this.pending;
94
+ this.controller = new AbortController();
95
+ return this.pending = this.run(force, this.controller.signal).finally(() => { this.pending = undefined; this.controller = undefined; });
96
+ }
97
+ async run(force, signal) {
98
+ await this.load();
99
+ for (const target of await this.hooks.targets()) {
100
+ if (signal.aborted)
101
+ break;
102
+ const previous = this.saved.states[target.scope];
103
+ const retryMs = previous?.state === "failed" ? 15 * 60_000 : this.intervalMs;
104
+ if (!force && previous?.checkedAt && Date.now() - Date.parse(previous.checkedAt) < retryMs)
105
+ continue;
106
+ const state = { providerId: target.id, name: target.name, state: "checking", added: 0, ...(previous?.succeededAt ? { succeededAt: previous.succeededAt } : {}) };
107
+ this.saved.states[target.scope] = state;
108
+ try {
109
+ const models = await this.hooks.discover(target, AbortSignal.any([signal, AbortSignal.timeout(30_000)]), force);
110
+ if (signal.aborted)
111
+ break;
112
+ const excluded = new Set(this.saved.excluded[target.scope] ?? []);
113
+ const added = await this.hooks.apply(target, models.filter(model => !excluded.has(model.id)));
114
+ if (added === undefined) {
115
+ delete this.saved.states[target.scope];
116
+ continue;
117
+ }
118
+ if (added > 0 || target.builtin)
119
+ await this.hooks.changed();
120
+ Object.assign(state, { state: "ready", checkedAt: new Date().toISOString(), succeededAt: new Date().toISOString(), added, detail: added ? `发现 ${added} 个新模型,已加入列表。` : "检查完成,模型列表已是最新。" });
121
+ }
122
+ catch (error) {
123
+ if (signal.aborted)
124
+ break;
125
+ const unsupported = error.code === "DISCOVERY_UNSUPPORTED";
126
+ Object.assign(state, { state: unsupported ? "unsupported" : "failed", checkedAt: new Date().toISOString(), detail: unsupported ? "此接口未提供可用的模型枚举;继续使用已有模型。" : "检查失败,已保留已有模型;请检查供应商凭据、网络或代理,稍后自动重试。" });
127
+ }
128
+ await this.save();
129
+ }
130
+ }
131
+ async close() {
132
+ this.closed = true;
133
+ clearInterval(this.timer);
134
+ clearTimeout(this.wake);
135
+ this.controller?.abort();
136
+ await this.pending?.catch(() => undefined);
137
+ await this.writes.catch(() => undefined);
138
+ }
139
+ }
@@ -0,0 +1,3 @@
1
+ export declare const modelPolicyExtensionPath: () => string;
2
+ /** Uses Pi's public native provider registration, including in the bundled CLI runtime. */
3
+ export default function modelPolicyExtension(pi: any): void;
@@ -0,0 +1,82 @@
1
+ import { join, resolve } from "node:path";
2
+ import { homedir } from "node:os";
3
+ import { createModelNormalizer } from "./model-capabilities.js";
4
+ import { withModelRequestPolicy } from "./model-request-policy.js";
5
+ import { compactionStream } from "./hierarchical-compaction.js";
6
+ import { boundedCompaction } from "./bounded-compaction.js";
7
+ export const modelPolicyExtensionPath = () => resolve(import.meta.dirname, "../../agents/super-pi-model-policy/index.ts");
8
+ /** Uses Pi's public native provider registration, including in the bundled CLI runtime. */
9
+ export default function modelPolicyExtension(pi) {
10
+ const normalize = createModelNormalizer(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"));
11
+ const installed = new Set();
12
+ const apply = async (_event, ctx) => {
13
+ const current = ctx.model;
14
+ if (!current)
15
+ return;
16
+ if (!installed.has(current.provider)) {
17
+ const original = ctx.modelRegistry.getProvider(current.provider);
18
+ if (!original)
19
+ throw new Error("无法加载当前模型供应商的请求策略。");
20
+ const models = (original.getAllModels?.() ?? original.getModels()).map((model) => typeof model.contextWindow === "number" ? normalize(model) : model);
21
+ ctx.modelRegistry.registerProvider(current.provider, {
22
+ name: original.name, baseUrl: original.baseUrl, api: current.api, ...ctx.modelRegistry.getRegisteredProviderConfig(current.provider), models,
23
+ streamSimple: (model, context, options) => withModelRequestPolicy(normalize(model), options, routed => original.streamSimple(normalize(model), context, routed)),
24
+ });
25
+ installed.add(current.provider);
26
+ }
27
+ const next = normalize(ctx.modelRegistry.find(current.provider, current.id));
28
+ if (next && (next.contextWindow !== current.contextWindow || next.maxTokens !== current.maxTokens || next.reasoning !== current.reasoning || JSON.stringify(next.thinkingLevelMap) !== JSON.stringify(current.thinkingLevelMap))) {
29
+ if (!await pi.setModel(next))
30
+ throw new Error("修正模型参数后鉴权不可用,请检查供应商配置。");
31
+ }
32
+ };
33
+ pi.on("session_start", apply);
34
+ pi.on("model_select", apply);
35
+ pi.on("session_before_compact", async (event, ctx) => {
36
+ const model = normalize(ctx.model);
37
+ if (!model || model.contextWindow <= 4096)
38
+ return;
39
+ const branchIndex = new Map(event.branchEntries.map((entry, index) => [entry.id, index]));
40
+ const firstKeptIndex = branchIndex.get(event.preparation.firstKeptEntryId) ?? Infinity;
41
+ const projection = ctx.sessionManager.buildSessionProjection();
42
+ const kept = projection.entries.filter((entry) => (branchIndex.get(entry.sourceEntry.id) ?? -1) >= Number(firstKeptIndex)).flatMap((entry) => entry.messages);
43
+ const retainedTooLarge = JSON.stringify(kept).length > Math.max(1024, (model.contextWindow - 4096) * 2);
44
+ const sdk = await import("@earendil-works/pi-coding-agent");
45
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
46
+ if (!auth.ok)
47
+ throw new Error("上下文压缩鉴权失败:" + auth.error);
48
+ const retry = sdk.SettingsManager.create(ctx.cwd, process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent")).getRetrySettings();
49
+ let preparation = event.preparation;
50
+ let marker;
51
+ const boundary = () => { if (!marker) {
52
+ pi.appendEntry("super_pi_context_boundary", { reason: "target-window" });
53
+ marker = ctx.sessionManager.getLeafId();
54
+ } return marker; };
55
+ if (retainedTooLarge) {
56
+ // A whole retained user turn can exceed the new model even with keepRecentTokens=1024.
57
+ // Preserve every original entry; a non-message marker provides a safe new projection boundary.
58
+ preparation = { ...preparation, firstKeptEntryId: boundary(), messagesToSummarize: projection.messages, turnPrefixMessages: [], isSplitTurn: false, previousSummary: undefined };
59
+ }
60
+ const ledger = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
61
+ const stream = compactionStream(ctx.modelRegistry, (usage) => {
62
+ for (const [key, value] of Object.entries(usage ?? {}))
63
+ if (typeof value === "number" && Number.isFinite(value))
64
+ ledger[key] = (ledger[key] ?? 0) + value;
65
+ for (const [key, value] of Object.entries(usage?.cost ?? {}))
66
+ if (typeof value === "number" && Number.isFinite(value))
67
+ ledger.cost[key] = (ledger.cost[key] ?? 0) + value;
68
+ });
69
+ const active = new Set(pi.getActiveTools());
70
+ try {
71
+ const result = await boundedCompaction({ model, signal: event.signal, systemPrompt: ctx.getSystemPrompt(), tools: pi.getAllTools().filter((tool) => active.has(tool.name)).map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })), preparation, retained: retainedTooLarge ? [] : kept, toLlm: sdk.convertToLlm, boundary,
72
+ compact: (prepared, instructions, budget) => sdk.compact(prepared, model, auth.apiKey, auth.headers, [event.customInstructions, instructions].filter(Boolean).join("\n"), event.signal, pi.getThinkingLevel(), (selected, context, options) => stream(selected, context, { ...options, maxTokens: budget, reasoning: "low" }), auth.env, retry) });
73
+ return { compaction: { ...result, usage: ledger } };
74
+ }
75
+ catch (error) {
76
+ if (ledger.input || ledger.output || ledger.cacheRead || ledger.cacheWrite)
77
+ pi.appendEntry("super_pi_compaction_usage", { usage: ledger });
78
+ ctx.abort();
79
+ throw error;
80
+ }
81
+ });
82
+ }
@@ -0,0 +1,2 @@
1
+ /** Shared by embedded runtimes and public native providers inside isolated Pi workers. */
2
+ export declare function withModelRequestPolicy(model: any, options: any, start: (options: any) => any): any;
@@ -0,0 +1,30 @@
1
+ import { outputLimitDetail } from "./model-capabilities.js";
2
+ import { isOfficialMinimaxFlash } from "./thinking-level-discovery.js";
3
+ /** Shared by embedded runtimes and public native providers inside isolated Pi workers. */
4
+ export function withModelRequestPolicy(model, options, start) {
5
+ let budget, effort;
6
+ const routed = { ...options, onPayload: async (payload, selected) => {
7
+ const fittedBudget = payload.max_completion_tokens ?? payload.max_tokens;
8
+ const changed = await options?.onPayload?.(payload, selected);
9
+ const final = changed ?? payload;
10
+ if (isOfficialMinimaxFlash(model) && final.reasoning_effort === undefined)
11
+ final.reasoning_effort = "low";
12
+ budget = final.max_completion_tokens ?? final.max_tokens;
13
+ const requested = final.reasoning_effort ?? final.output_config?.effort;
14
+ effort = typeof requested === "string" && /^(off|minimal|low|medium|high|xhigh|max)$/.test(requested) ? requested : undefined;
15
+ const desired = Math.min(options?.maxTokens ?? model?.maxTokens, model?.maxTokens);
16
+ if (typeof budget === "number" && budget === fittedBudget && budget < 1024 && Number.isFinite(desired) && desired >= 1024 && budget < desired) {
17
+ throw new Error(`Context length exceeded: 上下文挤占输出空间,${desired} token 输出预算被压缩为 ${budget} token。需要先压缩会话上下文,不能用相同上下文继续空回复。`);
18
+ }
19
+ return changed;
20
+ } };
21
+ const stream = start(routed);
22
+ void stream?.result?.().then((message) => {
23
+ const detail = outputLimitDetail(message, budget, effort);
24
+ if (!detail || message.errorMessage?.includes("供应商结束标记 length;"))
25
+ return;
26
+ message.errorMessage = message.errorMessage ? `${message.errorMessage}\n${detail}` : detail;
27
+ console.warn("Super Pi model output limit:", detail);
28
+ }).catch(() => { });
29
+ return stream;
30
+ }
@@ -16,6 +16,7 @@
16
16
  * be announced as unhandled is still announced as unhandled - this bridge changes WHERE the events come
17
17
  * from, not what they mean.
18
18
  */
19
+ import { type ContextCompactionEvent } from "../shared/context-compaction.js";
19
20
  import type { PiQueueSnapshot, ToolCallNotice, ToolCallPreparing } from "./types.js";
20
21
  /**
21
22
  * Reads a `queue_update` payload, or returns undefined when the record is not one.
@@ -64,6 +65,7 @@ export type TurnItem =
64
65
  };
65
66
  /** The callbacks a turn supplies. The names match the RPC runtime's, so the two paths behave alike. */
66
67
  export interface TurnEventHandlers {
68
+ onCompaction?(event: ContextCompactionEvent): void;
67
69
  onToolCall?(call: ToolCallNotice): void;
68
70
  /**
69
71
  * Called when a tool that WRITES A FILE is announced, with the path it is about to write.
@@ -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
@@ -23,6 +23,7 @@
23
23
  * the transcript on disk while the live session still holds the old context in memory, and nothing in Pi
24
24
  * would notice the difference.
25
25
  */
26
+ import type { DiscoveredModel } from "./types.js";
26
27
  import type { PiImageContent } from "./types.js";
27
28
  import type { PiCacheWarmingMode } from "../shared/pi-cache-warming.js";
28
29
  /**
@@ -85,8 +86,16 @@ interface PiSdk {
85
86
  ModelRuntime: {
86
87
  create(options?: Record<string, unknown>): Promise<{
87
88
  getModel?: (provider: string, modelId: string) => unknown;
88
- getAvailable?: () => Promise<unknown[]>;
89
+ getAvailable?: (providerId?: string) => Promise<unknown[]>;
89
90
  getModels?: () => unknown[];
91
+ getAuth?: (provider: string, options?: {
92
+ signal?: AbortSignal;
93
+ }) => Promise<{
94
+ auth: {
95
+ apiKey?: string;
96
+ headers?: Record<string, string>;
97
+ };
98
+ } | undefined>;
90
99
  /**
91
100
  * Pi's own verdict on its model configuration - the schema error that empties every picker
92
101
  * when one entry in `models.json` is refused.
@@ -114,7 +123,10 @@ interface PiSdk {
114
123
  agentName?: string;
115
124
  }) => Promise<unknown>;
116
125
  logout?: (providerId: string) => Promise<void>;
117
- refresh?: () => Promise<unknown>;
126
+ refresh?: (options?: Record<string, unknown>) => Promise<{
127
+ aborted: boolean;
128
+ errors: Map<string, Error>;
129
+ }>;
118
130
  }>;
119
131
  };
120
132
  AuthStorage?: {
@@ -125,6 +137,11 @@ interface PiSdk {
125
137
  getDefaultProvider?: () => string | undefined;
126
138
  getDefaultModel?: () => string | undefined;
127
139
  getDefaultThinkingLevel?: () => string | undefined;
140
+ getCompactionSettings?(model: unknown): {
141
+ enabled: boolean;
142
+ reserveTokens: number;
143
+ keepRecentTokens: number;
144
+ };
128
145
  getCacheWarmingMode(): PiCacheWarmingMode;
129
146
  setCacheWarmingMode(mode: PiCacheWarmingMode): void;
130
147
  flush(): Promise<void>;
@@ -148,6 +165,17 @@ interface PiSdk {
148
165
  * module and returns, and the caller decides what to do with a failure.
149
166
  */
150
167
  export declare function warmPiSdk(): Promise<boolean>;
168
+ /** Refresh catalogs without changing credentials, defaults, or any running session. */
169
+ export declare function discoverPiProviderModels(input: {
170
+ id: string;
171
+ builtin: boolean;
172
+ baseUrl: string;
173
+ api: string;
174
+ agentDir: string;
175
+ signal: AbortSignal;
176
+ force: boolean;
177
+ catalogBaseUrl?: string;
178
+ }): Promise<DiscoveredModel[]>;
151
179
  export declare function piCacheWarmingMode(mode?: PiCacheWarmingMode): Promise<PiCacheWarmingMode>;
152
180
  /**
153
181
  * A model catalog read from Pi's SDK, with NO PROCESS.
@@ -436,6 +464,15 @@ export interface PiSessionLike {
436
464
  readonly model?: {
437
465
  provider?: string;
438
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;
439
476
  } | undefined;
440
477
  /** Pi's estimate for the current context, including its post-compaction unknown state. */
441
478
  getContextUsage?(): {
@@ -28,7 +28,8 @@ import { open, readdir } from "node:fs/promises";
28
28
  import { StringDecoder } from "node:string_decoder";
29
29
  import { dirname, join, resolve } from "node:path";
30
30
  import { createModelResolver } from "./model-context-window.js";
31
- import { installProviderProxy, proxyCredentialStore } from "./provider-proxy.js";
31
+ import { installProviderProxy, proxyCredentialStore, readProviderProxyEnv, withAuthProxy } from "./provider-proxy.js";
32
+ import { fetchRemoteModels, KNOWN_APIS } from "./providers.js";
32
33
  import { SOURCE_LINK_GUIDANCE } from "../shared/message-source-link.js";
33
34
  import { fileURLToPath, pathToFileURL } from "node:url";
34
35
  import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, readNativeToolSettings } from "./native-tool-settings.js";
@@ -56,6 +57,34 @@ export async function warmPiSdk() {
56
57
  return false;
57
58
  }
58
59
  }
60
+ /** Refresh catalogs without changing credentials, defaults, or any running session. */
61
+ export async function discoverPiProviderModels(input) {
62
+ const sdk = await loadSdk();
63
+ const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(input.agentDir, "auth.json"))) : undefined;
64
+ const runtime = await sdk.ModelRuntime.create({ credentials, authPath: join(input.agentDir, "auth.json"), modelsPath: join(input.agentDir, "models.json"), refreshOnCreate: false, signal: input.signal, ...(input.catalogBaseUrl ? { catalogBaseUrl: input.catalogBaseUrl } : {}) });
65
+ await installProviderProxy(runtime, input.agentDir);
66
+ const proxyEnv = await readProviderProxyEnv(input.agentDir, input.id);
67
+ if (input.builtin) {
68
+ if (!runtime.refresh)
69
+ throw new Error("当前 Pi SDK 不支持目录刷新。");
70
+ const result = await withAuthProxy(proxyEnv, () => runtime.refresh({ providers: [input.id], allowNetwork: true, force: input.force, signal: input.signal }), input.id);
71
+ if (result.aborted)
72
+ throw new Error("模型目录刷新超时。");
73
+ if (result.errors.has(input.id))
74
+ throw result.errors.get(input.id);
75
+ const available = await runtime.getAvailable?.(input.id) ?? runtime.getModels?.() ?? [];
76
+ return available.flatMap((item) => {
77
+ const model = item;
78
+ if (model.provider !== input.id || !KNOWN_APIS.includes(model.api))
79
+ return [];
80
+ return [{ id: model.id, name: model.name ?? model.id, reasoning: model.reasoning === true, imageInput: model.input?.includes("image") === true, contextWindow: model.contextWindow, maxTokens: model.maxTokens, ...(model.thinkingLevelMap ? { thinkingLevelMap: model.thinkingLevelMap } : {}) }];
81
+ });
82
+ }
83
+ const auth = await runtime.getAuth?.(input.id, { signal: input.signal });
84
+ const models = await fetchRemoteModels({ baseUrl: input.baseUrl, api: input.api, apiKey: auth?.auth.apiKey, headers: auth?.auth.headers, proxyEnv, signal: input.signal });
85
+ // /models may also enumerate embeddings, speech, moderation and image-generation endpoints.
86
+ return models.filter(model => !/(?:embedding|embed-|whisper|tts-|dall-e|moderation|transcrib|^rerank|^bge-|^text-embedding)/i.test(model.id));
87
+ }
59
88
  let sdkPromise;
60
89
  let sdkFailure;
61
90
  export async function piCacheWarmingMode(mode) {
@@ -384,6 +413,7 @@ export async function createPiSession(creation) {
384
413
  traceSession(creation.sessionId, "sdk.transcript.ready", startedAt, `bytes=${transcriptBytes(sessionManager)}`);
385
414
  const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(agentDir, "auth.json"))) : undefined;
386
415
  const modelRuntime = await sdk.ModelRuntime.create(credentials ? { credentials } : undefined);
416
+ const settingsManager = sdk.SettingsManager.create(creation.cwd, agentDir);
387
417
  await installProviderProxy(modelRuntime, agentDir);
388
418
  traceSession(creation.sessionId, "sdk.model-runtime", startedAt);
389
419
  // THE MODEL IS RESOLVED, NOT PASSED THROUGH. Pi's SDK takes a whole Model object - the provider's
@@ -404,6 +434,7 @@ export async function createPiSession(creation) {
404
434
  modelRuntime,
405
435
  resourceLoader: loader,
406
436
  sessionManager,
437
+ settingsManager,
407
438
  ...(nativePolicy.tools ? { tools: nativePolicy.tools } : {}),
408
439
  ...(nativePolicy.excludeTools ? { excludeTools: nativePolicy.excludeTools } : {}),
409
440
  ...(model ? { model } : {}),
@@ -425,6 +456,12 @@ export async function createPiSession(creation) {
425
456
  // The window the model REALLY has is arbitrated inside the resolver - see
426
457
  // `model-context-window.ts` for the whole reasoning and for the tests that hold it in place.
427
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
+ };
428
465
  return live;
429
466
  })();
430
467
  }
@@ -626,6 +663,7 @@ export async function loadPromptTemplateSummaries(cwd) {
626
663
  }
627
664
  export function superPiExtensionPaths(repositoryRoot) {
628
665
  const paths = [
666
+ join(repositoryRoot, "agents", "super-pi-model-policy", "index.ts"),
629
667
  join(repositoryRoot, "agents", "super-pi-native-tools", "index.ts"),
630
668
  join(repositoryRoot, "agents", "super-pi-task", "index.ts"),
631
669
  join(repositoryRoot, "agents", "super-pi-memory", "index.ts"),
@@ -11,6 +11,8 @@ export declare function readProviderProxyEnv(agentDir: string, providerId?: stri
11
11
  type Env = Record<string, string | undefined>;
12
12
  /** Apply scoped proxy values without changing the server's process environment. */
13
13
  export declare function providerProxyFetch(env: Env | undefined, baseFetch?: typeof fetch): typeof fetch | undefined;
14
+ /** OAuth adapters call global fetch. Route only the current async auth operation through its proxy. */
15
+ export declare function withAuthProxy<T>(env: Env | undefined, operation: () => Promise<T>, providerId?: string): Promise<T>;
14
16
  /** Keep Pi's own cross-process credential lock, and preserve scoped env on OAuth rotation/login. */
15
17
  export declare function proxyCredentialStore<T extends object>(store: T): T;
16
18
  /** Read provider routing independently of Pi's auth result: OAuth resolution omits credential.env. */
@@ -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";
@@ -91,7 +93,7 @@ const authFetchScope = new AsyncLocalStorage();
91
93
  let scopedFetch;
92
94
  let baseAuthFetch;
93
95
  /** OAuth adapters call global fetch. Route only the current async auth operation through its proxy. */
94
- async function withAuthProxy(env, operation, providerId) {
96
+ export async function withAuthProxy(env, operation, providerId) {
95
97
  const active = authFetchScope.getStore();
96
98
  env = mergeEnv(env, providerId && active?.providerId === providerId ? active.env : undefined);
97
99
  if (!Object.keys(env).some(key => /^(http_proxy|https_proxy|all_proxy|no_proxy)$/i.test(key))) {
@@ -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 original.call(target, model, context, routed);
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 original.call(target, model, context, { ...routed, fetch: requestFetch });
202
+ return start({ ...routed, fetch: requestFetch });
198
203
  };
199
204
  }
200
205
  }
@@ -186,6 +186,8 @@ export declare class ProviderRegistry {
186
186
  * accident - it has to be given one.
187
187
  */
188
188
  constructor(dataDir: string, piDir?: string);
189
+ get discoveryPath(): string;
190
+ get agentDir(): string;
189
191
  private networkQueue;
190
192
  private sharedNetworkRecord;
191
193
  sharedNetwork(known: ReadonlyArray<{
@@ -286,6 +288,8 @@ export declare class ProviderRegistry {
286
288
  * Full visual editor semantics: any provider in models.json is editable and removable.
287
289
  */
288
290
  applyToPi(previous: ProviderDefinition[], next: ProviderDefinition[]): Promise<void>;
291
+ /** Append discovery results without normalizing any existing model or touching auth.json. */
292
+ appendDiscovered(provider: ProviderDefinition, models: DiscoveredModel[]): Promise<() => Promise<void>>;
289
293
  /**
290
294
  * Writes the keys into Pi's `auth.json`.
291
295
  */
@@ -306,6 +310,8 @@ export declare function validateProvider(input: unknown): ProviderDefinition;
306
310
  */
307
311
  export declare function fetchRemoteModels(input: {
308
312
  baseUrl: string;
313
+ signal?: AbortSignal;
314
+ headers?: Record<string, string>;
309
315
  proxyEnv?: Record<string, string>;
310
316
  apiKey?: string;
311
317
  api?: string;