agent-lyceum 0.43.0 → 0.44.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/cli.js CHANGED
@@ -10,7 +10,7 @@ import { openInEditor, prepareAnswers } from "./ask-answer.js";
10
10
  import { restoreMemory, tidyMemory, tidyStamp } from "./memory-tidy.js";
11
11
  import { RESULT_FILE, runTeam } from "./dispatcher.js";
12
12
  import { executeRunCleanup, planRunCleanup } from "./run-cleanup.js";
13
- import { diagnoseProject, formatDoctor, preflightRuntimes } from "./doctor.js";
13
+ import { diagnoseProject, formatDoctor, preflightRuntimes, runtimesUsed } from "./doctor.js";
14
14
  import { acquireProjectLock, forceUnlock, inspectRunLock, listRunLocks, listUnreadableRunLocks, LOCK_FILE, lockHolderAlive } from "./project-lock.js";
15
15
  import { planWorkspace } from "./worktree.js";
16
16
  import { loadRunState, newRunId, outcomeOf, resolveRun, roundLimit, roundsLabel, runLabel, slugify, uniqueName } from "./run-store.js";
@@ -30,7 +30,7 @@ import { createStatusWatcher } from "./status-watch.js";
30
30
  import { LAUNCH_PPID, startedByWrapper, watchParent } from "./parent-watch.js";
31
31
  import { onlyAgent, soloProject } from "./solo.js";
32
32
  import { DEMO_PROJECT, DEMO_TASK, defaultDemoDir, detectRuntime, prepareDemo } from "./demo.js";
33
- import { claudeQuota, codexQuota } from "./quota.js";
33
+ import { claudeQuota, codexQuota, cursorQuota } from "./quota.js";
34
34
  import { summarizeProgress } from "./summarize.js";
35
35
  import { createConsoleDeps } from "./web-console.js";
36
36
  const program = new Command();
@@ -39,6 +39,17 @@ program
39
39
  .description("Configure and run a team of Claude Code / Codex agents with scoped context and file mailboxes.")
40
40
  .option("--home <dir>", "agent-lyceum home (default: $AGENT_LYCEUM_HOME or ~/agent-lyceum-config)");
41
41
  const home = () => resolveHome(program.opts().home);
42
+ /** The web page asks Cursor for its allowance only when some project's agents or fallbacks run on Cursor. */
43
+ function anyProjectUsesCursor(dir) {
44
+ return listProjects(dir).some((item) => {
45
+ try {
46
+ return runtimesUsed(resolveProject(dir, item.name), true).includes("cursor");
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ });
52
+ }
42
53
  function fail(msg, code = 1) {
43
54
  console.error(msg);
44
55
  process.exit(code);
@@ -798,7 +809,7 @@ program
798
809
  debounceMs: 100,
799
810
  allTasks: true,
800
811
  }),
801
- quota: (signal) => Promise.all([claudeQuota(signal), codexQuota(signal)]),
812
+ quota: (signal) => Promise.all([claudeQuota(signal), codexQuota(signal), ...(anyProjectUsesCursor(home()) ? [cursorQuota(signal)] : [])]),
802
813
  summarize: ({ runtime, prompt }) => summarizeProgress(runtime, prompt),
803
814
  },
804
815
  };
package/dist/doctor.d.ts CHANGED
@@ -37,6 +37,8 @@ export interface DoctorReport {
37
37
  checks: DoctorCheck[];
38
38
  runtimes: RuntimeCapabilities[];
39
39
  }
40
+ /** Runtimes of the agents themselves; with `withFallback`, also those that only a fallback chain uses. */
41
+ export declare const runtimesUsed: (project: ResolvedProject, withFallback: boolean) => Runtime[];
40
42
  export declare function probeProjectRuntimes(project: ResolvedProject, opts?: ProbeOptions, withFallback?: boolean): Promise<RuntimeCapabilities[]>;
41
43
  /** Before a run starts: what is explicitly unsupported (refuse) and what is merely unknown (warn). */
