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
package/README.md
CHANGED
|
@@ -38,7 +38,7 @@ npm run dist
|
|
|
38
38
|
npm pack --pack-destination dist
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
-
exe 產物為 `dist/VansPod.exe`,本機套件為 `dist/vanspod-0.4.
|
|
41
|
+
exe 產物為 `dist/VansPod.exe`,本機套件為 `dist/vanspod-0.4.15.tgz`;可在 Windows 用 `npm install -g <套件路徑>` 安裝測試。圖片、favicon、系統匣與移除腳本均包含在發佈產物中。更新 logo 後執行 `powershell.exe -NoProfile -File scripts/build-icon.ps1` 重建多尺寸 Windows icon。
|
|
42
42
|
|
|
43
43
|
exe 發佈管道為本專案 GitHub Releases,npm 為公開 registry 的 [`vanspod`](https://www.npmjs.com/package/vanspod) 套件。更新時不要執行完整移除,否則會清除課堂資料。
|
|
44
44
|
|
|
@@ -46,12 +46,12 @@ exe 發佈管道為本專案 GitHub Releases,npm 為公開 registry 的 [`vans
|
|
|
46
46
|
|
|
47
47
|
一般 push 不發佈;推送 `v*` tag 會在 Windows runner 安裝 Node.js 24、檢查型別、執行測試、打包並驗證 exe/npm 生命週期,全部通過後才建立 GitHub Release,最後發佈 npm 套件。學生從 Release 下載 `VansPod.exe`,同頁提供 `SHA256SUMS.txt`。Release 另附 brotli 壓縮的 `VansPod.exe.br`(約三分之一大小),程式內更新只下載這份,解壓後再比對 `VansPod.exe` 的 SHA-256;SHA256SUMS 沒列出它的舊版 Release 則下載完整 exe。
|
|
48
48
|
|
|
49
|
-
發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.4.
|
|
49
|
+
發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.4.15` 為例:
|
|
50
50
|
|
|
51
51
|
```powershell
|
|
52
52
|
git push origin master
|
|
53
|
-
git tag -a v0.4.
|
|
54
|
-
git push origin v0.4.
|
|
53
|
+
git tag -a v0.4.15 -m "VansPod 0.4.15"
|
|
54
|
+
git push origin v0.4.15
|
|
55
55
|
```
|
|
56
56
|
|
|
57
57
|
新版本使用新的版本號與 tag。相同 tag 的 Actions 重跑會更新該 Release 的產物。
|
package/dist/classroomApp.js
CHANGED
|
@@ -19,6 +19,7 @@ exports.ENVIRONMENT_LABEL = {
|
|
|
19
19
|
pwsh: "PowerShell 7",
|
|
20
20
|
vscode: "VS Code",
|
|
21
21
|
};
|
|
22
|
+
const LOCAL_TOOLS_NEED_CONNECTION = "請先兌換課堂連線,才能讓 Agent Builder 使用這台電腦。";
|
|
22
23
|
const LOCAL_LIST_NOTE = "這是本機清單。";
|
|
23
24
|
exports.COPIED_KEY_NOTICE = "已複製 Classroom API Key。請勿分享給不信任的人。";
|
|
24
25
|
const KEY_REJECTED_NOTICE = {
|
|
@@ -100,6 +101,7 @@ class ClassroomApp {
|
|
|
100
101
|
routeRestartNoted = false;
|
|
101
102
|
vsCodeOrigin;
|
|
102
103
|
sending = new Map();
|
|
104
|
+
localToolsNotice;
|
|
103
105
|
constructor(deps) {
|
|
104
106
|
this.deps = deps;
|
|
105
107
|
}
|
|
@@ -134,6 +136,33 @@ class ClassroomApp {
|
|
|
134
136
|
};
|
|
135
137
|
if (this.connectionError)
|
|
136
138
|
view.connectionError = this.connectionError;
|
|
139
|
+
if (this.deps.device) {
|
|
140
|
+
const status = this.deps.device.status();
|
|
141
|
+
const local = { on: status.on, state: status.state, device: status.device };
|
|
142
|
+
if (this.nickname)
|
|
143
|
+
local.nickname = this.nickname;
|
|
144
|
+
const message = status.message ?? (status.on ? undefined : this.localToolsNotice);
|
|
145
|
+
if (message)
|
|
146
|
+
local.message = message;
|
|
147
|
+
if (status.retryInMs !== undefined)
|
|
148
|
+
local.retryInMs = status.retryInMs;
|
|
149
|
+
const shown = this.deps.approvals?.shown();
|
|
150
|
+
if (shown) {
|
|
151
|
+
local.approval = {
|
|
152
|
+
id: shown.id,
|
|
153
|
+
tool: shown.request.tool,
|
|
154
|
+
title: shown.request.title,
|
|
155
|
+
body: shown.request.body,
|
|
156
|
+
folder: shown.request.folder,
|
|
157
|
+
device: status.device,
|
|
158
|
+
secondsLeft: Math.max(0, Math.ceil((shown.expiresAt - Date.now()) / 1000)),
|
|
159
|
+
waiting: shown.waiting,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (this.deps.localCommands)
|
|
163
|
+
local.commands = this.deps.localCommands.list();
|
|
164
|
+
view.localTools = local;
|
|
165
|
+
}
|
|
137
166
|
if (this.notice && this.notice === this.connectionNotice)
|
|
138
167
|
view.connectionNotice = this.connectionNotice;
|
|
139
168
|
if (this.connectionDraft && !this.connected)
|
|
@@ -791,6 +820,8 @@ class ClassroomApp {
|
|
|
791
820
|
this.notice = this.connectionNotice = "無法安全保存或清除原有課堂連線,換堂未完成。請稍後再試。";
|
|
792
821
|
return;
|
|
793
822
|
}
|
|
823
|
+
// A new Classroom Connection never inherits Local Tool Access from the old one.
|
|
824
|
+
await this.turnLocalToolAccessOff();
|
|
794
825
|
const desiredMode = this.mode;
|
|
795
826
|
const desiredClientModes = { ...this.clientModes };
|
|
796
827
|
const desiredVsCodeMode = this.clientRoutes.vsCodeChat.mode;
|
|
@@ -1692,6 +1723,52 @@ class ClassroomApp {
|
|
|
1692
1723
|
return false;
|
|
1693
1724
|
}
|
|
1694
1725
|
}
|
|
1726
|
+
/** Turns Local Tool Access (讓 Agent Builder 使用這台電腦) on or off. It needs a Classroom Connection. */
|
|
1727
|
+
async setLocalToolAccess(on) {
|
|
1728
|
+
return this.serialConnectionOperation(async () => {
|
|
1729
|
+
const device = this.deps.device;
|
|
1730
|
+
if (!device)
|
|
1731
|
+
return;
|
|
1732
|
+
this.localToolsNotice = undefined;
|
|
1733
|
+
if (!on) {
|
|
1734
|
+
await this.turnLocalToolAccessOff();
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
let apiKey;
|
|
1738
|
+
try {
|
|
1739
|
+
apiKey = this.connected ? (await this.deps.storage.getConnection())?.apiKey : undefined;
|
|
1740
|
+
}
|
|
1741
|
+
catch {
|
|
1742
|
+
apiKey = undefined;
|
|
1743
|
+
}
|
|
1744
|
+
if (!apiKey) {
|
|
1745
|
+
this.localToolsNotice = LOCAL_TOOLS_NEED_CONNECTION;
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
device.start(apiKey);
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
/** Decides the shown Local Tool Approval from the page. False when it is no longer shown: the first decision wins. */
|
|
1752
|
+
decideLocalToolApproval(id, decision) {
|
|
1753
|
+
return this.deps.approvals?.decide(id, decision) ?? false;
|
|
1754
|
+
}
|
|
1755
|
+
/** The full body of the shown Local Tool Approval, or undefined when `id` is not the shown one. The page cuts a long body. */
|
|
1756
|
+
localToolApprovalBody(id) {
|
|
1757
|
+
const shown = this.deps.approvals?.shown();
|
|
1758
|
+
return shown && shown.id === id ? shown.request.body : undefined;
|
|
1759
|
+
}
|
|
1760
|
+
/** Stops a running `bash` command from the page. False when it is not running. */
|
|
1761
|
+
stopLocalCommand(id) {
|
|
1762
|
+
return this.deps.localCommands?.stop(id) ?? false;
|
|
1763
|
+
}
|
|
1764
|
+
// Denies every waiting approval, lets the denials reach the relay, then disconnects.
|
|
1765
|
+
async turnLocalToolAccessOff() {
|
|
1766
|
+
if (this.deps.approvals?.shown()) {
|
|
1767
|
+
this.deps.approvals.denyAll();
|
|
1768
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
1769
|
+
}
|
|
1770
|
+
this.deps.device?.stop();
|
|
1771
|
+
}
|
|
1695
1772
|
async clearConnection() {
|
|
1696
1773
|
return this.serialConnectionOperation(() => this.clearConnectionNow());
|
|
1697
1774
|
}
|
|
@@ -1703,6 +1780,8 @@ class ClassroomApp {
|
|
|
1703
1780
|
this.notice = this.connectionNotice = "無法清除課堂連線。已保留原本連線,重新啟動後仍可能恢復。請稍後再試。";
|
|
1704
1781
|
return;
|
|
1705
1782
|
}
|
|
1783
|
+
await this.turnLocalToolAccessOff();
|
|
1784
|
+
this.localToolsNotice = undefined;
|
|
1706
1785
|
this.applyConnectionIdentity(undefined);
|
|
1707
1786
|
this.connectionError = undefined;
|
|
1708
1787
|
this.connectionDraft = undefined;
|
package/dist/commandRunner.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.collectOutput = collectOutput;
|
|
4
|
+
exports.killTree = killTree;
|
|
4
5
|
exports.shellLaunch = shellLaunch;
|
|
5
6
|
exports.runCommand = runCommand;
|
|
6
7
|
const node_child_process_1 = require("node:child_process");
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Device connection: while Local Tool Access is on, VansPod keeps one WebSocket to the
|
|
3
|
+
// vans-mcp-server relay and answers the Local Tool calls that come through it.
|
|
4
|
+
// Wire protocol: vans-mcp-server docs/device-relay-protocol.md. Design: docs/adr/0013.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.deviceName = deviceName;
|
|
7
|
+
exports.createDeviceConnection = createDeviceConnection;
|
|
8
|
+
const MAX_DEVICE_NAME = 64;
|
|
9
|
+
const REFUSED = 4401;
|
|
10
|
+
const BAD_HELLO = 4400;
|
|
11
|
+
const REPLACED = 4409;
|
|
12
|
+
/** The computer name as the relay accepts it: trimmed, at most 64 characters, never empty. */
|
|
13
|
+
function deviceName(hostname) {
|
|
14
|
+
return hostname.trim().slice(0, MAX_DEVICE_NAME).trim() || "VansPod";
|
|
15
|
+
}
|
|
16
|
+
function createDeviceConnection(options) {
|
|
17
|
+
const retry = options.retry ?? { firstMs: 1_000, maxMs: 30_000 };
|
|
18
|
+
const device = deviceName(options.device);
|
|
19
|
+
let current = { on: false, state: "off", device };
|
|
20
|
+
let apiKey;
|
|
21
|
+
let socket;
|
|
22
|
+
let timer;
|
|
23
|
+
let nextDelay = retry.firstMs;
|
|
24
|
+
// Each attempt has its own number; events from an older socket are ignored.
|
|
25
|
+
let attempt = 0;
|
|
26
|
+
const calls = new Map();
|
|
27
|
+
const set = (next) => {
|
|
28
|
+
current = { ...next, device };
|
|
29
|
+
options.onChange?.({ ...current });
|
|
30
|
+
};
|
|
31
|
+
const abortCalls = () => {
|
|
32
|
+
for (const control of calls.values())
|
|
33
|
+
control.abort();
|
|
34
|
+
calls.clear();
|
|
35
|
+
};
|
|
36
|
+
const close = () => {
|
|
37
|
+
attempt += 1;
|
|
38
|
+
if (timer)
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
timer = undefined;
|
|
41
|
+
abortCalls();
|
|
42
|
+
const open = socket;
|
|
43
|
+
socket = undefined;
|
|
44
|
+
if (open && open.readyState !== WebSocket.CLOSED && open.readyState !== WebSocket.CLOSING)
|
|
45
|
+
open.close(1000);
|
|
46
|
+
};
|
|
47
|
+
const off = (message) => {
|
|
48
|
+
close();
|
|
49
|
+
apiKey = undefined;
|
|
50
|
+
set(message ? { on: false, state: "off", message } : { on: false, state: "off" });
|
|
51
|
+
};
|
|
52
|
+
const scheduleRetry = (message) => {
|
|
53
|
+
close();
|
|
54
|
+
const wait = nextDelay;
|
|
55
|
+
nextDelay = Math.min(nextDelay * 2, retry.maxMs);
|
|
56
|
+
set({ on: true, state: "retrying", retryInMs: wait, ...(message ? { message } : {}) });
|
|
57
|
+
timer = setTimeout(connect, wait);
|
|
58
|
+
};
|
|
59
|
+
const reply = (open, frame) => {
|
|
60
|
+
if (open === socket && open.readyState === WebSocket.OPEN)
|
|
61
|
+
open.send(JSON.stringify(frame));
|
|
62
|
+
};
|
|
63
|
+
const run = async (open, id, tool, args) => {
|
|
64
|
+
const control = new AbortController();
|
|
65
|
+
calls.set(id, control);
|
|
66
|
+
let answer;
|
|
67
|
+
try {
|
|
68
|
+
answer = await options.handle(tool, args, control.signal);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
answer = { ok: false, error: "failed", message: `本機工具失敗:${error instanceof Error ? error.message : "原因不明"}。` };
|
|
72
|
+
}
|
|
73
|
+
if (calls.get(id) !== control || control.signal.aborted)
|
|
74
|
+
return;
|
|
75
|
+
calls.delete(id);
|
|
76
|
+
reply(open, { type: "result", id, ...answer });
|
|
77
|
+
};
|
|
78
|
+
const connect = () => {
|
|
79
|
+
timer = undefined;
|
|
80
|
+
if (!apiKey)
|
|
81
|
+
return;
|
|
82
|
+
const mine = ++attempt;
|
|
83
|
+
const key = apiKey;
|
|
84
|
+
set({ on: true, state: "connecting" });
|
|
85
|
+
let open;
|
|
86
|
+
try {
|
|
87
|
+
open = new WebSocket(options.url);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
scheduleRetry();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
socket = open;
|
|
94
|
+
let refusal;
|
|
95
|
+
open.addEventListener("open", () => {
|
|
96
|
+
if (mine !== attempt)
|
|
97
|
+
return;
|
|
98
|
+
open.send(JSON.stringify({ type: "hello", api_key: key, device }));
|
|
99
|
+
});
|
|
100
|
+
open.addEventListener("message", event => {
|
|
101
|
+
if (mine !== attempt || typeof event.data !== "string")
|
|
102
|
+
return;
|
|
103
|
+
let frame;
|
|
104
|
+
try {
|
|
105
|
+
frame = JSON.parse(event.data);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (!frame || typeof frame !== "object")
|
|
111
|
+
return;
|
|
112
|
+
if (frame.type === "welcome") {
|
|
113
|
+
nextDelay = retry.firstMs;
|
|
114
|
+
set({ on: true, state: "connected" });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (frame.type === "refused") {
|
|
118
|
+
refusal = typeof frame.message === "string" ? frame.message : undefined;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (frame.type === "cancel" && typeof frame.id === "string") {
|
|
122
|
+
calls.get(frame.id)?.abort();
|
|
123
|
+
calls.delete(frame.id);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (frame.type === "call" && typeof frame.id === "string") {
|
|
127
|
+
const id = frame.id;
|
|
128
|
+
if (typeof frame.tool !== "string") {
|
|
129
|
+
reply(open, { type: "result", id, ok: false, error: "invalid_arguments", message: "工具名稱不正確。" });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const args = frame.arguments && typeof frame.arguments === "object" && !Array.isArray(frame.arguments) ? frame.arguments : {};
|
|
133
|
+
void run(open, id, frame.tool, args);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
open.addEventListener("close", event => {
|
|
137
|
+
if (mine !== attempt)
|
|
138
|
+
return;
|
|
139
|
+
if (event.code === REFUSED) {
|
|
140
|
+
off(refusal ?? "課堂連線被拒絕,已關閉「讓 Agent Builder 使用這台電腦」。");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (event.code === BAD_HELLO) {
|
|
144
|
+
off("VansPod 無法連上 Agent Builder 的轉送站(連線資料不正確),請更新 VansPod。");
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (event.code === REPLACED) {
|
|
148
|
+
off("這台電腦有另一個較新的連線,這個連線已停止。");
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
scheduleRetry(refusal);
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
return {
|
|
155
|
+
start(key) {
|
|
156
|
+
if (apiKey === key && current.on)
|
|
157
|
+
return;
|
|
158
|
+
close();
|
|
159
|
+
apiKey = key;
|
|
160
|
+
nextDelay = retry.firstMs;
|
|
161
|
+
connect();
|
|
162
|
+
},
|
|
163
|
+
stop() { off(); },
|
|
164
|
+
status() { return { ...current }; },
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The changed lines between two texts, for a Local Tool Approval of `write_file` on an existing file.
|
|
3
|
+
// Each group starts with "@@ 原本第 N 行 @@". A removed line starts with "-" and an added line with "+".
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.lineChanges = lineChanges;
|
|
6
|
+
const MAX_TABLE = 4_000_000;
|
|
7
|
+
function lines(text) {
|
|
8
|
+
const all = text.replace(/\r\n/g, "\n").split("\n");
|
|
9
|
+
if (all.length > 1 && all[all.length - 1] === "")
|
|
10
|
+
all.pop();
|
|
11
|
+
return all;
|
|
12
|
+
}
|
|
13
|
+
/** The steps from `a` to `b` by the longest common subsequence. A table too large becomes one replace. */
|
|
14
|
+
function steps(a, b) {
|
|
15
|
+
if (a.length * b.length > MAX_TABLE) {
|
|
16
|
+
return [...a.map(text => ({ kind: "removed", text })), ...b.map(text => ({ kind: "added", text }))];
|
|
17
|
+
}
|
|
18
|
+
const width = b.length + 1;
|
|
19
|
+
const table = new Uint32Array((a.length + 1) * width);
|
|
20
|
+
for (let i = a.length - 1; i >= 0; i--) {
|
|
21
|
+
for (let j = b.length - 1; j >= 0; j--) {
|
|
22
|
+
table[i * width + j] = a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const out = [];
|
|
26
|
+
let i = 0, j = 0;
|
|
27
|
+
while (i < a.length && j < b.length) {
|
|
28
|
+
if (a[i] === b[j]) {
|
|
29
|
+
out.push({ kind: "same", text: a[i] });
|
|
30
|
+
i++;
|
|
31
|
+
j++;
|
|
32
|
+
}
|
|
33
|
+
else if (table[(i + 1) * width + j] >= table[i * width + j + 1])
|
|
34
|
+
out.push({ kind: "removed", text: a[i++] });
|
|
35
|
+
else
|
|
36
|
+
out.push({ kind: "added", text: b[j++] });
|
|
37
|
+
}
|
|
38
|
+
while (i < a.length)
|
|
39
|
+
out.push({ kind: "removed", text: a[i++] });
|
|
40
|
+
while (j < b.length)
|
|
41
|
+
out.push({ kind: "added", text: b[j++] });
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function lineChanges(before, after) {
|
|
45
|
+
const a = lines(before), b = lines(after);
|
|
46
|
+
let start = 0;
|
|
47
|
+
while (start < a.length && start < b.length && a[start] === b[start])
|
|
48
|
+
start++;
|
|
49
|
+
let endA = a.length, endB = b.length;
|
|
50
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
51
|
+
endA--;
|
|
52
|
+
endB--;
|
|
53
|
+
}
|
|
54
|
+
const middle = steps(a.slice(start, endA), b.slice(start, endB));
|
|
55
|
+
const out = [];
|
|
56
|
+
let oldLine = start + 1;
|
|
57
|
+
let inGroup = false;
|
|
58
|
+
for (const step of middle) {
|
|
59
|
+
if (step.kind === "same") {
|
|
60
|
+
inGroup = false;
|
|
61
|
+
oldLine++;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (!inGroup) {
|
|
65
|
+
out.push(`@@ 原本第 ${oldLine} 行 @@`);
|
|
66
|
+
inGroup = true;
|
|
67
|
+
}
|
|
68
|
+
out.push(`${step.kind === "removed" ? "-" : "+"}${step.text}`);
|
|
69
|
+
if (step.kind === "removed")
|
|
70
|
+
oldLine++;
|
|
71
|
+
}
|
|
72
|
+
if (out.length === 0)
|
|
73
|
+
return before === after ? "(內容沒有改變)" : "(只改了換行符號)";
|
|
74
|
+
return out.join("\n");
|
|
75
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
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.MAX_OUTPUT_CHARS = exports.BASH_TIMEOUT_MS = void 0;
|
|
7
|
+
exports.createCommandLog = createCommandLog;
|
|
8
|
+
exports.bashTool = bashTool;
|
|
9
|
+
// The `bash` Local Tool (ADR 0013): one command in Git Bash, from the Project Folder, after a
|
|
10
|
+
// Local Tool Approval. Each command that ran is kept in a Command Log for this VansPod run only,
|
|
11
|
+
// like Prompt Capture. The page lists it and can stop a running command.
|
|
12
|
+
const node_child_process_1 = require("node:child_process");
|
|
13
|
+
const node_fs_1 = require("node:fs");
|
|
14
|
+
const node_os_1 = __importDefault(require("node:os"));
|
|
15
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
16
|
+
const commandRunner_1 = require("./commandRunner");
|
|
17
|
+
const localToolApproval_1 = require("./localToolApproval");
|
|
18
|
+
const systemPath_1 = require("./systemPath");
|
|
19
|
+
exports.BASH_TIMEOUT_MS = 60_000;
|
|
20
|
+
/** About this many characters of standard output and standard error together reach the agent. */
|
|
21
|
+
exports.MAX_OUTPUT_CHARS = 30_000;
|
|
22
|
+
// A UTF-8 character has at most 4 bytes. Keep this many bytes from the start and from the end.
|
|
23
|
+
const KEEP_BYTES = exports.MAX_OUTPUT_CHARS * 4;
|
|
24
|
+
/** The Command Log keeps the newest commands only. */
|
|
25
|
+
const MAX_RECORDS = 200;
|
|
26
|
+
function collector() {
|
|
27
|
+
return { head: [], headBytes: 0, tail: [], tailBytes: 0, total: 0 };
|
|
28
|
+
}
|
|
29
|
+
function collect(into, chunk) {
|
|
30
|
+
into.total += chunk.length;
|
|
31
|
+
if (into.headBytes < KEEP_BYTES) {
|
|
32
|
+
const part = chunk.subarray(0, KEEP_BYTES - into.headBytes);
|
|
33
|
+
into.head.push(part);
|
|
34
|
+
into.headBytes += part.length;
|
|
35
|
+
chunk = chunk.subarray(part.length);
|
|
36
|
+
}
|
|
37
|
+
if (chunk.length === 0)
|
|
38
|
+
return;
|
|
39
|
+
into.tail.push(chunk);
|
|
40
|
+
into.tailBytes += chunk.length;
|
|
41
|
+
while (into.tail.length > 1 && into.tailBytes - into.tail[0].length >= KEEP_BYTES)
|
|
42
|
+
into.tailBytes -= into.tail.shift().length;
|
|
43
|
+
}
|
|
44
|
+
/** The text of a stream, and its length in characters when nothing was dropped in the middle. */
|
|
45
|
+
function streamText(from) {
|
|
46
|
+
const head = Array.from(new TextDecoder("utf-8").decode(Buffer.concat(from.head)));
|
|
47
|
+
if (from.tailBytes === 0)
|
|
48
|
+
return head;
|
|
49
|
+
let tail = Buffer.concat(from.tail);
|
|
50
|
+
if (tail.length > KEEP_BYTES)
|
|
51
|
+
tail = tail.subarray(tail.length - KEEP_BYTES);
|
|
52
|
+
// Bytes between the head and the tail were not kept; mark the gap with an empty slot.
|
|
53
|
+
const gap = from.total > from.headBytes + tail.length;
|
|
54
|
+
return [...head, ...(gap ? [""] : []), ...Array.from(new TextDecoder("utf-8").decode(tail))];
|
|
55
|
+
}
|
|
56
|
+
/** Keeps the start and the end, which usually holds the error, and marks the cut. */
|
|
57
|
+
function cut(chars, keep) {
|
|
58
|
+
const missing = chars.includes("");
|
|
59
|
+
if (!missing && chars.length <= keep)
|
|
60
|
+
return { text: chars.join(""), cut: false };
|
|
61
|
+
const front = Math.ceil(keep / 2);
|
|
62
|
+
const back = keep - front;
|
|
63
|
+
const omitted = missing ? "很多" : String(chars.length - keep);
|
|
64
|
+
return { text: `${chars.slice(0, front).join("")}\n…(輸出太長,中間省略了 ${omitted} 個字元)…\n${chars.slice(chars.length - back).join("")}`, cut: true };
|
|
65
|
+
}
|
|
66
|
+
/** Shares MAX_OUTPUT_CHARS between the two streams; a short stream keeps all of its text. */
|
|
67
|
+
function shareOutput(stdout, stderr) {
|
|
68
|
+
const errorKeep = Math.min(stderr.length, Math.max(exports.MAX_OUTPUT_CHARS - stdout.length, exports.MAX_OUTPUT_CHARS / 3));
|
|
69
|
+
const out = cut(stdout, exports.MAX_OUTPUT_CHARS - errorKeep);
|
|
70
|
+
const err = cut(stderr, errorKeep);
|
|
71
|
+
return { stdout: out.text, stderr: err.text, truncated: out.cut || err.cut };
|
|
72
|
+
}
|
|
73
|
+
// Bash writes its own pid first. Without job control, every process that the command starts
|
|
74
|
+
// stays in that process group, so `kill -- -pid` ends them all, also after a parent has exited.
|
|
75
|
+
const RUN_SCRIPT = `echo $$ > "$VANSPOD_BASH_PID_FILE"; unset VANSPOD_BASH_PID_FILE; eval "$VANSPOD_BASH_COMMAND"`;
|
|
76
|
+
/**
|
|
77
|
+
* Ends the command and everything it started. Git Bash forks do not keep the Windows parent link,
|
|
78
|
+
* so the Windows process tree alone can miss a running program. Kill the Bash process group first.
|
|
79
|
+
*/
|
|
80
|
+
function stopProcesses(bash, child, pidFile) {
|
|
81
|
+
let pid = "";
|
|
82
|
+
try {
|
|
83
|
+
pid = (0, node_fs_1.readFileSync)(pidFile, "utf8").trim();
|
|
84
|
+
}
|
|
85
|
+
catch { /* bash has not written it yet */ }
|
|
86
|
+
if (!/^[0-9]+$/.test(pid)) {
|
|
87
|
+
(0, commandRunner_1.killTree)(child);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
(0, node_child_process_1.spawn)(bash, ["-c", `kill -9 -- -${pid}`], { windowsHide: true, stdio: "ignore" })
|
|
91
|
+
.on("error", () => (0, commandRunner_1.killTree)(child))
|
|
92
|
+
.on("exit", () => (0, commandRunner_1.killTree)(child));
|
|
93
|
+
}
|
|
94
|
+
function createCommandLog(options = {}) {
|
|
95
|
+
const timeoutMs = options.timeoutMs ?? exports.BASH_TIMEOUT_MS;
|
|
96
|
+
const records = [];
|
|
97
|
+
const running = new Map();
|
|
98
|
+
const listeners = new Set();
|
|
99
|
+
let nextId = 0;
|
|
100
|
+
const notify = () => {
|
|
101
|
+
for (const listener of [...listeners]) {
|
|
102
|
+
try {
|
|
103
|
+
listener();
|
|
104
|
+
}
|
|
105
|
+
catch { /* one listener must not stop the others */ }
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
return {
|
|
109
|
+
list: () => records.map(record => ({ ...record })).reverse(),
|
|
110
|
+
stop(id) {
|
|
111
|
+
const stop = running.get(id);
|
|
112
|
+
if (!stop)
|
|
113
|
+
return false;
|
|
114
|
+
stop();
|
|
115
|
+
return true;
|
|
116
|
+
},
|
|
117
|
+
subscribe(listener) {
|
|
118
|
+
listeners.add(listener);
|
|
119
|
+
return () => { listeners.delete(listener); };
|
|
120
|
+
},
|
|
121
|
+
async run(bash, command, folder, signal) {
|
|
122
|
+
const env = await (0, systemPath_1.envWithRegistryPath)();
|
|
123
|
+
// From here to the spawn nothing waits, so a listed running command can always be stopped.
|
|
124
|
+
const record = { id: `command-${++nextId}`, command, folder, startedAt: Date.now(), state: "running" };
|
|
125
|
+
records.push(record);
|
|
126
|
+
if (records.length > MAX_RECORDS)
|
|
127
|
+
records.splice(0, records.length - MAX_RECORDS);
|
|
128
|
+
const stdout = collector();
|
|
129
|
+
const stderr = collector();
|
|
130
|
+
const ended = await new Promise(resolve => {
|
|
131
|
+
let why;
|
|
132
|
+
let settled = false;
|
|
133
|
+
// The command and the pid file go in the environment, so no Windows argument quoting or globbing changes them.
|
|
134
|
+
const pidFile = node_path_1.default.join(node_os_1.default.tmpdir(), `vanspod-bash-${process.pid}-${record.id}.pid`);
|
|
135
|
+
const child = (0, node_child_process_1.spawn)(bash, ["-c", RUN_SCRIPT], {
|
|
136
|
+
cwd: folder,
|
|
137
|
+
env: { ...env, VANSPOD_BASH_COMMAND: command, VANSPOD_BASH_PID_FILE: pidFile },
|
|
138
|
+
windowsHide: true,
|
|
139
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
140
|
+
});
|
|
141
|
+
const finish = (result) => {
|
|
142
|
+
if (settled)
|
|
143
|
+
return;
|
|
144
|
+
settled = true;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
signal.removeEventListener("abort", onCancel);
|
|
147
|
+
running.delete(record.id);
|
|
148
|
+
(0, node_fs_1.rmSync)(pidFile, { force: true });
|
|
149
|
+
resolve({ ...result, ...(why ? { why } : {}) });
|
|
150
|
+
};
|
|
151
|
+
const end = (reason) => {
|
|
152
|
+
if (why || settled)
|
|
153
|
+
return;
|
|
154
|
+
why = reason;
|
|
155
|
+
stopProcesses(bash, child, pidFile);
|
|
156
|
+
// A grandchild can hold the pipes open; do not wait for it forever.
|
|
157
|
+
setTimeout(() => finish({}), 3_000).unref();
|
|
158
|
+
};
|
|
159
|
+
const timer = setTimeout(() => end("timed_out"), timeoutMs);
|
|
160
|
+
const onCancel = () => end("cancelled");
|
|
161
|
+
running.set(record.id, () => end("stopped"));
|
|
162
|
+
signal.addEventListener("abort", onCancel, { once: true });
|
|
163
|
+
if (signal.aborted)
|
|
164
|
+
onCancel();
|
|
165
|
+
child.stdout.on("data", (chunk) => collect(stdout, chunk));
|
|
166
|
+
child.stderr.on("data", (chunk) => collect(stderr, chunk));
|
|
167
|
+
child.on("error", error => finish({ error: error.message }));
|
|
168
|
+
child.on("close", code => finish(code === null ? {} : { code }));
|
|
169
|
+
notify();
|
|
170
|
+
});
|
|
171
|
+
record.endedAt = Date.now();
|
|
172
|
+
if (ended.error) {
|
|
173
|
+
record.state = "failed";
|
|
174
|
+
notify();
|
|
175
|
+
return { ok: false, error: "failed", message: `VansPod 無法啟動 Git Bash:${ended.error}。` };
|
|
176
|
+
}
|
|
177
|
+
record.state = ended.why === "timed_out" ? "timed_out" : ended.why ? "stopped" : "exited";
|
|
178
|
+
if (!ended.why && ended.code !== undefined)
|
|
179
|
+
record.exitCode = ended.code;
|
|
180
|
+
notify();
|
|
181
|
+
const output = shareOutput(streamText(stdout), streamText(stderr));
|
|
182
|
+
const result = { exit_code: ended.why ? null : ended.code ?? null, stdout: output.stdout, stderr: output.stderr };
|
|
183
|
+
const notes = [];
|
|
184
|
+
if (ended.why === "timed_out") {
|
|
185
|
+
result.timed_out = true;
|
|
186
|
+
notes.push(`指令執行超過 ${Math.round(timeoutMs / 1000)} 秒,VansPod 已停止它。下面是停止前的輸出。`);
|
|
187
|
+
}
|
|
188
|
+
if (ended.why === "stopped") {
|
|
189
|
+
result.stopped = true;
|
|
190
|
+
notes.push("學生在 VansPod 頁面停止了這個指令。下面是停止前的輸出。");
|
|
191
|
+
}
|
|
192
|
+
if (ended.why === "cancelled") {
|
|
193
|
+
result.stopped = true;
|
|
194
|
+
notes.push("這個呼叫已被取消,VansPod 已停止這個指令。");
|
|
195
|
+
}
|
|
196
|
+
if (output.truncated) {
|
|
197
|
+
result.truncated = true;
|
|
198
|
+
notes.push(`輸出太長,只回傳開頭和結尾,共約 ${exports.MAX_OUTPUT_CHARS.toLocaleString("en-US")} 個字元。`);
|
|
199
|
+
}
|
|
200
|
+
if (notes.length > 0)
|
|
201
|
+
result.note = notes.join(" ");
|
|
202
|
+
return { ok: true, result };
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
const NOT_RUN = "沒有執行";
|
|
207
|
+
/** The `bash` Local Tool. `gitBash` finds Git Bash; `commands` runs and records the command. */
|
|
208
|
+
async function bashTool(projectFolder, args, signal, context) {
|
|
209
|
+
if (typeof args.command !== "string" || args.command.trim() === "") {
|
|
210
|
+
return { ok: false, error: "invalid_arguments", message: "command 必須是要在 Git Bash 執行的指令。" };
|
|
211
|
+
}
|
|
212
|
+
const command = args.command;
|
|
213
|
+
const bash = await context.gitBash();
|
|
214
|
+
if (!bash) {
|
|
215
|
+
return { ok: false, error: "failed", message: `這台電腦找不到 Git Bash,${NOT_RUN}。請學生在 VansPod 的「環境安裝」安裝 Git。` };
|
|
216
|
+
}
|
|
217
|
+
const refusal = await (0, localToolApproval_1.askApproval)(context.approver, { tool: "bash", title: "在 Git Bash 執行指令", body: command, folder: projectFolder }, signal, NOT_RUN);
|
|
218
|
+
if (refusal)
|
|
219
|
+
return refusal;
|
|
220
|
+
return context.commands.run(bash, command, projectFolder, signal);
|
|
221
|
+
}
|