@armadra/agent 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/LICENSE +21 -0
- package/README.md +470 -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 +514 -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 +119 -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 +111 -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 +485 -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 +304 -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 +103 -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/channels.d.ts +51 -0
- package/dist/ai/providers/channels.js +96 -0
- package/dist/ai/providers/enrich.d.ts +34 -0
- package/dist/ai/providers/enrich.js +86 -0
- package/dist/ai/providers/models-dev-cache.d.ts +53 -0
- package/dist/ai/providers/models-dev-cache.js +147 -0
- package/dist/ai/providers/models-dev.d.ts +99 -0
- package/dist/ai/providers/models-dev.js +315 -0
- package/dist/ai/providers/registry.d.ts +114 -0
- package/dist/ai/providers/registry.js +458 -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 +448 -0
- package/dist/ai/types.js +19 -0
- package/dist/bundle/ama-sandbox.cjs +324 -0
- package/dist/bundle/ama.cjs +27837 -0
- package/dist/bundle.d.ts +9 -0
- package/dist/bundle.js +15 -0
- package/dist/cli/args.d.ts +85 -0
- package/dist/cli/args.js +408 -0
- package/dist/cli/bootstrap.d.ts +18 -0
- package/dist/cli/bootstrap.js +399 -0
- package/dist/cli/compose-providers.d.ts +37 -0
- package/dist/cli/compose-providers.js +107 -0
- package/dist/cli/compose-session.d.ts +72 -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 +108 -0
- package/dist/cli/compose.js +221 -0
- package/dist/cli/default-model.d.ts +16 -0
- package/dist/cli/default-model.js +24 -0
- package/dist/cli/deps.d.ts +207 -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 +27 -0
- package/dist/cli/main.js +177 -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 +202 -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 +53 -0
- package/dist/cli/subcommands/config.js +277 -0
- package/dist/cli/subcommands/context.d.ts +21 -0
- package/dist/cli/subcommands/context.js +42 -0
- package/dist/cli/subcommands/doctor.d.ts +11 -0
- package/dist/cli/subcommands/doctor.js +246 -0
- package/dist/cli/subcommands/init.d.ts +6 -0
- package/dist/cli/subcommands/init.js +22 -0
- package/dist/cli/subcommands/model-meta.d.ts +16 -0
- package/dist/cli/subcommands/model-meta.js +54 -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 +46 -0
- package/dist/cli/subcommands/models-discover.js +232 -0
- package/dist/cli/subcommands/models.d.ts +40 -0
- package/dist/cli/subcommands/models.js +152 -0
- package/dist/cli/subcommands/providers-list.d.ts +8 -0
- package/dist/cli/subcommands/providers-list.js +97 -0
- package/dist/cli/subcommands/providers-plan.d.ts +79 -0
- package/dist/cli/subcommands/providers-plan.js +215 -0
- package/dist/cli/subcommands/providers.d.ts +27 -0
- package/dist/cli/subcommands/providers.js +433 -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/init.d.ts +30 -0
- package/dist/config/init.js +92 -0
- package/dist/config/json-schema.d.ts +14 -0
- package/dist/config/json-schema.js +182 -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 +476 -0
- package/dist/config/trust.d.ts +42 -0
- package/dist/config/trust.js +122 -0
- package/dist/config/types.d.ts +190 -0
- package/dist/config/types.js +29 -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/image-input.d.ts +27 -0
- package/dist/modes/image-input.js +78 -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 +201 -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 +491 -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 +218 -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 +33 -0
- package/dist/modes/interactive/startup-ui.js +268 -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 +17 -0
- package/dist/modes/print/print-mode.js +107 -0
- package/dist/modes/rpc/commands.d.ts +40 -0
- package/dist/modes/rpc/commands.js +263 -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 +173 -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 +184 -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 +201 -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/image-file.d.ts +31 -0
- package/dist/tools/image-file.js +114 -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 +24 -0
- package/dist/tools/read.js +132 -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 +531 -0
- package/docs/rpc.md +253 -0
- package/docs/session-format.md +119 -0
- package/docs/tui.md +170 -0
- package/package.json +101 -4
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 循环与会话对象契约(设计 §4.1、§4.3、§13.1、§13.2 事件)。[B0] 契约文件,实现归 B2。
|
|
3
|
+
*
|
|
4
|
+
* 补全与偏差:
|
|
5
|
+
* - `ContentBlock / Usage / StopReason` 等定义在 ai/types.ts,`AgentMessage` 定义在
|
|
6
|
+
* session/types.ts(依赖方向),此处再导出,设计里「agent/types.ts 提供」的名字都能从这里拿到。
|
|
7
|
+
* - `LoopHooks.beforeToolCall` 的 `ctx` 补全为 `ToolCallGateContext`;`prepareRequest` 的
|
|
8
|
+
* `req` 补全为 `PreparedRequest`。
|
|
9
|
+
* - `SessionEvent` 是 AgentSession.subscribe 的进程内事件;RPC / stream-json 线上形状见
|
|
10
|
+
* src/rpc.ts(`message_update` 线上为纯增量)。
|
|
11
|
+
* - `AgentSession` 是接口;B2 的实现类不要再叫 `AgentSession`(建议 `AgentSessionImpl`),
|
|
12
|
+
* 否则与本接口在 index.ts 的再导出冲突。
|
|
13
|
+
* - 补全 `SessionState`、`SessionStats`、`CompactionResult`、`CompactionSettings`、
|
|
14
|
+
* `RetrySettings`、`QueueMode`。
|
|
15
|
+
* - (B2 追加)`PromptOptions.origin` 与 `steer / followUp` 的可选 `EnqueueOptions`:宿主
|
|
16
|
+
* `sendUser(text, origin)` 注入的消息要以 `origin` 落盘(§4.3);`"user"` 等同不填。
|
|
17
|
+
* - (W3-C0)缓存可观测性(第三波 §1.10):`SessionEvent` 加 `cache_miss` / `cache_warm` /
|
|
18
|
+
* `context_pressure`,`SessionStats.cache`(可选,C1b 填);`CacheSettings` 是
|
|
19
|
+
* `SessionCacheController` 的解析后设置(来自 config `cache` 段与环境变量)。
|
|
20
|
+
*/
|
|
21
|
+
import type { AssistantEvent, AssistantMessage, CacheRetention, ImageBlock, Message, MessageOrigin, Model, ModelRef, ModelThinkingLevel, ToolCallBlock, ToolResultMessage, TranscriptContext, Usage } from "../ai/types.js";
|
|
22
|
+
import type { CacheMiss, CacheMissReason, CacheReporting, WarmerStatus, WarmingMode } from "../ai/cache/types.js";
|
|
23
|
+
import type { HookEvent } from "../hooks/types.js";
|
|
24
|
+
import type { ActionPreview, ApprovalDecision, ApprovalReason, PermissionMode } from "../permissions/types.js";
|
|
25
|
+
import type { AgentMessage, SessionEntry } from "../session/types.js";
|
|
26
|
+
import type { ToolDefinition, ToolResult } from "../tools/types.js";
|
|
27
|
+
export type { AssistantContentBlock, AssistantMessage, ContentBlock, ImageBlock, Message, StopReason, SystemMessage, TextBlock, ThinkingBlock, ToolCallBlock, ToolResultMessage, Usage, UserMessage, } from "../ai/types.js";
|
|
28
|
+
export type { AgentMessage, BranchSummaryMessage, CompactionSummaryMessage, CustomMessage, } from "../session/types.js";
|
|
29
|
+
export type ToolCall = ToolCallBlock;
|
|
30
|
+
export interface TurnResult {
|
|
31
|
+
assistant: AssistantMessage;
|
|
32
|
+
toolResults: ToolResultMessage[];
|
|
33
|
+
}
|
|
34
|
+
export interface PreparedRequest {
|
|
35
|
+
context: TranscriptContext;
|
|
36
|
+
model: Model;
|
|
37
|
+
thinkingLevel: ModelThinkingLevel;
|
|
38
|
+
}
|
|
39
|
+
export interface ToolCallGateContext {
|
|
40
|
+
readonly signal: AbortSignal;
|
|
41
|
+
/** 产出该调用的助手消息。 */
|
|
42
|
+
readonly assistant: AssistantMessage;
|
|
43
|
+
/** 找不到工具时为 undefined(tool-runner 已先行报错,通常不会走到钩子)。 */
|
|
44
|
+
readonly tool: ToolDefinition | undefined;
|
|
45
|
+
/** 嵌套调用(工具里经 `ToolContext.tools.executeTool` 发起,例如 codemode 脚本)时的外层调用。 */
|
|
46
|
+
readonly parent?: NestedCallInfo;
|
|
47
|
+
}
|
|
48
|
+
/** 嵌套调用的外层:Hook 输入据此带 `parentToolCallId` 与 `viaCodemode`(设计 §5.5)。 */
|
|
49
|
+
export interface NestedCallInfo {
|
|
50
|
+
readonly toolCallId: string;
|
|
51
|
+
/** 外层是 codemode 工具。 */
|
|
52
|
+
readonly viaCodemode: boolean;
|
|
53
|
+
}
|
|
54
|
+
export interface ToolCallGate {
|
|
55
|
+
block?: boolean;
|
|
56
|
+
reason?: string;
|
|
57
|
+
/** Hook 的 updatedInput 替换后的输入。 */
|
|
58
|
+
input?: unknown;
|
|
59
|
+
}
|
|
60
|
+
export interface LoopHooks {
|
|
61
|
+
/** 档一裁剪、Hook 的 additionalContext 注入。 */
|
|
62
|
+
transformContext?(messages: AgentMessage[], signal: AbortSignal): Promise<AgentMessage[]>;
|
|
63
|
+
/** 不得抛错。 */
|
|
64
|
+
convertToLlm(messages: AgentMessage[]): Message[];
|
|
65
|
+
prepareRequest?(req: PreparedRequest): Promise<PreparedRequest>;
|
|
66
|
+
/** 阈值压缩在此。 */
|
|
67
|
+
prepareNextTurn?(prev: TurnResult): Promise<void>;
|
|
68
|
+
/** 命令式 Hook PreToolUse → 权限管线 → broker。 */
|
|
69
|
+
beforeToolCall(call: ToolCall, ctx: ToolCallGateContext): Promise<ToolCallGate>;
|
|
70
|
+
/** PostToolUse 可追加上下文 / 改为错误。 */
|
|
71
|
+
afterToolCall?(call: ToolCall, result: ToolResult): Promise<ToolResult>;
|
|
72
|
+
finishTurn?(turn: TurnResult): Promise<"continue" | "end">;
|
|
73
|
+
getSteeringMessages(): AgentMessage[];
|
|
74
|
+
getFollowUpMessages(): AgentMessage[];
|
|
75
|
+
}
|
|
76
|
+
export type QueueMode = "one-at-a-time" | "all";
|
|
77
|
+
export interface CompactionSettings {
|
|
78
|
+
enabled: boolean;
|
|
79
|
+
/** 缺省 16 384。 */
|
|
80
|
+
reserveTokens: number;
|
|
81
|
+
/** 缺省 20 000。 */
|
|
82
|
+
keepRecentTokens: number;
|
|
83
|
+
}
|
|
84
|
+
export interface RetrySettings {
|
|
85
|
+
enabled: boolean;
|
|
86
|
+
/** 缺省 3。 */
|
|
87
|
+
maxRetries: number;
|
|
88
|
+
/** 缺省 2 000。 */
|
|
89
|
+
baseDelayMs: number;
|
|
90
|
+
/** 缺省 60 000。 */
|
|
91
|
+
maxDelayMs: number;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* [W3-C0] 会话层缓存设置(第三波 §1.12),解析后的完整形状;缺省 streaming / short /
|
|
95
|
+
* 0.05 / true / false。
|
|
96
|
+
*/
|
|
97
|
+
export interface CacheSettings {
|
|
98
|
+
/** 子会话(depth > 0)在 `warmSubagents` 为 false 时按 off。 */
|
|
99
|
+
warming: WarmingMode;
|
|
100
|
+
retention: CacheRetention;
|
|
101
|
+
/** 保温的最低期望节省(美元),缺省 0.05。 */
|
|
102
|
+
minSavingsUsd: number;
|
|
103
|
+
/** 转录 / 消息区的未命中与上下文余量提示(统计不受影响)。 */
|
|
104
|
+
missNotices: boolean;
|
|
105
|
+
warmSubagents: boolean;
|
|
106
|
+
}
|
|
107
|
+
export interface CompactionResult {
|
|
108
|
+
summary: string;
|
|
109
|
+
firstKeptEntryId: string;
|
|
110
|
+
tokensBefore: number;
|
|
111
|
+
tokensAfter?: number;
|
|
112
|
+
usage?: Usage;
|
|
113
|
+
}
|
|
114
|
+
export type CompactionTrigger = "threshold" | "overflow" | "manual";
|
|
115
|
+
export type SessionEvent = {
|
|
116
|
+
type: "session_start";
|
|
117
|
+
sessionId: string;
|
|
118
|
+
sessionFile?: string;
|
|
119
|
+
cwd: string;
|
|
120
|
+
reason: "startup" | "resume" | "new" | "fork";
|
|
121
|
+
}
|
|
122
|
+
/** 用户提示经 UserPromptSubmit Hook 与模板展开之后、本次运行开始之前(设计 §11.1 第 16 步)。 */
|
|
123
|
+
| {
|
|
124
|
+
type: "before_agent_start";
|
|
125
|
+
prompt: string;
|
|
126
|
+
} | {
|
|
127
|
+
type: "agent_start";
|
|
128
|
+
} | {
|
|
129
|
+
type: "agent_end";
|
|
130
|
+
stopReason: string;
|
|
131
|
+
willRetry: boolean;
|
|
132
|
+
} | {
|
|
133
|
+
type: "agent_before_settle";
|
|
134
|
+
} | {
|
|
135
|
+
type: "agent_settled";
|
|
136
|
+
warning?: string;
|
|
137
|
+
} | {
|
|
138
|
+
type: "turn_start";
|
|
139
|
+
} | {
|
|
140
|
+
type: "turn_end";
|
|
141
|
+
message: AssistantMessage;
|
|
142
|
+
toolResults: ToolResultMessage[];
|
|
143
|
+
} | {
|
|
144
|
+
type: "message_start";
|
|
145
|
+
message: AgentMessage;
|
|
146
|
+
} | {
|
|
147
|
+
type: "message_update";
|
|
148
|
+
/** 当前累计的部分消息。 */
|
|
149
|
+
message: AssistantMessage;
|
|
150
|
+
assistantMessageEvent: AssistantEvent;
|
|
151
|
+
} | {
|
|
152
|
+
type: "message_end";
|
|
153
|
+
message: AgentMessage;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* `parentToolCallId`:codemode 脚本里经 `tools.*` 发起的内层调用带上外层 `codemode` 调用的
|
|
157
|
+
* id(设计 §5.5),TUI 据此折叠显示;模型直接发起的调用不带。
|
|
158
|
+
*/
|
|
159
|
+
| {
|
|
160
|
+
type: "tool_execution_start";
|
|
161
|
+
toolCallId: string;
|
|
162
|
+
toolName: string;
|
|
163
|
+
args: unknown;
|
|
164
|
+
parentToolCallId?: string;
|
|
165
|
+
} | {
|
|
166
|
+
type: "tool_execution_update";
|
|
167
|
+
toolCallId: string;
|
|
168
|
+
toolName: string;
|
|
169
|
+
partial: string;
|
|
170
|
+
parentToolCallId?: string;
|
|
171
|
+
} | {
|
|
172
|
+
type: "tool_execution_end";
|
|
173
|
+
toolCallId: string;
|
|
174
|
+
toolName: string;
|
|
175
|
+
result: ToolResult;
|
|
176
|
+
isError: boolean;
|
|
177
|
+
parentToolCallId?: string;
|
|
178
|
+
} | {
|
|
179
|
+
type: "queue_update";
|
|
180
|
+
steering: string[];
|
|
181
|
+
followUp: string[];
|
|
182
|
+
} | {
|
|
183
|
+
type: "compaction_start";
|
|
184
|
+
trigger: CompactionTrigger;
|
|
185
|
+
} | {
|
|
186
|
+
type: "compaction_end";
|
|
187
|
+
trigger: CompactionTrigger;
|
|
188
|
+
result?: CompactionResult;
|
|
189
|
+
aborted: boolean;
|
|
190
|
+
willRetry: boolean;
|
|
191
|
+
error?: string;
|
|
192
|
+
} | {
|
|
193
|
+
type: "auto_retry_start";
|
|
194
|
+
attempt: number;
|
|
195
|
+
maxAttempts: number;
|
|
196
|
+
delayMs: number;
|
|
197
|
+
errorMessage: string;
|
|
198
|
+
} | {
|
|
199
|
+
type: "auto_retry_end";
|
|
200
|
+
success: boolean;
|
|
201
|
+
attempt: number;
|
|
202
|
+
finalError?: string;
|
|
203
|
+
} | {
|
|
204
|
+
type: "permission_request";
|
|
205
|
+
requestId: string;
|
|
206
|
+
toolName: string;
|
|
207
|
+
input: unknown;
|
|
208
|
+
reason: ApprovalReason;
|
|
209
|
+
hookReason?: string;
|
|
210
|
+
timeoutMs: number;
|
|
211
|
+
/** [W3-C0] 执行前预览(同 `ApprovalRequest.preview`)。 */
|
|
212
|
+
preview?: ActionPreview;
|
|
213
|
+
} | {
|
|
214
|
+
type: "permission_resolved";
|
|
215
|
+
requestId: string;
|
|
216
|
+
decision: ApprovalDecision;
|
|
217
|
+
} | {
|
|
218
|
+
type: "permission_mode_changed";
|
|
219
|
+
mode: PermissionMode;
|
|
220
|
+
} | {
|
|
221
|
+
type: "entry_appended";
|
|
222
|
+
entry: SessionEntry;
|
|
223
|
+
} | {
|
|
224
|
+
type: "hook_executed";
|
|
225
|
+
event: HookEvent;
|
|
226
|
+
command: string;
|
|
227
|
+
exitCode: number | null;
|
|
228
|
+
durationMs: number;
|
|
229
|
+
} | {
|
|
230
|
+
type: "session_changed";
|
|
231
|
+
sessionId: string;
|
|
232
|
+
sessionFile?: string;
|
|
233
|
+
} | {
|
|
234
|
+
type: "model_changed";
|
|
235
|
+
model: ModelRef;
|
|
236
|
+
} | {
|
|
237
|
+
type: "thinking_level_changed";
|
|
238
|
+
level: ModelThinkingLevel;
|
|
239
|
+
}
|
|
240
|
+
/** [W3-C0] 一次缓存未命中(第三波 §1.5);统计计入全部,界面只提示超过门槛的那次。 */
|
|
241
|
+
| ({
|
|
242
|
+
type: "cache_miss";
|
|
243
|
+
} & CacheMiss)
|
|
244
|
+
/** [W3-C0] 保温状态变化(第三波 §1.7):排期、发出(带用量与花费)、停止(带原因)。 */
|
|
245
|
+
| {
|
|
246
|
+
type: "cache_warm";
|
|
247
|
+
phase: "scheduled" | "sent" | "stopped";
|
|
248
|
+
nextWarmAt?: number;
|
|
249
|
+
usage?: Usage;
|
|
250
|
+
/** 美元。 */
|
|
251
|
+
cost?: number;
|
|
252
|
+
reason?: string;
|
|
253
|
+
}
|
|
254
|
+
/** [W3-C0] 上下文占用跨越 70% / 90%(每个阈值每次跨越提示一次)。 */
|
|
255
|
+
| {
|
|
256
|
+
type: "context_pressure";
|
|
257
|
+
percent: number;
|
|
258
|
+
threshold: 70 | 90;
|
|
259
|
+
remainingTokens?: number;
|
|
260
|
+
/** 按最近 5 回合均值估算。 */
|
|
261
|
+
estimatedTurnsLeft?: number;
|
|
262
|
+
};
|
|
263
|
+
export type SessionEventType = SessionEvent["type"];
|
|
264
|
+
export type PromptDisposition = "started" | "queued" | "handled";
|
|
265
|
+
export interface PromptOptions {
|
|
266
|
+
images?: ImageBlock[];
|
|
267
|
+
streamingBehavior?: "steer" | "followUp";
|
|
268
|
+
/** 落盘到 user 消息的 origin(宿主注入为 "host");缺省:空闲时不填,入队时为 streamingBehavior。 */
|
|
269
|
+
origin?: MessageOrigin;
|
|
270
|
+
}
|
|
271
|
+
/** steer / followUp 的可选项。 */
|
|
272
|
+
export interface EnqueueOptions {
|
|
273
|
+
/** 缺省为 "steer" / "followUp";`"user"` 表示普通用户输入(不写 origin)。 */
|
|
274
|
+
origin?: MessageOrigin;
|
|
275
|
+
}
|
|
276
|
+
export interface SessionState {
|
|
277
|
+
isStreaming: boolean;
|
|
278
|
+
isCompacting: boolean;
|
|
279
|
+
isRetrying: boolean;
|
|
280
|
+
model: ModelRef | undefined;
|
|
281
|
+
thinkingLevel: ModelThinkingLevel;
|
|
282
|
+
permissionMode: PermissionMode;
|
|
283
|
+
sessionId: string;
|
|
284
|
+
sessionFile: string | undefined;
|
|
285
|
+
cwd: string;
|
|
286
|
+
sessionName: string | undefined;
|
|
287
|
+
messageCount: number;
|
|
288
|
+
pendingMessageCount: number;
|
|
289
|
+
steeringMode: QueueMode;
|
|
290
|
+
followUpMode: QueueMode;
|
|
291
|
+
autoCompaction: boolean;
|
|
292
|
+
autoRetry: boolean;
|
|
293
|
+
}
|
|
294
|
+
export interface SessionStats {
|
|
295
|
+
sessionId: string;
|
|
296
|
+
sessionFile: string | undefined;
|
|
297
|
+
userMessages: number;
|
|
298
|
+
assistantMessages: number;
|
|
299
|
+
toolCalls: number;
|
|
300
|
+
toolResults: number;
|
|
301
|
+
tokens: {
|
|
302
|
+
input: number;
|
|
303
|
+
output: number;
|
|
304
|
+
cacheRead: number;
|
|
305
|
+
cacheWrite: number;
|
|
306
|
+
total: number;
|
|
307
|
+
};
|
|
308
|
+
/** 美元;任一条消息缺成本时 undefined(显示 `$?`)。 */
|
|
309
|
+
cost: number | undefined;
|
|
310
|
+
/** 估算的当前上下文 token(§9 估算)。 */
|
|
311
|
+
contextTokens: number | undefined;
|
|
312
|
+
contextWindow: number | undefined;
|
|
313
|
+
/** 0–100;无窗口时 undefined(显示 `ctx ?`)。 */
|
|
314
|
+
contextPercent: number | undefined;
|
|
315
|
+
/**
|
|
316
|
+
* 缓存命中率 0–1 = cacheRead /(input + cacheRead + cacheWrite)(设计 §9.1);
|
|
317
|
+
* 还没有任何输入用量时不给。
|
|
318
|
+
*/
|
|
319
|
+
cacheHitRate?: number;
|
|
320
|
+
/** [W3-C0] 缓存可观测性(第三波 §1.10);会话层缓存控制器(C1b)未接线时缺省。 */
|
|
321
|
+
cache?: SessionCacheStats;
|
|
322
|
+
}
|
|
323
|
+
/** [W3-C0] `SessionStats.cache`(`get_session_stats` / `/session` / `-p --output-format json`)。 */
|
|
324
|
+
export interface SessionCacheStats {
|
|
325
|
+
/** 当前端点的三态。 */
|
|
326
|
+
reporting: CacheReporting;
|
|
327
|
+
/** 最近一次请求的命中率 0–1;`unknown` / `silent` 时不给。 */
|
|
328
|
+
lastHitRate?: number;
|
|
329
|
+
/** 会话累计命中率 0–1;不报缓存的请求不进分母。 */
|
|
330
|
+
hitRate?: number;
|
|
331
|
+
/** 未命中重计费的 token 合计。 */
|
|
332
|
+
reBilledTokens: number;
|
|
333
|
+
/** 重计费金额(美元);有无价模型参与时 undefined。 */
|
|
334
|
+
reBilledUsd?: number;
|
|
335
|
+
misses: {
|
|
336
|
+
count: number;
|
|
337
|
+
byReason: Partial<Record<CacheMissReason, number>>;
|
|
338
|
+
};
|
|
339
|
+
warming: WarmerStatus;
|
|
340
|
+
contextRemainingTokens?: number;
|
|
341
|
+
estimatedTurnsLeft?: number;
|
|
342
|
+
/** task 子会话的汇总(各自独立统计)。 */
|
|
343
|
+
subagents?: {
|
|
344
|
+
count: number;
|
|
345
|
+
hitRate?: number;
|
|
346
|
+
reBilledTokens: number;
|
|
347
|
+
};
|
|
348
|
+
/** 当前端点推断的缓存读分块粒度(token);未推断出时不给。 */
|
|
349
|
+
granularity?: number;
|
|
350
|
+
}
|
|
351
|
+
export interface AgentSession {
|
|
352
|
+
/** 运行中且无 streamingBehavior → reject AmaError{code:"busy"};run 结束(含重试与 followUp)后 resolve。 */
|
|
353
|
+
prompt(text: string, options?: PromptOptions): Promise<PromptDisposition>;
|
|
354
|
+
steer(text: string, options?: EnqueueOptions): Promise<"queued" | "handled">;
|
|
355
|
+
followUp(text: string, options?: EnqueueOptions): Promise<"queued" | "handled">;
|
|
356
|
+
/** 回到 idle 后 resolve;不清队列。 */
|
|
357
|
+
abort(): Promise<void>;
|
|
358
|
+
waitForIdle(): Promise<void>;
|
|
359
|
+
clearQueue(): {
|
|
360
|
+
steering: string[];
|
|
361
|
+
followUp: string[];
|
|
362
|
+
};
|
|
363
|
+
subscribe(listener: (event: SessionEvent) => void): () => void;
|
|
364
|
+
compact(instructions?: string): Promise<CompactionResult>;
|
|
365
|
+
fork(entryId: string): Promise<AgentSession>;
|
|
366
|
+
/** `provider/model-id`。 */
|
|
367
|
+
setModel(ref: string): Promise<void>;
|
|
368
|
+
setThinkingLevel(level: ModelThinkingLevel): void;
|
|
369
|
+
setPermissionMode(mode: PermissionMode): void;
|
|
370
|
+
setActiveTools(names: string[]): void;
|
|
371
|
+
getTools(): readonly ToolDefinition[];
|
|
372
|
+
readonly state: SessionState;
|
|
373
|
+
readonly messages: readonly AgentMessage[];
|
|
374
|
+
readonly entries: readonly SessionEntry[];
|
|
375
|
+
getLastAssistantText(): string | null;
|
|
376
|
+
getStats(): SessionStats;
|
|
377
|
+
dispose(): Promise<void>;
|
|
378
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 循环与会话对象契约(设计 §4.1、§4.3、§13.1、§13.2 事件)。[B0] 契约文件,实现归 B2。
|
|
3
|
+
*
|
|
4
|
+
* 补全与偏差:
|
|
5
|
+
* - `ContentBlock / Usage / StopReason` 等定义在 ai/types.ts,`AgentMessage` 定义在
|
|
6
|
+
* session/types.ts(依赖方向),此处再导出,设计里「agent/types.ts 提供」的名字都能从这里拿到。
|
|
7
|
+
* - `LoopHooks.beforeToolCall` 的 `ctx` 补全为 `ToolCallGateContext`;`prepareRequest` 的
|
|
8
|
+
* `req` 补全为 `PreparedRequest`。
|
|
9
|
+
* - `SessionEvent` 是 AgentSession.subscribe 的进程内事件;RPC / stream-json 线上形状见
|
|
10
|
+
* src/rpc.ts(`message_update` 线上为纯增量)。
|
|
11
|
+
* - `AgentSession` 是接口;B2 的实现类不要再叫 `AgentSession`(建议 `AgentSessionImpl`),
|
|
12
|
+
* 否则与本接口在 index.ts 的再导出冲突。
|
|
13
|
+
* - 补全 `SessionState`、`SessionStats`、`CompactionResult`、`CompactionSettings`、
|
|
14
|
+
* `RetrySettings`、`QueueMode`。
|
|
15
|
+
* - (B2 追加)`PromptOptions.origin` 与 `steer / followUp` 的可选 `EnqueueOptions`:宿主
|
|
16
|
+
* `sendUser(text, origin)` 注入的消息要以 `origin` 落盘(§4.3);`"user"` 等同不填。
|
|
17
|
+
* - (W3-C0)缓存可观测性(第三波 §1.10):`SessionEvent` 加 `cache_miss` / `cache_warm` /
|
|
18
|
+
* `context_pressure`,`SessionStats.cache`(可选,C1b 填);`CacheSettings` 是
|
|
19
|
+
* `SessionCacheController` 的解析后设置(来自 config `cache` 段与环境变量)。
|
|
20
|
+
*/
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* anthropic-messages 协议(设计 §3.1):POST `{baseUrl}/v1/messages`(stream;baseUrl 已以 `/v1`
|
|
3
|
+
* 结尾时不重复),SSE → 事件。
|
|
4
|
+
*
|
|
5
|
+
* SSE 事件:message_start(id、初始 usage)→ content_block_start / delta / stop(text、
|
|
6
|
+
* thinking + signature_delta、redacted_thinking、tool_use + input_json_delta)→ message_delta
|
|
7
|
+
* (stop_reason、累计 usage)→ message_stop。`event: error` 或缺 message_stop 都编码为 error。
|
|
8
|
+
*
|
|
9
|
+
* usage:`input_tokens` 本就不含缓存;`cache_read_input_tokens` → cacheRead,
|
|
10
|
+
* `cache_creation_input_tokens` → cacheWrite,`cache_creation.ephemeral_1h_input_tokens` →
|
|
11
|
+
* cacheWrite1h。message_delta 只覆盖非 null 字段(部分代理在 delta 里省略 input)。两个缓存字段
|
|
12
|
+
* 任一出现过(含 0)即 `cacheReported: true`,之后的事件不会把它改回 false。
|
|
13
|
+
*/
|
|
14
|
+
import type { AnthropicMessagesCompat, ApiImplementation, Usage } from "../types.js";
|
|
15
|
+
type Json = Record<string, unknown>;
|
|
16
|
+
/** 把 Anthropic usage 字段写进 Usage(只覆盖出现且非 null 的字段)。 */
|
|
17
|
+
export declare function applyAnthropicUsage(usage: Usage, raw: Json | undefined): void;
|
|
18
|
+
type MappedStop = {
|
|
19
|
+
reason: "stop" | "length" | "toolUse";
|
|
20
|
+
} | {
|
|
21
|
+
reason: "error";
|
|
22
|
+
message: string;
|
|
23
|
+
};
|
|
24
|
+
export declare function mapAnthropicStop(raw: string, details?: Json): MappedStop;
|
|
25
|
+
export declare const anthropicMessagesApi: ApiImplementation<AnthropicMessagesCompat>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* anthropic-messages 协议(设计 §3.1):POST `{baseUrl}/v1/messages`(stream;baseUrl 已以 `/v1`
|
|
3
|
+
* 结尾时不重复),SSE → 事件。
|
|
4
|
+
*
|
|
5
|
+
* SSE 事件:message_start(id、初始 usage)→ content_block_start / delta / stop(text、
|
|
6
|
+
* thinking + signature_delta、redacted_thinking、tool_use + input_json_delta)→ message_delta
|
|
7
|
+
* (stop_reason、累计 usage)→ message_stop。`event: error` 或缺 message_stop 都编码为 error。
|
|
8
|
+
*
|
|
9
|
+
* usage:`input_tokens` 本就不含缓存;`cache_read_input_tokens` → cacheRead,
|
|
10
|
+
* `cache_creation_input_tokens` → cacheWrite,`cache_creation.ephemeral_1h_input_tokens` →
|
|
11
|
+
* cacheWrite1h。message_delta 只覆盖非 null 字段(部分代理在 delta 里省略 input)。两个缓存字段
|
|
12
|
+
* 任一出现过(含 0)即 `cacheReported: true`,之后的事件不会把它改回 false。
|
|
13
|
+
*/
|
|
14
|
+
import { AssistantEventStreamImpl } from "../event-stream.js";
|
|
15
|
+
import { USER_AGENT, authHeaders, describeErrorJson, mergeHeaders } from "../http.js";
|
|
16
|
+
import { readSseEvents } from "../sse.js";
|
|
17
|
+
import { postWithCacheFallback } from "./cache-params.js";
|
|
18
|
+
import { ANTHROPIC_VERSION, anthropicMessagesUrl, buildAnthropicRequest, detectAnthropicCompat, } from "./anthropic-request.js";
|
|
19
|
+
import { BlockTracker, STREAM_ENDED_MESSAGE, ProviderStopError, createOutput, finishDone, finishError, requireApiKey, } from "./shared.js";
|
|
20
|
+
function num(value) {
|
|
21
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
22
|
+
}
|
|
23
|
+
function obj(value) {
|
|
24
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
25
|
+
? value
|
|
26
|
+
: undefined;
|
|
27
|
+
}
|
|
28
|
+
function str(value) {
|
|
29
|
+
return typeof value === "string" ? value : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** 把 Anthropic usage 字段写进 Usage(只覆盖出现且非 null 的字段)。 */
|
|
32
|
+
export function applyAnthropicUsage(usage, raw) {
|
|
33
|
+
if (!raw)
|
|
34
|
+
return;
|
|
35
|
+
const input = num(raw["input_tokens"]);
|
|
36
|
+
const output = num(raw["output_tokens"]);
|
|
37
|
+
const cacheRead = num(raw["cache_read_input_tokens"]);
|
|
38
|
+
const cacheWrite = num(raw["cache_creation_input_tokens"]);
|
|
39
|
+
const longWrite = num(obj(raw["cache_creation"])?.["ephemeral_1h_input_tokens"]);
|
|
40
|
+
const reasoning = num(obj(raw["output_tokens_details"])?.["thinking_tokens"]);
|
|
41
|
+
if (input !== undefined)
|
|
42
|
+
usage.input = input;
|
|
43
|
+
if (output !== undefined)
|
|
44
|
+
usage.output = output;
|
|
45
|
+
if (cacheRead !== undefined)
|
|
46
|
+
usage.cacheRead = cacheRead;
|
|
47
|
+
if (cacheWrite !== undefined)
|
|
48
|
+
usage.cacheWrite = cacheWrite;
|
|
49
|
+
if (cacheRead !== undefined || cacheWrite !== undefined)
|
|
50
|
+
usage.cacheReported = true;
|
|
51
|
+
else
|
|
52
|
+
usage.cacheReported ??= false;
|
|
53
|
+
if (longWrite !== undefined)
|
|
54
|
+
usage.cacheWrite1h = longWrite;
|
|
55
|
+
if (reasoning !== undefined)
|
|
56
|
+
usage.reasoning = reasoning;
|
|
57
|
+
}
|
|
58
|
+
export function mapAnthropicStop(raw, details) {
|
|
59
|
+
switch (raw) {
|
|
60
|
+
case "end_turn":
|
|
61
|
+
case "stop_sequence":
|
|
62
|
+
case "pause_turn":
|
|
63
|
+
return { reason: "stop" };
|
|
64
|
+
case "max_tokens":
|
|
65
|
+
return { reason: "length" };
|
|
66
|
+
case "tool_use":
|
|
67
|
+
return { reason: "toolUse" };
|
|
68
|
+
case "refusal":
|
|
69
|
+
return {
|
|
70
|
+
reason: "error",
|
|
71
|
+
message: str(details?.["explanation"]) ?? "The model refused to respond (refusal)",
|
|
72
|
+
};
|
|
73
|
+
case "model_context_window_exceeded":
|
|
74
|
+
return { reason: "error", message: "model_context_window_exceeded: prompt is too long" };
|
|
75
|
+
default:
|
|
76
|
+
return { reason: "stop" };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function buildHeaders(model, options, betas) {
|
|
80
|
+
return mergeHeaders({
|
|
81
|
+
"content-type": "application/json",
|
|
82
|
+
accept: "text/event-stream",
|
|
83
|
+
"anthropic-version": ANTHROPIC_VERSION,
|
|
84
|
+
"user-agent": USER_AGENT,
|
|
85
|
+
...(betas.length > 0 ? { "anthropic-beta": betas.join(",") } : {}),
|
|
86
|
+
}, authHeaders(options.apiKey, model.authHeader, "x-api-key"), model.headers, options.headers);
|
|
87
|
+
}
|
|
88
|
+
function handleEvent(data, state, tracker) {
|
|
89
|
+
const output = tracker.output;
|
|
90
|
+
const type = str(data["type"]);
|
|
91
|
+
if (type === "message_start") {
|
|
92
|
+
const message = obj(data["message"]);
|
|
93
|
+
const id = str(message?.["id"]);
|
|
94
|
+
if (id)
|
|
95
|
+
output.responseId = id;
|
|
96
|
+
applyAnthropicUsage(output.usage, obj(message?.["usage"]));
|
|
97
|
+
}
|
|
98
|
+
else if (type === "content_block_start") {
|
|
99
|
+
const index = num(data["index"]) ?? state.blocks.size;
|
|
100
|
+
const block = obj(data["content_block"]);
|
|
101
|
+
const kind = str(block?.["type"]);
|
|
102
|
+
if (kind === "text") {
|
|
103
|
+
state.blocks.set(index, tracker.startText(str(block?.["text"]) ?? ""));
|
|
104
|
+
}
|
|
105
|
+
else if (kind === "thinking") {
|
|
106
|
+
const signature = str(block?.["signature"]);
|
|
107
|
+
state.blocks.set(index, tracker.startThinking(str(block?.["thinking"]) ?? "", signature));
|
|
108
|
+
}
|
|
109
|
+
else if (kind === "redacted_thinking") {
|
|
110
|
+
const data = str(block?.["data"]) ?? "";
|
|
111
|
+
state.blocks.set(index, tracker.startThinking("[redacted]", data, true));
|
|
112
|
+
}
|
|
113
|
+
else if (kind === "tool_use") {
|
|
114
|
+
const input = obj(block?.["input"]) ?? {};
|
|
115
|
+
const id = str(block?.["id"]) ?? `toolu_${index}`;
|
|
116
|
+
state.blocks.set(index, tracker.startToolCall(id, str(block?.["name"]) ?? "", input));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else if (type === "content_block_delta") {
|
|
120
|
+
const target = state.blocks.get(num(data["index"]) ?? -1);
|
|
121
|
+
const delta = obj(data["delta"]);
|
|
122
|
+
if (target === undefined || !delta)
|
|
123
|
+
return;
|
|
124
|
+
const kind = str(delta["type"]);
|
|
125
|
+
if (kind === "text_delta")
|
|
126
|
+
tracker.appendText(target, str(delta["text"]) ?? "");
|
|
127
|
+
else if (kind === "thinking_delta")
|
|
128
|
+
tracker.appendThinking(target, str(delta["thinking"]) ?? "");
|
|
129
|
+
else if (kind === "signature_delta")
|
|
130
|
+
tracker.appendSignature(target, str(delta["signature"]) ?? "");
|
|
131
|
+
else if (kind === "input_json_delta")
|
|
132
|
+
tracker.appendToolArgs(target, str(delta["partial_json"]) ?? "");
|
|
133
|
+
}
|
|
134
|
+
else if (type === "content_block_stop") {
|
|
135
|
+
const target = state.blocks.get(num(data["index"]) ?? -1);
|
|
136
|
+
if (target !== undefined)
|
|
137
|
+
tracker.end(target);
|
|
138
|
+
}
|
|
139
|
+
else if (type === "message_delta") {
|
|
140
|
+
const delta = obj(data["delta"]);
|
|
141
|
+
const raw = str(delta?.["stop_reason"]);
|
|
142
|
+
if (raw) {
|
|
143
|
+
output.rawStopReason = raw;
|
|
144
|
+
state.stop = mapAnthropicStop(raw, obj(delta?.["stop_details"]));
|
|
145
|
+
}
|
|
146
|
+
applyAnthropicUsage(output.usage, obj(data["usage"]));
|
|
147
|
+
}
|
|
148
|
+
else if (type === "message_stop") {
|
|
149
|
+
state.sawMessageStop = true;
|
|
150
|
+
}
|
|
151
|
+
else if (type === "error") {
|
|
152
|
+
throw new Error(describeErrorJson(data) ?? JSON.stringify(data));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async function run(stream, model, context, options) {
|
|
156
|
+
const tracker = new BlockTracker(stream, createOutput(model));
|
|
157
|
+
try {
|
|
158
|
+
const request = buildAnthropicRequest(model, context, options);
|
|
159
|
+
tracker.output.thinkingLevel = request.thinkingLevel;
|
|
160
|
+
if (request.providerThinkingLevel !== undefined) {
|
|
161
|
+
tracker.output.providerThinkingLevel = request.providerThinkingLevel;
|
|
162
|
+
}
|
|
163
|
+
const replaced = options.onPayload?.(request.body);
|
|
164
|
+
const body = replaced === undefined ? request.body : replaced;
|
|
165
|
+
const baseUrl = model.baseUrl ?? "https://api.anthropic.com";
|
|
166
|
+
const response = await postWithCacheFallback(model, anthropicMessagesUrl(baseUrl), {
|
|
167
|
+
headers: buildHeaders(model, options, request.betas),
|
|
168
|
+
body,
|
|
169
|
+
signal: options.signal,
|
|
170
|
+
timeoutMs: options.timeoutMs,
|
|
171
|
+
onResponse: options.onResponse,
|
|
172
|
+
});
|
|
173
|
+
stream.push({ type: "start", partial: tracker.output });
|
|
174
|
+
const state = { blocks: new Map(), stop: undefined, sawMessageStop: false };
|
|
175
|
+
for await (const sse of readSseEvents(response.body, options.signal)) {
|
|
176
|
+
if (sse.event === "ping" || sse.data === "")
|
|
177
|
+
continue;
|
|
178
|
+
let data;
|
|
179
|
+
try {
|
|
180
|
+
data = obj(JSON.parse(sse.data)) ?? {};
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
throw new Error(`Malformed SSE data (${sse.event ?? "message"}): ${sse.data.slice(0, 200)}`);
|
|
184
|
+
}
|
|
185
|
+
if (sse.event === "error" && data["type"] !== "error")
|
|
186
|
+
data = { type: "error", error: data };
|
|
187
|
+
handleEvent(data, state, tracker);
|
|
188
|
+
if (state.sawMessageStop)
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
if (options.signal.aborted)
|
|
192
|
+
throw new Error("aborted");
|
|
193
|
+
if (!state.sawMessageStop)
|
|
194
|
+
throw new Error(STREAM_ENDED_MESSAGE);
|
|
195
|
+
const stop = state.stop ?? { reason: tracker.hasToolCalls ? "toolUse" : "stop" };
|
|
196
|
+
if (stop.reason === "error")
|
|
197
|
+
throw new ProviderStopError(stop.message);
|
|
198
|
+
finishDone(stream, tracker, model, stop.reason);
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
finishError(stream, tracker, model, error, options.signal);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function stream(model, context, options) {
|
|
205
|
+
requireApiKey(model, options);
|
|
206
|
+
const events = new AssistantEventStreamImpl();
|
|
207
|
+
void run(events, model, context, options).finally(() => events.end());
|
|
208
|
+
return events;
|
|
209
|
+
}
|
|
210
|
+
export const anthropicMessagesApi = {
|
|
211
|
+
id: "anthropic-messages",
|
|
212
|
+
stream,
|
|
213
|
+
detectCompat: detectAnthropicCompat,
|
|
214
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* anthropic-messages 请求体(设计 §3.1、§3.3、§3.6):消息转换、三断点缓存、thinking、工具。
|
|
3
|
+
*
|
|
4
|
+
* 缓存断点(cacheRetention 缺省 short,未指定时读 `AMA_CACHE_RETENTION`;none 不打;long 加
|
|
5
|
+
* `ttl: "1h"`,仅 `supportsLongCacheRetention`——官方端点缺省开,中转缺省关、降为 short;最后做 TTL
|
|
6
|
+
* 顺序校验,5m 之后出现 1h 则全部降为 5m)按优先级取前
|
|
7
|
+
* `maxCacheBreakpoints` 个:① 最后一条 user 消息(含工具结果)的最后一个块 ② system 末块
|
|
8
|
+
* ③ 最后一个工具定义(`supportsCacheControlOnTools`)。
|
|
9
|
+
*
|
|
10
|
+
* thinking:`adaptiveThinking` 模型发 `{type:"adaptive"}` + `output_config.effort`;
|
|
11
|
+
* 其余推理模型按预算发 `{type:"enabled", budget_tokens}`,预算计入 max_tokens;off 发
|
|
12
|
+
* `{type:"disabled"}`(映射表 off 为 null 的模型不发)。思考开启时不发 temperature,
|
|
13
|
+
* 除非 `supportsTemperatureWithThinking`。`toolChoice: "none"`(有工具时)→ `tool_choice:{type:"none"}`。
|
|
14
|
+
*/
|
|
15
|
+
import type { AnthropicMessagesCompat, AssistantMessage, Model, ModelThinkingLevel, ProviderData, StreamOptions, ToolResultMessage, TranscriptContext, UserMessage } from "../types.js";
|
|
16
|
+
export declare const ANTHROPIC_VERSION = "2023-06-01";
|
|
17
|
+
export declare const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
18
|
+
export declare const DEFAULT_ANTHROPIC_COMPAT: Readonly<AnthropicMessagesCompat>;
|
|
19
|
+
export declare function detectAnthropicCompat(model: Model, provider?: ProviderData): AnthropicMessagesCompat;
|
|
20
|
+
type Json = Record<string, unknown>;
|
|
21
|
+
export interface AnthropicRequest {
|
|
22
|
+
body: Json;
|
|
23
|
+
betas: string[];
|
|
24
|
+
thinkingLevel: ModelThinkingLevel;
|
|
25
|
+
providerThinkingLevel: string | undefined;
|
|
26
|
+
}
|
|
27
|
+
export declare function cacheControlFor(retention: StreamOptions["cacheRetention"]): {
|
|
28
|
+
type: "ephemeral";
|
|
29
|
+
ttl?: "1h";
|
|
30
|
+
} | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* TTL 顺序校验:Anthropic 按 tools → system → messages 的顺序处理断点,要求 1h 条目都在 5m 之前。
|
|
33
|
+
* 出现「5m 之后的 1h」→ 全部降为 5m(去掉 ttl)。返回是否做了降级。
|
|
34
|
+
*/
|
|
35
|
+
export declare function enforceCacheTtlOrder(body: Json): boolean;
|
|
36
|
+
/** `{baseUrl}/v1/messages`;baseUrl 已以 `/v1` 结尾(中转常见写法)时不再重复。 */
|
|
37
|
+
export declare function anthropicMessagesUrl(baseUrl: string): string;
|
|
38
|
+
/** Anthropic 要求 tool_use id 匹配 `^[a-zA-Z0-9_-]+$` 且 ≤ 64。 */
|
|
39
|
+
export declare function normalizeToolId(id: string): string;
|
|
40
|
+
export declare function convertMessages(messages: readonly (UserMessage | AssistantMessage | ToolResultMessage)[]): Json[];
|
|
41
|
+
export declare function buildAnthropicRequest(model: Model, context: TranscriptContext, options: StreamOptions): AnthropicRequest;
|
|
42
|
+
export {};
|