@jini-ai/agent-runtime 0.7.2 → 0.7.3-next.2
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 +6 -1
- package/dist/agent-protocol/acp/constants.js +7 -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 +161 -128
- 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 +231 -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 +28 -16
- 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
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { redactSecrets } from '@jini-ai/core';
|
|
2
1
|
/**
|
|
3
2
|
* @module providers/openai-chat
|
|
4
3
|
*
|
|
@@ -67,23 +66,20 @@ import { redactSecrets } from '@jini-ai/core';
|
|
|
67
66
|
* treating its own tool's output as a brand-new user request instead of a continuation of its own
|
|
68
67
|
* reasoning.
|
|
69
68
|
*/
|
|
70
|
-
import {
|
|
71
|
-
import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connection-guard.js';
|
|
72
|
-
import { decodeSseStream } from './sse-decode.js';
|
|
69
|
+
import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js';
|
|
73
70
|
import { buildOpenAIChatTokenParam } from './token-params.js';
|
|
74
71
|
import { createTurnEndGuard } from './turn-end-guard.js';
|
|
75
72
|
import { trimCharsEnd } from '@jini-ai/core/text';
|
|
76
73
|
import { toolLoopVerdict } from './tool-loop-verdict.js';
|
|
77
74
|
import { omitKeys } from '../core/omit-keys.js';
|
|
75
|
+
import {} from './openai-chat-types.js';
|
|
76
|
+
import { runOpenAiCompatibleRequest } from './openai-chat-request.js';
|
|
77
|
+
import { executeOpenAiToolCalls, buildOpenAiAssistantToolCallMessage, buildOpenAiToolExchangeMessages } from './openai-chat-tool-results.js';
|
|
78
78
|
const DEFAULT_OPENAI_BASE_URL = 'https://api.openai.com';
|
|
79
79
|
const DEFAULT_MAX_TOOL_TURNS = 8;
|
|
80
|
-
const DONE_SENTINEL = '[DONE]';
|
|
81
80
|
/** Matches OD's own default (`apps/daemon/src/routes/chat.ts`'s openai/azure handlers both fall back to this when the caller doesn't supply one) — a real, explicit bound is always sent, never an unbounded request. */
|
|
82
81
|
export const DEFAULT_OPENAI_MAX_TOKENS = 8192;
|
|
83
|
-
function
|
|
84
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
85
|
-
}
|
|
86
|
-
export function openAiRequestUrl({ baseUrl }) {
|
|
82
|
+
export function openAiRequestUrl({ baseUrl }, _optional = {}) {
|
|
87
83
|
const base = trimCharsEnd({ text: baseUrl ?? DEFAULT_OPENAI_BASE_URL, chars: '/' });
|
|
88
84
|
return /\/v\d+(\/|$)/.test(base) ? `${base}/chat/completions` : `${base}/v1/chat/completions`;
|
|
89
85
|
}
|
|
@@ -95,7 +91,7 @@ export function openAiHeaders(requiredArgs, optionalArgs = {}) {
|
|
|
95
91
|
...(options.extraHeaders ?? {}),
|
|
96
92
|
};
|
|
97
93
|
}
|
|
98
|
-
export function openAiRequestBody({ options, messages }) {
|
|
94
|
+
export function openAiRequestBody({ options, messages }, _optional = {}) {
|
|
99
95
|
const effectiveMaxTokens = typeof options.maxTokens === 'number' && options.maxTokens > 0 ? options.maxTokens : DEFAULT_OPENAI_MAX_TOKENS;
|
|
100
96
|
return {
|
|
101
97
|
model: options.model,
|
|
@@ -107,18 +103,6 @@ export function openAiRequestBody({ options, messages }) {
|
|
|
107
103
|
...(options.tools && options.tools.length > 0 ? { tools: options.tools } : {}),
|
|
108
104
|
};
|
|
109
105
|
}
|
|
110
|
-
export function extractOpenAiErrorDetail({ rawText }) {
|
|
111
|
-
try {
|
|
112
|
-
const parsed = JSON.parse(rawText);
|
|
113
|
-
if (isRecord(parsed) && isRecord(parsed.error) && typeof parsed.error.message === 'string') {
|
|
114
|
-
return parsed.error.message;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
catch {
|
|
118
|
-
// Non-JSON error body — fall through to the raw text below.
|
|
119
|
-
}
|
|
120
|
-
return rawText.trim().slice(0, 500);
|
|
121
|
-
}
|
|
122
106
|
/** Wordings a provider uses to refuse a strict/schema feature; any one matching is enough. */
|
|
123
107
|
const STRICT_REJECTION_PATTERNS = [
|
|
124
108
|
/unsupported|not support|unknown (?:field|parameter|name)|unrecognized|not (?:allowed|permitted)/i,
|
|
@@ -170,252 +154,11 @@ export function refreshOpenAiTools({ options, retry }, _optional = {}) {
|
|
|
170
154
|
let tools = options.getTools?.({ strict: retry.enabled }) ?? options.tools;
|
|
171
155
|
if (!retry.enabled)
|
|
172
156
|
tools = tools?.map(tool => {
|
|
173
|
-
const definition = omitKeys(tool.function, ['strict']);
|
|
157
|
+
const definition = omitKeys({ source: tool.function, keys: ['strict'] });
|
|
174
158
|
return { ...tool, function: definition };
|
|
175
159
|
});
|
|
176
160
|
return { ...options, ...(tools !== undefined ? { tools } : {}) };
|
|
177
161
|
}
|
|
178
|
-
/** 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". */
|
|
179
|
-
export function parseOpenAiSseData({ raw }) {
|
|
180
|
-
let data;
|
|
181
|
-
try {
|
|
182
|
-
data = JSON.parse(raw);
|
|
183
|
-
}
|
|
184
|
-
catch {
|
|
185
|
-
return null;
|
|
186
|
-
}
|
|
187
|
-
return isRecord(data) ? data : null;
|
|
188
|
-
}
|
|
189
|
-
export function applyOpenAiStreamUsage({ state, data, onEvent }) {
|
|
190
|
-
if (!isRecord(data.usage))
|
|
191
|
-
return;
|
|
192
|
-
state.usage = data.usage;
|
|
193
|
-
onEvent({ type: 'usage', usage: data.usage });
|
|
194
|
-
}
|
|
195
|
-
/** 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). */
|
|
196
|
-
export function firstOpenAiChoice({ data }) {
|
|
197
|
-
const choices = Array.isArray(data.choices) ? data.choices : [];
|
|
198
|
-
const choice = choices[0];
|
|
199
|
-
return isRecord(choice) ? choice : null;
|
|
200
|
-
}
|
|
201
|
-
/**
|
|
202
|
-
* Feeds one text delta through the role-marker guard and emits the safe portion. Returns
|
|
203
|
-
* `'break'` once the guard flags contamination (the caller ends the turn immediately), otherwise
|
|
204
|
-
* `'continue'` — same contract as `anthropic-messages.ts#handleAnthropicTextDelta`.
|
|
205
|
-
*/
|
|
206
|
-
export function handleOpenAiTextContentDelta({ state, content, onEvent }) {
|
|
207
|
-
const safe = state.guard.feedText({ text: content });
|
|
208
|
-
if (safe.length > 0) {
|
|
209
|
-
state.fullText += safe;
|
|
210
|
-
onEvent({ type: 'text_delta', delta: safe });
|
|
211
|
-
}
|
|
212
|
-
if (!state.guard.contaminated)
|
|
213
|
-
return 'continue';
|
|
214
|
-
const warn = state.guard.warningEvent();
|
|
215
|
-
if (warn)
|
|
216
|
-
onEvent(warn);
|
|
217
|
-
return 'break';
|
|
218
|
-
}
|
|
219
|
-
/** 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). */
|
|
220
|
-
export function newPendingOpenAiToolCall({ rawCall, index }) {
|
|
221
|
-
const id = typeof rawCall.id === 'string' ? rawCall.id : `call_${index}`;
|
|
222
|
-
const fn = isRecord(rawCall.function) ? rawCall.function : {};
|
|
223
|
-
const name = typeof fn.name === 'string' ? fn.name : '';
|
|
224
|
-
return { id, name, argsJson: '' };
|
|
225
|
-
}
|
|
226
|
-
/** Accumulates one `delta.tool_calls[]` entry from a streaming chunk into its running `PendingToolCall`. */
|
|
227
|
-
export function accumulateOpenAiToolCallDelta({ state, rawCall }) {
|
|
228
|
-
if (!isRecord(rawCall) || typeof rawCall.index !== 'number')
|
|
229
|
-
return;
|
|
230
|
-
let pending = state.toolCalls.get(rawCall.index);
|
|
231
|
-
if (!pending) {
|
|
232
|
-
pending = newPendingOpenAiToolCall({ rawCall: rawCall, index: rawCall.index });
|
|
233
|
-
state.toolCalls.set(rawCall.index, pending);
|
|
234
|
-
}
|
|
235
|
-
const fn = isRecord(rawCall.function) ? rawCall.function : null;
|
|
236
|
-
if (fn && typeof fn.arguments === 'string') {
|
|
237
|
-
pending.argsJson += fn.arguments;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
/** 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. */
|
|
241
|
-
export function handleOpenAiChoiceDelta({ state, choice, onEvent }) {
|
|
242
|
-
if (typeof choice.finish_reason === 'string') {
|
|
243
|
-
state.finishReason = choice.finish_reason;
|
|
244
|
-
}
|
|
245
|
-
const delta = isRecord(choice.delta) ? choice.delta : null;
|
|
246
|
-
if (!delta)
|
|
247
|
-
return 'continue';
|
|
248
|
-
const text = typeof delta.content === 'string' && delta.content.length > 0 ? delta.content : null;
|
|
249
|
-
if (text !== null && handleOpenAiTextContentDelta({ state: state, content: text, onEvent: onEvent }) === 'break')
|
|
250
|
-
return 'break';
|
|
251
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
252
|
-
for (const rawCall of delta.tool_calls) {
|
|
253
|
-
accumulateOpenAiToolCallDelta({ state: state, rawCall: rawCall });
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
return 'continue';
|
|
257
|
-
}
|
|
258
|
-
/** 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`. */
|
|
259
|
-
export function resolveOpenAiToolCalls({ pending }) {
|
|
260
|
-
return Array.from(pending.values()).map((call) => {
|
|
261
|
-
let input = {};
|
|
262
|
-
if (call.argsJson.trim()) {
|
|
263
|
-
try {
|
|
264
|
-
input = JSON.parse(call.argsJson);
|
|
265
|
-
}
|
|
266
|
-
catch {
|
|
267
|
-
input = {};
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
return { id: call.id, name: call.name, input };
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
function emitPendingOpenAiToolUseEvents(toolCalls, onEvent) {
|
|
274
|
-
for (const call of toolCalls) {
|
|
275
|
-
onEvent({ type: 'tool_use', id: call.id, name: call.name, input: call.input });
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
/** Tool-schema retry has precedence; consume only the hook that selected a replacement body. */
|
|
279
|
-
function resolveOpenAiRetry({ init, status, rawText }, _options = {}) {
|
|
280
|
-
const toolRetryBody = init.retryToolBody?.({ status, rawErrorText: rawText, body: init.body });
|
|
281
|
-
if (toolRetryBody) {
|
|
282
|
-
const retryInit = omitKeys(init, ['retryToolBody']);
|
|
283
|
-
return { type: 'retry', retryInit: { ...retryInit, body: toolRetryBody } };
|
|
284
|
-
}
|
|
285
|
-
const retryBody = init.retryableBody?.(status, rawText);
|
|
286
|
-
if (retryBody) {
|
|
287
|
-
const retryInit = omitKeys(init, ['retryableBody']);
|
|
288
|
-
return { type: 'retry', retryInit: { ...retryInit, body: retryBody } };
|
|
289
|
-
}
|
|
290
|
-
return null;
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* Opens the streaming POST and validates the response, returning its readable body once every
|
|
294
|
-
* pre-stream failure mode (network error, non-2xx status with no retry available, missing body)
|
|
295
|
-
* has been ruled out. Calls `emitEnd('error')` and returns `{type: 'ended'}` itself on any of
|
|
296
|
-
* those — the caller only has to branch on the outcome's `type`, keeping `hasEnded()` as the sole
|
|
297
|
-
* gate for every exit path (see `runOpenAiCompatibleRequest`'s doc).
|
|
298
|
-
*/
|
|
299
|
-
async function requestOpenAiCompatibleStream({ init }, _options = {}) {
|
|
300
|
-
const { onEvent, emitEnd } = init;
|
|
301
|
-
let response;
|
|
302
|
-
try {
|
|
303
|
-
response = await (init.fetchImpl ?? pinnedFetch)({ url: init.url, init: {
|
|
304
|
-
method: 'POST',
|
|
305
|
-
headers: init.headers,
|
|
306
|
-
body: JSON.stringify(init.body),
|
|
307
|
-
// The caller's SSRF check (`validateBaseUrlResolved`) only ever sees the
|
|
308
|
-
// ORIGINAL url. Following a redirect would let a public, guard-passing
|
|
309
|
-
// endpoint hand back a `302 -> http://169.254.169.254/...` and reach the
|
|
310
|
-
// address the guard exists to refuse — with the provider auth headers
|
|
311
|
-
// still attached. `model-catalog.ts`'s own fetch already refuses
|
|
312
|
-
// redirects for the same reason; a redirecting chat-completions endpoint
|
|
313
|
-
// is not a thing any supported provider does. `pinnedFetch` never
|
|
314
|
-
// follows one regardless (see its doc); `redirect: 'error'` here is
|
|
315
|
-
// self-documentation, not the mechanism.
|
|
316
|
-
redirect: 'error',
|
|
317
|
-
...(init.signal ? { signal: init.signal } : {}),
|
|
318
|
-
}, pinnedAddress: init.pinnedAddress });
|
|
319
|
-
}
|
|
320
|
-
catch (error) {
|
|
321
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
322
|
-
onEvent({ type: 'error', message: redactSecrets({ input: message }, { exactSecrets: init.redactSecretsList }) });
|
|
323
|
-
emitEnd('error');
|
|
324
|
-
return { type: 'ended' };
|
|
325
|
-
}
|
|
326
|
-
if (!response.ok) {
|
|
327
|
-
const rawText = await response.text();
|
|
328
|
-
const retryOutcome = resolveOpenAiRetry({ init, status: response.status, rawText });
|
|
329
|
-
if (retryOutcome)
|
|
330
|
-
return retryOutcome;
|
|
331
|
-
onEvent({
|
|
332
|
-
type: 'error',
|
|
333
|
-
message: redactSecrets({ input: extractOpenAiErrorDetail({ rawText: rawText }) }, { exactSecrets: init.redactSecretsList }),
|
|
334
|
-
code: String(response.status),
|
|
335
|
-
});
|
|
336
|
-
emitEnd('error');
|
|
337
|
-
return { type: 'ended' };
|
|
338
|
-
}
|
|
339
|
-
if (!response.body) {
|
|
340
|
-
onEvent({ type: 'error', message: `${init.providerLabel} response had no body` });
|
|
341
|
-
emitEnd('error');
|
|
342
|
-
return { type: 'ended' };
|
|
343
|
-
}
|
|
344
|
-
return { type: 'body', body: response.body };
|
|
345
|
-
}
|
|
346
|
-
/**
|
|
347
|
-
* Reduces one decoded SSE frame into `state`, reporting what the caller's loop should do next:
|
|
348
|
-
* `'done'` on the `[DONE]` sentinel, `'contaminated'` once the role-marker guard trips on this
|
|
349
|
-
* frame's text delta, otherwise `'continue'`. Pulling per-frame dispatch out of the loop body
|
|
350
|
-
* turns what would be four sequential, nesting-penalized `if`s into a single function call plus
|
|
351
|
-
* one outcome check — see `runOpenAiCompatibleRequest`'s loop below.
|
|
352
|
-
*/
|
|
353
|
-
export function processOpenAiStreamFrame({ state, frame, onEvent }) {
|
|
354
|
-
if (frame.data === DONE_SENTINEL)
|
|
355
|
-
return 'done';
|
|
356
|
-
const data = parseOpenAiSseData({ raw: frame.data });
|
|
357
|
-
if (!data)
|
|
358
|
-
return 'continue'; // malformed/empty keep-alive frame, or a non-object payload
|
|
359
|
-
applyOpenAiStreamUsage({ state: state, data: data, onEvent: onEvent });
|
|
360
|
-
const choice = firstOpenAiChoice({ data: data });
|
|
361
|
-
if (!choice)
|
|
362
|
-
return 'continue';
|
|
363
|
-
return handleOpenAiChoiceDelta({ state: state, choice: choice, onEvent: onEvent }) === 'break' ? 'contaminated' : 'continue';
|
|
364
|
-
}
|
|
365
|
-
/**
|
|
366
|
-
* Runs exactly one OpenAI-compatible (Chat Completions JSON wire format)
|
|
367
|
-
* streaming HTTP request and reduces its SSE events into a single outcome.
|
|
368
|
-
* Extracted so this SSE-reduction loop has exactly one implementation
|
|
369
|
-
* shared by every OpenAI-compatible provider turn-runner in this package:
|
|
370
|
-
* `runOpenAiToolTurn` itself (below), plus `azure-chat.ts#runAzureToolTurn`
|
|
371
|
-
* and `ollama-chat.ts#runOllamaToolTurn` — both target byte-identical
|
|
372
|
-
* chat-completions JSON, differing only in URL and auth. Callers own their
|
|
373
|
-
* own base-URL SSRF validation (`validateBaseUrl`) and URL/header/body
|
|
374
|
-
* construction *before* calling this function — it only knows how to run
|
|
375
|
-
* *a* request against whatever URL/headers/body it is handed, and has no
|
|
376
|
-
* opinion on any provider's defaults. Mirrors
|
|
377
|
-
* `anthropic-messages.ts#runSingleAnthropicRequest`'s `emitEnd` contract —
|
|
378
|
-
* see that function's doc.
|
|
379
|
-
*/
|
|
380
|
-
export async function runOpenAiCompatibleRequest(requiredArgs, optionalArgs = {}) {
|
|
381
|
-
const init = { ...optionalArgs, ...requiredArgs };
|
|
382
|
-
const { onEvent, hasEnded } = init;
|
|
383
|
-
const fetchOutcome = await requestOpenAiCompatibleStream({ init });
|
|
384
|
-
if (fetchOutcome.type === 'ended') {
|
|
385
|
-
return { finishReason: null, toolCalls: [], text: '' };
|
|
386
|
-
}
|
|
387
|
-
if (fetchOutcome.type === 'retry') {
|
|
388
|
-
return (({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded, ...optionalArgs }) => runOpenAiCompatibleRequest({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded }, optionalArgs))(fetchOutcome.retryInit);
|
|
389
|
-
}
|
|
390
|
-
onEvent({ type: 'status', label: 'requesting' });
|
|
391
|
-
const state = {
|
|
392
|
-
guard: createRoleMarkerGuard({ messageId: init.guardMessageId }),
|
|
393
|
-
toolCalls: new Map(),
|
|
394
|
-
fullText: '',
|
|
395
|
-
finishReason: null,
|
|
396
|
-
usage: null,
|
|
397
|
-
};
|
|
398
|
-
for await (const frame of decodeSseStream({ source: fetchOutcome.body })) {
|
|
399
|
-
// No `hasEnded()` re-check at the top of this loop: the only in-loop call to `emitEnd`
|
|
400
|
-
// (contamination, below) is immediately followed by `break`, and every other call site is a
|
|
401
|
-
// pre-loop early `return` — traced across all five call sites in this function and
|
|
402
|
-
// `requestOpenAiCompatibleStream`, same proof as
|
|
403
|
-
// `anthropic-messages.ts#runSingleAnthropicRequest`. `hasEnded()` is still consulted once,
|
|
404
|
-
// after this loop, to decide whether pending tool_use events should still be emitted (a
|
|
405
|
-
// contaminating delta can arrive on a *later* chunk than the one that set `finish_reason`).
|
|
406
|
-
const result = processOpenAiStreamFrame({ state: state, frame: frame, onEvent: onEvent });
|
|
407
|
-
if (result === 'done' || result === 'contaminated') {
|
|
408
|
-
if (result === 'contaminated')
|
|
409
|
-
init.emitEnd('contaminated');
|
|
410
|
-
break;
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
const resolvedToolCalls = resolveOpenAiToolCalls({ pending: state.toolCalls });
|
|
414
|
-
if (state.finishReason === 'tool_calls' && !hasEnded()) {
|
|
415
|
-
emitPendingOpenAiToolUseEvents(resolvedToolCalls, onEvent);
|
|
416
|
-
}
|
|
417
|
-
return { finishReason: state.finishReason, toolCalls: resolvedToolCalls, text: state.fullText };
|
|
418
|
-
}
|
|
419
162
|
/** Validates `options.baseUrl`, then delegates to {@link runOpenAiCompatibleRequest} with OpenAI's own URL/header/body builders. Thin wrapper kept so `runOpenAiToolTurn`'s per-iteration call site stays unchanged by the extraction. */
|
|
420
163
|
async function runSingleOpenAiRequest(options, messages, emitEnd, hasEnded, retry) {
|
|
421
164
|
// DNS-resolving, not merely textual: the synchronous check only inspects the literal hostname,
|
|
@@ -450,140 +193,18 @@ async function runSingleOpenAiRequest(options, messages, emitEnd, hasEnded, retr
|
|
|
450
193
|
hasEnded,
|
|
451
194
|
});
|
|
452
195
|
}
|
|
453
|
-
const OPENAI_ALLOWED_IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
|
|
454
|
-
/**
|
|
455
|
-
* OpenAI documents a 512 MB total-payload cap and a 1500-image-per-request cap for the Chat
|
|
456
|
-
* Completions API (see module doc's "Image support" section) but no single-image byte limit. This
|
|
457
|
-
* module still bounds one image's base64 length defensively, matching
|
|
458
|
-
* `anthropic-messages.ts`'s posture — 20 MB is this module's own conservative choice (not an
|
|
459
|
-
* OpenAI-documented per-image number), anchored to Gemini's documented 20 MB total-inline-request
|
|
460
|
-
* budget (`google-messages.ts`) as the closest real, vendor-documented single-request inline-image
|
|
461
|
-
* bound available across this package's providers. Approximated from the base64 *string* length,
|
|
462
|
-
* not decoded byte count — see `anthropic-messages.ts#MAX_IMAGE_BASE64_CHARS`'s doc for why that's
|
|
463
|
-
* the right thing to measure (O(1), no decode step, negligible rounding slack at this size).
|
|
464
|
-
*/
|
|
465
|
-
const MAX_IMAGE_DATA_URI_BASE64_CHARS = Math.ceil((20 * 1024 * 1024 * 4) / 3);
|
|
466
|
-
/** OpenAI's documented per-request image count cap (see module doc). Applied per tool-result content array as a conservative simplification — a real request can also carry images from earlier turns this module doesn't track. */
|
|
467
|
-
const MAX_IMAGES_PER_OPENAI_TOOL_RESULT = 1500;
|
|
468
|
-
const OPENAI_DATA_URI_PATTERN = /^data:([^;,]+)(?:;charset=[^;,]+)?;base64,(.+)$/su;
|
|
469
|
-
/**
|
|
470
|
-
* Validates one content part against OpenAI's real format/size constraints. Returns the violation
|
|
471
|
-
* reason, or `null` when the part is legal to send.
|
|
472
|
-
*
|
|
473
|
-
* A plain `https://` `image_url` (not a `data:` URI) is intentionally not size-checked: OpenAI's
|
|
474
|
-
* servers fetch that URL, not this adapter, so there is no local payload to bound — same threat-
|
|
475
|
-
* model split as `anthropic-messages.ts`'s URL-sourced skip (`connection-guard.ts`'s SSRF guard
|
|
476
|
-
* protects this adapter's own outbound `baseUrl` request, a different thing; an `image_url` that
|
|
477
|
-
* points at attacker-chosen infrastructure is a request OpenAI's own servers make, not this one).
|
|
478
|
-
*
|
|
479
|
-
* @complexity O(1) — reads `data.length`, never decodes or parses the base64 payload.
|
|
480
|
-
*/
|
|
481
|
-
export function invalidOpenAiContentPartReason({ part }) {
|
|
482
|
-
if (part.type === 'text')
|
|
483
|
-
return null;
|
|
484
|
-
const dataUriMatch = OPENAI_DATA_URI_PATTERN.exec(part.image_url.url);
|
|
485
|
-
if (!dataUriMatch)
|
|
486
|
-
return null;
|
|
487
|
-
const [, mediaType, base64Data] = dataUriMatch;
|
|
488
|
-
if (!mediaType || !OPENAI_ALLOWED_IMAGE_MEDIA_TYPES.has(mediaType.toLowerCase())) {
|
|
489
|
-
return `unsupported image media type ${JSON.stringify(mediaType)} (OpenAI's Chat Completions API supports image/jpeg, image/png, image/webp, and non-animated image/gif)`;
|
|
490
|
-
}
|
|
491
|
-
if (base64Data && base64Data.length > MAX_IMAGE_DATA_URI_BASE64_CHARS) {
|
|
492
|
-
return `image exceeds this adapter's 20 MB base64 size guard (${base64Data.length} base64 chars)`;
|
|
493
|
-
}
|
|
494
|
-
return null;
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* Runtime guard applied to every `OpenAiToolExecutor` result before it is wired onto the outbound
|
|
498
|
-
* request or reported via `onEvent`. `OpenAiToolResult` is host-owned (see `OpenAiToolExecutor`'s
|
|
499
|
-
* "Host-owned tool execution" doc comment) — the TS content-part union only constrains a
|
|
500
|
-
* well-behaved host at compile time, not a buggy one at runtime, e.g. a screenshot helper that
|
|
501
|
-
* hands back an oversized PNG or a HEIC file mislabeled as `image/jpeg`. Rather than forwarding an
|
|
502
|
-
* invalid part and letting OpenAI reject the *entire* turn with an opaque upstream 400, this
|
|
503
|
-
* substitutes a plain-text `isError: true` result the model can see and react to — matching this
|
|
504
|
-
* package's existing security-conscious posture (`connection-guard.ts`'s SSRF guard,
|
|
505
|
-
* `role-marker-guard.ts`'s contamination guard, and `anthropic-messages.ts`'s identical guard).
|
|
506
|
-
*
|
|
507
|
-
* @complexity O(n) in the number of content parts; O(1) per part (see `invalidOpenAiContentPartReason`).
|
|
508
|
-
*/
|
|
509
|
-
export function sanitizeOpenAiToolResult({ result }) {
|
|
510
|
-
if (typeof result.content === 'string')
|
|
511
|
-
return { content: result.content, isError: false };
|
|
512
|
-
if (result.content.length > MAX_IMAGES_PER_OPENAI_TOOL_RESULT) {
|
|
513
|
-
return { content: `tool result rejected: exceeds the ${MAX_IMAGES_PER_OPENAI_TOOL_RESULT}-image-per-request guard (${result.content.length} parts)`, isError: true };
|
|
514
|
-
}
|
|
515
|
-
for (const part of result.content) {
|
|
516
|
-
const reason = invalidOpenAiContentPartReason({ part: part });
|
|
517
|
-
if (reason)
|
|
518
|
-
return { content: `tool result rejected: ${reason}`, isError: true };
|
|
519
|
-
}
|
|
520
|
-
return { content: result.content, isError: false };
|
|
521
|
-
}
|
|
522
|
-
/**
|
|
523
|
-
* Splits one (already-sanitized) tool result's content into what can legally sit on the wire
|
|
524
|
-
* `role: 'tool'` message (text only — see module doc's "Tool messages cannot carry an image"
|
|
525
|
-
* section) and the `image_url` parts that must instead travel on a follow-up `user` message.
|
|
526
|
-
*
|
|
527
|
-
* A string `content` is left untouched (`imageParts: []`) — this is the pre-existing, unchanged
|
|
528
|
-
* path every current caller already exercises. For an array, text parts are kept in order for the
|
|
529
|
-
* `tool` message; if there is no text at all (an image-only result), a single placeholder text part
|
|
530
|
-
* is substituted so the `tool` message's content is never empty (OpenAI rejects empty content).
|
|
531
|
-
*
|
|
532
|
-
* @complexity O(n) in the number of content parts.
|
|
533
|
-
*/
|
|
534
|
-
export function splitOpenAiToolResultContent({ content }) {
|
|
535
|
-
if (typeof content === 'string')
|
|
536
|
-
return { toolMessageContent: content, imageParts: [] };
|
|
537
|
-
const textParts = content.filter((part) => part.type === 'text');
|
|
538
|
-
const imageParts = content.filter((part) => part.type === 'image_url');
|
|
539
|
-
const toolMessageContent = textParts.length > 0 ? textParts : [{ type: 'text', text: '(tool result included only non-text content; see the following message)' }];
|
|
540
|
-
return { toolMessageContent, imageParts };
|
|
541
|
-
}
|
|
542
196
|
/**
|
|
543
197
|
* Decides why the tool loop should stop after one request, or returns `null` when it should
|
|
544
198
|
* instead proceed to execute the pending tool calls — mirrors
|
|
545
199
|
* `anthropic-messages.ts#anthropicLoopExitReason`'s pure decision/effect split.
|
|
546
200
|
*/
|
|
547
|
-
export function openAiLoopExitReason({ outcome, toolTurns, maxToolTurns }) {
|
|
201
|
+
export function openAiLoopExitReason({ outcome, toolTurns, maxToolTurns }, _optional = {}) {
|
|
548
202
|
if (outcome.finishReason !== 'tool_calls' || outcome.toolCalls.length === 0)
|
|
549
203
|
return 'stop';
|
|
550
204
|
if (toolTurns >= maxToolTurns)
|
|
551
205
|
return 'max_tool_turns';
|
|
552
206
|
return null;
|
|
553
207
|
}
|
|
554
|
-
/**
|
|
555
|
-
* Runs every pending tool call in order, sanitizing and splitting each result into its `tool`
|
|
556
|
-
* message plus any labeled image parts for the batch's single follow-up `user` message — see
|
|
557
|
-
* module doc's "Tool messages cannot carry an image" section for why the split exists and why the
|
|
558
|
-
* follow-up is assembled once per batch rather than per call.
|
|
559
|
-
*/
|
|
560
|
-
export async function executeOpenAiToolCalls({ executeTool, calls, onEvent }) {
|
|
561
|
-
const toolResultMessages = [];
|
|
562
|
-
const followUpParts = [];
|
|
563
|
-
for (const call of calls) {
|
|
564
|
-
const result = await executeTool(call);
|
|
565
|
-
const sanitized = sanitizeOpenAiToolResult({ result: result });
|
|
566
|
-
onEvent({ type: 'tool_result', toolUseId: call.id, content: sanitized.content, isError: sanitized.isError });
|
|
567
|
-
const split = splitOpenAiToolResultContent({ content: sanitized.content });
|
|
568
|
-
toolResultMessages.push({ role: 'tool', content: split.toolMessageContent, tool_call_id: call.id });
|
|
569
|
-
if (split.imageParts.length > 0) {
|
|
570
|
-
// Attribution label — without it, the model cannot tell this image apart from a human
|
|
571
|
-
// having just pasted one into the conversation (see module doc). Named per-call so a batch
|
|
572
|
-
// with multiple image-bearing tool calls stays disambiguated in one follow-up message.
|
|
573
|
-
followUpParts.push({ type: 'text', text: `Image output from tool \`${call.name}\` (tool_call_id: ${call.id}):` });
|
|
574
|
-
followUpParts.push(...split.imageParts);
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
return { toolResultMessages, followUpParts };
|
|
578
|
-
}
|
|
579
|
-
/** 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. */
|
|
580
|
-
export function buildOpenAiAssistantToolCallMessage({ text, toolCalls }) {
|
|
581
|
-
return { role: 'assistant', content: text || null, tool_calls: toolCalls };
|
|
582
|
-
}
|
|
583
|
-
/** 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. */
|
|
584
|
-
export function buildOpenAiToolExchangeMessages({ toolResultMessages, followUpParts }) {
|
|
585
|
-
return [...toolResultMessages, ...(followUpParts.length > 0 ? [{ role: 'user', content: followUpParts }] : [])];
|
|
586
|
-
}
|
|
587
208
|
/**
|
|
588
209
|
* Runs a full OpenAI Chat Completions turn, including the tool-execution
|
|
589
210
|
* loop when `options.executeTool` is supplied and the model requests a
|
|
@@ -595,7 +216,7 @@ export async function runOpenAiToolTurn(requiredArgs, optionalArgs = {}) {
|
|
|
595
216
|
const retry = createStrictToolRetry({ protocol: 'openai', onSchemaFallback: options.onSchemaFallback });
|
|
596
217
|
const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
|
|
597
218
|
const executeTool = options.executeTool;
|
|
598
|
-
const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
|
|
219
|
+
const endGuard = createTurnEndGuard({ onEvent: options.onEvent, makeEndEvent: (reason) => ({ type: 'end', reason }) });
|
|
599
220
|
const emitEnd = endGuard.emitEnd;
|
|
600
221
|
let messages = options.messages.slice();
|
|
601
222
|
let toolTurns = 0;
|
package/dist/providers/pkce.d.ts
CHANGED
|
@@ -29,7 +29,7 @@ export interface PendingAuthState {
|
|
|
29
29
|
export declare function generateCodeVerifier(): string;
|
|
30
30
|
export declare function deriveCodeChallenge({ verifier }: {
|
|
31
31
|
verifier: string;
|
|
32
|
-
}): string;
|
|
32
|
+
}, _optional?: Record<string, never>): string;
|
|
33
33
|
export declare function generateState(): string;
|
|
34
34
|
export interface AuthorizeUrlInput {
|
|
35
35
|
authServer: AuthorizationServerMetadata;
|
package/dist/providers/pkce.js
CHANGED
|
@@ -29,7 +29,7 @@ import { createPkcePair, deriveCodeChallenge as deriveOAuthCodeChallenge, genera
|
|
|
29
29
|
const entropy = ({ byteLength }) => randomBytes(byteLength);
|
|
30
30
|
/** RFC 7636 §4.1 permits 43–128 verifier characters; 64 random bytes encode to 86. */
|
|
31
31
|
export function generateCodeVerifier() { return createPkcePair({ randomBytesFn: entropy }, { verifierBytes: 64 }).codeVerifier; }
|
|
32
|
-
export function deriveCodeChallenge({ verifier }) { return deriveOAuthCodeChallenge({ codeVerifier: verifier }); }
|
|
32
|
+
export function deriveCodeChallenge({ verifier }, _optional = {}) { return deriveOAuthCodeChallenge({ codeVerifier: verifier }); }
|
|
33
33
|
export function generateState() { return generateOAuthState({ randomBytesFn: entropy }); }
|
|
34
34
|
export function buildAuthorizeUrl(requiredArgs, optionalArgs = {}) {
|
|
35
35
|
return buildOAuthAuthorizationUrl({
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Append an API suffix, adding v1 only when the base path has no version. */
|
|
2
|
+
export declare function appendVersionedApiPath({ baseUrl, suffix }: {
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
suffix: string;
|
|
5
|
+
}, _optional?: Record<string, never>): string;
|
|
6
|
+
//# sourceMappingURL=provider-url.d.ts.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { trimCharsEnd } from '@jini-ai/core/text';
|
|
2
|
+
/** Append an API suffix, adding v1 only when the base path has no version. */
|
|
3
|
+
export function appendVersionedApiPath({ baseUrl, suffix }, _optional = {}) {
|
|
4
|
+
const url = new URL(baseUrl);
|
|
5
|
+
const pathname = trimCharsEnd({ text: url.pathname, chars: '/' });
|
|
6
|
+
url.pathname = /\/v\d+(\/|$)/.test(pathname) ? `${pathname}${suffix}` : `${pathname}/v1${suffix}`;
|
|
7
|
+
return url.toString();
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=provider-url.js.map
|
|
@@ -7,4 +7,8 @@ export declare function readProviderResponseText({ body }: {
|
|
|
7
7
|
}, { maxBytes }?: {
|
|
8
8
|
maxBytes?: number;
|
|
9
9
|
}): Promise<string>;
|
|
10
|
+
/** Extracts an upstream error message or a trimmed, bounded raw response. */
|
|
11
|
+
export declare function extractProviderErrorDetail({ rawText }: {
|
|
12
|
+
rawText: string;
|
|
13
|
+
}, _optional?: Record<string, never>): string;
|
|
10
14
|
//# sourceMappingURL=response-text.d.ts.map
|
|
@@ -20,4 +20,20 @@ export async function readProviderResponseText({ body }, { maxBytes = MAX_PROVID
|
|
|
20
20
|
}
|
|
21
21
|
return Buffer.concat(chunks, size).toString('utf8');
|
|
22
22
|
}
|
|
23
|
+
/** Extracts an upstream error message or a trimmed, bounded raw response. */
|
|
24
|
+
export function extractProviderErrorDetail({ rawText }, _optional = {}) {
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(rawText);
|
|
27
|
+
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
|
|
28
|
+
const error = parsed.error;
|
|
29
|
+
if (typeof error === 'object' && error !== null && !Array.isArray(error) && typeof error.message === 'string') {
|
|
30
|
+
return error.message;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// Non-JSON error body — fall through to the raw text below.
|
|
36
|
+
}
|
|
37
|
+
return rawText.trim().slice(0, 500);
|
|
38
|
+
}
|
|
23
39
|
//# sourceMappingURL=response-text.js.map
|
|
@@ -2,4 +2,8 @@
|
|
|
2
2
|
* dependency-free primitives; providers keep their JSON interpretation and select the exported EOF policy. */
|
|
3
3
|
export { decodeSseFrames, decodeSseStream, parseSseRecord } from '@jini-ai/core/primitives';
|
|
4
4
|
export type { DecodedSseEvent, DecodedSseFrame, SseFramingOptions } from '@jini-ai/core/primitives';
|
|
5
|
+
/** Parses an SSE frame as a JSON object; malformed and non-object payloads are ignored. */
|
|
6
|
+
export declare function parseSseJsonRecord({ raw }: {
|
|
7
|
+
raw: string;
|
|
8
|
+
}, _optional?: Record<string, never>): Record<string, unknown> | null;
|
|
5
9
|
//# sourceMappingURL=sse-decode.d.ts.map
|
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
/** Compatibility entry. Inbound SSE framing is shared with CLI consumers through core's
|
|
2
2
|
* dependency-free primitives; providers keep their JSON interpretation and select the exported EOF policy. */
|
|
3
3
|
export { decodeSseFrames, decodeSseStream, parseSseRecord } from '@jini-ai/core/primitives';
|
|
4
|
+
/** Parses an SSE frame as a JSON object; malformed and non-object payloads are ignored. */
|
|
5
|
+
export function parseSseJsonRecord({ raw }, _optional = {}) {
|
|
6
|
+
let data;
|
|
7
|
+
try {
|
|
8
|
+
data = JSON.parse(raw);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
return typeof data === 'object' && data !== null && !Array.isArray(data) ? data : null;
|
|
14
|
+
}
|
|
4
15
|
//# sourceMappingURL=sse-decode.js.map
|
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
/** True when `model` belongs to a family that rejects the legacy `max_tokens` field. */
|
|
12
12
|
export declare function usesMaxCompletionTokens({ model }: {
|
|
13
13
|
model: string;
|
|
14
|
-
}): boolean;
|
|
14
|
+
}, _optional?: Record<string, never>): boolean;
|
|
15
15
|
/** Selects `max_tokens` or `max_completion_tokens` per {@link usesMaxCompletionTokens}. */
|
|
16
16
|
export declare function buildOpenAIChatTokenParam({ model, maxTokens }: {
|
|
17
17
|
model: string;
|
|
18
18
|
maxTokens: number;
|
|
19
|
-
}): {
|
|
19
|
+
}, _optional?: Record<string, never>): {
|
|
20
20
|
max_tokens: number;
|
|
21
21
|
} | {
|
|
22
22
|
max_completion_tokens: number;
|
|
@@ -24,17 +24,17 @@ export declare function buildOpenAIChatTokenParam({ model, maxTokens }: {
|
|
|
24
24
|
/** Always the legacy `max_tokens` shape — for callers that already know the model family. */
|
|
25
25
|
export declare function buildLegacyMaxTokensParam({ maxTokens }: {
|
|
26
26
|
maxTokens: number;
|
|
27
|
-
}): {
|
|
27
|
+
}, _optional?: Record<string, never>): {
|
|
28
28
|
max_tokens: number;
|
|
29
29
|
};
|
|
30
30
|
/** Always the newer `max_completion_tokens` shape — for callers that already know the model family. */
|
|
31
31
|
export declare function buildMaxCompletionTokensParam({ maxTokens }: {
|
|
32
32
|
maxTokens: number;
|
|
33
|
-
}): {
|
|
33
|
+
}, _optional?: Record<string, never>): {
|
|
34
34
|
max_completion_tokens: number;
|
|
35
35
|
};
|
|
36
36
|
/** Detects the provider error text a gateway returns when `max_tokens` was rejected in favor of `max_completion_tokens`. */
|
|
37
37
|
export declare function isUnsupportedMaxTokensError({ detail }: {
|
|
38
38
|
detail: string;
|
|
39
|
-
}): boolean;
|
|
39
|
+
}, _optional?: Record<string, never>): boolean;
|
|
40
40
|
//# sourceMappingURL=token-params.d.ts.map
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* origin — ported verbatim.
|
|
10
10
|
*/
|
|
11
11
|
/** True when `model` belongs to a family that rejects the legacy `max_tokens` field. */
|
|
12
|
-
export function usesMaxCompletionTokens({ model }) {
|
|
12
|
+
export function usesMaxCompletionTokens({ model }, _optional = {}) {
|
|
13
13
|
const normalized = model.trim().toLowerCase();
|
|
14
14
|
return (/^gpt-5(?:[.-]|$)/.test(normalized) ||
|
|
15
15
|
/^o1(?:[.-]|$)/.test(normalized) ||
|
|
@@ -17,22 +17,22 @@ export function usesMaxCompletionTokens({ model }) {
|
|
|
17
17
|
/^o4(?:[.-]|$)/.test(normalized));
|
|
18
18
|
}
|
|
19
19
|
/** Selects `max_tokens` or `max_completion_tokens` per {@link usesMaxCompletionTokens}. */
|
|
20
|
-
export function buildOpenAIChatTokenParam({ model, maxTokens }) {
|
|
20
|
+
export function buildOpenAIChatTokenParam({ model, maxTokens }, _optional = {}) {
|
|
21
21
|
if (usesMaxCompletionTokens({ model: model })) {
|
|
22
22
|
return { max_completion_tokens: maxTokens };
|
|
23
23
|
}
|
|
24
24
|
return { max_tokens: maxTokens };
|
|
25
25
|
}
|
|
26
26
|
/** Always the legacy `max_tokens` shape — for callers that already know the model family. */
|
|
27
|
-
export function buildLegacyMaxTokensParam({ maxTokens }) {
|
|
27
|
+
export function buildLegacyMaxTokensParam({ maxTokens }, _optional = {}) {
|
|
28
28
|
return { max_tokens: maxTokens };
|
|
29
29
|
}
|
|
30
30
|
/** Always the newer `max_completion_tokens` shape — for callers that already know the model family. */
|
|
31
|
-
export function buildMaxCompletionTokensParam({ maxTokens }) {
|
|
31
|
+
export function buildMaxCompletionTokensParam({ maxTokens }, _optional = {}) {
|
|
32
32
|
return { max_completion_tokens: maxTokens };
|
|
33
33
|
}
|
|
34
34
|
/** Detects the provider error text a gateway returns when `max_tokens` was rejected in favor of `max_completion_tokens`. */
|
|
35
|
-
export function isUnsupportedMaxTokensError({ detail }) {
|
|
35
|
+
export function isUnsupportedMaxTokensError({ detail }, _optional = {}) {
|
|
36
36
|
const normalized = detail.toLowerCase();
|
|
37
37
|
return (normalized.includes('unsupported parameter') &&
|
|
38
38
|
normalized.includes('max_tokens') &&
|
|
@@ -18,5 +18,5 @@ export declare function toolLoopVerdict<R extends string>({ ended, hasExecutor,
|
|
|
18
18
|
ended: boolean;
|
|
19
19
|
hasExecutor: boolean;
|
|
20
20
|
exitReason: () => R | null;
|
|
21
|
-
}): ToolLoopVerdict<R>;
|
|
21
|
+
}, _optional?: Record<string, never>): ToolLoopVerdict<R>;
|
|
22
22
|
//# sourceMappingURL=tool-loop-verdict.d.ts.map
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* as `tool_use` events, so with nothing to run them the turn ends with `'stop'` rather than
|
|
9
9
|
* silently retrying forever. `exitReason` is only consulted for a turn that has not ended.
|
|
10
10
|
*/
|
|
11
|
-
export function toolLoopVerdict({ ended, hasExecutor, exitReason }) {
|
|
11
|
+
export function toolLoopVerdict({ ended, hasExecutor, exitReason }, _optional = {}) {
|
|
12
12
|
if (ended)
|
|
13
13
|
return { stop: true, emit: null };
|
|
14
14
|
const emit = exitReason() || (hasExecutor ? null : 'stop');
|