minimal-agent 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/package.json +52 -5
- package/plugins/computer_use/.claude-plugin/plugin.json +6 -0
- package/plugins/computer_use/README.md +94 -0
- package/plugins/computer_use/app/_template.md +142 -0
- package/plugins/computer_use/app/chrome.md +165 -0
- package/plugins/computer_use/app/finder.md +76 -0
- package/plugins/computer_use/app/macos-system-settings.md +81 -0
- package/plugins/computer_use/app/microsoft-excel.md +80 -0
- package/plugins/computer_use/app/microsoft-powerpoint.md +80 -0
- package/plugins/computer_use/app/microsoft-word.md +79 -0
- package/plugins/computer_use/app/wechat.md +413 -0
- package/plugins/computer_use/app/weread.md +319 -0
- package/plugins/computer_use/commands/computeruse.md +25 -0
- package/plugins/computer_use/commands/cu.md +9 -0
- package/plugins/computer_use/plugin.js +26 -0
- package/plugins/computer_use/plugin.ts +30 -0
- package/plugins/computer_use/src/capture.js +90 -0
- package/plugins/computer_use/src/capture.ts +104 -0
- package/plugins/computer_use/src/commands.js +91 -0
- package/plugins/computer_use/src/commands.ts +103 -0
- package/plugins/computer_use/src/daemon.js +134 -0
- package/plugins/computer_use/src/daemon.ts +161 -0
- package/plugins/computer_use/src/manuals.js +135 -0
- package/plugins/computer_use/src/manuals.ts +159 -0
- package/plugins/computer_use/src/verify.js +168 -0
- package/plugins/computer_use/src/verify.ts +219 -0
- package/plugins/computer_use/test/commands.test.ts +73 -0
- package/plugins/cron-runner/plugin.ts +38 -0
- package/plugins/cron-runner/src/commands.ts +373 -0
- package/plugins/cron-runner/src/cronTime.ts +155 -0
- package/plugins/cron-runner/src/lock.ts +79 -0
- package/plugins/cron-runner/src/runs.ts +99 -0
- package/plugins/cron-runner/src/scheduleEngine.ts +76 -0
- package/plugins/cron-runner/src/scheduler.ts +376 -0
- package/plugins/cron-runner/src/schema.ts +139 -0
- package/plugins/cron-runner/src/service.ts +193 -0
- package/plugins/cron-runner/src/store.ts +333 -0
- package/plugins/cron-runner/src/types.ts +141 -0
- package/plugins/cron-runner/test/cronTime.test.ts +41 -0
- package/plugins/cron-runner/test/plugin-integration.test.ts +47 -0
- package/plugins/cron-runner/test/scheduleEngine.test.ts +41 -0
- package/plugins/cron-runner/test/service.test.ts +76 -0
- package/plugins/cron-runner/test/store-and-scheduler.test.ts +501 -0
- package/plugins/workflow-runner/plugin.js +56 -2
- package/plugins/workflow-runner/plugin.ts +113 -0
- package/plugins/workflow-runner/src/agentCommon.js +43 -4
- package/plugins/workflow-runner/src/agentCommon.ts +435 -0
- package/plugins/workflow-runner/src/controlFlow/branch.js +40 -0
- package/plugins/workflow-runner/src/controlFlow/branch.ts +46 -0
- package/plugins/workflow-runner/src/controlFlow/loop.js +211 -0
- package/plugins/workflow-runner/src/controlFlow/loop.ts +248 -0
- package/plugins/workflow-runner/src/controlFlow/pause.js +129 -0
- package/plugins/workflow-runner/src/controlFlow/pause.ts +141 -0
- package/plugins/workflow-runner/src/controlFlow/signal.js +21 -0
- package/plugins/workflow-runner/src/controlFlow/signal.ts +29 -0
- package/plugins/workflow-runner/src/controlFlow/types.js +18 -0
- package/plugins/workflow-runner/src/controlFlow/types.ts +63 -0
- package/plugins/workflow-runner/src/dslManifest.ts +127 -0
- package/plugins/workflow-runner/src/expressions.ts +622 -0
- package/plugins/workflow-runner/src/index.js +13 -4
- package/plugins/workflow-runner/src/index.ts +338 -0
- package/plugins/workflow-runner/src/jsonPayload.ts +84 -0
- package/plugins/workflow-runner/src/loader.js +23 -0
- package/plugins/workflow-runner/src/loader.ts +721 -0
- package/plugins/workflow-runner/src/multimodal.js +2 -1
- package/plugins/workflow-runner/src/multimodal.ts +64 -0
- package/plugins/workflow-runner/src/recovery.ts +149 -0
- package/plugins/workflow-runner/src/runner.js +75 -659
- package/plugins/workflow-runner/src/runner.ts +604 -0
- package/plugins/workflow-runner/src/stepExecutors/agent.ts +234 -0
- package/plugins/workflow-runner/src/stepExecutors/assert.ts +50 -0
- package/plugins/workflow-runner/src/stepExecutors/echo.js +31 -0
- package/plugins/workflow-runner/src/stepExecutors/echo.ts +38 -0
- package/plugins/workflow-runner/src/stepExecutors/llm.ts +133 -0
- package/plugins/workflow-runner/src/stepExecutors/set.js +49 -0
- package/plugins/workflow-runner/src/stepExecutors/set.ts +56 -0
- package/plugins/workflow-runner/src/stepExecutors/skill.js +5 -6
- package/plugins/workflow-runner/src/stepExecutors/skill.ts +140 -0
- package/plugins/workflow-runner/src/stepExecutors/tool.js +80 -8
- package/plugins/workflow-runner/src/stepExecutors/tool.ts +256 -0
- package/plugins/workflow-runner/src/stepExecutors/verify.ts +68 -0
- package/plugins/workflow-runner/src/stepPipeline.js +277 -0
- package/plugins/workflow-runner/src/stepPipeline.ts +366 -0
- package/plugins/workflow-runner/src/taskIdentity.ts +405 -0
- package/plugins/workflow-runner/src/toolRuntime.js +48 -0
- package/plugins/workflow-runner/src/toolRuntime.ts +64 -0
- package/plugins/workflow-runner/src/types.js +37 -1
- package/plugins/workflow-runner/src/types.ts +602 -0
- package/plugins/workflow-runner/src/workflowState.ts +733 -0
- package/plugins/workflow-runner/test/agent.test.ts +587 -0
- package/plugins/workflow-runner/test/agentLlmError.test.ts +373 -0
- package/plugins/workflow-runner/test/bashBlacklist.sweep.test.ts +65 -0
- package/plugins/workflow-runner/test/captureMisbind.test.ts +99 -0
- package/plugins/workflow-runner/test/cli.e2e.test.ts +147 -0
- package/plugins/workflow-runner/test/context-files.test.ts +320 -0
- package/plugins/workflow-runner/test/e2e.test.ts +370 -0
- package/plugins/workflow-runner/test/engineRobustness.test.ts +226 -0
- package/plugins/workflow-runner/test/expressions.test.ts +397 -0
- package/plugins/workflow-runner/test/foundation.test.ts +126 -0
- package/plugins/workflow-runner/test/graceful.test.ts +139 -0
- package/plugins/workflow-runner/test/greedyInputs.load.test.ts +47 -0
- package/plugins/workflow-runner/test/hostCapability.test.ts +108 -0
- package/plugins/workflow-runner/test/illustrate.load.test.ts +183 -0
- package/plugins/workflow-runner/test/jsonPayload.test.ts +83 -0
- package/plugins/workflow-runner/test/loader.test.ts +617 -0
- package/plugins/workflow-runner/test/maxTurnsRetryDelay.test.ts +33 -0
- package/plugins/workflow-runner/test/multimodal.test.ts +342 -0
- package/plugins/workflow-runner/test/output-schema.test.ts +213 -0
- package/plugins/workflow-runner/test/parseWorkflowArgs.test.ts +87 -0
- package/plugins/workflow-runner/test/pluginRunner.isolation.test.ts +269 -0
- package/plugins/workflow-runner/test/ppt.load.test.ts +1220 -0
- package/plugins/workflow-runner/test/ralphLoop.e2e.test.ts +220 -0
- package/plugins/workflow-runner/test/recovery.test.ts +265 -0
- package/plugins/workflow-runner/test/runner.test.ts +911 -0
- package/plugins/workflow-runner/test/runnerPreflight.test.ts +379 -0
- package/plugins/workflow-runner/test/skillTurnDone.test.ts +71 -0
- package/plugins/workflow-runner/test/stateLifecycle.test.ts +150 -0
- package/plugins/workflow-runner/test/stepPipeline.test.ts +114 -0
- package/plugins/workflow-runner/test/taskArbitration.test.ts +338 -0
- package/plugins/workflow-runner/test/taskIdentity.test.ts +237 -0
- package/plugins/workflow-runner/test/taskLifecycle.test.ts +270 -0
- package/plugins/workflow-runner/test/toolArtifactOverwrite.test.ts +221 -0
- package/plugins/workflow-runner/test/toolCapabilityBoundary.test.ts +29 -0
- package/plugins/workflow-runner/test/toolRuntimeIntegration.test.ts +168 -0
- package/plugins/workflow-runner/test/webppt.load.test.ts +250 -0
- package/plugins/workflow-runner/test/word.load.test.ts +208 -0
- package/plugins/workflow-runner/test/workflows.smoke.test.ts +76 -0
- package/plugins/workflow-runner/test/yamlGuardConditions.test.ts +207 -0
- package/skills/browser-automation/SKILL.md +9 -19
- package/skills/web-crawler/SKILL.md +9 -11
- package/src/askBridge.ts +249 -0
- package/src/bootstrap/cwdArg.js +10 -3
- package/src/bootstrap/cwdArg.ts +31 -0
- package/src/bootstrap/workingDir.ts +48 -0
- package/src/cli/args.js +70 -7
- package/src/cli/args.ts +146 -0
- package/src/cli/computerUse.js +185 -0
- package/src/cli/computerUse.ts +221 -0
- package/src/cli/configMenu.js +274 -202
- package/src/cli/configMenu.tsx +521 -0
- package/src/cli/memoryAccess.js +45 -0
- package/src/cli/memoryAccess.ts +53 -0
- package/src/cli/print.js +119 -5
- package/src/cli/print.ts +597 -0
- package/src/cli/quickModelSetup.js +60 -0
- package/src/cli/quickModelSetup.tsx +96 -0
- package/src/cli/streamJson.js +80 -4
- package/src/cli/streamJson.ts +433 -0
- package/src/cli/wizards/advisorWizard.js +1 -0
- package/src/cli/wizards/advisorWizard.tsx +195 -0
- package/src/cli/wizards/agentRuntimeWizard.js +84 -0
- package/src/cli/wizards/agentRuntimeWizard.tsx +134 -0
- package/src/cli/wizards/browserWizard.js +55 -0
- package/src/cli/wizards/browserWizard.tsx +77 -0
- package/src/cli/wizards/contextAdvisorWizard.js +84 -0
- package/src/cli/wizards/contextAdvisorWizard.tsx +124 -0
- package/src/cli/wizards/fieldForm.js +7 -4
- package/src/cli/wizards/fieldForm.tsx +250 -0
- package/src/cli/wizards/imageWizard.js +4 -5
- package/src/cli/wizards/imageWizard.tsx +96 -0
- package/src/cli/wizards/openRouterWizard.tsx +48 -0
- package/src/cli/wizards/providerPresets.js +1 -8
- package/src/cli/wizards/providerPresets.ts +106 -0
- package/src/cli/wizards/providerWizard.js +152 -205
- package/src/cli/wizards/providerWizard.tsx +266 -0
- package/src/cli/wizards/searchWizard.tsx +47 -0
- package/src/cli/wizards/ttsWizard.js +4 -3
- package/src/cli/wizards/ttsWizard.tsx +61 -0
- package/src/config/configDefaults.js +25 -0
- package/src/config/configDefaults.ts +33 -0
- package/src/config/configDiagnostics.js +117 -0
- package/src/config/configDiagnostics.ts +166 -0
- package/src/config/configFile.js +52 -32
- package/src/config/configFile.ts +633 -0
- package/src/config/configManagement.js +126 -0
- package/src/config/configManagement.ts +159 -0
- package/src/config/configService.js +66 -11
- package/src/config/configService.ts +554 -0
- package/src/config/numericLimits.js +61 -0
- package/src/config/numericLimits.ts +80 -0
- package/src/config.ts +109 -0
- package/src/context/agentHome.ts +11 -0
- package/src/context/archive.ts +144 -0
- package/src/context/budgetPlan.js +54 -0
- package/src/context/budgetPlan.ts +88 -0
- package/src/context/compact.js +179 -106
- package/src/context/compact.ts +584 -0
- package/src/context/contextBundle.js +119 -0
- package/src/context/contextBundle.ts +176 -0
- package/src/context/contextLock.ts +84 -0
- package/src/context/microCompactLite.ts +218 -0
- package/src/context/persistContext.ts +177 -0
- package/src/context/reactiveCompact.js +19 -4
- package/src/context/reactiveCompact.ts +240 -0
- package/src/context/recentDirs.ts +42 -0
- package/src/context/sessionPath.ts +206 -0
- package/src/context/sessionRegistry.js +8 -2
- package/src/context/sessionRegistry.ts +414 -0
- package/src/context/snipCompact.ts +163 -0
- package/src/context/tokenCounter.ts +106 -0
- package/src/context/workspaceIndex.js +2 -2
- package/src/context/workspaceIndex.ts +751 -0
- package/src/entry.compiled.tsx +20 -0
- package/src/harness/claimValidation.js +9 -0
- package/src/harness/claimValidation.ts +22 -0
- package/src/harness/evidenceLedger.js +92 -0
- package/src/harness/evidenceLedger.ts +96 -0
- package/src/harness/stallGuard.js +60 -0
- package/src/harness/stallGuard.ts +81 -0
- package/src/humanIntervention.js +129 -0
- package/src/humanIntervention.ts +216 -0
- package/src/infra/verification.ts +295 -0
- package/src/irreversible/rules.js +216 -0
- package/src/irreversible/rules.ts +261 -0
- package/src/llm/client.js +40 -3
- package/src/llm/client.ts +621 -0
- package/src/llm/promptCache.js +27 -0
- package/src/llm/promptCache.ts +41 -0
- package/src/llm/providers/anthropicFormat.js +41 -5
- package/src/llm/providers/anthropicFormat.ts +290 -0
- package/src/llm/providers/openaiFormat.js +186 -8
- package/src/llm/providers/openaiFormat.ts +428 -0
- package/src/loop.js +614 -63
- package/src/loop.ts +1454 -0
- package/src/main.js +67 -10
- package/src/main.tsx +344 -0
- package/src/memory/codec.js +204 -0
- package/src/memory/codec.ts +249 -0
- package/src/memory/constants.js +34 -0
- package/src/memory/constants.ts +50 -0
- package/src/memory/episodicMemory.js +684 -0
- package/src/memory/episodicMemory.ts +815 -0
- package/src/memory/fileStore.js +148 -0
- package/src/memory/fileStore.ts +184 -0
- package/src/memory/memoryService.js +570 -0
- package/src/memory/memoryService.ts +859 -0
- package/src/memory/migration.js +128 -0
- package/src/memory/migration.ts +160 -0
- package/src/memory/repository.js +789 -0
- package/src/memory/repository.ts +893 -0
- package/src/memory/retrieval.js +108 -0
- package/src/memory/retrieval.ts +145 -0
- package/src/memory/searchIndex.js +107 -0
- package/src/memory/searchIndex.ts +153 -0
- package/src/memory/topicView.js +82 -0
- package/src/memory/topicView.ts +95 -0
- package/src/memory/turnJournal.js +95 -0
- package/src/memory/turnJournal.ts +120 -0
- package/src/memory/types.js +2 -0
- package/src/memory/types.ts +186 -0
- package/src/messageQueue.ts +123 -0
- package/src/multimodal.js +128 -46
- package/src/multimodal.ts +349 -0
- package/src/plugin-sdk.js +21 -1
- package/src/plugin-sdk.ts +134 -0
- package/src/plugins/builtinPluginIds.js +47 -0
- package/src/plugins/builtinPluginIds.ts +51 -0
- package/src/plugins/builtinRegistry.ts +43 -0
- package/src/plugins/commandRouter.js +40 -26
- package/src/plugins/commandRouter.ts +261 -0
- package/src/plugins/hookEngine.ts +341 -0
- package/src/plugins/pluginApi.ts +133 -0
- package/src/plugins/pluginLifecycle.ts +34 -0
- package/src/plugins/pluginLoader.ts +147 -0
- package/src/plugins/pluginManifest.js +127 -0
- package/src/plugins/pluginManifest.ts +152 -0
- package/src/plugins/pluginRunner.js +47 -2
- package/src/plugins/pluginRunner.ts +207 -0
- package/src/plugins/transcript.ts +208 -0
- package/src/prompts/lint.js +169 -0
- package/src/prompts/lint.ts +220 -0
- package/src/prompts/pluginList.js +32 -16
- package/src/prompts/pluginList.ts +86 -0
- package/src/prompts/policyRegistry.js +318 -0
- package/src/prompts/policyRegistry.ts +358 -0
- package/src/prompts/projectInstructions.js +24 -0
- package/src/prompts/projectInstructions.ts +81 -0
- package/src/prompts/promptAssembly.js +311 -202
- package/src/prompts/promptAssembly.ts +510 -0
- package/src/prompts/skillList.js +106 -45
- package/src/prompts/skillList.ts +198 -0
- package/src/prompts/system.js +31 -6
- package/src/prompts/system.ts +81 -0
- package/src/runtime/agentRuntimeContext.js +53 -0
- package/src/runtime/agentRuntimeContext.ts +112 -0
- package/src/session/runAgentTurn.js +71 -12
- package/src/session/runAgentTurn.ts +181 -0
- package/src/session/runTurn.js +29 -0
- package/src/session/runTurn.ts +160 -0
- package/src/session/runtimeStore.js +149 -0
- package/src/session/runtimeStore.ts +197 -0
- package/src/session/sessionState.js +79 -3
- package/src/session/sessionState.ts +134 -0
- package/src/toolGate.ts +50 -0
- package/src/tools/advisor/advisor.js +76 -15
- package/src/tools/advisor/advisor.ts +512 -0
- package/src/tools/agent/agent.js +245 -29
- package/src/tools/agent/agent.ts +837 -0
- package/src/tools/agent/agentTaskService.js +60 -0
- package/src/tools/agent/agentTaskService.ts +113 -0
- package/src/tools/agent/agentTypes.js +20 -8
- package/src/tools/agent/agentTypes.ts +94 -0
- package/src/tools/agent/coordinator.ts +111 -0
- package/src/tools/agent/worktree.ts +296 -0
- package/src/tools/ask/ask.js +17 -0
- package/src/tools/ask/ask.ts +122 -0
- package/src/tools/bash/attachImage.js +223 -0
- package/src/tools/bash/attachImage.ts +281 -0
- package/src/tools/bash/bash.js +132 -14
- package/src/tools/bash/bash.ts +642 -0
- package/src/tools/bash/semantics.ts +103 -0
- package/src/tools/bash/warnings.js +17 -11
- package/src/tools/bash/warnings.ts +117 -0
- package/src/tools/capabilities.js +42 -0
- package/src/tools/capabilities.ts +69 -0
- package/src/tools/computeruse/accessibilityPermission.js +261 -0
- package/src/tools/computeruse/accessibilityPermission.ts +294 -0
- package/src/tools/computeruse/axSearch.js +96 -0
- package/src/tools/computeruse/axSearch.ts +120 -0
- package/src/tools/computeruse/axSnap.js +272 -0
- package/src/tools/computeruse/axSnap.ts +349 -0
- package/src/tools/computeruse/capabilityLabels.js +95 -0
- package/src/tools/computeruse/capabilityLabels.ts +115 -0
- package/src/tools/computeruse/computerUseService.js +2235 -0
- package/src/tools/computeruse/computerUseService.ts +2686 -0
- package/src/tools/computeruse/computeruse.js +2742 -0
- package/src/tools/computeruse/computeruse.ts +3265 -0
- package/src/tools/computeruse/diagnosticTrace.js +154 -0
- package/src/tools/computeruse/diagnosticTrace.ts +195 -0
- package/src/tools/computeruse/diagnostics.js +369 -0
- package/src/tools/computeruse/diagnostics.ts +453 -0
- package/src/tools/computeruse/grants.js +53 -0
- package/src/tools/computeruse/grants.ts +70 -0
- package/src/tools/computeruse/humanBoundary.js +159 -0
- package/src/tools/computeruse/humanBoundary.ts +199 -0
- package/src/tools/computeruse/intervention.js +77 -0
- package/src/tools/computeruse/intervention.ts +110 -0
- package/src/tools/computeruse/manualSchema.js +709 -0
- package/src/tools/computeruse/manualSchema.ts +916 -0
- package/src/tools/computeruse/observationImages.js +705 -0
- package/src/tools/computeruse/observationImages.ts +889 -0
- package/src/tools/computeruse/protocol.js +60 -0
- package/src/tools/computeruse/protocol.ts +515 -0
- package/src/tools/computeruse/telemetryLog.js +57 -0
- package/src/tools/computeruse/telemetryLog.ts +67 -0
- package/src/tools/computeruse/vision/appGuide.js +325 -0
- package/src/tools/computeruse/vision/appGuide.ts +482 -0
- package/src/tools/computeruse/vision/focus.js +291 -0
- package/src/tools/computeruse/vision/focus.ts +382 -0
- package/src/tools/computeruse/vision/frames.js +248 -0
- package/src/tools/computeruse/vision/frames.ts +329 -0
- package/src/tools/computeruse/vision/geometry.js +131 -0
- package/src/tools/computeruse/vision/geometry.ts +163 -0
- package/src/tools/computeruse/vision/imaging.js +201 -0
- package/src/tools/computeruse/vision/imaging.ts +281 -0
- package/src/tools/computeruse/vision/png.js +274 -0
- package/src/tools/computeruse/vision/png.ts +317 -0
- package/src/tools/computeruse/vision/raster.js +320 -0
- package/src/tools/computeruse/vision/raster.ts +408 -0
- package/src/tools/computeruse/vision/settle.js +131 -0
- package/src/tools/computeruse/vision/settle.ts +220 -0
- package/src/tools/computeruse/vision/telemetry.js +196 -0
- package/src/tools/computeruse/vision/telemetry.ts +241 -0
- package/src/tools/computeruse/visionOcr.js +115 -0
- package/src/tools/computeruse/visionOcr.ts +128 -0
- package/src/tools/computeruse/waitFor.js +237 -0
- package/src/tools/computeruse/waitFor.ts +291 -0
- package/src/tools/download/download.js +10 -6
- package/src/tools/download/download.ts +187 -0
- package/src/tools/edit/edit.js +30 -18
- package/src/tools/edit/edit.ts +349 -0
- package/src/tools/edit/multi-edit.js +25 -14
- package/src/tools/edit/multi-edit.ts +223 -0
- package/src/tools/effectiveToolSet.js +73 -0
- package/src/tools/effectiveToolSet.ts +91 -0
- package/src/tools/genimage/genimage.ts +257 -0
- package/src/tools/genspeech/genspeech.ts +83 -0
- package/src/tools/glob/glob.js +176 -29
- package/src/tools/glob/glob.ts +283 -0
- package/src/tools/grep/grep.js +61 -19
- package/src/tools/grep/grep.ts +239 -0
- package/src/tools/grep/rgPath.ts +206 -0
- package/src/tools/index.js +99 -5
- package/src/tools/index.ts +293 -0
- package/src/tools/lsp/config.js +113 -0
- package/src/tools/lsp/config.ts +113 -0
- package/src/tools/lsp/lsp.js +256 -0
- package/src/tools/lsp/lsp.ts +274 -0
- package/src/tools/lsp/service.js +303 -0
- package/src/tools/lsp/service.ts +296 -0
- package/src/tools/memory/memory.js +520 -0
- package/src/tools/memory/memory.ts +625 -0
- package/src/tools/memory/policy.js +53 -0
- package/src/tools/memory/policy.ts +72 -0
- package/src/tools/notebook/notebookEdit.js +114 -0
- package/src/tools/notebook/notebookEdit.ts +126 -0
- package/src/tools/powershell/powershell.js +210 -0
- package/src/tools/powershell/powershell.ts +239 -0
- package/src/tools/presentresult/presentresult.js +145 -0
- package/src/tools/presentresult/presentresult.ts +156 -0
- package/src/tools/read/read.js +371 -163
- package/src/tools/read/read.ts +558 -0
- package/src/tools/shared/diffSummary.js +44 -0
- package/src/tools/shared/diffSummary.ts +63 -0
- package/src/tools/shared/fileActivity.js +51 -0
- package/src/tools/shared/fileActivity.ts +66 -0
- package/src/tools/shared/fileMutationBus.js +13 -0
- package/src/tools/shared/fileMutationBus.ts +14 -0
- package/src/tools/shared/fileState.js +73 -65
- package/src/tools/shared/fileState.ts +145 -0
- package/src/tools/shared/fileUtils.js +81 -4
- package/src/tools/shared/fileUtils.ts +504 -0
- package/src/tools/shared/killTree.ts +50 -0
- package/src/tools/shared/permanentDeleteGuard.js +26 -0
- package/src/tools/shared/permanentDeleteGuard.ts +34 -0
- package/src/tools/shared/schemas.ts +20 -0
- package/src/tools/shared/toolOutputStore.js +97 -0
- package/src/tools/shared/toolOutputStore.ts +110 -0
- package/src/tools/skill/skill.js +86 -0
- package/src/tools/skill/skill.ts +94 -0
- package/src/tools/snip/snip.js +67 -0
- package/src/tools/snip/snip.ts +80 -0
- package/src/tools/tasks/backgroundTaskService.js +275 -0
- package/src/tools/tasks/backgroundTaskService.ts +369 -0
- package/src/tools/tasks/processEvidence.js +24 -0
- package/src/tools/tasks/processEvidence.ts +34 -0
- package/src/tools/tasks/taskManagement.js +163 -0
- package/src/tools/tasks/taskManagement.ts +180 -0
- package/src/tools/tasks/taskOutput.js +113 -0
- package/src/tools/tasks/taskOutput.ts +145 -0
- package/src/tools/tasks/taskStop.js +74 -0
- package/src/tools/tasks/taskStop.ts +99 -0
- package/src/tools/tasks/taskStore.js +46 -0
- package/src/tools/tasks/taskStore.ts +77 -0
- package/src/tools/terminal/terminalCapture.js +167 -0
- package/src/tools/terminal/terminalCapture.ts +179 -0
- package/src/tools/trash/trash.js +233 -0
- package/src/tools/trash/trash.ts +283 -0
- package/src/tools/types.js +1 -1
- package/src/tools/types.ts +24 -0
- package/src/tools/webbrowser/agentBrowserPath.ts +286 -0
- package/src/tools/webbrowser/browser.js +214 -11
- package/src/tools/webbrowser/browser.ts +293 -0
- package/src/tools/webbrowser/browserControl.js +153 -48
- package/src/tools/webbrowser/browserControl.ts +262 -0
- package/src/tools/webbrowser/browserDaemon.js +147 -39
- package/src/tools/webbrowser/browserDaemon.ts +270 -0
- package/src/tools/webbrowser/browserOutcome.js +273 -0
- package/src/tools/webbrowser/browserOutcome.ts +306 -0
- package/src/tools/webbrowser/browserRunRegistry.js +150 -0
- package/src/tools/webbrowser/browserRunRegistry.ts +179 -0
- package/src/tools/webbrowser/browserService.js +20 -6
- package/src/tools/webbrowser/browserService.ts +56 -0
- package/src/tools/webbrowser/browserStream.js +30 -1
- package/src/tools/webbrowser/browserStream.ts +216 -0
- package/src/tools/webbrowser/browserTabs.js +143 -0
- package/src/tools/webbrowser/browserTabs.ts +210 -0
- package/src/tools/webbrowser/webbrowser.js +831 -150
- package/src/tools/webbrowser/webbrowser.ts +1537 -0
- package/src/tools/webfetch/preapproved.ts +274 -0
- package/src/tools/webfetch/webfetch.js +24 -23
- package/src/tools/webfetch/webfetch.ts +383 -0
- package/src/tools/websearch/websearch.js +12 -11
- package/src/tools/websearch/websearch.ts +292 -0
- package/src/tools/worktree/sessionWorktree.js +128 -0
- package/src/tools/worktree/sessionWorktree.ts +158 -0
- package/src/tools/write/write.js +27 -44
- package/src/tools/write/write.ts +136 -0
- package/src/types.ts +960 -0
- package/src/ui/App.js +216 -12
- package/src/ui/App.tsx +879 -0
- package/src/ui/AskQuestion.tsx +300 -0
- package/src/ui/InputBox.js +77 -1
- package/src/ui/InputBox.tsx +567 -0
- package/src/ui/LiveArea.tsx +344 -0
- package/src/ui/MessageList.js +27 -6
- package/src/ui/MessageList.tsx +559 -0
- package/src/ui/ModelPicker.tsx +107 -0
- package/src/ui/QueuedMessagesBanner.tsx +51 -0
- package/src/ui/Root.js +6 -8
- package/src/ui/Root.tsx +100 -0
- package/src/ui/SessionPicker.tsx +169 -0
- package/src/ui/StatusLine.js +22 -1
- package/src/ui/StatusLine.tsx +145 -0
- package/src/ui/WorkspacePicker.tsx +84 -0
- package/src/ui/advisorCommand.js +54 -0
- package/src/ui/advisorCommand.ts +63 -0
- package/src/ui/computerCommand.js +19 -0
- package/src/ui/computerCommand.ts +35 -0
- package/src/ui/figures.ts +45 -0
- package/src/ui/hooks/askSlot.ts +112 -0
- package/src/ui/hooks/useChat.js +271 -7
- package/src/ui/hooks/useChat.ts +1578 -0
- package/src/ui/hooks/useInputHistory.ts +235 -0
- package/src/ui/hooks/usePasteHandler.ts +220 -0
- package/src/ui/hooks/useTerminalSize.ts +41 -0
- package/src/ui/hooks/useTextBuffer.ts +108 -0
- package/src/ui/hooks/useTokenUsage.ts +44 -0
- package/src/ui/liveViewport.ts +189 -0
- package/src/ui/markdown.ts +230 -0
- package/src/ui/textBuffer.ts +239 -0
- package/src/ui/theme.ts +35 -0
- package/src/utils/clipboardImage.js +358 -0
- package/src/utils/clipboardImage.ts +420 -0
- package/src/utils/debugLog.ts +50 -0
- package/src/utils/greenRoot.ts +35 -0
- package/src/utils/packageRoot.ts +40 -0
- package/src/utils/pathContains.js +28 -0
- package/src/utils/pathContains.ts +31 -0
- package/src/utils/resourcePaths.ts +71 -0
- package/src/utils/stripThink.ts +49 -0
- package/src/utils/zodToJson.ts +73 -0
- package/src/web/browserBridge.js +365 -66
- package/src/web/browserBridge.ts +672 -0
- package/src/web/protocol.ts +1804 -0
- package/vendor/computer-use/arm64-darwin/cu-helperd +0 -0
- package/workflows/ppt.yaml +13 -2
- package/workflows/wechat-reading-shots.yaml +315 -0
- package/workflows/word.yaml +11 -1
- package/skills/docx/scripts/office/helpers/__pycache__/__init__.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/helpers/__pycache__/merge_runs.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/helpers/__pycache__/simplify_redlines.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/validators/__pycache__/__init__.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/validators/__pycache__/base.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/validators/__pycache__/docx.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/validators/__pycache__/pptx.cpython-314.pyc +0 -0
- package/skills/docx/scripts/office/validators/__pycache__/redlining.cpython-314.pyc +0 -0
- package/skills/image-stats/scripts/__pycache__/image_stats.cpython-314.pyc +0 -0
- package/skills/image-stats/scripts/__pycache__/image_stats_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/assemble_material.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/assemble_material_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/chart_sanity_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/check_language_policy.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/check_ui_artifact.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/check_ui_artifact_pptx_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/deck_pages_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/deck_pages_check_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/deck_visual_style_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/deck_visual_style_check_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/design_budget_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/design_budget_check_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/design_repair_hints.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/design_repair_hints_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/design_style_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/design_style_check_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/draft_coverage_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/extract_source_assets.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/extract_source_assets_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/generated_image_review_collect.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/generated_image_review_collect_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/image_plan_lint.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/image_plan_lint_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/image_prompt_rewrite.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/image_prompt_rewrite_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/layout_balance.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/layout_balance_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/normalize_design_json.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/normalize_design_json_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/plan_source_layout.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/plan_source_layout_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/resolve_source_hint.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/resolve_source_hint_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/resolve_source_input.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/resolve_source_input_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/scaffold_ui_artifact.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/source_usage_check.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/source_usage_check_test.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/text_readability_pixel.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/visual_quality_gate.cpython-314.pyc +0 -0
- package/skills/ui-design/scripts/__pycache__/visual_quality_gate_test.cpython-314.pyc +0 -0
- /package/skills/ai-image/scripts/{generate_test.mjs → generate.selftest.mjs} +0 -0
- /package/skills/ai-image/scripts/{generate_from_plan_test.mjs → generate_from_plan.selftest.mjs} +0 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { countTextTokens } from '../context/tokenCounter.js';
|
|
2
|
+
import { DEFAULT_REVIEW_WINDOWS } from './constants.js';
|
|
3
|
+
import { BM25_DOCUMENT_THRESHOLD, Bm25Index, recordSearchIndexBuild, recordSearchIndexCacheHit, recordSearchIndexFallback, recordSearchStrategy, searchTerms, } from './searchIndex.js';
|
|
4
|
+
const snapshotIndexes = new WeakMap();
|
|
5
|
+
export function memoryTerms(query) {
|
|
6
|
+
return searchTerms(query);
|
|
7
|
+
}
|
|
8
|
+
export function isReviewDue(record, settings, now = Date.now()) {
|
|
9
|
+
const days = settings.reviewAfterDays?.[record.category] ??
|
|
10
|
+
DEFAULT_REVIEW_WINDOWS[record.category];
|
|
11
|
+
return now - record.lastConfirmedAt > days * 86_400_000;
|
|
12
|
+
}
|
|
13
|
+
export function scoreMemory(record, query, settings) {
|
|
14
|
+
if (record.status === 'superseded')
|
|
15
|
+
return Number.NEGATIVE_INFINITY;
|
|
16
|
+
const haystack = `${record.category} ${record.subject} ${record.topicKey} ${record.aliases.join(' ')} ${record.statement}`.toLocaleLowerCase();
|
|
17
|
+
const terms = memoryTerms(query);
|
|
18
|
+
const lexical = terms.reduce((sum, term) => sum + (haystack.includes(term) ? 10 : 0), 0);
|
|
19
|
+
const phrase = query.trim() && haystack.includes(query.trim().toLocaleLowerCase())
|
|
20
|
+
? 25
|
|
21
|
+
: 0;
|
|
22
|
+
const stalePenalty = isReviewDue(record, settings) || record.status === 'needs_review' ? 8 : 0;
|
|
23
|
+
return lexical + phrase - stalePenalty + record.lastConfirmedAt / 1e13;
|
|
24
|
+
}
|
|
25
|
+
export function recallFromSnapshot(snapshot, query, settings, limit) {
|
|
26
|
+
const eligible = snapshot.records.filter((record) => record.status !== 'superseded');
|
|
27
|
+
if (!query.trim() || eligible.length < BM25_DOCUMENT_THRESHOLD) {
|
|
28
|
+
recordSearchStrategy('lexical', eligible.length);
|
|
29
|
+
return snapshot.records
|
|
30
|
+
.map((record) => ({ record, score: scoreMemory(record, query, settings) }))
|
|
31
|
+
.filter((item) => Number.isFinite(item.score) && (!query.trim() || item.score >= 2))
|
|
32
|
+
.sort((a, b) => b.score - a.score)
|
|
33
|
+
.slice(0, Math.min(100, Math.max(1, limit)))
|
|
34
|
+
.map((item) => item.record);
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
let index = snapshotIndexes.get(snapshot);
|
|
38
|
+
if (!index) {
|
|
39
|
+
index = new Bm25Index(eligible.map((record) => ({
|
|
40
|
+
id: record.id,
|
|
41
|
+
fields: [
|
|
42
|
+
{ text: record.subject, weight: 4 },
|
|
43
|
+
{ text: record.aliases.join(' '), weight: 3 },
|
|
44
|
+
{ text: `${record.topicKey} ${record.category}`, weight: 2 },
|
|
45
|
+
{ text: record.statement, weight: 1 },
|
|
46
|
+
],
|
|
47
|
+
})));
|
|
48
|
+
snapshotIndexes.set(snapshot, index);
|
|
49
|
+
recordSearchIndexBuild();
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
recordSearchIndexCacheHit();
|
|
53
|
+
}
|
|
54
|
+
recordSearchStrategy('bm25', eligible.length);
|
|
55
|
+
const bm25 = index.search(query);
|
|
56
|
+
const normalized = query.trim().toLocaleLowerCase();
|
|
57
|
+
return eligible
|
|
58
|
+
.map((record) => {
|
|
59
|
+
const haystack = `${record.category} ${record.subject} ${record.topicKey} ${record.aliases.join(' ')} ${record.statement}`.toLocaleLowerCase();
|
|
60
|
+
const phrase = normalized && haystack.includes(normalized) ? 25 : 0;
|
|
61
|
+
const stalePenalty = isReviewDue(record, settings) || record.status === 'needs_review' ? 8 : 0;
|
|
62
|
+
return {
|
|
63
|
+
record,
|
|
64
|
+
score: (bm25.get(record.id) ?? 0) * 10 + phrase - stalePenalty + record.lastConfirmedAt / 1e13,
|
|
65
|
+
};
|
|
66
|
+
})
|
|
67
|
+
.filter((item) => (bm25.get(item.record.id) ?? 0) > 0)
|
|
68
|
+
.sort((a, b) => b.score - a.score)
|
|
69
|
+
.slice(0, Math.min(100, Math.max(1, limit)))
|
|
70
|
+
.map((item) => item.record);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
recordSearchIndexFallback();
|
|
74
|
+
recordSearchStrategy('lexical', eligible.length);
|
|
75
|
+
return snapshot.records
|
|
76
|
+
.map((record) => ({ record, score: scoreMemory(record, query, settings) }))
|
|
77
|
+
.filter((item) => Number.isFinite(item.score) && item.score >= 2)
|
|
78
|
+
.sort((a, b) => b.score - a.score)
|
|
79
|
+
.slice(0, Math.min(100, Math.max(1, limit)))
|
|
80
|
+
.map((item) => item.record);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function takeTokenBudget(lines, maxTokens) {
|
|
84
|
+
const result = [];
|
|
85
|
+
let used = 0;
|
|
86
|
+
for (const line of lines) {
|
|
87
|
+
const tokens = countTextTokens(line);
|
|
88
|
+
if (used + tokens > maxTokens)
|
|
89
|
+
break;
|
|
90
|
+
result.push(line);
|
|
91
|
+
used += tokens;
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
export function truncateTokenBudget(text, maxTokens) {
|
|
96
|
+
if (countTextTokens(text) <= maxTokens)
|
|
97
|
+
return text;
|
|
98
|
+
let low = 0;
|
|
99
|
+
let high = text.length;
|
|
100
|
+
while (low < high) {
|
|
101
|
+
const middle = Math.ceil((low + high) / 2);
|
|
102
|
+
if (countTextTokens(text.slice(0, middle)) <= maxTokens)
|
|
103
|
+
low = middle;
|
|
104
|
+
else
|
|
105
|
+
high = middle - 1;
|
|
106
|
+
}
|
|
107
|
+
return `${text.slice(0, low).trimEnd()}…`;
|
|
108
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { countTextTokens } from '../context/tokenCounter.js';
|
|
2
|
+
import { DEFAULT_REVIEW_WINDOWS } from './constants.js';
|
|
3
|
+
import type {
|
|
4
|
+
MemoryRecordV2,
|
|
5
|
+
MemorySettings,
|
|
6
|
+
MemorySnapshot,
|
|
7
|
+
} from './types.js';
|
|
8
|
+
import {
|
|
9
|
+
BM25_DOCUMENT_THRESHOLD,
|
|
10
|
+
Bm25Index,
|
|
11
|
+
recordSearchIndexBuild,
|
|
12
|
+
recordSearchIndexCacheHit,
|
|
13
|
+
recordSearchIndexFallback,
|
|
14
|
+
recordSearchStrategy,
|
|
15
|
+
searchTerms,
|
|
16
|
+
} from './searchIndex.js';
|
|
17
|
+
|
|
18
|
+
const snapshotIndexes = new WeakMap<MemorySnapshot, Bm25Index>();
|
|
19
|
+
|
|
20
|
+
export function memoryTerms(query: string): string[] {
|
|
21
|
+
return searchTerms(query);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isReviewDue(
|
|
25
|
+
record: MemoryRecordV2,
|
|
26
|
+
settings: MemorySettings,
|
|
27
|
+
now = Date.now(),
|
|
28
|
+
): boolean {
|
|
29
|
+
const days =
|
|
30
|
+
settings.reviewAfterDays?.[record.category] ??
|
|
31
|
+
DEFAULT_REVIEW_WINDOWS[record.category];
|
|
32
|
+
return now - record.lastConfirmedAt > days * 86_400_000;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function scoreMemory(
|
|
36
|
+
record: MemoryRecordV2,
|
|
37
|
+
query: string,
|
|
38
|
+
settings: MemorySettings,
|
|
39
|
+
): number {
|
|
40
|
+
if (record.status === 'superseded') return Number.NEGATIVE_INFINITY;
|
|
41
|
+
const haystack =
|
|
42
|
+
`${record.category} ${record.subject} ${record.topicKey} ${record.aliases.join(' ')} ${record.statement}`.toLocaleLowerCase();
|
|
43
|
+
const terms = memoryTerms(query);
|
|
44
|
+
const lexical = terms.reduce(
|
|
45
|
+
(sum, term) => sum + (haystack.includes(term) ? 10 : 0),
|
|
46
|
+
0,
|
|
47
|
+
);
|
|
48
|
+
const phrase =
|
|
49
|
+
query.trim() && haystack.includes(query.trim().toLocaleLowerCase())
|
|
50
|
+
? 25
|
|
51
|
+
: 0;
|
|
52
|
+
const stalePenalty =
|
|
53
|
+
isReviewDue(record, settings) || record.status === 'needs_review' ? 8 : 0;
|
|
54
|
+
return lexical + phrase - stalePenalty + record.lastConfirmedAt / 1e13;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function recallFromSnapshot(
|
|
58
|
+
snapshot: MemorySnapshot,
|
|
59
|
+
query: string,
|
|
60
|
+
settings: MemorySettings,
|
|
61
|
+
limit: number,
|
|
62
|
+
): MemoryRecordV2[] {
|
|
63
|
+
const eligible = snapshot.records.filter((record) => record.status !== 'superseded');
|
|
64
|
+
if (!query.trim() || eligible.length < BM25_DOCUMENT_THRESHOLD) {
|
|
65
|
+
recordSearchStrategy('lexical', eligible.length);
|
|
66
|
+
return snapshot.records
|
|
67
|
+
.map((record) => ({ record, score: scoreMemory(record, query, settings) }))
|
|
68
|
+
.filter(
|
|
69
|
+
(item) =>
|
|
70
|
+
Number.isFinite(item.score) && (!query.trim() || item.score >= 2),
|
|
71
|
+
)
|
|
72
|
+
.sort((a, b) => b.score - a.score)
|
|
73
|
+
.slice(0, Math.min(100, Math.max(1, limit)))
|
|
74
|
+
.map((item) => item.record);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
let index = snapshotIndexes.get(snapshot);
|
|
79
|
+
if (!index) {
|
|
80
|
+
index = new Bm25Index(eligible.map((record) => ({
|
|
81
|
+
id: record.id,
|
|
82
|
+
fields: [
|
|
83
|
+
{ text: record.subject, weight: 4 },
|
|
84
|
+
{ text: record.aliases.join(' '), weight: 3 },
|
|
85
|
+
{ text: `${record.topicKey} ${record.category}`, weight: 2 },
|
|
86
|
+
{ text: record.statement, weight: 1 },
|
|
87
|
+
],
|
|
88
|
+
})));
|
|
89
|
+
snapshotIndexes.set(snapshot, index);
|
|
90
|
+
recordSearchIndexBuild();
|
|
91
|
+
} else {
|
|
92
|
+
recordSearchIndexCacheHit();
|
|
93
|
+
}
|
|
94
|
+
recordSearchStrategy('bm25', eligible.length);
|
|
95
|
+
const bm25 = index.search(query);
|
|
96
|
+
const normalized = query.trim().toLocaleLowerCase();
|
|
97
|
+
return eligible
|
|
98
|
+
.map((record) => {
|
|
99
|
+
const haystack = `${record.category} ${record.subject} ${record.topicKey} ${record.aliases.join(' ')} ${record.statement}`.toLocaleLowerCase();
|
|
100
|
+
const phrase = normalized && haystack.includes(normalized) ? 25 : 0;
|
|
101
|
+
const stalePenalty = isReviewDue(record, settings) || record.status === 'needs_review' ? 8 : 0;
|
|
102
|
+
return {
|
|
103
|
+
record,
|
|
104
|
+
score: (bm25.get(record.id) ?? 0) * 10 + phrase - stalePenalty + record.lastConfirmedAt / 1e13,
|
|
105
|
+
};
|
|
106
|
+
})
|
|
107
|
+
.filter((item) => (bm25.get(item.record.id) ?? 0) > 0)
|
|
108
|
+
.sort((a, b) => b.score - a.score)
|
|
109
|
+
.slice(0, Math.min(100, Math.max(1, limit)))
|
|
110
|
+
.map((item) => item.record);
|
|
111
|
+
} catch {
|
|
112
|
+
recordSearchIndexFallback();
|
|
113
|
+
recordSearchStrategy('lexical', eligible.length);
|
|
114
|
+
return snapshot.records
|
|
115
|
+
.map((record) => ({ record, score: scoreMemory(record, query, settings) }))
|
|
116
|
+
.filter((item) => Number.isFinite(item.score) && item.score >= 2)
|
|
117
|
+
.sort((a, b) => b.score - a.score)
|
|
118
|
+
.slice(0, Math.min(100, Math.max(1, limit)))
|
|
119
|
+
.map((item) => item.record);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function takeTokenBudget(lines: string[], maxTokens: number): string[] {
|
|
124
|
+
const result: string[] = [];
|
|
125
|
+
let used = 0;
|
|
126
|
+
for (const line of lines) {
|
|
127
|
+
const tokens = countTextTokens(line);
|
|
128
|
+
if (used + tokens > maxTokens) break;
|
|
129
|
+
result.push(line);
|
|
130
|
+
used += tokens;
|
|
131
|
+
}
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function truncateTokenBudget(text: string, maxTokens: number): string {
|
|
136
|
+
if (countTextTokens(text) <= maxTokens) return text;
|
|
137
|
+
let low = 0;
|
|
138
|
+
let high = text.length;
|
|
139
|
+
while (low < high) {
|
|
140
|
+
const middle = Math.ceil((low + high) / 2);
|
|
141
|
+
if (countTextTokens(text.slice(0, middle)) <= maxTokens) low = middle;
|
|
142
|
+
else high = middle - 1;
|
|
143
|
+
}
|
|
144
|
+
return `${text.slice(0, low).trimEnd()}…`;
|
|
145
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export const BM25_DOCUMENT_THRESHOLD = 200;
|
|
2
|
+
const BM25_K1 = 1.2;
|
|
3
|
+
const BM25_B = 0.75;
|
|
4
|
+
const diagnostics = {
|
|
5
|
+
builds: 0,
|
|
6
|
+
cacheHits: 0,
|
|
7
|
+
queries: 0,
|
|
8
|
+
fallbacks: 0,
|
|
9
|
+
lastStrategy: 'lexical',
|
|
10
|
+
lastDocumentCount: 0,
|
|
11
|
+
};
|
|
12
|
+
export function searchIndexDiagnostics() {
|
|
13
|
+
return { ...diagnostics };
|
|
14
|
+
}
|
|
15
|
+
export function resetSearchIndexDiagnostics() {
|
|
16
|
+
diagnostics.builds = 0;
|
|
17
|
+
diagnostics.cacheHits = 0;
|
|
18
|
+
diagnostics.queries = 0;
|
|
19
|
+
diagnostics.fallbacks = 0;
|
|
20
|
+
diagnostics.lastStrategy = 'lexical';
|
|
21
|
+
diagnostics.lastDocumentCount = 0;
|
|
22
|
+
}
|
|
23
|
+
export function recordSearchStrategy(strategy, documentCount) {
|
|
24
|
+
diagnostics.queries += 1;
|
|
25
|
+
diagnostics.lastStrategy = strategy;
|
|
26
|
+
diagnostics.lastDocumentCount = documentCount;
|
|
27
|
+
}
|
|
28
|
+
export function recordSearchIndexBuild() {
|
|
29
|
+
diagnostics.builds += 1;
|
|
30
|
+
}
|
|
31
|
+
export function recordSearchIndexCacheHit() {
|
|
32
|
+
diagnostics.cacheHits += 1;
|
|
33
|
+
}
|
|
34
|
+
export function recordSearchIndexFallback() {
|
|
35
|
+
diagnostics.fallbacks += 1;
|
|
36
|
+
}
|
|
37
|
+
/** Shared dependency-free tokenizer for lexical and BM25 retrieval. */
|
|
38
|
+
function tokenizeSearchText(input) {
|
|
39
|
+
const normalized = input.normalize('NFKC').toLocaleLowerCase();
|
|
40
|
+
const tokens = normalized
|
|
41
|
+
.split(/[\s,,。;;::/\\()[\]{}"'`!?!?\p{P}\p{S}]+/u)
|
|
42
|
+
.filter((item) => item.length > 1);
|
|
43
|
+
const cjkSequences = normalized.match(/[\p{Script=Han}]{2,}/gu) ?? [];
|
|
44
|
+
for (const sequence of cjkSequences) {
|
|
45
|
+
for (let index = 0; index < sequence.length - 1; index += 1) {
|
|
46
|
+
tokens.push(sequence.slice(index, index + 2));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return tokens;
|
|
50
|
+
}
|
|
51
|
+
export function searchTerms(input) {
|
|
52
|
+
return Array.from(new Set(tokenizeSearchText(input)));
|
|
53
|
+
}
|
|
54
|
+
export class Bm25Index {
|
|
55
|
+
documentCount;
|
|
56
|
+
documents;
|
|
57
|
+
documentFrequency = new Map();
|
|
58
|
+
averageLength;
|
|
59
|
+
constructor(input) {
|
|
60
|
+
this.documents = input.map((document) => {
|
|
61
|
+
const frequencies = new Map();
|
|
62
|
+
let length = 0;
|
|
63
|
+
for (const field of document.fields) {
|
|
64
|
+
if (!field.text || field.weight <= 0)
|
|
65
|
+
continue;
|
|
66
|
+
const terms = tokenizeSearchText(field.text);
|
|
67
|
+
length += terms.length * field.weight;
|
|
68
|
+
for (const term of terms) {
|
|
69
|
+
frequencies.set(term, (frequencies.get(term) ?? 0) + field.weight);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const term of frequencies.keys()) {
|
|
73
|
+
this.documentFrequency.set(term, (this.documentFrequency.get(term) ?? 0) + 1);
|
|
74
|
+
}
|
|
75
|
+
return { id: document.id, length: Math.max(1, length), frequencies };
|
|
76
|
+
});
|
|
77
|
+
this.documentCount = this.documents.length;
|
|
78
|
+
this.averageLength = this.documentCount
|
|
79
|
+
? this.documents.reduce((sum, document) => sum + document.length, 0)
|
|
80
|
+
/ this.documentCount
|
|
81
|
+
: 1;
|
|
82
|
+
}
|
|
83
|
+
search(query) {
|
|
84
|
+
const terms = searchTerms(query);
|
|
85
|
+
const scores = new Map();
|
|
86
|
+
if (!terms.length || !this.documentCount)
|
|
87
|
+
return scores;
|
|
88
|
+
for (const document of this.documents) {
|
|
89
|
+
let score = 0;
|
|
90
|
+
for (const term of terms) {
|
|
91
|
+
const frequency = document.frequencies.get(term) ?? 0;
|
|
92
|
+
if (!frequency)
|
|
93
|
+
continue;
|
|
94
|
+
const documentFrequency = this.documentFrequency.get(term) ?? 0;
|
|
95
|
+
const inverseDocumentFrequency = Math.log(1 + (this.documentCount - documentFrequency + 0.5)
|
|
96
|
+
/ (documentFrequency + 0.5));
|
|
97
|
+
const normalization = frequency
|
|
98
|
+
+ BM25_K1 * (1 - BM25_B + BM25_B * document.length / this.averageLength);
|
|
99
|
+
score += inverseDocumentFrequency
|
|
100
|
+
* (frequency * (BM25_K1 + 1)) / normalization;
|
|
101
|
+
}
|
|
102
|
+
if (score > 0)
|
|
103
|
+
scores.set(document.id, score);
|
|
104
|
+
}
|
|
105
|
+
return scores;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
export const BM25_DOCUMENT_THRESHOLD = 200;
|
|
2
|
+
|
|
3
|
+
const BM25_K1 = 1.2;
|
|
4
|
+
const BM25_B = 0.75;
|
|
5
|
+
|
|
6
|
+
export type SearchStrategy = 'lexical' | 'bm25';
|
|
7
|
+
|
|
8
|
+
export interface WeightedSearchField {
|
|
9
|
+
text: string;
|
|
10
|
+
weight: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface WeightedSearchDocument {
|
|
14
|
+
id: string;
|
|
15
|
+
fields: WeightedSearchField[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface IndexedDocument {
|
|
19
|
+
id: string;
|
|
20
|
+
length: number;
|
|
21
|
+
frequencies: Map<string, number>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface SearchIndexDiagnostics {
|
|
25
|
+
builds: number;
|
|
26
|
+
cacheHits: number;
|
|
27
|
+
queries: number;
|
|
28
|
+
fallbacks: number;
|
|
29
|
+
lastStrategy: SearchStrategy;
|
|
30
|
+
lastDocumentCount: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const diagnostics: SearchIndexDiagnostics = {
|
|
34
|
+
builds: 0,
|
|
35
|
+
cacheHits: 0,
|
|
36
|
+
queries: 0,
|
|
37
|
+
fallbacks: 0,
|
|
38
|
+
lastStrategy: 'lexical',
|
|
39
|
+
lastDocumentCount: 0,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export function searchIndexDiagnostics(): Readonly<SearchIndexDiagnostics> {
|
|
43
|
+
return { ...diagnostics };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function resetSearchIndexDiagnostics(): void {
|
|
47
|
+
diagnostics.builds = 0;
|
|
48
|
+
diagnostics.cacheHits = 0;
|
|
49
|
+
diagnostics.queries = 0;
|
|
50
|
+
diagnostics.fallbacks = 0;
|
|
51
|
+
diagnostics.lastStrategy = 'lexical';
|
|
52
|
+
diagnostics.lastDocumentCount = 0;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function recordSearchStrategy(
|
|
56
|
+
strategy: SearchStrategy,
|
|
57
|
+
documentCount: number,
|
|
58
|
+
): void {
|
|
59
|
+
diagnostics.queries += 1;
|
|
60
|
+
diagnostics.lastStrategy = strategy;
|
|
61
|
+
diagnostics.lastDocumentCount = documentCount;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function recordSearchIndexBuild(): void {
|
|
65
|
+
diagnostics.builds += 1;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function recordSearchIndexCacheHit(): void {
|
|
69
|
+
diagnostics.cacheHits += 1;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function recordSearchIndexFallback(): void {
|
|
73
|
+
diagnostics.fallbacks += 1;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Shared dependency-free tokenizer for lexical and BM25 retrieval. */
|
|
77
|
+
function tokenizeSearchText(input: string): string[] {
|
|
78
|
+
const normalized = input.normalize('NFKC').toLocaleLowerCase();
|
|
79
|
+
const tokens = normalized
|
|
80
|
+
.split(/[\s,,。;;::/\\()[\]{}"'`!?!?\p{P}\p{S}]+/u)
|
|
81
|
+
.filter((item) => item.length > 1);
|
|
82
|
+
const cjkSequences = normalized.match(/[\p{Script=Han}]{2,}/gu) ?? [];
|
|
83
|
+
for (const sequence of cjkSequences) {
|
|
84
|
+
for (let index = 0; index < sequence.length - 1; index += 1) {
|
|
85
|
+
tokens.push(sequence.slice(index, index + 2));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return tokens;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function searchTerms(input: string): string[] {
|
|
92
|
+
return Array.from(new Set(tokenizeSearchText(input)));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export class Bm25Index {
|
|
96
|
+
readonly documentCount: number;
|
|
97
|
+
private readonly documents: IndexedDocument[];
|
|
98
|
+
private readonly documentFrequency = new Map<string, number>();
|
|
99
|
+
private readonly averageLength: number;
|
|
100
|
+
|
|
101
|
+
constructor(input: readonly WeightedSearchDocument[]) {
|
|
102
|
+
this.documents = input.map((document) => {
|
|
103
|
+
const frequencies = new Map<string, number>();
|
|
104
|
+
let length = 0;
|
|
105
|
+
for (const field of document.fields) {
|
|
106
|
+
if (!field.text || field.weight <= 0) continue;
|
|
107
|
+
const terms = tokenizeSearchText(field.text);
|
|
108
|
+
length += terms.length * field.weight;
|
|
109
|
+
for (const term of terms) {
|
|
110
|
+
frequencies.set(term, (frequencies.get(term) ?? 0) + field.weight);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
for (const term of frequencies.keys()) {
|
|
114
|
+
this.documentFrequency.set(
|
|
115
|
+
term,
|
|
116
|
+
(this.documentFrequency.get(term) ?? 0) + 1,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return { id: document.id, length: Math.max(1, length), frequencies };
|
|
120
|
+
});
|
|
121
|
+
this.documentCount = this.documents.length;
|
|
122
|
+
this.averageLength = this.documentCount
|
|
123
|
+
? this.documents.reduce((sum, document) => sum + document.length, 0)
|
|
124
|
+
/ this.documentCount
|
|
125
|
+
: 1;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
search(query: string): Map<string, number> {
|
|
129
|
+
const terms = searchTerms(query);
|
|
130
|
+
const scores = new Map<string, number>();
|
|
131
|
+
if (!terms.length || !this.documentCount) return scores;
|
|
132
|
+
for (const document of this.documents) {
|
|
133
|
+
let score = 0;
|
|
134
|
+
for (const term of terms) {
|
|
135
|
+
const frequency = document.frequencies.get(term) ?? 0;
|
|
136
|
+
if (!frequency) continue;
|
|
137
|
+
const documentFrequency = this.documentFrequency.get(term) ?? 0;
|
|
138
|
+
const inverseDocumentFrequency = Math.log(
|
|
139
|
+
1 + (this.documentCount - documentFrequency + 0.5)
|
|
140
|
+
/ (documentFrequency + 0.5),
|
|
141
|
+
);
|
|
142
|
+
const normalization = frequency
|
|
143
|
+
+ BM25_K1 * (
|
|
144
|
+
1 - BM25_B + BM25_B * document.length / this.averageLength
|
|
145
|
+
);
|
|
146
|
+
score += inverseDocumentFrequency
|
|
147
|
+
* (frequency * (BM25_K1 + 1)) / normalization;
|
|
148
|
+
}
|
|
149
|
+
if (score > 0) scores.set(document.id, score);
|
|
150
|
+
}
|
|
151
|
+
return scores;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { ALL_CATEGORIES } from './constants.js';
|
|
4
|
+
import { atomicWriteFile, scopeDirectory } from './fileStore.js';
|
|
5
|
+
import { sha256 } from './codec.js';
|
|
6
|
+
const GENERATED_HEADER = '<!-- minimal-agent generated topic view; do not edit';
|
|
7
|
+
export function topicViewPath(scope, workspaceId) {
|
|
8
|
+
return join(scopeDirectory(scope, workspaceId), 'views', 'topics.md');
|
|
9
|
+
}
|
|
10
|
+
function viewGeneration(snapshot) {
|
|
11
|
+
const entries = snapshot.records
|
|
12
|
+
.map((record) => `${record.id}:${snapshot.versions[record.id] ?? ''}`)
|
|
13
|
+
.sort();
|
|
14
|
+
return sha256(entries.join('\n'));
|
|
15
|
+
}
|
|
16
|
+
function recordLine(record) {
|
|
17
|
+
const aliases = record.aliases.length ? record.aliases.join(', ') : '—';
|
|
18
|
+
const statement = record.sensitivity === 'sensitive'
|
|
19
|
+
? '[敏感记忆内容已隐藏;请读取权威 UUID 记录并遵守访问权限]'
|
|
20
|
+
: record.statement;
|
|
21
|
+
return [
|
|
22
|
+
`- **${record.subject}** — ${statement}`,
|
|
23
|
+
` - id: \`${record.id}\`; revision: ${record.revision}; status: ${record.status}; updated: ${new Date(record.updatedAt).toISOString()}`,
|
|
24
|
+
` - aliases: ${aliases}`,
|
|
25
|
+
];
|
|
26
|
+
}
|
|
27
|
+
function topicRecords(records) {
|
|
28
|
+
const grouped = new Map();
|
|
29
|
+
for (const record of records) {
|
|
30
|
+
const values = grouped.get(record.topicKey) ?? [];
|
|
31
|
+
values.push(record);
|
|
32
|
+
grouped.set(record.topicKey, values);
|
|
33
|
+
}
|
|
34
|
+
for (const values of grouped.values()) {
|
|
35
|
+
values.sort((a, b) => {
|
|
36
|
+
const activeRank = (record) => record.status === 'active' ? 0 : record.status === 'needs_review' ? 1 : 2;
|
|
37
|
+
return activeRank(a) - activeRank(b) || b.updatedAt - a.updatedAt || a.id.localeCompare(b.id);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return grouped;
|
|
41
|
+
}
|
|
42
|
+
export function renderTopicView(snapshot) {
|
|
43
|
+
const generation = viewGeneration(snapshot);
|
|
44
|
+
const lines = [
|
|
45
|
+
`${GENERATED_HEADER}; generation:${generation} -->`,
|
|
46
|
+
'# Memory Topics',
|
|
47
|
+
'',
|
|
48
|
+
'> 自动生成、禁止编辑。UUID Markdown 记录是唯一权威来源;删除本文件后会自动重建。',
|
|
49
|
+
];
|
|
50
|
+
for (const category of ALL_CATEGORIES) {
|
|
51
|
+
const records = snapshot.records.filter((record) => record.category === category);
|
|
52
|
+
if (!records.length)
|
|
53
|
+
continue;
|
|
54
|
+
lines.push('', `## ${category}`);
|
|
55
|
+
const grouped = topicRecords(records);
|
|
56
|
+
for (const topicKey of [...grouped.keys()].sort((a, b) => a.localeCompare(b, 'zh-CN'))) {
|
|
57
|
+
lines.push('', `### ${topicKey}`);
|
|
58
|
+
const values = grouped.get(topicKey);
|
|
59
|
+
const current = values.filter((record) => record.status !== 'superseded');
|
|
60
|
+
const superseded = values.filter((record) => record.status === 'superseded');
|
|
61
|
+
for (const record of current)
|
|
62
|
+
lines.push(...recordLine(record));
|
|
63
|
+
if (superseded.length) {
|
|
64
|
+
lines.push('- 被替代记录:');
|
|
65
|
+
for (const record of superseded) {
|
|
66
|
+
lines.push(` - \`${record.id}\` revision ${record.revision}, updated ${new Date(record.updatedAt).toISOString()}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (!snapshot.records.length)
|
|
72
|
+
lines.push('', '_当前没有记忆记录。_');
|
|
73
|
+
return `${lines.join('\n')}\n`;
|
|
74
|
+
}
|
|
75
|
+
export async function ensureTopicView(snapshot, scope, workspaceId) {
|
|
76
|
+
const path = topicViewPath(scope, workspaceId);
|
|
77
|
+
const expectedPrefix = `${GENERATED_HEADER}; generation:${viewGeneration(snapshot)} -->`;
|
|
78
|
+
const current = await readFile(path, 'utf8').catch(() => '');
|
|
79
|
+
if (current.startsWith(expectedPrefix))
|
|
80
|
+
return;
|
|
81
|
+
await atomicWriteFile(path, renderTopicView(snapshot));
|
|
82
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { ALL_CATEGORIES } from './constants.js';
|
|
5
|
+
import { atomicWriteFile, scopeDirectory } from './fileStore.js';
|
|
6
|
+
import { sha256 } from './codec.js';
|
|
7
|
+
import type {
|
|
8
|
+
MemoryRecordV2,
|
|
9
|
+
MemoryScope,
|
|
10
|
+
MemorySnapshot,
|
|
11
|
+
} from './types.js';
|
|
12
|
+
|
|
13
|
+
const GENERATED_HEADER = '<!-- minimal-agent generated topic view; do not edit';
|
|
14
|
+
|
|
15
|
+
export function topicViewPath(scope: MemoryScope, workspaceId?: string): string {
|
|
16
|
+
return join(scopeDirectory(scope, workspaceId), 'views', 'topics.md');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function viewGeneration(snapshot: MemorySnapshot): string {
|
|
20
|
+
const entries = snapshot.records
|
|
21
|
+
.map((record) => `${record.id}:${snapshot.versions[record.id] ?? ''}`)
|
|
22
|
+
.sort();
|
|
23
|
+
return sha256(entries.join('\n'));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function recordLine(record: MemoryRecordV2): string[] {
|
|
27
|
+
const aliases = record.aliases.length ? record.aliases.join(', ') : '—';
|
|
28
|
+
const statement = record.sensitivity === 'sensitive'
|
|
29
|
+
? '[敏感记忆内容已隐藏;请读取权威 UUID 记录并遵守访问权限]'
|
|
30
|
+
: record.statement;
|
|
31
|
+
return [
|
|
32
|
+
`- **${record.subject}** — ${statement}`,
|
|
33
|
+
` - id: \`${record.id}\`; revision: ${record.revision}; status: ${record.status}; updated: ${new Date(record.updatedAt).toISOString()}`,
|
|
34
|
+
` - aliases: ${aliases}`,
|
|
35
|
+
];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function topicRecords(records: MemoryRecordV2[]): Map<string, MemoryRecordV2[]> {
|
|
39
|
+
const grouped = new Map<string, MemoryRecordV2[]>();
|
|
40
|
+
for (const record of records) {
|
|
41
|
+
const values = grouped.get(record.topicKey) ?? [];
|
|
42
|
+
values.push(record);
|
|
43
|
+
grouped.set(record.topicKey, values);
|
|
44
|
+
}
|
|
45
|
+
for (const values of grouped.values()) {
|
|
46
|
+
values.sort((a, b) => {
|
|
47
|
+
const activeRank = (record: MemoryRecordV2) => record.status === 'active' ? 0 : record.status === 'needs_review' ? 1 : 2;
|
|
48
|
+
return activeRank(a) - activeRank(b) || b.updatedAt - a.updatedAt || a.id.localeCompare(b.id);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return grouped;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function renderTopicView(snapshot: MemorySnapshot): string {
|
|
55
|
+
const generation = viewGeneration(snapshot);
|
|
56
|
+
const lines = [
|
|
57
|
+
`${GENERATED_HEADER}; generation:${generation} -->`,
|
|
58
|
+
'# Memory Topics',
|
|
59
|
+
'',
|
|
60
|
+
'> 自动生成、禁止编辑。UUID Markdown 记录是唯一权威来源;删除本文件后会自动重建。',
|
|
61
|
+
];
|
|
62
|
+
for (const category of ALL_CATEGORIES) {
|
|
63
|
+
const records = snapshot.records.filter((record) => record.category === category);
|
|
64
|
+
if (!records.length) continue;
|
|
65
|
+
lines.push('', `## ${category}`);
|
|
66
|
+
const grouped = topicRecords(records);
|
|
67
|
+
for (const topicKey of [...grouped.keys()].sort((a, b) => a.localeCompare(b, 'zh-CN'))) {
|
|
68
|
+
lines.push('', `### ${topicKey}`);
|
|
69
|
+
const values = grouped.get(topicKey)!;
|
|
70
|
+
const current = values.filter((record) => record.status !== 'superseded');
|
|
71
|
+
const superseded = values.filter((record) => record.status === 'superseded');
|
|
72
|
+
for (const record of current) lines.push(...recordLine(record));
|
|
73
|
+
if (superseded.length) {
|
|
74
|
+
lines.push('- 被替代记录:');
|
|
75
|
+
for (const record of superseded) {
|
|
76
|
+
lines.push(` - \`${record.id}\` revision ${record.revision}, updated ${new Date(record.updatedAt).toISOString()}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (!snapshot.records.length) lines.push('', '_当前没有记忆记录。_');
|
|
82
|
+
return `${lines.join('\n')}\n`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function ensureTopicView(
|
|
86
|
+
snapshot: MemorySnapshot,
|
|
87
|
+
scope: MemoryScope,
|
|
88
|
+
workspaceId?: string,
|
|
89
|
+
): Promise<void> {
|
|
90
|
+
const path = topicViewPath(scope, workspaceId);
|
|
91
|
+
const expectedPrefix = `${GENERATED_HEADER}; generation:${viewGeneration(snapshot)} -->`;
|
|
92
|
+
const current = await readFile(path, 'utf8').catch(() => '');
|
|
93
|
+
if (current.startsWith(expectedPrefix)) return;
|
|
94
|
+
await atomicWriteFile(path, renderTopicView(snapshot));
|
|
95
|
+
}
|