vanspod 0.4.15 → 0.4.16

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 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.15.tgz`;可在 Windows 用 `npm install -g <套件路徑>` 安裝測試。圖片、favicon、系統匣與移除腳本均包含在發佈產物中。更新 logo 後執行 `powershell.exe -NoProfile -File scripts/build-icon.ps1` 重建多尺寸 Windows icon。
41
+ exe 產物為 `dist/VansPod.exe`,本機套件為 `dist/vanspod-0.4.16.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.15` 為例:
49
+ 發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.4.16` 為例:
50
50
 
51
51
  ```powershell
52
52
  git push origin master
53
- git tag -a v0.4.15 -m "VansPod 0.4.15"
54
- git push origin v0.4.15
53
+ git tag -a v0.4.16 -m "VansPod 0.4.16"
54
+ git push origin v0.4.16
55
55
  ```
56
56
 
57
57
  新版本使用新的版本號與 tag。相同 tag 的 Actions 重跑會更新該 Release 的產物。
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ClassroomApp = exports.COPIED_KEY_NOTICE = exports.ENVIRONMENT_LABEL = exports.ENVIRONMENT_TOOLS = void 0;
3
+ exports.ClassroomApp = exports.COPIED_KEY_NOTICE = exports.AUTO_APPROVAL_NEEDS_ACCESS = exports.AUTO_APPROVAL_DURATIONS = exports.ENVIRONMENT_LABEL = exports.ENVIRONMENT_TOOLS = void 0;
4
4
  const secureStorage_1 = require("./secureStorage");
5
5
  const storageErrors_1 = require("./storageErrors");
6
6
  const adapterSettings_1 = require("./adapterSettings");
@@ -9,6 +9,7 @@ const node_util_1 = require("node:util");
9
9
  const courseCatalog_1 = require("./courseCatalog");
10
10
  const modelProxy_1 = require("./modelProxy");
11
11
  const classroomKeyRejection_1 = require("./classroomKeyRejection");
12
+ const localToolApproval_1 = require("./localToolApproval");
12
13
  const CLIENT_ROUTE_OF = { codex: "codex", claude: "claudeCode", vscode: "vsCodeChat" };
13
14
  // 新工具加在最後,不改既有 id。
14
15
  exports.ENVIRONMENT_TOOLS = ["uv", "git", "node", "pwsh", "vscode"];
@@ -19,7 +20,13 @@ exports.ENVIRONMENT_LABEL = {
19
20
  pwsh: "PowerShell 7",
20
21
  vscode: "VS Code",
21
22
  };
22
- const LOCAL_TOOLS_NEED_CONNECTION = "請先兌換課堂連線,才能讓 Agent Builder 使用這台電腦。";
23
+ exports.AUTO_APPROVAL_DURATIONS = {
24
+ "10": { label: "10 分鐘", ms: 10 * 60_000 },
25
+ "30": { label: "30 分鐘", ms: 30 * 60_000 },
26
+ until_off: { label: "直到關閉開關" },
27
+ };
28
+ const LOCAL_TOOLS_NEED_CONNECTION = "請先兌換課堂連線,才能讓 Agent 使用這台電腦。";
29
+ exports.AUTO_APPROVAL_NEEDS_ACCESS = "請先打開「允許 Agent 使用這台電腦」,才能自動允許。";
23
30
  const LOCAL_LIST_NOTE = "這是本機清單。";
24
31
  exports.COPIED_KEY_NOTICE = "已複製 Classroom API Key。請勿分享給不信任的人。";
