Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*//**
* Local mock server that implements the OpenAI Chat Completions streaming API.
* Used by the chat perf benchmark to replace the real LLM backend with
* deterministic, zero-latency responses.
*
* Supports scenario-based responses: the `messages` array's last user message
* content is matched against scenario IDs. Unknown scenarios get a default
* text-only response.
*
* Note: this file is loaded as CommonJS (scripts/package.json declares
* `"type": "commonjs"`), so it uses `require()` / `module.exports` rather
* than ESM `import` / `export` syntax. TypeScript types are stripped by
* Node 24's native type-stripping; no compile step is required.
*/const http:typeofimport('http')=require('http');const path:typeofimport('path')=require('path');const{ EventEmitter }:typeofimport('events')=require(
path__dirname
msg log
_verbose
obj maxLen
text
text obj obj obj
text obj
textlength maxLen
text text maxLen
text
text
textl
content
delayMs
Record request Record
toolNamePattern RegExp
arguments ScenarioToolCallArguments
kind
toolCalls ScenarioToolCall
kind
chunks StreamChunk
kind
thinkingChunks StreamChunk
chunks StreamChunk
kind
kind
kind
message
kind
toolCalls ScenarioToolCall
kind
chunks StreamChunk
kind
thinkingChunks StreamChunk
chunks StreamChunk
kind
kind
kind
chunks StreamChunk
kind
thinkingChunks StreamChunk
chunks StreamChunk
type
turns ScenarioTurn
scenario scenario MultiTurnScenario
scenario scenario scenariotype
chunks StreamChunk
content
chunks content delayMs
ms content
chunks content delayMs ms
contents delayMs
content contents
chunks content delayMs
contents
contents
StreamChunk
chunks
Record StreamChunk MultiTurnScenario
StreamChunk
scenario
scenario
content delayMs
scenario content delayMs
input_price
cache_price
cache_write_price
output_price
context_max
batch_size
ModelTokenPriceTier
long_context ModelTokenPriceTier
restricted_to
is_premium
multiplier
token_prices ModelTokenPrices
max_prompt_image_size
max_prompt_images
supported_media_types
max_prompt_tokens
max_output_tokens
max_context_window_tokens
max_non_streaming_output_tokens
vision ModelVisionLimits
streaming
tool_calls
parallel_tool_calls
vision
structured_outputs
reasoning_effort
max_thinking_budget
min_thinking_budget
type
family
tokenizer
object
limits ModelLimits
supports ModelSupports
id
name
object
version
vendor
model_picker_enabled
model_picker_category
model_picker_price_category
is_chat_default
is_chat_fallback
preview
billing ModelBilling
capabilities ModelCapabilities
supported_endpoints
MockModel
id
name
object
version
vendor
model_picker_enabled
model_picker_category
model_picker_price_category
is_chat_default
is_chat_fallback
preview
billing restricted_to token_prices batch_size cache_price cache_write_price context_max input_price output_price
capabilities
type
family
tokenizer
object
limits max_prompt_tokens max_output_tokens max_context_window_tokens vision max_prompt_image_size max_prompt_images supported_media_types
supports streaming tool_calls parallel_tool_calls vision structured_outputs reasoning_effort
supported_endpoints
id
name
object
version
vendor
model_picker_enabled
model_picker_category
model_picker_price_category
is_chat_default
is_chat_fallback
preview
billing restricted_to token_prices batch_size cache_price cache_write_price input_price output_price
capabilities
type
family
tokenizer
object
limits max_prompt_tokens max_output_tokens max_context_window_tokens max_non_streaming_output_tokens vision max_prompt_image_size max_prompt_images supported_media_types
supports streaming tool_calls parallel_tool_calls vision max_thinking_budget min_thinking_budget
supported_endpoints
id
name
object
version
vendor
model_picker_enabled
model_picker_category
model_picker_price_category
is_chat_default
is_chat_fallback
preview
billing
restricted_to
token_prices
batch_size
cache_price cache_write_price input_price output_price context_max
long_context cache_price cache_write_price input_price output_price context_max
capabilities
type
family
tokenizer
object
limits max_prompt_tokens max_output_tokens max_context_window_tokens
supports streaming tool_calls parallel_tool_calls vision structured_outputs reasoning_effort
supported_endpoints
MockModel
id
name
object
version
vendor
model_picker_enabled
model_picker_price_category
is_chat_default
is_chat_fallback
preview
billing token_prices batch_size cache_price input_price output_price
capabilities
type
family
tokenizer
object
limits
max_prompt_tokens
max_output_tokens
max_context_window_tokens
supports streaming tool_calls parallel_tool_calls vision
supported_endpoints
id
name
object
version
vendor
model_picker_enabled
model_picker_price_category
is_chat_default
is_chat_fallback
preview
billing token_prices batch_size cache_price input_price output_price
capabilities
type
family
tokenizer
object
limits max_prompt_tokens max_output_tokens max_context_window_tokens
supports streaming tool_calls parallel_tool_calls
supported_endpoints
content index finish
id
object
created MathDate
model
choices
index
delta finish content
finish_reason finish
content_filter_results
usage
id
object
created MathDate
model
choices
index
delta role content
finish_reason
content_filter_results
usage
id
object
created MathDate
model
choices
index
delta role content
finish_reason
content_filter_results
usage
index callId functionName
id
object
created MathDate
model
choices
index
delta
tool_calls
index
id callId
type
name functionName arguments
finish_reason
content_filter_results
usage
index argsFragment
id
object
created MathDate
model
choices
index
delta
tool_calls
index
arguments argsFragment
finish_reason
content_filter_results
usage
id
object
created MathDate
model
choices
index
delta
finish_reason
content_filter_results
usage
text
id
object
created MathDate
model
choices
index
delta cot_summary text
finish_reason
content_filter_results
usage
cotId
id
object
created MathDate
model
choices
index
delta cot_id cotId
finish_reason
content_filter_results
usage
req IncomingMessage res ServerResponse
contentLength reqheaders
ts
res
res
res
reqmethod res res
reqUrl requrl
path reqUrlpathname
status data
resstatus
resdata
readBody resolve
body
req chunk body chunk
req body
path res res
path
path path
token
expires_at MathDate
refresh_in
sku
individual
copilot_plan
endpoints
api
proxy
path
path reqmethod
model
path reqmethod
available_models m mid
selected_model
session_token Date
expires_at MathDate
discounted_costs
path reqmethod
data
path reqmethod
modelId path
path
state terms
knownModel m mid modelId
result knownModel
id modelId
name
version
vendor
model_picker_enabled
is_chat_default
is_chat_fallback
billing is_premium multiplier
capabilities
type
family modelId
tokenizer
object
limits max_prompt_tokens max_output_tokens max_context_window_tokens
supports streaming tool_calls parallel_tool_calls vision
supported_endpoints
ts
result
path
path
sessions total_count page_size page_number
path
agents
path
data
id name vendor
capabilities type family supports streaming
path
agents
path reqmethod
body
serverEvents path method body
body res
path reqmethod
body
serverEvents path method body
body res
path reqmethod
body body res
path reqmethod
body body res
path path path
data
reqmethod
body
parsed body
parsedmessages parsedmessages
body res
serverEvents
sleep ms resolve resolve ms
messages
scenarioMsgIdx
i messageslength i i
msg messagesi
msgrole
content msgcontent
msgcontent
msgcontent
msgcontentc ctext
content
scenarioMsgIdx i
turns
startIdx scenarioMsgIdx scenarioMsgIdx
i startIdx i messageslength i
messagesirole
turns
turns
turns ScenarioTurn messages turn ModelScenarioTurn turnIndex
completedModelTurns messages
modelTurns turnst tkind ModelScenarioTurn
idx MathcompletedModelTurns modelTurnslength
turn modelTurnsidx turnIndex idx
items
i itemslength i i
item itemsi
itemrole itemtype
item
itemcontent
toolResult itemcontentpart parttype
toolResult
toolResult
body res ServerResponse
_verbose
body
body
scenarioId
isScenarioRequest
requestToolNames
messages
parsed body
messages parsedmessages
userMsgs messagesm mrole
userMsgslength
lastContent userMsgsuserMsgslength content
userMsgsuserMsgslength content
ts
tools parsedtools
requestToolNames toolst tfunctionnameBoolean
requestToolNameslength
ts
mi messageslength mi mi
msg messagesmi
msgrole
content msgcontent
msgcontent
msgcontent
msgcontentc ctext
match content
match match
scenarioId match
isScenarioRequest
scenario scenarioId
res
Date
scenario requestToolNameslength
turn turnIndex scenarioturns messages
modelTurnCount scenarioturnst tkind length
ts
turnkind
res turntoolCalls requestToolNames scenarioId messages
turnkind
res turnthinkingChunks turnchunks isScenarioRequest
turnkind
lastMsg messagesmessageslength
payload lastMsg
res content payload delayMs isScenarioRequest
turnkind
payload messages
res content payload delayMs isScenarioRequest
res turnchunks isScenarioRequest
chunks scenario
scenario
scenario StreamChunk
res chunks isScenarioRequest
scenario MultiTurnScenario StreamChunk
contentTurn ContentScenarioTurn
turn scenarioturns
turnkind
contentTurn turn
turnkind
contentTurn turn
contentTurnchunks
res ServerResponse chunks StreamChunk isScenarioRequest
res
chunk chunks
chunkdelayMs chunkdelayMs
res
res
res
res
isScenarioRequest
serverEvents
responseoutput_itemaddedresponseoutput_textdeltaresponseoutput_itemdoneresponsecompletedinputmessagesmockllm responses request bodyinputtoolsmockllm $ts → responsesapi $inputlength input items $requestToolNameslength tools scenario$scenarioIdmockllm $ts → responsesapi multiturn $scenarioId model turn $turnIndex $modelTurnCount $turnkindjson\n\njson\n\ninputscenariorole type resolveCurrentTurnfunction_callresp_mock_$Dateevent responsecreated\ndata $
type
sequence_number
response skeleton
\n\nevent responsein_progress\ndata $
type
sequence_number
response skeleton
\n\n`
finalOutput
i i toolCallslength i
call toolCallsi
toolName requestToolNamesname calltoolNamePatternname
toolName
toolName calltoolNamePatternsource
callId
itemId
argsJson callarguments request
item
id itemId
type
status
call_id callId
name toolName
arguments
res
res
res
doneItem item status arguments argsJson
finalOutputdoneItem
res
res
res
isScenarioRequest
serverEvents
res ServerResponse chunks StreamChunk isScenarioRequest
responseId
outputItemId
model
res
res
res
fullText
chunk chunks
chunkdelayMs chunkdelayMs
fullText chunkcontent
res
res
res
res
res
res
isScenarioRequest
serverEvents
res ServerResponse eventType payload Record
res
res
res ServerResponse chunks StreamChunk isScenarioRequest
messageId
model
res
message
id messageId
type
role
model
content
stop_reason
stop_sequence
usage
input_tokens
output_tokens
cache_creation_input_tokens
cache_read_input_tokens
res
index
content_block type text
totalOutputTokens
chunk chunks
chunkdelayMs chunkdelayMs
res
index
delta type text chunkcontent
totalOutputTokens Math Mathchunkcontentlength
res index
res
delta stop_reason stop_sequence
usage output_tokens totalOutputTokens
res
res
isScenarioRequest
serverEvents
body res ServerResponse
_verbose
body
body
scenarioId
isScenarioRequest
messages
requestToolNames
parsed body
messages parsedmessages
tools parsedtools
requestToolNames toolst tnameBoolean
userMsgs messagesm mrole
userMsgslength
last userMsgsuserMsgslength
lastContent lastcontent
lastcontent
lastcontent
lastcontentc ctext
ts
mi messageslength mi mi
msg messagesmi
msgrole
content msgcontent
msgcontent
msgcontent
msgcontentc ctext
match content
match match
scenarioId match
isScenarioRequest
isScenarioRequest parsedsystem
systemContent parsedsystem
parsedsystem
parsedsystem
parsedsystemc ctext
match systemContent
match match
scenarioId match
isScenarioRequest
scenario scenarioId
res
Date
scenario requestToolNameslength
turn turnIndex scenarioturns messages
modelTurnCount scenarioturnst tkind length
ts
turnkind
res turntoolCalls requestToolNames scenarioId isScenarioRequest messages
turnkind
lastMsg messagesmessageslength
payload lastMsg
res content payload delayMs isScenarioRequest
turnkind
payload messages
res content payload delayMs isScenarioRequest
res turnchunks isScenarioRequest
chunks scenario
scenario
scenario StreamChunk
res chunks isScenarioRequest
input_json_deltastop_reason msg_mock_$Date`
model
res
message
id messageId
type
role
model
content
stop_reason
stop_sequence
usage input_tokens output_tokens cache_creation_input_tokens cache_read_input_tokens
i i toolCallslength i
call toolCallsi
toolName requestToolNamesname calltoolNamePatternname
toolName
toolName calltoolNamePatternsource
callId
res
index i
content_block type id callId name toolName input
argsJson callarguments request
fragmentSize Math MathargsJsonlength
pos pos argsJsonlength pos fragmentSize
fragment argsJsonpos pos fragmentSize
res
index i
delta type partial_json fragment
res index i
res
delta stop_reason stop_sequence
usage output_tokens
res
res
isScenarioRequest
serverEvents
res ServerResponse
thinkingChunks StreamChunk
contentChunks StreamChunk
isScenarioRequest
res
chunk thinkingChunks
chunkdelayMs chunkdelayMs
res
cotId
res
chunk contentChunks
chunkdelayMs chunkdelayMs
res
res
res
res
isScenarioRequest
serverEvents
res ServerResponse
toolCalls ScenarioToolCall
requestToolNames
scenarioId
request
res
i i toolCallslength i
call toolCallsi
callId
toolName requestToolNamesname calltoolNamePatternname
toolName
toolName calltoolNamePatternsource
res
argsJson callarguments request
fragmentSize Math MathargsJsonlength
pos pos argsJsonlength pos fragmentSize
fragment argsJsonpos pos fragmentSize
res
res
res
res
argumentsOrResolver ScenarioToolCallArguments request Record
argumentsOrResolver request argumentsOrResolver
port
url
n timeoutMs
n timeoutMs
CapturedRequest
path
method
body
logger msg
verbose
requiredRequestHeader
name
value
trustedRequestHost
captureRequests
port options StartServerOptions MockLlmServerHandle
optionslogger
_log optionslogger
optionsverbose
_verbose
resolve reject
reqCount
completions
requestWaiters
completionWaiters
completions
completionWaiters completionWaitersfn
serverEvents onCompletion
capturedRequests CapturedRequest
captureRequests optionscaptureRequests
info path method body
parsed infobody
parsed infobody
capturedRequests path infopath method infomethod body parsed
captureRequests
serverEvents onCapturedRequest
server httpreq res
requiredRequestHeader optionsrequiredRequestHeader
requestHost reqheadershost
isTrustedProxy optionstrustedRequestHost requestHost optionstrustedRequestHost
requiredRequestHeader reqheadersrequiredRequestHeadername requiredRequestHeadervalue isTrustedProxy
res
res
reqCount
requestWaiters requestWaitersfn
req res
serverport
addr server
actualPort addr addr addrport port
url
port actualPort
url
resolve reject
serverEvents onCompletion
captureRequests
serverEvents onCapturedRequest
servererr err err
reqCount
n timeoutMs resolve reject
reqCount n
timer timeoutMs
requestWaiters
reqCount n timer
completions
n timeoutMs resolve reject
completions n
timer timeoutMs
completionWaiters
completions n timer
capturedRequests
server reject
scenarioId message afterModelTurn
scenario scenarioId
scenario
result message afterModelTurn
modelTurnsSeen
turn scenarioturns
turnkind
result message turnmessage afterModelTurn modelTurnsSeen
modelTurnsSeen
result
scenarioId
scenario scenarioId
scenario
scenarioturnst tkind length
id definition StreamChunk MultiTurnScenario
id definition
Object
moduleexports
startServer _startServer
ScenarioBuilder ScenarioBuilderImpl
registerScenario _registerScenario
getScenarioIds _getScenarioIds
getUserTurns _getUserTurns
getModelTurnCount _getModelTurnCount
StreamChunk
ScenarioTurn
ModelScenarioTurn
ContentScenarioTurn
MultiTurnScenario
MockLlmServerHandle
StartServerOptions
CapturedRequest
startServer _startServer
ScenarioBuilder ScenarioBuilderImpl
registerScenario _registerScenario
getScenarioIds _getScenarioIds
getUserTurns _getUserTurns
getModelTurnCount _getModelTurnCount
main module
registerPerfScenarios
port processargv
porthandle MockLlmServerHandle
/**
* A multi-turn scenario — an ordered sequence of turns.
* The mock server determines which model turn to serve based on the number
* of assistant→tool round-trips already present in the conversation.
* User turns are skipped by the server and instead injected by the test
* harness, which types them into the chat input and presses Enter.
*/
interface
MultiTurnScenario
{
:
'multi-turn'
;
:
[
]
;
}
function
isMultiTurnScenario
(
:
any
)
:
is
{
return
&&
typeof
===
'object'
&&
.
===
'multi-turn'
;
}
/**
* Helper for building scenario chunk sequences with timing control.
*/
class
ScenarioBuilderImpl
{
:
[
]
=
[
]
;
/**
* Emit a content chunk immediately (no delay before it).
*/
emit
(
:
string
)
:
this
{
this
.
.
push
(
{
,
:
0
}
)
;
return
this
;
}
/**
* Wait, then emit a content chunk — simulates network/token generation latency.
* @paramms - delay in milliseconds before this chunk
*/
wait
(
:
number
,
:
string
)
:
this
{
this
.
.
push
(
{
,
:
}
)
;
return
this
;
}
/**
* Emit multiple chunks with uniform inter-chunk delay.
* @paramdelayMs - delay between each chunk (default ~1 frame)
*/
stream
(
:
string
[
]
,
=
15
)
:
this
{
for
(
const
of
)
{
this
.
.
push
(
{
,
}
)
;
}
return
this
;
}
/**
* Emit multiple chunks with no delay (burst).
*/
// -- Model shape -------------------------------------------------------------
// Shared types describing the CAPI `/models` response shape the mock returns.
// Centralized here so all model fixtures stay in sync and can be tweaked in one
// place when the backend billing/capabilities contract changes. Mirrors the
// `CCAModel*` interfaces in `src/typings/copilot-api.d.ts`.
/**
* Per-tier token pricing (prices are in 1/1,000,000ths of a USD per token, i.e.
* scaled by `token_prices.batch_size`). A model may expose a `default` tier and
* an optional `long_context` tier with higher prices for large prompts.
*/
interface
ModelTokenPriceTier
{
?
:
number
;
/** Cache read price (per cached input token). */
?
:
number
;
/** Cache write price (per token written to the prompt cache). */
?
:
number
;
?
:
number
;
?
:
number
;
}
/**
* The set of pricing tiers advertised for a model.
*/
interface
ModelTokenPrices
{
?
:
number
;
default
?
:
;
?
:
;
}
/**
* Billing metadata: entitlement gating plus the token price tiers consumed by
* the model picker's cost table.
*/
interface
ModelBilling
{
?
:
string
[
]
;
?
:
boolean
;
?
:
number
;
?
:
;
}
/**
* Vision-related prompt limits.
*/
interface
ModelVisionLimits
{
:
number
;
:
number
;
:
string
[
]
;
}
/**
* Token/context window limits for a model.
*/
interface
ModelLimits
{
?
:
number
;
?
:
number
;
?
:
number
;
?
:
number
;
?
:
;
}
/**
* Feature flags advertised by a model.
*/
interface
ModelSupports
{
?
:
boolean
;
?
:
boolean
;
?
:
boolean
;
?
:
boolean
;
?
:
boolean
;
?
:
string
[
]
;
?
:
number
;
?
:
number
;
}
/**
* Model capabilities (family, tokenizer, limits, supported features).
*/
interface
ModelCapabilities
{
:
string
;
:
string
;
:
string
;
:
string
;
:
;
:
;
}
/**
* A single entry in the mock's `/models` list. Matches the CAPI `/models`
* response shape closely enough for the extension and CLI SDK to consume.
*/
interface
MockModel
{
:
string
;
:
string
;
:
string
;
:
string
;
:
string
;
:
boolean
;
?
:
string
;
?
:
string
;
:
boolean
;
:
boolean
;
:
boolean
;
:
;
:
;
:
string
[
]
;
}
/**
* Additional model definitions the mock advertises beyond `MODEL` and
* `gpt-4o-mini`. `gpt-5.3-codex` is the Copilot CLI SDK's hard-coded default
* model; smoke tests/automation that exercise the CLI need it in the mock's
* /models list, otherwise the SDK fails with "No model available".
*/
const
EXTRA_MODELS
:
[
]
=
[
// gpt-5.3-codex — the Copilot CLI SDK's default model.
// Shape matches real CAPI /models response exactly.
{
:
'gpt-5.3-codex'
,
:
'GPT-5.3-Codex (Mock)'
,
:
'model'
,
:
'gpt-5.3-codex'
,
:
'OpenAI'
,
:
true
,
:
'powerful'
,
:
'medium'
,
:
true
,
:
false
,
:
false
,
:
{
:
[
'pro'
,
'edu'
,
'pro_plus'
,
'individual_trial'
,
'business'
,
'enterprise'
,
'max'
]
,
:
{
:
1000000
,
default
:
{
:
17
,
:
219
,
:
272000
,
:
175
,
:
1400
}
}
}
,
:
{
:
'chat'
,
:
'gpt-5.3-codex'
,
:
'o200k_base'
,
:
'model_capabilities'
,
:
{
:
272000
,
:
128000
,
:
400000
,
:
{
:
3145728
,
:
1
,
:
[
'image/jpeg'
,
'image/png'
,
'image/webp'
,
'image/gif'
]
}
}
,
:
{
:
true
,
:
true
,
:
true
,
:
true
,
:
true
,
:
[
'low'
,
'medium'
,
'high'
,
'xhigh'
]
}
,
}
,
:
[
'/responses'
]
,
}
,
// Anthropic Claude model — required by the Claude Code session type.
{
:
'claude-sonnet-4.5'
,
:
'Claude Sonnet 4.5 (Mock)'
,
:
'model'
,
:
'claude-sonnet-4.5'
,
:
'Anthropic'
,
:
true
,
:
'versatile'
,
:
'medium'
,
:
false
,
:
false
,
:
false
,
:
{
:
[
'pro'
,
'pro_plus'
,
'max'
,
'business'
,
'enterprise'
]
,
:
{
:
1000000
,
default
:
{
:
30
,
:
375
,
:
300
,
:
1500
}
}
}
,
:
{
:
'chat'
,
:
'claude-sonnet-4.5'
,
:
'o200k_base'
,
:
'model_capabilities'
,
:
{
:
168000
,
:
32000
,
:
200000
,
:
16000
,
:
{
:
3145728
,
:
5
,
:
[
'image/jpeg'
,
'image/png'
,
'image/webp'
]
}
}
,
:
{
:
true
,
:
true
,
:
true
,
:
true
,
:
32000
,
:
1024
}
,
}
,
:
[
'/chat/completions'
,
'/v1/messages'
]
,
}
,
// mock-config-model — a Responses-API model that advertises BOTH a reasoning
// effort picker (capabilities.supports.reasoning_effort) AND a context size
// picker (a `long_context` billing tier whose context_max exceeds the default
// tier). Used by the `Chat Model Configuration` smoke tests to verify that the
// reasoning effort and context size selected in the model-picker UI are
// forwarded to the server (as `reasoning.effort` and the context-management
// `compact_threshold` in the /responses request body) and surfaced in the
// context-usage gauge. The `mock-config` family is intentionally absent from
// `modelsWithoutResponsesContextManagement` so context management stays enabled.
// Numbers mirror a GPT-5.5-class model: the default tier exposes a 272K prompt
// window (`default.context_max`) and the long tier the full window minus the
// Note `formatTokenCount` renders 922000 as "1M" (its `>900K → 1M` branch), so
// the long option/label reads "1M" even though the value is 922K. Output is
// 128K, so the context-usage gauge totals (input + output) read 400K and 1M.
{
:
'mock-config-model'
,
:
'Mock Config Model'
,
:
'model'
,
:
'mock-config-model'
,
:
'OpenAI'
,
:
true
,
:
'versatile'
,
:
'medium'
,
:
false
,
:
false
,
:
false
,
:
{
:
[
'pro'
,
'edu'
,
'pro_plus'
,
'individual_trial'
,
'business'
,
'enterprise'
,
'max'
]
,
:
{
:
1000000
,
default
:
{
:
17
,
:
219
,
:
175
,
:
1400
,
:
272000
}
,
:
{
:
34
,
:
438
,
:
350
,
:
2800
,
:
1050000
}
,
}
,
}
,
:
{
:
'chat'
,
:
'mock-config'
,
:
'o200k_base'
,
:
'model_capabilities'
,
:
{
:
922000
,
:
128000
,
:
1050000
}
,
:
{
:
true
,
:
true
,
:
true
,
:
false
,
:
true
,
:
[
'low'
,
'medium'
,
'high'
]
}
,
}
,
:
[
'/responses'
]
,
}
,
]
;
/**
* Complete model list used by both GET /models and GET /models/{id}.
* Kept in a single array so the two handlers always return consistent data.
*/
const
ALL_MODELS
:
[
]
=
[
{
:
MODEL
,
:
'GPT-4o (Mock)'
,
:
'model'
,
:
'gpt-4o-2024-08-06'
,
:
'Azure OpenAI'
,
:
false
,
:
'medium'
,
:
false
,
:
true
,
:
false
,
:
{
:
{
:
1000000
,
default
:
{
:
125
,
:
250
,
:
1000
}
}
}
,
:
{
:
'chat'
,
:
'gpt-4o'
,
:
'o200k_base'
,
:
'model_capabilities'
,
:
{
// Use a very large token limit so the Responses API compaction
// threshold (90% of max_prompt_tokens) is never reached during
// perf benchmarks.
:
10000000
,
:
131072
,
:
10000000
,
}
,
:
{
:
true
,
:
true
,
:
true
,
:
false
}
,
}
,
:
[
'/chat/completions'
]
,
}
,
{
:
'gpt-4o-mini'
,
:
'GPT-4o mini (Mock)'
,
:
'model'
,
:
'gpt-4o-mini-2024-07-18'
,
:
'Azure OpenAI'
,
:
false
,
:
'low'
,
:
false
,
:
false
,
:
false
,
:
{
:
{
:
1000000
,
default
:
{
:
15
,
:
30
,
:
120
}
}
}
,
:
{
:
'chat'
,
:
'gpt-4o-mini'
,
:
'o200k_base'
,
:
'model_capabilities'
,
:
{
:
12288
,
:
4096
,
:
128000
}
,
:
{
:
true
,
:
true
,
:
true
}
,
}
,
:
[
'/chat/completions'
]
,
}
,
...
EXTRA_MODELS
,
]
;
function
makeChunk
(
:
string
,
:
number
,
:
boolean
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
?
{
}
:
{
}
,
:
?
'stop'
:
null
,
:
{
}
,
}
]
,
:
null
,
}
;
}
function
makeInitialChunk
(
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
{
:
'assistant'
,
:
''
}
,
:
null
,
:
{
}
,
}
]
,
:
null
,
}
;
}
/**
* Build a tool-call initial chunk (role only, no content).
*/
function
makeToolCallInitialChunk
(
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
{
:
'assistant'
,
:
null
}
,
:
null
,
:
{
}
,
}
]
,
:
null
,
}
;
}
/**
* Build a tool-call function-start chunk.
* @paramindex - tool call index
* @paramcallId - unique call ID
* @paramfunctionName - tool function name
*/
function
makeToolCallStartChunk
(
:
number
,
:
string
,
:
string
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
{
:
[
{
,
:
,
:
'function'
,
function
:
{
:
,
:
''
}
,
}
]
,
}
,
:
null
,
:
{
}
,
}
]
,
:
null
,
}
;
}
/**
* Build a tool-call arguments chunk.
* @paramindex - tool call index
* @paramargsFragment - partial JSON arguments
*/
function
makeToolCallArgsChunk
(
:
number
,
:
string
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
{
:
[
{
,
function
:
{
:
}
,
}
]
,
}
,
:
null
,
:
{
}
,
}
]
,
:
null
,
}
;
}
/**
* Build a tool-call finish chunk.
*/
function
makeToolCallFinishChunk
(
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
{
}
,
:
'tool_calls'
,
:
{
}
,
}
]
,
:
null
,
}
;
}
/**
* Build a thinking (chain-of-thought summary) chunk.
* Uses the `cot_summary` field in the delta, matching the Copilot API wire format.
* @paramtext - thinking text fragment
*/
function
makeThinkingChunk
(
:
string
)
{
return
{
:
'chatcmpl-perf-benchmark'
,
:
'chat.completion.chunk'
,
:
.
floor
(
.
now
(
)
/
1000
)
,
:
MODEL
,
:
[
{
:
0
,
:
{
:
}
,
:
null
,
:
{
}
,
}
]
,
:
null
,
}
;
}
/**
* Build a thinking ID chunk (sent after thinking text to close the block).
* @paramcotId - unique chain-of-thought ID
*/
// -- Catch-all: any remaining POST with messages → chat completions
if
(
.
===
'POST'
)
{
readBody
(
)
.
then
(
(
:
string
)
=>
{
try
{
const
=
JSON
.
parse
(
)
;
if
(
.
&&
Array
.
isArray
(
.
)
)
{
handleChatCompletions
(
,
)
;
return
;
}
}
catch
{
}
json
(
200
,
{
}
)
;
}
)
;
return
;
}
// -- Catch-all GET → empty success --------------------------------
json
(
200
,
{
}
)
;
}
// -- Server lifecycle --------------------------------------------------------
/** Emitted when a scenario chat completion is fully served. */
const
=
new
EventEmitter
(
)
;
const
=
(
:
number
)
:
Promise
<
void
>
=>
new
Promise
(
=>
setTimeout
(
,
)
)
;
/**
* Count the number of model turns already completed for the CURRENT scenario.
* Only counts assistant messages that appear after the last user message
* containing a [scenario:X] tag. This prevents assistant messages from
* previous scenarios (in the same chat session) from inflating the count.
*/
function
countCompletedModelTurns
(
:
any
[
]
)
:
number
{
// Find the index of the last user message with a scenario tag
let
=
-
1
;
for
(
let
=
.
-
1
;
>=
0
;
--
)
{
const
=
[
]
;
if
(
.
!==
'user'
)
{
continue
;
}
const
=
typeof
.
===
'string'
?
.
:
Array
.
isArray
(
.
)
?
.
.
map
(
(
:
any
)
=>
.
||
''
)
.
join
(
''
)
:
''
;
if
(
/\[scenario:[^\]]+\]/
.
test
(
)
)
{
=
;
break
;
}
}
// Count assistant messages after the scenario tag message
let
=
0
;
const
=
>=
0
?
+
1
:
0
;
for
(
let
=
;
<
.
;
++
)
{
if
(
[
]
.
===
'assistant'
)
{
++
;
}
}
return
;
}
/**
* Compute the model-turn index for the current request given the scenario's
* turn list. User turns are skipped (they're handled by the test harness)
* and do not consume a model turn index.
*
* The algorithm counts completed assistant messages in the conversation
* history (each one = one served model turn), then maps that to the
* n-th model turn in the scenario (skipping user turns).
*/
function
resolveCurrentTurn
(
:
[
]
,
:
any
[
]
)
:
{
:
;
:
number
}
{
const
=
countCompletedModelTurns
(
)
;
// Build the model-only turn list (skip user turns)
const
=
.
filter
(
=>
.
!==
'user'
)
as
[
]
;
const
=
.
min
(
,
.
-
1
)
;
return
{
:
[
]
,
:
}
;
}
function
findLastToolResult
(
:
any
[
]
)
:
any
{
for
(
let
=
.
-
1
;
>=
0
;
--
)
{
const
=
[
]
;
if
(
?.
===
'tool'
||
?.
===
'function_call_output'
)
{
return
;
}
if
(
Array
.
isArray
(
?.
)
)
{
const
=
.
.
findLast
(
(
:
any
)
=>
?.
===
'tool_result'
)
;
if
(
)
{
return
;
}
}
}
return
undefined
;
}
async
function
handleChatCompletions
(
:
string
,
:
import
(
'http'
)
.
)
:
Promise
<
void
>
{
if
(
)
{
_log
(
`[mock-llm] chat/completions request body:`
)
;
try
{
_log
(
_indentVerbose
(
_formatVerbose
(
JSON
.
parse
(
)
)
)
)
;
}
catch
{
_log
(
_indentVerbose
(
_formatVerbose
(
)
)
)
;
}
}
let
=
DEFAULT_SCENARIO
;
let
=
false
;
let
:
string
[
]
=
[
]
;
let
:
any
[
]
=
[
]
;
try
{
const
=
JSON
.
parse
(
)
;
=
.
||
[
]
;
// Log user messages for debugging
const
=
.
filter
(
(
:
any
)
=>
.
===
'user'
)
;
if
(
.
>
0
)
{
const
=
typeof
[
.
-
1
]
.
===
'string'
?
[
.
-
1
]
.
.
substring
(
0
,
100
)
:
'(structured)'
;
const
=
new
Date
(
)
.
toISOString
(
)
.
slice
(
11
,
-
1
)
;
_log
(
`[mock-llm] ${ts} → ${messages.length} msgs, last user: "${lastContent}"`
)
;
}
// Extract available tool names from the request's tools array
// ----- Anthropic Messages API -------------------------------------------------
/**
* Anthropic SSE writer that emits a complete message response per the
* `processResponseFromMessagesEndpoint` parser in `messagesApi.ts`. The
* sequence is:
* `event: message_start` → opening message envelope with model + usage
* `event: content_block_start` → opens a `text` content block at index 0
* `event: content_block_delta` → one or more `text_delta` chunks
* `event: content_block_stop`
* `event: message_delta` → stop_reason + final usage
* `event: message_stop`
*
* Each event must be written as both an `event:` line and a `data:` line per
* the SSE spec; the Anthropic SDK's stream parser keys off the `event:` line.
*/
/**
* Stream a content scenario as an Anthropic Messages API SSE response.
*/
async
function
streamAnthropicContent
(
:
import
(
'http'
)
.
,
:
[
]
,
:
boolean
)
:
Promise
<
void
>
{
const
=
`msg_mock_${Date.now()}`
;
const
=
'claude-sonnet-4.5'
;
writeAnthropicEvent
(
,
'message_start'
,
{
:
{
:
,
:
'message'
,
:
'assistant'
,
,
:
[
]
,
:
null
,
:
null
,
:
{
:
1
,
:
0
,
:
0
,
:
0
,
}
,
}
,
}
)
;
writeAnthropicEvent
(
,
'content_block_start'
,
{
:
0
,
:
{
:
'text'
,
:
''
}
,
}
)
;
let
=
0
;
for
(
const
of
)
{
if
(
.
>
0
)
{
await
sleep
(
.
)
;
}
writeAnthropicEvent
(
,
'content_block_delta'
,
{
:
0
,
:
{
:
'text_delta'
,
:
.
}
,
}
)
;
// Rough token estimate — only used by usage accounting in the receiver.
+=
.
max
(
1
,
.
ceil
(
.
.
/
4
)
)
;
}
writeAnthropicEvent
(
,
'content_block_stop'
,
{
:
0
}
)
;
writeAnthropicEvent
(
,
'message_delta'
,
{
:
{
:
'end_turn'
,
:
null
}
,
:
{
:
}
,
}
)
;
writeAnthropicEvent
(
,
'message_stop'
,
{
}
)
;
.
end
(
)
;
if
(
)
{
.
emit
(
'scenarioCompletion'
)
;
}
}
/**
* Anthropic-format request handler. Resolves the scenario from the request's
* `[scenario:...]` tag the same way as `handleChatCompletions` (searching the
* `messages[].content` array for either a string or an array of `{ type:
* 'text', text }` blocks), then streams the matching content turn as
* Anthropic SSE events. Multi-turn / thinking / tool-call scenarios fall
* back to their first content turn for now — Claude Code smoke tests only
* need a single text response.
*/
`[mock-llm] No matching tool for pattern ${call.toolNamePattern}, using fallback: ${toolName}`
)
;
}
const
=
`toolu_${scenarioId}_${i}_${Date.now()}`
;
writeAnthropicEvent
(
,
'content_block_start'
,
{
:
,
:
{
:
'tool_use'
,
:
,
:
,
:
{
}
}
,
}
)
;
const
=
JSON
.
stringify
(
resolveScenarioToolCallArguments
(
.
,
)
)
;
const
=
.
max
(
20
,
.
ceil
(
.
/
4
)
)
;
for
(
let
=
0
;
<
.
;
+=
)
{
const
=
.
slice
(
,
+
)
;
writeAnthropicEvent
(
,
'content_block_delta'
,
{
:
,
:
{
:
'input_json_delta'
,
:
}
,
}
)
;
await
sleep
(
5
)
;
}
writeAnthropicEvent
(
,
'content_block_stop'
,
{
:
}
)
;
}
writeAnthropicEvent
(
,
'message_delta'
,
{
:
{
:
'tool_use'
,
:
null
}
,
:
{
:
1
}
,
}
)
;
writeAnthropicEvent
(
,
'message_stop'
,
{
}
)
;
.
end
(
)
;
if
(
)
{
.
emit
(
'scenarioCompletion'
)
;
}
}
/**
* Stream thinking chunks followed by content chunks as an SSE response.
* Thinking is emitted as `cot_summary` deltas, then a `cot_id` to close the
* thinking block, followed by standard content deltas.
*/
/** Wait until at least `n` requests have been received. */
waitForRequests
(
:
number
,
:
number
)
:
Promise
<
void
>
;
/** Return total scenario-completion count. */
completionCount
(
)
:
number
;
/** Wait until at least `n` scenario chat completions have been served. */
waitForCompletion
(
:
number
,
:
number
)
:
Promise
<
void
>
;
/**
* Return the parsed bodies of the chat requests received so far (one entry
* per POST to `/chat/completions` or `/responses`, in arrival order). The
* `body` is the JSON-parsed request payload (or the raw string when parsing
* fails). Used by tests to assert what the client forwarded to the server
* (e.g. `reasoning.effort` or the context-management `compact_threshold`).
*
* Returns an empty array unless the server was started with
* {@link StartServerOptions.captureRequests} set — request capture is off by
* default so perf/mem-leak harnesses don't retain request bodies.
*/
getRequests
(
)
:
[
]
;
}
/**
* A captured chat request, exposed via {@link MockLlmServerHandle.getRequests}.
*/
interface
CapturedRequest
{
:
string
;
:
string
;
:
any
;
}
interface
StartServerOptions
{
?
:
(
:
string
)
=>
void
;
?
:
boolean
;
/** Reject requests that do not carry this exact header. */
?
:
{
:
string
;
:
string
;
}
;
?
:
string
;
/**
* When `true`, the server retains the parsed body of every `/chat/completions`
* and `/responses` POST so tests can assert what the client forwarded (see
* {@link MockLlmServerHandle.getRequests}). Defaults to `false`: perf/mem-leak
* harnesses generate large volumes of traffic, so capture stays off to avoid
* unbounded in-memory retention of request bodies. Only the smoke suites that
* call `getRequests()` enable it.
*/
?
:
boolean
;
}
/**
* Start the mock server and return a handle.
*/
function
_startServer
(
=
0
,
?
:
)
:
Promise
<
>
{
if
(
?.
)
{
=
.
;
}
if
(
?.
)
{
=
true
;
}
return
new
Promise
(
(
,
)
=>
{
let
=
0
;
let
=
0
;
let
:
Array
<
(
)
=>
boolean
>
=
[
]
;
let
:
Array
<
(
)
=>
boolean
>
=
[
]
;
const
onCompletion
=
(
)
=>
{
++
;
=
.
filter
(
=>
!
fn
(
)
)
;
}
;
.
on
(
'scenarioCompletion'
,
)
;
// Accumulate the parsed bodies of chat requests so tests can assert what
// the client forwarded (see MockLlmServerHandle.getRequests). Off by default
// so the listener (and its JSON.parse + unbounded retention) is never wired
// up for perf/mem-leak harnesses that don't assert on request bodies.
const
:
[
]
=
[
]
;
const
=
?.
??
false
;
const
onCapturedRequest
=
(
:
{
:
string
;
:
string
;
:
string
}
)
=>
{
let
:
any
=
.
;
try
{
=
JSON
.
parse
(
.
)
;
}
catch
{
// Keep the raw string when the body is not valid JSON.
}
.
push
(
{
:
.
,
:
.
,
:
}
)
;
}
;
if
(
)
{
.
on
(
'capturedRequest'
,
)
;
}
const
=
.
createServer
(
(
,
)
=>
{
const
=
?.
;
const
=
.
.
?.
replace
(
/:\d+$/
,
''
)
.
toLowerCase
(
)
;
const
=
?.
&&
===
.
;
if
(
&&
.
[
.
.
toLowerCase
(
)
]
!==
.
&&
!
)
{
.
writeHead
(
403
)
;
.
end
(
'Request must use the configured test proxy'
)
;
return
;
}
++
;
=
.
filter
(
=>
!
fn
(
)
)
;
handleRequest
(
,
)
;
}
)
;
.
listen
(
,
'127.0.0.1'
,
(
)
=>
{
const
=
.
address
(
)
;
const
=
typeof
===
'object'
&&
?
.
:
;
const
=
`http://127.0.0.1:${actualPort}`
;
resolve
(
{
:
,
,
close
:
(
)
=>
new
Promise<void>
(
(
,
)
=>
{
.
removeListener
(
'scenarioCompletion'
,
)
;
if
(
)
{
.
removeListener
(
'capturedRequest'
,
)
;
}
.
close
(
=>
?
reject
(
)
:
resolve
(
undefined
)
)
;
}
)
,
requestCount
:
(
)
=>
,
waitForRequests
:
(
:
number
,
:
number
)
=>
new
Promise<void>
(
(
,
)
=>
{
if
(
>=
)
{
resolve
(
)
;
return
;
}
const
=
setTimeout
(
(
)
=>
reject
(
new
Error
(
`Timed out waiting for ${n} requests (got ${reqCount})`
)
)
,
)
;
.
push
(
(
)
=>
{
if
(
>=
)
{
clearTimeout
(
)
;
resolve
(
)
;
return
true
;
}
return
false
;
}
)
;
}
)
,
completionCount
:
(
)
=>
,
waitForCompletion
:
(
:
number
,
:
number
)
=>
new
Promise<void>
(
(
,
)
=>
{
if
(
>=
)
{
resolve
(
)
;
return
;
}
const
=
setTimeout
(
(
)
=>
reject
(
new
Error
(
`Timed out waiting for ${n} completions (got ${completions})`
)
)
,
)
;
.
push
(
(
)
=>
{
if
(
>=
)
{
clearTimeout
(
)
;
resolve
(
)
;
return
true
;
}
return
false
;
}
)
;
}
)
,
getRequests
:
(
)
=>
.
slice
(
)
,
}
)
;
}
)
;
.
on
(
'error'
,
)
;
}
)
;
}
/**
* Get the user follow-up messages for a scenario, in order.
* Returns an array of { message, afterModelTurn } objects where afterModelTurn
* is the 0-based index of the model turn after which this user message should
* be injected.
*/
function
_getUserTurns
(
:
string
)
:
Array
<
{
:
string
;
:
number
}
>
{
const
=
SCENARIOS
[
]
;
if
(
!
isMultiTurnScenario
(
)
)
{
return
[
]
;
}
const
:
Array
<
{
:
string
;
:
number
}
>
=
[
]
;
let
=
0
;
for
(
const
of
.
)
{
if
(
.
===
'user'
)
{
.
push
(
{
:
.
,
:
}
)
;
}
else
{
++
;
}
}
return
;
}
/**
* Get the total number of model turns (non-user turns) in a scenario.
*/
function
_getModelTurnCount
(
:
string
)
:
number
{
const
=
SCENARIOS
[
]
;
if
(
!
isMultiTurnScenario
(
)
)
{
return
1
;
}
return
.
.
filter
(
=>
.
!==
'user'
)
.
;
}
/**
* Register a scenario dynamically. Test files call this to add
* scenarios that are only relevant to them.
*/
function
_registerScenario
(
:
string
,
:
[
]
|
)
:
void
{
SCENARIOS
[
]
=
;
}
/**
* Return the IDs of all currently registered scenarios.
*/