myagentmemory 0.4.13 → 0.4.15

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.
package/dist/cli.js CHANGED
@@ -12,13 +12,22 @@
12
12
  * search — Search via qmd
13
13
  * init — Create dirs, detect qmd, setup collection
14
14
  * status — Show config, qmd status, file counts
15
+ * completion — Install or print shell completion
16
+ * install-hooks — Install managed session-start hooks
17
+ * uninstall-hooks — Remove managed session-start hooks
18
+ * plugin — Discover and bootstrap optional official plugins
15
19
  *
16
20
  * Global flags:
17
21
  * --dir <path> Override memory directory
18
22
  * --json Machine-readable JSON output
19
23
  */
24
+ import { spawn } from "node:child_process";
20
25
  import * as fs from "node:fs";
26
+ import { detectCompletionShell, generateCompletion, installCompletion } from "./completions.js";
21
27
  import { _setBaseDir, buildMemoryContext, checkCollection, dailyPath, detectQmd, distilMemories, ensureDirs, ensureQmdAvailableForSync, ensureQmdAvailableForUpdate, getCollectionName, getDailyDir, getMemoryDir, getMemoryFile, getQmdEmbedMode, getQmdHealth, getQmdResultPath, getQmdResultText, getScratchpadFile, getTopicsDir, installSkills, memoryWrite, nowTimestamp, parseScratchpad, probeEmbeddings, readFileSafe, redactSecrets, runQmdEmbedDetached, runQmdSearch, runQmdSync, runQmdUpdateNow, scheduleQmdUpdate, searchRelevantMemories, serializeScratchpad, setupQmdCollection, slugifyTopic, todayStr, topicPath, uninstallSkills, } from "./core.js";
28
+ import { detectHookAgents, installHooks, uninstallHooks } from "./hooks.js";
29
+ import { createDefaultPluginBootstrap, PluginBootstrapFailure, } from "./plugin-bootstrap.js";
30
+ import { InstalledPluginRuntimeV1 } from "./plugin-runtime.js";
22
31
  function readPackageVersion() {
23
32
  try {
24
33
  const packageJson = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
@@ -86,6 +95,114 @@ function exitError(message, json) {
86
95
  }
87
96
  process.exit(1);
88
97
  }
98
+ function openExternalUrl(url) {
99
+ let parsed;
100
+ try {
101
+ parsed = new URL(url);
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ if (parsed.protocol !== "https:")
107
+ return false;
108
+ try {
109
+ const child = process.platform === "darwin"
110
+ ? spawn("open", [parsed.toString()], { detached: true, stdio: "ignore" })
111
+ : process.platform === "win32"
112
+ ? spawn("explorer.exe", [parsed.toString()], { detached: true, stdio: "ignore" })
113
+ : spawn("xdg-open", [parsed.toString()], { detached: true, stdio: "ignore" });
114
+ child.unref();
115
+ return true;
116
+ }
117
+ catch {
118
+ return false;
119
+ }
120
+ }
121
+ function printProOverview(installed) {
122
+ console.log("");
123
+ console.log("AgentMemory Pro includes:");
124
+ console.log(" Session Intelligence Recall decisions and context across Pi, Codex, and Claude Code sessions.");
125
+ console.log(" Guided Learning Turn repeated corrections into reviewable, reversible memory.");
126
+ console.log(" Local Web Console Inspect memories, activity, health, and settings in your browser.");
127
+ console.log("");
128
+ console.log("Your session content stays on this device.");
129
+ console.log("");
130
+ if (installed) {
131
+ console.log("Try it:");
132
+ console.log(' agent-memory recall "what did we decide about authentication?"');
133
+ console.log(" agent-memory learn");
134
+ console.log(" agent-memory web");
135
+ }
136
+ else {
137
+ console.log("Start your Pro beta:");
138
+ console.log(" agent-memory plugin install");
139
+ }
140
+ }
141
+ function printPluginResult(result, json, allowBrowser) {
142
+ if (json) {
143
+ output(result, true);
144
+ }
145
+ else if (result.command === "plugin.list" && result.plugins) {
146
+ for (const plugin of result.plugins) {
147
+ const state = plugin.available ? "available" : plugin.installed ? plugin.entitlement : "not installed";
148
+ console.log(`${plugin.name}: ${state}`);
149
+ }
150
+ printProOverview(Boolean(result.bundle));
151
+ }
152
+ else {
153
+ const version = result.bundle?.version ? ` ${result.bundle.version}` : "";
154
+ let showOverview = false;
155
+ switch (result.result) {
156
+ case "installed":
157
+ console.log(`AgentMemory Pro${version} installed.`);
158
+ showOverview = true;
159
+ break;
160
+ case "upgraded":
161
+ console.log(`AgentMemory Pro upgraded to${version}.`);
162
+ showOverview = true;
163
+ break;
164
+ case "current":
165
+ console.log(result.bundle
166
+ ? `AgentMemory Pro${version} is installed and ready.`
167
+ : "AgentMemory Pro is not installed.");
168
+ showOverview = Boolean(result.bundle);
169
+ break;
170
+ case "update_available":
171
+ console.log(`AgentMemory Pro${version} has an update available.`);
172
+ break;
173
+ case "uninstalled":
174
+ console.log("AgentMemory Pro executable components were removed. Memory and billing state were preserved.");
175
+ break;
176
+ case "not_installed":
177
+ console.log("AgentMemory Pro is not installed.");
178
+ console.log("Run: agent-memory plugin install");
179
+ break;
180
+ case "auth_required":
181
+ console.log("Run this command in an interactive terminal to enter an email and activate free daily access.");
182
+ break;
183
+ case "renewal_required":
184
+ console.log("Renew AgentMemory Pro to continue using paid capabilities.");
185
+ break;
186
+ default:
187
+ console.log(result.error?.message ?? "AgentMemory Pro is currently unavailable.");
188
+ }
189
+ if (showOverview)
190
+ printProOverview(true);
191
+ }
192
+ if (result.nextAction) {
193
+ if (allowBrowser && openExternalUrl(result.nextAction.url)) {
194
+ if (!json)
195
+ console.log("Opened the AgentMemory account website.");
196
+ }
197
+ else if (!json) {
198
+ console.log(`Open: ${result.nextAction.url}`);
199
+ }
200
+ if (!json && result.nextAction.userCode)
201
+ console.log(`Code: ${result.nextAction.userCode}`);
202
+ }
203
+ if (!result.ok)
204
+ process.exitCode = 1;
205
+ }
89
206
  // ---------------------------------------------------------------------------
90
207
  // Commands
91
208
  // ---------------------------------------------------------------------------
@@ -423,6 +540,84 @@ function cmdInstallSkills(flags) {
423
540
  }
424
541
  }
425
542
  }
