vanspod 0.4.11 → 0.4.15
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 +4 -4
- package/dist/classroomApp.js +79 -0
- package/dist/commandRunner.js +1 -0
- package/dist/deviceConnection.js +166 -0
- package/dist/lineChanges.js +75 -0
- package/dist/localCommands.js +221 -0
- package/dist/localToolApproval.js +104 -0
- package/dist/localTools.js +209 -0
- package/dist/modelStatus.js +42 -1
- package/dist/page.js +126 -2
- package/dist/projectPath.js +86 -0
- package/dist/saveImage.js +111 -0
- package/dist/settingsActions.js +1 -1
- package/dist/start.js +55 -1
- package/dist/trayChannel.js +103 -0
- package/dist/version.js +1 -1
- package/dist/vsCodeDefaultModel.js +197 -0
- package/dist/vsCodeRouteSettings.js +55 -12
- package/dist/windowsEnvironmentSystem.js +1 -0
- package/package.json +1 -1
- package/scripts/tray.ps1 +268 -4
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.saveImage = saveImage;
|
|
7
|
+
// `save_image`: saves a generated image under `images/` in the Project Folder (ADR 0013).
|
|
8
|
+
// The Device-side contract is "save_image" in vans-mcp-server docs/device-relay-protocol.md.
|
|
9
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
10
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
11
|
+
const localToolApproval_1 = require("./localToolApproval");
|
|
12
|
+
const projectPath_1 = require("./projectPath");
|
|
13
|
+
const IMAGE_FOLDER = "images";
|
|
14
|
+
const NOT_SAVED = "沒有儲存圖片";
|
|
15
|
+
const EXTENSIONS = {
|
|
16
|
+
"image/png": [".png"],
|
|
17
|
+
"image/jpeg": [".jpg", ".jpeg"],
|
|
18
|
+
"image/webp": [".webp"],
|
|
19
|
+
"image/gif": [".gif"],
|
|
20
|
+
};
|
|
21
|
+
const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
22
|
+
// Characters that Windows does not allow in a file name, and control characters.
|
|
23
|
+
const BAD_NAME_CHARS = /[<>:"|?*\u0000-\u001f]/g;
|
|
24
|
+
function invalid(message) {
|
|
25
|
+
return { ok: false, error: "invalid_arguments", message };
|
|
26
|
+
}
|
|
27
|
+
/** Only the base name, safe for Windows, with an extension that matches `mimeType`. */
|
|
28
|
+
function imageFileName(suggested, mimeType) {
|
|
29
|
+
const extensions = EXTENSIONS[mimeType];
|
|
30
|
+
const base = typeof suggested === "string" ? suggested.split(/[\\/]/).pop() : "";
|
|
31
|
+
let name = base.replace(BAD_NAME_CHARS, "").replace(/^[.\s]+|[.\s]+$/g, "");
|
|
32
|
+
if (!name)
|
|
33
|
+
name = "image";
|
|
34
|
+
if (!extensions.includes(node_path_1.default.extname(name).toLowerCase()))
|
|
35
|
+
name += extensions[0];
|
|
36
|
+
return name;
|
|
37
|
+
}
|
|
38
|
+
/** Width x height from the image header, or undefined when the header is not known. */
|
|
39
|
+
function dimensions(bytes, mimeType) {
|
|
40
|
+
if (mimeType === "image/png" && bytes.length >= 24)
|
|
41
|
+
return [bytes.readUInt32BE(16), bytes.readUInt32BE(20)];
|
|
42
|
+
if (mimeType === "image/gif" && bytes.length >= 10)
|
|
43
|
+
return [bytes.readUInt16LE(6), bytes.readUInt16LE(8)];
|
|
44
|
+
if (mimeType === "image/jpeg") {
|
|
45
|
+
// Walk the segments to the first start-of-frame marker (SOF0-SOF15, without DHT, JPG, DAC).
|
|
46
|
+
let at = 2;
|
|
47
|
+
while (at + 9 <= bytes.length && bytes[at] === 0xff) {
|
|
48
|
+
const marker = bytes[at + 1];
|
|
49
|
+
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
|
|
50
|
+
return [bytes.readUInt16BE(at + 7), bytes.readUInt16BE(at + 5)];
|
|
51
|
+
}
|
|
52
|
+
at += 2 + bytes.readUInt16BE(at + 2);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
function approvalBody(bytes, mimeType) {
|
|
58
|
+
const size = dimensions(bytes, mimeType);
|
|
59
|
+
const lines = [`類型:${mimeType}`, `大小:${bytes.length.toLocaleString("en-US")} 位元組`];
|
|
60
|
+
if (size)
|
|
61
|
+
lines.splice(1, 0, `尺寸:${size[0]} × ${size[1]} 像素`);
|
|
62
|
+
return lines.join("\n");
|
|
63
|
+
}
|
|
64
|
+
/** The name in `images/` with "-2", "-3", ... before the extension when the name is taken. */
|
|
65
|
+
function candidate(name, count) {
|
|
66
|
+
if (count === 1)
|
|
67
|
+
return name;
|
|
68
|
+
const extension = node_path_1.default.extname(name);
|
|
69
|
+
return `${name.slice(0, name.length - extension.length)}-${count}${extension}`;
|
|
70
|
+
}
|
|
71
|
+
async function saveImage(projectFolder, args, signal, context) {
|
|
72
|
+
const mimeType = args.mime_type;
|
|
73
|
+
if (typeof mimeType !== "string" || !Object.hasOwn(EXTENSIONS, mimeType)) {
|
|
74
|
+
return invalid("mime_type 必須是 image/png、image/jpeg、image/webp 或 image/gif。");
|
|
75
|
+
}
|
|
76
|
+
const data = typeof args.data === "string" ? args.data.replace(/\s/g, "") : "";
|
|
77
|
+
if (!data || data.length % 4 === 1 || !BASE64.test(data))
|
|
78
|
+
return invalid("data 必須是圖片內容的 base64 文字。");
|
|
79
|
+
const bytes = Buffer.from(data, "base64");
|
|
80
|
+
if (bytes.length === 0)
|
|
81
|
+
return invalid("data 必須是圖片內容的 base64 文字。");
|
|
82
|
+
const name = imageFileName(args.file_name, mimeType);
|
|
83
|
+
const refusal = await (0, localToolApproval_1.askApproval)(context.approver, {
|
|
84
|
+
tool: "save_image",
|
|
85
|
+
title: `儲存圖片 ${IMAGE_FOLDER}/${name}`,
|
|
86
|
+
body: approvalBody(bytes, mimeType),
|
|
87
|
+
folder: projectFolder,
|
|
88
|
+
}, signal, NOT_SAVED);
|
|
89
|
+
if (refusal)
|
|
90
|
+
return refusal;
|
|
91
|
+
for (let count = 1; count <= 1000; count++) {
|
|
92
|
+
// Resolve each time: `images` may be a link out of the Project Folder, or may change while the student decided.
|
|
93
|
+
const target = await (0, projectPath_1.resolveProjectPath)(projectFolder, `${IMAGE_FOLDER}/${candidate(name, count)}`, { allowMissing: true });
|
|
94
|
+
if (!target.ok)
|
|
95
|
+
return target;
|
|
96
|
+
if (target.exists)
|
|
97
|
+
continue;
|
|
98
|
+
try {
|
|
99
|
+
await promises_1.default.mkdir(node_path_1.default.dirname(target.absolute), { recursive: true });
|
|
100
|
+
// "wx" fails when the file exists, so a file made in the meantime is never overwritten.
|
|
101
|
+
await promises_1.default.writeFile(target.absolute, bytes, { flag: "wx" });
|
|
102
|
+
return { ok: true, result: { path: target.relative } };
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error.code === "EEXIST")
|
|
106
|
+
continue;
|
|
107
|
+
return { ok: false, error: "failed", message: `無法儲存「${target.relative}」:${error instanceof Error ? error.message : "原因不明"}。` };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { ok: false, error: "failed", message: `${IMAGE_FOLDER}/ 裡同名的圖片太多,${NOT_SAVED}。` };
|
|
111
|
+
}
|
package/dist/settingsActions.js
CHANGED
|
@@ -5,7 +5,7 @@ exports.settingsActionsScript = `
|
|
|
5
5
|
var settingsBusy = false;
|
|
6
6
|
document.addEventListener("submit", async function (event) {
|
|
7
7
|
var form = event.target;
|
|
8
|
-
if (!form?.matches?.('form[action="/redeem"], form[action="/copy"], form[action="/clear"], form[action="/project-folder"], form[action="/pick-folder"], form[action="/switch"], form[action="/adapter"], form[action="/reload"], form[action="/environment-check"], form[action="/environment"]')) return;
|
|
8
|
+
if (!form?.matches?.('form[action="/redeem"], form[action="/copy"], form[action="/clear"], form[action="/local-tools"], form[action="/local-tool-approval"], form[action="/local-command-stop"], form[action="/project-folder"], form[action="/pick-folder"], form[action="/switch"], form[action="/adapter"], form[action="/reload"], form[action="/environment-check"], form[action="/environment"]')) return;
|
|
9
9
|
event.preventDefault();
|
|
10
10
|
if (settingsBusy || installBusy || installOpening || document.querySelector(".confirm-dialog")) return;
|
|
11
11
|
settingsBusy = true;
|
package/dist/start.js
CHANGED
|
@@ -7,6 +7,11 @@ exports.main = main;
|
|
|
7
7
|
const platformStorage_1 = require("./platformStorage");
|
|
8
8
|
const clientDetection_1 = require("./clientDetection");
|
|
9
9
|
const runtimeOptions_1 = require("./runtimeOptions");
|
|
10
|
+
const deviceConnection_1 = require("./deviceConnection");
|
|
11
|
+
const localTools_1 = require("./localTools");
|
|
12
|
+
const localToolApproval_1 = require("./localToolApproval");
|
|
13
|
+
const localCommands_1 = require("./localCommands");
|
|
14
|
+
const trayChannel_1 = require("./trayChannel");
|
|
10
15
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
11
16
|
const node_child_process_1 = require("node:child_process");
|
|
12
17
|
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
@@ -244,6 +249,7 @@ async function openTray(url) {
|
|
|
244
249
|
await promises_1.default.mkdir(directory, { recursive: true });
|
|
245
250
|
const script = await (0, desktop_1.materializeAsset)(directory, "tray.ps1");
|
|
246
251
|
const icon = await (0, desktop_1.materializeAsset)(directory, "brand-icon.ico");
|
|
252
|
+
const mascot = await (0, desktop_1.materializeAsset)(directory, "fadou-superhero.png");
|
|
247
253
|
return (0, node_child_process_1.spawn)("powershell.exe", [
|
|
248
254
|
"-STA",
|
|
249
255
|
"-NoProfile",
|
|
@@ -254,7 +260,10 @@ async function openTray(url) {
|
|
|
254
260
|
"-Url", url,
|
|
255
261
|
"-IconPath", icon,
|
|
256
262
|
"-StateFile", node_path_1.default.join((0, instance_1.managementDirectory)(), "runtime", "instance.json"),
|
|
257
|
-
|
|
263
|
+
"-MascotPath", mascot,
|
|
264
|
+
],
|
|
265
|
+
// stdin and stdout are the tray channel (src/trayChannel.ts).
|
|
266
|
+
{ stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
258
267
|
}
|
|
259
268
|
let proxyAccepting = false;
|
|
260
269
|
function createProxy() {
|
|
@@ -400,6 +409,12 @@ async function main(instance) {
|
|
|
400
409
|
},
|
|
401
410
|
handle: (accepted, req, res) => dispatch(accepted, req, res),
|
|
402
411
|
});
|
|
412
|
+
// One Local Tool Approval queue for this Device. The page and the Approval Popup (tray) decide here.
|
|
413
|
+
const approvals = (0, localToolApproval_1.createApprovalQueue)();
|
|
414
|
+
// The bash commands of this VansPod run. Only memory: a restart starts an empty list.
|
|
415
|
+
const localCommands = (0, localCommands_1.createCommandLog)();
|
|
416
|
+
let trayChannel;
|
|
417
|
+
approvals.subscribe(() => trayChannel?.update());
|
|
403
418
|
app = new classroomApp_1.ClassroomApp({
|
|
404
419
|
detectClient: clientDetection_1.detectClient,
|
|
405
420
|
adapterSettings: (0, adapterSettings_1.createAdapterSettingsStorage)(settingsFile),
|
|
@@ -409,6 +424,7 @@ async function main(instance) {
|
|
|
409
424
|
settingsFile: copilotModelsFile(),
|
|
410
425
|
journalFile: node_path_1.default.join(node_os_1.default.homedir(), ".vanspod", "vscode-route-journal.json"),
|
|
411
426
|
legacyOrigins: [pageUrl.replace(/\/$/, ""), "http://127.0.0.1:47821"],
|
|
427
|
+
userSettingsFile: routePaths().vsCode,
|
|
412
428
|
}),
|
|
413
429
|
router: { redeemNickname, fetchSessionModels },
|
|
414
430
|
catalog: { fetchCourseCatalog },
|
|
@@ -435,6 +451,14 @@ async function main(instance) {
|
|
|
435
451
|
},
|
|
436
452
|
proxy: createProxy(),
|
|
437
453
|
send: sendUpstream,
|
|
454
|
+
device: (0, deviceConnection_1.createDeviceConnection)({
|
|
455
|
+
url: process.env.CLASSROOM_DEVICE_RELAY_URL ?? "wss://mcp.vanscoding.com/device",
|
|
456
|
+
device: node_os_1.default.hostname(),
|
|
457
|
+
handle: (0, localTools_1.createLocalTools)({ projectFolder: () => app.view().projectFolder, system: localTools_1.localSystem, approver: approvals, commands: localCommands }),
|
|
458
|
+
onChange: () => trayChannel?.update(),
|
|
459
|
+
}),
|
|
460
|
+
approvals,
|
|
461
|
+
localCommands,
|
|
438
462
|
});
|
|
439
463
|
dispatch = async (accepted, req, res) => {
|
|
440
464
|
if (!/^(127\.0\.0\.1|localhost):\d+$/.test(req.headers.host ?? "")) {
|
|
@@ -537,6 +561,12 @@ async function main(instance) {
|
|
|
537
561
|
res.end(JSON.stringify((0, page_1.environmentStatus)(app.view())));
|
|
538
562
|
return;
|
|
539
563
|
}
|
|
564
|
+
if (req.method === "GET" && pathname === "/local-tool-approval-body") {
|
|
565
|
+
const answer = (0, page_1.localToolApprovalBodyResponse)(app, parsed.searchParams.get("id") ?? "");
|
|
566
|
+
res.writeHead(answer.status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
567
|
+
res.end(JSON.stringify(answer.body));
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
540
570
|
if (req.method === "GET" && pathname === "/model-status") {
|
|
541
571
|
res.writeHead(200, {
|
|
542
572
|
"Content-Type": "application/json; charset=utf-8",
|
|
@@ -702,6 +732,26 @@ async function main(instance) {
|
|
|
702
732
|
res.end(JSON.stringify({ ok }));
|
|
703
733
|
return;
|
|
704
734
|
}
|
|
735
|
+
if (req.method === "POST" && pathname === "/local-tools") {
|
|
736
|
+
const params = new URLSearchParams(await readBody(req));
|
|
737
|
+
await app.setLocalToolAccess(params.get("on") === "1");
|
|
738
|
+
goHome();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
if (req.method === "POST" && pathname === "/local-tool-approval") {
|
|
742
|
+
const params = new URLSearchParams(await readBody(req));
|
|
743
|
+
const decision = params.get("decision");
|
|
744
|
+
if (decision === "approve" || decision === "deny")
|
|
745
|
+
app.decideLocalToolApproval(params.get("id") ?? "", decision);
|
|
746
|
+
goHome();
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (req.method === "POST" && pathname === "/local-command-stop") {
|
|
750
|
+
const params = new URLSearchParams(await readBody(req));
|
|
751
|
+
app.stopLocalCommand(params.get("id") ?? "");
|
|
752
|
+
goHome();
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
705
755
|
if (req.method === "POST" && pathname === "/clear") {
|
|
706
756
|
const params = new URLSearchParams(await readBody(req));
|
|
707
757
|
await app.clearConnection();
|
|
@@ -866,6 +916,10 @@ async function main(instance) {
|
|
|
866
916
|
process.stderr.write(`系統匣圖示無法顯示:${trayError}\n`);
|
|
867
917
|
return undefined;
|
|
868
918
|
});
|
|
919
|
+
if (tray?.stdin && tray.stdout) {
|
|
920
|
+
const channel = trayChannel = (0, trayChannel_1.createTrayChannel)({ input: tray.stdout, output: tray.stdin, app });
|
|
921
|
+
tray.once("exit", () => channel.close());
|
|
922
|
+
}
|
|
869
923
|
}
|
|
870
924
|
if (runtimeOptions.desktop && !process.env.VANSPOD_WORKER_TOKEN)
|
|
871
925
|
(0, desktop_1.openBrowser)(home);
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TRAY_BODY_CHARS = void 0;
|
|
4
|
+
exports.createTrayChannel = createTrayChannel;
|
|
5
|
+
/** The popup shows this much of the body. On the page, 「顯示全部」 shows all of it. */
|
|
6
|
+
exports.TRAY_BODY_CHARS = 2_000;
|
|
7
|
+
function trayText(value, max) {
|
|
8
|
+
return value.length <= max ? value : `${value.slice(0, max)}\n…(內容太長,完整內容請看 VansPod 頁面)`;
|
|
9
|
+
}
|
|
10
|
+
/** JSON with every character outside printable ASCII escaped. */
|
|
11
|
+
function asciiJson(value) {
|
|
12
|
+
return JSON.stringify(value).replace(/[^\x20-\x7e]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
13
|
+
}
|
|
14
|
+
function createTrayChannel(options) {
|
|
15
|
+
const { input, output, app } = options;
|
|
16
|
+
let closed = false;
|
|
17
|
+
let lastState;
|
|
18
|
+
let buffer = "";
|
|
19
|
+
const send = (message) => {
|
|
20
|
+
if (closed || output.destroyed || output.writableEnded)
|
|
21
|
+
return;
|
|
22
|
+
try {
|
|
23
|
+
output.write(`${asciiJson(message)}\n`);
|
|
24
|
+
}
|
|
25
|
+
catch { /* the tray has gone */ }
|
|
26
|
+
};
|
|
27
|
+
const state = () => {
|
|
28
|
+
const local = app.view().localTools;
|
|
29
|
+
const shown = local?.approval;
|
|
30
|
+
return {
|
|
31
|
+
type: "state",
|
|
32
|
+
access: local?.on ?? false,
|
|
33
|
+
approval: shown ? {
|
|
34
|
+
id: shown.id,
|
|
35
|
+
tool: shown.tool,
|
|
36
|
+
title: trayText(shown.title, 200),
|
|
37
|
+
body: trayText(shown.body, exports.TRAY_BODY_CHARS),
|
|
38
|
+
folder: shown.folder,
|
|
39
|
+
device: shown.device,
|
|
40
|
+
secondsLeft: shown.secondsLeft,
|
|
41
|
+
waiting: shown.waiting,
|
|
42
|
+
} : null,
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
const update = () => {
|
|
46
|
+
if (closed)
|
|
47
|
+
return;
|
|
48
|
+
const current = state();
|
|
49
|
+
// secondsLeft alone does not make a new state: the tray counts down itself.
|
|
50
|
+
const key = JSON.stringify({ ...current, approval: current.approval && { ...current.approval, secondsLeft: 0 } });
|
|
51
|
+
if (key === lastState)
|
|
52
|
+
return;
|
|
53
|
+
lastState = key;
|
|
54
|
+
send(current);
|
|
55
|
+
};
|
|
56
|
+
const receive = async (line) => {
|
|
57
|
+
let message;
|
|
58
|
+
try {
|
|
59
|
+
message = JSON.parse(line.replace(/^/, "").trim());
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (!message || typeof message !== "object")
|
|
65
|
+
return;
|
|
66
|
+
const { type, id, decision, on } = message;
|
|
67
|
+
if (type === "decide" && typeof id === "string" && (decision === "approve" || decision === "deny")) {
|
|
68
|
+
app.decideLocalToolApproval(id, decision);
|
|
69
|
+
update();
|
|
70
|
+
}
|
|
71
|
+
else if (type === "access" && typeof on === "boolean") {
|
|
72
|
+
try {
|
|
73
|
+
await app.setLocalToolAccess(on);
|
|
74
|
+
}
|
|
75
|
+
catch { /* the state below tells the tray */ }
|
|
76
|
+
if (closed)
|
|
77
|
+
return;
|
|
78
|
+
const local = app.view().localTools;
|
|
79
|
+
if (on && !local?.on && local?.message)
|
|
80
|
+
send({ type: "refused", message: local.message });
|
|
81
|
+
update();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const onData = (chunk) => {
|
|
85
|
+
if (closed)
|
|
86
|
+
return;
|
|
87
|
+
buffer += chunk.toString();
|
|
88
|
+
const lines = buffer.split("\n");
|
|
89
|
+
buffer = lines.pop() ?? "";
|
|
90
|
+
for (const line of lines)
|
|
91
|
+
void receive(line);
|
|
92
|
+
};
|
|
93
|
+
input.on("data", onData);
|
|
94
|
+
output.on("error", () => { });
|
|
95
|
+
update();
|
|
96
|
+
return {
|
|
97
|
+
update,
|
|
98
|
+
close() {
|
|
99
|
+
closed = true;
|
|
100
|
+
input.off("data", onData);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.planClassroomDefaultModel = planClassroomDefaultModel;
|
|
7
|
+
exports.applyClassroomDefaultModel = applyClassroomDefaultModel;
|
|
8
|
+
exports.restoreClassroomDefaultModel = restoreClassroomDefaultModel;
|
|
9
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
10
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
11
|
+
// Classroom Default Model: same rules as the classroom-one-click-install extension
|
|
12
|
+
// (its ADR 0018). While Classroom, VS Code's user `chat.defaultModel` points at the
|
|
13
|
+
// first VCRouter model so new Chat conversations use it; Native puts back the
|
|
14
|
+
// student's own value, but only if the setting still holds the one VansPod wrote.
|
|
15
|
+
const CHAT_DEFAULT_MODEL = "chat.defaultModel";
|
|
16
|
+
// Comment- and string-aware tokens of a JSONC document. `depth` is the nesting level
|
|
17
|
+
// the token sits at (the root object's own braces are depth 0, its members depth 1).
|
|
18
|
+
function tokenize(text) {
|
|
19
|
+
const tokens = [];
|
|
20
|
+
let depth = 0;
|
|
21
|
+
let i = 0;
|
|
22
|
+
while (i < text.length) {
|
|
23
|
+
const c = text[i];
|
|
24
|
+
if (/\s|/.test(c)) {
|
|
25
|
+
i += 1;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (c === "/" && text[i + 1] === "/") {
|
|
29
|
+
while (i < text.length && text[i] !== "\n")
|
|
30
|
+
i += 1;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (c === "/" && text[i + 1] === "*") {
|
|
34
|
+
const close = text.indexOf("*/", i + 2);
|
|
35
|
+
i = close < 0 ? text.length : close + 2;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (c === '"') {
|
|
39
|
+
let j = i + 1;
|
|
40
|
+
while (j < text.length && text[j] !== '"')
|
|
41
|
+
j += text[j] === "\\" ? 2 : 1;
|
|
42
|
+
tokens.push({ kind: "string", start: i, end: Math.min(j + 1, text.length), depth });
|
|
43
|
+
i = j + 1;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if ("{[".includes(c)) {
|
|
47
|
+
tokens.push({ kind: "punct", char: c, start: i, end: i + 1, depth });
|
|
48
|
+
depth += 1;
|
|
49
|
+
i += 1;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if ("}]".includes(c)) {
|
|
53
|
+
depth -= 1;
|
|
54
|
+
tokens.push({ kind: "punct", char: c, start: i, end: i + 1, depth });
|
|
55
|
+
i += 1;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (":,".includes(c)) {
|
|
59
|
+
tokens.push({ kind: "punct", char: c, start: i, end: i + 1, depth });
|
|
60
|
+
i += 1;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
let j = i;
|
|
64
|
+
while (j < text.length && !/[\s{}[\]:,"/]/.test(text[j]))
|
|
65
|
+
j += 1;
|
|
66
|
+
tokens.push({ kind: "literal", start: i, end: Math.max(j, i + 1), depth });
|
|
67
|
+
i = Math.max(j, i + 1);
|
|
68
|
+
}
|
|
69
|
+
return tokens;
|
|
70
|
+
}
|
|
71
|
+
function inspect(text) {
|
|
72
|
+
const tokens = tokenize(text);
|
|
73
|
+
if (tokens.length === 0)
|
|
74
|
+
return { tokens, members: 0 };
|
|
75
|
+
const root = tokens[0];
|
|
76
|
+
if (root.char !== "{")
|
|
77
|
+
return undefined;
|
|
78
|
+
let entry;
|
|
79
|
+
let members = 0;
|
|
80
|
+
for (let i = 1; i + 2 < tokens.length; i += 1) {
|
|
81
|
+
const key = tokens[i];
|
|
82
|
+
if (key.depth !== 1 || key.kind !== "string" || tokens[i + 1].char !== ":")
|
|
83
|
+
continue;
|
|
84
|
+
members += 1;
|
|
85
|
+
if (JSON.parse(text.slice(key.start, key.end)) !== CHAT_DEFAULT_MODEL)
|
|
86
|
+
continue;
|
|
87
|
+
const value = tokens[i + 2];
|
|
88
|
+
// VS Code uses the last duplicate key, so the last one wins here too.
|
|
89
|
+
entry = { index: i, key, value, text: value.kind === "string" ? JSON.parse(text.slice(value.start, value.end)) : undefined };
|
|
90
|
+
}
|
|
91
|
+
return { tokens, root, entry, members };
|
|
92
|
+
}
|
|
93
|
+
async function readText(file) {
|
|
94
|
+
try {
|
|
95
|
+
return await promises_1.default.readFile(file, "utf8");
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code === "ENOENT")
|
|
99
|
+
return null;
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function readDefaultModel(file) {
|
|
104
|
+
const text = await readText(file);
|
|
105
|
+
return text === null ? undefined : inspect(text)?.entry?.text;
|
|
106
|
+
}
|
|
107
|
+
function lineStart(text, index) {
|
|
108
|
+
const start = text.lastIndexOf("\n", index - 1) + 1;
|
|
109
|
+
return text.slice(start, index).trim() === "" ? start : index;
|
|
110
|
+
}
|
|
111
|
+
function lineEnd(text, index) {
|
|
112
|
+
const rest = text.slice(index).match(/^[ \t]*(\r?\n)?/)[0];
|
|
113
|
+
return rest.endsWith("\n") ? index + rest.length : index;
|
|
114
|
+
}
|
|
115
|
+
/** The edited text, or undefined when the file cannot be edited safely. */
|
|
116
|
+
function edit(text, value) {
|
|
117
|
+
const line = `"${CHAT_DEFAULT_MODEL}": ${JSON.stringify(value)}`;
|
|
118
|
+
if (text === null)
|
|
119
|
+
return value === undefined ? undefined : `{\n ${line}\n}\n`;
|
|
120
|
+
const doc = inspect(text);
|
|
121
|
+
if (!doc)
|
|
122
|
+
return undefined;
|
|
123
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
124
|
+
if (!doc.root) {
|
|
125
|
+
// Only comments or nothing: keep them and add the object after.
|
|
126
|
+
if (value === undefined)
|
|
127
|
+
return undefined;
|
|
128
|
+
const sep = text === "" || text.endsWith("\n") ? "" : eol;
|
|
129
|
+
return `${text}${sep}{${eol} ${line}${eol}}${eol}`;
|
|
130
|
+
}
|
|
131
|
+
const { entry, tokens } = doc;
|
|
132
|
+
if (entry && value !== undefined) {
|
|
133
|
+
// A non-string value we can't place safely (object, array) is left alone.
|
|
134
|
+
if (entry.value.kind === "punct")
|
|
135
|
+
return undefined;
|
|
136
|
+
return text.slice(0, entry.value.start) + JSON.stringify(value) + text.slice(entry.value.end);
|
|
137
|
+
}
|
|
138
|
+
if (entry) {
|
|
139
|
+
if (entry.value.kind === "punct")
|
|
140
|
+
return undefined;
|
|
141
|
+
const next = tokens[entry.index + 3];
|
|
142
|
+
const before = tokens[entry.index - 1];
|
|
143
|
+
if (next?.char === ",") {
|
|
144
|
+
const from = lineStart(text, entry.key.start);
|
|
145
|
+
return text.slice(0, from) + text.slice(lineEnd(text, next.end));
|
|
146
|
+
}
|
|
147
|
+
if (before.char === ",")
|
|
148
|
+
return text.slice(0, before.start) + text.slice(entry.value.end);
|
|
149
|
+
const from = lineStart(text, entry.key.start);
|
|
150
|
+
return text.slice(0, from) + text.slice(lineEnd(text, entry.value.end));
|
|
151
|
+
}
|
|
152
|
+
if (value === undefined)
|
|
153
|
+
return undefined;
|
|
154
|
+
const at = doc.root.end;
|
|
155
|
+
const rest = text.slice(at);
|
|
156
|
+
const comma = doc.members > 0 ? "," : "";
|
|
157
|
+
// Match the file's layout so removing the entry later gives back the exact bytes:
|
|
158
|
+
// its own line in a multi-line object, inline right after `{` in a compact one.
|
|
159
|
+
return /^[ \t]*\r?\n/.test(rest)
|
|
160
|
+
? `${text.slice(0, at)}${eol} ${line}${comma}${rest}`
|
|
161
|
+
: `${text.slice(0, at)}${line}${comma}${rest}`;
|
|
162
|
+
}
|
|
163
|
+
async function writeDefaultModel(file, value) {
|
|
164
|
+
const next = edit(await readText(file), value);
|
|
165
|
+
if (next === undefined)
|
|
166
|
+
return;
|
|
167
|
+
await promises_1.default.mkdir(node_path_1.default.dirname(file), { recursive: true });
|
|
168
|
+
const temporary = `${file}.vanspod.tmp`;
|
|
169
|
+
try {
|
|
170
|
+
await promises_1.default.writeFile(temporary, next, "utf8");
|
|
171
|
+
await promises_1.default.rename(temporary, file);
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
await promises_1.default.rm(temporary, { force: true });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* What the journal should hold after this publish, or undefined to write nothing.
|
|
179
|
+
* Same model as last time → leave whatever the student has now, never re-override it.
|
|
180
|
+
*/
|
|
181
|
+
async function planClassroomDefaultModel(file, modelId, record) {
|
|
182
|
+
if (record?.written === modelId)
|
|
183
|
+
return undefined;
|
|
184
|
+
const current = await readDefaultModel(file);
|
|
185
|
+
const previous = record && current === record.written ? record.previous : current;
|
|
186
|
+
return previous === undefined ? { written: modelId } : { previous, written: modelId };
|
|
187
|
+
}
|
|
188
|
+
async function applyClassroomDefaultModel(file, record) {
|
|
189
|
+
if (await readDefaultModel(file) !== record.written)
|
|
190
|
+
await writeDefaultModel(file, record.written);
|
|
191
|
+
}
|
|
192
|
+
async function restoreClassroomDefaultModel(file, record) {
|
|
193
|
+
if (!record)
|
|
194
|
+
return;
|
|
195
|
+
if (await readDefaultModel(file) === record.written)
|
|
196
|
+
await writeDefaultModel(file, record.previous);
|
|
197
|
+
}
|
|
@@ -7,6 +7,7 @@ exports.createVsCodeRouteSettings = createVsCodeRouteSettings;
|
|
|
7
7
|
const node_util_1 = require("node:util");
|
|
8
8
|
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
9
9
|
const node_path_1 = __importDefault(require("node:path"));
|
|
10
|
+
const vsCodeDefaultModel_1 = require("./vsCodeDefaultModel");
|
|
10
11
|
function isJournal(value) {
|
|
11
12
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
12
13
|
return false;
|
|
@@ -144,7 +145,36 @@ function intendedProvider(template, adapter, origin) {
|
|
|
144
145
|
});
|
|
145
146
|
return provider;
|
|
146
147
|
}
|
|
148
|
+
function firstModelId(provider) {
|
|
149
|
+
for (const model of provider.models ?? []) {
|
|
150
|
+
const id = model?.id;
|
|
151
|
+
if (typeof id === "string" && id)
|
|
152
|
+
return id;
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
147
156
|
function createVsCodeRouteSettings(options) {
|
|
157
|
+
// 課堂預設模型是附加功能:讀寫失敗不擋連線或切回 Native,殘留的設定在 VCRouter 消失後也無作用。
|
|
158
|
+
// undefined = 不需要寫(同一個模型已寫過,或讀不到設定);journal 裡原有的紀錄要保留。
|
|
159
|
+
const planDefault = async (intended, journal) => {
|
|
160
|
+
const modelId = firstModelId(intended);
|
|
161
|
+
if (!options.userSettingsFile || !modelId)
|
|
162
|
+
return undefined;
|
|
163
|
+
try {
|
|
164
|
+
return await (0, vsCodeDefaultModel_1.planClassroomDefaultModel)(options.userSettingsFile, modelId, journal?.defaultModel);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const writeDefault = async (record) => {
|
|
171
|
+
if (!options.userSettingsFile || !record)
|
|
172
|
+
return;
|
|
173
|
+
try {
|
|
174
|
+
await (0, vsCodeDefaultModel_1.applyClassroomDefaultModel)(options.userSettingsFile, record);
|
|
175
|
+
}
|
|
176
|
+
catch { /* best effort */ }
|
|
177
|
+
};
|
|
148
178
|
// 只移除仍指向 VansPod 代理的 VCRouter;已被移除或改成別的網址的,視為不再由 VansPod 接管。
|
|
149
179
|
const restore = async () => {
|
|
150
180
|
const journal = await readJournal(options.journalFile);
|
|
@@ -156,6 +186,12 @@ function createVsCodeRouteSettings(options) {
|
|
|
156
186
|
const changed = next.length !== current.length;
|
|
157
187
|
if (changed)
|
|
158
188
|
await atomicJson(options.settingsFile, next);
|
|
189
|
+
if (options.userSettingsFile) {
|
|
190
|
+
try {
|
|
191
|
+
await (0, vsCodeDefaultModel_1.restoreClassroomDefaultModel)(options.userSettingsFile, journal.defaultModel);
|
|
192
|
+
}
|
|
193
|
+
catch { /* best effort */ }
|
|
194
|
+
}
|
|
159
195
|
await promises_1.default.rm(options.journalFile, { force: true });
|
|
160
196
|
return namedIndexes(next).length ? { changed, kept: true } : { changed };
|
|
161
197
|
};
|
|
@@ -182,18 +218,25 @@ function createVsCodeRouteSettings(options) {
|
|
|
182
218
|
}
|
|
183
219
|
next = [...current, intended];
|
|
184
220
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
221
|
+
const planned = await planDefault(intended, journal);
|
|
222
|
+
const defaultModel = planned ?? journal?.defaultModel;
|
|
223
|
+
const changed = !(0, node_util_1.isDeepStrictEqual)(next, current);
|
|
224
|
+
if (changed || planned) {
|
|
225
|
+
const nextJournal = {
|
|
226
|
+
version: 1,
|
|
227
|
+
route: "vsCodeChat",
|
|
228
|
+
original,
|
|
229
|
+
intended,
|
|
230
|
+
owned: { name: "VCRouter", vendor: "customendpoint" },
|
|
231
|
+
...(defaultModel ? { defaultModel } : {}),
|
|
232
|
+
};
|
|
233
|
+
await atomicJson(options.journalFile, nextJournal);
|
|
234
|
+
if (changed)
|
|
235
|
+
await atomicJson(options.settingsFile, next);
|
|
236
|
+
}
|
|
237
|
+
// chat.defaultModel 不需要重啟 VS Code,所以不算進 changed。
|
|
238
|
+
await writeDefault(planned);
|
|
239
|
+
return { changed };
|
|
197
240
|
},
|
|
198
241
|
restore,
|
|
199
242
|
async initializeNative() {
|
|
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.windowsEnvironmentSystem = void 0;
|
|
7
|
+
exports.resolveCommand = resolveCommand;
|
|
7
8
|
exports.createWindowsEnvironmentSystem = createWindowsEnvironmentSystem;
|
|
8
9
|
const node_child_process_1 = require("node:child_process");
|
|
9
10
|
const promises_1 = __importDefault(require("node:fs/promises"));
|