vanspod 0.1.3 → 0.2.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.2.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.2.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.2.0 -m "VansPod 0.2.0"
54
+ git push origin v0.2.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
+ }
@@ -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; } }`;
@@ -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" });
package/dist/page.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.modelStatus = modelStatus;
4
4
  exports.classroomBlocks = classroomBlocks;
5
5
  exports.renderPage = renderPage;
6
+ exports.renderInspectorPage = renderInspectorPage;
6
7
  const version_1 = require("./version");
7
8
  const appearance_1 = require("./appearance");
8
9
  const installProgress_1 = require("./installProgress");
@@ -12,6 +13,8 @@ const classroomUpdate_1 = require("./classroomUpdate");
12
13
  const connectionMascot_1 = require("./connectionMascot");
13
14
  const clientIcons_1 = require("./clientIcons");
14
15
  const environmentIcons_1 = require("./environmentIcons");
16
+ const promptCapture_1 = require("./promptCapture");
17
+ const inspectorView_1 = require("./inspectorView");
15
18
  const courseCatalog_1 = require("./courseCatalog");
16
19
  const PRODUCT = "VansPod";
17
20
  const VERSION = `v${version_1.VERSION}`;
@@ -556,7 +559,72 @@ function classroomBlocks(view) {
556
559
  stop: stopForm(),
557
560
  };
558
561
  }
559
- function basePage(view) {
562
+ const SIDE_PAGES = [
563
+ {
564
+ id: "settings",
565
+ href: "/",
566
+ label: "教室設定",
567
+ icon: `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m9.5 3-.6 2.3-2 .9-2.1-.6-2.5 4.3 1.5 1.7v2.3l-1.5 1.7 2.5 4.3 2.1-.6 2 .9.6 2.3h5l.6-2.3 2-.9 2.1.6 2.5-4.3-1.5-1.7v-2.3l1.5-1.7-2.5-4.3-2.1.6-2-.9L14.5 3z"/><circle cx="12" cy="12" r="3"/></svg>`,
568
+ },
569
+ {
570
+ id: "inspector",
571
+ href: "/prompt-inspector",
572
+ label: "Prompt 觀察室",
573
+ icon: `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.4-4.4M8 9.5h6M8 12.5h4"/></svg>`,
574
+ },
575
+ ];
576
+ const BRAND = `<div class="brand"><div class="logo-badge"><img src="/brand-logo.png" alt=""></div><h1 class="brand-title">${PRODUCT}</h1><span class="ver">${VERSION}</span></div>`;
577
+ /** 兩頁共用的側欄:行動版頂列、抽屜遮罩、選單與外觀切換。 */
578
+ function sideMenu(current) {
579
+ const items = SIDE_PAGES.map((page) => `<a class="side-item" href="${page.href}"${page.id === current ? ' aria-current="page"' : ""}>${page.icon}<span>${page.label}</span></a>`).join("");
580
+ return `<div class="mobile-top"><button type="button" class="menu-toggle" aria-label="開啟選單" aria-expanded="false" aria-controls="side-menu"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>${BRAND}</div><button type="button" class="drawer-scrim" aria-label="關閉選單"></button><header class="bar" id="side-menu">${BRAND}<nav aria-label="選單">${items}</nav><button type="button" data-appearance-toggle aria-label="切換外觀"></button></header>`;
581
+ }
582
+ /** 兩頁共用的頁殼版面:側欄、行動版抽屜。 */
583
+ const SHELL_LAYOUT_STYLES = `
584
+ .tile { border: 1px solid light-dark(#e6e6e6, #3d3d3d); }
585
+ body { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100dvh; }
586
+ .bar { position: sticky; top: 0; align-self: start; height: 100dvh; display: flex; flex-direction: column; align-items: stretch; justify-content: flex-start; gap: 4px; padding: 18px 14px; border-bottom: 0; border-right: 1px solid var(--line); }
587
+ .bar .brand { padding: 6px 8px 14px; }
588
+ .bar .logo-badge { width: 28px; height: 28px; }
589
+ .bar .brand-title, .mobile-top .brand-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: 0; line-height: 26px; color: light-dark(#0d0d0d, #ececec); background: none; -webkit-text-fill-color: currentColor; white-space: nowrap; }
590
+ .brand .ver { align-self: center; flex: 0 0 auto; font-family: Consolas, "Cascadia Mono", monospace; font-size: 10px; line-height: 1.2; color: var(--muted); background: light-dark(#f4f4f4, #303030); border: 1px solid light-dark(#e6e6e6, #3d3d3d); padding: 2px 6px; border-radius: 999px; white-space: nowrap; }
591
+ .bar nav { display: flex; flex-direction: column; gap: 2px; }
592
+ .side-item { display: flex; align-items: center; gap: 8px; align-self: stretch; justify-content: flex-start; min-height: 36px; padding: 8px 10px; border-radius: 8px; background: transparent; color: var(--text); font-size: 13px; font-weight: 500; text-align: left; text-decoration: none; }
593
+ .side-item:hover { background: light-dark(rgba(13, 13, 13, 0.04), rgba(255, 255, 255, 0.05)); }
594
+ .side-item[aria-current="page"] { background: light-dark(rgba(13, 13, 13, 0.06), rgba(255, 255, 255, 0.09)); font-weight: 600; }
595
+ .side-item:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
596
+ .side-item svg { width: 18px; height: 18px; flex-shrink: 0; }
597
+ .bar [data-appearance-toggle] { margin-top: auto; align-self: flex-start; }
598
+ .mobile-top, .drawer-scrim, .menu-toggle { display: none; }
599
+ main { justify-self: center; width: min(52rem, 100%); }
600
+ @media (max-width: 760px) {
601
+ body { display: block; }
602
+ .mobile-top { display: flex; position: sticky; top: 0; z-index: 20; align-items: center; gap: 4px; padding: 4px 10px; border-bottom: 1px solid var(--line); background: var(--bar); backdrop-filter: blur(24px) saturate(160%); }
603
+ .mobile-top .brand { flex: 1; min-width: 0; padding: 4px; }
604
+ .mobile-top .logo-badge { width: 32px; height: 32px; }
605
+ .mobile-top .brand-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
606
+ .menu-toggle { display: grid; place-items: center; width: 44px; height: 44px; min-height: 44px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: var(--text); }
607
+ .menu-toggle svg { width: 20px; height: 20px; }
608
+ .bar { position: fixed; top: 0; left: 0; bottom: 0; z-index: 40; width: min(280px, 84vw); height: 100dvh; transform: translateX(-100%); visibility: hidden; border-right: 1px solid var(--line); background: light-dark(rgba(242, 242, 247, 0.97), rgba(12, 12, 14, 0.96)); }
609
+ .bar.open { transform: translateX(0); visibility: visible; }
610
+ .bar .brand { display: none; }
611
+ .drawer-scrim.show { display: block; position: fixed; inset: 0; z-index: 30; border: 0; padding: 0; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.52)); }
612
+ main { width: min(52rem, 100%); margin: 0 auto; }
613
+ }
614
+ .tile-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
615
+ .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
616
+ [data-appearance="dark"] { --bg: #212121; }
617
+ @media (prefers-color-scheme: dark) {
618
+ :root:not([data-appearance="light"]) { --bg: #212121; }
619
+ }`;
620
+ /** 兩頁共用的頁首與按鈕樣式。 */
621
+ const SHELL_CONTROL_STYLES = `
622
+ .page-head { margin: 0.75rem 0 0.15rem; }
623
+ .page-head h2 { font-size: 20px; font-weight: 600; color: var(--text); letter-spacing: 0; }
624
+ .page-head p { margin-top: 4px; color: var(--muted); font-size: 14px; font-weight: 400; }
625
+ main button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid transparent; background: var(--accent); color: var(--on-accent); font-size: 13px; font-weight: 500; }
626
+ main button.quiet { background: light-dark(#ffffff, #212121); color: light-dark(#0d0d0d, #ececec); border-color: light-dark(#e6e6e6, #3d3d3d); padding: 8px 16px; }`;
627
+ function documentHead() {
560
628
  return `<!DOCTYPE html>
561
629
  <html lang="zh-Hant">
562
630
  <head>
@@ -566,7 +634,10 @@ function basePage(view) {
566
634
  <link rel="icon" href="/favicon.ico" sizes="any">
567
635
  <style>${CSS}</style>
568
636
  <script>${appearanceScript()}</script>
569
- </head>
637
+ </head>`;
638
+ }
639
+ function basePage(view) {
640
+ return `${documentHead()}
570
641
  <body>
571
642
  <header class="bar">
572
643
  <div class="brand">
@@ -794,8 +865,7 @@ function renderPage(view) {
794
865
  ? `<span class="badge">已連線</span>`
795
866
  : `<span class="badge off">未連線</span>`;
796
867
  let html = basePage(view).replace(`<section class="tile"><h2>連線</h2>`, `<section class="tile"><div class="tile-head"><h2>連線</h2>${tag}</div>`);
797
- html = html.replace(`<header class="bar">`, `<div class="mobile-top"><button type="button" class="menu-toggle" aria-label="開啟選單" aria-expanded="false" aria-controls="side-menu"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button><div class="brand"><div class="logo-badge"><img src="/brand-logo.png" alt=""></div><h1 class="gradient-text">VansPod</h1></div></div><button type="button" class="drawer-scrim" aria-label="關閉選單"></button><header class="bar" id="side-menu">`);
798
- html = html.replace(`<button type="button" data-appearance-toggle aria-label="切換外觀"></button>`, `<nav aria-label="選單"><button type="button" class="side-item" aria-current="page"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m9.5 3-.6 2.3-2 .9-2.1-.6-2.5 4.3 1.5 1.7v2.3l-1.5 1.7 2.5 4.3 2.1-.6 2 .9.6 2.3h5l.6-2.3 2-.9 2.1.6 2.5-4.3-1.5-1.7v-2.3l1.5-1.7-2.5-4.3-2.1.6-2-.9L14.5 3z"/><circle cx="12" cy="12" r="3"/></svg><span>教室設定</span></button></nav><button type="button" data-appearance-toggle aria-label="切換外觀"></button>`);
868
+ html = html.replace(/<header class="bar">[\s\S]*?<\/header>/, sideMenu("settings"));
799
869
  html = html.replace(/<section class="tile"><h2>資料夾<\/h2>[\s\S]*?<\/section>/, "");
800
870
  const modelCount = view.allowedModels?.length ?? (view.modelId ? 1 : 0);
801
871
  const modelTag = modelCount
@@ -832,7 +902,6 @@ function renderPage(view) {
832
902
  html = html.replace(/<p class="class-label">[\s\S]*?<\/p>/, "");
833
903
  html = html.replace(`<p class="detail">Classroom API Key 已設定。</p>`, "");
834
904
  }
835
- html = html.replaceAll(`<h1 class="gradient-text">${PRODUCT}</h1>`, `<h1 class="brand-title">VansPod</h1><span class="ver">${VERSION}</span>`);
836
905
  html = html.replace(`<div class="modules">`, `<header class="page-head"><h2>教室設定</h2><p>連線、模型與開發環境。</p></header><div class="modules">`);
837
906
  if (view.catalog?.actions.length) {
838
907
  html = html.replace(/<table>[\s\S]*?<\/table>/, installActionCards(view));
@@ -840,35 +909,8 @@ function renderPage(view) {
840
909
  html = organizeSettings(html, view);
841
910
  html = splitCourseCards(html, view);
842
911
  const extra = `<style>
843
- .tile { border: 1px solid light-dark(#e6e6e6, #3d3d3d); }
844
912
  .display { display: none; }
845
- body { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100dvh; }
846
- .bar { position: sticky; top: 0; align-self: start; height: 100dvh; display: flex; flex-direction: column; align-items: stretch; justify-content: flex-start; gap: 4px; padding: 18px 14px; border-bottom: 0; border-right: 1px solid var(--line); }
847
- .bar .brand { padding: 6px 8px 14px; }
848
- .bar .logo-badge { width: 28px; height: 28px; }
849
- .bar .brand-title, .mobile-top .brand-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: 0; line-height: 26px; color: light-dark(#0d0d0d, #ececec); background: none; -webkit-text-fill-color: currentColor; white-space: nowrap; }
850
- .brand .ver { align-self: center; flex: 0 0 auto; font-family: Consolas, "Cascadia Mono", monospace; font-size: 10px; line-height: 1.2; color: var(--muted); background: light-dark(#f4f4f4, #303030); border: 1px solid light-dark(#e6e6e6, #3d3d3d); padding: 2px 6px; border-radius: 999px; white-space: nowrap; }
851
- .bar nav { display: flex; flex-direction: column; }
852
- .side-item { display: flex; align-items: center; gap: 8px; align-self: stretch; justify-content: flex-start; min-height: 36px; padding: 8px 10px; border-radius: 8px; background: light-dark(rgba(13, 13, 13, 0.06), rgba(255, 255, 255, 0.09)); color: var(--text); font-size: 13px; font-weight: 600; text-align: left; }
853
- .side-item svg { width: 18px; height: 18px; flex-shrink: 0; }
854
- .bar [data-appearance-toggle] { margin-top: auto; align-self: flex-start; }
855
- .mobile-top, .drawer-scrim, .menu-toggle { display: none; }
856
- main { justify-self: center; width: min(52rem, 100%); }
857
- @media (max-width: 760px) {
858
- body { display: block; }
859
- .mobile-top { display: flex; position: sticky; top: 0; z-index: 20; align-items: center; gap: 4px; padding: 4px 10px; border-bottom: 1px solid var(--line); background: var(--bar); backdrop-filter: blur(24px) saturate(160%); }
860
- .mobile-top .brand { flex: 1; min-width: 0; padding: 4px; }
861
- .mobile-top .logo-badge { width: 32px; height: 32px; }
862
- .mobile-top .brand-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
863
- .menu-toggle { display: grid; place-items: center; width: 44px; height: 44px; min-height: 44px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: var(--text); }
864
- .menu-toggle svg { width: 20px; height: 20px; }
865
- .bar { position: fixed; top: 0; left: 0; bottom: 0; z-index: 40; width: min(280px, 84vw); height: 100dvh; transform: translateX(-100%); visibility: hidden; border-right: 1px solid var(--line); background: light-dark(rgba(242, 242, 247, 0.97), rgba(12, 12, 14, 0.96)); }
866
- .bar.open { transform: translateX(0); visibility: visible; }
867
- .bar .brand { display: none; }
868
- .drawer-scrim.show { display: block; position: fixed; inset: 0; z-index: 30; border: 0; padding: 0; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.52)); }
869
- main { width: min(52rem, 100%); margin: 0 auto; }
870
- }
871
- .tile-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
913
+ ${SHELL_LAYOUT_STYLES}
872
914
  .course-section > summary { cursor: pointer; list-style: none; border-radius: 6px; }
873
915
  .course-section > summary::-webkit-details-marker { display: none; }
874
916
  .course-section > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
@@ -916,7 +958,6 @@ function renderPage(view) {
916
958
  main .snippet-card > button { flex-shrink: 0; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
917
959
  .snippet-card > button svg { width: 14px; height: 14px; }
918
960
  .snippet-card.copied > button svg { display: none; }
919
- .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
920
961
  .confirm-dialog { position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; padding: 24px; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.52)); }
921
962
  .confirm-panel { width: min(36rem, 100%); max-height: min(70dvh, 32rem); overflow: hidden; display: flex; flex-direction: column; gap: 12px; padding: 16px; border-radius: 16px; background: var(--tile); border: 1px solid var(--line); }
922
963
  .confirm-panel > :not(pre) { flex-shrink: 0; }
@@ -929,10 +970,6 @@ function renderPage(view) {
929
970
  .confirm-panel button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid transparent; background: var(--accent); color: var(--on-accent); font-size: 13px; font-weight: 500; }
930
971
  .confirm-panel button.quiet { background: light-dark(#ffffff, #212121); color: light-dark(#0d0d0d, #ececec); border-color: light-dark(#e6e6e6, #3d3d3d); }
931
972
  .restart { color: light-dark(#9a4a08, #fbbf24); }
932
- [data-appearance="dark"] { --bg: #212121; }
933
- @media (prefers-color-scheme: dark) {
934
- :root:not([data-appearance="light"]) { --bg: #212121; }
935
- }
936
973
  .settings-grid { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
937
974
  .settings-card { gap: 16px; padding: 18px; }
938
975
  .settings-card .tile-head { padding-bottom: 12px; border-bottom: 1px solid var(--line); }
@@ -994,11 +1031,7 @@ function renderPage(view) {
994
1031
  .key-row p { color: var(--muted); font-size: 13px; }
995
1032
  .key-row form { flex-shrink: 0; }
996
1033
  ${connectionMascot_1.connectionMascotStyles}
997
- .page-head { margin: 0.75rem 0 0.15rem; }
998
- .page-head h2 { font-size: 20px; font-weight: 600; color: var(--text); letter-spacing: 0; }
999
- .page-head p { margin-top: 4px; color: var(--muted); font-size: 14px; font-weight: 400; }
1000
- main button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid transparent; background: var(--accent); color: var(--on-accent); font-size: 13px; font-weight: 500; }
1001
- main button.quiet { background: light-dark(#ffffff, #212121); color: light-dark(#0d0d0d, #ececec); border-color: light-dark(#e6e6e6, #3d3d3d); padding: 8px 16px; }
1034
+ ${SHELL_CONTROL_STYLES}
1002
1035
  main button.stop { background: transparent; color: light-dark(#b91c1c, #f87171); border-color: light-dark(rgba(185, 28, 28, 0.35), rgba(248, 113, 113, 0.35)); }
1003
1036
  main .modes { border-radius: 999px; padding: 2px; background: light-dark(#f4f4f4, #303030); border: 1px solid light-dark(#e6e6e6, #3d3d3d); }
1004
1037
  main .modes button { background: transparent; color: var(--text); border-color: transparent; }
@@ -1014,3 +1047,75 @@ function renderPage(view) {
1014
1047
  </script>`;
1015
1048
  return html.replace("</body>", `${extra}</body>`);
1016
1049
  }
1050
+ function recorderBar(recording) {
1051
+ const state = recording
1052
+ ? `<span class="pi-rec-dot" aria-hidden="true"></span><div><strong>錄製中</strong>`
1053
+ : `<div><strong>未錄製</strong>`;
1054
+ const toggle = recording
1055
+ ? `<form method="post" action="/prompt-capture/pause"><button type="submit" class="quiet">暫停</button></form>`
1056
+ : `<form method="post" action="/prompt-capture/start"><button type="submit">開始錄製</button></form>`;
1057
+ return `<section class="tile pi-recorder"><div class="pi-rec-state">${state}<p class="hint">只記在這台電腦的記憶體,最多 ${promptCapture_1.CAPTURE_LIMIT} 筆,關掉 VansPod 就清除。只有切到「課堂」的客戶端會被記錄。</p></div></div><div class="pi-rec-actions">${toggle}<form method="post" action="/prompt-capture/clear"><button type="submit" class="quiet">清除</button></form></div></section>`;
1058
+ }
1059
+ // 法鬥超人在頁首標題右邊巡邏,一圈的時間依寬度重算。
1060
+ const headPatrol = (0, connectionMascot_1.fittedPatrol)(".pi-head");
1061
+ // 錄製列的按鈕改用 fetch 換掉錄製列,整頁不重載,法鬥才不會每按一次就重新進場。
1062
+ const recorderActionsScript = `
1063
+ document.addEventListener("submit", async function (event) {
1064
+ var form = event.target;
1065
+ if (!form?.matches?.('form[action^="/prompt-capture/"]')) return;
1066
+ event.preventDefault();
1067
+ var bar = form.closest(".pi-recorder");
1068
+ bar.querySelectorAll("button").forEach(function (button) { button.disabled = true; });
1069
+ try {
1070
+ var response = await fetch(form.action, { method: "POST" });
1071
+ if (!response.ok) throw new Error("recorder action failed");
1072
+ var next = new DOMParser().parseFromString(await response.text(), "text/html").querySelector(".pi-recorder");
1073
+ if (!next) throw new Error("recorder bar unavailable");
1074
+ bar.replaceWith(next);
1075
+ document.dispatchEvent(new Event("pi-refresh"));
1076
+ } catch (error) {
1077
+ bar.querySelectorAll("button").forEach(function (button) { button.disabled = false; });
1078
+ }
1079
+ });
1080
+ `;
1081
+ /** Prompt 觀察室:與教室設定共用頁殼、側欄、主題與行動版抽屜。 */
1082
+ function renderInspectorPage(view) {
1083
+ const list = { captures: view.captures, dropped: view.dropped };
1084
+ // 頁面腳本拿同一份資料接手重繪;JSON 裡的 < 不能結束 script 元素。
1085
+ const data = JSON.stringify(list).replace(/</g, "\\u003c");
1086
+ return `${documentHead()}
1087
+ <body>
1088
+ ${sideMenu("inspector")}
1089
+ <main class="inspector-main">
1090
+ <header class="page-head pi-head"><div class="pi-head-text"><h2>Prompt 觀察室</h2><p>看看 Coding Agent 每次送給模型的完整內容。</p></div>${connectionMascot_1.connectionMascot}</header>
1091
+ ${recorderBar(view.recording)}
1092
+ <div id="pi-app">${(0, inspectorView_1.inspectorBody)(list, { selected: null, view: "parts", raw: "sent" })}</div>
1093
+ </main>
1094
+ <script type="application/json" id="pi-data">${data}</script>
1095
+ <style>
1096
+ ${SHELL_LAYOUT_STYLES}
1097
+ ${SHELL_CONTROL_STYLES}
1098
+ main.inspector-main { width: min(72rem, 100%); }
1099
+ #pi-app { margin-top: 12px; }
1100
+ .inspector-main .tile { gap: 12px; padding: 18px; min-width: 0; }
1101
+ .inspector-main .hint { color: var(--muted); font-size: 13px; line-height: 1.6; }
1102
+ .pi-recorder { flex-direction: row; align-items: center; justify-content: space-between; flex-wrap: wrap; }
1103
+ .pi-rec-state { display: flex; align-items: flex-start; gap: 10px; min-width: 0; flex: 1 1 22rem; }
1104
+ .pi-rec-state strong { font-size: 14px; }
1105
+ .pi-rec-dot { width: 10px; height: 10px; margin-top: 5px; border-radius: 50%; background: #e5484d; box-shadow: 0 0 0 4px rgba(229, 72, 77, 0.15); flex-shrink: 0; animation: pi-pulse 1.6s ease-in-out infinite; }
1106
+ @keyframes pi-pulse { 50% { opacity: 0.35; } }
1107
+ @media (prefers-reduced-motion: reduce) { .pi-rec-dot { animation: none; } }
1108
+ .pi-rec-actions { display: flex; gap: 8px; }
1109
+ .pi-head { display: flex; align-items: flex-end; flex-wrap: wrap; gap: 0 16px; }
1110
+ .pi-head-text { flex: 0 1 auto; padding-bottom: 12px; }
1111
+ /* 巡邏範圍撐滿標題右邊;一圈的時間依寬度重算,步速與教室設定一致。 */
1112
+ .pi-head .connection-mascot { flex: 1 1 260px; height: 144px; }
1113
+ ${connectionMascot_1.connectionMascotStyles}
1114
+ ${headPatrol.styles}
1115
+ ${inspectorView_1.INSPECTOR_STYLES}
1116
+ </style>
1117
+ ${headPatrol.sheet}
1118
+ <script>${drawerScript()}${connectionMascot_1.connectionMascotScript}${headPatrol.script}${recorderActionsScript}${(0, inspectorView_1.inspectorScript)()}</script>
1119
+ </body>
1120
+ </html>`;
1121
+ }
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ // Prompt Capture 記錄器:只存在記憶體,每次啟動錄製都是關閉(ADR-0009)。
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.CAPTURE_LIMIT = void 0;
5
+ exports.createPromptCapture = createPromptCapture;
6
+ // 協定由送往 Router 的路徑判斷,不由客戶端判斷。新協定只要在這裡加一行。
7
+ const PROTOCOLS = [
8
+ { path: "/v1/messages", protocol: "messages", parse: parseMessages },
9
+ { path: "/v1/responses", protocol: "responses", parse: parseResponses },
10
+ { path: "/v1/chat/completions", protocol: "chat", parse: parseChat },
11
+ ];
12
+ function protocolFor(path) {
13
+ const route = path.split("?")[0].replace(/\/+$/, "");
14
+ return PROTOCOLS.find(entry => route.endsWith(entry.path));
15
+ }
16
+ const noop = () => { };
17
+ /** Captures kept in memory; older ones are dropped and only counted. */
18
+ exports.CAPTURE_LIMIT = 20;
19
+ function createPromptCapture() {
20
+ let recording = false;
21
+ let entries = [];
22
+ let dropped = 0;
23
+ let nextId = 1;
24
+ return {
25
+ get recording() { return recording; },
26
+ start() { recording = true; },
27
+ pause() { recording = false; },
28
+ clear() { entries = []; dropped = 0; },
29
+ record(request) {
30
+ const match = protocolFor(request.path);
31
+ if (!recording || !match)
32
+ return noop;
33
+ // withoutBase64 also copies both bodies, so later changes by the caller never reach the capture.
34
+ const sent = withoutBase64(request.sent);
35
+ const parsed = match.parse(isObject(sent) ? sent : {});
36
+ const entry = { ...request, sent, raw: withoutBase64(request.raw), id: nextId++, time: clock(new Date()),
37
+ protocol: match.protocol, parsed, freshFrom: freshFrom(entries, request.client, parsed) };
38
+ entries.push(entry);
39
+ if (entries.length > exports.CAPTURE_LIMIT) {
40
+ dropped += entries.length - exports.CAPTURE_LIMIT;
41
+ entries = entries.slice(-exports.CAPTURE_LIMIT);
42
+ }
43
+ return status => { entry.failedStatus = status; };
44
+ },
45
+ list() { return { captures: entries.map(view).reverse(), dropped }; },
46
+ };
47
+ }
48
+ // 圖片和檔案的 base64 內容換成「[圖片 N KB]」這類佔位文字,存下的是副本。
49
+ const DATA_URL = /^data:([\w.+-]+\/[\w.+-]+)?(?:;[^,;]*)*;base64,/i;
50
+ function placeholder(mediaType, base64) {
51
+ const bytes = Math.floor(base64.replace(/=+$/, "").length * 3 / 4);
52
+ return `[${mediaType.startsWith("image/") ? "圖片" : "檔案"} ${Math.max(1, Math.round(bytes / 1024))} KB]`;
53
+ }
54
+ function withoutBase64(value) {
55
+ if (typeof value === "string") {
56
+ const match = DATA_URL.exec(value);
57
+ return match ? placeholder(match[1] ?? "", value.slice(match[0].length)) : value;
58
+ }
59
+ if (Array.isArray(value))
60
+ return value.map(withoutBase64);
61
+ if (!isObject(value))
62
+ return value;
63
+ const copy = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, withoutBase64(item)]));
64
+ if (value.type === "base64" && typeof value.data === "string")
65
+ copy.data = placeholder(String(value.media_type ?? ""), value.data);
66
+ return copy;
67
+ }
68
+ function clock(date) {
69
+ return [date.getHours(), date.getMinutes(), date.getSeconds()].map(part => String(part).padStart(2, "0")).join(":");
70
+ }
71
+ // 比對規則:往前找同一個客戶端、訊息序列剛好是本筆開頭的第一筆紀錄,超出的部分是本輪新增;
72
+ // 這樣能跨過交錯出現的子 agent 或背景請求。找不到就是新對話,全部都算新增。
73
+ // 錄下時就決定,之後較早的紀錄被捨去也不會改變。
74
+ function freshFrom(earlier, client, parsed) {
75
+ const match = [...earlier].reverse().find(other => other.client === client && startsWith(parsed.messages, other.parsed.messages));
76
+ return match ? match.parsed.messages.length : null;
77
+ }
78
+ function startsWith(messages, prefix) {
79
+ if (!prefix.length || prefix.length > messages.length)
80
+ return false;
81
+ return prefix.every((message, index) => sameMessage(message, messages[index]));
82
+ }
83
+ function sameMessage(a, b) {
84
+ return a.role === b.role && a.kind === b.kind && a.name === b.name && a.text === b.text;
85
+ }
86
+ function view(entry) {
87
+ const { parsed, freshFrom, sent } = entry;
88
+ const messages = parsed.messages.map((message, index) => ({ ...message, isNew: index >= (freshFrom ?? 0) }));
89
+ const sizes = { system: 0, tools: 0, reminder: 0, history: 0, fresh: 0 };
90
+ for (const text of parsed.system)
91
+ sizes.system += estimateTokens(text);
92
+ for (const tool of parsed.tools)
93
+ sizes.tools += estimateTokens(tool.name + tool.description + JSON.stringify(tool.schema ?? {}));
94
+ for (const message of messages) {
95
+ const size = estimateTokens((message.name ?? "") + message.text);
96
+ if (message.reminder)
97
+ sizes.reminder += size;
98
+ else if (message.isNew)
99
+ sizes.fresh += size;
100
+ else
101
+ sizes.history += size;
102
+ }
103
+ return {
104
+ id: entry.id, time: entry.time, client: entry.client, model: isObject(sent) && typeof sent.model === "string" ? sent.model : "",
105
+ protocol: entry.protocol, adapter: entry.adapter,
106
+ ...(entry.failedStatus !== undefined ? { failedStatus: entry.failedStatus } : {}),
107
+ webSearchFollowUp: entry.webSearchFollowUp === true, newConversation: freshFrom === null,
108
+ system: parsed.system, tools: parsed.tools, messages, sizes,
109
+ total: sizes.system + sizes.tools + sizes.reminder + sizes.history + sizes.fresh,
110
+ sent: entry.sent, raw: entry.raw, path: entry.path,
111
+ };
112
+ }
113
+ /** 中日韓字元每字算 1 個 token,其他字元每 4 個算 1 個。 */
114
+ function estimateTokens(text) {
115
+ const cjk = text.match(/[぀-ヿ㐀-鿿가-힯豈-﫿＀-￯]/g)?.length ?? 0;
116
+ return cjk + Math.ceil((text.length - cjk) / 4);
117
+ }
118
+ function isObject(value) {
119
+ return !!value && typeof value === "object" && !Array.isArray(value);
120
+ }
121
+ function blocks(content) {
122
+ if (typeof content === "string")
123
+ return [{ type: "text", text: content }];
124
+ return Array.isArray(content) ? content.filter(isObject) : [];
125
+ }
126
+ function plainText(content) {
127
+ if (typeof content === "string")
128
+ return content;
129
+ if (!Array.isArray(content))
130
+ return content == null ? "" : JSON.stringify(content, null, 2);
131
+ return blocks(content).map(block => typeof block.text === "string" ? block.text : `[${String(block.type)}]`).join("\n");
132
+ }
133
+ const isReminder = (text) => text.includes("<system-reminder>");
134
+ function textMessage(role, text) {
135
+ return { role, kind: "text", text, reminder: role === "user" && isReminder(text) };
136
+ }
137
+ const texts = (content) => blocks(content).map(block => typeof block.text === "string" ? block.text : "").filter(Boolean);
138
+ /** Each protocol keeps a tool's name and description in `fields` (the tool itself, or its `function`). */
139
+ function toolList(tools, definition) {
140
+ return (Array.isArray(tools) ? tools : []).filter(isObject).map(tool => {
141
+ const { fields, schema } = definition(tool);
142
+ return {
143
+ name: String(fields.name ?? tool.type ?? ""),
144
+ description: typeof fields.description === "string" ? fields.description : "",
145
+ schema: schema ?? null,
146
+ };
147
+ });
148
+ }
149
+ /** Names each tool result after the call it answers, matched by call id. */
150
+ function toolCalls() {
151
+ const names = new Map();
152
+ return {
153
+ use(id, name, text) {
154
+ const tool = String(name ?? "");
155
+ if (typeof id === "string")
156
+ names.set(id, tool);
157
+ return { role: "assistant", kind: "tool_use", name: tool, text, reminder: false };
158
+ },
159
+ result(id, output) {
160
+ const name = typeof id === "string" ? names.get(id) : undefined;
161
+ return { role: "tool", kind: "tool_result", ...(name ? { name } : {}), text: plainText(output), reminder: false };
162
+ },
163
+ };
164
+ }
165
+ /** Tool-call arguments arrive as a JSON string; lay them out like a Messages tool_use input. */
166
+ function callArguments(value) {
167
+ if (typeof value !== "string")
168
+ return JSON.stringify(value ?? {}, null, 2);
169
+ try {
170
+ return JSON.stringify(JSON.parse(value), null, 2);
171
+ }
172
+ catch {
173
+ return value;
174
+ }
175
+ }
176
+ function parseMessages(body) {
177
+ const system = texts(body.system);
178
+ const tools = toolList(body.tools, tool => ({ fields: tool, schema: tool.input_schema }));
179
+ const calls = toolCalls();
180
+ const messages = [];
181
+ for (const message of Array.isArray(body.messages) ? body.messages.filter(isObject) : []) {
182
+ const role = message.role === "assistant" ? "assistant" : "user";
183
+ for (const block of blocks(message.content)) {
184
+ if (block.type === "text" && typeof block.text === "string")
185
+ messages.push(textMessage(role, block.text));
186
+ else if (block.type === "tool_use")
187
+ messages.push(calls.use(block.id, block.name, JSON.stringify(block.input ?? {}, null, 2)));
188
+ else if (block.type === "tool_result")
189
+ messages.push(calls.result(block.tool_use_id, block.content));
190
+ }
191
+ }
192
+ return { system, tools, messages };
193
+ }
194
+ function parseResponses(body) {
195
+ const system = typeof body.instructions === "string" && body.instructions ? [body.instructions] : [];
196
+ const tools = toolList(body.tools, tool => ({ fields: tool, schema: tool.parameters }));
197
+ const calls = toolCalls();
198
+ const messages = [];
199
+ const items = typeof body.input === "string" ? [{ role: "user", content: body.input }] : Array.isArray(body.input) ? body.input.filter(isObject) : [];
200
+ for (const item of items) {
201
+ if (item.type === "function_call" || item.type === "custom_tool_call") {
202
+ messages.push(calls.use(item.call_id, item.name, item.type === "function_call" ? callArguments(item.arguments) : plainText(item.input)));
203
+ }
204
+ else if (item.type === "function_call_output" || item.type === "custom_tool_call_output") {
205
+ messages.push(calls.result(item.call_id, item.output));
206
+ }
207
+ else if (item.type === "input_text" && typeof item.text === "string") {
208
+ messages.push(textMessage("user", item.text));
209
+ }
210
+ else if (typeof item.role === "string" && (item.type === undefined || item.type === "message")) {
211
+ if (item.role === "system" || item.role === "developer")
212
+ system.push(...texts(item.content));
213
+ else
214
+ for (const text of texts(item.content))
215
+ messages.push(textMessage(item.role === "assistant" ? "assistant" : "user", text));
216
+ }
217
+ }
218
+ return { system, tools, messages };
219
+ }
220
+ function parseChat(body) {
221
+ const system = [];
222
+ const tools = toolList(body.tools, tool => {
223
+ const fields = isObject(tool.function) ? tool.function : tool;
224
+ return { fields, schema: fields.parameters };
225
+ });
226
+ const calls = toolCalls();
227
+ const messages = [];
228
+ for (const message of Array.isArray(body.messages) ? body.messages.filter(isObject) : []) {
229
+ if (message.role === "tool") {
230
+ messages.push(calls.result(message.tool_call_id, message.content));
231
+ continue;
232
+ }
233
+ if (message.role === "system" || message.role === "developer") {
234
+ system.push(...texts(message.content));
235
+ continue;
236
+ }
237
+ const role = message.role === "assistant" ? "assistant" : "user";
238
+ for (const text of texts(message.content))
239
+ messages.push(textMessage(role, text));
240
+ for (const call of Array.isArray(message.tool_calls) ? message.tool_calls.filter(isObject) : []) {
241
+ const fn = isObject(call.function) ? call.function : {};
242
+ messages.push(calls.use(call.id, fn.name, callArguments(fn.arguments)));
243
+ }
244
+ }
245
+ return { system, tools, messages };
246
+ }
package/dist/start.js CHANGED
@@ -14,6 +14,7 @@ const node_os_1 = __importDefault(require("node:os"));
14
14
  const node_path_1 = __importDefault(require("node:path"));
