owlmem 0.9.34 → 0.9.36

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 +157 -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.36";
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,49 @@ 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). A Codex rollout
528
+ // works too: the last token_count event's last_token_usage.input_tokens, with the window
529
+ // from that event (200k when it names none). Stop prints {"systemMessage": line};
530
+ // UserPromptSubmit prints additionalContext. Anything else prints nothing. Always
531
+ // offline, nothing on stderr, exit 0.
532
+ function contextMeterLine(payload) {
533
+ const p = payload?.transcript_path;
534
+ if (typeof p !== "string" || !p) return null;
535
+ let text;
536
+ try { text = readFileSync(p, "utf8"); } catch { return null; }
537
+ let tokens = null, over200k = false, codex = null;
538
+ for (const line of text.split("\n")) {
539
+ let e;
540
+ try { e = JSON.parse(line); } catch { continue; } // junk lines are skipped
541
+ if (e?.type === "event_msg" && e?.payload?.type === "token_count") {
542
+ // A Codex rollout line: the context length is the last turn's input tokens (cached input
543
+ // is already inside input_tokens; output tokens don't count). Null info / zero: not a reading.
544
+ const info = e?.payload?.info, n = info?.last_token_usage?.input_tokens;
545
+ if (info && typeof n === "number" && n > 0) codex = { tokens: n, window: info.model_context_window || 200000 };
546
+ continue;
547
+ }
548
+ if (e?.type !== "assistant" || e?.isSidechain) continue; // subagents don't count
549
+ const u = e?.message?.usage;
550
+ if (!u) continue;
551
+ const sum = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
552
+ if (!sum) continue;
553
+ if (sum > 200000) over200k = true;
554
+ tokens = sum; // keep the last one
555
+ }
556
+ let window;
557
+ if (codex) { tokens = codex.tokens; window = codex.window; } // a transcript is one app or the other
558
+ else {
559
+ if (tokens === null) return null;
560
+ window = over200k ? 1000000 : 200000;
561
+ }
562
+ const n = Math.round(tokens / 1000), pct = Math.round(tokens * 100 / window);
563
+ const icon = tokens < 80000 ? "🟢" : tokens < 150000 ? "🔵" : tokens < 180000 ? "🟡" : "🔴";
564
+ 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.";
565
+ return `${icon} Context: ~${n}k tokens (${pct}% of the window): ${advice}`;
566
+ }
524
567
  // The project this session runs in: the folder name of the git repository the cwd sits in
525
568
  // (walk up to the first folder holding `.git`, a dir or a worktree's file), else the cwd's
526
569
  // own folder name. No git binary, no network: just the filesystem.
@@ -545,10 +588,28 @@ function hookStdinCwd() {
545
588
  catch { return null; }
546
589
  }
547
590
  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 } }));