543
+ async function promptYesNo(question, defaultYes) {
544
+ const readline = await import("node:readline/promises");
545
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
546
+ try {
547
+ const answer = (await rl.question(`${question} ${defaultYes ? "[Y/n]" : "[y/N]"} `)).trim().toLowerCase();
548
+ if (!answer)
549
+ return defaultYes;
550
+ return answer === "y" || answer === "yes";
551
+ }
552
+ finally {
553
+ rl.close();
554
+ }
555
+ }
556
+ async function cmdInstallHooks(flags) {
557
+ const json = hasFlag(flags, "json");
558
+ const requested = getFlag(flags, "only");
559
+ const requestedKeys = requested ? new Set(requested.split(",").map((value) => value.trim())) : null;
560
+ const { homeDir, targets } = detectHookAgents();
561
+ if (!homeDir)
562
+ exitError("Home directory not found.", json);
563
+ const eligible = targets.filter((target) => target.supported && target.detected && (!requestedKeys || requestedKeys.has(target.key)));
564
+ const selected = new Set();
565
+ const applyAll = hasFlag(flags, "yes") || hasFlag(flags, "all") || !process.stdin.isTTY;
566
+ for (const target of eligible) {
567
+ if (applyAll || (await promptYesNo(`Install SessionStart hook for ${target.label}?`, true)))
568
+ selected.add(target.key);
569
+ }
570
+ const report = installHooks(selected);
571
+ if (!report.ok)
572
+ exitError(report.error ?? "install failed", json);
573
+ if (json)
574
+ return output(report, true);
575
+ if (!report.results.length)
576
+ return output("No eligible agents. Nothing to install.", false);
577
+ for (const result of report.results) {
578
+ console.log(result.installed
579
+ ? `Installed ${result.label} hook: ${result.path}`
580
+ : `Skipped ${result.label} (${result.reason ?? "unknown"})`);
581
+ }
582
+ }
583
+ function cmdUninstallHooks(flags) {
584
+ const json = hasFlag(flags, "json");
585
+ const only = getFlag(flags, "only");
586
+ const agents = only ? new Set(only.split(",").map((value) => value.trim())) : undefined;
587
+ const report = uninstallHooks(agents);
588
+ if (!report.ok)
589
+ exitError(report.error ?? "uninstall failed", json);
590
+ if (json) {
591
+ output(report, true);
592
+ return;
593
+ }
594
+ for (const result of report.results) {
595
+ console.log(result.installed
596
+ ? `Uninstalled ${result.label}: ${result.path}`
597
+ : `Skipped ${result.label} (${result.reason ?? "unknown"})`);
598
+ }
599
+ }
600
+ function cmdCompletion(flags, positional) {
601
+ const requestedShell = positional[0];
602
+ const shells = ["bash", "zsh", "fish", "powershell"];
603
+ if (requestedShell && !shells.includes(requestedShell))
604
+ exitError(`Unsupported shell '${requestedShell}'. Choose bash, zsh, fish, or powershell.`, hasFlag(flags, "json"));
605
+ const shell = requestedShell ?? detectCompletionShell();
606
+ if (!shell)
607
+ exitError("Could not detect your shell. Specify bash, zsh, fish, or powershell.", hasFlag(flags, "json"));
608
+ if (hasFlag(flags, "stdout")) {
609
+ process.stdout.write(generateCompletion(shell));
610
+ return;
611
+ }
612
+ const result = installCompletion(shell);
613
+ if (hasFlag(flags, "json")) {
614
+ output(result, true);
615
+ return;
616
+ }
617
+ console.log(`Installed ${shell} completion: ${result.completionPath}`);
618
+ if (result.profilePath)
619
+ console.log(`${result.profileUpdated ? "Configured" : "Already configured"}: ${result.profilePath}`);
620
+ }
426
621
  async function cmdSync(flags) {
427
622
  const json = hasFlag(flags, "json");
428
623
  ensureDirs();
@@ -509,6 +704,19 @@ async function cmdInit(flags) {
509
704
  console.log(` qmd not found — search features unavailable.`);
510
705
  console.log(` Install: bun install -g https://github.com/tobi/qmd`);
511
706
  }
707
+ if (process.stdout.isTTY) {
708
+ try {
709
+ const plugin = await createDefaultPluginBootstrap(VERSION).list();
710
+ if (plugin.result === "not_installed") {
711
+ console.log("");
712
+ console.log("Optional: AgentMemory Pro adds session recall and a local Web Console.");
713
+ console.log("Run: agent-memory plugin install");
714
+ }
715
+ }
716
+ catch {
717
+ // Commercial discovery must never make core initialization fail.
718
+ }
719
+ }
512
720
  }
