@edryslabs/edrys-dev 0.3.3 → 0.4.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/dist/tutor.js CHANGED
@@ -14,6 +14,11 @@ const QUEUE_MAX = 30;
14
14
  const HOUR = 3_600_000;
15
15
  // characters of room state per question, as JSON
16
16
  export const STATE_MAX = 20000;
17
+ // the student's tab gives up after 3 minutes: waiting for a run, reading the
18
+ // room state and the run itself stay below that
19
+ const QUEUE_MS = 30_000;
20
+ export const STATE_MS = 10_000;
21
+ export const CLASS_PER_HOUR = 200;
17
22
  // codex has no list of allowed tools: everything that adds one is switched off
18
23
  // (checked with codex 0.165.0; a feature it no longer knows makes it fail)
19
24
  const CODEX_OFF = [
@@ -31,6 +36,15 @@ const CODEX_CONFIG = [
31
36
  'include_collaboration_mode_instructions=false',
32
37
  'include_apps_instructions=false',
33
38
  ];
39
+ /**
40
+ * What the tutor's answers are paid with: an API key in the environment, or
41
+ * the account the agent CLI is signed in to.
42
+ */
43
+ export function tutorAuth(agent = 'claude', env = process.env) {
44
+ if (agent === 'codex')
45
+ return env.CODEX_API_KEY ? 'API key from CODEX_API_KEY' : 'the account codex is signed in to';
46
+ return env.ANTHROPIC_API_KEY ? 'API key from ANTHROPIC_API_KEY' : 'the account claude is signed in to';
47
+ }
34
48
  // what a codex --json run may report; anything else is a tool it used
35
49
  const CODEX_ITEMS = ['agent_message', 'reasoning', 'error'];
36
50
  const RULES = `You are the tutor of an edrys-Lite class: students ask you while they work through the lab below. Help each student learn: explain, give hints, ask back what they tried, point to the part of the lab that helps. Do not hand out whole solutions to tasks of the lab, unless the teacher's notes allow it. Answer short and friendly, in the language of the student, in Markdown.
@@ -60,8 +74,9 @@ function fileOf(student) {
60
74
  * student and `perHour` an hour.
61
75
  *
62
76
  * Emits `entry` ({student, name, entry}) for every question and answer,
63
- * `failed` ({student, name, error}) when the agent could not answer, and
64
- * `switch` (on) when the teacher turned it on or off.
77
+ * `failed` ({student, name, error}) when the agent could not answer,
78
+ * `switch` (on) when the teacher turned it on or off, and `limit` (perHour)
79
+ * when the class reached its questions per hour.
65
80
  */
66
81
  export class Tutor extends EventEmitter {
67
82
  options;
@@ -72,10 +87,17 @@ export class Tutor extends EventEmitter {
72
87
  queue = [];
73
88
  busy = new Set();
74
89
  asked = new Map();
90
+ classAsked = [];
91
+ // the class limit was reached; told once until questions pass again
92
+ limited = false;
75
93
  threads = new Map();
76
94
  // the room state each session got last; a restart sends it again
77
95
  sent = new Map();
78
96
  saving = Promise.resolve();
97
+ // the system prompt as written last: another run may be reading the file
98
+ written = '';
99
+ children = new Set();
100
+ stopped = false;
79
101
  /** Off, it answers no questions, and the class tab no longer offers it. */
80
102
  enabled = true;
81
103
  constructor(options) {
@@ -143,9 +165,19 @@ export class Tutor extends EventEmitter {
143
165
  if (recent.length >= (this.options.perHour ?? 20)) {
144
166
  throw new Error('You asked a lot this hour. Ask your teacher, or try again later.');
145
167
  }
168
+ this.classAsked = this.classAsked.filter((t) => t > now - HOUR);
169
+ const classPerHour = this.options.classPerHour ?? CLASS_PER_HOUR;
170
+ if (this.classAsked.length >= classPerHour) {
171
+ if (!this.limited)
172
+ this.emit('limit', classPerHour);
173
+ this.limited = true;
174
+ throw new Error('The tutor has answered a lot this hour. Ask your teacher.');
175
+ }
146
176
  if (this.queue.length >= QUEUE_MAX)
147
177
  throw new Error('The tutor is busy. Try again in a minute.');
178
+ this.limited = false;
148
179
  this.asked.set(question.student, [...recent, now]);
180
+ this.classAsked.push(now);
149
181
  this.busy.add(question.student);
150
182
  try {
151
183
  const thread = this.thread(question.student) ?? {
@@ -156,7 +188,16 @@ export class Tutor extends EventEmitter {
156
188
  };
157
189
  thread.name = question.name;
158
190
  this.add(thread, { t: now, from: 'student', text, room: question.room });
159
- await this.turn();
191
+ try {
192
+ await this.turn();
193
+ }
194
+ catch (error) {
195
+ // it never ran: no use of the account to count
196
+ this.classAsked.splice(this.classAsked.indexOf(now), 1);
197
+ this.asked.get(question.student)?.pop();
198
+ this.emit('failed', { student: question.student, name: question.name, error: error.message });
199
+ throw new Error('The tutor is busy. Try again in a minute.');
200
+ }
160
201
  try {
161
202
  const head = `[student: ${oneLine(question.name)}, room: ${oneLine(question.room)}]\n${text}`;
162
203
  const answer = await this.run(thread, head, await this.readState(question.room));
@@ -181,43 +222,92 @@ export class Tutor extends EventEmitter {
181
222
  flush() {
182
223
  return this.saving;
183
224
  }
184
- // waits for a free run
225
+ /** Stops the runs in progress, which fail; for a clean stop. */
226
+ stop() {
227
+ this.stopped = true;
228
+ for (const child of this.children)
229
+ kill(child);
230
+ }
231
+ // waits for a free run, at most queueMs
185
232
  turn() {
186
233
  if (this.running < (this.options.concurrency ?? 2)) {
187
234
  this.running++;
188
235
  return Promise.resolve();
189
236
  }
190
- return new Promise((resolve) => this.queue.push(() => {
191
- this.running++;
192
- resolve();
193
- }));
237
+ const ms = this.options.queueMs ?? QUEUE_MS;
238
+ return new Promise((resolve, reject) => {
239
+ const start = () => {
240
+ clearTimeout(timer);
241
+ this.running++;
242
+ resolve();
243
+ };
244
+ const timer = setTimeout(() => {
245
+ this.queue.splice(this.queue.indexOf(start), 1);
246
+ reject(new Error(`no free run within ${ms / 1000} s: more questions than answers at once`));
247
+ }, ms);
248
+ this.queue.push(start);
249
+ });
194
250
  }
195
251
  add(thread, entry) {
196
252
  thread.entries.push(entry);
197
253
  if (thread.entries.length > THREAD_MAX)
198
254
  thread.entries.splice(0, thread.entries.length - THREAD_MAX);
199
255
  this.threads.set(thread.student, thread);
256
+ this.save(thread);
257
+ this.emit('entry', { student: thread.student, name: thread.name, entry });
258
+ }
259
+ // a copy renamed over the file: a crash midway leaves the old thread, not half a one
260
+ save(thread) {
200
261
  const json = JSON.stringify(thread);
201
262
  const file = path.join(this.dir, fileOf(thread.student));
202
- this.saving = this.saving.then(() => fsp.writeFile(file, json)).catch(() => { });
203
- this.emit('entry', { student: thread.student, name: thread.name, entry });
263
+ this.saving = this.saving
264
+ .then(async () => {
265
+ await fsp.writeFile(file + '.tmp', json);
266
+ await fsp.rename(file + '.tmp', file);
267
+ })
268
+ .catch(() => { });
269
+ }
270
+ // written anew only when the lab or the notes changed, and renamed into
271
+ // place: a run that reads it meanwhile gets the old prompt or the new one
272
+ async writePrompt(system) {
273
+ const prompt = await tutorPrompt(this.options.lab);
274
+ if (prompt === this.written)
275
+ return;
276
+ const tmp = `${system}.${crypto.randomUUID()}.tmp`;
277
+ await fsp.writeFile(tmp, prompt);
278
+ try {
279
+ await fsp.rename(tmp, system);
280
+ this.written = prompt;
281
+ }
282
+ catch (error) {
283
+ await fsp.rm(tmp, { force: true });
284
+ // Windows refuses while a run has it open: that run keeps the old one, the next writes it
285
+ if (!fs.existsSync(system))
286
+ throw error;
287
+ }
204
288
  }
205
- // the room's state as JSON, null when the class tab could not tell, undefined without a class tab
289
+ // the room's state as JSON, null when the class tab could not tell within
290
+ // STATE_MS, undefined without a class tab
206
291
  async readState(room) {
207
292
  if (!this.options.roomState)
208
293
  return undefined;
209
294
  if (!room)
210
295
  return null;
296
+ let timer;
297
+ const late = new Promise((_, reject) => (timer = setTimeout(() => reject(new Error('late')), this.options.stateMs ?? STATE_MS)));
211
298
  try {
212
- return stateText(await this.options.roomState(room));
299
+ return stateText(await Promise.race([this.options.roomState(room), late]));
213
300
  }
214
301
  catch {
215
302
  return null;
216
303
  }
304
+ finally {
305
+ clearTimeout(timer);
306
+ }
217
307
  }
218
308
  async run(thread, head, state) {
219
309
  const system = path.join(this.dir, 'system.md');
220
- await fsp.writeFile(system, await tutorPrompt(this.options.lab));
310
+ await this.writePrompt(system);
221
311
  // without a session, the agent starts one and tells which
222
312
  const once = async (session) => {
223
313
  const prompt = this.message(session, head, state);
@@ -236,8 +326,13 @@ export class Tutor extends EventEmitter {
236
326
  // what a tool brought into the session must not come up in a later answer
237
327
  if (error.tool) {
238
328
  thread.session = '';
329
+ // saved now: a restart before the next answer must not resume it either
330
+ this.save(thread);
239
331
  throw error;
240
332
  }
333
+ // no time left for a second run: the student gives up after 3 minutes
334
+ if (error.late)
335
+ throw error;
241
336
  // the agent's own session store may have lost it: start a new one
242
337
  return once();
243
338
  }
@@ -256,6 +351,9 @@ export class Tutor extends EventEmitter {
256
351
  const id = session ?? crypto.randomUUID();
257
352
  const { code, out, err } = await this.spawn([
258
353
  '-p',
354
+ // signed in, claude -p answers with that account and passes over ANTHROPIC_API_KEY;
355
+ // --bare takes strictly the key (checked with Claude Code 2.1.316)
356
+ ...(process.env.ANTHROPIC_API_KEY ? ['--bare'] : []),
259
357
  '--tools', '',
260
358
  '--strict-mcp-config',
261
359
  '--setting-sources', '',
@@ -322,6 +420,8 @@ export class Tutor extends EventEmitter {
322
420
  spawn(args, prompt, onEvent) {
323
421
  const command = this.options.command ?? this.options.agent ?? 'claude';
324
422
  return new Promise((resolve, reject) => {
423
+ if (this.stopped)
424
+ return reject(new Error('edrys-dev is stopping'));
325
425
  // Windows starts claude.cmd through a shell, which drops empty arguments
326
426
  const quoted = process.platform === 'win32' ? args.map((a) => (a === '' || /\s/.test(a) ? `"${a}"` : a)) : args;
327
427
  const child = spawn(command, quoted, {
@@ -329,11 +429,12 @@ export class Tutor extends EventEmitter {
329
429
  stdio: ['pipe', 'pipe', 'pipe'],
330
430
  shell: process.platform === 'win32',
331
431
  });
432
+ this.children.add(child);
332
433
  let out = '';
333
434
  let err = '';
334
435
  let line = '';
335
436
  let timedOut = false;
336
- const stop = () => child.kill();
437
+ const stop = () => kill(child);
337
438
  child.stdout.on('data', (d) => {
338
439
  out += d;
339
440
  if (!onEvent)
@@ -359,12 +460,18 @@ export class Tutor extends EventEmitter {
359
460
  }, this.options.timeoutMs ?? 120_000);
360
461
  child.on('error', (error) => {
361
462
  clearTimeout(timer);
463
+ this.children.delete(child);
362
464
  reject(new Error(`the tutor could not start ${command}: ${error.message}`));
363
465
  });
364
466
  child.on('close', (code) => {
365
467
  clearTimeout(timer);
366
- if (timedOut)
367
- return reject(new Error(`${command} gave no answer within ${(this.options.timeoutMs ?? 120_000) / 1000} s`));
468
+ this.children.delete(child);
469
+ if (this.stopped)
470
+ return reject(Object.assign(new Error('edrys-dev stopped'), { late: true }));
471
+ if (timedOut) {
472
+ const s = (this.options.timeoutMs ?? 120_000) / 1000;
473
+ return reject(Object.assign(new Error(`${command} gave no answer within ${s} s`), { late: true }));
474
+ }
368
475
  resolve({ code, out, err });
369
476
  });
370
477
  child.stdin.on('error', () => { });
@@ -372,6 +479,14 @@ export class Tutor extends EventEmitter {
372
479
  });
373
480
  }
374
481
  }
482
+ // on Windows the child is the shell that runs claude.cmd: its whole tree goes
483
+ function kill(child) {
484
+ if (process.platform === 'win32' && child.pid) {
485
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on('error', () => child.kill());
486
+ }
487
+ else
488
+ child.kill();
489
+ }
375
490
  // a TOML literal string: no escapes, and no " for the shell on Windows
376
491
  function tomlString(text) {
377
492
  return text.includes("'") ? JSON.stringify(text) : `'${text}'`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edryslabs/edrys-dev",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
4
4
  "description": "Develop edrys-Lite labs locally: serves edrys-Lite, syncs on its own port and republishes the class whenever the lab file changes",
5
5
  "type": "module",
6
6
  "bin": {
@@ -36,11 +36,9 @@
36
36
  },
37
37
  "homepage": "https://github.com/edrys-labs/edrys-devserver#readme",
38
38
  "dependencies": {
39
- "@edryslabs/edrys-lite": "3.2.0-dev.3",
39
+ "@edryslabs/edrys-lite": "3.2.0-dev.5",
40
40
  "chokidar": "^4.0.3",
41
- "dompurify": "^3.4.17",
42
41
  "express": "^5.1.0",
43
- "marked": "^18.1.1",
44
42
  "msgpackr": "^2.1.2",
45
43
  "open": "^10.1.0"
46
44
  },
@@ -0,0 +1,9 @@
1
+ // Injected by edrys-dev into edrys-Lite's page: student and station tabs load
2
+ // again when a local module changed. The tab opened with ?dev (DevBridge keeps
3
+ // that in sessionStorage) reloads only the changed modules itself, and shows
4
+ // the agent chat (AgentChat.vue in edrys-Lite).
5
+ ;(function () {
6
+ if (location.search === '?dev' || sessionStorage.getItem('edrys-dev')) return
7
+ if (!/^\?\/(classroom|station)\//.test(location.search)) return
8
+ new EventSource('/edrys-dev/reload').addEventListener('reload-module', () => location.reload())
9
+ })()