om-memory-system 5.3.0 → 5.4.1
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/README.md +4 -0
- package/dist/adapters/claude-code/hook-client.d.ts +1 -1
- package/dist/adapters/claude-code/hook-client.js +15 -2
- package/dist/adapters/opencode/tui-recall.js +13 -3
- package/dist/adapters/pi/extension.d.ts +1 -0
- package/dist/adapters/pi/extension.js +28 -11
- package/dist/adapters/pi/recall-rows.d.ts +31 -0
- package/dist/adapters/pi/recall-rows.js +148 -0
- package/dist/adapters/pi/session-context.d.ts +22 -0
- package/dist/adapters/pi/session-context.js +125 -0
- package/dist/config-template.d.ts +1 -1
- package/dist/config-template.js +18 -3
- package/dist/config.d.ts +6 -0
- package/dist/config.js +5 -4
- package/dist/core/context-budget.d.ts +2 -0
- package/dist/core/context-budget.js +2 -1
- package/dist/core/opening-context.d.ts +45 -0
- package/dist/core/opening-context.js +60 -0
- package/dist/core/recall-summary.d.ts +11 -7
- package/dist/core/recall-summary.js +14 -8
- package/dist/core/retrieval.d.ts +16 -0
- package/dist/core/retrieval.js +33 -11
- package/dist/importer/claude-hook-api.d.ts +5 -4
- package/dist/importer/claude-hook-api.js +58 -41
- package/dist/importer/claude-hook-context.d.ts +49 -0
- package/dist/importer/claude-hook-context.js +264 -0
- package/dist/services/ai/local-api-url.d.ts +2 -0
- package/dist/services/ai/local-api-url.js +12 -0
- package/dist/services/ai/provider-config.d.ts +2 -0
- package/dist/services/ai/provider-config.js +3 -1
- package/dist/services/ai/providers/google-gemini.js +2 -1
- package/dist/services/ai/providers/openai-responses.js +2 -1
- package/dist/services/chat/chat-runtime.js +5 -1
- package/dist/services/chat/chat-status.js +4 -1
- package/dist/services/global-config-writer.js +39 -14
- package/dist/services/injection-options-config.d.ts +53 -0
- package/dist/services/injection-options-config.js +56 -0
- package/dist/services/settings-snapshot.js +44 -12
- package/dist/services/visible-recall-config.d.ts +7 -2
- package/dist/services/visible-recall-config.js +2 -1
- package/dist/utils/memory-limits.d.ts +2 -1
- package/dist/utils/memory-limits.js +6 -3
- package/dist/v2/adapter.d.ts +2 -0
- package/dist/v2/adapter.js +107 -33
- package/dist/v2/memory-bridge.d.ts +13 -0
- package/dist/v2/memory-bridge.js +17 -0
- package/dist/v2/recall-reporter.d.ts +6 -3
- package/dist/v2/recall-reporter.js +4 -27
- package/dist/v2/session-parent.d.ts +14 -0
- package/dist/v2/session-parent.js +26 -0
- package/dist/web/assets/index-7p-aYnWZ.css +2 -0
- package/dist/web/assets/{index-CJ_K-hMG.js → index-CaFFlcl1.js} +17 -17
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/index-ccH97VE2.css +0 -2
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* src/config.ts until that file reached its size ceiling; the text is
|
|
4
4
|
* unchanged. Shared by config.ts and the global settings writer.
|
|
5
5
|
*/
|
|
6
|
-
export declare const CONFIG_TEMPLATE = "{\n // ============================================\n // omms (Opinionated Modular Memory System) Configuration\n // ============================================\n \n // Storage location for the vector database. Leave unset to use the\n // default ~/.omms/data (a legacy ~/.opencode-mem/data store is migrated\n // there automatically on first start; see docs/omms-migration.md).\n // \"storagePath\": \"~/.omms/data\",\n\n \"userEmailOverride\": \"\",\n \"userNameOverride\": \"\",\n \n // ============================================\n // Embedding Model (for similarity search)\n // ============================================\n // Local = Hugging Face / ONNX via @huggingface/transformers (not Apple MLX).\n // Remote = set embeddingApiUrl (OpenAI-compatible /embeddings); embeddingApiKey is optional.\n \n // Default: Nomic Embed v1 (768 dimensions, 8192 context, multilingual)\n \"embeddingModel\": \"Xenova/nomic-embed-text-v1\",\n\n // Opt-in Nomic task prefixes (search_document: / search_query:). After enabling,\n // re-index existing memories so store and query vectors stay aligned.\n // \"embeddingUseTaskPrefixes\": true,\n \n // Auto-detected dimensions (no need to set manually)\n // \"embeddingDimensions\": 768,\n \n // Other recommended local models:\n // \"embeddingModel\": \"Xenova/jina-embeddings-v2-base-en\", // 768 dims, English-only, 8192 context\n // \"embeddingModel\": \"Xenova/jina-embeddings-v2-small-en\", // 512 dims, faster, 8192 context\n // \"embeddingModel\": \"Xenova/all-MiniLM-L6-v2\", // 384 dims, very fast, 512 context\n // \"embeddingModel\": \"Xenova/all-mpnet-base-v2\", // 768 dims, good quality, 512 context\n \n // Optional: OpenAI-compatible API for embeddings (URL required; key only if the server needs one)\n // \"embeddingApiUrl\": \"https://api.openai.com/v1\",\n // \"embeddingApiKey\": \"env://OPENAI_API_KEY\", // or \"sk-...\" / \"file:///path/to/key\"\n // \"embeddingModel\": \"text-embedding-3-small\", // 1536 dims, auto-detected\n \n // ============================================\n // Web Server Settings\n // ============================================\n \n // Start a background import of past chats on each host's next start.\n \"autoBackfill\": true,\n // \"piBackfillModel\": \"inherit\", // or \"external\", or \"provider/model\"\n // \"opencodeBackfillModel\": \"inherit\", // or \"external\", or \"provider/model\"\n // Directory maps for history recorded in moved or deleted directories.\n // \"importPathMaps\": [{ \"from\": \"~/code/app-feat-x\", \"to\": \"~/code/app\" }],\n // Unresolved directories to hide on the Directory maps page. They stay unimported.\n // \"importIgnoredDirectories\": [\"/private/tmp/scratch\"],\n // Claude Code's folder, when it is not ~/.claude (like CLAUDE_CONFIG_DIR).\n // \"claudeConfigDir\": \"~/.claude-work\",\n\n // Register the web app to start when you log in.\n \"webServerAutoStart\": true,\n // Enable web UI for managing memories (accessible at http://localhost:4747)\n \"webServerEnabled\": true,\n \n // Port for web UI server\n \"webServerPort\": 4747,\n \n // Host address for web UI (use 127.0.0.1 for local only, 0.0.0.0 for network access)\n \"webServerHost\": \"127.0.0.1\",\n\n // Optional HTTP Basic Auth for the web UI. Accepts literal, env://, or file:// secrets.\n // \"webServerAuthPassword\": \"\",\n // \"webServerAuthUsername\": \"\",\n\n // Deprecated: imported once into the API token table, then no longer read.\n // Create API tokens on the Settings page (Keys and access) instead.\n // \"webServerApiToken\": \"env://OMMS_WEB_TOKEN\",\n \n // ============================================\n // Database Settings\n // ============================================\n \n // Maximum vectors per database shard (auto-creates new shard when limit reached)\n \"maxVectorsPerShard\": 50000,\n \n // Automatically delete old memories based on retention period\n \"autoCleanupEnabled\": true,\n \n // Days to keep memories before auto-cleanup (only if autoCleanupEnabled is true)\n \"autoCleanupRetentionDays\": 30,\n \n // Automatically detect and remove duplicate memories\n \"deduplicationEnabled\": true,\n \n // Similarity threshold (0-1) for detecting duplicates (higher = stricter)\n \"deduplicationSimilarityThreshold\": 0.90,\n \n // ============================================\n // Memory Scope Settings\n // ============================================\n\n // Default scope for memory list/search queries\n // \"project\" keeps queries within the current project, \"all-projects\" searches across all project shards\n \"memory\": {\n \"defaultScope\": \"project\"\n },\n\n // ============================================\n // Model for auto-capture and profile learning (same rule in OpenCode and Pi)\n // ============================================\n\n // Which model summarises your work, in this order:\n // 1. The host model below: opencodeProvider/opencodeModel in OpenCode,\n // piProvider/piModel in Pi. Set the model to \"inherit\" to follow\n // whatever model the session is using, or to \"external\" to send\n // every call to the external API below.\n // 2. If no host model is set: the external API (memoryModel/memoryApiUrl/\n // memoryApiKey further down).\n // 3. If neither is set: the session's own model.\n // If the host model fails and the external API is configured, the external\n // API is used instead.\n //\n // Host models go through OpenCode's or Pi's own sign-in (OAuth like Claude\n // Pro/Max, GitHub Copilot, ChatGPT, or your own key there), so no separate API\n // key is needed here.\n //\n // Examples (OpenCode names from 'opencode providers list'; Pi names from its model list):\n // \"opencodeProvider\": \"anthropic\", \"opencodeModel\": \"claude-haiku-4-5-20251001\"\n // \"opencodeProvider\": \"openai\", \"opencodeModel\": \"inherit\"\n // \"piProvider\": \"openai-codex\", \"piModel\": \"gpt-5.6-luna\"\n //\n // \"opencodeProvider\": \"anthropic\",\n // \"opencodeModel\": \"claude-haiku-4-5-20251001\",\n // \"piProvider\": \"openai-codex\",\n // \"piModel\": \"gpt-5.6-luna\",\n\n // ============================================\n // Auto-Capture Settings\n // ============================================\n \n // Auto-capture runs in the background without blocking your main session.\n // Note: Ollama may not support tool calling. Use OpenAI, Anthropic, or Groq for best results.\n \n \"autoCaptureEnabled\": true,\n \n // Provider type: \"openai-chat\" | \"openai-responses\" | \"anthropic\" | \"minimax\" | \"orcarouter\" | \"google-gemini\"\n // Note: \"openai-chat\" is a generic OpenAI API-compatible mode.\n // Any service that follows the OpenAI Chat Completions API can use it via custom \"memoryApiUrl\".\n \"memoryProvider\": \"openai-chat\",\n \n // External API (step 2 above, and the fallback when a host model fails).\n // Uncomment all 3 lines and replace memoryApiKey before use:\n // \"memoryModel\": \"gpt-4o-mini\",\n // \"memoryApiUrl\": \"https://api.openai.com/v1\",\n // \"memoryApiKey\": \"sk-...\",\n\n // API Key Formats:\n // Direct value: \"sk-...\"\n // From file: \"file://~/.config/litellm-key.txt\"\n // From env variable: \"env://LITELLM_API_KEY\"\n \n // Examples for different providers:\n // Any OpenAI-compatible endpoint can use the \"openai-chat\" provider pattern below.\n // Common examples: DeepSeek, Qwen (via Alibaba Cloud ModelStudio),\n // Zhipu GLM (BigModel platform), and Kimi (Moonshot AI platform).\n\n // OpenAI Chat Completion (default, backward compatible):\n // \"memoryProvider\": \"openai-chat\"\n // \"memoryModel\": \"gpt-4o-mini\"\n // \"memoryApiUrl\": \"https://api.openai.com/v1\"\n // \"memoryApiKey\": \"sk-...\"\n\n // DeepSeek (OpenAI-compatible example):\n // \"memoryProvider\": \"openai-chat\"\n // \"memoryModel\": \"deepseek-chat\"\n // \"memoryApiUrl\": \"https://api.deepseek.com/v1\"\n // \"memoryApiKey\": \"sk-...\"\n \n // OpenAI Responses API (recommended, with session support):\n // \"memoryProvider\": \"openai-responses\"\n // \"memoryModel\": \"gpt-4o\"\n // \"memoryApiUrl\": \"https://api.openai.com/v1\"\n // \"memoryApiKey\": \"sk-...\"\n \n // Anthropic (with session support):\n // \"memoryProvider\": \"anthropic\"\n // \"memoryModel\": \"claude-3-5-haiku-20241022\"\n // \"memoryApiUrl\": \"https://api.anthropic.com/v1\"\n // \"memoryApiKey\": \"sk-ant-...\"\n\n // MiniMax (Anthropic Messages-compatible endpoint, with session support):\n // \"memoryProvider\": \"minimax\"\n // \"memoryModel\": \"MiniMax-M3\"\n // \"memoryApiUrl\": \"https://api.minimax.io\" // global endpoint\n // \"memoryApiKey\": \"<MiniMax API key>\"\n // // China endpoint: \"memoryApiUrl\": \"https://api.minimaxi.com\"\n // // Optional adaptive thinking for MiniMax-M3:\n // \"memoryExtraParams\": { \"thinking\": { \"type\": \"adaptive\" } }\n\n // OrcaRouter (OpenAI-compatible gateway, namespaced model IDs, with session support):\n // \"memoryProvider\": \"orcarouter\"\n // \"memoryApiKey\": \"<OrcaRouter API key>\"\n // // memoryApiUrl and memoryModel are optional \u2014 they default to\n // // https://api.orcarouter.ai/v1 and \"orcarouter/auto\" (a routing alias).\n // // OrcaRouter rejects bare model names, so if you set memoryModel, use a\n // // namespaced ID such as \"openai/gpt-5.5\" or \"deepseek/deepseek-v4-flash\".\n // \"memoryModel\": \"openai/gpt-5.5\"\n\n // Groq (OpenAI-compatible, use openai-chat provider):\n // \"memoryProvider\": \"openai-chat\"\n // \"memoryModel\": \"llama-3.3-70b-versatile\"\n // \"memoryApiUrl\": \"https://api.groq.com/openai/v1\"\n // \"memoryApiKey\": \"gsk_...\"\n \n // Maximum iterations for multi-turn AI analysis (for openai-responses, anthropic, and minimax)\n \"autoCaptureMaxIterations\": 5,\n \n // Timeout per iteration in milliseconds (30 seconds default)\n \"autoCaptureIterationTimeout\": 30000,\n\n // Tries for one turn's capture, on Pi and OpenCode, 2 and 4 seconds apart. After the\n // last one fails, a turn the model could not reach goes to the capture retry queue.\n \"autoCaptureMaxRetries\": 3,\n\n // Maximum UTF-8 bytes for the auto-capture markdown context sent to the summary model.\n // Prevents HTTP 400 context overflows on models with ~131K token windows (e.g. Groq Llama).\n // Rough guide: tokens \u2248 bytes / 4 for mixed code/prose.\n \"autoCaptureMaxContextBytes\": 131072,\n \n // Days to keep AI session history before cleanup\n \"aiSessionRetentionDays\": 7,\n\n // Capture diagnostics: every capture attempt always writes one metadata line\n // (model, stop reason, sizes, outcome) to ~/.omms/omms.log, with no\n // conversation text. Set captureTrace to true to also write each attempt's\n // prompt and raw reply to ~/.omms/traces/ for debugging. Traces can contain\n // conversation content: <private> text and common API key formats are\n // redacted, files are readable only by you, and they are deleted after\n // captureTraceRetentionDays. Only this global file can turn tracing on.\n // \"captureTrace\": false,\n // \"captureTraceRetentionDays\": 7,\n // \"captureAttemptRetentionDays\": 30,\n\n // Skill learning: record each full turn (prompt, replies, tool calls with\n // their outcome, and the skills used) in ~/.omms/data/skills.db, so OMMS can\n // rank your skills and draft better versions. Off by default. A project config\n // can turn it off but never on. No model call is made to record a turn.\n // \"skillLearning\": false,\n // Remove <private> text and common API key formats before a turn is stored.\n // Global config only. Turning this off stores text as written.\n // \"skillLearningRedact\": true,\n // Folders OMMS reads skills from. Absolute or starting with ~/. Global config\n // only. Unset: ~/.agents/skills and the Claude Code folder's skills folder.\n // \"skillFolders\": [\"~/.agents/skills\"],\n\n // Visible recall: the OpenCode tui entrypoint draws a row in the session for\n // each memory recall. On by default. A project config can turn it off but\n // never on.\n // \"visibleRecall\": true,\n\n // Capture retry queue: when a live capture fails because the model cannot be\n // reached (network error, timeout, HTTP 408, 429 or 5xx), OMMS keeps a copy of\n // the turn in ~/.omms/data and tries it again later. The copy has <private>\n // text and common API key formats removed. Turns are deleted when the retry\n // ends or after captureRetryRetentionHours (0 to 720). 0 turns the queue off.\n // Only this global file can set it.\n // \"captureRetryRetentionHours\": 72,\n\n // Temperature for AI API requests (set to false to omit parameter for models that don't support it)\n // Some reasoning models (like o1, o3, gpt-5) don't support temperature parameter\n // Set to false and add \"memoryTemperature\": false in config when using such models\n \"memoryTemperature\": 0.3,\n\n // Extra parameters to include in API request body\n // Useful for local inference servers (e.g. llama-server with --jinja) that support\n // additional parameters like disabling thinking/reasoning mode\n // Example for Qwen3 models: { \"enable_thinking\": false }\n // \"memoryExtraParams\": {},\n\n // Language for auto-capture summaries (default: \"auto\" for auto-detection)\n // Options: \"auto\", \"en\", \"id\", \"zh\", \"ja\", \"es\", \"fr\", \"de\", \"ru\", \"pt\", \"ar\", \"ko\"\n // \"autoCaptureLanguage\": \"auto\",\n\n // ============================================\n // Toast Notifications\n // ============================================\n\n // Show toast when memory is auto-captured\n \"showAutoCaptureToasts\": true,\n\n // Show toast when user profile is updated\n \"showUserProfileToasts\": true,\n\n // Show toast for error messages\n \"showErrorToasts\": true,\n\n // ============================================\n // User Profile System\n // ============================================\n\n // Analyze user prompts every N prompts to build/update your user profile\n // When N uncaptured prompts accumulate, AI will analyze them to identify:\n // - User preferences (code style, communication style, tool preferences)\n // - User patterns (recurring topics, problem domains, technical interests)\n // - User workflows (development habits, sequences, learning style)\n // - Skill level (overall and per-domain assessment)\n \"userProfileAnalysisInterval\": 10,\n\n // Days before inactive items (all types) are eligible for removal\n \"userProfileStaleDays\": 2,\n\n // Days before an inactive workflow is eligible for removal. A workflow seen\n // userProfileMinEvidenceForRetention times or more is kept.\n \"userProfileWorkflowStaleDays\": 30,\n\n // Number of preferences shown in UI\n \"userProfileDisplayPreferences\": 20,\n \n // Number of patterns shown in UI\n \"userProfileDisplayPatterns\": 15,\n \n // Number of workflows shown in UI\n \"userProfileDisplayWorkflows\": 10,\n \n // Number of preferences injected into LLM conversation context\n // Keep this small \u2014 the strongest signals are enough; more dilute LLM attention\n \"userProfileInjectPreferences\": 5,\n \n // Number of patterns injected into LLM conversation context\n \"userProfileInjectPatterns\": 5,\n \n // Number of workflows injected into LLM conversation context\n \"userProfileInjectWorkflows\": 3,\n \n // Days before preference confidence starts to decay (if not reinforced)\n // Preferences that aren't seen again will gradually lose confidence and be removed\n \"userProfileConfidenceDecayDays\": 30,\n \n // Number of profile versions to keep in changelog (for rollback/debugging)\n // Older versions are automatically cleaned up\n \"userProfileChangelogRetentionCount\": 5,\n\n // Minimum evidence count for a preference/pattern to survive confidence decay\n // Items confirmed fewer times are more likely to be pruned when confidence decays\n \"userProfileMinEvidenceForRetention\": 3,\n\n // Merge duplicate or vague profile items every N analysed prompts (about 1 model call per 100 items)\n \"userProfileAutoCleanupEnabled\": true,\n \"userProfileAutoCleanupInterval\": 500,\n\n // Enable LLM validation of existing preferences against recent behavior.\n // When enabled, each analysis round checks if top-5 preferences still match recent prompts.\n // Experimental \u2014 disabled by default.\n \"userProfileValidationEnabled\": false,\n\n // ============================================\n // Search Settings\n // ============================================\n \n // Minimum similarity score (0-1) for memory search results. Leave unset to\n // follow the default for your embedding model: 0.5 for qwen3-embedding:0.6b\n // (the only model measured), 0.6 for every other embedder.\n // \"similarityThreshold\": 0.5,\n\n // Maximum number of memories to return in search results.\n // Manual searches can ask for fewer; prompt retrieval uses this ceiling.\n \"maxMemories\": 10,\n\n // ============================================\n // Memory Context Controls\n // ============================================\n\n // Recent memories added at fresh session start (OpenCode V1 and Claude Code).\n // Pi and OpenCode V2 search the store with each prompt instead.\n \"chatMessage\": {\n \"enabled\": true,\n // Recent memories injected at session start.\n \"maxMemories\": 3,\n \"excludeCurrentSession\": true,\n // When to inject: \"first\" message of a session or \"always\".\n // \"injectOn\": \"first\",\n },\n\n // OpenCode profile-learning input limit, in UTF-8 bytes. Smaller values can\n // omit prompts from that input. Does not limit Pi or Claude Code profile input.\n \"userProfileMaxContextBytes\": 32768,\n\n // Shared budget for automatic memory context (profile text, memories, and\n // formatting) across all hosts, in approximate tokens: ceil(UTF-8 bytes / 4).\n // Covers prompt retrieval, recent-memory injection, and session-memory\n // restoration. Not an exact provider token limit or a spending limit.\n \"retrievalMaxTokens\": 2000,\n\n // ============================================\n // Advanced Settings\n // ============================================\n \n // Inject user profile into AI context (preferences, patterns, workflows)\n \"injectProfile\": true\n}\n";
|
|
6
|
+
export declare const CONFIG_TEMPLATE = "{\n // ============================================\n // omms (Opinionated Modular Memory System) Configuration\n // ============================================\n \n // Storage location for the vector database. Leave unset to use the\n // default ~/.omms/data (a legacy ~/.opencode-mem/data store is migrated\n // there automatically on first start; see docs/omms-migration.md).\n // \"storagePath\": \"~/.omms/data\",\n\n \"userEmailOverride\": \"\",\n \"userNameOverride\": \"\",\n \n // ============================================\n // Embedding Model (for similarity search)\n // ============================================\n // Local = Hugging Face / ONNX via @huggingface/transformers (not Apple MLX).\n // Remote = set embeddingApiUrl (OpenAI-compatible /embeddings); embeddingApiKey is optional.\n \n // Default: Nomic Embed v1 (768 dimensions, 8192 context, multilingual)\n \"embeddingModel\": \"Xenova/nomic-embed-text-v1\",\n\n // Opt-in Nomic task prefixes (search_document: / search_query:). After enabling,\n // re-index existing memories so store and query vectors stay aligned.\n // \"embeddingUseTaskPrefixes\": true,\n \n // Auto-detected dimensions (no need to set manually)\n // \"embeddingDimensions\": 768,\n \n // Other recommended local models:\n // \"embeddingModel\": \"Xenova/jina-embeddings-v2-base-en\", // 768 dims, English-only, 8192 context\n // \"embeddingModel\": \"Xenova/jina-embeddings-v2-small-en\", // 512 dims, faster, 8192 context\n // \"embeddingModel\": \"Xenova/all-MiniLM-L6-v2\", // 384 dims, very fast, 512 context\n // \"embeddingModel\": \"Xenova/all-mpnet-base-v2\", // 768 dims, good quality, 512 context\n \n // Optional: OpenAI-compatible API for embeddings (URL required; key only if the server needs one)\n // \"embeddingApiUrl\": \"https://api.openai.com/v1\",\n // \"embeddingApiKey\": \"env://OPENAI_API_KEY\", // or \"sk-...\" / \"file:///path/to/key\"\n // \"embeddingModel\": \"text-embedding-3-small\", // 1536 dims, auto-detected\n \n // ============================================\n // Web Server Settings\n // ============================================\n \n // Start a background import of past chats on each host's next start.\n \"autoBackfill\": true,\n // \"piBackfillModel\": \"inherit\", // or \"external\", or \"provider/model\"\n // \"opencodeBackfillModel\": \"inherit\", // or \"external\", or \"provider/model\"\n // Directory maps for history recorded in moved or deleted directories.\n // \"importPathMaps\": [{ \"from\": \"~/code/app-feat-x\", \"to\": \"~/code/app\" }],\n // Unresolved directories to hide on the Directory maps page. They stay unimported.\n // \"importIgnoredDirectories\": [\"/private/tmp/scratch\"],\n // Claude Code's folder, when it is not ~/.claude (like CLAUDE_CONFIG_DIR).\n // \"claudeConfigDir\": \"~/.claude-work\",\n\n // Register the web app to start when you log in.\n \"webServerAutoStart\": true,\n // Enable web UI for managing memories (accessible at http://localhost:4747)\n \"webServerEnabled\": true,\n \n // Port for web UI server\n \"webServerPort\": 4747,\n \n // Host address for web UI (use 127.0.0.1 for local only, 0.0.0.0 for network access)\n \"webServerHost\": \"127.0.0.1\",\n\n // Optional HTTP Basic Auth for the web UI. Accepts literal, env://, or file:// secrets.\n // \"webServerAuthPassword\": \"\",\n // \"webServerAuthUsername\": \"\",\n\n // Deprecated: imported once into the API token table, then no longer read.\n // Create API tokens on the Settings page (Keys and access) instead.\n // \"webServerApiToken\": \"env://OMMS_WEB_TOKEN\",\n \n // ============================================\n // Database Settings\n // ============================================\n \n // Maximum vectors per database shard (auto-creates new shard when limit reached)\n \"maxVectorsPerShard\": 50000,\n \n // Automatically delete old memories based on retention period\n \"autoCleanupEnabled\": true,\n \n // Days to keep memories before auto-cleanup (only if autoCleanupEnabled is true)\n \"autoCleanupRetentionDays\": 30,\n \n // Automatically detect and remove duplicate memories\n \"deduplicationEnabled\": true,\n \n // Similarity threshold (0-1) for detecting duplicates (higher = stricter)\n \"deduplicationSimilarityThreshold\": 0.90,\n \n // ============================================\n // Memory Scope Settings\n // ============================================\n\n // Default scope for memory list/search queries\n // \"project\" keeps queries within the current project, \"all-projects\" searches across all project shards\n \"memory\": {\n \"defaultScope\": \"project\"\n },\n\n // ============================================\n // Model for auto-capture and profile learning (same rule in OpenCode and Pi)\n // ============================================\n\n // Which model summarises your work, in this order:\n // 1. The host model below: opencodeProvider/opencodeModel in OpenCode,\n // piProvider/piModel in Pi. Set the model to \"inherit\" to follow\n // whatever model the session is using, or to \"external\" to send\n // every call to the external API below.\n // 2. If no host model is set: the external API (memoryModel/memoryApiUrl/\n // memoryApiKey further down).\n // 3. If neither is set: the session's own model.\n // If the host model fails and the external API is configured, the external\n // API is used instead.\n //\n // Host models go through OpenCode's or Pi's own sign-in (OAuth like Claude\n // Pro/Max, GitHub Copilot, ChatGPT, or your own key there), so no separate API\n // key is needed here.\n //\n // Examples (OpenCode names from 'opencode providers list'; Pi names from its model list):\n // \"opencodeProvider\": \"anthropic\", \"opencodeModel\": \"claude-haiku-4-5-20251001\"\n // \"opencodeProvider\": \"openai\", \"opencodeModel\": \"inherit\"\n // \"piProvider\": \"openai-codex\", \"piModel\": \"gpt-5.6-luna\"\n //\n // \"opencodeProvider\": \"anthropic\",\n // \"opencodeModel\": \"claude-haiku-4-5-20251001\",\n // \"piProvider\": \"openai-codex\",\n // \"piModel\": \"gpt-5.6-luna\",\n\n // ============================================\n // Auto-Capture Settings\n // ============================================\n \n // Auto-capture runs in the background without blocking your main session.\n // Note: Ollama may not support tool calling. Use OpenAI, Anthropic, or Groq for best results.\n \n \"autoCaptureEnabled\": true,\n \n // Provider type: \"openai-chat\" | \"openai-responses\" | \"anthropic\" | \"minimax\" | \"orcarouter\" | \"google-gemini\"\n // Note: \"openai-chat\" is a generic OpenAI API-compatible mode.\n // Any service that follows the OpenAI Chat Completions API can use it via custom \"memoryApiUrl\".\n \"memoryProvider\": \"openai-chat\",\n \n // External API (step 2 above, and the fallback when a host model fails).\n // Uncomment all 3 lines and replace memoryApiKey before use:\n // \"memoryModel\": \"gpt-4o-mini\",\n // \"memoryApiUrl\": \"https://api.openai.com/v1\",\n // \"memoryApiKey\": \"sk-...\",\n\n // API Key Formats:\n // Direct value: \"sk-...\"\n // From file: \"file://~/.config/litellm-key.txt\"\n // From env variable: \"env://LITELLM_API_KEY\"\n \n // Examples for different providers:\n // Any OpenAI-compatible endpoint can use the \"openai-chat\" provider pattern below.\n // Common examples: DeepSeek, Qwen (via Alibaba Cloud ModelStudio),\n // Zhipu GLM (BigModel platform), and Kimi (Moonshot AI platform).\n\n // OpenAI Chat Completion (default, backward compatible):\n // \"memoryProvider\": \"openai-chat\"\n // \"memoryModel\": \"gpt-4o-mini\"\n // \"memoryApiUrl\": \"https://api.openai.com/v1\"\n // \"memoryApiKey\": \"sk-...\"\n\n // DeepSeek (OpenAI-compatible example):\n // \"memoryProvider\": \"openai-chat\"\n // \"memoryModel\": \"deepseek-chat\"\n // \"memoryApiUrl\": \"https://api.deepseek.com/v1\"\n // \"memoryApiKey\": \"sk-...\"\n \n // OpenAI Responses API (recommended, with session support):\n // \"memoryProvider\": \"openai-responses\"\n // \"memoryModel\": \"gpt-4o\"\n // \"memoryApiUrl\": \"https://api.openai.com/v1\"\n // \"memoryApiKey\": \"sk-...\"\n \n // Anthropic (with session support):\n // \"memoryProvider\": \"anthropic\"\n // \"memoryModel\": \"claude-3-5-haiku-20241022\"\n // \"memoryApiUrl\": \"https://api.anthropic.com/v1\"\n // \"memoryApiKey\": \"sk-ant-...\"\n\n // MiniMax (Anthropic Messages-compatible endpoint, with session support):\n // \"memoryProvider\": \"minimax\"\n // \"memoryModel\": \"MiniMax-M3\"\n // \"memoryApiUrl\": \"https://api.minimax.io\" // global endpoint\n // \"memoryApiKey\": \"<MiniMax API key>\"\n // // China endpoint: \"memoryApiUrl\": \"https://api.minimaxi.com\"\n // // Optional adaptive thinking for MiniMax-M3:\n // \"memoryExtraParams\": { \"thinking\": { \"type\": \"adaptive\" } }\n\n // OrcaRouter (OpenAI-compatible gateway, namespaced model IDs, with session support):\n // \"memoryProvider\": \"orcarouter\"\n // \"memoryApiKey\": \"<OrcaRouter API key>\"\n // // memoryApiUrl and memoryModel are optional \u2014 they default to\n // // https://api.orcarouter.ai/v1 and \"orcarouter/auto\" (a routing alias).\n // // OrcaRouter rejects bare model names, so if you set memoryModel, use a\n // // namespaced ID such as \"openai/gpt-5.5\" or \"deepseek/deepseek-v4-flash\".\n // \"memoryModel\": \"openai/gpt-5.5\"\n\n // Groq (OpenAI-compatible, use openai-chat provider):\n // \"memoryProvider\": \"openai-chat\"\n // \"memoryModel\": \"llama-3.3-70b-versatile\"\n // \"memoryApiUrl\": \"https://api.groq.com/openai/v1\"\n // \"memoryApiKey\": \"gsk_...\"\n \n // Maximum iterations for multi-turn AI analysis (for openai-responses, anthropic, and minimax)\n \"autoCaptureMaxIterations\": 5,\n \n // Timeout per iteration in milliseconds (30 seconds default)\n \"autoCaptureIterationTimeout\": 30000,\n\n // Tries for one turn's capture, on Pi and OpenCode, 2 and 4 seconds apart. After the\n // last one fails, a turn the model could not reach goes to the capture retry queue.\n \"autoCaptureMaxRetries\": 3,\n\n // Maximum UTF-8 bytes for the auto-capture markdown context sent to the summary model.\n // Prevents HTTP 400 context overflows on models with ~131K token windows (e.g. Groq Llama).\n // Rough guide: tokens \u2248 bytes / 4 for mixed code/prose.\n \"autoCaptureMaxContextBytes\": 131072,\n \n // Days to keep AI session history before cleanup\n \"aiSessionRetentionDays\": 7,\n\n // Capture diagnostics: every capture attempt always writes one metadata line\n // (model, stop reason, sizes, outcome) to ~/.omms/omms.log, with no\n // conversation text. Set captureTrace to true to also write each attempt's\n // prompt and raw reply to ~/.omms/traces/ for debugging. Traces can contain\n // conversation content: <private> text and common API key formats are\n // redacted, files are readable only by you, and they are deleted after\n // captureTraceRetentionDays. Only this global file can turn tracing on.\n // \"captureTrace\": false,\n // \"captureTraceRetentionDays\": 7,\n // \"captureAttemptRetentionDays\": 30,\n\n // Skill learning: record each full turn (prompt, replies, tool calls with\n // their outcome, and the skills used) in ~/.omms/data/skills.db, so OMMS can\n // rank your skills and draft better versions. Off by default. A project config\n // can turn it off but never on. No model call is made to record a turn.\n // \"skillLearning\": false,\n // Remove <private> text and common API key formats before a turn is stored.\n // Global config only. Turning this off stores text as written.\n // \"skillLearningRedact\": true,\n // Folders OMMS reads skills from. Absolute or starting with ~/. Global config\n // only. Unset: ~/.agents/skills and the Claude Code folder's skills folder.\n // \"skillFolders\": [\"~/.agents/skills\"],\n\n // Visible recall: the OpenCode terminal TUI and Pi's interactive terminal draw\n // a row for each memory recall. On by default. A project config can turn it\n // off but never on.\n // \"visibleRecall\": true,\n\n // Memory injection, on OpenCode V2, Pi and Claude Code. Each prompt gets the\n // memories that match it. openingContext also searches memory with\n // openingContextQuery and adds the matches to the\n // first message of a new session. The query is global only, trimmed, and\n // 500 characters at most. subagentMemory gives each subagent the memories\n // that match its task. For both switches, a project config can only turn these off.\n // \"openingContext\": false,\n // \"openingContextQuery\": \"project architecture, setup, conventions and key decisions\",\n // \"subagentMemory\": true,\n\n // Capture retry queue: when a live capture fails because the model cannot be\n // reached (network error, timeout, HTTP 408, 429 or 5xx), OMMS keeps a copy of\n // the turn in ~/.omms/data and tries it again later. The copy has <private>\n // text and common API key formats removed. Turns are deleted when the retry\n // ends or after captureRetryRetentionHours (0 to 720). 0 turns the queue off.\n // Only this global file can set it.\n // \"captureRetryRetentionHours\": 72,\n\n // Temperature for AI API requests (set to false to omit parameter for models that don't support it)\n // Some reasoning models (like o1, o3, gpt-5) don't support temperature parameter\n // Set to false and add \"memoryTemperature\": false in config when using such models\n \"memoryTemperature\": 0.3,\n\n // Extra parameters to include in API request body\n // Useful for local inference servers (e.g. llama-server with --jinja) that support\n // additional parameters like disabling thinking/reasoning mode\n // Example for Qwen3 models: { \"enable_thinking\": false }\n // \"memoryExtraParams\": {},\n\n // Language for auto-capture summaries (default: \"auto\" for auto-detection)\n // Options: \"auto\", \"en\", \"id\", \"zh\", \"ja\", \"es\", \"fr\", \"de\", \"ru\", \"pt\", \"ar\", \"ko\"\n // \"autoCaptureLanguage\": \"auto\",\n\n // ============================================\n // Toast Notifications\n // ============================================\n\n // Show toast when memory is auto-captured\n \"showAutoCaptureToasts\": true,\n\n // Show toast when user profile is updated\n \"showUserProfileToasts\": true,\n\n // Show toast for error messages\n \"showErrorToasts\": true,\n\n // ============================================\n // User Profile System\n // ============================================\n\n // Analyze user prompts every N prompts to build/update your user profile\n // When N uncaptured prompts accumulate, AI will analyze them to identify:\n // - User preferences (code style, communication style, tool preferences)\n // - User patterns (recurring topics, problem domains, technical interests)\n // - User workflows (development habits, sequences, learning style)\n // - Skill level (overall and per-domain assessment)\n \"userProfileAnalysisInterval\": 10,\n\n // Days before inactive items (all types) are eligible for removal\n \"userProfileStaleDays\": 2,\n\n // Days before an inactive workflow is eligible for removal. A workflow seen\n // userProfileMinEvidenceForRetention times or more is kept.\n \"userProfileWorkflowStaleDays\": 30,\n\n // Number of preferences shown in UI\n \"userProfileDisplayPreferences\": 20,\n \n // Number of patterns shown in UI\n \"userProfileDisplayPatterns\": 15,\n \n // Number of workflows shown in UI\n \"userProfileDisplayWorkflows\": 10,\n \n // Number of preferences injected into LLM conversation context\n // Keep this small \u2014 the strongest signals are enough; more dilute LLM attention\n \"userProfileInjectPreferences\": 5,\n \n // Number of patterns injected into LLM conversation context\n \"userProfileInjectPatterns\": 5,\n \n // Number of workflows injected into LLM conversation context\n \"userProfileInjectWorkflows\": 3,\n \n // Days before preference confidence starts to decay (if not reinforced)\n // Preferences that aren't seen again will gradually lose confidence and be removed\n \"userProfileConfidenceDecayDays\": 30,\n \n // Number of profile versions to keep in changelog (for rollback/debugging)\n // Older versions are automatically cleaned up\n \"userProfileChangelogRetentionCount\": 5,\n\n // Minimum evidence count for a preference/pattern to survive confidence decay\n // Items confirmed fewer times are more likely to be pruned when confidence decays\n \"userProfileMinEvidenceForRetention\": 3,\n\n // Merge duplicate or vague profile items every N analysed prompts (about 1 model call per 100 items)\n \"userProfileAutoCleanupEnabled\": true,\n \"userProfileAutoCleanupInterval\": 500,\n\n // Enable LLM validation of existing preferences against recent behavior.\n // When enabled, each analysis round checks if top-5 preferences still match recent prompts.\n // Experimental \u2014 disabled by default.\n \"userProfileValidationEnabled\": false,\n\n // ============================================\n // Search Settings\n // ============================================\n \n // Minimum similarity score (0-1) for memory search results. Leave unset to\n // follow the default for your embedding model: 0.5 for qwen3-embedding:0.6b\n // (the only model measured), 0.6 for every other embedder.\n // \"similarityThreshold\": 0.5,\n\n // Maximum number of memories to return in search results.\n // Manual searches can ask for fewer; prompt retrieval uses this ceiling.\n \"maxMemories\": 10,\n\n // ============================================\n // Memory Context Controls\n // ============================================\n\n // Recent memories added at fresh session start (OpenCode V1 and Claude Code).\n // Pi and OpenCode V2 search the store with each prompt instead.\n \"chatMessage\": {\n \"enabled\": true,\n // Recent memories injected at session start.\n \"maxMemories\": 3,\n \"excludeCurrentSession\": true,\n // When to inject: \"first\" message of a session or \"always\".\n // \"injectOn\": \"first\",\n },\n\n // OpenCode profile-learning input limit, in UTF-8 bytes. Smaller values can\n // omit prompts from that input. Does not limit Pi or Claude Code profile input.\n \"userProfileMaxContextBytes\": 32768,\n\n // Shared budget for automatic memory context (profile text, memories, and\n // formatting) across all hosts, in approximate tokens: ceil(UTF-8 bytes / 4).\n // Covers prompt retrieval, recent-memory injection, and session-memory\n // restoration. Not an exact provider token limit or a spending limit.\n \"retrievalMaxTokens\": 2000,\n\n // Restore a session's own memories after compaction and after resume, on\n // OpenCode V2, Pi and Claude Code. memoryLimit is the most memories to\n // restore. A project config can turn it on or off.\n // \"compaction\": { \"enabled\": true, \"memoryLimit\": 10 },\n\n // ============================================\n // Advanced Settings\n // ============================================\n \n // Inject user profile into AI context (preferences, patterns, workflows)\n \"injectProfile\": true\n}\n";
|
package/dist/config-template.js
CHANGED
|
@@ -254,11 +254,21 @@ export const CONFIG_TEMPLATE = `{
|
|
|
254
254
|
// only. Unset: ~/.agents/skills and the Claude Code folder's skills folder.
|
|
255
255
|
// "skillFolders": ["~/.agents/skills"],
|
|
256
256
|
|
|
257
|
-
// Visible recall: the OpenCode
|
|
258
|
-
// each memory recall. On by default. A project config can turn it
|
|
259
|
-
// never on.
|
|
257
|
+
// Visible recall: the OpenCode terminal TUI and Pi's interactive terminal draw
|
|
258
|
+
// a row for each memory recall. On by default. A project config can turn it
|
|
259
|
+
// off but never on.
|
|
260
260
|
// "visibleRecall": true,
|
|
261
261
|
|
|
262
|
+
// Memory injection, on OpenCode V2, Pi and Claude Code. Each prompt gets the
|
|
263
|
+
// memories that match it. openingContext also searches memory with
|
|
264
|
+
// openingContextQuery and adds the matches to the
|
|
265
|
+
// first message of a new session. The query is global only, trimmed, and
|
|
266
|
+
// 500 characters at most. subagentMemory gives each subagent the memories
|
|
267
|
+
// that match its task. For both switches, a project config can only turn these off.
|
|
268
|
+
// "openingContext": false,
|
|
269
|
+
// "openingContextQuery": "project architecture, setup, conventions and key decisions",
|
|
270
|
+
// "subagentMemory": true,
|
|
271
|
+
|
|
262
272
|
// Capture retry queue: when a live capture fails because the model cannot be
|
|
263
273
|
// reached (network error, timeout, HTTP 408, 429 or 5xx), OMMS keeps a copy of
|
|
264
274
|
// the turn in ~/.omms/data and tries it again later. The copy has <private>
|
|
@@ -392,6 +402,11 @@ export const CONFIG_TEMPLATE = `{
|
|
|
392
402
|
// restoration. Not an exact provider token limit or a spending limit.
|
|
393
403
|
"retrievalMaxTokens": 2000,
|
|
394
404
|
|
|
405
|
+
// Restore a session's own memories after compaction and after resume, on
|
|
406
|
+
// OpenCode V2, Pi and Claude Code. memoryLimit is the most memories to
|
|
407
|
+
// restore. A project config can turn it on or off.
|
|
408
|
+
// "compaction": { "enabled": true, "memoryLimit": 10 },
|
|
409
|
+
|
|
395
410
|
// ============================================
|
|
396
411
|
// Advanced Settings
|
|
397
412
|
// ============================================
|
package/dist/config.d.ts
CHANGED
|
@@ -188,6 +188,9 @@ declare function buildConfig(fileConfig: OmmsConfig): {
|
|
|
188
188
|
maxAgeDays: number | undefined;
|
|
189
189
|
injectOn: "first" | "always";
|
|
190
190
|
};
|
|
191
|
+
openingContext: boolean;
|
|
192
|
+
openingContextQuery: string;
|
|
193
|
+
subagentMemory: boolean;
|
|
191
194
|
visibleRecall: boolean;
|
|
192
195
|
skillLearning: boolean;
|
|
193
196
|
skillLearningRedact: boolean;
|
|
@@ -299,6 +302,9 @@ export declare let CONFIG: {
|
|
|
299
302
|
maxAgeDays: number | undefined;
|
|
300
303
|
injectOn: "first" | "always";
|
|
301
304
|
};
|
|
305
|
+
openingContext: boolean;
|
|
306
|
+
openingContextQuery: string;
|
|
307
|
+
subagentMemory: boolean;
|
|
302
308
|
visibleRecall: boolean;
|
|
303
309
|
skillLearning: boolean;
|
|
304
310
|
skillLearningRedact: boolean;
|
package/dist/config.js
CHANGED
|
@@ -11,6 +11,7 @@ import { parseBackfillModel } from "./importer/backfill-model.js";
|
|
|
11
11
|
import { parseIgnoredDirectories, parseImportPathMaps } from "./importer/import-path-maps.js";
|
|
12
12
|
import { normaliseSkillConfig, projectSkillOverride, } from "./services/skill-learning/skill-config.js";
|
|
13
13
|
import * as visibleRecall from "./services/visible-recall-config.js";
|
|
14
|
+
import * as injectionOptions from "./services/injection-options-config.js";
|
|
14
15
|
import { checkedMemoryLimit, MEMORY_LIMITS } from "./utils/memory-limits.js";
|
|
15
16
|
import { defaultSimilarityThreshold } from "./utils/threshold-default.js";
|
|
16
17
|
import { RERANKER_TIMEOUT_DEFAULT_MS } from "./services/request-timeouts.js";
|
|
@@ -31,12 +32,10 @@ const CONFIG_FILES = [
|
|
|
31
32
|
join(OMMS_CONFIG_DIR, "omms.json"),
|
|
32
33
|
...LEGACY_CONFIG_FILES,
|
|
33
34
|
];
|
|
34
|
-
if (!existsSync(OMMS_CONFIG_DIR))
|
|
35
|
+
if (!existsSync(OMMS_CONFIG_DIR))
|
|
35
36
|
mkdirSync(OMMS_CONFIG_DIR, { recursive: true });
|
|
36
|
-
|
|
37
|
-
if (!existsSync(DATA_DIR)) {
|
|
37
|
+
if (!existsSync(DATA_DIR))
|
|
38
38
|
mkdirSync(DATA_DIR, { recursive: true });
|
|
39
|
-
}
|
|
40
39
|
const DEFAULTS = {
|
|
41
40
|
// Default store: ~/.omms/data (see resolveDefaultStoragePath for the
|
|
42
41
|
// legacy-layout fallback while a legacy store exists unmigrated).
|
|
@@ -373,6 +372,7 @@ function buildConfig(fileConfig) {
|
|
|
373
372
|
captureRetryRetentionHours: normalizeCaptureRetryRetentionHours(fileConfig.captureRetryRetentionHours),
|
|
374
373
|
...normaliseSkillConfig(fileConfig),
|
|
375
374
|
...visibleRecall.visibleRecallFromFile(fileConfig),
|
|
375
|
+
...injectionOptions.injectionOptionsFromFile(fileConfig, log),
|
|
376
376
|
autoBackfill: fileConfig.autoBackfill ?? DEFAULTS.autoBackfill,
|
|
377
377
|
opencodeBackfillModel: fileConfig.opencodeBackfillModel ?? DEFAULTS.opencodeBackfillModel,
|
|
378
378
|
piBackfillModel: fileConfig.piBackfillModel ?? DEFAULTS.piBackfillModel,
|
|
@@ -546,6 +546,7 @@ export function initConfig(directory, options = {}) {
|
|
|
546
546
|
delete projectOverrides.skillFolders;
|
|
547
547
|
Object.assign(projectOverrides, skillRule.override);
|
|
548
548
|
visibleRecall.applyProjectVisibleRecall(projectConfig, projectOverrides, directory, log);
|
|
549
|
+
injectionOptions.applyProjectInjectionOptions(projectConfig, projectOverrides, directory, log);
|
|
549
550
|
delete projectOverrides.autoBackfill;
|
|
550
551
|
delete projectOverrides.opencodeBackfillModel;
|
|
551
552
|
delete projectOverrides.piBackfillModel;
|
|
@@ -59,6 +59,8 @@ export interface PackedSection {
|
|
|
59
59
|
/** UTF-8 bytes of `text` (the host wrapper is not part of `text`). */
|
|
60
60
|
bytesUsed: number;
|
|
61
61
|
}
|
|
62
|
+
/** The byte ceiling of a budget: `maxBytes` when set, else `maxTokens` (default 2000) in bytes. */
|
|
63
|
+
export declare function resolveCeiling(options: ContextBudgetOptions): number;
|
|
62
64
|
/**
|
|
63
65
|
* Pack payload blocks into a section that fits one byte ceiling.
|
|
64
66
|
*
|
|
@@ -16,7 +16,8 @@ export function estimateTokens(text) {
|
|
|
16
16
|
export function tokensToByteCeiling(maxTokens) {
|
|
17
17
|
return maxTokens * 4;
|
|
18
18
|
}
|
|
19
|
-
|
|
19
|
+
/** The byte ceiling of a budget: `maxBytes` when set, else `maxTokens` (default 2000) in bytes. */
|
|
20
|
+
export function resolveCeiling(options) {
|
|
20
21
|
if (options.maxBytes !== undefined)
|
|
21
22
|
return options.maxBytes;
|
|
22
23
|
return tokensToByteCeiling(options.maxTokens ?? DEFAULT_RETRIEVAL_MAX_TOKENS);
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type ContextBudgetOptions } from "./context-budget.js";
|
|
2
|
+
/**
|
|
3
|
+
* The opening context (design D1c of change align-recall-host-parity): on the
|
|
4
|
+
* first prompt of a main session, one extra search with the configured query,
|
|
5
|
+
* added as a second retrieval section after the prompt's own. Shared by
|
|
6
|
+
* OpenCode V2, Pi and Claude Code. Hosts read `CONFIG` and pass the values in;
|
|
7
|
+
* this module does not import it, because many tests stub `src/config.js`.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* The opening search query, or null when the option is off or the query is
|
|
11
|
+
* empty. Pass `CONFIG.openingContext` and `CONFIG.openingContextQuery`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function openingQueryFor(options: {
|
|
14
|
+
openingContext: boolean;
|
|
15
|
+
openingContextQuery: string;
|
|
16
|
+
}): string | null;
|
|
17
|
+
export interface FirstPromptSectionsInput {
|
|
18
|
+
prompt: string;
|
|
19
|
+
/** From `openingQueryFor`. Null runs no opening search. */
|
|
20
|
+
openingQuery: string | null;
|
|
21
|
+
directory: string;
|
|
22
|
+
sessionId: string;
|
|
23
|
+
/**
|
|
24
|
+
* The request budget, as `buildRetrievalSection` takes it. `wrapperBytes` is
|
|
25
|
+
* what the host adds around each section, the retrieval tag included; it
|
|
26
|
+
* defaults to the tag alone.
|
|
27
|
+
*/
|
|
28
|
+
budget: ContextBudgetOptions;
|
|
29
|
+
/** Bytes the host adds to the opening section only, such as Claude Code's opening marker. */
|
|
30
|
+
openingReserveBytes: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The sections for the first prompt of a main session, each wrapped in the
|
|
34
|
+
* retrieval tag. The prompt section is `wrapRetrievalSection` of what
|
|
35
|
+
* `buildRetrievalSection` returns for the same budget, when the budget names
|
|
36
|
+
* its `wrapperBytes` as every host passes it. Both searches run in parallel with the same rules
|
|
37
|
+
* (`searchSectionMemories`). The opening section leaves out memories the
|
|
38
|
+
* prompt search found, carries no user profile (the prompt section holds it),
|
|
39
|
+
* and is packed with what the prompt section leaves of the budget, minus
|
|
40
|
+
* `openingReserveBytes`. Either section is null when nothing fits or matches.
|
|
41
|
+
*/
|
|
42
|
+
export declare function buildFirstPromptSections(input: FirstPromptSectionsInput): Promise<{
|
|
43
|
+
promptSection: string | null;
|
|
44
|
+
openingSection: string | null;
|
|
45
|
+
}>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { formatContextForPrompt } from "../services/context.js";
|
|
2
|
+
import { getTags } from "../services/tags.js";
|
|
3
|
+
import { utf8ByteLength } from "../utils/context-limit.js";
|
|
4
|
+
import { resolveCeiling } from "./context-budget.js";
|
|
5
|
+
import { retrievalWrapperBytes, searchablePrompt, searchSectionMemories, wrapRetrievalSection, } from "./retrieval.js";
|
|
6
|
+
/**
|
|
7
|
+
* The opening context (design D1c of change align-recall-host-parity): on the
|
|
8
|
+
* first prompt of a main session, one extra search with the configured query,
|
|
9
|
+
* added as a second retrieval section after the prompt's own. Shared by
|
|
10
|
+
* OpenCode V2, Pi and Claude Code. Hosts read `CONFIG` and pass the values in;
|
|
11
|
+
* this module does not import it, because many tests stub `src/config.js`.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* The opening search query, or null when the option is off or the query is
|
|
15
|
+
* empty. Pass `CONFIG.openingContext` and `CONFIG.openingContextQuery`.
|
|
16
|
+
*/
|
|
17
|
+
export function openingQueryFor(options) {
|
|
18
|
+
if (!options.openingContext)
|
|
19
|
+
return null;
|
|
20
|
+
return options.openingContextQuery.trim() || null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The sections for the first prompt of a main session, each wrapped in the
|
|
24
|
+
* retrieval tag. The prompt section is `wrapRetrievalSection` of what
|
|
25
|
+
* `buildRetrievalSection` returns for the same budget, when the budget names
|
|
26
|
+
* its `wrapperBytes` as every host passes it. Both searches run in parallel with the same rules
|
|
27
|
+
* (`searchSectionMemories`). The opening section leaves out memories the
|
|
28
|
+
* prompt search found, carries no user profile (the prompt section holds it),
|
|
29
|
+
* and is packed with what the prompt section leaves of the budget, minus
|
|
30
|
+
* `openingReserveBytes`. Either section is null when nothing fits or matches.
|
|
31
|
+
*/
|
|
32
|
+
export async function buildFirstPromptSections(input) {
|
|
33
|
+
// A fully private prompt gets no section at all, the opening section included.
|
|
34
|
+
const promptQuery = searchablePrompt(input.prompt);
|
|
35
|
+
if (!promptQuery)
|
|
36
|
+
return { promptSection: null, openingSection: null };
|
|
37
|
+
const tags = getTags(input.directory);
|
|
38
|
+
const [promptSearch, openingSearch] = await Promise.all([
|
|
39
|
+
searchSectionMemories(promptQuery, tags.project.tag, input.sessionId),
|
|
40
|
+
input.openingQuery
|
|
41
|
+
? searchSectionMemories(input.openingQuery, tags.project.tag, input.sessionId)
|
|
42
|
+
: null,
|
|
43
|
+
]);
|
|
44
|
+
const wrapperBytes = input.budget.wrapperBytes ?? retrievalWrapperBytes();
|
|
45
|
+
const promptResults = promptSearch?.results ?? [];
|
|
46
|
+
const promptText = promptResults.length > 0
|
|
47
|
+
? await formatContextForPrompt(tags.user.userEmail || null, { results: promptResults }, { ...input.budget, wrapperBytes }, promptSearch?.queryVector)
|
|
48
|
+
: "";
|
|
49
|
+
const promptIds = new Set(promptResults.map((result) => result.id));
|
|
50
|
+
const openingResults = (openingSearch?.results ?? []).filter((result) => !promptIds.has(result.id));
|
|
51
|
+
const promptBytes = promptText ? utf8ByteLength(promptText) + wrapperBytes : 0;
|
|
52
|
+
const remaining = resolveCeiling(input.budget) - promptBytes - input.openingReserveBytes;
|
|
53
|
+
const openingText = openingResults.length > 0 && remaining > 0
|
|
54
|
+
? await formatContextForPrompt(null, { results: openingResults }, { maxBytes: remaining, wrapperBytes })
|
|
55
|
+
: "";
|
|
56
|
+
return {
|
|
57
|
+
promptSection: promptText ? wrapRetrievalSection(promptText) : null,
|
|
58
|
+
openingSection: openingText ? wrapRetrievalSection(openingText) : null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
/** One memory a recall injected, reduced to what a fold row shows. */
|
|
1
|
+
/** One memory a recall injected, reduced to what a fold row shows. A restored memory has no relevance. */
|
|
2
2
|
export type RecallItem = {
|
|
3
|
-
relevance: number;
|
|
3
|
+
relevance: number | null;
|
|
4
4
|
id?: string;
|
|
5
5
|
headline: string;
|
|
6
6
|
};
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* One recall as OMMS made it: a prompt search, the opening search with the configured query, a
|
|
9
|
+
* restored session after compaction or resume, or the recent memories a session opens with.
|
|
10
|
+
*/
|
|
8
11
|
export type RecallSummary = {
|
|
9
|
-
mode: "search" | "recent";
|
|
12
|
+
mode: "search" | "recent" | "opening" | "restore";
|
|
10
13
|
query: string | null;
|
|
11
14
|
items: RecallItem[];
|
|
12
15
|
/** Per-session counter the v2 reporter sets when it stores the summary; the TUI keys rows by it. */
|
|
@@ -18,10 +21,11 @@ export declare function queryLine(query: string, max?: number): string;
|
|
|
18
21
|
export declare function headline(body: string): string;
|
|
19
22
|
/**
|
|
20
23
|
* Summarise a formatted retrieval section for a host to show. Returns null when the section holds
|
|
21
|
-
* no memory (a profile-only section included), so the host draws nothing. A `
|
|
22
|
-
*
|
|
24
|
+
* no memory (a profile-only section included), so the host draws nothing. A `restore` summary
|
|
25
|
+
* reads the restored-session entries, with no relevance. A `restore` or `recent` recall has no
|
|
26
|
+
* query, whatever the caller passes.
|
|
23
27
|
*/
|
|
24
|
-
export declare function buildRecallSummary(section: string, mode: "
|
|
28
|
+
export declare function buildRecallSummary(section: string, mode: RecallSummary["mode"], query: string | null): RecallSummary | null;
|
|
25
29
|
/** `memory [mode=search, query="...", limit=4]`: the call's name and arguments, as a tool row shows them. */
|
|
26
30
|
export declare function callTitle(summary: RecallSummary): string;
|
|
27
31
|
/** Body of an unfolded row, one string per line, without indentation (the host indents). */
|
|
@@ -14,6 +14,9 @@ export function queryLine(query, max = QUERY_CUT) {
|
|
|
14
14
|
const SECTION_CLOSE = String.raw `<\/project_knowledge>|<\/memory_context>|<\/omms-retrieval>`;
|
|
15
15
|
const MEMORY_ENTRY = new RegExp(String.raw `<memory(?:\s+id="([^"]*)")?\s+relevance="(\d+)%">([\s\S]*?)` +
|
|
16
16
|
String.raw `(?=<\/memory>\s*(?:<memory\s|${SECTION_CLOSE}|$)|${SECTION_CLOSE}|$)`, "g");
|
|
17
|
+
// A restored-session section from `formatMemoriesForCompaction`: `### Memory N (id)`, no relevance.
|
|
18
|
+
// Same rule as the Claude Code parser (`hooks/omms-recall-parse.js`).
|
|
19
|
+
const RESTORED_ENTRY = /### Memory \d+(?: \(([^)\n]+)\))?\n([\s\S]*?)(?=### Memory \d+|<\/omms-retrieval>|$)/g;
|
|
17
20
|
/** One line that names a memory: the first line under `## Request`, else the first line. */
|
|
18
21
|
export function headline(body) {
|
|
19
22
|
const lines = body
|
|
@@ -27,23 +30,25 @@ export function headline(body) {
|
|
|
27
30
|
}
|
|
28
31
|
/**
|
|
29
32
|
* Summarise a formatted retrieval section for a host to show. Returns null when the section holds
|
|
30
|
-
* no memory (a profile-only section included), so the host draws nothing. A `
|
|
31
|
-
*
|
|
33
|
+
* no memory (a profile-only section included), so the host draws nothing. A `restore` summary
|
|
34
|
+
* reads the restored-session entries, with no relevance. A `restore` or `recent` recall has no
|
|
35
|
+
* query, whatever the caller passes.
|
|
32
36
|
*/
|
|
33
37
|
export function buildRecallSummary(section, mode, query) {
|
|
34
38
|
const items = [];
|
|
35
|
-
|
|
36
|
-
|
|
39
|
+
const restore = mode === "restore";
|
|
40
|
+
for (const match of section.matchAll(restore ? RESTORED_ENTRY : MEMORY_ENTRY)) {
|
|
41
|
+
const text = headline((restore ? match[2] : match[3]) ?? "");
|
|
37
42
|
if (!text)
|
|
38
43
|
continue;
|
|
39
|
-
const item = { relevance: Number(match[2]), headline: text };
|
|
44
|
+
const item = { relevance: restore ? null : Number(match[2]), headline: text };
|
|
40
45
|
if (match[1])
|
|
41
46
|
item.id = match[1];
|
|
42
47
|
items.push(item);
|
|
43
48
|
}
|
|
44
49
|
if (items.length === 0)
|
|
45
50
|
return null;
|
|
46
|
-
return { mode, query: mode === "recent" ? null : query, items };
|
|
51
|
+
return { mode, query: restore || mode === "recent" ? null : query, items };
|
|
47
52
|
}
|
|
48
53
|
/** Escape backslashes and double quotes so the quoted value in the title reads as one string. */
|
|
49
54
|
function escapeQuoted(text) {
|
|
@@ -64,8 +69,9 @@ export function unfoldLines(summary) {
|
|
|
64
69
|
lines.push(`query: ${queryLine(summary.query, UNFOLDED_QUERY_CUT)}`);
|
|
65
70
|
lines.push(`limit: ${summary.items.length}`);
|
|
66
71
|
summary.items.forEach((item, index) => {
|
|
67
|
-
const
|
|
68
|
-
|
|
72
|
+
const relevance = item.relevance === null ? "" : `${item.relevance}%`;
|
|
73
|
+
const id = item.id ? `id=${item.id}` : "";
|
|
74
|
+
lines.push(`${index + 1}. ${[relevance, id, item.headline].filter(Boolean).join(" ")}`);
|
|
69
75
|
});
|
|
70
76
|
return lines;
|
|
71
77
|
}
|
package/dist/core/retrieval.d.ts
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
import { type ContextBudgetOptions } from "./context-budget.js";
|
|
2
2
|
export declare const RETRIEVAL_SECTION_TAG = "omms-retrieval";
|
|
3
|
+
/**
|
|
4
|
+
* The search step of every query-driven section (`buildRetrievalSection` and
|
|
5
|
+
* the opening search in `opening-context.ts`), so they share one rule set: the
|
|
6
|
+
* store applies the result limit and the relevance threshold, then memories
|
|
7
|
+
* from the current session are dropped when `chatMessage.excludeCurrentSession`
|
|
8
|
+
* is on. Returns null when the search failed.
|
|
9
|
+
*/
|
|
10
|
+
export declare function searchSectionMemories(query: string, projectTag: string, sessionId: string): Promise<{
|
|
11
|
+
results: any[];
|
|
12
|
+
queryVector?: ArrayLike<number>;
|
|
13
|
+
} | null>;
|
|
14
|
+
/**
|
|
15
|
+
* The prompt text that may reach a search: `<private>` regions removed. Null when nothing is
|
|
16
|
+
* left, so a fully private prompt runs no search and nothing of it reaches an embedding provider.
|
|
17
|
+
*/
|
|
18
|
+
export declare function searchablePrompt(prompt: string): string | null;
|
|
3
19
|
/**
|
|
4
20
|
* Prompt-aware semantic retrieval shared by every host (Pi `before_agent_start`,
|
|
5
21
|
* OpenCode v2 `prompt`/`context` hooks): search the shared project memory with
|
package/dist/core/retrieval.js
CHANGED
|
@@ -2,31 +2,53 @@ import { CONFIG } from "../config.js";
|
|
|
2
2
|
import { formatContextForPrompt } from "../services/context.js";
|
|
3
3
|
import { memoryClient } from "../services/client.js";
|
|
4
4
|
import { getTags } from "../services/tags.js";
|
|
5
|
+
import { isFullyPrivate, stripPrivateContent } from "../services/privacy.js";
|
|
5
6
|
import { utf8ByteLength } from "../utils/context-limit.js";
|
|
6
7
|
import { packContextSection } from "./context-budget.js";
|
|
7
8
|
export const RETRIEVAL_SECTION_TAG = "omms-retrieval";
|
|
8
9
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* the
|
|
12
|
-
*
|
|
10
|
+
* The search step of every query-driven section (`buildRetrievalSection` and
|
|
11
|
+
* the opening search in `opening-context.ts`), so they share one rule set: the
|
|
12
|
+
* store applies the result limit and the relevance threshold, then memories
|
|
13
|
+
* from the current session are dropped when `chatMessage.excludeCurrentSession`
|
|
14
|
+
* is on. Returns null when the search failed.
|
|
13
15
|
*/
|
|
14
|
-
export async function
|
|
15
|
-
if (!prompt.trim())
|
|
16
|
-
return null;
|
|
16
|
+
export async function searchSectionMemories(query, projectTag, sessionId) {
|
|
17
17
|
// Snapshot before the async search: an excludeCurrentSession edit during
|
|
18
18
|
// the search must not change this operation's filtering.
|
|
19
19
|
const excludeCurrentSession = CONFIG.chatMessage.excludeCurrentSession;
|
|
20
|
-
const
|
|
21
|
-
const search = await memoryClient.searchMemories(prompt, tags.project.tag);
|
|
20
|
+
const search = await memoryClient.searchMemories(query, projectTag);
|
|
22
21
|
if (!search.success)
|
|
23
22
|
return null;
|
|
24
23
|
const results = excludeCurrentSession
|
|
25
24
|
? search.results.filter((result) => result.metadata?.sessionID !== sessionId)
|
|
26
25
|
: search.results;
|
|
27
|
-
|
|
26
|
+
return { results, queryVector: search.queryVector };
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The prompt text that may reach a search: `<private>` regions removed. Null when nothing is
|
|
30
|
+
* left, so a fully private prompt runs no search and nothing of it reaches an embedding provider.
|
|
31
|
+
*/
|
|
32
|
+
export function searchablePrompt(prompt) {
|
|
33
|
+
if (isFullyPrivate(prompt))
|
|
34
|
+
return null;
|
|
35
|
+
return stripPrivateContent(prompt).trim() || null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Prompt-aware semantic retrieval shared by every host (Pi `before_agent_start`,
|
|
39
|
+
* OpenCode v2 `prompt`/`context` hooks): search the shared project memory with
|
|
40
|
+
* the incoming prompt and format a bounded context section (memory + user
|
|
41
|
+
* profile). Returns null when nothing relevant is found.
|
|
42
|
+
*/
|
|
43
|
+
export async function buildRetrievalSection(prompt, directory, sessionId, budget) {
|
|
44
|
+
const query = searchablePrompt(prompt);
|
|
45
|
+
if (!query)
|
|
46
|
+
return null;
|
|
47
|
+
const tags = getTags(directory);
|
|
48
|
+
const search = await searchSectionMemories(query, tags.project.tag, sessionId);
|
|
49
|
+
if (!search || search.results.length === 0)
|
|
28
50
|
return null;
|
|
29
|
-
const memoryContext = await formatContextForPrompt(tags.user.userEmail || null, { results }, budget, search.queryVector);
|
|
51
|
+
const memoryContext = await formatContextForPrompt(tags.user.userEmail || null, { results: search.results }, budget, search.queryVector);
|
|
30
52
|
return memoryContext || null;
|
|
31
53
|
}
|
|
32
54
|
/**
|
|
@@ -15,10 +15,11 @@ export declare class ClaudeHookRequestError extends Error {
|
|
|
15
15
|
constructor(message: string);
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* `POST /api/claude/retrieve`:
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
18
|
+
* `POST /api/claude/retrieve`: the retrieval section for a prompt (and the
|
|
19
|
+
* opening section on a session's first prompt, when on), the memories for a
|
|
20
|
+
* starting subagent's task, or the session's own memories after compaction or
|
|
21
|
+
* resume. A fresh or cleared session adds nothing. Every text is wrapped in the
|
|
22
|
+
* retrieval tag; an empty string means nothing to add.
|
|
22
23
|
*/
|
|
23
24
|
export declare function handleClaudeRetrieve(body: unknown, deps?: ClaudeHookDeps): Promise<{
|
|
24
25
|
additionalContext: string;
|