@jini-ai/agent-runtime 0.7.1 → 0.7.3-next.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 +3 -3
- package/README.md +1 -0
- package/dist/acp-model-probe.d.ts +2 -3
- package/dist/acp-model-probe.js +1 -1
- package/dist/agent-protocol/acp/account-failure.d.ts +3 -1
- package/dist/agent-protocol/acp/account-failure.js +1 -1
- package/dist/agent-protocol/acp/constants.d.ts +3 -1
- package/dist/agent-protocol/acp/constants.js +2 -0
- package/dist/agent-protocol/acp/index.d.ts +2 -1
- package/dist/agent-protocol/acp/index.js +2 -1
- package/dist/agent-protocol/acp/json.d.ts +26 -7
- package/dist/agent-protocol/acp/json.js +11 -11
- package/dist/agent-protocol/acp/models.d.ts +26 -6
- package/dist/agent-protocol/acp/models.js +157 -129
- package/dist/agent-protocol/acp/rpc.d.ts +37 -9
- package/dist/agent-protocol/acp/rpc.js +19 -16
- package/dist/agent-protocol/acp/session-params.d.ts +4 -1
- package/dist/agent-protocol/acp/session-params.js +1 -1
- package/dist/agent-protocol/acp/session-permission.d.ts +13 -0
- package/dist/agent-protocol/acp/session-permission.js +110 -0
- package/dist/agent-protocol/acp/session-results.d.ts +61 -0
- package/dist/agent-protocol/acp/session-results.js +226 -0
- package/dist/agent-protocol/acp/session-run.d.ts +92 -0
- package/dist/agent-protocol/acp/session-run.js +555 -0
- package/dist/agent-protocol/acp/session-state.d.ts +9 -0
- package/dist/agent-protocol/acp/session-state.js +29 -0
- package/dist/agent-protocol/acp/session-text-updates.d.ts +56 -0
- package/dist/agent-protocol/acp/session-text-updates.js +119 -0
- package/dist/agent-protocol/acp/session-tool-updates.d.ts +21 -0
- package/dist/agent-protocol/acp/session-tool-updates.js +90 -0
- package/dist/agent-protocol/acp/session-types.d.ts +166 -0
- package/dist/agent-protocol/acp/session-types.js +4 -0
- package/dist/agent-protocol/acp/session.d.ts +4 -280
- package/dist/agent-protocol/acp/session.js +65 -998
- package/dist/agent-protocol/acp/text-suppression.d.ts +5 -1
- package/dist/agent-protocol/acp/text-suppression.js +1 -1
- package/dist/agent-protocol/acp/updates.d.ts +43 -12
- package/dist/agent-protocol/acp/updates.js +34 -34
- package/dist/agent-protocol/core/json-line-stream.d.ts +133 -36
- package/dist/agent-protocol/core/json-line-stream.js +62 -62
- package/dist/agent-protocol/pi-rpc/events.d.ts +14 -4
- package/dist/agent-protocol/pi-rpc/events.js +14 -14
- package/dist/agent-protocol/pi-rpc/internal.d.ts +9 -3
- package/dist/agent-protocol/pi-rpc/internal.js +3 -3
- package/dist/agent-protocol/pi-rpc/models.d.ts +3 -17
- package/dist/agent-protocol/pi-rpc/models.js +1 -45
- package/dist/agent-protocol/pi-rpc/session.d.ts +36 -12
- package/dist/agent-protocol/pi-rpc/session.js +134 -122
- package/dist/amr-model-cache.d.ts +1 -1
- package/dist/anthropic-live-models.d.ts +8 -3
- package/dist/anthropic-live-models.js +0 -0
- package/dist/auth-common.d.ts +2 -0
- package/dist/auth-common.js +2 -0
- package/dist/auth.d.ts +7 -34
- package/dist/auth.js +25 -139
- package/dist/capabilities.d.ts +1 -1
- package/dist/claude-code-models.d.ts +13 -5
- package/dist/claude-code-models.js +12 -10
- package/dist/claude-filesystem-policy.d.ts +1 -1
- package/dist/claude-stream-frames.d.ts +125 -0
- package/dist/claude-stream-frames.js +327 -0
- package/dist/claude-stream-handler.d.ts +19 -0
- package/dist/claude-stream-handler.js +480 -0
- package/dist/claude-stream.d.ts +3 -72
- package/dist/claude-stream.js +2 -801
- package/dist/core/model-discovery-shared.d.ts +14 -8
- package/dist/core/model-discovery-shared.js +6 -9
- package/dist/core/omit-keys.d.ts +4 -1
- package/dist/core/omit-keys.js +1 -1
- package/dist/defs/aider/executable.d.ts +2 -0
- package/dist/defs/aider/executable.js +2 -0
- package/dist/defs/aider/model-discovery.d.ts +3 -0
- package/dist/defs/aider/model-discovery.js +6 -0
- package/dist/defs/aider.d.ts +10 -10
- package/dist/defs/amp/index.d.ts +35 -0
- package/dist/defs/amp/index.js +75 -0
- package/dist/defs/amp.d.ts +1 -34
- package/dist/defs/amp.js +1 -74
- package/dist/defs/amr/executable-resolution.d.ts +7 -0
- package/dist/defs/amr/executable-resolution.js +50 -0
- package/dist/defs/amr/executable.d.ts +2 -0
- package/dist/defs/amr/executable.js +2 -0
- package/dist/defs/amr/index.d.ts +69 -0
- package/dist/defs/amr/index.js +279 -0
- package/dist/defs/amr/model-discovery.d.ts +3 -0
- package/dist/defs/amr/model-discovery.js +4 -0
- package/dist/defs/amr.d.ts +1 -68
- package/dist/defs/amr.js +1 -291
- package/dist/defs/antigravity/auth.d.ts +14 -0
- package/dist/defs/antigravity/auth.js +47 -0
- package/dist/defs/antigravity/index.d.ts +9 -9
- package/dist/defs/antigravity/index.js +3 -3
- package/dist/defs/antigravity/model-discovery.d.ts +3 -0
- package/dist/defs/antigravity/model-discovery.js +5 -0
- package/dist/defs/auggie/executable.d.ts +2 -0
- package/dist/defs/auggie/executable.js +2 -0
- package/dist/defs/auggie.d.ts +13 -13
- package/dist/defs/auggie.js +2 -9
- package/dist/defs/claude/auth.d.ts +15 -0
- package/dist/defs/claude/auth.js +47 -0
- package/dist/defs/claude/executable.d.ts +2 -0
- package/dist/defs/claude/executable.js +2 -0
- package/dist/defs/claude/model-discovery.d.ts +3 -0
- package/dist/defs/claude/model-discovery.js +20 -0
- package/dist/defs/claude-compatible-args.d.ts +10 -6
- package/dist/defs/claude-compatible-args.js +5 -5
- package/dist/defs/claude.d.ts +11 -11
- package/dist/defs/claude.js +5 -4
- package/dist/defs/cline/executable.d.ts +2 -0
- package/dist/defs/cline/executable.js +2 -0
- package/dist/defs/cline.d.ts +13 -13
- package/dist/defs/cline.js +2 -9
- package/dist/defs/codebuddy/executable.d.ts +2 -0
- package/dist/defs/codebuddy/executable.js +2 -0
- package/dist/defs/codebuddy/index.d.ts +48 -0
- package/dist/defs/codebuddy/index.js +121 -0
- package/dist/defs/codebuddy/model-discovery.d.ts +3 -0
- package/dist/defs/codebuddy/model-discovery.js +5 -0
- package/dist/defs/codebuddy.d.ts +1 -47
- package/dist/defs/codebuddy.js +1 -120
- package/dist/defs/codex/auth.d.ts +4 -0
- package/dist/defs/codex/auth.js +2 -0
- package/dist/defs/codex/event-stream.d.ts +10 -0
- package/dist/defs/codex/event-stream.js +353 -0
- package/dist/defs/codex/executable-resolution.d.ts +7 -0
- package/dist/defs/codex/executable-resolution.js +37 -0
- package/dist/defs/codex/executable.d.ts +2 -0
- package/dist/defs/codex/executable.js +2 -0
- package/dist/defs/codex/launch.d.ts +3 -0
- package/dist/defs/codex/launch.js +155 -0
- package/dist/defs/codex/model-discovery.d.ts +3 -0
- package/dist/defs/codex/model-discovery.js +11 -0
- package/dist/defs/codex/options.d.ts +11 -0
- package/dist/defs/codex/options.js +5 -0
- package/dist/defs/codex.d.ts +18 -11
- package/dist/defs/codex.js +32 -29
- package/dist/defs/crush/executable.d.ts +2 -0
- package/dist/defs/crush/executable.js +2 -0
- package/dist/defs/crush/model-discovery.d.ts +3 -0
- package/dist/defs/crush/model-discovery.js +6 -0
- package/dist/defs/crush.d.ts +10 -10
- package/dist/defs/cursor-agent/auth.d.ts +13 -0
- package/dist/defs/cursor-agent/auth.js +22 -0
- package/dist/defs/cursor-agent/event-stream.d.ts +8 -0
- package/dist/defs/cursor-agent/event-stream.js +104 -0
- package/dist/defs/cursor-agent/executable.d.ts +2 -0
- package/dist/defs/cursor-agent/executable.js +2 -0
- package/dist/defs/cursor-agent/model-discovery.d.ts +3 -0
- package/dist/defs/cursor-agent/model-discovery.js +5 -0
- package/dist/defs/cursor-agent.d.ts +11 -13
- package/dist/defs/cursor-agent.js +1 -1
- package/dist/defs/deepseek/auth.d.ts +13 -0
- package/dist/defs/deepseek/auth.js +18 -0
- package/dist/defs/deepseek/executable.d.ts +2 -0
- package/dist/defs/deepseek/executable.js +2 -0
- package/dist/defs/deepseek/model-discovery.d.ts +3 -0
- package/dist/defs/deepseek/model-discovery.js +5 -0
- package/dist/defs/deepseek.d.ts +10 -10
- package/dist/defs/devin/executable.d.ts +2 -0
- package/dist/defs/devin/executable.js +2 -0
- package/dist/defs/devin.d.ts +15 -15
- package/dist/defs/devin.js +3 -10
- package/dist/defs/droid/executable.d.ts +2 -0
- package/dist/defs/droid/executable.js +2 -0
- package/dist/defs/droid/model-discovery.d.ts +3 -0
- package/dist/defs/droid/model-discovery.js +5 -0
- package/dist/defs/droid.d.ts +10 -10
- package/dist/defs/gemini/event-stream.d.ts +14 -0
- package/dist/defs/gemini/event-stream.js +193 -0
- package/dist/defs/goose/executable.d.ts +2 -0
- package/dist/defs/goose/executable.js +2 -0
- package/dist/defs/goose.d.ts +13 -13
- package/dist/defs/goose.js +2 -9
- package/dist/defs/grok-build/model-discovery.d.ts +3 -0
- package/dist/defs/grok-build/model-discovery.js +5 -0
- package/dist/defs/grok-build.d.ts +10 -10
- package/dist/defs/hermes/executable.d.ts +2 -0
- package/dist/defs/hermes/executable.js +2 -0
- package/dist/defs/hermes/index.d.ts +34 -0
- package/dist/defs/hermes/index.js +57 -0
- package/dist/defs/hermes.d.ts +1 -33
- package/dist/defs/hermes.js +1 -56
- package/dist/defs/index.d.ts +1 -0
- package/dist/defs/index.js +1 -0
- package/dist/defs/kilo/executable.d.ts +2 -0
- package/dist/defs/kilo/executable.js +2 -0
- package/dist/defs/kilo.d.ts +13 -13
- package/dist/defs/kilo.js +2 -9
- package/dist/defs/kimi/event-stream.d.ts +3 -0
- package/dist/defs/kimi/event-stream.js +46 -0
- package/dist/defs/kimi/executable.d.ts +2 -0
- package/dist/defs/kimi/executable.js +2 -0
- package/dist/defs/kimi.d.ts +13 -13
- package/dist/defs/kimi.js +2 -9
- package/dist/defs/kiro/executable.d.ts +2 -0
- package/dist/defs/kiro/executable.js +2 -0
- package/dist/defs/kiro.d.ts +13 -13
- package/dist/defs/kiro.js +2 -9
- package/dist/defs/mimo/executable.d.ts +2 -0
- package/dist/defs/mimo/executable.js +2 -0
- package/dist/defs/mimo/model-discovery.d.ts +3 -0
- package/dist/defs/mimo/model-discovery.js +7 -0
- package/dist/defs/mimo.d.ts +10 -10
- package/dist/defs/opencode/event-stream.d.ts +8 -0
- package/dist/defs/opencode/event-stream.js +108 -0
- package/dist/defs/opencode/executable.d.ts +2 -0
- package/dist/defs/opencode/executable.js +2 -0
- package/dist/defs/opencode/model-discovery.d.ts +4 -0
- package/dist/defs/opencode/model-discovery.js +14 -0
- package/dist/defs/opencode-acp.d.ts +42 -0
- package/dist/defs/opencode-acp.js +23 -0
- package/dist/defs/opencode.d.ts +9 -9
- package/dist/defs/pi/executable.d.ts +2 -0
- package/dist/defs/pi/executable.js +2 -0
- package/dist/defs/pi/model-discovery.d.ts +4 -0
- package/dist/defs/pi/model-discovery.js +16 -0
- package/dist/defs/pi/options.d.ts +11 -0
- package/dist/defs/pi/options.js +5 -0
- package/dist/defs/pi.d.ts +10 -10
- package/dist/defs/qoder/executable.d.ts +2 -0
- package/dist/defs/qoder/executable.js +2 -0
- package/dist/defs/qoder/model-discovery.d.ts +3 -0
- package/dist/defs/qoder/model-discovery.js +7 -0
- package/dist/defs/qoder.d.ts +9 -9
- package/dist/defs/qwen/executable.d.ts +2 -0
- package/dist/defs/qwen/executable.js +2 -0
- package/dist/defs/qwen/model-discovery.d.ts +3 -0
- package/dist/defs/qwen/model-discovery.js +7 -0
- package/dist/defs/qwen.d.ts +10 -10
- package/dist/defs/reasonix/auth.d.ts +13 -0
- package/dist/defs/reasonix/auth.js +18 -0
- package/dist/defs/reasonix/executable.d.ts +2 -0
- package/dist/defs/reasonix/executable.js +2 -0
- package/dist/defs/reasonix.d.ts +13 -13
- package/dist/defs/reasonix.js +2 -9
- package/dist/defs/shared.d.ts +10 -2
- package/dist/defs/shared.js +5 -1
- package/dist/defs/trae-cli/executable.d.ts +2 -0
- package/dist/defs/trae-cli/executable.js +2 -0
- package/dist/defs/trae-cli.d.ts +15 -15
- package/dist/defs/trae-cli.js +2 -9
- package/dist/defs/vibe/executable.d.ts +2 -0
- package/dist/defs/vibe/executable.js +2 -0
- package/dist/defs/vibe.d.ts +13 -13
- package/dist/defs/vibe.js +2 -9
- package/dist/detection.d.ts +4 -3
- package/dist/detection.js +22 -22
- package/dist/diagnostics.d.ts +4 -4
- package/dist/diagnostics.js +2 -2
- package/dist/env.js +2 -1
- package/dist/executable-helpers.d.ts +21 -0
- package/dist/executable-helpers.js +2 -0
- package/dist/executables.d.ts +2 -2
- package/dist/executables.js +68 -114
- package/dist/index.d.ts +6 -2
- package/dist/index.js +5 -1
- package/dist/invocation.d.ts +22 -6
- package/dist/invocation.js +19 -17
- package/dist/json-event-stream-shared.d.ts +81 -0
- package/dist/json-event-stream-shared.js +147 -0
- package/dist/json-event-stream.d.ts +2 -4
- package/dist/json-event-stream.js +15 -940
- package/dist/launch.d.ts +1 -9
- package/dist/launch.js +6 -155
- package/dist/log-file.d.ts +2 -8
- package/dist/log-file.js +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +1 -1
- package/dist/mmd-routes.d.ts +7 -7
- package/dist/mmd-routes.js +19 -27
- package/dist/model-discovery-adapters.d.ts +47 -11
- package/dist/model-discovery-adapters.js +47 -41
- package/dist/model-discovery-config-types.d.ts +44 -0
- package/dist/model-discovery-config-types.js +20 -0
- package/dist/model-discovery-config.d.ts +19 -11
- package/dist/model-discovery-config.js +64 -87
- package/dist/model-discovery-native.d.ts +2 -1
- package/dist/model-discovery-native.js +3 -3
- package/dist/model-discovery-sdk.d.ts +6 -2
- package/dist/model-discovery-sdk.js +2 -2
- package/dist/model-discovery-types.d.ts +1 -138
- package/dist/model-discovery-yaml.d.ts +3 -1
- package/dist/model-discovery-yaml.js +1 -1
- package/dist/model-discovery.d.ts +15 -5
- package/dist/model-discovery.js +119 -105
- package/dist/model-loading-state.d.ts +1 -1
- package/dist/model-loading-state.js +1 -1
- package/dist/model-registry.d.ts +5 -5
- package/dist/model-registry.js +7 -6
- package/dist/models.d.ts +4 -3
- package/dist/models.js +2 -2
- package/dist/native-permissions.d.ts +47 -0
- package/dist/native-permissions.js +80 -0
- package/dist/native-runtime.d.ts +11 -8
- package/dist/native-runtime.js +8 -4
- package/dist/native-tool-policy.d.ts +1 -40
- package/dist/opencode-log.d.ts +3 -3
- package/dist/opencode-log.js +5 -3
- package/dist/paths.d.ts +1 -1
- package/dist/paths.js +1 -1
- package/dist/pi-models.d.ts +12 -2
- package/dist/pi-models.js +11 -1
- package/dist/prompt-augmenter.d.ts +1 -37
- package/dist/prompt-augmenter.js +0 -6
- package/dist/prompt-budget.d.ts +3 -3
- package/dist/prompt-budget.js +2 -2
- package/dist/prompt-file.d.ts +2 -6
- package/dist/prompt-file.js +1 -1
- package/dist/providers/aihubmix.d.ts +8 -8
- package/dist/providers/aihubmix.js +8 -8
- package/dist/providers/anthropic-messages.d.ts +22 -23
- package/dist/providers/anthropic-messages.js +26 -53
- package/dist/providers/azure-chat.d.ts +7 -6
- package/dist/providers/azure-chat.js +9 -6
- package/dist/providers/connection-guard.d.ts +3 -9
- package/dist/providers/connection-guard.js +6 -14
- package/dist/providers/connection-test.d.ts +1 -2
- package/dist/providers/connection-test.js +51 -51
- package/dist/providers/credentials.d.ts +59 -0
- package/dist/providers/credentials.js +80 -0
- package/dist/providers/elevenlabs.d.ts +2 -6
- package/dist/providers/elevenlabs.js +2 -31
- package/dist/providers/google-messages.d.ts +11 -10
- package/dist/providers/google-messages.js +16 -35
- package/dist/providers/google-schema.d.ts +1 -1
- package/dist/providers/google-schema.js +1 -1
- package/dist/providers/google.d.ts +6 -6
- package/dist/providers/google.js +6 -6
- package/dist/providers/index.d.ts +5 -2
- package/dist/providers/index.js +5 -2
- package/dist/providers/model-catalog.d.ts +4 -9
- package/dist/providers/model-catalog.js +3 -11
- package/dist/providers/oauth-callback-server.js +93 -87
- package/dist/providers/oauth-provider.d.ts +1 -1
- package/dist/providers/oauth-provider.js +1 -1
- package/dist/providers/oauth-tokens.d.ts +5 -5
- package/dist/providers/oauth-tokens.js +8 -9
- package/dist/providers/ollama-chat.d.ts +13 -12
- package/dist/providers/ollama-chat.js +15 -24
- package/dist/providers/openai-chat-request.d.ts +34 -0
- package/dist/providers/openai-chat-request.js +152 -0
- package/dist/providers/openai-chat-stream.d.ts +48 -0
- package/dist/providers/openai-chat-stream.js +89 -0
- package/dist/providers/openai-chat-tool-results.d.ts +81 -0
- package/dist/providers/openai-chat-tool-results.js +124 -0
- package/dist/providers/openai-chat-types.d.ts +180 -0
- package/dist/providers/openai-chat-types.js +3 -0
- package/dist/providers/openai-chat.d.ts +5 -405
- package/dist/providers/openai-chat.js +9 -388
- package/dist/providers/pkce.d.ts +1 -1
- package/dist/providers/pkce.js +1 -1
- package/dist/providers/provider-url.d.ts +6 -0
- package/dist/providers/provider-url.js +9 -0
- package/dist/providers/response-text.d.ts +4 -0
- package/dist/providers/response-text.js +16 -0
- package/dist/providers/sse-decode.d.ts +4 -0
- package/dist/providers/sse-decode.js +11 -0
- package/dist/providers/token-params.d.ts +5 -5
- package/dist/providers/token-params.js +5 -5
- package/dist/providers/tool-loop-verdict.d.ts +1 -1
- package/dist/providers/tool-loop-verdict.js +1 -1
- package/dist/providers/tool-turn-types.d.ts +2 -1
- package/dist/providers/tool-turn.js +30 -50
- package/dist/providers/turn-end-guard.d.ts +4 -1
- package/dist/providers/turn-end-guard.js +1 -1
- package/dist/qoder-stream.d.ts +1 -1
- package/dist/qoder-stream.js +1 -1
- package/dist/registry.d.ts +5 -5
- package/dist/registry.js +4 -4
- package/dist/role-marker-guard.d.ts +13 -1
- package/dist/role-marker-guard.js +15 -1
- package/dist/runtime-def-binding.d.ts +15 -0
- package/dist/runtime-def-binding.js +19 -0
- package/dist/runtime-port-bindings.d.ts +181 -0
- package/dist/runtime-port-bindings.js +95 -0
- package/dist/runtime-state.d.ts +2 -11
- package/dist/runtime-state.js +0 -13
- package/dist/types.d.ts +1 -454
- package/package.json +27 -15
- package/dist/ai-trace/capture.d.ts +0 -17
- package/dist/ai-trace/capture.js +0 -43
- package/dist/ai-trace/classify.d.ts +0 -12
- package/dist/ai-trace/classify.js +0 -16
- package/dist/ai-trace/index.d.ts +0 -13
- package/dist/ai-trace/index.js +0 -6
- package/dist/ai-trace/recorder.d.ts +0 -64
- package/dist/ai-trace/recorder.js +0 -258
- package/dist/ai-trace/sinks.d.ts +0 -51
- package/dist/ai-trace/sinks.js +0 -153
- package/dist/ai-trace/types.d.ts +0 -123
- package/dist/ai-trace/types.js +0 -17
- package/dist/ai-trace/usage.d.ts +0 -13
- package/dist/ai-trace/usage.js +0 -45
- package/dist/model-contracts.d.ts +0 -29
- package/dist/model-contracts.js +0 -2
- package/dist/providers/types.d.ts +0 -36
- package/dist/providers/types.js +0 -13
|
@@ -14,320 +14,29 @@
|
|
|
14
14
|
* re-exported from the package barrel — only `attachAcpSession` and the
|
|
15
15
|
* public types are part of this package's supported surface.
|
|
16
16
|
*/
|
|
17
|
-
import path from 'node:path';
|
|
18
|
-
import { createDsmlArtifactTextSuppressor, createToolCallTextSuppressor, } from './text-suppression.js';
|
|
19
17
|
import { createJsonLineStream } from '../core/index.js';
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
18
|
+
import { DEFAULT_STAGE_TIMEOUT_MS } from './constants.js';
|
|
19
|
+
import { asObject } from './json.js';
|
|
20
|
+
import { rpcErrorMessage, isJsonRpcId, sendRpcError } from './rpc.js';
|
|
21
|
+
import { promotedAmrRetryStatusPayload } from './updates.js';
|
|
22
|
+
import { currentModelFromSessionResult } from './models.js';
|
|
23
|
+
import { buildAcpEffects, buildAcpController, createAcpRun, failRun, resetStageTimer, sendInitialize, wireAcpProcessListeners } from './session-run.js';
|
|
24
|
+
import { replyPermission } from './session-permission.js';
|
|
26
25
|
import { noopAccountFailureClassifier } from './account-failure.js';
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
/** ACP `ToolKind` values; anything else is logged as `other`. */
|
|
32
|
-
const ACP_TOOL_KINDS = ['read', 'edit', 'delete', 'move', 'search', 'execute', 'think', 'fetch', 'switch_mode', 'other'];
|
|
33
|
-
/** Builds a fresh {@link AcpSessionState} with every field at its initial value. */
|
|
34
|
-
export function createAcpSessionState() {
|
|
35
|
-
return {
|
|
36
|
-
expectedId: 1,
|
|
37
|
-
nextId: 2,
|
|
38
|
-
promptRequestId: null,
|
|
39
|
-
setModelRequestId: null,
|
|
40
|
-
sessionId: null,
|
|
41
|
-
durableSessionId: null,
|
|
42
|
-
activeModel: null,
|
|
43
|
-
modelConfigId: null,
|
|
44
|
-
emittedThinkingStart: false,
|
|
45
|
-
emittedTextChunk: false,
|
|
46
|
-
emittedVisibleTextChunk: false,
|
|
47
|
-
emittedTextBuffer: '',
|
|
48
|
-
emittedToolCall: false,
|
|
49
|
-
emittedConcreteToolEvent: false,
|
|
50
|
-
dsmlArtifactSuppressor: null,
|
|
51
|
-
dsmlArtifactSuppressorLastSuppressedChars: 0,
|
|
52
|
-
dsmlArtifactSuppressorToolCallId: null,
|
|
53
|
-
dsmlArtifactSuppressorArmedAfterText: false,
|
|
54
|
-
dsmlArtifactSuppressorSawIncrementalProse: false,
|
|
55
|
-
acpArtifactWriteToolCallIds: new Set(),
|
|
56
|
-
acpArtifactRunEventState: new Map(),
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
/** The well-formed options of a permission request: a non-empty `optionId`
|
|
60
|
-
* and an ACP `PermissionOptionKind`; anything else offered is ignored. */
|
|
61
|
-
function offeredPermissionOptions(params) {
|
|
62
|
-
if (!Array.isArray(params?.options))
|
|
63
|
-
return [];
|
|
64
|
-
return params.options.filter((option) => {
|
|
65
|
-
const record = asObject(option);
|
|
66
|
-
return typeof record?.optionId === 'string' && record.optionId !== '' &&
|
|
67
|
-
typeof record.kind === 'string' && ACP_PERMISSION_OPTION_KINDS.includes(record.kind);
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
/** The tool call's ACP `ToolKind` for permission logging, `other` when absent or unknown. */
|
|
71
|
-
function permissionToolKind(toolCall) {
|
|
72
|
-
return typeof toolCall?.kind === 'string' && ACP_TOOL_KINDS.includes(toolCall.kind) ? toolCall.kind : 'other';
|
|
73
|
-
}
|
|
74
|
-
/** The permission decision used when no `onPermissionRequest` handler is
|
|
75
|
-
* injected: the option `choosePermissionOutcome` picks under the run's
|
|
76
|
-
* `permissionMode` / `cliParity`, or a cancellation when it picks none. */
|
|
77
|
-
function defaultPermissionDecision({ optionRecords }, { permissionMode, cliParity, } = {}) {
|
|
78
|
-
const optionId = choosePermissionOutcome(optionRecords, { ...(permissionMode ? { permissionMode } : {}), ...(cliParity ? { cliParity: true } : {}) });
|
|
79
|
-
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
|
|
80
|
-
}
|
|
81
|
-
/** `typeof value === 'string' ? value : null` as a named predicate — too trivial to export on its own. */
|
|
82
|
-
function asOptionalString(value) {
|
|
83
|
-
return typeof value === 'string' ? value : null;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Handles a JSON-RPC error frame from the agent.
|
|
87
|
-
*
|
|
88
|
-
* -32603 unexpected-id errors are cleanup noise. Expected-id model selection
|
|
89
|
-
* failures are recoverable; all other RPC errors are real protocol failures
|
|
90
|
-
* for initialize/session/new/session/prompt.
|
|
91
|
-
*/
|
|
92
|
-
export function handleRpcError({ state, effects, obj, error, rpcErr, }) {
|
|
93
|
-
if (isRecoverableModelSelectionError({ state, effects, obj, error })) {
|
|
94
|
-
effects.recoverFromModelSelectionError();
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
if (error?.code === -32603 && obj.id !== state.expectedId) {
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
failWithRpcError({ effects, obj, rpcErr });
|
|
101
|
-
}
|
|
102
|
-
/** True when `obj` is a recoverable error answering our own `session/set_model`
|
|
103
|
-
* request, sent before any prompt, for a run that asked for no specific model. */
|
|
104
|
-
function isRecoverableModelSelectionError({ state, effects, obj, error, }) {
|
|
105
|
-
const awaitingSetModel = obj.id === state.setModelRequestId && state.promptRequestId === null;
|
|
106
|
-
return awaitingSetModel && modelSelectionErrorIsRecoverable(error?.code) && (!effects.model || effects.model === 'default');
|
|
107
|
-
}
|
|
108
|
-
/** Fails the run for a real RPC error, promoting a known OpenCode session error
|
|
109
|
-
* payload when present and carrying the RPC `data` details and retryability. */
|
|
110
|
-
function failWithRpcError({ effects, obj, rpcErr, }) {
|
|
111
|
-
const details = rpcErrorData(obj);
|
|
112
|
-
const promotedPayload = promotedOpenCodeSessionErrorPayload(details, rpcErr);
|
|
113
|
-
if (promotedPayload) {
|
|
114
|
-
effects.failWithPayload(promotedPayload);
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
const retryable = rpcErrorRetryable(details);
|
|
118
|
-
effects.fail(rpcErr, {
|
|
119
|
-
details,
|
|
120
|
-
...(retryable === undefined ? {} : { retryable }),
|
|
121
|
-
});
|
|
122
|
-
}
|
|
26
|
+
import {} from './session-types.js';
|
|
27
|
+
import { handleThoughtChunkUpdate, handleMessageChunkUpdate } from './session-text-updates.js';
|
|
28
|
+
import { handleToolCallUpdate } from './session-tool-updates.js';
|
|
29
|
+
import { handleRpcError, routeResultById } from './session-results.js';
|
|
123
30
|
/** Promotes an AMR retry-status `session/update` into a structured account-failure error, if the classifier matches. Returns `true` when it did (and thus failed the session). */
|
|
124
|
-
export function tryPromoteAmrRetryStatus({ effects, update, }) {
|
|
125
|
-
const promotedPayload = promotedAmrRetryStatusPayload(update, effects.accountFailureClassifier);
|
|
31
|
+
export function tryPromoteAmrRetryStatus({ effects, update, }, _optional = {}) {
|
|
32
|
+
const promotedPayload = promotedAmrRetryStatusPayload({ update }, { classifier: effects.accountFailureClassifier });
|
|
126
33
|
if (!promotedPayload)
|
|
127
34
|
return false;
|
|
128
35
|
effects.failWithPayload(promotedPayload);
|
|
129
36
|
return true;
|
|
130
37
|
}
|
|
131
|
-
/** Translates an `agent_thought_chunk` update into `thinking_start` (once) / `thinking_delta` events. */
|
|
132
|
-
export function handleThoughtChunkUpdate({ state, effects, update, }) {
|
|
133
|
-
effects.emitAcpRawShapeDiagnostic(update);
|
|
134
|
-
const text = extractAcpUpdateText(update);
|
|
135
|
-
if (!text)
|
|
136
|
-
return;
|
|
137
|
-
if (!state.emittedThinkingStart) {
|
|
138
|
-
state.emittedThinkingStart = true;
|
|
139
|
-
effects.send({ event: 'agent', payload: { type: 'thinking_start' } });
|
|
140
|
-
}
|
|
141
|
-
effects.send({ event: 'agent', payload: { type: 'thinking_delta', delta: text } });
|
|
142
|
-
}
|
|
143
|
-
/** Strips tool-call XML from a raw message delta via the session's tool-call text suppressor, noting the suppression reason. */
|
|
144
|
-
export function stripToolCallText({ effects, delta }) {
|
|
145
|
-
const wasSuppressingToolCall = effects.toolCallTextSuppressor.isSuppressing();
|
|
146
|
-
const toolCallStrippedDelta = effects.toolCallTextSuppressor.strip(delta);
|
|
147
|
-
effects.noteToolCallTextSuppression(wasSuppressingToolCall || toolCallStrippedDelta !== delta ? 'tool_call_xml' : 'tool_call_candidate');
|
|
148
|
-
return toolCallStrippedDelta;
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Whether a non-cumulative message delta should be emitted as-is (prose)
|
|
152
|
-
* rather than the DSML artifact suppressor's stripped output. True when this
|
|
153
|
-
* delta isn't itself part of an artifact echo/candidate, AND either nothing
|
|
154
|
-
* was actually stripped, or the suppressor was armed mid-stream (after
|
|
155
|
-
* visible text) and prior deltas already established this is ordinary prose
|
|
156
|
-
* rather than the start of another artifact echo.
|
|
157
|
-
*/
|
|
158
|
-
export function shouldPreserveIncrementalProse(args) {
|
|
159
|
-
const { isCumulativeSnapshot, wasSuppressingArtifact, hadPendingArtifactCandidate, hasOpenArtifactCandidate, strippedDelta, toolCallStrippedDelta, dsmlArtifactSuppressorArmedAfterText, dsmlArtifactSuppressorSawIncrementalProse, } = args;
|
|
160
|
-
if (isCumulativeSnapshot || wasSuppressingArtifact || hadPendingArtifactCandidate || hasOpenArtifactCandidate) {
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
if (strippedDelta === toolCallStrippedDelta)
|
|
164
|
-
return true;
|
|
165
|
-
return (!dsmlArtifactSuppressorArmedAfterText &&
|
|
166
|
-
dsmlArtifactSuppressorSawIncrementalProse &&
|
|
167
|
-
!ACP_ARTIFACT_ECHO_START_RE.test(toolCallStrippedDelta));
|
|
168
|
-
}
|
|
169
|
-
/** Whether a delta passed through the DSML suppressor completely unchanged and there is no artifact suppression in progress. */
|
|
170
|
-
export function isPlainIncrementalDelta(args) {
|
|
171
|
-
const { strippedDelta, toolCallStrippedDelta, wasSuppressingArtifact, hadPendingArtifactCandidate, hasOpenArtifactCandidate, } = args;
|
|
172
|
-
return (strippedDelta === toolCallStrippedDelta &&
|
|
173
|
-
!wasSuppressingArtifact &&
|
|
174
|
-
!hadPendingArtifactCandidate &&
|
|
175
|
-
!hasOpenArtifactCandidate);
|
|
176
|
-
}
|
|
177
|
-
/** Runs a tool-call-stripped delta through the DSML artifact suppressor, emits whatever should stay visible, and arms/disarms the "saw incremental prose" and suppressor-cleared state. */
|
|
178
|
-
export function applyDsmlArtifactSuppression({ state, effects, suppressor, toolCallStrippedDelta, isCumulativeSnapshot, }) {
|
|
179
|
-
const wasSuppressingArtifact = suppressor.isSuppressing();
|
|
180
|
-
const hadPendingArtifactCandidate = suppressor.hasPendingCandidate();
|
|
181
|
-
const strippedDelta = suppressor.strip(toolCallStrippedDelta);
|
|
182
|
-
effects.noteArtifactTextSuppression(wasSuppressingArtifact || strippedDelta !== toolCallStrippedDelta ? 'artifact_echo' : 'artifact_candidate');
|
|
183
|
-
const hasOpenArtifactCandidate = suppressor.isSuppressing() || suppressor.hasPendingCandidate();
|
|
184
|
-
const consumedArtifactText = wasSuppressingArtifact || strippedDelta !== toolCallStrippedDelta;
|
|
185
|
-
const preserveIncrementalProse = shouldPreserveIncrementalProse({
|
|
186
|
-
isCumulativeSnapshot,
|
|
187
|
-
wasSuppressingArtifact,
|
|
188
|
-
hadPendingArtifactCandidate,
|
|
189
|
-
hasOpenArtifactCandidate,
|
|
190
|
-
strippedDelta,
|
|
191
|
-
toolCallStrippedDelta,
|
|
192
|
-
dsmlArtifactSuppressorArmedAfterText: state.dsmlArtifactSuppressorArmedAfterText,
|
|
193
|
-
dsmlArtifactSuppressorSawIncrementalProse: state.dsmlArtifactSuppressorSawIncrementalProse,
|
|
194
|
-
});
|
|
195
|
-
const outputDelta = preserveIncrementalProse ? toolCallStrippedDelta : strippedDelta;
|
|
196
|
-
if (outputDelta) {
|
|
197
|
-
effects.emitVisibleTextDelta(outputDelta);
|
|
198
|
-
}
|
|
199
|
-
if (isPlainIncrementalDelta({
|
|
200
|
-
strippedDelta,
|
|
201
|
-
toolCallStrippedDelta,
|
|
202
|
-
wasSuppressingArtifact,
|
|
203
|
-
hadPendingArtifactCandidate,
|
|
204
|
-
hasOpenArtifactCandidate,
|
|
205
|
-
})) {
|
|
206
|
-
state.dsmlArtifactSuppressorSawIncrementalProse = true;
|
|
207
|
-
}
|
|
208
|
-
if (consumedArtifactText && !hasOpenArtifactCandidate) {
|
|
209
|
-
state.dsmlArtifactSuppressor = null;
|
|
210
|
-
state.dsmlArtifactSuppressorToolCallId = null;
|
|
211
|
-
state.dsmlArtifactSuppressorArmedAfterText = false;
|
|
212
|
-
state.dsmlArtifactSuppressorSawIncrementalProse = false;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
/** Translates an `agent_message_chunk` update into `text_delta` events, applying tool-call and DSML-artifact text suppression. */
|
|
216
|
-
export function handleMessageChunkUpdate({ state, effects, update, }) {
|
|
217
|
-
effects.emitAcpRawShapeDiagnostic(update);
|
|
218
|
-
const text = extractAcpUpdateText(update);
|
|
219
|
-
if (!text)
|
|
220
|
-
return;
|
|
221
|
-
const isCumulativeSnapshot = state.emittedTextBuffer.length > 0 &&
|
|
222
|
-
text.length > state.emittedTextBuffer.length && text.startsWith(state.emittedTextBuffer);
|
|
223
|
-
const delta = isCumulativeSnapshot ? text.slice(state.emittedTextBuffer.length) : text;
|
|
224
|
-
// text is nonempty above; a cumulative snapshot is strictly longer than the prior buffer.
|
|
225
|
-
state.emittedTextChunk = true;
|
|
226
|
-
state.emittedTextBuffer += delta;
|
|
227
|
-
const toolCallStrippedDelta = stripToolCallText({ effects, delta });
|
|
228
|
-
if (!toolCallStrippedDelta)
|
|
229
|
-
return;
|
|
230
|
-
if (state.dsmlArtifactSuppressor) {
|
|
231
|
-
applyDsmlArtifactSuppression({
|
|
232
|
-
state,
|
|
233
|
-
effects,
|
|
234
|
-
suppressor: state.dsmlArtifactSuppressor,
|
|
235
|
-
toolCallStrippedDelta,
|
|
236
|
-
delta,
|
|
237
|
-
isCumulativeSnapshot,
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
else {
|
|
241
|
-
effects.emitVisibleTextDelta(toolCallStrippedDelta);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
// Mirror artifact-write tool calls into the daemon's canonical
|
|
245
|
-
// tool_use/tool_result event shape so a run-artifacts scanner can see
|
|
246
|
-
// ACP file writes. Without this, an ACP agent that emits only
|
|
247
|
-
// text/status/thinking events (never a tool_use/tool_result pair)
|
|
248
|
-
// would report zero artifacts even when the run wrote artifacts.
|
|
249
|
-
//
|
|
250
|
-
// This path only feeds the NO-PROJECT fallback (project runs use the
|
|
251
|
-
// filesystem snapshot). Two correctness rules, both learned the hard
|
|
252
|
-
// way in review:
|
|
253
|
-
// 1. Defer emission to the TERMINAL frame and accumulate the best
|
|
254
|
-
// concrete path across frames — ACP often sends `locations` only
|
|
255
|
-
// on the completing update, and emitting on the first frame would
|
|
256
|
-
// lock in a wrong/empty guess that a later path can't correct.
|
|
257
|
-
// 2. Never fabricate an artifact extension. `isArtifactPath` is what
|
|
258
|
-
// decides whether a write counts; feeding it a real path lets it
|
|
259
|
-
// correctly EXCLUDE non-artifact edits (`config.json`, `README.md`)
|
|
260
|
-
// and INCLUDE real artifacts. A write that never carries a concrete
|
|
261
|
-
// path stays keyed on its (extension-less) toolCallId, so it is
|
|
262
|
-
// simply not counted rather than inflating the metric with a
|
|
263
|
-
// synthetic `.html` — under-counting a truly opaque write is
|
|
264
|
-
// acceptable; a false-positive artifact is not.
|
|
265
|
-
export function mirrorArtifactWriteToolEvent({ state, effects, update, toolCallId, }) {
|
|
266
|
-
if (!toolCallId)
|
|
267
|
-
return;
|
|
268
|
-
const isWriteCall = isAcpArtifactWriteLabel(update) || state.acpArtifactWriteToolCallIds.has(toolCallId);
|
|
269
|
-
if (!isWriteCall)
|
|
270
|
-
return;
|
|
271
|
-
let st = state.acpArtifactRunEventState.get(toolCallId);
|
|
272
|
-
if (!st) {
|
|
273
|
-
st = { path: null, emitted: false };
|
|
274
|
-
state.acpArtifactRunEventState.set(toolCallId, st);
|
|
275
|
-
}
|
|
276
|
-
if (!st.path)
|
|
277
|
-
st.path = acpArtifactWritePath(update);
|
|
278
|
-
const failed = isAcpTerminalFailureStatus(update);
|
|
279
|
-
const shouldEmit = !st.emitted && (failed || isAcpCompletedStatus(update));
|
|
280
|
-
if (!shouldEmit)
|
|
281
|
-
return;
|
|
282
|
-
st.emitted = true;
|
|
283
|
-
effects.send({ event: 'agent', payload: {
|
|
284
|
-
type: 'tool_use',
|
|
285
|
-
id: toolCallId,
|
|
286
|
-
name: 'Write',
|
|
287
|
-
input: { file_path: st.path ?? toolCallId },
|
|
288
|
-
} });
|
|
289
|
-
effects.send({ event: 'agent', payload: { type: 'tool_result', toolUseId: toolCallId, isError: failed } });
|
|
290
|
-
state.emittedConcreteToolEvent = true;
|
|
291
|
-
}
|
|
292
|
-
/** Arms the DSML artifact suppressor when a tool_call/tool_call_update completes an artifact write, or disarms it once its owning write call terminally fails. */
|
|
293
|
-
export function updateDsmlSuppressorForToolCall({ state, update, toolCallId, }) {
|
|
294
|
-
if (isAcpArtifactWriteUpdate(update, state.acpArtifactWriteToolCallIds)) {
|
|
295
|
-
state.dsmlArtifactSuppressor = createDsmlArtifactTextSuppressor();
|
|
296
|
-
state.dsmlArtifactSuppressorLastSuppressedChars = 0;
|
|
297
|
-
state.dsmlArtifactSuppressorToolCallId = toolCallId;
|
|
298
|
-
state.dsmlArtifactSuppressorArmedAfterText = state.emittedTextBuffer.length > 0;
|
|
299
|
-
state.dsmlArtifactSuppressorSawIncrementalProse = false;
|
|
300
|
-
if (toolCallId)
|
|
301
|
-
state.acpArtifactWriteToolCallIds.delete(toolCallId);
|
|
302
|
-
return;
|
|
303
|
-
}
|
|
304
|
-
if (!toolCallId || !isAcpTerminalFailureStatus(update))
|
|
305
|
-
return;
|
|
306
|
-
const ownsPendingWriteSuppression = toolCallId === state.dsmlArtifactSuppressorToolCallId;
|
|
307
|
-
const ownsPendingWriteCall = state.acpArtifactWriteToolCallIds.has(toolCallId);
|
|
308
|
-
state.acpArtifactWriteToolCallIds.delete(toolCallId);
|
|
309
|
-
if (!ownsPendingWriteSuppression && !ownsPendingWriteCall)
|
|
310
|
-
return;
|
|
311
|
-
state.dsmlArtifactSuppressor = null;
|
|
312
|
-
state.dsmlArtifactSuppressorToolCallId = null;
|
|
313
|
-
state.dsmlArtifactSuppressorArmedAfterText = false;
|
|
314
|
-
state.dsmlArtifactSuppressorSawIncrementalProse = false;
|
|
315
|
-
}
|
|
316
|
-
/** Translates a `tool_call` / `tool_call_update` update: tracks it as real turn output, mirrors artifact writes, and manages DSML suppressor arming. */
|
|
317
|
-
export function handleToolCallUpdate({ state, effects, update, }) {
|
|
318
|
-
// The turn did real work (a tool call / file edit), which is valid output even
|
|
319
|
-
// when the model emits no closing assistant text. Track it so the prompt-complete
|
|
320
|
-
// handler does not misreport such a turn as "no output / model unavailable".
|
|
321
|
-
state.emittedToolCall = true;
|
|
322
|
-
const toolCallId = acpToolCallId(update);
|
|
323
|
-
if (toolCallId && isAcpArtifactWriteLabel(update)) {
|
|
324
|
-
state.acpArtifactWriteToolCallIds.add(toolCallId);
|
|
325
|
-
}
|
|
326
|
-
mirrorArtifactWriteToolEvent({ state, effects, update, toolCallId });
|
|
327
|
-
updateDsmlSuppressorForToolCall({ state, update, toolCallId });
|
|
328
|
-
}
|
|
329
38
|
/** Top-level `session/update` dispatcher: emits a generic status for non-streaming update kinds, then routes to the matching per-kind handler. */
|
|
330
|
-
export function handleSessionUpdate({ state, effects, update, }) {
|
|
39
|
+
export function handleSessionUpdate({ state, effects, update, }, _optional = {}) {
|
|
331
40
|
applyModelChangeUpdate({ state, effects, update });
|
|
332
41
|
if (effects.modelUnavailableErrorCode && tryPromoteAmrRetryStatus({ effects, update }))
|
|
333
42
|
return;
|
|
@@ -344,7 +53,7 @@ export function handleSessionUpdate({ state, effects, update, }) {
|
|
|
344
53
|
/** Tracks a model switch reported by a `session/update` and emits a `model` status when it changes. */
|
|
345
54
|
function applyModelChangeUpdate({ state, effects, update, }) {
|
|
346
55
|
// Model/config updates are authoritative protocol metadata, not assistant self-report.
|
|
347
|
-
const changedModel = currentModelFromSessionResult(update) ?? currentModelUpdateId(update);
|
|
56
|
+
const changedModel = currentModelFromSessionResult({ result: update }) ?? currentModelUpdateId(update);
|
|
348
57
|
if (changedModel && changedModel !== state.activeModel) {
|
|
349
58
|
state.activeModel = changedModel;
|
|
350
59
|
effects.send({ event: 'agent', payload: { type: 'status', label: 'model', model: changedModel } });
|
|
@@ -370,132 +79,6 @@ function routeSessionUpdateKind({ state, effects, update, }) {
|
|
|
370
79
|
handleToolCallUpdate({ state, effects, update });
|
|
371
80
|
}
|
|
372
81
|
}
|
|
373
|
-
/** Handles the `initialize` ack: sends `session/load` (resume) or `session/new` (fresh). */
|
|
374
|
-
export function handleInitializeAck({ state, effects }) {
|
|
375
|
-
state.expectedId = state.nextId;
|
|
376
|
-
if (effects.resumeSessionId) {
|
|
377
|
-
// Resume the prior upstream session instead of creating a fresh one.
|
|
378
|
-
effects.writeRpc(state.nextId, 'session/load', {
|
|
379
|
-
...buildAcpSessionNewParams({ cwd: effects.effectiveCwd }, effects.mcpServers
|
|
380
|
-
? { mcpServers: effects.mcpServers, envFormat: effects.envFormat }
|
|
381
|
-
: { envFormat: effects.envFormat }),
|
|
382
|
-
sessionId: effects.resumeSessionId,
|
|
383
|
-
}, 'session/load');
|
|
384
|
-
}
|
|
385
|
-
else {
|
|
386
|
-
effects.writeRpc(state.nextId, 'session/new', buildAcpSessionNewParams({ cwd: effects.effectiveCwd }, effects.mcpServers ? { mcpServers: effects.mcpServers, envFormat: effects.envFormat } : { envFormat: effects.envFormat }), 'session/new');
|
|
387
|
-
}
|
|
388
|
-
state.nextId += 1;
|
|
389
|
-
}
|
|
390
|
-
/** Sends `session/set_model` (or `session/set_config_option`) when a non-default model was requested. Returns `true` when it did (caller should not send the prompt yet). */
|
|
391
|
-
export function triggerSetModelIfNeeded({ state, effects, }) {
|
|
392
|
-
if (!state.sessionId || !effects.model || effects.model === 'default')
|
|
393
|
-
return false;
|
|
394
|
-
// Hosts now pin the concrete starting model on every run. When session/new already reports that
|
|
395
|
-
// model, a set_model round-trip is redundant, and a CLI without set_model support would turn it
|
|
396
|
-
// into a fatal explicit-model rejection.
|
|
397
|
-
if (state.activeModel === effects.model)
|
|
398
|
-
return false;
|
|
399
|
-
state.setModelRequestId = state.nextId;
|
|
400
|
-
state.expectedId = state.nextId;
|
|
401
|
-
const setModelMethod = state.modelConfigId ? 'session/set_config_option' : 'session/set_model';
|
|
402
|
-
const setModelParams = state.modelConfigId
|
|
403
|
-
? { sessionId: state.sessionId, configId: state.modelConfigId, value: effects.model }
|
|
404
|
-
: { sessionId: state.sessionId, modelId: effects.model };
|
|
405
|
-
effects.writeRpc(state.nextId, setModelMethod, setModelParams, setModelMethod);
|
|
406
|
-
state.nextId += 1;
|
|
407
|
-
return true;
|
|
408
|
-
}
|
|
409
|
-
/** Records handshake identity, retaining the requested handle on an ID-free load ack.
|
|
410
|
-
* Mutates only the two session handles; performs no I/O.
|
|
411
|
-
* @complexity O(1) time and space.
|
|
412
|
-
*/
|
|
413
|
-
function recordSessionIdentity({ state, result }, { resumeSessionId = null } = {}) {
|
|
414
|
-
// ACP load responses need not repeat the handle supplied in the request.
|
|
415
|
-
state.sessionId = asOptionalString(result.sessionId) ?? resumeSessionId;
|
|
416
|
-
// The durable handle for resuming this session on the next turn.
|
|
417
|
-
state.durableSessionId = asOptionalString(result.openCodeSessionId) ?? resumeSessionId;
|
|
418
|
-
}
|
|
419
|
-
/** Handles the `session/new` (or `session/load`) ack: records the session id, model config, and either triggers a model switch or sends the prompt. */
|
|
420
|
-
export function handleSessionNewAck({ state, effects, result, rawLine, }) {
|
|
421
|
-
recordSessionIdentity({ state, result }, { resumeSessionId: effects.resumeSessionId });
|
|
422
|
-
// session/new acknowledged with a session id = handshake done.
|
|
423
|
-
// Invoke the optional callback here instead of relocating its complexity score to a one-line wrapper.
|
|
424
|
-
if (state.sessionId)
|
|
425
|
-
effects.onSessionInit?.();
|
|
426
|
-
// findModelConfigOption returns null or a parsed config with a required string id.
|
|
427
|
-
const modelConfig = findModelConfigOption(result.configOptions);
|
|
428
|
-
state.modelConfigId = modelConfig ? modelConfig.configId : null;
|
|
429
|
-
state.activeModel = currentModelFromSessionResult(result);
|
|
430
|
-
if (state.sessionId && state.activeModel && (!effects.model || effects.model === state.activeModel)) {
|
|
431
|
-
effects.send({ event: 'agent', payload: { type: 'status', label: 'model', model: state.activeModel } });
|
|
432
|
-
}
|
|
433
|
-
if (triggerSetModelIfNeeded({ state, effects }))
|
|
434
|
-
return;
|
|
435
|
-
if (!state.sessionId) {
|
|
436
|
-
effects.fail(`invalid session/new response: ${rawLine}`);
|
|
437
|
-
return;
|
|
438
|
-
}
|
|
439
|
-
effects.sendPrompt();
|
|
440
|
-
}
|
|
441
|
-
/** Handles the `session/prompt` ack: fails a turn that reported model activity but produced no visible output, otherwise flushes and finishes cleanly. */
|
|
442
|
-
export function handlePromptResult({ state, effects, result, }) {
|
|
443
|
-
const usage = formatUsage(result.usage);
|
|
444
|
-
if (!state.emittedVisibleTextChunk && !state.emittedConcreteToolEvent && effects.modelUnavailableErrorCode) {
|
|
445
|
-
const outputTokens = usage?.output_tokens;
|
|
446
|
-
const hadCompletionTokens = typeof outputTokens === 'number' && outputTokens > 0;
|
|
447
|
-
if (hadCompletionTokens || state.emittedToolCall || state.emittedTextChunk) {
|
|
448
|
-
effects.fail('ACP session completed after reporting model activity, but did not produce visible assistant text, concrete tool results, or artifacts.', {
|
|
449
|
-
retryable: true,
|
|
450
|
-
details: {
|
|
451
|
-
kind: 'acp_no_visible_output',
|
|
452
|
-
output_tokens: outputTokens,
|
|
453
|
-
raw_tool_update_seen: state.emittedToolCall,
|
|
454
|
-
text_chunk_seen: state.emittedTextChunk,
|
|
455
|
-
},
|
|
456
|
-
});
|
|
457
|
-
}
|
|
458
|
-
else {
|
|
459
|
-
effects.fail('ACP session completed without producing any assistant text. Refresh the AMR model list, choose a supported model, and retry this run.', { forceModelUnavailable: true });
|
|
460
|
-
}
|
|
461
|
-
return;
|
|
462
|
-
}
|
|
463
|
-
effects.finishCleanPrompt(result.usage);
|
|
464
|
-
}
|
|
465
|
-
/** Whether an incoming result frame is the ack for an in-flight `session/set_model` (or `set_config_option`) request. */
|
|
466
|
-
export function isModelSetAckExpected({ state, effects, obj, }) {
|
|
467
|
-
return Boolean(state.sessionId && effects.model && effects.model !== 'default' && obj.id === state.expectedId);
|
|
468
|
-
}
|
|
469
|
-
/** Handles the `session/set_model` (or `set_config_option`) ack: records the confirmed model and sends the prompt. */
|
|
470
|
-
export function handleModelSetAck({ state, effects, result, }) {
|
|
471
|
-
// `isModelSetAckExpected` already confirmed `effects.model` is a truthy
|
|
472
|
-
// string before this runs; the assertion is only to carry that narrowing
|
|
473
|
-
// across the function boundary for the type checker (it doesn't survive
|
|
474
|
-
// the call), not a behavior change.
|
|
475
|
-
state.activeModel = currentModelFromSessionResult(result) ?? effects.model;
|
|
476
|
-
effects.send({ event: 'agent', payload: { type: 'status', label: 'model', model: state.activeModel } });
|
|
477
|
-
effects.sendPrompt();
|
|
478
|
-
}
|
|
479
|
-
/** Top-level JSON-RPC result dispatcher, keyed by which request `expectedId`/`promptRequestId` is currently outstanding. */
|
|
480
|
-
export function routeResultById({ state, effects, obj, result, rawLine, }) {
|
|
481
|
-
if (obj.id !== state.expectedId || !result)
|
|
482
|
-
return;
|
|
483
|
-
if (state.expectedId === 1) {
|
|
484
|
-
handleInitializeAck({ state, effects });
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
if (state.expectedId === 2) {
|
|
488
|
-
handleSessionNewAck({ state, effects, result, rawLine });
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
if (state.promptRequestId !== null && obj.id === state.promptRequestId) {
|
|
492
|
-
handlePromptResult({ state, effects, result });
|
|
493
|
-
return;
|
|
494
|
-
}
|
|
495
|
-
if (isModelSetAckExpected({ state, effects, obj })) {
|
|
496
|
-
handleModelSetAck({ state, effects, result });
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
82
|
function resolveAcpSessionOptionDefaults(options) {
|
|
500
83
|
return {
|
|
501
84
|
imagePaths: options.imagePaths ?? [],
|
|
@@ -534,572 +117,56 @@ function resolveAcpSessionOptionDefaults(options) {
|
|
|
534
117
|
*/
|
|
535
118
|
export function attachAcpSession(requiredArgs, optionalArgs = {}) {
|
|
536
119
|
const options = { ...optionalArgs, ...requiredArgs };
|
|
537
|
-
const
|
|
538
|
-
const
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
120
|
+
const run = createAcpRun({ options, resolved: resolveAcpSessionOptionDefaults(options) });
|
|
121
|
+
const effects = buildAcpEffects({ run });
|
|
122
|
+
const parser = createJsonLineStream({
|
|
123
|
+
onMessage: ({ message: raw, rawLine }) => handleAcpMessage({ run, effects, raw, rawLine }),
|
|
124
|
+
}, { onError: error => failRun({ run, message: error.message }) });
|
|
125
|
+
wireAcpProcessListeners({ run, parser });
|
|
126
|
+
sendInitialize({ run });
|
|
127
|
+
return buildAcpController({ run });
|
|
128
|
+
}
|
|
129
|
+
function handleAcpMessage({ run, effects, raw, rawLine }) {
|
|
130
|
+
if (run.aborted || run.finished)
|
|
131
|
+
return;
|
|
132
|
+
resetStageTimer({ run, label: 'response' });
|
|
133
|
+
const obj = asObject({ value: raw });
|
|
134
|
+
if (!obj)
|
|
135
|
+
return;
|
|
136
|
+
// First well-formed ACP JSON-RPC message = CLI ready. Caller dedupes, so
|
|
137
|
+
// re-notifying on later messages is harmless.
|
|
138
|
+
run.options.onCliReady?.();
|
|
139
|
+
routeAcpMessage({ run, effects, obj, rawLine });
|
|
140
|
+
}
|
|
141
|
+
function routeAcpMessage({ run, effects, obj, rawLine }) {
|
|
142
|
+
const { state } = run;
|
|
143
|
+
const params = asObject({ value: obj.params });
|
|
144
|
+
const rpcErr = rpcErrorMessage({ raw: obj });
|
|
145
|
+
if (rpcErr) {
|
|
146
|
+
handleRpcError({ state, effects, obj, error: asObject({ value: obj.error }), rpcErr });
|
|
147
|
+
return;
|
|
548
148
|
}
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
openedBlocks: 0,
|
|
572
|
-
closedBlocks: 0,
|
|
573
|
-
};
|
|
574
|
-
const stageWatchdogDisabled = stageTimeoutMs <= 0;
|
|
575
|
-
const resetStageTimer = (label) => {
|
|
576
|
-
if (stageTimer)
|
|
577
|
-
clearTimeout(stageTimer);
|
|
578
|
-
// `stageTimeoutMs <= 0` disables the watchdog. Mirrors a typical outer
|
|
579
|
-
// run-level inactivity watchdog's escape hatch. Without this, a caller
|
|
580
|
-
// passing a zero stage timeout would schedule a 0ms timeout that fires on
|
|
581
|
-
// the next tick and kills the session immediately.
|
|
582
|
-
if (stageWatchdogDisabled || pendingPermissionRequests.size > 0)
|
|
583
|
-
return;
|
|
584
|
-
stageTimer = setTimeout(() => {
|
|
585
|
-
fail(`ACP ${label} timed out after ${stageTimeoutMs}ms`);
|
|
586
|
-
}, stageTimeoutMs);
|
|
587
|
-
};
|
|
588
|
-
const clearStageTimer = () => {
|
|
589
|
-
if (stageTimer)
|
|
590
|
-
clearTimeout(stageTimer);
|
|
591
|
-
stageTimer = null;
|
|
592
|
-
};
|
|
593
|
-
const amrModelUnavailablePayload = (message) => ({
|
|
594
|
-
message,
|
|
595
|
-
error: {
|
|
596
|
-
code: 'AMR_MODEL_UNAVAILABLE',
|
|
597
|
-
message,
|
|
598
|
-
retryable: false,
|
|
599
|
-
details: { kind: 'amr_model', action: 'choose_model' },
|
|
600
|
-
},
|
|
601
|
-
});
|
|
602
|
-
const isModelUnavailableError = (message) => {
|
|
603
|
-
const value = message.toLowerCase();
|
|
604
|
-
return (value.includes('model not found') ||
|
|
605
|
-
value.includes('providermodelnotfounderror') ||
|
|
606
|
-
value.includes('unknown model') ||
|
|
607
|
-
value.includes('invalid model'));
|
|
608
|
-
};
|
|
609
|
-
/** Emits a failure, tagging an unacknowledged resume without losing its cause.
|
|
610
|
-
* The session id is only set by a valid load acknowledgement, so the same
|
|
611
|
-
* boundary covers initialize/load RPC errors, watchdogs, and transport loss.
|
|
612
|
-
* Fresh sessions and errors after load keep their existing payloads.
|
|
613
|
-
* @complexity O(1), excluding the host's event sink.
|
|
614
|
-
*/
|
|
615
|
-
const sendFailure = ({ payload }) => {
|
|
616
|
-
if (!resumeSessionId || state.sessionId) {
|
|
617
|
-
send({ event: 'error', payload });
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
const original = payload;
|
|
621
|
-
const originalError = asObject(original.error);
|
|
622
|
-
send({ event: 'error', payload: {
|
|
623
|
-
...original,
|
|
624
|
-
error: {
|
|
625
|
-
code: 'AGENT_EXECUTION_FAILED',
|
|
626
|
-
message: original.message,
|
|
627
|
-
retryable: false,
|
|
628
|
-
...originalError,
|
|
629
|
-
details: {
|
|
630
|
-
kind: 'resume_failed',
|
|
631
|
-
sessionId: resumeSessionId,
|
|
632
|
-
...(originalError?.details === undefined ? {} : { cause: originalError.details }),
|
|
633
|
-
},
|
|
634
|
-
},
|
|
635
|
-
} });
|
|
636
|
-
};
|
|
637
|
-
// Both call sites below (the session/update retry-status promotion and the
|
|
638
|
-
// stderr promotion) are already nested inside a scope gated by `finished`
|
|
639
|
-
// at their own entry point (the parser callback's own `if (aborted ||
|
|
640
|
-
// finished) return;`, and the stderr handler's `if (!modelUnavailableErrorCode
|
|
641
|
-
// || finished) return;`), and neither is re-entrant within a single
|
|
642
|
-
// synchronous call — so `failWithPayload` can never actually be invoked a
|
|
643
|
-
// second time once `finished` is true. The origin file carried its own
|
|
644
|
-
// `if (finished) return;` re-entry guard here anyway; removed per this
|
|
645
|
-
// package's coverage-driven dead-branch discipline (verified unreachable
|
|
646
|
-
// by tracing every call site — see archived provenance ledger), not suppressed.
|
|
647
|
-
const failWithPayload = (payload) => {
|
|
648
|
-
finished = true;
|
|
649
|
-
fatal = true;
|
|
650
|
-
clearStageTimer();
|
|
651
|
-
sendFailure({ payload });
|
|
652
|
-
if (!child.killed)
|
|
653
|
-
child.kill('SIGTERM');
|
|
654
|
-
};
|
|
655
|
-
const fail = (message, options = {}) => {
|
|
656
|
-
if (finished)
|
|
657
|
-
return;
|
|
658
|
-
finished = true;
|
|
659
|
-
fatal = true;
|
|
660
|
-
clearStageTimer();
|
|
661
|
-
const useModelUnavailable = modelUnavailableErrorCode &&
|
|
662
|
-
(options.forceModelUnavailable || isModelUnavailableError(message));
|
|
663
|
-
const bareFailure = options.details === undefined && options.retryable === undefined;
|
|
664
|
-
const failurePayload = bareFailure ? { message } : {
|
|
665
|
-
message,
|
|
666
|
-
error: {
|
|
667
|
-
code: 'AGENT_EXECUTION_FAILED',
|
|
668
|
-
message,
|
|
669
|
-
retryable: options.retryable ?? false,
|
|
670
|
-
// Every real call site that reaches this branch (the
|
|
671
|
-
// RPC-error path and the no-visible-output path) always
|
|
672
|
-
// supplies `details` whenever it supplies `retryable`, and
|
|
673
|
-
// `retryable` is itself derived from the same `details`
|
|
674
|
-
// source at the RPC-error call site — so `options.details`
|
|
675
|
-
// is never actually undefined here. Spreading it
|
|
676
|
-
// unconditionally (rather than conditionally omitting the
|
|
677
|
-
// key) is behaviorally identical for every real caller;
|
|
678
|
-
// simplified per this package's coverage-driven
|
|
679
|
-
// dead-branch discipline. See archived provenance ledger.
|
|
680
|
-
details: options.details,
|
|
681
|
-
},
|
|
682
|
-
};
|
|
683
|
-
sendFailure({ payload: useModelUnavailable ? amrModelUnavailablePayload(message) : failurePayload });
|
|
684
|
-
if (!child.killed)
|
|
685
|
-
child.kill('SIGTERM');
|
|
686
|
-
};
|
|
687
|
-
const writeRpc = (id, method, params, timeoutLabel) => {
|
|
688
|
-
resetStageTimer(timeoutLabel);
|
|
689
|
-
try {
|
|
690
|
-
sendRpc(stdin, id, method, params);
|
|
691
|
-
}
|
|
692
|
-
catch (err) {
|
|
693
|
-
fail(`stdin write failed: ${errorMessage(err)}`);
|
|
694
|
-
}
|
|
695
|
-
};
|
|
696
|
-
const emitAcpRawShapeDiagnostic = (update) => {
|
|
697
|
-
if (!modelUnavailableErrorCode)
|
|
698
|
-
return;
|
|
699
|
-
if (rawAcpShapeDiagnosticCount >= ACP_RAW_EVENT_SHAPE_DIAGNOSTIC_LIMIT)
|
|
700
|
-
return;
|
|
701
|
-
rawAcpShapeDiagnosticCount += 1;
|
|
702
|
-
send({ event: 'agent', payload: {
|
|
703
|
-
type: 'diagnostic',
|
|
704
|
-
name: 'acp_raw_event_shape',
|
|
705
|
-
source: ACP_JSON_RPC_SOURCE,
|
|
706
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
707
|
-
shape: acpRawEventShape(update),
|
|
708
|
-
} });
|
|
709
|
-
};
|
|
710
|
-
// All three call sites guard against an empty `delta` before calling this
|
|
711
|
-
// (the finishCleanPrompt flush, the `if (outputDelta)` branch, and the
|
|
712
|
-
// plain-else branch which is only reached after an earlier `if
|
|
713
|
-
// (!toolCallStrippedDelta) return;` already ruled out emptiness) — so the
|
|
714
|
-
// origin file's own `if (!delta) return;` guard here can never actually
|
|
715
|
-
// fire. Removed per this package's coverage-driven dead-branch
|
|
716
|
-
// discipline (verified unreachable by tracing every call site — see
|
|
717
|
-
// archived provenance ledger), not suppressed.
|
|
718
|
-
const emitVisibleTextDelta = (delta) => {
|
|
719
|
-
state.emittedVisibleTextChunk = true;
|
|
720
|
-
if (!emittedFirstTokenStatus) {
|
|
721
|
-
emittedFirstTokenStatus = true;
|
|
722
|
-
send({ event: 'agent', payload: {
|
|
723
|
-
type: 'status',
|
|
724
|
-
label: 'streaming',
|
|
725
|
-
ttftMs: Date.now() - runStartedAt,
|
|
726
|
-
} });
|
|
727
|
-
}
|
|
728
|
-
send({ event: 'agent', payload: { type: 'text_delta', delta } });
|
|
729
|
-
};
|
|
730
|
-
const noteArtifactTextSuppression = (reason) => {
|
|
731
|
-
if (!state.dsmlArtifactSuppressor)
|
|
732
|
-
return;
|
|
733
|
-
const stats = state.dsmlArtifactSuppressor.stats();
|
|
734
|
-
const suppressedDelta = stats.suppressedChars - state.dsmlArtifactSuppressorLastSuppressedChars;
|
|
735
|
-
if (suppressedDelta <= 0)
|
|
736
|
-
return;
|
|
737
|
-
state.dsmlArtifactSuppressorLastSuppressedChars = stats.suppressedChars;
|
|
738
|
-
artifactTextSuppressionSummary.suppressedChars += suppressedDelta;
|
|
739
|
-
artifactTextSuppressionSummary.suppressedChunks = stats.suppressedChunks;
|
|
740
|
-
artifactTextSuppressionSummary.openedBlocks = stats.openedBlocks;
|
|
741
|
-
artifactTextSuppressionSummary.closedBlocks = stats.closedBlocks;
|
|
742
|
-
if (artifactSuppressionDiagnosticCount >= ACP_RAW_EVENT_SHAPE_DIAGNOSTIC_LIMIT)
|
|
743
|
-
return;
|
|
744
|
-
artifactSuppressionDiagnosticCount += 1;
|
|
745
|
-
send({ event: 'agent', payload: {
|
|
746
|
-
type: 'diagnostic',
|
|
747
|
-
name: 'acp_artifact_text_suppression',
|
|
748
|
-
source: ACP_JSON_RPC_SOURCE,
|
|
749
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
750
|
-
reason,
|
|
751
|
-
suppressedChars: artifactTextSuppressionSummary.suppressedChars,
|
|
752
|
-
suppressedChunks: artifactTextSuppressionSummary.suppressedChunks,
|
|
753
|
-
openedBlocks: artifactTextSuppressionSummary.openedBlocks,
|
|
754
|
-
closedBlocks: artifactTextSuppressionSummary.closedBlocks,
|
|
755
|
-
pendingCandidateChars: stats.pendingCandidateChars,
|
|
756
|
-
suppressing: stats.suppressing,
|
|
757
|
-
} });
|
|
758
|
-
};
|
|
759
|
-
const emitArtifactTextSuppressionSummary = () => {
|
|
760
|
-
if (artifactTextSuppressionSummary.suppressedChars <= 0)
|
|
761
|
-
return;
|
|
762
|
-
if (executionProfile === 'filesystem') {
|
|
763
|
-
send({ event: 'agent', payload: {
|
|
764
|
-
type: 'diagnostic',
|
|
765
|
-
name: 'unexpected_text_artifact_in_filesystem_run',
|
|
766
|
-
source: ACP_JSON_RPC_SOURCE,
|
|
767
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
768
|
-
suppressedChars: artifactTextSuppressionSummary.suppressedChars,
|
|
769
|
-
suppressedChunks: artifactTextSuppressionSummary.suppressedChunks,
|
|
770
|
-
openedBlocks: artifactTextSuppressionSummary.openedBlocks,
|
|
771
|
-
closedBlocks: artifactTextSuppressionSummary.closedBlocks,
|
|
772
|
-
} });
|
|
773
|
-
}
|
|
774
|
-
send({ event: 'agent', payload: {
|
|
775
|
-
type: 'diagnostic',
|
|
776
|
-
name: 'acp_artifact_text_suppression_summary',
|
|
777
|
-
source: ACP_JSON_RPC_SOURCE,
|
|
778
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
779
|
-
...artifactTextSuppressionSummary,
|
|
780
|
-
} });
|
|
781
|
-
};
|
|
782
|
-
const noteToolCallTextSuppression = (reason) => {
|
|
783
|
-
const stats = toolCallTextSuppressor.stats();
|
|
784
|
-
const suppressedDelta = stats.suppressedChars - toolCallTextSuppressorLastSuppressedChars;
|
|
785
|
-
if (suppressedDelta <= 0)
|
|
786
|
-
return;
|
|
787
|
-
toolCallTextSuppressorLastSuppressedChars = stats.suppressedChars;
|
|
788
|
-
toolCallTextSuppressionSummary.suppressedChars += suppressedDelta;
|
|
789
|
-
toolCallTextSuppressionSummary.suppressedChunks = stats.suppressedChunks;
|
|
790
|
-
toolCallTextSuppressionSummary.openedBlocks = stats.openedBlocks;
|
|
791
|
-
toolCallTextSuppressionSummary.closedBlocks = stats.closedBlocks;
|
|
792
|
-
if (artifactSuppressionDiagnosticCount >= ACP_RAW_EVENT_SHAPE_DIAGNOSTIC_LIMIT)
|
|
793
|
-
return;
|
|
794
|
-
artifactSuppressionDiagnosticCount += 1;
|
|
795
|
-
send({ event: 'agent', payload: {
|
|
796
|
-
type: 'diagnostic',
|
|
797
|
-
name: 'acp_tool_call_text_suppression',
|
|
798
|
-
source: ACP_JSON_RPC_SOURCE,
|
|
799
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
800
|
-
reason,
|
|
801
|
-
suppressedChars: toolCallTextSuppressionSummary.suppressedChars,
|
|
802
|
-
suppressedChunks: toolCallTextSuppressionSummary.suppressedChunks,
|
|
803
|
-
openedBlocks: toolCallTextSuppressionSummary.openedBlocks,
|
|
804
|
-
closedBlocks: toolCallTextSuppressionSummary.closedBlocks,
|
|
805
|
-
pendingCandidateChars: stats.pendingCandidateChars,
|
|
806
|
-
suppressing: stats.suppressing,
|
|
807
|
-
} });
|
|
808
|
-
};
|
|
809
|
-
const emitToolCallTextSuppressionSummary = () => {
|
|
810
|
-
if (toolCallTextSuppressionSummary.suppressedChars <= 0)
|
|
811
|
-
return;
|
|
812
|
-
send({ event: 'agent', payload: {
|
|
813
|
-
type: 'diagnostic',
|
|
814
|
-
name: 'acp_tool_call_text_suppression_summary',
|
|
815
|
-
source: ACP_JSON_RPC_SOURCE,
|
|
816
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
817
|
-
...toolCallTextSuppressionSummary,
|
|
818
|
-
} });
|
|
819
|
-
};
|
|
820
|
-
const sendPrompt = () => {
|
|
821
|
-
state.promptRequestId = state.nextId;
|
|
822
|
-
state.expectedId = state.promptRequestId;
|
|
823
|
-
writeRpc(state.promptRequestId, 'session/prompt', {
|
|
824
|
-
sessionId: state.sessionId,
|
|
825
|
-
prompt: buildPromptBlocks(prompt, imagePaths),
|
|
826
|
-
}, 'session/prompt');
|
|
827
|
-
send({ event: 'agent', payload: {
|
|
828
|
-
type: 'status',
|
|
829
|
-
label: 'waiting_for_first_output',
|
|
830
|
-
elapsedMs: Date.now() - runStartedAt,
|
|
831
|
-
} });
|
|
832
|
-
state.nextId += 1;
|
|
833
|
-
};
|
|
834
|
-
// `finishCleanPrompt` has exactly one call site (`handlePromptResult`,
|
|
835
|
-
// called only from `routeResultById`'s promptRequestId-match branch),
|
|
836
|
-
// which is itself only ever reached from the parser callback's own `if
|
|
837
|
-
// (aborted || finished) return;` guard at entry — so this function can
|
|
838
|
-
// never actually be invoked once `finished` is true. The origin file
|
|
839
|
-
// carried its own re-entry guard here anyway; removed per this package's
|
|
840
|
-
// coverage-driven dead-branch discipline. See archived provenance ledger.
|
|
841
|
-
const finishCleanPrompt = (usageSource) => {
|
|
842
|
-
const flushedToolText = toolCallTextSuppressor.flush();
|
|
843
|
-
noteToolCallTextSuppression('tool_call_xml_flush');
|
|
844
|
-
const flushedText = flushedToolText
|
|
845
|
-
? (state.dsmlArtifactSuppressor?.strip(flushedToolText) ?? flushedToolText)
|
|
846
|
-
: '';
|
|
847
|
-
if (flushedText) {
|
|
848
|
-
emitVisibleTextDelta(flushedText);
|
|
849
|
-
}
|
|
850
|
-
noteArtifactTextSuppression('artifact_flush');
|
|
851
|
-
emitToolCallTextSuppressionSummary();
|
|
852
|
-
emitArtifactTextSuppressionSummary();
|
|
853
|
-
const usage = formatUsage(usageSource);
|
|
854
|
-
if (usage) {
|
|
855
|
-
send({ event: 'agent', payload: {
|
|
856
|
-
type: 'usage',
|
|
857
|
-
usage,
|
|
858
|
-
durationMs: Date.now() - runStartedAt,
|
|
859
|
-
} });
|
|
860
|
-
}
|
|
861
|
-
finished = true;
|
|
862
|
-
clearStageTimer();
|
|
863
|
-
stdin.end();
|
|
864
|
-
// Some ACP agents keep the child process alive after stdin closes,
|
|
865
|
-
// waiting for another prompt. Each run owns one process per turn, so
|
|
866
|
-
// close it once this prompt is cleanly complete.
|
|
867
|
-
const cleanExitTimer = setTimeout(() => {
|
|
868
|
-
if (!child.killed)
|
|
869
|
-
child.kill('SIGTERM');
|
|
870
|
-
}, 500);
|
|
871
|
-
child.once('close', () => clearTimeout(cleanExitTimer));
|
|
872
|
-
};
|
|
873
|
-
const replyPermission = (raw) => {
|
|
874
|
-
const params = asObject(raw.params);
|
|
875
|
-
const toolCall = asObject(params?.toolCall);
|
|
876
|
-
const optionRecords = offeredPermissionOptions(params);
|
|
877
|
-
// One status event per request. Only protocol categories leave this
|
|
878
|
-
// boundary: titles, names, option ids and raw arguments can contain
|
|
879
|
-
// commands, paths or credentials.
|
|
880
|
-
const logDecision = (selected) => {
|
|
881
|
-
try {
|
|
882
|
-
const tool = permissionToolKind(toolCall);
|
|
883
|
-
send({ event: 'agent', payload: { type: 'status', label: 'acp_permission', detail: `tool=${tool} decision=${selected?.kind ?? 'cancelled'}` } });
|
|
884
|
-
}
|
|
885
|
-
catch {
|
|
886
|
-
// Host telemetry must not turn a handled request into a run failure.
|
|
887
|
-
}
|
|
888
|
-
};
|
|
889
|
-
if (!isJsonRpcId(raw.id)) {
|
|
890
|
-
// No response can be correlated without a valid id; drop it rather
|
|
891
|
-
// than failing the run.
|
|
892
|
-
logDecision();
|
|
893
|
-
return;
|
|
894
|
-
}
|
|
895
|
-
const requestId = raw.id;
|
|
896
|
-
const respond = (decision) => {
|
|
897
|
-
pendingPermissionRequests.delete(requestId);
|
|
898
|
-
if (aborted || finished)
|
|
899
|
-
return;
|
|
900
|
-
// Anything but an offered option (including an invalid handler result) cancels.
|
|
901
|
-
const choice = asObject(decision);
|
|
902
|
-
const selected = choice?.outcome === 'selected'
|
|
903
|
-
? optionRecords.find((option) => option.optionId === choice.optionId)
|
|
904
|
-
: undefined;
|
|
905
|
-
resetStageTimer('session/request_permission');
|
|
906
|
-
try {
|
|
907
|
-
sendRpcResult(stdin, requestId, {
|
|
908
|
-
outcome: selected ? { outcome: 'selected', optionId: selected.optionId } : { outcome: 'cancelled' },
|
|
909
|
-
});
|
|
910
|
-
}
|
|
911
|
-
catch {
|
|
912
|
-
// A broken pipe cannot carry a response; ordinary transport lifecycle
|
|
913
|
-
// handling still owns process failure, not the permission decision.
|
|
914
|
-
}
|
|
915
|
-
logDecision(selected);
|
|
916
|
-
};
|
|
917
|
-
const cancel = () => respond({ outcome: 'cancelled' });
|
|
918
|
-
if (!params) {
|
|
919
|
-
cancel();
|
|
920
|
-
return;
|
|
921
|
-
}
|
|
922
|
-
pendingPermissionRequests.set(requestId, () => logDecision());
|
|
923
|
-
// Human decision time is outside the agent's inactivity budget. All timer
|
|
924
|
-
// resets stay paused until the last pending permission response is sent.
|
|
925
|
-
clearStageTimer();
|
|
926
|
-
try {
|
|
927
|
-
if (!onPermissionRequest) {
|
|
928
|
-
respond(defaultPermissionDecision({ optionRecords }, { permissionMode, cliParity: options.cliParity }));
|
|
929
|
-
return;
|
|
930
|
-
}
|
|
931
|
-
const request = {
|
|
932
|
-
requestId,
|
|
933
|
-
sessionId: asOptionalString(params.sessionId),
|
|
934
|
-
toolCall: toolCall ?? null,
|
|
935
|
-
options: optionRecords,
|
|
936
|
-
rawParams: params,
|
|
937
|
-
};
|
|
938
|
-
Promise.resolve(onPermissionRequest(request)).then(respond, cancel);
|
|
939
|
-
}
|
|
940
|
-
catch {
|
|
941
|
-
cancel();
|
|
942
|
-
}
|
|
943
|
-
};
|
|
944
|
-
const recoverFromModelSelectionError = () => {
|
|
945
|
-
state.setModelRequestId = null;
|
|
946
|
-
state.activeModel = state.activeModel || 'default';
|
|
947
|
-
send({ event: 'agent', payload: { type: 'status', label: 'model', model: state.activeModel } });
|
|
948
|
-
sendPrompt();
|
|
949
|
-
};
|
|
950
|
-
const effects = {
|
|
951
|
-
send,
|
|
952
|
-
fail,
|
|
953
|
-
failWithPayload,
|
|
954
|
-
writeRpc,
|
|
955
|
-
sendPrompt,
|
|
956
|
-
recoverFromModelSelectionError,
|
|
957
|
-
finishCleanPrompt,
|
|
958
|
-
emitVisibleTextDelta,
|
|
959
|
-
noteArtifactTextSuppression,
|
|
960
|
-
noteToolCallTextSuppression,
|
|
961
|
-
emitAcpRawShapeDiagnostic,
|
|
962
|
-
toolCallTextSuppressor,
|
|
963
|
-
runStartedAt,
|
|
964
|
-
modelUnavailableErrorCode,
|
|
965
|
-
accountFailureClassifier,
|
|
966
|
-
model,
|
|
967
|
-
onSessionInit,
|
|
968
|
-
resumeSessionId,
|
|
969
|
-
effectiveCwd,
|
|
970
|
-
mcpServers,
|
|
971
|
-
envFormat,
|
|
972
|
-
};
|
|
973
|
-
const parser = createJsonLineStream({ onError: error => fail(error.message), onMessage: ({ message: raw, rawLine }) => {
|
|
974
|
-
if (aborted || finished)
|
|
975
|
-
return;
|
|
976
|
-
resetStageTimer('response');
|
|
977
|
-
const obj = asObject(raw);
|
|
978
|
-
if (!obj)
|
|
979
|
-
return;
|
|
980
|
-
// First well-formed ACP JSON-RPC message = CLI ready. Caller dedupes, so
|
|
981
|
-
// re-notifying on later messages is harmless.
|
|
982
|
-
onCliReady?.();
|
|
983
|
-
const error = asObject(obj.error);
|
|
984
|
-
const params = asObject(obj.params);
|
|
985
|
-
const result = asObject(obj.result);
|
|
986
|
-
const rpcErr = rpcErrorMessage(obj);
|
|
987
|
-
if (rpcErr) {
|
|
988
|
-
handleRpcError({ state, effects, obj, error, rpcErr });
|
|
989
|
-
return;
|
|
990
|
-
}
|
|
991
|
-
if (obj.method === 'session/request_permission') {
|
|
992
|
-
replyPermission(obj);
|
|
993
|
-
return;
|
|
994
|
-
}
|
|
995
|
-
const update = asObject(params?.update);
|
|
996
|
-
if (obj.method === 'session/update' && update) {
|
|
997
|
-
handleSessionUpdate({ state, effects, update });
|
|
998
|
-
return;
|
|
999
|
-
}
|
|
1000
|
-
routeResultById({ state, effects, obj, result, rawLine });
|
|
1001
|
-
} });
|
|
1002
|
-
stdout.on('data', (chunk) => parser.feed({ chunk: chunk }));
|
|
1003
|
-
child.stderr?.setEncoding('utf8');
|
|
1004
|
-
child.stderr?.on('data', (chunk) => {
|
|
1005
|
-
if (!modelUnavailableErrorCode || finished)
|
|
1006
|
-
return;
|
|
1007
|
-
amrStderrRetryTail = `${amrStderrRetryTail}${String(chunk)}`.slice(-AMR_STDERR_RETRY_TAIL_LIMIT);
|
|
1008
|
-
const promotedPayload = promotedAmrStderrPayload(amrStderrRetryTail, accountFailureClassifier);
|
|
1009
|
-
if (promotedPayload)
|
|
1010
|
-
failWithPayload(promotedPayload);
|
|
1011
|
-
});
|
|
1012
|
-
child.on('close', (code, signal) => {
|
|
1013
|
-
clearStageTimer();
|
|
1014
|
-
parser.flush();
|
|
1015
|
-
if (!finished && !aborted && !fatal) {
|
|
1016
|
-
fail(`ACP session exited before completion (code=${code ?? 'null'}, signal=${signal ?? 'none'})`);
|
|
1017
|
-
}
|
|
1018
|
-
});
|
|
1019
|
-
child.on('error', (err) => fail(err.message));
|
|
1020
|
-
stdin.on('error', (err) => fail(`stdin error: ${err.message}`));
|
|
1021
|
-
writeRpc(1, 'initialize', {
|
|
1022
|
-
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
1023
|
-
clientCapabilities: { terminal: false },
|
|
1024
|
-
clientInfo: { name: clientName, version: clientVersion },
|
|
1025
|
-
}, 'initialize');
|
|
1026
|
-
// ACP requires pending permission requests to receive a terminal
|
|
1027
|
-
// `cancelled` response when the prompt turn is cancelled. Called before
|
|
1028
|
-
// closing stdin, which may otherwise make the response impossible to
|
|
1029
|
-
// deliver.
|
|
1030
|
-
const cancelPendingPermissionRequests = () => {
|
|
1031
|
-
for (const [requestId, logCancellation] of pendingPermissionRequests) {
|
|
1032
|
-
try {
|
|
1033
|
-
sendRpcResult(stdin, requestId, { outcome: { outcome: 'cancelled' } });
|
|
1034
|
-
}
|
|
1035
|
-
catch {
|
|
1036
|
-
// Closing stdin/process signalling below remains the fallback.
|
|
1037
|
-
}
|
|
1038
|
-
logCancellation();
|
|
1039
|
-
}
|
|
1040
|
-
pendingPermissionRequests.clear();
|
|
1041
|
-
};
|
|
1042
|
-
// Only cancel an established session; before session/new resolves there is
|
|
1043
|
-
// no sessionId to cancel, but the caller still closes stdin below.
|
|
1044
|
-
const sendSessionCancelIfEstablished = (activeStdin) => {
|
|
1045
|
-
if (!state.sessionId)
|
|
1046
|
-
return;
|
|
1047
|
-
try {
|
|
1048
|
-
sendRpc(activeStdin, state.nextId, 'session/cancel', { sessionId: state.sessionId });
|
|
1049
|
-
state.nextId += 1;
|
|
1050
|
-
}
|
|
1051
|
-
catch {
|
|
1052
|
-
// The caller owns process-signal fallback if the ACP transport is gone.
|
|
1053
|
-
}
|
|
1054
|
-
};
|
|
1055
|
-
return {
|
|
1056
|
-
/** Returns `true` when the session ended with a fatal protocol or transport error, allowing the caller to surface the failure. */
|
|
1057
|
-
hasFatalError() {
|
|
1058
|
-
return fatal;
|
|
1059
|
-
},
|
|
1060
|
-
// The durable upstream session handle to persist for resume, or null when
|
|
1061
|
-
// none was reported (older agents, or a handshake that never established a
|
|
1062
|
-
// session). Mirrors pi-rpc's getLastSessionPath().
|
|
1063
|
-
/** Returns the durable upstream session id (e.g. a vendor bridge's own session id) to persist for next-turn resume, or `null` when the agent did not report one. */
|
|
1064
|
-
getDurableSessionId() {
|
|
1065
|
-
return state.durableSessionId;
|
|
1066
|
-
},
|
|
1067
|
-
/** Returns `true` when the prompt request resolved cleanly without a fatal error and without an abort, even if the child process later exited via SIGTERM. */
|
|
1068
|
-
completedSuccessfully() {
|
|
1069
|
-
// Returns true when the prompt request resolved without a fatal error
|
|
1070
|
-
// and was not aborted. The chat consumer treats this as a successful
|
|
1071
|
-
// run even if the child process subsequently exited via SIGTERM
|
|
1072
|
-
// (which is expected for agents that don't shut down on stdin.end()).
|
|
1073
|
-
return finished && !fatal && !aborted;
|
|
1074
|
-
},
|
|
1075
|
-
/**
|
|
1076
|
-
* Aborts an in-progress ACP session. Sends `session/cancel` when a session
|
|
1077
|
-
* id has already been established, then always closes stdin so the agent
|
|
1078
|
-
* receives EOF and can tear down its own runtime (e.g. a vendor bridge's
|
|
1079
|
-
* private backing server). Idempotent — subsequent calls are no-ops.
|
|
1080
|
-
*/
|
|
1081
|
-
abort() {
|
|
1082
|
-
if (aborted || finished)
|
|
1083
|
-
return;
|
|
1084
|
-
aborted = true;
|
|
1085
|
-
finished = true;
|
|
1086
|
-
clearStageTimer();
|
|
1087
|
-
cancelPendingPermissionRequests();
|
|
1088
|
-
if (!child.stdin || child.stdin.destroyed || child.stdin.writableEnded)
|
|
1089
|
-
return;
|
|
1090
|
-
sendSessionCancelIfEstablished(child.stdin);
|
|
1091
|
-
// Always close stdin so the agent receives EOF and shuts down its own
|
|
1092
|
-
// runtime — some ACP bridges tear down a private backing server on EOF —
|
|
1093
|
-
// instead of lingering (and leaking that server) until the caller's
|
|
1094
|
-
// SIGTERM fallback fires. This also covers aborts during ACP startup,
|
|
1095
|
-
// before session/new returns. Mirrors the clean-completion path above.
|
|
1096
|
-
try {
|
|
1097
|
-
child.stdin.end();
|
|
1098
|
-
}
|
|
1099
|
-
catch {
|
|
1100
|
-
// Best effort; the caller still owns the SIGTERM/SIGKILL fallback.
|
|
1101
|
-
}
|
|
1102
|
-
},
|
|
1103
|
-
};
|
|
149
|
+
if (obj.method === 'session/request_permission') {
|
|
150
|
+
replyPermission({ run, raw: obj });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const update = asObject({ value: params?.update });
|
|
154
|
+
if (obj.method === 'session/update' && update) {
|
|
155
|
+
handleSessionUpdate({ state, effects, update });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (typeof obj.method === 'string') {
|
|
159
|
+
replyMethodNotFound({ run, obj });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
routeResultById({ state, effects, obj, result: asObject({ value: obj.result }), rawLine });
|
|
163
|
+
}
|
|
164
|
+
function replyMethodNotFound({ run, obj }) {
|
|
165
|
+
if (!isJsonRpcId(obj.id))
|
|
166
|
+
return;
|
|
167
|
+
try {
|
|
168
|
+
sendRpcError({ writable: run.stdin, id: obj.id, code: -32601, message: `Method not found: ${String(obj.method)}` });
|
|
169
|
+
}
|
|
170
|
+
catch { /* broken pipe: transport lifecycle owns process failure */ }
|
|
1104
171
|
}
|
|
1105
172
|
//# sourceMappingURL=session.js.map
|