vc-extras 0.0.0-stage → 0.1.1
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/README.md +128 -3
- package/agent-install.mjs +159 -0
- package/agents/tester.md +23 -0
- package/install-extras.mjs +66 -0
- package/install-menu.mjs +42 -0
- package/install-skills.mjs +112 -0
- package/package.json +72 -6
- package/plugin-registry.mjs +73 -0
- package/plugins/config-ui/index.ts +160 -0
- package/plugins/config-ui/lib/arguments.mjs +24 -0
- package/plugins/config-ui/lib/documents.mjs +67 -0
- package/plugins/config-ui/lib/frontmatter.mjs +91 -0
- package/plugins/config-ui/lib/open.mjs +17 -0
- package/plugins/config-ui/lib/ownership.mjs +99 -0
- package/plugins/config-ui/lib/page.mjs +11 -0
- package/plugins/config-ui/lib/patch.mjs +36 -0
- package/plugins/config-ui/lib/paths.mjs +14 -0
- package/plugins/config-ui/lib/plugin-fields.mjs +86 -0
- package/plugins/config-ui/lib/plugin-validation.mjs +28 -0
- package/plugins/config-ui/lib/redaction.mjs +8 -0
- package/plugins/config-ui/lib/registry.mjs +282 -0
- package/plugins/config-ui/lib/secrets.mjs +45 -0
- package/plugins/config-ui/lib/server.mjs +251 -0
- package/plugins/config-ui/lib/sources.mjs +96 -0
- package/plugins/config-ui/lib/state.mjs +157 -0
- package/plugins/config-ui/lib/themes.mjs +113 -0
- package/plugins/config-ui/lib/writer.mjs +691 -0
- package/plugins/config-ui/package.json +12 -0
- package/plugins/config-ui/project-local-owner.ts +106 -0
- package/plugins/config-ui/vc-extras.plugin.json +13 -0
- package/plugins/config-ui/web/app.mjs +997 -0
- package/plugins/config-ui/web/index.html +342 -0
- package/plugins/pi-blackhole/vc-extras.plugin.json +12 -0
- package/plugins/pi-btw/vc-extras.plugin.json +12 -0
- package/plugins/pi-claude-code/vc-extras.plugin.json +12 -0
- package/plugins/pi-fff/vc-extras.plugin.json +12 -0
- package/plugins/pi-jev-auto-mode/vc-extras.plugin.json +12 -0
- package/plugins/pi-mcp-adapter/vc-extras.plugin.json +12 -0
- package/plugins/pi-web-access/vc-extras.plugin.json +12 -0
- package/plugins/vc-ask/claude-hook.mjs +37 -0
- package/plugins/vc-ask/codex-native.mjs +28 -0
- package/plugins/vc-ask/host-channel.mjs +75 -0
- package/plugins/vc-ask/index.ts +57 -0
- package/plugins/vc-ask/native-questions.mjs +33 -0
- package/plugins/vc-ask/package.json +10 -0
- package/plugins/vc-ask/payload.ts +170 -0
- package/plugins/vc-ask/questionnaire/LICENSE.ask-user-question +21 -0
- package/plugins/vc-ask/questionnaire/UPSTREAM.md +104 -0
- package/plugins/vc-ask/questionnaire/answer-channel.ts +135 -0
- package/plugins/vc-ask/questionnaire/config.ts +180 -0
- package/plugins/vc-ask/questionnaire/events.ts +154 -0
- package/plugins/vc-ask/questionnaire/execute.ts +688 -0
- package/plugins/vc-ask/questionnaire/i18n.ts +73 -0
- package/plugins/vc-ask/questionnaire/inline-entry.ts +312 -0
- package/plugins/vc-ask/questionnaire/locales/de.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/en.json +42 -0
- package/plugins/vc-ask/questionnaire/locales/es.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/fr.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/pt-BR.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/pt.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/ru.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/uk.json +43 -0
- package/plugins/vc-ask/questionnaire/locales/zh.json +46 -0
- package/plugins/vc-ask/questionnaire/presentation.ts +11 -0
- package/plugins/vc-ask/questionnaire/question-preview.ts +6 -0
- package/plugins/vc-ask/questionnaire/rpc.ts +221 -0
- package/plugins/vc-ask/questionnaire/session-timeout.ts +67 -0
- package/plugins/vc-ask/questionnaire/state/build-questionnaire.ts +144 -0
- package/plugins/vc-ask/questionnaire/state/external-editor.ts +62 -0
- package/plugins/vc-ask/questionnaire/state/geometry.ts +131 -0
- package/plugins/vc-ask/questionnaire/state/key-router.ts +382 -0
- package/plugins/vc-ask/questionnaire/state/panel-router.ts +32 -0
- package/plugins/vc-ask/questionnaire/state/questionnaire-session.ts +642 -0
- package/plugins/vc-ask/questionnaire/state/row-intent.ts +143 -0
- package/plugins/vc-ask/questionnaire/state/selectors/contract.ts +24 -0
- package/plugins/vc-ask/questionnaire/state/selectors/derivations.ts +40 -0
- package/plugins/vc-ask/questionnaire/state/selectors/focus.ts +17 -0
- package/plugins/vc-ask/questionnaire/state/selectors/projections.ts +99 -0
- package/plugins/vc-ask/questionnaire/state/state-reducer.ts +455 -0
- package/plugins/vc-ask/questionnaire/state/state.ts +90 -0
- package/plugins/vc-ask/questionnaire/state/vertical.ts +158 -0
- package/plugins/vc-ask/questionnaire/timeout.ts +59 -0
- package/plugins/vc-ask/questionnaire/tool/external-answer.ts +103 -0
- package/plugins/vc-ask/questionnaire/tool/format-answer.ts +24 -0
- package/plugins/vc-ask/questionnaire/tool/normalize-params.ts +37 -0
- package/plugins/vc-ask/questionnaire/tool/response-envelope.ts +75 -0
- package/plugins/vc-ask/questionnaire/tool/types.ts +74 -0
- package/plugins/vc-ask/questionnaire/tool/validate-questionnaire.ts +75 -0
- package/plugins/vc-ask/questionnaire/view/card-theme.ts +245 -0
- package/plugins/vc-ask/questionnaire/view/components/inline-input.ts +66 -0
- package/plugins/vc-ask/questionnaire/view/components/multi-select-view.ts +177 -0
- package/plugins/vc-ask/questionnaire/view/components/option-list-view.ts +65 -0
- package/plugins/vc-ask/questionnaire/view/components/preview/markdown-content-cache.ts +101 -0
- package/plugins/vc-ask/questionnaire/view/components/preview/preview-block-renderer.ts +130 -0
- package/plugins/vc-ask/questionnaire/view/components/preview/preview-box-renderer.ts +86 -0
- package/plugins/vc-ask/questionnaire/view/components/preview/preview-layout-decider.ts +204 -0
- package/plugins/vc-ask/questionnaire/view/components/preview/preview-pane.ts +257 -0
- package/plugins/vc-ask/questionnaire/view/components/submit-picker.ts +65 -0
- package/plugins/vc-ask/questionnaire/view/components/tab-bar.ts +57 -0
- package/plugins/vc-ask/questionnaire/view/components/wrapping-select.ts +269 -0
- package/plugins/vc-ask/questionnaire/view/dialog-builder.ts +319 -0
- package/plugins/vc-ask/questionnaire/view/document-theme.ts +53 -0
- package/plugins/vc-ask/questionnaire/view/document-view.ts +306 -0
- package/plugins/vc-ask/questionnaire/view/panel-chrome.ts +133 -0
- package/plugins/vc-ask/questionnaire/view/props-adapter.ts +77 -0
- package/plugins/vc-ask/questionnaire/view/stateful-view.ts +24 -0
- package/plugins/vc-ask/questionnaire/view/tab-components.ts +16 -0
- package/plugins/vc-ask/questionnaire/view/tab-content-strategy.ts +280 -0
- package/plugins/vc-ask/questionnaire/view/vertical-view.ts +218 -0
- package/plugins/vc-ask/user-input-events.ts +34 -0
- package/plugins/vc-ask/vc-extras.plugin.json +18 -0
- package/plugins/vc-footer/agents/claude-code/adapter.mjs +29 -0
- package/plugins/vc-footer/agents/claude-code/cli.mjs +23 -0
- package/plugins/vc-footer/agents/claude-code/renderer.mjs +1 -0
- package/plugins/vc-footer/agents/claude-code/types.d.ts +38 -0
- package/plugins/vc-footer/agents/codex/adapter.mjs +13 -0
- package/plugins/vc-footer/agents/codex/mcp.mjs +45 -0
- package/plugins/vc-footer/agents/codex/native.mjs +19 -0
- package/plugins/vc-footer/agents/codex/renderer.mjs +2 -0
- package/plugins/vc-footer/agents/pi/adapter.mjs +23 -0
- package/plugins/vc-footer/agents/pi/index.js +84 -0
- package/plugins/vc-footer/agents/pi/project-local-owner.mjs +97 -0
- package/plugins/vc-footer/agents/pi/renderer.mjs +5 -0
- package/plugins/vc-footer/core/data.mjs +218 -0
- package/plugins/vc-footer/core/render.mjs +291 -0
- package/plugins/vc-footer/core/types.d.ts +29 -0
- package/plugins/vc-footer/package.json +22 -0
- package/plugins/vc-footer/vc-extras.plugin.json +32 -0
- package/skills/animate/LICENSE +21 -0
- package/skills/animate/RECIPES.md +324 -0
- package/skills/animate/SKILL.md +208 -0
- package/skills/animate/UPSTREAM.md +19 -0
- package/skills/animation-performance/LICENSE +21 -0
- package/skills/animation-performance/SKILL.md +223 -0
- package/skills/animation-performance/UPSTREAM.md +19 -0
- package/skills/answer-me-with-html/SKILL.md +174 -0
- package/skills/answer-me-with-html/scripts/am.mjs +12896 -0
- package/skills/apple-design/LICENSE +21 -0
- package/skills/apple-design/SKILL.md +291 -0
- package/skills/apple-design/UPSTREAM.md +19 -0
- package/skills/bad-smell/SKILL.md +44 -0
- package/skills/commit/SKILL.md +90 -0
- package/skills/emil-design-eng/LICENSE +21 -0
- package/skills/emil-design-eng/SKILL.md +677 -0
- package/skills/emil-design-eng/UPSTREAM.md +19 -0
- package/skills/find-the-truth/SKILL.md +38 -0
- package/skills/find-the-truth/references/trace-method.md +48 -0
- package/skills/find-the-truth/references/truth-method.md +39 -0
- package/skills/gestures/LICENSE +21 -0
- package/skills/gestures/SKILL.md +107 -0
- package/skills/gestures/UPSTREAM.md +19 -0
- package/skills/humanizer-zh/LICENSE +21 -0
- package/skills/humanizer-zh/SKILL.md +409 -0
- package/skills/humanizer-zh/UPSTREAM.md +7 -0
- package/skills/impeccable/LICENSE +191 -0
- package/skills/impeccable/NOTICE.md +11 -0
- package/skills/impeccable/SKILL.md +90 -0
- package/skills/impeccable/licenses/modern-screenshot-MIT.txt +9 -0
- package/skills/impeccable/licenses/platform-design-skills-MIT.txt +21 -0
- package/skills/impeccable/reference/adapt.md +318 -0
- package/skills/impeccable/reference/adapt.native.md +58 -0
- package/skills/impeccable/reference/android.md +46 -0
- package/skills/impeccable/reference/animate.md +89 -0
- package/skills/impeccable/reference/audit.md +139 -0
- package/skills/impeccable/reference/audit.native.md +139 -0
- package/skills/impeccable/reference/bolder.md +33 -0
- package/skills/impeccable/reference/clarify.md +94 -0
- package/skills/impeccable/reference/colorize.md +86 -0
- package/skills/impeccable/reference/component-review.md +63 -0
- package/skills/impeccable/reference/craft-floor.md +44 -0
- package/skills/impeccable/reference/craft.md +5 -0
- package/skills/impeccable/reference/critique.md +819 -0
- package/skills/impeccable/reference/degraded/asset-producer.md +42 -0
- package/skills/impeccable/reference/degraded/documenter.md +24 -0
- package/skills/impeccable/reference/degraded/finish-reviewer.md +38 -0
- package/skills/impeccable/reference/degraded/manual-edit-applier.md +93 -0
- package/skills/impeccable/reference/delight.md +70 -0
- package/skills/impeccable/reference/distill.md +111 -0
- package/skills/impeccable/reference/doctor.md +54 -0
- package/skills/impeccable/reference/document.md +416 -0
- package/skills/impeccable/reference/extract.md +69 -0
- package/skills/impeccable/reference/generate.md +101 -0
- package/skills/impeccable/reference/harden.md +362 -0
- package/skills/impeccable/reference/hooks.md +114 -0
- package/skills/impeccable/reference/init.md +131 -0
- package/skills/impeccable/reference/ios.md +51 -0
- package/skills/impeccable/reference/layout.md +84 -0
- package/skills/impeccable/reference/live-setup.md +104 -0
- package/skills/impeccable/reference/live.md +327 -0
- package/skills/impeccable/reference/mode-operate.md +21 -0
- package/skills/impeccable/reference/mode-persuade.md +19 -0
- package/skills/impeccable/reference/mode-read.md +21 -0
- package/skills/impeccable/reference/new-work.md +152 -0
- package/skills/impeccable/reference/onboard.md +234 -0
- package/skills/impeccable/reference/operate.md +61 -0
- package/skills/impeccable/reference/optimize.md +257 -0
- package/skills/impeccable/reference/overdrive.md +127 -0
- package/skills/impeccable/reference/polish.md +105 -0
- package/skills/impeccable/reference/quieter.md +99 -0
- package/skills/impeccable/reference/region-map.md +26 -0
- package/skills/impeccable/reference/routing.md +24 -0
- package/skills/impeccable/reference/shape.md +59 -0
- package/skills/impeccable/reference/typeset.md +90 -0
- package/skills/impeccable/reference/visualize.md +47 -0
- package/skills/impeccable/scripts/VERSION +1 -0
- package/skills/impeccable/scripts/command-metadata.json +98 -0
- package/skills/impeccable/scripts/data/font-index-failures.json +121 -0
- package/skills/impeccable/scripts/data/font-index.json +1 -0
- package/skills/impeccable/scripts/engine-checksums.txt +9 -0
- package/skills/impeccable/scripts/impeccable +249 -0
- package/skills/impeccable/scripts/impeccable.cmd +278 -0
- package/skills/impeccable/scripts/live-browser-dom.js +320 -0
- package/skills/impeccable/scripts/live-browser-ignores.js +246 -0
- package/skills/impeccable/scripts/live-browser-session.js +183 -0
- package/skills/impeccable/scripts/live-browser.js +13862 -0
- package/skills/impeccable/scripts/modern-screenshot.umd.js +14 -0
- package/skills/improve-animations/AUDIT.md +115 -0
- package/skills/improve-animations/LICENSE +21 -0
- package/skills/improve-animations/PLAN-TEMPLATE.md +73 -0
- package/skills/improve-animations/SKILL.md +110 -0
- package/skills/improve-animations/UPSTREAM.md +19 -0
- package/skills/pick-ui-library/LICENSE +21 -0
- package/skills/pick-ui-library/SKILL.md +85 -0
- package/skills/pick-ui-library/UPSTREAM.md +19 -0
- package/skills/review-animations/LICENSE +21 -0
- package/skills/review-animations/SKILL.md +120 -0
- package/skills/review-animations/STANDARDS.md +187 -0
- package/skills/review-animations/UPSTREAM.md +19 -0
- package/skills/test/SKILL.md +29 -0
- package/skills/test/references/test-method.md +60 -0
- package/skills/write-doc/SKILL.md +115 -0
- package/skills/write-doc/examples/result-report.md +53 -0
- package/skills/write-doc/examples/task-summary.md +45 -0
- package/skills/write-doc/references/terminology.md +147 -0
- package/specs/ask-host-protocol-v1.md +58 -0
- package/specs/design-demo.md +1102 -0
- package/specs/frontend-immersive.md +28 -0
- package/specs/plugin-install-v2.md +123 -0
- package/specs/plugin-install.md +38 -0
- package/specs/web-modes/explore.md +31 -0
- package/specs/web-modes/risk.md +15 -0
- package/specs/web-modes/verify.md +16 -0
- package/vc-extras.mjs +62 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// The local service exists so that clicking 保存 actually writes. That is a real
|
|
2
|
+
// network surface, so it is kept as small as possible: loopback only, a random
|
|
3
|
+
// port, a one-time token that the page must echo, an Origin check, a small body
|
|
4
|
+
// cap, and an idle exit so the process does not keep listening forever.
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as http from "node:http";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { readState } from "./state.mjs";
|
|
10
|
+
import { applyChanges, fileSnapshot, planChanges } from "./writer.mjs";
|
|
11
|
+
import { FIELDS, FILES } from "./registry.mjs";
|
|
12
|
+
import { discoverThemes } from "./themes.mjs";
|
|
13
|
+
|
|
14
|
+
const FIELD_FILES = Object.fromEntries(FIELDS.map((field) => [field.id, field.file]));
|
|
15
|
+
// The offline page has no service to ask which fields are read-only, so the ids travel
|
|
16
|
+
// with the boot payload; the labels make the skip note readable.
|
|
17
|
+
const FIELD_READONLY = FIELDS.filter((field) => field.strategy === "readonly").map((field) => field.id);
|
|
18
|
+
const FIELD_NAMES = Object.fromEntries(FIELDS.map((field) => [field.id, field.label]));
|
|
19
|
+
const FIELD_SEMANTICS = Object.fromEntries(FIELDS.map(({ id, kind, empty }) => [id, { kind, empty }]));
|
|
20
|
+
|
|
21
|
+
const MAX_BODY = 512 * 1024;
|
|
22
|
+
const IDLE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
23
|
+
const EXIT_AFTER_SAVE_MS = 30 * 1000;
|
|
24
|
+
|
|
25
|
+
export function createToken() {
|
|
26
|
+
return randomBytes(24).toString("hex");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function startConfigServer(options) {
|
|
30
|
+
const { context, pageDir, idleTimeoutMs = IDLE_TIMEOUT_MS, exitAfterSaveMs = EXIT_AFTER_SAVE_MS } = options;
|
|
31
|
+
// Port 0 means an ephemeral port, so two projects never collide.
|
|
32
|
+
const wantedPort = options.port ?? 0;
|
|
33
|
+
const token = options.token ?? createToken();
|
|
34
|
+
const signal = options.signal;
|
|
35
|
+
signal?.throwIfAborted();
|
|
36
|
+
const versions = new Map();
|
|
37
|
+
const previews = new Map();
|
|
38
|
+
let idleTimer;
|
|
39
|
+
let saveTimer;
|
|
40
|
+
let stopped = false;
|
|
41
|
+
|
|
42
|
+
// Keep recent snapshots per load and only a small number of reviewed plans
|
|
43
|
+
// (which contain the edited values, including any newly typed secrets).
|
|
44
|
+
function remember(map, value, maximum) {
|
|
45
|
+
const id = createToken();
|
|
46
|
+
map.set(id, value);
|
|
47
|
+
while (map.size > maximum) map.delete(map.keys().next().value);
|
|
48
|
+
return id;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const server = http.createServer((request, response) => {
|
|
52
|
+
handle(request, response).catch((error) => send(response, 500, { error: error instanceof Error ? error.message : String(error) }));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const stop = () => {
|
|
56
|
+
if (stopped) return;
|
|
57
|
+
stopped = true;
|
|
58
|
+
clearTimeout(idleTimer);
|
|
59
|
+
clearTimeout(saveTimer);
|
|
60
|
+
versions.clear();
|
|
61
|
+
previews.clear();
|
|
62
|
+
signal?.removeEventListener("abort", stop);
|
|
63
|
+
server.close();
|
|
64
|
+
options.onClose?.();
|
|
65
|
+
};
|
|
66
|
+
const touch = () => {
|
|
67
|
+
clearTimeout(idleTimer);
|
|
68
|
+
idleTimer = setTimeout(stop, idleTimeoutMs);
|
|
69
|
+
};
|
|
70
|
+
server.on("close", () => { clearTimeout(idleTimer); clearTimeout(saveTimer); });
|
|
71
|
+
await new Promise((resolve, reject) => {
|
|
72
|
+
server.once("error", reject);
|
|
73
|
+
server.listen(wantedPort, "127.0.0.1", () => { server.removeListener("error", reject); resolve(); });
|
|
74
|
+
});
|
|
75
|
+
if (signal?.aborted) { stop(); signal.throwIfAborted(); }
|
|
76
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
77
|
+
touch();
|
|
78
|
+
const { port } = server.address();
|
|
79
|
+
const origin = `http://127.0.0.1:${port}`;
|
|
80
|
+
|
|
81
|
+
async function handle(request, response) {
|
|
82
|
+
if (stopped) return send(response, 503, { error: "配置服务已关闭" });
|
|
83
|
+
touch();
|
|
84
|
+
const url = new URL(request.url ?? "/", origin);
|
|
85
|
+
const frame = request.headers.origin;
|
|
86
|
+
if (frame && frame !== origin) return send(response, 403, { error: "origin 不被接受" });
|
|
87
|
+
// Host pins the request to this listener too, so a DNS-rebinding name cannot reach it.
|
|
88
|
+
const host = (request.headers.host ?? "").replace(/^\[|\]$/g, "");
|
|
89
|
+
if (host && host !== `127.0.0.1:${port}` && host !== "127.0.0.1" && host !== `localhost:${port}` && host !== "localhost")
|
|
90
|
+
return send(response, 403, { error: "host 不被接受" });
|
|
91
|
+
if (url.pathname === "/") return sendPage(response, url);
|
|
92
|
+
if (url.pathname === "/favicon.ico" && request.method === "GET") { response.writeHead(204); return response.end(); }
|
|
93
|
+
if (request.method === "GET" && /^\/[\w.-]+\.(mjs|js|css|svg)$/.test(url.pathname)) return sendAsset(response, url.pathname);
|
|
94
|
+
if (request.headers["x-emma-token"] !== token) return send(response, 401, { error: "令牌无效" });
|
|
95
|
+
if (url.pathname === "/api/state" && request.method === "GET") {
|
|
96
|
+
const before = snapshotExpectations();
|
|
97
|
+
const state = readState({ context });
|
|
98
|
+
const after = snapshotExpectations();
|
|
99
|
+
// An external edit while loading must not create a fresh but stale baseline.
|
|
100
|
+
if (JSON.stringify(before) !== JSON.stringify(after)) return send(response, 409, { error: "配置在读取时变化,请重新载入" });
|
|
101
|
+
const expectations = Object.fromEntries(Object.entries(after).map(([key, value]) => [key, { ...state.expectations[key], path: value.target, snapshot: value.snapshot }]));
|
|
102
|
+
return send(response, 200, { ...state, version: remember(versions, expectations, 64) });
|
|
103
|
+
}
|
|
104
|
+
// Planning is a separate call on purpose: the user reviews the diff before
|
|
105
|
+
// anything is written, and the diff they review is the one the writer would do.
|
|
106
|
+
if (url.pathname === "/api/plan" && request.method === "POST") return plan(request, response);
|
|
107
|
+
if (url.pathname === "/api/save" && request.method === "POST") return save(request, response);
|
|
108
|
+
return send(response, 404, { error: "not found" });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function sendPage(response, url) {
|
|
112
|
+
const file = path.join(pageDir, "index.html");
|
|
113
|
+
if (!fs.existsSync(file)) return send(response, 500, { error: `缺少配置页文件:${file}` });
|
|
114
|
+
// The page needs the token to call the API, so it is injected at serve time
|
|
115
|
+
// rather than shipped in the file.
|
|
116
|
+
const html = inject(fs.readFileSync(file, "utf8"), { token, origin, themes: discoverThemes(context) });
|
|
117
|
+
void url;
|
|
118
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
119
|
+
response.end(html);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function snapshotExpectations() {
|
|
123
|
+
return Object.fromEntries(Object.entries(FILES).map(([key, definition]) => {
|
|
124
|
+
const target = definition.resolve(context);
|
|
125
|
+
try { return [key, { target, snapshot: fileSnapshot(target) }]; }
|
|
126
|
+
catch { return [key, { target, unavailable: true }]; }
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function readPayload(request, response) {
|
|
131
|
+
const body = await readBody(request);
|
|
132
|
+
if (body === null) {
|
|
133
|
+
send(response, 413, { error: "请求体过大" });
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
let payload;
|
|
137
|
+
try {
|
|
138
|
+
payload = JSON.parse(body);
|
|
139
|
+
} catch {
|
|
140
|
+
send(response, 400, { error: "请求体不是 JSON" });
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
if (stopped) { send(response, 503, { error: "配置服务已关闭" }); return null; }
|
|
144
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
145
|
+
send(response, 400, { error: "请求格式不正确" });
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
return payload;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function plan(request, response) {
|
|
152
|
+
const payload = await readPayload(request, response);
|
|
153
|
+
if (!payload) return;
|
|
154
|
+
const { values, version } = payload;
|
|
155
|
+
if (!values || typeof values !== "object" || Array.isArray(values)) return send(response, 400, { error: "缺少 values" });
|
|
156
|
+
const expectations = versions.get(version);
|
|
157
|
+
if (!expectations) return send(response, 409, { error: "页面版本已失效,请重新载入" });
|
|
158
|
+
const planned = planChanges({ values, context, expectations });
|
|
159
|
+
const preview = !planned.problems.length && planned.files.length && !planned.files.some(entry => entry.conflict)
|
|
160
|
+
? remember(previews, { version, values, planned }, 16) : null;
|
|
161
|
+
return send(response, 200, { problems: planned.problems, skipped: planned.skipped, changes: describe(planned), preview });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The page is served from the disk so `app.mjs` can be a real module next to it.
|
|
165
|
+
function sendAsset(response, pathname) {
|
|
166
|
+
const file = path.join(pageDir, path.basename(pathname));
|
|
167
|
+
if (!fs.existsSync(file)) return send(response, 404, { error: "not found" });
|
|
168
|
+
const type = file.endsWith(".mjs") || file.endsWith(".js") ? "text/javascript; charset=utf-8"
|
|
169
|
+
: file.endsWith(".css") ? "text/css; charset=utf-8"
|
|
170
|
+
: file.endsWith(".svg") ? "image/svg+xml" : "application/octet-stream";
|
|
171
|
+
response.writeHead(200, { "content-type": type, "cache-control": "no-store" });
|
|
172
|
+
response.end(fs.readFileSync(file));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function save(request, response) {
|
|
176
|
+
const payload = await readPayload(request, response);
|
|
177
|
+
if (!payload) return;
|
|
178
|
+
const { preview, version } = payload;
|
|
179
|
+
const reviewed = previews.get(preview);
|
|
180
|
+
if (!reviewed || reviewed.version !== version || !versions.has(version) || Object.hasOwn(payload, "values"))
|
|
181
|
+
return send(response, 409, { error: "没有有效的预览,请重新预览" });
|
|
182
|
+
previews.delete(preview);
|
|
183
|
+
const { values, planned } = reviewed;
|
|
184
|
+
const { results, failure } = applyChanges(planned, { context });
|
|
185
|
+
if (!failure && results.some(result => result.status === "written")) {
|
|
186
|
+
versions.delete(version);
|
|
187
|
+
for (const [id, item] of previews) if (item.version === version) previews.delete(id);
|
|
188
|
+
clearTimeout(saveTimer);
|
|
189
|
+
if (exitAfterSaveMs > 0) saveTimer = setTimeout(stop, exitAfterSaveMs);
|
|
190
|
+
// A live-apply failure cannot change the disk outcome.
|
|
191
|
+
try { options.onApplied?.({ values, results }); } catch {}
|
|
192
|
+
}
|
|
193
|
+
send(response, 200, { results, failure, skipped: planned.skipped, changes: describe(planned) });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return { url: `${origin}/?token=${token}`, origin, port, token, close: stop };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Over-sized bodies are drained rather than aborted: killing the socket would take
|
|
200
|
+
// the 413 response down with it, and the caller would see a network error instead
|
|
201
|
+
// of a reason.
|
|
202
|
+
// The page needs its token and the field→file map; both are injected at serve time
|
|
203
|
+
// instead of living in the file.
|
|
204
|
+
export function inject(html, { token = "", origin = "", state = null, themes = null }) {
|
|
205
|
+
const boot = { token, origin, fields: FIELD_FILES, readonly: FIELD_READONLY, names: FIELD_NAMES, semantics: FIELD_SEMANTICS, controls: FIELDS, themes };
|
|
206
|
+
const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
|
|
207
|
+
const payload = `<script>window.__EMMA_BOOT__=${scriptJson(boot)};`
|
|
208
|
+
+ (state ? `window.__EMMA_STATE__=${scriptJson(state)};` : "")
|
|
209
|
+
+ "</script>";
|
|
210
|
+
// A replacement function, not a string: `$$`, `$&`, `$'` in the payload (policy text
|
|
211
|
+
// and paths are free-form) would otherwise be expanded while injecting.
|
|
212
|
+
return html.replace("<!--__EMMA_BOOT__-->", () => payload);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function describe(plan) {
|
|
216
|
+
return plan.files.map((entry) => ({
|
|
217
|
+
key: entry.key,
|
|
218
|
+
path: entry.path,
|
|
219
|
+
sample: entry.sample,
|
|
220
|
+
conflict: entry.conflict === true,
|
|
221
|
+
notice: entry.notice,
|
|
222
|
+
reload: entry.reload,
|
|
223
|
+
changes: entry.changes,
|
|
224
|
+
}));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function readBody(request) {
|
|
228
|
+
return new Promise((resolve, reject) => {
|
|
229
|
+
let size = 0;
|
|
230
|
+
let tooLarge = false;
|
|
231
|
+
const chunks = [];
|
|
232
|
+
request.on("data", (chunk) => {
|
|
233
|
+
size += chunk.length;
|
|
234
|
+
if (size > MAX_BODY) {
|
|
235
|
+
tooLarge = true;
|
|
236
|
+
chunks.length = 0;
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
chunks.push(chunk);
|
|
240
|
+
});
|
|
241
|
+
request.on("end", () => resolve(tooLarge ? null : Buffer.concat(chunks).toString("utf8")));
|
|
242
|
+
request.on("error", reject);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function send(response, status, payload) {
|
|
247
|
+
if (response.writableEnded) return;
|
|
248
|
+
const body = `${JSON.stringify(payload)}\n`;
|
|
249
|
+
response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "content-length": Buffer.byteLength(body) });
|
|
250
|
+
response.end(body);
|
|
251
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
|
|
7
|
+
export const VERIFIED_PLUGIN_VERSIONS = {
|
|
8
|
+
piFff: { name: "@ff-labs/pi-fff", version: "0.11.0" },
|
|
9
|
+
webSearch: { name: "pi-web-access", version: "0.44.0", reviewedVersions: ["0.37.0", "0.44.0"] },
|
|
10
|
+
piCcExtensions: { name: "pi-cc-extensions", version: "1.0.14", reviewedVersions: ["1.0.14"] },
|
|
11
|
+
subagents: { name: "@tintinweb/pi-subagents", version: "0.22.0" },
|
|
12
|
+
piBtw: { name: "@narumitw/pi-btw", version: "0.62.0", reviewedVersions: ["0.61.2", "0.62.0"] },
|
|
13
|
+
jev: { name: "pi-jev-auto-mode", version: "0.6.0" },
|
|
14
|
+
mcp: { name: "pi-mcp-adapter", version: "5.4.0", reviewedVersions: ["2.38.0", "5.4.0"] },
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// ESM caches public config modules for the lifetime of Pi. Reopening /config
|
|
18
|
+
// after an upgrade must not certify a path returned by the previous module.
|
|
19
|
+
const mcpApiVersions = new Map();
|
|
20
|
+
|
|
21
|
+
function installedVersion(context, name) {
|
|
22
|
+
try {
|
|
23
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(context.agentDir, "npm", "node_modules", name, "package.json"), "utf8"));
|
|
24
|
+
if (manifest?.name === name && typeof manifest.version === "string") return manifest.version;
|
|
25
|
+
} catch {}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function sourceStatus(context, key) {
|
|
29
|
+
const source = context.sources?.[key] ?? {};
|
|
30
|
+
if (key === "piCcExtensions" && (installedVersion(context, "pi-claude-code") || fs.existsSync(path.join(context.agentDir, "pi-claude-code.json")) || fs.existsSync(path.join(context.agentDir, "statusline.json")))) {
|
|
31
|
+
// Both packages may use this filename. Without a proven exclusive owner,
|
|
32
|
+
// neither the renderer form nor an offline patch should interpret the file.
|
|
33
|
+
return { ...source, writable: false, verified: false, legacyRenderer: true, warning: "检测到独立的 pi-claude-code;无法确认渲染器配置的归属,此页不会读取、迁移或写入它。" };
|
|
34
|
+
}
|
|
35
|
+
const contract = VERIFIED_PLUGIN_VERSIONS[key === "jevPolicy" ? "jev" : key];
|
|
36
|
+
if (contract) {
|
|
37
|
+
const version = installedVersion(context, contract.name);
|
|
38
|
+
// A version number is not a config contract: the page edits keys it knows and the
|
|
39
|
+
// writer preserves everything else, so only a stale write path blocks editing.
|
|
40
|
+
if (key === "mcp" && source.version !== undefined && source.version !== version)
|
|
41
|
+
return { ...source, version, writable: false, verified: false, warning: "MCP 安装版本已改变,原配置路径尚未重新核实;请重新加载 Pi 后打开 /config。" };
|
|
42
|
+
return { ...source, version, verified: true };
|
|
43
|
+
}
|
|
44
|
+
return source;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const configEnv = (context) => context.env ?? (context.homeDir === os.homedir() ? process.env : {});
|
|
48
|
+
const home = (c) => c.homeDir ?? os.homedir();
|
|
49
|
+
|
|
50
|
+
export function webConfigPath(c) {
|
|
51
|
+
const env = configEnv(c);
|
|
52
|
+
if (env.PI_CODING_AGENT_DIR) return path.join(c.agentDir, "web-search.json");
|
|
53
|
+
const directory = env.XDG_CONFIG_HOME ? path.join(env.XDG_CONFIG_HOME, "pi") : c.agentDir;
|
|
54
|
+
const preferred = path.join(directory, "web-search.json");
|
|
55
|
+
const legacy = path.join(home(c), ".pi", "web-search.json");
|
|
56
|
+
return fs.existsSync(preferred) || !fs.existsSync(legacy) ? preferred : legacy;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const mcpConfigPath = (c) => c.sources?.mcp?.path || path.join(c.agentDir, "mcp.json");
|
|
60
|
+
|
|
61
|
+
export function optionValue(argv, name) {
|
|
62
|
+
const i = argv.indexOf(name);
|
|
63
|
+
return i >= 0 ? argv[i + 1] : argv.find(arg => arg.startsWith(name + "="))?.slice(name.length + 1);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Only the plugin's public config module is loaded, never its extension entry.
|
|
67
|
+
export async function prepareSources(context) {
|
|
68
|
+
const c = { ...context, env: { ...configEnv(context) }, sources: {} };
|
|
69
|
+
const require = createRequire(path.join(c.agentDir, "npm", "package.json"));
|
|
70
|
+
let mcpVersion;
|
|
71
|
+
try {
|
|
72
|
+
mcpVersion = JSON.parse(fs.readFileSync(path.join(c.agentDir, "npm/node_modules/pi-mcp-adapter/package.json"), "utf8")).version;
|
|
73
|
+
if (typeof mcpVersion !== "string") throw new Error("missing MCP version");
|
|
74
|
+
const modulePath = require.resolve("pi-mcp-adapter/config");
|
|
75
|
+
if (mcpApiVersions.has(modulePath) && mcpApiVersions.get(modulePath) !== mcpVersion) throw new Error("cached MCP config API version changed");
|
|
76
|
+
mcpApiVersions.set(modulePath, mcpVersion);
|
|
77
|
+
const api = await import(pathToFileURL(modulePath).href);
|
|
78
|
+
if (typeof api.getPiGlobalConfigPath !== "function") throw new Error("unsupported config API");
|
|
79
|
+
const override = optionValue(c.argv ?? process.argv, "--mcp-config");
|
|
80
|
+
const target = api.getPiGlobalConfigPath(override);
|
|
81
|
+
const discovery = typeof api.getConfigDiscoveryPaths === "function" ? api.getConfigDiscoveryPaths(override, c.projectRoot) : [];
|
|
82
|
+
c.sources.mcp = { path: target, version: mcpVersion, writable: true, warning: "编辑指定用户文件;MCP 还可能合并项目、共享、导入和程序化配置。程序化注入无法由本页核实。", discovery: discovery.filter(item => item.exists).map(item => item.path) };
|
|
83
|
+
} catch {
|
|
84
|
+
c.sources.mcp = { path: mcpConfigPath(c), version: mcpVersion, writable: false, warning: "无法核实已安装 MCP 的公开配置路径 API;如插件已升级,请重新加载 Pi 后打开 /config。拒绝猜测写入位置。" };
|
|
85
|
+
}
|
|
86
|
+
const packages = { piFff: "@ff-labs/pi-fff", webSearch: "pi-web-access", piCcExtensions: "pi-cc-extensions", subagents: "@tintinweb/pi-subagents", piBtw: "@narumitw/pi-btw", jev: "pi-jev-auto-mode", mcp: "pi-mcp-adapter", blackhole: "pi-blackhole" };
|
|
87
|
+
for (const [key, name] of Object.entries(packages)) {
|
|
88
|
+
c.sources[key] ??= {};
|
|
89
|
+
try {
|
|
90
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(c.agentDir, "npm", "node_modules", name, "package.json"), "utf8"));
|
|
91
|
+
// MCP's version belongs to the API/path snapshot, not a later manifest read.
|
|
92
|
+
if (key !== "mcp") c.sources[key].version = manifest.version;
|
|
93
|
+
} catch {}
|
|
94
|
+
}
|
|
95
|
+
return c;
|
|
96
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// The page must show what is on disk, not what a mock said. This reads each registry
|
|
2
|
+
// file once, hands the form a flat `{ fieldId: value }` map, and keeps every file's
|
|
3
|
+
// size and mtime so a later save can prove nothing changed underneath.
|
|
4
|
+
//
|
|
5
|
+
// Secrets are the exception: the form never receives a key, only whether one exists.
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import { FIELDS, FILES, readField } from "./registry.mjs";
|
|
8
|
+
import { readCredentials } from "./secrets.mjs";
|
|
9
|
+
import { parseFrontmatter } from "./frontmatter.mjs";
|
|
10
|
+
import { parseDocument, pageValue } from "./documents.mjs";
|
|
11
|
+
import { EXISTING_DEFAULTS } from "./plugin-fields.mjs";
|
|
12
|
+
import { sourceStatus } from "./sources.mjs";
|
|
13
|
+
import { safeUrl } from "./redaction.mjs";
|
|
14
|
+
|
|
15
|
+
function loadFile(target, definition) {
|
|
16
|
+
if (definition.kind === "text") return fs.readFileSync(target, "utf8");
|
|
17
|
+
if (definition.kind === "frontmatter") return parseFrontmatter(fs.readFileSync(target, "utf8"));
|
|
18
|
+
return parseDocument(fs.readFileSync(target, "utf8"), definition.kind);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function readState({ context }) {
|
|
22
|
+
const files = {};
|
|
23
|
+
const expectations = {};
|
|
24
|
+
const problems = [];
|
|
25
|
+
const loaded = new Map();
|
|
26
|
+
const trusted = context.trusted !== false;
|
|
27
|
+
|
|
28
|
+
for (const [key, definition] of Object.entries(FILES)) {
|
|
29
|
+
const target = definition.resolve(context);
|
|
30
|
+
const exists = fs.existsSync(target);
|
|
31
|
+
const source = sourceStatus(context, key);
|
|
32
|
+
const writable = (trusted || definition.scope !== "project") && source.writable !== false;
|
|
33
|
+
const projectOverride = definition.projectOverrides?.(context).find(file => fs.existsSync(file));
|
|
34
|
+
files[key] = { ...source, reload: "需重新加载 Pi", sample: definition.sample, path: target, scope: definition.scope, kind: definition.kind, exists, writable,
|
|
35
|
+
...(projectOverride ? { projectOverride, warning: [source.warning, "当前项目覆盖: " + projectOverride + ";此页只编辑用户共享默认值,不修改该项目覆盖。"].filter(Boolean).join(" ") } : {}) };
|
|
36
|
+
if (source.legacyRenderer) {
|
|
37
|
+
loaded.set(key, { kind: definition.kind, container: {} });
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (!exists) {
|
|
41
|
+
expectations[key] = { missing: true, path: target, ...(source.version ? { version: source.version } : {}) };
|
|
42
|
+
// A role override that does not exist yet still has an effective definition: the
|
|
43
|
+
// built-in one. The page shows that value, and a change creates the override.
|
|
44
|
+
const builtin = definition.builtin?.(context);
|
|
45
|
+
if (definition.kind === "frontmatter" && builtin && fs.existsSync(builtin)) {
|
|
46
|
+
files[key].effectiveFrom = builtin;
|
|
47
|
+
loaded.set(key, { kind: "frontmatter", container: parseFrontmatter(fs.readFileSync(builtin, "utf8")) });
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
loaded.set(key, { kind: definition.kind, container: definition.kind === "text" ? "" : {} });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const stat = fs.statSync(target);
|
|
54
|
+
expectations[key] = { mtimeMs: stat.mtimeMs, size: stat.size, path: target, ...(source.version ? { version: source.version } : {}) };
|
|
55
|
+
try {
|
|
56
|
+
loaded.set(key, { kind: definition.kind, container: loadFile(target, definition) });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
files[key].writable = false;
|
|
59
|
+
problems.push({ file: key, sample: definition.sample, reason: "配置文件无法解析;修正后再保存。" });
|
|
60
|
+
loaded.set(key, { kind: definition.kind, container: definition.kind === "text" ? "" : {} });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const values = {};
|
|
65
|
+
const present = {};
|
|
66
|
+
const defaults = {};
|
|
67
|
+
const fieldMeta = {};
|
|
68
|
+
// mcpServers enters `values` as plain booleans (the page owns only the enable flag),
|
|
69
|
+
// but the panel still needs each server's transport and target — and those must come
|
|
70
|
+
// from the raw document, not from the toggle map.
|
|
71
|
+
const raw = {};
|
|
72
|
+
for (const field of FIELDS) {
|
|
73
|
+
const source = loaded.get(field.file);
|
|
74
|
+
if (field.kind === "secret") {
|
|
75
|
+
values[field.id] = "";
|
|
76
|
+
present[field.id] = Boolean(readField(source.container, field));
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (field.kind === "credentials") {
|
|
80
|
+
values[field.id] = {};
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (source.kind === "text") {
|
|
84
|
+
values[field.id] = source.container;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const rawValue = pageValue(readField(source.container, field));
|
|
88
|
+
const value = ["webProxy"].includes(field.id) && rawValue ? safeUrl(rawValue) : rawValue;
|
|
89
|
+
if (value === undefined) {
|
|
90
|
+
const fallback = field.id === "mcpScript" && files.mcp.version === "5.4.0" ? false : field.default ?? EXISTING_DEFAULTS[field.id];
|
|
91
|
+
if (fallback !== undefined && files[field.file].verified !== false) defaults[field.id] = fallback;
|
|
92
|
+
}
|
|
93
|
+
fieldMeta[field.id] = { from: value === undefined ? "插件默认 / 未设置" : "用户配置" };
|
|
94
|
+
// models.json may hold a literal apiKey. The page only needs endpoints and model
|
|
95
|
+
// lists, and anything it receives ends up in an HTTP response and in the offline
|
|
96
|
+
// page on disk, so provider entries are handed over without their credentials.
|
|
97
|
+
// mcp-adapter.json is the same story: env and headers can carry tokens, and the
|
|
98
|
+
// page owns nothing there but the enable flag.
|
|
99
|
+
if (field.kind === "mcp-servers") raw[field.id] = value;
|
|
100
|
+
values[field.id] = field.kind === "providers" ? withoutCredentials(value)
|
|
101
|
+
: field.kind === "mcp-servers" ? serverToggles(value)
|
|
102
|
+
: value === undefined ? null : value;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return { values, defaults, fieldMeta, present, expectations, problems, files, credentials: credentialProviders(files, loaded), mcpDetail: serverDetails(raw.mcpServers) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// The page shows each server's transport and target but never receives env or headers:
|
|
109
|
+
// those are where MCP tokens live.
|
|
110
|
+
function serverToggles(servers) {
|
|
111
|
+
if (!servers || typeof servers !== "object") return {};
|
|
112
|
+
return Object.fromEntries(Object.entries(servers).map(([id, server]) => [id, server?.disabled !== true]));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function serverDetails(servers) {
|
|
116
|
+
if (!servers || typeof servers !== "object") return {};
|
|
117
|
+
return Object.fromEntries(Object.entries(servers).map(([id, server]) => [id, {
|
|
118
|
+
transport: typeof server?.transport === "string" ? server.transport : (server?.url ? "streamable-http" : "stdio"),
|
|
119
|
+
url: typeof server?.url === "string" ? safeUrl(server.url) : "",
|
|
120
|
+
// A url the page shows in full is one it can also write back; a masked one cannot be
|
|
121
|
+
// edited without destroying the credentials or query it hides.
|
|
122
|
+
urlEditable: typeof server?.url === "string" && safeUrl(server.url) === server.url,
|
|
123
|
+
command: typeof server?.command === "string" ? "已配置本地命令(参数已隐藏)" : "",
|
|
124
|
+
hasEnv: Boolean(server?.env && typeof server.env === "object" && Object.keys(server.env).length),
|
|
125
|
+
hasHeaders: Boolean(server?.headers && typeof server.headers === "object" && Object.keys(server.headers).length),
|
|
126
|
+
}]));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Which providers have a stored credential — names only, never a value. The provider page
|
|
130
|
+
// needs this to say whether leaving its key box empty keeps a key.
|
|
131
|
+
function credentialProviders(files, loaded) {
|
|
132
|
+
const entry = files.auth;
|
|
133
|
+
if (!entry?.exists) return [];
|
|
134
|
+
const parsed = loaded.get("auth");
|
|
135
|
+
try {
|
|
136
|
+
const source = parsed?.container && typeof parsed.container === "object" ? parsed.container : readCredentials(entry.path);
|
|
137
|
+
return Object.keys(source);
|
|
138
|
+
} catch {
|
|
139
|
+
return [];
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Provider-level credentials (and per-model apiKey overrides) stay on disk: the writer
|
|
144
|
+
// merges the page's fields into the existing entry, so it never needs to see them.
|
|
145
|
+
function withoutCredentials(providers) {
|
|
146
|
+
if (!providers || typeof providers !== "object") return providers;
|
|
147
|
+
const clean = {};
|
|
148
|
+
for (const [id, provider] of Object.entries(providers)) {
|
|
149
|
+
if (!provider || typeof provider !== "object") {
|
|
150
|
+
clean[id] = provider;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
clean[id] = { baseUrl: safeUrl(provider.baseUrl), api: provider.api,
|
|
154
|
+
models: Array.isArray(provider.models) ? provider.models.map(model => ({ id: model.id, ...(model.contextWindow !== undefined ? { contextWindow: model.contextWindow } : {}), ...(model.maxTokens !== undefined ? { maxTokens: model.maxTokens } : {}) })) : [] };
|
|
155
|
+
}
|
|
156
|
+
return clean;
|
|
157
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// `settings.theme` is a name Pi resolves through its own theme resolution: the generated
|
|
2
|
+
// `system` theme, the `dark` / `light` built-ins, and every custom or package theme.
|
|
3
|
+
// Pi hands that exact list to extensions (`ui.getAllThemes()`), so the page prefers it
|
|
4
|
+
// and only falls back to reading the directories when it is unavailable — otherwise
|
|
5
|
+
// the picker could offer a name Pi cannot load, or hide one it can.
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
|
|
9
|
+
// The names Pi provides without a readable theme file of our own.
|
|
10
|
+
export const BUILTIN_THEMES = ["system", "dark", "light"];
|
|
11
|
+
|
|
12
|
+
const isHex = (value) => typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value);
|
|
13
|
+
|
|
14
|
+
function themeDirectories(agentDir) {
|
|
15
|
+
const directories = [{ dir: path.join(agentDir, "themes"), source: "用户主题" }];
|
|
16
|
+
const packagesDir = path.join(agentDir, "npm", "node_modules");
|
|
17
|
+
let entries;
|
|
18
|
+
try { entries = fs.readdirSync(packagesDir, { withFileTypes: true }); } catch { return directories; }
|
|
19
|
+
for (const entry of entries) {
|
|
20
|
+
if (!entry.isDirectory()) continue;
|
|
21
|
+
const names = entry.name.startsWith("@")
|
|
22
|
+
? scopedPackages(packagesDir, entry.name)
|
|
23
|
+
: [entry.name];
|
|
24
|
+
for (const name of names) {
|
|
25
|
+
const dir = path.join(packagesDir, name, "themes");
|
|
26
|
+
if (fs.existsSync(dir)) directories.push({ dir, source: name });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return directories;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function scopedPackages(packagesDir, scope) {
|
|
33
|
+
try {
|
|
34
|
+
return fs.readdirSync(path.join(packagesDir, scope), { withFileTypes: true })
|
|
35
|
+
.filter((entry) => entry.isDirectory())
|
|
36
|
+
.map((entry) => `${scope}/${entry.name}`);
|
|
37
|
+
} catch { return []; }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A theme names colors through `vars` and maps roles onto those names in `colors`;
|
|
41
|
+
// `text` is often empty, meaning "the terminal's default foreground".
|
|
42
|
+
function ref(theme, value) {
|
|
43
|
+
if (isHex(value)) return value;
|
|
44
|
+
return isHex(theme.vars?.[value]) ? theme.vars[value] : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function previewColors(theme) {
|
|
48
|
+
const role = (name) => ref(theme, theme.colors?.[name]);
|
|
49
|
+
const base = ref(theme, theme.vars?.bg) ?? ref(theme, theme.export?.pageBg) ?? role("userMessageBg");
|
|
50
|
+
const ink = role("text") ?? ref(theme, theme.vars?.fg) ?? ref(theme, theme.vars?.ink) ?? ref(theme, theme.vars?.foreground);
|
|
51
|
+
// The preview is decoration on a page whose own background is fixed: a theme that
|
|
52
|
+
// cannot answer for its background or accent gets the neutral swatch instead of a
|
|
53
|
+
// half-rendered card that looks like a rendering bug.
|
|
54
|
+
if (!base || !ink) return null;
|
|
55
|
+
return { bg: base, fg: ink, accent: role("accent"), success: role("success"), error: role("error") };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function colorsFromFile(file) {
|
|
59
|
+
if (!file) return null;
|
|
60
|
+
try { return previewColors(JSON.parse(fs.readFileSync(file, "utf8"))); } catch { return null; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function scannedThemes(agentDir) {
|
|
64
|
+
const themes = BUILTIN_THEMES.map((name) => ({ name, source: "Pi 内置", colors: null }));
|
|
65
|
+
const seen = new Set(BUILTIN_THEMES);
|
|
66
|
+
for (const { dir, source } of themeDirectories(agentDir)) {
|
|
67
|
+
let files;
|
|
68
|
+
try { files = fs.readdirSync(dir).filter((file) => file.endsWith(".json")).sort(); } catch { continue; }
|
|
69
|
+
for (const file of files) {
|
|
70
|
+
let theme;
|
|
71
|
+
try { theme = JSON.parse(fs.readFileSync(path.join(dir, file), "utf8")); } catch { continue; }
|
|
72
|
+
const name = typeof theme.name === "string" && theme.name.trim() ? theme.name.trim() : file.slice(0, -".json".length);
|
|
73
|
+
if (seen.has(name)) continue;
|
|
74
|
+
seen.add(name);
|
|
75
|
+
themes.push({ name, source, colors: previewColors(theme) });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return themes;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// `knownThemes` is Pi's own answer (`ui.getAllThemes()`): name plus the file it loads,
|
|
82
|
+
// or undefined for a generated theme. Without it, the directories are read directly.
|
|
83
|
+
export function discoverThemes(context) {
|
|
84
|
+
const known = context.knownThemes;
|
|
85
|
+
if (!Array.isArray(known) || known.length === 0) return scannedThemes(context.agentDir);
|
|
86
|
+
return known.map((theme) => ({
|
|
87
|
+
name: theme.name,
|
|
88
|
+
source: sourceFor(theme.path, context.agentDir),
|
|
89
|
+
colors: colorsFromFile(theme.path),
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function sourceFor(file, agentDir) {
|
|
94
|
+
if (!file) return "Pi 内置";
|
|
95
|
+
const marker = `${path.sep}npm${path.sep}node_modules${path.sep}`;
|
|
96
|
+
const index = file.indexOf(marker);
|
|
97
|
+
if (index >= 0) {
|
|
98
|
+
const parts = file.slice(index + marker.length).split(path.sep);
|
|
99
|
+
return parts[0].startsWith("@") ? `${parts[0]}/${parts[1]}` : parts[0];
|
|
100
|
+
}
|
|
101
|
+
return path.dirname(file) === path.join(agentDir, "themes") ? "用户主题" : "Pi 内置";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function themeNames(context) {
|
|
105
|
+
return discoverThemes(context).map((theme) => theme.name);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// A live switch must follow the file, not the submitted value: a conflicted or skipped
|
|
109
|
+
// settings.json write leaves Pi reading the old theme, so switching anyway would make
|
|
110
|
+
// the running session disagree with the file until the next start.
|
|
111
|
+
export function themeWritten(results) {
|
|
112
|
+
return (results ?? []).some((result) => result.key === "piSettings" && result.status === "written");
|
|
113
|
+
}
|