591
+ if (sub === "session-start") {
592
+ const key = `<your name>-handoff-${projectName(hookStdinCwd() || process.cwd())}`;
593
+ 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).`;
594
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: ctx } }));
595
+ return;
596
+ }
597
+ if (sub === "context-meter") {
598
+ // The hook JSON is on stdin; only read it when stdin isn't a terminal (a TTY would
599
+ // block). Anything unusable prints nothing and exits 0.
600
+ let payload = null;
601
+ if (!process.stdin.isTTY) {
602
+ try { payload = JSON.parse(readFileSync(0, "utf8") || "{}"); } catch {}
603
+ }
604
+ const event = payload?.hook_event_name;
605
+ if (event === "Stop" && payload?.stop_hook_active) return; // another hook already ran
606
+ const line = (event === "Stop" || event === "UserPromptSubmit") ? contextMeterLine(payload) : null;
607
+ if (!line) return;
608
+ if (event === "Stop") console.log(JSON.stringify({ systemMessage: line }));
609
+ else console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: line } }));
610
+ return;
611
+ }
612
+ throw new Fail("Usage: owlmem hook session-start|context-meter");
552
613
  }
553
614
 
554
615
  // ── install: connect the AI apps on this machine to OwlMem's MCP server ──
@@ -708,7 +769,14 @@ export function sessionStartCommand(o = {}) {
708
769
  function sessionStartFile() {
709
770
  return join(process.env.CLAUDE_CONFIG_DIR || join(home(), ".claude"), "settings.json");
710
771
  }
772
+ // The context meter (Stop + UserPromptSubmit): ~/.claude/settings.json gets entries that
773
+ // run `owlmem hook context-meter` after each reply and before each prompt, showing the
774
+ // measured context length. Same shape as the SessionStart hook, no matcher.
775
+ export function contextMeterCommand() {
776
+ return `node ${join(wakeDir(), "owlmem.mjs")} hook context-meter`;
777
+ }
711
778
  const isSessionStartOurs = (e) => (e?.hooks || []).some((h) => typeof h?.command === "string" && h.command.includes("owlmem") && h.command.includes("hook session-start"));
779
+ const isContextMeterOurs = (e) => (e?.hooks || []).some((h) => typeof h?.command === "string" && h.command.includes("owlmem") && h.command.includes("hook context-meter"));
712
780
  export function planSessionStartHook(uninstall) {
713
781
  const file = sessionStartFile();
714
782
  const text = readText(file);
@@ -719,17 +787,83 @@ export function planSessionStartHook(uninstall) {
719
787
  }
720
788
  if (obj.hooks !== undefined && (typeof obj.hooks !== "object" || Array.isArray(obj.hooks) || obj.hooks === null)) return null;
721
789
  const hooks = obj.hooks || {};
722
- if (hooks.SessionStart !== undefined && !Array.isArray(hooks.SessionStart)) return null;
723
- const list = hooks.SessionStart || [];
790
+ // The three hook events we manage: SessionStart (search first) and the context meter
791
+ // (Stop + UserPromptSubmit, showing the measured context length after each reply).
792
+ const events = [
793
+ { event: "SessionStart", ours: isSessionStartOurs, command: sessionStartCommand() },
794
+ { event: "Stop", ours: isContextMeterOurs, command: contextMeterCommand() },
795
+ { event: "UserPromptSubmit", ours: isContextMeterOurs, command: contextMeterCommand() },
796
+ ];
797
+ for (const { event } of events) {
798
+ if (hooks[event] !== undefined && !Array.isArray(hooks[event])) return null;
799
+ }
800
+ if (uninstall) {
801
+ if (!events.some(({ event, ours }) => (hooks[event] || []).some(ours))) return null;
802
+ const next = { ...obj, hooks: { ...hooks } };
803
+ for (const { event, ours } of events) {
804
+ if (hooks[event]) next.hooks[event] = hooks[event].filter((e) => !ours(e));
805
+ }
806
+ return { file, text: JSON.stringify(next, null, 2) + "\n" };
807
+ }
808
+ const next = { ...obj, hooks: { ...hooks } };
809
+ let changed = false;
810
+ for (const { event, ours, command } of events) {
811
+ const list = hooks[event] || [];
812
+ if (!list.some(ours)) {
813
+ next.hooks[event] = [...list, { hooks: [{ type: "command", command }] }];
814
+ changed = true;
815
+ }
816
+ }
817
+ if (!changed) return null; // already installed
818
+ return { file, text: JSON.stringify(next, null, 2) + "\n" };
819
+ }
820
+
821
+ // Codex hooks: $CODEX_HOME/hooks.json (default ~/.codex/hooks.json) has the same shape as
822
+ // Claude Code's settings.json "hooks". Codex gets only the context meter (Stop +
823
+ // UserPromptSubmit) — it has no SessionStart search-first hook. A hook written by a
824
+ // program does not run until the person trusts it in Codex with /hooks, so install says
825
+ // so; install never writes trust state (no trusted_hash / hooks.state in config.toml).
826
+ function codexHooksFile() {
827
+ return join(process.env.CODEX_HOME || join(home(), ".codex"), "hooks.json");
828
+ }
829
+ export function planCodexHooks(uninstall) {
830
+ const file = codexHooksFile();
831
+ const text = readText(file);
832
+ let obj = {};
833
+ if (text !== null && text.trim()) {
834
+ try { obj = JSON.parse(text); } catch { return null; } // bad JSON: leave alone
835
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) return null;
836
+ }
837
+ if (obj.hooks !== undefined && (typeof obj.hooks !== "object" || Array.isArray(obj.hooks) || obj.hooks === null)) return null;
838
+ const hooks = obj.hooks || {};
839
+ const events = [
840
+ { event: "Stop", ours: isContextMeterOurs, command: contextMeterCommand() },
841
+ { event: "UserPromptSubmit", ours: isContextMeterOurs, command: contextMeterCommand() },
842
+ ];
843
+ for (const { event } of events) {
844
+ if (hooks[event] !== undefined && !Array.isArray(hooks[event])) return null;
845
+ }
724
846
  if (uninstall) {
725
- if (!list.some(isSessionStartOurs)) return null;
726
- const next = { ...obj, hooks: { ...hooks, SessionStart: list.filter((e) => !isSessionStartOurs(e)) } };
847
+ if (!events.some(({ event, ours }) => (hooks[event] || []).some(ours))) return null;
848
+ const next = { ...obj, hooks: { ...hooks } };
849
+ for (const { event, ours } of events) {
850
+ if (hooks[event]) next.hooks[event] = hooks[event].filter((e) => !ours(e));
851
+ }
727
852
  return { file, text: JSON.stringify(next, null, 2) + "\n" };
728
853
  }
729
- if (list.some(isSessionStartOurs)) return null; // already installed
730
- const next = { ...obj, hooks: { ...hooks, SessionStart: [...list, { hooks: [{ type: "command", command: sessionStartCommand() }] }] } };
854
+ const next = { ...obj, hooks: { ...hooks } };
855
+ let changed = false;
856
+ for (const { event, ours, command } of events) {
857
+ const list = hooks[event] || [];
858
+ if (!list.some(ours)) {
859
+ next.hooks[event] = [...list, { hooks: [{ type: "command", command }] }];
860
+ changed = true;
861
+ }
862
+ }
863
+ if (!changed) return null; // already installed
731
864
  return { file, text: JSON.stringify(next, null, 2) + "\n" };
732
865
  }
866
+ const codexHooksPresent = () => (readText(codexHooksFile()) || "").includes("hook context-meter");
733
867
 
734
868
  export function plan(opts = {}) {
735
869
  const only = opts.only ? new Set(opts.only) : null;
@@ -751,6 +885,14 @@ export function plan(opts = {}) {
751
885
  r.ops.push({ type: "write", file: hop.file, text: hop.text, hook: true });
752
886
  }
753
887
  }
888
+ if (c.id === "codex" && !opts.noRules && r.state !== "fail") {
889
+ const hop = planCodexHooks(opts.uninstall);
890
+ if (hop) {
891
+ if (!opts.uninstall) r.ops.unshift({ type: "copy", file: join(wakeDir(), "owlmem.mjs") });
892
+ r.ops.push({ type: "write", file: hop.file, text: hop.text, hook: true, codex: true });
893
+ }
894
+ if (!opts.uninstall) r.codexHooks = !!hop || codexHooksPresent();
895
+ }
754
896
  out.push(r);
755
897
  }
756
898
  return out;
@@ -799,7 +941,8 @@ function describe(r, done, uninstall) {
799
941
  for (const op of r.ops) {
800
942
  if (op.type === "run" && !done) lines.push(" run: " + op.argv.join(" "));
801
943
  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)}`);
