owlmem 0.9.34 → 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 +86 -12
  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.34";
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 ──
@@ -708,7 +756,14 @@ export function sessionStartCommand(o = {}) {
708
756
  function sessionStartFile() {
709
757
  return join(process.env.CLAUDE_CONFIG_DIR || join(home(), ".claude"), "settings.json");
710
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
+ }
711
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"));
712
767
  export function planSessionStartHook(uninstall) {
713
768
  const file = sessionStartFile();
714
769
  const text = readText(file);
@@ -719,15 +774,34 @@ export function planSessionStartHook(uninstall) {
719
774
  }
720
775
  if (obj.hooks !== undefined && (typeof obj.hooks !== "object" || Array.isArray(obj.hooks) || obj.hooks === null)) return null;
721
776
  const hooks = obj.hooks || {};
722
- if (hooks.SessionStart !== undefined && !Array.isArray(hooks.SessionStart)) return null;
723
- 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
+ }
724
787
  if (uninstall) {
725
- if (!list.some(isSessionStartOurs)) return null;
726
- 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
+ }
727
793
  return { file, text: JSON.stringify(next, null, 2) + "\n" };
728
794
  }
729
- if (list.some(isSessionStartOurs)) return null; // already installed
730
- 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
731
805
  return { file, text: JSON.stringify(next, null, 2) + "\n" };
732
806
  }
733
807
 
@@ -799,7 +873,7 @@ function describe(r, done, uninstall) {
799
873
  for (const op of r.ops) {
800
874
  if (op.type === "run" && !done) lines.push(" run: " + op.argv.join(" "));
801
875
  if (op.rules) lines.push(` ${done ? "" : "will "}${uninstall ? (done ? "removed" : "remove") : (done ? "wrote" : "write")} the OwlMem rules block in ${tilde(op.file)}`);
802
- 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)}`);
803
877
  }
804
878
  if (done && r.backups?.length) lines.push(" backup: " + r.backups.join(", "));
805
879
  return lines.join("\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owlmem",
3
- "version": "0.9.34",
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" },