@lendle/classroomai 0.0.0-stage → 0.5.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,4 @@
1
+ {
2
+ "relayServerPort": 4141,
3
+ "heartbeatIntervalSec": 10
4
+ }
package/main.js ADDED
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Student Relay 入口(Node.js;CLI-only)。
4
+ *
5
+ * 與 Python 版 student/main.py 對齊:
6
+ * - 預設 CLI:--server-ip / --server-port(缺資訊互動詢問;PIN 隱藏輸入)
7
+ * - 設定檔:工作目錄 classroomai.conf(找不到再用 classroomai.txt;.conf 優先)
8
+ * - 專案目錄=目前工作目錄;連上 Teacher 後自動下載樣板(原子解壓)與 credential
9
+ * - `--gui`:本版為 CLI-only,顯示提示後結束
10
+ *
11
+ * 用法:
12
+ * node main.js --server-ip 192.168.1.100 --server-port 8080 --student-id S042 --pin 583921
13
+ */
14
+ "use strict";
15
+
16
+ const fs = require("fs");
17
+ const path = require("path");
18
+ const readline = require("readline");
19
+
20
+ const STUDENT_DIR = __dirname;
21
+ const CONF_BASE = "classroomai";
22
+ const CONF_EXTENSIONS = [".conf", ".txt"]; // .conf 優先
23
+
24
+ // ---------------------------------------------------------------
25
+ // 參數解析
26
+ // ---------------------------------------------------------------
27
+
28
+ function parseArgs(argv) {
29
+ const args = {
30
+ serverIp: "",
31
+ serverPort: null,
32
+ studentId: "",
33
+ templateId: null,
34
+ pin: "",
35
+ relayPort: null,
36
+ logPayloads: false,
37
+ gui: false,
38
+ headless: false,
39
+ noInteractive: false,
40
+ };
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const a = argv[i];
43
+ const next = () => argv[++i];
44
+ switch (a) {
45
+ case "--server-ip":
46
+ args.serverIp = next() || "";
47
+ break;
48
+ case "--server-port":
49
+ args.serverPort = Number(next());
50
+ break;
51
+ case "--student-id":
52
+ args.studentId = next() || "";
53
+ break;
54
+ case "--template-id":
55
+ args.templateId = next() || "";
56
+ break;
57
+ case "--pin":
58
+ args.pin = next() || "";
59
+ break;
60
+ case "--relay-port":
61
+ args.relayPort = Number(next());
62
+ break;
63
+ case "--log-payloads":
64
+ args.logPayloads = true;
65
+ break;
66
+ case "--gui":
67
+ args.gui = true;
68
+ break;
69
+ case "--headless": // 相容舊參數(等同預設 CLI)
70
+ args.headless = true;
71
+ break;
72
+ case "--no-interactive":
73
+ args.noInteractive = true;
74
+ break;
75
+ default:
76
+ break;
77
+ }
78
+ }
79
+ return args;
80
+ }
81
+
82
+ // ---------------------------------------------------------------
83
+ // 設定檔(classroomai.conf / classroomai.txt)
84
+ // ---------------------------------------------------------------
85
+
86
+ const CONF_KEYS = ["server-ip", "server-port", "pin", "student-id", "template-id", "log-payloads"];
87
+
88
+ function confTruthy(value) {
89
+ return ["1", "true", "yes", "on"].includes(String(value || "").trim().toLowerCase());
90
+ }
91
+
92
+ function parseConfText(text) {
93
+ const conf = {};
94
+ for (const line0 of String(text).split(/\r?\n/)) {
95
+ const line = line0.trim();
96
+ if (!line || line.startsWith("#")) continue;
97
+ const idx = line.indexOf("=");
98
+ if (idx < 0) continue;
99
+ const key = line.slice(0, idx).trim().toLowerCase().replace(/_/g, "-");
100
+ let value = line.slice(idx + 1).trim();
101
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
102
+ value = value.slice(1, -1).trim();
103
+ }
104
+ if (CONF_KEYS.includes(key)) conf[key] = value;
105
+ }
106
+ return conf;
107
+ }
108
+
109
+ /**
110
+ * 讀取設定檔。預設找 CWD 的 classroomai.conf,其次 classroomai.txt。
111
+ * @param {string|null} confPath 指定檔案(測試用)
112
+ */
113
+ function loadConf(confPath = null) {
114
+ const candidates = confPath
115
+ ? [confPath]
116
+ : CONF_EXTENSIONS.map((ext) => path.join(process.cwd(), CONF_BASE + ext));
117
+ const p = candidates.find((c) => fs.existsSync(c) && fs.statSync(c).isFile());
118
+ if (!p) return {};
119
+ try {
120
+ return parseConfText(fs.readFileSync(p, "utf8"));
121
+ } catch {
122
+ return {};
123
+ }
124
+ }
125
+
126
+ /** conf 值只填補 CLI 未提供的欄位(CLI 優先) */
127
+ function applyConf(args, conf) {
128
+ if (conf["server-ip"] && !args.serverIp) args.serverIp = conf["server-ip"];
129
+ if (conf["server-port"] && args.serverPort === null) {
130
+ const n = Number(conf["server-port"]);
131
+ if (!Number.isFinite(n)) {
132
+ const err = new Error(`classroomai.conf 的 server-port 不是數字:${conf["server-port"]}`);
133
+ err.exitCode = 2;
134
+ throw err;
135
+ }
136
+ args.serverPort = n;
137
+ }
138
+ if (conf.pin && !args.pin) args.pin = conf.pin;
139
+ if (conf["student-id"] && !args.studentId) args.studentId = conf["student-id"];
140
+ if (conf["template-id"] && !args.templateId) args.templateId = conf["template-id"];
141
+ if (!args.logPayloads && confTruthy(conf["log-payloads"])) args.logPayloads = true;
142
+ return args;
143
+ }
144
+
145
+ // ---------------------------------------------------------------
146
+ // 互動補齊(缺資訊時詢問;PIN 隱藏輸入)
147
+ // ---------------------------------------------------------------
148
+
149
+ function readHidden(promptText) {
150
+ return new Promise((resolve) => {
151
+ const stdin = process.stdin;
152
+ if (!stdin.isTTY) {
153
+ // 非 TTY(piped):退回一般行輸入(與 Python getpass 的 fallback 類似)
154
+ const rl = readline.createInterface({ input: stdin, output: process.stdout });
155
+ rl.question(promptText, (answer) => {
156
+ rl.close();
157
+ resolve(answer);
158
+ });
159
+ return;
160
+ }
161
+ process.stdout.write(promptText);
162
+ let buf = "";
163
+ const onData = (raw) => {
164
+ const s = raw.toString("utf8");
165
+ if (s === "\u0003") {
166
+ cleanup();
167
+ process.stdout.write("\n");
168
+ process.exit(130);
169
+ }
170
+ if (s.includes("\n") || s.includes("\r") || s.includes("\u0004")) {
171
+ cleanup();
172
+ process.stdout.write("\n");
173
+ resolve(buf);
174
+ return;
175
+ }
176
+ if (s === "\u007f" || s === "\b") {
177
+ buf = buf.slice(0, -1);
178
+ return;
179
+ }
180
+ buf += s;
181
+ };
182
+ const cleanup = () => {
183
+ stdin.setRawMode(false);
184
+ stdin.pause();
185
+ stdin.removeListener("data", onData);
186
+ };
187
+ stdin.setRawMode(true);
188
+ stdin.resume();
189
+ stdin.setEncoding("utf8");
190
+ stdin.on("data", onData);
191
+ });
192
+ }
193
+
194
+ function askLine(promptText) {
195
+ return new Promise((resolve) => {
196
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
197
+ rl.question(promptText, (answer) => {
198
+ rl.close();
199
+ resolve(answer);
200
+ });
201
+ });
202
+ }
203
+
204
+ /**
205
+ * 補齊缺漏欄位:server-ip / server-port / student-id / pin。
206
+ * @param {object} args
207
+ * @param {{askInput?:Function, askSecret?:Function}} [fns] 可注入(測試)
208
+ */
209
+ async function askMissing(args, fns = {}) {
210
+ const askInput = fns.askInput || askLine;
211
+ const askSecret = fns.askSecret || readHidden;
212
+
213
+ if (!args.noInteractive) {
214
+ if (!args.serverIp) args.serverIp = (await askInput("Teacher IP [127.0.0.1]: ")).trim() || "127.0.0.1";
215
+ if (args.serverPort === null) {
216
+ const raw = (await askInput("Teacher port [8080]: ")).trim();
217
+ args.serverPort = raw ? Number(raw) : 8080;
218
+ }
219
+ if (!args.studentId) args.studentId = (await askInput("Student ID(如 S042): ")).trim();
220
+ if (!args.pin) args.pin = (await askSecret("課堂 PIN(輸入不顯示): ")).trim();
221
+ }
222
+
223
+ const missing = [];
224
+ if (!args.serverIp) missing.push("serverIp");
225
+ if (!args.serverPort) missing.push("serverPort");
226
+ if (!args.studentId) missing.push("studentId");
227
+ if (!args.pin) missing.push("pin");
228
+ if (missing.length) {
229
+ const err = new Error(
230
+ `缺少必要資訊:${missing.join(", ")}\n` +
231
+ "請用 --server-ip/--server-port/--student-id/--pin 提供,或開啟互動詢問。"
232
+ );
233
+ err.exitCode = 2;
234
+ throw err;
235
+ }
236
+ return args;
237
+ }
238
+
239
+ // ---------------------------------------------------------------
240
+ // 執行
241
+ // ---------------------------------------------------------------
242
+
243
+ function loadConfig() {
244
+ const p = path.join(STUDENT_DIR, "config", "config.json");
245
+ const defaults = { relayServerPort: 4141, heartbeatIntervalSec: 10 };
246
+ try {
247
+ return { ...defaults, ...JSON.parse(fs.readFileSync(p, "utf8")) };
248
+ } catch {
249
+ return defaults;
250
+ }
251
+ }
252
+
253
+ async function runCli(args) {
254
+ // 參數來源優先序:commandline > classroomai.conf/.txt > 互動詢問 > 預設
255
+ args = await askMissing(applyConf(args, loadConf()));
256
+
257
+ const { RelayRuntime } = require("./relay/runtime");
258
+ const projectDir = process.cwd();
259
+ const config = loadConfig();
260
+ if (args.relayPort) config.relayServerPort = args.relayPort;
261
+
262
+ const runtime = new RelayRuntime(args.serverIp, Number(args.serverPort), args.studentId, args.pin, config, {
263
+ projectDir,
264
+ templateId: args.templateId || "default",
265
+ logPayloads: !!args.logPayloads,
266
+ });
267
+
268
+ await runtime.start();
269
+ console.log(`[relay] student: ${args.studentId} 專案資料夾: ${projectDir}`);
270
+ console.log(`[relay] OpenCode endpoint: http://127.0.0.1:${config.relayServerPort}/v1`);
271
+ console.log("[relay] 連上 Teacher 後會自動下載樣板(解壓至專案資料夾)與 credential(key)");
272
+
273
+ const shutdown = async () => {
274
+ console.log("stopped");
275
+ await runtime.stop();
276
+ process.exit(0);
277
+ };
278
+ process.on("SIGINT", shutdown);
279
+ process.on("SIGTERM", shutdown);
280
+ }
281
+
282
+ const USAGE = `AI Coding Classroom Student Relay(Node.js;CLI 為主)
283
+
284
+ 用法:
285
+ node main.js --server-ip 192.168.1.100 --server-port 8080 --student-id S042 --pin 583921 [選項]
286
+
287
+ 選項:
288
+ --server-ip <ip> Teacher 的 IP(缺少時互動詢問,預設 127.0.0.1)
289
+ --server-port <port> Teacher 的 port(缺少時互動詢問,預設 8080)
290
+ --student-id <id> Student ID(如 S042)
291
+ --pin <pin> 課堂 PIN(只存記憶體)
292
+ --template-id <name> 要求的模板名稱(預設 default)
293
+ --relay-port <port> local API 埠(預設 4141)
294
+ --log-payloads 記錄成功請求的完整 prompt/response 到工作目錄 .logs/relay
295
+ --no-interactive 缺資訊時不詢問、直接報錯(自動化腳本用)
296
+ --headless (相容舊參數)等同預設 CLI 模式
297
+ -h, --help 顯示本說明
298
+
299
+ 設定檔(工作目錄):classroomai.conf(找不到時 classroomai.txt)
300
+ 可設定:server-ip / server-port / pin / student-id / template-id / log-payloads
301
+ 參數優先序:commandline > 設定檔 > 互動詢問 > 預設值
302
+ `;
303
+
304
+ async function main(argv = process.argv.slice(2)) {
305
+ if (argv.includes("--help") || argv.includes("-h")) {
306
+ console.log(USAGE);
307
+ return 0;
308
+ }
309
+ const args = parseArgs(argv);
310
+ if (args.gui) {
311
+ console.error("studentJS 為 CLI-only 版本,不支援 --gui(請使用 Python 版的 GUI 或直接以 CLI 執行)。");
312
+ return 1;
313
+ }
314
+ try {
315
+ await runCli(args);
316
+ return 0;
317
+ } catch (e) {
318
+ console.error(e.message || String(e));
319
+ return e.exitCode || 1;
320
+ }
321
+ }
322
+
323
+ if (require.main === module) {
324
+ main().then((code) => {
325
+ if (code !== 0) process.exit(code);
326
+ // 否則由 runtime 持續執行(SIGINT 時結束)
327
+ });
328
+ }
329
+
330
+ module.exports = {
331
+ parseArgs,
332
+ loadConf,
333
+ parseConfText,
334
+ applyConf,
335
+ confTruthy,
336
+ askMissing,
337
+ readHidden,
338
+ loadConfig,
339
+ runCli,
340
+ main,
341
+ CONF_KEYS,
342
+ };
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@lendle/classroomai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "AI Coding Classroom Student Relay (Node.js CLI; Data Plane)",
5
+ "main": "main.js",
6
+ "scripts": {
7
+ "start": "node main.js",
8
+ "test": "node --test --test-reporter=dot \"test/*.test.js\""
9
+ },
10
+ "bin": {
11
+ "classroomai": "./main.js"
12
+ },
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "dependencies": {
17
+ "ws": "^8.18.0"
18
+ },
19
+ "author": "Chun-Hsiung Tseng",
20
+ "license": "Apache-2.0",
21
+ "files":[
22
+ "relay/",
23
+ "main.js",
24
+ "standalone.js",
25
+ "config/"
26
+ ]
27
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * RelayEngine:State + Limiter + session 統計 + 降速(與 Python 版對齊)。
3
+ *
4
+ * - canAcceptRequest:gate(status + 三窗口),通過才記錄 timestamp。
5
+ * - recordChatResponse:記錄實際 upstream model id / tokens(session 統計)。
6
+ * - throttleDelay:依 5m 窗口「進來當下」用量計算請求間等待(10/15/30s 檔位)。
7
+ */
8
+ "use strict";
9
+
10
+ const { RequestLimiter } = require("./limiter");
11
+ const { RelayState, timeNowMs } = require("./state");
12
+
13
+ // 降速檔位(秒):依 5m window 動態使用量
14
+ const THROTTLE_STEPS_SECONDS = [10, 15, 30];
15
+
16
+ class RelayEngine {
17
+ constructor(relayId = "") {
18
+ this.state = new RelayState(relayId);
19
+ this.limiter = new RequestLimiter();
20
+ this.activeRequests = 0;
21
+ this.errorCount = 0;
22
+ // API key 只存記憶體(Teacher credential 或 fallback key)
23
+ this.apiKey = null;
24
+ // 是否使用 fallback key(true = 只能 openrouter/free;heartbeat 回報 Teacher)
25
+ this.usingFallbackKey = false;
26
+ this.sessionStartedMs = timeNowMs();
27
+ this.sessionRequests = 0;
28
+ this.sessionTokens = 0;
29
+ this.sessionByModel = {};
30
+ }
31
+
32
+ // --- gate ---
33
+
34
+ /** @returns {{ok:boolean, reason?:string}} */
35
+ canAcceptRequest() {
36
+ if (this.state.status !== "enabled") {
37
+ return { ok: false, reason: "relay is disabled" };
38
+ }
39
+ this.limiter.setLimits(this.state.requestLimit);
40
+ const res = this.limiter.allow();
41
+ return res.ok ? { ok: true } : { ok: false, reason: res.reason || "limit exceeded" };
42
+ }
43
+
44
+ requestStarted() {
45
+ this.activeRequests += 1;
46
+ }
47
+
48
+ requestFinished(hadError = false) {
49
+ this.activeRequests = Math.max(0, this.activeRequests - 1);
50
+ if (hadError) this.errorCount += 1;
51
+ }
52
+
53
+ usageSnapshot() {
54
+ return this.limiter.usage();
55
+ }
56
+
57
+ // --- session 統計 ---
58
+
59
+ recordChatResponse(modelId, totalTokens) {
60
+ const mid = modelId || "(unknown)";
61
+ this.sessionRequests += 1;
62
+ if (typeof totalTokens === "number") this.sessionTokens += totalTokens;
63
+ this.sessionByModel[mid] = (this.sessionByModel[mid] || 0) + 1;
64
+ }
65
+
66
+ sessionStats() {
67
+ return {
68
+ startedAt: this.sessionStartedMs,
69
+ totalRequests: this.sessionRequests,
70
+ totalTokens: this.sessionTokens,
71
+ byModel: { ...this.sessionByModel },
72
+ };
73
+ }
74
+
75
+ // --- 降速 ---
76
+
77
+ fiveMinWindowCount() {
78
+ return this.limiter.usage()["5m"] || 0;
79
+ }
80
+
81
+ /**
82
+ * 依 5m window 目前用量,回傳此 request 應等待的秒數(0 = 不限速)。
83
+ * prior < 1/4 → 0;1/4–2/4 → 10s;2/4–3/4 → 15s;≥3/4 → 30s。
84
+ */
85
+ throttleDelay(priorCount) {
86
+ const limit = this.state.requestLimit["5m"] || 0;
87
+ if (!limit || limit <= 0) return 0;
88
+ const [s1, s2, s3] = THROTTLE_STEPS_SECONDS;
89
+ if (priorCount < (limit * 1) / 4) return 0;
90
+ if (priorCount < (limit * 2) / 4) return s1;
91
+ if (priorCount < (limit * 3) / 4) return s2;
92
+ return s3;
93
+ }
94
+ }
95
+
96
+ module.exports = { RelayEngine, THROTTLE_STEPS_SECONDS };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Request Limiter:5m / 30m / 60m 三個滑動窗口(與 Python 版對齊)。
3
+ *
4
+ * - 只做固定三窗口計數。
5
+ * - 任一窗口超過限制 → 拒絕新 request;執行中的不中斷。
6
+ * - now 可注入(測試用)。
7
+ */
8
+ "use strict";
9
+
10
+ const WINDOW_SECONDS = { "5m": 300, "30m": 1800, "60m": 3600 };
11
+
12
+ class RequestLimiter {
13
+ constructor(limits = { "5m": 20, "30m": 80, "60m": 120 }, now = Date.now) {
14
+ this.limits = { ...limits };
15
+ this._now = now;
16
+ this._timestamps = {};
17
+ for (const k of Object.keys(WINDOW_SECONDS)) this._timestamps[k] = [];
18
+ }
19
+
20
+ setLimits(limits = {}) {
21
+ for (const k of Object.keys(WINDOW_SECONDS)) {
22
+ if (limits[k] !== undefined) this.limits[k] = limits[k];
23
+ }
24
+ }
25
+
26
+ /**
27
+ * 檢查並記錄一次 request。
28
+ * @returns {{ok:boolean, reason?:string}}
29
+ */
30
+ allow() {
31
+ const now = this._now();
32
+ this._prune(now);
33
+ for (const [window, limit] of Object.entries(this.limits)) {
34
+ if (this._timestamps[window].length >= limit) {
35
+ return {
36
+ ok: false,
37
+ reason: `limit exceeded: ${window} (${this._timestamps[window].length}/${limit})`,
38
+ };
39
+ }
40
+ }
41
+ for (const window of Object.keys(this._timestamps)) {
42
+ this._timestamps[window].push(now);
43
+ }
44
+ return { ok: true };
45
+ }
46
+
47
+ /** 三窗口目前計數 */
48
+ usage() {
49
+ const now = this._now();
50
+ this._prune(now);
51
+ const out = {};
52
+ for (const [k, v] of Object.entries(this._timestamps)) out[k] = v.length;
53
+ return out;
54
+ }
55
+
56
+ _prune(now) {
57
+ for (const [window, seconds] of Object.entries(WINDOW_SECONDS)) {
58
+ const q = this._timestamps[window];
59
+ const cutoff = now - seconds * 1000;
60
+ while (q.length && q[0] <= cutoff) q.shift();
61
+ }
62
+ }
63
+ }
64
+
65
+ module.exports = { RequestLimiter, WINDOW_SECONDS };