agent-lyceum 0.43.0 → 0.44.1

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,29 @@
1
+ /** Who did the work and who reviewed it, written as git trailers at the end of agent-lyceum's commit messages. */
2
+ export declare const VERDICTS: readonly ["pass", "changes_requested", "fail"];
3
+ export type Verdict = (typeof VERDICTS)[number];
4
+ export declare function isVerdict(v: unknown): v is Verdict;
5
+ /** A review a teammate gave in a `reply` that carried `verdict:`. */
6
+ export interface ReviewRecord {
7
+ reviewer: string;
8
+ model?: string;
9
+ verdict: Verdict;
10
+ subject: string;
11
+ at: string;
12
+ }
13
+ export interface WorkerRef {
14
+ agent: string;
15
+ model?: string;
16
+ }
17
+ /** `name (model)`, or just `name` when the model is not known. Newlines are dropped so a value cannot start another trailer. */
18
+ export declare function agentLabel(w: WorkerRef): string;
19
+ /** The latest review per reviewer, in the order they first reviewed. */
20
+ export declare function latestReviews(reviews: readonly ReviewRecord[]): ReviewRecord[];
21
+ /** Trailer block (no leading blank line) for one commit. `Reviewed-by` appears only for reviews that really happened. */
22
+ export declare function trailers(i: {
23
+ implementers?: readonly WorkerRef[];
24
+ lead?: WorkerRef;
25
+ reviews?: readonly ReviewRecord[];
26
+ runId?: string;
27
+ }): string;
28
+ /** `<subject>\n\n<body?>\n\n<trailers>`. */
29
+ export declare function withTrailers(subject: string, body: string | undefined, t: string): string;
@@ -0,0 +1,35 @@
1
+ /** Who did the work and who reviewed it, written as git trailers at the end of agent-lyceum's commit messages. */
2
+ export const VERDICTS = ["pass", "changes_requested", "fail"];
3
+ export function isVerdict(v) {
4
+ return typeof v === "string" && VERDICTS.includes(v);
5
+ }
6
+ /** `name (model)`, or just `name` when the model is not known. Newlines are dropped so a value cannot start another trailer. */
7
+ export function agentLabel(w) {
8
+ const clean = (s) => s.replace(/\s+/g, " ").trim();
9
+ return w.model ? `${clean(w.agent)} (${clean(w.model)})` : clean(w.agent);
10
+ }
11
+ /** The latest review per reviewer, in the order they first reviewed. */
12
+ export function latestReviews(reviews) {
13
+ const byReviewer = new Map();
14
+ for (const r of reviews)
15
+ byReviewer.set(r.reviewer, r);
16
+ return [...byReviewer.values()];
17
+ }
18
+ /** Trailer block (no leading blank line) for one commit. `Reviewed-by` appears only for reviews that really happened. */
19
+ export function trailers(i) {
20
+ const lines = [];
21
+ for (const w of i.implementers ?? [])
22
+ lines.push(`Implemented-by: ${agentLabel(w)}`);
23
+ if (i.lead)
24
+ lines.push(`Led-by: ${agentLabel(i.lead)}`);
25
+ for (const r of latestReviews(i.reviews ?? []))
26
+ lines.push(`Reviewed-by: ${agentLabel({ agent: r.reviewer, model: r.model })} [${r.verdict}]`);
27
+ if (i.runId)
28
+ lines.push(`Run: ${i.runId.replace(/\s+/g, "")}`);
29
+ lines.push("Generated-by: agent-lyceum");
30
+ return lines.join("\n");
31
+ }
32
+ /** `<subject>\n\n<body?>\n\n<trailers>`. */
33
+ export function withTrailers(subject, body, t) {
34
+ return [subject, body?.trim(), t].filter(Boolean).join("\n\n");
35
+ }
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/mailbox.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type Step } from "./format.js";
3
3
  import { atomicWrite } from "./fs-util.js";
4
4
  import { type InstanceCap } from "./instances.js";
5
5
  import type { Tier } from "./schema.js";
6
+ import { type Verdict } from "./attribution.js";
6
7
  import { RouteJournal } from "./message-store.js";
7
8
  export { atomicWrite };
8
9
  export declare const MESSAGE_TYPES: readonly ["task", "reply", "failure", "done", "ask"];