25
32
  const KEY_REJECTED_NOTICE = {
@@ -102,8 +109,15 @@ class ClassroomApp {
102
109
  vsCodeOrigin;
103
110
  sending = new Map();
104
111
  localToolsNotice;
112
+ autoApprovalLabel;
105
113
  constructor(deps) {
106
114
  this.deps = deps;
115
+ // Every way that Local Tool Access turns off (the switch, or the relay by itself) ends Auto Approval
116
+ // and denies the waiting approvals (ADR 0014).
117
+ const { device, approvals } = deps;
118
+ if (device && approvals)
119
+ device.subscribe(status => { if (!status.on)
120
+ approvals.denyAll(); });
107
121
  }
108
122
  serialConnectionOperation(operation) {
109
123
  const next = this.connectionOperations.then(operation, operation);
@@ -141,7 +155,8 @@ class ClassroomApp {
141
155
  const local = { on: status.on, state: status.state, device: status.device };
142
156
  if (this.nickname)
143
157
  local.nickname = this.nickname;
144
- const message = status.message ?? (status.on ? undefined : this.localToolsNotice);
158
+ // While it is off, the newest notice (from the student's last action) comes before the relay's reason.
159
+ const message = status.on ? status.message : this.localToolsNotice ?? status.message;
145
160
  if (message)
146
161
  local.message = message;
147
162
  if (status.retryInMs !== undefined)
@@ -157,10 +172,17 @@ class ClassroomApp {
157
172
  device: status.device,
158
173
  secondsLeft: Math.max(0, Math.ceil((shown.expiresAt - Date.now()) / 1000)),
159
174
  waiting: shown.waiting,
175
+ ...(shown.exception ? { exception: localToolApproval_1.AUTO_APPROVAL_EXCEPTION_LABELS[shown.exception] } : {}),
160
176
  };
161
177
  }
162
- if (this.deps.localCommands)
163
- local.commands = this.deps.localCommands.list();
178
+ const auto = this.deps.approvals?.autoApproval();
179
+ if (auto) {
180
+ local.autoApproval = auto.endsAt === undefined
181
+ ? { label: this.autoApprovalLabel ?? exports.AUTO_APPROVAL_DURATIONS.until_off.label }
182
+ : { label: this.autoApprovalLabel ?? "", endsAt: auto.endsAt, secondsLeft: Math.max(0, Math.ceil((auto.endsAt - Date.now()) / 1000)) };
183
+ }
184
+ if (this.deps.remoteAgentLog)
185
+ local.log = { entries: this.deps.remoteAgentLog.list(), dropped: this.deps.remoteAgentLog.dropped() };
164
186
  view.localTools = local;
165
187
  }
166
188
  if (this.notice && this.notice === this.connectionNotice)
@@ -1723,7 +1745,7 @@ class ClassroomApp {
1723
1745
  return false;
1724
1746
  }
1725
1747
  }
1726
- /** Turns Local Tool Access (讓 Agent Builder 使用這台電腦) on or off. It needs a Classroom Connection. */
1748
+ /** Turns Local Tool Access (允許 Agent 使用這台電腦) on or off. It needs a Classroom Connection. */
1727
1749
  async setLocalToolAccess(on) {
1728
1750
  return this.serialConnectionOperation(async () => {
1729
1751
  const device = this.deps.device;
@@ -1752,21 +1774,43 @@ class ClassroomApp {
1752
1774
  decideLocalToolApproval(id, decision) {
1753
1775
  return this.deps.approvals?.decide(id, decision) ?? false;
1754
1776
  }
1777
+ /**
1778
+ * Starts Auto Approval (ADR 0014) from the page or the Approval Popup. The waiting approvals that are not
1779
+ * Auto Approval Exceptions are approved now. False when Local Tool Access is off: the page then tells the student.
1780
+ */
1781
+ startAutoApproval(duration) {
1782
+ const approvals = this.deps.approvals;
1783
+ if (!approvals || !Object.hasOwn(exports.AUTO_APPROVAL_DURATIONS, duration))
1784
+ return false;
1785
+ if (!this.deps.device?.status().on) {
1786
+ this.localToolsNotice = exports.AUTO_APPROVAL_NEEDS_ACCESS;
1787
+ return false;
1788
+ }
1789
+ const { label, ms } = exports.AUTO_APPROVAL_DURATIONS[duration];
1790
+ this.autoApprovalLabel = label;
1791
+ approvals.startAutoApproval(ms);
1792
+ return true;
1793
+ }
1794
+ /** Stops Auto Approval from the page or the tray menu. */
1795
+ stopAutoApproval() {
1796
+ this.deps.approvals?.stopAutoApproval();
1797
+ }
1755
1798
  /** 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
1799
  localToolApprovalBody(id) {
1757
1800
  const shown = this.deps.approvals?.shown();
1758
1801
  return shown && shown.id === id ? shown.request.body : undefined;
1759
1802
  }
1760
1803
  /** 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;
1804
+ stopRemoteAgentCommand(id) {
1805
+ return this.deps.remoteAgentLog?.stop(id) ?? false;
1763
1806
  }
1764
1807
  // Denies every waiting approval, lets the denials reach the relay, then disconnects.
1765
1808
  async turnLocalToolAccessOff() {
1766
- if (this.deps.approvals?.shown()) {
1767
- this.deps.approvals.denyAll();
1809
+ const approvals = this.deps.approvals;
1810
+ const waiting = approvals?.shown() !== undefined;
1811
+ approvals?.denyAll();
1812
+ if (waiting)
1768
1813
  await new Promise(resolve => setImmediate(resolve));
1769
- }
1770
1814
  this.deps.device?.stop();
1771
1815
  }
1772
1816
  async clearConnection() {
@@ -16,7 +16,7 @@ function unsupported(commands) {
16
16
  return `課堂模式沒有這些網路指令。${commands.length ? `These web commands are not supported in this classroom session and were not run: ${commands.join(", ")}.` : "This request named no web command that this classroom session runs."} Searching is done with search_query (searching by query text); its results already include a text snippet of each page. Do not retry the unsupported commands. Do not use shell commands (curl, wget, scripts) to get that information some other way. If that is not enough, tell the user this classroom session cannot do it.`;
17
17
  }
18
18
  // open, click and find read a page Codex already knows the address of. That is not Web
19
- // Search (CONTEXT.md): Router is not called, so whether the Class Session allows Web
19
+ // Search (GLOSSARY.md): Router is not called, so whether the Class Session allows Web
20
20
  // Search is never asked, and the Coding Agent fetches the page itself.
21
21
  const READ_COMMANDS = ["open", "click", "find"];
22
22
  // What is written back to the model; a longer ref_id is still answered, just not quoted.
@@ -24,9 +24,16 @@ function createDeviceConnection(options) {
24
24
  // Each attempt has its own number; events from an older socket are ignored.
25
25
  let attempt = 0;
26
26
  const calls = new Map();
27
+ const listeners = new Set();
27
28
  const set = (next) => {
28
29
  current = { ...next, device };
29
30
  options.onChange?.({ ...current });
31
+ for (const listener of [...listeners]) {
32
+ try {
33
+ listener({ ...current });
34
+ }
35
+ catch { /* one listener must not stop the others */ }
36
+ }
30
37
  };
31
38
  const abortCalls = () => {
32
39
  for (const control of calls.values())
@@ -137,11 +144,11 @@ function createDeviceConnection(options) {
137
144
  if (mine !== attempt)
138
145
  return;
139
146
  if (event.code === REFUSED) {
140
- off(refusal ?? "課堂連線被拒絕,已關閉「讓 Agent Builder 使用這台電腦」。");
147
+ off(refusal ?? "課堂連線被拒絕,已關閉「允許 Agent 使用這台電腦」。");
141
148
  return;
142
149
  }
143
150
  if (event.code === BAD_HELLO) {
144
- off("VansPod 無法連上 Agent Builder 的轉送站(連線資料不正確),請更新 VansPod。");
151
+ off("VansPod 無法連上遠端 Agent 的轉送站(連線資料不正確),請更新 VansPod。");
145
152
  return;
146
153
  }
147
154
  if (event.code === REPLACED) {
@@ -162,5 +169,9 @@ function createDeviceConnection(options) {
162
169
  },
163
170
  stop() { off(); },
164
171
  status() { return { ...current }; },
172
+ subscribe(listener) {
173
+ listeners.add(listener);
174
+ return () => { listeners.delete(listener); };
175
+ },
165
176
  };
166
177
  }
package/dist/html.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.escapeHtml = escapeHtml;
4
+ /** Escapes text for HTML text and attribute values. */
5
+ function escapeHtml(value) {
6
+ return value
7
+ .replaceAll("&", "&amp;")
8
+ .replaceAll("<", "&lt;")
9
+ .replaceAll(">", "&gt;")
10
+ .replaceAll('"', "&quot;")
11
+ .replaceAll("'", "&#39;");
12
+ }
@@ -4,11 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.MAX_OUTPUT_CHARS = exports.BASH_TIMEOUT_MS = void 0;
7
- exports.createCommandLog = createCommandLog;
7
+ exports.runBashCommand = runBashCommand;
8
8
  exports.bashTool = bashTool;
9
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.
10
+ // Local Tool Approval. The Remote Agent Log keeps each call and can stop a running command.
12
11
  const node_child_process_1 = require("node:child_process");
13
12
  const node_fs_1 = require("node:fs");
14
13
  const node_os_1 = __importDefault(require("node:os"));
@@ -21,8 +20,6 @@ exports.BASH_TIMEOUT_MS = 60_000;
21
20
  exports.MAX_OUTPUT_CHARS = 30_000;
22
21
  // A UTF-8 character has at most 4 bytes. Keep this many bytes from the start and from the end.
23
22
  const KEEP_BYTES = exports.MAX_OUTPUT_CHARS * 4;
24
- /** The Command Log keeps the newest commands only. */
25
- const MAX_RECORDS = 200;
26
23
  function collector() {
27
24
  return { head: [], headBytes: 0, tail: [], tailBytes: 0, total: 0 };
28
25
  }
@@ -91,120 +88,86 @@ function stopProcesses(bash, child, pidFile) {
91
88
  .on("error", () => (0, commandRunner_1.killTree)(child))
92
89
  .on("exit", () => (0, commandRunner_1.killTree)(child));
93
90
  }
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
- };
91
+ let nextRun = 0;
92
+ /**
93
+ * Runs one approved command and answers what the Agent receives. `stoppable` gets the function
94
+ * that stops the command as soon as it runs; `ended` hears how it ended, before the answer.
95
+ */
96
+ async function runBashCommand(bash, command, folder, signal, options) {
97
+ const timeoutMs = options.timeoutMs;
98
+ const env = await (0, systemPath_1.envWithRegistryPath)();
99
+ // From here to the spawn nothing waits, so a listed running command can always be stopped.
100
+ const stdout = collector();
101
+ const stderr = collector();
102
+ const ended = await new Promise(resolve => {
103
+ let why;
104
+ let settled = false;
105
+ // The command and the pid file go in the environment, so no Windows argument quoting or globbing changes them.
106
+ const pidFile = node_path_1.default.join(node_os_1.default.tmpdir(), `vanspod-bash-${process.pid}-${++nextRun}.pid`);
107
+ const child = (0, node_child_process_1.spawn)(bash, ["-c", RUN_SCRIPT], {
108
+ cwd: folder,
109
+ env: { ...env, VANSPOD_BASH_COMMAND: command, VANSPOD_BASH_PID_FILE: pidFile },
110
+ windowsHide: true,
111
+ stdio: ["ignore", "pipe", "pipe"],
112
+ });
113
+ const finish = (result) => {
114
+ if (settled)
115
+ return;
116
+ settled = true;
117
+ clearTimeout(timer);
118
+ signal.removeEventListener("abort", onCancel);
119
+ (0, node_fs_1.rmSync)(pidFile, { force: true });
120
+ resolve({ ...result, ...(why ? { why } : {}) });
121
+ };
122
+ const end = (reason) => {
123
+ if (why || settled)
124
+ return;
125
+ why = reason;
126
+ stopProcesses(bash, child, pidFile);
127
+ // A grandchild can hold the pipes open; do not wait for it forever.
128
+ setTimeout(() => finish({}), 3_000).unref();
129
+ };
130
+ const timer = setTimeout(() => end("timed_out"), timeoutMs);
131
+ const onCancel = () => end("cancelled");
132
+ signal.addEventListener("abort", onCancel, { once: true });
133
+ if (signal.aborted)
134
+ onCancel();
135
+ child.stdout.on("data", (chunk) => collect(stdout, chunk));
136
+ child.stderr.on("data", (chunk) => collect(stderr, chunk));
137
+ child.on("error", error => finish({ error: error.message }));
138
+ child.on("close", code => finish(code === null ? {} : { code }));
139
+ options.stoppable(() => end("stopped"));
140
+ });
141
+ if (ended.error) {
142
+ options.ended({});
143
+ return { ok: false, error: "failed", message: `VansPod 無法啟動 Git Bash:${ended.error}。` };
144
+ }
145
+ options.ended(!ended.why && ended.code !== undefined ? { exitCode: ended.code } : {});
146
+ const output = shareOutput(streamText(stdout), streamText(stderr));
147
+ const result = { exit_code: ended.why ? null : ended.code ?? null, stdout: output.stdout, stderr: output.stderr };
148
+ const notes = [];
149
+ if (ended.why === "timed_out") {
150
+ result.timed_out = true;
151
+ notes.push(`指令執行超過 ${Math.round(timeoutMs / 1000)} 秒,VansPod 已停止它。下面是停止前的輸出。`);
152
+ }
153
+ if (ended.why === "stopped") {
154
+ result.stopped = true;
155
+ notes.push("學生在 VansPod 頁面停止了這個指令。下面是停止前的輸出。");
156
+ }
157
+ if (ended.why === "cancelled") {
158
+ result.stopped = true;
159
+ notes.push("這個呼叫已被取消,VansPod 已停止這個指令。");
160
+ }
161
+ if (output.truncated) {
162
+ result.truncated = true;
163
+ notes.push(`輸出太長,只回傳開頭和結尾,共約 ${exports.MAX_OUTPUT_CHARS.toLocaleString("en-US")} 個字元。`);
164
+ }
165
+ if (notes.length > 0)
166
+ result.note = notes.join(" ");
167
+ return { ok: true, result };
205
168
  }
206
169
  const NOT_RUN = "沒有執行";
207
- /** The `bash` Local Tool. `gitBash` finds Git Bash; `commands` runs and records the command. */
170
+ /** The `bash` Local Tool. The log entry of the call runs the command, so the page can stop it. */
208
171
  async function bashTool(projectFolder, args, signal, context) {
209
172
  if (typeof args.command !== "string" || args.command.trim() === "") {
210
173
  return { ok: false, error: "invalid_arguments", message: "command 必須是要在 Git Bash 執行的指令。" };
@@ -214,8 +177,8 @@ async function bashTool(projectFolder, args, signal, context) {
214
177
  if (!bash) {
215
178
  return { ok: false, error: "failed", message: `這台電腦找不到 Git Bash,${NOT_RUN}。請學生在 VansPod 的「環境安裝」安裝 Git。` };
216
179
  }
217
- const refusal = await (0, localToolApproval_1.askApproval)(context.approver, { tool: "bash", title: "在 Git Bash 執行指令", body: command, folder: projectFolder }, signal, NOT_RUN);
180
+ const refusal = await (0, localToolApproval_1.askApproval)(context.approver, { tool: "bash", title: "在 Git Bash 執行指令", body: command, target: command, folder: projectFolder }, signal, NOT_RUN);
218
181
  if (refusal)
219
182
  return refusal;
220
- return context.commands.run(bash, command, projectFolder, signal);
183
+ return context.call.runBash(bash, command, projectFolder, signal);
221
184
  }
@@ -1,26 +1,69 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APPROVAL_TIMEOUT_MS = void 0;
3
+ exports.APPROVAL_TIMEOUT_MS = exports.AUTO_APPROVAL_EXCEPTION_LABELS = void 0;
4
4
  exports.askApproval = askApproval;
5
5
  exports.approvalRefusal = approvalRefusal;
6
+ exports.autoApprovalException = autoApprovalException;
6
7
  exports.createApprovalQueue = createApprovalQueue;
8
+ const projectPath_1 = require("./projectPath");
7
9
  /**
8
10
  * Asks `approver` and turns anything but approval into the reply for the agent.
9
11
  * `notDone` says what did not happen, for example "沒有寫入檔案".
10
12
  */
11
13
  async function askApproval(approver, request, signal, notDone) {
12
14
  const outcome = await approver.request(request, signal);
13
- return outcome === "approved" ? undefined : approvalRefusal(outcome, notDone);
15
+ return outcome === "approved" || outcome === "auto" ? undefined : approvalRefusal(outcome, notDone);
14
16
  }
15
17
  function approvalRefusal(outcome, notDone) {
16
18
  if (outcome === "timeout")
17
19
  return { ok: false, error: "approval_timeout", message: `學生在 ${exports.APPROVAL_TIMEOUT_MS / 60_000} 分鐘內沒有決定,${notDone}。` };
18
20
  if (outcome === "access_off")
19
- return { ok: false, error: "denied", message: `學生關閉了「讓 Agent Builder 使用這台電腦」,${notDone}。` };
21
+ return { ok: false, error: "denied", message: `學生關閉了「允許 Agent 使用這台電腦」,${notDone}。` };
20
22
  if (outcome === "cancelled")
21
23
  return { ok: false, error: "denied", message: `這個呼叫已被取消,${notDone}。` };
22
24
  return { ok: false, error: "denied", message: `學生拒絕了,${notDone}。` };
23
25
  }
26
+ exports.AUTO_APPROVAL_EXCEPTION_LABELS = {
27
+ secret_file: "碰到機密檔案",
28
+ delete_outside: "刪除專案資料夾以外的檔案",
29
+ };
30
+ // The words of a command, split at spaces, quotes and shell punctuation.
31
+ const commandWords = (command) => command.split(/[\s'"`=<>|;&()]+/).filter(Boolean);
32
+ // A target outside the Project Folder: absolute, the home folder, the parent folder, or a drive letter.
33
+ const OUTSIDE_TARGET = /^(\/|~|\$HOME\b|\$\{HOME\}|\.\.|[A-Za-z]:)/;
34
+ // The parts of a command that run on their own: split at `;`, `&&`, `||`, `|`, `&`, line ends, `( )`, `$(` and backquotes.
35
+ const COMMAND_BREAKS = /&&|\|\||\$\(|[;|&\n()`]/;
36
+ // `rm` as a command word, also with a path such as `/bin/rm`.
37
+ const isRm = (word) => word === "rm" || word.endsWith("/rm");
38
+ // An `rm` anywhere in the command, also inside `bash -c "..."`, `$( )` or after `xargs`, with -r/-f and a target outside.
39
+ function deletesOutside(command) {
40
+ for (const part of command.split(COMMAND_BREAKS)) {
41
+ const words = part.replace(/["']/g, " ").trim().split(/\s+/);
42
+ const at = words.findIndex(isRm);
43
+ if (at < 0)
44
+ continue;
45
+ const rest = words.slice(at + 1);
46
+ const forced = rest.some(word => word === "--recursive" || word === "--force" || /^-[^-]*[rRf]/.test(word));
47
+ if (forced && rest.some(word => !word.startsWith("-") && OUTSIDE_TARGET.test(word)))
48
+ return true;
49
+ }
50
+ return false;
51
+ }
52
+ /**
53
+ * The Auto Approval Exception of a request, or undefined. The rules match text, so they catch only clear cases (ADR 0014).
54
+ * The Secret File check is the one that `read_file` uses: the file name, and for `write_file` also a private key in the text.
55
+ */
56
+ function autoApprovalException(request) {
57
+ if (request.tool === "write_file") {
58
+ const secret = (0, projectPath_1.isSecretFileName)(request.target) || (request.contents ?? []).some(projectPath_1.hasPrivateKey);
59
+ return secret ? "secret_file" : undefined;
60
+ }
61
+ if (request.tool !== "bash")
62
+ return undefined;
63
+ if (commandWords(request.target).some(projectPath_1.isSecretFileName))
64
+ return "secret_file";
65
+ return deletesOutside(request.target) ? "delete_outside" : undefined;
66
+ }
24
67
  /** The default time limit, from when an approval is shown (ADR 0013). */
25
68
  exports.APPROVAL_TIMEOUT_MS = 120_000;
26
69
  function createApprovalQueue(options = {}) {
@@ -29,6 +72,8 @@ function createApprovalQueue(options = {}) {
29
72
  const listeners = new Set();
30
73
  let shown;
31
74
  let timer;
75
+ let auto;
76
+ let autoTimer;
32
77
  let nextId = 0;
33
78
  const snapshot = () => shown && { ...shown, waiting: entries.length - 1 };
34
79
  const notify = () => {
@@ -45,7 +90,7 @@ function createApprovalQueue(options = {}) {
45
90
  if (!shown && entries.length > 0) {
46
91
  const first = entries[0];
47
92
  const shownAt = Date.now();
48
- shown = { id: first.id, request: first.request, shownAt, expiresAt: shownAt + timeoutMs, waiting: 0 };
93
+ shown = { id: first.id, request: first.request, ...(first.exception ? { exception: first.exception } : {}), shownAt, expiresAt: shownAt + timeoutMs, waiting: 0 };
49
94
  timer = setTimeout(() => end(first.id, "timeout"), timeoutMs);
50
95
  changed = true;
51
96
  }
@@ -69,10 +114,23 @@ function createApprovalQueue(options = {}) {
69
114
  showNext(wasShown);
70
115
  return true;
71
116
  };
117
+ /** Ends Auto Approval. True when it was on. */
118
+ const endAuto = () => {
119
+ if (!auto)
120
+ return false;
121
+ auto = undefined;
122
+ if (autoTimer)
123
+ clearTimeout(autoTimer);
124
+ autoTimer = undefined;
125
+ return true;
126
+ };
72
127
  return {
73
128
  request(request, signal) {
74
129
  if (signal?.aborted)
75
130
  return Promise.resolve("cancelled");
131
+ const exception = autoApprovalException(request);
132
+ if (auto && !exception)
133
+ return Promise.resolve("auto");
76
134
  return new Promise(resolve => {
77
135
  const id = `approval-${++nextId}`;
78
136
  const onAbort = () => end(id, "cancelled");
@@ -80,6 +138,7 @@ function createApprovalQueue(options = {}) {
80
138
  entries.push({
81
139
  id,
82
140
  request,
141
+ ...(exception ? { exception } : {}),
83
142
  settle(outcome) { signal?.removeEventListener("abort", onAbort); resolve(outcome); },
84
143
  });
85
144
  // A new waiting approval changes the count that the shown one carries.
@@ -93,9 +152,27 @@ function createApprovalQueue(options = {}) {
93
152
  return end(id, decision === "approve" ? "approved" : "denied");
94
153
  },
95
154
  denyAll() {
155
+ const changed = endAuto();
96
156
  for (const entry of [...entries].reverse())
97
157
  end(entry.id, "access_off");
158
+ if (changed)
159
+ notify();
160
+ },
161
+ startAutoApproval(durationMs) {
162
+ endAuto();
163
+ auto = durationMs === undefined ? {} : { endsAt: Date.now() + durationMs };
164
+ if (durationMs !== undefined)
165
+ autoTimer = setTimeout(() => { if (endAuto())
166
+ notify(); }, durationMs);
167
+ for (const entry of entries.filter(entry => !entry.exception))
168
+ end(entry.id, "auto");
169
+ notify();
170
+ },
171
+ stopAutoApproval() {
172
+ if (endAuto())
173
+ notify();
98
174
  },
175
+ autoApproval: () => auto && { ...auto },
99
176
  subscribe(listener) {
100
177
  listeners.add(listener);
101
178
  return () => { listeners.delete(listener); };