agent-lyceum 0.55.0 → 0.56.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.
@@ -588,6 +588,22 @@ export const ADVICE_COMMITS = 50;
588
588
  /** Hints only: project memory whose index is larger than what an agent is shown, or whose baseline is far behind. Never acts. */
589
589
  export function tidyAdvice(project) {
590
590
  const out = [];
591
+ // One report walks every target. The repo check and each baseline count are shared; the text stays the same.
592
+ let repo;
593
+ const counts = new Map();
594
+ const inRepo = () => {
595
+ if (repo === undefined)
596
+ repo = fs.existsSync(project.dir) && isGitRepo(project.dir);
597
+ return repo;
598
+ };
599
+ const commitsSince = (since) => {
600
+ const cached = counts.get(since);
601
+ if (cached !== undefined)
602
+ return cached;
603
+ const n = Number(tryGit(project.dir, ["rev-list", "--count", `${since}..HEAD`]));
604
+ counts.set(since, n);
605
+ return n;
606
+ };
591
607
  for (const t of targetsFor(project, { layer: "project" })) {
592
608
  if (!fs.existsSync(t.dir))
593
609
  continue;
@@ -597,9 +613,9 @@ export function tidyAdvice(project) {
597
613
  continue;
598
614
  }
599
615
  const since = readTidyState(t.dir)?.head;
600
- if (!since || !fs.existsSync(project.dir) || !isGitRepo(project.dir))
616
+ if (!since || !inRepo())
601
617
  continue;
602
- const n = Number(tryGit(project.dir, ["rev-list", "--count", `${since}..HEAD`]));
618
+ const n = commitsSince(since);
603
619
  if (Number.isFinite(n) && n >= ADVICE_COMMITS)
604
620
  out.push({ agent: t.agent, reason: `${n} commits since the last tidy` });
605
621
  }
package/dist/quota.js CHANGED
@@ -50,9 +50,16 @@ function windowOf(label, used, resets) {
50
50
  function roundPercent(n) {
51
51
  return Math.round(n * 10) / 10;
52
52
  }
53
+ const CLAUDE_USAGE = ["-p", "--no-session-persistence", "--output-format", "text", "/usage"];
54
+ const CODEX_LIMITS = ["app-server", "--stdio"];
55
+ const CODEX_LIMITS_NO_PLUGINS = ["app-server", "--disable", "plugins", "--stdio"];
56
+ const CLAUDE_ADDED_OPTIONS = ["--safe-mode"];
57
+ const CODEX_ADDED_OPTIONS = ["--disable", "plugins"];
53
58
  export async function claudeQuota(signal) {
54
59
  try {
55
- const text = await capture("claude", ["-p", "--no-session-persistence", "--output-format", "text", "/usage"], 20_000, signal);
60
+ let text = await capture("claude", ["--safe-mode", ...CLAUDE_USAGE], 20_000, signal);
61
+ if (optionRejected(text, CLAUDE_ADDED_OPTIONS))
62
+ text = await capture("claude", CLAUDE_USAGE, 20_000, signal);
56
63
  const windows = parseClaudeUsage(text.stdout);
57
64
  if (windows.length === 0)
58
65
  return { runtime: "claude", windows: [], error: firstLine(text.stderr) || firstLine(text.stdout) || "claude /usage 沒有回傳額度。" };
@@ -66,7 +73,15 @@ export async function claudeQuota(signal) {
66
73
  }
67
74
  export async function codexQuota(signal) {
68
75
  try {
69
- const limits = await readCodexLimits(signal);
76
+ let limits;
77
+ try {
78
+ limits = await readCodexLimits(signal, CODEX_LIMITS_NO_PLUGINS);
79
+ }
80
+ catch (error) {
81
+ if (isAbort(error) || !(error instanceof OptionRejected))
82
+ throw error;
83
+ limits = await readCodexLimits(signal, CODEX_LIMITS);
84
+ }
70
85
  return { runtime: "codex", windows: codexWindows(limits) };
71
86
  }
72
87
  catch (error) {
@@ -347,35 +362,61 @@ function missing(cmd, error) {
347
362
  function firstLine(text) {
348
363
  return text.split("\n").map((line) => line.trim()).find(Boolean) ?? "";
349
364
  }
365
+ /** An old CLI that does not know the new flag. Timeouts and aborts are not this. */
366
+ class OptionRejected extends Error {
367
+ constructor(message) {
368
+ super(message);
369
+ this.name = "OptionRejected";
370
+ }
371
+ }
372
+ /** The rejection names one of the flags this version added. Any other unknown option stays a real failure. */
373
+ function addedOptionRejected(text, added) {
374
+ for (const match of text.matchAll(/(?:unknown option|unexpected argument)\s+(['"]?)([^\s'"]+)\1/gi)) {
375
+ const name = match[2];
376
+ if (name && added.includes(name))
377
+ return true;
378
+ }
379
+ return false;
380
+ }
381
+ function optionRejected(out, added) {
382
+ return out.code !== 0 && out.code !== null && addedOptionRejected(`${out.stderr}\n${out.stdout}`, added);
383
+ }
350
384
  function capture(cmd, args, timeoutMs, signal) {
351
385
  return new Promise((resolve, reject) => {
352
386
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], ...(signal ? { signal } : {}) });
353
387
  let stdout = "";
354
388
  let stderr = "";
389
+ let settled = false;
355
390
  const timer = setTimeout(() => {
391
+ if (settled)
392
+ return;
393
+ settled = true;
356
394
  child.kill();
357
395
  reject(new Error(`${cmd} 超過 ${Math.round(timeoutMs / 1000)} 秒沒有回應。`));
358
396
  }, timeoutMs);
359
397
  child.stdout.on("data", (chunk) => (stdout += String(chunk)));
360
398
  child.stderr.on("data", (chunk) => (stderr += String(chunk)));
361
399
  child.on("error", (error) => {
400
+ if (settled)
401
+ return;
402
+ settled = true;
362
403
  clearTimeout(timer);
363
404
  reject(error);
364
405
  });
365
- child.on("close", () => {
406
+ child.on("close", (code) => {
407
+ if (settled)
408
+ return;
409
+ settled = true;
366
410
  clearTimeout(timer);
367
- resolve({ stdout, stderr });
411
+ resolve({ stdout, stderr, code });
368
412
  });
369
413
  });
370
414
  }
371
- function readCodexLimits(signal) {
415
+ function readCodexLimits(signal, args) {
372
416
  return new Promise((resolve, reject) => {
373
- const child = spawn("codex", ["app-server", "--stdio"], { stdio: ["pipe", "pipe", "pipe"], ...(signal ? { signal } : {}) });
417
+ const child = spawn("codex", args, { stdio: ["pipe", "pipe", "pipe"], ...(signal ? { signal } : {}) });
374
418
  let buf = "";
375
- const timer = setTimeout(() => {
376
- child.kill();
377
- reject(new Error("codex 超過 20 秒沒有回應。"));
378
- }, 20_000);
419
+ let stderr = "";
379
420
  let done = false;
380
421
  const finish = (error, limits) => {
381
422
  if (done)
@@ -388,7 +429,18 @@ function readCodexLimits(signal) {
388
429
  else
389
430
  resolve(limits ?? {});
390
431
  };
432
+ const timer = setTimeout(() => {
433
+ finish(new Error("codex 超過 20 秒沒有回應。"));
434
+ }, 20_000);
391
435
  child.on("error", (error) => finish(error));
436
+ child.stderr.on("data", (chunk) => (stderr += String(chunk)));
437
+ child.on("close", (code) => {
438
+ const text = `${stderr}\n${buf}`;
439
+ if (code !== 0 && code !== null && addedOptionRejected(text, CODEX_ADDED_OPTIONS))
440
+ finish(new OptionRejected(firstLine(text)));
441
+ else
442
+ finish(new Error(firstLine(stderr) || firstLine(buf) || "codex 沒有回傳額度。"));
443
+ });
392
444
  child.stdout.on("data", (chunk) => {
393
445
  buf += String(chunk);
394
446
  let cut = buf.indexOf("\n");
@@ -15,8 +15,9 @@ export type WatchFrame = {
15
15
  */
16
16
  /**
17
17
  * Reports of finished runs, kept so a sweep does not rebuild them (about 300 ms each). An entry is reused while the
18
- * run's state.json is unchanged and it is younger than `FINISHED_TTL_MS`; the TTL picks up what lives outside that file
19
- * (unread mail, memory advice).
18
+ * run's state.json is unchanged and it is younger than `FINISHED_TTL_MS`. That TTL still covers what lives outside
19
+ * the file, such as unread mail. Advice is copied from the lines passed for this call, so it stays inside
20
+ * `ADVICE_TTL_MS` and the two TTLs do not stack.
20
21
  */
21
22
  export type FinishedCache = Map<string, {
22
23
  stamp: string;
@@ -26,6 +27,7 @@ export type FinishedCache = Map<string, {
26
27
  export declare function buildWatchFrame(project: ResolvedProject, tracked: Set<string>, opts?: {
27
28
  allTasks?: boolean;
28
29
  cache?: FinishedCache;
30
+ advice?: string[];
29
31
  }): WatchFrame;
30
32
  export interface WatchDeps {
31
33
  /** The project, loaded again each time so config edits and new runs show up. */
@@ -1,7 +1,19 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { buildStatusReport, buildTaskListReport, currentRun, isFinishedRun } from "./status.js";
3
+ import { buildStatusReport, buildTaskListReport, currentRun, isFinishedRun, memoryAdviceLines } from "./status.js";
4
4
  const FINISHED_TTL_MS = 5 * 60_000;
5
+ /** Tidy advice is the same for every run of a project. Recompute it on this cadence, not on every beat. */
6
+ const ADVICE_TTL_MS = 5 * 60_000;
7
+ function withAdvice(report, advice) {
8
+ const current = report.memory_advice ?? [];
9
+ if (current.length === advice.length && current.every((line, index) => line === advice[index]))
10
+ return report;
11
+ if (advice.length === 0) {
12
+ const { memory_advice: _dropped, ...rest } = report;
13
+ return rest;
14
+ }
15
+ return { ...report, memory_advice: advice };
16
+ }
5
17
  function stampOf(project, id) {
6
18
  try {
7
19
  const st = fs.statSync(path.join(project.paths.runs, id, "state.json"));
@@ -21,14 +33,18 @@ export function buildWatchFrame(project, tracked, opts) {
21
33
  const finished = new Set(all.filter(isFinishedRun).map((r) => r.run_id));
22
34
  const cache = opts?.cache;
23
35
  const now = Date.now();
36
+ const advice = opts?.advice ?? memoryAdviceLines(project);
24
37
  for (const id of new Set(ids)) {
25
38
  const stamp = cache && finished.has(id) ? stampOf(project, id) : "";
26
39
  const hit = stamp ? cache?.get(id) : undefined;
27
40
  if (hit && hit.stamp === stamp && now - hit.at < FINISHED_TTL_MS) {
28
- runs[id] = hit.report;
41
+ const report = withAdvice(hit.report, advice);
42
+ if (report !== hit.report)
43
+ cache?.set(id, { stamp: hit.stamp, at: hit.at, report });
44
+ runs[id] = report;
29
45
  continue;
30
46
  }
31
- runs[id] = buildStatusReport(project, id);
47
+ runs[id] = buildStatusReport(project, id, now, advice);
32
48
  if (stamp)
33
49
  cache?.set(id, { stamp, at: now, report: runs[id] });
34
50
  }
@@ -38,7 +54,7 @@ export function buildWatchFrame(project, tracked, opts) {
38
54
  cache.delete(id);
39
55
  // The project's own report shows the current run, which is usually one already built above.
40
56
  const currentId = currentRun(project)?.state.run_id;
41
- const report = currentId && runs[currentId] ? runs[currentId] : buildStatusReport(project);
57
+ const report = currentId && runs[currentId] ? runs[currentId] : buildStatusReport(project, undefined, now, advice);
42
58
  tracked.clear();
43
59
  for (const id of running)
44
60
  tracked.add(id);
@@ -60,12 +76,18 @@ export function createStatusWatcher(d) {
60
76
  let watching = "";
61
77
  let watcher;
62
78
  let timer;
79
+ let adviceCache;
63
80
  const emit = () => {
64
81
  let frame;
65
82
  let project;
66
83
  try {
67
84
  project = d.load();
68
- frame = buildWatchFrame(project, tracked, { allTasks: d.allTasks, cache });
85
+ const now = Date.now();
86
+ const key = `${project.name}\0${project.dir}`;
87
+ if (!adviceCache || adviceCache.key !== key || now - adviceCache.at >= ADVICE_TTL_MS) {
88
+ adviceCache = { key, at: now, lines: memoryAdviceLines(project) };
89
+ }
90
+ frame = buildWatchFrame(project, tracked, { allTasks: d.allTasks, cache, advice: adviceCache.lines });
69
91
  }
70
92
  catch (e) {
71
93
  frame = { schema_version: 1, error: e.message };
package/dist/status.d.ts CHANGED
@@ -177,8 +177,10 @@ export declare function buildRunReport(run: {
177
177
  }): RunReport;
178
178
  /** A run that ended with a `completed` or `partial` outcome: the only kinds the monitor stops listing (blocked, failed and cancelled stay). */
179
179
  export declare const isFinishedRun: (r: Pick<RunReport, "state" | "outcome">) => boolean;
180
+ /** Tidy hints for a status report. A failure is an empty list: a hint must not break status. */
181
+ export declare function memoryAdviceLines(project: ResolvedProject): string[];
180
182
  /** The status of a project: its agents and one run (the newest running one, else the newest, or the one named by `runId`). */
181
- export declare function buildStatusReport(base: ResolvedProject, runId?: string, now?: number): StatusReport;
183
+ export declare function buildStatusReport(base: ResolvedProject, runId?: string, now?: number, memoryAdvice?: string[]): StatusReport;
182
184
  /** Every run of the project, newest first. */
183
185
  export declare function buildTaskListReport(project: ResolvedProject): TaskListReport;
184
186
  /** Live view: summary and agent table, plus the latest run and any run still going, wake by wake. */
package/dist/status.js CHANGED
@@ -306,8 +306,17 @@ function fallbackView(a, state, now) {
306
306
  .filter((c) => Number.isFinite(c.remaining_sec) && c.remaining_sec > 0);
307
307
  return { runtime: ran?.runtime ?? a.runtime, ...(model ? { model } : {}), ...(fallback ? { fallback } : {}), ...(cooldowns.length ? { cooldowns } : {}) };
308
308
  }
309
+ /** Tidy hints for a status report. A failure is an empty list: a hint must not break status. */
310
+ export function memoryAdviceLines(project) {
311
+ try {
312
+ return tidyAdvice(project).map((a) => `${a.agent}: ${a.reason}`);
313
+ }
314
+ catch {
315
+ return [];
316
+ }
317
+ }
309
318
  /** The status of a project: its agents and one run (the newest running one, else the newest, or the one named by `runId`). */
310
- export function buildStatusReport(base, runId, now = Date.now()) {
319
+ export function buildStatusReport(base, runId, now = Date.now(), memoryAdvice) {
311
320
  let run;
312
321
  if (runId) {
313
322
  const dir = path.join(base.paths.runs, runId);
@@ -320,13 +329,7 @@ export function buildStatusReport(base, runId, now = Date.now()) {
320
329
  // Mail is per run: count the unread mail of the run being shown.
321
330
  const project = run ? bindRunProject(base, run.dir, run.state.mail_layout, run.state.instances) : base;
322
331
  const report = run ? buildRunReport(run, base) : undefined;
323
- let advice = [];
324
- try {
325
- advice = tidyAdvice(base).map((a) => `${a.agent}: ${a.reason}`);
326
- }
327
- catch {
328
- /* a hint only: never let it break status */
329
- }
332
+ const advice = memoryAdvice ?? memoryAdviceLines(base);
330
333
  const wakes = run?.state.wakes ?? [];
331
334
  const below = new Set();
332
335
  for (const a of Object.values(project.agents)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-lyceum",
3
- "version": "0.55.0",
3
+ "version": "0.56.0",
4
4
  "description": "Config + dispatcher for teams of Claude Code / Codex agents with scoped context and file-based mailboxes",
5
5
  "keywords": [
6
6
  "ai",
@@ -1,9 +1,11 @@
1
- export function createWebHub(factory) {
1
+ export function createWebHub(factory, hooks) {
2
2
  const watchers = new Map();
3
3
  const latest = new Map();
4
4
  const listeners = new Set();
5
5
  let quota;
6
+ let quotaAt = 0;
6
7
  let quotaToken = 0;
8
+ let inflight = 0;
7
9
  const quotaAbort = new AbortController();
8
10
  const emit = (event) => {
9
11
  for (const listener of listeners) {
@@ -61,22 +63,47 @@ export function createWebHub(factory) {
61
63
  if (!factory.quota)
62
64
  return Promise.resolve(quota);
63
65
  const token = ++quotaToken;
64
- return factory
65
- .quota(quotaAbort.signal)
66
+ inflight += 1;
67
+ const read = factory.quota;
68
+ // Call now, so a subscriber sees the in-flight read before the next turn. A throw still becomes a rejection.
69
+ let pending;
70
+ try {
71
+ pending = Promise.resolve(read(quotaAbort.signal));
72
+ }
73
+ catch (error) {
74
+ pending = Promise.reject(error);
75
+ }
76
+ return pending
66
77
  .then((reports) => {
67
78
  if (token !== quotaToken)
68
79
  return quota;
69
80
  quota = reports;
81
+ quotaAt = Date.now();
70
82
  emit({ type: "quota", reports });
71
83
  return reports;
72
84
  })
73
- .catch(() => quota);
85
+ .catch(() => quota)
86
+ .finally(() => {
87
+ inflight -= 1;
88
+ });
74
89
  };
75
90
  const projectList = () => [...latest].map(([name, frame]) => ({ name, frame })).sort((a, b) => a.name.localeCompare(b.name));
76
91
  return {
77
92
  start: sync,
78
93
  beat: sync,
79
94
  refreshQuota,
95
+ subscriberCount: () => listeners.size,
96
+ quotaBusy: () => inflight > 0,
97
+ /**
98
+ * Milliseconds until a successful read leaves the freshness window, capped at `maxAgeMs`.
99
+ * A missing or failed read has none left, so the next subscriber reads at once.
100
+ */
101
+ quotaRemaining: (maxAgeMs) => {
102
+ if (quota === undefined)
103
+ return 0;
104
+ const left = maxAgeMs - (Date.now() - quotaAt);
105
+ return Math.min(maxAgeMs, Math.max(0, left));
106
+ },
80
107
  frame(name) {
81
108
  return latest.get(name);
82
109
  },
@@ -90,6 +117,7 @@ export function createWebHub(factory) {
90
117
  },
91
118
  snapshot: projectList,
92
119
  subscribe(listener) {
120
+ const previous = listeners.size;
93
121
  listeners.add(listener);
94
122
  const projects = projectList();
95
123
  try {
@@ -97,8 +125,15 @@ export function createWebHub(factory) {
97
125
  }
98
126
  catch {
99
127
  listeners.delete(listener);
128
+ return () => { };
100
129
  }
101
- return () => listeners.delete(listener);
130
+ hooks?.onSubscribers?.(listeners.size, previous);
131
+ return () => {
132
+ const before = listeners.size;
133
+ if (!listeners.delete(listener))
134
+ return;
135
+ hooks?.onSubscribers?.(listeners.size, before);
136
+ };
102
137
  },
103
138
  };
104
139
  }
package/web/dist/start.js CHANGED
@@ -8,9 +8,12 @@ import { handleSummary } from "./server/summary.js";
8
8
  /** A repeated header arrives as an array; it is never valid for Origin or the token, so it becomes "" (the guard refuses an empty value). */
9
9
  const singleHeader = (v) => (Array.isArray(v) ? "" : v);
10
10
  const JSON_HEADERS = { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" };
11
+ /** How often a page that is watching `/events` asks the account usage commands again. */
12
+ const QUOTA_REFRESH_MS = 5 * 60_000;
11
13
  /** Binds first; the hub, the quota reads and the timers start only once the port is ours, and are undone if that fails. */
12
14
  export async function startWebServer(opts) {
13
- const hub = createWebHub(opts.factory);
15
+ let onSubscribers = (_count, _previous) => { };
16
+ const hub = createWebHub(opts.factory, { onSubscribers: (count, previous) => onSubscribers(count, previous) });
14
17
  const startedAt = new Date().toISOString();
15
18
  let boundPort = opts.port;
16
19
  const token = randomBytes(24).toString("hex");
@@ -105,10 +108,49 @@ export async function startWebServer(opts) {
105
108
  const address = server.address();
106
109
  boundPort = typeof address === "object" && address ? address.port : opts.port;
107
110
  let heartbeat;
108
- let quotaBeat;
111
+ let quotaTimer;
112
+ const clearQuotaTimer = () => {
113
+ if (quotaTimer)
114
+ clearTimeout(quotaTimer);
115
+ quotaTimer = undefined;
116
+ };
117
+ const readIfIdle = () => {
118
+ if (hub.subscriberCount() === 0 || hub.quotaBusy())
119
+ return;
120
+ void hub.refreshQuota();
121
+ };
122
+ // The delay is the cadence. It does not ask again whether the cache is still fresh: a read that
123
+ // finishes after the timer was armed would otherwise skip the first beat.
124
+ const armQuota = (delayMs) => {
125
+ clearQuotaTimer();
126
+ quotaTimer = setTimeout(() => {
127
+ quotaTimer = undefined;
128
+ readIfIdle();
129
+ if (hub.subscriberCount() > 0)
130
+ armQuota(QUOTA_REFRESH_MS);
131
+ }, delayMs);
132
+ };
133
+ onSubscribers = (count, previous) => {
134
+ if (count === 0) {
135
+ clearQuotaTimer();
136
+ return;
137
+ }
138
+ // Only the 0 → 1 transition may read or arm. A later page joining, and a
139
+ // disconnect that still leaves a page, must not read and must not move the
140
+ // timer, including after a failed read that left no cached quota.
141
+ if (previous !== 0)
142
+ return;
143
+ const remaining = hub.quotaRemaining(QUOTA_REFRESH_MS);
144
+ if (remaining > 0) {
145
+ armQuota(remaining);
146
+ return;
147
+ }
148
+ readIfIdle();
149
+ armQuota(QUOTA_REFRESH_MS);
150
+ };
109
151
  const close = () => new Promise((resolve, reject) => {
110
152
  clearInterval(heartbeat);
111
- clearInterval(quotaBeat);
153
+ clearQuotaTimer();
112
154
  hub.close();
113
155
  for (const socket of sockets)
114
156
  socket.destroy();
@@ -124,9 +166,7 @@ export async function startWebServer(opts) {
124
166
  const url = `http://${shown}:${boundPort}/`;
125
167
  try {
126
168
  hub.start();
127
- void hub.refreshQuota();
128
169
  heartbeat = setInterval(() => hub.beat(), opts.heartbeatMs ?? 5_000);
129
- quotaBeat = setInterval(() => void hub.refreshQuota(), 60_000);
130
170
  if (opts.open)
131
171
  openBrowser(url);
132
172
  }