@aislop-inc/opencode-mem 0.0.0-stage → 2.41.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/LICENSE +21 -0
- package/README.md +811 -2
- package/dist/config.d.ts +577 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +1141 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1268 -0
- package/dist/plugin.d.ts +10 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +10 -0
- package/dist/services/ai/ai-provider-factory.d.ts +8 -0
- package/dist/services/ai/ai-provider-factory.d.ts.map +1 -0
- package/dist/services/ai/ai-provider-factory.js +61 -0
- package/dist/services/ai/api-key-placeholder.d.ts +2 -0
- package/dist/services/ai/api-key-placeholder.d.ts.map +1 -0
- package/dist/services/ai/api-key-placeholder.js +14 -0
- package/dist/services/ai/internal-capture-sessions.d.ts +7 -0
- package/dist/services/ai/internal-capture-sessions.d.ts.map +1 -0
- package/dist/services/ai/internal-capture-sessions.js +31 -0
- package/dist/services/ai/opencode-diagnostics.d.ts +8 -0
- package/dist/services/ai/opencode-diagnostics.d.ts.map +1 -0
- package/dist/services/ai/opencode-diagnostics.js +36 -0
- package/dist/services/ai/opencode-host-config.d.ts +11 -0
- package/dist/services/ai/opencode-host-config.d.ts.map +1 -0
- package/dist/services/ai/opencode-host-config.js +51 -0
- package/dist/services/ai/opencode-provider-loader.d.ts +4 -0
- package/dist/services/ai/opencode-provider-loader.d.ts.map +1 -0
- package/dist/services/ai/opencode-provider-loader.js +4 -0
- package/dist/services/ai/opencode-provider.d.ts +154 -0
- package/dist/services/ai/opencode-provider.d.ts.map +1 -0
- package/dist/services/ai/opencode-provider.js +731 -0
- package/dist/services/ai/opencode-sdk-client.d.ts +7 -0
- package/dist/services/ai/opencode-sdk-client.d.ts.map +1 -0
- package/dist/services/ai/opencode-sdk-client.js +38 -0
- package/dist/services/ai/profile-llm-client.d.ts +3 -0
- package/dist/services/ai/profile-llm-client.d.ts.map +1 -0
- package/dist/services/ai/profile-llm-client.js +29 -0
- package/dist/services/ai/provider-config.d.ts +19 -0
- package/dist/services/ai/provider-config.d.ts.map +1 -0
- package/dist/services/ai/provider-config.js +36 -0
- package/dist/services/ai/providers/anthropic-messages.d.ts +35 -0
- package/dist/services/ai/providers/anthropic-messages.d.ts.map +1 -0
- package/dist/services/ai/providers/anthropic-messages.js +220 -0
- package/dist/services/ai/providers/api-route.d.ts +49 -0
- package/dist/services/ai/providers/api-route.d.ts.map +1 -0
- package/dist/services/ai/providers/api-route.js +57 -0
- package/dist/services/ai/providers/atlas-cloud.d.ts +51 -0
- package/dist/services/ai/providers/atlas-cloud.d.ts.map +1 -0
- package/dist/services/ai/providers/atlas-cloud.js +59 -0
- package/dist/services/ai/providers/base-provider.d.ts +33 -0
- package/dist/services/ai/providers/base-provider.d.ts.map +1 -0
- package/dist/services/ai/providers/base-provider.js +24 -0
- package/dist/services/ai/providers/cheaper-inference.d.ts +50 -0
- package/dist/services/ai/providers/cheaper-inference.d.ts.map +1 -0
- package/dist/services/ai/providers/cheaper-inference.js +58 -0
- package/dist/services/ai/providers/cloudgpu.d.ts +52 -0
- package/dist/services/ai/providers/cloudgpu.d.ts.map +1 -0
- package/dist/services/ai/providers/cloudgpu.js +60 -0
- package/dist/services/ai/providers/google-gemini.d.ts +16 -0
- package/dist/services/ai/providers/google-gemini.d.ts.map +1 -0
- package/dist/services/ai/providers/google-gemini.js +228 -0
- package/dist/services/ai/providers/minimax.d.ts +38 -0
- package/dist/services/ai/providers/minimax.d.ts.map +1 -0
- package/dist/services/ai/providers/minimax.js +57 -0
- package/dist/services/ai/providers/openai-chat-completion.d.ts +30 -0
- package/dist/services/ai/providers/openai-chat-completion.d.ts.map +1 -0
- package/dist/services/ai/providers/openai-chat-completion.js +532 -0
- package/dist/services/ai/providers/openai-responses.d.ts +14 -0
- package/dist/services/ai/providers/openai-responses.d.ts.map +1 -0
- package/dist/services/ai/providers/openai-responses.js +182 -0
- package/dist/services/ai/providers/orcarouter.d.ts +52 -0
- package/dist/services/ai/providers/orcarouter.d.ts.map +1 -0
- package/dist/services/ai/providers/orcarouter.js +66 -0
- package/dist/services/ai/providers/runcrate.d.ts +49 -0
- package/dist/services/ai/providers/runcrate.d.ts.map +1 -0
- package/dist/services/ai/providers/runcrate.js +57 -0
- package/dist/services/ai/session/ai-session-manager.d.ts +25 -0
- package/dist/services/ai/session/ai-session-manager.d.ts.map +1 -0
- package/dist/services/ai/session/ai-session-manager.js +180 -0
- package/dist/services/ai/session/session-types.d.ts +43 -0
- package/dist/services/ai/session/session-types.d.ts.map +1 -0
- package/dist/services/ai/session/session-types.js +1 -0
- package/dist/services/ai/tools/tool-schema.d.ts +41 -0
- package/dist/services/ai/tools/tool-schema.d.ts.map +1 -0
- package/dist/services/ai/tools/tool-schema.js +24 -0
- package/dist/services/ai/validators/user-profile-validator.d.ts +13 -0
- package/dist/services/ai/validators/user-profile-validator.d.ts.map +1 -0
- package/dist/services/ai/validators/user-profile-validator.js +114 -0
- package/dist/services/api-handlers.d.ts +277 -0
- package/dist/services/api-handlers.d.ts.map +1 -0
- package/dist/services/api-handlers.js +1740 -0
- package/dist/services/auth-token.d.ts +11 -0
- package/dist/services/auth-token.d.ts.map +1 -0
- package/dist/services/auth-token.js +44 -0
- package/dist/services/auto-capture-config-status.d.ts +15 -0
- package/dist/services/auto-capture-config-status.d.ts.map +1 -0
- package/dist/services/auto-capture-config-status.js +31 -0
- package/dist/services/auto-capture.d.ts +33 -0
- package/dist/services/auto-capture.d.ts.map +1 -0
- package/dist/services/auto-capture.js +906 -0
- package/dist/services/auto-update.d.ts +28 -0
- package/dist/services/auto-update.d.ts.map +1 -0
- package/dist/services/auto-update.js +197 -0
- package/dist/services/capture-evidence-events.d.ts +3 -0
- package/dist/services/capture-evidence-events.d.ts.map +1 -0
- package/dist/services/capture-evidence-events.js +15 -0
- package/dist/services/capture-evidence.d.ts +21 -0
- package/dist/services/capture-evidence.d.ts.map +1 -0
- package/dist/services/capture-evidence.js +168 -0
- package/dist/services/capture-tool-evidence.d.ts +21 -0
- package/dist/services/capture-tool-evidence.d.ts.map +1 -0
- package/dist/services/capture-tool-evidence.js +109 -0
- package/dist/services/cleanup-service.d.ts +26 -0
- package/dist/services/cleanup-service.d.ts.map +1 -0
- package/dist/services/cleanup-service.js +199 -0
- package/dist/services/client.d.ts +167 -0
- package/dist/services/client.d.ts.map +1 -0
- package/dist/services/client.js +535 -0
- package/dist/services/context.d.ts +15 -0
- package/dist/services/context.d.ts.map +1 -0
- package/dist/services/context.js +44 -0
- package/dist/services/cors.d.ts +13 -0
- package/dist/services/cors.d.ts.map +1 -0
- package/dist/services/cors.js +52 -0
- package/dist/services/deduplication-service.d.ts +29 -0
- package/dist/services/deduplication-service.d.ts.map +1 -0
- package/dist/services/deduplication-service.js +113 -0
- package/dist/services/dreaming-lock.d.ts +6 -0
- package/dist/services/dreaming-lock.d.ts.map +1 -0
- package/dist/services/dreaming-lock.js +84 -0
- package/dist/services/dreaming-service.d.ts +96 -0
- package/dist/services/dreaming-service.d.ts.map +1 -0
- package/dist/services/dreaming-service.js +626 -0
- package/dist/services/embedding.d.ts +92 -0
- package/dist/services/embedding.d.ts.map +1 -0
- package/dist/services/embedding.js +467 -0
- package/dist/services/injected-prompt-filter.d.ts +49 -0
- package/dist/services/injected-prompt-filter.d.ts.map +1 -0
- package/dist/services/injected-prompt-filter.js +79 -0
- package/dist/services/jsonc.d.ts +7 -0
- package/dist/services/jsonc.d.ts.map +1 -0
- package/dist/services/jsonc.js +110 -0
- package/dist/services/language-detector.d.ts +3 -0
- package/dist/services/language-detector.d.ts.map +1 -0
- package/dist/services/language-detector.js +33 -0
- package/dist/services/logger.d.ts +15 -0
- package/dist/services/logger.d.ts.map +1 -0
- package/dist/services/logger.js +171 -0
- package/dist/services/markdown/backend.d.ts +35 -0
- package/dist/services/markdown/backend.d.ts.map +1 -0
- package/dist/services/markdown/backend.js +111 -0
- package/dist/services/markdown/document.d.ts +44 -0
- package/dist/services/markdown/document.d.ts.map +1 -0
- package/dist/services/markdown/document.js +159 -0
- package/dist/services/markdown/reconcile.d.ts +26 -0
- package/dist/services/markdown/reconcile.d.ts.map +1 -0
- package/dist/services/markdown/reconcile.js +333 -0
- package/dist/services/markdown/vault.d.ts +32 -0
- package/dist/services/markdown/vault.d.ts.map +1 -0
- package/dist/services/markdown/vault.js +142 -0
- package/dist/services/markdown/watcher.d.ts +22 -0
- package/dist/services/markdown/watcher.d.ts.map +1 -0
- package/dist/services/markdown/watcher.js +131 -0
- package/dist/services/memory-portability-service.d.ts +38 -0
- package/dist/services/memory-portability-service.d.ts.map +1 -0
- package/dist/services/memory-portability-service.js +372 -0
- package/dist/services/memory-provenance.d.ts +16 -0
- package/dist/services/memory-provenance.d.ts.map +1 -0
- package/dist/services/memory-provenance.js +115 -0
- package/dist/services/memory-recall.d.ts +49 -0
- package/dist/services/memory-recall.d.ts.map +1 -0
- package/dist/services/memory-recall.js +196 -0
- package/dist/services/memory-scope.d.ts +17 -0
- package/dist/services/memory-scope.d.ts.map +1 -0
- package/dist/services/memory-scope.js +43 -0
- package/dist/services/migration-service.d.ts +43 -0
- package/dist/services/migration-service.d.ts.map +1 -0
- package/dist/services/migration-service.js +333 -0
- package/dist/services/onnxruntime-resolve.d.ts +25 -0
- package/dist/services/onnxruntime-resolve.d.ts.map +1 -0
- package/dist/services/onnxruntime-resolve.js +176 -0
- package/dist/services/privacy.d.ts +38 -0
- package/dist/services/privacy.d.ts.map +1 -0
- package/dist/services/privacy.js +156 -0
- package/dist/services/request-timeouts.d.ts +4 -0
- package/dist/services/request-timeouts.d.ts.map +1 -0
- package/dist/services/request-timeouts.js +5 -0
- package/dist/services/runtime-require.d.ts +18 -0
- package/dist/services/runtime-require.d.ts.map +1 -0
- package/dist/services/runtime-require.js +75 -0
- package/dist/services/secret-resolver.d.ts +2 -0
- package/dist/services/secret-resolver.d.ts.map +1 -0
- package/dist/services/secret-resolver.js +65 -0
- package/dist/services/shard-inventory-service.d.ts +70 -0
- package/dist/services/shard-inventory-service.d.ts.map +1 -0
- package/dist/services/shard-inventory-service.js +315 -0
- package/dist/services/shard-path-migration-service.d.ts +32 -0
- package/dist/services/shard-path-migration-service.d.ts.map +1 -0
- package/dist/services/shard-path-migration-service.js +386 -0
- package/dist/services/skills/skills-manager.d.ts +39 -0
- package/dist/services/skills/skills-manager.d.ts.map +1 -0
- package/dist/services/skills/skills-manager.js +231 -0
- package/dist/services/skills/types.d.ts +32 -0
- package/dist/services/skills/types.d.ts.map +1 -0
- package/dist/services/skills/types.js +5 -0
- package/dist/services/stats-service.d.ts +71 -0
- package/dist/services/stats-service.d.ts.map +1 -0
- package/dist/services/stats-service.js +288 -0
- package/dist/services/tags.d.ts +30 -0
- package/dist/services/tags.d.ts.map +1 -0
- package/dist/services/tags.js +245 -0
- package/dist/services/transformers-resolve.d.ts +17 -0
- package/dist/services/transformers-resolve.d.ts.map +1 -0
- package/dist/services/transformers-resolve.js +142 -0
- package/dist/services/turso/connection-manager.d.ts +66 -0
- package/dist/services/turso/connection-manager.d.ts.map +1 -0
- package/dist/services/turso/connection-manager.js +408 -0
- package/dist/services/turso/encryption-key.d.ts +17 -0
- package/dist/services/turso/encryption-key.d.ts.map +1 -0
- package/dist/services/turso/encryption-key.js +111 -0
- package/dist/services/turso/encryption-migrator.d.ts +6 -0
- package/dist/services/turso/encryption-migrator.d.ts.map +1 -0
- package/dist/services/turso/encryption-migrator.js +234 -0
- package/dist/services/turso/engine-migrator.d.ts +6 -0
- package/dist/services/turso/engine-migrator.d.ts.map +1 -0
- package/dist/services/turso/engine-migrator.js +318 -0
- package/dist/services/turso/error-classifiers.d.ts +4 -0
- package/dist/services/turso/error-classifiers.d.ts.map +1 -0
- package/dist/services/turso/error-classifiers.js +19 -0
- package/dist/services/turso/legacy-migrator.d.ts +2 -0
- package/dist/services/turso/legacy-migrator.d.ts.map +1 -0
- package/dist/services/turso/legacy-migrator.js +535 -0
- package/dist/services/turso/lifecycle.d.ts +11 -0
- package/dist/services/turso/lifecycle.d.ts.map +1 -0
- package/dist/services/turso/lifecycle.js +32 -0
- package/dist/services/turso/operation-lock.d.ts +26 -0
- package/dist/services/turso/operation-lock.d.ts.map +1 -0
- package/dist/services/turso/operation-lock.js +188 -0
- package/dist/services/turso/plugin-refs.d.ts +13 -0
- package/dist/services/turso/plugin-refs.d.ts.map +1 -0
- package/dist/services/turso/plugin-refs.js +43 -0
- package/dist/services/turso/ready.d.ts +3 -0
- package/dist/services/turso/ready.d.ts.map +1 -0
- package/dist/services/turso/ready.js +32 -0
- package/dist/services/turso/schema-migrations.d.ts +24 -0
- package/dist/services/turso/schema-migrations.d.ts.map +1 -0
- package/dist/services/turso/schema-migrations.js +367 -0
- package/dist/services/turso/shard-manager.d.ts +41 -0
- package/dist/services/turso/shard-manager.d.ts.map +1 -0
- package/dist/services/turso/shard-manager.js +419 -0
- package/dist/services/turso/sqlite-handle-release.d.ts +31 -0
- package/dist/services/turso/sqlite-handle-release.d.ts.map +1 -0
- package/dist/services/turso/sqlite-handle-release.js +101 -0
- package/dist/services/turso/turso-db.d.ts +61 -0
- package/dist/services/turso/turso-db.d.ts.map +1 -0
- package/dist/services/turso/turso-db.js +214 -0
- package/dist/services/turso/types.d.ts +52 -0
- package/dist/services/turso/types.d.ts.map +1 -0
- package/dist/services/turso/types.js +1 -0
- package/dist/services/turso/vector-search.d.ts +63 -0
- package/dist/services/turso/vector-search.d.ts.map +1 -0
- package/dist/services/turso/vector-search.js +510 -0
- package/dist/services/turso/vector-utils.d.ts +16 -0
- package/dist/services/turso/vector-utils.d.ts.map +1 -0
- package/dist/services/turso/vector-utils.js +98 -0
- package/dist/services/turso/wal-index-recovery.d.ts +51 -0
- package/dist/services/turso/wal-index-recovery.d.ts.map +1 -0
- package/dist/services/turso/wal-index-recovery.js +248 -0
- package/dist/services/update-on-capture.d.ts +77 -0
- package/dist/services/update-on-capture.d.ts.map +1 -0
- package/dist/services/update-on-capture.js +116 -0
- package/dist/services/user-memory-learning.d.ts +137 -0
- package/dist/services/user-memory-learning.d.ts.map +1 -0
- package/dist/services/user-memory-learning.js +787 -0
- package/dist/services/user-profile/ai-cleanup.d.ts +59 -0
- package/dist/services/user-profile/ai-cleanup.d.ts.map +1 -0
- package/dist/services/user-profile/ai-cleanup.js +488 -0
- package/dist/services/user-profile/learning-lock.d.ts +41 -0
- package/dist/services/user-profile/learning-lock.d.ts.map +1 -0
- package/dist/services/user-profile/learning-lock.js +619 -0
- package/dist/services/user-profile/profile-context.d.ts +2 -0
- package/dist/services/user-profile/profile-context.d.ts.map +1 -0
- package/dist/services/user-profile/profile-context.js +105 -0
- package/dist/services/user-profile/profile-utils.d.ts +17 -0
- package/dist/services/user-profile/profile-utils.d.ts.map +1 -0
- package/dist/services/user-profile/profile-utils.js +77 -0
- package/dist/services/user-profile/types.d.ts +93 -0
- package/dist/services/user-profile/types.d.ts.map +1 -0
- package/dist/services/user-profile/types.js +1 -0
- package/dist/services/user-profile/user-profile-manager.d.ts +106 -0
- package/dist/services/user-profile/user-profile-manager.d.ts.map +1 -0
- package/dist/services/user-profile/user-profile-manager.js +1793 -0
- package/dist/services/user-prompt/user-prompt-manager.d.ts +64 -0
- package/dist/services/user-prompt/user-prompt-manager.d.ts.map +1 -0
- package/dist/services/user-prompt/user-prompt-manager.js +428 -0
- package/dist/services/web-api-auth.d.ts +4 -0
- package/dist/services/web-api-auth.d.ts.map +1 -0
- package/dist/services/web-api-auth.js +24 -0
- package/dist/services/web-auth.d.ts +47 -0
- package/dist/services/web-auth.d.ts.map +1 -0
- package/dist/services/web-auth.js +105 -0
- package/dist/services/web-server.d.ts +58 -0
- package/dist/services/web-server.d.ts.map +1 -0
- package/dist/services/web-server.js +774 -0
- package/dist/shared/api/index.d.ts +5 -0
- package/dist/shared/api/index.d.ts.map +1 -0
- package/dist/shared/api/index.js +2 -0
- package/dist/shared/api/portability-schemas.d.ts +57 -0
- package/dist/shared/api/portability-schemas.d.ts.map +1 -0
- package/dist/shared/api/portability-schemas.js +39 -0
- package/dist/shared/api/schemas.d.ts +296 -0
- package/dist/shared/api/schemas.d.ts.map +1 -0
- package/dist/shared/api/schemas.js +134 -0
- package/dist/shared/api/types.d.ts +29 -0
- package/dist/shared/api/types.d.ts.map +1 -0
- package/dist/shared/api/types.js +1 -0
- package/dist/tui.d.ts +10 -0
- package/dist/tui.d.ts.map +1 -0
- package/dist/tui.js +17 -0
- package/dist/types/index.d.ts +19 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +1 -0
- package/dist/utils/context-limit.d.ts +11 -0
- package/dist/utils/context-limit.d.ts.map +1 -0
- package/dist/utils/context-limit.js +43 -0
- package/dist/utils/math.d.ts +8 -0
- package/dist/utils/math.d.ts.map +1 -0
- package/dist/utils/math.js +48 -0
- package/dist/utils/profile.d.ts +3 -0
- package/dist/utils/profile.d.ts.map +1 -0
- package/dist/utils/profile.js +15 -0
- package/dist/v2/adapter.d.ts +3 -0
- package/dist/v2/adapter.d.ts.map +1 -0
- package/dist/v2/adapter.js +217 -0
- package/dist/v2/legacy-client.d.ts +22 -0
- package/dist/v2/legacy-client.d.ts.map +1 -0
- package/dist/v2/legacy-client.js +410 -0
- package/dist/v2/plugin.d.ts +4 -0
- package/dist/v2/plugin.d.ts.map +1 -0
- package/dist/v2/plugin.js +34 -0
- package/dist/v2/toast-rpc.d.ts +43 -0
- package/dist/v2/toast-rpc.d.ts.map +1 -0
- package/dist/v2/toast-rpc.js +26 -0
- package/dist/web/accent-preview.html +444 -0
- package/dist/web/assets/index-mTgxOb5l.css +2 -0
- package/dist/web/assets/index-ysje17yK.js +109 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/favicon.svg +11 -0
- package/dist/web/index.html +29 -0
- package/dist/web/opencode-mem-icon.png +0 -0
- package/package.json +122 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1268 @@
|
|
|
1
|
+
import { tool } from "@opencode-ai/plugin";
|
|
2
|
+
import { memoryClient } from "./services/client.js";
|
|
3
|
+
import { formatContextForPrompt } from "./services/context.js";
|
|
4
|
+
import { shouldRefreshRecallOnPrompt } from "./services/memory-recall.js";
|
|
5
|
+
import { buildMemoryProvenanceSuffix } from "./services/memory-provenance.js";
|
|
6
|
+
import { getTags } from "./services/tags.js";
|
|
7
|
+
import { stripPrivateContent, isFullyPrivate, sanitizeMemoryContent } from "./services/privacy.js";
|
|
8
|
+
import { awaitCaptureDrain, performAutoCapture } from "./services/auto-capture.js";
|
|
9
|
+
import { CaptureEvidenceRecorder } from "./services/capture-evidence.js";
|
|
10
|
+
import { performUserProfileLearning } from "./services/user-memory-learning.js";
|
|
11
|
+
import { userPromptManager } from "./services/user-prompt/user-prompt-manager.js";
|
|
12
|
+
import { startWebServer, WebServer } from "./services/web-server.js";
|
|
13
|
+
import { ensureTursoReady } from "./services/turso/ready.js";
|
|
14
|
+
import { tursoConnectionManager } from "./services/turso/connection-manager.js";
|
|
15
|
+
import { retainPluginTurso } from "./services/turso/plugin-refs.js";
|
|
16
|
+
import { WebAuth } from "./services/web-auth.js";
|
|
17
|
+
import { isConfigured, CONFIG, initConfig } from "./config.js";
|
|
18
|
+
import { log } from "./services/logger.js";
|
|
19
|
+
import { getLanguageName } from "./services/language-detector.js";
|
|
20
|
+
import { filterInjectedParts } from "./services/injected-prompt-filter.js";
|
|
21
|
+
import { getHostClientConfig } from "./services/ai/opencode-host-config.js";
|
|
22
|
+
import { loadOpencodeProvider } from "./services/ai/opencode-provider-loader.js";
|
|
23
|
+
import { isInternalStructuredSession, noteStructuredOutputStep, rememberSessionModel, STRUCTURED_OUTPUT_AGENT, STRUCTURED_OUTPUT_MAX_STEPS, STRUCTURED_OUTPUT_TOOLS, } from "./services/ai/opencode-provider.js";
|
|
24
|
+
import { INTERNAL_CAPTURE_SESSION_TITLE, isInternalCaptureSessionTitle, isTrackedInternalCaptureSession, } from "./services/ai/internal-capture-sessions.js";
|
|
25
|
+
import { notifyAutoCaptureProviderStatus } from "./services/auto-capture-config-status.js";
|
|
26
|
+
export { INTERNAL_CAPTURE_SESSION_TITLE, isInternalCaptureSessionTitle };
|
|
27
|
+
export { buildAutoCaptureConfigReminderMessage, notifyAutoCaptureProviderStatus, } from "./services/auto-capture-config-status.js";
|
|
28
|
+
export function isStructuredSummaryPromptMessage(userMessage) {
|
|
29
|
+
// This is the plugin's own structured-summary or profile-analysis request.
|
|
30
|
+
// OpenCode echoes it through chat.message like a normal user message, but
|
|
31
|
+
// capturing it would create self-referential memories / an infinite learning loop.
|
|
32
|
+
if (userMessage.includes("# User Profile Analysis")) {
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
return userMessage.includes("Analyze this conversation.") && userMessage.includes('type="skip"');
|
|
36
|
+
}
|
|
37
|
+
function extractSessionTitle(response) {
|
|
38
|
+
if (!response || typeof response !== "object")
|
|
39
|
+
return undefined;
|
|
40
|
+
const obj = response;
|
|
41
|
+
return obj.data?.title ?? obj.title;
|
|
42
|
+
}
|
|
43
|
+
function unwrapSdkData(response) {
|
|
44
|
+
if (!response || typeof response !== "object")
|
|
45
|
+
return undefined;
|
|
46
|
+
const obj = response;
|
|
47
|
+
return (obj.data ?? response);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Resolve the session's active agent so compaction memory injection does not
|
|
51
|
+
* reset OpenCode to the stock "general-purpose" fallback (issue #236).
|
|
52
|
+
*
|
|
53
|
+
* Preference order:
|
|
54
|
+
* 1. session.get().agent (v2 hosts)
|
|
55
|
+
* 2. Latest non-compaction user message agent
|
|
56
|
+
* 3. Latest non-compaction / non-summary assistant mode (v1) or agent (v2)
|
|
57
|
+
*/
|
|
58
|
+
export async function resolveSessionAgent(client, sessionID) {
|
|
59
|
+
const sessionClient = client?.session;
|
|
60
|
+
if (typeof sessionClient?.get === "function") {
|
|
61
|
+
try {
|
|
62
|
+
const session = unwrapSdkData(await sessionClient.get({ path: { id: sessionID } }));
|
|
63
|
+
if (typeof session?.agent === "string" && session.agent.trim()) {
|
|
64
|
+
return session.agent.trim();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
log("resolveSessionAgent: session.get failed", { sessionID, error: String(error) });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (typeof sessionClient?.messages !== "function") {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const messages = unwrapSdkData(await sessionClient.messages({ path: { id: sessionID } }));
|
|
76
|
+
if (!Array.isArray(messages))
|
|
77
|
+
return undefined;
|
|
78
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
79
|
+
const info = messages[i]?.info;
|
|
80
|
+
if (!info)
|
|
81
|
+
continue;
|
|
82
|
+
if (info.role === "user") {
|
|
83
|
+
if (typeof info.agent === "string" && info.agent.trim()) {
|
|
84
|
+
return info.agent.trim();
|
|
85
|
+
}
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (info.role === "assistant") {
|
|
89
|
+
if (info.summary === true || info.mode === "compaction")
|
|
90
|
+
continue;
|
|
91
|
+
const agent = (typeof info.agent === "string" && info.agent.trim()) ||
|
|
92
|
+
(typeof info.mode === "string" && info.mode.trim()) ||
|
|
93
|
+
undefined;
|
|
94
|
+
if (agent)
|
|
95
|
+
return agent;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
log("resolveSessionAgent: session.messages failed", { sessionID, error: String(error) });
|
|
101
|
+
}
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Resolve the session's current model (the server-side `session.model`, written by the most
|
|
106
|
+
* recent real user message and left untouched by compaction). Compaction memory injection must
|
|
107
|
+
* pass it explicitly: OpenCode resolves `input.model ?? agent.model ?? session.model`, so when the
|
|
108
|
+
* active agent declares its own model the injected message would otherwise switch the session to
|
|
109
|
+
* that agent's default model and variant.
|
|
110
|
+
*/
|
|
111
|
+
export async function resolveSessionModel(client, sessionID) {
|
|
112
|
+
const sessionClient = client
|
|
113
|
+
?.session;
|
|
114
|
+
if (typeof sessionClient?.get !== "function")
|
|
115
|
+
return undefined;
|
|
116
|
+
try {
|
|
117
|
+
const session = unwrapSdkData(await sessionClient.get({ path: { id: sessionID } }));
|
|
118
|
+
const model = session?.model;
|
|
119
|
+
if (typeof model?.providerID !== "string" || typeof model?.id !== "string")
|
|
120
|
+
return undefined;
|
|
121
|
+
const variant = typeof model.variant === "string" && model.variant && model.variant !== "default"
|
|
122
|
+
? model.variant
|
|
123
|
+
: undefined;
|
|
124
|
+
return {
|
|
125
|
+
model: { providerID: model.providerID, modelID: model.id },
|
|
126
|
+
...(variant ? { variant } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
log("resolveSessionModel: session.get failed", { sessionID, error: String(error) });
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async function isInternalCaptureSession(client, sessionID) {
|
|
135
|
+
// Fast path: sessions we created ourselves (survives brief post-delete window).
|
|
136
|
+
if (isTrackedInternalCaptureSession(sessionID)) {
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
const sessionClient = client?.session;
|
|
140
|
+
// Plugin host client uses path-based args (same as session.messages).
|
|
141
|
+
if (typeof sessionClient?.get === "function") {
|
|
142
|
+
try {
|
|
143
|
+
const response = await sessionClient.get({ path: { id: sessionID } });
|
|
144
|
+
const title = extractSessionTitle(response);
|
|
145
|
+
if (isInternalCaptureSessionTitle(title)) {
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
log("internal capture session check via session.get", {
|
|
149
|
+
sessionID,
|
|
150
|
+
title: title ?? null,
|
|
151
|
+
matched: false,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
log("internal capture session check via session.get failed", {
|
|
156
|
+
sessionID,
|
|
157
|
+
error: String(error),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
log("internal capture session check: session.get unavailable", { sessionID });
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Bounded per-plugin cache of sessionID → has-parentID lookups. parentID never
|
|
168
|
+
* changes for a session, so each session pays one session.get across all its
|
|
169
|
+
* messages instead of one per message.
|
|
170
|
+
*/
|
|
171
|
+
const CHILD_SESSION_LOOKUPS = new Map();
|
|
172
|
+
const CHILD_SESSION_LOOKUP_CACHE_LIMIT = 1000;
|
|
173
|
+
function extractSessionParentID(response) {
|
|
174
|
+
if (!response || typeof response !== "object")
|
|
175
|
+
return undefined;
|
|
176
|
+
const obj = response;
|
|
177
|
+
const parentID = obj.data?.parentID ?? obj.parentID;
|
|
178
|
+
// Empty string is not a real parent link (OpenCode uses a non-empty id).
|
|
179
|
+
return typeof parentID === "string" && parentID.length > 0 ? parentID : undefined;
|
|
180
|
+
}
|
|
181
|
+
async function isChildSession(client, sessionID) {
|
|
182
|
+
const cached = CHILD_SESSION_LOOKUPS.get(sessionID);
|
|
183
|
+
if (cached !== undefined)
|
|
184
|
+
return cached;
|
|
185
|
+
const sessionClient = client?.session;
|
|
186
|
+
if (typeof sessionClient?.get !== "function") {
|
|
187
|
+
// Fail open (capture proceeds) — same behaviour as before this check existed.
|
|
188
|
+
log("child session check: session.get unavailable", { sessionID });
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
const hasParent = extractSessionParentID(await sessionClient.get({ path: { id: sessionID } })) !== undefined;
|
|
193
|
+
if (CHILD_SESSION_LOOKUPS.size >= CHILD_SESSION_LOOKUP_CACHE_LIMIT) {
|
|
194
|
+
// Insertion-order eviction keeps the map bounded without timers.
|
|
195
|
+
const oldest = CHILD_SESSION_LOOKUPS.keys().next().value;
|
|
196
|
+
if (oldest !== undefined)
|
|
197
|
+
CHILD_SESSION_LOOKUPS.delete(oldest);
|
|
198
|
+
}
|
|
199
|
+
CHILD_SESSION_LOOKUPS.set(sessionID, hasParent);
|
|
200
|
+
return hasParent;
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
// Fail open on lookup failure and do not cache: a transient host error
|
|
204
|
+
// must not permanently misclassify the session.
|
|
205
|
+
log("child session check via session.get failed", { sessionID, error: String(error) });
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Least-privilege agent used only by internal structured-output sessions (issue #189). */
|
|
210
|
+
export function applyStructuredOutputAgentConfig(cfg) {
|
|
211
|
+
cfg.agent = {
|
|
212
|
+
...cfg.agent,
|
|
213
|
+
[STRUCTURED_OUTPUT_AGENT]: {
|
|
214
|
+
description: "Internal least-privilege agent for opencode-mem structured output",
|
|
215
|
+
mode: "subagent",
|
|
216
|
+
// OpenCode reads `steps` at runtime; SDK AgentConfig also documents maxSteps.
|
|
217
|
+
steps: STRUCTURED_OUTPUT_MAX_STEPS,
|
|
218
|
+
maxSteps: STRUCTURED_OUTPUT_MAX_STEPS,
|
|
219
|
+
tools: STRUCTURED_OUTPUT_TOOLS,
|
|
220
|
+
permission: {
|
|
221
|
+
"*": "deny",
|
|
222
|
+
StructuredOutput: "allow",
|
|
223
|
+
},
|
|
224
|
+
// OpenCode maps format:json_schema to tool_choice:"required". Thinking-enabled
|
|
225
|
+
// models (e.g. DeepSeek V4) reject that combo — disable thinking for this
|
|
226
|
+
// internal agent so auto-capture / profile learning can force StructuredOutput (#253).
|
|
227
|
+
options: {
|
|
228
|
+
thinking: { type: "disabled" },
|
|
229
|
+
},
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Force-disable thinking on structured-output chat.params after OpenCode merges
|
|
235
|
+
* model/agent/variant options. A user reasoning variant merges last and can
|
|
236
|
+
* otherwise re-enable thinking (#253).
|
|
237
|
+
*/
|
|
238
|
+
export function applyStructuredOutputChatParams(input, output) {
|
|
239
|
+
if (!output || input.agent !== STRUCTURED_OUTPUT_AGENT)
|
|
240
|
+
return;
|
|
241
|
+
output.options = {
|
|
242
|
+
...(output.options ?? {}),
|
|
243
|
+
thinking: { type: "disabled" },
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
export async function configureOpencodeHostTransport(ctx) {
|
|
247
|
+
const { createV2Client, resetHostFetch, setHostFetch, setV2Client, setStructuredOutputTimeoutConfig, } = await loadOpencodeProvider();
|
|
248
|
+
resetHostFetch();
|
|
249
|
+
// Configured structured-output timeout (opencodeTimeoutMs): injected here so
|
|
250
|
+
// the lazily-bundled provider module never imports config.js (whose import
|
|
251
|
+
// side effects would leak into subprocess gates and loader bundles).
|
|
252
|
+
setStructuredOutputTimeoutConfig(CONFIG.opencodeTimeoutMs);
|
|
253
|
+
const hostConfig = getHostClientConfig(ctx);
|
|
254
|
+
if (hostConfig.fetch) {
|
|
255
|
+
setHostFetch(hostConfig.fetch);
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
log("OpenCode host fetch unavailable; falling back to global fetch", {
|
|
259
|
+
clientKeys: hostConfig.clientKeys,
|
|
260
|
+
sdkConfigCount: hostConfig.sdkConfigCount,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
const serverUrl = hostConfig.baseUrl ?? ctx.serverUrl;
|
|
264
|
+
if (serverUrl) {
|
|
265
|
+
setV2Client(createV2Client(serverUrl, {
|
|
266
|
+
fetch: hostConfig.fetch,
|
|
267
|
+
headers: hostConfig.headers,
|
|
268
|
+
}));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
export const OpenCodeMemPlugin = async (ctx) => {
|
|
272
|
+
const { directory } = ctx;
|
|
273
|
+
initConfig(directory);
|
|
274
|
+
notifyAutoCaptureProviderStatus(ctx.client);
|
|
275
|
+
const { startAutoUpdate } = await import("./services/auto-update.js");
|
|
276
|
+
startAutoUpdate(ctx, CONFIG.autoUpdate);
|
|
277
|
+
const tags = getTags(directory);
|
|
278
|
+
let webServer = null;
|
|
279
|
+
// One idle debounce timer per session: a new idle for the same session resets
|
|
280
|
+
// its own timer, but must never cancel another session's pending capture
|
|
281
|
+
// (starving a finished session's summary forever once no further idle
|
|
282
|
+
// events arrive).
|
|
283
|
+
const idleTimers = new Map();
|
|
284
|
+
// Aborted on plugin dispose: queued-but-not-started auto-capture jobs are
|
|
285
|
+
// skipped; in-flight work keeps its original (uncancellable) semantics.
|
|
286
|
+
const pluginLifetime = new AbortController();
|
|
287
|
+
let cleanedUp = false;
|
|
288
|
+
const captureEvidence = new CaptureEvidenceRecorder(directory);
|
|
289
|
+
const resumePendingCaptures = async () => {
|
|
290
|
+
if (cleanedUp || !isConfigured() || !CONFIG.autoCaptureEnabled)
|
|
291
|
+
return;
|
|
292
|
+
try {
|
|
293
|
+
for (const sessionID of await userPromptManager.getPendingCaptureSessions(directory)) {
|
|
294
|
+
if (cleanedUp)
|
|
295
|
+
break;
|
|
296
|
+
await performAutoCapture(ctx, sessionID, directory, {
|
|
297
|
+
signal: pluginLifetime.signal,
|
|
298
|
+
preferSavedEvidence: true,
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
log("Pending capture recovery deferred", { error: String(error) });
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
// Lease the shared Turso pool for this plugin instance. Several OpenCode
|
|
307
|
+
// sessions share one process; dispose must not closeAll while siblings live (#443).
|
|
308
|
+
retainPluginTurso();
|
|
309
|
+
const GLOBAL_PLUGIN_WARMUP_KEY = Symbol.for("opencode-mem.plugin.warmedup");
|
|
310
|
+
if (!globalThis[GLOBAL_PLUGIN_WARMUP_KEY] && isConfigured()) {
|
|
311
|
+
// Fire-and-forget: DB ready + embedding model must not block plugin init.
|
|
312
|
+
(async () => {
|
|
313
|
+
try {
|
|
314
|
+
await memoryClient.warmup();
|
|
315
|
+
globalThis[GLOBAL_PLUGIN_WARMUP_KEY] = true;
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
log("Plugin memory warmup failed", { error: String(error) });
|
|
319
|
+
}
|
|
320
|
+
})();
|
|
321
|
+
}
|
|
322
|
+
await configureOpencodeHostTransport(ctx);
|
|
323
|
+
// Re-reads the provider directory into the connectivity snapshot. Errors
|
|
324
|
+
// are logged and the previous snapshot retained. The host registers
|
|
325
|
+
// user-config providers after plugin setup (provider.updated/model.updated),
|
|
326
|
+
// so this runs again on those events and on connectivity-gate misses.
|
|
327
|
+
const refreshConnectedProviders = async () => {
|
|
328
|
+
try {
|
|
329
|
+
const providerResult = await ctx.client.provider.list();
|
|
330
|
+
if (providerResult.data?.connected) {
|
|
331
|
+
const { setConnectedProviders } = await loadOpencodeProvider();
|
|
332
|
+
setConnectedProviders(providerResult.data.connected);
|
|
333
|
+
log("opencode providers connected", {
|
|
334
|
+
list: providerResult.data.connected,
|
|
335
|
+
configured: CONFIG.opencodeProvider || "(not set)",
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
log("opencode provider list empty or failed", {
|
|
340
|
+
data: JSON.stringify(providerResult.data).substring(0, 100),
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
log("Failed to refresh opencode provider state", { error: String(error) });
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
// Coalesce refresh triggers into one in-flight pass plus trailing drain.
|
|
349
|
+
// Event handlers and ensureProviderConnected (gate miss) share this path so
|
|
350
|
+
// concurrent list() calls collapse; callers can await the same promise.
|
|
351
|
+
let refreshInFlight;
|
|
352
|
+
let refreshQueued = false;
|
|
353
|
+
const runCoalescedRefresh = () => {
|
|
354
|
+
refreshQueued = true;
|
|
355
|
+
if (refreshInFlight)
|
|
356
|
+
return refreshInFlight;
|
|
357
|
+
refreshInFlight = (async () => {
|
|
358
|
+
while (refreshQueued && !cleanedUp) {
|
|
359
|
+
refreshQueued = false;
|
|
360
|
+
await refreshConnectedProviders();
|
|
361
|
+
void resumePendingCaptures();
|
|
362
|
+
}
|
|
363
|
+
})().finally(() => {
|
|
364
|
+
refreshInFlight = undefined;
|
|
365
|
+
if (refreshQueued && !cleanedUp) {
|
|
366
|
+
void runCoalescedRefresh();
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
return refreshInFlight;
|
|
370
|
+
};
|
|
371
|
+
void runCoalescedRefresh();
|
|
372
|
+
// Gate miss awaits the same coalesced refresh; cleared on dispose so no
|
|
373
|
+
// refresh fires afterwards. Only clear our own refresher identity.
|
|
374
|
+
const { setConnectedProvidersRefresher, clearConnectedProvidersRefresher } = await loadOpencodeProvider();
|
|
375
|
+
const providerRefresher = async () => {
|
|
376
|
+
await runCoalescedRefresh();
|
|
377
|
+
};
|
|
378
|
+
setConnectedProvidersRefresher(providerRefresher);
|
|
379
|
+
const clearProviderRefreshWiring = () => {
|
|
380
|
+
clearConnectedProvidersRefresher(providerRefresher);
|
|
381
|
+
};
|
|
382
|
+
let tursoReadyForWeb = !isConfigured();
|
|
383
|
+
if (CONFIG.webServerEnabled && isConfigured()) {
|
|
384
|
+
try {
|
|
385
|
+
await ensureTursoReady();
|
|
386
|
+
tursoReadyForWeb = true;
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
log("Turso ready gate failed before web server start", { error: String(error) });
|
|
390
|
+
if (ctx.client?.tui) {
|
|
391
|
+
const { isTursoMultiProcessLockError } = await import("./services/turso/connection-manager.js");
|
|
392
|
+
const lockHeld = isTursoMultiProcessLockError(error);
|
|
393
|
+
ctx.client.tui
|
|
394
|
+
.showToast({
|
|
395
|
+
body: {
|
|
396
|
+
title: "Memory Explorer",
|
|
397
|
+
message: lockHeld
|
|
398
|
+
? process.platform === "win32"
|
|
399
|
+
? "Memory DB locked by another OpenCode session (Windows is single-owner)"
|
|
400
|
+
: "Memory DB locked by another session — close it or restart all OpenCode windows"
|
|
401
|
+
: "Database migration failed; web UI not started",
|
|
402
|
+
variant: "error",
|
|
403
|
+
duration: 8000,
|
|
404
|
+
},
|
|
405
|
+
})
|
|
406
|
+
.catch(() => { });
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (isConfigured() && CONFIG.memoryBackend === "markdown") {
|
|
411
|
+
try {
|
|
412
|
+
if (!tursoReadyForWeb) {
|
|
413
|
+
await ensureTursoReady();
|
|
414
|
+
tursoReadyForWeb = true;
|
|
415
|
+
}
|
|
416
|
+
const { startMarkdownBackend } = await import("./services/markdown/backend.js");
|
|
417
|
+
await startMarkdownBackend();
|
|
418
|
+
}
|
|
419
|
+
catch (mdError) {
|
|
420
|
+
log("Markdown backend failed to start", { error: String(mdError) });
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (CONFIG.webServerEnabled && tursoReadyForWeb) {
|
|
424
|
+
const webAuth = new WebAuth({
|
|
425
|
+
password: CONFIG.webServerAuthPassword,
|
|
426
|
+
username: CONFIG.webServerAuthUsername,
|
|
427
|
+
});
|
|
428
|
+
startWebServer({
|
|
429
|
+
port: CONFIG.webServerPort,
|
|
430
|
+
host: CONFIG.webServerHost,
|
|
431
|
+
enabled: CONFIG.webServerEnabled,
|
|
432
|
+
auth: webAuth,
|
|
433
|
+
apiToken: CONFIG.webServerApiToken,
|
|
434
|
+
})
|
|
435
|
+
.then((server) => {
|
|
436
|
+
webServer = server;
|
|
437
|
+
const url = webServer.getUrl();
|
|
438
|
+
webServer.setOnTakeoverCallback(async () => {
|
|
439
|
+
if (ctx.client?.tui) {
|
|
440
|
+
ctx.client.tui
|
|
441
|
+
.showToast({
|
|
442
|
+
body: {
|
|
443
|
+
title: "Memory Explorer",
|
|
444
|
+
message: "Took over web server ownership",
|
|
445
|
+
variant: "success",
|
|
446
|
+
duration: 3000,
|
|
447
|
+
},
|
|
448
|
+
})
|
|
449
|
+
.catch(() => { });
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
webServer.setOnPortsExhaustedCallback(() => {
|
|
453
|
+
if (ctx.client?.tui) {
|
|
454
|
+
ctx.client.tui
|
|
455
|
+
.showToast({
|
|
456
|
+
body: {
|
|
457
|
+
title: "Memory Explorer",
|
|
458
|
+
message: `Web UI unavailable: ports ${CONFIG.webServerPort}-${CONFIG.webServerPort + 10} are held by non-responsive processes`,
|
|
459
|
+
variant: "error",
|
|
460
|
+
duration: 5000,
|
|
461
|
+
},
|
|
462
|
+
})
|
|
463
|
+
.catch(() => { });
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
if (webServer.isServerOwner()) {
|
|
467
|
+
if (ctx.client?.tui) {
|
|
468
|
+
ctx.client.tui
|
|
469
|
+
.showToast({
|
|
470
|
+
body: {
|
|
471
|
+
title: "Memory Explorer",
|
|
472
|
+
message: webAuth.isEnabled()
|
|
473
|
+
? `Web UI started at ${url} (auth required)`
|
|
474
|
+
: `Web UI started at ${url}`,
|
|
475
|
+
variant: "success",
|
|
476
|
+
duration: 5000,
|
|
477
|
+
},
|
|
478
|
+
})
|
|
479
|
+
.catch(() => { });
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
if (ctx.client?.tui) {
|
|
484
|
+
ctx.client.tui
|
|
485
|
+
.showToast({
|
|
486
|
+
body: {
|
|
487
|
+
title: "Memory Explorer",
|
|
488
|
+
message: `Web UI available at ${url}`,
|
|
489
|
+
variant: "info",
|
|
490
|
+
duration: 3000,
|
|
491
|
+
},
|
|
492
|
+
})
|
|
493
|
+
.catch(() => { });
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
})
|
|
497
|
+
.catch((error) => {
|
|
498
|
+
log("Web server failed to start", { error: String(error) });
|
|
499
|
+
if (ctx.client?.tui) {
|
|
500
|
+
ctx.client.tui
|
|
501
|
+
.showToast({
|
|
502
|
+
body: {
|
|
503
|
+
title: "Memory Explorer Error",
|
|
504
|
+
message: `Failed to start: ${String(error)}`,
|
|
505
|
+
variant: "error",
|
|
506
|
+
duration: 5000,
|
|
507
|
+
},
|
|
508
|
+
})
|
|
509
|
+
.catch(() => { });
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
const cleanupPlugin = async () => {
|
|
514
|
+
if (cleanedUp)
|
|
515
|
+
return;
|
|
516
|
+
cleanedUp = true;
|
|
517
|
+
clearProviderRefreshWiring();
|
|
518
|
+
pluginLifetime.abort();
|
|
519
|
+
for (const timer of idleTimers.values())
|
|
520
|
+
clearTimeout(timer);
|
|
521
|
+
idleTimers.clear();
|
|
522
|
+
// Drain in-flight (and already-queued-before-abort) captures before
|
|
523
|
+
// closing storage: abort only skips not-yet-started jobs.
|
|
524
|
+
await captureEvidence.drain();
|
|
525
|
+
await awaitCaptureDrain();
|
|
526
|
+
try {
|
|
527
|
+
const { stopMarkdownBackend } = await import("./services/markdown/backend.js");
|
|
528
|
+
stopMarkdownBackend();
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
/* ignore */
|
|
532
|
+
}
|
|
533
|
+
if (webServer)
|
|
534
|
+
await webServer.stop();
|
|
535
|
+
if (memoryClient)
|
|
536
|
+
await memoryClient.close();
|
|
537
|
+
};
|
|
538
|
+
const shutdownHandler = async (signal) => {
|
|
539
|
+
try {
|
|
540
|
+
await cleanupPlugin();
|
|
541
|
+
}
|
|
542
|
+
catch (error) {
|
|
543
|
+
log("Shutdown error", { error: String(error) });
|
|
544
|
+
process.exitCode = 1;
|
|
545
|
+
}
|
|
546
|
+
// Registering listeners disables the runtime's default termination.
|
|
547
|
+
// After cleanup, remove ours and re-raise so the host can exit (#408).
|
|
548
|
+
// Avoid forced process exit here — that crashes onnxruntime-node finalizers (#114).
|
|
549
|
+
process.off("SIGINT", shutdownHandler);
|
|
550
|
+
process.off("SIGTERM", shutdownHandler);
|
|
551
|
+
process.kill(process.pid, signal);
|
|
552
|
+
};
|
|
553
|
+
const beforeExitHandler = () => {
|
|
554
|
+
if (!cleanedUp) {
|
|
555
|
+
void cleanupPlugin();
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
const exitHandler = () => {
|
|
559
|
+
// Best-effort sync close when the host exits without SIGINT/SIGTERM.
|
|
560
|
+
if (!cleanedUp) {
|
|
561
|
+
try {
|
|
562
|
+
tursoConnectionManager.closeAllSync();
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
// ignore — module may already be torn down
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
process.on("SIGINT", shutdownHandler);
|
|
570
|
+
process.on("SIGTERM", shutdownHandler);
|
|
571
|
+
process.on("beforeExit", beforeExitHandler);
|
|
572
|
+
process.on("exit", exitHandler);
|
|
573
|
+
const disposePlugin = async () => {
|
|
574
|
+
process.off("SIGINT", shutdownHandler);
|
|
575
|
+
process.off("SIGTERM", shutdownHandler);
|
|
576
|
+
process.off("beforeExit", beforeExitHandler);
|
|
577
|
+
process.off("exit", exitHandler);
|
|
578
|
+
CHILD_SESSION_LOOKUPS.clear();
|
|
579
|
+
await cleanupPlugin();
|
|
580
|
+
};
|
|
581
|
+
void resumePendingCaptures();
|
|
582
|
+
// Capture remains tied to authored prompts. V2 can rebuild request context
|
|
583
|
+
// independently when its in-memory session cache is lost on host/plugin reload.
|
|
584
|
+
const capturePrompt = async (sessionID, messageID, parts) => {
|
|
585
|
+
if (!isConfigured() || !CONFIG.chatMessage.enabled)
|
|
586
|
+
return false;
|
|
587
|
+
const textParts = parts.filter((p) => p.type === "text");
|
|
588
|
+
if (textParts.length === 0)
|
|
589
|
+
return false;
|
|
590
|
+
// Host- and plugin-injected blocks reach this hook through the same
|
|
591
|
+
// parts array as real user input. Recording them would train both
|
|
592
|
+
// auto-capture and profile learning on another plugin's boilerplate.
|
|
593
|
+
const authoredParts = CONFIG.chatMessage.filterInjectedPrompts
|
|
594
|
+
? filterInjectedParts(textParts, CONFIG.chatMessage.injectionMarkers)
|
|
595
|
+
: textParts;
|
|
596
|
+
if (authoredParts.length === 0)
|
|
597
|
+
return false;
|
|
598
|
+
const userMessage = authoredParts.map((p) => p.text).join("\n");
|
|
599
|
+
if (!userMessage.trim())
|
|
600
|
+
return false;
|
|
601
|
+
if (isStructuredSummaryPromptMessage(userMessage) || isInternalStructuredSession(sessionID)) {
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
// Orchestrator child sessions (task/subagent) have a parentID; their
|
|
605
|
+
// "user" messages are parent-agent prompts, not human input. Skipping the
|
|
606
|
+
// save keeps them out of auto-capture and profile learning. Like other
|
|
607
|
+
// non-authored turns, a false return also skips memory-context injection
|
|
608
|
+
// for that turn (V1 chat.message returns early; the V2 adapter suppresses it).
|
|
609
|
+
if (!CONFIG.chatMessage.captureChildSessions && (await isChildSession(ctx.client, sessionID))) {
|
|
610
|
+
log("skipping child-session prompt capture", { sessionID });
|
|
611
|
+
return false;
|
|
612
|
+
}
|
|
613
|
+
await userPromptManager.savePrompt(sessionID, messageID, directory, userMessage);
|
|
614
|
+
return true;
|
|
615
|
+
};
|
|
616
|
+
const loadMemoryContext = async (sessionID) => {
|
|
617
|
+
const { loadRecallMemoriesForSession } = await import("./services/memory-recall.js");
|
|
618
|
+
const queryText = await userPromptManager.getLatestPromptTextForSession(sessionID);
|
|
619
|
+
const memories = await loadRecallMemoriesForSession(tags.project.tag, sessionID, queryText);
|
|
620
|
+
// Still format an empty project-memory payload so injectProfile can emit
|
|
621
|
+
// <user_profile> on its own (e.g. chatMessage.maxMemories: 0).
|
|
622
|
+
const projectMemories = {
|
|
623
|
+
results: memories.map((m) => ({
|
|
624
|
+
similarity: m.similarity,
|
|
625
|
+
selection: m.selection,
|
|
626
|
+
memory: m.memory,
|
|
627
|
+
id: m.id,
|
|
628
|
+
createdAt: m.createdAt,
|
|
629
|
+
projectName: m.projectName,
|
|
630
|
+
})),
|
|
631
|
+
total: memories.length,
|
|
632
|
+
timing: 0,
|
|
633
|
+
};
|
|
634
|
+
const userId = tags.user.userEmail || null;
|
|
635
|
+
return formatContextForPrompt(userId, projectMemories);
|
|
636
|
+
};
|
|
637
|
+
return {
|
|
638
|
+
// V1 ignores this extra hook; the V2 adapter uses it during plugin reload.
|
|
639
|
+
dispose: disposePlugin,
|
|
640
|
+
// Internal V2 bridge; V1 still injects synthetic parts through chat.message.
|
|
641
|
+
memoryContext: {
|
|
642
|
+
ownsPendingCaptureSession: async (sessionID) => !cleanedUp &&
|
|
643
|
+
isConfigured() &&
|
|
644
|
+
CONFIG.autoCaptureEnabled &&
|
|
645
|
+
userPromptManager.hasPendingCaptureSession(sessionID, directory),
|
|
646
|
+
enabled: () => isConfigured() && CONFIG.chatMessage.enabled,
|
|
647
|
+
refreshOnPrompt: () => shouldRefreshRecallOnPrompt(CONFIG.chatMessage.recall ?? "relevant", CONFIG.chatMessage.injectOn ?? "first"),
|
|
648
|
+
capturePrompt: async (input, output) => capturePrompt(input.sessionID, output.message.id, output.parts),
|
|
649
|
+
load: async (sessionID) => {
|
|
650
|
+
if (!isConfigured() ||
|
|
651
|
+
!CONFIG.chatMessage.enabled ||
|
|
652
|
+
isInternalStructuredSession(sessionID) ||
|
|
653
|
+
(await isInternalCaptureSession(ctx.client, sessionID)) ||
|
|
654
|
+
// Same child-session gate as capture: after plugin reload the V2
|
|
655
|
+
// context hook can rehydrate via load() without going through
|
|
656
|
+
// capturePrompt, so skip injection for orchestrator children too.
|
|
657
|
+
(!CONFIG.chatMessage.captureChildSessions &&
|
|
658
|
+
(await isChildSession(ctx.client, sessionID)))) {
|
|
659
|
+
return "";
|
|
660
|
+
}
|
|
661
|
+
return loadMemoryContext(sessionID);
|
|
662
|
+
},
|
|
663
|
+
},
|
|
664
|
+
config: async (cfg) => {
|
|
665
|
+
applyStructuredOutputAgentConfig(cfg);
|
|
666
|
+
},
|
|
667
|
+
"chat.message": async (input, output) => {
|
|
668
|
+
if (!isConfigured() || !CONFIG.chatMessage.enabled)
|
|
669
|
+
return;
|
|
670
|
+
try {
|
|
671
|
+
if (!(await capturePrompt(input.sessionID, output.message.id, output.parts)))
|
|
672
|
+
return;
|
|
673
|
+
const messagesResponse = await ctx.client.session.messages({
|
|
674
|
+
path: { id: input.sessionID },
|
|
675
|
+
});
|
|
676
|
+
const messages = messagesResponse.data || [];
|
|
677
|
+
const hasNonSyntheticUserMessages = messages.some((m) => m.info.role === "user" &&
|
|
678
|
+
!m.parts.every((p) => p.type !== "text" || p.synthetic === true));
|
|
679
|
+
const lastMessage = messages.length > 0 ? messages[messages.length - 1] : null;
|
|
680
|
+
const isAfterCompaction = lastMessage?.info?.summary === true;
|
|
681
|
+
// Relevance/both re-inject every authored turn so the query matches the
|
|
682
|
+
// current message (issue #460). Legacy recent keeps injectOn: first.
|
|
683
|
+
const shouldInject = shouldRefreshRecallOnPrompt(CONFIG.chatMessage.recall ?? "relevant", CONFIG.chatMessage.injectOn ?? "first") ||
|
|
684
|
+
!hasNonSyntheticUserMessages ||
|
|
685
|
+
(isAfterCompaction &&
|
|
686
|
+
messages.filter((m) => m.info.role === "user" &&
|
|
687
|
+
!m.parts.every((p) => p.type !== "text" || p.synthetic === true)).length === 1);
|
|
688
|
+
if (!shouldInject)
|
|
689
|
+
return;
|
|
690
|
+
const memoryContext = await loadMemoryContext(input.sessionID);
|
|
691
|
+
if (memoryContext) {
|
|
692
|
+
const contextPart = {
|
|
693
|
+
id: `prt-memory-context-${Date.now()}`,
|
|
694
|
+
sessionID: input.sessionID,
|
|
695
|
+
messageID: output.message.id,
|
|
696
|
+
type: "text",
|
|
697
|
+
text: memoryContext,
|
|
698
|
+
synthetic: true,
|
|
699
|
+
};
|
|
700
|
+
output.parts.unshift(contextPart);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
catch (error) {
|
|
704
|
+
log("chat.message: ERROR", { error: String(error) });
|
|
705
|
+
if (ctx.client?.tui && CONFIG.showErrorToasts) {
|
|
706
|
+
await ctx.client.tui
|
|
707
|
+
.showToast({
|
|
708
|
+
body: {
|
|
709
|
+
title: "Memory System Error",
|
|
710
|
+
message: String(error),
|
|
711
|
+
variant: "error",
|
|
712
|
+
duration: 5000,
|
|
713
|
+
},
|
|
714
|
+
})
|
|
715
|
+
.catch(() => { });
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
},
|
|
719
|
+
"chat.params": async (input, output) => {
|
|
720
|
+
applyStructuredOutputChatParams(input, output);
|
|
721
|
+
const sessionModel = input?.model;
|
|
722
|
+
if (typeof sessionModel?.providerID === "string" && typeof sessionModel?.id === "string") {
|
|
723
|
+
// Keep the host-resolved model for inherit on idle paths (profile
|
|
724
|
+
// learning, dedup, …). OpenCode v2 no longer writes model.json (#453).
|
|
725
|
+
rememberSessionModel(sessionModel.providerID, sessionModel.id);
|
|
726
|
+
}
|
|
727
|
+
if (!isConfigured() || CONFIG.opencodeModel !== "inherit")
|
|
728
|
+
return;
|
|
729
|
+
try {
|
|
730
|
+
await userPromptManager.setPromptModel(input.message.id, input.model.providerID, input.model.id);
|
|
731
|
+
}
|
|
732
|
+
catch (error) {
|
|
733
|
+
log("chat.params: ERROR", { error: String(error) });
|
|
734
|
+
}
|
|
735
|
+
},
|
|
736
|
+
tool: {
|
|
737
|
+
memory: tool({
|
|
738
|
+
description: `Manage and query project memory (MATCH USER LANGUAGE: ${getLanguageName(CONFIG.autoCaptureLanguage || "en")}). Use 'search' with technical keywords/tags, 'add' to store knowledge, 'profile' for preferences. Use migrate/list-shards/export/import when a project directory moves. Search/list scope: project or all-projects.`,
|
|
739
|
+
args: {
|
|
740
|
+
mode: tool.schema
|
|
741
|
+
.enum([
|
|
742
|
+
"add",
|
|
743
|
+
"search",
|
|
744
|
+
"profile",
|
|
745
|
+
"list",
|
|
746
|
+
"forget",
|
|
747
|
+
"help",
|
|
748
|
+
"migrate",
|
|
749
|
+
"list-shards",
|
|
750
|
+
"export",
|
|
751
|
+
"import",
|
|
752
|
+
])
|
|
753
|
+
.optional(),
|
|
754
|
+
content: tool.schema.string().optional(),
|
|
755
|
+
query: tool.schema.string().optional(),
|
|
756
|
+
tags: tool.schema.string().optional(),
|
|
757
|
+
type: tool.schema.string().optional(),
|
|
758
|
+
memoryId: tool.schema.string().optional(),
|
|
759
|
+
limit: tool.schema.number().optional(),
|
|
760
|
+
scope: tool.schema.enum(["project", "all-projects"]).optional(),
|
|
761
|
+
fromPath: tool.schema.string().optional(),
|
|
762
|
+
fromHash: tool.schema.string().optional(),
|
|
763
|
+
outputPath: tool.schema.string().optional(),
|
|
764
|
+
inputPath: tool.schema.string().optional(),
|
|
765
|
+
dryRun: tool.schema.boolean().optional(),
|
|
766
|
+
allowLinkedSource: tool.schema.boolean().optional(),
|
|
767
|
+
},
|
|
768
|
+
async execute(args) {
|
|
769
|
+
if (!isConfigured()) {
|
|
770
|
+
return JSON.stringify({
|
|
771
|
+
success: false,
|
|
772
|
+
error: "Memory system not configured properly.",
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
const mode = args.mode || "help";
|
|
776
|
+
const needsEmbedding = !["help", "list-shards", "migrate", "export"].includes(mode);
|
|
777
|
+
if (needsEmbedding) {
|
|
778
|
+
const embeddingInitError = memoryClient.getEmbeddingInitError?.();
|
|
779
|
+
if (embeddingInitError) {
|
|
780
|
+
return JSON.stringify({ success: false, error: embeddingInitError });
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
try {
|
|
784
|
+
if (needsEmbedding) {
|
|
785
|
+
await memoryClient.warmup();
|
|
786
|
+
}
|
|
787
|
+
else if (mode !== "help") {
|
|
788
|
+
await memoryClient.ensureStorageReady();
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
catch (error) {
|
|
792
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
793
|
+
return JSON.stringify({
|
|
794
|
+
success: false,
|
|
795
|
+
error: `Memory system failed to initialize: ${message}`,
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
const langName = getLanguageName(CONFIG.autoCaptureLanguage || "en");
|
|
799
|
+
try {
|
|
800
|
+
switch (mode) {
|
|
801
|
+
case "help":
|
|
802
|
+
return JSON.stringify({
|
|
803
|
+
success: true,
|
|
804
|
+
message: "Memory System Usage Guide",
|
|
805
|
+
commands: [
|
|
806
|
+
{
|
|
807
|
+
command: "add",
|
|
808
|
+
description: `Store new memory (MATCH USER LANGUAGE: ${langName})`,
|
|
809
|
+
args: ["content", "type?", "tags?"],
|
|
810
|
+
},
|
|
811
|
+
{
|
|
812
|
+
command: "search",
|
|
813
|
+
description: `Search memories via keywords (MATCH USER LANGUAGE: ${langName})`,
|
|
814
|
+
args: ["query"],
|
|
815
|
+
},
|
|
816
|
+
{
|
|
817
|
+
command: "profile",
|
|
818
|
+
description: "View user profile or save an explicit preference (provide content to write)",
|
|
819
|
+
args: ["content?"],
|
|
820
|
+
},
|
|
821
|
+
{ command: "list", description: "List recent memories", args: ["limit?"] },
|
|
822
|
+
{ command: "forget", description: "Remove memory", args: ["memoryId"] },
|
|
823
|
+
{
|
|
824
|
+
command: "list-shards",
|
|
825
|
+
description: "List project memory shards and orphaned path associations",
|
|
826
|
+
args: [],
|
|
827
|
+
},
|
|
828
|
+
{
|
|
829
|
+
command: "migrate",
|
|
830
|
+
description: "Reassociate orphaned project shards after a directory move (target must be empty)",
|
|
831
|
+
args: ["fromPath?", "fromHash?", "dryRun?", "allowLinkedSource?"],
|
|
832
|
+
},
|
|
833
|
+
{
|
|
834
|
+
command: "export",
|
|
835
|
+
description: "Export current project memories to a portable JSON file",
|
|
836
|
+
args: ["outputPath"],
|
|
837
|
+
},
|
|
838
|
+
{
|
|
839
|
+
command: "import",
|
|
840
|
+
description: "Import memories from a portable JSON file (re-embeds; aborts on duplicate ids)",
|
|
841
|
+
args: ["inputPath", "dryRun?"],
|
|
842
|
+
},
|
|
843
|
+
],
|
|
844
|
+
tagGuidance: "Use technical keywords for search. Tags rank highest.",
|
|
845
|
+
});
|
|
846
|
+
case "add": {
|
|
847
|
+
if (!args.content)
|
|
848
|
+
return JSON.stringify({ success: false, error: "content required" });
|
|
849
|
+
const sanitizedContent = stripPrivateContent(args.content);
|
|
850
|
+
if (isFullyPrivate(args.content))
|
|
851
|
+
return JSON.stringify({ success: false, error: "Private content blocked" });
|
|
852
|
+
const tagInfo = tags.project;
|
|
853
|
+
const parsedTags = args.tags
|
|
854
|
+
? args.tags.split(",").map((t) => sanitizeMemoryContent(t).trim().toLowerCase())
|
|
855
|
+
: undefined;
|
|
856
|
+
const result = await memoryClient.addMemory(sanitizedContent, tagInfo.tag, {
|
|
857
|
+
type: args.type,
|
|
858
|
+
tags: parsedTags,
|
|
859
|
+
displayName: tagInfo.displayName,
|
|
860
|
+
userName: tagInfo.userName,
|
|
861
|
+
userEmail: tagInfo.userEmail,
|
|
862
|
+
projectPath: tagInfo.projectPath,
|
|
863
|
+
projectName: tagInfo.projectName,
|
|
864
|
+
gitRepoUrl: tagInfo.gitRepoUrl,
|
|
865
|
+
});
|
|
866
|
+
return JSON.stringify({
|
|
867
|
+
success: result.success,
|
|
868
|
+
message: result.success ? `Memory added` : result.error,
|
|
869
|
+
id: result.success ? result.id : undefined,
|
|
870
|
+
tags: parsedTags,
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
case "search": {
|
|
874
|
+
if (!args.query)
|
|
875
|
+
return JSON.stringify({ success: false, error: "query required" });
|
|
876
|
+
const searchRes = await memoryClient.searchMemories(args.query, tags.project.tag, args.scope ?? CONFIG.memory.defaultScope);
|
|
877
|
+
if (!searchRes.success)
|
|
878
|
+
return JSON.stringify({ success: false, error: searchRes.error });
|
|
879
|
+
return formatSearchResults(args.query, searchRes, args.limit);
|
|
880
|
+
}
|
|
881
|
+
case "profile": {
|
|
882
|
+
if (args.query) {
|
|
883
|
+
return JSON.stringify({
|
|
884
|
+
success: false,
|
|
885
|
+
error: "query is not valid for profile mode. Use content to write a preference or omit all args to read.",
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
const { userProfileManager } = await import("./services/user-profile/user-profile-manager.js");
|
|
889
|
+
const { toPublicProfileData } = await import("./services/user-profile/profile-utils.js");
|
|
890
|
+
const { tryAcquireProfileLearningLock } = await import("./services/user-profile/learning-lock.js");
|
|
891
|
+
const userId = tags.user.userEmail || "unknown";
|
|
892
|
+
// --- WRITE: explicit preference ---
|
|
893
|
+
if (args.content !== undefined) {
|
|
894
|
+
const trimmed = args.content.trim();
|
|
895
|
+
if (!trimmed) {
|
|
896
|
+
return JSON.stringify({ success: false, error: "content must not be blank" });
|
|
897
|
+
}
|
|
898
|
+
if (!tags.user.userEmail) {
|
|
899
|
+
return JSON.stringify({
|
|
900
|
+
success: false,
|
|
901
|
+
error: "Cannot save profile preference because no user email could be resolved. Configure userEmailOverride or git user.email.",
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
const sanitizedContent = stripPrivateContent(trimmed);
|
|
905
|
+
const hasNonPrivateContent = sanitizedContent.replace(/\[REDACTED\]/g, "").trim().length > 0;
|
|
906
|
+
if (isFullyPrivate(trimmed) || !hasNonPrivateContent) {
|
|
907
|
+
return JSON.stringify({ success: false, error: "Private content blocked" });
|
|
908
|
+
}
|
|
909
|
+
// Hold the same non-reentrant learning lock as performUserProfileLearning
|
|
910
|
+
// so mergeProfileData's cold-buffer round cannot race learning. Do not
|
|
911
|
+
// acquire inside mergeProfileData — learning already holds this lock.
|
|
912
|
+
const releaseProfileWriteLock = await tryAcquireProfileLearningLock(directory);
|
|
913
|
+
if (!releaseProfileWriteLock) {
|
|
914
|
+
return JSON.stringify({
|
|
915
|
+
success: false,
|
|
916
|
+
error: "Profile preference save is temporarily unavailable because profile learning holds the lock. Retry shortly.",
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
try {
|
|
920
|
+
const newPreference = {
|
|
921
|
+
category: "explicit",
|
|
922
|
+
description: sanitizedContent,
|
|
923
|
+
confidence: 1.0,
|
|
924
|
+
frequency: 1,
|
|
925
|
+
evidence: ["manual-write"],
|
|
926
|
+
lastSeen: Date.now(),
|
|
927
|
+
};
|
|
928
|
+
const existingProfile = await userProfileManager.getActiveProfile(userId);
|
|
929
|
+
if (existingProfile) {
|
|
930
|
+
const existingData = JSON.parse(existingProfile.profileData);
|
|
931
|
+
const mergedData = await userProfileManager.mergeProfileData(existingData, {
|
|
932
|
+
preferences: [newPreference],
|
|
933
|
+
}, undefined, existingProfile.id);
|
|
934
|
+
await userProfileManager.updateProfile(existingProfile.id, mergedData, 0, `Explicit preference added: ${sanitizedContent.slice(0, 80)}`);
|
|
935
|
+
return JSON.stringify({
|
|
936
|
+
success: true,
|
|
937
|
+
message: "Preference saved to profile",
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
await userProfileManager.createProfile(userId, tags.user.displayName || userId, tags.user.userName || userId, tags.user.userEmail || userId, { preferences: [newPreference], patterns: [], workflows: [] }, 0);
|
|
941
|
+
return JSON.stringify({
|
|
942
|
+
success: true,
|
|
943
|
+
message: "Profile created with preference",
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
finally {
|
|
947
|
+
await releaseProfileWriteLock();
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
// --- READ: no content provided ---
|
|
951
|
+
const profile = await userProfileManager.getActiveProfile(userId);
|
|
952
|
+
if (!profile)
|
|
953
|
+
return JSON.stringify({ success: true, profile: null });
|
|
954
|
+
const pData = toPublicProfileData(JSON.parse(profile.profileData));
|
|
955
|
+
return JSON.stringify({
|
|
956
|
+
success: true,
|
|
957
|
+
profile: {
|
|
958
|
+
...pData,
|
|
959
|
+
version: profile.version,
|
|
960
|
+
lastAnalyzed: profile.lastAnalyzedAt,
|
|
961
|
+
},
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
case "list": {
|
|
965
|
+
const listRes = await memoryClient.listMemories(tags.project.tag, args.limit || 20, args.scope ?? CONFIG.memory.defaultScope);
|
|
966
|
+
if (!listRes.success)
|
|
967
|
+
return JSON.stringify({ success: false, error: listRes.error });
|
|
968
|
+
return JSON.stringify({
|
|
969
|
+
success: true,
|
|
970
|
+
count: listRes.memories?.length,
|
|
971
|
+
memories: listRes.memories?.map((m) => ({
|
|
972
|
+
id: m.id,
|
|
973
|
+
content: m.summary,
|
|
974
|
+
createdAt: m.createdAt,
|
|
975
|
+
})),
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
case "forget": {
|
|
979
|
+
if (!args.memoryId)
|
|
980
|
+
return JSON.stringify({ success: false, error: "memoryId required" });
|
|
981
|
+
const delRes = await memoryClient.deleteMemory(args.memoryId);
|
|
982
|
+
return JSON.stringify({ success: delRes.success, message: `Memory removed` });
|
|
983
|
+
}
|
|
984
|
+
case "list-shards": {
|
|
985
|
+
const listShardsRes = await memoryClient.listShards(directory);
|
|
986
|
+
return JSON.stringify(listShardsRes);
|
|
987
|
+
}
|
|
988
|
+
case "migrate": {
|
|
989
|
+
if (!args.fromPath && !args.fromHash) {
|
|
990
|
+
return JSON.stringify({
|
|
991
|
+
success: false,
|
|
992
|
+
error: "fromPath or fromHash required. Run memory list-shards to discover orphaned shards.",
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
const migrateRes = await memoryClient.migrateProjectPath({
|
|
996
|
+
currentDirectory: directory,
|
|
997
|
+
fromPath: args.fromPath,
|
|
998
|
+
fromHash: args.fromHash,
|
|
999
|
+
dryRun: args.dryRun,
|
|
1000
|
+
allowLinkedSource: args.allowLinkedSource,
|
|
1001
|
+
});
|
|
1002
|
+
return JSON.stringify(migrateRes);
|
|
1003
|
+
}
|
|
1004
|
+
case "export": {
|
|
1005
|
+
if (!args.outputPath) {
|
|
1006
|
+
return JSON.stringify({ success: false, error: "outputPath required" });
|
|
1007
|
+
}
|
|
1008
|
+
const exportRes = await memoryClient.exportMemories(directory, args.outputPath);
|
|
1009
|
+
return JSON.stringify(exportRes);
|
|
1010
|
+
}
|
|
1011
|
+
case "import": {
|
|
1012
|
+
if (!args.inputPath) {
|
|
1013
|
+
return JSON.stringify({ success: false, error: "inputPath required" });
|
|
1014
|
+
}
|
|
1015
|
+
const importRes = await memoryClient.importMemories(directory, args.inputPath, args.dryRun);
|
|
1016
|
+
return JSON.stringify(importRes);
|
|
1017
|
+
}
|
|
1018
|
+
default:
|
|
1019
|
+
return JSON.stringify({ success: false, error: `Unknown mode: ${mode}` });
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
return JSON.stringify({ success: false, error: String(error) });
|
|
1024
|
+
}
|
|
1025
|
+
},
|
|
1026
|
+
}),
|
|
1027
|
+
},
|
|
1028
|
+
event: async (input) => {
|
|
1029
|
+
const event = input.event;
|
|
1030
|
+
if (!cleanedUp && isConfigured() && CONFIG.autoCaptureEnabled) {
|
|
1031
|
+
try {
|
|
1032
|
+
await captureEvidence.observe(event);
|
|
1033
|
+
}
|
|
1034
|
+
catch (error) {
|
|
1035
|
+
log("Capture evidence preservation failed", { error: String(error) });
|
|
1036
|
+
}
|
|
1037
|
+
if (event.type === "session.deleted") {
|
|
1038
|
+
const sessionID = event.properties?.sessionID ?? event.properties?.info?.id;
|
|
1039
|
+
if (typeof sessionID === "string") {
|
|
1040
|
+
// Deletion supersedes a pending idle debounce for the same session.
|
|
1041
|
+
const pendingIdle = idleTimers.get(sessionID);
|
|
1042
|
+
if (pendingIdle) {
|
|
1043
|
+
clearTimeout(pendingIdle);
|
|
1044
|
+
idleTimers.delete(sessionID);
|
|
1045
|
+
}
|
|
1046
|
+
// Evidence checkpoint is best-effort above; still attempt recovery.
|
|
1047
|
+
void performAutoCapture(ctx, sessionID, directory, {
|
|
1048
|
+
signal: pluginLifetime.signal,
|
|
1049
|
+
preferSavedEvidence: true,
|
|
1050
|
+
}).catch((error) => log("Deleted-session capture deferred", { error: String(error) }));
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
// Late host provider registration: user-config providers can appear
|
|
1055
|
+
// (or disappear) after plugin setup; refresh the connectivity snapshot.
|
|
1056
|
+
if (event.type === "provider.updated" || event.type === "model.updated") {
|
|
1057
|
+
if (!cleanedUp)
|
|
1058
|
+
runCoalescedRefresh();
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
// Client-side step watchdog for internal structured-output sessions (#278).
|
|
1062
|
+
// OpenCode's agent.steps soft-cap does not hard-stop json_schema loops when
|
|
1063
|
+
// forced StructuredOutput keeps failing (e.g. opencode-claude-auth).
|
|
1064
|
+
if (event.type === "message.part.updated") {
|
|
1065
|
+
const part = event.properties?.part;
|
|
1066
|
+
if (part?.type === "step-start" && typeof part.sessionID === "string") {
|
|
1067
|
+
const { shouldAbort, steps } = noteStructuredOutputStep(part.sessionID);
|
|
1068
|
+
if (shouldAbort) {
|
|
1069
|
+
log("Aborting structured-output session after step budget", {
|
|
1070
|
+
sessionID: part.sessionID,
|
|
1071
|
+
steps,
|
|
1072
|
+
maxSteps: STRUCTURED_OUTPUT_MAX_STEPS,
|
|
1073
|
+
});
|
|
1074
|
+
try {
|
|
1075
|
+
await ctx.client.session.abort({ path: { id: part.sessionID } });
|
|
1076
|
+
}
|
|
1077
|
+
catch (error) {
|
|
1078
|
+
log("structured-output step abort failed", {
|
|
1079
|
+
sessionID: part.sessionID,
|
|
1080
|
+
error: String(error),
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
if (event.type === "session.idle") {
|
|
1088
|
+
if (!isConfigured() || !CONFIG.autoCaptureEnabled)
|
|
1089
|
+
return;
|
|
1090
|
+
if (cleanedUp)
|
|
1091
|
+
return;
|
|
1092
|
+
const sessionID = event.properties?.sessionID;
|
|
1093
|
+
if (!sessionID)
|
|
1094
|
+
return;
|
|
1095
|
+
// Transient structured-output sessions must not re-trigger capture/learning
|
|
1096
|
+
// (that self-schedules an unbounded idle → LLM → idle loop).
|
|
1097
|
+
if (await isInternalCaptureSession(ctx.client, sessionID)) {
|
|
1098
|
+
log("Skipping idle processing for internal capture session", { sessionID });
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
// The internal-capture check above awaits: dispose may have run while it
|
|
1102
|
+
// was in flight. Never arm post-dispose timers.
|
|
1103
|
+
if (cleanedUp)
|
|
1104
|
+
return;
|
|
1105
|
+
// Same-session idles debounce into one capture; different sessions
|
|
1106
|
+
// each keep their own pending timer (see idleTimers comment above).
|
|
1107
|
+
const existingTimer = idleTimers.get(sessionID);
|
|
1108
|
+
if (existingTimer)
|
|
1109
|
+
clearTimeout(existingTimer);
|
|
1110
|
+
const timer = setTimeout(async () => {
|
|
1111
|
+
try {
|
|
1112
|
+
idleTimers.delete(sessionID);
|
|
1113
|
+
await performAutoCapture(ctx, sessionID, directory, {
|
|
1114
|
+
signal: pluginLifetime.signal,
|
|
1115
|
+
});
|
|
1116
|
+
// Prompts are shared across projects, but web-server ownership tracks
|
|
1117
|
+
// whoever bound the port first and is never handed over while that
|
|
1118
|
+
// process stays reachable. Gating learning on it stalls the queue
|
|
1119
|
+
// whenever the owner stops seeing sessions, and disables learning
|
|
1120
|
+
// outright when the web server is off. Any active instance may learn;
|
|
1121
|
+
// performUserProfileLearning holds a cross-process lock internally.
|
|
1122
|
+
if (cleanedUp)
|
|
1123
|
+
return;
|
|
1124
|
+
await performUserProfileLearning(ctx, directory);
|
|
1125
|
+
// Retention cleanup stays owner-only: it is storage-wide maintenance
|
|
1126
|
+
// that has no reason to run once per active instance.
|
|
1127
|
+
if (webServer?.isServerOwner()) {
|
|
1128
|
+
const { cleanupService } = await import("./services/cleanup-service.js");
|
|
1129
|
+
if (await cleanupService.shouldRunCleanup())
|
|
1130
|
+
await cleanupService.runCleanup();
|
|
1131
|
+
const { dreamingService } = await import("./services/dreaming-service.js");
|
|
1132
|
+
await dreamingService.maybeRun(directory);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
catch (error) {
|
|
1136
|
+
log("Idle processing error", { error: String(error) });
|
|
1137
|
+
}
|
|
1138
|
+
finally {
|
|
1139
|
+
// Only drop the entry if it is still ours: a newer idle for this
|
|
1140
|
+
// session may have re-armed a fresh timer while we ran.
|
|
1141
|
+
if (idleTimers.get(sessionID) === timer)
|
|
1142
|
+
idleTimers.delete(sessionID);
|
|
1143
|
+
}
|
|
1144
|
+
}, 10000);
|
|
1145
|
+
idleTimers.set(sessionID, timer);
|
|
1146
|
+
// Dispose may have cleared the map between the cleanedUp check above
|
|
1147
|
+
// and this set; never leave an orphan timer armed after cleanup.
|
|
1148
|
+
if (cleanedUp) {
|
|
1149
|
+
clearTimeout(timer);
|
|
1150
|
+
idleTimers.delete(sessionID);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
if (event.type === "session.compacted") {
|
|
1154
|
+
if (!isConfigured() || !CONFIG.compaction.enabled)
|
|
1155
|
+
return;
|
|
1156
|
+
const sessionID = event.properties?.sessionID;
|
|
1157
|
+
if (!sessionID)
|
|
1158
|
+
return;
|
|
1159
|
+
try {
|
|
1160
|
+
const tags = getTags(directory);
|
|
1161
|
+
const memoriesResult = await memoryClient.searchMemoriesBySessionID(sessionID, tags.project.tag, CONFIG.compaction.memoryLimit);
|
|
1162
|
+
if (!memoriesResult.success || memoriesResult.results.length === 0) {
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
const memoryContext = formatMemoriesForCompaction(memoriesResult.results);
|
|
1166
|
+
const agent = await resolveSessionAgent(ctx.client, sessionID);
|
|
1167
|
+
if (!agent) {
|
|
1168
|
+
log("Compaction: skipped memory injection because session agent could not be resolved", {
|
|
1169
|
+
sessionID,
|
|
1170
|
+
});
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
const current = await resolveSessionModel(ctx.client, sessionID);
|
|
1174
|
+
await ctx.client.session.prompt({
|
|
1175
|
+
path: { id: sessionID },
|
|
1176
|
+
body: {
|
|
1177
|
+
parts: [
|
|
1178
|
+
{
|
|
1179
|
+
id: `prt-compaction-${Date.now()}`,
|
|
1180
|
+
type: "text",
|
|
1181
|
+
text: memoryContext,
|
|
1182
|
+
synthetic: true,
|
|
1183
|
+
},
|
|
1184
|
+
],
|
|
1185
|
+
noReply: true,
|
|
1186
|
+
agent,
|
|
1187
|
+
...(current ? { model: current.model } : {}),
|
|
1188
|
+
...(current?.variant ? { variant: current.variant } : {}),
|
|
1189
|
+
},
|
|
1190
|
+
});
|
|
1191
|
+
if (ctx.client?.tui) {
|
|
1192
|
+
await ctx.client.tui
|
|
1193
|
+
.showToast({
|
|
1194
|
+
body: {
|
|
1195
|
+
title: "Memory Restored",
|
|
1196
|
+
message: `${memoriesResult.results.length} memories injected after compaction`,
|
|
1197
|
+
variant: "success",
|
|
1198
|
+
duration: 3000,
|
|
1199
|
+
},
|
|
1200
|
+
})
|
|
1201
|
+
.catch(() => { });
|
|
1202
|
+
}
|
|
1203
|
+
log("Compaction memory injected", {
|
|
1204
|
+
sessionID,
|
|
1205
|
+
count: memoriesResult.results.length,
|
|
1206
|
+
agent: agent ?? null,
|
|
1207
|
+
model: current ? `${current.model.providerID}/${current.model.modelID}` : null,
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
catch (error) {
|
|
1211
|
+
log("Compaction handler error", { error: String(error) });
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
},
|
|
1215
|
+
};
|
|
1216
|
+
};
|
|
1217
|
+
function formatSearchResults(query, results, limit) {
|
|
1218
|
+
const memoryResults = results.results || [];
|
|
1219
|
+
return JSON.stringify({
|
|
1220
|
+
success: true,
|
|
1221
|
+
query,
|
|
1222
|
+
count: memoryResults.length,
|
|
1223
|
+
results: memoryResults.slice(0, limit || 10).map((r) => ({
|
|
1224
|
+
id: r.id,
|
|
1225
|
+
content: r.memory || r.chunk,
|
|
1226
|
+
similarity: Math.round(r.similarity * 100),
|
|
1227
|
+
})),
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
const EMBEDDED_TAGS_FOOTER_RE = /\n*Tags: ([^\n]*)\s*$/;
|
|
1231
|
+
function normalizeTagsKey(tags) {
|
|
1232
|
+
return tags
|
|
1233
|
+
.map((tag) => tag.trim())
|
|
1234
|
+
.filter((tag) => tag.length > 0)
|
|
1235
|
+
.sort()
|
|
1236
|
+
.join("\0");
|
|
1237
|
+
}
|
|
1238
|
+
function stripMatchingEmbeddedTagsFooter(memory, tags) {
|
|
1239
|
+
const match = memory.match(EMBEDDED_TAGS_FOOTER_RE);
|
|
1240
|
+
if (!match) {
|
|
1241
|
+
return memory;
|
|
1242
|
+
}
|
|
1243
|
+
const footerValue = match[1];
|
|
1244
|
+
if (footerValue === undefined) {
|
|
1245
|
+
return memory;
|
|
1246
|
+
}
|
|
1247
|
+
const embeddedTags = footerValue
|
|
1248
|
+
.split(",")
|
|
1249
|
+
.map((tag) => tag.trim())
|
|
1250
|
+
.filter((tag) => tag.length > 0);
|
|
1251
|
+
if (normalizeTagsKey(embeddedTags) !== normalizeTagsKey(tags)) {
|
|
1252
|
+
return memory;
|
|
1253
|
+
}
|
|
1254
|
+
return memory.replace(EMBEDDED_TAGS_FOOTER_RE, "");
|
|
1255
|
+
}
|
|
1256
|
+
export function formatMemoriesForCompaction(memories) {
|
|
1257
|
+
let output = `## Restored Session Memory\n\n`;
|
|
1258
|
+
memories.forEach((m, i) => {
|
|
1259
|
+
const tags = Array.isArray(m.tags) ? m.tags : [];
|
|
1260
|
+
const body = tags.length > 0 ? stripMatchingEmbeddedTagsFooter(m.memory ?? "", tags) : (m.memory ?? "");
|
|
1261
|
+
output += `### Memory ${i + 1}${buildMemoryProvenanceSuffix(m)}\n`;
|
|
1262
|
+
output += `${body}\n\n`;
|
|
1263
|
+
if (tags.length > 0) {
|
|
1264
|
+
output += `Tags: ${tags.join(", ")}\n\n`;
|
|
1265
|
+
}
|
|
1266
|
+
});
|
|
1267
|
+
return output;
|
|
1268
|
+
}
|