513
721
  }
514
722
  async function cmdStatus(flags) {
@@ -553,6 +761,22 @@ async function cmdStatus(flags) {
553
761
  }
554
762
  }
555
763
  const embedMode = getQmdEmbedMode();
764
+ let officialPlugin = {
765
+ installed: false,
766
+ result: "unavailable",
767
+ entitlement: "missing",
768
+ };
769
+ try {
770
+ const plugin = await createDefaultPluginBootstrap(VERSION).status();
771
+ officialPlugin = {
772
+ installed: Boolean(plugin.bundle),
773
+ result: plugin.result,
774
+ entitlement: plugin.entitlement.state,
775
+ };
776
+ }
777
+ catch {
778
+ // Commercial status must never make core status fail.
779
+ }
556
780
  if (json) {
557
781
  output({
558
782
  directory: dir,
@@ -575,6 +799,7 @@ async function cmdStatus(flags) {
575
799
  embeddings,
576
800
  },
577
801
  embedMode,
802
+ officialPlugin,
578
803
  }, true);
579
804
  }
580
805
  else {
@@ -626,6 +851,11 @@ async function cmdStatus(flags) {
626
851
  else {
627
852
  console.log("qmd: not installed");
628
853
  }
854
+ if (!officialPlugin.installed) {
855
+ console.log("");
856
+ console.log("Optional official plugins: not installed");
857
+ console.log(" run: agent-memory plugin install");
858
+ }
629
859
  }
630
860
  }
631
861
  async function cmdDistil(flags) {
@@ -651,6 +881,100 @@ async function cmdDistil(flags) {
651
881
  }
652
882
  }
