@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
|
@@ -1,940 +1,22 @@
|
|
|
1
1
|
/** @module json-event-stream
|
|
2
2
|
* Multi-CLI JSON event parsing with per-handler stream state. */
|
|
3
3
|
import { createBoundedLineStream } from './core/bounded-line-stream.js';
|
|
4
|
-
import { sanitizeUntrustedText } from '@jini-ai/core/text';
|
|
5
4
|
import { handleAntigravityEvent } from './defs/antigravity/event-stream.js';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
function trimmedNonBlank(value) {
|
|
13
|
-
const trimmed = typeof value === 'string' ? value.trim() : '';
|
|
14
|
-
return trimmed || null;
|
|
15
|
-
}
|
|
16
|
-
function optionalString(value) {
|
|
17
|
-
return typeof value === 'string' ? value : undefined;
|
|
18
|
-
}
|
|
19
|
-
function optionalNumber(value) {
|
|
20
|
-
return typeof value === 'number' ? value : undefined;
|
|
21
|
-
}
|
|
22
|
-
/** Copies the numeric vendor counters named in `fields` into a `Usage`, skipping absent ones. */
|
|
23
|
-
function pickUsage(source, fields) {
|
|
24
|
-
const usage = {};
|
|
25
|
-
for (const [from, to] of fields) {
|
|
26
|
-
const value = source[from];
|
|
27
|
-
if (typeof value === 'number')
|
|
28
|
-
usage[to] = value;
|
|
29
|
-
}
|
|
30
|
-
return usage;
|
|
31
|
-
}
|
|
32
|
-
/** Routes a record frame to the handler registered for its `type`; unknown types are unhandled. */
|
|
33
|
-
function dispatchFrame(handlers, obj, onEvent, state) {
|
|
34
|
-
const handler = handlers.get(obj.type);
|
|
35
|
-
return handler ? handler(obj, onEvent, state) : false;
|
|
36
|
-
}
|
|
37
|
-
function safeParseJson(value) {
|
|
38
|
-
if (value == null)
|
|
39
|
-
return null;
|
|
40
|
-
if (typeof value === 'object')
|
|
41
|
-
return value;
|
|
42
|
-
if (typeof value !== 'string')
|
|
43
|
-
return null;
|
|
44
|
-
try {
|
|
45
|
-
return JSON.parse(value);
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
return null;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
function stringifyContent(value) {
|
|
52
|
-
if (typeof value === 'string')
|
|
53
|
-
return value;
|
|
54
|
-
if (value == null)
|
|
55
|
-
return '';
|
|
56
|
-
try {
|
|
57
|
-
return JSON.stringify(value);
|
|
58
|
-
}
|
|
59
|
-
catch {
|
|
60
|
-
// Current callers pass JSON.parse results or their fields, which cannot contain cycles or
|
|
61
|
-
// BigInts, so stringify cannot throw. Keep this fallback for future non-JSON callers without
|
|
62
|
-
// forcing a coverage test around data the current parser cannot produce.
|
|
63
|
-
return String(value);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
function parseJsonObjectsFromContent(value) {
|
|
67
|
-
// The caller requires CONNECTOR_TOOL_NOT_FOUND before parsing. Empty input also reaches the
|
|
68
|
-
// existing [] fallback naturally, so no separate empty-string branch is needed.
|
|
69
|
-
const trimmed = value.trim();
|
|
70
|
-
const direct = safeParseJson(trimmed);
|
|
71
|
-
if (isRecord(direct))
|
|
72
|
-
return [direct];
|
|
73
|
-
const objects = [];
|
|
74
|
-
for (const line of trimmed.split(/\r?\n/u)) {
|
|
75
|
-
const parsedLine = safeParseJson(line.trim());
|
|
76
|
-
if (isRecord(parsedLine))
|
|
77
|
-
objects.push(parsedLine);
|
|
78
|
-
}
|
|
79
|
-
return objects;
|
|
80
|
-
}
|
|
81
|
-
function extractConnectorApiError(value) {
|
|
82
|
-
if (isRecord(value.error)) {
|
|
83
|
-
if (typeof value.error.code === 'string')
|
|
84
|
-
return value.error;
|
|
85
|
-
if (isRecord(value.error.data) && isRecord(value.error.data.error)) {
|
|
86
|
-
const wrappedError = value.error.data.error;
|
|
87
|
-
if (typeof wrappedError.code === 'string')
|
|
88
|
-
return wrappedError;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
function connectorToolSelectionErrorMessage(content) {
|
|
94
|
-
if (!content.includes('CONNECTOR_TOOL_NOT_FOUND'))
|
|
95
|
-
return null;
|
|
96
|
-
const error = parseJsonObjectsFromContent(content)
|
|
97
|
-
.map(extractConnectorApiError)
|
|
98
|
-
.find((parsedError) => parsedError?.code === 'CONNECTOR_TOOL_NOT_FOUND');
|
|
99
|
-
if (!error)
|
|
100
|
-
return null;
|
|
101
|
-
const details = isRecord(error.details) ? error.details : {};
|
|
102
|
-
const connectorId = nonEmptyString(details.connectorId);
|
|
103
|
-
const toolName = nonEmptyString(details.toolName) ?? 'the requested connector tool';
|
|
104
|
-
const target = connectorId
|
|
105
|
-
? `Connector tool ${toolName} is not allowed for connector ${connectorId}.`
|
|
106
|
-
: `Connector tool ${toolName} is not allowed.`;
|
|
107
|
-
return `${target} Re-list the connector catalog and choose one of the currently allowed read-only tools.`;
|
|
108
|
-
}
|
|
109
|
-
function isNonNullObject(value) {
|
|
110
|
-
return value !== null && typeof value === 'object';
|
|
111
|
-
}
|
|
112
|
-
/** Unwrap string/record error envelopes, retaining string or numeric codes alongside messages. */
|
|
113
|
-
function extractErrorMessage(value, fallback) {
|
|
114
|
-
if (typeof value === 'string') {
|
|
115
|
-
const parsed = safeParseJson(value);
|
|
116
|
-
return isNonNullObject(parsed) ? extractErrorMessage(parsed, value) : value;
|
|
117
|
-
}
|
|
118
|
-
if (!isRecord(value))
|
|
119
|
-
return fallback;
|
|
120
|
-
const message = extractRecordErrorMessage(value, '');
|
|
121
|
-
const code = typeof value.code === 'number' ? String(value.code) : trimmedNonBlank(value.code);
|
|
122
|
-
return (code ? [code, message].filter(Boolean).join(': ') : message) || fallback;
|
|
123
|
-
}
|
|
124
|
-
/** Field precedence for an error object: detail, message (itself maybe JSON), error, data, name. */
|
|
125
|
-
function extractRecordErrorMessage(value, fallback) {
|
|
126
|
-
const detail = nonEmptyString(value.detail);
|
|
127
|
-
if (detail)
|
|
128
|
-
return detail;
|
|
129
|
-
const message = nonEmptyString(value.message);
|
|
130
|
-
if (message)
|
|
131
|
-
return extractErrorMessage(message, message);
|
|
132
|
-
const error = nonEmptyString(value.error);
|
|
133
|
-
if (error)
|
|
134
|
-
return error;
|
|
135
|
-
if (isNonNullObject(value.error))
|
|
136
|
-
return extractErrorMessage(value.error, fallback);
|
|
137
|
-
const dataMessage = isNonNullObject(value.data) ? extractErrorMessage(value.data, '') : '';
|
|
138
|
-
return dataMessage || nonEmptyString(value.name) || fallback;
|
|
139
|
-
}
|
|
140
|
-
function isRecoverableCodexReconnect(message) {
|
|
141
|
-
return (message.startsWith('Reconnecting...') &&
|
|
142
|
-
(message.includes('timeout waiting for child process to exit') ||
|
|
143
|
-
message.includes('stream disconnected before completion')));
|
|
144
|
-
}
|
|
145
|
-
const OPENCODE_USAGE_FIELDS = [
|
|
146
|
-
['input', 'input_tokens'],
|
|
147
|
-
['output', 'output_tokens'],
|
|
148
|
-
['reasoning', 'thought_tokens'],
|
|
149
|
-
];
|
|
150
|
-
const OPENCODE_CACHE_USAGE_FIELDS = [
|
|
151
|
-
['read', 'cached_read_tokens'],
|
|
152
|
-
['write', 'cached_write_tokens'],
|
|
153
|
-
];
|
|
154
|
-
function formatOpenCodeUsage(tokens) {
|
|
155
|
-
if (!isRecord(tokens))
|
|
156
|
-
return null;
|
|
157
|
-
const usage = {
|
|
158
|
-
...pickUsage(tokens, OPENCODE_USAGE_FIELDS),
|
|
159
|
-
...(isRecord(tokens.cache) ? pickUsage(tokens.cache, OPENCODE_CACHE_USAGE_FIELDS) : {}),
|
|
160
|
-
};
|
|
161
|
-
return Object.keys(usage).length > 0 ? usage : null;
|
|
162
|
-
}
|
|
163
|
-
function openCodePart(obj) {
|
|
164
|
-
return isRecord(obj.part) ? obj.part : {};
|
|
165
|
-
}
|
|
166
|
-
function handleOpenCodeStepStart(obj, onEvent) {
|
|
167
|
-
// `sessionID` is OpenCode's own session handle (capture-style resume).
|
|
168
|
-
// Surface it on the step-start status so the daemon can persist it to
|
|
169
|
-
// `agent_sessions` and replay it as `run -s <id>` next turn. OpenCode
|
|
170
|
-
// stamps it on every stream event; step_start is the turn opener, so a
|
|
171
|
-
// create turn always exposes it here.
|
|
172
|
-
onEvent({ type: 'status', label: 'running', sessionId: nonEmptyString(obj.sessionID) });
|
|
173
|
-
return true;
|
|
174
|
-
}
|
|
175
|
-
function handleOpenCodeText(obj, onEvent) {
|
|
176
|
-
const text = nonEmptyString(openCodePart(obj).text);
|
|
177
|
-
if (!text)
|
|
178
|
-
return false;
|
|
179
|
-
onEvent({ type: 'text_delta', delta: text });
|
|
180
|
-
return true;
|
|
181
|
-
}
|
|
182
|
-
function handleOpenCodeToolUse(obj, onEvent, state) {
|
|
183
|
-
const part = openCodePart(obj);
|
|
184
|
-
if (typeof part.tool !== 'string' || typeof part.callID !== 'string')
|
|
185
|
-
return false;
|
|
186
|
-
const statePart = isRecord(part.state) ? part.state : {};
|
|
187
|
-
const key = `${obj.sessionID || 'session'}:${part.callID}`;
|
|
188
|
-
if (!state.openCodeToolUses.has(key)) {
|
|
189
|
-
state.openCodeToolUses.add(key);
|
|
190
|
-
onEvent({
|
|
191
|
-
type: 'tool_use',
|
|
192
|
-
id: part.callID,
|
|
193
|
-
name: part.tool,
|
|
194
|
-
input: safeParseJson(statePart.input) ?? statePart.input ?? null,
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
if (statePart.status === 'completed') {
|
|
198
|
-
onEvent({
|
|
199
|
-
type: 'tool_result',
|
|
200
|
-
toolUseId: part.callID,
|
|
201
|
-
content: stringifyContent(statePart.output),
|
|
202
|
-
isError: false,
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
return true;
|
|
206
|
-
}
|
|
207
|
-
function handleOpenCodeStepFinish(obj, onEvent) {
|
|
208
|
-
const part = openCodePart(obj);
|
|
209
|
-
const usage = formatOpenCodeUsage(part.tokens);
|
|
210
|
-
if (usage) {
|
|
211
|
-
onEvent({ type: 'usage', usage, costUsd: optionalNumber(part.cost) });
|
|
212
|
-
}
|
|
213
|
-
return true;
|
|
214
|
-
}
|
|
215
|
-
function handleOpenCodeError(obj, onEvent) {
|
|
216
|
-
// OpenCode emits structured error frames on stdout (e.g. provider auth
|
|
217
|
-
// failures, network errors, schema mismatches) and still exits 0. Surface
|
|
218
|
-
// them as proper `error` events so server.ts's `sendAgentEvent` wrapper
|
|
219
|
-
// can flip the run to `failed` and forward a visible SSE error to the
|
|
220
|
-
// chat UI. Previously we downgraded these to `type:'raw'`, which is not
|
|
221
|
-
// rendered as an assistant message — the run looked like a fast clean
|
|
222
|
-
// success while the user actually got nothing back. See issue #691.
|
|
223
|
-
//
|
|
224
|
-
// Shape mirrors the qoder-stream contract (`{type, message, raw}`) so
|
|
225
|
-
// the daemon's existing error-handling path recognises it without
|
|
226
|
-
// further wiring.
|
|
227
|
-
const message = extractErrorMessage(obj.error ?? obj.message, 'OpenCode error');
|
|
228
|
-
onEvent({ type: 'error', message, raw: stringifyContent(obj) });
|
|
229
|
-
return true;
|
|
230
|
-
}
|
|
231
|
-
const OPENCODE_FRAME_HANDLERS = new Map([
|
|
232
|
-
['step_start', handleOpenCodeStepStart],
|
|
233
|
-
['text', handleOpenCodeText],
|
|
234
|
-
['tool_use', handleOpenCodeToolUse],
|
|
235
|
-
['step_finish', handleOpenCodeStepFinish],
|
|
236
|
-
['error', handleOpenCodeError],
|
|
237
|
-
]);
|
|
238
|
-
function handleOpenCodeEvent(obj, onEvent, state) {
|
|
239
|
-
if (!isRecord(obj))
|
|
240
|
-
return false;
|
|
241
|
-
return dispatchFrame(OPENCODE_FRAME_HANDLERS, obj, onEvent, state);
|
|
242
|
-
}
|
|
243
|
-
function initializingStatus(obj) {
|
|
244
|
-
return { type: 'status', label: 'initializing', model: optionalString(obj.model) };
|
|
245
|
-
}
|
|
246
|
-
function isGoogleAssistantText(obj) {
|
|
247
|
-
return (obj.type === 'message' &&
|
|
248
|
-
obj.role === 'assistant' &&
|
|
249
|
-
typeof obj.content === 'string' &&
|
|
250
|
-
obj.content.length > 0);
|
|
251
|
-
}
|
|
252
|
-
function handleGoogleInit(obj, onEvent) {
|
|
253
|
-
onEvent(initializingStatus(obj));
|
|
254
|
-
return true;
|
|
255
|
-
}
|
|
256
|
-
function handleGoogleMessage(obj, onEvent, state) {
|
|
257
|
-
if (obj.role === 'user')
|
|
258
|
-
return true;
|
|
259
|
-
if (!isGoogleAssistantText(obj))
|
|
260
|
-
return false;
|
|
261
|
-
const delta = stripDuplicateArtifactText(obj.content, state);
|
|
262
|
-
if (delta)
|
|
263
|
-
onEvent({ type: 'text_delta', delta });
|
|
264
|
-
return true;
|
|
265
|
-
}
|
|
266
|
-
function handleGoogleToolUse(obj, onEvent, state) {
|
|
267
|
-
if (typeof obj.tool_id !== 'string' || typeof obj.tool_name !== 'string')
|
|
268
|
-
return false;
|
|
269
|
-
const input = safeParseJson(obj.parameters) ?? obj.parameters ?? null;
|
|
270
|
-
const todoInput = obj.tool_name === 'write_todos' ? todoWriteInputFromParsedValue(input) : null;
|
|
271
|
-
if (todoInput) {
|
|
272
|
-
onEvent({
|
|
273
|
-
type: 'tool_use',
|
|
274
|
-
id: `${obj.tool_id}:todo-native`,
|
|
275
|
-
name: 'TodoWrite',
|
|
276
|
-
input: todoInput,
|
|
277
|
-
});
|
|
278
|
-
return true;
|
|
279
|
-
}
|
|
280
|
-
if (isFileWriteToolUse(obj.tool_name, input)) {
|
|
281
|
-
state.suppressNextArtifactText = true;
|
|
282
|
-
}
|
|
283
|
-
onEvent({
|
|
284
|
-
type: 'tool_use',
|
|
285
|
-
id: obj.tool_id,
|
|
286
|
-
name: obj.tool_name,
|
|
287
|
-
input,
|
|
288
|
-
});
|
|
289
|
-
return true;
|
|
290
|
-
}
|
|
291
|
-
function handleGoogleToolResult(obj, onEvent) {
|
|
292
|
-
if (typeof obj.tool_id !== 'string')
|
|
293
|
-
return false;
|
|
294
|
-
const error = isRecord(obj.error) ? obj.error : null;
|
|
295
|
-
const errorMessage = error ? extractErrorMessage(error, '') : '';
|
|
296
|
-
const output = typeof obj.output === 'string'
|
|
297
|
-
? obj.output
|
|
298
|
-
: errorMessage || stringifyContent(obj.output);
|
|
299
|
-
onEvent({
|
|
300
|
-
type: 'tool_result',
|
|
301
|
-
toolUseId: obj.tool_id,
|
|
302
|
-
content: output,
|
|
303
|
-
isError: obj.status === 'error' || Boolean(error),
|
|
304
|
-
});
|
|
305
|
-
return true;
|
|
306
|
-
}
|
|
307
|
-
function handleGoogleError(obj, onEvent) {
|
|
308
|
-
const severity = typeof obj.severity === 'string' ? obj.severity.toLowerCase() : '';
|
|
309
|
-
const message = extractErrorMessage(obj.message ?? obj.error, severity === 'warning' ? 'Google stream warning' : 'Google stream error');
|
|
310
|
-
if (severity === 'warning') {
|
|
311
|
-
onEvent({ type: 'status', label: 'warning', detail: message });
|
|
312
|
-
}
|
|
313
|
-
else {
|
|
314
|
-
onEvent({ type: 'error', message, raw: stringifyContent(obj) });
|
|
315
|
-
}
|
|
316
|
-
return true;
|
|
317
|
-
}
|
|
318
|
-
const GOOGLE_USAGE_FIELDS = [
|
|
319
|
-
['input_tokens', 'input_tokens'],
|
|
320
|
-
['output_tokens', 'output_tokens'],
|
|
321
|
-
['cached', 'cached_read_tokens'],
|
|
322
|
-
];
|
|
323
|
-
function handleGoogleResult(obj, onEvent) {
|
|
324
|
-
if (obj.status === 'error' || isRecord(obj.error)) {
|
|
325
|
-
onEvent({
|
|
326
|
-
type: 'error',
|
|
327
|
-
message: extractErrorMessage(obj.error, 'Google stream error'),
|
|
328
|
-
raw: stringifyContent(obj),
|
|
329
|
-
});
|
|
330
|
-
return true;
|
|
331
|
-
}
|
|
332
|
-
if (!isRecord(obj.stats))
|
|
333
|
-
return true;
|
|
334
|
-
onEvent({
|
|
335
|
-
type: 'usage',
|
|
336
|
-
usage: pickUsage(obj.stats, GOOGLE_USAGE_FIELDS),
|
|
337
|
-
durationMs: optionalNumber(obj.stats.duration_ms),
|
|
338
|
-
});
|
|
339
|
-
return true;
|
|
340
|
-
}
|
|
341
|
-
const GOOGLE_FRAME_HANDLERS = new Map([
|
|
342
|
-
['init', handleGoogleInit],
|
|
343
|
-
['message', handleGoogleMessage],
|
|
344
|
-
['tool_use', handleGoogleToolUse],
|
|
345
|
-
['tool_result', handleGoogleToolResult],
|
|
346
|
-
['error', handleGoogleError],
|
|
347
|
-
['result', handleGoogleResult],
|
|
348
|
-
]);
|
|
349
|
-
// Retain the neutral legacy wire decoder for stored streams; no CLI agent uses this kind.
|
|
350
|
-
function handleLegacyGoogleStreamEvent(obj, onEvent, state) {
|
|
351
|
-
if (!isRecord(obj))
|
|
352
|
-
return false;
|
|
353
|
-
if (!isGoogleAssistantText(obj)) {
|
|
354
|
-
flushPendingArtifactText(state, onEvent);
|
|
355
|
-
}
|
|
356
|
-
return dispatchFrame(GOOGLE_FRAME_HANDLERS, obj, onEvent, state);
|
|
357
|
-
}
|
|
358
|
-
function emitKimiToolCalls(toolCalls, onEvent) {
|
|
359
|
-
for (const rawCall of toolCalls) {
|
|
360
|
-
const call = isRecord(rawCall) ? rawCall : {};
|
|
361
|
-
const fn = isRecord(call.function) ? call.function : {};
|
|
362
|
-
const id = trimmedNonBlank(call.id);
|
|
363
|
-
const name = trimmedNonBlank(fn.name);
|
|
364
|
-
if (!id || !name)
|
|
365
|
-
continue;
|
|
366
|
-
const input = safeParseJson(fn.arguments) ?? fn.arguments ?? null;
|
|
367
|
-
onEvent({ type: 'tool_use', id, name, input });
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
function handleKimiAssistant(obj, onEvent) {
|
|
371
|
-
if (Array.isArray(obj.tool_calls)) {
|
|
372
|
-
emitKimiToolCalls(obj.tool_calls, onEvent);
|
|
373
|
-
return true;
|
|
374
|
-
}
|
|
375
|
-
const text = nonEmptyString(obj.content);
|
|
376
|
-
if (!text)
|
|
377
|
-
return false;
|
|
378
|
-
onEvent({ type: 'text_delta', delta: text });
|
|
379
|
-
return true;
|
|
380
|
-
}
|
|
381
|
-
function handleKimiToolResult(obj, onEvent) {
|
|
382
|
-
const toolUseId = trimmedNonBlank(obj.tool_call_id);
|
|
383
|
-
if (!toolUseId)
|
|
384
|
-
return false;
|
|
385
|
-
onEvent({
|
|
386
|
-
type: 'tool_result',
|
|
387
|
-
toolUseId,
|
|
388
|
-
content: stringifyContent(obj.content),
|
|
389
|
-
isError: false,
|
|
390
|
-
});
|
|
391
|
-
return true;
|
|
392
|
-
}
|
|
393
|
-
function handleKimiEvent(obj, onEvent) {
|
|
394
|
-
if (!isRecord(obj))
|
|
395
|
-
return false;
|
|
396
|
-
if (obj.role === 'assistant')
|
|
397
|
-
return handleKimiAssistant(obj, onEvent);
|
|
398
|
-
if (obj.role === 'tool')
|
|
399
|
-
return handleKimiToolResult(obj, onEvent);
|
|
400
|
-
return obj.role === 'meta' && obj.type === 'session.resume_hint';
|
|
401
|
-
}
|
|
402
|
-
function extractCursorText(message) {
|
|
403
|
-
const content = isRecord(message) ? message.content : undefined;
|
|
404
|
-
const blocks = Array.isArray(content) ? content : [];
|
|
405
|
-
return blocks
|
|
406
|
-
.filter((block) => isRecord(block) && block.type === 'text' && typeof block.text === 'string')
|
|
407
|
-
.map((block) => block.text)
|
|
408
|
-
.join('');
|
|
409
|
-
}
|
|
410
|
-
/** Ordered status buckets: the first rule whose exact alias or prefix matches wins; else `pending`. */
|
|
411
|
-
const TODO_STATUS_RULES = [
|
|
412
|
-
{ status: 'completed', exact: ['complete', 'done'], prefixes: ['completed'] },
|
|
413
|
-
{ status: 'in_progress', exact: ['doing', 'active'], prefixes: ['in_progress'] },
|
|
414
|
-
{ status: 'stopped', exact: [], prefixes: ['stopped', 'failed', 'blocked', 'canceled', 'cancelled'] },
|
|
415
|
-
];
|
|
416
|
-
function normalizeTodoStatus(value) {
|
|
417
|
-
const status = typeof value === 'string'
|
|
418
|
-
? value.trim().toLowerCase().replace(/[-\s]+/g, '_')
|
|
419
|
-
: '';
|
|
420
|
-
const rule = TODO_STATUS_RULES.find((candidate) => candidate.exact.includes(status) || candidate.prefixes.some((prefix) => status.startsWith(prefix)));
|
|
421
|
-
return rule ? rule.status : 'pending';
|
|
422
|
-
}
|
|
423
|
-
/** Text fields of a to-do item in precedence order; the first string-typed one wins, even when empty. */
|
|
424
|
-
const TODO_CONTENT_FIELDS = ['content', 'label', 'description', 'text'];
|
|
425
|
-
function todoFromItem(raw) {
|
|
426
|
-
if (!isRecord(raw))
|
|
427
|
-
return null;
|
|
428
|
-
const field = TODO_CONTENT_FIELDS.find((key) => typeof raw[key] === 'string');
|
|
429
|
-
const content = field ? raw[field] : '';
|
|
430
|
-
if (!content)
|
|
431
|
-
return null;
|
|
432
|
-
return {
|
|
433
|
-
content,
|
|
434
|
-
status: raw.completed === true
|
|
435
|
-
? 'completed'
|
|
436
|
-
: normalizeTodoStatus(raw.status),
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
// Takes `unknown[]`, not `unknown`: every real call site
|
|
440
|
-
// (`todoWriteInputFromParsedValue`'s three call sites and
|
|
441
|
-
// `codexTodoListInput`) already runs `Array.isArray(...)` before calling in,
|
|
442
|
-
// so a runtime `!Array.isArray` guard here was dead code for every real
|
|
443
|
-
// caller. Narrowed the parameter type to remove the branch instead of
|
|
444
|
-
// padding a test around unreachable data.
|
|
445
|
-
function todoWriteInputFromItems(items) {
|
|
446
|
-
const todos = items
|
|
447
|
-
.map(todoFromItem)
|
|
448
|
-
.filter((todo) => todo !== null);
|
|
449
|
-
return todos.length > 0 ? { todos } : null;
|
|
450
|
-
}
|
|
451
|
-
function todoWriteInputFromParsedValue(value) {
|
|
452
|
-
if (Array.isArray(value))
|
|
453
|
-
return todoWriteInputFromItems(value);
|
|
454
|
-
if (!isRecord(value))
|
|
455
|
-
return null;
|
|
456
|
-
if (Array.isArray(value.todos))
|
|
457
|
-
return todoWriteInputFromItems(value.todos);
|
|
458
|
-
if (Array.isArray(value.todo))
|
|
459
|
-
return todoWriteInputFromItems(value.todo);
|
|
460
|
-
return null;
|
|
461
|
-
}
|
|
462
|
-
function stripDuplicateArtifactText(text, state) {
|
|
463
|
-
if (!state.suppressNextArtifactText &&
|
|
464
|
-
!state.suppressDuplicateArtifactText &&
|
|
465
|
-
state.artifactOpenCandidate.length === 0) {
|
|
466
|
-
return text;
|
|
467
|
-
}
|
|
468
|
-
const openTag = '<artifact';
|
|
469
|
-
const current = `${state.artifactOpenCandidate}${text}`;
|
|
470
|
-
state.artifactOpenCandidate = '';
|
|
471
|
-
if (state.suppressDuplicateArtifactText) {
|
|
472
|
-
const closeIndex = current.indexOf('</artifact>');
|
|
473
|
-
if (closeIndex === -1)
|
|
474
|
-
return '';
|
|
475
|
-
state.suppressDuplicateArtifactText = false;
|
|
476
|
-
state.suppressNextArtifactText = false;
|
|
477
|
-
return stripDuplicateArtifactText(current.slice(closeIndex + '</artifact>'.length), state);
|
|
478
|
-
}
|
|
479
|
-
const openIndex = current.indexOf(openTag);
|
|
480
|
-
if (openIndex === -1) {
|
|
481
|
-
const candidateLength = artifactOpenCandidateLength(current, openTag);
|
|
482
|
-
if (state.suppressNextArtifactText && candidateLength > 0) {
|
|
483
|
-
state.artifactOpenCandidate = current.slice(-candidateLength);
|
|
484
|
-
return current.slice(0, -candidateLength);
|
|
485
|
-
}
|
|
486
|
-
// Reaching here with `suppressNextArtifactText` false is structurally
|
|
487
|
-
// unreachable. To get past the top guard without it, `artifactOpenCandidate`
|
|
488
|
-
// must have been non-empty at entry — but the only place that sets a
|
|
489
|
-
// non-empty candidate is the branch right above (which requires this same
|
|
490
|
-
// flag to be true when it does), and the only place that clears the
|
|
491
|
-
// candidate other than the unconditional reset at the top of this function
|
|
492
|
-
// (`flushPendingArtifactText`) clears the flag in the same breath. So a
|
|
493
|
-
// leftover non-empty candidate always implies the flag is still true too.
|
|
494
|
-
// No `if` needed — it's always true by the time we get here.
|
|
495
|
-
state.suppressNextArtifactText = false;
|
|
496
|
-
return current;
|
|
497
|
-
}
|
|
498
|
-
state.suppressDuplicateArtifactText = true;
|
|
499
|
-
state.suppressNextArtifactText = false;
|
|
500
|
-
const prefix = `${state.pendingArtifactText}${current.slice(0, openIndex)}`;
|
|
501
|
-
state.pendingArtifactText = '';
|
|
502
|
-
return `${prefix}${stripDuplicateArtifactText(current.slice(openIndex), state)}`;
|
|
503
|
-
}
|
|
504
|
-
function artifactOpenCandidateLength(text, openTag) {
|
|
505
|
-
const max = Math.min(openTag.length - 1, text.length);
|
|
506
|
-
for (let len = max; len > 0; len -= 1) {
|
|
507
|
-
if (openTag.startsWith(text.slice(-len)))
|
|
508
|
-
return len;
|
|
509
|
-
}
|
|
510
|
-
return 0;
|
|
511
|
-
}
|
|
512
|
-
function flushPendingArtifactText(state, onEvent) {
|
|
513
|
-
const delta = `${state.pendingArtifactText}${state.artifactOpenCandidate}`;
|
|
514
|
-
if (!delta)
|
|
515
|
-
return;
|
|
516
|
-
state.pendingArtifactText = '';
|
|
517
|
-
state.artifactOpenCandidate = '';
|
|
518
|
-
state.suppressNextArtifactText = false;
|
|
519
|
-
onEvent({ type: 'text_delta', delta });
|
|
520
|
-
}
|
|
521
|
-
function isFileWriteToolUse(toolName, input) {
|
|
522
|
-
if (!isRecord(input))
|
|
523
|
-
return false;
|
|
524
|
-
const path = [input.file_path, input.path].find((value) => typeof value === 'string') ?? '';
|
|
525
|
-
const writesFile = toolName === 'write_file' ||
|
|
526
|
-
toolName === 'write' ||
|
|
527
|
-
toolName === 'replace' ||
|
|
528
|
-
toolName === 'edit';
|
|
529
|
-
if (!writesFile)
|
|
530
|
-
return false;
|
|
531
|
-
if (/\.(html|htm|css|js|jsx|ts|tsx|md)$/iu.test(path))
|
|
532
|
-
return true;
|
|
533
|
-
return typeof input.content === 'string' || typeof input.new_string === 'string';
|
|
534
|
-
}
|
|
535
|
-
function codexTodoListInput(item) {
|
|
536
|
-
if (item.type !== 'todo_list' || !Array.isArray(item.items))
|
|
537
|
-
return null;
|
|
538
|
-
return todoWriteInputFromItems(item.items);
|
|
539
|
-
}
|
|
540
|
-
function emitCodexTodoList(item, onEvent) {
|
|
541
|
-
if (typeof item.id !== 'string')
|
|
542
|
-
return false;
|
|
543
|
-
const input = codexTodoListInput(item);
|
|
544
|
-
if (!input)
|
|
545
|
-
return false;
|
|
546
|
-
onEvent({
|
|
547
|
-
type: 'tool_use',
|
|
548
|
-
id: item.id,
|
|
549
|
-
name: 'TodoWrite',
|
|
550
|
-
input,
|
|
551
|
-
});
|
|
552
|
-
return true;
|
|
553
|
-
}
|
|
554
|
-
function hasStringId(item) {
|
|
555
|
-
return typeof item.id === 'string';
|
|
556
|
-
}
|
|
557
|
-
/** Marks `key` as emitted in `state.codexToolUses`; `true` only the first time (Codex repeats frames per call). */
|
|
558
|
-
function claimCodexToolUse(state, key) {
|
|
559
|
-
if (state.codexToolUses.has(key))
|
|
560
|
-
return false;
|
|
561
|
-
state.codexToolUses.add(key);
|
|
562
|
-
return true;
|
|
563
|
-
}
|
|
564
|
-
function resetCodexAgentMessageBoundary(state) {
|
|
565
|
-
state.codexPreviousEventWasAgentMessage = false;
|
|
566
|
-
state.codexLastAgentMessageEndedWithNewline = false;
|
|
567
|
-
}
|
|
568
|
-
/** Emits a Codex `error` only for the first error of the stream; later ones are dropped. */
|
|
569
|
-
function emitCodexErrorOnce(message, onEvent, state) {
|
|
570
|
-
if (state.codexErrorEmitted)
|
|
571
|
-
return;
|
|
572
|
-
state.codexErrorEmitted = true;
|
|
573
|
-
onEvent({ type: 'error', message });
|
|
574
|
-
}
|
|
575
|
-
function codexMcpToolName(item) {
|
|
576
|
-
const tool = nonEmptyString(item.tool);
|
|
577
|
-
// Preserve the bridge's catalog names; external MCP must never masquerade as Bash/Edit.
|
|
578
|
-
// A Jini call is named `mcp__jini__X` exactly as Claude Code names it: the daemon bridge also
|
|
579
|
-
// reports a direct call as its own `X` row, and @jini-ai/chat folds the pair into one row only
|
|
580
|
-
// when the CLI row carries the MCP prefix (a bare `X` drew every Codex direct call twice).
|
|
581
|
-
const server = typeof item.server === 'string' ? item.server : 'external';
|
|
582
|
-
return `mcp__${server}__${tool ?? 'call'}`;
|
|
583
|
-
}
|
|
584
|
-
/**
|
|
585
|
-
* Emits the `tool_use` for one `item.type: 'mcp_tool_call'` item, deduped per `item.id` via
|
|
586
|
-
* `state.codexToolUses` (the same dedup `command_execution`'s two call sites — `item.started` and
|
|
587
|
-
* `item.completed` — already rely on, since Codex reports both frames for one call).
|
|
588
|
-
*
|
|
589
|
-
* `item.tool` — the literal MCP tool name Codex called (`search_tools`, `describe_tool`,
|
|
590
|
-
* `execute_delegated_tool`) — is used verbatim (behind the `mcp__jini__` prefix, see
|
|
591
|
-
* {@link codexMcpToolName}) as the emitted `name`, never unwrapped to the
|
|
592
|
-
* delegated `toolId` inside `item.arguments`: `@jini-ai/chat`'s `ToolCard`/`DelegatedToolCard`
|
|
593
|
-
* already recover that id from `{toolId, input}` for `execute_delegated_tool` specifically (see that
|
|
594
|
-
* component's own doc), so duplicating the unwrap here would be a second, driftable copy of the same
|
|
595
|
-
* decision.
|
|
596
|
-
*
|
|
597
|
-
* @param item - The `item.started`/`item.completed` payload's `item` object.
|
|
598
|
-
* @param onEvent - Sink for the emitted `tool_use`.
|
|
599
|
-
* @param state - Parser state; only `codexToolUses` is read/written.
|
|
600
|
-
* @returns `true` iff this item is an `mcp_tool_call` with a usable id (whether or not a `tool_use`
|
|
601
|
-
* was newly emitted vs. already deduped) — this is what `handleCodexEvent`'s `item.started` branch
|
|
602
|
-
* uses to decide the frame was handled.
|
|
603
|
-
* @complexity O(1).
|
|
604
|
-
* @overallScore 100
|
|
605
|
-
*/
|
|
606
|
-
function emitCodexMcpToolUse(item, onEvent, state) {
|
|
607
|
-
if (item.type !== 'mcp_tool_call' || !hasStringId(item))
|
|
608
|
-
return false;
|
|
609
|
-
if (claimCodexToolUse(state, item.id)) {
|
|
610
|
-
onEvent({
|
|
611
|
-
type: 'tool_use',
|
|
612
|
-
id: item.id,
|
|
613
|
-
name: codexMcpToolName(item),
|
|
614
|
-
input: item.arguments ?? {},
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
return true;
|
|
618
|
-
}
|
|
619
|
-
function emitCodexBashToolUse(item, onEvent, state) {
|
|
620
|
-
if (!claimCodexToolUse(state, item.id))
|
|
621
|
-
return;
|
|
622
|
-
onEvent({
|
|
623
|
-
type: 'tool_use',
|
|
624
|
-
id: item.id,
|
|
625
|
-
name: 'Bash',
|
|
626
|
-
input: {
|
|
627
|
-
command: typeof item.command === 'string' ? item.command : '',
|
|
628
|
-
},
|
|
629
|
-
});
|
|
630
|
-
}
|
|
631
|
-
function emitCodexCollabToolCall(item, completed, onEvent, state) {
|
|
632
|
-
if (claimCodexToolUse(state, item.id)) {
|
|
633
|
-
onEvent({ type: 'tool_use', id: item.id,
|
|
634
|
-
name: typeof item.tool === 'string' ? item.tool : 'collab_tool_call', input: {} });
|
|
635
|
-
}
|
|
636
|
-
if (completed && claimCodexToolUse(state, `${item.id}:completed`)) {
|
|
637
|
-
onEvent({ type: 'tool_result', toolUseId: item.id,
|
|
638
|
-
content: 'Native agent action completed.', isError: item.status === 'failed' });
|
|
639
|
-
}
|
|
640
|
-
return true;
|
|
641
|
-
}
|
|
642
|
-
function handleCodexItemStarted(item, onEvent, state) {
|
|
643
|
-
if (emitCodexTodoList(item, onEvent)) {
|
|
644
|
-
resetCodexAgentMessageBoundary(state);
|
|
645
|
-
return true;
|
|
646
|
-
}
|
|
647
|
-
if (item.type === 'command_execution' && hasStringId(item)) {
|
|
648
|
-
resetCodexAgentMessageBoundary(state);
|
|
649
|
-
emitCodexBashToolUse(item, onEvent, state);
|
|
650
|
-
return true;
|
|
651
|
-
}
|
|
652
|
-
if (item.type !== 'mcp_tool_call')
|
|
653
|
-
return false;
|
|
654
|
-
resetCodexAgentMessageBoundary(state);
|
|
655
|
-
return emitCodexMcpToolUse(item, onEvent, state);
|
|
656
|
-
}
|
|
657
|
-
function handleCodexItemUpdated(item, onEvent, state) {
|
|
658
|
-
if (!emitCodexTodoList(item, onEvent))
|
|
659
|
-
return false;
|
|
660
|
-
resetCodexAgentMessageBoundary(state);
|
|
661
|
-
return true;
|
|
662
|
-
}
|
|
663
|
-
function completeCodexFileChange(item, onEvent, state) {
|
|
664
|
-
// Codex reports direct patches as file_change, rather than command_execution. Surface paths
|
|
665
|
-
// through the SAME native-tool event channel so audit sees edits without persisting patches.
|
|
666
|
-
if (claimCodexToolUse(state, item.id))
|
|
667
|
-
emitCodexFileChange(item, onEvent);
|
|
668
|
-
return true;
|
|
669
|
-
}
|
|
670
|
-
function emitCodexFileChange(item, onEvent) {
|
|
671
|
-
const changes = Array.isArray(item.changes) ? item.changes : [];
|
|
672
|
-
onEvent({ type: 'tool_use', id: item.id, name: 'apply_patch',
|
|
673
|
-
input: { paths: changes.filter(isRecord).map(change => change.path).filter(path => typeof path === 'string') } });
|
|
674
|
-
onEvent({ type: 'tool_result', toolUseId: item.id, content: 'File change reported by Codex.', isError: item.status === 'failed' });
|
|
675
|
-
}
|
|
676
|
-
function completeCodexCommand(item, onEvent, state) {
|
|
677
|
-
resetCodexAgentMessageBoundary(state);
|
|
678
|
-
emitCodexBashToolUse(item, onEvent, state);
|
|
679
|
-
const content = stringifyContent(item.aggregated_output ?? '');
|
|
680
|
-
onEvent({
|
|
681
|
-
type: 'tool_result',
|
|
682
|
-
toolUseId: item.id,
|
|
683
|
-
content,
|
|
684
|
-
isError: typeof item.exit_code === 'number' ? item.exit_code !== 0 : item.status === 'failed',
|
|
685
|
-
});
|
|
686
|
-
const connectorToolError = connectorToolSelectionErrorMessage(content);
|
|
687
|
-
if (connectorToolError)
|
|
688
|
-
emitCodexErrorOnce(connectorToolError, onEvent, state);
|
|
689
|
-
return true;
|
|
690
|
-
}
|
|
691
|
-
/**
|
|
692
|
-
* Select a failed MCP call's diagnostic without exposing arguments or result metadata.
|
|
693
|
-
* Codex 0.161.0's exec mapper carries result content/structured_content independently of error:
|
|
694
|
-
* https://github.com/openai/codex/blob/rust-v0.161.0/codex-rs/exec/src/event_processor_with_jsonl_output.rs#L195
|
|
695
|
-
* @returns Sanitized error text, or the generic failure when no diagnostic is present.
|
|
696
|
-
* @complexity O(n) time/space for n diagnostic characters, including the shared sanitizer pass.
|
|
697
|
-
*/
|
|
698
|
-
function codexMcpFailureContent({ item }, _options = {}) {
|
|
699
|
-
const error = trimmedNonBlank(extractErrorMessage(item.error, ''));
|
|
700
|
-
const result = isRecord(item.result) ? item.result : {};
|
|
701
|
-
const blocks = Array.isArray(result.content) ? result.content : [];
|
|
702
|
-
// Keep text verbatim until sanitizing so JSON error envelopes retain codes and recovery hints.
|
|
703
|
-
const text = blocks.filter(isRecord)
|
|
704
|
-
.filter(block => block.type === 'text')
|
|
705
|
-
.map(block => trimmedNonBlank(block.text))
|
|
706
|
-
.filter(Boolean)
|
|
707
|
-
.join('\n');
|
|
708
|
-
const structuredText = extractErrorMessage(result.structured_content, '');
|
|
709
|
-
const diagnostic = error || text || trimmedNonBlank(structuredText) || 'MCP tool call failed';
|
|
710
|
-
return sanitizeUntrustedText({ text: diagnostic });
|
|
711
|
-
}
|
|
712
|
-
function completeCodexMcpToolCall(item, onEvent, state) {
|
|
713
|
-
resetCodexAgentMessageBoundary(state);
|
|
714
|
-
// `item.started` normally already emitted the matching `tool_use` (see
|
|
715
|
-
// `emitCodexMcpToolUse`); this call is a no-op then, and only actually emits one for a
|
|
716
|
-
// call whose `item.started` frame this parser never saw (a truncated/mid-stream feed —
|
|
717
|
-
// the same fallback shape `command_execution`'s own `item.completed` branch above uses).
|
|
718
|
-
emitCodexMcpToolUse(item, onEvent, state);
|
|
719
|
-
// A call Codex's own approval gate denies before ever reaching the target MCP server
|
|
720
|
-
// reports back exactly this shape — `status: 'failed'`, `result: null`, an `error` object
|
|
721
|
-
// — which is otherwise indistinguishable from "never happened" downstream: no
|
|
722
|
-
// `tool_use`/`tool_result` pair means no audit row, no error card, nothing an operator or
|
|
723
|
-
// the model itself can ground a claim on. `isError` on `status !== 'completed'` (not a
|
|
724
|
-
// truthiness check on `item.error`) matches every other status branch in this file and
|
|
725
|
-
// stays correct even for a hypothetical future status this union does not name yet.
|
|
726
|
-
const isError = item.status !== 'completed';
|
|
727
|
-
const content = isError
|
|
728
|
-
? codexMcpFailureContent({ item })
|
|
729
|
-
: stringifyContent(item.result);
|
|
730
|
-
onEvent({ type: 'tool_result', toolUseId: item.id, content, isError });
|
|
731
|
-
return true;
|
|
732
|
-
}
|
|
733
|
-
function emitCodexAgentMessage(item, onEvent, state) {
|
|
734
|
-
const text = item.type === 'agent_message' ? nonEmptyString(item.text) : null;
|
|
735
|
-
if (!text)
|
|
736
|
-
return false;
|
|
737
|
-
const needsBoundary = state.codexPreviousEventWasAgentMessage &&
|
|
738
|
-
!state.codexLastAgentMessageEndedWithNewline &&
|
|
739
|
-
!text.startsWith('\n');
|
|
740
|
-
const delta = needsBoundary ? `\n${text}` : text;
|
|
741
|
-
onEvent({ type: 'text_delta', delta });
|
|
742
|
-
state.codexPreviousEventWasAgentMessage = true;
|
|
743
|
-
state.codexLastAgentMessageEndedWithNewline = text.endsWith('\n');
|
|
744
|
-
return true;
|
|
745
|
-
}
|
|
746
|
-
function handleCodexItemCompleted(item, onEvent, state) {
|
|
747
|
-
if (item.type === 'file_change' && hasStringId(item))
|
|
748
|
-
return completeCodexFileChange(item, onEvent, state);
|
|
749
|
-
if (emitCodexTodoList(item, onEvent)) {
|
|
750
|
-
resetCodexAgentMessageBoundary(state);
|
|
751
|
-
return true;
|
|
752
|
-
}
|
|
753
|
-
if (item.type === 'command_execution' && hasStringId(item))
|
|
754
|
-
return completeCodexCommand(item, onEvent, state);
|
|
755
|
-
if (item.type === 'mcp_tool_call' && hasStringId(item))
|
|
756
|
-
return completeCodexMcpToolCall(item, onEvent, state);
|
|
757
|
-
return emitCodexAgentMessage(item, onEvent, state);
|
|
758
|
-
}
|
|
759
|
-
/**
|
|
760
|
-
* Wraps a per-frame item handler with the checks every `item.*` frame shares: a record `item`, and
|
|
761
|
-
* native `collab_tool_call` items, which report the same way on started/updated/completed.
|
|
762
|
-
*/
|
|
763
|
-
function codexItemFrame(handleItem) {
|
|
764
|
-
return (obj, onEvent, state) => {
|
|
765
|
-
if (!isRecord(obj.item))
|
|
766
|
-
return false;
|
|
767
|
-
const item = obj.item;
|
|
768
|
-
if (item.type === 'collab_tool_call' && hasStringId(item)) {
|
|
769
|
-
return emitCodexCollabToolCall(item, obj.type === 'item.completed', onEvent, state);
|
|
770
|
-
}
|
|
771
|
-
return handleItem(item, onEvent, state);
|
|
772
|
-
};
|
|
773
|
-
}
|
|
774
|
-
function handleCodexError(obj, onEvent, state) {
|
|
775
|
-
const message = extractErrorMessage(obj.message ?? obj.error, 'Codex error');
|
|
776
|
-
// Reconnecting events are recoverable — treat as status warning, not fatal
|
|
777
|
-
if (isRecoverableCodexReconnect(message)) {
|
|
778
|
-
onEvent({ type: 'status', label: message });
|
|
779
|
-
return true;
|
|
780
|
-
}
|
|
781
|
-
emitCodexErrorOnce(message, onEvent, state);
|
|
782
|
-
return true;
|
|
783
|
-
}
|
|
784
|
-
function handleCodexTurnFailed(obj, onEvent, state) {
|
|
785
|
-
emitCodexErrorOnce(extractErrorMessage(obj.error ?? obj.message, 'Codex turn failed'), onEvent, state);
|
|
786
|
-
return true;
|
|
787
|
-
}
|
|
788
|
-
function handleCodexThreadStarted(obj, onEvent) {
|
|
789
|
-
// `thread_id` is Codex's own session handle, surfaced on the same
|
|
790
|
-
// `sessionId` status channel claude uses (claude-stream.ts). It serves two
|
|
791
|
-
// consumers: (1) the daemon persists it to `agent_sessions` and replays it
|
|
792
|
-
// as `exec resume <thread_id>` on the next turn (capture-style resume), and
|
|
793
|
-
// (2) it identifies this run's rollout file
|
|
794
|
-
// (`$CODEX_HOME/sessions/**/rollout-*-<thread_id>.jsonl`), the only place
|
|
795
|
-
// codex records per-call usage, which run_finished reads to recover the
|
|
796
|
-
// turn's first-call cache hit (codex's stream usage is cumulative only).
|
|
797
|
-
// Codex emits this both for a fresh `exec` and for `exec resume` (echoing
|
|
798
|
-
// the resumed id), so it is a stable capture point either way.
|
|
799
|
-
onEvent({ type: 'status', label: 'initializing', sessionId: nonEmptyString(obj.thread_id) });
|
|
800
|
-
return true;
|
|
801
|
-
}
|
|
802
|
-
function handleCodexTurnStarted(_obj, onEvent, state) {
|
|
803
|
-
resetCodexAgentMessageBoundary(state);
|
|
804
|
-
onEvent({ type: 'status', label: 'thinking' });
|
|
805
|
-
return true;
|
|
806
|
-
}
|
|
807
|
-
const CODEX_USAGE_FIELDS = [
|
|
808
|
-
['input_tokens', 'input_tokens'],
|
|
809
|
-
['output_tokens', 'output_tokens'],
|
|
810
|
-
['reasoning_output_tokens', 'thought_tokens'],
|
|
811
|
-
['cached_input_tokens', 'cached_read_tokens'],
|
|
812
|
-
];
|
|
813
|
-
function handleCodexTurnCompleted(obj, onEvent) {
|
|
814
|
-
if (!isRecord(obj.usage))
|
|
815
|
-
return false;
|
|
816
|
-
onEvent({ type: 'usage', usage: pickUsage(obj.usage, CODEX_USAGE_FIELDS) });
|
|
817
|
-
return true;
|
|
818
|
-
}
|
|
819
|
-
const CODEX_FRAME_HANDLERS = new Map([
|
|
820
|
-
['error', handleCodexError],
|
|
821
|
-
['turn.failed', handleCodexTurnFailed],
|
|
822
|
-
['thread.started', handleCodexThreadStarted],
|
|
823
|
-
['turn.started', handleCodexTurnStarted],
|
|
824
|
-
['item.started', codexItemFrame(handleCodexItemStarted)],
|
|
825
|
-
['item.updated', codexItemFrame(handleCodexItemUpdated)],
|
|
826
|
-
['item.completed', codexItemFrame(handleCodexItemCompleted)],
|
|
827
|
-
['turn.completed', handleCodexTurnCompleted],
|
|
828
|
-
]);
|
|
829
|
-
function handleCodexEvent(obj, onEvent, state) {
|
|
830
|
-
if (!isRecord(obj))
|
|
831
|
-
return false;
|
|
832
|
-
return dispatchFrame(CODEX_FRAME_HANDLERS, obj, onEvent, state);
|
|
833
|
-
}
|
|
834
|
-
function emitCursorTextDelta(text, onEvent, state) {
|
|
835
|
-
// Timestamped assistant events WITHOUT `model_call_id` are cursor-agent's
|
|
836
|
-
// real-time incremental deltas (`--stream-partial-output`): the final turn
|
|
837
|
-
// text is the in-order concatenation of every such delta. Emit each one
|
|
838
|
-
// verbatim — do NOT dedupe by content. Legitimately repeated deltas
|
|
839
|
-
// (`"ha"`, `"ha"` -> `"haha"`) or a delta that happens to be a prefix of
|
|
840
|
-
// earlier text are real content, not duplicates; content-based prefix or
|
|
841
|
-
// equality checks would silently drop them. Duplicate suppression and
|
|
842
|
-
// dropped-chunk recovery belong to the buffered terminal replay paths
|
|
843
|
-
// (`model_call_id` and no-timestamp events) via reconcileCursorTurnReplay.
|
|
844
|
-
//
|
|
845
|
-
// No `!text` guard: this function's only real call site
|
|
846
|
-
// (`handleCursorAssistant`, below) already returns early on `if (!text) return
|
|
847
|
-
// false;` before ever calling in, so `text` is always non-empty here. The
|
|
848
|
-
// guard was dead code for the one real caller; removed rather than padded
|
|
849
|
-
// with a test.
|
|
850
|
-
state.cursorTextSoFar += text;
|
|
851
|
-
onEvent({ type: 'text_delta', delta: text });
|
|
852
|
-
}
|
|
853
|
-
/**
|
|
854
|
-
* Reconcile a Cursor terminal replay against the text already emitted for the
|
|
855
|
-
* CURRENT turn. A terminal replay (either a `model_call_id` message or a
|
|
856
|
-
* non-timestamped final assistant message) carries the full text for the
|
|
857
|
-
* current turn only, so it must be compared against
|
|
858
|
-
* `cursorTextSoFar.slice(cursorTurnStart)` — NOT the whole cross-turn buffer,
|
|
859
|
-
* which would miss the current-turn prefix on later turns and re-append the
|
|
860
|
-
* whole replay (duplicate output like "secondsecond turn").
|
|
861
|
-
*
|
|
862
|
-
* Only a verified prefix permits suffix recovery: if the emitted turn text is
|
|
863
|
-
* a prefix of the replay (including the empty case where no chunk arrived),
|
|
864
|
-
* emit the missing suffix. On divergence (a non-final chunk was dropped, so
|
|
865
|
-
* the emitted text is not a prefix) leave the append-only stream untouched
|
|
866
|
-
* rather than duplicate already-shown text. Always advances the turn boundary.
|
|
867
|
-
*/
|
|
868
|
-
function reconcileCursorTurnReplay(text, onEvent, state) {
|
|
869
|
-
const emittedTurn = state.cursorTextSoFar.slice(state.cursorTurnStart);
|
|
870
|
-
if (text && text !== emittedTurn && text.startsWith(emittedTurn)) {
|
|
871
|
-
const suffix = text.slice(emittedTurn.length);
|
|
872
|
-
if (suffix)
|
|
873
|
-
onEvent({ type: 'text_delta', delta: suffix });
|
|
874
|
-
state.cursorTextSoFar += suffix;
|
|
875
|
-
}
|
|
876
|
-
state.cursorTurnStart = state.cursorTextSoFar.length;
|
|
877
|
-
}
|
|
878
|
-
function handleCursorAssistant(obj, onEvent, state) {
|
|
879
|
-
// Cursor sends a final assistant message that replays the full text for
|
|
880
|
-
// the current turn — either tagged with `model_call_id`, or (fallback)
|
|
881
|
-
// as a non-timestamped terminal assistant message. Both are reconciled
|
|
882
|
-
// against the current turn's emitted text via reconcileCursorTurnReplay.
|
|
883
|
-
const text = extractCursorText(obj.message);
|
|
884
|
-
if (typeof obj.model_call_id === 'string') {
|
|
885
|
-
reconcileCursorTurnReplay(text, onEvent, state);
|
|
886
|
-
return true;
|
|
887
|
-
}
|
|
888
|
-
if (!text)
|
|
889
|
-
return false;
|
|
890
|
-
if (typeof obj.timestamp_ms === 'number') {
|
|
891
|
-
// Incremental streaming chunk within a turn — accumulate as usual.
|
|
892
|
-
emitCursorTextDelta(text, onEvent, state);
|
|
893
|
-
return true;
|
|
894
|
-
}
|
|
895
|
-
// Non-timestamped final assistant message: a terminal replay that marks a
|
|
896
|
-
// turn boundary. Reconcile against the current turn (not the whole
|
|
897
|
-
// cross-turn buffer) so later fallback-terminated turns do not duplicate
|
|
898
|
-
// output, then advance the turn boundary.
|
|
899
|
-
reconcileCursorTurnReplay(text, onEvent, state);
|
|
900
|
-
return true;
|
|
901
|
-
}
|
|
902
|
-
const CURSOR_USAGE_FIELDS = [
|
|
903
|
-
['inputTokens', 'input_tokens'],
|
|
904
|
-
['outputTokens', 'output_tokens'],
|
|
905
|
-
['cacheReadTokens', 'cached_read_tokens'],
|
|
906
|
-
['cacheWriteTokens', 'cached_write_tokens'],
|
|
907
|
-
];
|
|
908
|
-
function handleCursorEvent(obj, onEvent, state) {
|
|
909
|
-
if (!isRecord(obj))
|
|
910
|
-
return false;
|
|
911
|
-
if (obj.type === 'system' && obj.subtype === 'init') {
|
|
912
|
-
onEvent(initializingStatus(obj));
|
|
913
|
-
return true;
|
|
914
|
-
}
|
|
915
|
-
if (obj.type === 'assistant' && obj.message)
|
|
916
|
-
return handleCursorAssistant(obj, onEvent, state);
|
|
917
|
-
if (obj.type === 'result' && isRecord(obj.usage)) {
|
|
918
|
-
onEvent({
|
|
919
|
-
type: 'usage',
|
|
920
|
-
usage: pickUsage(obj.usage, CURSOR_USAGE_FIELDS),
|
|
921
|
-
durationMs: optionalNumber(obj.duration_ms),
|
|
922
|
-
});
|
|
923
|
-
return true;
|
|
924
|
-
}
|
|
925
|
-
return false;
|
|
926
|
-
}
|
|
5
|
+
import { createCodexStreamState, handleCodexEvent } from './defs/codex/event-stream.js';
|
|
6
|
+
import { createOpenCodeStreamState, emitOpenCodeModelReceipt, handleOpenCodeEvent } from './defs/opencode/event-stream.js';
|
|
7
|
+
import { createLegacyGoogleStreamState, flushPendingArtifactText, handleLegacyGoogleStreamEvent } from './defs/gemini/event-stream.js';
|
|
8
|
+
import { handleKimiEvent } from './defs/kimi/event-stream.js';
|
|
9
|
+
import { createCursorStreamState, handleCursorEvent } from './defs/cursor-agent/event-stream.js';
|
|
10
|
+
import { isRecord } from './json-event-stream-shared.js';
|
|
927
11
|
const MODEL_RECEIPT_FRAME_TYPES = new Set(['session.created', 'thread.started', 'turn.started', 'model.changed']);
|
|
12
|
+
const MODEL_RECEIPT_EXTRACTORS = [emitOpenCodeModelReceipt];
|
|
928
13
|
// Preserve structured model receipts before vendor event translation. These fields describe
|
|
929
14
|
// session/turn/assistant-message metadata; generated text is never used for model identity.
|
|
930
15
|
function emitModelReceipts(obj, onEvent) {
|
|
931
16
|
if (!isRecord(obj))
|
|
932
17
|
return;
|
|
933
|
-
const
|
|
934
|
-
|
|
935
|
-
if (info?.role === 'assistant' && typeof info.modelID === 'string') {
|
|
936
|
-
onEvent({ type: 'status', label: 'model', model: info.providerID ? `${info.providerID}/${info.modelID}` : info.modelID });
|
|
937
|
-
}
|
|
18
|
+
for (const extract of MODEL_RECEIPT_EXTRACTORS)
|
|
19
|
+
extract(obj, onEvent);
|
|
938
20
|
if (typeof obj.model === 'string' && MODEL_RECEIPT_FRAME_TYPES.has(String(obj.type))) {
|
|
939
21
|
onEvent({ type: 'status', label: 'model', model: obj.model });
|
|
940
22
|
}
|
|
@@ -947,7 +29,7 @@ const PARSERS_BY_KIND = new Map([
|
|
|
947
29
|
['cursor-agent', handleCursorEvent],
|
|
948
30
|
['codex', handleCodexEvent],
|
|
949
31
|
]);
|
|
950
|
-
export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
32
|
+
export function createJsonEventStreamHandler({ kind, onEvent }, _optional = {}) {
|
|
951
33
|
const lines = createBoundedLineStream({
|
|
952
34
|
onLine: line => { const trimmed = line.trim(); if (trimmed)
|
|
953
35
|
handleLine(trimmed); },
|
|
@@ -955,17 +37,10 @@ export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
|
955
37
|
});
|
|
956
38
|
const state = {
|
|
957
39
|
antigravity: { textEmitted: false, toolUses: new Set(), toolResults: new Set() },
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
codexErrorEmitted: false,
|
|
963
|
-
codexPreviousEventWasAgentMessage: false,
|
|
964
|
-
codexLastAgentMessageEndedWithNewline: false,
|
|
965
|
-
suppressNextArtifactText: false,
|
|
966
|
-
suppressDuplicateArtifactText: false,
|
|
967
|
-
artifactOpenCandidate: '',
|
|
968
|
-
pendingArtifactText: '',
|
|
40
|
+
cursor: createCursorStreamState(),
|
|
41
|
+
opencode: createOpenCodeStreamState(),
|
|
42
|
+
codex: createCodexStreamState(),
|
|
43
|
+
legacyGoogle: createLegacyGoogleStreamState(),
|
|
969
44
|
};
|
|
970
45
|
const parse = PARSERS_BY_KIND.get(kind);
|
|
971
46
|
function handleLine(line) {
|
|
@@ -987,7 +62,7 @@ export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
|
987
62
|
}
|
|
988
63
|
function flush() {
|
|
989
64
|
lines.flush();
|
|
990
|
-
flushPendingArtifactText(state, onEvent);
|
|
65
|
+
flushPendingArtifactText({ state, onEvent });
|
|
991
66
|
}
|
|
992
67
|
return { feed, flush };
|
|
993
68
|
}
|