@armadra/agent 0.0.0-stage → 0.2.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 +22 -0
- package/LICENSE +21 -0
- package/README.md +426 -2
- package/dist/agent/agent.d.ts +56 -0
- package/dist/agent/agent.js +129 -0
- package/dist/agent/loop.d.ts +51 -0
- package/dist/agent/loop.js +158 -0
- package/dist/agent/queue.d.ts +25 -0
- package/dist/agent/queue.js +55 -0
- package/dist/agent/retry.d.ts +22 -0
- package/dist/agent/retry.js +92 -0
- package/dist/agent/schema.d.ts +27 -0
- package/dist/agent/schema.js +186 -0
- package/dist/agent/session-cache.d.ts +100 -0
- package/dist/agent/session-cache.js +511 -0
- package/dist/agent/session-compaction.d.ts +49 -0
- package/dist/agent/session-compaction.js +251 -0
- package/dist/agent/session-core.d.ts +103 -0
- package/dist/agent/session-core.js +7 -0
- package/dist/agent/session-run.d.ts +55 -0
- package/dist/agent/session-run.js +246 -0
- package/dist/agent/session-state.d.ts +39 -0
- package/dist/agent/session-state.js +118 -0
- package/dist/agent/session-subagent.d.ts +54 -0
- package/dist/agent/session-subagent.js +157 -0
- package/dist/agent/session-sync.d.ts +20 -0
- package/dist/agent/session-sync.js +104 -0
- package/dist/agent/session-tools.d.ts +24 -0
- package/dist/agent/session-tools.js +277 -0
- package/dist/agent/session.d.ts +117 -0
- package/dist/agent/session.js +484 -0
- package/dist/agent/system-prompt.d.ts +49 -0
- package/dist/agent/system-prompt.js +121 -0
- package/dist/agent/tool-runner.d.ts +64 -0
- package/dist/agent/tool-runner.js +309 -0
- package/dist/agent/transform.d.ts +26 -0
- package/dist/agent/transform.js +171 -0
- package/dist/agent/types.d.ts +378 -0
- package/dist/agent/types.js +21 -0
- package/dist/ai/apis/anthropic-messages.d.ts +26 -0
- package/dist/ai/apis/anthropic-messages.js +214 -0
- package/dist/ai/apis/anthropic-request.d.ts +42 -0
- package/dist/ai/apis/anthropic-request.js +282 -0
- package/dist/ai/apis/api.d.ts +28 -0
- package/dist/ai/apis/api.js +102 -0
- package/dist/ai/apis/cache-params.d.ts +48 -0
- package/dist/ai/apis/cache-params.js +163 -0
- package/dist/ai/apis/google-generative-ai.d.ts +32 -0
- package/dist/ai/apis/google-generative-ai.js +249 -0
- package/dist/ai/apis/google-request.d.ts +40 -0
- package/dist/ai/apis/google-request.js +255 -0
- package/dist/ai/apis/openai-compat.d.ts +35 -0
- package/dist/ai/apis/openai-compat.js +142 -0
- package/dist/ai/apis/openai-completions.d.ts +28 -0
- package/dist/ai/apis/openai-completions.js +246 -0
- package/dist/ai/apis/openai-request.d.ts +35 -0
- package/dist/ai/apis/openai-request.js +303 -0
- package/dist/ai/apis/openai-responses-request.d.ts +52 -0
- package/dist/ai/apis/openai-responses-request.js +266 -0
- package/dist/ai/apis/openai-responses.d.ts +28 -0
- package/dist/ai/apis/openai-responses.js +303 -0
- package/dist/ai/apis/shared.d.ts +56 -0
- package/dist/ai/apis/shared.js +179 -0
- package/dist/ai/cache/economics.d.ts +24 -0
- package/dist/ai/cache/economics.js +69 -0
- package/dist/ai/cache/fingerprint.d.ts +17 -0
- package/dist/ai/cache/fingerprint.js +39 -0
- package/dist/ai/cache/miss.d.ts +49 -0
- package/dist/ai/cache/miss.js +96 -0
- package/dist/ai/cache/reporting.d.ts +39 -0
- package/dist/ai/cache/reporting.js +102 -0
- package/dist/ai/cache/types.d.ts +94 -0
- package/dist/ai/cache/types.js +19 -0
- package/dist/ai/cache/warmer.d.ts +94 -0
- package/dist/ai/cache/warmer.js +224 -0
- package/dist/ai/context.d.ts +35 -0
- package/dist/ai/context.js +114 -0
- package/dist/ai/cost.d.ts +21 -0
- package/dist/ai/cost.js +60 -0
- package/dist/ai/event-stream.d.ts +33 -0
- package/dist/ai/event-stream.js +101 -0
- package/dist/ai/fake/fake-provider.d.ts +68 -0
- package/dist/ai/fake/fake-provider.js +278 -0
- package/dist/ai/fake/fake-script.d.ts +69 -0
- package/dist/ai/fake/fake-script.js +142 -0
- package/dist/ai/http.d.ts +54 -0
- package/dist/ai/http.js +212 -0
- package/dist/ai/json-partial.d.ts +17 -0
- package/dist/ai/json-partial.js +243 -0
- package/dist/ai/overflow.d.ts +22 -0
- package/dist/ai/overflow.js +61 -0
- package/dist/ai/providers/auth.d.ts +71 -0
- package/dist/ai/providers/auth.js +202 -0
- package/dist/ai/providers/builtin.d.ts +23 -0
- package/dist/ai/providers/builtin.js +148 -0
- package/dist/ai/providers/catalog-data.d.ts +5 -0
- package/dist/ai/providers/catalog-data.js +19 -0
- package/dist/ai/providers/catalog.d.ts +28 -0
- package/dist/ai/providers/catalog.js +166 -0
- package/dist/ai/providers/registry.d.ts +83 -0
- package/dist/ai/providers/registry.js +305 -0
- package/dist/ai/sse.d.ts +32 -0
- package/dist/ai/sse.js +140 -0
- package/dist/ai/thinking.d.ts +42 -0
- package/dist/ai/thinking.js +101 -0
- package/dist/ai/types.d.ts +428 -0
- package/dist/ai/types.js +19 -0
- package/dist/bundle/ama-sandbox.cjs +324 -0
- package/dist/bundle/ama.cjs +25770 -0
- package/dist/bundle.d.ts +9 -0
- package/dist/bundle.js +15 -0
- package/dist/cli/args.d.ts +82 -0
- package/dist/cli/args.js +381 -0
- package/dist/cli/bootstrap.d.ts +18 -0
- package/dist/cli/bootstrap.js +398 -0
- package/dist/cli/compose-providers.d.ts +37 -0
- package/dist/cli/compose-providers.js +104 -0
- package/dist/cli/compose-session.d.ts +69 -0
- package/dist/cli/compose-session.js +370 -0
- package/dist/cli/compose-store.d.ts +24 -0
- package/dist/cli/compose-store.js +125 -0
- package/dist/cli/compose.d.ts +106 -0
- package/dist/cli/compose.js +206 -0
- package/dist/cli/default-model.d.ts +16 -0
- package/dist/cli/default-model.js +24 -0
- package/dist/cli/deps.d.ts +205 -0
- package/dist/cli/deps.js +12 -0
- package/dist/cli/exit-codes.d.ts +29 -0
- package/dist/cli/exit-codes.js +40 -0
- package/dist/cli/main.d.ts +26 -0
- package/dist/cli/main.js +165 -0
- package/dist/cli/runtime.d.ts +90 -0
- package/dist/cli/runtime.js +8 -0
- package/dist/cli/startup-screen.d.ts +15 -0
- package/dist/cli/startup-screen.js +56 -0
- package/dist/cli/startup-steps.d.ts +35 -0
- package/dist/cli/startup-steps.js +197 -0
- package/dist/cli/subcommands/auth.d.ts +12 -0
- package/dist/cli/subcommands/auth.js +91 -0
- package/dist/cli/subcommands/config.d.ts +44 -0
- package/dist/cli/subcommands/config.js +201 -0
- package/dist/cli/subcommands/context.d.ts +21 -0
- package/dist/cli/subcommands/context.js +41 -0
- package/dist/cli/subcommands/doctor.d.ts +11 -0
- package/dist/cli/subcommands/doctor.js +246 -0
- package/dist/cli/subcommands/models-cache-probe.d.ts +34 -0
- package/dist/cli/subcommands/models-cache-probe.js +190 -0
- package/dist/cli/subcommands/models-discover.d.ts +40 -0
- package/dist/cli/subcommands/models-discover.js +204 -0
- package/dist/cli/subcommands/models.d.ts +40 -0
- package/dist/cli/subcommands/models.js +144 -0
- package/dist/cli/subcommands/sessions.d.ts +11 -0
- package/dist/cli/subcommands/sessions.js +100 -0
- package/dist/codemode/capability.d.ts +37 -0
- package/dist/codemode/capability.js +55 -0
- package/dist/codemode/declarations.d.ts +44 -0
- package/dist/codemode/declarations.js +111 -0
- package/dist/codemode/host-side.d.ts +59 -0
- package/dist/codemode/host-side.js +253 -0
- package/dist/codemode/modes.d.ts +23 -0
- package/dist/codemode/modes.js +40 -0
- package/dist/codemode/protocol.d.ts +91 -0
- package/dist/codemode/protocol.js +114 -0
- package/dist/codemode/sandbox-entry.d.ts +25 -0
- package/dist/codemode/sandbox-entry.js +323 -0
- package/dist/codemode/store.d.ts +26 -0
- package/dist/codemode/store.js +53 -0
- package/dist/codemode/tool.d.ts +105 -0
- package/dist/codemode/tool.js +283 -0
- package/dist/compaction/branch-summary.d.ts +30 -0
- package/dist/compaction/branch-summary.js +79 -0
- package/dist/compaction/breaker.d.ts +32 -0
- package/dist/compaction/breaker.js +65 -0
- package/dist/compaction/cut-point.d.ts +23 -0
- package/dist/compaction/cut-point.js +70 -0
- package/dist/compaction/estimate.d.ts +30 -0
- package/dist/compaction/estimate.js +114 -0
- package/dist/compaction/prune-tier.d.ts +31 -0
- package/dist/compaction/prune-tier.js +83 -0
- package/dist/compaction/serialize.d.ts +20 -0
- package/dist/compaction/serialize.js +115 -0
- package/dist/compaction/summarize-tier.d.ts +111 -0
- package/dist/compaction/summarize-tier.js +305 -0
- package/dist/config/auth-file.d.ts +39 -0
- package/dist/config/auth-file.js +92 -0
- package/dist/config/context-files.d.ts +30 -0
- package/dist/config/context-files.js +77 -0
- package/dist/config/load.d.ts +45 -0
- package/dist/config/load.js +97 -0
- package/dist/config/merge.d.ts +73 -0
- package/dist/config/merge.js +248 -0
- package/dist/config/paths.d.ts +38 -0
- package/dist/config/paths.js +108 -0
- package/dist/config/profile.d.ts +27 -0
- package/dist/config/profile.js +65 -0
- package/dist/config/schema.d.ts +34 -0
- package/dist/config/schema.js +413 -0
- package/dist/config/trust.d.ts +42 -0
- package/dist/config/trust.js +122 -0
- package/dist/config/types.d.ts +172 -0
- package/dist/config/types.js +27 -0
- package/dist/config/write.d.ts +10 -0
- package/dist/config/write.js +25 -0
- package/dist/errors.d.ts +28 -0
- package/dist/errors.js +30 -0
- package/dist/hooks/config.d.ts +49 -0
- package/dist/hooks/config.js +102 -0
- package/dist/hooks/dispatcher.d.ts +41 -0
- package/dist/hooks/dispatcher.js +104 -0
- package/dist/hooks/matcher.d.ts +22 -0
- package/dist/hooks/matcher.js +108 -0
- package/dist/hooks/protocol.d.ts +33 -0
- package/dist/hooks/protocol.js +240 -0
- package/dist/hooks/runner.d.ts +30 -0
- package/dist/hooks/runner.js +143 -0
- package/dist/hooks/types.d.ts +147 -0
- package/dist/hooks/types.js +20 -0
- package/dist/host/api-impl.d.ts +75 -0
- package/dist/host/api-impl.js +173 -0
- package/dist/host/loader.d.ts +31 -0
- package/dist/host/loader.js +147 -0
- package/dist/host/types.d.ts +169 -0
- package/dist/host/types.js +14 -0
- package/dist/host.d.ts +5 -0
- package/dist/host.js +4 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +28 -0
- package/dist/modes/commands-core.d.ts +44 -0
- package/dist/modes/commands-core.js +171 -0
- package/dist/modes/interactive/approval-dialog.d.ts +48 -0
- package/dist/modes/interactive/approval-dialog.js +202 -0
- package/dist/modes/interactive/commands.d.ts +41 -0
- package/dist/modes/interactive/commands.js +202 -0
- package/dist/modes/interactive/completion.d.ts +53 -0
- package/dist/modes/interactive/completion.js +157 -0
- package/dist/modes/interactive/interactive-mode.d.ts +46 -0
- package/dist/modes/interactive/interactive-mode.js +487 -0
- package/dist/modes/interactive/key-dispatch.d.ts +29 -0
- package/dist/modes/interactive/key-dispatch.js +107 -0
- package/dist/modes/interactive/line/line-editor.d.ts +50 -0
- package/dist/modes/interactive/line/line-editor.js +232 -0
- package/dist/modes/interactive/line/line-mode.d.ts +20 -0
- package/dist/modes/interactive/line/line-mode.js +216 -0
- package/dist/modes/interactive/line/line-render.d.ts +35 -0
- package/dist/modes/interactive/line/line-render.js +171 -0
- package/dist/modes/interactive/line/paste-state.d.ts +26 -0
- package/dist/modes/interactive/line/paste-state.js +72 -0
- package/dist/modes/interactive/message-view.d.ts +77 -0
- package/dist/modes/interactive/message-view.js +269 -0
- package/dist/modes/interactive/pickers.d.ts +42 -0
- package/dist/modes/interactive/pickers.js +115 -0
- package/dist/modes/interactive/startup-ui.d.ts +28 -0
- package/dist/modes/interactive/startup-ui.js +238 -0
- package/dist/modes/interactive/status-bar.d.ts +48 -0
- package/dist/modes/interactive/status-bar.js +139 -0
- package/dist/modes/interactive/tool-view.d.ts +95 -0
- package/dist/modes/interactive/tool-view.js +344 -0
- package/dist/modes/print/json-event.d.ts +15 -0
- package/dist/modes/print/json-event.js +39 -0
- package/dist/modes/print/print-mode.d.ts +15 -0
- package/dist/modes/print/print-mode.js +96 -0
- package/dist/modes/rpc/commands.d.ts +40 -0
- package/dist/modes/rpc/commands.js +258 -0
- package/dist/modes/rpc/jsonl.d.ts +16 -0
- package/dist/modes/rpc/jsonl.js +55 -0
- package/dist/modes/rpc/rpc-mode.d.ts +22 -0
- package/dist/modes/rpc/rpc-mode.js +153 -0
- package/dist/modes/session-report.d.ts +55 -0
- package/dist/modes/session-report.js +278 -0
- package/dist/modes/shared.d.ts +13 -0
- package/dist/modes/shared.js +52 -0
- package/dist/modes/startup-ui-text.d.ts +16 -0
- package/dist/modes/startup-ui-text.js +103 -0
- package/dist/permissions/broker.d.ts +47 -0
- package/dist/permissions/broker.js +107 -0
- package/dist/permissions/dangerous.d.ts +47 -0
- package/dist/permissions/dangerous.js +370 -0
- package/dist/permissions/pipeline.d.ts +51 -0
- package/dist/permissions/pipeline.js +181 -0
- package/dist/permissions/preview.d.ts +43 -0
- package/dist/permissions/preview.js +463 -0
- package/dist/permissions/rules.d.ts +58 -0
- package/dist/permissions/rules.js +249 -0
- package/dist/permissions/types.d.ts +100 -0
- package/dist/permissions/types.js +18 -0
- package/dist/rpc.d.ts +171 -0
- package/dist/rpc.js +13 -0
- package/dist/sdk.d.ts +98 -0
- package/dist/sdk.js +195 -0
- package/dist/session/manager.d.ts +70 -0
- package/dist/session/manager.js +278 -0
- package/dist/session/migrate.d.ts +19 -0
- package/dist/session/migrate.js +53 -0
- package/dist/session/projection.d.ts +50 -0
- package/dist/session/projection.js +180 -0
- package/dist/session/store.d.ts +47 -0
- package/dist/session/store.js +210 -0
- package/dist/session/tree.d.ts +21 -0
- package/dist/session/tree.js +88 -0
- package/dist/session/types.d.ts +199 -0
- package/dist/session/types.js +18 -0
- package/dist/skills/discover.d.ts +60 -0
- package/dist/skills/discover.js +160 -0
- package/dist/skills/expand.d.ts +35 -0
- package/dist/skills/expand.js +46 -0
- package/dist/skills/frontmatter.d.ts +27 -0
- package/dist/skills/frontmatter.js +157 -0
- package/dist/skills/index-prompt.d.ts +13 -0
- package/dist/skills/index-prompt.js +42 -0
- package/dist/skills/templates.d.ts +52 -0
- package/dist/skills/templates.js +177 -0
- package/dist/tools/bash.d.ts +49 -0
- package/dist/tools/bash.js +222 -0
- package/dist/tools/edit-fuzzy.d.ts +36 -0
- package/dist/tools/edit-fuzzy.js +129 -0
- package/dist/tools/edit.d.ts +38 -0
- package/dist/tools/edit.js +241 -0
- package/dist/tools/file-mutex.d.ts +8 -0
- package/dist/tools/file-mutex.js +29 -0
- package/dist/tools/glob.d.ts +44 -0
- package/dist/tools/glob.js +217 -0
- package/dist/tools/grep.d.ts +39 -0
- package/dist/tools/grep.js +179 -0
- package/dist/tools/ignore.d.ts +40 -0
- package/dist/tools/ignore.js +174 -0
- package/dist/tools/ls.d.ts +21 -0
- package/dist/tools/ls.js +96 -0
- package/dist/tools/output-accumulator.d.ts +48 -0
- package/dist/tools/output-accumulator.js +106 -0
- package/dist/tools/paths.d.ts +20 -0
- package/dist/tools/paths.js +58 -0
- package/dist/tools/presets.d.ts +71 -0
- package/dist/tools/presets.js +128 -0
- package/dist/tools/process-tree.d.ts +35 -0
- package/dist/tools/process-tree.js +125 -0
- package/dist/tools/read.d.ts +28 -0
- package/dist/tools/read.js +181 -0
- package/dist/tools/registry.d.ts +43 -0
- package/dist/tools/registry.js +106 -0
- package/dist/tools/shell.d.ts +38 -0
- package/dist/tools/shell.js +91 -0
- package/dist/tools/task.d.ts +29 -0
- package/dist/tools/task.js +107 -0
- package/dist/tools/todo.d.ts +28 -0
- package/dist/tools/todo.js +107 -0
- package/dist/tools/truncate.d.ts +44 -0
- package/dist/tools/truncate.js +175 -0
- package/dist/tools/types.d.ts +135 -0
- package/dist/tools/types.js +19 -0
- package/dist/tools/write.d.ts +20 -0
- package/dist/tools/write.js +84 -0
- package/dist/tui/ansi.d.ts +29 -0
- package/dist/tui/ansi.js +420 -0
- package/dist/tui/component.d.ts +38 -0
- package/dist/tui/component.js +13 -0
- package/dist/tui/components/box.d.ts +26 -0
- package/dist/tui/components/box.js +65 -0
- package/dist/tui/components/container.d.ts +14 -0
- package/dist/tui/components/container.js +39 -0
- package/dist/tui/components/editor-buffer.d.ts +67 -0
- package/dist/tui/components/editor-buffer.js +300 -0
- package/dist/tui/components/editor-paste.d.ts +29 -0
- package/dist/tui/components/editor-paste.js +64 -0
- package/dist/tui/components/editor.d.ts +114 -0
- package/dist/tui/components/editor.js +530 -0
- package/dist/tui/components/key-value.d.ts +29 -0
- package/dist/tui/components/key-value.js +48 -0
- package/dist/tui/components/loader.d.ts +35 -0
- package/dist/tui/components/loader.js +71 -0
- package/dist/tui/components/markdown.d.ts +90 -0
- package/dist/tui/components/markdown.js +462 -0
- package/dist/tui/components/meter.d.ts +29 -0
- package/dist/tui/components/meter.js +47 -0
- package/dist/tui/components/overlay.d.ts +24 -0
- package/dist/tui/components/overlay.js +52 -0
- package/dist/tui/components/select-list.d.ts +57 -0
- package/dist/tui/components/select-list.js +179 -0
- package/dist/tui/components/spacer.d.ts +11 -0
- package/dist/tui/components/spacer.js +16 -0
- package/dist/tui/components/text.d.ts +30 -0
- package/dist/tui/components/text.js +65 -0
- package/dist/tui/keybindings.d.ts +66 -0
- package/dist/tui/keybindings.js +120 -0
- package/dist/tui/keys.d.ts +38 -0
- package/dist/tui/keys.js +275 -0
- package/dist/tui/stdin-buffer.d.ts +41 -0
- package/dist/tui/stdin-buffer.js +206 -0
- package/dist/tui/terminal.d.ts +79 -0
- package/dist/tui/terminal.js +153 -0
- package/dist/tui/theme.d.ts +31 -0
- package/dist/tui/theme.js +199 -0
- package/dist/tui/tui.d.ts +103 -0
- package/dist/tui/tui.js +363 -0
- package/dist/tui/vt-screen.d.ts +46 -0
- package/dist/tui/vt-screen.js +251 -0
- package/dist/tui.d.ts +30 -0
- package/dist/tui.js +31 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.js +24 -0
- package/docs/codemode.md +102 -0
- package/docs/hooks.md +196 -0
- package/docs/host-api.md +161 -0
- package/docs/providers.md +316 -0
- package/docs/rpc.md +253 -0
- package/docs/session-format.md +119 -0
- package/docs/tui.md +168 -0
- package/package.json +101 -4
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话层缓存控制器(第三波 §1.2、§1.5–§1.7、§1.9、§1.10)。[W3-C1b]
|
|
3
|
+
*
|
|
4
|
+
* `wrapStream()` 包住会话的流函数:每次真实请求记一条 `RequestRecord`(内存)、算前缀指纹、
|
|
5
|
+
* 更新三态、检测未命中(发 `cache_miss`)、跨 70% / 90% 发 `context_pressure`,turn 请求完成后
|
|
6
|
+
* 交给保温状态机。摘要请求自成一条链,不与主链比对;压缩 / 分支摘要 / 档一裁剪 / `/tree`
|
|
7
|
+
* 之后的首个请求是重置点。子会话(depth > 0)有自己的控制器,`warmSubagents` 为 false 时不保温。
|
|
8
|
+
* fork 出的会话沿用根会话 id 作 `prompt_cache_key`(只是路由提示);task 子会话不沿用。
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import { evaluateWarm } from "../ai/cache/economics.js";
|
|
12
|
+
import { fingerprintContext } from "../ai/cache/fingerprint.js";
|
|
13
|
+
import { DEFAULT_MIN_CACHE_TOKENS, IMPLICIT_CACHE_TTL_MS, detectMiss } from "../ai/cache/miss.js";
|
|
14
|
+
import { endpointKey, sharedCacheReporting, } from "../ai/cache/reporting.js";
|
|
15
|
+
import { CacheWarmer, replayBlocker } from "../ai/cache/warmer.js";
|
|
16
|
+
import { SUMMARY_MAX_TOKENS } from "../compaction/summarize-tier.js";
|
|
17
|
+
import { convertToLlm } from "./transform.js";
|
|
18
|
+
export const DEFAULT_CACHE_SETTINGS = Object.freeze({
|
|
19
|
+
warming: "streaming",
|
|
20
|
+
retention: "short",
|
|
21
|
+
minSavingsUsd: 0.05,
|
|
22
|
+
missNotices: true,
|
|
23
|
+
warmSubagents: false,
|
|
24
|
+
});
|
|
25
|
+
export const PRESSURE_THRESHOLDS = [70, 90];
|
|
26
|
+
const GROWTH_SAMPLES = 5;
|
|
27
|
+
const TASK_CUSTOM_TYPE = "ama.task";
|
|
28
|
+
export function resolveCacheSettings(partial = {}) {
|
|
29
|
+
const settings = { ...DEFAULT_CACHE_SETTINGS };
|
|
30
|
+
for (const [key, value] of Object.entries(partial)) {
|
|
31
|
+
if (value !== undefined)
|
|
32
|
+
settings[key] = value;
|
|
33
|
+
}
|
|
34
|
+
return settings;
|
|
35
|
+
}
|
|
36
|
+
/** 目录 TTL(毫秒):long 保留且有 long 档时用 long;无承诺 → undefined。 */
|
|
37
|
+
export function cacheTtlMs(model, retention) {
|
|
38
|
+
const cache = model.promptCache;
|
|
39
|
+
const seconds = retention === "long" && cache?.long !== undefined ? cache.long : cache?.short;
|
|
40
|
+
return seconds === undefined ? undefined : seconds * 1000;
|
|
41
|
+
}
|
|
42
|
+
function readHead(file) {
|
|
43
|
+
try {
|
|
44
|
+
const [header, first] = readFileSync(file, "utf8").split("\n", 2);
|
|
45
|
+
const parsed = JSON.parse(header ?? "{}");
|
|
46
|
+
const entry = first ? JSON.parse(first) : undefined;
|
|
47
|
+
return { ...parsed, task: entry?.customType === TASK_CUSTOM_TYPE };
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { task: false };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** fork 链上的根会话 id(task 子会话与非 fork 会话用自己的 id)。 */
|
|
54
|
+
export function cacheKeyOf(manager) {
|
|
55
|
+
const header = manager.header();
|
|
56
|
+
const isTask = manager
|
|
57
|
+
.entries()
|
|
58
|
+
.some((entry) => entry.type === "custom" && entry.customType === TASK_CUSTOM_TYPE);
|
|
59
|
+
if (header.parentSession === undefined || isTask)
|
|
60
|
+
return manager.id;
|
|
61
|
+
let id = manager.id;
|
|
62
|
+
let file = header.parentSession;
|
|
63
|
+
for (let depth = 0; depth < 8 && file !== undefined; depth++) {
|
|
64
|
+
const head = readHead(file);
|
|
65
|
+
if (head.id === undefined || head.task)
|
|
66
|
+
break;
|
|
67
|
+
id = head.id;
|
|
68
|
+
file = head.parentSession;
|
|
69
|
+
}
|
|
70
|
+
return id;
|
|
71
|
+
}
|
|
72
|
+
export class SessionCacheController {
|
|
73
|
+
core;
|
|
74
|
+
settings;
|
|
75
|
+
now;
|
|
76
|
+
tracker;
|
|
77
|
+
decider;
|
|
78
|
+
warmer;
|
|
79
|
+
models = new WeakMap();
|
|
80
|
+
snapshots = new WeakMap();
|
|
81
|
+
replaced = new WeakSet();
|
|
82
|
+
inner;
|
|
83
|
+
warmingOverride;
|
|
84
|
+
cacheKey;
|
|
85
|
+
prev;
|
|
86
|
+
lastTurnRecord;
|
|
87
|
+
resetPending = false;
|
|
88
|
+
disposed = false;
|
|
89
|
+
activeTasks = 0;
|
|
90
|
+
taskSince = 0;
|
|
91
|
+
taskMs = 0;
|
|
92
|
+
sums = new Map();
|
|
93
|
+
missCount = 0;
|
|
94
|
+
byReason = {};
|
|
95
|
+
reBilledTokens = 0;
|
|
96
|
+
reBilledUsd = 0;
|
|
97
|
+
growth = [];
|
|
98
|
+
lastPercent = 0;
|
|
99
|
+
subagents = { count: 0, read: 0, prompt: 0, reBilledTokens: 0 };
|
|
100
|
+
constructor(core, settings, deps = {}) {
|
|
101
|
+
this.core = core;
|
|
102
|
+
this.settings = settings;
|
|
103
|
+
this.now = deps.now ?? (() => Date.now());
|
|
104
|
+
this.tracker = deps.tracker ?? sharedCacheReporting;
|
|
105
|
+
this.decider = deps.decider ?? (() => undefined);
|
|
106
|
+
const warmerDeps = {
|
|
107
|
+
mode: () => this.mode(),
|
|
108
|
+
now: this.now,
|
|
109
|
+
send: (record, signal) => this.replay(record, signal),
|
|
110
|
+
isCurrent: (record) => this.isCurrent(record),
|
|
111
|
+
evaluate: (record, phase) => evaluateWarm(this.modelOf(record), record.promptTokens, phase, this.settings.minSavingsUsd),
|
|
112
|
+
decide: (decision) => this.decider()?.(decision) ?? decision.action,
|
|
113
|
+
onWarmed: (record, message, sentAt) => this.onWarmed(record, message, sentAt),
|
|
114
|
+
onScheduled: (nextWarmAt) => this.core.emit({ type: "cache_warm", phase: "scheduled", nextWarmAt }),
|
|
115
|
+
onStopped: (reason) => this.core.emit({ type: "cache_warm", phase: "stopped", reason }),
|
|
116
|
+
};
|
|
117
|
+
if (deps.timers !== undefined)
|
|
118
|
+
warmerDeps.timers = deps.timers;
|
|
119
|
+
this.warmer = new CacheWarmer(warmerDeps);
|
|
120
|
+
}
|
|
121
|
+
/** 生效的保温模式:子会话在 warmSubagents 为 false 时 off;`/cache warm` 会话内覆盖。 */
|
|
122
|
+
mode() {
|
|
123
|
+
if (this.core.depth > 0 && !this.settings.warmSubagents)
|
|
124
|
+
return "off";
|
|
125
|
+
return this.warmingOverride ?? this.settings.warming;
|
|
126
|
+
}
|
|
127
|
+
get cacheSettings() {
|
|
128
|
+
return this.settings;
|
|
129
|
+
}
|
|
130
|
+
setWarming(mode) {
|
|
131
|
+
this.warmingOverride = mode;
|
|
132
|
+
if (mode === "off")
|
|
133
|
+
this.warmer.cancel();
|
|
134
|
+
}
|
|
135
|
+
/** 最后一条 turn 请求(摘要续写的前缀依据)。 */
|
|
136
|
+
get lastTurn() {
|
|
137
|
+
return this.lastTurnRecord;
|
|
138
|
+
}
|
|
139
|
+
wrapStream(inner) {
|
|
140
|
+
this.inner = inner;
|
|
141
|
+
return (model, context, options) => {
|
|
142
|
+
const purpose = options.purpose ?? "turn";
|
|
143
|
+
if (this.disposed || purpose === "warm" || purpose === "probe") {
|
|
144
|
+
return inner(model, context, options);
|
|
145
|
+
}
|
|
146
|
+
const sent = { ...options };
|
|
147
|
+
let snapshot;
|
|
148
|
+
let subtaskMs = 0;
|
|
149
|
+
const at = this.now();
|
|
150
|
+
if (purpose === "turn") {
|
|
151
|
+
sent.cacheRetention ??= this.settings.retention;
|
|
152
|
+
if (sent.sessionId !== undefined && sent.sessionId === this.core.manager.id) {
|
|
153
|
+
this.cacheKey ??= cacheKeyOf(this.core.manager);
|
|
154
|
+
sent.sessionId = this.cacheKey;
|
|
155
|
+
}
|
|
156
|
+
this.warmer.pause();
|
|
157
|
+
snapshot = {
|
|
158
|
+
messages: this.core.agent.messages.slice(),
|
|
159
|
+
tools: this.toolsKey(),
|
|
160
|
+
thinking: options.thinkingLevel,
|
|
161
|
+
};
|
|
162
|
+
subtaskMs = this.takeTaskMs(at);
|
|
163
|
+
}
|
|
164
|
+
let replaced = false;
|
|
165
|
+
const onPayload = options.onPayload;
|
|
166
|
+
if (onPayload !== undefined) {
|
|
167
|
+
sent.onPayload = (payload) => {
|
|
168
|
+
const result = onPayload(payload);
|
|
169
|
+
if (result !== undefined)
|
|
170
|
+
replaced = true;
|
|
171
|
+
return result;
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const stream = inner(model, context, sent);
|
|
175
|
+
void stream.result().then((message) => {
|
|
176
|
+
if (this.disposed || message.stopReason === "error" || message.stopReason === "aborted")
|
|
177
|
+
return;
|
|
178
|
+
const { signal: _signal, ...rest } = sent;
|
|
179
|
+
const stored = { ...rest };
|
|
180
|
+
if (onPayload !== undefined)
|
|
181
|
+
stored.onPayload = onPayload;
|
|
182
|
+
const usage = message.usage;
|
|
183
|
+
const record = {
|
|
184
|
+
at,
|
|
185
|
+
purpose,
|
|
186
|
+
model: { provider: model.provider, id: model.id },
|
|
187
|
+
api: model.api,
|
|
188
|
+
baseUrl: model.baseUrl ?? "",
|
|
189
|
+
fingerprint: fingerprintContext(context, model),
|
|
190
|
+
promptTokens: usage.input + usage.cacheRead + usage.cacheWrite,
|
|
191
|
+
usage,
|
|
192
|
+
contextRef: context,
|
|
193
|
+
options: stored,
|
|
194
|
+
};
|
|
195
|
+
this.models.set(record, model);
|
|
196
|
+
if (snapshot !== undefined)
|
|
197
|
+
this.snapshots.set(record, snapshot);
|
|
198
|
+
if (replaced)
|
|
199
|
+
this.replaced.add(record);
|
|
200
|
+
this.observe(record, model, subtaskMs);
|
|
201
|
+
}, () => undefined);
|
|
202
|
+
return stream;
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
/** 会话事件(AgentSessionImpl.emit 转交)。 */
|
|
206
|
+
onEvent(event) {
|
|
207
|
+
switch (event.type) {
|
|
208
|
+
case "agent_settled":
|
|
209
|
+
this.onAgentSettled();
|
|
210
|
+
return;
|
|
211
|
+
case "model_changed":
|
|
212
|
+
case "thinking_level_changed":
|
|
213
|
+
case "compaction_start":
|
|
214
|
+
this.warmer.cancel();
|
|
215
|
+
return;
|
|
216
|
+
case "entry_appended": {
|
|
217
|
+
const { entry } = event;
|
|
218
|
+
if (entry.type === "compaction" ||
|
|
219
|
+
entry.type === "branch_summary" ||
|
|
220
|
+
(entry.type === "context_edit" && entry.reason === "prune")) {
|
|
221
|
+
this.onContextChanged();
|
|
222
|
+
}
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
case "tool_execution_start":
|
|
226
|
+
if (event.toolName === "task" && this.activeTasks++ === 0)
|
|
227
|
+
this.taskSince = this.now();
|
|
228
|
+
return;
|
|
229
|
+
case "tool_execution_end":
|
|
230
|
+
if (event.toolName === "task" && this.activeTasks > 0 && --this.activeTasks === 0)
|
|
231
|
+
this.taskMs += this.now() - this.taskSince;
|
|
232
|
+
return;
|
|
233
|
+
default:
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
onAgentSettled() {
|
|
238
|
+
this.warmer.onAgentSettled();
|
|
239
|
+
}
|
|
240
|
+
/** 压缩 / context_edit / setModel / navigate 之后:下一条请求是重置点,保温作废。 */
|
|
241
|
+
onContextChanged() {
|
|
242
|
+
this.resetPending = true;
|
|
243
|
+
this.warmer.cancel();
|
|
244
|
+
}
|
|
245
|
+
/** task 子会话结束时由父会话汇总(各自独立统计)。 */
|
|
246
|
+
addSubagent(tokens, reBilledTokens) {
|
|
247
|
+
this.subagents.count++;
|
|
248
|
+
this.subagents.read += tokens.cacheRead;
|
|
249
|
+
this.subagents.prompt += tokens.prompt;
|
|
250
|
+
this.subagents.reBilledTokens += reBilledTokens;
|
|
251
|
+
}
|
|
252
|
+
stats(context = {}) {
|
|
253
|
+
const model = this.core.model();
|
|
254
|
+
const setting = model.compat?.cacheReporting;
|
|
255
|
+
const endpoint = endpointKey({ model, baseUrl: model.baseUrl ?? "" });
|
|
256
|
+
const reporting = this.tracker.get(endpoint, setting);
|
|
257
|
+
const stats = {
|
|
258
|
+
reporting,
|
|
259
|
+
reBilledTokens: this.reBilledTokens,
|
|
260
|
+
misses: { count: this.missCount, byReason: { ...this.byReason } },
|
|
261
|
+
warming: this.warmer.status,
|
|
262
|
+
};
|
|
263
|
+
const granularity = this.tracker.granularity(endpoint);
|
|
264
|
+
if (granularity !== undefined)
|
|
265
|
+
stats.granularity = granularity;
|
|
266
|
+
const last = this.lastTurnRecord;
|
|
267
|
+
if (reporting === "reported" && last !== undefined && last.promptTokens > 0)
|
|
268
|
+
stats.lastHitRate = last.usage.cacheRead / last.promptTokens;
|
|
269
|
+
let read = 0;
|
|
270
|
+
let prompt = 0;
|
|
271
|
+
for (const [key, sum] of this.sums) {
|
|
272
|
+
if (this.tracker.get(key) !== "reported")
|
|
273
|
+
continue;
|
|
274
|
+
read += sum.read;
|
|
275
|
+
prompt += sum.prompt;
|
|
276
|
+
}
|
|
277
|
+
if (prompt > 0)
|
|
278
|
+
stats.hitRate = read / prompt;
|
|
279
|
+
if (this.reBilledUsd !== undefined)
|
|
280
|
+
stats.reBilledUsd = this.reBilledUsd;
|
|
281
|
+
if (context.tokens !== undefined && context.window !== undefined) {
|
|
282
|
+
const remaining = Math.max(0, context.window - context.tokens);
|
|
283
|
+
stats.contextRemainingTokens = remaining;
|
|
284
|
+
const turns = this.turnsLeft(remaining);
|
|
285
|
+
if (turns !== undefined)
|
|
286
|
+
stats.estimatedTurnsLeft = turns;
|
|
287
|
+
}
|
|
288
|
+
if (this.subagents.count > 0) {
|
|
289
|
+
const sub = {
|
|
290
|
+
count: this.subagents.count,
|
|
291
|
+
reBilledTokens: this.subagents.reBilledTokens,
|
|
292
|
+
};
|
|
293
|
+
if (this.subagents.prompt > 0)
|
|
294
|
+
sub.hitRate = this.subagents.read / this.subagents.prompt;
|
|
295
|
+
stats.subagents = sub;
|
|
296
|
+
}
|
|
297
|
+
return stats;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* 摘要续写的前缀(第三波 §1.8):当前转录按回合同样的方式转换,且上一次 turn 请求的消息
|
|
301
|
+
* 逐条是它的前缀(缓存必然命中)、加上摘要输出放得进窗口;否则 undefined(走独立请求)。
|
|
302
|
+
*/
|
|
303
|
+
summaryContinuation() {
|
|
304
|
+
const record = this.lastTurnRecord;
|
|
305
|
+
const model = this.core.model();
|
|
306
|
+
if (record === undefined || this.disposed)
|
|
307
|
+
return undefined;
|
|
308
|
+
if (model.provider !== record.model.provider || model.id !== record.model.id)
|
|
309
|
+
return undefined;
|
|
310
|
+
const messages = convertToLlm(this.core.agent.messages, {
|
|
311
|
+
provider: model.provider,
|
|
312
|
+
model: model.id,
|
|
313
|
+
});
|
|
314
|
+
const prev = record.contextRef.messages;
|
|
315
|
+
if (prev.length > messages.length)
|
|
316
|
+
return undefined;
|
|
317
|
+
for (let i = 0; i < prev.length; i++)
|
|
318
|
+
if (JSON.stringify(prev[i]) !== JSON.stringify(messages[i]))
|
|
319
|
+
return undefined;
|
|
320
|
+
const extra = Math.ceil(JSON.stringify(messages.slice(prev.length)).length / 4);
|
|
321
|
+
const window = model.contextWindow;
|
|
322
|
+
if (window !== undefined && record.promptTokens + extra + SUMMARY_MAX_TOKENS + 2048 > window)
|
|
323
|
+
return undefined;
|
|
324
|
+
const { onPayload: _p, onResponse: _r, purpose: _u, toolChoice: _t, cacheRetention: _c, maxTokens, ...rest } = record.options;
|
|
325
|
+
const streamOptions = { ...rest };
|
|
326
|
+
// 预算型思考的预算从 max_tokens 推导,改它会让消息缓存失效:沿用回合的值。
|
|
327
|
+
const budget = replayBlocker({
|
|
328
|
+
model,
|
|
329
|
+
options: rest,
|
|
330
|
+
payloadReplaced: false,
|
|
331
|
+
reporting: "reported",
|
|
332
|
+
});
|
|
333
|
+
if (budget === "thinking_budget")
|
|
334
|
+
streamOptions.maxTokens = maxTokens ?? model.maxTokens;
|
|
335
|
+
return { prefix: { messages }, streamOptions };
|
|
336
|
+
}
|
|
337
|
+
dispose() {
|
|
338
|
+
this.disposed = true;
|
|
339
|
+
this.warmer.cancel();
|
|
340
|
+
}
|
|
341
|
+
// -------------------------------------------------------------------------
|
|
342
|
+
// 内部
|
|
343
|
+
// -------------------------------------------------------------------------
|
|
344
|
+
modelOf(record) {
|
|
345
|
+
return this.models.get(record) ?? this.core.model();
|
|
346
|
+
}
|
|
347
|
+
toolsKey() {
|
|
348
|
+
return this.core.activeToolNames().sort().join(",");
|
|
349
|
+
}
|
|
350
|
+
takeTaskMs(at) {
|
|
351
|
+
let total = this.taskMs;
|
|
352
|
+
if (this.activeTasks > 0) {
|
|
353
|
+
total += at - this.taskSince;
|
|
354
|
+
this.taskSince = at;
|
|
355
|
+
}
|
|
356
|
+
this.taskMs = 0;
|
|
357
|
+
return total;
|
|
358
|
+
}
|
|
359
|
+
turnsLeft(remaining) {
|
|
360
|
+
if (this.growth.length === 0)
|
|
361
|
+
return undefined;
|
|
362
|
+
const average = this.growth.reduce((a, b) => a + b, 0) / this.growth.length;
|
|
363
|
+
return average > 0 ? Math.floor(remaining / average) : undefined;
|
|
364
|
+
}
|
|
365
|
+
observe(record, model, subtaskMs) {
|
|
366
|
+
const minTokens = model.promptCache?.minTokens ?? DEFAULT_MIN_CACHE_TOKENS;
|
|
367
|
+
const ttl = cacheTtlMs(model, record.options.cacheRetention);
|
|
368
|
+
const reporting = this.tracker.observe(record, minTokens, ttl ?? IMPLICIT_CACHE_TTL_MS, model.compat?.cacheReporting);
|
|
369
|
+
const key = endpointKey(record);
|
|
370
|
+
const sum = this.sums.get(key) ?? { read: 0, prompt: 0 };
|
|
371
|
+
sum.read += record.usage.cacheRead;
|
|
372
|
+
sum.prompt += record.promptTokens;
|
|
373
|
+
this.sums.set(key, sum);
|
|
374
|
+
if (record.purpose !== "turn")
|
|
375
|
+
return reporting;
|
|
376
|
+
const prev = this.resetPending ? undefined : this.prev;
|
|
377
|
+
const lastTurn = this.resetPending ? undefined : this.lastTurnRecord;
|
|
378
|
+
this.resetPending = false;
|
|
379
|
+
const missOptions = { reporting, minTokens, subtaskMs };
|
|
380
|
+
if (model.cost !== undefined)
|
|
381
|
+
missOptions.cost = model.cost;
|
|
382
|
+
const granularity = this.tracker.granularity(key);
|
|
383
|
+
if (granularity !== undefined)
|
|
384
|
+
missOptions.granularity = granularity;
|
|
385
|
+
const miss = detectMiss(prev, record, ttl, missOptions);
|
|
386
|
+
if (miss !== undefined) {
|
|
387
|
+
this.missCount++;
|
|
388
|
+
this.byReason[miss.reason] = (this.byReason[miss.reason] ?? 0) + 1;
|
|
389
|
+
this.reBilledTokens += miss.missedTokens;
|
|
390
|
+
this.reBilledUsd =
|
|
391
|
+
this.reBilledUsd === undefined || miss.missedCost === undefined
|
|
392
|
+
? undefined
|
|
393
|
+
: this.reBilledUsd + miss.missedCost;
|
|
394
|
+
this.core.emit({ type: "cache_miss", ...miss });
|
|
395
|
+
}
|
|
396
|
+
if (lastTurn !== undefined && record.promptTokens > lastTurn.promptTokens) {
|
|
397
|
+
this.growth.push(record.promptTokens - lastTurn.promptTokens);
|
|
398
|
+
if (this.growth.length > GROWTH_SAMPLES)
|
|
399
|
+
this.growth.shift();
|
|
400
|
+
}
|
|
401
|
+
this.prev = record;
|
|
402
|
+
this.lastTurnRecord = record;
|
|
403
|
+
this.checkPressure(record, model);
|
|
404
|
+
this.scheduleWarm(record, model, reporting, ttl);
|
|
405
|
+
return reporting;
|
|
406
|
+
}
|
|
407
|
+
checkPressure(record, model) {
|
|
408
|
+
const window = model.contextWindow;
|
|
409
|
+
if (window === undefined || window <= 0)
|
|
410
|
+
return;
|
|
411
|
+
const used = record.promptTokens + record.usage.output;
|
|
412
|
+
const percent = Math.min(100, Math.round((used / window) * 1000) / 10);
|
|
413
|
+
const before = this.lastPercent;
|
|
414
|
+
this.lastPercent = percent;
|
|
415
|
+
for (const threshold of PRESSURE_THRESHOLDS) {
|
|
416
|
+
if (before >= threshold || percent < threshold)
|
|
417
|
+
continue;
|
|
418
|
+
const remainingTokens = Math.max(0, window - used);
|
|
419
|
+
const event = {
|
|
420
|
+
type: "context_pressure",
|
|
421
|
+
percent,
|
|
422
|
+
threshold,
|
|
423
|
+
remainingTokens,
|
|
424
|
+
};
|
|
425
|
+
const turns = this.turnsLeft(remainingTokens);
|
|
426
|
+
if (turns !== undefined)
|
|
427
|
+
event.estimatedTurnsLeft = turns;
|
|
428
|
+
this.core.emit(event);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
scheduleWarm(record, model, reporting, ttl) {
|
|
432
|
+
if (this.mode() === "off")
|
|
433
|
+
return this.warmer.cancel();
|
|
434
|
+
const blocker = replayBlocker({
|
|
435
|
+
model,
|
|
436
|
+
options: record.options,
|
|
437
|
+
payloadReplaced: this.replaced.has(record),
|
|
438
|
+
reporting,
|
|
439
|
+
});
|
|
440
|
+
if (blocker !== undefined)
|
|
441
|
+
return this.warmer.block(blocker);
|
|
442
|
+
if (ttl === undefined)
|
|
443
|
+
return this.warmer.block("no_ttl");
|
|
444
|
+
if (this.decider() === undefined) {
|
|
445
|
+
const decision = evaluateWarm(model, record.promptTokens, "streaming", this.settings.minSavingsUsd);
|
|
446
|
+
if (decision.action === "stop")
|
|
447
|
+
return this.warmer.block(decision.reason ?? "declined");
|
|
448
|
+
}
|
|
449
|
+
this.warmer.start(record, ttl);
|
|
450
|
+
}
|
|
451
|
+
isCurrent(record) {
|
|
452
|
+
const model = this.core.model();
|
|
453
|
+
if (model.provider !== record.model.provider || model.id !== record.model.id)
|
|
454
|
+
return false;
|
|
455
|
+
const snapshot = this.snapshots.get(record);
|
|
456
|
+
if (snapshot === undefined)
|
|
457
|
+
return false;
|
|
458
|
+
if (snapshot.thinking !== undefined && snapshot.thinking !== this.core.thinkingLevel())
|
|
459
|
+
return false;
|
|
460
|
+
if (snapshot.tools !== this.toolsKey())
|
|
461
|
+
return false;
|
|
462
|
+
const current = this.core.agent.messages;
|
|
463
|
+
if (current.length < snapshot.messages.length)
|
|
464
|
+
return false;
|
|
465
|
+
return snapshot.messages.every((message, i) => current[i] === message);
|
|
466
|
+
}
|
|
467
|
+
async replay(record, signal) {
|
|
468
|
+
const inner = this.inner;
|
|
469
|
+
if (inner === undefined)
|
|
470
|
+
throw new Error("stream not wrapped");
|
|
471
|
+
const options = { ...record.options, maxTokens: 1, purpose: "warm", signal };
|
|
472
|
+
return inner(this.modelOf(record), record.contextRef, options).result();
|
|
473
|
+
}
|
|
474
|
+
onWarmed(record, message, sentAt) {
|
|
475
|
+
const usage = message.usage;
|
|
476
|
+
try {
|
|
477
|
+
this.core.appendEntry({
|
|
478
|
+
type: "usage",
|
|
479
|
+
kind: "cache_warm",
|
|
480
|
+
provider: record.model.provider,
|
|
481
|
+
model: record.model.id,
|
|
482
|
+
usage,
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
this.core.log("debug", `cache warm usage not recorded: ${String(error)}`);
|
|
487
|
+
}
|
|
488
|
+
const event = { type: "cache_warm", phase: "sent", usage };
|
|
489
|
+
if (usage.cost !== undefined)
|
|
490
|
+
event.cost = usage.cost.total;
|
|
491
|
+
this.core.emit(event);
|
|
492
|
+
const warm = {
|
|
493
|
+
...record,
|
|
494
|
+
at: sentAt,
|
|
495
|
+
purpose: "warm",
|
|
496
|
+
usage,
|
|
497
|
+
promptTokens: usage.input + usage.cacheRead + usage.cacheWrite,
|
|
498
|
+
};
|
|
499
|
+
const model = this.modelOf(record);
|
|
500
|
+
this.models.set(warm, model);
|
|
501
|
+
const minTokens = model.promptCache?.minTokens ?? DEFAULT_MIN_CACHE_TOKENS;
|
|
502
|
+
this.tracker.observe(warm, minTokens, cacheTtlMs(model), model.compat?.cacheReporting);
|
|
503
|
+
const sum = this.sums.get(endpointKey(warm));
|
|
504
|
+
if (sum !== undefined) {
|
|
505
|
+
sum.read += usage.cacheRead;
|
|
506
|
+
sum.prompt += warm.promptTokens;
|
|
507
|
+
}
|
|
508
|
+
if (!this.resetPending)
|
|
509
|
+
this.prev = warm;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话侧的压缩调度(设计 §9)。[B2]
|
|
3
|
+
*
|
|
4
|
+
* - 阈值检查(新提示前、`prepareNextTurn` 里):估算 > 0.7 ×(窗口 − 预留)→ 档一裁剪;仍 > 窗口 − 预留
|
|
5
|
+
* 且熔断允许 → 档二摘要(trigger `threshold`)。
|
|
6
|
+
* - 溢出恢复(会话 run 结束后,失败尝试已用 context_edit 剔除):PreCompact Hook → 档二摘要(trigger
|
|
7
|
+
* `overflow`,不受「每 run 一次」限制但受跳闸限制)→ 压缩后估算 ≤ 0.8 × 窗口才重试。
|
|
8
|
+
* - 手动 `/compact`:PreCompact(trigger `manual`)→ 摘要;成功清零熔断。
|
|
9
|
+
* PreCompact 的 `decision: "block"` 取消本次压缩;`customInstructions` 追加到摘要提示。
|
|
10
|
+
* [W3-C1b] 阈值 / 手动压缩与分支摘要优先走会话前缀续写(缓存控制器给前缀),溢出恢复不走
|
|
11
|
+
* (前缀本身已超窗口);续写失败回落独立请求并记 warning。
|
|
12
|
+
*/
|
|
13
|
+
import { CompactionBreaker } from "../compaction/breaker.js";
|
|
14
|
+
import { type ContextEstimate } from "../compaction/estimate.js";
|
|
15
|
+
import type { BranchSummaryEntry } from "../session/types.js";
|
|
16
|
+
import type { SessionCore } from "./session-core.js";
|
|
17
|
+
import type { CompactionResult, CompactionSettings } from "./types.js";
|
|
18
|
+
export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings;
|
|
19
|
+
/** 保留区不超过 (窗口 − 预留) 的 40%,否则小窗口模型上摘要后仍然溢出。 */
|
|
20
|
+
export declare const KEEP_RECENT_MAX_RATIO = 0.4;
|
|
21
|
+
export declare class CompactionController {
|
|
22
|
+
readonly breaker: CompactionBreaker;
|
|
23
|
+
settings: CompactionSettings;
|
|
24
|
+
private readonly core;
|
|
25
|
+
private compacting;
|
|
26
|
+
constructor(core: SessionCore, settings?: Partial<CompactionSettings>);
|
|
27
|
+
get isCompacting(): boolean;
|
|
28
|
+
/** 模型或开关变化后调用。 */
|
|
29
|
+
refresh(): void;
|
|
30
|
+
setAuto(enabled: boolean): void;
|
|
31
|
+
estimate(): ContextEstimate;
|
|
32
|
+
private budget;
|
|
33
|
+
private keepRecent;
|
|
34
|
+
/** 摘要请求的公共选项;`continuation` 时附上会话前缀续写的材料。 */
|
|
35
|
+
private summarizer;
|
|
36
|
+
/** 档一;返回是否裁剪了内容。 */
|
|
37
|
+
prune(): boolean;
|
|
38
|
+
/** 阈值检查(档一 → 档二)。失败只记录,不打断 run。 */
|
|
39
|
+
checkThreshold(signal: AbortSignal): Promise<void>;
|
|
40
|
+
/** 溢出恢复:返回是否应以新 run 重试。 */
|
|
41
|
+
recoverOverflow(signal: AbortSignal): Promise<{
|
|
42
|
+
retry: boolean;
|
|
43
|
+
warning?: string;
|
|
44
|
+
}>;
|
|
45
|
+
compactManual(instructions: string | undefined, signal: AbortSignal): Promise<CompactionResult>;
|
|
46
|
+
/** `/tree` 离开分支:换叶子,并为离开的那段写 branch_summary(挂在新叶子下)。 */
|
|
47
|
+
leaveBranch(targetId: string | null, instructions: string | undefined, signal: AbortSignal): Promise<BranchSummaryEntry | undefined>;
|
|
48
|
+
private summarize;
|
|
49
|
+
}
|