@evandu/super-pi 0.1.303 → 0.1.304
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/super-pi-managed-model/index.ts +2 -0
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +10 -6
- package/dist/client/assets/CodeMirrorEditor-BgCUmuUG.js +2 -0
- package/dist/client/assets/GitDiffEditor-BT1PriQU.js +29 -0
- package/dist/client/assets/index-2PIw_FRw.css +1 -0
- package/dist/client/assets/index-BklBoCmG.js +355 -0
- package/dist/client/index.html +2 -2
- package/dist/server/explicit-file-open.d.ts +2 -0
- package/dist/server/explicit-file-open.js +3 -2
- package/dist/server/files.d.ts +4 -1
- package/dist/server/files.js +24 -8
- package/dist/server/http-server.js +5 -5
- package/dist/server/managed-helper-model.d.ts +11 -0
- package/dist/server/managed-helper-model.js +58 -0
- package/dist/server/managed-model-adapter.js +4 -1
- package/dist/server/pi-session.js +1 -1
- package/dist/server/runtime.d.ts +1 -0
- package/dist/server/runtime.js +48 -4
- package/package.json +4 -1
- package/dist/client/assets/CodeMirrorEditor-DlcBTysV.js +0 -2
- package/dist/client/assets/GitDiffEditor-CyDiA4rj.js +0 -29
- package/dist/client/assets/index-DBuR5Y3G.css +0 -1
- package/dist/client/assets/index-DDvvcuuS.js +0 -354
package/dist/client/index.html
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
<link rel="alternate icon" href="/favicon.ico" />
|
|
9
9
|
<link rel="apple-touch-icon" href="/favicon.svg" />
|
|
10
10
|
<title>Super Pi</title>
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-BklBoCmG.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-2PIw_FRw.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
|
16
16
|
<div id="root"></div>
|
|
@@ -4,6 +4,7 @@ export declare function createExplicitFileOpen(): {
|
|
|
4
4
|
text: boolean;
|
|
5
5
|
path: string;
|
|
6
6
|
name: string;
|
|
7
|
+
writeTargetId?: string | undefined;
|
|
7
8
|
} | {
|
|
8
9
|
content: string;
|
|
9
10
|
eol: "\n" | "\r\n";
|
|
@@ -12,6 +13,7 @@ export declare function createExplicitFileOpen(): {
|
|
|
12
13
|
text: boolean;
|
|
13
14
|
path: string;
|
|
14
15
|
name: string;
|
|
16
|
+
writeTargetId?: string | undefined;
|
|
15
17
|
} | {
|
|
16
18
|
meta: import("./files.js").FileMeta;
|
|
17
19
|
text: boolean;
|
|
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { constants } from "node:fs";
|
|
3
3
|
import { lstat, open, realpath } from "node:fs/promises";
|
|
4
4
|
import { basename, isAbsolute, posix, resolve } from "node:path";
|
|
5
|
-
import { contains, decodeWorkspaceText, fileMetaFromStat, FilesError, hasBinaryExtension, MAX_FILE_BYTES, toRelative } from "./files.js";
|
|
5
|
+
import { contains, decodeWorkspaceText, fileMetaFromStat, FilesError, hasBinaryExtension, MAX_FILE_BYTES, toRelative, writeTargetId } from "./files.js";
|
|
6
6
|
import { explorerInternalPath, explorerPath } from "./workspace-file-operations.js";
|
|
7
7
|
const MAX_OPEN_TICKETS = 256;
|
|
8
8
|
function localAbsolute(path) {
|
|
@@ -76,7 +76,8 @@ export function createExplicitFileOpen() {
|
|
|
76
76
|
const scoped = toRelative(canonicalRoot, path);
|
|
77
77
|
await explorerPath(workspace, root, scoped);
|
|
78
78
|
const displayPath = contains(resolve(root), selected) ? toRelative(root, selected) : scoped;
|
|
79
|
-
|
|
79
|
+
const contents = await readOpenedFile(path);
|
|
80
|
+
return { path: displayPath, name: basename(selected), ...contents, ...(contents.text ? { writeTargetId: await writeTargetId(resolve(root, displayPath)) } : {}) };
|
|
80
81
|
}
|
|
81
82
|
const contents = await readOpenedFile(path);
|
|
82
83
|
const ticket = randomUUID();
|
package/dist/server/files.d.ts
CHANGED
|
@@ -77,6 +77,8 @@ export declare function resolveInsideRoot(root: string, requested: string | null
|
|
|
77
77
|
* user has been told it is safe to save.
|
|
78
78
|
*/
|
|
79
79
|
export declare function fileEtag(path: string): Promise<string>;
|
|
80
|
+
/** Identify the directory entry atomically replaced by a save, preserving a final symlink's name. */
|
|
81
|
+
export declare function writeTargetId(target: string): Promise<string>;
|
|
80
82
|
export type FileMeta = {
|
|
81
83
|
etag: string;
|
|
82
84
|
size: number;
|
|
@@ -208,6 +210,7 @@ export type SearchResult = {
|
|
|
208
210
|
*/
|
|
209
211
|
export declare function searchByName(root: string, query: string): Promise<SearchResult>;
|
|
210
212
|
export type FileContents = {
|
|
213
|
+
writeTargetId: string;
|
|
211
214
|
path: string;
|
|
212
215
|
content: string;
|
|
213
216
|
meta: FileMeta;
|
|
@@ -256,7 +259,7 @@ export type WriteOutcome = {
|
|
|
256
259
|
* is derived from the target's OWN name rather than living in the system temp directory, because a rename
|
|
257
260
|
* across filesystems is not atomic and would silently become a copy.
|
|
258
261
|
*/
|
|
259
|
-
export declare function writeWorkspaceFile(root: string, requested: string, content: string, baseEtag: string | null | undefined): Promise<WriteOutcome>;
|
|
262
|
+
export declare function writeWorkspaceFile(root: string, requested: string, content: string, baseEtag: string | null | undefined, baseTargetId?: string): Promise<WriteOutcome>;
|
|
260
263
|
/** Every `FilesError` carries the status it should be rendered with; anything else is a real fault and
|
|
261
264
|
* becomes a 500 rather than being dressed up as a refusal the user is asked to understand. */
|
|
262
265
|
export declare function describe(error: unknown): {
|
package/dist/server/files.js
CHANGED
|
@@ -311,6 +311,12 @@ export function resolveInsideRoot(root, requested) {
|
|
|
311
311
|
export async function fileEtag(path) {
|
|
312
312
|
return fileMetaFromStat(await stat(path, { bigint: true })).etag;
|
|
313
313
|
}
|
|
314
|
+
/** Identify the directory entry atomically replaced by a save, preserving a final symlink's name. */
|
|
315
|
+
export async function writeTargetId(target) {
|
|
316
|
+
const parent = await realpath(dirname(target));
|
|
317
|
+
const key = join(parent, basename(target));
|
|
318
|
+
return createHash("sha256").update("write-target-v1\0" + key).digest("hex");
|
|
319
|
+
}
|
|
314
320
|
export async function fileMeta(path) {
|
|
315
321
|
return fileMetaFromStat(await stat(path, { bigint: true }));
|
|
316
322
|
}
|
|
@@ -608,7 +614,7 @@ export async function readWorkspaceFile(root, requested) {
|
|
|
608
614
|
if (meta.size > MAX_FILE_BYTES) {
|
|
609
615
|
throw new FilesError(413, `文件过大(${(meta.size / 1024 / 1024).toFixed(1)}MB),上限 ${MAX_FILE_BYTES / 1024 / 1024}MB:${requested}`, "too_large");
|
|
610
616
|
}
|
|
611
|
-
return { path: toRelative(root, target), meta, ...decodeWorkspaceText(await readFile(target), requested) };
|
|
617
|
+
return { path: toRelative(root, target), meta, ...decodeWorkspaceText(await readFile(target), requested), writeTargetId: await writeTargetId(target) };
|
|
612
618
|
}
|
|
613
619
|
export function decodeWorkspaceText(raw, requested) {
|
|
614
620
|
if (looksBinary(raw))
|
|
@@ -650,13 +656,23 @@ const writeLocks = new Map();
|
|
|
650
656
|
* is derived from the target's OWN name rather than living in the system temp directory, because a rename
|
|
651
657
|
* across filesystems is not atomic and would silently become a copy.
|
|
652
658
|
*/
|
|
653
|
-
export async function writeWorkspaceFile(root, requested, content, baseEtag) {
|
|
654
|
-
const
|
|
655
|
-
const
|
|
659
|
+
export async function writeWorkspaceFile(root, requested, content, baseEtag, baseTargetId) {
|
|
660
|
+
const logicalTarget = await resolveInsideRoot(root, requested);
|
|
661
|
+
const parent = await realpath(dirname(logicalTarget)).catch((error) => {
|
|
662
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
663
|
+
throw new FilesError(428, `文件不存在,本面板只允许写入已存在的文件:${requested}`, "missing_target");
|
|
664
|
+
throw error;
|
|
665
|
+
});
|
|
666
|
+
const target = join(parent, basename(logicalTarget));
|
|
667
|
+
if (baseTargetId && await writeTargetId(target) !== baseTargetId)
|
|
668
|
+
throw new FilesError(409, "文件指向的保存目标已变化,未写入;原草稿已保留", "target_changed");
|
|
669
|
+
// A directory mutex also serializes case aliases without merging distinct case-sensitive entries.
|
|
670
|
+
const writeKey = parent;
|
|
671
|
+
const previous = writeLocks.get(writeKey) ?? Promise.resolve();
|
|
656
672
|
let release;
|
|
657
673
|
const currentLock = new Promise((resolve) => { release = resolve; });
|
|
658
674
|
const queued = previous.then(() => currentLock);
|
|
659
|
-
writeLocks.set(
|
|
675
|
+
writeLocks.set(writeKey, queued);
|
|
660
676
|
await previous;
|
|
661
677
|
try {
|
|
662
678
|
const info = await stat(target).catch((error) => {
|
|
@@ -720,10 +736,10 @@ export async function writeWorkspaceFile(root, requested, content, baseEtag) {
|
|
|
720
736
|
finally {
|
|
721
737
|
await import("node:fs/promises").then(({ rm }) => rm(temporary, { recursive: true, force: true })).catch(() => { });
|
|
722
738
|
release();
|
|
723
|
-
if (writeLocks.get(
|
|
724
|
-
writeLocks.delete(
|
|
739
|
+
if (writeLocks.get(writeKey) === queued)
|
|
740
|
+
writeLocks.delete(writeKey);
|
|
725
741
|
}
|
|
726
|
-
return { path: toRelative(root,
|
|
742
|
+
return { path: toRelative(root, logicalTarget), meta: await fileMeta(target), created: false };
|
|
727
743
|
}
|
|
728
744
|
catch (error) {
|
|
729
745
|
release();
|
|
@@ -2002,7 +2002,7 @@ export function createHttpServer(options) {
|
|
|
2002
2002
|
const editSession = checkout?.path ?? sessionRoot;
|
|
2003
2003
|
await explorerPath(editRoot, editSession, body.path, true);
|
|
2004
2004
|
const path = await workspacePathFromSession(editRoot, editSession, body.path);
|
|
2005
|
-
const saved = await serializeWorkspaceWrite(workspace.path, () => writeWorkspaceFile(editRoot, path, body.content, body.baseEtag));
|
|
2005
|
+
const saved = await serializeWorkspaceWrite(workspace.path, () => writeWorkspaceFile(editRoot, path, body.content, body.baseEtag, typeof body.baseTargetId === "string" ? body.baseTargetId : undefined));
|
|
2006
2006
|
broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id, paths: checkout ? [] : [path] });
|
|
2007
2007
|
json(200, saved);
|
|
2008
2008
|
return;
|
|
@@ -2104,7 +2104,7 @@ export function createHttpServer(options) {
|
|
|
2104
2104
|
gitIndexFileContent(editRoot, path),
|
|
2105
2105
|
readWorkspaceFile(editRoot, path),
|
|
2106
2106
|
]);
|
|
2107
|
-
json(200, { path: file.path, original, content: file.content, eol: file.eol, bom: file.bom, meta: file.meta });
|
|
2107
|
+
json(200, { path: file.path, original, content: file.content, eol: file.eol, bom: file.bom, meta: file.meta, writeTargetId: file.writeTargetId });
|
|
2108
2108
|
}
|
|
2109
2109
|
else if (op === "diff") {
|
|
2110
2110
|
const path = url.searchParams.get("path");
|
|
@@ -3782,12 +3782,12 @@ export function createHttpServer(options) {
|
|
|
3782
3782
|
const meta = await fileMeta(resolved);
|
|
3783
3783
|
const path = toRelative(root, resolved);
|
|
3784
3784
|
context.fileIndexes?.get(indexKey)?.recordFile(path, meta);
|
|
3785
|
-
json(200, { path, ...meta });
|
|
3785
|
+
json(200, { path, ...meta, writeTargetId: await import("./files.js").then(files => files.writeTargetId(resolved)) });
|
|
3786
3786
|
return;
|
|
3787
3787
|
}
|
|
3788
3788
|
const file = await readWorkspaceFile(root, rel);
|
|
3789
3789
|
context.fileIndexes?.get(indexKey)?.recordFile(file.path, file.meta);
|
|
3790
|
-
json(200, { path: file.path, content: file.content, eol: file.eol, bom: file.bom, meta: file.meta, maxBytes: MAX_FILE_BYTES });
|
|
3790
|
+
json(200, { path: file.path, content: file.content, eol: file.eol, bom: file.bom, meta: file.meta, maxBytes: MAX_FILE_BYTES, writeTargetId: file.writeTargetId });
|
|
3791
3791
|
return;
|
|
3792
3792
|
}
|
|
3793
3793
|
if (request.method === "PUT") {
|
|
@@ -3824,7 +3824,7 @@ export function createHttpServer(options) {
|
|
|
3824
3824
|
const { path, content, baseEtag } = parsed;
|
|
3825
3825
|
const outcome = await serializeWorkspaceWrite(workspace.path, async () => {
|
|
3826
3826
|
await explorerPath(workspace.path, root, path, true);
|
|
3827
|
-
const saved = await writeWorkspaceFile(root, path, content, baseEtag);
|
|
3827
|
+
const saved = await writeWorkspaceFile(root, path, content, baseEtag, typeof parsed.baseTargetId === "string" ? parsed.baseTargetId : undefined);
|
|
3828
3828
|
const changedPath = await workspacePathFromSession(workspace.path, root, saved.path);
|
|
3829
3829
|
context.fileIndexes?.get(indexKey)?.recordFile(saved.path, saved.meta);
|
|
3830
3830
|
refreshWorkspaceIndex(context.fileIndexes, workspaceId, changedPath, workspace.path);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ManagedModelConfig } from "./managed-model-adapter.js";
|
|
3
|
+
type Context = Pick<ExtensionContext, "model" | "modelRegistry" | "sessionManager" | "signal">;
|
|
4
|
+
/** Pi uses this sentinel when its initial availability snapshot did not contain a default. */
|
|
5
|
+
export declare function isUnresolvedModel(model: {
|
|
6
|
+
provider?: unknown;
|
|
7
|
+
id?: unknown;
|
|
8
|
+
} | undefined): boolean;
|
|
9
|
+
/** Repair startup before RPC input is attached, preserving the session's actual model precedence. */
|
|
10
|
+
export declare function initializeManagedHelperModel(config: ManagedModelConfig, pi: Pick<ExtensionAPI, "getSettings" | "setModel">, ctx: Context, timeoutMs?: number): Promise<void>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
/** Pi uses this sentinel when its initial availability snapshot did not contain a default. */
|
|
3
|
+
export function isUnresolvedModel(model) {
|
|
4
|
+
return !model || !model.provider || !model.id || model.provider === "unknown" && model.id === "unknown";
|
|
5
|
+
}
|
|
6
|
+
// Read only the current branch. A virtual model selection survives the physical responses it routes.
|
|
7
|
+
function branchSelection(branch, registry) {
|
|
8
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
9
|
+
const entry = branch[i];
|
|
10
|
+
if (entry.type === "model_change")
|
|
11
|
+
return { provider: entry.provider, modelId: entry.modelId };
|
|
12
|
+
if (entry.type !== "message" || entry.message.role !== "assistant" || entry.message.api === "pi-virtual")
|
|
13
|
+
continue;
|
|
14
|
+
for (let j = i - 1; j >= 0; j--) {
|
|
15
|
+
const change = branch[j];
|
|
16
|
+
if (change.type !== "model_change")
|
|
17
|
+
continue;
|
|
18
|
+
if (registry.find(change.provider, change.modelId)?.api === "pi-virtual")
|
|
19
|
+
return { provider: change.provider, modelId: change.modelId };
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
return { provider: entry.message.provider, modelId: entry.message.model };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Repair startup before RPC input is attached, preserving the session's actual model precedence. */
|
|
26
|
+
export async function initializeManagedHelperModel(config, pi, ctx, timeoutMs = 30_000) {
|
|
27
|
+
const unresolved = isUnresolvedModel(ctx.model);
|
|
28
|
+
let target;
|
|
29
|
+
if (!unresolved) {
|
|
30
|
+
target = { provider: ctx.model.provider, modelId: ctx.model.id };
|
|
31
|
+
// A real non-managed provider is Pi's decision, not a reason to select the entry's default.
|
|
32
|
+
if (!config.models.some(model => model.provider === target.provider && model.id === target.modelId))
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
target = branchSelection(ctx.sessionManager.getBranch(), ctx.modelRegistry);
|
|
37
|
+
const settings = pi.getSettings();
|
|
38
|
+
if (!target && settings.defaultProvider && settings.defaultModel)
|
|
39
|
+
target = { provider: settings.defaultProvider, modelId: settings.defaultModel };
|
|
40
|
+
target ??= config.defaultModel;
|
|
41
|
+
}
|
|
42
|
+
const model = target && ctx.modelRegistry.find(target.provider, target.modelId);
|
|
43
|
+
if (!model || isUnresolvedModel(model))
|
|
44
|
+
throw new Error("托管 Pi 未能恢复有效模型,请检查当前历史模型与默认模型配置;不会自动改用其他模型。");
|
|
45
|
+
const deadline = Date.now() + timeoutMs;
|
|
46
|
+
// registerNativeProvider starts a refresh without awaiting it. A later awaited refresh may be
|
|
47
|
+
// invalidated by that pass, so its completion alone does not prove the availability snapshot is ready.
|
|
48
|
+
while (!ctx.modelRegistry.getAvailable().some(item => item.provider === model.provider && item.id === model.id)) {
|
|
49
|
+
ctx.signal?.throwIfAborted();
|
|
50
|
+
const remaining = deadline - Date.now();
|
|
51
|
+
if (remaining <= 0)
|
|
52
|
+
throw new Error(`托管模型 ${model.provider}/${model.id} 的可用目录未在 ${timeoutMs / 1000} 秒内就绪,请重试或检查模型配置。`);
|
|
53
|
+
await delay(Math.min(25, remaining), undefined, { signal: ctx.signal });
|
|
54
|
+
}
|
|
55
|
+
ctx.signal?.throwIfAborted();
|
|
56
|
+
if (unresolved && !await pi.setModel(model))
|
|
57
|
+
throw new Error(`托管 Pi 无法选择已恢复的模型 ${model.provider}/${model.id},请检查模型目录初始化状态。`);
|
|
58
|
+
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { Agent } from "undici";
|
|
2
3
|
import { MODEL_OPTION_KEYS, MODEL_REQUEST_HEADER, ModelFlowTrace, modelRequestId } from "./managed-model-flow.js";
|
|
3
4
|
import { MODEL_STREAM_PROTOCOL, ModelWireDecoder } from "./managed-model-wire.js";
|
|
5
|
+
// This authenticated channel is restricted to loopback, independently of provider/global proxies.
|
|
6
|
+
const modelChannelDispatcher = new Agent();
|
|
4
7
|
export async function readManagedModelConfig() {
|
|
5
8
|
const path = process.env.SUPER_PI_MANAGED_CONFIG;
|
|
6
9
|
if (!path)
|
|
@@ -47,7 +50,7 @@ export async function managedProviderDefinitions(config) {
|
|
|
47
50
|
const latest = await readManagedModelConfig() ?? config;
|
|
48
51
|
const { signal, ...rest } = options ?? {};
|
|
49
52
|
const safeOptions = Object.fromEntries(Object.entries(rest).filter(([key, value]) => MODEL_OPTION_KEYS.includes(key) && typeof value !== "function"));
|
|
50
|
-
const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json", [MODEL_REQUEST_HEADER]: requestId }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions, streamProtocol: MODEL_STREAM_PROTOCOL }) }).catch(cause => {
|
|
53
|
+
const response = await fetch(latest.endpoint, { method: "POST", signal, dispatcher: modelChannelDispatcher, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json", [MODEL_REQUEST_HEADER]: requestId }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions, streamProtocol: MODEL_STREAM_PROTOCOL }) }).catch(cause => {
|
|
51
54
|
if (signal?.aborted)
|
|
52
55
|
throw cause;
|
|
53
56
|
const detail = transportDetail(cause);
|
|
@@ -234,7 +234,7 @@ async function resolveDefaultModel(sdk, options) {
|
|
|
234
234
|
});
|
|
235
235
|
session = created.session;
|
|
236
236
|
const model = session.model;
|
|
237
|
-
if (typeof model?.provider !== "string" || !model.provider || typeof model.id !== "string" || !model.id)
|
|
237
|
+
if (typeof model?.provider !== "string" || !model.provider || typeof model.id !== "string" || !model.id || model.provider === "unknown" && model.id === "unknown")
|
|
238
238
|
return undefined;
|
|
239
239
|
return { model: { provider: model.provider, modelId: model.id }, thinking: sessionThinking(session) };
|
|
240
240
|
}
|
package/dist/server/runtime.d.ts
CHANGED
|
@@ -1276,6 +1276,7 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
1276
1276
|
groupMembersBusy(workspaceId: string, roomId: string): boolean;
|
|
1277
1277
|
stopGroupMembers(workspaceId: string, roomId: string, memberIds: string[]): Promise<void>;
|
|
1278
1278
|
forgetGroupMemberSessions(workspaceId: string, roomId: string): Promise<void>;
|
|
1279
|
+
private confirmManagedHelperModel;
|
|
1279
1280
|
private completeOnce;
|
|
1280
1281
|
/**
|
|
1281
1282
|
* The live session for a conversation, if there is one.
|
package/dist/server/runtime.js
CHANGED
|
@@ -45,6 +45,9 @@ const traceLatency = (conversationId, phase, startedAt, extra = "") => {
|
|
|
45
45
|
return;
|
|
46
46
|
console.warn(`[super-pi latency] conversation=${conversationId} phase=${phase} elapsedMs=${Math.round(performance.now() - startedAt)}${extra ? ` ${extra}` : ""}`);
|
|
47
47
|
};
|
|
48
|
+
// Let the managed startup hook see an explicit helper selection before RPC commands are accepted.
|
|
49
|
+
const managedHelperArgs = (model) => process.env.SUPER_PI_MANAGED_CONFIG && model?.provider && model.modelId
|
|
50
|
+
? ["--provider", model.provider, "--model", model.modelId] : [];
|
|
48
51
|
/** A steer that provably never reached Pi; the caller may safely use the next turn instead. */
|
|
49
52
|
export class SteerUnavailableError extends Error {
|
|
50
53
|
}
|
|
@@ -2732,7 +2735,7 @@ export class PiRpcRuntime {
|
|
|
2732
2735
|
// The selected model is carried over, but the current conversation transcript and its live cache are
|
|
2733
2736
|
// deliberately not: title generation is an isolated, bounded one-shot request.
|
|
2734
2737
|
const selectedModel = conversation.model;
|
|
2735
|
-
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())], {
|
|
2738
|
+
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()), ...managedHelperArgs(selectedModel).map(arg => shellQuote(arg))], {
|
|
2736
2739
|
cwd: resolve(cwd),
|
|
2737
2740
|
env: { ...process.env, ...await readProviderProxyEnv(defaultAgentDir(), selectedModel?.provider) },
|
|
2738
2741
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -2768,6 +2771,7 @@ export class PiRpcRuntime {
|
|
|
2768
2771
|
if (modelResponse.success !== true)
|
|
2769
2772
|
throw new Error(modelResponse.error || `Pi 无法使用当前会话模型 ${selectedModel.provider}/${selectedModel.modelId}`);
|
|
2770
2773
|
}
|
|
2774
|
+
await this.confirmManagedHelperModel(channel, deadline, signal);
|
|
2771
2775
|
// Reasoning adds latency without improving a short session label. Keep this one-shot call fast
|
|
2772
2776
|
// even when the user's normal default thinking level is high.
|
|
2773
2777
|
const thinkingResponse = await channel.request({ id: "autotitle_thinking", type: "set_thinking_level", level: "off" }, Math.max(1, Math.min(30_000, deadline - Date.now())));
|
|
@@ -2784,7 +2788,10 @@ export class PiRpcRuntime {
|
|
|
2784
2788
|
transcript,
|
|
2785
2789
|
].join("\n"),
|
|
2786
2790
|
});
|
|
2787
|
-
let settled = false, text = "";
|
|
2791
|
+
let settled = false, text = "", failure;
|
|
2792
|
+
const noteTitleOutcome = (message, reason) => {
|
|
2793
|
+
failure = ["error", "aborted", "length"].includes(message?.stopReason ?? reason ?? "") ? message?.errorMessage || "模型未完成标题生成" : undefined;
|
|
2794
|
+
};
|
|
2788
2795
|
while (!settled && Date.now() < deadline) {
|
|
2789
2796
|
if (signal?.aborted)
|
|
2790
2797
|
throw new Error("已取消");
|
|
@@ -2793,6 +2800,11 @@ export class PiRpcRuntime {
|
|
|
2793
2800
|
continue;
|
|
2794
2801
|
if (record.type === "message_update" && record.assistantMessageEvent?.type === "text_delta")
|
|
2795
2802
|
text += record.assistantMessageEvent.delta ?? "";
|
|
2803
|
+
if (record.type === "message_update" && ["done", "error"].includes(record.assistantMessageEvent?.type ?? "")) {
|
|
2804
|
+
noteTitleOutcome(record.assistantMessageEvent?.message, record.assistantMessageEvent?.type === "error" ? "error" : record.assistantMessageEvent?.reason);
|
|
2805
|
+
}
|
|
2806
|
+
if (record.type === "agent_end" && !record.willRetry && record.messages)
|
|
2807
|
+
noteTitleOutcome([...record.messages].reverse().find(message => message.role === "assistant"));
|
|
2796
2808
|
if (record.type === "agent_settled")
|
|
2797
2809
|
settled = true;
|
|
2798
2810
|
if (record.type === "response" && record.id === "autotitle_prompt" && record.success === false)
|
|
@@ -2802,6 +2814,8 @@ export class PiRpcRuntime {
|
|
|
2802
2814
|
}
|
|
2803
2815
|
if (!settled)
|
|
2804
2816
|
throw new Error(`模型在 ${TIMEOUT_MS / 1000} 秒内没有返回标题`);
|
|
2817
|
+
if (failure)
|
|
2818
|
+
throw new Error(failure);
|
|
2805
2819
|
// A model asked for "only the title" still wraps it now and then. Stripping the wrappers is not
|
|
2806
2820
|
// cosmetic: without it a leading quote or a `Title:` prefix becomes the first characters of every
|
|
2807
2821
|
// title in the sidebar.
|
|
@@ -2849,11 +2863,40 @@ export class PiRpcRuntime {
|
|
|
2849
2863
|
await this.groupLifecycle?.forget(workspaceId, roomId);
|
|
2850
2864
|
await (this.memberSessions ??= new GroupMemberSessions(join(this.sessionDir, "group-members"))).removeRoom(workspaceId, roomId);
|
|
2851
2865
|
}
|
|
2866
|
+
async confirmManagedHelperModel(channel, deadline, signal) {
|
|
2867
|
+
if (!process.env.SUPER_PI_MANAGED_CONFIG)
|
|
2868
|
+
return;
|
|
2869
|
+
signal?.throwIfAborted();
|
|
2870
|
+
const remaining = deadline - Date.now();
|
|
2871
|
+
if (remaining <= 0)
|
|
2872
|
+
throw new Error("托管辅助请求在模型初始化完成前超时,请重试。");
|
|
2873
|
+
const request = channel.request({ id: "managed_helper_state", type: "get_state" }, Math.min(30_000, remaining));
|
|
2874
|
+
let abort;
|
|
2875
|
+
let response;
|
|
2876
|
+
try {
|
|
2877
|
+
response = signal ? await Promise.race([request, new Promise((_resolve, reject) => {
|
|
2878
|
+
abort = () => reject(signal.reason ?? new Error("已取消"));
|
|
2879
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
2880
|
+
if (signal.aborted)
|
|
2881
|
+
abort();
|
|
2882
|
+
})]) : await request;
|
|
2883
|
+
}
|
|
2884
|
+
finally {
|
|
2885
|
+
if (abort)
|
|
2886
|
+
signal?.removeEventListener("abort", abort);
|
|
2887
|
+
}
|
|
2888
|
+
signal?.throwIfAborted();
|
|
2889
|
+
if (response.success !== true)
|
|
2890
|
+
throw new Error(response.error || "无法确认托管辅助请求的模型状态。");
|
|
2891
|
+
if (!describeModel(response.data?.model)) {
|
|
2892
|
+
throw new Error("托管 Pi 尚未选定有效模型,请检查历史模型、默认模型与模型目录初始化状态后重试。此错误不表示入口缺少 API Key。");
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2852
2895
|
async completeOnce(input, sessionFile) {
|
|
2853
2896
|
if (!this.pi.found)
|
|
2854
2897
|
throw new Error(this.pi.reason);
|
|
2855
2898
|
const executable = Boolean(input.agent && input.onToolStart);
|
|
2856
|
-
const args = ["--mode", "rpc", ...(sessionFile ? ["--session", sessionFile] : ["--no-session"]), "--no-mcp"];
|
|
2899
|
+
const args = ["--mode", "rpc", ...(sessionFile ? ["--session", sessionFile] : ["--no-session"]), "--no-mcp", ...managedHelperArgs(input.model)];
|
|
2857
2900
|
if (executable)
|
|
2858
2901
|
args.push(...superPiExtensionPaths(repositoryRootFrom()).flatMap(path => ["--extension", path]));
|
|
2859
2902
|
else
|
|
@@ -2888,6 +2931,7 @@ export class PiRpcRuntime {
|
|
|
2888
2931
|
if (response.success !== true)
|
|
2889
2932
|
throw new Error(response.error || "Pi 无法选择指定模型");
|
|
2890
2933
|
}
|
|
2934
|
+
await this.confirmManagedHelperModel(channel, deadline, input.signal);
|
|
2891
2935
|
if (input.onModel) {
|
|
2892
2936
|
let selected = input.model;
|
|
2893
2937
|
try {
|
|
@@ -3534,7 +3578,7 @@ export function describeModel(value) {
|
|
|
3534
3578
|
if (!value || typeof value !== "object")
|
|
3535
3579
|
return undefined;
|
|
3536
3580
|
const model = value;
|
|
3537
|
-
if (typeof model.provider !== "string" || model.provider === "" || typeof model.id !== "string" || model.id === "")
|
|
3581
|
+
if (typeof model.provider !== "string" || model.provider === "" || typeof model.id !== "string" || model.id === "" || model.provider === "unknown" && model.id === "unknown")
|
|
3538
3582
|
return undefined;
|
|
3539
3583
|
const label = typeof model.name === "string" && model.name !== "" ? model.name : model.id;
|
|
3540
3584
|
// Anything that is not an array of strings is treated as absent rather than searched with
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"superPi": {
|
|
4
4
|
"managedDirectListener": true
|
|
5
5
|
},
|
|
6
|
-
"version": "0.1.
|
|
6
|
+
"version": "0.1.304",
|
|
7
7
|
"description": "Web control plane and companion for Pi",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"type": "module",
|
|
@@ -83,6 +83,7 @@
|
|
|
83
83
|
"scripts/desktop-runtime.test.mjs",
|
|
84
84
|
"scripts/managed-ssh.test.mjs",
|
|
85
85
|
"scripts/managed-model.test.mjs",
|
|
86
|
+
"scripts/managed-helper-default.test.mjs",
|
|
86
87
|
"scripts/managed-model-flow.test.mjs",
|
|
87
88
|
"scripts/managed-offline-recovery.test.mjs",
|
|
88
89
|
"scripts/multi-server.test.mjs",
|
|
@@ -227,6 +228,7 @@
|
|
|
227
228
|
"scripts/files-api.test.mjs",
|
|
228
229
|
"scripts/http-body-utf8-chunking.test.mjs",
|
|
229
230
|
"scripts/files-eol-roundtrip.test.mjs",
|
|
231
|
+
"scripts/document-drafts.test.mjs",
|
|
230
232
|
"scripts/files-missing-path.test.mjs",
|
|
231
233
|
"scripts/file-changes.test.mjs",
|
|
232
234
|
"scripts/file-index.test.mjs",
|
|
@@ -343,6 +345,7 @@
|
|
|
343
345
|
"scripts/git-panel-upgrade-browser.test.mjs",
|
|
344
346
|
"scripts/welcome-workspace-git-browser.test.mjs",
|
|
345
347
|
"scripts/editor-search-design-browser.test.mjs",
|
|
348
|
+
"scripts/workbench-document-drafts-browser.test.mjs",
|
|
346
349
|
"scripts/terminal-activity-focus-browser.test.mjs",
|
|
347
350
|
"scripts/context-meter-browser.test.mjs",
|
|
348
351
|
"scripts/rsi-sidebar-browser.test.mjs",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-D978o95T.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-DTIPfQj7.js","assets/dist-S5ntGzJB.js","assets/dist-Cus6_oaF.js","assets/dist-DP4hrTBF.js","assets/dist-Qjm1p8SR.js","assets/dist-BJHpSQV1.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{_ as t,c as n,g as r,h as i,i as a,l as o,o as s,r as c,s as l,u,v as d,y as f}from"./index-DDvvcuuS.js";var p=e(f(),1);function m(e,t,n,r){return[n.EditorView.decorations.compute([`selection`,`doc`],e=>n.Decoration.set(e.selection.ranges.filter(e=>!e.empty).map(e=>n.Decoration.mark({class:`cm-workbench-selectedText`}).range(e.from,e.to)),!0)),n.ViewPlugin.define(e=>{let n=null,i,a=!1,s=e=>{n&&(e===`expanded`?(a=!a,l()):n.querySelector(`input[name="${e===`caseSensitive`?`case`:e===`wholeWord`?`word`:`re`}"]`)?.click())},c=e=>{let t=o(e);t&&(e.preventDefault(),e.stopPropagation(),s(t))},l=()=>{if(!n||!i)return;let r=t.getSearchQuery(e.state);if(n.dataset.editorSearchExpanded=String(a),i.update({caseSensitive:r.caseSensitive,wholeWord:r.wholeWord,regexp:r.regexp,expanded:a}),n.querySelector(`[data-find-error]`)?.remove(),r.search&&!r.valid){let e=document.createElement(`output`);e.dataset.findError=``,e.setAttribute(`role`,`alert`),e.textContent=`正则表达式无效`,n.append(e)}},d=()=>{let o=r.querySelector(`.cm-panel.cm-search`);if(o===n)return;if(n?.removeEventListener(`keydown`,c,!0),i?.destroy(),n=o,!n){i=void 0;return}for(let[e,t,r]of[[`next`,`↓`,`下一处`],[`prev`,`↑`,`上一处`]]){let i=n.querySelector(`button[name="${e}"]`);i&&(i.textContent=t,i.setAttribute(`aria-label`,r),i.title=r)}let d=document.createElement(`span`);d.dataset.findControls=``,n.prepend(d);let f=t.getSearchQuery(e.state);a=!1,i=u(d,{...f,expanded:a},s),n.addEventListener(`keydown`,c,!0),l()},f=new MutationObserver(d);return f.observe(r,{childList:!0,subtree:!0}),d(),{update(){l()},destroy(){f.disconnect(),n?.removeEventListener(`keydown`,c,!0),i?.destroy()}}}),e.Prec.highest(n.keymap.of([{key:`Mod-Shift-l`,run:t.selectSelectionMatches},{key:`Mod-h`,scope:`editor search-panel`,run:e=>(t.searchPanelOpen(e.state)||t.openSearchPanel(e),requestAnimationFrame(()=>{e.dom.isConnected&&r.querySelector(`[data-editor-search-options][aria-expanded="false"]`)?.click()}),!0)},...[`c`,`w`,`r`].map(e=>({key:`Alt-${e}`,run:n=>{t.searchPanelOpen(n.state)||t.openSearchPanel(n);let r=t.getSearchQuery(n.state);return n.dispatch({effects:t.setSearchQuery.of(new t.SearchQuery({...r,...e===`c`?{caseSensitive:!r.caseSensitive}:e===`w`?{wholeWord:!r.wholeWord}:{regexp:!r.regexp}}))}),!0}}))])),n.panels({topContainer:r}),n.EditorView.scrollMargins.of(()=>({top:r.querySelector(`.cm-search`)?Math.min(r.getBoundingClientRect().height+8,Math.max(0,(r.parentElement?.clientHeight??0)-32)):0})),t.highlightSelectionMatches({wholeWords:!0,minSelectionLength:1,maxMatches:1e3}),t.search({top:!0}),e.EditorState.phrases.of({Find:`查找`,Replace:`替换为`,next:`下一处`,previous:`上一处`,all:`全部选中`,"match case":`区分大小写`,regexp:`正则表达式`,"by word":`全词匹配`,replace:`替换`,"replace all":`全部替换`,close:`关闭查找`,"current match":`当前匹配`,"on line":`所在行`})]}function h(e,t,r,i,a){let o=new e.Compartment,c=()=>{let n=s();return[e.EditorState.tabSize.of(n.tabSize),r.indentUnit.of(n.indent===`tabs`?` `:` `.repeat(n.tabSize)),n.wrap?t.EditorView.lineWrapping:[],n.whitespace?[t.highlightWhitespace(),t.highlightTrailingWhitespace()]:[]]};return[e.EditorState.allowMultipleSelections.of(!0),t.rectangularSelection(),t.crosshairCursor({key:`Alt`}),e.EditorState.phrases.of({"folded code":`已折叠代码`,unfold:`展开代码`,"Fold line":`折叠代码`,"Unfold line":`展开代码`}),t.highlightActiveLineGutter(),t.highlightSpecialChars(),t.dropCursor(),r.bracketMatching(),r.indentOnInput(),r.foldGutter(),i.closeBrackets(),e.Prec.highest(t.keymap.of([...i.closeBracketsKeymap,...r.foldKeymap,{key:`Alt-z`,run:()=>(l({wrap:!s().wrap}),!0)},{key:`Mod-Shift-z`,run:a.redo},{key:`Mod-y`,run:a.redo}])),o.of(c()),t.ViewPlugin.define(e=>({destroy:n(()=>{e.dispatch({effects:o.reconfigure(c())})})}))]}var g=new Map;function ee(e){let t=g.get(e);return t&&(g.delete(e),g.set(e,t)),t}function _(e,t){g.delete(e),g.set(e,t);let n=[...g.values()].reduce((e,t)=>e+t.state.doc.length,0);for(;g.size>32||n>16777216;){let e=g.keys().next().value;n-=g.get(e).state.doc.length,g.delete(e)}}var v=d(),te=262144,y=131072;function b(e){return e.split(`.`).pop()?.toLowerCase()??``}function x(e,t,n=!1){let r=e=>n?`var(--git-diff-${e.slice(5)}, var(${e}))`:`var(${e})`;return e.HighlightStyle.define([{tag:t.tags.keyword,color:r(`--cm-keyword`)},{tag:t.tags.string,color:r(`--cm-string`)},{tag:t.tags.number,color:r(`--cm-number`)},{tag:t.tags.comment,color:r(`--cm-comment`),fontStyle:`italic`},{tag:t.tags.function(t.tags.variableName),color:r(`--cm-function`)},{tag:t.tags.typeName,color:r(`--cm-type`)},{tag:t.tags.className,color:r(`--cm-type`)},{tag:t.tags.propertyName,color:r(`--cm-property`)},{tag:t.tags.operator,color:r(`--cm-operator`)},{tag:t.tags.variableName,color:r(`--cm-variable`)}])}function S({path:e,value:n,onChange:o,jumpToLine:s,onSave:l,workspaceId:u,cwd:d=``,blame:f,onPosition:g,onView:S,readOnly:C=!1,languageOverride:w}){let T=(0,p.useRef)(null),E=(0,p.useRef)(null),D=(0,p.useRef)(null),ne=(0,p.useRef)(null),O=JSON.stringify([u,d,e]),k=(0,p.useRef)(void 0),A=(0,p.useRef)(null),j=(0,p.useRef)(null),re=(0,p.useRef)(null),M=(0,p.useRef)(null),N=(0,p.useRef)(null),P=(0,p.useRef)(null),F=(0,p.useRef)(o),ie=(0,p.useRef)(l),I=(0,p.useRef)(!1),L=(0,p.useRef)(S);L.current=S,F.current=o,ie.current=l;let[R,ae]=(0,p.useState)(!1),[z,B]=(0,p.useState)(!1),[V,H]=(0,p.useState)(`0,0`),[U,oe]=(0,p.useState)(0),[W,G]=(0,p.useState)(1);(0,p.useEffect)(()=>{let i=!1,o,s,c,l,u;return(async()=>{try{let d=w??b(e),f=r(d),[p,g,_,v,y,S,R,z,V]=await Promise.all([t(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([0,1])),t(()=>import(`./dist-DTIPfQj7.js`).then(e=>e.s),__vite__mapDeps([2,1,0])),t(()=>import(`./dist-S5ntGzJB.js`),__vite__mapDeps([3,0,1,2,4,5])),t(()=>import(`./dist-Qjm1p8SR.js`),__vite__mapDeps([6,0,1,2])),t(()=>import(`./dist-DP4hrTBF.js`).then(e=>e.d),__vite__mapDeps([5,1,0,2,4])),t(()=>import(`./dist-Cus6_oaF.js`).then(e=>e.n),__vite__mapDeps([4,1])),f?f().catch(e=>(console.warn(`[CodeMirror] Failed to load language for .${d}:`,e),null)):Promise.resolve(null),a().catch(e=>(console.warn(`[CodeMirror] Failed to build the blame extension:`,e),null)),t(()=>import(`./dist-BJHpSQV1.js`).then(e=>e.r),__vite__mapDeps([7,1,0,2,5,4]))]);if(i||!T.current||!E.current)return;ne.current=g.EditorView,l=y,u=S,j.current=p.Annotation.define(),re.current=p.Transaction.addToHistory;let U=n.length<=te&&R!==null;s=new p.Compartment;let W=[g.lineNumbers(),g.highlightActiveLine(),g.drawSelection(),_.history(),g.keymap.of([_.indentWithTab,..._.defaultKeymap,..._.historyKeymap,...v.searchKeymap,{key:`Mod-s`,run:()=>(ie.current(),!0)}]),g.EditorView.updateListener.of(e=>{e.docChanged&&!(j.current&&e.transactions.some(e=>e.annotation(j.current)===!0))&&F.current(e.state.doc.toString()),e.selectionSet&&H(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),g.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(W.push(g.EditorView.updateListener.of(e=>{e.selectionSet&&G(e.state.selection.ranges.length),e.docChanged?I.current=!1:e.selectionSet&&(I.current=e.transactions.some(e=>e.isUserEvent(`select.search`)||e.isUserEvent(`select.pointer`)))}),m(p,v,g,E.current),h(p,g,y,V,_)),C&&W.push(p.EditorState.readOnly.of(!0),g.EditorView.editable.of(!1),g.EditorView.contentAttributes.of({tabindex:`0`})),z&&!C&&(c=new p.Compartment,W.splice(1,0,c.of([])),W.push(z.base)),R)try{W.push(R)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${d}:`,e),U=!1}if(U&&s&&l&&u)try{W.push(s.of(l.syntaxHighlighting(x(l,u))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${d}:`,e),U=!1}let K=ee(O),q=K&&K.state.doc.toString()===n,J=q?K.state.update({effects:p.StateEffect.reconfigure.of(W)}).state:p.EditorState.create({doc:n,extensions:W});if(o=new g.EditorView({state:J,parent:T.current}),k.current=q?K.jump:void 0,G(o.state.selection.ranges.length),H(`${o.state.selection.main.from},${o.state.selection.main.to}`),q&&(o.scrollDOM.scrollTop=K.top,o.scrollDOM.scrollLeft=K.left,k.current=K.jump),i){o.destroy();return}D.current=o,L.current?.(o),ae(U),B(!0),M.current=z,N.current=c??null,P.current=null,oe(e=>e+1);let Y=new MutationObserver(()=>{let e=D.current;if(e&&U&&s&&l&&u)try{e.dispatch({effects:s.reconfigure(l.syntaxHighlighting(x(l,u)))})}catch{}});A.current=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),i||B(!0)}})(),()=>{i=!0,A.current?.disconnect(),A.current=null,o&&_(O,{state:o.state,top:o.scrollDOM.scrollTop,left:o.scrollDOM.scrollLeft,jump:k.current}),o?.destroy(),D.current=null,L.current?.(),B(!1),T.current&&(T.current.textContent=``)}},[O,C,w]),(0,p.useEffect)(()=>{let e=D.current;if(!e)return;let t=e.state.doc.toString();t!==n&&e.dispatch({changes:{from:0,to:t.length,insert:n},annotations:j.current?j.current.of(!0):void 0})},[n]),(0,p.useEffect)(()=>{let e=D.current;if(!e||!s||k.current===s.request)return;k.current=s.request;let t=e.state.doc.line(Math.min(Math.max(1,s.line),e.state.doc.lines)),n=Math.min(t.to,t.from+(s.column??1)-1);e.dispatch({selection:{anchor:t.to,head:n},effects:ne.current?.scrollIntoView(n,{y:`start`,yMargin:Math.round(e.scrollDOM.clientHeight/3)})}),e.focus()},[s,z]);let K=!!(f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===u);(0,p.useEffect)(()=>{let t=D.current,n=M.current,r=N.current;if(!t||!n||!r)return;let i=f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===u?f.response:null,a=i?c(i):null;P.current!==a&&(P.current=a,t.dispatch({effects:[n.setBlame.of(a),r.reconfigure(a?n.gutter:[])]}))},[f?.state,f?.response,f?.path,f?.workspaceId,e,u,U]);let q=D.current?.state.doc.toString()??n,J=q.length<=y?q:q.slice(0,y),Y=w??b(e),X=i(Y),Z=D.current?.state,Q=Z?.selection.main.head,$=Q===void 0?void 0:Z?.doc.lineAt(Q),se=$?.number,ce=Q!==void 0&&$?Q-$.from+1:void 0;return(0,p.useEffect)(()=>{let e=D.current;if(z&&e&&(!s||k.current===s.request)){let t=e.state.selection.main.head,n=e.state.doc.lineAt(t);g?.({line:n.number,column:t-n.from+1,language:R&&X||`纯文本`,highlight:R?Y:`plain`,navigation:I.current,selections:e.state.selection.ranges.length})}},[z,se,ce,R,X,Y,g,W,s?.request]),(0,p.useEffect)(()=>()=>g?.(),[g]),(0,v.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":J,"data-file-content-truncated":q.length>y?`1`:`0`,"data-file-selection":V,"data-editor-selection-count":W,"data-file-editor-ready":z?`1`:`0`,"data-file-blame-gutter":K?`1`:void 0,onMouseDown:e=>{e.target.closest(`.cm-panels`)||D.current?.focus()},children:[(0,v.jsx)(`div`,{className:`file-cm`,ref:T,"aria-label":`${C?`查看`:`编辑`} ${e}`}),(0,v.jsx)(`div`,{className:`workbench-editor-search`,ref:E,"data-editor-find-host":`file`}),(!z||!g)&&(0,v.jsxs)(`div`,{className:`file-editor-status`,children:[!z&&(0,v.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),z&&Q!==void 0&&$&&(0,v.jsxs)(`span`,{children:[`第 `,$.number,` 行,第 `,Q-$.from+1,` 列`]}),z&&!R&&(0,v.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),z&&R&&X&&(0,v.jsx)(`span`,{"data-file-highlight-status":Y,children:X})]})]})}export{S as CodeMirrorEditor,m as n,h as t,x as themeHighlightStyle};
|