15
15
  const classroomApp_1 = require("./classroomApp");
16
16
  const page_1 = require("./page");
17
+ const promptCapture_1 = require("./promptCapture");
17
18
  const clipboard_1 = require("./clipboard");
18
19
  const folderPicker_1 = require("./folderPicker");
19
20
  const commandRunner_1 = require("./commandRunner");
@@ -40,6 +41,13 @@ const activeRequests = new Set();
40
41
  function abortRequests() { for (const controller of activeRequests)
41
42
  controller.abort(); }
42
43
  const traffic = (0, clientTraffic_1.createClientTraffic)();
44
+ // 只存在記憶體;每次啟動錄製都是關閉(ADR-0009)。
45
+ const promptCapture = (0, promptCapture_1.createPromptCapture)();
46
+ const promptCaptureActions = new Map([
47
+ ["/prompt-capture/start", () => promptCapture.start()],
48
+ ["/prompt-capture/pause", () => promptCapture.pause()],
49
+ ["/prompt-capture/clear", () => promptCapture.clear()],
50
+ ]);
43
51
  function routerBaseUrl() {
44
52
  return (process.env.CLASSROOM_ROUTER_BASE_URL ?? "https://ai.vanscoding.com").replace(/\/+$/, "");
45
53
  }
@@ -299,22 +307,7 @@ function modelFromBody(body) {
299
307
  }
