vanspod 0.1.2 → 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.
@@ -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.2";
4
+ exports.VERSION = "0.2.0";
package/package.json CHANGED
@@ -1,29 +1,30 @@
1
- {
2
- "name": "vanspod",
3
- "version": "0.1.2",
4
- "bin": { "vanspod": "bin/vanspod.cjs" },
5
- "engines": { "node": ">=24" },
6
- "os": ["win32"],
7
- "files": ["bin/", "dist/**/*.js", "!dist/test/**", "!dist/sea-*.js", "media/brand-logo.png", "media/brand-icon.ico", "media/fadou-superhero.png", "media/fadou-superhero-blink.png", "scripts/tray.ps1", "scripts/uninstall.ps1", "README.md"],
8
- "publishConfig": { "access": "public" },
9
- "description": "本機 VansPod。學生用系統瀏覽器兌換課堂連線。",
10
- "scripts": {
11
- "test": "tsc -p . && node --test dist/test/*.test.js",
12
- "typecheck": "tsc -p . --noEmit",
13
- "build": "tsc -p .",
14
- "start": "tsc -p . && node dist/entry.js",
15
- "prepack": "npm run build",
16
- "postinstall": "node bin/register.cjs",
17
- "dist": "node scripts/dist.mjs",
18
- "test:windows-exe": "npm run dist && node scripts/test-windows-exe.mjs",
19
- "test:lifecycle": "tsc -p . && node --test dist/test/launcher.test.js",
20
- "test:distribution": "npm run dist && node scripts/test-distribution.mjs"
21
- },
22
- "devDependencies": {
23
- "@types/node": "^24.5.2",
24
- "typescript": "^5.9.2"
25
- },
26
- "dependencies": {
27
- "yaml": "^2.9.1"
28
- }
29
- }
1
+ {
2
+ "name": "vanspod",
3
+ "version": "0.2.0",
4
+ "bin": { "vanspod": "bin/vanspod.cjs" },
5
+ "engines": { "node": ">=24" },
6
+ "os": ["win32"],
7
+ "files": ["bin/", "dist/**/*.js", "!dist/test/**", "!dist/sea-*.js", "media/brand-logo.png", "media/brand-icon.ico", "media/fadou-superhero.png", "media/fadou-superhero-blink.png", "scripts/tray.ps1", "scripts/uninstall.ps1", "README.md"],
8
+ "publishConfig": { "access": "public" },
9
+ "description": "本機 VansPod。學生用系統瀏覽器兌換課堂連線。",
10
+ "repository": { "type": "git", "url": "git+https://github.com/mz038197/VansPod.git" },
11
+ "scripts": {
12
+ "test": "tsc -p . && node --test dist/test/*.test.js",
13
+ "typecheck": "tsc -p . --noEmit",
14
+ "build": "tsc -p .",
15
+ "start": "tsc -p . && node dist/entry.js",
16
+ "prepack": "npm run build",
17
+ "postinstall": "node bin/register.cjs",
18
+ "dist": "node scripts/dist.mjs",
19
+ "test:windows-exe": "npm run dist && node scripts/test-windows-exe.mjs",
20
+ "test:lifecycle": "tsc -p . && node --test dist/test/launcher.test.js",
21
+ "test:distribution": "npm run dist && node scripts/test-distribution.mjs"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^24.5.2",
25
+ "typescript": "^5.9.2"
26
+ },
27
+ "dependencies": {
28
+ "yaml": "^2.9.1"
29
+ }
30
+ }