vanspod 0.4.13 → 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 +54 -1
- package/dist/trayChannel.js +103 -0
- package/dist/version.js +1 -1
- package/dist/windowsEnvironmentSystem.js +1 -0
- package/package.json +1 -1
- package/scripts/tray.ps1 +268 -4
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.APPROVAL_TIMEOUT_MS = void 0;
|
|
4
|
+
exports.askApproval = askApproval;
|
|
5
|
+
exports.approvalRefusal = approvalRefusal;
|
|
6
|
+
exports.createApprovalQueue = createApprovalQueue;
|
|
7
|
+
/**
|
|
8
|
+
* Asks `approver` and turns anything but approval into the reply for the agent.
|
|
9
|
+
* `notDone` says what did not happen, for example "沒有寫入檔案".
|
|
10
|
+
*/
|
|
11
|
+
async function askApproval(approver, request, signal, notDone) {
|
|
12
|
+
const outcome = await approver.request(request, signal);
|
|
13
|
+
return outcome === "approved" ? undefined : approvalRefusal(outcome, notDone);
|
|
14
|
+
}
|
|
15
|
+
function approvalRefusal(outcome, notDone) {
|
|
16
|
+
if (outcome === "timeout")
|
|
17
|
+
return { ok: false, error: "approval_timeout", message: `學生在 ${exports.APPROVAL_TIMEOUT_MS / 60_000} 分鐘內沒有決定,${notDone}。` };
|
|
18
|
+
if (outcome === "access_off")
|
|
19
|
+
return { ok: false, error: "denied", message: `學生關閉了「讓 Agent Builder 使用這台電腦」,${notDone}。` };
|
|
20
|
+
if (outcome === "cancelled")
|
|
21
|
+
return { ok: false, error: "denied", message: `這個呼叫已被取消,${notDone}。` };
|
|
22
|
+
return { ok: false, error: "denied", message: `學生拒絕了,${notDone}。` };
|
|
23
|
+
}
|
|
24
|
+
/** The default time limit, from when an approval is shown (ADR 0013). */
|
|
25
|
+
exports.APPROVAL_TIMEOUT_MS = 120_000;
|
|
26
|
+
function createApprovalQueue(options = {}) {
|
|
27
|
+
const timeoutMs = options.timeoutMs ?? exports.APPROVAL_TIMEOUT_MS;
|
|
28
|
+
const entries = [];
|
|
29
|
+
const listeners = new Set();
|
|
30
|
+
let shown;
|
|
31
|
+
let timer;
|
|
32
|
+
let nextId = 0;
|
|
33
|
+
const snapshot = () => shown && { ...shown, waiting: entries.length - 1 };
|
|
34
|
+
const notify = () => {
|
|
35
|
+
const current = snapshot();
|
|
36
|
+
for (const listener of [...listeners]) {
|
|
37
|
+
try {
|
|
38
|
+
listener(current);
|
|
39
|
+
}
|
|
40
|
+
catch { /* one listener must not stop the others */ }
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
/** Shows the first entry if nothing is shown, and tells the listeners when the shown approval changed. */
|
|
44
|
+
const showNext = (changed) => {
|
|
45
|
+
if (!shown && entries.length > 0) {
|
|
46
|
+
const first = entries[0];
|
|
47
|
+
const shownAt = Date.now();
|
|
48
|
+
shown = { id: first.id, request: first.request, shownAt, expiresAt: shownAt + timeoutMs, waiting: 0 };
|
|
49
|
+
timer = setTimeout(() => end(first.id, "timeout"), timeoutMs);
|
|
50
|
+
changed = true;
|
|
51
|
+
}
|
|
52
|
+
if (changed)
|
|
53
|
+
notify();
|
|
54
|
+
};
|
|
55
|
+
/** Ends one entry, shown or waiting. False when it has already ended. */
|
|
56
|
+
const end = (id, outcome) => {
|
|
57
|
+
const index = entries.findIndex(entry => entry.id === id);
|
|
58
|
+
if (index < 0)
|
|
59
|
+
return false;
|
|
60
|
+
const [entry] = entries.splice(index, 1);
|
|
61
|
+
const wasShown = shown?.id === id;
|
|
62
|
+
if (wasShown) {
|
|
63
|
+
shown = undefined;
|
|
64
|
+
if (timer)
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
timer = undefined;
|
|
67
|
+
}
|
|
68
|
+
entry.settle(outcome);
|
|
69
|
+
showNext(wasShown);
|
|
70
|
+
return true;
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
request(request, signal) {
|
|
74
|
+
if (signal?.aborted)
|
|
75
|
+
return Promise.resolve("cancelled");
|
|
76
|
+
return new Promise(resolve => {
|
|
77
|
+
const id = `approval-${++nextId}`;
|
|
78
|
+
const onAbort = () => end(id, "cancelled");
|
|
79
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
80
|
+
entries.push({
|
|
81
|
+
id,
|
|
82
|
+
request,
|
|
83
|
+
settle(outcome) { signal?.removeEventListener("abort", onAbort); resolve(outcome); },
|
|
84
|
+
});
|
|
85
|
+
// A new waiting approval changes the count that the shown one carries.
|
|
86
|
+
showNext(shown !== undefined);
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
shown: snapshot,
|
|
90
|
+
decide(id, decision) {
|
|
91
|
+
if (shown?.id !== id)
|
|
92
|
+
return false;
|
|
93
|
+
return end(id, decision === "approve" ? "approved" : "denied");
|
|
94
|
+
},
|
|
95
|
+
denyAll() {
|
|
96
|
+
for (const entry of [...entries].reverse())
|
|
97
|
+
end(entry.id, "access_off");
|
|
98
|
+
},
|
|
99
|
+
subscribe(listener) {
|
|
100
|
+
listeners.add(listener);
|
|
101
|
+
return () => { listeners.delete(listener); };
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
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.localSystem = exports.MAX_READ_CHARS = exports.NO_PROJECT_FOLDER_NOTE = void 0;
|
|
7
|
+
exports.createLocalTools = createLocalTools;
|
|
8
|
+
exports.findGitBash = findGitBash;
|
|
9
|
+
// The Local Tools that a Device answers for Agent Builder (ADR 0013).
|
|
10
|
+
// A tool that is not built yet answers `unknown_tool`.
|
|
11
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
12
|
+
const node_os_1 = __importDefault(require("node:os"));
|
|
13
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
14
|
+
const lineChanges_1 = require("./lineChanges");
|
|
15
|
+
const localCommands_1 = require("./localCommands");
|
|
16
|
+
const localToolApproval_1 = require("./localToolApproval");
|
|
17
|
+
const projectPath_1 = require("./projectPath");
|
|
18
|
+
const saveImage_1 = require("./saveImage");
|
|
19
|
+
const systemPath_1 = require("./systemPath");
|
|
20
|
+
const windowsEnvironmentSystem_1 = require("./windowsEnvironmentSystem");
|
|
21
|
+
const MAX_ENTRIES = 200;
|
|
22
|
+
exports.NO_PROJECT_FOLDER_NOTE = "學生還沒有在 VansPod 選擇專案資料夾。請學生打開 VansPod,按「選擇專案資料夾」。";
|
|
23
|
+
async function topLevelEntries(folder) {
|
|
24
|
+
const found = await promises_1.default.readdir(folder, { withFileTypes: true });
|
|
25
|
+
const entries = found
|
|
26
|
+
.map(entry => ({ name: entry.name, type: entry.isDirectory() ? "folder" : "file" }))
|
|
27
|
+
.sort((a, b) => a.type === b.type ? a.name.localeCompare(b.name, "en", { sensitivity: "base" }) : a.type === "folder" ? -1 : 1);
|
|
28
|
+
return { entries: entries.slice(0, MAX_ENTRIES), truncated: entries.length > MAX_ENTRIES };
|
|
29
|
+
}
|
|
30
|
+
async function localStatus(options) {
|
|
31
|
+
const [bash, python] = await Promise.all([options.system.gitBash(), options.system.python()]);
|
|
32
|
+
const result = {
|
|
33
|
+
os: options.system.os(),
|
|
34
|
+
shell: bash ? { name: "Git Bash", available: true, path: bash } : { name: "Git Bash", available: false },
|
|
35
|
+
};
|
|
36
|
+
const folder = options.projectFolder();
|
|
37
|
+
if (!folder) {
|
|
38
|
+
result.project_folder = null;
|
|
39
|
+
result.project_folder_note = exports.NO_PROJECT_FOLDER_NOTE;
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
result.project_folder = folder;
|
|
43
|
+
try {
|
|
44
|
+
const { entries, truncated } = await topLevelEntries(folder);
|
|
45
|
+
result.entries = entries;
|
|
46
|
+
if (truncated)
|
|
47
|
+
result.entries_truncated = true;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
result.project_folder_note = "VansPod 讀不到這個專案資料夾,它可能已被移動或刪除。";
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
result.python = python ?? null;
|
|
54
|
+
return { ok: true, result };
|
|
55
|
+
}
|
|
56
|
+
async function listFiles(projectFolder, args) {
|
|
57
|
+
const target = await (0, projectPath_1.resolveProjectPath)(projectFolder, args.path ?? ".");
|
|
58
|
+
if (!target.ok)
|
|
59
|
+
return target;
|
|
60
|
+
if (!(await promises_1.default.stat(target.absolute)).isDirectory()) {
|
|
61
|
+
return { ok: false, error: "invalid_arguments", message: `「${target.relative}」是檔案,不是資料夾。請用 read_file 讀取它。` };
|
|
62
|
+
}
|
|
63
|
+
const { entries, truncated } = await topLevelEntries(target.absolute);
|
|
64
|
+
return { ok: true, result: truncated ? { path: target.relative, entries, truncated: true } : { path: target.relative, entries } };
|
|
65
|
+
}
|
|
66
|
+
exports.MAX_READ_CHARS = 30_000;
|
|
67
|
+
// A UTF-8 character has at most 4 bytes, so this many bytes always hold MAX_READ_CHARS characters.
|
|
68
|
+
const MAX_READ_BYTES = exports.MAX_READ_CHARS * 4;
|
|
69
|
+
async function readFile(projectFolder, args) {
|
|
70
|
+
const target = await (0, projectPath_1.resolveProjectPath)(projectFolder, args.path);
|
|
71
|
+
if (!target.ok)
|
|
72
|
+
return target;
|
|
73
|
+
if ((0, projectPath_1.isSecretFileName)(target.relative) || (0, projectPath_1.isSecretFileName)(target.absolute))
|
|
74
|
+
return (0, projectPath_1.secretFileRefusal)(target.relative);
|
|
75
|
+
const stat = await promises_1.default.stat(target.absolute);
|
|
76
|
+
if (stat.isDirectory()) {
|
|
77
|
+
return { ok: false, error: "invalid_arguments", message: `「${target.relative}」是資料夾,不是檔案。請用 list_files 看裡面有什麼。` };
|
|
78
|
+
}
|
|
79
|
+
const file = await promises_1.default.open(target.absolute, "r");
|
|
80
|
+
let bytes;
|
|
81
|
+
try {
|
|
82
|
+
const buffer = Buffer.alloc(Math.min(stat.size, MAX_READ_BYTES));
|
|
83
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
84
|
+
bytes = buffer.subarray(0, bytesRead);
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
await file.close();
|
|
88
|
+
}
|
|
89
|
+
if (bytes.includes(0)) {
|
|
90
|
+
return { ok: false, error: "failed", message: `「${target.relative}」不是文字檔,read_file 只能讀取文字檔。` };
|
|
91
|
+
}
|
|
92
|
+
const text = new TextDecoder("utf-8").decode(bytes);
|
|
93
|
+
if ((0, projectPath_1.hasPrivateKey)(text))
|
|
94
|
+
return (0, projectPath_1.secretFileRefusal)(target.relative);
|
|
95
|
+
const chars = Array.from(text);
|
|
96
|
+
const truncated = chars.length > exports.MAX_READ_CHARS || stat.size > bytes.length;
|
|
97
|
+
if (!truncated)
|
|
98
|
+
return { ok: true, result: { path: target.relative, content: text, truncated: false } };
|
|
99
|
+
return {
|
|
100
|
+
ok: true,
|
|
101
|
+
result: {
|
|
102
|
+
path: target.relative,
|
|
103
|
+
content: chars.slice(0, exports.MAX_READ_CHARS).join(""),
|
|
104
|
+
truncated: true,
|
|
105
|
+
note: `檔案太長,只回傳前 ${exports.MAX_READ_CHARS.toLocaleString("en-US")} 個字元(檔案共 ${stat.size} 位元組)。`,
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const NOT_WRITTEN = "沒有寫入檔案";
|
|
110
|
+
async function writeFile(projectFolder, args, signal, context) {
|
|
111
|
+
if (typeof args.content !== "string")
|
|
112
|
+
return { ok: false, error: "invalid_arguments", message: "content 必須是要寫入的文字。" };
|
|
113
|
+
const content = args.content;
|
|
114
|
+
const target = await (0, projectPath_1.resolveProjectPath)(projectFolder, args.path, { allowMissing: true });
|
|
115
|
+
if (!target.ok)
|
|
116
|
+
return target;
|
|
117
|
+
let title = `寫入新檔案 ${target.relative}`;
|
|
118
|
+
let body = content;
|
|
119
|
+
if (target.exists) {
|
|
120
|
+
if ((await promises_1.default.stat(target.absolute)).isDirectory()) {
|
|
121
|
+
return { ok: false, error: "invalid_arguments", message: `「${target.relative}」是資料夾,不能寫成檔案。` };
|
|
122
|
+
}
|
|
123
|
+
const old = await promises_1.default.readFile(target.absolute);
|
|
124
|
+
title = `修改檔案 ${target.relative}`;
|
|
125
|
+
body = old.includes(0)
|
|
126
|
+
? `(原本不是文字檔,整個檔案會換成下面的內容)\n${content}`
|
|
127
|
+
: (0, lineChanges_1.lineChanges)(old.toString("utf8"), content);
|
|
128
|
+
}
|
|
129
|
+
const refusal = await (0, localToolApproval_1.askApproval)(context.approver, { tool: "write_file", title, body, folder: projectFolder }, signal, NOT_WRITTEN);
|
|
130
|
+
if (refusal)
|
|
131
|
+
return refusal;
|
|
132
|
+
// Resolve again: the folder may have changed while the student decided.
|
|
133
|
+
const now = await (0, projectPath_1.resolveProjectPath)(projectFolder, args.path, { allowMissing: true });
|
|
134
|
+
if (!now.ok)
|
|
135
|
+
return now;
|
|
136
|
+
try {
|
|
137
|
+
await promises_1.default.mkdir(node_path_1.default.dirname(now.absolute), { recursive: true });
|
|
138
|
+
await promises_1.default.writeFile(now.absolute, content, "utf8");
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
return { ok: false, error: "failed", message: `無法寫入「${now.relative}」:${error instanceof Error ? error.message : "原因不明"}。` };
|
|
142
|
+
}
|
|
143
|
+
return { ok: true, result: { path: now.relative, created: !now.exists } };
|
|
144
|
+
}
|
|
145
|
+
/** Add a Project Folder tool here. */
|
|
146
|
+
const PROJECT_TOOLS = {
|
|
147
|
+
list_files: listFiles,
|
|
148
|
+
read_file: readFile,
|
|
149
|
+
write_file: writeFile,
|
|
150
|
+
bash: localCommands_1.bashTool,
|
|
151
|
+
save_image: saveImage_1.saveImage,
|
|
152
|
+
};
|
|
153
|
+
function createLocalTools(options) {
|
|
154
|
+
const context = { approver: options.approver, commands: options.commands ?? (0, localCommands_1.createCommandLog)(), gitBash: () => options.system.gitBash() };
|
|
155
|
+
return async (tool, args, signal) => {
|
|
156
|
+
if (tool === "local_status")
|
|
157
|
+
return localStatus(options);
|
|
158
|
+
const projectTool = Object.hasOwn(PROJECT_TOOLS, tool) ? PROJECT_TOOLS[tool] : undefined;
|
|
159
|
+
if (projectTool) {
|
|
160
|
+
const folder = options.projectFolder();
|
|
161
|
+
if (!folder)
|
|
162
|
+
return { ok: false, error: "no_project_folder", message: exports.NO_PROJECT_FOLDER_NOTE };
|
|
163
|
+
return projectTool(folder, args, signal, context);
|
|
164
|
+
}
|
|
165
|
+
return { ok: false, error: "unknown_tool", message: `這台電腦的 VansPod 不認識工具「${tool}」,請更新 VansPod。` };
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function osName() {
|
|
169
|
+
const release = node_os_1.default.release();
|
|
170
|
+
if (process.platform === "win32") {
|
|
171
|
+
const build = Number(release.split(".")[2]);
|
|
172
|
+
return `Windows ${build >= 22000 ? "11" : "10"} (${release}, ${node_os_1.default.arch()})`;
|
|
173
|
+
}
|
|
174
|
+
return `${process.platform === "darwin" ? "macOS" : process.platform} (${release}, ${node_os_1.default.arch()})`;
|
|
175
|
+
}
|
|
176
|
+
/** Git Bash is `bin\bash.exe` in Git's install folder (git.exe is in `cmd\` or `mingw64\bin\`). */
|
|
177
|
+
async function findGitBash() {
|
|
178
|
+
const env = await (0, systemPath_1.envWithRegistryPath)();
|
|
179
|
+
if (process.platform !== "win32")
|
|
180
|
+
return (0, windowsEnvironmentSystem_1.resolveCommand)("bash", env);
|
|
181
|
+
const git = await (0, windowsEnvironmentSystem_1.resolveCommand)("git", env);
|
|
182
|
+
const gitFolders = git ? [node_path_1.default.dirname(node_path_1.default.dirname(git)), node_path_1.default.dirname(node_path_1.default.dirname(node_path_1.default.dirname(git)))] : [];
|
|
183
|
+
// process.env, not the copied env: only process.env reads Windows names in any case.
|
|
184
|
+
const programs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && node_path_1.default.join(process.env.LOCALAPPDATA, "Programs")]
|
|
185
|
+
.filter((folder) => Boolean(folder))
|
|
186
|
+
.map(folder => node_path_1.default.join(folder, "Git"));
|
|
187
|
+
const candidates = [...gitFolders, ...programs].map(folder => node_path_1.default.join(folder, "bin", "bash.exe"));
|
|
188
|
+
for (const candidate of candidates) {
|
|
189
|
+
try {
|
|
190
|
+
if ((await promises_1.default.stat(candidate)).isFile())
|
|
191
|
+
return candidate;
|
|
192
|
+
}
|
|
193
|
+
catch { /* next one */ }
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
async function pythonVersion() {
|
|
198
|
+
const tries = process.platform === "win32"
|
|
199
|
+
? [["python", ["--version"]], ["py", ["-3", "--version"]]]
|
|
200
|
+
: [["python3", ["--version"]], ["python", ["--version"]]];
|
|
201
|
+
for (const [command, args] of tries) {
|
|
202
|
+
const result = await windowsEnvironmentSystem_1.windowsEnvironmentSystem.run(command, args, { timeoutMs: 10_000 });
|
|
203
|
+
const output = result.output.trim();
|
|
204
|
+
if (result.exitCode === 0 && /^Python \d+\.\d+/.test(output))
|
|
205
|
+
return output.split(/\r?\n/)[0];
|
|
206
|
+
}
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
exports.localSystem = { os: osName, gitBash: findGitBash, python: pythonVersion };
|
package/dist/modelStatus.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.modelStatusScript = void 0;
|
|
3
|
+
exports.approvalFullScript = exports.modelStatusScript = void 0;
|
|
4
4
|
exports.modelStatusScript = `
|
|
5
5
|
async function refreshModelStatus() {
|
|
6
6
|
try {
|
|
@@ -15,6 +15,30 @@ exports.modelStatusScript = `
|
|
|
15
15
|
setTimeout(refreshModelStatus, 1000);
|
|
16
16
|
}
|
|
17
17
|
function applyModelStatus(status) {
|
|
18
|
+
if (status.localTools) {
|
|
19
|
+
var localState = document.querySelector("[data-local-tools-state]");
|
|
20
|
+
if (localState && localState.textContent !== status.localTools.text) localState.textContent = status.localTools.text;
|
|
21
|
+
var localSwitch = document.querySelector("[data-local-tools-switch]");
|
|
22
|
+
if (localSwitch && localSwitch.getAttribute("aria-checked") !== String(status.localTools.on)) {
|
|
23
|
+
localSwitch.setAttribute("aria-checked", String(status.localTools.on));
|
|
24
|
+
localSwitch.value = status.localTools.on ? "0" : "1";
|
|
25
|
+
localSwitch.textContent = status.localTools.on ? "開" : "關";
|
|
26
|
+
localSwitch.classList.toggle("on", status.localTools.on);
|
|
27
|
+
}
|
|
28
|
+
var commandList = document.querySelector("[data-local-commands]");
|
|
29
|
+
var commands = status.localTools.commands;
|
|
30
|
+
if (commandList && commands && (commandList.getAttribute("data-commands-key") || "") !== commands.key) commandList.outerHTML = commands.html;
|
|
31
|
+
var approvalBlock = document.querySelector("[data-local-approval]");
|
|
32
|
+
if (approvalBlock) {
|
|
33
|
+
var approval = status.localTools.approval;
|
|
34
|
+
if ((approvalBlock.getAttribute("data-approval-key") || null) !== (approval ? approval.key : null)) {
|
|
35
|
+
approvalBlock.outerHTML = approval ? approval.html : '<div data-local-approval hidden></div>';
|
|
36
|
+
} else if (approval) {
|
|
37
|
+
var seconds = approvalBlock.querySelector("[data-approval-seconds]");
|
|
38
|
+
if (seconds) seconds.textContent = String(approval.secondsLeft);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
18
42
|
document.querySelectorAll("[data-client-light]").forEach(function (light) {
|
|
19
43
|
var next = status.lights[light.getAttribute("data-client-light")];
|
|
20
44
|
if (!next || (light.className === next.className && light.title === next.status)) return;
|
|
@@ -40,3 +64,20 @@ exports.modelStatusScript = `
|
|
|
40
64
|
}
|
|
41
65
|
setTimeout(refreshModelStatus, 1000);
|
|
42
66
|
`;
|
|
67
|
+
// 「顯示全部」 on a cut Local Tool Approval body: loads the full body of that approval once.
|
|
68
|
+
// The status poll redraws the block only when the shown approval changes, so the full body stays.
|
|
69
|
+
exports.approvalFullScript = `
|
|
70
|
+
document.addEventListener("click", async function (event) {
|
|
71
|
+
var button = event.target && event.target.closest && event.target.closest("[data-approval-full]");
|
|
72
|
+
if (!button) return;
|
|
73
|
+
try {
|
|
74
|
+
var response = await fetch("/local-tool-approval-body?id=" + encodeURIComponent(button.getAttribute("data-approval-full")), { cache: "no-store" });
|
|
75
|
+
if (!response.ok) return;
|
|
76
|
+
var answer = await response.json();
|
|
77
|
+
var block = button.closest("[data-local-approval]");
|
|
78
|
+
var pre = block && block.querySelector(".local-approval-body");
|
|
79
|
+
if (pre) pre.textContent = answer.body;
|
|
80
|
+
button.remove();
|
|
81
|
+
} catch (error) {}
|
|
82
|
+
});
|
|
83
|
+
`;
|
package/dist/page.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.modelStatus = modelStatus;
|
|
4
|
+
exports.localToolApprovalBodyResponse = localToolApprovalBodyResponse;
|
|
5
|
+
exports.localToolsStateText = localToolsStateText;
|
|
4
6
|
exports.environmentStageText = environmentStageText;
|
|
5
7
|
exports.environmentStatus = environmentStatus;
|
|
6
8
|
exports.renderPage = renderPage;
|
|
@@ -17,6 +19,7 @@ const clientIcons_1 = require("./clientIcons");
|
|
|
17
19
|
const environmentIcons_1 = require("./environmentIcons");
|
|
18
20
|
const classroomApp_1 = require("./classroomApp");
|
|
19
21
|
const promptCapture_1 = require("./promptCapture");
|
|
22
|
+
const localCommands_1 = require("./localCommands");
|
|
20
23
|
const inspectorView_1 = require("./inspectorView");
|
|
21
24
|
const versionUpdateView_1 = require("./versionUpdateView");
|
|
22
25
|
const powerMenuView_1 = require("./powerMenuView");
|
|
@@ -140,8 +143,114 @@ function modelStatus(view) {
|
|
|
140
143
|
return {
|
|
141
144
|
lights: { codex: clientLight(view, "codex"), claude: clientLight(view, "claude"), vscode: clientLight(view, "vscode") },
|
|
142
145
|
restart: restartHtml(view),
|
|
146
|
+
...(view.localTools ? { localTools: { on: view.localTools.on, text: localToolsStateText(view.localTools), approval: approvalStatus(view.localTools.approval), commands: commandsStatus(view.localTools.commands) } } : {}),
|
|
143
147
|
};
|
|
144
148
|
}
|
|
149
|
+
// The poll redraws the block only when the shown approval or the count changes; the seconds change every poll.
|
|
150
|
+
function approvalStatus(approval) {
|
|
151
|
+
return approval ? { key: approvalKey(approval), secondsLeft: approval.secondsLeft, html: approvalBlock(approval) } : null;
|
|
152
|
+
}
|
|
153
|
+
function approvalKey(approval) {
|
|
154
|
+
return `${approval.id}:${approval.waiting}`;
|
|
155
|
+
}
|
|
156
|
+
const NO_APPROVAL = `<div data-local-approval hidden></div>`;
|
|
157
|
+
/**
|
|
158
|
+
* The page sends the approval on every status poll, so a long body is cut here.
|
|
159
|
+
* 「顯示全部」 loads the full body from GET /local-tool-approval-body. The Approval Popup has its own view.
|
|
160
|
+
*/
|
|
161
|
+
const MAX_SHOWN_BODY = 10_000;
|
|
162
|
+
function shownBody(body) {
|
|
163
|
+
const chars = Array.from(body);
|
|
164
|
+
if (chars.length <= MAX_SHOWN_BODY)
|
|
165
|
+
return { text: body, cut: false };
|
|
166
|
+
return {
|
|
167
|
+
text: `${chars.slice(0, MAX_SHOWN_BODY).join("")}
|
|
168
|
+
…(內容太長,頁面只顯示前 ${MAX_SHOWN_BODY.toLocaleString("en-US")} 個字元,共 ${chars.length.toLocaleString("en-US")} 個字元。)`,
|
|
169
|
+
cut: true,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/** The answer of GET /local-tool-approval-body?id=...: the full body of the shown approval, or 404. */
|
|
173
|
+
function localToolApprovalBodyResponse(app, id) {
|
|
174
|
+
const body = app.localToolApprovalBody(id);
|
|
175
|
+
return body === undefined ? { status: 404, body: { error: "這個確認已經結束。" } } : { status: 200, body: { id, body } };
|
|
176
|
+
}
|
|
177
|
+
// The Command Log on the page: the `bash` commands of this VansPod run (ADR 0013).
|
|
178
|
+
const SHOWN_COMMANDS = 50;
|
|
179
|
+
const SHOWN_COMMAND_CHARS = 300;
|
|
180
|
+
function commandsKey(commands) {
|
|
181
|
+
return commands.slice(0, SHOWN_COMMANDS).map(command => `${command.id}:${command.state}`).join(",");
|
|
182
|
+
}
|
|
183
|
+
// The poll redraws the list only when a command starts or ends.
|
|
184
|
+
function commandsStatus(commands) {
|
|
185
|
+
return commands ? { key: commandsKey(commands), html: commandsBlock(commands) } : null;
|
|
186
|
+
}
|
|
187
|
+
function commandStateText(command) {
|
|
188
|
+
if (command.state === "running")
|
|
189
|
+
return "執行中";
|
|
190
|
+
if (command.state === "exited")
|
|
191
|
+
return `結束代碼 ${command.exitCode ?? "不明"}`;
|
|
192
|
+
if (command.state === "timed_out")
|
|
193
|
+
return `超過 ${localCommands_1.BASH_TIMEOUT_MS / 1000} 秒,已停止`;
|
|
194
|
+
if (command.state === "stopped")
|
|
195
|
+
return "已停止";
|
|
196
|
+
return "無法啟動";
|
|
197
|
+
}
|
|
198
|
+
function commandsBlock(commands) {
|
|
199
|
+
if (!commands || commands.length === 0)
|
|
200
|
+
return `<div class="local-commands" data-local-commands data-commands-key="" hidden></div>`;
|
|
201
|
+
const items = commands.slice(0, SHOWN_COMMANDS).map(command => {
|
|
202
|
+
const chars = Array.from(command.command);
|
|
203
|
+
const text = chars.length > SHOWN_COMMAND_CHARS ? `${chars.slice(0, SHOWN_COMMAND_CHARS).join("")}…(共 ${chars.length} 個字元)` : command.command;
|
|
204
|
+
const time = new Date(command.startedAt).toLocaleTimeString("zh-TW", { hour12: false });
|
|
205
|
+
const stop = command.state === "running"
|
|
206
|
+
? `<form method="post" action="/local-command-stop"><input type="hidden" name="id" value="${escapeHtml(command.id)}"><button type="submit" class="local-command-stop">停止</button></form>`
|
|
207
|
+
: "";
|
|
208
|
+
return `<li><code>${escapeHtml(text)}</code><span class="hint">${escapeHtml(time)}・${escapeHtml(commandStateText(command))}</span>${stop}</li>`;
|
|
209
|
+
}).join("");
|
|
210
|
+
const older = commands.length > SHOWN_COMMANDS ? `<p class="hint">較早的 ${commands.length - SHOWN_COMMANDS} 個指令沒有顯示。</p>` : "";
|
|
211
|
+
return `<div class="local-commands" data-local-commands data-commands-key="${escapeHtml(commandsKey(commands))}"><p class="hint">Agent Builder 這次執行過的指令(關掉 VansPod 就清除):</p>${older}<ol>${items}</ol></div>`;
|
|
212
|
+
}
|
|
213
|
+
// Local Tool Approval on the page (ADR 0013). No text field and no autofocus, so Enter cannot approve.
|
|
214
|
+
function approvalBodyHtml(approval) {
|
|
215
|
+
const { text, cut } = shownBody(approval.body);
|
|
216
|
+
const more = cut ? `<button type="button" class="local-approval-full" data-approval-full="${escapeHtml(approval.id)}">顯示全部</button>` : "";
|
|
217
|
+
return `<pre class="local-approval-body">${escapeHtml(text)}</pre>${more}`;
|
|
218
|
+
}
|
|
219
|
+
function approvalBlock(approval) {
|
|
220
|
+
if (!approval)
|
|
221
|
+
return NO_APPROVAL;
|
|
222
|
+
const waiting = approval.waiting > 0 ? `還有 ${approval.waiting} 個確認在排隊。` : "";
|
|
223
|
+
return `<div class="local-approval" role="group" aria-label="Local Tool 確認" data-local-approval data-approval-key="${escapeHtml(approvalKey(approval))}">`
|
|
224
|
+
+ `<p class="local-approval-title">Agent Builder 要求:<strong>${escapeHtml(approval.title)}</strong></p>`
|
|
225
|
+
+ `<p class="hint">電腦:${escapeHtml(approval.device)} 資料夾:${escapeHtml(approval.folder)}</p>`
|
|
226
|
+
+ approvalBodyHtml(approval)
|
|
227
|
+
+ `<p class="hint"><span data-approval-seconds>${approval.secondsLeft}</span> 秒後自動拒絕。${waiting}</p>`
|
|
228
|
+
+ `<form class="local-approval-actions" method="post" action="/local-tool-approval"><input type="hidden" name="id" value="${escapeHtml(approval.id)}">`
|
|
229
|
+
+ `<button type="submit" name="decision" value="approve" class="local-approval-approve">允許一次</button>`
|
|
230
|
+
+ `<button type="submit" name="decision" value="deny" class="local-approval-deny">拒絕</button></form></div>`;
|
|
231
|
+
}
|
|
232
|
+
/** One line about Local Tool Access for the student: the relay's message, or the connection state. */
|
|
233
|
+
function localToolsStateText(local) {
|
|
234
|
+
if (local.message)
|
|
235
|
+
return local.message;
|
|
236
|
+
if (local.state === "connected")
|
|
237
|
+
return "已連上,Agent Builder 可以使用這台電腦。";
|
|
238
|
+
if (local.state === "connecting")
|
|
239
|
+
return "正在連線…";
|
|
240
|
+
if (local.state === "retrying")
|
|
241
|
+
return `連線中斷,${Math.max(1, Math.round((local.retryInMs ?? 1000) / 1000))} 秒後重新連線。`;
|
|
242
|
+
return "已關閉,Agent Builder 不能使用這台電腦。";
|
|
243
|
+
}
|
|
244
|
+
// 讓 Agent Builder 使用這台電腦 (Local Tool Access, ADR 0013). Only with a Classroom Connection.
|
|
245
|
+
function localToolsBlock(view) {
|
|
246
|
+
const local = view.localTools;
|
|
247
|
+
if (!local || !view.connected)
|
|
248
|
+
return "";
|
|
249
|
+
const nickname = local.nickname
|
|
250
|
+
? `<p class="hint">在 Agent Builder 的授權頁選「暱稱」,輸入 <strong>${escapeHtml(local.nickname)}</strong>(大小寫要一樣)。這台電腦在 Agent Builder 叫做 <strong>${escapeHtml(local.device)}</strong>。</p>`
|
|
251
|
+
: `<p class="hint">這台電腦在 Agent Builder 叫做 <strong>${escapeHtml(local.device)}</strong>。</p>`;
|
|
252
|
+
return `<div class="local-tools" data-local-tools><form class="local-tools-row" method="post" action="/local-tools"><span>讓 Agent Builder 使用這台電腦</span><button type="submit" name="on" value="${local.on ? "0" : "1"}" role="switch" aria-checked="${local.on}" class="local-tools-switch${local.on ? " on" : ""}" data-local-tools-switch>${local.on ? "開" : "關"}</button></form><p class="hint" role="status" data-local-tools-state>${escapeHtml(localToolsStateText(local))}</p>${approvalBlock(local.approval)}${commandsBlock(local.commands)}${nickname}</div>`;
|
|
253
|
+
}
|
|
145
254
|
function adapterForms(view) {
|
|
146
255
|
const selected = view.adapters ?? { codex: "responses", claude: "responses" };
|
|
147
256
|
const forms = ["codex", "claude", "vscode"].map(client => {
|
|
@@ -949,7 +1058,7 @@ function renderPage(view) {
|
|
|
949
1058
|
? `<div class="connection-identity">${course}${meta ? `<p class="connection-meta">${meta}</p>` : ""}</div>`
|
|
950
1059
|
: "";
|
|
951
1060
|
const mascot = `<div class="classroom-update-home"><div class="classroom-update">${connectionMascot_1.connectionMascot}${(0, classroomUpdate_1.classroomUpdateControl)(view, restartHtml(view))}</div></div>`;
|
|
952
|
-
const block = `${identity}<div class="key-row"><p>API Key 已設定</p><form method="post" action="/copy"><button type="submit" class="connection-copy" aria-label="複製 Classroom API Key"${off}>${COPY_ICON}<span>複製</span></button></form></div>${mascot}<form method="post" action="/clear"><button type="submit" class="connection-clear"${off}>清除連線</button></form
|
|
1061
|
+
const block = `${identity}<div class="key-row"><p>API Key 已設定</p><form method="post" action="/copy"><button type="submit" class="connection-copy" aria-label="複製 Classroom API Key"${off}>${COPY_ICON}<span>複製</span></button></form></div>${mascot}<form method="post" action="/clear"><button type="submit" class="connection-clear"${off}>清除連線</button></form>${localToolsBlock(view)}`;
|
|
953
1062
|
html = html.replace(/<form method="post" action="\/copy">[\s\S]*?<\/form>\s*<form method="post" action="\/clear">[\s\S]*?<\/form>/, block);
|
|
954
1063
|
html = html.replace(/<p class="class-label">[\s\S]*?<\/p>/, "");
|
|
955
1064
|
html = html.replace(`<p class="detail">Classroom API Key 已設定。</p>`, "");
|
|
@@ -981,6 +1090,21 @@ function renderPage(view) {
|
|
|
981
1090
|
.connection-meta { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 8px; color: var(--muted); font-size: 13px; line-height: 1.6; }
|
|
982
1091
|
.connection-meta > span { min-width: 0; overflow-wrap: anywhere; }
|
|
983
1092
|
.connection-separator { opacity: 0.5; }
|
|
1093
|
+
.local-tools { display: flex; flex-direction: column; gap: 6px; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
|
|
1094
|
+
.local-tools-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
|
1095
|
+
.local-tools-switch { min-width: 3.5rem; background: var(--modes); color: var(--text); }
|
|
1096
|
+
.local-tools-switch.on { background: var(--accent); color: var(--on-accent); }
|
|
1097
|
+
.local-tools .hint { font-size: 13px; overflow-wrap: anywhere; }
|
|
1098
|
+
.local-approval { display: flex; flex-direction: column; gap: 6px; padding: 10px; border: 2px solid var(--accent); border-radius: 8px; }
|
|
1099
|
+
.local-approval-title { margin: 0; overflow-wrap: anywhere; }
|
|
1100
|
+
.local-approval-body { margin: 0; max-height: 16rem; overflow: auto; padding: 8px; background: var(--modes); border-radius: 6px; font-size: 13px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
1101
|
+
.local-approval-full { align-self: flex-start; background: none; color: var(--accent); padding: 0; text-decoration: underline; }
|
|
1102
|
+
.local-approval-actions { display: flex; gap: 8px; }
|
|
1103
|
+
.local-commands ol { margin: 0; padding-left: 1.4rem; display: flex; flex-direction: column; gap: 4px; max-height: 14rem; overflow: auto; }
|
|
1104
|
+
.local-commands li code { white-space: pre-wrap; overflow-wrap: anywhere; margin-right: 6px; }
|
|
1105
|
+
.local-command-stop { margin-left: 6px; padding: 2px 10px; }
|
|
1106
|
+
.local-commands form { display: inline; }
|
|
1107
|
+
.local-approval-approve { background: var(--accent); color: var(--on-accent); }
|
|
984
1108
|
.tool em { color: var(--text); }
|
|
985
1109
|
.tool em.missing { color: var(--muted); }
|
|
986
1110
|
.tool em.needs-repair { color: light-dark(#9a4a08, #fbbf24); }
|
|
@@ -1098,7 +1222,7 @@ function renderPage(view) {
|
|
|
1098
1222
|
main button.connection-clear:hover:not(:disabled) { color: light-dark(#b91c1c, #f87171); }
|
|
1099
1223
|
${classroomUpdate_1.classroomUpdateStyles}
|
|
1100
1224
|
</style>
|
|
1101
|
-
<script>${drawerScript()}${powerMenuView_1.powerMenuScript}${installProgress_1.installProgressScript}${environmentProgress_1.environmentProgressScript}${snippetCopyScript()}${courseSectionScript()}${connectionMascot_1.connectionMascotScript}${classroomUpdate_1.classroomUpdateScript}${settingsActions_1.settingsActionsScript}${modelStatus_1.modelStatusScript}
|
|
1225
|
+
<script>${drawerScript()}${powerMenuView_1.powerMenuScript}${installProgress_1.installProgressScript}${environmentProgress_1.environmentProgressScript}${snippetCopyScript()}${courseSectionScript()}${connectionMascot_1.connectionMascotScript}${classroomUpdate_1.classroomUpdateScript}${settingsActions_1.settingsActionsScript}${modelStatus_1.modelStatusScript}${modelStatus_1.approvalFullScript}
|
|
1102
1226
|
</script>`;
|
|
1103
1227
|
return html.replace("</body>", `${extra}</body>`);
|
|
1104
1228
|
}
|
|
@@ -0,0 +1,86 @@
|
|
|
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.resolveProjectPath = resolveProjectPath;
|
|
7
|
+
exports.isSecretFileName = isSecretFileName;
|
|
8
|
+
exports.hasPrivateKey = hasPrivateKey;
|
|
9
|
+
exports.secretFileRefusal = secretFileRefusal;
|
|
10
|
+
// The Project Folder boundary for the Local Tools (ADR 0013).
|
|
11
|
+
// `list_files`, `read_file`, and `write_file` resolve every path here before they touch the disk.
|
|
12
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
13
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
14
|
+
function inside(folder, target) {
|
|
15
|
+
const relative = node_path_1.default.relative(folder, target);
|
|
16
|
+
return relative === "" || (relative.split(node_path_1.default.sep)[0] !== ".." && !node_path_1.default.isAbsolute(relative));
|
|
17
|
+
}
|
|
18
|
+
async function exists(target) {
|
|
19
|
+
try {
|
|
20
|
+
await promises_1.default.lstat(target);
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Follows links in the longest part of `target` that exists, then adds the rest unchanged. */
|
|
28
|
+
async function realTarget(target) {
|
|
29
|
+
const rest = [];
|
|
30
|
+
let current = target;
|
|
31
|
+
for (;;) {
|
|
32
|
+
try {
|
|
33
|
+
return node_path_1.default.join(await promises_1.default.realpath(current), ...rest.reverse());
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
const parent = node_path_1.default.dirname(current);
|
|
37
|
+
if (parent === current)
|
|
38
|
+
return target;
|
|
39
|
+
rest.push(node_path_1.default.basename(current));
|
|
40
|
+
current = parent;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Resolves `requested` (relative to the Project Folder) and refuses it when it resolves outside,
|
|
46
|
+
* through `..`, an absolute path, or a link. Without `allowMissing`, a path that does not exist is `not_found`.
|
|
47
|
+
*/
|
|
48
|
+
async function resolveProjectPath(projectFolder, requested, options = {}) {
|
|
49
|
+
if (typeof requested !== "string" || requested.trim() === "") {
|
|
50
|
+
return { ok: false, error: "invalid_arguments", message: "path 必須是專案資料夾裡的相對路徑文字。" };
|
|
51
|
+
}
|
|
52
|
+
const outside = { ok: false, error: "outside_project_folder", message: `「${requested}」在專案資料夾外面,Local Tool 只能用專案資料夾裡的檔案。` };
|
|
53
|
+
const root = node_path_1.default.resolve(projectFolder);
|
|
54
|
+
const lexical = node_path_1.default.resolve(root, requested);
|
|
55
|
+
if (!inside(root, lexical))
|
|
56
|
+
return outside;
|
|
57
|
+
let realRoot;
|
|
58
|
+
try {
|
|
59
|
+
realRoot = await promises_1.default.realpath(root);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return { ok: false, error: "not_found", message: "VansPod 讀不到專案資料夾,它可能已被移動或刪除。請在 VansPod 重新選擇專案資料夾。" };
|
|
63
|
+
}
|
|
64
|
+
const real = await realTarget(lexical);
|
|
65
|
+
if (!inside(realRoot, real))
|
|
66
|
+
return outside;
|
|
67
|
+
const found = await exists(lexical);
|
|
68
|
+
if (!found && !options.allowMissing)
|
|
69
|
+
return { ok: false, error: "not_found", message: `專案資料夾裡沒有「${requested}」。` };
|
|
70
|
+
const relative = node_path_1.default.relative(root, lexical).split(node_path_1.default.sep).join("/") || ".";
|
|
71
|
+
return { ok: true, absolute: real, relative, exists: found };
|
|
72
|
+
}
|
|
73
|
+
const SSH_KEY_NAMES = /^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/;
|
|
74
|
+
/** A secret file by its name: `.env`, `.env.*`, `.dev.vars`, `*.pem`, `*.key`, or an SSH private key. */
|
|
75
|
+
function isSecretFileName(name) {
|
|
76
|
+
const lower = node_path_1.default.basename(name).toLowerCase();
|
|
77
|
+
return lower === ".env" || lower.startsWith(".env.") || lower === ".dev.vars"
|
|
78
|
+
|| lower.endsWith(".pem") || lower.endsWith(".key") || SSH_KEY_NAMES.test(lower);
|
|
79
|
+
}
|
|
80
|
+
/** A secret file by its content: a PEM or OpenSSH private key block, whatever the file name is. */
|
|
81
|
+
function hasPrivateKey(text) {
|
|
82
|
+
return /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/.test(text);
|
|
83
|
+
}
|
|
84
|
+
function secretFileRefusal(requested) {
|
|
85
|
+
return { ok: false, error: "secret_file", message: `「${requested}」是機密檔案(例如金鑰或密碼設定),Local Tool 不會讀取它。` };
|
|
86
|
+
}
|