300
308
  return "";
301
309
  }
302
- function rewriteModel(body, model) {
303
- try {
304
- const parsed = JSON.parse(body);
305
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
306
- return JSON.stringify({ ...parsed, model });
307
- }
308
- }
309
- catch {
310
- return body;
311
- }
312
- return body;
313
- }
314
310
  function upstreamOrigin(target) {
315
- if (target === "router") {
316
- return routerBaseUrl();
317
- }
318
311
  if (target === "chatgpt") {
319
312
  return "https://chatgpt.com";
320
313
  }
@@ -327,25 +320,18 @@ async function sendUpstream(upstream) {
327
320
  const slot = responseSlot.getStore();
328
321
  if (!slot)
329
322
  return { ok: false };
330
- if (upstream.target === "router" && upstream.client !== "copilot") {
331
- slot.response = await (0, modelProxy_1.sendRouter)(upstream, routerBaseUrl());
323
+ if (upstream.target === "router") {
324
+ // VS Code Chat already speaks Router's protocol; Codex and Claude Code go through a Model API Adapter.
325
+ slot.response = upstream.client === "copilot"
326
+ ? await (0, modelProxy_1.forwardRouter)(upstream, routerBaseUrl(), promptCapture)
327
+ : await (0, modelProxy_1.sendRouter)(upstream, routerBaseUrl(), promptCapture);
332
328
  return { ok: slot.response.ok };
333
329
  }
334
330
  try {
335
- const headers = {
336
- "Content-Type": "application/json",
337
- };
338
- if (upstream.target === "router" && upstream.apiKey) {
339
- headers.Authorization = `Bearer ${upstream.apiKey}`;
340
- }
341
- const body = upstream.target === "router"
342
- ? rewriteModel(upstream.body ?? "", upstream.model)
343
- : upstream.body;
344
- const url = `${upstreamOrigin(upstream.target)}${upstream.path}`;
345
- const response = await fetch(url, {
331
+ const response = await fetch(`${upstreamOrigin(upstream.target)}${upstream.path}`, {
346
332
  method: upstream.method ?? "POST",
347
- headers,
348
- body,
333
+ headers: { "Content-Type": "application/json" },
334
+ body: upstream.body,
349
335
  signal: upstream.signal,
350
336
  });
351
337
  slot.response = response;
@@ -529,6 +515,26 @@ async function main(instance) {
529
515
  res.end(JSON.stringify({ ...(0, page_1.modelStatus)(app.view()), traffic: traffic.flowing() }));
530
516
  return;
531
517
  }
518
+ const captureAction = req.method === "POST" ? promptCaptureActions.get(pathname) : undefined;
519
+ if (captureAction) {
520
+ await readBody(req);
521
+ captureAction();
522
+ if (!(req.headers.accept ?? "").includes("application/json")) {
523
+ redirect(res, "/prompt-inspector");
524
+ return;
525
+ }
526
+ }
527
+ if (captureAction || (req.method === "GET" && pathname === "/prompt-capture")) {
528
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
529
+ res.end(JSON.stringify({ recording: promptCapture.recording, ...promptCapture.list() }));
530
+ return;
531
+ }
532
+ if (req.method === "GET" && pathname === "/prompt-inspector") {
533
+ const html = (0, page_1.renderInspectorPage)({ recording: promptCapture.recording, ...promptCapture.list() });
534
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
535
+ res.end(instance ? (0, lifecyclePage_1.lifecyclePage)(html, instance.token) : html);
536
+ return;
537
+ }
532
538
  if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
533
539
  const variant = parsed.searchParams.get("variant") ?? "";
534
540
  const html = process.env.NODE_ENV !== "production" && (0, pagePrototype_1.isPrototypeVariant)(variant)
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = "0.1.3";
4
+ exports.VERSION = "0.2.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vanspod",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "bin": { "vanspod": "bin/vanspod.cjs" },
5
5
  "engines": { "node": ">=24" },
6
6
  "os": ["win32"],