@jini-ai/agent-runtime 0.7.2 → 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 -13
- 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/copilot-stream.d.ts +0 -65
- package/dist/copilot-stream.js +0 -131
- package/dist/defs/antigravity.d.ts +0 -94
- package/dist/defs/antigravity.js +0 -320
- package/dist/defs/copilot.d.ts +0 -34
- package/dist/defs/copilot.js +0 -96
- package/dist/defs/gemini.d.ts +0 -24
- package/dist/defs/gemini.js +0 -81
- 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
|
@@ -104,8 +104,9 @@ import { redactSecrets } from '@jini-ai/core';
|
|
|
104
104
|
* set `isError` keeps its exact prior behavior.
|
|
105
105
|
* See docs/decisions/DR-001-provider-native-tool-lifecycle.md.
|
|
106
106
|
*/
|
|
107
|
-
import { createRoleMarkerGuard } from '../role-marker-guard.js';
|
|
107
|
+
import { createRoleMarkerGuard, emitGuardedTextDelta } from '../role-marker-guard.js';
|
|
108
108
|
import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connection-guard.js';
|
|
109
|
+
import {} from '@jini-ai/core/contracts/agents';
|
|
109
110
|
import { createTurnEndGuard } from './turn-end-guard.js';
|
|
110
111
|
import { trimCharsEnd } from '@jini-ai/core/text';
|
|
111
112
|
import { toolLoopVerdict } from './tool-loop-verdict.js';
|
|
@@ -203,7 +204,7 @@ function guardToolResult(result) {
|
|
|
203
204
|
return result;
|
|
204
205
|
}
|
|
205
206
|
/** Parses one `function.arguments` value: Ollama's native tool-call payload documents it as a native JSON object, but a strict/older server can still send a stringified blob — this tolerates either, falling back to the raw string on malformed JSON. */
|
|
206
|
-
export function parseOllamaToolCallArguments({ args }) {
|
|
207
|
+
export function parseOllamaToolCallArguments({ args }, _optional = {}) {
|
|
207
208
|
if (typeof args !== 'string')
|
|
208
209
|
return args;
|
|
209
210
|
try {
|
|
@@ -214,7 +215,7 @@ export function parseOllamaToolCallArguments({ args }) {
|
|
|
214
215
|
}
|
|
215
216
|
}
|
|
216
217
|
/** Resolves one raw `message.tool_calls[]` entry into an `OllamaToolCall`, or `null` when the entry is missing its `function`/`name` (malformed, so skipped rather than surfaced). `index` seeds the synthetic id fallback — see `OllamaToolCallParam`'s doc for why a call id is generated locally rather than trusted off the wire. */
|
|
217
|
-
export function resolveOllamaToolCall({ rawCall, index }) {
|
|
218
|
+
export function resolveOllamaToolCall({ rawCall, index }, _optional = {}) {
|
|
218
219
|
if (!isRecord(rawCall) || !isRecord(rawCall.function))
|
|
219
220
|
return null;
|
|
220
221
|
const name = typeof rawCall.function.name === 'string' ? rawCall.function.name : '';
|
|
@@ -225,7 +226,7 @@ export function resolveOllamaToolCall({ rawCall, index }) {
|
|
|
225
226
|
return { id, name, input };
|
|
226
227
|
}
|
|
227
228
|
/** Resolves every entry in `message.tool_calls` into `state.toolCalls`, then marks `finishReason: 'tool_calls'` once at least one resolved — mirrors the original inline loop's behavior of setting `finishReason` after the whole batch rather than per-call. */
|
|
228
|
-
export function handleOllamaToolCallsField({ state, message }) {
|
|
229
|
+
export function handleOllamaToolCallsField({ state, message }, _optional = {}) {
|
|
229
230
|
if (!Array.isArray(message.tool_calls))
|
|
230
231
|
return;
|
|
231
232
|
for (const rawCall of message.tool_calls) {
|
|
@@ -241,18 +242,8 @@ export function handleOllamaToolCallsField({ state, message }) {
|
|
|
241
242
|
* Returns `'break'` once the guard flags contamination, otherwise `'continue'` — same contract as
|
|
242
243
|
* `anthropic-messages.ts#handleAnthropicTextDelta`/`openai-chat.ts#handleOpenAiTextContentDelta`.
|
|
243
244
|
*/
|
|
244
|
-
export function handleOllamaTextContent({ state, content, onEvent }) {
|
|
245
|
-
|
|
246
|
-
if (safe.length > 0) {
|
|
247
|
-
state.fullText += safe;
|
|
248
|
-
onEvent({ type: 'text_delta', delta: safe });
|
|
249
|
-
}
|
|
250
|
-
if (!state.guard.contaminated)
|
|
251
|
-
return 'continue';
|
|
252
|
-
const warn = state.guard.warningEvent();
|
|
253
|
-
if (warn)
|
|
254
|
-
onEvent(warn);
|
|
255
|
-
return 'break';
|
|
245
|
+
export function handleOllamaTextContent({ state, content, onEvent }, _optional = {}) {
|
|
246
|
+
return emitGuardedTextDelta({ state, text: content, onEvent });
|
|
256
247
|
}
|
|
257
248
|
/**
|
|
258
249
|
* Reduces one already-parsed NDJSON line into `state`, reporting whether the caller's line loop
|
|
@@ -266,7 +257,7 @@ export function handleOllamaTextContent({ state, content, onEvent }) {
|
|
|
266
257
|
function nonEmptyContent(message) {
|
|
267
258
|
return message && typeof message.content === 'string' && message.content.length > 0 ? message.content : null;
|
|
268
259
|
}
|
|
269
|
-
export function processOllamaLine({ state, line, onEvent, emitEnd }) {
|
|
260
|
+
export function processOllamaLine({ state, line, onEvent, emitEnd }, _optional = {}) {
|
|
270
261
|
const message = isRecord(line.message) ? line.message : null;
|
|
271
262
|
const text = nonEmptyContent(message);
|
|
272
263
|
if (text !== null && handleOllamaTextContent({ state: state, content: text, onEvent: onEvent }) === 'break') {
|
|
@@ -343,7 +334,7 @@ async function openOllamaResponseStream(options, messages, emitEnd) {
|
|
|
343
334
|
return response.body;
|
|
344
335
|
}
|
|
345
336
|
/** Parses one NDJSON line, returning `undefined` for a malformed/empty line — JSON has no `undefined` literal, so a successful parse is never confused with a failed one. Extracted so the generator below never nests a `try`/`catch` inside its loops (see that function's doc). */
|
|
346
|
-
export function parseNdjsonLine({ line }) {
|
|
337
|
+
export function parseNdjsonLine({ line }, _optional = {}) {
|
|
347
338
|
try {
|
|
348
339
|
return JSON.parse(line);
|
|
349
340
|
}
|
|
@@ -352,7 +343,7 @@ export function parseNdjsonLine({ line }) {
|
|
|
352
343
|
}
|
|
353
344
|
}
|
|
354
345
|
/** Splits already-accumulated buffer content into complete newline-terminated lines (newline stripped) plus the remaining partial-line `remainder`. Pure — no I/O — so this buffering/splitting logic is exercised as plain value-in/value-out assertions instead of through the full streaming generator. */
|
|
355
|
-
export function splitNdjsonLines({ buffer }) {
|
|
346
|
+
export function splitNdjsonLines({ buffer }, _optional = {}) {
|
|
356
347
|
const lines = [];
|
|
357
348
|
let rest = buffer;
|
|
358
349
|
let newlineIndex;
|
|
@@ -363,7 +354,7 @@ export function splitNdjsonLines({ buffer }) {
|
|
|
363
354
|
return { lines, remainder: rest };
|
|
364
355
|
}
|
|
365
356
|
/** Trims and parses each complete line in `rawLines`, yielding only the ones that parsed to something other than `undefined` — a plain (non-async) generator so `decodeNdjsonStream` below can delegate to it with `yield*` instead of nesting a `for`/`if`/`if` inside its own `for await` loop. */
|
|
366
|
-
export function* parseNdjsonLines({ rawLines }) {
|
|
357
|
+
export function* parseNdjsonLines({ rawLines }, _optional = {}) {
|
|
367
358
|
for (const rawLine of rawLines) {
|
|
368
359
|
const line = rawLine.trim();
|
|
369
360
|
if (!line)
|
|
@@ -426,7 +417,7 @@ async function runSingleOllamaRequest(options, messages, emitEnd) {
|
|
|
426
417
|
* instead proceed to execute the pending tool calls — mirrors
|
|
427
418
|
* `anthropic-messages.ts#anthropicLoopExitReason`'s pure decision/effect split.
|
|
428
419
|
*/
|
|
429
|
-
export function ollamaLoopExitReason({ outcome, toolTurns, maxToolTurns }) {
|
|
420
|
+
export function ollamaLoopExitReason({ outcome, toolTurns, maxToolTurns }, _optional = {}) {
|
|
430
421
|
if (outcome.finishReason !== 'tool_calls' || outcome.toolCalls.length === 0)
|
|
431
422
|
return 'stop';
|
|
432
423
|
if (toolTurns >= maxToolTurns)
|
|
@@ -434,7 +425,7 @@ export function ollamaLoopExitReason({ outcome, toolTurns, maxToolTurns }) {
|
|
|
434
425
|
return null;
|
|
435
426
|
}
|
|
436
427
|
/** Builds the assistant continuation's `tool_calls` field — Ollama's native shape has no `id`/`type` on the wire (see `OllamaToolCallParam`'s doc). */
|
|
437
|
-
export function buildOllamaAssistantToolCalls({ toolCalls }) {
|
|
428
|
+
export function buildOllamaAssistantToolCalls({ toolCalls }, _optional = {}) {
|
|
438
429
|
return toolCalls.map((call) => ({ function: { name: call.name, arguments: call.input } }));
|
|
439
430
|
}
|
|
440
431
|
/**
|
|
@@ -443,7 +434,7 @@ export function buildOllamaAssistantToolCalls({ toolCalls }) {
|
|
|
443
434
|
* see module doc's "Design decision: native `tool`-role images" section for why no separate
|
|
444
435
|
* follow-up message is needed here, unlike `openai-chat.ts`/`azure-chat.ts`.
|
|
445
436
|
*/
|
|
446
|
-
export async function executeOllamaToolCalls({ executeTool, calls, onEvent }) {
|
|
437
|
+
export async function executeOllamaToolCalls({ executeTool, calls, onEvent }, _optional = {}) {
|
|
447
438
|
const toolResultMessages = [];
|
|
448
439
|
for (const call of calls) {
|
|
449
440
|
const rawResult = await executeTool(call);
|
|
@@ -474,7 +465,7 @@ export async function runOllamaToolTurn(requiredArgs, optionalArgs = {}) {
|
|
|
474
465
|
const options = { ...optionalArgs, ...requiredArgs };
|
|
475
466
|
const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
|
|
476
467
|
const executeTool = options.executeTool;
|
|
477
|
-
const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
|
|
468
|
+
const endGuard = createTurnEndGuard({ onEvent: options.onEvent, makeEndEvent: (reason) => ({ type: 'end', reason }) });
|
|
478
469
|
const emitEnd = endGuard.emitEnd;
|
|
479
470
|
let messages = options.messages.slice();
|
|
480
471
|
let toolTurns = 0;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { extractProviderErrorDetail } from './response-text.js';
|
|
2
|
+
import { type DecodedSseEvent } from './sse-decode.js';
|
|
3
|
+
import { type OpenAiCompatibleRequestInit, type OpenAiStreamState, type OpenAiTurnEvent, type OpenAiCompatibleRequestOutcome } from './openai-chat-types.js';
|
|
4
|
+
export declare const extractOpenAiErrorDetail: typeof extractProviderErrorDetail;
|
|
5
|
+
export type OpenAiFrameResult = 'continue' | 'done' | 'contaminated';
|
|
6
|
+
/**
|
|
7
|
+
* Reduces one decoded SSE frame into `state`, reporting what the caller's loop should do next:
|
|
8
|
+
* `'done'` on the `[DONE]` sentinel, `'contaminated'` once the role-marker guard trips on this
|
|
9
|
+
* frame's text delta, otherwise `'continue'`. Pulling per-frame dispatch out of the loop body
|
|
10
|
+
* turns what would be four sequential, nesting-penalized `if`s into a single function call plus
|
|
11
|
+
* one outcome check — see `runOpenAiCompatibleRequest`'s loop below.
|
|
12
|
+
*/
|
|
13
|
+
export declare function processOpenAiStreamFrame({ state, frame, onEvent }: {
|
|
14
|
+
state: OpenAiStreamState;
|
|
15
|
+
frame: DecodedSseEvent;
|
|
16
|
+
onEvent: (event: OpenAiTurnEvent) => void;
|
|
17
|
+
}, _optional?: Record<string, never>): OpenAiFrameResult;
|
|
18
|
+
/**
|
|
19
|
+
* Runs exactly one OpenAI-compatible (Chat Completions JSON wire format)
|
|
20
|
+
* streaming HTTP request and reduces its SSE events into a single outcome.
|
|
21
|
+
* Extracted so this SSE-reduction loop has exactly one implementation
|
|
22
|
+
* shared by every OpenAI-compatible provider turn-runner in this package:
|
|
23
|
+
* `runOpenAiToolTurn` itself (below), plus `azure-chat.ts#runAzureToolTurn`
|
|
24
|
+
* and `ollama-chat.ts#runOllamaToolTurn` — both target byte-identical
|
|
25
|
+
* chat-completions JSON, differing only in URL and auth. Callers own their
|
|
26
|
+
* own base-URL SSRF validation (`validateBaseUrl`) and URL/header/body
|
|
27
|
+
* construction *before* calling this function — it only knows how to run
|
|
28
|
+
* *a* request against whatever URL/headers/body it is handed, and has no
|
|
29
|
+
* opinion on any provider's defaults. Mirrors
|
|
30
|
+
* `anthropic-messages.ts#runSingleAnthropicRequest`'s `emitEnd` contract —
|
|
31
|
+
* see that function's doc.
|
|
32
|
+
*/
|
|
33
|
+
export declare function runOpenAiCompatibleRequest(requiredArgs: Pick<OpenAiCompatibleRequestInit, "url" | "headers" | "body" | "redactSecretsList" | "guardMessageId" | "providerLabel" | "onEvent" | "emitEnd" | "hasEnded">, optionalArgs?: Omit<OpenAiCompatibleRequestInit, "url" | "headers" | "body" | "redactSecretsList" | "guardMessageId" | "providerLabel" | "onEvent" | "emitEnd" | "hasEnded">): Promise<OpenAiCompatibleRequestOutcome>;
|
|
34
|
+
//# sourceMappingURL=openai-chat-request.d.ts.map
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { redactSecrets } from '@jini-ai/core';
|
|
2
|
+
import { createRoleMarkerGuard } from '../role-marker-guard.js';
|
|
3
|
+
import { extractProviderErrorDetail } from './response-text.js';
|
|
4
|
+
import { pinnedFetch } from './connection-guard.js';
|
|
5
|
+
import { decodeSseStream } from './sse-decode.js';
|
|
6
|
+
import { omitKeys } from '../core/omit-keys.js';
|
|
7
|
+
import {} from './openai-chat-types.js';
|
|
8
|
+
import { parseOpenAiSseData, applyOpenAiStreamUsage, firstOpenAiChoice, handleOpenAiChoiceDelta, resolveOpenAiToolCalls, emitPendingOpenAiToolUseEvents } from './openai-chat-stream.js';
|
|
9
|
+
const DONE_SENTINEL = '[DONE]';
|
|
10
|
+
export const extractOpenAiErrorDetail = extractProviderErrorDetail;
|
|
11
|
+
/** Tool-schema retry has precedence; consume only the hook that selected a replacement body. */
|
|
12
|
+
function resolveOpenAiRetry({ init, status, rawText }, _options = {}) {
|
|
13
|
+
const toolRetryBody = init.retryToolBody?.({ status, rawErrorText: rawText, body: init.body });
|
|
14
|
+
if (toolRetryBody) {
|
|
15
|
+
const retryInit = omitKeys({ source: init, keys: ['retryToolBody'] });
|
|
16
|
+
return { type: 'retry', retryInit: { ...retryInit, body: toolRetryBody } };
|
|
17
|
+
}
|
|
18
|
+
const retryBody = init.retryableBody?.(status, rawText);
|
|
19
|
+
if (retryBody) {
|
|
20
|
+
const retryInit = omitKeys({ source: init, keys: ['retryableBody'] });
|
|
21
|
+
return { type: 'retry', retryInit: { ...retryInit, body: retryBody } };
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Opens the streaming POST and validates the response, returning its readable body once every
|
|
27
|
+
* pre-stream failure mode (network error, non-2xx status with no retry available, missing body)
|
|
28
|
+
* has been ruled out. Calls `emitEnd('error')` and returns `{type: 'ended'}` itself on any of
|
|
29
|
+
* those — the caller only has to branch on the outcome's `type`, keeping `hasEnded()` as the sole
|
|
30
|
+
* gate for every exit path (see `runOpenAiCompatibleRequest`'s doc).
|
|
31
|
+
*/
|
|
32
|
+
async function requestOpenAiCompatibleStream({ init }, _options = {}) {
|
|
33
|
+
const { onEvent, emitEnd } = init;
|
|
34
|
+
let response;
|
|
35
|
+
try {
|
|
36
|
+
response = await (init.fetchImpl ?? pinnedFetch)({ url: init.url, init: {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: init.headers,
|
|
39
|
+
body: JSON.stringify(init.body),
|
|
40
|
+
// The caller's SSRF check (`validateBaseUrlResolved`) only ever sees the
|
|
41
|
+
// ORIGINAL url. Following a redirect would let a public, guard-passing
|
|
42
|
+
// endpoint hand back a `302 -> http://169.254.169.254/...` and reach the
|
|
43
|
+
// address the guard exists to refuse — with the provider auth headers
|
|
44
|
+
// still attached. `model-catalog.ts`'s own fetch already refuses
|
|
45
|
+
// redirects for the same reason; a redirecting chat-completions endpoint
|
|
46
|
+
// is not a thing any supported provider does. `pinnedFetch` never
|
|
47
|
+
// follows one regardless (see its doc); `redirect: 'error'` here is
|
|
48
|
+
// self-documentation, not the mechanism.
|
|
49
|
+
redirect: 'error',
|
|
50
|
+
...(init.signal ? { signal: init.signal } : {}),
|
|
51
|
+
}, pinnedAddress: init.pinnedAddress });
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
55
|
+
onEvent({ type: 'error', message: redactSecrets({ input: message }, { exactSecrets: init.redactSecretsList }) });
|
|
56
|
+
emitEnd('error');
|
|
57
|
+
return { type: 'ended' };
|
|
58
|
+
}
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
const rawText = await response.text();
|
|
61
|
+
const retryOutcome = resolveOpenAiRetry({ init, status: response.status, rawText });
|
|
62
|
+
if (retryOutcome)
|
|
63
|
+
return retryOutcome;
|
|
64
|
+
onEvent({
|
|
65
|
+
type: 'error',
|
|
66
|
+
message: redactSecrets({ input: extractOpenAiErrorDetail({ rawText: rawText }) }, { exactSecrets: init.redactSecretsList }),
|
|
67
|
+
code: String(response.status),
|
|
68
|
+
});
|
|
69
|
+
emitEnd('error');
|
|
70
|
+
return { type: 'ended' };
|
|
71
|
+
}
|
|
72
|
+
if (!response.body) {
|
|
73
|
+
onEvent({ type: 'error', message: `${init.providerLabel} response had no body` });
|
|
74
|
+
emitEnd('error');
|
|
75
|
+
return { type: 'ended' };
|
|
76
|
+
}
|
|
77
|
+
return { type: 'body', body: response.body };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Reduces one decoded SSE frame into `state`, reporting what the caller's loop should do next:
|
|
81
|
+
* `'done'` on the `[DONE]` sentinel, `'contaminated'` once the role-marker guard trips on this
|
|
82
|
+
* frame's text delta, otherwise `'continue'`. Pulling per-frame dispatch out of the loop body
|
|
83
|
+
* turns what would be four sequential, nesting-penalized `if`s into a single function call plus
|
|
84
|
+
* one outcome check — see `runOpenAiCompatibleRequest`'s loop below.
|
|
85
|
+
*/
|
|
86
|
+
export function processOpenAiStreamFrame({ state, frame, onEvent }, _optional = {}) {
|
|
87
|
+
if (frame.data === DONE_SENTINEL)
|
|
88
|
+
return 'done';
|
|
89
|
+
const data = parseOpenAiSseData({ raw: frame.data });
|
|
90
|
+
if (!data)
|
|
91
|
+
return 'continue'; // malformed/empty keep-alive frame, or a non-object payload
|
|
92
|
+
applyOpenAiStreamUsage({ state: state, data: data, onEvent: onEvent });
|
|
93
|
+
const choice = firstOpenAiChoice({ data: data });
|
|
94
|
+
if (!choice)
|
|
95
|
+
return 'continue';
|
|
96
|
+
return handleOpenAiChoiceDelta({ state: state, choice: choice, onEvent: onEvent }) === 'break' ? 'contaminated' : 'continue';
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Runs exactly one OpenAI-compatible (Chat Completions JSON wire format)
|
|
100
|
+
* streaming HTTP request and reduces its SSE events into a single outcome.
|
|
101
|
+
* Extracted so this SSE-reduction loop has exactly one implementation
|
|
102
|
+
* shared by every OpenAI-compatible provider turn-runner in this package:
|
|
103
|
+
* `runOpenAiToolTurn` itself (below), plus `azure-chat.ts#runAzureToolTurn`
|
|
104
|
+
* and `ollama-chat.ts#runOllamaToolTurn` — both target byte-identical
|
|
105
|
+
* chat-completions JSON, differing only in URL and auth. Callers own their
|
|
106
|
+
* own base-URL SSRF validation (`validateBaseUrl`) and URL/header/body
|
|
107
|
+
* construction *before* calling this function — it only knows how to run
|
|
108
|
+
* *a* request against whatever URL/headers/body it is handed, and has no
|
|
109
|
+
* opinion on any provider's defaults. Mirrors
|
|
110
|
+
* `anthropic-messages.ts#runSingleAnthropicRequest`'s `emitEnd` contract —
|
|
111
|
+
* see that function's doc.
|
|
112
|
+
*/
|
|
113
|
+
export async function runOpenAiCompatibleRequest(requiredArgs, optionalArgs = {}) {
|
|
114
|
+
const init = { ...optionalArgs, ...requiredArgs };
|
|
115
|
+
const { onEvent, hasEnded } = init;
|
|
116
|
+
const fetchOutcome = await requestOpenAiCompatibleStream({ init });
|
|
117
|
+
if (fetchOutcome.type === 'ended') {
|
|
118
|
+
return { finishReason: null, toolCalls: [], text: '' };
|
|
119
|
+
}
|
|
120
|
+
if (fetchOutcome.type === 'retry') {
|
|
121
|
+
return (({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded, ...optionalArgs }) => runOpenAiCompatibleRequest({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded }, optionalArgs))(fetchOutcome.retryInit);
|
|
122
|
+
}
|
|
123
|
+
onEvent({ type: 'status', label: 'requesting' });
|
|
124
|
+
const state = {
|
|
125
|
+
guard: createRoleMarkerGuard({ messageId: init.guardMessageId }),
|
|
126
|
+
toolCalls: new Map(),
|
|
127
|
+
fullText: '',
|
|
128
|
+
finishReason: null,
|
|
129
|
+
usage: null,
|
|
130
|
+
};
|
|
131
|
+
for await (const frame of decodeSseStream({ source: fetchOutcome.body })) {
|
|
132
|
+
// No `hasEnded()` re-check at the top of this loop: the only in-loop call to `emitEnd`
|
|
133
|
+
// (contamination, below) is immediately followed by `break`, and every other call site is a
|
|
134
|
+
// pre-loop early `return` — traced across all five call sites in this function and
|
|
135
|
+
// `requestOpenAiCompatibleStream`, same proof as
|
|
136
|
+
// `anthropic-messages.ts#runSingleAnthropicRequest`. `hasEnded()` is still consulted once,
|
|
137
|
+
// after this loop, to decide whether pending tool_use events should still be emitted (a
|
|
138
|
+
// contaminating delta can arrive on a *later* chunk than the one that set `finish_reason`).
|
|
139
|
+
const result = processOpenAiStreamFrame({ state: state, frame: frame, onEvent: onEvent });
|
|
140
|
+
if (result === 'done' || result === 'contaminated') {
|
|
141
|
+
if (result === 'contaminated')
|
|
142
|
+
init.emitEnd('contaminated');
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const resolvedToolCalls = resolveOpenAiToolCalls({ pending: state.toolCalls });
|
|
147
|
+
if (state.finishReason === 'tool_calls' && !hasEnded()) {
|
|
148
|
+
emitPendingOpenAiToolUseEvents({ toolCalls: resolvedToolCalls, onEvent });
|
|
149
|
+
}
|
|
150
|
+
return { finishReason: state.finishReason, toolCalls: resolvedToolCalls, text: state.fullText };
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=openai-chat-request.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { parseSseJsonRecord } from './sse-decode.js';
|
|
2
|
+
import { type OpenAiStreamState, type OpenAiTurnEvent, type PendingToolCall, type OpenAiToolCall } from './openai-chat-types.js';
|
|
3
|
+
/** Parses one SSE frame's data as a JSON object, or `null` for a malformed/empty keep-alive frame or a non-object payload — both are tolerated by the caller as "nothing to do this frame". */
|
|
4
|
+
export declare const parseOpenAiSseData: typeof parseSseJsonRecord;
|
|
5
|
+
export declare function applyOpenAiStreamUsage({ state, data, onEvent }: {
|
|
6
|
+
state: OpenAiStreamState;
|
|
7
|
+
data: Record<string, unknown>;
|
|
8
|
+
onEvent: (event: OpenAiTurnEvent) => void;
|
|
9
|
+
}, _optional?: Record<string, never>): void;
|
|
10
|
+
/** The chunk's first (and, for Chat Completions, only) choice — `null` when the chunk carries no choice at all (e.g. a usage-only trailer chunk). */
|
|
11
|
+
export declare function firstOpenAiChoice({ data }: {
|
|
12
|
+
data: Record<string, unknown>;
|
|
13
|
+
}, _optional?: Record<string, never>): Record<string, unknown> | null;
|
|
14
|
+
/**
|
|
15
|
+
* Feeds one text delta through the role-marker guard and emits the safe portion. Returns
|
|
16
|
+
* `'break'` once the guard flags contamination (the caller ends the turn immediately), otherwise
|
|
17
|
+
* `'continue'` — same contract as `anthropic-messages.ts#handleAnthropicTextDelta`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function handleOpenAiTextContentDelta({ state, content, onEvent }: {
|
|
20
|
+
state: OpenAiStreamState;
|
|
21
|
+
content: string;
|
|
22
|
+
onEvent: (event: OpenAiTurnEvent) => void;
|
|
23
|
+
}, _optional?: Record<string, never>): 'continue' | 'break';
|
|
24
|
+
/** Builds a fresh `PendingToolCall` from the streaming chunk that first mentions a given tool-call index — OpenAI sends `id`/`function.name` once, on that first chunk, then dribbles `function.arguments` in across subsequent chunks (accumulated separately by the caller). */
|
|
25
|
+
export declare function newPendingOpenAiToolCall({ rawCall, index }: {
|
|
26
|
+
rawCall: Record<string, unknown>;
|
|
27
|
+
index: number;
|
|
28
|
+
}, _optional?: Record<string, never>): PendingToolCall;
|
|
29
|
+
/** Accumulates one `delta.tool_calls[]` entry from a streaming chunk into its running `PendingToolCall`. */
|
|
30
|
+
export declare function accumulateOpenAiToolCallDelta({ state, rawCall }: {
|
|
31
|
+
state: OpenAiStreamState;
|
|
32
|
+
rawCall: unknown;
|
|
33
|
+
}, _optional?: Record<string, never>): void;
|
|
34
|
+
/** Reduces one chunk's `choices[0]` — `finish_reason`, text content, and tool-call deltas — into `state`. Returns `'break'` when the text-delta guard detects contamination. */
|
|
35
|
+
export declare function handleOpenAiChoiceDelta({ state, choice, onEvent }: {
|
|
36
|
+
state: OpenAiStreamState;
|
|
37
|
+
choice: Record<string, unknown>;
|
|
38
|
+
onEvent: (event: OpenAiTurnEvent) => void;
|
|
39
|
+
}, _optional?: Record<string, never>): 'continue' | 'break';
|
|
40
|
+
/** Parses one accumulated tool call's `argsJson`, falling back to `{}` for empty or malformed JSON — mirrors Anthropic's identical fallback for `input_json_delta` accumulation in `anthropic-messages.ts`. */
|
|
41
|
+
export declare function resolveOpenAiToolCalls({ pending }: {
|
|
42
|
+
pending: ReadonlyMap<number, PendingToolCall>;
|
|
43
|
+
}, _optional?: Record<string, never>): OpenAiToolCall[];
|
|
44
|
+
export declare function emitPendingOpenAiToolUseEvents({ toolCalls, onEvent }: {
|
|
45
|
+
toolCalls: readonly OpenAiToolCall[];
|
|
46
|
+
onEvent: (event: OpenAiTurnEvent) => void;
|
|
47
|
+
}, _optional?: {}): void;
|
|
48
|
+
//# sourceMappingURL=openai-chat-stream.d.ts.map
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { emitGuardedTextDelta } from '../role-marker-guard.js';
|
|
2
|
+
import { parseSseJsonRecord } from './sse-decode.js';
|
|
3
|
+
import {} from './openai-chat-types.js';
|
|
4
|
+
function isRecord(value) {
|
|
5
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
6
|
+
}
|
|
7
|
+
/** Parses one SSE frame's data as a JSON object, or `null` for a malformed/empty keep-alive frame or a non-object payload — both are tolerated by the caller as "nothing to do this frame". */
|
|
8
|
+
export const parseOpenAiSseData = parseSseJsonRecord;
|
|
9
|
+
export function applyOpenAiStreamUsage({ state, data, onEvent }, _optional = {}) {
|
|
10
|
+
if (!isRecord(data.usage))
|
|
11
|
+
return;
|
|
12
|
+
state.usage = data.usage;
|
|
13
|
+
onEvent({ type: 'usage', usage: data.usage });
|
|
14
|
+
}
|
|
15
|
+
/** The chunk's first (and, for Chat Completions, only) choice — `null` when the chunk carries no choice at all (e.g. a usage-only trailer chunk). */
|
|
16
|
+
export function firstOpenAiChoice({ data }, _optional = {}) {
|
|
17
|
+
const choices = Array.isArray(data.choices) ? data.choices : [];
|
|
18
|
+
const choice = choices[0];
|
|
19
|
+
return isRecord(choice) ? choice : null;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Feeds one text delta through the role-marker guard and emits the safe portion. Returns
|
|
23
|
+
* `'break'` once the guard flags contamination (the caller ends the turn immediately), otherwise
|
|
24
|
+
* `'continue'` — same contract as `anthropic-messages.ts#handleAnthropicTextDelta`.
|
|
25
|
+
*/
|
|
26
|
+
export function handleOpenAiTextContentDelta({ state, content, onEvent }, _optional = {}) {
|
|
27
|
+
return emitGuardedTextDelta({ state, text: content, onEvent });
|
|
28
|
+
}
|
|
29
|
+
/** Builds a fresh `PendingToolCall` from the streaming chunk that first mentions a given tool-call index — OpenAI sends `id`/`function.name` once, on that first chunk, then dribbles `function.arguments` in across subsequent chunks (accumulated separately by the caller). */
|
|
30
|
+
export function newPendingOpenAiToolCall({ rawCall, index }, _optional = {}) {
|
|
31
|
+
const id = typeof rawCall.id === 'string' ? rawCall.id : `call_${index}`;
|
|
32
|
+
const fn = isRecord(rawCall.function) ? rawCall.function : {};
|
|
33
|
+
const name = typeof fn.name === 'string' ? fn.name : '';
|
|
34
|
+
return { id, name, argsJson: '' };
|
|
35
|
+
}
|
|
36
|
+
/** Accumulates one `delta.tool_calls[]` entry from a streaming chunk into its running `PendingToolCall`. */
|
|
37
|
+
export function accumulateOpenAiToolCallDelta({ state, rawCall }, _optional = {}) {
|
|
38
|
+
if (!isRecord(rawCall) || typeof rawCall.index !== 'number')
|
|
39
|
+
return;
|
|
40
|
+
let pending = state.toolCalls.get(rawCall.index);
|
|
41
|
+
if (!pending) {
|
|
42
|
+
pending = newPendingOpenAiToolCall({ rawCall: rawCall, index: rawCall.index });
|
|
43
|
+
state.toolCalls.set(rawCall.index, pending);
|
|
44
|
+
}
|
|
45
|
+
const fn = isRecord(rawCall.function) ? rawCall.function : null;
|
|
46
|
+
if (fn && typeof fn.arguments === 'string') {
|
|
47
|
+
pending.argsJson += fn.arguments;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function openAiDeltaText(delta) { return typeof delta.content === 'string' && delta.content.length > 0 ? delta.content : null; }
|
|
51
|
+
/** Reduces one chunk's `choices[0]` — `finish_reason`, text content, and tool-call deltas — into `state`. Returns `'break'` when the text-delta guard detects contamination. */
|
|
52
|
+
export function handleOpenAiChoiceDelta({ state, choice, onEvent }, _optional = {}) {
|
|
53
|
+
if (typeof choice.finish_reason === 'string') {
|
|
54
|
+
state.finishReason = choice.finish_reason;
|
|
55
|
+
}
|
|
56
|
+
const delta = isRecord(choice.delta) ? choice.delta : null;
|
|
57
|
+
if (!delta)
|
|
58
|
+
return 'continue';
|
|
59
|
+
const text = openAiDeltaText(delta);
|
|
60
|
+
if (text !== null && handleOpenAiTextContentDelta({ state: state, content: text, onEvent: onEvent }) === 'break')
|
|
61
|
+
return 'break';
|
|
62
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
63
|
+
for (const rawCall of delta.tool_calls) {
|
|
64
|
+
accumulateOpenAiToolCallDelta({ state: state, rawCall: rawCall });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return 'continue';
|
|
68
|
+
}
|
|
69
|
+
/** Parses one accumulated tool call's `argsJson`, falling back to `{}` for empty or malformed JSON — mirrors Anthropic's identical fallback for `input_json_delta` accumulation in `anthropic-messages.ts`. */
|
|
70
|
+
export function resolveOpenAiToolCalls({ pending }, _optional = {}) {
|
|
71
|
+
return Array.from(pending.values()).map((call) => {
|
|
72
|
+
let input = {};
|
|
73
|
+
if (call.argsJson.trim()) {
|
|
74
|
+
try {
|
|
75
|
+
input = JSON.parse(call.argsJson);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
input = {};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { id: call.id, name: call.name, input };
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
export function emitPendingOpenAiToolUseEvents({ toolCalls, onEvent }, _optional = {}) {
|
|
85
|
+
for (const call of toolCalls) {
|
|
86
|
+
onEvent({ type: 'tool_use', id: call.id, name: call.name, input: call.input });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
//# sourceMappingURL=openai-chat-stream.js.map
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type OpenAiContentPart, type OpenAiToolResult, type OpenAiTextPart, type OpenAiImageUrlPart, type OpenAiMessageParam, type OpenAiToolExecutor, type OpenAiToolCall, type OpenAiTurnEvent, type OpenAiToolCallParam } from './openai-chat-types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Validates one content part against OpenAI's real format/size constraints. Returns the violation
|
|
4
|
+
* reason, or `null` when the part is legal to send.
|
|
5
|
+
*
|
|
6
|
+
* A plain `https://` `image_url` (not a `data:` URI) is intentionally not size-checked: OpenAI's
|
|
7
|
+
* servers fetch that URL, not this adapter, so there is no local payload to bound — same threat-
|
|
8
|
+
* model split as `anthropic-messages.ts`'s URL-sourced skip (`connection-guard.ts`'s SSRF guard
|
|
9
|
+
* protects this adapter's own outbound `baseUrl` request, a different thing; an `image_url` that
|
|
10
|
+
* points at attacker-chosen infrastructure is a request OpenAI's own servers make, not this one).
|
|
11
|
+
*
|
|
12
|
+
* @complexity O(1) — reads `data.length`, never decodes or parses the base64 payload.
|
|
13
|
+
*/
|
|
14
|
+
export declare function invalidOpenAiContentPartReason({ part }: {
|
|
15
|
+
part: OpenAiContentPart;
|
|
16
|
+
}, _optional?: Record<string, never>): string | null;
|
|
17
|
+
export interface SanitizedOpenAiToolResult {
|
|
18
|
+
readonly content: string | readonly OpenAiContentPart[];
|
|
19
|
+
readonly isError: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Runtime guard applied to every `OpenAiToolExecutor` result before it is wired onto the outbound
|
|
23
|
+
* request or reported via `onEvent`. `OpenAiToolResult` is host-owned (see `OpenAiToolExecutor`'s
|
|
24
|
+
* "Host-owned tool execution" doc comment) — the TS content-part union only constrains a
|
|
25
|
+
* well-behaved host at compile time, not a buggy one at runtime, e.g. a screenshot helper that
|
|
26
|
+
* hands back an oversized PNG or a HEIC file mislabeled as `image/jpeg`. Rather than forwarding an
|
|
27
|
+
* invalid part and letting OpenAI reject the *entire* turn with an opaque upstream 400, this
|
|
28
|
+
* substitutes a plain-text `isError: true` result the model can see and react to — matching this
|
|
29
|
+
* package's existing security-conscious posture (`connection-guard.ts`'s SSRF guard,
|
|
30
|
+
* `role-marker-guard.ts`'s contamination guard, and `anthropic-messages.ts`'s identical guard).
|
|
31
|
+
*
|
|
32
|
+
* @complexity O(n) in the number of content parts; O(1) per part (see `invalidOpenAiContentPartReason`).
|
|
33
|
+
*/
|
|
34
|
+
export declare function sanitizeOpenAiToolResult({ result }: {
|
|
35
|
+
result: OpenAiToolResult;
|
|
36
|
+
}, _optional?: Record<string, never>): SanitizedOpenAiToolResult;
|
|
37
|
+
export interface SplitOpenAiToolResultContent {
|
|
38
|
+
readonly toolMessageContent: string | readonly OpenAiTextPart[];
|
|
39
|
+
readonly imageParts: readonly OpenAiImageUrlPart[];
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Splits one (already-sanitized) tool result's content into what can legally sit on the wire
|
|
43
|
+
* `role: 'tool'` message (text only — see module doc's "Tool messages cannot carry an image"
|
|
44
|
+
* section) and the `image_url` parts that must instead travel on a follow-up `user` message.
|
|
45
|
+
*
|
|
46
|
+
* A string `content` is left untouched (`imageParts: []`) — this is the pre-existing, unchanged
|
|
47
|
+
* path every current caller already exercises. For an array, text parts are kept in order for the
|
|
48
|
+
* `tool` message; if there is no text at all (an image-only result), a single placeholder text part
|
|
49
|
+
* is substituted so the `tool` message's content is never empty (OpenAI rejects empty content).
|
|
50
|
+
*
|
|
51
|
+
* @complexity O(n) in the number of content parts.
|
|
52
|
+
*/
|
|
53
|
+
export declare function splitOpenAiToolResultContent({ content }: {
|
|
54
|
+
content: string | readonly OpenAiContentPart[];
|
|
55
|
+
}, _optional?: Record<string, never>): SplitOpenAiToolResultContent;
|
|
56
|
+
export interface OpenAiToolExecutionOutcome {
|
|
57
|
+
readonly toolResultMessages: OpenAiMessageParam[];
|
|
58
|
+
readonly followUpParts: OpenAiContentPart[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Runs every pending tool call in order, sanitizing and splitting each result into its `tool`
|
|
62
|
+
* message plus any labeled image parts for the batch's single follow-up `user` message — see
|
|
63
|
+
* module doc's "Tool messages cannot carry an image" section for why the split exists and why the
|
|
64
|
+
* follow-up is assembled once per batch rather than per call.
|
|
65
|
+
*/
|
|
66
|
+
export declare function executeOpenAiToolCalls({ executeTool, calls, onEvent }: {
|
|
67
|
+
executeTool: OpenAiToolExecutor;
|
|
68
|
+
calls: readonly OpenAiToolCall[];
|
|
69
|
+
onEvent: (event: OpenAiTurnEvent) => void;
|
|
70
|
+
}, _optional?: Record<string, never>): Promise<OpenAiToolExecutionOutcome>;
|
|
71
|
+
/** Builds the assistant turn that records the model's pending tool calls in `messages` history — `content` falls back to `null` (never `''`) per the wire schema. */
|
|
72
|
+
export declare function buildOpenAiAssistantToolCallMessage({ text, toolCalls }: {
|
|
73
|
+
text: string;
|
|
74
|
+
toolCalls: readonly OpenAiToolCallParam[];
|
|
75
|
+
}, _optional?: Record<string, never>): OpenAiMessageParam;
|
|
76
|
+
/** Appends the batch's `tool` messages plus, when present, the single labeled-image follow-up message — see module doc's "Tool messages cannot carry an image" section for why the follow-up is at most one message per batch. */
|
|
77
|
+
export declare function buildOpenAiToolExchangeMessages({ toolResultMessages, followUpParts }: {
|
|
78
|
+
toolResultMessages: readonly OpenAiMessageParam[];
|
|
79
|
+
followUpParts: readonly OpenAiContentPart[];
|
|
80
|
+
}, _optional?: Record<string, never>): OpenAiMessageParam[];
|
|
81
|
+
//# sourceMappingURL=openai-chat-tool-results.d.ts.map
|