vanspod 0.1.3 → 0.3.0

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.1.3.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.3.0.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`。
48
48
 
49
- 發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.1.3` 為例:
49
+ 發版前同步 `package.json`、`package-lock.json` 與 `src/version.ts` 的版本;tag 必須等於 `v` 加版本號,否則流程失敗。以 `0.3.0` 為例:
50
50
 
51
51
  ```powershell
52
52
  git push origin master
53
- git tag -a v0.1.3 -m "VansPod 0.1.3"
54
- git push origin v0.1.3
53
+ git tag -a v0.3.0 -m "VansPod 0.3.0"
54
+ git push origin v0.3.0
55
55
  ```
56
56
 
57
57
  新版本使用新的版本號與 tag。相同 tag 的 Actions 重跑會更新該 Release 的產物。
@@ -4,12 +4,16 @@ exports.upstreamRequest = upstreamRequest;
4
4
  exports.jsonResponse = jsonResponse;
5
5
  const types_1 = require("./types");
6
6
  async function upstreamRequest(request, path, body, extraHeaders = {}) {
7
+ const markFailed = request.record?.(path, body);
7
8
  const controller = new AbortController();
8
9
  const response = await fetch(`${request.routerBaseUrl.replace(/\/+$/, "")}${path}`, {
9
10
  method: "POST", signal: AbortSignal.any([request.signal, controller.signal]),
10
11
  headers: { ...extraHeaders, "Content-Type": "application/json", Authorization: `Bearer ${request.apiKey}` },
11
12
  body: JSON.stringify(body),
12
13
  });
14
+ // Prompt Capture keeps the failing status only, never Router's error body.
15
+ if (!response.ok)
16
+ markFailed?.(response.status);
13
17
  if (response.ok && body.stream === true && !response.headers.get("content-type")?.includes("text/event-stream")) {
14
18
  controller.abort();
15
19
  throw new types_1.AdapterError("上游沒有回傳所要求的 SSE 串流。", 502);
@@ -93,6 +93,7 @@ class SearchLoop {
93
93
  asked = 0;
94
94
  searches = 0;
95
95
  turnsWithoutTools = 0;
96
+ askedModel = false;
96
97
  constructor(adapter, request) {
97
98
  this.adapter = adapter;
98
99
  this.request = request;
@@ -104,10 +105,14 @@ class SearchLoop {
104
105
  // With its searches used up the model is asked with tool calls switched off, so it
105
106
  // has to answer. One that asks again is refused without a search; twice ends the reply.
106
107
  askModel() {
108
+ // Prompt Capture marks every request after the first as a Web Search follow-up.
109
+ const record = this.request.record, first = !this.askedModel;
110
+ const request = { ...this.request, record: record && !first ? (path, body) => record(path, body, { webSearchFollowUp: true }) : record };
111
+ this.askedModel = true;
107
112
  if (this.asked < this.limit)
108
- return this.adapter.send({ ...this.request, body: { ...this.body, messages: this.messages } });
113
+ return this.adapter.send({ ...request, body: { ...this.body, messages: this.messages } });
109
114
  this.turnsWithoutTools++;
110
- return this.adapter.send({ ...this.request, body: { ...this.body, messages: this.messages, tool_choice: { type: "none" } } });
115
+ return this.adapter.send({ ...request, body: { ...this.body, messages: this.messages, tool_choice: { type: "none" } } });
111
116
  }
112
117
  async answerSearch(call) {
113
118
  if (this.asked++ >= this.limit)
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.connectionMascotScript = exports.connectionMascotStyles = exports.connectionMascot = void 0;
4
+ exports.patrolKeyframes = patrolKeyframes;
5
+ exports.fittedPatrol = fittedPatrol;
4
6
  /** Keep the original brand artwork; animate its layers in the browser. */
5
7
  exports.connectionMascot = `<div class="connection-mascot">
6
8
  <div class="mascot-traveler">
@@ -48,30 +50,65 @@ exports.connectionMascot = `<div class="connection-mascot">
48
50
  </div>
49
51
  <button type="button" class="mascot-pause" aria-label="暫停法鬥超人動畫" aria-pressed="false" title="暫停動畫"><svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M8 5v14M16 5v14" fill="none" stroke="currentColor" stroke-width="2"/></svg></button>
50
52
  </div>`;
51
- // One lap: centre → left (6s), rest (6s), right (12s), rest (6s), centre (6s).
52
- // Both feet settle at each edge; no stepping in place during the rests.
53
- function footstepKeyframes(name, direction) {
54
- const frames = [];
55
- for (const [start, end] of [[0, 6], [12, 24], [30, 36]]) {
56
- for (let time = start; time <= end; time += 0.5) {
57
- const phase = (time - start) % 1;
58
- const angle = time === start || time === end ? 0 : (phase === 0.5 ? -5 : 5) * direction;
59
- frames.push(`${time / 36 * 100}% { transform: translateY(${angle < 0 ? -6 : 0}px) rotate(${angle}deg); }`);
53
+ /**
54
+ * One lap: centre → left, rest (6s), right, rest (6s), centre. At scale 1 the
55
+ * walks take 6s, 12s and 6s (a 36s lap) across the 教室設定 card; a wider lane
56
+ * passes a larger scale so the walks stretch while the pace, the step cadence
57
+ * and the rests stay the same. Both feet settle at each edge; no stepping in
58
+ * place during the rests. Self-contained: the inspector page injects its
59
+ * source to refit the lap to the lane's width.
60
+ */
61
+ function patrolKeyframes(suffix, scale) {
62
+ const reachLeft = 6 * scale, leaveLeft = reachLeft + 6;
63
+ const reachRight = leaveLeft + 12 * scale, leaveRight = reachRight + 6;
64
+ const lap = leaveRight + 6 * scale;
65
+ // 152px = the traveler's 136px width plus its 8px inset on each side.
66
+ const at = (time) => `${Number((time / lap * 100).toFixed(6))}%`;
67
+ const feet = (name, direction) => {
68
+ const frames = [];
69
+ for (const [start, end] of [[0, reachLeft], [leaveLeft, reachRight], [leaveRight, lap]]) {
70
+ const steps = Math.floor((end - start) / 0.5 + 0.001);
71
+ for (let step = 0; step <= steps; step++) {
72
+ const time = start + step * 0.5;
73
+ const edge = step === 0 || end - time < 0.001;
74
+ const angle = edge ? 0 : (step % 2 === 1 ? -5 : 5) * direction;
75
+ frames.push(`${at(time)} { transform: translateY(${angle < 0 ? -6 : 0}px) rotate(${angle}deg); }`);
76
+ }
77
+ if (end - (start + steps * 0.5) >= 0.001)
78
+ frames.push(`${at(end)} { transform: translateY(0px) rotate(0deg); }`);
60
79
  }
61
- }
62
- return `@keyframes ${name} { ${frames.join("\n")} }`;
80
+ return `@keyframes ${name}${suffix} { ${frames.join("\n")} }`;
81
+ };
82
+ const css = `@keyframes mascot-walk${suffix} {
83
+ 0%, 100% { transform: translateX(max(0px, calc((100cqw - 152px) / 2))); }
84
+ ${at(reachLeft)}, ${at(leaveLeft)} { transform: translateX(0); }
85
+ ${at(reachRight)}, ${at(leaveRight)} { transform: translateX(max(0px, calc(100cqw - 152px))); }
86
+ }
87
+ @keyframes mascot-turn${suffix} {
88
+ 0% { transform: scaleX(1); }
89
+ ${at(reachLeft)} { transform: scaleX(-1); }
90
+ ${at(reachRight)}, 100% { transform: scaleX(1); }
91
+ }
92
+ ${feet("mascot-left-step", 1)}
93
+ ${feet("mascot-right-step", -1)}`;
94
+ return { lap, marks: [0, reachLeft, leaveLeft, reachRight, leaveRight, lap], css };
63
95
  }
96
+ const BASE_PATROL = patrolKeyframes("", 1);
97
+ /** The 教室設定 card's lane is 356px wide: the base lap walks 204px each way. */
98
+ const BASE_LANE = 356;
99
+ const TRAVELER_SPAN = 152;
64
100
  exports.connectionMascotStyles = `
65
101
  .settings-card[data-setting="連線"]:has(.connection-mascot) { row-gap: 0; }
66
102
  .settings-card[data-setting="連線"]:has(.connection-mascot) .settings-content { padding-top: 16px; }
67
103
  .settings-card[data-setting="連線"]:has(.connection-mascot) .connection-feedback { order: -1; }
68
104
  .connection-mascot { position: relative; flex: 1 0 144px; width: 100%; min-height: 144px; overflow: hidden; container-type: inline-size; }
69
105
  /* Compensate for the PNG's transparent space below the soles. */
70
- .mascot-traveler { position: absolute; bottom: -4px; left: 8px; width: 136px; max-width: calc(100% - 16px); animation: mascot-walk 36s linear 780ms infinite both; }
71
- .mascot-facing { display: block; animation: mascot-turn 36s linear 780ms infinite; }
72
- .mascot-logo { transform-origin: 440.5px 664.5px; animation: mascot-turn 36s linear 780ms infinite; }
73
- .mascot-left-foot { transform-origin: 322px 915px; animation: mascot-left-step 36s linear 780ms infinite; }
74
- .mascot-right-foot { transform-origin: 580px 927px; animation: mascot-right-step 36s linear 780ms infinite; }
106
+ .mascot-traveler { position: absolute; bottom: -4px; left: 8px; width: 136px; max-width: calc(100% - 16px); animation: mascot-walk ${BASE_PATROL.lap}s linear 780ms infinite both; }
107
+ /* 走到端點直接換邊,不播翻面過渡。 */
108
+ .mascot-facing { display: block; animation: mascot-turn ${BASE_PATROL.lap}s step-end 780ms infinite; }
109
+ .mascot-logo { transform-origin: 440.5px 664.5px; animation: mascot-turn ${BASE_PATROL.lap}s step-end 780ms infinite; }
110
+ .mascot-left-foot { transform-origin: 322px 915px; animation: mascot-left-step ${BASE_PATROL.lap}s linear 780ms infinite; }
111
+ .mascot-right-foot { transform-origin: 580px 927px; animation: mascot-right-step ${BASE_PATROL.lap}s linear 780ms infinite; }
75
112
  .mascot-waiting { flex-basis: 164px; min-height: 164px; padding: 12px 148px 32px 0; }
76
113
  .mascot-waiting .mascot-traveler { left: auto; right: 8px; transform: none; }
77
114
  .mascot-waiting .mascot-traveler, .mascot-waiting .mascot-facing, .mascot-waiting .mascot-logo, .mascot-waiting .mascot-foot, .mascot-waiting .mascot-arrival { animation: none; }
@@ -118,18 +155,7 @@ exports.connectionMascotStyles = `
118
155
  0%, 42%, 85%, 90%, 100% { opacity: 0; }
119
156
  40%, 83%, 88% { opacity: 1; }
120
157
  }
121
- @keyframes mascot-walk {
122
- 0%, 100% { transform: translateX(max(0px, calc((100cqw - 152px) / 2))); }
123
- 16.666667%, 33.333333% { transform: translateX(0); }
124
- 66.666667%, 83.333333% { transform: translateX(max(0px, calc(100cqw - 152px))); }
125
- }
126
- @keyframes mascot-turn {
127
- 0%, 16.666667% { transform: scaleX(1); }
128
- 18%, 66.666667% { transform: scaleX(-1); }
129
- 68%, 100% { transform: scaleX(1); }
130
- }
131
- ${footstepKeyframes("mascot-left-step", 1)}
132
- ${footstepKeyframes("mascot-right-step", -1)}
158
+ ${BASE_PATROL.css}
133
159
  @media (prefers-reduced-motion: reduce) {
134
160
  .mascot-arrival, .mascot-idle, .mascot-cape, .mascot-blink, .mascot-traveler, .mascot-facing, .mascot-logo, .mascot-foot { animation: none; }
135
161
  .mascot-traveler { left: 50%; transform: translateX(-50%); }
@@ -233,3 +259,52 @@ exports.connectionMascotScript = `
233
259
  ], { duration: reduced ? 180 : 600, easing: 'ease-out' });
234
260
  });
235
261
  `;
262
+ /**
263
+ * A lane of any width: the page script rewrites the "-fit" keyframes for the
264
+ * lane's measured width, so 法鬥超人 walks at the 教室設定 card's pace instead of
265
+ * covering a longer (or shorter) lane in the same lap. Use all three parts.
266
+ */
267
+ function fittedPatrol(scope) {
268
+ const lap = `var(--patrol-lap, ${BASE_PATROL.lap}s)`;
269
+ const styles = `
270
+ @media (prefers-reduced-motion: no-preference) {
271
+ ${scope} .mascot-traveler { animation-name: mascot-walk-fit; animation-duration: ${lap}; }
272
+ ${scope} .mascot-facing, ${scope} .mascot-logo { animation-name: mascot-turn-fit; animation-duration: ${lap}; }
273
+ ${scope} .mascot-left-foot { animation-name: mascot-left-step-fit; animation-duration: ${lap}; }
274
+ ${scope} .mascot-right-foot { animation-name: mascot-right-step-fit; animation-duration: ${lap}; }
275
+ }`;
276
+ const sheet = `<style id="mascot-patrol-fit">${patrolKeyframes("-fit", 1).css}</style>`;
277
+ const script = `(function () {
278
+ ${patrolKeyframes.toString()}
279
+ var stage = document.querySelector(${JSON.stringify(`${scope} .connection-mascot`)});
280
+ var sheet = document.getElementById("mascot-patrol-fit");
281
+ if (!stage || !sheet || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
282
+ var DELAY = 780;
283
+ var applied = Object.assign({ scale: 1 }, patrolKeyframes("-fit", 1));
284
+ // Same leg, same share of it: a refit keeps 法鬥超人 where he was instead of jumping.
285
+ function remap(time, from, to) {
286
+ var leg = 0;
287
+ while (leg < from.length - 2 && time >= from[leg + 1]) leg++;
288
+ var share = (time - from[leg]) / (from[leg + 1] - from[leg]);
289
+ return to[leg] + share * (to[leg + 1] - to[leg]);
290
+ }
291
+ function fit() {
292
+ var scale = Math.max(0.25, (stage.clientWidth - ${TRAVELER_SPAN}) / ${BASE_LANE - TRAVELER_SPAN});
293
+ if (Math.abs(scale - applied.scale) < 0.01) return;
294
+ var patrol = patrolKeyframes("-fit", scale);
295
+ var walking = stage.getAnimations({ subtree: true }).filter(function (animation) {
296
+ return /-fit$/.test(animation.animationName) && animation.currentTime >= DELAY;
297
+ }).map(function (animation) {
298
+ return { animation: animation, time: ((animation.currentTime - DELAY) / 1000) % applied.lap };
299
+ });
300
+ sheet.textContent = patrol.css;
301
+ stage.style.setProperty("--patrol-lap", patrol.lap + "s");
302
+ walking.forEach(function (entry) { entry.animation.currentTime = DELAY + remap(entry.time, applied.marks, patrol.marks) * 1000; });
303
+ applied = Object.assign({ scale: scale }, patrol);
304
+ }
305
+ fit();
306
+ var settle;
307
+ new ResizeObserver(function () { clearTimeout(settle); settle = setTimeout(fit, 150); }).observe(stage);
308
+ })();`;
309
+ return { styles, sheet, script };
310
+ }
package/dist/desktop.js CHANGED
@@ -5,6 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.openBrowser = openBrowser;
7
7
  exports.asset = asset;
8
+ exports.writeTool = writeTool;
9
+ exports.startHiddenTool = startHiddenTool;
8
10
  const node_child_process_1 = require("node:child_process");
9
11
  const node_sea_1 = require("node:sea");
10
12
  const promises_1 = __importDefault(require("node:fs/promises"));
@@ -23,3 +25,23 @@ function asset(name) {
23
25
  ? Promise.resolve(Buffer.from((0, node_sea_1.getAsset)(name)))
24
26
  : promises_1.default.readFile(node_path_1.default.join(__dirname, "..", name.startsWith("brand-") || name.startsWith("fadou-superhero") ? "media" : "scripts", name));
25
27
  }
28
+ /** 把內嵌的 PowerShell 工具寫到磁碟;Windows PowerShell 5.1 需要 BOM 才會以 UTF-8 讀中文。 */
29
+ async function writeTool(file, name) {
30
+ await promises_1.default.writeFile(file, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), await asset(name)]));
31
+ }
32
+ /** 啟動一個在 VansPod 結束後仍會繼續執行的 PowerShell 工具,等它寫出 ready 檔才返回。 */
33
+ async function startHiddenTool(script, plan, ready, name) {
34
+ await promises_1.default.rm(ready, { force: true });
35
+ // Start-Process gives the helper its own hidden console. A PowerShell child
36
+ // attached to the worker's console would die when that worker exits.
37
+ const literal = (value) => `'${value.replaceAll("'", "''")}'`;
38
+ const command = `Start-Process -FilePath powershell.exe -WindowStyle Hidden -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ${literal(`"${script}"`)}, '-Plan', ${literal(`"${plan}"`)})`;
39
+ const child = (0, node_child_process_1.spawn)("powershell.exe", ["-NoProfile", "-EncodedCommand", Buffer.from(command, "utf16le").toString("base64")], { windowsHide: true, stdio: "ignore" });
40
+ await new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", code => code === 0 ? resolve() : reject(new Error(`無法啟動${name}。`))); });
41
+ for (let attempt = 0; attempt < 100; attempt++) {
42
+ if (await promises_1.default.stat(ready).catch(() => undefined))
43
+ return;
44
+ await new Promise(resolve => setTimeout(resolve, 100));
45
+ }
46
+ throw new Error(`${name}未回應,請重試。`);
47
+ }
package/dist/exitGuard.js CHANGED
@@ -10,7 +10,7 @@ function exitDecision(action, work, confirmed) {
10
10
  ];
11
11
  if (!running.length || confirmed)
12
12
  return { proceed: true };
13
- return { proceed: false, message: `${running.join("、")},確認中止並${action === "stop" ? "結束" : "移除"} VansPod?` };
13
+ return { proceed: false, message: `${running.join("、")},確認中止並${{ stop: "結束", uninstall: "移除", update: "更新" }[action]} VansPod?` };
14
14
  }
15
15
  function removalInterruptions(work) {
16
16
  return `${work.installing ? "\n安裝仍在執行,移除前將中止安裝。" : ""}${work.activeRequests ? "\n仍有模型回答,移除將中斷目前回答。" : ""}`;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INSPECTOR_STYLES = void 0;
4
+ exports.inspectorBody = inspectorBody;
5
+ exports.inspectorScript = inspectorScript;
6
+ function inspectorBody(list, state) {
7
+ const esc = (value) => String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
8
+ const fmt = (value) => value.toLocaleString("en-US");
9
+ const segments = [
10
+ { key: "system", label: "System" }, { key: "tools", label: "Tools" }, { key: "reminder", label: "Skill/提醒" },
11
+ { key: "history", label: "先前對話" }, { key: "fresh", label: "本輪新增" },
12
+ ];
13
+ const clients = { claude: "Claude Code", codex: "Codex", copilot: "VS Code Chat" };
14
+ const protocols = { messages: "Messages", responses: "Responses", chat: "Chat Completions" };
15
+ const clientName = (one) => clients[one.client] ?? one.client;
16
+ const highlight = (text) => esc(text).replace(/&lt;system-reminder&gt;[\s\S]*?&lt;\/system-reminder&gt;/g, match => `<mark class="pi-skill">${match}</mark>`);
17
+ const stack = (one) => `<div class="pi-stack" role="img" aria-label="各區塊大小">${segments.map(segment => {
18
+ const size = one.sizes[segment.key];
19
+ return size ? `<span class="pi-seg" data-seg="${segment.key}" style="width:${(size / one.total) * 100}%" title="${segment.label} 約 ${fmt(size)} tokens"></span>` : "";
20
+ }).join("")}</div>`;
21
+ const summary = (one) => {
22
+ const last = one.messages.filter(message => message.isNew && !message.reminder).slice(-1)[0];
23
+ return last ? (last.kind === "tool_use" ? `呼叫 ${last.name ?? ""}` : last.text.replace(/\s+/g, " ").slice(0, 120)) : "";
24
+ };
25
+ const tags = (one) => (one.failedStatus !== undefined ? `<span class="pi-tag pi-failed">失敗 HTTP ${one.failedStatus}</span>` : "")
26
+ + (one.webSearchFollowUp ? `<span class="pi-tag">Web Search 追加</span>` : "");
27
+ if (!list.captures.length)
28
+ return `<section class="tile pi-empty"><p class="hint">切到「課堂」並開始錄製後,送出的 prompt 會出現在這裡。</p></section>`;
29
+ const current = list.captures.find(one => one.id === state.selected) ?? list.captures[0];
30
+ const items = list.captures.map(one => `<button type="button" class="pi-req${one === current ? " on" : ""}" data-pick="${one.id}">`
31
+ + `<span class="pi-req-top"><strong>#${one.id} ${esc(clientName(one))}</strong>${one.newConversation ? `<em class="pi-newconv">新對話</em>` : ""}<span>${esc(one.time)}</span></span>`
32
+ + `<span class="pi-req-model">${esc(one.model || "(未指定模型)")}</span>`
33
+ + (tags(one) ? `<span class="pi-tags">${tags(one)}</span>` : "")
34
+ + `<span class="pi-req-sub">${esc(summary(one))}</span>${stack(one)}</button>`).join("");
35
+ const dropped = list.dropped ? `<p class="hint pi-dropped">較早的 ${list.dropped} 筆已捨去</p>` : "";
36
+ const legend = `<ul class="pi-legend">${segments.map(segment => `<li><span class="pi-dot" data-seg="${segment.key}"></span>${segment.label}<b>${current.total ? Math.round((current.sizes[segment.key] / current.total) * 100) : 0}%</b></li>`).join("")}</ul>`;
37
+ const meta = `<p class="pi-meta">${esc(clientName(current))} · ${esc(current.model || "(未指定模型)")} · ${esc(protocols[current.protocol] ?? current.protocol)} · ${esc(current.adapter)} adapter · 約 ${fmt(current.total)} tokens(估算)</p>`;
38
+ const tool = (item) => `<details class="pi-tool${item.name === "Skill" ? " is-skill" : ""}"><summary><code>${esc(item.name)}</code><span>${esc(item.description.split(/(?<=[.。])\s/)[0])}</span></summary>`
39
+ + `<pre>${esc(item.description)}</pre><pre class="pi-schema">${esc(JSON.stringify(item.schema ?? {}, null, 2))}</pre></details>`;
40
+ const message = (item) => {
41
+ const head = item.kind === "tool_use" ? `Assistant 呼叫工具 <code>${esc(item.name ?? "")}</code>`
42
+ : item.kind === "tool_result" ? `Tool 結果${item.name ? ` <code>${esc(item.name)}</code>` : ""}`
43
+ : item.reminder ? "User(客戶端自動附加)" : item.role === "assistant" ? "Assistant" : "User";
44
+ const classes = `pi-msg role-${item.role}${item.reminder ? " is-reminder" : ""}${item.kind === "tool_use" ? " kind-call" : ""}${item.isNew ? " is-new" : ""}`;
45
+ const tag = item.isNew && !item.reminder ? `<span class="pi-new">本輪新增</span>` : "";
46
+ return `<div class="${classes}"><div class="pi-msg-head"><span>${head}</span>${tag}</div><pre>${highlight(item.text)}</pre></div>`;
47
+ };
48
+ const talkSize = current.sizes.reminder + current.sizes.history + current.sizes.fresh;
49
+ const sections = `<details class="pi-sec" data-sec="system" open><summary><span class="pi-dot" data-seg="system"></span>System<span class="pi-count">約 ${fmt(current.sizes.system)} tokens</span></summary>`
50
+ + (current.system.length ? current.system.map(text => `<pre>${highlight(text)}</pre>`).join("") : `<p class="hint">這筆請求沒有 System。</p>`) + `</details>`
51
+ + `<details class="pi-sec" data-sec="tools"><summary><span class="pi-dot" data-seg="tools"></span>Tools · ${current.tools.length} 個<span class="pi-count">約 ${fmt(current.sizes.tools)} tokens</span></summary>`
52
+ + (current.tools.length ? current.tools.map(tool).join("") : `<p class="hint">這筆請求沒有附工具。</p>`) + `</details>`
53
+ + `<details class="pi-sec" data-sec="messages" open><summary><span class="pi-dot" data-seg="fresh"></span>對話 · ${current.messages.length} 則<span class="pi-count">約 ${fmt(talkSize)} tokens</span></summary>`
54
+ + current.messages.map(message).join("") + `</details>`;
55
+ const raw = `<div class="pi-raw"${state.view === "raw" ? "" : " hidden"}><div class="modes pi-raw-tabs" role="tablist">`
56
+ + `<button type="button" class="${state.raw === "sent" ? "on" : ""}" data-raw="sent">送給 Router</button>`
57
+ + `<button type="button" class="${state.raw === "raw" ? "on" : ""}" data-raw="raw">客戶端原始請求</button></div>`
58
+ + `<pre class="pi-json"${state.raw === "sent" ? "" : " hidden"} data-raw-pane="sent">POST ${esc(current.path)}\n${esc(JSON.stringify(current.sent, null, 2))}</pre>`
59
+ + `<pre class="pi-json"${state.raw === "raw" ? "" : " hidden"} data-raw-pane="raw">${esc(JSON.stringify(current.raw, null, 2))}</pre></div>`;
60
+ const tabs = `<div class="modes pi-view-tabs"><button type="button" class="${state.view === "parts" ? "on" : ""}" data-view="parts">結構</button>`
61
+ + `<button type="button" class="${state.view === "raw" ? "on" : ""}" data-view="raw">原始 JSON</button></div>`;
62
+ return `<div class="pi-a"><section class="tile pi-list"><div class="tile-head"><h2>觀察紀錄</h2><span class="badge">${list.captures.length} 筆</span></div>`
63
+ + `<div class="pi-req-list">${items}</div>${dropped}</section>`
64
+ + `<section class="tile pi-detail"><div class="tile-head"><h2>#${current.id} 解剖</h2>${current.newConversation ? `<span class="badge">新對話</span>` : ""}${tags(current) ? `<span class="pi-tags">${tags(current)}</span>` : ""}</div>${meta}${stack(current)}${legend}${tabs}`
65
+ + `<div class="pi-parts"${state.view === "parts" ? "" : " hidden"}>${sections}</div>${raw}</section></div>`;
66
+ }
67
+ /** Page script: keeps the selection and open sections while it redraws every 2 seconds. */
68
+ function inspectorScript() {
69
+ return `(function () {
70
+ ${inspectorBody.toString()}
71
+ var host = document.getElementById("pi-app");
72
+ if (!host) return;
73
+ var data = JSON.parse(document.getElementById("pi-data").textContent);
74
+ var state = { selected: null, view: "parts", raw: "sent" };
75
+ var open = {};
76
+ function draw() {
77
+ host.querySelectorAll("details[data-sec]").forEach(function (box) { open[box.dataset.sec] = box.open; });
78
+ var scroll = host.querySelector(".pi-req-list"); var top = scroll ? scroll.scrollTop : 0;
79
+ host.innerHTML = inspectorBody(data, state);
80
+ host.querySelectorAll("details[data-sec]").forEach(function (box) { if (box.dataset.sec in open) box.open = open[box.dataset.sec]; });
81
+ scroll = host.querySelector(".pi-req-list"); if (scroll) scroll.scrollTop = top;
82
+ }
83
+ host.addEventListener("click", function (event) {
84
+ var target = event.target.closest && event.target.closest("[data-pick],[data-view],[data-raw]");
85
+ if (!target) return;
86
+ if (target.dataset.pick) state.selected = Number(target.dataset.pick);
87
+ if (target.dataset.view) state.view = target.dataset.view;
88
+ if (target.dataset.raw) state.raw = target.dataset.raw;
89
+ draw();
90
+ });
91
+ var last = "";
92
+ async function refresh() {
93
+ try {
94
+ var response = await fetch("/prompt-capture", { cache: "no-store" });
95
+ if (!response.ok) return;
96
+ var text = await response.text();
97
+ if (text === last) return;
98
+ last = text; data = JSON.parse(text);
99
+ // 選取的那筆仍在就不動;沒有選取(或已被捨去)時跟著最新的一筆。
100
+ if (state.selected !== null && !data.captures.some(function (one) { return one.id === state.selected; })) state.selected = null;
101
+ draw();
102
+ } catch (error) { /* VansPod 關閉時保持最後的畫面 */ }
103
+ }
104
+ setInterval(refresh, 2000);
105
+ // 錄製列按下清除等動作後立刻更新,不等下一次輪詢。
106
+ document.addEventListener("pi-refresh", refresh);
107
+ })();`;
108
+ }
109
+ exports.INSPECTOR_STYLES = `
110
+ .pi-empty { align-items: center; text-align: center; padding: 40px 18px; }
111
+ .inspector-main pre { margin: 0; padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--input); font: 12px/1.65 "Cascadia Mono", Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 22rem; overflow: auto; color: var(--text); }
112
+ .inspector-main code { font: 12px "Cascadia Mono", Consolas, monospace; }
113
+ .inspector-main details > summary { cursor: pointer; }
114
+ .inspector-main .tile-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding-bottom: 12px; border-bottom: 1px solid var(--line); }
115
+ .inspector-main .tile-head h2 { font-size: 15px; font-weight: 600; }
116
+ [data-seg="system"] { --seg: light-dark(#7c3aed, #a78bfa); }
117
+ [data-seg="tools"] { --seg: light-dark(#2563eb, #60a5fa); }
118
+ [data-seg="reminder"] { --seg: light-dark(#db2777, #f472b6); }
119
+ [data-seg="history"] { --seg: light-dark(#a3a3a3, #6b6b6b); }
120
+ [data-seg="fresh"] { --seg: light-dark(#059669, #4ecb9d); }
121
+ .pi-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--seg); flex-shrink: 0; }
122
+ .pi-stack { display: flex; height: 10px; width: 100%; border-radius: 999px; overflow: hidden; background: light-dark(#ececec, #333333); }
123
+ .pi-seg { display: block; height: 100%; background: var(--seg); min-width: 2px; }
124
+ .pi-seg + .pi-seg { box-shadow: inset 1px 0 0 var(--tile); }
125
+ .pi-legend { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 12px; color: var(--muted); }
126
+ .pi-legend li { display: inline-flex; align-items: center; gap: 6px; }
127
+ .pi-legend b { color: var(--text); font-weight: 600; }
128
+ .pi-meta { color: var(--muted); font-size: 13px; overflow-wrap: anywhere; }
129
+ .pi-count { margin-left: auto; color: var(--muted); font-size: 12px; font-weight: 400; }
130
+ .pi-msg { display: flex; flex-direction: column; gap: 6px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line); border-left: 3px solid light-dark(#d4d4d4, #4a4a4a); background: var(--tile); }
131
+ .pi-msg + .pi-msg { margin-top: 8px; }
132
+ .pi-msg pre { max-height: 14rem; }
133
+ .pi-msg-head { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--muted); }
134
+ .pi-msg.role-user { border-left-color: light-dark(#059669, #4ecb9d); }
135
+ .pi-msg.role-assistant { border-left-color: light-dark(#d97706, #fbbf24); }
136
+ .pi-msg.role-tool { border-left-color: light-dark(#64748b, #94a3b8); }
137
+ .pi-msg.kind-call pre { background: #0d1117; color: #e6edf3; border-color: #30363d; }
138
+ .pi-msg.is-reminder { border-left-color: light-dark(#db2777, #f472b6); }
139
+ .pi-msg:not(.is-new) { opacity: 0.62; }
140
+ .pi-new, .pi-newconv { display: inline-flex; align-items: center; min-height: 20px; padding: 0 8px; border-radius: 999px; background: light-dark(rgba(16, 163, 127, 0.10), rgba(78, 203, 157, 0.13)); color: light-dark(#0a7d5c, #4ecb9d); font: 600 11px system-ui, sans-serif; }
141
+ .pi-req-top .pi-newconv { margin-right: auto; }
142
+ mark.pi-skill { background: light-dark(#fce7f3, #4a1d36); color: light-dark(#9d174d, #fbcfe8); border-radius: 4px; padding: 0 2px; }
143
+ .pi-tool { border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; }
144
+ .pi-tool + .pi-tool { margin-top: 6px; }
145
+ .pi-tool summary { display: flex; align-items: baseline; gap: 10px; font-size: 13px; min-width: 0; }
146
+ .pi-tool summary span { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
147
+ .pi-tool > pre { margin-top: 8px; }
148
+ .pi-tool.is-skill { border-color: light-dark(#f9a8d4, #7a2a55); }
149
+ .pi-tool.is-skill summary code::after { content: "skill"; margin-left: 6px; padding: 0 6px; border-radius: 999px; background: light-dark(#fce7f3, #4a1d36); color: light-dark(#9d174d, #fbcfe8); font: 600 10px system-ui, sans-serif; }
150
+ .pi-schema { opacity: 0.8; }
151
+ .pi-raw { display: flex; flex-direction: column; gap: 8px; }
152
+ .pi-raw-tabs, .pi-view-tabs { align-self: flex-start; display: inline-flex; width: auto; }
153
+ .inspector-main .modes button { min-height: 30px; padding: 5px 12px; font-size: 12px; white-space: nowrap; flex: 0 0 auto; }
154
+ .inspector-main .pi-json { max-height: 30rem; }
155
+ .inspector-main [hidden] { display: none !important; }
156
+ .pi-a { display: grid; grid-template-columns: 19rem minmax(0, 1fr); gap: 12px; align-items: start; }
157
+ .pi-list { position: sticky; top: 12px; }
158
+ .pi-req-list { display: flex; flex-direction: column; gap: 6px; max-height: 70dvh; overflow: auto; }
159
+ main button.pi-req { display: flex; flex-direction: column; align-items: stretch; gap: 6px; width: 100%; min-height: 0; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--tile); color: var(--text); text-align: left; font-weight: 400; }
160
+ main button.pi-req.on { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
161
+ .pi-req-top { display: flex; justify-content: space-between; gap: 8px; font-size: 13px; }
162
+ .pi-req-top span { color: var(--muted); font-size: 12px; }
163
+ .pi-req-model { font: 12px "Cascadia Mono", Consolas, monospace; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
164
+ .pi-req-sub { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
165
+ .pi-req .pi-stack { height: 5px; }
166
+ .pi-tags { display: flex; flex-wrap: wrap; gap: 4px; }
167
+ .pi-tag { padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; background: light-dark(#e0e7ff, #2a3350); color: light-dark(#3730a3, #c7d2fe); }
168
+ .pi-tag.pi-failed { background: light-dark(#fee2e2, #4a1d1d); color: light-dark(#b91c1c, #fca5a5); }
169
+ .pi-sec { border-top: 1px solid var(--line); padding-top: 12px; }
170
+ .pi-sec > summary { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; margin-bottom: 10px; }
171
+ .pi-sec pre + pre { margin-top: 8px; }
172
+ @media (max-width: 760px) { .pi-a { grid-template-columns: 1fr; } .pi-list { position: static; } }`;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.installations = installations;
7
+ exports.detectInstallation = detectInstallation;
7
8
  exports.registerInstallation = registerInstallation;
8
9
  const node_crypto_1 = require("node:crypto");
9
10
  const node_sea_1 = require("node:sea");
@@ -24,21 +25,21 @@ async function installations() {
24
25
  throw error;
25
26
  }
26
27
  }
28
+ /** 目前這個行程是哪一份可登記的安裝;原始碼執行時沒有。 */
29
+ async function detectInstallation() {
30
+ if ((0, node_sea_1.isSea)())
31
+ return { kind: "exe", file: process.execPath, sha256: (0, node_crypto_1.createHash)("sha256").update(await promises_1.default.readFile(process.execPath)).digest("hex") };
32
+ const root = node_path_1.default.resolve(__dirname, "..");
33
+ if (node_path_1.default.basename(root).toLowerCase() !== "vanspod" || node_path_1.default.basename(node_path_1.default.dirname(root)) !== "node_modules")
34
+ return undefined;
35
+ const npmCli = process.env.npm_execpath && node_path_1.default.basename(process.env.npm_execpath) === "npm-cli.js"
36
+ ? process.env.npm_execpath : node_path_1.default.join(node_path_1.default.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
37
+ return await promises_1.default.stat(npmCli).catch(() => undefined) ? { kind: "npm", root, prefix: node_path_1.default.dirname(node_path_1.default.dirname(root)), node: process.execPath, npmCli } : undefined;
38
+ }
27
39
  async function registerInstallation() {
28
40
  if (await (0, instance_1.removalInProgress)())
29
41
  throw new Error("VansPod 完整移除中,請稍後重試。");
30
- let installation;
31
- if ((0, node_sea_1.isSea)())
32
- installation = { kind: "exe", file: process.execPath, sha256: (0, node_crypto_1.createHash)("sha256").update(await promises_1.default.readFile(process.execPath)).digest("hex") };
33
- else {
34
- const root = node_path_1.default.resolve(__dirname, "..");
35
- if (node_path_1.default.basename(root).toLowerCase() === "vanspod" && node_path_1.default.basename(node_path_1.default.dirname(root)) === "node_modules") {
36
- const npmCli = process.env.npm_execpath && node_path_1.default.basename(process.env.npm_execpath) === "npm-cli.js"
37
- ? process.env.npm_execpath : node_path_1.default.join(node_path_1.default.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
38
- if (await promises_1.default.stat(npmCli).catch(() => undefined))
39
- installation = { kind: "npm", root, prefix: node_path_1.default.dirname(node_path_1.default.dirname(root)), node: process.execPath, npmCli };
40
- }
41
- }
42
+ const installation = await detectInstallation();
42
43
  if (!installation)
43
44
  return;
44
45
  await promises_1.default.mkdir((0, instance_1.managementDirectory)(), { recursive: true });
package/dist/launcher.js CHANGED
@@ -137,7 +137,9 @@ async function runCli(args = process.argv.slice(2)) {
137
137
  throw new Error("VansPod 啟動逾時,請稍後用 vanspod status 檢查。");
138
138
  const live = (await (0, instance_1.readInstance)());
139
139
  await (0, instance_1.control)(live, "open", { version: version_1.VERSION });
140
- (0, desktop_1.openBrowser)(`${ready.origin}/`);
140
+ // 版本更新的工具重新啟動時,原本的分頁會自己重新連線。
141
+ if (process.env.VANSPOD_RESTART !== "1")
142
+ (0, desktop_1.openBrowser)(`${ready.origin}/`);
141
143
  process.stdout.write(`VansPod ${ready.version}: ${ready.origin}/\n`);
142
144
  if (ready.version !== version_1.VERSION)
143
145
  process.stdout.write(`本次開啟版本 ${version_1.VERSION},目前執行版本 ${ready.version};換版請先結束 VansPod。\n`);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.lifecyclePage = lifecyclePage;
4
+ const versionUpdateView_1 = require("./versionUpdateView");
4
5
  function lifecyclePage(html, token) {
5
6
  const controls = `<div style="margin-top:16px"><button type="button" data-lifecycle="stop">結束 VansPod</button> <button type="button" data-lifecycle="uninstall">移除 VansPod</button><p role="status" data-lifecycle-message></p></div>`;
6
7
  const script = `<script>
@@ -37,5 +38,5 @@ function lifecyclePage(html, token) {
37
38
  }).catch(function () {});
38
39
  })();
39
40
  </script>`;
40
- return html.replace(/<form method="post" action="\/stop">[\s\S]*?<\/form>/, controls).replace('</body>', `${script}</body>`);
41
+ return html.replace(/<form method="post" action="\/stop">[\s\S]*?<\/form>/, controls).replace('</body>', `${script}${(0, versionUpdateView_1.versionUpdateScript)(token)}</body>`);
41
42
  }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.proxyError = proxyError;
4
4
  exports.isCodexSearch = isCodexSearch;
5
5
  exports.sendRouter = sendRouter;
6
+ exports.forwardRouter = forwardRouter;
6
7
  exports.relayResponse = relayResponse;
7
8
  const adapters_1 = require("./adapters");
8
9
  const types_1 = require("./adapters/types");
@@ -19,7 +20,18 @@ function proxyError(client, message, status) {
19
20
  function isCodexSearch(client, path) {
20
21
  return client === "codex" && (path ?? "").split("?")[0].endsWith("/alpha/search");
21
22
  }
22
- async function sendRouter(upstream, baseUrl) {
23
+ function redact(text, apiKey) {
24
+ return apiKey ? text.split(apiKey).join("[redacted]") : text;
25
+ }
26
+ function redactBody(body, apiKey) {
27
+ return apiKey ? JSON.parse(redact(JSON.stringify(body), apiKey)) : body;
28
+ }
29
+ // Prompt Capture sees the body each request sends to Router, never its headers or the Classroom API Key.
30
+ function recordUpstream(capture, upstream, adapter, raw) {
31
+ return (path, sent, options) => capture.record({ client: upstream.client, adapter, path,
32
+ sent: redactBody(sent, upstream.apiKey), raw: redactBody(raw, upstream.apiKey), ...options });
33
+ }
34
+ async function sendRouter(upstream, baseUrl, capture) {
23
35
  const client = upstream.client === "claude" ? "claude" : "codex";
24
36
  try {
25
37
  const path = upstream.path ?? "";
@@ -42,6 +54,8 @@ async function sendRouter(upstream, baseUrl) {
42
54
  const request = { client, model: upstream.model, body: parsed,
43
55
  apiKey: upstream.apiKey ?? "", routerBaseUrl: baseUrl.replace(/\/+$/, ""), headers: upstream.headers,
44
56
  signal: upstream.signal ?? new AbortController().signal };
57
+ if (capture)
58
+ request.record = recordUpstream(capture, upstream, adapter.id, parsed);
45
59
  // Claude Code searches inside a model request: Router runs the searches, not the model upstream.
46
60
  const response = (0, claudeWebSearch_1.declaresWebSearch)(request) ? await (0, claudeWebSearch_1.claudeWebSearch)(adapter, request) : await adapter.send(request);
47
61
  if (response.ok)
@@ -54,9 +68,7 @@ async function sendRouter(upstream, baseUrl) {
54
68
  message += ` ${error.message}`;
55
69
  }
56
70
  catch { /* HTTP status remains useful without exposing an arbitrary upstream body. */ }
57
- if (upstream.apiKey)
58
- message = message.split(upstream.apiKey).join("[redacted]");
59
- return proxyError(client, message, response.status);
71
+ return proxyError(client, redact(message, upstream.apiKey), response.status);
60
72
  }
61
73
  catch (error) {
62
74
  if (upstream.signal?.aborted)
@@ -64,6 +76,34 @@ async function sendRouter(upstream, baseUrl) {
64
76
  return proxyError(client, error instanceof types_1.AdapterError ? error.message : "上游沒有回應或回應格式無效。", error instanceof types_1.AdapterError ? error.status : 502);
65
77
  }
66
78
  }
79
+ // VS Code Chat already speaks the protocol Router expects: its body goes to Router as is,
80
+ // with only the model swapped for the Class Session model.
81
+ async function forwardRouter(upstream, baseUrl, capture) {
82
+ const path = upstream.path ?? "";
83
+ let raw;
84
+ try {
85
+ raw = JSON.parse(upstream.body ?? "");
86
+ }
87
+ catch {
88
+ raw = undefined;
89
+ }
90
+ const sent = raw && typeof raw === "object" && !Array.isArray(raw) ? { ...raw, model: upstream.model } : undefined;
91
+ const markFailed = capture && sent ? recordUpstream(capture, upstream, upstream.adapter ?? "chat", raw)(path, sent) : undefined;
92
+ try {
93
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}${path}`, {
94
+ method: upstream.method ?? "POST",
95
+ headers: { "Content-Type": "application/json", ...(upstream.apiKey ? { Authorization: `Bearer ${upstream.apiKey}` } : {}) },
96
+ body: sent ? JSON.stringify(sent) : upstream.body,
97
+ signal: upstream.signal,
98
+ });
99
+ if (!response.ok)
100
+ markFailed?.(response.status);
101
+ return response;
102
+ }
103
+ catch {
104
+ return Response.json({ error: { message: "上游沒有回應。" } }, { status: 502 });
105
+ }
106
+ }
67
107
  async function relayResponse(response, res, client, signal) {
68
108
  const type = response.headers.get("content-type") ?? "application/json; charset=utf-8";
69
109
  res.writeHead(response.status, { "Content-Type": type, "Cache-Control": "no-store" });