owlmem 0.9.33 → 0.9.35

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 (2) hide show
  1. package/owlmem.mjs +125 -27
  2. package/package.json +1 -1
package/owlmem.mjs CHANGED
@@ -44,7 +44,7 @@ import { fileURLToPath } from "node:url";
44
44
  import { spawn, spawnSync } from "node:child_process";
45
45
  import { createConnection } from "node:net";
46
46
 
47
- export const VERSION = "0.9.33";
47
+ export const VERSION = "0.9.35";
48
48
  const BASE = (process.env.OWLMEM_URL || "https://owlmem.com").replace(/\/$/, "");
49
49
  const DIR = process.env.OWLMEM_HOME || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "owlmem");
50
50
  const enc = new TextEncoder(), dec = new TextDecoder();
@@ -521,6 +521,36 @@ async function mcpServe() {
521
521
  // only the session cwd from stdin (to name this project's handoff key) and ignores
522
522
  // anything else Claude Code sends there.
523
523
  export const SESSION_START_CONTEXT = "Before reading any code or files, search OwlMem with kb_find: it is the first step of every task. In Claude Code, load it first with ToolSearch select:mcp__owlmem__kb_find. Then read code, run commands, and save reusable findings with kb_write.";
524
+ // `owlmem hook context-meter` shows the measured context length after each reply, so the
525
+ // AI quotes a number instead of guessing one. It reads the hook JSON on stdin
526
+ // (hook_event_name, transcript_path) and takes the length from the last non-sidechain
527
+ // assistant usage in the transcript (input + cache read + cache creation). Stop prints
528
+ // {"systemMessage": line}; UserPromptSubmit prints additionalContext. Anything else
529
+ // prints nothing. Always offline, nothing on stderr, exit 0.
530
+ function contextMeterLine(payload) {
531
+ const p = payload?.transcript_path;
532
+ if (typeof p !== "string" || !p) return null;
533
+ let text;
534
+ try { text = readFileSync(p, "utf8"); } catch { return null; }
535
+ let tokens = null, over200k = false;
536
+ for (const line of text.split("\n")) {
537
+ let e;
538
+ try { e = JSON.parse(line); } catch { continue; } // junk lines are skipped
539
+ if (e?.type !== "assistant" || e?.isSidechain) continue; // subagents don't count
540
+ const u = e?.message?.usage;
541
+ if (!u) continue;
542
+ const sum = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
543
+ if (!sum) continue;
544
+ if (sum > 200000) over200k = true;
545
+ tokens = sum; // keep the last one
546
+ }
547
+ if (tokens === null) return null;
548
+ const window = over200k ? 1000000 : 200000;
549
+ const n = Math.round(tokens / 1000), pct = Math.round(tokens * 100 / window);
550
+ const icon = tokens < 80000 ? "🟢" : tokens < 150000 ? "🔵" : tokens < 180000 ? "🟡" : "🔴";
551
+ const advice = tokens < 80000 ? "Keep going." : tokens < 150000 ? "You may clear at the next task boundary." : tokens < 180000 ? "Consider clearing, even mid-task." : "Hand off and clear now.";
552
+ return `${icon} Context: ~${n}k tokens (${pct}% of the window): ${advice}`;
553
+ }
524
554
  // The project this session runs in: the folder name of the git repository the cwd sits in
525
555
  // (walk up to the first folder holding `.git`, a dir or a worktree's file), else the cwd's
526
556
  // own folder name. No git binary, no network: just the filesystem.
@@ -545,10 +575,28 @@ function hookStdinCwd() {
545
575
  catch { return null; }
546
576
  }
547
577
  function hookCmd(sub) {
548
- if (sub !== "session-start") throw new Fail("Usage: owlmem hook session-start");
549
- const key = `<your name>-handoff-${projectName(hookStdinCwd() || process.cwd())}`;
550
- const ctx = SESSION_START_CONTEXT + ` Handoff key for this project: \`${key}\` (kb_retain to save, kb_find to read; don't read another project's).`;
551
- console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: ctx } }));
578
+ if (sub === "session-start") {
579
+ const key = `<your name>-handoff-${projectName(hookStdinCwd() || process.cwd())}`;
580
+ const ctx = SESSION_START_CONTEXT + ` Handoff key for this project: \`${key}\` (kb_retain to save, kb_find to read; don't read another project's).`;
581
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: ctx } }));
582
+ return;
583
+ }
584
+ if (sub === "context-meter") {
585
+ // The hook JSON is on stdin; only read it when stdin isn't a terminal (a TTY would
586
+ // block). Anything unusable prints nothing and exits 0.
587
+ let payload = null;
588
+ if (!process.stdin.isTTY) {
589
+ try { payload = JSON.parse(readFileSync(0, "utf8") || "{}"); } catch {}
590
+ }
591
+ const event = payload?.hook_event_name;
592
+ if (event === "Stop" && payload?.stop_hook_active) return; // another hook already ran
593
+ const line = (event === "Stop" || event === "UserPromptSubmit") ? contextMeterLine(payload) : null;
594
+ if (!line) return;
595
+ if (event === "Stop") console.log(JSON.stringify({ systemMessage: line }));
596
+ else console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: line } }));
597
+ return;
598
+ }
599
+ throw new Fail("Usage: owlmem hook session-start|context-meter");
552
600
  }
