@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
|
@@ -0,0 +1,787 @@
|
|
|
1
|
+
import { getTags } from "./tags.js";
|
|
2
|
+
import { log } from "./logger.js";
|
|
3
|
+
import { CONFIG } from "../config.js";
|
|
4
|
+
import { userPromptManager } from "./user-prompt/user-prompt-manager.js";
|
|
5
|
+
import { userProfileManager } from "./user-profile/user-profile-manager.js";
|
|
6
|
+
import { sortProfileItems } from "../utils/profile.js";
|
|
7
|
+
import { loadOpencodeProvider } from "./ai/opencode-provider-loader.js";
|
|
8
|
+
import { tryAcquireProfileLearningLock } from "./user-profile/learning-lock.js";
|
|
9
|
+
let isLearningRunning = false;
|
|
10
|
+
export function shouldRunAutomaticProfileCleanup(previousPromptCount, addedPromptCount, interval = CONFIG.userProfileAutoCleanupInterval) {
|
|
11
|
+
if (!CONFIG.userProfileAutoCleanupEnabled || !Number.isInteger(interval) || interval <= 0) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
return (Math.floor(previousPromptCount / interval) <
|
|
15
|
+
Math.floor((previousPromptCount + addedPromptCount) / interval));
|
|
16
|
+
}
|
|
17
|
+
async function runAutomaticProfileCleanup(userId) {
|
|
18
|
+
try {
|
|
19
|
+
const profile = await userProfileManager.getActiveProfile(userId);
|
|
20
|
+
if (!profile)
|
|
21
|
+
return;
|
|
22
|
+
const profileData = JSON.parse(profile.profileData);
|
|
23
|
+
const itemCount = profileData.preferences.length + profileData.patterns.length + profileData.workflows.length;
|
|
24
|
+
if (itemCount < 2)
|
|
25
|
+
return;
|
|
26
|
+
const { aiCleanupProfile } = await import("./user-profile/ai-cleanup.js");
|
|
27
|
+
const result = await aiCleanupProfile(profileData);
|
|
28
|
+
if (result.diff.merged.length === 0 && result.diff.removed.length === 0)
|
|
29
|
+
return;
|
|
30
|
+
const updated = await userProfileManager.updateProfile(profile.id, result.cleaned, 0, `Automatic AI cleanup: ${result.diff.merged.length} merged, ${result.diff.removed.length} removed`);
|
|
31
|
+
log("user-profile-learning: automatic cleanup complete", {
|
|
32
|
+
userId,
|
|
33
|
+
updated,
|
|
34
|
+
merged: result.diff.merged.length,
|
|
35
|
+
removed: result.diff.removed.length,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
log("user-profile-learning: automatic cleanup failed", { userId, error: String(error) });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export async function performUserProfileLearning(ctx, directory) {
|
|
43
|
+
if (isLearningRunning)
|
|
44
|
+
return;
|
|
45
|
+
if (!CONFIG.autoCaptureProviderStatus || !CONFIG.autoCaptureProviderStatus.ready) {
|
|
46
|
+
log("user-profile-learning: skipped (provider not ready)", {
|
|
47
|
+
issues: CONFIG.autoCaptureProviderStatus?.issues ?? ["status undefined"],
|
|
48
|
+
});
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
// Set before the first await so a same-process re-entry bounces off the flag
|
|
52
|
+
// instead of queueing behind this run and running a second analysis.
|
|
53
|
+
//
|
|
54
|
+
// `isLearningRunning` only guards re-entry inside one process. Prompt selection
|
|
55
|
+
// is a plain SELECT and the batch is marked only after the LLM responds, so
|
|
56
|
+
// without cross-process exclusion two instances sharing this storage would
|
|
57
|
+
// analyze the same prompts and the slower writer would clobber the faster
|
|
58
|
+
// one's profile update. Contention skips this round; the next idle retries.
|
|
59
|
+
isLearningRunning = true;
|
|
60
|
+
let releaseLearningLock = null;
|
|
61
|
+
try {
|
|
62
|
+
releaseLearningLock = await tryAcquireProfileLearningLock(directory);
|
|
63
|
+
if (!releaseLearningLock) {
|
|
64
|
+
log("user-profile-learning: skipped (another process holds the learning lock)");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const count = await userPromptManager.countUnanalyzedForUserLearning();
|
|
68
|
+
const threshold = CONFIG.userProfileAnalysisInterval;
|
|
69
|
+
log("user-profile-learning: check", { count, threshold });
|
|
70
|
+
if (count < threshold) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const prompts = await userPromptManager.getPromptsForUserLearning(threshold);
|
|
74
|
+
if (prompts.length === 0) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const tags = getTags(directory);
|
|
78
|
+
const userId = tags.user.userEmail || "unknown";
|
|
79
|
+
let existingProfile = await userProfileManager.getActiveProfile(userId);
|
|
80
|
+
const analysisStartTime = Date.now();
|
|
81
|
+
let validationPrompt;
|
|
82
|
+
let validationPrefKeys;
|
|
83
|
+
if (existingProfile && CONFIG.userProfileValidationEnabled) {
|
|
84
|
+
const profileData = JSON.parse(existingProfile.profileData);
|
|
85
|
+
const { data: decayed } = userProfileManager.decayInMemory(profileData);
|
|
86
|
+
for (const arr of [decayed.preferences, decayed.patterns, decayed.workflows]) {
|
|
87
|
+
for (const item of arr) {
|
|
88
|
+
if (item.pendingValidation && (item.lastSeen || 0) < analysisStartTime) {
|
|
89
|
+
item.pendingValidation = false;
|
|
90
|
+
item.alpha = (item.alpha || 1) + 1;
|
|
91
|
+
userProfileManager.syncConfidence(item);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
existingProfile = { ...existingProfile, profileData: JSON.stringify(decayed) };
|
|
96
|
+
const topPrefs = sortProfileItems(decayed.preferences, "confidence").slice(0, 5);
|
|
97
|
+
const topPats = sortProfileItems(decayed.patterns, "frequency").slice(0, 3);
|
|
98
|
+
const hasValidator = topPrefs.length >= 5;
|
|
99
|
+
if (hasValidator) {
|
|
100
|
+
const allValidated = [...topPrefs, ...topPats];
|
|
101
|
+
validationPrefKeys = allValidated.map((p) => `${p.category || "_"}||${(p.description || "").substring(0, 30)}`);
|
|
102
|
+
log("user-profile-learning: validation enabled", {
|
|
103
|
+
topPrefs: topPrefs.map((p) => `[${p.category}] ${(p.description || "").substring(0, 30)}`),
|
|
104
|
+
topPats: topPats.map((p) => `[${p.category}] ${(p.description || "").substring(0, 30)}`),
|
|
105
|
+
});
|
|
106
|
+
validationPrompt = `## Task 3: Validate Existing Profile Entries
|
|
107
|
+
|
|
108
|
+
CRITICAL: Complete Tasks 1-2 (new observations) FIRST. This task is separate — only check whether the entries below still match recent behavior. Do NOT let these descriptions influence your new observations.
|
|
109
|
+
|
|
110
|
+
${allValidated.map((p, i) => `${i}. [${p.category || "_"}] ${(p.description || "").substring(0, 30)} (conf: ${Math.round((p.confidence || 0) * 100) / 100})`).join("\n")}
|
|
111
|
+
|
|
112
|
+
For each entry above, judge whether recent prompts confirm or contradict it. Output:
|
|
113
|
+
{"validations": [{"index": 0, "verdict": "confirmed|contradicted|no_evidence|inaccurate|oversimplified", "reason": "one sentence"}]}
|
|
114
|
+
|
|
115
|
+
Rules:
|
|
116
|
+
- confirmed: recent prompts show clear evidence
|
|
117
|
+
- contradicted: recent prompts show the user has changed
|
|
118
|
+
- inaccurate: the description is directionally wrong (opposite behavior seen)
|
|
119
|
+
- oversimplified: the description is too vague, missing important nuance
|
|
120
|
+
- no_evidence: recent prompts don't address this topic
|
|
121
|
+
- Only mark contradicted if there is explicit evidence the user's behavior has changed`;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
log("user-profile-learning: validation skipped", {
|
|
125
|
+
prefCount: topPrefs.length,
|
|
126
|
+
reason: "needs ≥ 5 preferences",
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else if (existingProfile) {
|
|
131
|
+
const profileData = JSON.parse(existingProfile.profileData);
|
|
132
|
+
const { data: decayed } = userProfileManager.decayInMemory(profileData);
|
|
133
|
+
for (const arr of [decayed.preferences, decayed.patterns, decayed.workflows]) {
|
|
134
|
+
for (const item of arr) {
|
|
135
|
+
if (item.pendingValidation && (item.lastSeen || 0) < analysisStartTime) {
|
|
136
|
+
item.pendingValidation = false;
|
|
137
|
+
item.alpha = (item.alpha || 1) + 1;
|
|
138
|
+
userProfileManager.syncConfidence(item);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
existingProfile = { ...existingProfile, profileData: JSON.stringify(decayed) };
|
|
143
|
+
}
|
|
144
|
+
const context = buildUserAnalysisContext(prompts, existingProfile, validationPrompt);
|
|
145
|
+
const langName = await resolveProfileLanguageName(prompts);
|
|
146
|
+
const analysisResult = await analyzeUserProfile(context, existingProfile, langName);
|
|
147
|
+
log("user-profile-learning: analyze done", { hasResult: !!analysisResult });
|
|
148
|
+
if (!analysisResult) {
|
|
149
|
+
await userPromptManager.markMultipleAsUserLearningCaptured(prompts.map((p) => p.id));
|
|
150
|
+
if (prompts.length >= 10 && existingProfile) {
|
|
151
|
+
buildLearningPaths(prompts, existingProfile.id).catch(() => { });
|
|
152
|
+
}
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const { raw: llmResult, merged: initialMerged } = analysisResult;
|
|
156
|
+
let cleanupPreviousPromptCount = 0;
|
|
157
|
+
if (existingProfile) {
|
|
158
|
+
let updatedProfileData = initialMerged;
|
|
159
|
+
const MAX_RETRIES = 2;
|
|
160
|
+
let retries = 0;
|
|
161
|
+
let success = false;
|
|
162
|
+
while (!success && retries <= MAX_RETRIES) {
|
|
163
|
+
if (retries > 0) {
|
|
164
|
+
existingProfile = await userProfileManager.getActiveProfile(userId);
|
|
165
|
+
if (!existingProfile)
|
|
166
|
+
break;
|
|
167
|
+
const retryProfileData = JSON.parse(existingProfile.profileData);
|
|
168
|
+
const { data: decayedRetry } = userProfileManager.decayInMemory(retryProfileData);
|
|
169
|
+
existingProfile = { ...existingProfile, profileData: JSON.stringify(decayedRetry) };
|
|
170
|
+
updatedProfileData = await userProfileManager.mergeProfileData(decayedRetry, llmResult, undefined, existingProfile.id);
|
|
171
|
+
log("user-profile-learning: retry merge", {
|
|
172
|
+
retry: retries,
|
|
173
|
+
profileId: existingProfile.id,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
cleanupPreviousPromptCount = existingProfile.totalPromptsAnalyzed;
|
|
177
|
+
let changeSummary = generateChangeSummary(JSON.parse(existingProfile.profileData), updatedProfileData);
|
|
178
|
+
const validationSummary = await applyValidations(updatedProfileData, llmResult, existingProfile.id, validationPrefKeys);
|
|
179
|
+
if (validationSummary) {
|
|
180
|
+
changeSummary = changeSummary + "; " + validationSummary;
|
|
181
|
+
}
|
|
182
|
+
success = await userProfileManager.updateProfile(existingProfile.id, updatedProfileData, prompts.length, changeSummary);
|
|
183
|
+
if (!success) {
|
|
184
|
+
log("User profile update conflict, retrying", {
|
|
185
|
+
profileId: existingProfile.id,
|
|
186
|
+
userId,
|
|
187
|
+
retry: retries,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
retries++;
|
|
191
|
+
}
|
|
192
|
+
if (!success) {
|
|
193
|
+
// Mark the batch anyway so the same prompts are not retried forever
|
|
194
|
+
// (token burn + repeated toasts on every subsequent idle).
|
|
195
|
+
log("User profile update conflict: exhausted retries", {
|
|
196
|
+
profileId: existingProfile?.id,
|
|
197
|
+
userId,
|
|
198
|
+
});
|
|
199
|
+
await userPromptManager.markMultipleAsUserLearningCaptured(prompts.map((p) => p.id));
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
await userPromptManager.markMultipleAsUserLearningCaptured(prompts.map((p) => p.id));
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
await userProfileManager.createProfile(userId, tags.user.displayName || "Unknown", tags.user.userName || "unknown", tags.user.userEmail || "unknown", llmResult, prompts.length);
|
|
206
|
+
await userPromptManager.markMultipleAsUserLearningCaptured(prompts.map((p) => p.id));
|
|
207
|
+
}
|
|
208
|
+
if (shouldRunAutomaticProfileCleanup(cleanupPreviousPromptCount, prompts.length)) {
|
|
209
|
+
await runAutomaticProfileCleanup(userId);
|
|
210
|
+
}
|
|
211
|
+
if (CONFIG.showUserProfileToasts) {
|
|
212
|
+
await ctx.client?.tui
|
|
213
|
+
.showToast({
|
|
214
|
+
body: {
|
|
215
|
+
title: "User Profile Updated",
|
|
216
|
+
message: `Analyzed ${prompts.length} of ${count} pending prompts and updated your profile`,
|
|
217
|
+
variant: "success",
|
|
218
|
+
duration: 3000,
|
|
219
|
+
},
|
|
220
|
+
})
|
|
221
|
+
.catch(() => { });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
// Guard against corrupt stored profileData (JSON.parse throws) and any other
|
|
226
|
+
// fault: this runs fire-and-forget from the idle timer, so an uncaught rejection
|
|
227
|
+
// would surface as an unhandled promise rejection. The caller (src/index.ts idle
|
|
228
|
+
// timer) already wraps this call in its own try/catch, and issue #265 requires
|
|
229
|
+
// provider errors to propagate instead of being masked, so rethrow after logging.
|
|
230
|
+
log("user-profile-learning: aborted", { error: String(error) });
|
|
231
|
+
throw error;
|
|
232
|
+
}
|
|
233
|
+
finally {
|
|
234
|
+
// Release only when the lock was actually acquired (contention return,
|
|
235
|
+
// acquisition failure, and any throw before acquisition all leave it null).
|
|
236
|
+
// The flag resets in a nested finally so it stays raised while the release
|
|
237
|
+
// await is in flight — otherwise a same-process re-entry could slip in and
|
|
238
|
+
// find the cross-process lock already gone — and it still resets when the
|
|
239
|
+
// release itself rejects.
|
|
240
|
+
try {
|
|
241
|
+
await releaseLearningLock?.();
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
isLearningRunning = false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function generateChangeSummary(oldProfile, newProfile) {
|
|
249
|
+
const changes = [];
|
|
250
|
+
const prefDiff = newProfile.preferences.length - oldProfile.preferences.length;
|
|
251
|
+
if (prefDiff > 0)
|
|
252
|
+
changes.push(`+${prefDiff} preferences`);
|
|
253
|
+
const patternDiff = newProfile.patterns.length - oldProfile.patterns.length;
|
|
254
|
+
if (patternDiff > 0)
|
|
255
|
+
changes.push(`+${patternDiff} patterns`);
|
|
256
|
+
const workflowDiff = newProfile.workflows.length - oldProfile.workflows.length;
|
|
257
|
+
if (workflowDiff > 0)
|
|
258
|
+
changes.push(`+${workflowDiff} workflows`);
|
|
259
|
+
return changes.length > 0 ? changes.join(", ") : "Profile refinement";
|
|
260
|
+
}
|
|
261
|
+
function buildCategorySummary(profileData) {
|
|
262
|
+
const prefCats = [...new Set(profileData.preferences.map((p) => p.category))];
|
|
263
|
+
const patCats = [...new Set(profileData.patterns.map((p) => p.category))];
|
|
264
|
+
const catParts = [];
|
|
265
|
+
if (prefCats.length > 0) {
|
|
266
|
+
const catCounts = prefCats
|
|
267
|
+
.map((cat) => {
|
|
268
|
+
const cnt = profileData.preferences.filter((p) => p.category === cat).length;
|
|
269
|
+
return `${cat} (${cnt})`;
|
|
270
|
+
})
|
|
271
|
+
.join(", ");
|
|
272
|
+
catParts.push(`Preference categories: ${catCounts}`);
|
|
273
|
+
}
|
|
274
|
+
if (patCats.length > 0) {
|
|
275
|
+
const catCounts = patCats
|
|
276
|
+
.map((cat) => {
|
|
277
|
+
const cnt = profileData.patterns.filter((p) => p.category === cat).length;
|
|
278
|
+
return `${cat} (${cnt})`;
|
|
279
|
+
})
|
|
280
|
+
.join(", ");
|
|
281
|
+
catParts.push(`Pattern categories: ${catCounts}`);
|
|
282
|
+
}
|
|
283
|
+
const catSection = catParts.length > 0
|
|
284
|
+
? `## Existing Categories\nUse these exact category names when your observation fits:\n\n${catParts.join("\n")}\n`
|
|
285
|
+
: "";
|
|
286
|
+
const prefCount = profileData.preferences.length;
|
|
287
|
+
const patCount = profileData.patterns.length;
|
|
288
|
+
const wfCount = profileData.workflows.length;
|
|
289
|
+
const wfParts = [];
|
|
290
|
+
if (wfCount > 0) {
|
|
291
|
+
wfParts.push("## Existing Workflows\nFor reference — only report a workflow when recent prompts show a genuinely NEW sequence, NOT a minor variant of an existing one:");
|
|
292
|
+
profileData.workflows.forEach((wf, i) => {
|
|
293
|
+
const steps = wf.steps?.length
|
|
294
|
+
? ` (freq ${wf.frequency || 1}x: ${wf.steps.join(" → ")})`
|
|
295
|
+
: "";
|
|
296
|
+
wfParts.push(`${i + 1}. ${wf.description}${steps}`);
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
const countSection = `## Profile Size\nPreferences: ${prefCount} | Patterns: ${patCount} | Workflows: ${wfCount}\n
|
|
300
|
+
New observations are matched via embedding cosine similarity — write descriptions in your own words; do not reuse existing wording.`;
|
|
301
|
+
return [catSection, ...wfParts, countSection].filter(Boolean).join("\n");
|
|
302
|
+
}
|
|
303
|
+
function buildUserAnalysisContext(prompts, existingProfile, validationPrompt) {
|
|
304
|
+
const base = `# User Profile Analysis
|
|
305
|
+
|
|
306
|
+
Analyze ${prompts.length} user prompts to ${existingProfile ? "update" : "create"} the user profile.
|
|
307
|
+
${existingProfile ? `The merge system will automatically connect your observations to existing profile entries — you only need to describe what you see in these recent prompts.` : `Create a new user profile from scratch based on the prompts below.`}
|
|
308
|
+
|
|
309
|
+
${existingProfile ? buildCategorySummary(JSON.parse(existingProfile.profileData)) : ""}
|
|
310
|
+
## Recent Prompts
|
|
311
|
+
|
|
312
|
+
${prompts.map((p, i) => `${i + 1}. ${p.content}`).join("\n\n")}
|
|
313
|
+
|
|
314
|
+
## Analysis Guidelines
|
|
315
|
+
|
|
316
|
+
Identify and ${existingProfile ? "report" : "create"}:
|
|
317
|
+
|
|
318
|
+
1. **Preferences**
|
|
319
|
+
- Code style, communication style, tool preferences
|
|
320
|
+
- Assign confidence 0.3-0.5 based on evidence strength in these recent prompts
|
|
321
|
+
- Include 1-3 example prompts as evidence
|
|
322
|
+
- **Revealed preferences**: when the user chooses one approach over alternatives (e.g. picks simpler solution, skips certain steps), capture the choice as a lower-confidence preference (0.3-0.5). What the user does NOT do is also a signal.
|
|
323
|
+
|
|
324
|
+
2. **Patterns**
|
|
325
|
+
- Recurring topics, problem domains, technical interests seen in these prompts
|
|
326
|
+
- Track frequency of occurrence
|
|
327
|
+
|
|
328
|
+
3. **Workflows**
|
|
329
|
+
- Distinct, named step sequences the user follows repeatedly
|
|
330
|
+
- Each workflow should represent a DIFFERENT activity (different purpose, different steps)
|
|
331
|
+
- Break down into 3-6 concrete, observable steps, NOT abstract phases
|
|
332
|
+
- Do NOT repeat the same workflow every cycle — only output when you observe a NEW recurring sequence
|
|
333
|
+
- Examples of distinct workflows: "debugging workflow", "code review workflow", "learning workflow", "refactoring workflow"
|
|
334
|
+
|
|
335
|
+
CRITICAL: Only output observations grounded in the RECENT PROMPTS above. Write descriptions in your own words — the system matches by embedding similarity, not exact wording. Do NOT output entries that lack evidence in recent prompts. Put the core semantics at the beginning of each description, keeping descriptions concise and specific (under 120 characters). Do NOT extract one-time debugging tasks, environment setup issues, or specific error investigations as preferences — these are transient events, not behavioral patterns.
|
|
336
|
+
|
|
337
|
+
## Few-Shot Examples
|
|
338
|
+
|
|
339
|
+
❌ Do NOT extract as preference:
|
|
340
|
+
- "User is debugging a NullPointerException in auth service" (one-time debugging task)
|
|
341
|
+
- "User installed Redis for the first time" (one-time setup event)
|
|
342
|
+
- "User ran npm audit fix" (routine maintenance, not a behavioral pattern)
|
|
343
|
+
|
|
344
|
+
✅ DO extract as preference:
|
|
345
|
+
- "User prefers functional programming style over OOP"
|
|
346
|
+
- "User consistently writes tests before implementation"
|
|
347
|
+
- "User asks for explanations before accepting code changes"
|
|
348
|
+
|
|
349
|
+
✅ DO extract as workflow (distinct, non-overlapping):
|
|
350
|
+
- Debugging workflow: "reproduce the error → check logs → grep source code → trace call chain → propose fix → verify fix"
|
|
351
|
+
- Code review workflow: "read the diff → check edge cases → verify consistency with existing patterns → report issues → suggest alternatives"
|
|
352
|
+
- Learning workflow: "ask for explanation → request examples → test understanding with a small task → apply to real problem"
|
|
353
|
+
|
|
354
|
+
❌ Do NOT extract as workflow:
|
|
355
|
+
- "User analyzes problems and verifies solutions" (too abstract — not a concrete step sequence)
|
|
356
|
+
- "User writes code and tests it" (too generic — covers everything)`;
|
|
357
|
+
const maxBytes = CONFIG.userProfileMaxContextBytes ?? 32768;
|
|
358
|
+
const truncate = (s) => s.length > maxBytes
|
|
359
|
+
? s.substring(0, maxBytes) + "\n[... context truncated to userProfileMaxContextBytes ...]"
|
|
360
|
+
: s;
|
|
361
|
+
if (validationPrompt) {
|
|
362
|
+
return truncate(base + "\n\n" + validationPrompt);
|
|
363
|
+
}
|
|
364
|
+
return truncate(base);
|
|
365
|
+
}
|
|
366
|
+
/** Upper bound for LLM-inferred preference confidence (0–1 scale). */
|
|
367
|
+
export const USER_PROFILE_LLM_CONFIDENCE_MAX = 1;
|
|
368
|
+
/** Shared analysis schema for OpenCode structured output and external tool calls. */
|
|
369
|
+
export function createUserProfileAnalysisSchema(z) {
|
|
370
|
+
return z.object({
|
|
371
|
+
preferences: z.array(z.object({
|
|
372
|
+
category: z.string(),
|
|
373
|
+
description: z.string(),
|
|
374
|
+
confidence: z.number().min(0).max(USER_PROFILE_LLM_CONFIDENCE_MAX),
|
|
375
|
+
evidence: z.array(z.string()),
|
|
376
|
+
})),
|
|
377
|
+
patterns: z.array(z.object({
|
|
378
|
+
category: z.string(),
|
|
379
|
+
description: z.string(),
|
|
380
|
+
})),
|
|
381
|
+
workflows: z.array(z.object({
|
|
382
|
+
description: z.string(),
|
|
383
|
+
steps: z.array(z.string()),
|
|
384
|
+
})),
|
|
385
|
+
validations: z
|
|
386
|
+
.array(z.object({
|
|
387
|
+
index: z.number(),
|
|
388
|
+
verdict: z.enum([
|
|
389
|
+
"confirmed",
|
|
390
|
+
"contradicted",
|
|
391
|
+
"no_evidence",
|
|
392
|
+
"inaccurate",
|
|
393
|
+
"oversimplified",
|
|
394
|
+
]),
|
|
395
|
+
reason: z.string(),
|
|
396
|
+
}))
|
|
397
|
+
.optional(),
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
export function createUserProfileToolSchema(existingProfile) {
|
|
401
|
+
return {
|
|
402
|
+
type: "function",
|
|
403
|
+
function: {
|
|
404
|
+
name: "update_user_profile",
|
|
405
|
+
description: existingProfile
|
|
406
|
+
? "Update existing user profile with new insights"
|
|
407
|
+
: "Create new user profile",
|
|
408
|
+
parameters: {
|
|
409
|
+
type: "object",
|
|
410
|
+
properties: {
|
|
411
|
+
preferences: {
|
|
412
|
+
type: "array",
|
|
413
|
+
items: {
|
|
414
|
+
type: "object",
|
|
415
|
+
properties: {
|
|
416
|
+
category: { type: "string" },
|
|
417
|
+
description: { type: "string" },
|
|
418
|
+
confidence: {
|
|
419
|
+
type: "number",
|
|
420
|
+
minimum: 0,
|
|
421
|
+
maximum: USER_PROFILE_LLM_CONFIDENCE_MAX,
|
|
422
|
+
},
|
|
423
|
+
evidence: { type: "array", items: { type: "string" }, maxItems: 3 },
|
|
424
|
+
},
|
|
425
|
+
required: ["category", "description", "confidence", "evidence"],
|
|
426
|
+
},
|
|
427
|
+
},
|
|
428
|
+
patterns: {
|
|
429
|
+
type: "array",
|
|
430
|
+
items: {
|
|
431
|
+
type: "object",
|
|
432
|
+
properties: {
|
|
433
|
+
category: { type: "string" },
|
|
434
|
+
description: { type: "string" },
|
|
435
|
+
},
|
|
436
|
+
required: ["category", "description"],
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
workflows: {
|
|
440
|
+
type: "array",
|
|
441
|
+
items: {
|
|
442
|
+
type: "object",
|
|
443
|
+
properties: {
|
|
444
|
+
description: { type: "string" },
|
|
445
|
+
steps: { type: "array", items: { type: "string" } },
|
|
446
|
+
},
|
|
447
|
+
required: ["description", "steps"],
|
|
448
|
+
},
|
|
449
|
+
},
|
|
450
|
+
validations: {
|
|
451
|
+
type: "array",
|
|
452
|
+
items: {
|
|
453
|
+
type: "object",
|
|
454
|
+
properties: {
|
|
455
|
+
index: { type: "number" },
|
|
456
|
+
verdict: {
|
|
457
|
+
type: "string",
|
|
458
|
+
enum: [
|
|
459
|
+
"confirmed",
|
|
460
|
+
"contradicted",
|
|
461
|
+
"no_evidence",
|
|
462
|
+
"inaccurate",
|
|
463
|
+
"oversimplified",
|
|
464
|
+
],
|
|
465
|
+
},
|
|
466
|
+
reason: { type: "string" },
|
|
467
|
+
},
|
|
468
|
+
required: ["index", "verdict", "reason"],
|
|
469
|
+
},
|
|
470
|
+
},
|
|
471
|
+
},
|
|
472
|
+
required: ["preferences", "patterns", "workflows"],
|
|
473
|
+
},
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
async function applyValidations(profileData, llmResult, profileId, prefKeys) {
|
|
478
|
+
const validations = llmResult.validations;
|
|
479
|
+
if (!validations?.length || !prefKeys?.length)
|
|
480
|
+
return null;
|
|
481
|
+
const allItems = [...profileData.preferences, ...profileData.patterns];
|
|
482
|
+
const results = [];
|
|
483
|
+
let confirmed = 0;
|
|
484
|
+
let contradicted = 0;
|
|
485
|
+
let inaccurate = 0;
|
|
486
|
+
let oversimplified = 0;
|
|
487
|
+
for (const v of validations) {
|
|
488
|
+
const key = prefKeys[v.index];
|
|
489
|
+
if (!key)
|
|
490
|
+
continue;
|
|
491
|
+
const item = allItems.find((i) => `${i.category || "_"}||${(i.description || "").substring(0, 30)}` === key);
|
|
492
|
+
if (!item) {
|
|
493
|
+
log("user-profile-learning: validation match failed", { index: v.index, key });
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
if (v.verdict === "confirmed") {
|
|
497
|
+
item.alpha = (item.alpha || 1) + 0.5;
|
|
498
|
+
userProfileManager.syncConfidence(item);
|
|
499
|
+
confirmed++;
|
|
500
|
+
results.push(`confirmed [${v.index}] ${v.reason}`);
|
|
501
|
+
}
|
|
502
|
+
else if (v.verdict === "contradicted") {
|
|
503
|
+
const oldAlpha = item.alpha || 1;
|
|
504
|
+
item.alpha = oldAlpha * 0.75;
|
|
505
|
+
item.beta = (item.beta || 1) + oldAlpha * 0.25;
|
|
506
|
+
userProfileManager.syncConfidence(item);
|
|
507
|
+
contradicted++;
|
|
508
|
+
results.push(`contradicted [${v.index}] ${v.reason}`);
|
|
509
|
+
}
|
|
510
|
+
else if (v.verdict === "inaccurate") {
|
|
511
|
+
const oldAlpha = item.alpha || 1;
|
|
512
|
+
item.alpha = oldAlpha * 0.6;
|
|
513
|
+
item.beta = (item.beta || 1) + oldAlpha * 0.4;
|
|
514
|
+
userProfileManager.syncConfidence(item);
|
|
515
|
+
inaccurate++;
|
|
516
|
+
results.push(`inaccurate [${v.index}] ${v.reason}`);
|
|
517
|
+
}
|
|
518
|
+
else if (v.verdict === "oversimplified") {
|
|
519
|
+
const oldAlpha = item.alpha || 1;
|
|
520
|
+
item.alpha = oldAlpha * 0.85;
|
|
521
|
+
item.beta = (item.beta || 1) + oldAlpha * 0.15;
|
|
522
|
+
userProfileManager.syncConfidence(item);
|
|
523
|
+
oversimplified++;
|
|
524
|
+
results.push(`oversimplified [${v.index}] ${v.reason}`);
|
|
525
|
+
const evidence = item.evidence;
|
|
526
|
+
if (Array.isArray(evidence) && evidence.length >= 3) {
|
|
527
|
+
const itemType = profileData.preferences.includes(item) ? "preference" : "pattern";
|
|
528
|
+
// Await so the in-place description/centroid mutation completes before the
|
|
529
|
+
// caller serializes updatedProfileData — otherwise the evolved description is
|
|
530
|
+
// included or lost nondeterministically. Failures stay non-fatal.
|
|
531
|
+
try {
|
|
532
|
+
await userProfileManager.evolveAndUpdate(item, itemType, profileId);
|
|
533
|
+
}
|
|
534
|
+
catch {
|
|
535
|
+
// description evolution is best-effort
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
results.push(`no_evidence [${v.index}] ${v.reason}`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
if (results.length > 0) {
|
|
544
|
+
log("user-profile-learning: validation results", { validated: results });
|
|
545
|
+
}
|
|
546
|
+
if (confirmed === 0 && contradicted === 0 && inaccurate === 0 && oversimplified === 0)
|
|
547
|
+
return null;
|
|
548
|
+
return `validated: ${confirmed} confirmed, ${contradicted} contradicted, ${inaccurate} inaccurate, ${oversimplified} oversimplified`;
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Resolves the language the profile-analysis LLM must write in, honoring the
|
|
552
|
+
* same `autoCaptureLanguage` config used by auto-capture (src/services/auto-capture.ts)
|
|
553
|
+
* so auto-captured memories and the user profile follow the same language setting.
|
|
554
|
+
*
|
|
555
|
+
* In "auto" mode, detection runs on the raw prompt text only — never on the
|
|
556
|
+
* analysis context, whose English instruction scaffold would bias detection
|
|
557
|
+
* toward English for short non-English prompts.
|
|
558
|
+
*/
|
|
559
|
+
export async function resolveProfileLanguageName(prompts) {
|
|
560
|
+
const { detectLanguage, getLanguageName } = await import("./language-detector.js");
|
|
561
|
+
const targetLang = CONFIG.autoCaptureLanguage === "auto" || !CONFIG.autoCaptureLanguage
|
|
562
|
+
? detectLanguage(prompts.map((p) => p.content).join("\n\n"))
|
|
563
|
+
: CONFIG.autoCaptureLanguage;
|
|
564
|
+
return getLanguageName(targetLang);
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Outer safety-net timeout wrapping one structured-output call: the configured
|
|
568
|
+
* timeout plus a fixed margin, so the inner, more informative provider
|
|
569
|
+
* timeout always fires first. Local (not imported from config.ts) because
|
|
570
|
+
* subprocess test scenarios mock the config module with a minimal export
|
|
571
|
+
* surface.
|
|
572
|
+
*/
|
|
573
|
+
function outerStructuredTimeoutMs(configured) {
|
|
574
|
+
return (configured ?? 90_000) + 30_000;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* System prompt for the profile analysis.
|
|
578
|
+
*
|
|
579
|
+
* `mode` selects the transport the same analysis is served through:
|
|
580
|
+
* - "tool": the external-API tool-call path (`update_user_profile` forced
|
|
581
|
+
* tool). The prompt must instruct the model to use that tool.
|
|
582
|
+
* - "json": the OpenCode structured-output path (v2 Generate API exposes no
|
|
583
|
+
* tools). A tool instruction here makes obedient models stall on a
|
|
584
|
+
* preamble ("Let me load the profile update tool first.") and return no
|
|
585
|
+
* JSON, so the model is told to answer with the profile JSON object itself.
|
|
586
|
+
*/
|
|
587
|
+
function buildProfileSystemPrompt(existingProfile, langName, mode) {
|
|
588
|
+
const closing = mode === "tool"
|
|
589
|
+
? `Use the update_user_profile tool to save the ${existingProfile ? "updated" : "new"} profile.`
|
|
590
|
+
: `Return the ${existingProfile ? "updated" : "new"} profile as the JSON object described in the request. Reply with JSON only.`;
|
|
591
|
+
return `You are a user behavior analyst for a coding assistant.
|
|
592
|
+
|
|
593
|
+
Your task is to analyze user prompts and ${existingProfile ? "update" : "create"} a comprehensive user profile.
|
|
594
|
+
|
|
595
|
+
CRITICAL: You MUST write all descriptions, categories, and text in ${langName}.
|
|
596
|
+
|
|
597
|
+
CRITICAL: All JSON string values MUST escape double quotes with backslash. Do NOT use unescaped quotation marks inside string values.
|
|
598
|
+
|
|
599
|
+
${closing}`;
|
|
600
|
+
}
|
|
601
|
+
async function analyzeUserProfile(context, existingProfile, langName) {
|
|
602
|
+
// Outer safety net for the structured-output call. Derived from the same
|
|
603
|
+
// configured timeout the inner (informative) structured-output timeout uses,
|
|
604
|
+
// plus a margin, so the inner one always fires first and the error message
|
|
605
|
+
// names the real cause instead of a generic race timeout.
|
|
606
|
+
const outerTimeoutMs = outerStructuredTimeoutMs(CONFIG.opencodeTimeoutMs);
|
|
607
|
+
let opencodeProviderError;
|
|
608
|
+
if (CONFIG.opencodeProvider && CONFIG.opencodeModel) {
|
|
609
|
+
const systemPrompt = buildProfileSystemPrompt(existingProfile, langName, "json");
|
|
610
|
+
log("user-profile-learning: analyze called", { hasProfile: !!existingProfile });
|
|
611
|
+
log("user-profile-learning: trying opencode provider");
|
|
612
|
+
// The try/catch boundary is the provider only: LLM client construction,
|
|
613
|
+
// the structured-output call, and schema binding. Stored-profile parsing
|
|
614
|
+
// and merging happen AFTER a successful LLM response and outside this
|
|
615
|
+
// try — a cold-storage read/parse/merge failure must propagate to the
|
|
616
|
+
// caller (logged + rethrown there), never be mistaken for a provider
|
|
617
|
+
// fault that silently falls back to the external API and then
|
|
618
|
+
// re-reads/re-merges the same broken storage.
|
|
619
|
+
let rawData = null;
|
|
620
|
+
try {
|
|
621
|
+
const { generateStructuredOutput } = await loadOpencodeProvider();
|
|
622
|
+
const { getOpenCodeClient } = await import("./ai/profile-llm-client.js");
|
|
623
|
+
log("user-profile-learning: opencode provider diag", {
|
|
624
|
+
provider: CONFIG.opencodeProvider,
|
|
625
|
+
model: CONFIG.opencodeModel,
|
|
626
|
+
...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}),
|
|
627
|
+
});
|
|
628
|
+
const v2Client = await getOpenCodeClient();
|
|
629
|
+
const { z } = await import("zod");
|
|
630
|
+
const schema = createUserProfileAnalysisSchema(z);
|
|
631
|
+
log("user-profile-learning: calling LLM", { contextLen: context.length });
|
|
632
|
+
const result = await Promise.race([
|
|
633
|
+
generateStructuredOutput({
|
|
634
|
+
client: v2Client,
|
|
635
|
+
providerID: CONFIG.opencodeProvider,
|
|
636
|
+
modelID: CONFIG.opencodeModel,
|
|
637
|
+
...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}),
|
|
638
|
+
systemPrompt,
|
|
639
|
+
userPrompt: context,
|
|
640
|
+
schema,
|
|
641
|
+
}),
|
|
642
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("user-profile-learning: timeout")), outerTimeoutMs)),
|
|
643
|
+
]);
|
|
644
|
+
log("user-profile-learning: LLM returned", {
|
|
645
|
+
prefCount: result.preferences?.length,
|
|
646
|
+
patCount: result.patterns?.length,
|
|
647
|
+
wfCount: result.workflows?.length,
|
|
648
|
+
});
|
|
649
|
+
rawData = result;
|
|
650
|
+
}
|
|
651
|
+
catch (e) {
|
|
652
|
+
opencodeProviderError = e;
|
|
653
|
+
log("user-profile-learning: opencode provider failed, falling back to external API", {
|
|
654
|
+
error: String(e),
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
// Stored-profile parse/merge runs only after a native success and is
|
|
658
|
+
// deliberately OUTSIDE the provider catch: storage faults here are not
|
|
659
|
+
// provider faults and must not trigger the external fallback.
|
|
660
|
+
if (rawData !== null) {
|
|
661
|
+
if (existingProfile) {
|
|
662
|
+
const existingData = JSON.parse(existingProfile.profileData);
|
|
663
|
+
const merged = await userProfileManager.mergeProfileData(existingData, rawData, undefined, existingProfile.id);
|
|
664
|
+
return { raw: rawData, merged };
|
|
665
|
+
}
|
|
666
|
+
return { raw: rawData, merged: null };
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (!CONFIG.memoryModel || !CONFIG.memoryApiUrl) {
|
|
670
|
+
if (opencodeProviderError) {
|
|
671
|
+
throw opencodeProviderError;
|
|
672
|
+
}
|
|
673
|
+
log("User Profile Config Check Failed:", {
|
|
674
|
+
memoryModel: CONFIG.memoryModel,
|
|
675
|
+
memoryApiUrl: CONFIG.memoryApiUrl,
|
|
676
|
+
});
|
|
677
|
+
throw new Error("External API not configured for user memory learning");
|
|
678
|
+
}
|
|
679
|
+
const { AIProviderFactory } = await import("./ai/ai-provider-factory.js");
|
|
680
|
+
const { buildMemoryProviderConfig } = await import("./ai/provider-config.js");
|
|
681
|
+
const providerConfig = buildMemoryProviderConfig(CONFIG);
|
|
682
|
+
const provider = AIProviderFactory.createProvider(CONFIG.memoryProvider, providerConfig);
|
|
683
|
+
const toolSchema = createUserProfileToolSchema(Boolean(existingProfile));
|
|
684
|
+
const result = await provider.executeToolCall(buildProfileSystemPrompt(existingProfile, langName, "tool"), context, toolSchema, `user-profile-${Date.now()}`);
|
|
685
|
+
if (!result.success || !result.data) {
|
|
686
|
+
throw new Error(result.error || "Failed to analyze user profile");
|
|
687
|
+
}
|
|
688
|
+
const rawData = result.data;
|
|
689
|
+
if (existingProfile) {
|
|
690
|
+
const existingData = JSON.parse(existingProfile.profileData);
|
|
691
|
+
const merged = await userProfileManager.mergeProfileData(existingData, rawData, undefined, existingProfile.id);
|
|
692
|
+
return { raw: rawData, merged };
|
|
693
|
+
}
|
|
694
|
+
return { raw: rawData, merged: null };
|
|
695
|
+
}
|
|
696
|
+
async function buildLearningPaths(prompts, profileId) {
|
|
697
|
+
const promptTexts = prompts.map((p, i) => `${i + 1}. ${p.content}`).join("\n");
|
|
698
|
+
const systemPrompt = "You are a learning path analyst. Identify causal chains across a user's prompts. Output valid JSON.";
|
|
699
|
+
const userPrompt = `Analyze these user prompts for causal learning chains:
|
|
700
|
+
|
|
701
|
+
${promptTexts}
|
|
702
|
+
|
|
703
|
+
Identify sequences where earlier prompts led to later ones (e.g. "learned X → applied X → refined X"). Return JSON:
|
|
704
|
+
{ "paths": [{ "topic": "string", "chain": ["step1", "step2", "step3"], "description": "one sentence summary" }] }
|
|
705
|
+
If no clear chains, return { "paths": [] }.`;
|
|
706
|
+
let result = null;
|
|
707
|
+
if (CONFIG.opencodeProvider && CONFIG.opencodeModel) {
|
|
708
|
+
try {
|
|
709
|
+
const { z } = await import("zod");
|
|
710
|
+
const { generateStructuredOutput } = await loadOpencodeProvider();
|
|
711
|
+
const { getOpenCodeClient } = await import("./ai/profile-llm-client.js");
|
|
712
|
+
let v2Client;
|
|
713
|
+
try {
|
|
714
|
+
v2Client = await getOpenCodeClient();
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
// provider not available, skip learning paths
|
|
718
|
+
}
|
|
719
|
+
if (v2Client) {
|
|
720
|
+
result = (await Promise.race([
|
|
721
|
+
generateStructuredOutput({
|
|
722
|
+
client: v2Client,
|
|
723
|
+
providerID: CONFIG.opencodeProvider,
|
|
724
|
+
modelID: CONFIG.opencodeModel,
|
|
725
|
+
...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}),
|
|
726
|
+
systemPrompt,
|
|
727
|
+
userPrompt,
|
|
728
|
+
schema: z.object({
|
|
729
|
+
paths: z.array(z.object({
|
|
730
|
+
topic: z.string(),
|
|
731
|
+
chain: z.array(z.string()),
|
|
732
|
+
description: z.string(),
|
|
733
|
+
})),
|
|
734
|
+
}),
|
|
735
|
+
}),
|
|
736
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("learning paths: opencode timeout")), outerStructuredTimeoutMs(CONFIG.opencodeTimeoutMs))),
|
|
737
|
+
]));
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
catch (e) {
|
|
741
|
+
log("learning paths: native provider failed", { error: String(e) });
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (!result && CONFIG.memoryModel && CONFIG.memoryApiUrl) {
|
|
745
|
+
try {
|
|
746
|
+
const response = await fetch(`${CONFIG.memoryApiUrl}/chat/completions`, {
|
|
747
|
+
method: "POST",
|
|
748
|
+
headers: {
|
|
749
|
+
"Content-Type": "application/json",
|
|
750
|
+
Authorization: `Bearer ${CONFIG.memoryApiKey || ""}`,
|
|
751
|
+
},
|
|
752
|
+
body: JSON.stringify({
|
|
753
|
+
model: CONFIG.memoryModel,
|
|
754
|
+
messages: [
|
|
755
|
+
{ role: "system", content: systemPrompt },
|
|
756
|
+
{ role: "user", content: userPrompt },
|
|
757
|
+
],
|
|
758
|
+
temperature: 0.3,
|
|
759
|
+
response_format: { type: "json_object" },
|
|
760
|
+
}),
|
|
761
|
+
signal: AbortSignal.timeout(60000),
|
|
762
|
+
});
|
|
763
|
+
if (response.ok) {
|
|
764
|
+
const data = (await response.json());
|
|
765
|
+
const content = data.choices?.[0]?.message?.content;
|
|
766
|
+
if (content)
|
|
767
|
+
result = JSON.parse(content);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
catch (e) {
|
|
771
|
+
log("learning paths: external API failed", { error: String(e) });
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
if (!result?.paths?.length)
|
|
775
|
+
return;
|
|
776
|
+
log("learning paths: detected", {
|
|
777
|
+
profileId,
|
|
778
|
+
pathCount: result.paths.length,
|
|
779
|
+
topics: result.paths.map((p) => p.topic).join(", "),
|
|
780
|
+
});
|
|
781
|
+
const profile = await userProfileManager.getProfileById(profileId);
|
|
782
|
+
if (!profile)
|
|
783
|
+
return;
|
|
784
|
+
const data = JSON.parse(profile.profileData);
|
|
785
|
+
data.learning_paths = result.paths;
|
|
786
|
+
await userProfileManager.updateProfile(profileId, data, 0, `Updated learning paths: ${result.paths.map((p) => p.topic).join(", ")}`);
|
|
787
|
+
}
|