owlmem 0.9.22 → 0.9.24

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.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/owlmem.mjs +292 -3
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -60,6 +60,7 @@ npx -y owlmem wake disable # also done by npx -y owlmem uninstall
60
60
  the computer. When the computer is removed, the AI is disconnected or the account is gone, the program gets a 401,
61
61
  removes its own autostart entry and exits. The command for each app is in `~/.config/owlmem/wake/wake.json`;
62
62
  logs and worktrees stay in that folder after uninstalling.
63
+ - **Plan usage.** The waker also reports each app's plan usage to OwlMem. Cursor:自动报套餐用量。
63
64
 
64
65
  ## Vault
65
66
 
package/owlmem.mjs CHANGED
@@ -42,8 +42,9 @@ import { homedir, hostname, userInfo } from "node:os";
42
42
  import { join, dirname, basename, relative, isAbsolute } from "node:path";
43
43
  import { fileURLToPath } from "node:url";
44
44
  import { spawn, spawnSync } from "node:child_process";
45
+ import { createConnection } from "node:net";
45
46
 
46
- export const VERSION = "0.9.22";
47
+ export const VERSION = "0.9.24";
47
48
  const BASE = (process.env.OWLMEM_URL || "https://owlmem.com").replace(/\/$/, "");
48
49
  const DIR = process.env.OWLMEM_HOME || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "owlmem");
49
50
  const enc = new TextEncoder(), dec = new TextDecoder();
@@ -845,8 +846,12 @@ export const WAKE_CLIENTS = {
845
846
  // closes stdin. Full: --auto; limited: file edits, shell and web fetches denied through OPENCODE_CONFIG_CONTENT (wakeEnv).
846
847
  // Tested 11-03 against a local OwlMem with opencode 1.19.5: full did the task; limited refused a shell command and declined.
847
848
  opencode: { name: "opencode", bin: "opencode", command: ["opencode", "run"], prompt: "arg", home: [[".opencode", "bin", "opencode"]] },
849
+ // Cursor: quota-only (0.9.24) — no headless command to run a task, only its plan usage is reported. The waker
850
+ // never starts it; the server never sends it a task (hub/wake.py QUOTA_ONLY). `wake enable` offers it when
851
+ // Cursor's own state database exists on this computer.
852
+ cursor: { name: "Cursor", quotaOnly: true },
848
853
  };
849
- export const WAKE_APP_IDS = ["claude-code", "codex", "antigravity", "hermes", "dsh", "opencode", "gemini", "custom"];
854
+ export const WAKE_APP_IDS = ["claude-code", "codex", "antigravity", "hermes", "dsh", "opencode", "gemini", "custom", "cursor"];
850
855
  // Where an app's command is: on PATH, or the first of its default install places that exists (path parts under your home
851
856
  // folder, or an absolute path), used by full path
