micro-models-agent 2.16.1 → 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 +28 -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 -1250
- 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 -291
- package/dist/assets/setup.js +3 -816
- package/dist/assets/smd.js +29 -1665
- package/dist/assets/styles.css +1 -1598
- 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,482 +0,0 @@
|
|
|
1
|
-
import { getMessageText } from "../../llm/provider";
|
|
2
|
-
import { FactExtractor } from "./fact-extractor";
|
|
3
|
-
import { truncate } from "../../utils/truncate";
|
|
4
|
-
const COMPACTION_INTERVAL = 15;
|
|
5
|
-
const KEEP_LAST_N = 6;
|
|
6
|
-
function summarizeArgs(args) {
|
|
7
|
-
if (!args)
|
|
8
|
-
return "";
|
|
9
|
-
if (typeof args === "string")
|
|
10
|
-
return args.slice(0, 80);
|
|
11
|
-
try {
|
|
12
|
-
const keys = Object.keys(args);
|
|
13
|
-
return keys.slice(0, 3).join(", ");
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
return String(args).slice(0, 80);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
function looksLikeErrorPaste(text) {
|
|
20
|
-
// Маркеры ошибок.
|
|
21
|
-
if (/(?:^|\s)ERROR|Error:|error TS\d+|Transform failed|\[plugin:|SyntaxError|Cannot find|Uncaught|exception/i.test(text)) {
|
|
22
|
-
return true;
|
|
23
|
-
}
|
|
24
|
-
// Структурные сигналы вставленного вывода компилятора/рантайма: фреймы
|
|
25
|
-
// исходников ("270| }_s(...)"), ссылки path:line:col и строки стектрейсов.
|
|
26
|
-
if (/(?:^|\n)\s*\d+\s*\|/.test(text))
|
|
27
|
-
return true;
|
|
28
|
-
if (/[\w./\\-]+\.[a-z]{1,6}:\d+:\d+/.test(text))
|
|
29
|
-
return true;
|
|
30
|
-
if (/(?:^|\n)\s*at\s+\S+/.test(text))
|
|
31
|
-
return true;
|
|
32
|
-
return false;
|
|
33
|
-
}
|
|
34
|
-
/** Извлекает повторы "пробовали и не вышло" (≥2 фейлов одного тула+args). */
|
|
35
|
-
export function extractTriedAndFailed(messages) {
|
|
36
|
-
const failures = new Map();
|
|
37
|
-
for (const msg of messages) {
|
|
38
|
-
if (msg.role === "tool" && msg.name && msg.success === false) {
|
|
39
|
-
// Заблокированные плагином вызовы — решения гардов, не попытки: транзиентный
|
|
40
|
-
// гард (или его баг) нельзя запоминать как "пробовали и не вышло — НЕ повторять"
|
|
41
|
-
// (было: ложный plan-alignment блок заставил модель отказываться переписывать
|
|
42
|
-
// файл собственного шага).
|
|
43
|
-
if (msg.blocked)
|
|
44
|
-
continue;
|
|
45
|
-
const key = `${msg.name}:${summarizeArgs(msg.arguments)}`;
|
|
46
|
-
const existing = failures.get(key);
|
|
47
|
-
const errorText = truncate(typeof msg.content === "string" ? msg.content : getMessageText(msg.content), 100);
|
|
48
|
-
if (existing) {
|
|
49
|
-
existing.count++;
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
failures.set(key, {
|
|
53
|
-
tool: msg.name,
|
|
54
|
-
args: summarizeArgs(msg.arguments),
|
|
55
|
-
error: errorText,
|
|
56
|
-
count: 1,
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
return Array.from(failures.values()).filter((f) => f.count >= 2);
|
|
62
|
-
}
|
|
63
|
-
/** Менеджер контекста: история, бюджеты, компакция, трекинг задачи/миссии сессии. */
|
|
64
|
-
export class ContextManager {
|
|
65
|
-
contextWindow;
|
|
66
|
-
messages = [];
|
|
67
|
-
compactedBlock = null;
|
|
68
|
-
iterationsSinceCompaction = 0;
|
|
69
|
-
compactionCount = 0;
|
|
70
|
-
peakTokens = 0;
|
|
71
|
-
budget;
|
|
72
|
-
compactionThreshold;
|
|
73
|
-
/**
|
|
74
|
-
* Минимальная загрузка истории (доля бюджета), нужная интервалу итераций для
|
|
75
|
-
* срабатывания компакции. Интервал — защита от частоты, не триггер: слабо
|
|
76
|
-
* загруженный контекст нельзя уплотнять лишь потому, что прошло N итераций
|
|
77
|
-
* (было: компакция на ~40% бюджета стирала 33-44 полезных хода посреди задачи).
|
|
78
|
-
*/
|
|
79
|
-
compactionMinLoad;
|
|
80
|
-
facts = new FactExtractor();
|
|
81
|
-
/** Последняя реальная инструкция юзера (мимо <system-summary>). */
|
|
82
|
-
lastUserTask = "";
|
|
83
|
-
/** Первая реальная инструкция сессии — переживает resetUserTurn(). */
|
|
84
|
-
sessionMission = "";
|
|
85
|
-
/** Последнее сообщение юзера, похожее на вставленную ошибку/лог (не задача). */
|
|
86
|
-
lastUserFeedback = "";
|
|
87
|
-
tokenCounter;
|
|
88
|
-
pendingImageParts = [];
|
|
89
|
-
toolTokens = 0;
|
|
90
|
-
/** Текущий reasoning-уровень (ставит цикл агента, входит в сводку компакции). */
|
|
91
|
-
thinkingLevel = null;
|
|
92
|
-
onCompact = null;
|
|
93
|
-
/**
|
|
94
|
-
* Опциональная короткая строка в сводку компакции, чтобы модель знала про
|
|
95
|
-
* активный план с прогрессом. Прокидывается из bootstrap в execution-модуль —
|
|
96
|
-
* без неё 9B-модель пересоздаёт план с нуля сразу после компакции (было:
|
|
97
|
-
* ses_msvuao0h — plan_e07pb2 (1/6) выброшен ради свежего plan_xzq9xe в ту же
|
|
98
|
-
* итерацию, когда старый план ещё был виден).
|
|
99
|
-
*/
|
|
100
|
-
planSummaryProvider = null;
|
|
101
|
-
constructor(contextWindow, contextBudget, tokenCounter) {
|
|
102
|
-
this.contextWindow = contextWindow;
|
|
103
|
-
this.compactionThreshold = contextBudget?.compactionThreshold ?? 0.75;
|
|
104
|
-
this.compactionMinLoad = contextBudget?.compactionMinLoad ?? 0.5;
|
|
105
|
-
this.budget = this.calculateBudget(contextWindow, contextBudget);
|
|
106
|
-
this.tokenCounter = tokenCounter ?? null;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Задаёт короткую строку "текущий план" для сводки компакции, или null если
|
|
110
|
-
* плана нет. Инжектится один раз на bootstrap (не per-turn состояние).
|
|
111
|
-
*/
|
|
112
|
-
setPlanSummaryProvider(fn) {
|
|
113
|
-
this.planSummaryProvider = fn;
|
|
114
|
-
}
|
|
115
|
-
calculateBudget(window, contextBudget) {
|
|
116
|
-
if (contextBudget) {
|
|
117
|
-
const systemPrompt = Math.floor(window * contextBudget.systemPrompt);
|
|
118
|
-
const responseReserve = Math.floor(window * contextBudget.responseReserve);
|
|
119
|
-
const history = Math.max(0, window - systemPrompt - responseReserve);
|
|
120
|
-
return { systemPrompt, responseReserve, history };
|
|
121
|
-
}
|
|
122
|
-
// Фолбэк для обратной совместимости (тесты, сабагенты без явного бюджета)
|
|
123
|
-
return {
|
|
124
|
-
systemPrompt: Math.floor(window * 0.25),
|
|
125
|
-
responseReserve: Math.floor(window * 0.12),
|
|
126
|
-
history: Math.floor(window * 0.63),
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
/** Копия текущего бюджета. */
|
|
130
|
-
getBudget() {
|
|
131
|
-
return { ...this.budget };
|
|
132
|
-
}
|
|
133
|
-
/** Число выполненных компакций. */
|
|
134
|
-
getCompactionCount() {
|
|
135
|
-
return this.compactionCount;
|
|
136
|
-
}
|
|
137
|
-
/** Итераций с последней компакции. */
|
|
138
|
-
getIterationsSinceCompaction() {
|
|
139
|
-
return this.iterationsSinceCompaction;
|
|
140
|
-
}
|
|
141
|
-
/** Файлы, известные из сводок компакции — сидируют known-files проверки
|
|
142
|
-
* галлюцинаций, чтобы голые имена переживали сбросы контекста. */
|
|
143
|
-
getKnownFiles() {
|
|
144
|
-
return this.facts.getKnownFiles();
|
|
145
|
-
}
|
|
146
|
-
/** Отмечает прошедшую итерацию (счётчик для интервала компакции). */
|
|
147
|
-
noteIteration() {
|
|
148
|
-
this.iterationsSinceCompaction++;
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Начинает свежий ход юзера. 15-итерационный интервал компакции не должен
|
|
152
|
-
* течь через сообщения юзера — иначе ход, кончившийся на итерации 14,
|
|
153
|
-
* форсит компакцию на первой же итерации следующего сообщения (было:
|
|
154
|
-
* компакция на итерации 8 нового хода снесла свежеприсланную задачу юзера
|
|
155
|
-
* вместе с 40+ старыми ходами). Факты сохраняются.
|
|
156
|
-
*/
|
|
157
|
-
resetUserTurn() {
|
|
158
|
-
this.iterationsSinceCompaction = 0;
|
|
159
|
-
// Новое сообщение юзера начинает новый ход — сбрасываем задачу прошлого хода,
|
|
160
|
-
// чтобы сводка сохранила свежую инструкцию. Миссия сессии выживает: вставка
|
|
161
|
-
// ошибки/лога в новом ходе не должна стирать исходную цель.
|
|
162
|
-
this.lastUserTask = "";
|
|
163
|
-
this.lastUserFeedback = "";
|
|
164
|
-
}
|
|
165
|
-
/** Оценка качества контекста 0–100 (нагрузка, компакции, ошибки, свежесть). */
|
|
166
|
-
getQuality() {
|
|
167
|
-
const usedTokens = this.getEstimatedTokens();
|
|
168
|
-
const tokenLoad = this.budget.history > 0
|
|
169
|
-
? Math.max(0, 1 - usedTokens / this.budget.history)
|
|
170
|
-
: 0;
|
|
171
|
-
// Восстанавливаемый штраф: каждая компакция теряет часть информации, но штраф
|
|
172
|
-
// ОГРАНИЧЕН СВЕРХУ, чтобы кумулятивные компакции не прикалывали качество ниже
|
|
173
|
-
// триггера форсированной компакции (40%). До капа сессия с ~7+ компакциями
|
|
174
|
-
// клампила слагаемое в 0 навсегда; вместе с тяжёлой токенной нагрузкой и
|
|
175
|
-
// плотностью ошибок качество застревало ниже 40 и компакция срабатывала на
|
|
176
|
-
// КАЖДОЙ итерации (было: 56 компакций за 28 минут).
|
|
177
|
-
const COMPACTION_PENALTY_FLOOR = 0.5;
|
|
178
|
-
const compactionLoss = Math.max(COMPACTION_PENALTY_FLOOR, 1 - this.compactionCount * 0.15);
|
|
179
|
-
const msgCount = this.messages.length || 1;
|
|
180
|
-
const errorDensity = Math.max(0, 1 - Math.min(1, this.facts.errorCount / msgCount));
|
|
181
|
-
const freshness = Math.max(0, 1 - this.iterationsSinceCompaction / COMPACTION_INTERVAL);
|
|
182
|
-
const score = tokenLoad * 0.4 + compactionLoss * 0.25 + errorDensity * 0.2 + freshness * 0.15;
|
|
183
|
-
return Math.round(Math.min(100, Math.max(0, score * 100)));
|
|
184
|
-
}
|
|
185
|
-
/** Добавляет сообщение в историю (трекает задачу, аттачит pending-картинки, пик токенов). */
|
|
186
|
-
addMessage(msg) {
|
|
187
|
-
// Трекаем задачу, над которой работает агент, чтобы пережила компакцию.
|
|
188
|
-
// Реальная инструкция юзера — ПЕРВОЕ не-system-summary user-сообщение хода;
|
|
189
|
-
// всё после (результаты тулов, retry-nudge'и) — инжектированные `user`-
|
|
190
|
-
// конверты, которые не должны её затирать (было: после компакции модель
|
|
191
|
-
// забывала "удали /bicycles, почини стили" и 40+ итераций бесцельно читала файлы).
|
|
192
|
-
if (msg.role === "user") {
|
|
193
|
-
const text = typeof msg.content === "string" ? msg.content : getMessageText(msg.content);
|
|
194
|
-
if (text.trim() && !text.startsWith("<system-summary>") && !text.includes("[Compressed:")) {
|
|
195
|
-
if (looksLikeErrorPaste(text) && (this.lastUserTask || this.sessionMission)) {
|
|
196
|
-
this.lastUserFeedback = text.trim().slice(0, 400);
|
|
197
|
-
}
|
|
198
|
-
else if (!this.lastUserTask && !this.lastUserFeedback) {
|
|
199
|
-
// Нет новой задачи внутри хода, где уже поймана вставка ошибки/лога:
|
|
200
|
-
// последующие сообщения — продолжения результатов тулов, не свежая
|
|
201
|
-
// инструкция, поэтому на компакции побеждает миссия сессии.
|
|
202
|
-
this.lastUserTask = text.trim();
|
|
203
|
-
if (!this.sessionMission)
|
|
204
|
-
this.sessionMission = text.trim();
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
// Авто-аттач pending-картинок к следующему user-сообщению
|
|
209
|
-
if (msg.role === "user" && this.pendingImageParts.length > 0) {
|
|
210
|
-
const textPart = {
|
|
211
|
-
type: "text",
|
|
212
|
-
text: typeof msg.content === "string" ? msg.content : getMessageText(msg.content),
|
|
213
|
-
};
|
|
214
|
-
msg = {
|
|
215
|
-
...msg,
|
|
216
|
-
content: [textPart, ...this.pendingImageParts],
|
|
217
|
-
};
|
|
218
|
-
this.pendingImageParts = [];
|
|
219
|
-
}
|
|
220
|
-
this.messages.push(msg);
|
|
221
|
-
const tokens = this.getEstimatedTokens();
|
|
222
|
-
if (tokens > this.peakTokens)
|
|
223
|
-
this.peakTokens = tokens;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Кладёт картинку в очередь на аттач к следующему user-сообщению.
|
|
227
|
-
*/
|
|
228
|
-
addPendingImage(part) {
|
|
229
|
-
this.pendingImageParts.push(part);
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* True, если есть картинки, ждущие аттача.
|
|
233
|
-
*/
|
|
234
|
-
hasPendingImages() {
|
|
235
|
-
return this.pendingImageParts.length > 0;
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Возвращает pending-картинки, не очищая очередь.
|
|
239
|
-
*/
|
|
240
|
-
getPendingImages() {
|
|
241
|
-
return [...this.pendingImageParts];
|
|
242
|
-
}
|
|
243
|
-
/**
|
|
244
|
-
* Очищает pending-картинки (напр., юзер шлёт чисто текстовое сообщение).
|
|
245
|
-
*/
|
|
246
|
-
clearPendingImages() {
|
|
247
|
-
this.pendingImageParts = [];
|
|
248
|
-
}
|
|
249
|
-
/** Число сообщений в истории. */
|
|
250
|
-
getMessageCount() {
|
|
251
|
-
return this.messages.length;
|
|
252
|
-
}
|
|
253
|
-
// Токенный кэш на сообщение: сообщения считаются иммутабельными после добавления
|
|
254
|
-
// (компакция/updateSystemPrompt создают новые объекты), поэтому WeakMap безопасен
|
|
255
|
-
// и превращает повторную оценку всей истории из O(n) кодирований в O(1).
|
|
256
|
-
tokenCache = new WeakMap();
|
|
257
|
-
estimateMessageTokensCached(m) {
|
|
258
|
-
let t = this.tokenCache.get(m);
|
|
259
|
-
if (t === undefined) {
|
|
260
|
-
t = this.estimateMessageTokens(m);
|
|
261
|
-
this.tokenCache.set(m, t);
|
|
262
|
-
}
|
|
263
|
-
return t;
|
|
264
|
-
}
|
|
265
|
-
estimateMessageTokens(m) {
|
|
266
|
-
const text = getMessageText(m.content);
|
|
267
|
-
if (this.tokenCounter) {
|
|
268
|
-
let t = this.tokenCounter.count(text);
|
|
269
|
-
// Токены картинок: base64 ~130 токенов на тайл 512x512; грубая оценка
|
|
270
|
-
if (Array.isArray(m.content)) {
|
|
271
|
-
for (const part of m.content) {
|
|
272
|
-
if (part.type === "image_url" && part.image_url?.url) {
|
|
273
|
-
const b64Len = part.image_url.url.includes(",")
|
|
274
|
-
? (part.image_url.url.split(",")[1]?.length ?? 0)
|
|
275
|
-
: part.image_url.url.length;
|
|
276
|
-
// ~130 токенов на 512 байт base64
|
|
277
|
-
t += Math.ceil(b64Len / 512) * 130;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
if (m.tool_calls) {
|
|
282
|
-
for (const tc of m.tool_calls) {
|
|
283
|
-
t += this.tokenCounter.count(tc.id);
|
|
284
|
-
t += this.tokenCounter.count(tc.function.name);
|
|
285
|
-
t += this.tokenCounter.count(tc.function.arguments);
|
|
286
|
-
t += 4;
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
return t;
|
|
290
|
-
}
|
|
291
|
-
let t = Math.ceil(text.length / 2);
|
|
292
|
-
if (Array.isArray(m.content)) {
|
|
293
|
-
for (const part of m.content) {
|
|
294
|
-
if (part.type === "image_url" && part.image_url?.url) {
|
|
295
|
-
const b64Len = part.image_url.url.includes(",")
|
|
296
|
-
? (part.image_url.url.split(",")[1]?.length ?? 0)
|
|
297
|
-
: part.image_url.url.length;
|
|
298
|
-
t += Math.ceil(b64Len / 512) * 130;
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
if (m.tool_calls) {
|
|
303
|
-
for (const tc of m.tool_calls) {
|
|
304
|
-
t += Math.ceil(tc.id.length / 2);
|
|
305
|
-
t += Math.ceil(tc.function.name.length / 2);
|
|
306
|
-
t += Math.ceil(tc.function.arguments.length / 2);
|
|
307
|
-
t += 4;
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
return t;
|
|
311
|
-
}
|
|
312
|
-
/** True, если истории нужна компакция (бюджет превышен или интервал + загрузка). */
|
|
313
|
-
needsCompaction() {
|
|
314
|
-
const totalTokens = this.messages.reduce((sum, m) => sum + this.estimateMessageTokensCached(m), 0);
|
|
315
|
-
if (totalTokens > this.budget.history * this.compactionThreshold)
|
|
316
|
-
return true;
|
|
317
|
-
// Интервал итераций уплотняет только значимо загруженную историю.
|
|
318
|
-
// Уплотнять слабозагруженный контекст — терять рабочее состояние без
|
|
319
|
-
// бюджетной причины (см. `compactionMinLoad`).
|
|
320
|
-
if (this.iterationsSinceCompaction < COMPACTION_INTERVAL)
|
|
321
|
-
return false;
|
|
322
|
-
const load = this.budget.history > 0 ? totalTokens / this.budget.history : 0;
|
|
323
|
-
return load >= this.compactionMinLoad;
|
|
324
|
-
}
|
|
325
|
-
/** Уплотняет историю: старые ходы → сводка фактов, свежие — дословно. Null, если уплотнять нечего. */
|
|
326
|
-
compact() {
|
|
327
|
-
// Снимаем состояние ДО компакции ПЕРЕД сбросом/ростом счётчиков —
|
|
328
|
-
// qualityBefore обязан отражать контекст, который реально видела модель.
|
|
329
|
-
const tokensBefore = this.getEstimatedTokens();
|
|
330
|
-
const qualityBefore = this.getQuality();
|
|
331
|
-
const messagesBefore = this.messages.length;
|
|
332
|
-
// Сбрасываем счётчик, даже если уплотнять нечего — иначе
|
|
333
|
-
// needsCompaction() вечно true после 15 итераций с малым числом сообщений.
|
|
334
|
-
this.iterationsSinceCompaction = 0;
|
|
335
|
-
if (this.messages.length <= KEEP_LAST_N * 2)
|
|
336
|
-
return null;
|
|
337
|
-
this.compactionCount++;
|
|
338
|
-
let cutoff = this.messages.length - KEEP_LAST_N * 2;
|
|
339
|
-
// Не режем группу assistant(tool_calls) по cutoff: сохранённая история не
|
|
340
|
-
// должна начинаться с сиротских role:"tool", а assistant-половина — остаться
|
|
341
|
-
// в уплотняемой части (OpenAI-совместимые бэкенды такие истории отвергают).
|
|
342
|
-
while (cutoff > 0 &&
|
|
343
|
-
(this.messages[cutoff]?.role === "tool" || this.messages[cutoff - 1]?.tool_calls?.length)) {
|
|
344
|
-
cutoff--;
|
|
345
|
-
}
|
|
346
|
-
const oldTurns = this.messages.slice(0, cutoff);
|
|
347
|
-
const recentTurns = this.messages.slice(cutoff);
|
|
348
|
-
this.facts.extract(oldTurns);
|
|
349
|
-
const parts = [];
|
|
350
|
-
parts.push(`[Compressed: ${oldTurns.length} old turns removed]`);
|
|
351
|
-
// Проносим реальную инструкцию юзера — модель не должна терять задачу,
|
|
352
|
-
// над которой работает, лишь потому что уплотнилось 40 ходов. Задача хода
|
|
353
|
-
// фолбэчится на миссию сессии (первую реальную инструкцию), чтобы вставка
|
|
354
|
-
// ошибки/лога в текущем ходе не стирала цель.
|
|
355
|
-
const task = (this.lastUserTask || this.sessionMission).slice(0, 400);
|
|
356
|
-
if (task)
|
|
357
|
-
parts.push(`[Task: ${task}]`);
|
|
358
|
-
if (this.lastUserFeedback && !task.startsWith(this.lastUserFeedback)) {
|
|
359
|
-
parts.push(`[User feedback: ${this.lastUserFeedback}]`);
|
|
360
|
-
}
|
|
361
|
-
// Ориентируем модель после компакции: активный план нельзя пересоздавать
|
|
362
|
-
// с нуля (см. доку planSummaryProvider).
|
|
363
|
-
const planLine = this.planSummaryProvider?.();
|
|
364
|
-
if (planLine)
|
|
365
|
-
parts.push(`[Plan: ${planLine}]`);
|
|
366
|
-
const filesLine = this.facts.filesLine();
|
|
367
|
-
if (filesLine)
|
|
368
|
-
parts.push(filesLine);
|
|
369
|
-
const deletedLine = this.facts.deletedLine();
|
|
370
|
-
if (deletedLine)
|
|
371
|
-
parts.push(deletedLine);
|
|
372
|
-
const readLine = this.facts.readLine();
|
|
373
|
-
if (readLine)
|
|
374
|
-
parts.push(readLine);
|
|
375
|
-
const decisionsLine = this.facts.decisionsLine();
|
|
376
|
-
if (decisionsLine)
|
|
377
|
-
parts.push(decisionsLine);
|
|
378
|
-
const errorsLine = this.facts.errorsLine();
|
|
379
|
-
if (errorsLine)
|
|
380
|
-
parts.push(errorsLine);
|
|
381
|
-
if (this.thinkingLevel)
|
|
382
|
-
parts.push(`[Thinking: ${this.thinkingLevel}]`);
|
|
383
|
-
const triedAndFailed = extractTriedAndFailed(oldTurns);
|
|
384
|
-
if (triedAndFailed.length > 0) {
|
|
385
|
-
const lines = triedAndFailed.map((t) => `- ${t.tool}(${t.args}): ${t.error} (failed ${t.count}x)`);
|
|
386
|
-
parts.push(`[Already tried & failed — do NOT repeat:]\n${lines.join("\n")}`);
|
|
387
|
-
}
|
|
388
|
-
this.compactedBlock = parts.join(" ");
|
|
389
|
-
const summary = {
|
|
390
|
-
role: "user",
|
|
391
|
-
content: `<system-summary>${this.compactedBlock}</system-summary>`,
|
|
392
|
-
};
|
|
393
|
-
const firstSystem = this.messages.find((m) => m.role === "system");
|
|
394
|
-
// Чистим протухшие system-summary из свежих ходов против вложенности
|
|
395
|
-
const freshRecent = recentTurns.filter((m) => {
|
|
396
|
-
if (m.role !== "user")
|
|
397
|
-
return true;
|
|
398
|
-
const text = getMessageText(m.content);
|
|
399
|
-
return !text.startsWith("<system-summary>");
|
|
400
|
-
});
|
|
401
|
-
this.messages = [...(firstSystem ? [firstSystem] : []), summary, ...freshRecent];
|
|
402
|
-
this.iterationsSinceCompaction = 0;
|
|
403
|
-
if (this.onCompact) {
|
|
404
|
-
this.onCompact(summary);
|
|
405
|
-
}
|
|
406
|
-
return {
|
|
407
|
-
removedTurns: oldTurns.length,
|
|
408
|
-
keptTurns: freshRecent.length,
|
|
409
|
-
tokensBefore,
|
|
410
|
-
tokensAfter: this.getEstimatedTokens(),
|
|
411
|
-
qualityBefore,
|
|
412
|
-
qualityAfter: this.getQuality(),
|
|
413
|
-
messagesBefore,
|
|
414
|
-
messagesAfter: this.messages.length,
|
|
415
|
-
summary: this.compactedBlock ?? "",
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Снапшот текущего состояния контекста — для лога начальной структуры
|
|
420
|
-
* контекста на старте сессии и per-iteration статистики.
|
|
421
|
-
*/
|
|
422
|
-
getSnapshot() {
|
|
423
|
-
return {
|
|
424
|
-
window: this.contextWindow,
|
|
425
|
-
budget: { ...this.budget },
|
|
426
|
-
tokens: this.getEstimatedTokens(),
|
|
427
|
-
toolTokens: this.toolTokens,
|
|
428
|
-
messageCount: this.messages.length,
|
|
429
|
-
quality: this.getQuality(),
|
|
430
|
-
compactionCount: this.compactionCount,
|
|
431
|
-
iterationsSinceCompaction: this.iterationsSinceCompaction,
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
/**
|
|
435
|
-
* Заменяет системный промпт на месте (остаётся первым) или пренпендит новый.
|
|
436
|
-
* Обновляет динамические блоки промпта (напр. чеклист плана) посреди прогона.
|
|
437
|
-
*/
|
|
438
|
-
updateSystemPrompt(content) {
|
|
439
|
-
const idx = this.messages.findIndex((m) => m.role === "system");
|
|
440
|
-
if (idx >= 0) {
|
|
441
|
-
this.messages[idx] = { ...this.messages[idx], content };
|
|
442
|
-
}
|
|
443
|
-
else {
|
|
444
|
-
this.messages.unshift({ role: "system", content });
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
/** Копия активной истории сообщений. */
|
|
448
|
-
getActiveHistory() {
|
|
449
|
-
return [...this.messages];
|
|
450
|
-
}
|
|
451
|
-
/**
|
|
452
|
-
* Сбрасывает всё, что принадлежит текущему ходу диалога.
|
|
453
|
-
* Списки фактов (FactExtractor) осознанно переживают clear() — это
|
|
454
|
-
* session-scoped состояние компакции, не per-turn.
|
|
455
|
-
*/
|
|
456
|
-
clear() {
|
|
457
|
-
this.messages = [];
|
|
458
|
-
this.compactedBlock = null;
|
|
459
|
-
this.iterationsSinceCompaction = 0;
|
|
460
|
-
this.compactionCount = 0;
|
|
461
|
-
this.peakTokens = 0;
|
|
462
|
-
this.lastUserTask = "";
|
|
463
|
-
this.lastUserFeedback = "";
|
|
464
|
-
this.sessionMission = "";
|
|
465
|
-
}
|
|
466
|
-
/** Оценка токенов истории (сообщения + токены тулов). */
|
|
467
|
-
getEstimatedTokens() {
|
|
468
|
-
return (this.messages.reduce((sum, m) => sum + this.estimateMessageTokensCached(m), 0) + this.toolTokens);
|
|
469
|
-
}
|
|
470
|
-
/** Задаёт токены определений тулов (прибавляются к оценке). */
|
|
471
|
-
setToolTokens(tokens) {
|
|
472
|
-
this.toolTokens = tokens;
|
|
473
|
-
}
|
|
474
|
-
/** Пересчитывает бюджеты под новое окно контекста (и опционально счётчик). */
|
|
475
|
-
resize(contextWindow, contextBudget, tokenCounter) {
|
|
476
|
-
this.contextWindow = contextWindow;
|
|
477
|
-
this.budget = this.calculateBudget(contextWindow, contextBudget);
|
|
478
|
-
if (tokenCounter !== undefined) {
|
|
479
|
-
this.tokenCounter = tokenCounter ?? null;
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
}
|
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
// Клиент контр-агента: верификация пакета доказательств с опциональным read-only контуром.
|
|
2
|
-
import { jsonrepair } from "jsonrepair";
|
|
3
|
-
import { parseChecks, runCriticChecks, renderCheckResults, CRITIC_READONLY_TOOLS } from "./tools";
|
|
4
|
-
export const CRITIC_SYSTEM_PROMPT = `You are a strict but fair verifier ("counter-agent") reviewing an AI agent's in-progress work.
|
|
5
|
-
Rules:
|
|
6
|
-
- Flag ONLY issues that can be verified from the evidence provided. Do not speculate or invent.
|
|
7
|
-
- Do not nitpick style, wording, or preferences unless the user's task demanded it.
|
|
8
|
-
- If the evidence is insufficient to judge, return status "ok" (prefer silence over noise).
|
|
9
|
-
- "critical" = the task's stated result is demonstrably not delivered. "concern" = a concrete, checkable gap. "info" = minor.
|
|
10
|
-
- Every issue must reference concrete evidence (file, command, output).
|
|
11
|
-
Reply with JSON ONLY:
|
|
12
|
-
{"status":"ok|concern|critical","summary":"one line","issues":[{"severity":"info|concern|critical","claim":"...","problem":"...","suggestion":"...","evidence":"..."}]}`;
|
|
13
|
-
const CHECK_REQUEST_INSTRUCTION = `If your verdict is concern/critical and a read-only file check could confirm or refute an issue, request up to 3 checks by adding "checks":[{"tool":"...","args":{...}}] to your JSON. Available tools ONLY: ${CRITIC_READONLY_TOOLS.join(", ")} (read-only; no writes, shell, web, or memory exist — do not request anything else). Checks run locally and their outputs return to you for a FINAL verdict. If no check would help, omit "checks".`;
|
|
14
|
-
const FINAL_VERDICT_INSTRUCTION = `Check outputs above are ground truth from the workspace. Reply with your FINAL verdict as JSON (same shape, no more "checks"): confirm each issue the checks support, drop the ones they refute, and set status accordingly.`;
|
|
15
|
-
/** Клиент критика: судит пакет доказательств, при concern/critical — до 3 read-only проверок. */
|
|
16
|
-
export class CriticClient {
|
|
17
|
-
opts;
|
|
18
|
-
constructor(opts) {
|
|
19
|
-
this.opts = opts;
|
|
20
|
-
}
|
|
21
|
-
isEnabled() {
|
|
22
|
-
return true;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Верифицирует пакет доказательств (Phase 2: опциональный ограниченный тул-контур).
|
|
26
|
-
*
|
|
27
|
-
* Проход 1 судит пакет как есть (поведение v1). При concern/critical с
|
|
28
|
-
* раннером `runCheck` проход 2 даёт критику до 3 read-only проверок,
|
|
29
|
-
* проход 3 выносит финальный вердикт по их выводам. Вся цепочка делит
|
|
30
|
-
* один таймаут-бюджет и откатывается к вердикту прохода 1
|
|
31
|
-
* (или null, если упал сам проход 1) — глубина верификации best-effort,
|
|
32
|
-
* никогда не блокирует.
|
|
33
|
-
*/
|
|
34
|
-
async verify(pack, signal, opts) {
|
|
35
|
-
const controller = new AbortController();
|
|
36
|
-
const timer = setTimeout(() => controller.abort(), this.opts.timeoutMs ?? 15000);
|
|
37
|
-
const onAbort = () => controller.abort();
|
|
38
|
-
signal?.addEventListener("abort", onAbort);
|
|
39
|
-
try {
|
|
40
|
-
const messages = [
|
|
41
|
-
{ role: "system", content: CRITIC_SYSTEM_PROMPT },
|
|
42
|
-
{ role: "user", content: renderPack(pack) },
|
|
43
|
-
];
|
|
44
|
-
const firstRaw = await this.chat(messages, controller.signal);
|
|
45
|
-
const first = parseVerdict(firstRaw);
|
|
46
|
-
if (!first || first.status === "ok" || !opts?.runCheck)
|
|
47
|
-
return first;
|
|
48
|
-
return await this.verifyWithChecks(messages, firstRaw, first, controller.signal, opts.runCheck);
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
finally {
|
|
54
|
-
clearTimeout(timer);
|
|
55
|
-
signal?.removeEventListener("abort", onAbort);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Проходы 2–3: запрашиваем ограниченные read-only проверки (доп. LLM-вызовы
|
|
60
|
-
* только если первый вердикт actionable), выполняем их и заземляем финальный
|
|
61
|
-
* вердикт на выводах. История сохраняется, чтобы "твой вердикт" резолвился в проход 1.
|
|
62
|
-
* Любой сбой — откат к вердикту прохода 1.
|
|
63
|
-
*/
|
|
64
|
-
async verifyWithChecks(messages, firstRaw, first, signal, runCheck) {
|
|
65
|
-
try {
|
|
66
|
-
messages.push({ role: "assistant", content: firstRaw });
|
|
67
|
-
messages.push({ role: "user", content: CHECK_REQUEST_INSTRUCTION });
|
|
68
|
-
const checksRaw = await this.chat(messages, signal);
|
|
69
|
-
const checks = parseChecks(parseVerdict(checksRaw));
|
|
70
|
-
if (checks.length === 0)
|
|
71
|
-
return first;
|
|
72
|
-
const results = await runCriticChecks(checks, runCheck);
|
|
73
|
-
if (results.length === 0)
|
|
74
|
-
return first;
|
|
75
|
-
messages.push({ role: "assistant", content: checksRaw });
|
|
76
|
-
messages.push({
|
|
77
|
-
role: "user",
|
|
78
|
-
content: `CHECK RESULTS (ground truth):\n${renderCheckResults(results)}\n\n${FINAL_VERDICT_INSTRUCTION}`,
|
|
79
|
-
});
|
|
80
|
-
return parseVerdict(await this.chat(messages, signal)) ?? first;
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
return first;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
async chat(messages, signal) {
|
|
87
|
-
let text = "";
|
|
88
|
-
for await (const chunk of this.opts.provider.chat(messages, undefined, signal, {
|
|
89
|
-
maxTokens: this.opts.maxTokens ?? 512,
|
|
90
|
-
reasoningEffort: "none",
|
|
91
|
-
})) {
|
|
92
|
-
if (chunk.type === "text" && chunk.content)
|
|
93
|
-
text += chunk.content;
|
|
94
|
-
}
|
|
95
|
-
return text;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
function renderPack(pack) {
|
|
99
|
-
const cmdLines = pack.commands.map((c) => {
|
|
100
|
-
const base = `${c.command} (exit ${c.exitCode ?? "?"})`;
|
|
101
|
-
return c.output ? `${base}\n output: ${c.output}` : base;
|
|
102
|
-
});
|
|
103
|
-
const files = (pack.fileExcerpts ?? []).map((f) => `--- ${f.path} ---\n${f.excerpt}`);
|
|
104
|
-
return [
|
|
105
|
-
`TASK: ${pack.task}`,
|
|
106
|
-
pack.planSummary ? `PLAN: ${pack.planSummary}` : "",
|
|
107
|
-
`CHANGED FILES: ${pack.changedFiles.join(", ") || "(none)"}`,
|
|
108
|
-
`COMMANDS: ${cmdLines.join("; ") || "(none)"}`,
|
|
109
|
-
"TOOL TRAIL:",
|
|
110
|
-
pack.toolDigest || "(empty)",
|
|
111
|
-
files.length > 0 ? `FILE CONTENTS:\n${files.join("\n")}` : "",
|
|
112
|
-
]
|
|
113
|
-
.filter(Boolean)
|
|
114
|
-
.join("\n");
|
|
115
|
-
}
|
|
116
|
-
const SEVERITIES = new Set(["info", "concern", "critical"]);
|
|
117
|
-
/** Парсит вердикт критика из сырого текста (строгий JSON → jsonrepair → вырезание блока). Null, если не вердикт. */
|
|
118
|
-
export function parseVerdict(text) {
|
|
119
|
-
let parsed = null;
|
|
120
|
-
try {
|
|
121
|
-
parsed = JSON.parse(text);
|
|
122
|
-
}
|
|
123
|
-
catch {
|
|
124
|
-
try {
|
|
125
|
-
parsed = JSON.parse(jsonrepair(text));
|
|
126
|
-
}
|
|
127
|
-
catch {
|
|
128
|
-
const match = text.match(/\{[\s\S]*\}/);
|
|
129
|
-
if (!match)
|
|
130
|
-
return null;
|
|
131
|
-
try {
|
|
132
|
-
parsed = JSON.parse(jsonrepair(match[0]));
|
|
133
|
-
}
|
|
134
|
-
catch {
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
if (!parsed || typeof parsed !== "object")
|
|
140
|
-
return null;
|
|
141
|
-
const obj = parsed;
|
|
142
|
-
const status = obj.status;
|
|
143
|
-
if (status !== "ok" && status !== "concern" && status !== "critical")
|
|
144
|
-
return null;
|
|
145
|
-
const issues = parseIssuesList(obj.issues);
|
|
146
|
-
// Запрошенные проверки верификации (Phase 2): несём сырыми, кап здесь;
|
|
147
|
-
// форма + allowlist enforced в parseChecks, вслепую не доверяем.
|
|
148
|
-
const checks = parseRawChecks(obj.checks);
|
|
149
|
-
return { status, summary: String(obj.summary ?? ""), issues, ...(checks ? { checks } : {}) };
|
|
150
|
-
}
|
|
151
|
-
/** Проблемы вердикта с санитизированными severity; записи без claim+problem дропаются. */
|
|
152
|
-
function parseIssuesList(raw) {
|
|
153
|
-
if (!Array.isArray(raw))
|
|
154
|
-
return [];
|
|
155
|
-
return raw
|
|
156
|
-
.filter((i) => !!i && typeof i === "object")
|
|
157
|
-
.map((i) => ({
|
|
158
|
-
severity: (SEVERITIES.has(String(i.severity)) ? String(i.severity) : "concern"),
|
|
159
|
-
claim: String(i.claim ?? ""),
|
|
160
|
-
problem: String(i.problem ?? ""),
|
|
161
|
-
suggestion: i.suggestion ? String(i.suggestion) : undefined,
|
|
162
|
-
evidence: i.evidence ? String(i.evidence) : undefined,
|
|
163
|
-
}))
|
|
164
|
-
.filter((i) => i.claim || i.problem);
|
|
165
|
-
}
|
|
166
|
-
/** Сырые запрошенные проверки (с капом); форма + allowlist enforced в parseChecks. */
|
|
167
|
-
function parseRawChecks(raw) {
|
|
168
|
-
if (!Array.isArray(raw))
|
|
169
|
-
return undefined;
|
|
170
|
-
const out = raw
|
|
171
|
-
.filter((c) => !!c &&
|
|
172
|
-
typeof c === "object" &&
|
|
173
|
-
typeof c.tool === "string")
|
|
174
|
-
.map((c) => ({ tool: c.tool, args: c.args }));
|
|
175
|
-
return out.length > 0 ? out : undefined;
|
|
176
|
-
}
|