micro-models-agent 2.16.0 → 2.17.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/CHANGELOG.md +34 -0
- package/dist/assets/app.js +1 -314
- package/dist/assets/hljs.js +5 -1244
- package/dist/assets/index.html +11 -0
- package/dist/assets/js/api.js +1 -28
- package/dist/assets/js/core/menus.js +1 -0
- package/dist/assets/js/core/store/feed.js +1 -0
- package/dist/assets/js/core/store/index.js +1 -0
- package/dist/assets/js/core/store/session.js +1 -0
- package/dist/assets/js/core/store/settings.js +1 -0
- package/dist/assets/js/core/store/tabs.js +1 -0
- package/dist/assets/js/dialog.js +1 -105
- package/dist/assets/js/dom.js +1 -178
- package/dist/assets/js/feed/core.js +1 -0
- package/dist/assets/js/feed/history.js +1 -0
- package/dist/assets/js/feed/plan.js +1 -0
- package/dist/assets/js/feed/question.js +3 -0
- package/dist/assets/js/feed/sidebar.js +1 -0
- package/dist/assets/js/feed/stream.js +1 -0
- package/dist/assets/js/feed/turn.js +5 -0
- package/dist/assets/js/feed.js +1 -1211
- package/dist/assets/js/format.js +2 -122
- package/dist/assets/js/i18n.js +1 -46
- package/dist/assets/js/rail.js +1 -114
- package/dist/assets/js/session/cmdk.js +1 -0
- package/dist/assets/js/session/composer.js +1 -0
- package/dist/assets/js/session/sessions-menu.js +1 -0
- package/dist/assets/js/session/tabs.js +1 -0
- package/dist/assets/js/settings/controls.js +1 -0
- package/dist/assets/js/settings/editors.js +1 -0
- package/dist/assets/js/settings/form.js +1 -0
- package/dist/assets/js/settings/modal.js +1 -0
- package/dist/assets/js/settings/panels.js +1 -0
- package/dist/assets/js/settings/providers.js +1 -0
- package/dist/assets/js/settings/search.js +1 -0
- package/dist/assets/js/settings/subdialog.js +1 -0
- package/dist/assets/js/settings/write.js +1 -0
- package/dist/assets/js/settings.js +1 -1914
- package/dist/assets/js/sidebar/core.js +1 -0
- package/dist/assets/js/sidebar/lsp.js +2 -0
- package/dist/assets/js/sidebar/map.js +1 -0
- package/dist/assets/js/sidebar/state.js +1 -0
- package/dist/assets/js/sidebar/trace.js +5 -0
- package/dist/assets/js/sidebar.js +1 -705
- package/dist/assets/js/store.js +1 -82
- package/dist/assets/js/subdialog.js +1 -0
- package/dist/assets/md.js +1 -277
- package/dist/assets/setup.js +3 -816
- package/dist/assets/smd.js +29 -1665
- package/dist/assets/styles.css +1 -1592
- package/dist/certification/certifications.json +1 -494
- package/dist/i18n/en.json +1 -1851
- package/dist/i18n/ru.json +1 -1854
- package/dist/main.js +815 -55797
- package/dist/modules/browser/bridge-server.mjs +2 -252
- package/package.json +10 -5
- package/dist/assets/js/settings-controls.js +0 -452
- package/dist/assets/js/tabs.js +0 -867
- package/dist/cli/cache-line.js +0 -31
- package/dist/cli/command-suggest.js +0 -39
- package/dist/cli/commands.js +0 -781
- package/dist/cli/completer.js +0 -268
- package/dist/cli/index.js +0 -3
- package/dist/cli/json-payload.js +0 -32
- package/dist/cli/main.js +0 -346
- package/dist/cli/onboarding-commands.js +0 -126
- package/dist/cli/plugin-commands.js +0 -38
- package/dist/cli/relaunch.js +0 -40
- package/dist/cli/repl-commands-lsp.js +0 -75
- package/dist/cli/repl-commands-skills.js +0 -105
- package/dist/cli/repl-commands.js +0 -1218
- package/dist/cli/repl.js +0 -1238
- package/dist/cli/run-result.js +0 -38
- package/dist/cli/security-commands.js +0 -177
- package/dist/cli/setup-order.js +0 -6
- package/dist/cli/setup-prompt.js +0 -50
- package/dist/cli/setup.js +0 -161
- package/dist/cli/web-command.js +0 -98
- package/dist/config/budget.js +0 -48
- package/dist/config/config.js +0 -345
- package/dist/config/defaults.js +0 -197
- package/dist/config/domains.js +0 -135
- package/dist/config/env.js +0 -46
- package/dist/config/experts.js +0 -17
- package/dist/config/index.js +0 -5
- package/dist/config/paths.js +0 -56
- package/dist/config/redact.js +0 -44
- package/dist/config/registry-extra.js +0 -334
- package/dist/config/registry.js +0 -584
- package/dist/config/security.js +0 -212
- package/dist/config/timeouts.js +0 -74
- package/dist/config/types.js +0 -1
- package/dist/config/utils.js +0 -57
- package/dist/core/agent/artifact-progress.js +0 -59
- package/dist/core/agent/artifact-resolve.js +0 -79
- package/dist/core/agent/audit-gate.js +0 -53
- package/dist/core/agent/compaction.js +0 -89
- package/dist/core/agent/constants.js +0 -90
- package/dist/core/agent/context-log.js +0 -454
- package/dist/core/agent/context-renderer.js +0 -45
- package/dist/core/agent/critic-gate.js +0 -132
- package/dist/core/agent/hallucination-gate.js +0 -197
- package/dist/core/agent/loop-state.js +0 -68
- package/dist/core/agent/prefix-monitor.js +0 -101
- package/dist/core/agent/reasoning-resolver.js +0 -65
- package/dist/core/agent/token-tracker.js +0 -99
- package/dist/core/agent/tool-batch.js +0 -312
- package/dist/core/agent/tool-images.js +0 -18
- package/dist/core/agent/tool-output.js +0 -116
- package/dist/core/agent/tool-pairing.js +0 -60
- package/dist/core/agent-moe.js +0 -248
- package/dist/core/agent.js +0 -1299
- package/dist/core/bootstrap/agent-phase.js +0 -66
- package/dist/core/bootstrap/config-phase.js +0 -86
- package/dist/core/bootstrap/modules-phase.js +0 -269
- package/dist/core/bootstrap/provider-phase.js +0 -183
- package/dist/core/bootstrap/session-phase.js +0 -204
- package/dist/core/bootstrap/state.js +0 -94
- package/dist/core/bootstrap/workspace-phase.js +0 -115
- package/dist/core/bootstrap.js +0 -112
- package/dist/core/crash-handler.js +0 -62
- package/dist/core/environment.js +0 -224
- package/dist/core/host-plan.js +0 -43
- package/dist/core/host.js +0 -23
- package/dist/core/index.js +0 -3
- package/dist/core/prompt-builder.js +0 -95
- package/dist/core/prompt-overflow.js +0 -306
- package/dist/core/session-logger.js +0 -375
- package/dist/core/system-prompt.js +0 -117
- package/dist/core/types.js +0 -1
- package/dist/core/version.js +0 -28
- package/dist/core/web-host.js +0 -34
- package/dist/core/workspace.js +0 -80
- package/dist/i18n/index.js +0 -80
- package/dist/index.js +0 -30
- package/dist/llm/cache-usage.js +0 -76
- package/dist/llm/image-utils.js +0 -138
- package/dist/llm/index.js +0 -4
- package/dist/llm/llm-errors.js +0 -50
- package/dist/llm/model-loader.js +0 -86
- package/dist/llm/models-dev.js +0 -121
- package/dist/llm/openai-compat.js +0 -756
- package/dist/llm/orchestrator.js +0 -294
- package/dist/llm/provider-budget.js +0 -68
- package/dist/llm/provider-context.js +0 -233
- package/dist/llm/provider.js +0 -9
- package/dist/llm/response.js +0 -44
- package/dist/llm/stream-state.js +0 -26
- package/dist/llm/token-counter.js +0 -83
- package/dist/llm/types.js +0 -1
- package/dist/logger/app-logger.js +0 -212
- package/dist/logger/file-log.js +0 -160
- package/dist/logger/index.js +0 -2
- package/dist/migration/backup.js +0 -56
- package/dist/migration/detect.js +0 -61
- package/dist/migration/index.js +0 -3
- package/dist/modules/artifacts/store.js +0 -62
- package/dist/modules/browser/actions.js +0 -79
- package/dist/modules/browser/bridge-client.js +0 -203
- package/dist/modules/browser/bridge-path.js +0 -10
- package/dist/modules/browser/console-buffer.js +0 -37
- package/dist/modules/browser/cookie-store.js +0 -29
- package/dist/modules/browser/driver-types.js +0 -1
- package/dist/modules/browser/driver.js +0 -186
- package/dist/modules/browser/index.js +0 -9
- package/dist/modules/browser/module.js +0 -30
- package/dist/modules/browser/session.js +0 -322
- package/dist/modules/browser/snapshot.js +0 -154
- package/dist/modules/browser/types.js +0 -13
- package/dist/modules/certification/cli.js +0 -264
- package/dist/modules/certification/fact-checker.js +0 -90
- package/dist/modules/certification/loader.js +0 -127
- package/dist/modules/certification/manifest.js +0 -231
- package/dist/modules/certification/runner.js +0 -233
- package/dist/modules/certification/scenarios.js +0 -586
- package/dist/modules/certification/syntax-scenarios.js +0 -50
- package/dist/modules/certification/types.js +0 -1
- package/dist/modules/context/chunk-query.js +0 -122
- package/dist/modules/context/fact-extractor.js +0 -170
- package/dist/modules/context/history.js +0 -15
- package/dist/modules/context/index.js +0 -2
- package/dist/modules/context/manager.js +0 -482
- package/dist/modules/critic/client.js +0 -176
- package/dist/modules/critic/evidence.js +0 -81
- package/dist/modules/critic/provider.js +0 -45
- package/dist/modules/critic/tools.js +0 -78
- package/dist/modules/critic/types.js +0 -1
- package/dist/modules/execution/audit-runners.js +0 -206
- package/dist/modules/execution/auditor.js +0 -222
- package/dist/modules/execution/execution-plugin.js +0 -478
- package/dist/modules/execution/index.js +0 -8
- package/dist/modules/execution/input-from.js +0 -70
- package/dist/modules/execution/module.js +0 -891
- package/dist/modules/execution/moe-executor.js +0 -443
- package/dist/modules/execution/plan-actions.js +0 -642
- package/dist/modules/execution/plan-checks.js +0 -35
- package/dist/modules/execution/plan-coverage.js +0 -71
- package/dist/modules/execution/plan-persister.js +0 -46
- package/dist/modules/execution/plan-steps.js +0 -31
- package/dist/modules/execution/plan-store.js +0 -274
- package/dist/modules/execution/plan-tool.js +0 -249
- package/dist/modules/execution/plan-validator.js +0 -197
- package/dist/modules/execution/planner.js +0 -103
- package/dist/modules/execution/stuck-detector.js +0 -834
- package/dist/modules/execution/tracker.js +0 -92
- package/dist/modules/execution/transient-error.js +0 -30
- package/dist/modules/execution/types.js +0 -1
- package/dist/modules/execution/verifier.js +0 -343
- package/dist/modules/execution/windows-commands.js +0 -52
- package/dist/modules/hallucination/artifact-claim.js +0 -93
- package/dist/modules/hallucination/confidence.js +0 -81
- package/dist/modules/hallucination/consistency.js +0 -37
- package/dist/modules/hallucination/detector.js +0 -57
- package/dist/modules/hallucination/factual.js +0 -205
- package/dist/modules/hallucination/index.js +0 -6
- package/dist/modules/hallucination/js-identifiers.js +0 -261
- package/dist/modules/hallucination/llm-judge.js +0 -116
- package/dist/modules/hallucination/success-claim.js +0 -59
- package/dist/modules/index.js +0 -5
- package/dist/modules/indexer/cache.js +0 -88
- package/dist/modules/indexer/index.js +0 -4
- package/dist/modules/indexer/map-command.js +0 -33
- package/dist/modules/indexer/map-select.js +0 -87
- package/dist/modules/indexer/module.js +0 -293
- package/dist/modules/indexer/project-profile.js +0 -184
- package/dist/modules/indexer/symbols.js +0 -189
- package/dist/modules/indexer/walker.js +0 -285
- package/dist/modules/lsp/check-tool.js +0 -61
- package/dist/modules/lsp/client.js +0 -406
- package/dist/modules/lsp/command.js +0 -53
- package/dist/modules/lsp/config.js +0 -189
- package/dist/modules/lsp/index.js +0 -4
- package/dist/modules/lsp/module.js +0 -295
- package/dist/modules/lsp/probe.js +0 -86
- package/dist/modules/lsp/project-root.js +0 -69
- package/dist/modules/lsp/startup-check.js +0 -154
- package/dist/modules/lsp/types.js +0 -1
- package/dist/modules/mcp/client.js +0 -445
- package/dist/modules/mcp/index.js +0 -4
- package/dist/modules/mcp/module.js +0 -295
- package/dist/modules/mcp/registry.js +0 -20
- package/dist/modules/memory/index.js +0 -2
- package/dist/modules/memory/module.js +0 -101
- package/dist/modules/memory/search.js +0 -45
- package/dist/modules/memory/store.js +0 -107
- package/dist/modules/onboarding/init.js +0 -47
- package/dist/modules/onboarding/meet.js +0 -30
- package/dist/modules/onboarding/mode.js +0 -30
- package/dist/modules/onboarding/prompts.js +0 -43
- package/dist/modules/pipelines/engine.js +0 -70
- package/dist/modules/pipelines/index.js +0 -4
- package/dist/modules/pipelines/parser.js +0 -59
- package/dist/modules/pipelines/template.js +0 -18
- package/dist/modules/plugins/builtin/lint-on-write.js +0 -377
- package/dist/modules/plugins/builtin/notify.js +0 -11
- package/dist/modules/plugins/index.js +0 -2
- package/dist/modules/plugins/loader.js +0 -85
- package/dist/modules/plugins/manager.js +0 -244
- package/dist/modules/plugins/types.js +0 -1
- package/dist/modules/pricing/index.js +0 -70
- package/dist/modules/pricing/prices.js +0 -147
- package/dist/modules/processes/detect.js +0 -34
- package/dist/modules/processes/index.js +0 -4
- package/dist/modules/processes/kill-tree.js +0 -52
- package/dist/modules/processes/registry.js +0 -294
- package/dist/modules/processes/runner.js +0 -23
- package/dist/modules/providers/cache.js +0 -23
- package/dist/modules/providers/capabilities.js +0 -28
- package/dist/modules/providers/create.js +0 -21
- package/dist/modules/providers/factory.js +0 -28
- package/dist/modules/providers/fallback.js +0 -81
- package/dist/modules/providers/health.js +0 -47
- package/dist/modules/providers/index.js +0 -6
- package/dist/modules/providers/manager.js +0 -207
- package/dist/modules/providers/naming.js +0 -15
- package/dist/modules/providers/preflight.js +0 -71
- package/dist/modules/providers/presets.js +0 -232
- package/dist/modules/providers/registry.js +0 -27
- package/dist/modules/providers/types.js +0 -1
- package/dist/modules/reasoning/policy.js +0 -42
- package/dist/modules/reasoning/probe.js +0 -116
- package/dist/modules/registry.js +0 -48
- package/dist/modules/security/audit-log.js +0 -119
- package/dist/modules/security/audit-notifier.js +0 -267
- package/dist/modules/security/command-validator.js +0 -272
- package/dist/modules/security/content-scanner.js +0 -53
- package/dist/modules/security/data-sanitizer.js +0 -82
- package/dist/modules/security/encryption.js +0 -216
- package/dist/modules/security/index.js +0 -15
- package/dist/modules/security/network-validator.js +0 -236
- package/dist/modules/security/path-validator.js +0 -261
- package/dist/modules/security/protected-paths.js +0 -73
- package/dist/modules/security/rate-limiter.js +0 -98
- package/dist/modules/security/security-policies.js +0 -499
- package/dist/modules/security/session-encryption.js +0 -182
- package/dist/modules/security/session-isolation.js +0 -75
- package/dist/modules/session/auto-name.js +0 -63
- package/dist/modules/session/export.js +0 -98
- package/dist/modules/session/index.js +0 -4
- package/dist/modules/session/manager.js +0 -234
- package/dist/modules/session/module.js +0 -33
- package/dist/modules/session/store.js +0 -295
- package/dist/modules/session/types.js +0 -1
- package/dist/modules/setup/answers.js +0 -35
- package/dist/modules/setup/apply.js +0 -79
- package/dist/modules/setup/discovery.js +0 -72
- package/dist/modules/skills/index.js +0 -3
- package/dist/modules/skills/loader.js +0 -86
- package/dist/modules/skills/matcher.js +0 -27
- package/dist/modules/skills/module.js +0 -141
- package/dist/modules/types.js +0 -1
- package/dist/modules/updater/changelog-reader.js +0 -93
- package/dist/modules/updater/checker.js +0 -101
- package/dist/modules/updater/dev-detect.js +0 -18
- package/dist/modules/updater/index.js +0 -4
- package/dist/modules/updater/module.js +0 -129
- package/dist/modules/user-profile/compressor.js +0 -18
- package/dist/modules/user-profile/index.js +0 -2
- package/dist/modules/user-profile/profile.js +0 -77
- package/dist/modules/webui/answer-api.js +0 -29
- package/dist/modules/webui/assets.js +0 -50
- package/dist/modules/webui/body.js +0 -21
- package/dist/modules/webui/commands-settings.js +0 -209
- package/dist/modules/webui/commands-shared.js +0 -60
- package/dist/modules/webui/commands.js +0 -174
- package/dist/modules/webui/config-api.js +0 -134
- package/dist/modules/webui/file-api.js +0 -202
- package/dist/modules/webui/forward.js +0 -159
- package/dist/modules/webui/history-api.js +0 -112
- package/dist/modules/webui/host-state.js +0 -60
- package/dist/modules/webui/i18n-api.js +0 -9
- package/dist/modules/webui/limits.js +0 -6
- package/dist/modules/webui/log-forward.js +0 -20
- package/dist/modules/webui/memory-commands.js +0 -64
- package/dist/modules/webui/model-cache.js +0 -18
- package/dist/modules/webui/module.js +0 -148
- package/dist/modules/webui/persist.js +0 -24
- package/dist/modules/webui/prompt-io.js +0 -97
- package/dist/modules/webui/providers-api.js +0 -337
- package/dist/modules/webui/providers-view.js +0 -56
- package/dist/modules/webui/reasoning-view.js +0 -15
- package/dist/modules/webui/run-agent.js +0 -81
- package/dist/modules/webui/server.js +0 -284
- package/dist/modules/webui/sessions-api.js +0 -178
- package/dist/modules/webui/settings-api.js +0 -561
- package/dist/modules/webui/setup-api.js +0 -201
- package/dist/modules/webui/state.js +0 -74
- package/dist/modules/webui/util.js +0 -261
- package/dist/output/bus.js +0 -37
- package/dist/output/channel.js +0 -285
- package/dist/output/format.js +0 -15
- package/dist/output/index.js +0 -8
- package/dist/output/json-sink.js +0 -24
- package/dist/output/machine.js +0 -9
- package/dist/output/session-sink.js +0 -27
- package/dist/output/types.js +0 -1
- package/dist/tools/approve.js +0 -41
- package/dist/tools/attach-image.js +0 -102
- package/dist/tools/auto-fixer.js +0 -180
- package/dist/tools/auto-tags.js +0 -83
- package/dist/tools/bash.js +0 -649
- package/dist/tools/browser.js +0 -160
- package/dist/tools/chunk-query.js +0 -112
- package/dist/tools/create-dir.js +0 -60
- package/dist/tools/delete-file.js +0 -67
- package/dist/tools/download-file.js +0 -142
- package/dist/tools/edit-file.js +0 -136
- package/dist/tools/enable-tools.js +0 -59
- package/dist/tools/executor.js +0 -304
- package/dist/tools/file-info.js +0 -49
- package/dist/tools/filter-tools.js +0 -17
- package/dist/tools/glob-tool.js +0 -37
- package/dist/tools/grep-tool.js +0 -142
- package/dist/tools/hidden-tools-block.js +0 -37
- package/dist/tools/index.js +0 -88
- package/dist/tools/list-dir.js +0 -53
- package/dist/tools/load-skill.js +0 -51
- package/dist/tools/mcp-call.js +0 -80
- package/dist/tools/meet-done.js +0 -14
- package/dist/tools/move-file.js +0 -94
- package/dist/tools/path-utils.js +0 -108
- package/dist/tools/pipeline-run.js +0 -167
- package/dist/tools/preview.js +0 -2
- package/dist/tools/process-ids.js +0 -31
- package/dist/tools/process-kill.js +0 -33
- package/dist/tools/process-list.js +0 -38
- package/dist/tools/process-log.js +0 -49
- package/dist/tools/process-wait.js +0 -63
- package/dist/tools/prompt-io.js +0 -29
- package/dist/tools/question.js +0 -288
- package/dist/tools/read-file.js +0 -200
- package/dist/tools/recall.js +0 -124
- package/dist/tools/registry.js +0 -48
- package/dist/tools/remember.js +0 -72
- package/dist/tools/scope-check.js +0 -32
- package/dist/tools/scope-request.js +0 -96
- package/dist/tools/search-history.js +0 -88
- package/dist/tools/session-info.js +0 -46
- package/dist/tools/set-thinking.js +0 -75
- package/dist/tools/subagent.js +0 -257
- package/dist/tools/syntax-validator.js +0 -379
- package/dist/tools/types.js +0 -1
- package/dist/tools/user-input.js +0 -134
- package/dist/tools/web-browse.js +0 -93
- package/dist/tools/web-fetch.js +0 -108
- package/dist/tools/web-search.js +0 -107
- package/dist/tools/write-file.js +0 -128
- package/dist/ui/action-log.js +0 -13
- package/dist/ui/box.js +0 -78
- package/dist/ui/colors.js +0 -6
- package/dist/ui/diff.js +0 -189
- package/dist/ui/index.js +0 -7
- package/dist/ui/line-editor.js +0 -1083
- package/dist/ui/line-math.js +0 -98
- package/dist/ui/md-formatter.js +0 -322
- package/dist/ui/output.js +0 -19
- package/dist/ui/plan-view.js +0 -109
- package/dist/ui/renderer.js +0 -589
- package/dist/ui/spinner.js +0 -91
- package/dist/ui/table.js +0 -142
- package/dist/ui/theme.js +0 -143
- package/dist/utils/child-run.js +0 -20
- package/dist/utils/error.js +0 -4
- package/dist/utils/index.js +0 -6
- package/dist/utils/retry.js +0 -17
- package/dist/utils/sleep.js +0 -23
- package/dist/utils/truncate.js +0 -9
|
@@ -1,306 +0,0 @@
|
|
|
1
|
-
/** Переполнение системного промпта: dry-run, суммаризация, подсказки. */
|
|
2
|
-
import { createHash } from "crypto";
|
|
3
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
4
|
-
import { join } from "path";
|
|
5
|
-
import { PromptBuilder } from "./prompt-builder";
|
|
6
|
-
import { estimateTokens } from "../llm/token-counter";
|
|
7
|
-
import { t } from "../i18n/index";
|
|
8
|
-
/** Цена model-facing hint-блока в токенах (верхняя граница для аллокации). */
|
|
9
|
-
export const HINT_BLOCK_TOKENS = 60;
|
|
10
|
-
/** Грубый фактор символов на токен для жёсткого усечения. */
|
|
11
|
-
const CHARS_PER_TOKEN = 4;
|
|
12
|
-
const KIND_ORDER = ["instructions", "project-map"];
|
|
13
|
-
const KIND_LABEL = {
|
|
14
|
-
instructions: "project instructions (AGENTS.md)",
|
|
15
|
-
"project-map": "project map",
|
|
16
|
-
};
|
|
17
|
-
const KIND_SOURCE_FILE = {
|
|
18
|
-
instructions: "AGENTS.md",
|
|
19
|
-
"project-map": "",
|
|
20
|
-
};
|
|
21
|
-
/**
|
|
22
|
-
* Статический dry-run бюджета системного промпта: какие kind-блоки не влезают.
|
|
23
|
-
* Нужен bootstrap для стартового баннера и Agent перед первым LLM-вызовом.
|
|
24
|
-
*/
|
|
25
|
-
export function dryRunOverflow(allBlocks, systemBudget) {
|
|
26
|
-
const builder = new PromptBuilder(systemBudget);
|
|
27
|
-
builder.addBlocks(allBlocks);
|
|
28
|
-
const result = builder.build();
|
|
29
|
-
const includedTokens = result.blocks
|
|
30
|
-
.filter((b) => b.included)
|
|
31
|
-
.reduce((sum, b) => sum + b.tokens, 0);
|
|
32
|
-
const overflow = result.excludedBlocks.filter((b) => Boolean(b.kind));
|
|
33
|
-
return { includedTokens, overflow };
|
|
34
|
-
}
|
|
35
|
-
function cacheKey(kind, content, maxTokens) {
|
|
36
|
-
return createHash("sha256").update(`${kind}|${maxTokens}|${content}`).digest("hex").slice(0, 24);
|
|
37
|
-
}
|
|
38
|
-
function readCache(cacheDir, key) {
|
|
39
|
-
try {
|
|
40
|
-
const path = join(cacheDir, `${key}.md`);
|
|
41
|
-
if (!existsSync(path))
|
|
42
|
-
return null;
|
|
43
|
-
const raw = readFileSync(path, "utf-8").trim();
|
|
44
|
-
if (!raw)
|
|
45
|
-
return null;
|
|
46
|
-
try {
|
|
47
|
-
const parsed = JSON.parse(raw);
|
|
48
|
-
if ((parsed.mode === "summary" || parsed.mode === "truncate") && typeof parsed.text === "string" && parsed.text) {
|
|
49
|
-
return parsed;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
// Легаси plain-text запись — считаем попаданием суммаризации
|
|
54
|
-
return { mode: "summary", text: raw };
|
|
55
|
-
}
|
|
56
|
-
return null;
|
|
57
|
-
}
|
|
58
|
-
catch {
|
|
59
|
-
// Битый кэш — идём на повторную суммаризацию
|
|
60
|
-
}
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
function writeCache(cacheDir, key, entry) {
|
|
64
|
-
try {
|
|
65
|
-
mkdirSync(cacheDir, { recursive: true });
|
|
66
|
-
writeFileSync(join(cacheDir, `${key}.md`), JSON.stringify(entry), "utf-8");
|
|
67
|
-
}
|
|
68
|
-
catch {
|
|
69
|
-
// Best-effort — падение кэша не должно ронять агента
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
/** Собирает полный текстовый ответ через стриминговый API провайдера. */
|
|
73
|
-
async function collectText(provider, prompt, maxTokens) {
|
|
74
|
-
let text = "";
|
|
75
|
-
// Reasoning выкл: думающая модель сожгла бы cap на <think> до любого
|
|
76
|
-
// суммаризирующего контента (наблюдалось на qwen3.5-9b).
|
|
77
|
-
// 2x запас сверх цели: оценки токенов эвристичны, а clamp ниже держит
|
|
78
|
-
// реальный cap независимо от ответа модели.
|
|
79
|
-
for await (const chunk of provider.chat([{ role: "user", content: prompt }], undefined, undefined, {
|
|
80
|
-
maxTokens: maxTokens * 2,
|
|
81
|
-
reasoningEffort: "none",
|
|
82
|
-
})) {
|
|
83
|
-
if (chunk.type === "text" && chunk.content)
|
|
84
|
-
text += chunk.content;
|
|
85
|
-
}
|
|
86
|
-
return text.trim();
|
|
87
|
-
}
|
|
88
|
-
function truncateToTokens(content, maxTokens) {
|
|
89
|
-
const maxChars = Math.max(200, maxTokens * CHARS_PER_TOKEN);
|
|
90
|
-
if (content.length <= maxChars)
|
|
91
|
-
return content;
|
|
92
|
-
let cut = content.slice(0, maxChars);
|
|
93
|
-
const lastBreak = cut.lastIndexOf("\n");
|
|
94
|
-
if (lastBreak > maxChars * 0.5)
|
|
95
|
-
cut = cut.slice(0, lastBreak);
|
|
96
|
-
return `${cut.trimEnd()}\n\n[...truncated — read the full file for details...]`;
|
|
97
|
-
}
|
|
98
|
-
/** Однострочная метка по первой строке (для варнингов/логов). */
|
|
99
|
-
function blockLabel(content) {
|
|
100
|
-
const first = content.split("\n")[0].trim();
|
|
101
|
-
return first.length > 60 ? `${first.slice(0, 57)}...` : first;
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Суммаризирует (или, не вышло, усекает) блоки сверх бюджета, чтобы инструкции
|
|
105
|
-
* проекта/карта всё равно дошли до модели. Суммаризации кэшируются на диске
|
|
106
|
-
* (ключ: kind + контент + бюджет). Порядок — KIND_ORDER; первый забирает весь
|
|
107
|
-
* остаток бюджета, остальным — что останется.
|
|
108
|
-
*/
|
|
109
|
-
export async function resolvePromptOverflow(opts) {
|
|
110
|
-
const { overflow, includedTokens, systemBudget, provider, cacheDir, logger } = opts;
|
|
111
|
-
const sorted = [...overflow].sort((a, b) => KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind));
|
|
112
|
-
const replacements = [];
|
|
113
|
-
const warnings = [];
|
|
114
|
-
let used = includedTokens;
|
|
115
|
-
const unresolved = [];
|
|
116
|
-
// Dry-run bootstrap лишь предупреждает, что блоки «будут суммаризированы
|
|
117
|
-
// перед первым запуском». Без нотиса тут первый промпт выглядит зависшим,
|
|
118
|
-
// пока модель переписывает AGENTS.md / карту — показываем явно.
|
|
119
|
-
if (sorted.length > 0) {
|
|
120
|
-
logger?.warn(t("prompt.overflow.compressing", { count: String(sorted.length) }));
|
|
121
|
-
}
|
|
122
|
-
for (const block of sorted) {
|
|
123
|
-
const kind = block.kind;
|
|
124
|
-
const maxTokens = systemBudget - used - HINT_BLOCK_TOKENS;
|
|
125
|
-
if (maxTokens < 100) {
|
|
126
|
-
unresolved.push(kind);
|
|
127
|
-
continue;
|
|
128
|
-
}
|
|
129
|
-
let mode = "summary";
|
|
130
|
-
let text = "";
|
|
131
|
-
const key = cacheKey(kind, block.content, maxTokens);
|
|
132
|
-
const cached = readCache(cacheDir, key);
|
|
133
|
-
if (cached) {
|
|
134
|
-
text = cached.text;
|
|
135
|
-
mode = cached.mode;
|
|
136
|
-
logger?.debug(`Prompt overflow: cache hit for ${kind} (${key}, ${mode})`);
|
|
137
|
-
}
|
|
138
|
-
else if (provider) {
|
|
139
|
-
const targetChars = Math.floor(maxTokens * (CHARS_PER_TOKEN - 1));
|
|
140
|
-
logger?.warn(t("prompt.overflow.summarizing", {
|
|
141
|
-
label: blockLabel(block.content),
|
|
142
|
-
original: String(block.estimatedTokens),
|
|
143
|
-
budget: String(maxTokens),
|
|
144
|
-
}));
|
|
145
|
-
try {
|
|
146
|
-
const prompt = [
|
|
147
|
-
`Summarize the following ${KIND_LABEL[kind]} document.`,
|
|
148
|
-
// 3 символа/токен (не 4): нелатиница (кириллица и т.п.) — ~2–3 символа
|
|
149
|
-
// на токен, поэтому цель x4 уводит суммаризацию за clamp.
|
|
150
|
-
`Target length: at most ${targetChars} characters (~${maxTokens} tokens). Be strict about it.`,
|
|
151
|
-
`Preserve concrete facts: file paths, commands, rules, naming conventions, workflow steps.`,
|
|
152
|
-
`Keep the structure (headings / bullet lists). Output ONLY the summary text.`,
|
|
153
|
-
``,
|
|
154
|
-
`--- DOCUMENT START ---`,
|
|
155
|
-
block.content,
|
|
156
|
-
`--- DOCUMENT END ---`,
|
|
157
|
-
].join("\n");
|
|
158
|
-
text = await collectText(provider, prompt, maxTokens);
|
|
159
|
-
// Маленькие модели регулярно игнорируют лимит длины (наблюдалось: 9B
|
|
160
|
-
// выдала ~4700 символов при цели 3170). Один retry самокомпрессии на
|
|
161
|
-
// перелёт — короткий вход резко повышает послушание — затем жёсткий clamp.
|
|
162
|
-
let retries = 0;
|
|
163
|
-
while (text && estimateTokens(text) > maxTokens && retries < 1) {
|
|
164
|
-
retries++;
|
|
165
|
-
logger?.debug(`Prompt overflow: ${kind} summary overshot (${estimateTokens(text)} > ${maxTokens} tok), compressing (retry ${retries})`);
|
|
166
|
-
text = await collectText(provider, [
|
|
167
|
-
`Compress the following text to at most ${targetChars} characters.`,
|
|
168
|
-
`Keep the structure (headings / bullet lists) and all concrete facts: file paths, commands, rules.`,
|
|
169
|
-
`Output ONLY the compressed text.`,
|
|
170
|
-
``,
|
|
171
|
-
`--- TEXT START ---`,
|
|
172
|
-
text,
|
|
173
|
-
`--- TEXT END ---`,
|
|
174
|
-
].join("\n"), maxTokens);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
catch (err) {
|
|
178
|
-
logger?.warn(t("prompt.overflow.summarize_failed", {
|
|
179
|
-
label: blockLabel(block.content),
|
|
180
|
-
error: String(err?.message ?? err),
|
|
181
|
-
}));
|
|
182
|
-
text = "";
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
if (!text) {
|
|
186
|
-
// Нет провайдера или суммаризация упала — фолбэк жёсткого усечения.
|
|
187
|
-
mode = "truncate";
|
|
188
|
-
logger?.warn(t("prompt.overflow.truncating", {
|
|
189
|
-
label: blockLabel(block.content),
|
|
190
|
-
original: String(block.estimatedTokens),
|
|
191
|
-
}));
|
|
192
|
-
text = truncateToTokens(block.content, maxTokens);
|
|
193
|
-
}
|
|
194
|
-
// LLM перелетают: держим cap независимо от источника текста.
|
|
195
|
-
if (estimateTokens(text) > maxTokens) {
|
|
196
|
-
if (mode === "summary") {
|
|
197
|
-
mode = "truncate";
|
|
198
|
-
}
|
|
199
|
-
text = truncateToTokens(text, maxTokens);
|
|
200
|
-
}
|
|
201
|
-
const resolvedTokens = estimateTokens(text);
|
|
202
|
-
used += resolvedTokens;
|
|
203
|
-
writeCache(cacheDir, key, { mode, text });
|
|
204
|
-
replacements.push({
|
|
205
|
-
content: text,
|
|
206
|
-
priority: "high",
|
|
207
|
-
essential: false,
|
|
208
|
-
estimatedTokens: resolvedTokens,
|
|
209
|
-
kind,
|
|
210
|
-
});
|
|
211
|
-
warnings.push({
|
|
212
|
-
kind,
|
|
213
|
-
label: blockLabel(block.content),
|
|
214
|
-
originalTokens: block.estimatedTokens,
|
|
215
|
-
resolvedTokens,
|
|
216
|
-
mode,
|
|
217
|
-
});
|
|
218
|
-
}
|
|
219
|
-
const hintBlock = replacements.length > 0
|
|
220
|
-
? {
|
|
221
|
-
content: [
|
|
222
|
-
`[Instructions note] Some project blocks exceeded the system-prompt budget and were compressed:`,
|
|
223
|
-
...warnings.map((w) => `- ${KIND_LABEL[w.kind]}: ${w.originalTokens} tokens → ${w.resolvedTokens} tokens (${w.mode})`),
|
|
224
|
-
...(unresolved.length > 0
|
|
225
|
-
? unresolved.map((k) => `- ${KIND_LABEL[k]}: did not fit at all — read it yourself if needed`)
|
|
226
|
-
: []),
|
|
227
|
-
...warnings
|
|
228
|
-
.filter((w) => KIND_SOURCE_FILE[w.kind])
|
|
229
|
-
.map((w) => `Read the full ${KIND_SOURCE_FILE[w.kind]} with read_file if details are missing.`),
|
|
230
|
-
].join("\n"),
|
|
231
|
-
priority: "high",
|
|
232
|
-
essential: true,
|
|
233
|
-
estimatedTokens: HINT_BLOCK_TOKENS,
|
|
234
|
-
}
|
|
235
|
-
: null;
|
|
236
|
-
return { replacements, hintBlock, warnings };
|
|
237
|
-
}
|
|
238
|
-
/**
|
|
239
|
-
* Резолвит источник активного окна контекста (запись провайдера или глобал).
|
|
240
|
-
* @param config конфиг приложения; @returns источник и значение окна.
|
|
241
|
-
*/
|
|
242
|
-
export function resolveContextWindowSource(config) {
|
|
243
|
-
const entries = config.provider.entries ?? [];
|
|
244
|
-
const activeLabel = config.provider.active;
|
|
245
|
-
const activeEntry = entries.find((e) => e.label && e.label === activeLabel) ??
|
|
246
|
-
(entries.length === 1 ? entries[0] : undefined);
|
|
247
|
-
if (activeEntry?.contextWindow) {
|
|
248
|
-
return { source: "entry", label: activeEntry.label, value: activeEntry.contextWindow };
|
|
249
|
-
}
|
|
250
|
-
return { source: "global", value: config.contextWindow };
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Человеческая подсказка, как поднять окно контекста: глобал (`mma context <N>`)
|
|
254
|
-
* или override записи провайдера (править файл домена провайдера).
|
|
255
|
-
*/
|
|
256
|
-
export function contextWindowHint(config, configDir, recommended) {
|
|
257
|
-
const src = resolveContextWindowSource(config);
|
|
258
|
-
if (src.source === "global") {
|
|
259
|
-
return `run "mma context ${recommended}"`;
|
|
260
|
-
}
|
|
261
|
-
return `edit "${join(configDir, "config", "provider.json")}" → provider.entries[label="${src.label}"].contextWindow = ${recommended}`;
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* Ближайший стандартный размер контекста, чей системный бюджет (10%)
|
|
265
|
-
* вмещает `neededSystemTokens`. Фолбэк — крупнейший известный.
|
|
266
|
-
*/
|
|
267
|
-
export function recommendContextSize(neededSystemTokens) {
|
|
268
|
-
const sizes = [8192, 16384, 32768, 65536, 131072, 262144];
|
|
269
|
-
return (sizes.find((s) => Math.floor(s * 0.1) >= neededSystemTokens) ?? sizes[sizes.length - 1]);
|
|
270
|
-
}
|
|
271
|
-
/** Окно контекста, чтобы доля `systemFraction` покрыла `neededTokens`. */
|
|
272
|
-
export function requiredContextWindow(neededTokens, systemFraction) {
|
|
273
|
-
const fraction = systemFraction > 0 ? systemFraction : 0.1;
|
|
274
|
-
return Math.ceil(neededTokens / fraction);
|
|
275
|
-
}
|
|
276
|
-
/** Доля системного промпта ТЕКУЩЕГО окна, чтобы покрыть `neededTokens`. */
|
|
277
|
-
export function requiredSystemFraction(neededTokens, contextWindow) {
|
|
278
|
-
if (contextWindow <= 0)
|
|
279
|
-
return 1;
|
|
280
|
-
return Math.min(1, Math.ceil((neededTokens / contextWindow) * 100) / 100);
|
|
281
|
-
}
|
|
282
|
-
/**
|
|
283
|
-
* Локализованный конкретный фикс переполненного системного промпта. Вместо
|
|
284
|
-
* грубого стандартного размера (проект 32K прыгал бы сразу на 131072) даёт
|
|
285
|
-
* сырое требование и оба рычага: больше окно или больше доля текущего окна.
|
|
286
|
-
*/
|
|
287
|
-
export function overflowHint(config, configDir, neededTokens) {
|
|
288
|
-
const fraction = config.contextBudget?.systemPrompt ?? 0.1;
|
|
289
|
-
const budget = Math.floor(config.contextWindow * fraction);
|
|
290
|
-
const recommended = recommendContextSize(neededTokens);
|
|
291
|
-
const requiredWindow = requiredContextWindow(neededTokens, fraction);
|
|
292
|
-
const requiredFraction = requiredSystemFraction(neededTokens, config.contextWindow);
|
|
293
|
-
const how = configDir
|
|
294
|
-
? contextWindowHint(config, configDir, recommended)
|
|
295
|
-
: `increase contextWindow (e.g. to ${recommended})`;
|
|
296
|
-
return [
|
|
297
|
-
t("prompt.overflow.hint_needed", {
|
|
298
|
-
needed: neededTokens,
|
|
299
|
-
window: config.contextWindow,
|
|
300
|
-
fraction,
|
|
301
|
-
budget,
|
|
302
|
-
}),
|
|
303
|
-
t("prompt.overflow.hint_window", { required: requiredWindow, recommended, how }),
|
|
304
|
-
t("prompt.overflow.hint_fraction", { fraction: requiredFraction }),
|
|
305
|
-
].join(" ");
|
|
306
|
-
}
|
|
@@ -1,375 +0,0 @@
|
|
|
1
|
-
import { setAuditSessionDir } from "../modules/security/audit-log";
|
|
2
|
-
import { sanitizeLogMessage } from "../modules/security/data-sanitizer";
|
|
3
|
-
import { redactContextSecrets } from "./agent/context-log";
|
|
4
|
-
/**
|
|
5
|
-
* Тонкая обёртка над SessionManager: убирает повторяющиеся
|
|
6
|
-
* `if (sessionManager)` + `new Date().toISOString()` из цикла агента.
|
|
7
|
-
*
|
|
8
|
-
* При создании привязывает логгер приложения и аудит-лог к каталогу сессии
|
|
9
|
-
* (вместо глобального ~/.mma/logs/).
|
|
10
|
-
*/
|
|
11
|
-
export class SessionLogger {
|
|
12
|
-
session;
|
|
13
|
-
getCaller;
|
|
14
|
-
logger;
|
|
15
|
-
constructor(session, logger, getCaller) {
|
|
16
|
-
this.session = session;
|
|
17
|
-
this.getCaller = getCaller;
|
|
18
|
-
this.logger = logger;
|
|
19
|
-
this.bindSessionDir();
|
|
20
|
-
}
|
|
21
|
-
bindSessionDir() {
|
|
22
|
-
const session = this.session;
|
|
23
|
-
const meta = session?.getActiveMeta();
|
|
24
|
-
if (!session || !meta)
|
|
25
|
-
return;
|
|
26
|
-
const dir = session.getSessionDirectory(meta.id);
|
|
27
|
-
if (this.logger) {
|
|
28
|
-
this.logger.setSessionDir(dir);
|
|
29
|
-
this.logger.initSessionLog(meta.id);
|
|
30
|
-
}
|
|
31
|
-
setAuditSessionDir(dir);
|
|
32
|
-
}
|
|
33
|
-
/** Есть ли активная сессия. */
|
|
34
|
-
get active() {
|
|
35
|
-
return !!this.session?.getActive();
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Пишет системное сообщение в лог сессии.
|
|
39
|
-
* @param content текст системного сообщения.
|
|
40
|
-
*/
|
|
41
|
-
logSystem(content) {
|
|
42
|
-
this.session?.appendLog({
|
|
43
|
-
ts: new Date().toISOString(),
|
|
44
|
-
type: "system",
|
|
45
|
-
content: redactContextSecrets(content),
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Пишет сообщение пользователя (санитизированное).
|
|
50
|
-
* @param content текст пользователя.
|
|
51
|
-
*/
|
|
52
|
-
logUser(content) {
|
|
53
|
-
const sanitized = sanitizeLogMessage(content);
|
|
54
|
-
this.session?.appendMessage({
|
|
55
|
-
role: "user",
|
|
56
|
-
content: sanitized,
|
|
57
|
-
timestamp: new Date().toISOString(),
|
|
58
|
-
});
|
|
59
|
-
this.session?.appendLog({
|
|
60
|
-
ts: new Date().toISOString(),
|
|
61
|
-
type: "user",
|
|
62
|
-
content: sanitized,
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Пишет ответ ассистента (+ reasoning и tool_calls при наличии).
|
|
67
|
-
* @param content текст ответа; @param reasoning reasoning-контент;
|
|
68
|
-
* @param toolCalls вызовы тулов; @param iteration номер итерации.
|
|
69
|
-
*/
|
|
70
|
-
logAssistant(content, reasoning, toolCalls, iteration) {
|
|
71
|
-
const caller = this.getCaller?.();
|
|
72
|
-
if (reasoning) {
|
|
73
|
-
this.session?.appendLog({
|
|
74
|
-
ts: new Date().toISOString(),
|
|
75
|
-
type: "reasoning",
|
|
76
|
-
content: redactContextSecrets(reasoning),
|
|
77
|
-
iteration,
|
|
78
|
-
provider: caller?.provider,
|
|
79
|
-
model: caller?.model,
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
this.session?.appendLog({
|
|
83
|
-
ts: new Date().toISOString(),
|
|
84
|
-
type: "assistant",
|
|
85
|
-
content: redactContextSecrets(content),
|
|
86
|
-
...(toolCalls
|
|
87
|
-
? {
|
|
88
|
-
tool_calls: toolCalls.map((tc) => ({
|
|
89
|
-
id: tc.id,
|
|
90
|
-
name: tc.name,
|
|
91
|
-
arguments: tc.arguments,
|
|
92
|
-
})),
|
|
93
|
-
}
|
|
94
|
-
: {}),
|
|
95
|
-
iteration,
|
|
96
|
-
provider: caller?.provider,
|
|
97
|
-
model: caller?.model,
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Сохраняет сообщение ассистента в историю сессии (для resume).
|
|
102
|
-
* @param content текст сообщения.
|
|
103
|
-
*/
|
|
104
|
-
saveAssistantMessage(content) {
|
|
105
|
-
const caller = this.getCaller?.();
|
|
106
|
-
this.session?.appendMessage({
|
|
107
|
-
role: "assistant",
|
|
108
|
-
content: redactContextSecrets(content),
|
|
109
|
-
timestamp: new Date().toISOString(),
|
|
110
|
-
provider: caller?.provider,
|
|
111
|
-
model: caller?.model,
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* Пишет набор определений тулов итерации (состав для пост-анализа).
|
|
116
|
-
* @param toolCount число тулов; @param toolNames имена; @param iteration итерация.
|
|
117
|
-
*/
|
|
118
|
-
logToolDefs(toolCount, toolNames, iteration) {
|
|
119
|
-
this.session?.appendLog({
|
|
120
|
-
ts: new Date().toISOString(),
|
|
121
|
-
type: "tool_defs",
|
|
122
|
-
toolCount,
|
|
123
|
-
toolNames,
|
|
124
|
-
iteration,
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Пишет вызов тула (имя, id, санитизированные аргументы).
|
|
129
|
-
* @param call вызов тула; @param iteration номер итерации.
|
|
130
|
-
*/
|
|
131
|
-
logToolCall(call, iteration) {
|
|
132
|
-
this.session?.appendLog({
|
|
133
|
-
ts: new Date().toISOString(),
|
|
134
|
-
type: "tool_call",
|
|
135
|
-
tool: call.name,
|
|
136
|
-
tool_call_id: call.id,
|
|
137
|
-
args: this.sanitizeArgs(call.arguments),
|
|
138
|
-
iteration,
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* Сериализует аргументы тула для лога. Санитайзер может испортить JSON
|
|
143
|
-
* (например, режет закрывающую кавычку в `password=secret"`), поэтому при
|
|
144
|
-
* ошибке парсинга пишем сырую санитизированную строку и предупреждаем —
|
|
145
|
-
* запись tool_call не должна теряться.
|
|
146
|
-
*/
|
|
147
|
-
sanitizeArgs(args) {
|
|
148
|
-
const raw = JSON.stringify(args ?? {});
|
|
149
|
-
const sanitized = sanitizeLogMessage(raw);
|
|
150
|
-
try {
|
|
151
|
-
const parsed = JSON.parse(sanitized);
|
|
152
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
153
|
-
return parsed;
|
|
154
|
-
}
|
|
155
|
-
return { raw: sanitized };
|
|
156
|
-
}
|
|
157
|
-
catch {
|
|
158
|
-
this.logger?.warn(`tool_call args sanitization broke JSON; storing raw string (${raw.length} chars)`);
|
|
159
|
-
return { raw: sanitized };
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Пишет результат тула (успех, вывод, diff, длительность).
|
|
164
|
-
* @param call вызов; @param result результат; @param duration длительность, мс;
|
|
165
|
-
* @param iteration номер итерации.
|
|
166
|
-
*/
|
|
167
|
-
logToolResult(call, result, duration, iteration) {
|
|
168
|
-
const caller = this.getCaller?.();
|
|
169
|
-
this.session?.appendMessage({
|
|
170
|
-
role: "tool",
|
|
171
|
-
content: sanitizeLogMessage(result.output),
|
|
172
|
-
name: call.name,
|
|
173
|
-
timestamp: new Date().toISOString(),
|
|
174
|
-
provider: caller?.provider,
|
|
175
|
-
model: caller?.model,
|
|
176
|
-
});
|
|
177
|
-
this.session?.appendLog({
|
|
178
|
-
ts: new Date().toISOString(),
|
|
179
|
-
type: "tool_result",
|
|
180
|
-
tool: call.name,
|
|
181
|
-
tool_call_id: call.id,
|
|
182
|
-
success: result.success,
|
|
183
|
-
content: sanitizeLogMessage(result.output.slice(0, 1000)),
|
|
184
|
-
diff: result.diff,
|
|
185
|
-
duration,
|
|
186
|
-
iteration,
|
|
187
|
-
provider: caller?.provider,
|
|
188
|
-
model: caller?.model,
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Пишет событие компакции (причина, токены/качество до и после).
|
|
193
|
-
* @param info параметры компакции.
|
|
194
|
-
*/
|
|
195
|
-
logCompaction(info) {
|
|
196
|
-
this.session?.appendLog({
|
|
197
|
-
ts: new Date().toISOString(),
|
|
198
|
-
type: "compaction",
|
|
199
|
-
content: `${info.reason}, iteration ${info.iteration}`,
|
|
200
|
-
iteration: info.iteration,
|
|
201
|
-
reason: info.reason,
|
|
202
|
-
tokensBefore: info.tokensBefore,
|
|
203
|
-
tokensAfter: info.tokensAfter,
|
|
204
|
-
qualityBefore: info.qualityBefore,
|
|
205
|
-
qualityAfter: info.qualityAfter,
|
|
206
|
-
messagesBefore: info.messagesBefore,
|
|
207
|
-
messagesAfter: info.messagesAfter,
|
|
208
|
-
removedTurns: info.removedTurns,
|
|
209
|
-
keptTurns: info.keptTurns,
|
|
210
|
-
summary: info.summary,
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Пишет снапшот контекста (бюджеты, токены, качество, состав блоков).
|
|
215
|
-
* @param info параметры снапшота.
|
|
216
|
-
*/
|
|
217
|
-
logContext(info) {
|
|
218
|
-
this.session?.appendLog({
|
|
219
|
-
ts: new Date().toISOString(),
|
|
220
|
-
type: "context",
|
|
221
|
-
content: info.kind === "start"
|
|
222
|
-
? "context snapshot at session start"
|
|
223
|
-
: `context at iteration ${info.iteration}`,
|
|
224
|
-
iteration: info.iteration,
|
|
225
|
-
provider: info.provider,
|
|
226
|
-
model: info.model,
|
|
227
|
-
window: info.window,
|
|
228
|
-
systemBudget: info.systemBudget,
|
|
229
|
-
reserveBudget: info.reserveBudget,
|
|
230
|
-
historyBudget: info.historyBudget,
|
|
231
|
-
systemTokens: info.systemTokens,
|
|
232
|
-
toolTokens: info.toolTokens,
|
|
233
|
-
contextTokens: info.tokens,
|
|
234
|
-
quality: info.quality,
|
|
235
|
-
messageCount: info.messageCount,
|
|
236
|
-
compactionCount: info.compactionCount,
|
|
237
|
-
iterationsSinceCompaction: info.iterationsSinceCompaction,
|
|
238
|
-
blocks: info.blocks,
|
|
239
|
-
});
|
|
240
|
-
}
|
|
241
|
-
/**
|
|
242
|
-
* Пишет usage LLM-вызова (токены, источник, кеш, стабильность префикса).
|
|
243
|
-
* @param iteration номер итерации; @param usage токены и мета.
|
|
244
|
-
*/
|
|
245
|
-
logLlmUsage(iteration, usage) {
|
|
246
|
-
this.session?.appendLog({
|
|
247
|
-
ts: new Date().toISOString(),
|
|
248
|
-
type: "llm_usage",
|
|
249
|
-
iteration,
|
|
250
|
-
provider: usage.provider,
|
|
251
|
-
model: usage.model,
|
|
252
|
-
promptTokens: usage.promptTokens,
|
|
253
|
-
completionTokens: usage.completionTokens,
|
|
254
|
-
totalTokens: usage.totalTokens,
|
|
255
|
-
source: usage.source,
|
|
256
|
-
durationMs: usage.durationMs,
|
|
257
|
-
cacheStable: usage.prefix ? Number(usage.prefix.stableRatio.toFixed(4)) : undefined,
|
|
258
|
-
cacheCause: usage.prefix?.cause,
|
|
259
|
-
cachedTokens: usage.cache?.cachedTokens,
|
|
260
|
-
cacheWriteTokens: usage.cache?.cacheWriteTokens,
|
|
261
|
-
cacheSource: usage.cache?.source,
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Пишет ошибку в лог сессии.
|
|
266
|
-
* @param message текст ошибки.
|
|
267
|
-
*/
|
|
268
|
-
logError(message) {
|
|
269
|
-
this.session?.appendLog({
|
|
270
|
-
ts: new Date().toISOString(),
|
|
271
|
-
type: "error",
|
|
272
|
-
content: redactContextSecrets(message),
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* Пишет вердикт финального аудита.
|
|
277
|
-
* @param summary сводка аудита; @param iteration номер итерации.
|
|
278
|
-
*/
|
|
279
|
-
logAudit(summary, iteration) {
|
|
280
|
-
this.session?.appendLog({
|
|
281
|
-
ts: new Date().toISOString(),
|
|
282
|
-
type: "audit",
|
|
283
|
-
content: summary,
|
|
284
|
-
iteration,
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
/**
|
|
288
|
-
* Пишет событие плана MoE/обычного (создание, шаги, re-plan).
|
|
289
|
-
* @param event имя события; @param detail детали; @param iteration итерация.
|
|
290
|
-
*/
|
|
291
|
-
logPlan(event, detail, iteration) {
|
|
292
|
-
this.session?.appendLog({
|
|
293
|
-
ts: new Date().toISOString(),
|
|
294
|
-
type: "plan",
|
|
295
|
-
content: detail,
|
|
296
|
-
tool: event,
|
|
297
|
-
...(iteration !== undefined ? { iteration } : {}),
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
/**
|
|
301
|
-
* Пишет стартовую диагностику сессии: окружение, LSP-проба, плагины, скиллы.
|
|
302
|
-
* Должна быть ПЕРВОЙ записью в session.jsonl (файл самоописываем).
|
|
303
|
-
* Пропускает, если session_start уже есть (напр., записан REPL).
|
|
304
|
-
*/
|
|
305
|
-
logSessionStart(data) {
|
|
306
|
-
// Пропуск при уже записанном session_start (REPL мог записать с LSP-пробой).
|
|
307
|
-
// Чтение через decrypt-aware store: при шифровании сессии строки на диске —
|
|
308
|
-
// шифртекст, поэтому проверка подстрокой никогда не срабатывала и дубль дописывался.
|
|
309
|
-
const meta = this.session?.getActiveMeta();
|
|
310
|
-
if (meta) {
|
|
311
|
-
try {
|
|
312
|
-
const entries = this.session.loadSessionLog(meta.id);
|
|
313
|
-
if (entries.some((e) => e.type === "session_start"))
|
|
314
|
-
return;
|
|
315
|
-
}
|
|
316
|
-
catch {
|
|
317
|
-
// Ошибка чтения — всё равно пишем
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
this.session?.appendLog({
|
|
321
|
-
ts: new Date().toISOString(),
|
|
322
|
-
type: "session_start",
|
|
323
|
-
content: "session started",
|
|
324
|
-
environment: data.environment,
|
|
325
|
-
lspProbe: data.lspProbe,
|
|
326
|
-
plugins: data.plugins,
|
|
327
|
-
skills: data.skills,
|
|
328
|
-
});
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* Пишет событие управления reasoning (уровень, оценка политики).
|
|
332
|
-
*/
|
|
333
|
-
logReasoningControl(data) {
|
|
334
|
-
this.session?.appendLog({
|
|
335
|
-
ts: new Date().toISOString(),
|
|
336
|
-
type: "reasoning_control",
|
|
337
|
-
content: `reasoning level: ${data.level} (source: ${data.source ?? "policy"})`,
|
|
338
|
-
iteration: data.iteration,
|
|
339
|
-
level: data.level,
|
|
340
|
-
strategy: data.strategy,
|
|
341
|
-
probePassed: data.probePassed,
|
|
342
|
-
source: data.source,
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
/**
|
|
346
|
-
* Пишет событие наблюдаемости MoE (moe_plan / moe_subtask / moe_replan /
|
|
347
|
-
* moe_verify). Эмитят runWithMoE и MoEExecutor (Plan 4.2).
|
|
348
|
-
*/
|
|
349
|
-
logMoE(event, data) {
|
|
350
|
-
this.session?.appendLog({
|
|
351
|
-
ts: new Date().toISOString(),
|
|
352
|
-
type: event,
|
|
353
|
-
content: data.detail ?? data.explanation ?? event,
|
|
354
|
-
...data,
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
/** Пишет событие онбординга (meet/init) для пост-анализа. */
|
|
358
|
-
logOnboarding(event, data = {}) {
|
|
359
|
-
this.session?.appendLog({
|
|
360
|
-
ts: new Date().toISOString(),
|
|
361
|
-
type: `onboarding_${event}`,
|
|
362
|
-
content: event,
|
|
363
|
-
...data,
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
/** Пишет событие критика (контр-агент). */
|
|
367
|
-
logCritic(event, data = {}) {
|
|
368
|
-
this.session?.appendLog({
|
|
369
|
-
ts: new Date().toISOString(),
|
|
370
|
-
type: event,
|
|
371
|
-
content: data.summary ?? event,
|
|
372
|
-
...data,
|
|
373
|
-
});
|
|
374
|
-
}
|
|
375
|
-
}
|