Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
// A stream error carrying no message has no diagnostic value, so keep the
// original reason rather than replacing it with a hollow serialized struct.
:
.
.
?
JSON
.
stringify
(
.
)
:
.
,
}
;
}
else
if
(
.
===
.
)
{
return
{
:
.
,
:
.
,
:
.
,
:
.
?
'Rate limit exceeded\n\n'
+
JSON
.
stringify
(
.
)
:
'Rate limit exceeded'
,
:
''
,
:
undefined
,
:
false
,
:
.
}
;
}
return
;
}
/**
* Checks to see if a given endpoint is a BYOK model.
* @paramendpoint The endpoint to check if it's a BYOK model
* @returns 1 if client side byok, 2 if server side byok, -1 if not a byok model
*/
export
function
isBYOKModel
(
:
|
undefined
)
:
number
{
if
(
!
)
{
return
-
1
;
}
return
(
instanceof
OpenAIEndpoint
||
.
)
?
1
:
(
.
?
2
:
-
1
)
;
}
export
class
OpenAIEndpoint
extends
ChatEndpoint
{
// Reserved headers that cannot be overridden for security and functionality reasons
// Including forbidden request headers: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header
private
static
readonly
:
<
string
>
=
new
Set
(
[
// Forbidden Request Headers
'accept-charset'
,
'accept-encoding'
,
'access-control-request-headers'
,
'access-control-request-method'
,
'connection'
,
'content-length'
,
'cookie'
,
'date'
,
'dnt'
,
'expect'
,
'host'
,
'keep-alive'
,
'origin'
,
'permissions-policy'
,
'referer'
,
'te'
,
'trailer'
,
'transfer-encoding'
,
'upgrade'
,
'user-agent'
,
'via'
,
// Forwarding & Routing
'forwarded'
,
'x-forwarded-for'
,
'x-forwarded-host'
,
'x-forwarded-proto'
,
// Others
'api-key'
,
'authorization'
,
'content-type'
,
'openai-intent'
,
'x-github-api-version'
,
'x-initiator'
,
'x-interaction-id'
,
'x-interaction-type'
,
'x-onbehalf-extension-id'
,
'x-request-id'
,
'x-vscode-user-agent-library-version'
,
// Pattern-based forbidden headers are checked separately:
// - 'proxy-*' headers (handled in sanitization logic)
// - 'sec-*' headers (handled in sanitization logic)
// - 'x-http-method*' with forbidden methods CONNECT, TRACE, TRACK (handled in sanitization logic)
]
)
;
// RFC 7230 compliant header name pattern: token characters only
private
static
readonly
=
/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/
;
// Maximum limits to prevent abuse
private
static
readonly
=
256
;
private
static
readonly
=
8192
;
private
static
readonly
=
20
;
protected
readonly
:
<
string
,
string
>
;
constructor
(
:
,
protected
readonly
:
string
,
protected
readonly
:
string
,
@IDomainService
:
,
@IChatMLFetcher
:
,
@ITokenizerProvider
:
,
@IInstantiationService
protected
:
,
@IConfigurationService
:
,
@IExperimentationService
:
,
@IChatWebSocketManager
:
,
@ILogService
protected
:
)
{
super
(
,
,
,
,
,
,
,
,
)
;
this
.
=
this
.
_sanitizeCustomHeaders
(
.
)
;
}
/**
* BYOK endpoints supply their own credential (`api-key
` / `
`)
* via {@link getExtraHeaders}, so the chat fetcher must not fall back to the
* CAPI Copilot bearer token nor raise a missing-key error for these requests.
*/
public readonly ownsAuthorization = true;
protected override getCompletionsCallback(): RawMessageConversionCallback {
const supportsThinking = !!this.modelMetadata.capabilities.supports.thinking;
return (out, data) => {
if (data?.id) {
out.cot_id = data.id;
const text = Array.isArray(data.text) ? data.text.join('') : data.text;
out.cot_summary = text;
if (supportsThinking) {
out.reasoning_content = text;
out.reasoning = text;
}
}
};
}
protected _isReservedHeader(lowerKey: string): boolean {
return OpenAIEndpoint._reservedHeaders.has(lowerKey);
}
private _sanitizeCustomHeaders(headers: Readonly<Record<string, string>> | undefined): Record<string, string> {
if (!headers) {
return {};
}
const entries = Object.entries(headers);
if (entries.length > OpenAIEndpoint._maxCustomHeaderCount) {
this.logService.warn(`
[
]
'${this.modelMetadata.id}'
{
.
}
,
of
{
.
}
.
{
.
}
.
`);
}
const sanitized: Record<string, string> = {};
let processedCount = 0;
for (const [rawKey, rawValue] of entries) {
if (processedCount >= OpenAIEndpoint._maxCustomHeaderCount) {
break;
}
const key = rawKey.trim();
if (!key) {
this.logService.warn(`
[
]
'${this.modelMetadata.id}'
,
.
`);
continue;
}
if (key.length > OpenAIEndpoint._maxHeaderNameLength) {
this.logService.warn(`
[
]
'${this.modelMetadata.id}'
{
.
}
,
.
`);
continue;
}
if (!OpenAIEndpoint._validHeaderNamePattern.test(key)) {
this.logService.warn(`
`);
continue;
}
sanitized[key] = sanitizedValue;
processedCount++;
}
return sanitized;
}
private _sanitizeHeaderValue(value: unknown): string | undefined {
if (typeof value !== 'string') {
return undefined;
}
const trimmed = value.trim();
if (trimmed.length > OpenAIEndpoint._maxHeaderValueLength) {
return undefined;
}
// Disallow control characters including CR, LF, and others (0x00-0x1F, 0x7F)
// This prevents HTTP header injection and response splitting attacks
if (/[\x00-\x1F\x7F]/.test(trimmed)) {
return undefined;
}
// Additional check for potential Unicode issues
// Reject headers with bidirectional override characters or zero-width characters
if (/[\u200B-\u200D\u202A-\u202E\uFEFF]/.test(trimmed)) {
return undefined;
}
return trimmed;
}
override createRequestBody(options: ICreateEndpointBodyOptions): IEndpointBody {
if (this.useResponsesApi) {
// Handle Responses API: customize the body directly
const zdr = !!this.modelMetadata.zeroDataRetentionEnabled;
// When ZDR is on the server refuses to retain responses, so we must
// not chain via `
` and must not ask it to `
`.
options.ignoreStatefulMarker = options.ignoreStatefulMarker || zdr;
const body = super.createRequestBody(options);
body.store = !zdr;
body.n = undefined;
body.stream_options = undefined;
if (!this.modelMetadata.capabilities.supports.thinking) {
body.reasoning = undefined;
body.include = undefined;
}
if (body.previous_response_id && (!body.previous_response_id.startsWith('resp_') || zdr)) {
// Don't use a response ID from CAPI or when zero data retention is enabled
body.previous_response_id = undefined;
}
this._applyReasoningEffort(body, options);
return this._applyConfiguredModelOptions(body, options);
} else if (this.useMessagesApi) {
// Delegate to base ChatEndpoint for Messages API dispatch
const body = super.createRequestBody(options);
this._applyReasoningEffort(body, options);
return this._applyConfiguredModelOptions(body, options);
} else {
const body = createCapiRequestBody(options, this.model, this.getCompletionsCallback());
if (body.messages && isKimiFamily(this)) {
body.messages = normalizeKimiToolCallIds(body.messages);
}
this._applyReasoningEffort(body, options);
return this._applyConfiguredModelOptions(body, options);
}
}
private _applyConfiguredModelOptions(body: IEndpointBody, options: ICreateEndpointBodyOptions): IEndpointBody {
const modelOptions = this.modelMetadata.modelOptions;
if (!modelOptions) {
return body;
}
for (const key of ['temperature', 'top_p'] as const) {
const requestValue = options.requestOptions?.[key];
if (requestValue !== undefined) {
body[key] = requestValue;
continue;
}
const configuredValue = modelOptions[key];
if (configuredValue === null) {
delete body[key];
} else if (configuredValue !== undefined) {
body[key] = configuredValue;
}
}
return body;
}
/**
* Forwards the per-request reasoning effort to the model body in the shape the endpoint expects.
* Default shape mirrors the API path (`
` \u2192 nested `
.
`, `
` \u2192 `
.
`,
* `
` \u2192 top-level `
`).
* `
.
` overrides the default so users hosting OpenAI-compatible servers
* with diverging conventions (e.g. nested `
.
` on `
/
/
`) can opt in deterministically.
*/
private _applyReasoningEffort(body: IEndpointBody, options: ICreateEndpointBodyOptions): void {
const supports = this.supportsReasoningEffort;
if (!supports?.length) {
return;
}
const format = this.modelMetadata.reasoningEffortFormat
?? (this.useResponsesApi ? 'responses' : this.useMessagesApi ? 'messages' : 'chat-completions');
const override = this._configurationService.getConfig(ConfigKey.Advanced.ReasoningEffortOverride);
const requested = override || options.modelCapabilities?.reasoningEffort || body.reasoning?.effort || body.reasoning_effort || body.output_config?.effort;
const effort = requested && supports.includes(requested) ? requested : undefined;
// Scrub any pre-populated effort first so unsupported values (e.g. the hard-coded `
` default
// from `
`) cannot leak through, then write the resolved value into the
// expected shape.
if (body.reasoning) {
const { effort: _drop, ...rest } = body.reasoning;
body.reasoning = Object.keys(rest).length > 0 ? rest : undefined;
}
body.reasoning_effort = undefined;
if (body.output_config) {
// Drop only the effort so other output_config fields (e.g. structured output format) survive
const { effort: _drop, ...rest } = body.output_config;
body.output_config = Object.keys(rest).length > 0 ? rest : undefined;
}
if (effort) {
if (format === 'responses') {
body.reasoning = { ...body.reasoning, effort };
} else if (format === 'messages') {
body.output_config = { ...body.output_config, effort };
} else {
body.reasoning_effort = effort;
}
}
}
override interceptBody(body: IEndpointBody | undefined): void {
super.interceptBody(body);
// TODO @lramos15 - We should do this for all models and not just here
if (body?.tools?.length === 0) {
delete body.tools;
}
if (body?.tools) {
body.tools = body.tools.map(tool => {
if (isOpenAiFunctionTool(tool) && tool.function.parameters === undefined) {
tool.function.parameters = { type: 'object', properties: {} };
}
return tool;
});
}
if (body) {
if (this.modelMetadata.capabilities.supports.thinking) {
delete body.temperature;
if (!this.useMessagesApi && !this.useResponsesApi) {
// OpenAI Chat Completions thinking models (e.g. o1/o3) require `
` instead of `
`.
// Responses bodies use `
` natively, and Messages requires `
` — neither needs this rename.
body['max_completion_tokens'] = body.max_tokens;
delete body.max_tokens;
}
}
// Chat Completions: drop `
` so the server defaults to its maximum (preferred for BYOK).
// Responses uses `
`, so this delete is a no-op there. Messages requires `
`, so leave it alone.
if (!this.useMessagesApi) {
delete body.max_tokens;
}
if (!this.useResponsesApi && !this.useMessagesApi && body.stream) {
body['stream_options'] = { 'include_usage': true };
}
}
}
override get urlOrRequestMetadata(): string {
return this._modelUrl;
}
public override getExtraHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json'
};
if (this._modelUrl.includes('openai.azure')) {
headers['api-key'] = this._apiKey;
} else {
headers['Authorization'] = `
{
this
.
}
;
}
for
(
const
[
,
]
of
.
entries
(
this
.
)
)
{
[
]
=
;
}
return
;
}
cloneWithTokenOverride
(
:
number
)
:
{
const
=
{
...
this
.
,
:
}
;
return
this
.
.
createInstance
(
,
,
this
.
,
this
.
)
;
}
public
async
makeChatRequest2
(
:
,
:
)
:
Promise
<
>
{
// Use ignoreStatefulMarker: false as the initial request default; the parent retry flow can override it on InvalidStatefulMarker retries.