852
857
  export function wakeBin(c, home_ = home(), exists = existsSync, path = onPath) {
@@ -1307,9 +1312,224 @@ const OUTSIDE_FULL_NOTE = `This came from outside the team (an alert source, the
1307
1312
  // only the wording is about the outside case).
1308
1313
  const limitedNote = (task) => (task.trust === TRUST_FULL ? (task.external ? OUTSIDE_FULL_NOTE : "") : EXTERNAL_NOTE);
1309
1314
 
1315
+ // ── foreground delivery (#1809/#1815): hand the job to a live foreground session first ──
1316
+ // When the wake program has a job for an AI, it first tries that AI's configured foreground delivery
1317
+ // methods, in order; the first method that succeeds counts as delivered and no headless session is
1318
+ // started. Only when every configured method fails does it fall back to starting a headless session
1319
+ // as before (and the failure is logged, one line in wake.log). Only full-trust jobs go to the
1320
+ // foreground: a job from outside the team is never relayed into a session that can do more than look
1321
+ // (same boundary as the in-prompt relay in foregroundFirst below).
1322
+ //
1323
+ // Two methods, both generic (not tied to any one CLI):
1324
+ // - {type: "claude-socket"}: deliver into the newest live Claude Code session on this machine, over
1325
+ // its cross-session-messaging socket (Claude Code 2.1.224+; the socket file name is the pid).
1326
+ // Implemented from Anthropic's public docs (code.claude.com/docs/en/cross-session-messaging) and
1327
+ // the socket protocol as shipped in Claude Code 2.1.325: each session registers in
1328
+ // ~/.claude/sessions/<pid>.json (messagingSocketPath) and takes newline-delimited JSON on its
1329
+ // socket — an optional {"type":"auth","token":"<peerToken>"} first line (the token lives in
1330
+ // ~/.claude/sessions/<pid>.<sha256(socket path)>.key), then one {"msgV":1,"msg_id":...,
1331
+ // "type":"user","message":{"role":"user","content":"<cross-session-message ...>...</cross-session-message>"},
1332
+ // "priority":"next"} line. The reference implementation (vpn-vps configs/ori/owlmem-fg-wake.py)
1333
+ // was not reachable from the machine this was built on, so this is a from-docs reimplementation;
1334
+ // live delivery on ori is still to be verified. A socket accept is "delivered" as far as this
1335
+ // program can tell: the session may still hold the message for approval when its
1336
+ // crossSessionInbound is not "accept" (see the docs). There is no SessionStart-hook registration
1337
+ // (#1809's original design): nothing is written when a session starts, sessions are found by
1338
+ // reading the registry Claude Code itself keeps. The registry directory is injectable
1339
+ // (OWLMEM_CLAUDE_SESSIONS_DIR, or CLAUDE_CONFIG_DIR); under the test suite the default is
1340
+ // refused, so tests can only ever read a directory they injected themselves (#1863).
1341
+ // - {type: "command", command: "..."}: run an arbitrary command (through the system shell) with the
1342
+ // wake note on stdin; exit code 0 means delivered, anything else means failed (try the next method).
1343
+ // Configuration lives in wake.json, per client: clients.<id>.foreground is an ordered list of methods.
1344
+ // Defaults: claude-code gets [{type: "claude-socket"}], every other client gets none (headless as
1345
+ // today). An explicit empty list turns foreground delivery off for that client.
1346
+ export const FOREGROUND_SOCKET_TIMEOUT_MS = 5000;
1347
+ export const FOREGROUND_COMMAND_TIMEOUT_MS = 30000;
1348
+ function validForegroundMethod(m) {
1349
+ if (!m || typeof m !== "object" || Array.isArray(m)) return false;
1350
+ if (m.type === "claude-socket") return true;
1351
+ if (m.type === "command" && typeof m.command === "string" && m.command.trim()) return true;
1352
+ return false;
1353
+ }
1354
+ export function foregroundMethods(client, cfg = {}) {
1355
+ const entry = ((cfg.clients || {})[client] || {}).foreground;
1356
+ if (Array.isArray(entry)) return entry.filter(validForegroundMethod);
1357
+ if (client === "claude-code") return [{ type: "claude-socket" }];
1358
+ return [];
1359
+ }
1360
+
1361
+ // Short wake note for a foreground session: what arrived, and to read it with kb_inbox (that marks it
1362
+ // read). Not the full payload — the session reads the rest itself.
1363
+ export function foregroundNote(task, o = {}) {
1364
+ const mins = o.timeout_min || WAKE_DEFAULTS.timeout_min;
1365
+ if (isReply(task)) {
1366
+ const done = task.result === "done";
1367
+ if (task.zh) return `奥麦自动唤醒:回信 #${task.id}——你派的任务 #${task.task_id}「${task.task_title || ""}」有了结果:${shortName(task.by)}${done ? "完成" : "拒绝"}了。用 kb_inbox 看这封回信(会标成已读);需要接着做(换人派、把结果告诉站长、自己补做)就做,没有要做的就结束,不要发消息。`;
1368
+ return `OwlMem auto-wake: reply #${task.id} — the task you gave out, #${task.task_id} "${task.task_title || ""}", was ${done ? "finished" : "declined"} by ${shortName(task.by)}. Read it with kb_inbox (that marks it read); if something needs doing next, do it, otherwise just end and don't send any message.`;
1369
+ }
1370
+ if (isNote(task)) {
1371
+ if (task.zh) return `奥麦自动唤醒:留言 #${task.id}——${shortName(task.from)}:${task.title}。用 kb_inbox 看这条留言(会标成已读);要你做事就做完、用 kb_send 回结果,不用做就结束,不要发消息。`;
1372
+ return `OwlMem auto-wake: note #${task.id} from ${shortName(task.from)}: ${task.title}. Read it with kb_inbox (that marks it read); if it asks you to do something, do it and report back with kb_send, otherwise just end and don't send a message.`;
1373
+ }
1374
+ if (task.zh) return `奥麦自动唤醒:任务 #${task.id}「${task.title}」等你处理(${shortName(task.from)}派来)。用 kb_task_update 接(doing),做完标 done、做不了标 declined,结果写进 note。你有 ${mins} 分钟。`;
1375
+ return `OwlMem auto-wake: task #${task.id} "${task.title}" is waiting for you (from ${shortName(task.from)}). Take it with kb_task_update (doing), mark it done when finished or declined if you can't, with the result in the note. You have ${mins} minutes.`;
1376
+ }
1377
+
1378
+ // Claude Code sessions on this machine, most recently active first: ~/.claude/sessions/<pid>.json
1379
+ // carries messagingSocketPath (and updatedAt). A record whose pid is gone, or whose socket is gone,
1380
+ // is stale and skipped. The directory is injectable: OWLMEM_CLAUDE_SESSIONS_DIR wins, then
1381
+ // CLAUDE_CONFIG_DIR (its sessions/ subdir), then <home>/.claude/sessions. home_ is injectable for
1382
+ // tests. Under the test suite (OWLMEM_TEST, set by cli/owlmem.test.mjs, or NODE_ENV=test) the
1383
+ // default is refused and null is returned: without an injected directory there is no registry to
1384
+ // read, so a test can never reach a real session by accident (#1863 — a test once delivered a fake
1385
+ // wake note into a live session on ori because an old runTask test called without home/sessionsDir).
1386
+ export function claudeSessionsDir(home_ = home()) {
1387
+ if (process.env.OWLMEM_CLAUDE_SESSIONS_DIR) return process.env.OWLMEM_CLAUDE_SESSIONS_DIR;
1388
+ if (process.env.CLAUDE_CONFIG_DIR) return join(process.env.CLAUDE_CONFIG_DIR, "sessions");
1389
+ if (process.env.OWLMEM_TEST || process.env.NODE_ENV === "test") return null;
1390
+ return join(home_, ".claude", "sessions");
1391
+ }
1392
+ const alivePid = (pid, o = {}) => {
1393
+ if (o.alive) return o.alive(pid);
1394
+ try { process.kill(pid, 0); return true; }
1395
+ catch (e) { return e?.code === "EPERM"; } // exists, but not ours
1396
+ };
1397
+ export function listClaudeSessions(o = {}) {
1398
+ const dir = o.sessionsDir || claudeSessionsDir(o.home);
1399
+ if (!dir) return []; // test suite without an injected directory: no registry, never the real one
1400
+ let names;
1401
+ try { names = readdirSync(dir); } catch { return []; }
1402
+ const out = [];
1403
+ for (const name of names) {
1404
+ if (!/^\d+\.json$/.test(name)) continue;
1405
+ let rec;
1406
+ try { rec = JSON.parse(readFileSync(join(dir, name), "utf8")); } catch { continue; }
1407
+ const sock = typeof rec.messagingSocketPath === "string" ? rec.messagingSocketPath : "";
1408
+ if (!sock || !existsSync(sock)) continue;
1409
+ const pid = Number(name.slice(0, -5));
1410
+ if (!pid || !alivePid(pid, o)) continue;
1411
+ let mtime = 0;
1412
+ try { mtime = statSync(sock).mtimeMs; } catch {}
1413
+ out.push({ pid, sock, name: typeof rec.name === "string" ? rec.name : "", updatedAt: Number(rec.updatedAt) || 0, mtime });
1414
+ }
1415
+ out.sort((a, b) => (b.updatedAt - a.updatedAt) || (b.mtime - a.mtime) || (b.pid - a.pid));
1416
+ return out;
1417
+ }
1418
+
1419
+ // The session's peer token: ~/.claude/sessions/<pid>.<sha256(canonical socket path)>.key,
1420
+ // JSON {peerToken: "<32 hex>"}. Without it the message still arrives on Linux, but a session in
1421
+ // bypass-permissions mode holds it for approval instead of delivering it — so send it when present.
1422
+ export function claudeSocketToken(sock, o = {}) {
1423
+ const dir = o.sessionsDir || claudeSessionsDir(o.home);
1424
+ if (!dir) return null; // test suite without an injected directory: no registry, never the real one
1425
+ let canon = sock;
1426
+ try { canon = realpathSync(sock); } catch {}
1427
+ const hash = createHash("sha256").update(canon).digest("hex");
1428
+ let names;
1429
+ try { names = readdirSync(dir); } catch { return null; }
1430
+ const pid = basename(sock).replace(/\.sock$/, "");
1431
+ const cands = names.filter((n) => n.endsWith("." + hash + ".key"))
1432
+ .sort((a, b) => (b.startsWith(pid + ".") ? 1 : 0) - (a.startsWith(pid + ".") ? 1 : 0)); // the session's own key first
1433
+ for (const n of cands) {
1434
+ try {
1435
+ const tok = JSON.parse(readFileSync(join(dir, n), "utf8")).peerToken;
1436
+ if (typeof tok === "string" && /^[0-9a-f]{32}$/.test(tok)) return tok;
1437
+ } catch {}
1438
+ }
1439
+ return null;
1440
+ }
1441
+
1442
+ // Escape the one tag the receiving session parses, so job text can't forge a cross-session wrapper.
1443
+ const escapeCrossSession = (s) => String(s).replace(/<\/?cross-session-message/g, (m) => "<\\" + m.slice(1));
1444
+ export function claudeSocketFrame(text, o = {}) {
1445
+ const name = String(o.fromName || "owlmem-wake").replace(/["<>\n\r]/g, "");
1446
+ const content = `<cross-session-message${name ? ` from-name="${name}"` : ""}>\n${escapeCrossSession(text)}\n</cross-session-message>`;
1447
+ return { msgV: 1, msg_id: crypto.randomUUID(), type: "user", message: { role: "user", content }, priority: "next" };
1448
+ }
1449
+
1450
+ // One JSON-lines message into a Claude Code inbox socket: optional auth line, then the message line,
1451
+ // then half-close; the session closes the connection once it took the lines. "Delivered" here means
1452
+ // the socket took it — a held message (crossSessionInbound is not "accept") is still reported sent.
1453
+ export async function sendClaudeSocket(sock, text, o = {}) {
1454
+ const token = o.token !== undefined ? o.token : claudeSocketToken(sock, o);
1455
+ const frame = claudeSocketFrame(text, o);
1456
+ const lines = (token ? JSON.stringify({ type: "auth", token }) + "\n" : "") + JSON.stringify(frame) + "\n";
1457
+ const timeoutMs = o.timeoutMs ?? FOREGROUND_SOCKET_TIMEOUT_MS;
1458
+ return new Promise((res) => {
1459
+ let done = false;
1460
+ const finish = (r) => { if (!done) { done = true; res(r); } };
1461
+ let s;
1462
+ try { s = createConnection({ path: sock }); } catch (e) { finish({ ok: false, detail: e.message }); return; }
1463
+ const timer = setTimeout(() => { try { s.destroy(); } catch {} finish({ ok: false, detail: "timed out after " + timeoutMs + " ms" }); }, timeoutMs);
1464
+ timer.unref?.();
1465
+ s.on("error", (e) => { clearTimeout(timer); finish({ ok: false, detail: (e.code === "ENOENT" || e.code === "ECONNREFUSED") ? "no session at " + sock + " (" + e.code + ")" : e.message }); });
1466
+ s.on("close", () => { clearTimeout(timer); finish({ ok: true }); });
1467
+ s.on("connect", () => { s.end(lines); });
1468
+ });
1469
+ }
1470
+
1471
+ // claude-socket: newest live session first, then the next if that socket won't take it.
1472
+ export async function deliverClaudeSocket(note, o = {}) {
1473
+ const sessions = listClaudeSessions(o);
1474
+ if (!sessions.length) return { ok: false, detail: "no live Claude Code session on this computer" };
1475
+ const tried = [];
1476
+ for (const s of sessions) {
1477
+ const r = await sendClaudeSocket(s.sock, note, o);
1478
+ if (r.ok) return { ok: true, detail: "Claude Code session " + (s.name || s.pid) };
1479
+ tried.push((s.name || s.pid) + ": " + r.detail);
1480
+ }
1481
+ return { ok: false, detail: tried.join("; ") };
1482
+ }
1483
+
1484
+ // command: the configured command runs through the system shell with the note on stdin; exit 0 = delivered.
1485
+ export async function runForegroundCommand(method, text, o = {}) {
1486
+ const timeoutMs = o.timeoutMs ?? FOREGROUND_COMMAND_TIMEOUT_MS;
1487
+ const win = (o.platform || platform()) === "win32";
1488
+ return new Promise((res) => {
1489
+ let done = false;
1490
+ const finish = (r) => { if (!done) { done = true; res(r); } };
1491
+ let ch;
1492
+ try { ch = spawn(method.command, { shell: true, stdio: ["pipe", "ignore", "ignore"], windowsHide: true, detached: !win }); }
1493
+ catch (e) { finish({ ok: false, detail: "couldn't start: " + e.message }); return; }
1494
+ // Timeout kills the whole process group, not just the shell: a command that spawned a child
1495
+ // must not outlive the timeout and deliver late — the timeout already moved on to the next
1496
+ // method / headless, so a late delivery would deliver twice (#1870). Windows: taskkill /T
1497
+ // takes the tree. Same kill as the headless session in runTask below.
1498
+ const kill = (sig) => { try { if (win) spawnSync("taskkill", ["/T", "/F", "/PID", String(ch.pid)]); else process.kill(-ch.pid, sig); } catch { try { ch.kill(sig); } catch {} } };
1499
+ const timer = setTimeout(() => { kill("SIGKILL"); finish({ ok: false, detail: "timed out after " + timeoutMs + " ms" }); }, timeoutMs);
1500
+ timer.unref?.();
1501
+ ch.on("error", (e) => { clearTimeout(timer); finish({ ok: false, detail: e.message }); });
1502
+ ch.on("close", (code) => { clearTimeout(timer); finish(code === 0 ? { ok: true } : { ok: false, detail: "exit code " + (code ?? "signal") }); });
1503
+ ch.stdin.on("error", () => {});
1504
+ ch.stdin.end(text);
1505
+ });
1506
+ }
1507
+
1508
+ // Try the configured foreground methods in order; the first success counts as delivered.
1509
+ export async function deliverForeground(task, cfg, o = {}) {
1510
+ const note = o.note ?? foregroundNote(task, { timeout_min: cfg.timeout_min });
1511
+ const tried = [];
1512
+ for (const m of foregroundMethods(task.client, cfg)) {
1513
+ const r = m.type === "claude-socket" ? await deliverClaudeSocket(note, o) : await runForegroundCommand(m, note, o);
1514
+ if (r.ok) return { ok: true, method: m.type, detail: r.detail || "" };
1515
+ tried.push(m.type + ": " + (r.detail || "failed"));
1516
+ }
1517
+ return { ok: false, detail: tried.join("; ") || "no foreground method configured" };
1518
+ }
1519
+
1310
1520
  // ── running a task ──
1311
1521
  export async function runTask(task, cfg, o = {}) {
1312
1522
  const dir = o.dir || DIR, cl = (cfg.clients || {})[task.client];
1523
+ const log = o.log || (() => {});
1524
+ if (task.trust === TRUST_FULL) { // full trust only: outside work is never relayed into a foreground session
1525
+ const methods = foregroundMethods(task.client, cfg);
1526
+ if (task.foreground_tried) log("Foreground delivery was already tried for " + jobLabel(task) + "; starting a headless session."); // #1870:前台送过一次没接,这次直接无头
1527
+ else if (methods.length) {
1528
+ const d = await deliverForeground(task, cfg, o);
1529
+ if (d.ok) return { outcome: "foreground", detail: "delivered to the foreground (" + d.method + (d.detail ? ": " + d.detail : "") + ")" };
1530
+ log("Foreground delivery failed for " + jobLabel(task) + " (" + d.detail + "); starting a headless session.");
1531
+ }
1532
+ }
1313
1533
  if (!cl || !Array.isArray(cl.command) || !cl.command.length) return { outcome: "error", detail: "no command for " + task.client + " on this computer (wake.json)" };
1314
1534
  let place;
1315
1535
  try { const plan = o.plan || planWorkdir(task, o.home || home(), o.git); place = prepareWorkdir(task, plan, dir, o.git); if (plan.kind === "scratch") place.scratch = true; }
@@ -1760,6 +1980,67 @@ async function dshBalance(fetchImpl = fetch, home = homedir()) {
1760
1980
  if (!r.ok) return null;
1761
1981
  return dshBalanceFrom(await r.json());
1762
1982
  }
1983
+ // Cursor's plan usage (0.9.24, owner 11-17): Cursor's own dashboard (cursor.com) has a usage summary;
1984
+ // the sign-in lives in Cursor's own state database (state.vscdb, ItemTable key cursorAuth/accessToken).
1985
+ // The token is only sent to cursor.com and never leaves this computer otherwise; OwlMem gets the
1986
+ // percentages and reset times. No database / no sqlite / expired sign-in: no quota this round.
1987
+ export function cursorStateDb(home_ = home(), platform_ = process.platform, env = process.env) {
1988
+ if (platform_ === "darwin") return join(home_, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb");
1989
+ if (platform_ === "win32") return join(env.APPDATA || join(home_, "AppData", "Roaming"), "Cursor", "User", "globalStorage", "state.vscdb");
1990
+ return join(home_, ".config", "Cursor", "User", "globalStorage", "state.vscdb");
1991
+ }
1992
+ export function cursorSession(jwt) {
1993
+ // the cookie value cursor.com's own dashboard sends: "<user id>%3A%3A<jwt>", user id = the part of
1994
+ // the token's "sub" claim after the last "|". Anything that isn't a JWT with a sub: null.
1995
+ if (typeof jwt !== "string") return null;
1996
+ const parts = jwt.split(".");
1997
+ if (parts.length !== 3) return null;
1998
+ let payload;
1999
+ try { payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")); } catch { return null; }
2000
+ const sub = payload?.sub;
2001
+ if (typeof sub !== "string" || !sub) return null;
2002
+ return sub.split("|").pop() + "%3A%3A" + jwt;
2003
+ }
2004
+ export function cursorWindows(j) {
2005
+ if (j?.isUnlimited) return [];
2006
+ const start = Date.parse(j?.billingCycleStart), end = Date.parse(j?.billingCycleEnd);
2007
+ const used = j?.individualUsage?.plan?.totalPercentUsed;
2008
+ if (isNaN(start) || isNaN(end) || end <= start || typeof used !== "number") return [];
2009
+ return [{ minutes: Math.round((end - start) / 60000), used_percent: used, resets_at: Math.floor(end / 1000) }];
2010
+ }
2011
+ // The stored value is the token itself, or JSON holding it ({"accessToken": ...}); VS Code-style
2012
+ // databases sometimes double-encode it. Anything else: not a token.
2013
+ export function cursorTokenFromValue(v) {
2014
+ let x = v;
2015
+ for (let i = 0; i < 2 && typeof x === "string"; i++) { try { x = JSON.parse(x); } catch { break; } }
2016
+ if (typeof x === "string") return x || null;
2017
+ if (x && typeof x.accessToken === "string" && x.accessToken) return x.accessToken;
2018
+ return null;
2019
+ }
2020
+ async function cursorToken(db = cursorStateDb()) {
2021
+ if (!existsSync(db)) return null; // never create the file: the sqlite3 CLI would make an empty one
2022
+ let raw = null;
2023
+ try {
2024
+ const { DatabaseSync } = await import("node:sqlite");
2025
+ const d = new DatabaseSync(db, { readOnly: true });
2026
+ try { raw = d.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken")?.value ?? null; }
2027
+ finally { d.close(); }
2028
+ } catch {}
2029
+ if (raw == null) {
2030
+ const r = spawnSync("sqlite3", [db, "SELECT value FROM ItemTable WHERE key='cursorAuth/accessToken';"], { encoding: "utf8", timeout: 10000 });
2031
+ if (r.status === 0 && r.stdout.trim()) raw = r.stdout.replace(/\n$/, "");
2032
+ }
2033
+ return cursorTokenFromValue(raw);
2034
+ }
2035
+ async function cursorQuota(fetchImpl = fetch) {
2036
+ const tok = await cursorToken().catch(() => null);
2037
+ const session = tok ? cursorSession(tok) : null;
2038
+ if (!session) return null;
2039
+ const r = await fetchImpl("https://cursor.com/api/usage-summary", { headers: { Cookie: "WorkosCursorSessionToken=" + session, "User-Agent": "owlmem-cli/" + VERSION }, signal: AbortSignal.timeout(15000) });
2040
+ if (!r.ok) return null;
2041
+ const w = cursorWindows(await r.json());
2042
+ return w.length ? w : null;
2043
+ }
1763
2044
  async function usageTick(cfg, api, log, dir = DIR) {
1764
2045
  const file = join(wakeDir(dir), "usage.json");
1765
2046
  let state = {}; try { state = JSON.parse(readFileSync(file, "utf8")); } catch {}
@@ -1779,6 +2060,13 @@ async function usageTick(cfg, api, log, dir = DIR) {
1779
2060
  if (r.status !== 200 && r.status !== 404) log("usage: OwlMem answered " + (r.data?.detail || "HTTP " + r.status));
1780
2061
  }
1781
2062
  }
2063
+ if (cfg.clients?.cursor) { // no transcripts to count here either, only its plan usage
2064
+ const w = await cursorQuota().catch(() => null);
2065
+ if (w) {
2066
+ const r = await api("usage", { days: {}, status: { cursor: { windows: w, limit_at: Math.floor(Date.now() / 1000) } } });
2067
+ if (r.status !== 200 && r.status !== 404) log("usage: OwlMem answered " + (r.data?.detail || "HTTP " + r.status));
2068
+ }
2069
+ }
1782
2070
  if (!clients.length) return;
1783
2071
  scanUsage(state, Object.fromEntries(Object.entries(usageRoots()).filter(([c]) => clients.includes(c))));
1784
2072
  try { writeFileSync(file + ".tmp", JSON.stringify(state)); renameSync(file + ".tmp", file); } catch (e) { log("usage: " + e.message); }
@@ -1808,7 +2096,7 @@ async function wakeRun() {
1808
2096
  await new Promise((ok) => setTimeout(ok, 5000 * (i + 1)));
1809
2097
  }
1810
2098
  };
1811
- const sched = new Scheduler({ max: cfg.max_parallel || WAKE_DEFAULTS.max_parallel, start: (j) => runTask(j.task, cfg, { plan: j.plan }), onDone: (j, res) => { report(j, res); } });
2099
+ const sched = new Scheduler({ max: cfg.max_parallel || WAKE_DEFAULTS.max_parallel, start: (j) => runTask(j.task, cfg, { plan: j.plan, log }), onDone: (j, res) => { report(j, res); } });
1812
2100
  log("OwlMem auto-wake " + VERSION + " running on " + (cfg.machine || hostname()) + ".");
1813
2101
  const usage = () => usageTick(cfg, api, log).catch((e) => log("usage: " + e.message));
1814
2102
  setTimeout(usage, 30000).unref(); setInterval(usage, USAGE_EVERY).unref();
@@ -1838,6 +2126,7 @@ async function wakeEnable(args = []) {
1838
2126
  const bin = !clients[id] && wakeBin(c);
1839
2127
  if (bin) clients[id] = { command: [bin, ...c.command.slice(1)], prompt: c.prompt };
1840
2128
  }
2129
+ if (!clients.cursor && existsSync(cursorStateDb())) clients.cursor = {}; // Cursor: quota-only — no command to run, only its plan usage is reported
1841
2130
  if (!Object.keys(clients).length) {
1842
2131
  const told = await wakeNoClients(wakeApi()).catch(() => false);
1843
2132
  throw new Fail("No AI command line found on this computer that auto-wake can start (Claude Code: claude, Codex: codex, Antigravity: agy, Hermes: hermes, DeepSeek Harness: dsh). Install one, or add its command to " + wakeFile() + " under \"clients\"." +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owlmem",
3
- "version": "0.9.22",
3
+ "version": "0.9.24",
4
4
  "description": "OwlMem command line: connect your AI apps to OwlMem in one command (npx -y owlmem install), an end-to-end encrypted vault for your AI agents, and a local MCP server.",
5
5
  "type": "module",
6
6
  "bin": { "owlmem": "owlmem.mjs" },