553
601
 
554
602
  // ── install: connect the AI apps on this machine to OwlMem's MCP server ──
@@ -698,13 +746,24 @@ export function withRules(text, uninstall) {
698
746
  // network on every session start, and the npx cache can be cleaned out. install
699
747
  // copies this script there when it adds the hook; --uninstall removes only our
700
748
  // entry and leaves the copy (auto-wake runs it too).
701
- export function sessionStartCommand() {
702
- return `node ${join(wakeDir(), "owlmem.mjs")} hook session-start`;
749
+ export function sessionStartCommand(o = {}) {
750
+ // The script path is quoted: a user name with spaces would otherwise split it. On Windows the hook runs in
751
+ // Git Bash, so the path uses forward slashes there. o.dir is the config dir (the script lives in its wake/).
752
+ let p = join(o.dir ? join(o.dir, "wake") : wakeDir(), "owlmem.mjs");
753
+ if ((o.platform || platform()) === "win32") p = p.replace(/\\/g, "/");
754
+ return `node "${p}" hook session-start`;
703
755
  }
704
756
  function sessionStartFile() {
705
757
  return join(process.env.CLAUDE_CONFIG_DIR || join(home(), ".claude"), "settings.json");
706
758
  }
759
+ // The context meter (Stop + UserPromptSubmit): ~/.claude/settings.json gets entries that
760
+ // run `owlmem hook context-meter` after each reply and before each prompt, showing the
761
+ // measured context length. Same shape as the SessionStart hook, no matcher.
762
+ export function contextMeterCommand() {
763
+ return `node ${join(wakeDir(), "owlmem.mjs")} hook context-meter`;
764
+ }
707
765
  const isSessionStartOurs = (e) => (e?.hooks || []).some((h) => typeof h?.command === "string" && h.command.includes("owlmem") && h.command.includes("hook session-start"));
766
+ const isContextMeterOurs = (e) => (e?.hooks || []).some((h) => typeof h?.command === "string" && h.command.includes("owlmem") && h.command.includes("hook context-meter"));
708
767
  export function planSessionStartHook(uninstall) {
709
768
  const file = sessionStartFile();
710
769
  const text = readText(file);
@@ -715,15 +774,34 @@ export function planSessionStartHook(uninstall) {
715
774
  }
716
775
  if (obj.hooks !== undefined && (typeof obj.hooks !== "object" || Array.isArray(obj.hooks) || obj.hooks === null)) return null;
717
776
  const hooks = obj.hooks || {};
718
- if (hooks.SessionStart !== undefined && !Array.isArray(hooks.SessionStart)) return null;
719
- const list = hooks.SessionStart || [];
777
+ // The three hook events we manage: SessionStart (search first) and the context meter
778
+ // (Stop + UserPromptSubmit, showing the measured context length after each reply).
779
+ const events = [
780
+ { event: "SessionStart", ours: isSessionStartOurs, command: sessionStartCommand() },
781
+ { event: "Stop", ours: isContextMeterOurs, command: contextMeterCommand() },
782
+ { event: "UserPromptSubmit", ours: isContextMeterOurs, command: contextMeterCommand() },
783
+ ];
784
+ for (const { event } of events) {
785
+ if (hooks[event] !== undefined && !Array.isArray(hooks[event])) return null;
786
+ }
720
787
  if (uninstall) {
721
- if (!list.some(isSessionStartOurs)) return null;
722
- const next = { ...obj, hooks: { ...hooks, SessionStart: list.filter((e) => !isSessionStartOurs(e)) } };
788
+ if (!events.some(({ event, ours }) => (hooks[event] || []).some(ours))) return null;
789
+ const next = { ...obj, hooks: { ...hooks } };
790
+ for (const { event, ours } of events) {
791
+ if (hooks[event]) next.hooks[event] = hooks[event].filter((e) => !ours(e));
792
+ }
723
793
  return { file, text: JSON.stringify(next, null, 2) + "\n" };
724
794
  }
725
- if (list.some(isSessionStartOurs)) return null; // already installed
726
- const next = { ...obj, hooks: { ...hooks, SessionStart: [...list, { hooks: [{ type: "command", command: sessionStartCommand() }] }] } };
795
+ const next = { ...obj, hooks: { ...hooks } };
796
+ let changed = false;
797
+ for (const { event, ours, command } of events) {
798
+ const list = hooks[event] || [];
799
+ if (!list.some(ours)) {
800
+ next.hooks[event] = [...list, { hooks: [{ type: "command", command }] }];
801
+ changed = true;
802
+ }
803
+ }
804
+ if (!changed) return null; // already installed
727
805
  return { file, text: JSON.stringify(next, null, 2) + "\n" };
728
806
  }
729
807
 
@@ -795,7 +873,7 @@ function describe(r, done, uninstall) {
795
873
  for (const op of r.ops) {
796
874
  if (op.type === "run" && !done) lines.push(" run: " + op.argv.join(" "));
797
875
  if (op.rules) lines.push(` ${done ? "" : "will "}${uninstall ? (done ? "removed" : "remove") : (done ? "wrote" : "write")} the OwlMem rules block in ${tilde(op.file)}`);
798
- if (op.hook) lines.push(` ${done ? "" : "will "}${uninstall ? (done ? "removed" : "remove") : (done ? "added" : "add")} the SessionStart hook in ${tilde(op.file)}`);
876
+ if (op.hook) lines.push(` ${done ? "" : "will "}${uninstall ? (done ? "removed" : "remove") : (done ? "added" : "add")} the SessionStart and context-meter hooks in ${tilde(op.file)}`);
799
877
  }
800
878
  if (done && r.backups?.length) lines.push(" backup: " + r.backups.join(", "));
801
879
  return lines.join("\n");
@@ -2125,19 +2203,34 @@ async function claudeQuota(fetchImpl = fetch) {
2125
2203
  // the command line has only the port.
2126
2204
  // 11-21: also the desktop app's own language server (language_server_macos_arm etc. under Antigravity.app), which carries
2127
2205
  // --csrf_token and its ports on the command line; that's how a Mac without agy is found (fabric's Cirila.local).
2206
+ // The command lines of running processes, one per line (0.9.33, #4611). Windows has no ps: PowerShell reads
2207
+ // Win32_Process CommandLine instead. o.run(cmd, args) → { stdout } is injectable; tests never read the real
2208
+ // process list. A failing command → "" (never throws), the same as a computer with nothing running.
2209
+ export function agyProcesses(o = {}) {
2210
+ const run = o.run || ((cmd, args) => spawnSync(cmd, args, { encoding: "utf8", timeout: 10000 }));
2211
+ try {
2212
+ const r = (o.platform || process.platform) === "win32"
2213
+ ? run("powershell", ["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_Process | ForEach-Object { $_.CommandLine }"])
2214
+ : run("ps", ["-axww", "-o", "args="]);
2215
+ return !r || r.error ? "" : (r.stdout || "");
2216
+ } catch { return ""; }
2217
+ }
2128
2218
  // agyFind keeps only the ones that answer.
2129
2219
  export function agyServers(psOut, daemonDir = join(homedir(), ".gemini", "antigravity", "daemon")) {
2130
2220
  const out = [];
2131
2221
  const add = (port, token) => { port = Number(port); if (port > 0 && /^[\w-]{8,}$/.test(token || "") && !out.some((s) => s.port === port)) out.push({ port, token }); };
2132
- for (const l of String(psOut || "").split("\n")) {
2133
- const exe = l.trim().split(/\s/)[0] || "", tok = /--csrf_token[= ]([\w-]{8,})/.exec(l)?.[1];
2134
- if (/(^|\/)agy$/.test(exe)) {
2222
+ for (const raw of String(psOut || "").split("\n")) {
2223
+ // trim() also drops the \r of Windows CRLF output. The program may be a quoted Windows path, or an unquoted
2224
+ // one with spaces in it (C:\Users\Ann Lee\...), so classify by the program name wherever it sits in the
2225
+ // line, not by the first word.
2226
+ const l = raw.trim(), tok = /--csrf_token[= ]([\w-]{8,})/.exec(l)?.[1];
2227
+ if (/(?:^|[\s"\\/])agy(?:\.exe)?(?=[\s"]|$)/.test(l)) {
2135
2228
  const port = /--hub-port[= ](\d{2,5})\b/.exec(l);
2136
2229
  if (!port) continue;
2137
2230
  let token = tok;
2138
2231
  if (!token) { try { const d = JSON.parse(readFileSync(join(daemonDir, "hub_" + port[1] + ".json"), "utf8")); token = d?.csrfToken; } catch {} }
2139
2232
  add(port[1], token);
2140
- } else if (/(^|\/)language_server[\w.-]*$/.test(exe) && /antigravity/i.test(l) && tok) {
2233
+ } else if (/language_server[\w.-]*/.test(l) && /antigravity/i.test(l) && tok) {
2141
2234
  const before = out.length;
2142
2235
  for (const m of l.matchAll(/--(?:server_port|extension_server_port|http_server_port|lsp_port)[= ](\d{2,5})\b/g)) add(m[1], tok);
2143
2236
  // macOS app 2.33 (Cirila.local 11-21): no http port flag (only --https_server_port 0); the port is in its daemon file,
@@ -2155,6 +2248,12 @@ export function agyServers(psOut, daemonDir = join(homedir(), ".gemini", "antigr
2155
2248
  // its chat panel makes. Found and tested on ori 11-21 (a woken conversation answered OwlMem note #4114 in 26 s by itself).
2156
2249
  export function agyAppInstalled(o = {}) {
2157
2250
  const plat = o.platform || platform(), h = o.home || home(), exists = o.exists || existsSync;
2251
+ if (plat === "win32") {
2252
+ // %LOCALAPPDATA%\Programs\Antigravity\Antigravity.exe; joined with backslashes by hand — path.join on the
2253
+ // (possibly non-Windows) machine writing wake.json would use the wrong separator.
2254
+ const local = (o.env || process.env).LOCALAPPDATA || (h + "\\AppData\\Local");
2255
+ return exists(local + "\\Programs\\Antigravity\\Antigravity.exe");
2256
+ }
2158
2257
  if (plat !== "darwin") return false;
2159
2258
  return ["/Applications/Antigravity.app", join(h, "Applications", "Antigravity.app")].some((p) => exists(p));
2160
2259
  }
@@ -2192,11 +2291,11 @@ export function agyCall(s, fetchImpl = fetch) {
2192
2291
  return j || {};
2193
2292
  };
2194
2293
  }
2195
- // The first running app / agy hub that answers.
2196
- export async function agyFind(fetchImpl = fetch) {
2197
- if (process.platform === "win32") return null;
2198
- const ps = spawnSync("ps", ["-axww", "-o", "args="], { encoding: "utf8", timeout: 10000 });
2199
- for (const s of agyServers(ps.stdout)) { try { if ((await agyCall(s, fetchImpl)("GetUserStatus"))?.userStatus) return s; } catch {} }
2294
+ // The first running app / agy hub that answers. o.ps injects the process list; otherwise agyProcesses(o)
2295
+ // reads it (PowerShell on Windows, ps elsewhere), so Windows finds the app the same way (0.9.33, #4611).
2296
+ export async function agyFind(fetchImpl = fetch, o = {}) {
2297
+ const ps = o.ps !== undefined ? o.ps : agyProcesses(o);
2298
+ for (const s of agyServers(ps)) { try { if ((await agyCall(s, fetchImpl)("GetUserStatus"))?.userStatus) return s; } catch {} }
2200
2299
  return null;
2201
2300
  }
2202
2301
  const AGY_IDLE = "CASCADE_RUN_STATUS_IDLE";
@@ -2266,14 +2365,13 @@ export function agySummaryWindows(j) {
2266
2365
  }
2267
2366
  return Object.values(by).sort((a, b) => a.minutes - b.minutes).slice(0, 4);
2268
2367
  }
2269
- async function antigravityQuota(fetchImpl = fetch) {
2270
- if (process.platform === "win32") return null;
2271
- const ps = spawnSync("ps", ["-axww", "-o", "args="], { encoding: "utf8", timeout: 10000 });
2368
+ export async function antigravityQuota(fetchImpl = fetch, o = {}) {
2369
+ const ps = o.ps !== undefined ? o.ps : agyProcesses(o);
2272
2370
  const ask = (s, method) => fetchImpl("http://127.0.0.1:" + s.port + "/exa.language_server_pb.LanguageServerService/" + method,
2273
2371
  { method: "POST", headers: { "Content-Type": "application/json", "Connect-Protocol-Version": "1", "X-Codeium-Csrf-Token": s.token },
2274
2372
  body: JSON.stringify(method === "GetUserStatus" ? { metadata: { ideName: "antigravity" } } : {}), signal: AbortSignal.timeout(10000) })
2275
2373
  .then((r) => (r.ok ? r.json() : null));
2276
- for (const s of agyServers(ps.stdout)) {
2374
+ for (const s of agyServers(ps)) {
2277
2375
  try { const w = agySummaryWindows(await ask(s, "RetrieveUserQuotaSummary")); if (w.length) return w; } catch {}
2278
2376
  try { const w = agyWindows(await ask(s, "GetUserStatus")); if (w.length) return w; } catch {} // older apps without the summary
2279
2377
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owlmem",
3
- "version": "0.9.33",
3
+ "version": "0.9.35",
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" },