@@ -85,7 +86,8 @@ export interface RouteResult {
85
86
  id: string;
86
87
  file: string;
87
88
  type: MessageType;
88
- subject: string;
89
+ subject: string; /** A reply's `verdict:` (a review result). */
90
+ verdict?: Verdict;
89
91
  }[];
90
92
  rejected: {
91
93
  from: string;
package/dist/mailbox.js CHANGED
@@ -8,6 +8,7 @@ import { atomicWrite, readRegularFileNoFollow } from "./fs-util.js";
8
8
  import { countFormatRejection, formatRejectionKey, formatRejections, MAX_FORMAT_REJECTIONS } from "./format-rejections.js";
9
9
  import { parallelFlag, roleOfName } from "./instances.js";
10
10
  import { effectiveTier, tierFlag } from "./tiers.js";
11
+ import { isVerdict } from "./attribution.js";
11
12
  import { deterministicId, fault, RouteJournal, sourceIdOf } from "./message-store.js";
12
13
  import { inboxDir, outboxDir, sharedDir } from "./policy.js";
13
14
  import { activeRecordsBytes, RECORD_KINDS, RECORDS_BUDGET } from "./records.js";
@@ -295,6 +296,15 @@ export function routeOutboxes(project, routing) {
295
296
  continue;
296
297
  }
297
298
  const subject = String(d.subject ?? "(no subject)");
299
+ // `verdict` is how a reviewer's result is recorded (it ends up as a `Reviewed-by` trailer); it is only meaningful on a reply.
300
+ let verdict;
301
+ if (d.verdict !== undefined && d.verdict !== null && d.verdict !== "") {
302
+ if (!isVerdict(d.verdict) || type !== "reply") {
303
+ reject(`verdict must be pass, changes_requested or fail, and only a \`reply\` carries one (got ${JSON.stringify(d.verdict)} on a ${type}). Leave the line out if you did not review anything.`);
304
+ continue;
305
+ }
306
+ verdict = d.verdict;
307
+ }
298
308
  if (type === "ask") {
299
309
  if (!sender.canAskUser) {
300
310
  reject(`you may not ask the user directly (can_ask_user is off for "${sender.name}"). Put the question in a reply to the lead ("${project.lead}"), who can ask.`);
@@ -438,7 +448,7 @@ export function routeOutboxes(project, routing) {
438
448
  });
439
449
  if (!fresh)
440
450
  continue;
441
- res.delivered.push({ from: sender.name, to, id: msg.meta.id, file: msg.file, type, subject });
451
+ res.delivered.push({ from: sender.name, to, id: msg.meta.id, file: msg.file, type, subject, ...(verdict ? { verdict } : {}) });
442
452
  if (missing.length)
443
453
  res.warnings.push({ from: sender.name, id: msg.meta.id, subject, missing });
444
454
  }
package/dist/prompt.js CHANGED
@@ -180,7 +180,7 @@ export function buildSystemPrompt(project, agent) {
180
180
  ? [
181
181
  `That directory is your own isolated git worktree (branch \`${project.workspaces?.[agent.name]?.branch}\`): teammates cannot see your changes while you work, and you cannot see theirs. Do not commit, push, switch branches or touch any other checkout; the dispatcher collects your changes from this directory after you finish.`,
182
182
  ]
183
- : []), `The team lead is **${project.lead}**${isLead ? " (that is you)" : ""}. Teammates: ${mates.join(", ") || "(none)"}.`, "", "## Sending mail", "You cannot talk to teammates directly. Mail you receive is shown in your prompt. To send mail, create a Markdown file", `(any name ending in \`.md\`) directly inside \`${outbox}\` with this exact shape:`, "", "```", "---", "to: <agent-name>", `type: reply # task | reply${agent.canAskUser ? " | ask" : ""}${isLead ? " | done" : ""}`, "subject: <short subject>", "reply_to: <message id> # optional", "---", "", "<body>", "```", "", `You may send to: ${recipients.join(", ") || "(nobody)"}.`, isLead
183
+ : []), `The team lead is **${project.lead}**${isLead ? " (that is you)" : ""}. Teammates: ${mates.join(", ") || "(none)"}.`, "", "## Sending mail", "You cannot talk to teammates directly. Mail you receive is shown in your prompt. To send mail, create a Markdown file", `(any name ending in \`.md\`) directly inside \`${outbox}\` with this exact shape:`, "", "```", "---", "to: <agent-name>", `type: reply # task | reply${agent.canAskUser ? " | ask" : ""}${isLead ? " | done" : ""}`, "subject: <short subject>", "reply_to: <message id> # optional", "verdict: pass | changes_requested | fail # optional; only in a reply that reviews someone's work, it is recorded as `Reviewed-by` in the commit", "---", "", "<body>", "```", "", `You may send to: ${recipients.join(", ") || "(nobody)"}.`, isLead
184
184
  ? `When the whole job is finished, send a message with \`type: done\` (no \`to\` needed). That ends the run. A summary in your reply text is never delivered and does not end the run: after the last teammate reply is verified you MUST send \`done\` (or a \`task\` for the remaining work), or the run stops as "idle" with no final report.`
