agent-lyceum 0.42.2 → 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.
@@ -0,0 +1,27 @@
1
+ import type { ErrorKind } from "../schema.js";
2
+ import type { Invocation, WakeInput } from "./types.js";
3
+ /** The user's own Cursor config dir: the one the CLI would read without our override. */
4
+ export declare function cursorConfigDir(env?: NodeJS.ProcessEnv): string;
5
+ /** Whether `dir` holds a login the CLI can use (a regular `auth.json`). */
6
+ export declare function hasCursorAuth(dir: string): boolean;
7
+ /**
8
+ * Writes `cli-config.json` under `workDir` (read via `CURSOR_CONFIG_DIR`, so the repo's own `.cursor/cli.json` is never touched).
9
+ * Carries auth files and keeps the user's `version`/`editor` when present. Permissions.allow is **only** lyceum's Write/WebFetch
10
+ * rules (never the user's allow — that could import `Shell(*)` etc.). Deny is unioned with the user's deny (stricter).
11
+ * Web: denied unless `allowWeb` is `fetch`. `search` has no Cursor permission token, so it stays denied (documented gap).
12
+ * Shell under `--force` follows Cursor's default approval rules; we do not emit a broad `Shell(*)` allow.
13
+ */
14
+ export declare function writeCursorCliConfig(workDir: string, input: WakeInput): string;
15
+ /** The prompt travels as one argv entry (spike: no stdin path), so the OS argument limit bounds it. */
16
+ export declare const MAX_PROMPT_BYTES = 100000;
17
+ /** The prompt cannot be passed on argv: a config problem (retrying the same prompt cannot help), not a transient failure. */
18
+ export declare class CursorPromptTooLongError extends Error {
19
+ }
20
+ export declare function buildCursorInvocation(raw: WakeInput): Invocation;
21
+ /** Reads the error channels only (the result message of a failed run, else stderr): stdout carries the agent's own words. */
22
+ export declare function classifyCursorError(out: {
23
+ code: number | null;
24
+ stdout: string;
25
+ stderr: string;
26
+ result?: string;
27
+ }): ErrorKind;
@@ -0,0 +1,229 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { projectCommonDir, projectCommonDirAllowed, repoDirFor, scratchCwd, writePolicy } from "../policy.js";
5
+ import { applyShipToWake } from "../ship-wire.js";
6
+ const CLI_CONFIG_FILE = "cli-config.json";
7
+ /** Cursor permission token for a path: covers the path itself and, when it is (or may become) a directory, everything under it. */
8
+ function denyRules(p) {
9
+ let isFile = false;
10
+ try {
11
+ isFile = fs.statSync(p).isFile();
12
+ }
13
+ catch {
14
+ /* missing: cover both */
15
+ }
16
+ return isFile ? [`Write(${p})`] : [`Write(${p})`, `Write(${p}/**)`];
17
+ }
18
+ /** Credential files carried from the user's Cursor config dir into the per-run one (`CURSOR_CONFIG_DIR` replaces the whole dir, so login would be lost). */
19
+ const AUTH_FILES = ["auth.json"];
20
+ /** The user's own Cursor config dir: the one the CLI would read without our override. */
21
+ export function cursorConfigDir(env = process.env) {
22
+ return env.CURSOR_CONFIG_DIR || path.join(os.homedir(), ".cursor");
23
+ }
24
+ /** Whether `dir` holds a login the CLI can use (a regular `auth.json`). */
25
+ export function hasCursorAuth(dir) {
26
+ try {
27
+ return AUTH_FILES.some((n) => fs.statSync(path.join(dir, n)).isFile());
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ function readJsonObject(file) {
34
+ try {
35
+ const j = JSON.parse(fs.readFileSync(file, "utf8"));
36
+ return j && typeof j === "object" && !Array.isArray(j) ? j : undefined;
37
+ }
38
+ catch {
39
+ return undefined; // missing or malformed: ignore the source config
40
+ }
41
+ }
42
+ const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
43
+ /**
44
+ * Copies (mode 0600) auth files that exist in `src` into `workDir`; never touches cli-config.json.
45
+ * A copy, not a symlink: if the CLI refreshes the token by rewriting or renaming the file, a link would either mutate the
46
+ * user's own login file or leave it with a stale refresh token. The copy is run-scoped and replaced on every wake.
47
+ */
48
+ function carryAuthFiles(src, workDir) {
49
+ if (path.resolve(src) === path.resolve(workDir))
50
+ return;
51
+ for (const name of AUTH_FILES) {
52
+ const from = path.join(src, name);
53
+ const to = path.join(workDir, name);
54
+ try {
55
+ if (!fs.statSync(from).isFile())
56
+ continue;
57
+ fs.rmSync(to, { force: true }); // a stale link or copy from an earlier wake (never write through an old link)
58
+ fs.copyFileSync(from, to);
59
+ fs.chmodSync(to, 0o600);
60
+ }
61
+ catch {
62
+ /* absent: nothing to carry */
63
+ }
64
+ }
65
+ }
66
+ /**
67
+ * Writes `cli-config.json` under `workDir` (read via `CURSOR_CONFIG_DIR`, so the repo's own `.cursor/cli.json` is never touched).
68
+ * Carries auth files and keeps the user's `version`/`editor` when present. Permissions.allow is **only** lyceum's Write/WebFetch
69
+ * rules (never the user's allow — that could import `Shell(*)` etc.). Deny is unioned with the user's deny (stricter).
70
+ * Web: denied unless `allowWeb` is `fetch`. `search` has no Cursor permission token, so it stays denied (documented gap).
71
+ * Shell under `--force` follows Cursor's default approval rules; we do not emit a broad `Shell(*)` allow.
72
+ */
73
+ export function writeCursorCliConfig(workDir, input) {
74
+ const { project, agent } = input;
75
+ const pol = input.policy ?? writePolicy(project, agent);
76
+ const allow = [...pol.allowDirs.map((d) => `Write(${d}/**)`), ...pol.allowFiles.map((f) => `Write(${f})`)];
77
+ const deny = pol.deny.flatMap(denyRules);
78
+ if (agent.allowWeb === "fetch" && !input.policy)
79
+ allow.push("WebFetch(*)");
80
+ else
81
+ deny.push("WebFetch(*)");
82
+ fs.mkdirSync(workDir, { recursive: true });
83
+ const src = cursorConfigDir();
84
+ carryAuthFiles(src, workDir);
85
+ const base = path.resolve(src) === path.resolve(workDir) ? undefined : readJsonObject(path.join(src, CLI_CONFIG_FILE));
86
+ const srcPerms = base?.permissions;
87
+ const version = typeof base?.version === "number" ? base.version : 1;
88
+ const editor = base?.editor && typeof base.editor === "object" && !Array.isArray(base.editor) ? base.editor : { vimMode: false };
89
+ const file = path.join(workDir, CLI_CONFIG_FILE);
90
+ const cfg = {
91
+ version,
92
+ editor,
93
+ permissions: {
94
+ allow: [...new Set(allow)],
95
+ deny: [...new Set([...deny, ...strings(srcPerms?.deny)])],
96
+ },
97
+ };
98
+ fs.writeFileSync(file, JSON.stringify(cfg, null, 2));
99
+ return file;
100
+ }
101
+ /** The prompt travels as one argv entry (spike: no stdin path), so the OS argument limit bounds it. */
102
+ export const MAX_PROMPT_BYTES = 100_000;
103
+ /** The prompt cannot be passed on argv: a config problem (retrying the same prompt cannot help), not a transient failure. */
104
+ export class CursorPromptTooLongError extends Error {
105
+ }
106
+ /** Persona + task as the positional argument (as with Codex). Guards the argv size and keeps a leading `-` from reading as a flag. */
107
+ function promptArg(systemPrompt, userPrompt) {
108
+ const prompt = `${systemPrompt}\n\n=====\n\n${userPrompt}`;
109
+ const bytes = Buffer.byteLength(prompt, "utf8");
110
+ if (bytes > MAX_PROMPT_BYTES)
111
+ throw new CursorPromptTooLongError(`Cursor prompt too long for argv: ${bytes} bytes > ${MAX_PROMPT_BYTES} (cursor passes the prompt as a command-line argument)`);
112
+ // The agent CLI is not known to accept `--`, so a harmless leading newline stops a flag-looking prompt from being parsed as an option.
113
+ return prompt.startsWith("-") ? `\n${prompt}` : prompt;
114
+ }
115
+ export function buildCursorInvocation(raw) {
116
+ const { input } = applyShipToWake(raw);
117
+ const { project, agent, workDir } = input;
118
+ const prompt = promptArg(input.systemPrompt, input.userPrompt); // before any file is created
119
+ const repo = input.policy ? scratchCwd(workDir) : repoDirFor(project, agent.name);
120
+ fs.mkdirSync(workDir, { recursive: true });
121
+ if (input.policy)
122
+ fs.mkdirSync(repo, { recursive: true });
123
+ writeCursorCliConfig(workDir, input);
124
+ // Writable paths outside --workspace (memory, outbox, ...) need --add-dir as well as the Write(...) rules, like Claude.
125
+ // workDir is deliberately not added (not a writable path; also holds the ship session).
126
+ const pol = input.policy ?? writePolicy(project, agent);
127
+ // Like Codex, withhold shared/common when it overlaps another agent's protected paths (the deny rules would be the only layer).
128
+ const common = projectCommonDir(project);
129
+ const withholdCommon = !input.policy && !projectCommonDirAllowed(project, agent);
130
+ const fileDirs = pol.allowFiles.map((f) => path.dirname(f)).filter((d) => !withholdCommon || (d !== common && !d.startsWith(common + path.sep)));
131
+ const addDirs = [...new Set([...pol.allowDirs, ...fileDirs].filter((d) => !(d === repo || d.startsWith(repo + path.sep))))];
132
+ const args = ["-p", "--force", "--trust", "--sandbox", "enabled", "--workspace", repo];
133
+ // Placed before other flags so a variadic --add-dir can never swallow the positional prompt.
134
+ for (const d of addDirs)
135
+ args.push("--add-dir", d);
136
+ args.push("--output-format", "stream-json");
137
+ if (agent.model)
138
+ args.push("--model", agent.model);
139
+ if (input.sessionId)
140
+ args.push("--resume", input.sessionId);
141
+ args.push(prompt);
142
+ return {
143
+ cmd: "agent",
144
+ args,
145
+ stdin: "",
146
+ cwd: repo,
147
+ env: { ...process.env, AGENT_LYCEUM_AGENT: agent.name, CURSOR_CONFIG_DIR: workDir },
148
+ parse({ stdout, stderr, code }) {
149
+ const s = cursorStream();
150
+ for (const l of stdout.split("\n"))
151
+ s.line(l);
152
+ return s.finish({ code, stdoutTail: stdout, stderrTail: stderr });
153
+ },
154
+ stream: () => cursorStream(),
155
+ };
156
+ }
157
+ function parseEvent(line) {
158
+ const t = line.trim();
159
+ if (!t.startsWith("{"))
160
+ return undefined;
161
+ try {
162
+ const j = JSON.parse(t);
163
+ return j && typeof j === "object" ? j : undefined;
164
+ }
165
+ catch {
166
+ return undefined; // not json
167
+ }
168
+ }
169
+ function cursorStream() {
170
+ let sessionId;
171
+ let last;
172
+ return {
173
+ line(l) {
174
+ const e = parseEvent(l);
175
+ if (!e)
176
+ return;
177
+ if (typeof e.session_id === "string")
178
+ sessionId = e.session_id;
179
+ if (e.type === "result")
180
+ last = e;
181
+ },
182
+ finish({ code, stdoutTail, stderrTail }) {
183
+ return finishCursor(last, sessionId, stdoutTail, stderrTail, code);
184
+ },
185
+ };
186
+ }
187
+ function finishCursor(result, sessionId, stdout, stderr, code) {
188
+ const text = typeof result?.result === "string" ? result.result : "";
189
+ const ok = code === 0 && !!result && !result.is_error;
190
+ if (ok)
191
+ return { ok, text, sessionId };
192
+ const resultError = result?.is_error ? text : undefined;
193
+ return {
194
+ ok,
195
+ text: result ? text : stdout,
196
+ sessionId,
197
+ error: (resultError || stderr || stdout || `exit code ${code}`).slice(-500),
198
+ kind: classifyCursorError({ code, stdout, stderr, result: resultError }),
199
+ };
200
+ }
201
+ /**
202
+ * Ordered, first match wins: a spent quota is more specific than a 429.
203
+ * Patterns follow the Codex adapter style (status/phrase anchors), documented/expected — not yet observed in real Cursor logs.
204
+ */
205
+ const CURSOR_RULES = [
206
+ { kind: "quota", re: /insufficient_quota|exceeded your (current )?quota|usage limit|out of (usage|credits)|quota (exceeded|exhausted)/i },
207
+ { kind: "rate_limit", re: /\bstatus:? 429\b|\b429 too many requests|rate_limit_exceeded|rate[ _]limit (reached|exceeded)/i },
208
+ { kind: "auth", re: /\bstatus:? 401\b|\b401 unauthori[sz]ed|invalid[_ ]api[_ ]key|incorrect api key|not logged in|agent login|authentication (required|failed)/i },
209
+ { kind: "network", re: /ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|socket hang up|network (error|unreachable)|fetch failed/i },
210
+ { kind: "crash", re: /segmentation fault|panicked at|heap out of memory/i },
211
+ ];
212
+ /** Reads the error channels only (the result message of a failed run, else stderr): stdout carries the agent's own words. */
213
+ export function classifyCursorError(out) {
214
+ let text = out.result ?? out.stderr;
215
+ if (!text) {
216
+ // a failed `result` event in stdout is the final verdict when stderr is silent
217
+ for (const l of out.stdout.split("\n").reverse()) {
218
+ const e = parseEvent(l);
219
+ if (e?.type === "result" && e.is_error && typeof e.result === "string") {
220
+ text = e.result;
221
+ break;
222
+ }
223
+ }
224
+ }
225
+ const hit = CURSOR_RULES.find((r) => r.re.test(text));
226
+ if (hit)
227
+ return hit.kind;
228
+ return out.code === null ? "crash" : "unknown";
229
+ }
@@ -2,19 +2,34 @@ import path from "node:path";
2
2
  import { runInvocation } from "../process-runner.js";
3
3
  import { buildClaudeInvocation } from "./claude.js";
4
4
  import { buildCodexInvocation } from "./codex.js";
5
+ import { buildCursorInvocation, CursorPromptTooLongError } from "./cursor.js";
5
6
  export function buildInvocation(input) {
6
7
  switch (input.agent.runtime) {
7
8
  case "claude-code":
8
9
  return buildClaudeInvocation(input);
9
10
  case "codex":
10
11
  return buildCodexInvocation(input);
12
+ case "cursor":
13
+ return buildCursorInvocation(input);
11
14
  default:
12
15
  throw new Error(`Agent "${input.agent.name}" has no runtime`);
13
16
  }
14
17
  }
15
- export const realInvoker = (input) => runInvocation(buildInvocation(input), {
16
- timeoutSec: input.timeoutSec,
17
- signal: input.signal,
18
- logDir: input.logDir ?? path.join(input.workDir, "logs"),
19
- });
18
+ export const realInvoker = async (input) => {
19
+ let inv;
20
+ try {
21
+ inv = buildInvocation(input);
22
+ }
23
+ catch (e) {
24
+ // kind "config" stops at once and is not retried with backoff; the same oversized prompt would fail again.
25
+ if (e instanceof CursorPromptTooLongError)
26
+ return { ok: false, text: "", exitCode: null, timedOut: false, error: e.message, kind: "config" };
27
+ throw e;
28
+ }
29
+ return runInvocation(inv, {
30
+ timeoutSec: input.timeoutSec,
31
+ signal: input.signal,
32
+ logDir: input.logDir ?? path.join(input.workDir, "logs"),
33
+ });
34
+ };
20
35
  export { runInvocation };
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
  };
@@ -945,6 +956,8 @@ program
945
956
  let runtime = opts.runtime;
946
957
  if (runtime && !RUNTIMES.includes(runtime))
947
958
  fail(`Unknown runtime "${runtime}". Use one of: ${RUNTIMES.join(", ")}.`);
959
+ if (runtime === "cursor")
960
+ fail("The demo does not support cursor yet (it needs a grok-* model). Use claude-code or codex.");
948
961
  runtime ??= detectRuntime();
949
962
  if (!runtime) {
950
963
  if (!opts.setupOnly)
package/dist/config.d.ts CHANGED
@@ -97,9 +97,10 @@ export declare function loadGlobal(home: string): {
97
97
  model_tiers?: {
98
98
  "claude-code"?: string[] | undefined;
99
99
  codex?: string[] | undefined;
100
+ cursor?: string[] | undefined;
100
101
  } | undefined;
101
102
  agents: Record<string, {
102
- runtime?: "claude-code" | "codex" | undefined;
103
+ runtime?: "claude-code" | "codex" | "cursor" | undefined;
103
104
  model?: string | undefined;
104
105
  effort?: "high" | "low" | "max" | "medium" | "minimal" | "xhigh" | undefined;
105
106
  agent_md?: string | undefined;
@@ -113,7 +114,7 @@ export declare function loadGlobal(home: string): {
113
114
  can_ask_user?: boolean | undefined;
114
115
  allow_web?: "fetch" | "none" | "search" | undefined;
115
116
  fallback?: {
116
- runtime?: "claude-code" | "codex" | undefined;
117
+ runtime?: "claude-code" | "codex" | "cursor" | undefined;
117
118
  model?: string | undefined;
118
119
  effort?: "high" | "low" | "max" | "medium" | "minimal" | "xhigh" | undefined;
119
120
  }[] | undefined;
@@ -138,6 +139,7 @@ export declare function loadProjectRaw(home: string, name: string): {
138
139
  model_tiers?: {
139
140
  "claude-code"?: string[] | undefined;
140
141
  codex?: string[] | undefined;
142
+ cursor?: string[] | undefined;
141
143
  } | undefined;
142
144
  verify?: {
143
145
  max_rejections?: number | undefined;
@@ -157,7 +159,7 @@ export declare function loadProjectRaw(home: string, name: string): {
157
159
  workspace_mode?: unknown;
158
160
  log_max_bytes?: number | undefined;
159
161
  fallback?: {
160
- runtime?: "claude-code" | "codex" | undefined;
162
+ runtime?: "claude-code" | "codex" | "cursor" | undefined;
161
163
  model?: string | undefined;
162
164
  effort?: "high" | "low" | "max" | "medium" | "minimal" | "xhigh" | undefined;
163
165
  }[] | undefined;
@@ -165,7 +167,7 @@ export declare function loadProjectRaw(home: string, name: string): {
165
167
  max_instances?: number | undefined;
166
168
  };
167
169
  agents: Record<string, {
168
- runtime?: "claude-code" | "codex" | undefined;
170
+ runtime?: "claude-code" | "codex" | "cursor" | undefined;
169
171
  model?: string | undefined;
170
172
  effort?: "high" | "low" | "max" | "medium" | "minimal" | "xhigh" | undefined;
171
173
  agent_md?: string | undefined;
@@ -179,7 +181,7 @@ export declare function loadProjectRaw(home: string, name: string): {
179
181
  can_ask_user?: boolean | undefined;
180
182
  allow_web?: "fetch" | "none" | "search" | undefined;
181
183
  fallback?: {
182
- runtime?: "claude-code" | "codex" | undefined;
184
+ runtime?: "claude-code" | "codex" | "cursor" | undefined;
183
185
  model?: string | undefined;
184
186
  effort?: "high" | "low" | "max" | "medium" | "minimal" | "xhigh" | undefined;
185
187
  }[] | undefined;
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
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { cursorConfigDir, hasCursorAuth } from "./adapters/cursor.js";
4
5
  import { findOnPath } from "./fs-util.js";
5
6
  import { tidyAdvice } from "./memory-tidy.js";
6
7
  import { listRecords, RECORD_KINDS } from "./records.js";
@@ -28,7 +29,7 @@ export function suggestVerify(dir) {
28
29
  return undefined;
29
30
  return `\`verify\` is not set, so a lead's \`done\` is not checked. To check it, add to project.yaml:\n verify:\n commands:\n${lines.map((l) => ` ${l}`).join("\n")}\nSee docs/configuration.md#verify. These commands run outside the sandbox.`;
30
31
  }
31
- const BINARY = { "claude-code": "claude", codex: "codex" };
32
+ const BINARY = { "claude-code": "claude", codex: "codex", cursor: "agent" };
32
33
  /** Run a read-only CLI query (`--version`, `--help`): bounded in time and output, never an agent task. */
33
34
  async function query(cmd, args, opts) {
34
35
  const logDir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-lyceum-probe-"));
@@ -76,6 +77,12 @@ export async function probeRuntime(runtime, opts = {}) {
76
77
  caps.sandbox = has(h.out, /--settings\b/) === "yes" ? "yes" : "unknown";
77
78
  caps.effort = has(h.out, /--effort\b/);
78
79
  }
80
+ else if (runtime === "cursor") {
81
+ caps.json = has(h.out, /--output-format\b/);
82
+ caps.resume = has(h.out, /--resume\b/);
83
+ caps.sandbox = has(h.out, /--sandbox\b/);
84
+ caps.effort = "no"; // the Cursor CLI has no effort flag
85
+ }
79
86
  else {
80
87
  caps.json = has(h.out, /--json\b/);
81
88
  caps.sandbox = has(h.out, /--sandbox\b|\s-s,/);
@@ -124,7 +131,7 @@ function judgeRuntimes(project, caps) {
124
131
  return checks;
125
132
  }
126
133
  /** Runtimes of the agents themselves; with `withFallback`, also those that only a fallback chain uses. */
127
- const runtimesUsed = (project, withFallback) => [
134
+ export const runtimesUsed = (project, withFallback) => [
128
135
  ...new Set(Object.values(project.agents).flatMap((a) => [a.runtime, ...(withFallback ? a.fallback.map((f) => f.runtime) : [])]).filter((r) => !!r)),
129
136
  ];
130
137
  export async function probeProjectRuntimes(project, opts = {}, withFallback = false) {
@@ -219,6 +226,18 @@ export async function diagnoseProject(project, opts = {}) {
219
226
  const runtimes = await probeProjectRuntimes(project, opts, true);
220
227
  checks.push(...judgeRuntimes(project, runtimes));
221
228
  checks.push({ level: "info", subject: "login", message: "Login status is unknown: agent-lyceum does not read credentials, and the CLIs offer no read-only login check it can rely on." });
229
+ if (runtimesUsed(project, true).includes("cursor")) {
230
+ const env = opts.env ?? process.env;
231
+ const hasKey = !!(env.CURSOR_API_KEY ?? "").trim();
232
+ const hasAuth = hasCursorAuth(cursorConfigDir(env));
233
+ if (!hasKey && !hasAuth) {
234
+ checks.push({
235
+ level: "warn",
236
+ subject: "cursor",
237
+ message: "Cursor agents need `agent login` or CURSOR_API_KEY; neither CURSOR_API_KEY nor auth.json in the Cursor config dir was found.",
238
+ });
239
+ }
240
+ }
222
241
  return { project: project.name, ok: !checks.some((c) => c.level === "error"), checks, runtimes };
223
242
  }
224
243
  export function formatDoctor(r) {
package/dist/policy.js CHANGED
@@ -229,6 +229,15 @@ export function enforcementFor(project, agent) {
229
229
  if (!isLeadAgent && !os)
230
230
  notes.push("Without the OS sandbox Bash can write _shared; only the handoff index (_shared/MEMORY.md) is checked after each wake-up.");
231
231
  }
232
+ else if (agent.runtime === "cursor") {
233
+ // Permissions + `--sandbox enabled` are tool/CLI enforcement, not Claude/Codex OS per-path denies. Do not report "os"
234
+ // or `dispatcher.strict` / fallback parity will treat Cursor as OS-enforced.
235
+ const lvl = "tool-rules";
236
+ e = { memory: lvl, agentMd: lvl, otherContext: lvl, shared: isLeadAgent ? "n/a" : lvl, repoInstructions: "post-hoc" };
237
+ notes.push("Cursor uses --sandbox enabled and cli-config permissions (Write/WebFetch); this is not OS per-path enforcement. Single-file denies rely on permissions rules; CLAUDE.md/AGENTS.md changes are detected and reverted after each wake-up.");
238
+ if (agent.canEditAgentMd)
239
+ notes.push("can_edit_agent_md widens Cursor Write allow rules to whole agent directories.");
240
+ }
232
241
  else {
233
242
  const lvl = os ? "os" : "prompt-only";
234
243
  e = { memory: lvl, agentMd: lvl, otherContext: lvl, shared: isLeadAgent ? "n/a" : os ? "os" : "post-hoc", repoInstructions: "post-hoc" };
@@ -253,28 +262,19 @@ function sandboxNotes(agent, os) {
253
262
  const s = agent.sandbox;
254
263
  if (!s)
255
264
  return [];
256
- const claude = agent.runtime === "claude-code";
257
265
  const notes = [];
258
- if (!os) {
259
- notes.push(claude
260
- ? "no OS sandbox; sandbox.write changes Edit tool rules only; network/local_binding/unix_sockets have no effect."
261
- : "no OS sandbox; enforcement is prompt-only; sandbox allowances provide no OS enforcement.");
262
- }
266
+ const rt = agent.runtime === "claude-code" ? "claude" : agent.runtime === "cursor" ? "cursor" : "codex";
267
+ const T = SANDBOX_NOTE_TEXT[rt];
268
+ if (!os)
269
+ notes.push(T.noOs);
263
270
  if (s.network.length) {
264
- notes.push(`network: ${s.network.join(", ")} (${claude ? "claude-code: per-domain" : "codex: all hosts"})`);
265
- if (!claude)
266
- notes.push(`warn: sandbox.network is all-or-nothing on Codex: this agent may reach any host, not only ${s.network.join(", ")}.`);
267
- }
268
- if (s.localBinding) {
269
- notes.push(claude ? (process.platform === "darwin" ? "local_binding: on" : "local_binding: requested, no effect on this platform (macOS only)") : "local_binding: requested, not supported by codex");
270
- if (!claude)
271
- notes.push("warn: sandbox.local_binding has no Codex setting; whether a workspace-write sandbox lets it bind ports is unverified. sandbox.network turns on all network access, not only binding.");
272
- }
273
- if (s.unixSockets.length) {
274
- notes.push(`unix_sockets: ${s.unixSockets.map(canonicalPath).join(", ")} (${claude ? "applied" : "not applied by codex"})`);
275
- if (!claude)
276
- notes.push("warn: sandbox.unix_sockets has no per-socket Codex control; no setting emitted.");
271
+ const list = s.network.join(", ");
272
+ notes.push(...T.network(list));
277
273
  }
274
+ if (s.localBinding)
275
+ notes.push(...T.localBinding());
276
+ if (s.unixSockets.length)
277
+ notes.push(...T.unixSockets(s.unixSockets.map(canonicalPath).join(", ")));
278
278
  for (const [key, list] of [["write", s.write], ["unix_sockets", s.unixSockets]]) {
279
279
  list.forEach((p, i) => {
280
280
  if (!fs.existsSync(p))
@@ -283,6 +283,30 @@ function sandboxNotes(agent, os) {
283
283
  }
284
284
  return notes;
285
285
  }
286
+ /** Per-runtime wording of the sandbox doctor notes: a new runtime adds one entry instead of touching every line. */
287
+ const SANDBOX_NOTE_TEXT = {
288
+ claude: {
289
+ noOs: "no OS sandbox; sandbox.write changes Edit tool rules only; network/local_binding/unix_sockets have no effect.",
290
+ network: (list) => [`network: ${list} (claude-code: per-domain)`],
291
+ localBinding: () => [process.platform === "darwin" ? "local_binding: on" : "local_binding: requested, no effect on this platform (macOS only)"],
292
+ unixSockets: (list) => [`unix_sockets: ${list} (applied)`],
293
+ },
294
+ codex: {
295
+ noOs: "no OS sandbox; enforcement is prompt-only; sandbox allowances provide no OS enforcement.",
296
+ network: (list) => [`network: ${list} (codex: all hosts)`, `warn: sandbox.network is all-or-nothing on Codex: this agent may reach any host, not only ${list}.`],
297
+ localBinding: () => [
298
+ "local_binding: requested, not supported by codex",
299
+ "warn: sandbox.local_binding has no Codex setting; whether a workspace-write sandbox lets it bind ports is unverified. sandbox.network turns on all network access, not only binding.",
300
+ ],
301
+ unixSockets: (list) => [`unix_sockets: ${list} (not applied by codex)`, "warn: sandbox.unix_sockets has no per-socket Codex control; no setting emitted."],
302
+ },
303
+ cursor: {
304
+ noOs: "Cursor allowances still rely on cli-config permissions and --sandbox; network/local_binding/unix_sockets are not emitted.",
305
+ network: (list) => [`network: ${list} (not applied by cursor)`, `warn: sandbox.network has no Cursor setting; no setting emitted, so ${list} is not opened by agent-lyceum.`],
306
+ localBinding: () => ["local_binding: requested, not supported by cursor", "warn: sandbox.local_binding has no Cursor setting; no setting emitted."],
307
+ unixSockets: (list) => [`unix_sockets: ${list} (not applied by cursor)`, "warn: sandbox.unix_sockets has no per-socket Cursor control; no setting emitted."],
308
+ },
309
+ };
286
310
  /** Can `agent` legitimately change this protected file? */
287
311
  export function mayEditProtected(project, agent, file) {
288
312
  const pol = writePolicy(project, agent);
@@ -318,6 +342,9 @@ export function sandboxCaps(agent, runtime = agent.runtime) {
318
342
  unixSockets: s.unixSockets.length > 0,
319
343
  };
320
344
  }
345
+ // Cursor emits no network setting yet, so nothing is applied whatever was requested.
346
+ if (runtime === "cursor")
347
+ return none;
321
348
  return { ...none, network: s.network.length ? "all" : "none" };
322
349
  }
323
350
  /** Components in which `backup` applies more than `primary`, as `name: primary -> backup`. */
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 {};