653
883
  }
884
+ function printPluginUsage() {
885
+ console.log(`agent-memory plugin — optional official plugins
886
+
887
+ Usage:
888
+ agent-memory plugin [list]
889
+ agent-memory plugin status
890
+ agent-memory plugin install [--channel stable] [--no-browser]
891
+ agent-memory plugin update [--channel stable]
892
+ agent-memory plugin uninstall --yes
893
+ agent-memory plugin manage [--no-browser]
894
+
895
+ The public core remains fully usable without AgentMemory Pro. Interactive install
896
+ opens a loopback website for email activation and a configurable free daily
897
+ agent-session allowance. Memory and session content stay on this device.`);
898
+ }
899
+ function pluginCommandFailure(command, error) {
900
+ return {
901
+ schemaVersion: 1,
902
+ command: `plugin.${command}`,
903
+ ok: false,
904
+ result: "unavailable",
905
+ bundle: null,
906
+ entitlement: {
907
+ plan: null,
908
+ state: "missing",
909
+ features: [],
910
+ capabilities: {},
911
+ },
912
+ nextAction: null,
913
+ error: {
914
+ code: error instanceof PluginBootstrapFailure ? error.code : "plugin_command_failed",
915
+ message: error instanceof Error ? error.message : String(error),
916
+ ...(error instanceof PluginBootstrapFailure && error.retryable ? { retryable: true } : {}),
917
+ },
918
+ };
919
+ }
920
+ async function cmdPlugin(flags, positional) {
921
+ const json = hasFlag(flags, "json");
922
+ const subcommand = positional[0] ?? "list";
923
+ if (subcommand === "help" || hasFlag(flags, "help")) {
924
+ printPluginUsage();
925
+ return;
926
+ }
927
+ const channel = getFlag(flags, "channel") ?? "stable";
928
+ if (channel !== "stable") {
929
+ printPluginResult(pluginCommandFailure(subcommand, new PluginBootstrapFailure("channel_invalid", "--channel supports only 'stable'")), json, false);
930
+ return;
931
+ }
932
+ const allowBrowser = !json && !hasFlag(flags, "no-browser") && Boolean(process.stdin.isTTY && process.stdout.isTTY);
933
+ const manager = createDefaultPluginBootstrap(VERSION);
934
+ let result;
935
+ try {
936
+ switch (subcommand) {
937
+ case "list":
938
+ result = await manager.list();
939
+ break;
940
+ case "status":
941
+ result = await manager.status(channel);
942
+ break;
943
+ case "install":
944
+ result = await manager.install({ channel, allowAuthentication: allowBrowser });
945
+ break;
946
+ case "update":
947
+ result = await manager.update({ channel, allowAuthentication: false });
948
+ break;
949
+ case "uninstall":
950
+ if (!hasFlag(flags, "yes")) {
951
+ const status = await manager.status(channel);
952
+ result = {
953
+ ...status,
954
+ command: "plugin.uninstall",
955
+ ok: false,
956
+ result: "unavailable",
957
+ error: {
958
+ code: "confirmation_required",
959
+ message: "Re-run with --yes to remove AgentMemory Pro executable components",
960
+ },
961
+ };
962
+ break;
963
+ }
964
+ result = await manager.uninstall();
965
+ break;
966
+ case "manage":
967
+ result = await manager.manage();
968
+ break;
969
+ default:
970
+ result = pluginCommandFailure(subcommand, new PluginBootstrapFailure("unknown_plugin_command", `Unknown plugin command: ${subcommand}. Available bootstrap commands: list, status, install, update, uninstall, manage.`));
971
+ }
972
+ }
973
+ catch (error) {
974
+ result = pluginCommandFailure(subcommand, error);
975
+ }
976
+ printPluginResult(result, json, allowBrowser && (subcommand === "install" || subcommand === "manage"));
977
+ }
654
978
  // ---------------------------------------------------------------------------
655
979
  // Usage
656
980
  // ---------------------------------------------------------------------------
@@ -673,6 +997,10 @@ Commands:
673
997
  sync Re-index and embed all files (requires qmd)
674
998
  init Initialize memory directory and qmd collection
675
999
  status Show configuration and status (--probe for a live embeddings check)
1000
+ completion Install or print shell completion
1001
+ install-hooks Install managed SessionStart hooks
1002
+ uninstall-hooks Remove only managed SessionStart hooks
1003
+ plugin Discover, install, update, or remove optional official plugins
676
1004
 
