@lendle/classroomai 0.0.0-stage → 0.6.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/relay/log.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Relay 檔案 log(與 Python 版同格式/保留策略)。
3
+ *
4
+ * - `studentJS/.logs/relay/relay.log`:每日輪替、保留 5 天(`relay.log.YYYY-MM-DD`)。
5
+ * - `studentJS/.logs/status/template_installed`:只有 ms timestamp(覆寫模式)。
6
+ * - 不輸出到 console(由呼叫端決定是否另外 print)。
7
+ * - `RELAY_LOG_DIR` 可覆寫 log 目錄(測試用)。
8
+ */
9
+ "use strict";
10
+
11
+ const fs = require("fs");
12
+ const path = require("path");
13
+
14
+ const STUDENT_DIR = path.resolve(__dirname, "..");
15
+ const DEFAULT_LOG_DIR = path.join(STUDENT_DIR, ".logs", "relay");
16
+ const KEEP_DAYS = 5;
17
+
18
+ let _configured = false;
19
+ let _logDir = null;
20
+ let _currentDay = "";
21
+ let _installedCache = new Set();
22
+
23
+ function pad2(n) {
24
+ return String(n).padStart(2, "0");
25
+ }
26
+
27
+ function dayStamp(d = new Date()) {
28
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
29
+ }
30
+
31
+ function timeStamp(d = new Date()) {
32
+ return `${dayStamp(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
33
+ }
34
+
35
+ function defaultLogDir() {
36
+ return process.env.RELAY_LOG_DIR ? path.resolve(process.env.RELAY_LOG_DIR) : DEFAULT_LOG_DIR;
37
+ }
38
+
39
+ class RelayLogger {
40
+ constructor(dir) {
41
+ this.dir = path.resolve(dir);
42
+ this.file = path.join(this.dir, "relay.log");
43
+ fs.mkdirSync(this.dir, { recursive: true });
44
+ this._cleanupRotated();
45
+ }
46
+
47
+ _cleanupRotated() {
48
+ let files;
49
+ try {
50
+ files = fs.readdirSync(this.dir).filter((f) => /^relay\.log\.\d{4}-\d{2}-\d{2}$/.test(f)).sort();
51
+ } catch {
52
+ return;
53
+ }
54
+ while (files.length > KEEP_DAYS) {
55
+ const f = files.shift();
56
+ try {
57
+ fs.unlinkSync(path.join(this.dir, f));
58
+ } catch {
59
+ /* 忽略 */
60
+ }
61
+ }
62
+ }
63
+
64
+ /** 跨日 → 將 relay.log 改名為 relay.log.<舊日期> 並清舊檔 */
65
+ _rotateIfNeeded() {
66
+ const today = dayStamp();
67
+ if (_currentDay === today) return;
68
+ if (_currentDay && fs.existsSync(this.file)) {
69
+ try {
70
+ fs.renameSync(this.file, `${this.file}.${_currentDay}`);
71
+ } catch {
72
+ /* 忽略改名失敗,繼續寫入 */
73
+ }
74
+ }
75
+ _currentDay = today;
76
+ this._cleanupRotated();
77
+ }
78
+
79
+ _write(level, msg) {
80
+ // 每次寫入前確保目錄存在(執行中 .logs/relay 被刪除也能自動重建)
81
+ try {
82
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
83
+ } catch {
84
+ /* 忽略 */
85
+ }
86
+ this._rotateIfNeeded();
87
+ const line = `${timeStamp()} ${level} ${msg}\n`;
88
+ try {
89
+ fs.appendFileSync(this.file, line, "utf8");
90
+ } catch {
91
+ /* log 寫入失敗不影響 relay 本體(template 的嚴格模式由呼叫端處理) */
92
+ }
93
+ }
94
+
95
+ info(msg) {
96
+ this._write("INFO", msg);
97
+ }
98
+
99
+ warning(msg) {
100
+ this._write("WARNING", msg);
101
+ }
102
+
103
+ error(msg) {
104
+ this._write("ERROR", msg);
105
+ }
106
+
107
+ statusPath(event) {
108
+ return path.join(path.dirname(this.dir), "status", event);
109
+ }
110
+
111
+ /** 寫 status 事件(內容只有 ms timestamp,覆寫模式) */
112
+ recordStatusEvent(event, ts = Date.now()) {
113
+ const p = this.statusPath(event);
114
+ fs.mkdirSync(path.dirname(p), { recursive: true });
115
+ fs.writeFileSync(p, `${ts}\n`, "utf8");
116
+ }
117
+ }
118
+
119
+ function setupRelayLogger(dir) {
120
+ if (_configured || _logger) return _logger;
121
+ _logDir = path.resolve(dir || defaultLogDir());
122
+ _logger = new RelayLogger(_logDir);
123
+ _configured = true;
124
+ return _logger;
125
+ }
126
+
127
+ let _logger = null;
128
+
129
+ function relayLogger() {
130
+ return setupRelayLogger();
131
+ }
132
+
133
+ /**
134
+ * 記錄 template 安裝完成(去重 key:name|version|target|via)。
135
+ * 寫入順序:relay.log → status → 才登記 cache;任一寫入失敗會 throw(呼叫端據此不前進版本)。
136
+ */
137
+ function logTemplateInstalled(name, version, targetDir, fileCount, via = "auto") {
138
+ const logger = relayLogger();
139
+ const key = `${name}|v${version}|${targetDir}|${via}`;
140
+ if (_installedCache.has(key)) return false;
141
+ logger.info(
142
+ `template installed: name=${name} version=${version} target=${targetDir} files=${fileCount} via=${via}`
143
+ );
144
+ logger.recordStatusEvent("template_installed");
145
+ _installedCache.add(key);
146
+ return true;
147
+ }
148
+
149
+ /**
150
+ * 記錄 template 安裝失敗(只寫 relay.log;phase = extract / log / no-content)。
151
+ * 寫入失敗不拋(最後防線)。
152
+ */
153
+ function logTemplateFailed(name, version, targetDir, phase, error) {
154
+ try {
155
+ relayLogger().error(
156
+ `template install failed: phase=${phase} name=${name} version=${version} target=${targetDir} error=${error}`
157
+ );
158
+ } catch (e) {
159
+ console.error(`[relay] 無法寫入 relay.log(${e.message});安裝失敗:phase=${phase} ${error}`);
160
+ }
161
+ }
162
+
163
+ module.exports = {
164
+ STUDENT_DIR,
165
+ DEFAULT_LOG_DIR,
166
+ KEEP_DAYS,
167
+ RelayLogger,
168
+ setupRelayLogger,
169
+ relayLogger,
170
+ logTemplateInstalled,
171
+ logTemplateFailed,
172
+ dayStamp,
173
+ // 測試用
174
+ _installedCache,
175
+ _resetForTests() {
176
+ _configured = false;
177
+ _logger = null;
178
+ _logDir = null;
179
+ _currentDay = "";
180
+ _installedCache = new Set();
181
+ },
182
+ };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * OpenRouter 轉發(Data Plane)。
3
+ *
4
+ * - OpenAI-compatible request 轉送 https://openrouter.ai/api/v1(可用
5
+ * OPENROUTER_BASE_OVERRIDE 覆寫,整合測試用)。
6
+ * - 回應完全串流(SSE 不暫存);由 server 把 chunk 直接寫回 client。
7
+ * - 只讀 API Key(記憶體);不落檔、不落 log。
8
+ */
9
+ "use strict";
10
+
11
+ const http = require("http");
12
+ const https = require("https");
13
+
14
+ const OPENROUTER_BASE = process.env.OPENROUTER_BASE_OVERRIDE || "https://openrouter.ai/api/v1";
15
+ const STREAM_IDLE_TIMEOUT_MS = 300_000; // 串流:只限 idle(LLM 回應可能很慢)
16
+
17
+ class OpenRouterClient {
18
+ constructor(baseUrl = OPENROUTER_BASE) {
19
+ this.baseUrl = String(baseUrl).replace(/\/+$/, "");
20
+ }
21
+
22
+ _url(pathname) {
23
+ return `${this.baseUrl}/${String(pathname).replace(/^\/+/, "")}`;
24
+ }
25
+
26
+ _request(method, pathname, apiKey, body) {
27
+ const url = new URL(this._url(pathname));
28
+ const transport = url.protocol === "https:" ? https : http;
29
+ const payload = body === undefined ? null : Buffer.from(JSON.stringify(body), "utf8");
30
+ const headers = {
31
+ Accept: "text/event-stream, application/json",
32
+ };
33
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
34
+ if (payload) {
35
+ headers["Content-Type"] = "application/json";
36
+ headers["Content-Length"] = String(payload.length);
37
+ }
38
+ return { url, transport, payload, headers, method };
39
+ }
40
+
41
+ /**
42
+ * 開啟串流轉發(POST)。
43
+ * @returns {Promise<{status:number, headers:object, stream:import("stream").Readable, close:Function}>}
44
+ */
45
+ openStream(apiKey, pathname, body) {
46
+ const { url, transport, payload, headers, method } = this._request("POST", pathname, apiKey, body);
47
+ return new Promise((resolve, reject) => {
48
+ const req = transport.request(
49
+ url,
50
+ { method, headers },
51
+ (res) => {
52
+ resolve({
53
+ status: res.statusCode,
54
+ headers: res.headers,
55
+ stream: res,
56
+ close: () => {
57
+ try {
58
+ res.destroy();
59
+ } catch {
60
+ /* 忽略 */
61
+ }
62
+ },
63
+ });
64
+ }
65
+ );
66
+ req.setTimeout(STREAM_IDLE_TIMEOUT_MS, () => {
67
+ req.destroy(new Error("upstream idle timeout"));
68
+ });
69
+ req.on("error", (e) => reject(e));
70
+ if (payload) req.write(payload);
71
+ req.end();
72
+ });
73
+ }
74
+
75
+ /** 一般 GET(如 /models);回傳 { status, text } */
76
+ get(apiKey, pathname) {
77
+ const { url, transport, headers, method } = this._request("GET", pathname, apiKey);
78
+ return new Promise((resolve, reject) => {
79
+ const req = transport.request(url, { method, headers }, (res) => {
80
+ const chunks = [];
81
+ res.on("data", (c) => chunks.push(c));
82
+ res.on("end", () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString("utf8") }));
83
+ res.on("error", reject);
84
+ });
85
+ req.setTimeout(STREAM_IDLE_TIMEOUT_MS, () => req.destroy(new Error("upstream idle timeout")));
86
+ req.on("error", reject);
87
+ req.end();
88
+ });
89
+ }
90
+ }
91
+
92
+ module.exports = { OpenRouterClient, OPENROUTER_BASE, STREAM_IDLE_TIMEOUT_MS };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Payload logger(opt-in):記錄每一次成功 chat/completions 的完整 prompt 與 response。
3
+ *
4
+ * 與 Python 版一致:
5
+ * - `log-payloads=true` / `--log-payloads` 才啟用;否則維持原樣。
6
+ * - 寫到「工作目錄」`.logs/relay/payload-*.json`(不寫 relay.log)。
7
+ * - prompt 以 messages **陣列**保存;request 存放其餘欄位。
8
+ * - 只記錄成功(2xx);單檔 10MB(先截 response,必要時截 prompt);保留 5 天。
9
+ */
10
+ "use strict";
11
+
12
+ const fs = require("fs");
13
+ const path = require("path");
14
+
15
+ const MAX_FILE_BYTES = 10 * 1024 * 1024;
16
+ const MAX_RESPONSE_CAPTURE = MAX_FILE_BYTES;
17
+ const KEEP_DAYS = 5;
18
+
19
+ function pad2(n) {
20
+ return String(n).padStart(2, "0");
21
+ }
22
+
23
+ function payloadName(d = new Date()) {
24
+ return (
25
+ `payload-${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-` +
26
+ `${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`
27
+ );
28
+ }
29
+
30
+ class PayloadLogger {
31
+ constructor(enabled = false, baseDir = null) {
32
+ this.enabled = !!enabled;
33
+ // 「工作目錄」下的 .logs/relay(CLI 的 CWD 即專案目錄)
34
+ this.dir = baseDir ? path.resolve(baseDir) : path.join(process.cwd(), ".logs", "relay");
35
+ this._seq = 0;
36
+ this._lastCleanupDay = "";
37
+ if (this.enabled) {
38
+ try {
39
+ fs.mkdirSync(this.dir, { recursive: true });
40
+ } catch {
41
+ /* 忽略 */
42
+ }
43
+ this.cleanup();
44
+ }
45
+ }
46
+
47
+ /** 刪除超過 5 天的 payload-*.json(只動自己的檔案) */
48
+ cleanup(nowMs = Date.now()) {
49
+ const cutoff = nowMs - KEEP_DAYS * 86400 * 1000;
50
+ let files;
51
+ try {
52
+ files = fs.readdirSync(this.dir);
53
+ } catch {
54
+ return;
55
+ }
56
+ for (const f of files) {
57
+ if (!f.startsWith("payload-") || !f.endsWith(".json")) continue;
58
+ const p = path.join(this.dir, f);
59
+ try {
60
+ if (fs.statSync(p).mtimeMs < cutoff) fs.unlinkSync(p);
61
+ } catch {
62
+ /* 忽略 */
63
+ }
64
+ }
65
+ }
66
+
67
+ _cleanupDaily() {
68
+ const today = payloadName().slice("payload-".length, "payload-".length + 8);
69
+ if (today !== this._lastCleanupDay) {
70
+ this._lastCleanupDay = today;
71
+ this.cleanup();
72
+ }
73
+ }
74
+
75
+ /**
76
+ * 寫入一筆(僅 enabled;僅供 2xx 成功請求呼叫)。
77
+ * @returns {string|null} 寫入檔案路徑;未啟用/失敗回 null。
78
+ */
79
+ record({ path: reqPath, body, response, status, modelId, tokens, durationMs, responseTruncated = false }) {
80
+ if (!this.enabled) return null;
81
+ try {
82
+ this._cleanupDaily();
83
+ this._seq += 1;
84
+ const record = {
85
+ timestamp: Date.now(),
86
+ prompt: Array.isArray(body && body.messages) ? body.messages : [],
87
+ request: Object.fromEntries(Object.entries(body || {}).filter(([k]) => k !== "messages")),
88
+ response: Buffer.from(response || []).toString("utf8"),
89
+ response_truncated: !!responseTruncated,
90
+ path: reqPath,
91
+ status,
92
+ actual_model: modelId,
93
+ tokens: tokens === undefined ? null : tokens,
94
+ duration_ms: durationMs,
95
+ };
96
+ const text = PayloadLogger._serializeWithLimits(record);
97
+ const name = `${payloadName()}-${String(this._seq).padStart(4, "0")}.json`;
98
+ const dest = path.join(this.dir, name);
99
+ fs.mkdirSync(this.dir, { recursive: true });
100
+ fs.writeFileSync(dest, text, "utf8");
101
+ return dest;
102
+ } catch {
103
+ return null; // best-effort
104
+ }
105
+ }
106
+
107
+ /** 序列化;超過 10MB 依序截 response → prompt(並標記)。 */
108
+ static _serializeWithLimits(record) {
109
+ let text = JSON.stringify(record);
110
+ if (Buffer.byteLength(text, "utf8") <= MAX_FILE_BYTES) return text;
111
+
112
+ record = { ...record };
113
+ record.response_truncated = true;
114
+ const overhead = Buffer.byteLength(JSON.stringify({ ...record, response: "" }), "utf8");
115
+ const budget = Math.max(0, MAX_FILE_BYTES - overhead - 256);
116
+ record.response = Buffer.from(record.response, "utf8").subarray(0, budget).toString("utf8");
117
+ text = JSON.stringify(record);
118
+ if (Buffer.byteLength(text, "utf8") <= MAX_FILE_BYTES) return text;
119
+
120
+ record.prompt = ["[prompt too large: truncated]"];
121
+ record.prompt_truncated = true;
122
+ record.request = {};
123
+ return JSON.stringify(record);
124
+ }
125
+ }
126
+
127
+ module.exports = { PayloadLogger, MAX_FILE_BYTES, MAX_RESPONSE_CAPTURE, KEEP_DAYS };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Protocol envelope 與 heartbeat/register 訊息(與 Python protocol/messages.py 對齊)。
3
+ */
4
+ "use strict";
5
+
6
+ const crypto = require("crypto");
7
+ const os = require("os");
8
+
9
+ const PROTOCOL_VERSION = 1;
10
+
11
+ function newEnvelope(type, payload = {}) {
12
+ return {
13
+ type,
14
+ messageId: crypto.randomUUID(),
15
+ timestamp: Date.now(),
16
+ payload,
17
+ };
18
+ }
19
+
20
+ function getHostname() {
21
+ return os.hostname();
22
+ }
23
+
24
+ function makeRegister(relayId, studentId, pin, templateId = "default") {
25
+ return newEnvelope("register", {
26
+ relayId,
27
+ studentId,
28
+ hostname: getHostname(),
29
+ pin,
30
+ templateId,
31
+ protocolVersion: PROTOCOL_VERSION,
32
+ });
33
+ }
34
+
35
+ /**
36
+ * heartbeat 訊息;session 以節流方式附帶(第 1 次與每 10 次)。
37
+ * @param {{relayId:string, status:string, usage:object, activeRequests:number, errorCount:number,
38
+ * policyVersion:number, templateVersion:number, modelRoutingVersion:number,
39
+ * usingFallbackKey:boolean, sessionStats:(()=>object|null)}} rep
40
+ */
41
+ function makeHeartbeat(rep) {
42
+ const msg = newEnvelope("heartbeat", {
43
+ relayId: rep.relayId,
44
+ status: rep.status,
45
+ usage: rep.usage,
46
+ activeRequests: rep.activeRequests,
47
+ errorCount: rep.errorCount,
48
+ policyVersion: rep.policyVersion,
49
+ projectTemplateVersion: rep.templateVersion,
50
+ modelRoutingVersion: rep.modelRoutingVersion,
51
+ usingFallbackKey: !!rep.usingFallbackKey,
52
+ });
53
+ const session = rep.sessionStats();
54
+ if (session) msg.payload.session = session;
55
+ return msg;
56
+ }
57
+
58
+ function parseMessage(raw) {
59
+ let msg;
60
+ try {
61
+ msg = JSON.parse(raw.toString());
62
+ } catch {
63
+ throw new Error("invalid json");
64
+ }
65
+ if (!msg || typeof msg !== "object" || !msg.type) throw new Error("message missing type");
66
+ return msg;
67
+ }
68
+
69
+ module.exports = {
70
+ PROTOCOL_VERSION,
71
+ newEnvelope,
72
+ getHostname,
73
+ makeRegister,
74
+ makeHeartbeat,
75
+ parseMessage,
76
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Relay runtime:把 engine + TeacherClient + LocalApiServer 串成一座 Relay
3
+ * (與 Python 版 relay/runtime.py 對齊;CLI 模式)。
4
+ */
5
+ "use strict";
6
+
7
+ const crypto = require("crypto");
8
+ const { RelayEngine } = require("./engine");
9
+ const { LocalApiServer } = require("./server");
10
+ const { OpenRouterClient } = require("./openrouter");
11
+ const { TeacherClient } = require("./websocket");
12
+ const { PayloadLogger } = require("./payload-log");
13
+
14
+ const DEFAULT_CONFIG = { relayServerPort: 4141, heartbeatIntervalSec: 10 };
15
+
16
+ class RelayRuntime {
17
+ /**
18
+ * @param {string} host Teacher IP
19
+ * @param {number} port Teacher port
20
+ * @param {string} studentId
21
+ * @param {string} pin
22
+ * @param {{relayServerPort?:number, heartbeatIntervalSec?:number}} config
23
+ * @param {{projectDir?:string|null, templateId?:string, logPayloads?:boolean}} [opts]
24
+ */
25
+ constructor(host, port, studentId, pin, config = {}, opts = {}) {
26
+ this.engine = new RelayEngine(`relay-${crypto.randomBytes(4).toString("hex")}`);
27
+ this.engine.state.studentId = studentId;
28
+ this.config = { ...DEFAULT_CONFIG, ...config };
29
+ this.projectDir = opts.projectDir ?? null;
30
+ this.teacher = new TeacherClient(this.engine, host, port, studentId, pin, {
31
+ heartbeatInterval: this.config.heartbeatIntervalSec ?? 10,
32
+ autoTemplateDir: this.projectDir,
33
+ templateId: opts.templateId || "default",
34
+ });
35
+ this.apiServer = new LocalApiServer(this.engine, {
36
+ port: this.config.relayServerPort ?? 4141,
37
+ client: new OpenRouterClient(),
38
+ payloadLog: new PayloadLogger(!!opts.logPayloads),
39
+ });
40
+ this._runPromise = null;
41
+ }
42
+
43
+ async start() {
44
+ // 先載入 fallback(若有):即使 Teacher 完全連不上也能提供 free 模型服務
45
+ this.teacher._ensureApiKey();
46
+ await this.apiServer.start();
47
+ this._runPromise = this.teacher.run();
48
+ this._runPromise.catch(() => {
49
+ /* 由 run() 內部處理重連 */
50
+ });
51
+ }
52
+
53
+ async stop() {
54
+ this.teacher.stop();
55
+ await this.apiServer.stop();
56
+ if (this._runPromise) {
57
+ try {
58
+ await Promise.race([this._runPromise, new Promise((r) => setTimeout(r, 1000))]);
59
+ } catch {
60
+ /* 忽略 */
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ module.exports = { RelayRuntime, DEFAULT_CONFIG };