@evandu/super-pi 0.1.273 → 0.1.275

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 (97) hide show
  1. package/agents/group-rsi.md +18 -0
  2. package/agents/super-pi-documents/index.ts +16 -1
  3. package/agents/super-pi-task/core.ts +8 -8
  4. package/bin/completion.js +19 -5
  5. package/bin/render-presentation.ps1 +35 -0
  6. package/bin/super-pi.js +3 -0
  7. package/desktop/main.cjs +16 -9
  8. package/desktop/notifications.cjs +2 -1
  9. package/desktop/relaunch.cjs +5 -2
  10. package/desktop/restart-handoff.cjs +35 -0
  11. package/desktop/runtime.cjs +28 -4
  12. package/dist/client/.super-pi-client-sources.json +34 -19
  13. package/dist/client/assets/CodeMirrorEditor-DJgZdigq.js +2 -0
  14. package/dist/client/assets/{GitDiffEditor-CpoDDQrA.css → GitDiffEditor-DIRyUxnb.css} +1 -1
  15. package/dist/client/assets/GitDiffEditor-lOnvlR42.js +29 -0
  16. package/dist/client/assets/{dist-DGBjhKI9.js → dist-AW5lyI3I.js} +1 -1
  17. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  18. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  19. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  20. package/dist/client/assets/{dist-BvjUKkwy.js → dist-BRVQKlcp.js} +1 -1
  21. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  22. package/dist/client/assets/{dist-BlRuQIg1.js → dist-BXAOrsjq.js} +1 -1
  23. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  24. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  25. package/dist/client/assets/{dist-i79xiXVk.js → dist-Cus6_oaF.js} +2 -2
  26. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  27. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  28. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  29. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  30. package/dist/client/assets/dist-DeD9copn.js +1 -0
  31. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  32. package/dist/client/assets/{dist-D5u1uPmZ.js → dist-Dvb0SqcK.js} +2 -2
  33. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  34. package/dist/client/assets/{dist-CQncCwUc.js → dist-QzbOCAU6.js} +1 -1
  35. package/dist/client/assets/{dist-DjI7p99D.js → dist-moiMRpw_.js} +1 -1
  36. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  37. package/dist/client/assets/index-BWm699nV.js +350 -0
  38. package/dist/client/assets/index-CnNljc5p.css +1 -0
  39. package/dist/client/index.html +2 -2
  40. package/dist/server/agents.d.ts +1 -1
  41. package/dist/server/agents.js +10 -3
  42. package/dist/server/application/conversation-service.d.ts +1 -1
  43. package/dist/server/application/conversation-service.js +3 -2
  44. package/dist/server/application/document-service.d.ts +134 -0
  45. package/dist/server/application/document-service.js +9 -0
  46. package/dist/server/application/group-chat-service.d.ts +17 -0
  47. package/dist/server/application/group-chat-service.js +168 -3
  48. package/dist/server/application/group-rsi.d.ts +13 -0
  49. package/dist/server/application/group-rsi.js +69 -0
  50. package/dist/server/application/worktree-service.js +6 -2
  51. package/dist/server/http-server.js +54 -3
  52. package/dist/server/index.js +15 -2
  53. package/dist/server/managed-http.js +2 -1
  54. package/dist/server/managed-model-adapter.d.ts +4 -0
  55. package/dist/server/managed-model-relay.d.ts +1 -1
  56. package/dist/server/managed-model-relay.js +18 -15
  57. package/dist/server/managed-servers.d.ts +10 -1
  58. package/dist/server/managed-servers.js +63 -4
  59. package/dist/server/presentations/brief.d.ts +49 -0
  60. package/dist/server/presentations/brief.js +132 -0
  61. package/dist/server/presentations/inspect.d.ts +15 -0
  62. package/dist/server/presentations/inspect.js +30 -0
  63. package/dist/server/presentations/native.d.ts +8 -0
  64. package/dist/server/presentations/native.js +33 -0
  65. package/dist/server/presentations/render.d.ts +16 -0
  66. package/dist/server/presentations/render.js +152 -0
  67. package/dist/server/presentations/service.d.ts +176 -0
  68. package/dist/server/presentations/service.js +155 -0
  69. package/dist/server/remote-bootstrap.d.ts +11 -0
  70. package/dist/server/remote-bootstrap.js +105 -29
  71. package/dist/server/runtime.js +3 -2
  72. package/dist/shared/group-chat.d.ts +40 -0
  73. package/dist/shared/message-source-link.d.ts +1 -0
  74. package/dist/shared/message-source-link.js +4 -0
  75. package/dist/shared/workspace-file-preview.d.ts +1 -1
  76. package/dist/shared/workspace-file-preview.js +2 -0
  77. package/package.json +5 -1
  78. package/skills/presentation/SKILL.md +23 -1
  79. package/skills/presentation/references/spec.md +15 -0
  80. package/dist/client/assets/CodeMirrorEditor-D8MjtASz.js +0 -2
  81. package/dist/client/assets/GitDiffEditor-DFJmhUHc.js +0 -29
  82. package/dist/client/assets/dist-3qQVP6l8.js +0 -6
  83. package/dist/client/assets/dist-CZ4PyxQu.js +0 -9
  84. package/dist/client/assets/dist-CfTFp0AF.js +0 -2
  85. package/dist/client/assets/dist-CxmJXjJI.js +0 -1
  86. package/dist/client/assets/dist-D8HpMxmZ.js +0 -1
  87. package/dist/client/assets/dist-DRBIy9A1.js +0 -1
  88. package/dist/client/assets/dist-Dcww9FSw.js +0 -1
  89. package/dist/client/assets/dist-DlPa5gNa.js +0 -7
  90. package/dist/client/assets/dist-DxPJ1PN-.js +0 -1
  91. package/dist/client/assets/dist-HXD8sSA4.js +0 -23
  92. package/dist/client/assets/dist-LbeLCeoq.js +0 -1
  93. package/dist/client/assets/dist-ONdtnupI.js +0 -1
  94. package/dist/client/assets/dist-YqmXusLA.js +0 -11
  95. package/dist/client/assets/dist-ZAR1Tu2c.js +0 -3
  96. package/dist/client/assets/index-Bqutm6qV.js +0 -350
  97. package/dist/client/assets/index-DV3qc1Hh.css +0 -1
@@ -1,5 +1,6 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, open, rename, rm } from "node:fs/promises";
3
+ import { setTimeout as delay } from "node:timers/promises";
3
4
  import { join, basename, posix } from "node:path";