677
1005
  Global flags:
678
1006
  --dir <path> Override memory directory
@@ -695,7 +1023,11 @@ Examples:
695
1023
  agent-memory distil --dry-run
696
1024
  agent-memory context --query "database choice"
697
1025
  agent-memory sync
698
- agent-memory status --json`);
1026
+ agent-memory status --json
1027
+ agent-memory completion zsh
1028
+ agent-memory install-hooks --yes
1029
+ agent-memory plugin status
1030
+ agent-memory plugin install`);
699
1031
  }
700
1032
  // ---------------------------------------------------------------------------
701
1033
  // Main
@@ -712,7 +1044,7 @@ async function main() {
712
1044
  output(json ? { version: VERSION } : VERSION, json);
713
1045
  return;
714
1046
  }
715
- if (!command || command === "help" || hasFlag(flags, "help")) {
1047
+ if (!command || command === "help" || (hasFlag(flags, "help") && command !== "plugin")) {
716
1048
  printUsage();
717
1049
  return;
718
1050
  }
@@ -751,8 +1083,59 @@ async function main() {
751
1083
  case "status":
752
1084
  await cmdStatus(flags);
753
1085
  break;
754
- default:
755
- exitError(`Unknown command: ${command}. Run 'agent-memory help' for usage.`, json);
1086
+ case "completion":
1087
+ cmdCompletion(flags, positional);
1088
+ break;
1089
+ case "install-hooks":
1090
+ await cmdInstallHooks(flags);
1091
+ break;
1092
+ case "uninstall-hooks":
1093
+ cmdUninstallHooks(flags);
1094
+ break;
1095
+ case "hook": {
1096
+ if (positional[0] !== "session-start")
1097
+ exitError("hook requires 'session-start'", json);
1098
+ const agent = getFlag(flags, "agent");
1099
+ if (!agent)
1100
+ exitError("hook session-start requires --agent", json);
1101
+ await cmdContext({ "no-search": true });
1102
+ try {
1103
+ const decision = await new InstalledPluginRuntimeV1({ coreVersion: VERSION }).runSessionStart({
1104
+ host: agent,
1105
+ cwd: process.cwd(),
1106
+ signal: new AbortController().signal,
1107
+ });
1108
+ if (decision?.state === "exhausted")
1109
+ console.error(`AgentMemory free session allowance resets at ${decision.resetAt}`);
1110
+ }
1111
+ catch {
1112
+ // Paid SessionStart work must never make public-core context unavailable.
1113
+ }
1114
+ break;
1115
+ }
1116
+ case "plugin":
1117
+ await cmdPlugin(flags, positional);
1118
+ break;
1119
+ default: {
1120
+ const controller = new AbortController();
1121
+ const abort = () => controller.abort();
1122
+ process.once("SIGINT", abort);
1123
+ try {
1124
+ const result = await new InstalledPluginRuntimeV1({ coreVersion: VERSION }).run(command, {
1125
+ args: positional,
1126
+ flags,
1127
+ signal: controller.signal,
1128
+ });
1129
+ if (!result)
1130
+ exitError(`Unknown command: ${command}. Run 'agent-memory help' for usage.`, json);
1131
+ if (!result.ok)
1132
+ exitError(result.error?.message ?? `Plugin command ${command} failed`, json);
1133
+ output(result.data ?? { ok: true }, json);
1134
+ }
1135
+ finally {
1136
+ process.removeListener("SIGINT", abort);
1137
+ }
1138
+ }
756
1139
  }
757
1140
  }
758
1141
  main().catch((err) => {
@@ -0,0 +1,13 @@
1
+ export type CompletionShell = "bash" | "zsh" | "fish" | "powershell";
2
+ export interface CompletionInstallResult {
3
+ shell: CompletionShell;
4
+ completionPath: string;
5
+ profilePath?: string;
6
+ profileUpdated: boolean;
7
+ }
8
+ export declare function generateCompletion(shell: CompletionShell): string;
9
+ export declare function detectCompletionShell(environment?: Record<string, string | undefined>, platform?: NodeJS.Platform): CompletionShell | null;
10
+ export declare function installCompletion(shell: CompletionShell, options?: {
11
+ homeDir?: string;
12
+ platform?: NodeJS.Platform;
13
+ }): CompletionInstallResult;