42
44
  export declare function preflightRuntimes(project: ResolvedProject, opts?: ProbeOptions): Promise<{
package/dist/doctor.js CHANGED
@@ -131,7 +131,7 @@ function judgeRuntimes(project, caps) {
131
131
  return checks;
132
132
  }
133
133
  /** Runtimes of the agents themselves; with `withFallback`, also those that only a fallback chain uses. */
134
- const runtimesUsed = (project, withFallback) => [
134
+ export const runtimesUsed = (project, withFallback) => [
135
135
  ...new Set(Object.values(project.agents).flatMap((a) => [a.runtime, ...(withFallback ? a.fallback.map((f) => f.runtime) : [])]).filter((r) => !!r)),
136
136
  ];
137
137
  export async function probeProjectRuntimes(project, opts = {}, withFallback = false) {
package/dist/quota.d.ts CHANGED
@@ -5,10 +5,19 @@ export type QuotaWindow = {
5
5
  resets: string;
6
6
  };
7
7
  export type QuotaReport = {
8
- runtime: "claude" | "codex";
8
+ runtime: "claude" | "codex" | "cursor";
9
9
  windows: QuotaWindow[];
10
10
  error?: string;
11
11
  };
12
+ export type CursorTokenReaders = {
13
+ readCliToken?: () => Promise<string | undefined>;
14
+ readEnvApiKey?: () => string | undefined;
15
+ readIdeToken?: () => Promise<string | undefined>;
16
+ };
17
+ export type CursorQuotaDeps = {
18
+ tokens?: () => AsyncIterable<string>;
19
+ fetchUsage?: (token: string, signal?: AbortSignal) => Promise<unknown>;
20
+ };
12
21
  export declare function parseClaudeUsage(text: string): QuotaWindow[];
13
22
  type LimitWindow = {
14
23
  usedPercent?: number;
@@ -22,4 +31,25 @@ type RateLimits = {
22
31
  export declare function codexWindows(limits: RateLimits): QuotaWindow[];
23
32
  export declare function claudeQuota(signal?: AbortSignal): Promise<QuotaReport>;
24
33
  export declare function codexQuota(signal?: AbortSignal): Promise<QuotaReport>;
34
+ type CursorPlanUsage = {
35
+ totalPercentUsed?: number;
36
+ limit?: number;
37
+ remaining?: number;
38
+ };
39
+ type CursorPeriodUsage = {
40
+ billingCycleStart?: string | number;
41
+ billingCycleEnd?: string | number;
42
+ planUsage?: CursorPlanUsage | null;
43
+ };
44
+ /** Map DashboardService/GetCurrentPeriodUsage into the shared QuotaWindow shape. */
45
+ export declare function parseCursorUsage(data: CursorPeriodUsage): QuotaWindow[];
46
+ /**
47
+ * Candidate tokens, most specific login first: the CLI login (auth.json, then the macOS keychain),
48
+ * CURSOR_API_KEY, then the Cursor IDE session. Read lazily, so a working CLI token never touches the IDE database.
49
+ */
50
+ export declare function cursorAccessTokens(readers?: CursorTokenReaders): AsyncGenerator<string>;
51
+ export declare function cursorQuota(signal?: AbortSignal, deps?: CursorQuotaDeps): Promise<QuotaReport>;
52
+ /** CURSOR_API_ENDPOINT may only point at another https Cursor host: the request carries the user's session token. */
53
+ export declare function cursorApiBase(env?: NodeJS.ProcessEnv): string;
54
+ export declare function fetchCursorPeriodUsage(token: string, signal?: AbortSignal, timeoutMs?: number): Promise<unknown>;
25
55
  export {};
package/dist/quota.js CHANGED
@@ -1,4 +1,15 @@
1
- import { spawn } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { cursorConfigDir } from "./adapters/cursor.js";
7
+ /** Run a short local lookup without blocking the web server's event loop (5 s cap). */
8
+ function execText(cmd, args) {
9
+ return new Promise((resolve, reject) => {
10
+ execFile(cmd, args, { encoding: "utf8", timeout: 5_000 }, (error, stdout) => (error ? reject(error) : resolve(stdout)));
11
+ });
12
+ }
2
13
  export function parseClaudeUsage(text) {
3
14
  const session = text.match(/Current session:\s*(\d+(?:\.\d+)?)%\s*used\s*·\s*resets\s+(.+)/);
4
15
  const week = text.match(/Current week(?: \([^)]*\))?:\s*(\d+(?:\.\d+)?)%\s*used\s*·\s*resets\s+(.+)/);
@@ -14,7 +25,7 @@ export function codexWindows(limits) {
14
25
  if (!window || window.usedPercent === undefined)
15
26
  return [];
16
27
  const mins = window.windowDurationMins ?? 0;
17
- const resets = window.resetsAt ? new Date(window.resetsAt * 1000).toLocaleString("zh-Hant", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" }) : "時間不明";
28
+ const resets = window.resetsAt ? formatResets(window.resetsAt * 1000) : "時間不明";
18
29
  return [windowOf(durationLabel(mins), window.usedPercent, resets)];
19
30
  });
20
31
  }
@@ -29,6 +40,9 @@ function durationLabel(mins) {
29
40
  return `${mins / 60} 小時`;
30
41
  return mins > 0 ? `${mins} 分鐘` : "用量";
31
42
  }
43
+ function formatResets(ms) {
44
+ return new Date(ms).toLocaleString("zh-Hant", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" });
45
+ }
32
46
  function windowOf(label, used, resets) {
33
47
  const usedPercent = roundPercent(used);
34
48
  return { label, used_percent: usedPercent, remaining_percent: roundPercent(Math.max(0, 100 - used)), resets };
@@ -61,6 +75,265 @@ export async function codexQuota(signal) {
61
75
  return { runtime: "codex", windows: [], error: missing("codex", error) };
62
76
  }
63
77
  }
78
+ /** Map DashboardService/GetCurrentPeriodUsage into the shared QuotaWindow shape. */
79
+ export function parseCursorUsage(data) {
80
+ const used = usedPercentOf(data.planUsage);
81
+ if (used === undefined)
82
+ return [];
83
+ const endMs = millis(data.billingCycleEnd);
84
+ const startMs = millis(data.billingCycleStart);
85
+ const resets = endMs === undefined ? "時間不明" : formatResets(endMs);
86
+ return [windowOf(cycleLabel(startMs, endMs), used, resets)];
87
+ }
88
+ /**
89
+ * Candidate tokens, most specific login first: the CLI login (auth.json, then the macOS keychain),
90
+ * CURSOR_API_KEY, then the Cursor IDE session. Read lazily, so a working CLI token never touches the IDE database.
91
+ */
92
+ export async function* cursorAccessTokens(readers = {}) {
93
+ const sources = [
94
+ readers.readCliToken ?? defaultReadCliToken,
95
+ async () => (readers.readEnvApiKey ?? (() => process.env.CURSOR_API_KEY))(),
96
+ readers.readIdeToken ?? defaultReadIdeToken,
97
+ ];
98
+ const seen = new Set();
99
+ for (const read of sources) {
100
+ const token = (await read())?.trim();
101
+ if (!token || seen.has(token))
102
+ continue;
103
+ seen.add(token);
104
+ yield token;
105
+ }
106
+ }
107
+ /** A token the dashboard API refused (401/403): try the next login source instead of giving up. */
108
+ class CursorAuthRejected extends Error {
109
+ }
110
+ export async function cursorQuota(signal, deps = {}) {
111
+ try {
112
+ const fetchUsage = deps.fetchUsage ?? fetchCursorPeriodUsage;
113
+ let rejected;
114
+ for await (const token of (deps.tokens ?? (() => cursorAccessTokens()))()) {
115
+ let data;
116
+ try {
117
+ data = await fetchUsage(token, signal);
118
+ }
119
+ catch (error) {
120
+ if (error instanceof CursorAuthRejected) {
121
+ rejected = error.message;
122
+ continue;
123
+ }
124
+ throw error;
125
+ }
126
+ const windows = parseCursorUsage(data);
127
+ if (windows.length === 0)
128
+ return { runtime: "cursor", windows: [], error: "cursor 沒有回傳額度。" };
129
+ return { runtime: "cursor", windows };
130
+ }
131
+ return {
132
+ runtime: "cursor",
133
+ windows: [],
134
+ error: rejected
135
+ ? `${rejected}:Cursor 登入已失效。請重新執行 agent login。`
136
+ : "Cursor 未登入。請先執行 agent login,或設定 CURSOR_API_KEY。",
137
+ };
138
+ }
139
+ catch (error) {
140
+ if (isAbort(error))
141
+ throw error;
142
+ return { runtime: "cursor", windows: [], error: error.message || "cursor 沒有回傳額度。" };
143
+ }
144
+ }
145
+ function usedPercentOf(plan) {
146
+ if (!plan)
147
+ return undefined;
148
+ if (typeof plan.totalPercentUsed === "number" && Number.isFinite(plan.totalPercentUsed))
149
+ return clampPercent(plan.totalPercentUsed);
150
+ const limit = plan.limit;
151
+ const remaining = plan.remaining;
152
+ if (typeof limit === "number" && limit > 0 && typeof remaining === "number" && Number.isFinite(remaining)) {
153
+ return clampPercent(((limit - remaining) / limit) * 100);
154
+ }
155
+ return undefined;
156
+ }
157
+ /** Bonus credit can push `remaining` above `limit`; overage can push it below 0. */
158
+ function clampPercent(n) {
159
+ return Math.min(100, Math.max(0, n));
160
+ }
161
+ function cycleLabel(startMs, endMs) {
162
+ if (startMs === undefined || endMs === undefined || endMs <= startMs)
163
+ return "計費週期";
164
+ const days = (endMs - startMs) / 86_400_000;
165
+ if (days >= 6 && days <= 8)
166
+ return "本週";
167
+ if (days >= 27 && days <= 32)
168
+ return "本月";
169
+ return "計費週期";
170
+ }
171
+ function millis(value) {
172
+ if (value === undefined || value === null || value === "")
173
+ return undefined;
174
+ const n = typeof value === "number" ? value : Number(value);
175
+ return Number.isFinite(n) ? n : undefined;
176
+ }
177
+ async function defaultReadCliToken() {
178
+ for (const file of cursorAuthJsonPaths()) {
179
+ const token = readAccessTokenFromJsonFile(file);
180
+ if (token)
181
+ return token;
182
+ }
183
+ return readCursorKeychainToken();
184
+ }
185
+ function cursorAuthJsonPaths() {
186
+ const home = os.homedir();
187
+ const paths = [path.join(cursorConfigDir(process.env), "auth.json")];
188
+ if (process.platform === "linux" || process.env.XDG_CONFIG_HOME) {
189
+ paths.push(path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "cursor", "auth.json"));
190
+ }
191
+ if (process.platform === "win32") {
192
+ const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming");
193
+ paths.push(path.join(appData, "Cursor", "auth.json"));
194
+ }
195
+ return [...new Set(paths)];
196
+ }
197
+ function readAccessTokenFromJsonFile(file) {
198
+ try {
199
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
200
+ return typeof raw.accessToken === "string" ? raw.accessToken : undefined;
201
+ }
202
+ catch {
203
+ return undefined;
204
+ }
205
+ }
206
+ /** Cursor Agent CLI stores the session JWT in the macOS keychain as cursor-access-token. */
207
+ async function readCursorKeychainToken() {
208
+ if (process.platform !== "darwin")
209
+ return undefined;
210
+ try {
211
+ const stdout = await execText("security", ["find-generic-password", "-s", "cursor-access-token", "-a", "cursor-user", "-w"]);
212
+ return stdout.trim() || undefined;
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
217
+ }
218
+ async function defaultReadIdeToken() {
219
+ const dbPath = cursorIdeStateDbPath();
220
+ if (!dbPath || !fs.existsSync(dbPath))
221
+ return undefined;
222
+ const fromNode = readIdeTokenViaNodeSqlite(dbPath);
223
+ if (fromNode)
224
+ return fromNode;
225
+ return readIdeTokenViaSqliteCli(dbPath);
226
+ }
227
+ function cursorIdeStateDbPath() {
228
+ const home = os.homedir();
229
+ if (process.platform === "darwin") {
230
+ return path.join(home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb");
231
+ }
232
+ if (process.platform === "win32") {
233
+ const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming");
234
+ return path.join(appData, "Cursor", "User", "globalStorage", "state.vscdb");
235
+ }
236
+ const config = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
237
+ return path.join(config, "Cursor", "User", "globalStorage", "state.vscdb");
238
+ }
239
+ function readIdeTokenViaNodeSqlite(dbPath) {
240
+ try {
241
+ const require = createRequire(import.meta.url);
242
+ const { DatabaseSync } = require("node:sqlite");
243
+ const db = new DatabaseSync(dbPath, { readOnly: true });
244
+ try {
245
+ const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken");
246
+ return normalizeSqliteText(row?.value);
247
+ }
248
+ finally {
249
+ db.close();
250
+ }
251
+ }
252
+ catch {
253
+ return undefined;
254
+ }
255
+ }
256
+ async function readIdeTokenViaSqliteCli(dbPath) {
257
+ try {
258
+ const stdout = await execText("sqlite3", ["-readonly", dbPath, "SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken';"]);
259
+ return normalizeSqliteText(stdout.trim());
260
+ }
261
+ catch {
262
+ return undefined;
263
+ }
264
+ }
265
+ function normalizeSqliteText(value) {
266
+ if (typeof value !== "string")
267
+ return undefined;
268
+ const trimmed = value.trim();
269
+ if (!trimmed)
270
+ return undefined;
271
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
272
+ try {
273
+ const parsed = JSON.parse(trimmed);
274
+ return typeof parsed === "string" ? parsed : trimmed.slice(1, -1);
275
+ }
276
+ catch {
277
+ return trimmed.slice(1, -1);
278
+ }
279
+ }
280
+ return trimmed;
281
+ }
282
+ const CURSOR_API_DEFAULT = "https://api2.cursor.sh";
283
+ /** CURSOR_API_ENDPOINT may only point at another https Cursor host: the request carries the user's session token. */
284
+ export function cursorApiBase(env = process.env) {
285
+ const raw = env.CURSOR_API_ENDPOINT?.trim();
286
+ if (!raw)
287
+ return CURSOR_API_DEFAULT;
288
+ try {
289
+ const url = new URL(raw);
290
+ const host = url.hostname;
291
+ if (url.protocol === "https:" && (host === "cursor.sh" || host.endsWith(".cursor.sh")))
292
+ return url.origin;
293
+ }
294
+ catch {
295
+ // Not a URL: fall through to the default.
296
+ }
297
+ return CURSOR_API_DEFAULT;
298
+ }
299
+ export async function fetchCursorPeriodUsage(token, signal, timeoutMs = 20_000) {
300
+ // Combined by hand: AbortSignal.any needs Node 20.3, engines allows 20.0.
301
+ const controller = new AbortController();
302
+ const onAbort = () => controller.abort();
303
+ const timer = setTimeout(onAbort, timeoutMs);
304
+ signal?.addEventListener("abort", onAbort, { once: true });
305
+ if (signal?.aborted)
306
+ controller.abort();
307
+ try {
308
+ const response = await fetch(`${cursorApiBase()}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`, {
309
+ method: "POST",
310
+ headers: {
311
+ Authorization: `Bearer ${token}`,
312
+ "Content-Type": "application/json",
313
+ "Connect-Protocol-Version": "1",
314
+ },
315
+ body: "{}",
316
+ signal: controller.signal,
317
+ });
318
+ if (response.status === 401 || response.status === 403)
319
+ throw new CursorAuthRejected(`cursor 額度 API HTTP ${response.status}`);
320
+ if (!response.ok)
321
+ throw new Error(`cursor 額度 API HTTP ${response.status}`);
322
+ return await response.json();
323
+ }
324
+ catch (error) {
325
+ // Hub aborts → AbortError (discard). Own timeout → plain Error (report, keep Claude/Codex).
326
+ if (signal?.aborted)
327
+ throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
328
+ if (controller.signal.aborted)
329
+ throw new Error(`cursor 超過 ${Math.round(timeoutMs / 1000)} 秒沒有回應。`);
330
+ throw error;
331
+ }
332
+ finally {
333
+ clearTimeout(timer);
334
+ signal?.removeEventListener("abort", onAbort);
335
+ }
336
+ }
64
337
  /** An aborted quota read is a cancelled request, not a report: callers (the hub) discard it. */
65
338
  function isAbort(error) {
66
339
  return error.name === "AbortError";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-lyceum",
3
- "version": "0.43.0",
3
+ "version": "0.44.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",