4
5
  import { sh, sshExec, sshSftp, sshWrite } from "./managed-ssh.js";
5
6
  import { isServiceListenHost } from "../shared/managed-servers.js";
@@ -12,30 +13,93 @@ export async function uploadFile(client, local, remote) {
12
13
  sftp.end();
13
14
  }
14
15
  }
15
- async function nodeArchive(platform, arch, directory) {
16
- const version = "v22.20.0", filename = `node-${version}-${platform}-${arch}.tar.gz`;
17
- const path = join(directory, filename);
18
- await mkdir(directory, { recursive: true });
19
- const sums = await fetch(`https://nodejs.org/dist/${version}/SHASUMS256.txt`, { signal: AbortSignal.timeout(30_000) });
20
- if (!sums.ok)
21
- throw new Error("无法下载 Node.js 校验信息,请检查本地网络");
22
- const expected = (await sums.text()).split("\n").find(line => line.endsWith(` ${filename}`))?.trim().split(/\s+/)[0];
16
+ export const NODE_RUNTIME_VERSION = "v22.20.0";
17
+ // Pinned from https://nodejs.org/dist/v22.20.0/SHASUMS256.txt.
18
+ export const NODE_RUNTIME_CHECKSUMS = Object.freeze({
19
+ "darwin-arm64": "cc04a76a09f79290194c0646f48fec40354d88969bec467789a5d55dd097f949",
20
+ "darwin-x64": "00df9c5df3e4ec6848c26b70fb47bf96492f342f4bed6b17f12d99b3a45eeecc",
21
+ "linux-arm64": "4181609e03dcb9880e7e5bf956061ecc0503c77a480c6631d868cb1f65a2c7dd",
22
+ "linux-x64": "eeaccb0378b79406f2208e8b37a62479c70595e20be6b659125eb77dd1ab2a29",
23
+ });
24
+ export async function nodeArchive(platform, arch, directory, options = {}) {
25
+ const expected = NODE_RUNTIME_CHECKSUMS[`${platform}-${arch}`];
23
26
  if (!expected)
24
27
  throw new Error("Node.js 官方未提供该平台的安装包");
28
+ return downloadVerifiedNodeArchive(`node-${NODE_RUNTIME_VERSION}-${platform}-${arch}.tar.gz`, expected, directory, options);
29
+ }
30
+ export async function downloadVerifiedNodeArchive(filename, expected, directory, options = {}) {
31
+ if (basename(filename) !== filename || !/^node-v\d+\.\d+\.\d+-(linux|darwin)-(x64|arm64)\.tar\.gz$/.test(filename)
32
+ || !/^[a-f0-9]{64}$/i.test(expected))
33
+ throw new Error("Node.js 安装包或校验值无效");
34
+ expected = expected.toLowerCase();
35
+ const request = options.fetch ?? globalThis.fetch;
36
+ const version = NODE_RUNTIME_VERSION;
37
+ const path = join(directory, filename);
38
+ await mkdir(directory, { recursive: true });
25
39
  try {
26
40
  const bytes = await readFile(path);
27
41
  if (createHash("sha256").update(bytes).digest("hex") === expected)
28
42
  return path;
29
43
  }
30
44
  catch { }
31
- const result = await fetch(`https://nodejs.org/dist/${version}/${filename}`, { signal: AbortSignal.timeout(10 * 60_000) });
32
- if (!result.ok)
33
- throw new Error("下载 Node.js 失败");
34
- const data = Buffer.from(await result.arrayBuffer());
35
- if (data.length > 150 * 1024 * 1024 || createHash("sha256").update(data).digest("hex") !== expected)
36
- throw new Error("Node.js 安装包校验失败");
37
- await writeFile(path, data);
38
- return path;
45
+ const sources = [
46
+ [`https://nodejs.org/dist/${version}/${filename}`, "官方源"],
47
+ [`https://npmmirror.com/mirrors/node/${version}/${filename}`, "备用源 1"],
48
+ [`https://mirrors.huaweicloud.com/nodejs/${version}/${filename}`, "备用源 2"],
49
+ ];
50
+ const stop = new AbortController(), temporaries = [];
51
+ const signal = AbortSignal.any([stop.signal, AbortSignal.timeout(10 * 60_000)]);
52
+ const maximum = 150 * 1024 * 1024;
53
+ const downloads = sources.map(async ([url, label], index) => {
54
+ // A slow first source must not consume the entire deployment deadline.
55
+ if (index)
56
+ await delay(index * (options.fallbackDelayMs ?? 15_000), undefined, { signal });
57
+ signal.throwIfAborted();
58
+ options.progress?.(`下载并校验 Node.js · ${label}`);
59
+ const response = await request(url, { signal });
60
+ if (!response.ok || !response.body)
61
+ throw new Error(`Node.js ${label}下载失败(${response.status})`);
62
+ if (Number(response.headers.get("content-length")) > maximum) {
63
+ await response.body.cancel();
64
+ throw new Error("Node.js 安装包超过大小上限");
65
+ }
66
+ const temporary = `${path}.download-${randomUUID()}`;
67
+ temporaries.push(temporary);
68
+ const file = await open(temporary, "wx", 0o600);
69
+ const hash = createHash("sha256");
70
+ let bytes = 0;
71
+ try {
72
+ for await (const chunk of response.body) {
73
+ signal.throwIfAborted();
74
+ bytes += chunk.length;
75
+ if (bytes > maximum)
76
+ throw new Error("Node.js 安装包超过大小上限");
77
+ hash.update(chunk);
78
+ await file.writeFile(chunk);
79
+ }
80
+ if (hash.digest("hex") !== expected.toLowerCase())
81
+ throw new Error("Node.js 安装包校验失败");
82
+ return temporary;
83
+ }
84
+ finally {
85
+ await file.close();
86
+ }
87
+ });
88
+ try {
89
+ const verified = await Promise.any(downloads);
90
+ stop.abort();
91
+ await Promise.allSettled(downloads);
92
+ await rename(verified, path);
93
+ return path;
94
+ }
95
+ catch (cause) {
96
+ throw new Error("下载 Node.js 失败:官方源及备用源未返回校验通过的完整文件,请检查入口网络后重试", { cause });
97
+ }
98
+ finally {
99
+ stop.abort();
100
+ await Promise.allSettled(downloads);
101
+ await Promise.all(temporaries.map(temporary => rm(temporary, { force: true })));
102
+ }
39
103
  }
40
104
  export async function installRemote(options) {
41
105
  const { client, progress } = options;
@@ -52,17 +116,24 @@ export async function installRemote(options) {
52
116
  const root = posix.join(home, ".super-pi", "managed", options.id);
53
117
  await sshExec(client, `umask 077; mkdir -p ${sh(root)} ${sh(posix.join(root, "data"))} ${sh(posix.join(root, "agent"))}`);
54
118
  let node = "", npm = "";
55
- try {
56
- const found = JSON.parse((await sshExec(client, "node -p 'JSON.stringify({version:process.versions.node,path:process.execPath})'")).trim());
57
- const [major, minor] = String(found.version).split(".").map(Number);
58
- npm = (await sshExec(client, "command -v npm")).trim();
59
- if (major > 22 || (major === 22 && minor >= 19))
60
- node = found.path;
119
+ for (const executable of [sh(posix.join(root, "node", "bin", "node")), "node"]) {
120
+ try {
121
+ const found = JSON.parse((await sshExec(client, `${executable} -p 'JSON.stringify({version:process.versions.node,path:process.execPath})'`)).trim());
122
+ const [major, minor] = String(found.version).split(".").map(Number);
123
+ if (!(major > 22 || (major === 22 && minor >= 19)))
124
+ continue;
125
+ const adjacentNpm = posix.join(posix.dirname(found.path), "npm");
126
+ npm = (await sshExec(client, `if [ -x ${sh(adjacentNpm)} ]; then printf '%s' ${sh(adjacentNpm)}; else command -v npm; fi`)).trim();
127
+ if (npm) {
128
+ node = found.path;
129
+ break;
130
+ }
131
+ }
132
+ catch { /* Bootstrap only when neither the private nor login runtime is usable. */ }
61
133
  }
62
- catch { /* A private Node runtime is installed when the login environment lacks a usable one. */ }
63
134
  if (!node || !npm) {
64
135
  progress("下载并校验 Node.js(仅首次需要)");
65
- const local = await nodeArchive(platform, arch, options.cacheDir), remote = posix.join(root, basename(local));
136
+ const local = await nodeArchive(platform, arch, options.cacheDir, { progress: step => progress(step) }), remote = posix.join(root, basename(local));
66
137
  await uploadFile(client, local, remote);
67
138
  const nodeRoot = posix.join(root, "node");
68
139
  progress("安装用户目录内的 Node.js,无需管理员权限");
@@ -74,10 +145,15 @@ export async function installRemote(options) {
74
145
  progress("上传纯服务安装包");
75
146
  const remoteArchive = posix.join(root, "server.tgz");
76
147
  await uploadFile(client, options.archive, remoteArchive);
77
- const runtime = posix.join(root, `runtime-${options.archiveHash.slice(0, 16)}`);
148
+ // A repair must not depend on npm noticing missing files in an existing package.
149
+ const runtimeTag = createHash("sha256").update(options.archiveHash + randomUUID()).digest("hex").slice(0, 16);
150
+ const runtime = posix.join(root, `runtime-${runtimeTag}`);
78
151
  const packageRoot = posix.join(runtime, "node_modules", "@evandu", "super-pi-server");
152
+ const policy = `const{execFileSync}=require('node:child_process');const keys=['ONNXRUNTIME_NODE_INSTALL','ONNXRUNTIME_NODE_INSTALL_CUDA','npm_config_onnxruntime_node_install','npm_config_onnxruntime_node_install_cuda'];const configured=name=>{try{const value=execFileSync(${JSON.stringify(npm)},['config','get',name],{encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();return value!==''&&value!=='undefined'&&value!=='null';}catch{return false;}};process.stdout.write(keys.some(key=>Boolean(process.env[key]))||configured('onnxruntime-node-install')||configured('onnxruntime-node-install-cuda')?'configured':'cpu');`;
153
+ const mode = (await sshExec(client, `export PATH=${sh(posix.dirname(node))}:"$PATH"; ${sh(node)} -e ${sh(policy)}`)).trim();
154
+ const cpuRuntime = mode === "cpu" ? "ONNXRUNTIME_NODE_INSTALL=skip " : "";
79
155
  progress("安装远端服务依赖");
80
- await sshExec(client, `umask 077; export PATH=${sh(posix.dirname(node))}:"$PATH"; ${sh(npm)} install --prefix ${sh(runtime)} --omit=dev --no-audit --no-fund --fetch-timeout=900000 --fetch-retries=3 ${sh(remoteArchive)}`, { timeout: 20 * 60_000, onOutput: output => progress("安装远端服务依赖", output) });
156
+ await sshExec(client, `umask 077; export PATH=${sh(posix.dirname(node))}:"$PATH"; ${cpuRuntime}${sh(npm)} install --prefix ${sh(runtime)} --omit=dev --no-audit --no-fund --fetch-timeout=900000 --fetch-retries=3 ${sh(remoteArchive)}`, { timeout: 20 * 60_000, onOutput: output => progress("安装远端服务依赖", output) });
81
157
  const piCommand = posix.join(root, "pi-managed");
82
158
  progress("配置远端 Pi 启动器");
83
159
  const resolvePi = `import{fileURLToPath}from'node:url';import{dirname,resolve,join}from'node:path';import{readFileSync,accessSync}from'node:fs';const root=resolve(dirname(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent'))),'..');const bin=JSON.parse(readFileSync(join(root,'package.json'),'utf8')).bin.pi;const cli=resolve(root,bin);accessSync(cli);process.stdout.write(cli);`;
@@ -86,7 +162,7 @@ export async function installRemote(options) {
86
162
  throw new Error("远端 Pi 安装不完整,请重试部署");
87
163
  const extension = posix.join(packageRoot, "agents", "super-pi-managed-model", "index.ts");
88
164
  await sshWrite(client, piCommand, `#!/bin/sh\nexec ${sh(node)} ${sh(piCli)} --extension ${sh(extension)} "$@"\n`, 0o700);
89
- return { root, packageRoot, node, piCommand };
165
+ return { root, packageRoot, node, piCommand, archiveHash: options.archiveHash };
90
166
  }
91
167
  export function remoteStartScript(installation, port, host = "127.0.0.1") {
92
168
  if (!isServiceListenHost(host) || !Number.isInteger(port) || port < 1 || port > 65535)
@@ -4,6 +4,7 @@ export { RpcChannel } from "./rpc-channel.js";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { KNOWLEDGE_IMPORT_TOOL_NAME, KNOWLEDGE_TOOL_NAME } from "./knowledge.js";
6
6
  import { DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME } from "./documents.js";
7
+ import { PRESENTATION_TOOL_NAMES } from "./presentations/service.js";
7
8
  import { FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME } from "./feishu-cli.js";
8
9
  import { WEB_FETCH_TOOL_NAME, WEB_SEARCH_TOOL_NAME } from "./web.js";
9
10
  import { existsSync } from "node:fs";
@@ -1384,7 +1385,7 @@ export class PiRpcRuntime {
1384
1385
  // whether the extension registers them. An agent that declares `tools: {"*": false, read: true}`
1385
1386
  // would otherwise get a loaded-but-undeclared tool - broken with no error to explain it.
1386
1387
  if (this.options.documentsEndpoint)
1387
- names.push(DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME);
1388
+ names.push(DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME, ...PRESENTATION_TOOL_NAMES);
1388
1389
  // The Feishu tools are named whenever the endpoint is configured, for the same reason the
1389
1390
  // document tools are: the endpoint is what decides whether the extension registers them, and
1390
1391
  // an agent that declares `tools: {"*": false, read: true}` would otherwise get a
@@ -1617,7 +1618,7 @@ export class PiRpcRuntime {
1617
1618
  // allowlist and naming a tool Pi has not registered would change the spawn line for every other
1618
1619
  // mode. The prompt asks for a bare JSON array and nothing else; if the model spends a turn on a
1619
1620
  // tool call anyway the reranker times out and falls back to the lexical order.
1620
- const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", "tool_shortcut", "tool_remove", ...(this.options.orchestratorEndpoint ? [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] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1621
+ const agentArgs = memoryReview ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates", "--tools", "memory,skill_manage,session_search"] : knowledgeRerank ? ["--no-extensions", "--no-skills", "--no-mcp", "--no-context-files", "--no-prompt-templates"] : await agentSpawnArgs(this.agents.promptDir, agent, { extraAllowedTools: [...(extensionArgs.length ? [TASK_TOOL_NAME, TODO_TOOL_NAME, PROJECT_TOOL_NAME, WORKFLOW_TOOL_NAME, RUN_ASYNC_TOOL_NAME, SCHEDULED_TASK_TOOL_NAME, "question", "tool_register", "tool_shortcut", "tool_remove", ...(this.options.orchestratorEndpoint ? [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] : [])] : []), ...(memoryEnabled ? ["memory", "skill_manage", "session_search"] : []), ...(knowledgeEnabled ? [KNOWLEDGE_TOOL_NAME, KNOWLEDGE_IMPORT_TOOL_NAME] : []), ...(documentsEnabled ? [DOCUMENT_READ_TOOL_NAME, DOCUMENT_WRITE_TOOL_NAME, ...PRESENTATION_TOOL_NAMES] : []), ...(webEnabled ? [WEB_SEARCH_TOOL_NAME, WEB_FETCH_TOOL_NAME] : []), ...(feishuEnabled ? [FEISHU_READ_TOOL_NAME, FEISHU_WRITE_TOOL_NAME] : [])] });
1621
1622
  // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
1622
1623
  // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
1623
1624
  if (!this.pi.found)
@@ -4,6 +4,45 @@ export type GroupModel = {
4
4
  modelId: string;
5
5
  label: string;
6
6
  };
7
+ export type GroupRsiCategory = "division" | "prompt" | "tools" | "mechanism" | "execution";
8
+ export type GroupRsiFinding = {
9
+ id: string;
10
+ category: GroupRsiCategory;
11
+ priority: "high" | "medium" | "low";
12
+ observation: string;
13
+ evidence: {
14
+ messageId: string;
15
+ quote: string;
16
+ }[];
17
+ recommendation: string;
18
+ verification: string;
19
+ applicability: string;
20
+ disposition?: "accepted" | "dismissed";
21
+ feedback?: string;
22
+ };
23
+ export type GroupRsiReport = {
24
+ id: string;
25
+ createdAt: string;
26
+ sourceKey: string;
27
+ observedMessages: number;
28
+ totalMessages: number;
29
+ compressed: boolean;
30
+ summary: string;
31
+ retrospective: string;
32
+ findings: GroupRsiFinding[];
33
+ model?: GroupModel;
34
+ };
35
+ export type GroupRsi = {
36
+ enabled: boolean;
37
+ model?: GroupModel;
38
+ prompt: string;
39
+ status: "idle" | "running" | "completed" | "failed" | "interrupted";
40
+ error?: string;
41
+ startedAt?: string;
42
+ sourceKey?: string;
43
+ reports: GroupRsiReport[];
44
+ pending?: boolean;
45
+ };
7
46
  export type GroupModerator = {
8
47
  model?: GroupModel;
9
48
  prompt: string;
@@ -128,6 +167,7 @@ export type GroupRoom = GroupIdentity & {
128
167
  revision: number;
129
168
  messages: GroupMessage[];
130
169
  cloneRequests?: GroupCloneRequest[];
170
+ rsi?: GroupRsi;
131
171
  };
132
172
  export type GroupSnapshot = Omit<GroupRoom, "revision"> & {
133
173
  revision: string;
@@ -3,6 +3,7 @@ type Position = {
3
3
  path: string;
4
4
  line: number;
5
5
  column?: number;
6
+ artifact?: boolean;
6
7
  };
7
8
  export type SourceLinkScope = {
8
9
  root: string;
@@ -1,5 +1,9 @@
1
1
  export const SOURCE_LINK_GUIDANCE = "When referencing code locations, use Markdown links with paths relative to your working directory and a line fragment, such as [`function_name`](./src/example.cpp#L397). Do not prefix them with a localhost URL.";
2
2
  function position(value) {
3
+ // Managed presentations are artifacts, not code locations, but use the same scoped opener.
4
+ const artifact = sourcePath(value);
5
+ if (artifact && /\.pptx$/i.test(artifact))
6
+ return { path: value, line: 1, artifact: true };
3
7
  const marker = /#L([1-9]\d*)(?:C([1-9]\d*))?(?:-L?[1-9]\d*)?$/i.exec(value)
4
8
  ?? /:([1-9]\d*)(?::([1-9]\d*))?$/.exec(value);
5
9
  if (!marker || marker.index === 0)
@@ -1,4 +1,4 @@
1
- export type WorkspacePreviewKind = "image" | "pdf" | "audio" | "video" | "table" | "document" | "download";
1
+ export type WorkspacePreviewKind = "image" | "pdf" | "audio" | "video" | "table" | "document" | "presentation" | "download";
2
2
  export declare function workspaceFileExtension(path: string): string;
3
3
  export declare function workspaceFileMime(path: string): string | undefined;
4
4
  export declare function workspacePreviewKind(path: string): WorkspacePreviewKind | undefined;
@@ -24,5 +24,7 @@ export function workspacePreviewKind(path) {
24
24
  return "table";
25
25
  if (/\.docx$/i.test(path))
26
26
  return "document";
27
+ if (/\.pptx$/i.test(path))
28
+ return "presentation";
27
29
  return undefined;
28
30
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "superPi": {
4
4
  "managedDirectListener": true
5
5
  },
6
- "version": "0.1.273",
6
+ "version": "0.1.275",
7
7
  "description": "Web control plane and companion for Pi",
8
8
  "license": "MIT",
9
9
  "type": "module",
@@ -37,6 +37,7 @@
37
37
  "node": ">=22.19.0"
38
38
  },
39
39
  "scripts": {
40
+ "postinstall": "node --input-type=module -e \"import('./bin/completion.js').then(m => m.installGlobalCompletion()).catch(() => console.warn('Super Pi shell completion registration could not finish.'))\"",
40
41
  "prepack": "node scripts/clean-build.mjs",
41
42
  "prepublishOnly": "node scripts/clean-build.mjs && cross-env SUPER_PI_REQUIRE_REAL_PI=1 node scripts/extension-load.test.mjs",
42
43
  "dev": "concurrently --kill-others-on-fail \"npm:dev:server\" \"npm:dev:client\"",
@@ -266,6 +267,7 @@
266
267
  "scripts/skills-discovery.test.mjs",
267
268
  "scripts/built-in-skills.test.mjs",
268
269
  "scripts/presentation-schema.test.mjs",
270
+ "scripts/presentation-tools.test.mjs",
269
271
  "scripts/session-state-icon.test.mjs",
270
272
  "scripts/provider-fetch-models.test.mjs",
271
273
  "scripts/shared-chrome.test.mjs",
@@ -442,6 +444,7 @@
442
444
  "scripts/ux-polish-browser.test.mjs",
443
445
  "scripts/prompt-templates-browser.test.mjs",
444
446
  "scripts/documents-browser.test.mjs",
447
+ "scripts/presentation-browser.test.mjs",
445
448
  "scripts/feishu-browser.test.mjs",
446
449
  "scripts/session-read-state-regression.test.mjs",
447
450
  "scripts/orchestrated-order-role-browser.test.mjs",
@@ -515,6 +518,7 @@
515
518
  },
516
519
  "optionalDependencies": {
517
520
  "@huggingface/transformers": "^4.3.1",
521
+ "@resvg/resvg-js": "^2.6.2",
518
522
  "cfb": "^1.2.2",
519
523
  "docx": "^9.14.0",
520
524
  "exceljs": "^4.4.0",
@@ -24,7 +24,29 @@ Treat a deck as a communication artifact, not a document split across slides. Pr
24
24
  - Read [references/data.md](references/data.md) for tables, quantitative claims, and chart selection.
25
25
  - Read [references/templates-and-editing.md](references/templates-and-editing.md) when a template or existing deck must be preserved or edited.
26
26
  - Read [references/quality.md](references/quality.md) before final validation and delivery.
27
+ - Read [references/spec.md](references/spec.md) only when a semantic brief cannot express the requested layout; it documents positioned JSON without needing a custom generator.
27
28
 
28
29
  ## Current tool boundary
29
30
 
30
- The legacy `document_write` PPT path accepts Markdown and produces a clean text-first deck. It cannot faithfully implement positioned elements, images, native charts, templates, object-level edits, or visual rendering. When those capabilities are absent, produce the strongest honest text-first deck possible and state the limitation; do not simulate visual completion in prose.
31
+ Use `presentation_create` for new decks. Submit one compact JSON brief (inline or a JSON file) with the content, data and notes. The platform handles reusable layouts, native editable charts/tables, PPTX output and all slide layout previews in one call. Do not write a Python/JS framework, COM wrapper, OOXML patcher, or per-slide checker for a normal deck. Use existing generic computation tools for calculations, not a new rendering program. Aim for a usable ten-slide draft in five to ten minutes; visual polish is a bounded second pass.
32
+
33
+ Example brief:
34
+ ```json
35
+ {"title":"试点评审","data":{"budget":2000},"slides":[
36
+ {"id":"intro","layout":"cover","title":"建议开展六周试点","subtitle":"工程与财务联合评审","notes":"说明本次需要批准的事项。"},
37
+ {"id":"benefit","layout":"chart","title":"三组试点均减少处理时间","chart":{"type":"column","categories":["A组","B组","C组"],"series":[{"name":"每周节省分钟","values":[30,42,36]}]},"notes":"口径为每人每周,样本不足以推断因果。"},
38
+ {"id":"decision","layout":"body","title":"批准预算 {{budget}} 元后开始试点","bullets":["明确负责人和退出条件","每周回顾收益与质量"],"notes":"预算来自统一数据绑定,修改时全稿更新。"}
39
+ ]}
40
+ ```
41
+
42
+ Layouts: cover/subtitle, body/bullets, comparison/columns (1–3), chart/chart, table/table (rectangular rows, first row header), timeline/steps (1–5), metrics/metrics (1–5). Each slide needs a stable ASCII id and title. Charts accept bar/column/line/area/pie/doughnut and numeric series matching categories. Supply sources and speaker notes. Keep slides short; put detail into notes. Platform diagnostics are estimates, not proof of typography fidelity. Imported templates, image elements and scatter charts are not supported by this first writer; state that limitation rather than silently dropping objects.
43
+
44
+ `presentation_create` already produces all PNG previews, ten-page contact sheets and diagnostics. On Windows the platform also tries its managed PowerPoint adapter when installed and not already in use; it preserves existing user presentations. It returns `verification: native-office` only after actual export. Otherwise it returns `layout-only` and a nativeReason. Other platforms currently use layout previews. Do not probe Office, inspect Super Pi source, or write a COM/rendering wrapper: the platform has already handled that decision. Missing native rendering is a reported limitation, not a reason to rebuild the deck with another framework. Requesting PNG previews does not require native rendering; describe the actual preview type honestly.
45
+
46
+ Use `presentation_render` once per ten-page contact sheet to SEE the cached image. Review the whole deck, then inspect full-size PNG paths only where needed. Fix flagged pages with small patches instead of rewriting everything. Do not generate a throwaway probe deck before the real deck. Distinguish structural checks, layout approximation and native rendering in delivery; do not claim checks beyond the returned verification. Engine installation/distribution and arbitrary-template fidelity remain future work.
47
+
48
+ The tool result's inspection reports actual OOXML slide/notes/chart/table/text/workbook counts, canvas size and relationship completeness. Reuse that evidence instead of writing a ZIP checker. It does not prove that your numbers match external source data; check those using your calculations. If PNG **or** PDF was requested, PNG already satisfies that request: do not add a PDF pipeline unless the user needs it. A content brief and data calculations are reproducible sources; they do not need a generation program. Keep new revisions at new paths even when the original was only a draft, and link the latest version. Never delete a managed draft merely to reuse its filename.
49
+
50
+ For a revision, use `presentation_read` to get the source and etag, then `presentation_edit` with a different outputPath and a compact patch: `{"data":{"budget":2500},"slides":{"benefit":{"chart":{"type":"bar","categories":["A组","B组","C组"],"series":[{"name":"每周节省分钟","values":[30,42,36]}]}}}}`. Slide field arrays are replaced entirely; existing fields otherwise stay. The original file is immutable. Do not rebuild it to compare versions. Identical retries reuse a verified artifact; conflicting targets require another filename.
51
+
52
+ Deliver a clickable Markdown link `[查看演示稿](relative/path.pptx)`; do not leave only backtick paths. PPTX opens in the main file tab with all page previews and notes; source JSON can be downloaded there. The legacy `document_write` Markdown PPT path remains a text-only fallback. Arbitrary imported PPTX can be read as text with `document_read` and downloaded; they do not have editable managed sources or automatic layout previews.
@@ -0,0 +1,15 @@
1
+ # Positioned specification (only when a brief cannot express the requested layout)
2
+
3
+ Prefer the compact semantic brief for normal decks. Do not inspect Super Pi source or build a generator to discover this contract. The same `presentation_create` brief/briefPath accepts the following JSON instead:
4
+
5
+ ```json
6
+ {"version":1,"metadata":{"title":"评审","author":"团队","language":"zh-CN"},"canvas":{"width":13.333,"height":7.5},"slides":[{"id":"page-1","title":"试点收益","notes":"模拟数据。","background":"F8FAFD","elements":[
7
+ {"id":"title-1","type":"text","x":0.7,"y":0.5,"width":12,"height":0.9,"text":"试点收益需要质量护栏","fontSize":28,"bold":true,"color":"233047"},
8
+ {"id":"chart-1","type":"chart","x":0.8,"y":1.6,"width":8,"height":4.8,"chart":"column","categories":["基线","试点"],"series":[{"name":"中位周期(小时)","values":[18,14.5]}],"showLegend":true,"showValues":true},
9
+ {"id":"caption-1","type":"text","x":9.3,"y":2,"width":3,"height":3,"text":"这是观察结果,不能推断因果。","fontSize":22,"color":"233047"}
10
+ ]}]}
11
+ ```
12
+
13
+ All dimensions are inches; fontSize is points. All frames must fit the canvas. IDs are unique across the deck, start with a letter, and contain only ASCII letters/digits/dot/underscore/hyphen. Colors are six-digit RGB, with optional leading #. Text fields: fontFamily, fontSize, color, bold, italic, align (left/center/right/justify), verticalAlign (top/middle/bottom). Shape fields: shape (rectangle/roundRectangle/ellipse/triangle/chevron), fill, stroke, strokeWidth. Line fields: stroke, strokeWidth. Table fields: rectangular rows (string/number/boolean/null) and headerRows. Chart fields as above, plus chart types bar/column/line/area/pie/doughnut. Null data values, scatter and images are not supported by the writer; do not silently replace them. Layout PNG approximates these shapes; native-office previews are actual PowerPoint output.
14
+
15
+ Semantic brief data bindings: strings can contain `{{budget.monthly}}`; objects/arrays can be shared as `{"$ref":"teamChart"}`. A chart/table reference resolves from the brief's data object before validation. Updating that data through presentation_edit updates every reference. References cannot execute code or access files. Patch slide fields by ID; positioned slides can replace their elements array as a unit. Preserve IDs of unchanged elements. Object-level insert/remove patches and arbitrary imported deck editing remain future work.
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-ZAR1Tu2c.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-i79xiXVk.js","assets/dist-D978o95T.js","assets/dist-DlPa5gNa.js","assets/dist-DRBIy9A1.js","assets/dist-BlRuQIg1.js","assets/dist-HXD8sSA4.js","assets/dist-DjI7p99D.js","assets/dist-CZ4PyxQu.js","assets/dist-DGBjhKI9.js","assets/dist-LbeLCeoq.js","assets/dist-D8HpMxmZ.js","assets/dist-Dcww9FSw.js","assets/dist-D5u1uPmZ.js","assets/dist-CxmJXjJI.js","assets/dist-ONdtnupI.js","assets/dist-CQncCwUc.js","assets/dist-3qQVP6l8.js","assets/dist-BvjUKkwy.js","assets/dist-YqmXusLA.js","assets/dist-DxPJ1PN-.js","assets/dist-CfTFp0AF.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{c as t,l as n,n as r,r as i,t as a}from"./index-Bqutm6qV.js";var o=e(n(),1);async function s(e,t){let[{StreamLanguage:n},r]=await Promise.all([i(()=>import(`./dist-ZAR1Tu2c.js`).then(e=>e.d),__vite__mapDeps([0,1,2,3,4])),e()]),a=r[t]??r.default??r;return n.define(a)}var c={cpp:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),cc:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),cxx:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),hpp:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),hh:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),hxx:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),c:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),h:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),cu:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),cuh:()=>i(()=>import(`./dist-DRBIy9A1.js`).then(e=>e.cpp()),__vite__mapDeps([5,6,2,1,0,3,4])),js:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript()),__vite__mapDeps([7,1,6,2,0,3,4,8])),jsx:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript({jsx:!0})),__vite__mapDeps([7,1,6,2,0,3,4,8])),mjs:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript()),__vite__mapDeps([7,1,6,2,0,3,4,8])),cjs:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript()),__vite__mapDeps([7,1,6,2,0,3,4,8])),ts:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0})),__vite__mapDeps([7,1,6,2,0,3,4,8])),tsx:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0,jsx:!0})),__vite__mapDeps([7,1,6,2,0,3,4,8])),mts:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0})),__vite__mapDeps([7,1,6,2,0,3,4,8])),cts:()=>i(()=>import(`./dist-HXD8sSA4.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0})),__vite__mapDeps([7,1,6,2,0,3,4,8])),py:()=>i(()=>import(`./dist-CZ4PyxQu.js`).then(e=>e.python()),__vite__mapDeps([9,6,2,1,0,3,4,8])),pyi:()=>i(()=>import(`./dist-CZ4PyxQu.js`).then(e=>e.python()),__vite__mapDeps([9,6,2,1,0,3,4,8])),java:()=>i(()=>import(`./dist-DGBjhKI9.js`).then(e=>e.java()),__vite__mapDeps([10,6,2,1,0,3,4])),php:()=>i(()=>import(`./dist-LbeLCeoq.js`).then(e=>e.php()),__vite__mapDeps([11,6,2,1,12,13,0,3,4,7,8])),sql:()=>i(()=>import(`./dist-D5u1uPmZ.js`).then(e=>e.sql()),__vite__mapDeps([14,0,1,2,3,4,6,8])),yaml:()=>i(()=>import(`./dist-CxmJXjJI.js`).then(e=>e.yaml()),__vite__mapDeps([15,6,2,1,0,3,4])),yml:()=>i(()=>import(`./dist-CxmJXjJI.js`).then(e=>e.yaml()),__vite__mapDeps([15,6,2,1,0,3,4])),xml:()=>i(()=>import(`./dist-ONdtnupI.js`).then(e=>e.xml()),__vite__mapDeps([16,6,2,1,0,3,4])),json:()=>i(()=>import(`./dist-CQncCwUc.js`).then(e=>e.json()),__vite__mapDeps([17,6,2,1,0,3,4])),jsonc:()=>i(()=>import(`./dist-CQncCwUc.js`).then(e=>e.json()),__vite__mapDeps([17,6,2,1,0,3,4])),json5:()=>i(()=>import(`./dist-CQncCwUc.js`).then(e=>e.json()),__vite__mapDeps([17,6,2,1,0,3,4])),html:()=>i(()=>import(`./dist-D8HpMxmZ.js`).then(e=>e.html()),__vite__mapDeps([12,6,2,1,13,0,3,4,7,8])),htm:()=>i(()=>import(`./dist-D8HpMxmZ.js`).then(e=>e.html()),__vite__mapDeps([12,6,2,1,13,0,3,4,7,8])),vue:()=>i(()=>import(`./dist-D8HpMxmZ.js`).then(e=>e.html()),__vite__mapDeps([12,6,2,1,13,0,3,4,7,8])),svelte:()=>i(()=>import(`./dist-D8HpMxmZ.js`).then(e=>e.html()),__vite__mapDeps([12,6,2,1,13,0,3,4,7,8])),css:()=>i(()=>import(`./dist-Dcww9FSw.js`).then(e=>e.r).then(e=>e.css()),__vite__mapDeps([13,1,6,2,0,3,4])),md:()=>i(()=>import(`./dist-3qQVP6l8.js`).then(e=>e.markdown()),__vite__mapDeps([18,3,1,4,0,2,8,12,6,13,7])),markdown:()=>i(()=>import(`./dist-3qQVP6l8.js`).then(e=>e.markdown()),__vite__mapDeps([18,3,1,4,0,2,8,12,6,13,7])),mdx:()=>i(()=>import(`./dist-3qQVP6l8.js`).then(e=>e.markdown()),__vite__mapDeps([18,3,1,4,0,2,8,12,6,13,7])),rs:()=>i(()=>import(`./dist-BvjUKkwy.js`).then(e=>e.rust()),__vite__mapDeps([19,6,2,1,0,3,4])),go:()=>i(()=>import(`./dist-YqmXusLA.js`).then(e=>e.go()),__vite__mapDeps([20,6,2,1,0,3,4,8])),sh:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),bash:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),zsh:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),fish:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),ps1:()=>s(()=>i(()=>import(`./powershell-D8WpQPaX.js`),[]),`powershell`),psm1:()=>s(()=>i(()=>import(`./powershell-D8WpQPaX.js`),[]),`powershell`),rb:()=>s(()=>i(()=>import(`./ruby-ChfNwlCY.js`),[]),`ruby`),swift:()=>s(()=>i(()=>import(`./swift-DKB6_1j6.js`),[]),`swift`),toml:()=>s(()=>i(()=>import(`./toml-BPTmHmyx.js`),[]),`toml`),ini:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),cfg:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),conf:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),properties:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),dockerfile:()=>s(()=>i(()=>import(`./dockerfile-BDePf5PZ.js`),[]),`dockerfile`),diff:()=>s(()=>i(()=>import(`./diff-ChtP43wD.js`),[]),`diff`),patch:()=>s(()=>i(()=>import(`./diff-ChtP43wD.js`),[]),`diff`)},l={cpp:`C++`,cc:`C++`,cxx:`C++`,hpp:`C++`,hh:`C++`,hxx:`C++`,cu:`CUDA C++`,cuh:`CUDA C++`,c:`C`,h:`C/C++ Header`,js:`JavaScript`,jsx:`JSX`,mjs:`JavaScript`,cjs:`JavaScript`,ts:`TypeScript`,tsx:`TSX`,mts:`TypeScript`,cts:`TypeScript`,py:`Python`,pyi:`Python Stub`,java:`Java`,php:`PHP`,sql:`SQL`,yaml:`YAML`,yml:`YAML`,xml:`XML`,json:`JSON`,jsonc:`JSON with Comments`,json5:`JSON5`,css:`CSS`,md:`Markdown`,markdown:`Markdown`,mdx:`MDX`,rs:`Rust`,go:`Go`,html:`HTML`,htm:`HTML`,vue:`Vue`,svelte:`Svelte`,sh:`Shell`,bash:`Bash`,zsh:`Zsh`,fish:`Fish`,ps1:`PowerShell`,psm1:`PowerShell`,rb:`Ruby`,swift:`Swift`,toml:`TOML`,ini:`INI`,cfg:`Config`,conf:`Config`,properties:`Properties`,dockerfile:`Dockerfile`,diff:`Diff`,patch:`Patch`};function u(e){return c[e.toLowerCase()]}function d(e){return l[e.toLowerCase()]}var f=t(),p=262144,m=131072;function h(e){return e.split(`.`).pop()?.toLowerCase()??``}function g(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function _(e,t){return e.HighlightStyle.define([{tag:t.tags.keyword,color:g(`--cm-keyword`)},{tag:t.tags.string,color:g(`--cm-string`)},{tag:t.tags.number,color:g(`--cm-number`)},{tag:t.tags.comment,color:g(`--cm-comment`),fontStyle:`italic`},{tag:t.tags.function(t.tags.variableName),color:g(`--cm-function`)},{tag:t.tags.typeName,color:g(`--cm-type`)},{tag:t.tags.className,color:g(`--cm-type`)},{tag:t.tags.propertyName,color:g(`--cm-property`)},{tag:t.tags.operator,color:g(`--cm-operator`)},{tag:t.tags.variableName,color:g(`--cm-variable`)}])}function v({path:e,value:t,onChange:n,jumpToLine:s,onSave:c,workspaceId:l,blame:g,onPosition:v,readOnly:y=!1}){let b=(0,o.useRef)(null),x=(0,o.useRef)(null),S=(0,o.useRef)(null),C=(0,o.useRef)(null),w=(0,o.useRef)(null),T=(0,o.useRef)(null),E=(0,o.useRef)(null),D=(0,o.useRef)(null),O=(0,o.useRef)(n),k=(0,o.useRef)(c);O.current=n,k.current=c;let[A,j]=(0,o.useState)(!1),[M,N]=(0,o.useState)(!1),[P,F]=(0,o.useState)(`0,0`),[I,L]=(0,o.useState)(0);(0,o.useEffect)(()=>{let n=!1,a,o,s,c,l;return(async()=>{try{let d=h(e),f=u(d),[m,g,v,A,M,P,I,R]=await Promise.all([i(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([3,1])),i(()=>import(`./dist-DlPa5gNa.js`).then(e=>e.s),__vite__mapDeps([4,1,3])),i(()=>import(`./dist-DxPJ1PN-.js`),__vite__mapDeps([21,3,1,4,0,2])),i(()=>import(`./dist-CfTFp0AF.js`),__vite__mapDeps([22,4,1,3])),i(()=>import(`./dist-ZAR1Tu2c.js`).then(e=>e.d),__vite__mapDeps([0,1,2,3,4])),i(()=>import(`./dist-i79xiXVk.js`).then(e=>e.n),__vite__mapDeps([2,1])),f?f().catch(e=>(console.warn(`[CodeMirror] Failed to load language for .${d}:`,e),null)):Promise.resolve(null),r().catch(e=>(console.warn(`[CodeMirror] Failed to build the blame extension:`,e),null))]);if(n||!b.current)return;c=M,l=P,C.current=m.Annotation.define(),w.current=m.Transaction.addToHistory;let z=t.length<=p&&I!==null;o=new m.Compartment;let B=[g.lineNumbers(),g.highlightActiveLine(),g.drawSelection(),v.history(),g.keymap.of([v.indentWithTab,...v.defaultKeymap,...v.historyKeymap,...A.searchKeymap,{key:`Mod-s`,run:()=>(k.current(),!0)}]),g.EditorView.updateListener.of(e=>{e.docChanged&&!(C.current&&e.transactions.some(e=>e.annotation(C.current)===!0))&&O.current(e.state.doc.toString()),e.selectionSet&&F(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),g.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(y&&B.push(m.EditorState.readOnly.of(!0),g.EditorView.editable.of(!1)),R&&!y&&(s=new m.Compartment,B.splice(1,0,s.of([])),B.push(R.base)),I)try{B.push(I)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${d}:`,e),z=!1}if(z&&o&&c&&l)try{B.push(o.of(c.syntaxHighlighting(_(c,l))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${d}:`,e),z=!1}if(a=new g.EditorView({state:m.EditorState.create({doc:t,extensions:B}),parent:b.current}),n){a.destroy();return}x.current=a,j(z),N(!0),T.current=R,E.current=s??null,D.current=null,L(e=>e+1);let V=new MutationObserver(()=>{let e=x.current;if(e&&z&&o&&c&&l)try{e.dispatch({effects:o.reconfigure(c.syntaxHighlighting(_(c,l)))})}catch{}});S.current=V,V.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),n||N(!0)}})(),()=>{n=!0,S.current?.disconnect(),S.current=null,a?.destroy(),x.current=null,N(!1),b.current&&(b.current.textContent=``)}},[e,y]),(0,o.useEffect)(()=>{let e=x.current;if(!e)return;let n=e.state.doc.toString();n!==t&&e.dispatch({changes:{from:0,to:n.length,insert:t},annotations:C.current?C.current.of(!0):void 0})},[t]),(0,o.useEffect)(()=>{let e=x.current;if(!e||!s)return;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},scrollIntoView:!0}),e.focus()},[s,M]);let R=!!(g&&g.state===`ready`&&g.response&&g.path===e&&g.workspaceId===l);(0,o.useEffect)(()=>{let t=x.current,n=T.current,r=E.current;if(!t||!n||!r)return;let i=g&&g.state===`ready`&&g.response&&g.path===e&&g.workspaceId===l?g.response:null,o=i?a(i):null;D.current!==o&&(D.current=o,t.dispatch({effects:[n.setBlame.of(o),r.reconfigure(o?n.gutter:[])]}))},[g?.state,g?.response,g?.path,g?.workspaceId,e,l,I]);let z=x.current?.state.doc.toString()??t,B=z.length<=m?z:z.slice(0,m),V=h(e),H=d(V),U=x.current?.state,W=U?.selection.main.head,G=W===void 0?void 0:U?.doc.lineAt(W),K=G?.number,q=W!==void 0&&G?W-G.from+1:void 0;return(0,o.useEffect)(()=>{M&&K!==void 0&&q!==void 0&&v?.({line:K,column:q,language:A&&H||`纯文本`,highlight:A?V:`plain`})},[M,K,q,A,H,V,v]),(0,o.useEffect)(()=>()=>v?.(),[v]),(0,f.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":B,"data-file-content-truncated":z.length>m?`1`:`0`,"data-file-selection":P,"data-file-editor-ready":M?`1`:`0`,"data-file-blame-gutter":R?`1`:void 0,onMouseDown:()=>x.current?.focus(),children:[(0,f.jsx)(`div`,{className:`file-cm`,ref:b,"aria-label":`${y?`查看`:`编辑`} ${e}`}),(!M||!v)&&(0,f.jsxs)(`div`,{className:`file-editor-status`,children:[!M&&(0,f.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),M&&W!==void 0&&G&&(0,f.jsxs)(`span`,{children:[`第 `,G.number,` 行,第 `,W-G.from+1,` 列`]}),M&&!A&&(0,f.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),M&&A&&H&&(0,f.jsx)(`span`,{"data-file-highlight-status":V,children:H})]})]})}export{v as CodeMirrorEditor,u as t,_ as themeHighlightStyle};