944
+ if (op.hook && op.codex) lines.push(` ${done ? "" : "will "}${uninstall ? (done ? "removed" : "remove") : (done ? "added" : "add")} the context-meter hooks in ${tilde(op.file)} (Codex runs them only once you trust them with /hooks)`);
945
+ else 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
946
  }
804
947
  if (done && r.backups?.length) lines.push(" backup: " + r.backups.join(", "));
805
948
  return lines.join("\n");
@@ -891,6 +1034,8 @@ function nextSteps(items, out) {
891
1034
  out("Next: sign in once in each app. The first time an app uses OwlMem it opens the owlmem.com sign-in page —");
892
1035
  out("sign in with your email (new accounts get a free space) and click \"Allow\". An AI can't click it for you.");
893
1036
  for (const r of live) out(" • " + LOGIN[r.id]);
1037
+ if (live.some((r) => r.id === "codex" && r.codexHooks))
1038
+ out("Codex: the context-meter hooks in ~/.codex/hooks.json don't run until you trust them — open /hooks in Codex and trust the OwlMem entries.");
894
1039
  if (live.some((r) => ["cursor", "vscode", "vscode-insiders", "windsurf"].includes(r.id)))
895
1040
  out("Cursor, VS Code and Windsurf have no global rules file: add the rules from https://owlmem.com/docs#instructions to your project rules.");
896
1041
  if (live.some((r) => r.id === "claude-desktop")) out("Claude Desktop: restart it to load OwlMem. (Or add https://mcp.owlmem.com/mcp under Settings → Connectors instead.)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owlmem",
3
- "version": "0.9.34",
3
+ "version": "0.9.36",
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" },