185
185
  : `Report results to the lead by mail; the lead decides what happens next.`, isLead
186
186
  ? "Each wake-up handles one message, except that several `reply`/`failure` messages waiting together are handed to you in one wake-up: weigh them together, then decide the next step once."
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";
@@ -171,6 +171,8 @@ export declare class RunSession {
171
171
  * A finished member's files go from its worktree into the repo before anyone reads its mail, so the lead
172
172
  * sees them. When that cannot be done, nothing is applied, the member's work stays on its branch, and the lead is told.
173
173
  */
174
+ /** The agent and the model it last ran on (a tier or fallback shows in `last_wake`), else its configured model. */
175
+ private workerRef;
174
176
  private integrateMember;
175
177
  /** A member whose worktree was refused: it is not woken again in this run, and the lead is told so it can react. */
176
178
  private refuseMember;
@@ -19,6 +19,7 @@ import { inboxDir, outboxDir, sharedIndex } from "./policy.js";
19
19
  import { buildSystemPrompt, buildUserPrompt, pickMessages } from "./prompt.js";
20
20
  import { collectDrafts, priorFailedAttempts, redoUserPrompt } from "./redo.js";
21
21
  import { atomicWrite, readFileCapped } from "./fs-util.js";
22
+ import { trailers, withTrailers } from "./attribution.js";
22
23
  import { assertWorktreeRunnable, collectAgentChanges, dirtyPaths, existingAgentWorkspace, finishLeadBranch, integrateAgentChanges, prepareAgentWorkspace, recutLeadWorkspace, refusedIntegration, snapshotBase, snapshotHead, toplevel } from "./worktree.js";
23
24
  import { workingTreeHash } from "./worktree.js";
24
25
  import { bindRunProject, newRunId, newRunState, roundLimit, roundsLabel, saveRunState } from "./run-store.js";
@@ -865,12 +866,18 @@ export class RunSession {
865
866
  * A finished member's files go from its worktree into the repo before anyone reads its mail, so the lead
866
867
  * sees them. When that cannot be done, nothing is applied, the member's work stays on its branch, and the lead is told.
867
868
  */
869
+ /** The agent and the model it last ran on (a tier or fallback shows in `last_wake`), else its configured model. */
870
+ workerRef(agent) {
871
+ const model = this.state.last_wake[agent.name]?.model ?? agent.model;
872
+ return { agent: agent.name, ...(model ? { model } : {}) };
873
+ }
868
874
  integrateMember(agent, ws, key) {
869
875
  const { say, project, log, state } = this;
870
876
  let changes;
871
877
  let r;
872
878
  try {
873
- changes = collectAgentChanges(ws);
879
+ const who = this.workerRef(agent);
880
+ changes = collectAgentChanges(ws, withTrailers(`agent-lyceum: changes by ${agent.name}`, undefined, trailers({ implementers: [who], runId: this.runId })));
874
881
  r = integrateAgentChanges(project, changes, this.leadSpace);
875
882
  }
876
883
  catch (e) {
@@ -881,6 +888,10 @@ export class RunSession {
881
888
  const blocked = (state.blocked_integrations ?? []).filter((b) => b.agent !== agent.name);
882
889
  if (r.status === "integrated") {
883
890
  state.blocked_integrations = blocked;
891
+ if (r.files.length) {
892
+ const who = this.workerRef(agent);
893
+ state.implementers = [...(state.implementers ?? []).filter((w) => w.agent !== who.agent), who];
894
+ }
884
895
  if (r.files.length)
885
896
  say(` ${agent.name}: ${r.files.length} changed file(s) brought into the repo`);
886
897
  return;
@@ -945,6 +956,12 @@ export class RunSession {
945
956
  this.integrateMember(a, ws, claims.get(a.name)?.id ?? `${a.name}-${state.rounds}`);
946
957
  });
947
958
  const route = routeOutboxes(project, this.routing());
959
+ for (const m of route.delivered) {
960
+ const a = m.verdict ? (project.agents[m.from] ?? project.agents[roleOfName(project.agents, m.from)]) : undefined;
961
+ if (!m.verdict || !a)
962
+ continue;
963
+ state.reviews = [...(state.reviews ?? []), { reviewer: a.name, ...(this.workerRef(a).model ? { model: this.workerRef(a).model } : {}), verdict: m.verdict, subject: m.subject, at: new Date().toISOString() }];
964
+ }
948
965
  // A done that breaks the completion contract goes back to the lead (a limited number of times).
949
966
  let contract;
950
967
  if (route.done) {
@@ -1224,7 +1241,9 @@ export class RunSession {
1224
1241
  if (!this.leadSpace || endReason === "waiting")
1225
1242
  return undefined;
1226
1243
  try {
1227
- const rb = finishLeadBranch(this.leadSpace, `agent-lyceum: ${project.lead}'s work for run ${runId}\n\n${state.task_summary}`, path.join(runDir, "lead.patch"));
1244
+ const lead = project.agents[project.lead];
1245
+ const message = withTrailers(`agent-lyceum: ${project.lead}'s work for run ${runId}`, state.task_summary, trailers({ implementers: state.implementers, lead: lead ? this.workerRef(lead) : undefined, reviews: state.reviews, runId }));
1246
+ const rb = finishLeadBranch(this.leadSpace, message, path.join(runDir, "lead.patch"));
1228
1247
  state.result_branch = rb;
1229
1248
  log("lead-branch", { ...rb });
1230
1249
  say(rb.files ? ` work is on branch ${rb.branch} (${rb.files} file(s)); bring it into your repo with: git merge ${rb.branch}` : ` ${rb.branch}: no file changes`);
@@ -2,6 +2,7 @@ import type { ResolvedProject } from "./config.js";
2
2
  import type { DigestSection, Step } from "./format.js";
3
3
  import { type ErrorKind, type Runtime, type RunOutcome, type Tier } from "./schema.js";
4
4
  import type { ResultBranch } from "./worktree.js";
5
+ import type { ReviewRecord, WorkerRef } from "./attribution.js";
5
6
  export declare const STATE_FILE = "state.json";
6
7
  /** The newest state format this version reads. */
7
8
  export declare const STATE_SCHEMA_VERSION = 3;
@@ -140,6 +141,10 @@ export interface RunState {
140
141
  result_branch?: ResultBranch;
141
142
  /** Set when the run started with the lead in its own worktree (isolation mode); its resumes keep that, whatever the config says later. */
142
143
  lead_workspace?: true;
144
+ /** Reviews given in this run (a reply's `verdict:`), oldest first; written into the lead's commit as `Reviewed-by`. */
145
+ reviews?: ReviewRecord[];
146
+ /** Members whose files were brought into the repo, with the model they last ran on; written into the lead's commit as `Implemented-by`. */
147
+ implementers?: WorkerRef[];
143
148
  /** The pull request the dispatcher opened for this run (when the lead asked for one and it worked). */
144
149
  pr_url?: string;
145
150
  sessions: Record<string, string>;
package/dist/run-store.js CHANGED
@@ -68,6 +68,8 @@ const WireState = z
68
68
  active: z.record(z.string(), z.any()).optional(),
69
69
  wakes: z.array(z.any()).optional(),
70
70
  solo_agent: z.string().optional(),
71
+ reviews: z.array(z.any()).optional(),
72
+ implementers: z.array(z.any()).optional(),
71
73
  steps: z.array(z.object({ text: z.string(), done: z.boolean() })).optional(),
72
74
  failure: z
73
75
  .object({
@@ -126,7 +126,7 @@ export declare function commitWorkspace(ws: AgentWorkspace, message: string): {
126
126
  * changed path (modified, added, deleted, or either end of a rename) against the project
127
127
  * folder, the protected instruction files, and symlink/submodule rules. Nothing is applied here.
128
128
  */
129
- export declare function collectAgentChanges(workspace: AgentWorkspace): ChangeSet;
129
+ export declare function collectAgentChanges(workspace: AgentWorkspace, message?: string): ChangeSet;
130
130
  export type IntegrationResult = {
131
131
  status: "integrated";
132
132
  files: ChangedFile[];