bkper 5.6.1 → 5.7.0
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/lib/agent/bundle/agent-entry.js +206 -188
- package/lib/agent/bundle/bedrock-converse-stream.js +6 -3
- package/lib/agent/bundle/github-copilot.js +1 -1
- package/lib/agent/extensions/bkper-ai-provider.d.ts.map +1 -1
- package/lib/agent/extensions/bkper-ai-provider.js +11 -5
- package/lib/agent/extensions/bkper-ai-provider.js.map +1 -1
- package/lib/docs/ai/decision-models.md +3 -2
- package/lib/docs/api/ai-gateway.md +1 -0
- package/lib/docs/api/managed-agent.md +40 -8
- package/lib/docs/apps/ai.md +1 -0
- package/lib/docs/apps/context-menu.md +1 -4
- package/lib/docs/apps/quality.md +3 -3
- package/package.json +8 -8
|
@@ -124,10 +124,13 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
124
124
|
`);let{connect:connect5,buffered}=await proxyResponsePromise;if(req.emit("proxyConnect",connect5),this.emit("proxyConnect",connect5,req),req.emit("proxy",{proxy:this.proxy.href,socket}),connect5.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug3("Upgrading socket connection to TLS"),tls2.connect({...omit2(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;if(connect5.statusCode===407&&this.onProxyAuth){debug3("Got 407 response, invoking onProxyAuth callback"),socket.destroy();let proxyAuthenticate=connect5.headers["proxy-authenticate"]||"",scheme=Array.isArray(proxyAuthenticate)?proxyAuthenticate[0].split(/\s/)[0]:proxyAuthenticate.split(/\s/)[0],authResponse=await this.onProxyAuth({response:connect5,scheme});return this._connectWithAuth(req,opts,authResponse.headers)}socket.destroy();let fakeSocket=new net3.Socket({writable:!1});return fakeSocket.readable=!0,req.once("socket",s2=>{debug3("Replaying proxy buffer for failed request"),assert(s2.listenerCount("data")>0),s2.push(buffered),s2.push(null)}),fakeSocket}async _connectWithAuth(req,opts,authHeaders){let{proxy}=this,socket;proxy.protocol==="https:"?socket=tls2.connect(setServernameFromNonIpHost(this.connectOpts)):socket=net3.connect(this.connectOpts);let headers=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},host=net3.isIPv6(opts.host)?`[${opts.host}]`:opts.host,payload2=`CONNECT ${host}:${opts.port} HTTP/1.1\r
|
|
125
125
|
`;if(proxy.username||proxy.password){let auth=`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;headers["Proxy-Authorization"]=`Basic ${Buffer.from(auth).toString("base64")}`}Object.assign(headers,authHeaders),headers.Host=`${host}:${opts.port}`,headers["Proxy-Connection"]||(headers["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let name of Object.keys(headers))payload2+=`${name}: ${headers[name]}\r
|
|
126
126
|
`;let proxyResponsePromise=parseProxyResponse(socket);socket.write(`${payload2}\r
|
|
127
|
-
`);let{connect:connect5}=await proxyResponsePromise;if(req.emit("proxyConnect",connect5),this.emit("proxyConnect",connect5,req),connect5.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug3("Upgrading socket connection to TLS"),tls2.connect({...omit2(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;throw socket.destroy(),new Error(`Proxy authentication failed with status ${connect5.statusCode} after retry`)}};HttpsProxyAgent.protocols=["http","https"];function resume(socket){setImmediate(()=>{socket.resume()})}function omit2(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}function contentText(content,separator=`
|
|
127
|
+
`);let{connect:connect5}=await proxyResponsePromise;if(req.emit("proxyConnect",connect5),this.emit("proxyConnect",connect5,req),connect5.statusCode===200)return req.once("socket",resume),opts.secureEndpoint?(debug3("Upgrading socket connection to TLS"),tls2.connect({...omit2(setServernameFromNonIpHost(opts),"host","path","port"),socket})):socket;throw socket.destroy(),new Error(`Proxy authentication failed with status ${connect5.statusCode} after retry`)}};HttpsProxyAgent.protocols=["http","https"];function resume(socket){setImmediate(()=>{socket.resume()})}function omit2(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}var PI_AI_VERSION="1.4.0";function getClientVersion(identity){return identity?.version??PI_AI_VERSION}function contentText(content,separator=`
|
|
128
128
|
`){return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(separator)}function getSystemMessageText(message){let parts=[contentText(message.content)];for(let text of Object.values(message.sections??{}))text!==null&&parts.push(text);return parts.filter(part=>part.length>0).join(`
|
|
129
129
|
|
|
130
130
|
`)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
131
131
|
|
|
132
|
-
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i7=requestedIndex;i7<EXTENDED_THINKING_LEVELS.length;i7++){let candidate=EXTENDED_THINKING_LEVELS[i7];if(availableLevels.includes(candidate))return candidate}for(let i7=requestedIndex-1;i7>=0;i7--){let candidate=EXTENDED_THINKING_LEVELS[i7];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"
|
|
133
|
-
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",inString=!1;for(let index=0;index<json.length;index++){let char=json[index];if(!inString){repaired+=char,char==='"'&&(inString=!0);continue}if(char==='"'){repaired+=char,inString=!1;continue}if(char==="\\"){let nextChar=json[index+1];if(nextChar===void 0){repaired+="\\\\";continue}if(nextChar==="u"){let unicodeDigits=json.slice(index+2,index+6);if(/^[0-9a-fA-F]{4}$/.test(unicodeDigits)){repaired+=`\\u${unicodeDigits}`,index+=5;continue}}if(VALID_JSON_ESCAPES.has(nextChar)){repaired+=`\\${nextChar}`,index+=1;continue}repaired+="\\\\";continue}repaired+=isControlCharacter(char)?escapeControlCharacter(char):char}return repaired}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseStreamingJson(partialJson){if(!partialJson||partialJson.trim()==="")return{};try{return parseJsonWithRepair(partialJson)}catch{try{return(0,import_partial_json.parse)(partialJson)??{}}catch{try{return(0,import_partial_json.parse)(repairJson(partialJson))??{}}catch{return{}}}}}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env9){return env9?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env9){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env9?.[lowercaseKey]||env9?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env9){let noProxy=getProxyEnv("no_proxy",env9).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env9){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env9))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env9)||getProxyEnv("all_proxy",env9);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env9){let proxy=getProxyForUrl(targetUrl,env9);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error2){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error2 instanceof Error?error2.message:String(error2)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error2){if(!(error2 instanceof UnsupportedStrictJsonSchemaError))throw error2;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error2.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars2=0;for(let block of content)chars2+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars2}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars2=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars2+=block.text.length:block.type==="thinking"?chars2+=block.thinking.length:chars2+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars2/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i7=0;i7<messages.length;i7++){let message=messages[i7];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i7})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i7=usageInfo.index+1;i7<messages.length;i7++)trailingTokens+=estimateMessageTokens(messages[i7]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let available=model.contextWindow-estimateContextTokens(context).tokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetryContext:options?.telemetryContext,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)";function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId2){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return block.redacted?isSameModel?block:[]:isSameModel&&block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:isSameModel?block:{type:"text",text:block.thinking};if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId2){let normalizedId=normalizeToolCallId2(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i7=0;i7<transformed.length;i7++){let msg=transformed[i7];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b7=>b7.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}var EMPTY_TEXT_PLACEHOLDER="<empty>",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",REDACTED_THINKING_PLACEHOLDER="[Reasoning redacted]",stream=(model,context,options={})=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"bedrock-converse-stream",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},blocks=output.content,optionsProfile=options.profile||options.env?.AWS_PROFILE,config={profile:optionsProfile||getProviderEnvValue("AWS_PROFILE",options.env)},configuredRegion=getConfiguredBedrockRegion(options),hasAmbientConfiguredProfile=!!getProviderEnvValue("AWS_PROFILE"),endpointRegion=getStandardBedrockEndpointRegion(model.baseUrl),useExplicitEndpoint=shouldUseExplicitBedrockEndpoint(model.baseUrl,configuredRegion,hasAmbientConfiguredProfile);useExplicitEndpoint&&(config.endpoint=model.baseUrl);let skipAuth=getProviderEnvValue("AWS_BEDROCK_SKIP_AUTH",options.env)==="1",bearerToken=options.bearerToken||options.apiKey||getProviderEnvValue("AWS_BEARER_TOKEN_BEDROCK",options.env)||void 0,useBearerToken=bearerToken!==void 0&&!skipAuth;if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){let arnRegionMatch=model.id.match(/^arn:aws(?:-[a-z0-9-]+)?:bedrock:([a-z0-9-]+):/);arnRegionMatch?config.region=arnRegionMatch[1]:configuredRegion?config.region=configuredRegion:endpointRegion&&useExplicitEndpoint?config.region=endpointRegion:hasAmbientConfiguredProfile||(config.region="us-east-1"),skipAuth&&(config.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"});let credentials=getConfiguredBedrockCredentials(options.env);!skipAuth&&credentials&&!optionsProfile&&(config.credentials=credentials);let proxyUrl=resolveHttpProxyUrlForTarget(model.baseUrl,options.env);proxyUrl?config.requestHandler=new import_node_http_handler7.NodeHttpHandler({httpAgent:new HttpProxyAgent(proxyUrl),httpsAgent:new HttpsProxyAgent(proxyUrl)}):getProviderEnvValue("AWS_BEDROCK_FORCE_HTTP1",options.env)==="1"&&(config.requestHandler=new import_node_http_handler7.NodeHttpHandler)}else config.region=configuredRegion||(endpointRegion&&useExplicitEndpoint?endpointRegion:void 0)||"us-east-1";useBearerToken&&(config.token={token:bearerToken},config.authSchemePreference=["httpBearerAuth"]);let responseRequestId;try{let supportsStrictMode=model.compat?.supportsStrictMode??!1,client=new import_client_bedrock_runtime.BedrockRuntimeClient(config),observedRawResponse=!1;options.onResponse&&addResponseHeadersMiddleware(client,options.onResponse,model,()=>{observedRawResponse=!0});let customHeaders=providerHeadersToRecord(options.headers);customHeaders&&addCustomHeadersMiddleware(client,customHeaders);let cacheRetention=resolveCacheRetention(options.cacheRetention,options.env),inferenceMaxTokens=options.maxTokens??(isAnthropicClaudeModel(model)?model.maxTokens:void 0),initialSystemMessage=getInitialSystemMessage(normalizedContext.messages),initialSystemPrompt=initialSystemMessage?getSystemMessageText(initialSystemMessage):void 0,commandInput={modelId:model.id,messages:convertMessages(normalizedContext,model,cacheRetention,options.env),system:buildSystemPrompt(initialSystemPrompt,model,cacheRetention,options.env),inferenceConfig:{...inferenceMaxTokens!==void 0&&{maxTokens:inferenceMaxTokens},...options.temperature!==void 0&&{temperature:options.temperature}},toolConfig:convertToolConfig(getCurrentTools(normalizedContext.messages),options.toolChoice,supportsStrictMode),additionalModelRequestFields:buildAdditionalModelRequestFields(model,options),...options.requestMetadata!==void 0&&{requestMetadata:options.requestMetadata}},nextCommandInput=await options?.onPayload?.(commandInput,model);nextCommandInput!==void 0&&(commandInput=nextCommandInput);let command7=new import_client_bedrock_runtime.ConverseStreamCommand(commandInput),response=await client.send(command7,{abortSignal:options.signal});if(responseRequestId=normalizeDiagnosticValue(response.$metadata.requestId),!observedRawResponse&&response.$metadata.httpStatusCode!==void 0){let responseHeaders={};response.$metadata.requestId&&(responseHeaders["x-amzn-requestid"]=response.$metadata.requestId),await options?.onResponse?.({status:response.$metadata.httpStatusCode,headers:responseHeaders},model)}for await(let item of response.stream)if(await options.onProviderStreamEvent?.(item,model),item.messageStart){if(item.messageStart.role!==import_client_bedrock_runtime.ConversationRole.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");stream2.push({type:"start",partial:output})}else if(item.contentBlockStart)handleContentBlockStart(item.contentBlockStart,blocks,output,stream2);else if(item.contentBlockDelta)handleContentBlockDelta(item.contentBlockDelta,blocks,output,stream2);else if(item.contentBlockStop)handleContentBlockStop(item.contentBlockStop,blocks,output,stream2);else if(item.messageStop){output.rawStopReason=item.messageStop.stopReason;let{stopReason,errorMessage}=mapStopReason(item.messageStop.stopReason);output.stopReason=stopReason,errorMessage&&(output.errorMessage=errorMessage)}else if(item.metadata)handleMetadata(item.metadata,model,output);else{if(item.internalServerException)throw item.internalServerException;if(item.modelStreamErrorException)throw item.modelStreamErrorException;if(item.validationException)throw item.validationException;if(item.throttlingException)throw item.throttlingException;if(item.serviceUnavailableException)throw item.serviceUnavailableException}if(options.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Bedrock stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred");for(let block of output.content)finalizeStreamingBlock(block);stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error2){for(let block of output.content)finalizeStreamingBlock(block);output.stopReason=options.signal?.aborted?"aborted":"error",output.errorMessage=formatBedrockError(error2),output.stopReason==="error"&&appendBedrockFailureDiagnostic(output,error2,responseRequestId),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},BEDROCK_ERROR_PREFIXES={InternalServerException:"Internal server error",ModelStreamErrorException:"Model stream error",ValidationException:"Validation error",ThrottlingException:"Throttling error",ServiceUnavailableException:"Service unavailable"},BEDROCK_DATA_RETENTION_DOCS_URL="https://docs.aws.amazon.com/bedrock/latest/userguide/data-retention.html";function formatBedrockError(error2){let norm=normalizeProviderError(error2),core=!norm.messageCarriesBody&&norm.status!==void 0&&norm.body!==void 0?`${norm.status}: ${norm.body}`:norm.message,dataRetentionHint=/data retention mode/i.test(core)?` See ${BEDROCK_DATA_RETENTION_DOCS_URL} for supported data retention modes.`:"";return error2 instanceof import_client_bedrock_runtime.BedrockRuntimeServiceException?`${BEDROCK_ERROR_PREFIXES[error2.name]??error2.name}: ${core}${dataRetentionHint}`:`${core}${dataRetentionHint}`}var MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS=200;function normalizeDiagnosticValue(value){if(typeof value!="string")return;let trimmed=value.trim();if(!(trimmed.length===0||trimmed.length>MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS))return trimmed}function extractBedrockErrorCode(error2){if(!(!(error2 instanceof Error)||!error2.name.endsWith("Exception")))return normalizeDiagnosticValue(error2.name)}function appendBedrockFailureDiagnostic(output,error2,fallbackRequestId){let metadata=error2?.$metadata,details={};typeof metadata?.httpStatusCode=="number"&&(details.status=metadata.httpStatusCode);let errorCode=extractBedrockErrorCode(error2);errorCode!==void 0&&(details.errorCode=errorCode);let requestId=normalizeDiagnosticValue(metadata?.requestId)??fallbackRequestId;requestId!==void 0&&(details.requestId=requestId),Object.keys(details).length!==0&&appendAssistantMessageDiagnostic(output,{type:"bedrock_response_failure",timestamp:Date.now(),details})}var RESERVED_HEADER_EXACT=new Set(["authorization","host"]);function isReservedHeader(key){let lower=key.toLowerCase();return lower.startsWith("x-amz-")||RESERVED_HEADER_EXACT.has(lower)}function addCustomHeadersMiddleware(client,headers){let middleware=next=>async args=>{let request=args.request;if(request&&typeof request=="object"&&"headers"in request){let requestHeaders=request.headers;for(let[key,value]of Object.entries(headers))isReservedHeader(key)||(requestHeaders[key]=value)}return next(args)};client.middlewareStack.add(middleware,{step:"build",name:"pi-ai-custom-headers",priority:"low"})}function isSmithyHttpResponse(response){if(!response||typeof response!="object")return!1;let candidate=response;return typeof candidate.statusCode=="number"&&!!candidate.headers&&typeof candidate.headers=="object"}function toProviderResponse(response){if(isSmithyHttpResponse(response))return{status:response.statusCode,headers:{...response.headers}}}function addResponseHeadersMiddleware(client,onResponse,model,onObserved){let middleware=next=>async args=>{let result=await next(args),providerResponse=toProviderResponse(result.response);return providerResponse&&(onObserved(),await onResponse(providerResponse,model)),result};client.middlewareStack.add(middleware,{step:"deserialize",name:"pi-ai-response-headers"})}var streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,reasoning:void 0});if(isAnthropicClaudeModel(model)){if(supportsAdaptiveThinking(model.id,model.name))return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets});let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,reasoning:options.reasoning,thinkingBudgets:{...options.thinkingBudgets||{},[clampReasoning(options.reasoning)]:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))}})}return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets})};function handleContentBlockStart(event,blocks,output,stream2){let index=event.contentBlockIndex,start=event.start;if(start?.toolUse){let block={type:"toolCall",id:start.toolUse.toolUseId||"",name:start.toolUse.name||"",arguments:{},partialJson:"",index};output.content.push(block),stream2.push({type:"toolcall_start",contentIndex:blocks.length-1,partial:output})}}function handleContentBlockDelta(event,blocks,output,stream2){let contentBlockIndex=event.contentBlockIndex,delta=event.delta,index=blocks.findIndex(b7=>b7.index===contentBlockIndex),block=blocks[index];if(delta?.text!==void 0){if(!block){let newBlock={type:"text",text:"",index:contentBlockIndex};output.content.push(newBlock),index=blocks.length-1,block=blocks[index],stream2.push({type:"text_start",contentIndex:index,partial:output})}block.type==="text"&&(block.text+=delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:delta.text,partial:output}))}else if(delta?.toolUse&&block?.type==="toolCall")block.partialJson=(block.partialJson||"")+(delta.toolUse.input||""),block.arguments=parseStreamingJson(block.partialJson),stream2.push({type:"toolcall_delta",contentIndex:index,delta:delta.toolUse.input||"",partial:output});else if(delta?.reasoningContent){let thinkingBlock=block,thinkingIndex=index;if(!thinkingBlock){let newBlock={type:"thinking",thinking:"",thinkingSignature:"",index:contentBlockIndex};output.content.push(newBlock),thinkingIndex=blocks.length-1,thinkingBlock=blocks[thinkingIndex],stream2.push({type:"thinking_start",contentIndex:thinkingIndex,partial:output})}thinkingBlock?.type==="thinking"&&(delta.reasoningContent.text&&(thinkingBlock.thinking+=delta.reasoningContent.text,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:delta.reasoningContent.text,partial:output})),delta.reasoningContent.signature&&!thinkingBlock.redacted&&(thinkingBlock.thinkingSignature=(thinkingBlock.thinkingSignature||"")+delta.reasoningContent.signature),delta.reasoningContent.redactedContent?.length&&(thinkingBlock.redacted||(thinkingBlock.redacted=!0,thinkingBlock.thinkingSignature="",thinkingBlock.thinking+=REDACTED_THINKING_PLACEHOLDER,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:REDACTED_THINKING_PLACEHOLDER,partial:output})),thinkingBlock.redactedChunks??=[],thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent)))}}function flushRedactedContent(block){block.type!=="thinking"||!block.redactedChunks||(block.thinkingSignature=bytesToBase64(block.redactedChunks),delete block.redactedChunks)}function finalizeStreamingBlock(block){delete block.index,delete block.partialJson,flushRedactedContent(block)}function handleMetadata(event,model,output){event.usage&&(output.usage.input=event.usage.inputTokens||0,output.usage.output=event.usage.outputTokens||0,output.usage.cacheRead=event.usage.cacheReadInputTokens||0,output.usage.cacheWrite=event.usage.cacheWriteInputTokens||0,output.usage.cacheWrite1h=event.usage.cacheDetails?.reduce((total,detail)=>total+(detail.ttl===import_client_bedrock_runtime.CacheTTL.ONE_HOUR?detail.inputTokens??0:0),0),output.usage.totalTokens=event.usage.totalTokens||output.usage.input+output.usage.output,calculateCost(model,output.usage))}function handleContentBlockStop(event,blocks,output,stream2){let index=blocks.findIndex(b7=>b7.index===event.contentBlockIndex),block=blocks[index];if(block)switch(delete block.index,block.type){case"text":stream2.push({type:"text_end",contentIndex:index,content:block.text,partial:output});break;case"thinking":flushRedactedContent(block),stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output});break;case"toolCall":block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output});break}}function getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(value=>{let lower=value.toLowerCase();return[lower,lower.replace(/[\s_.:]+/g,"-")]})}function supportsAdaptiveThinking(modelId,modelName){return getModelMatchCandidates(modelId,modelName).some(s2=>s2.includes("opus-4-6")||s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-4-6")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsThinkingBlockBinding(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function mapThinkingLevelToEffort(model,level){if(level==="xhigh"&&supportsNativeXhighEffort(model))return"xhigh";let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}function resolveCacheRetention(cacheRetention,env9){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env9)==="long"?"long":"short")}function isAnthropicClaudeModel(model){let id=model.id.toLowerCase(),name=model.name?.toLowerCase()??"";return id.includes("anthropic.claude")||id.includes("anthropic/claude")||name.includes("anthropic.claude")||name.includes("anthropic/claude")||name.includes("claude")}function supportsPromptCaching(model,env9){let candidates=getModelMatchCandidates(model.id,model.name);return candidates.some(s2=>s2.includes("claude"))?!!(candidates.some(s2=>s2.includes("fable-5")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5"))||candidates.some(s2=>s2.includes("-4-"))||candidates.some(s2=>s2.includes("claude-3-7-sonnet"))||candidates.some(s2=>s2.includes("claude-3-5-haiku"))):getProviderEnvValue("AWS_BEDROCK_FORCE_CACHE",env9)==="1"}function supportsThinkingSignature(model){return isAnthropicClaudeModel(model)}function buildSystemPrompt(systemPrompt,model,cacheRetention,env9){if(!systemPrompt)return;let blocks=[{text:sanitizeSurrogates(systemPrompt)}];return cacheRetention!=="none"&&supportsPromptCaching(model,env9)&&blocks.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}}),blocks}function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");return sanitized.length>64?sanitized.slice(0,64):sanitized}function createNonBlankTextBlock(text){let sanitized=sanitizeSurrogates(text);return sanitized.trim().length===0?void 0:{text:sanitized}}function createRequiredTextBlock(text){return createNonBlankTextBlock(text)??{text:EMPTY_TEXT_PLACEHOLDER}}function sanitizeBedrockDocument(value){return Array.isArray(value)?value.map(sanitizeBedrockDocument):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).filter(([key])=>key.length>0).map(([key,nestedValue])=>[key,sanitizeBedrockDocument(nestedValue)])):value}function convertToolResultContent(content){let result=[];for(let c7 of content)if(c7.type==="image")result.push({image:createImageBlock(c7.mimeType,c7.data)});else{let textBlock=createNonBlankTextBlock(c7.text);textBlock&&result.push(textBlock)}return result.length===0&&result.push({text:EMPTY_TEXT_PLACEHOLDER}),result}function convertMessages(context,model,cacheRetention,env9){let result=[],transformedMessages=transformMessages(withoutInitialSystemMessage(context.messages),model,normalizeToolCallId);for(let i7=0;i7<transformedMessages.length;i7++){let m4=transformedMessages[i7];switch(m4.role){case"user":{let content=[];if(typeof m4.content=="string")content.push(createRequiredTextBlock(m4.content));else{for(let c7 of m4.content)switch(c7.type){case"text":{let textBlock=createNonBlankTextBlock(c7.text);textBlock&&content.push(textBlock);break}case"image":content.push({image:createImageBlock(c7.mimeType,c7.data)});break;default:continue}content.length===0&&content.push({text:EMPTY_TEXT_PLACEHOLDER})}result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content});break}case"assistant":{if(m4.content.length===0)continue;let contentBlocks=[];for(let c7 of m4.content)switch(c7.type){case"text":{let textBlock=createNonBlankTextBlock(c7.text);if(!textBlock)continue;contentBlocks.push(textBlock);break}case"toolCall":contentBlocks.push({toolUse:{toolUseId:c7.id,name:c7.name,input:sanitizeBedrockDocument(c7.arguments)}});break;case"thinking":{if(c7.redacted){let redactedContent=decodeRedactedContent(c7.thinkingSignature);redactedContent?.length&&contentBlocks.push({reasoningContent:{redactedContent}});continue}let thinking=sanitizeSurrogates(c7.thinking);if(thinking.trim().length===0)continue;supportsThinkingSignature(model)?!c7.thinkingSignature||c7.thinkingSignature.trim().length===0?contentBlocks.push({text:thinking}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking,signature:c7.thinkingSignature}}}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking}}});break}default:continue}if(contentBlocks.length===0)continue;result.push({role:import_client_bedrock_runtime.ConversationRole.ASSISTANT,content:contentBlocks});break}case"toolResult":{let toolResults=[];toolResults.push({toolResult:{toolUseId:m4.toolCallId,content:convertToolResultContent(m4.content),status:m4.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}});let j7=i7+1;for(;j7<transformedMessages.length&&transformedMessages[j7].role==="toolResult";){let nextMsg=transformedMessages[j7];toolResults.push({toolResult:{toolUseId:nextMsg.toolCallId,content:convertToolResultContent(nextMsg.content),status:nextMsg.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}}),j7++}i7=j7-1,result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content:toolResults});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,env9)&&result.length>0){let lastMessage=result[result.length-1];lastMessage.role===import_client_bedrock_runtime.ConversationRole.USER&&lastMessage.content&&lastMessage.content.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}})}return result}function convertToolConfig(tools,toolChoice,supportsStrictMode){if(!tools?.length||toolChoice==="none")return;let bedrockTools=tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode);return{toolSpec:{name:tool.name,description:tool.description,inputSchema:{json:getJsonSchemaToolParameters(tool,strict)},...strict===!0?{strict:!0}:{}}}}),bedrockToolChoice;switch(toolChoice){case"auto":bedrockToolChoice={auto:{}};break;case"any":bedrockToolChoice={any:{}};break;default:toolChoice?.type==="tool"&&(bedrockToolChoice={tool:{name:toolChoice.name}})}return{tools:bedrockTools,toolChoice:bedrockToolChoice}}function mapStopReason(reason){switch(reason){case import_client_bedrock_runtime.StopReason.END_TURN:case import_client_bedrock_runtime.StopReason.STOP_SEQUENCE:return{stopReason:"stop"};case import_client_bedrock_runtime.StopReason.MAX_TOKENS:case import_client_bedrock_runtime.StopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:return{stopReason:"length"};case import_client_bedrock_runtime.StopReason.TOOL_USE:return{stopReason:"toolUse"};default:return reason?{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}:{stopReason:"error"}}}function getConfiguredBedrockRegion(options){return options.region||getProviderEnvValue("AWS_REGION",options.env)||getProviderEnvValue("AWS_DEFAULT_REGION",options.env)||void 0}function getConfiguredBedrockCredentials(env9){let accessKeyId=getProviderEnvValue("AWS_ACCESS_KEY_ID",env9),secretAccessKey=getProviderEnvValue("AWS_SECRET_ACCESS_KEY",env9);if(!accessKeyId||!secretAccessKey)return;let sessionToken=getProviderEnvValue("AWS_SESSION_TOKEN",env9);return{accessKeyId,secretAccessKey,...sessionToken?{sessionToken}:{}}}function getStandardBedrockEndpointRegion(baseUrl){if(baseUrl)try{let{hostname}=new URL(baseUrl);return hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/)?.[1]}catch{return}}function shouldUseExplicitBedrockEndpoint(baseUrl,configuredRegion,hasAmbientConfiguredProfile){return getStandardBedrockEndpointRegion(baseUrl)?!configuredRegion&&!hasAmbientConfiguredProfile:!0}function isGovCloudBedrockTarget(model,options){if(getConfiguredBedrockRegion(options)?.toLowerCase().startsWith("us-gov-"))return!0;let modelId=model.id.toLowerCase();return modelId.startsWith("us-gov.")||modelId.startsWith("arn:aws-us-gov:")}function buildAdditionalModelRequestFields(model,options){if(!options.reasoning||!model.reasoning)return;if(isAnthropicClaudeModel(model)){let isGovCloud=isGovCloudBedrockTarget(model,options),display=isGovCloud?void 0:options.thinkingDisplay??"summarized",useBlockBinding=!isGovCloud&&supportsThinkingBlockBinding(model),result=supportsAdaptiveThinking(model.id,model.name)?{thinking:{type:"adaptive",...display!==void 0?{display}:{},...useBlockBinding?{block_binding:{prefix_mismatch_behavior:"drop_block"}}:{}},output_config:{effort:mapThinkingLevelToEffort(model,options.reasoning)},...useBlockBinding?{anthropic_beta:[THINKING_BINDING_CONTROLS_BETA]}:{}}:(()=>{let defaultBudgets={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384,max:16384},level=options.reasoning==="xhigh"||options.reasoning==="max"?"high":options.reasoning;return{thinking:{type:"enabled",budget_tokens:options.thinkingBudgets?.[level]??defaultBudgets[options.reasoning],...display!==void 0?{display}:{}}}})();return!supportsAdaptiveThinking(model.id,model.name)&&(options.interleavedThinking??!0)&&(result.anthropic_beta=["interleaved-thinking-2025-05-14"]),result}let candidates=getModelMatchCandidates(model.id,model.name);if(candidates.some(s2=>s2.includes("gpt-oss")))return{reasoning_effort:OPENAI_GPT_OSS_EFFORT[options.reasoning]};if(candidates.some(s2=>s2.includes("gpt-"))){let mapped=model.thinkingLevelMap?.[options.reasoning];return{reasoning:{effort:typeof mapped=="string"?mapped:OPENAI_GPT_EFFORT[options.reasoning]}}}}var OPENAI_GPT_EFFORT={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},OPENAI_GPT_OSS_EFFORT={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"};function createImageBlock(mimeType,data){let format2;switch(mimeType){case"image/jpeg":case"image/jpg":format2=import_client_bedrock_runtime.ImageFormat.JPEG;break;case"image/png":format2=import_client_bedrock_runtime.ImageFormat.PNG;break;case"image/gif":format2=import_client_bedrock_runtime.ImageFormat.GIF;break;case"image/webp":format2=import_client_bedrock_runtime.ImageFormat.WEBP;break;default:throw new Error(`Unknown image type: ${mimeType}`)}return{source:{bytes:base64ToBytes(data)},format:format2}}function base64ToBytes(data){let binaryString=atob(data),bytes=new Uint8Array(binaryString.length);for(let i7=0;i7<binaryString.length;i7++)bytes[i7]=binaryString.charCodeAt(i7);return bytes}function decodeRedactedContent(signature){if(signature)try{return base64ToBytes(signature)}catch{return}}function bytesToBase64(chunks){let binary="";for(let chunk of chunks)for(let i7=0;i7<chunk.length;i7+=32768)binary+=String.fromCharCode(...chunk.subarray(i7,i7+32768));return btoa(binary)}export{stream,streamSimple};
|
|
132
|
+
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i7=requestedIndex;i7<EXTENDED_THINKING_LEVELS.length;i7++){let candidate=EXTENDED_THINKING_LEVELS[i7];if(availableLevels.includes(candidate))return candidate}for(let i7=requestedIndex-1;i7>=0;i7--){let candidate=EXTENDED_THINKING_LEVELS[i7];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
133
|
+
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",inString=!1;for(let index=0;index<json.length;index++){let char=json[index];if(!inString){repaired+=char,char==='"'&&(inString=!0);continue}if(char==='"'){repaired+=char,inString=!1;continue}if(char==="\\"){let nextChar=json[index+1];if(nextChar===void 0){repaired+="\\\\";continue}if(nextChar==="u"){let unicodeDigits=json.slice(index+2,index+6);if(/^[0-9a-fA-F]{4}$/.test(unicodeDigits)){repaired+=`\\u${unicodeDigits}`,index+=5;continue}}if(VALID_JSON_ESCAPES.has(nextChar)){repaired+=`\\${nextChar}`,index+=1;continue}repaired+="\\\\";continue}repaired+=isControlCharacter(char)?escapeControlCharacter(char):char}return repaired}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseToolCallArguments(json){if(!json?.trim())return{arguments:{}};try{let parsed=parseJsonWithRepair(json);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Tool arguments must be a JSON object");return{arguments:parsed}}catch(error2){return{arguments:{},argumentsError:`${error2 instanceof Error?error2.message:String(error2)}
|
|
134
|
+
|
|
135
|
+
Received arguments:
|
|
136
|
+
${json}`}}}function parseStreamingJson(partialJson){if(!partialJson||partialJson.trim()==="")return{};try{return parseJsonWithRepair(partialJson)}catch{try{return(0,import_partial_json.parse)(partialJson)??{}}catch{try{return(0,import_partial_json.parse)(repairJson(partialJson))??{}}catch{return{}}}}}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env9){return env9?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env9){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env9?.[lowercaseKey]||env9?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env9){let noProxy=getProxyEnv("no_proxy",env9).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env9){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env9))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env9)||getProxyEnv("all_proxy",env9);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env9){let proxy=getProxyForUrl(targetUrl,env9);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error2){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error2 instanceof Error?error2.message:String(error2)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error2){if(!(error2 instanceof UnsupportedStrictJsonSchemaError))throw error2;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error2.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars2=0;for(let block of content)chars2+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars2}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars2=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars2+=block.text.length:block.type==="thinking"?chars2+=block.thinking.length:chars2+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars2/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i7=0;i7<messages.length;i7++){let message=messages[i7];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i7})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i7=usageInfo.index+1;i7<messages.length;i7++)trailingTokens+=estimateMessageTokens(messages[i7]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let available=model.contextWindow-estimateContextTokens(context).tokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId2){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId2){let normalizedId=normalizeToolCallId2(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i7=0;i7<transformed.length;i7++){let msg=transformed[i7];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b7=>b7.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}var EMPTY_TEXT_PLACEHOLDER="<empty>",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",REDACTED_THINKING_PLACEHOLDER="[Reasoning redacted]",stream=(model,context,options={})=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"bedrock-converse-stream",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},blocks=output.content,optionsProfile=options.profile||options.env?.AWS_PROFILE,config={profile:optionsProfile||getProviderEnvValue("AWS_PROFILE",options.env),customUserAgent:bedrockUserAgent(options.identity)},configuredRegion=getConfiguredBedrockRegion(options),hasAmbientConfiguredProfile=!!getProviderEnvValue("AWS_PROFILE"),endpointRegion=getStandardBedrockEndpointRegion(model.baseUrl),useExplicitEndpoint=shouldUseExplicitBedrockEndpoint(model.baseUrl,configuredRegion,hasAmbientConfiguredProfile);useExplicitEndpoint&&(config.endpoint=model.baseUrl);let skipAuth=getProviderEnvValue("AWS_BEDROCK_SKIP_AUTH",options.env)==="1",bearerToken=options.bearerToken||options.apiKey||getProviderEnvValue("AWS_BEARER_TOKEN_BEDROCK",options.env)||void 0,useBearerToken=bearerToken!==void 0&&!skipAuth;if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){let arnRegionMatch=model.id.match(/^arn:aws(?:-[a-z0-9-]+)?:bedrock:([a-z0-9-]+):/);arnRegionMatch?config.region=arnRegionMatch[1]:configuredRegion?config.region=configuredRegion:endpointRegion&&useExplicitEndpoint?config.region=endpointRegion:hasAmbientConfiguredProfile||(config.region="us-east-1"),skipAuth&&(config.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"});let credentials=getConfiguredBedrockCredentials(options.env);!skipAuth&&credentials&&!optionsProfile&&(config.credentials=credentials);let proxyUrl=resolveHttpProxyUrlForTarget(model.baseUrl,options.env);proxyUrl?config.requestHandler=new import_node_http_handler7.NodeHttpHandler({httpAgent:new HttpProxyAgent(proxyUrl),httpsAgent:new HttpsProxyAgent(proxyUrl)}):getProviderEnvValue("AWS_BEDROCK_FORCE_HTTP1",options.env)==="1"&&(config.requestHandler=new import_node_http_handler7.NodeHttpHandler)}else config.region=configuredRegion||(endpointRegion&&useExplicitEndpoint?endpointRegion:void 0)||"us-east-1";useBearerToken&&(config.token={token:bearerToken},config.authSchemePreference=["httpBearerAuth"]);let responseRequestId;try{let supportsStrictMode=model.compat?.supportsStrictMode??!1,client=new import_client_bedrock_runtime.BedrockRuntimeClient(config),observedRawResponse=!1;options.onResponse&&addResponseHeadersMiddleware(client,options.onResponse,model,()=>{observedRawResponse=!0});let customHeaders=providerHeadersToRecord(options.headers);customHeaders&&addCustomHeadersMiddleware(client,customHeaders);let cacheRetention=resolveCacheRetention(options.cacheRetention,options.env),inferenceMaxTokens=options.maxTokens??(isAnthropicClaudeModel(model)?model.maxTokens:void 0),initialSystemMessage=getInitialSystemMessage(normalizedContext.messages),initialSystemPrompt=initialSystemMessage?getSystemMessageText(initialSystemMessage):void 0,commandInput={modelId:model.id,messages:convertMessages(normalizedContext,model,cacheRetention,options.env),system:buildSystemPrompt(initialSystemPrompt,model,cacheRetention,options.env),inferenceConfig:{...inferenceMaxTokens!==void 0&&{maxTokens:inferenceMaxTokens},...options.temperature!==void 0&&{temperature:options.temperature}},toolConfig:convertToolConfig(getCurrentTools(normalizedContext.messages),options.toolChoice,supportsStrictMode),additionalModelRequestFields:buildAdditionalModelRequestFields(model,options),...options.requestMetadata!==void 0&&{requestMetadata:options.requestMetadata}},nextCommandInput=await options?.onPayload?.(commandInput,model);nextCommandInput!==void 0&&(commandInput=nextCommandInput);let command7=new import_client_bedrock_runtime.ConverseStreamCommand(commandInput),response=await client.send(command7,{abortSignal:options.signal});if(responseRequestId=normalizeDiagnosticValue(response.$metadata.requestId),!observedRawResponse&&response.$metadata.httpStatusCode!==void 0){let responseHeaders={};response.$metadata.requestId&&(responseHeaders["x-amzn-requestid"]=response.$metadata.requestId),await options?.onResponse?.({status:response.$metadata.httpStatusCode,headers:responseHeaders},model)}for await(let item of response.stream)if(await options.onProviderStreamEvent?.(item,model),item.messageStart){if(item.messageStart.role!==import_client_bedrock_runtime.ConversationRole.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");stream2.push({type:"start",partial:output})}else if(item.contentBlockStart)handleContentBlockStart(item.contentBlockStart,blocks,output,stream2);else if(item.contentBlockDelta)handleContentBlockDelta(item.contentBlockDelta,blocks,output,stream2);else if(item.contentBlockStop)handleContentBlockStop(item.contentBlockStop,blocks,output,stream2);else if(item.messageStop){output.rawStopReason=item.messageStop.stopReason;let{stopReason,errorMessage}=mapStopReason(item.messageStop.stopReason);output.stopReason=stopReason,errorMessage&&(output.errorMessage=errorMessage)}else if(item.metadata)handleMetadata(item.metadata,model,output);else{if(item.internalServerException)throw item.internalServerException;if(item.modelStreamErrorException)throw item.modelStreamErrorException;if(item.validationException)throw item.validationException;if(item.throttlingException)throw item.throttlingException;if(item.serviceUnavailableException)throw item.serviceUnavailableException}if(options.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Bedrock stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred");for(let block of output.content)finalizeStreamingBlock(block);stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error2){for(let block of output.content)finalizeStreamingBlock(block);output.stopReason=options.signal?.aborted?"aborted":"error",output.errorMessage=formatBedrockError(error2),output.stopReason==="error"&&appendBedrockFailureDiagnostic(output,error2,responseRequestId),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},BEDROCK_ERROR_PREFIXES={InternalServerException:"Internal server error",ModelStreamErrorException:"Model stream error",ValidationException:"Validation error",ThrottlingException:"Throttling error",ServiceUnavailableException:"Service unavailable"},BEDROCK_DATA_RETENTION_DOCS_URL="https://docs.aws.amazon.com/bedrock/latest/userguide/data-retention.html";function formatBedrockError(error2){let norm=normalizeProviderError(error2),core=!norm.messageCarriesBody&&norm.status!==void 0&&norm.body!==void 0?`${norm.status}: ${norm.body}`:norm.message,dataRetentionHint=/data retention mode/i.test(core)?` See ${BEDROCK_DATA_RETENTION_DOCS_URL} for supported data retention modes.`:"";return error2 instanceof import_client_bedrock_runtime.BedrockRuntimeServiceException?`${BEDROCK_ERROR_PREFIXES[error2.name]??error2.name}: ${core}${dataRetentionHint}`:`${core}${dataRetentionHint}`}var MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS=200;function normalizeDiagnosticValue(value){if(typeof value!="string")return;let trimmed=value.trim();if(!(trimmed.length===0||trimmed.length>MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS))return trimmed}function extractBedrockErrorCode(error2){if(!(!(error2 instanceof Error)||!error2.name.endsWith("Exception")))return normalizeDiagnosticValue(error2.name)}function appendBedrockFailureDiagnostic(output,error2,fallbackRequestId){let metadata=error2?.$metadata,details={};typeof metadata?.httpStatusCode=="number"&&(details.status=metadata.httpStatusCode);let errorCode=extractBedrockErrorCode(error2);errorCode!==void 0&&(details.errorCode=errorCode);let requestId=normalizeDiagnosticValue(metadata?.requestId)??fallbackRequestId;requestId!==void 0&&(details.requestId=requestId),Object.keys(details).length!==0&&appendAssistantMessageDiagnostic(output,{type:"bedrock_response_failure",timestamp:Date.now(),details})}var RESERVED_HEADER_EXACT=new Set(["authorization","host"]);function isReservedHeader(key){let lower=key.toLowerCase();return lower.startsWith("x-amz-")||RESERVED_HEADER_EXACT.has(lower)}function bedrockUserAgent(identity){let mode=identity?.userAgent??"detailed";return typeof mode=="object"?mode.custom:mode==="short"?[["pi"]]:[["pi",getClientVersion(identity)]]}function addCustomHeadersMiddleware(client,headers){let middleware=next=>async args=>{let request=args.request;if(request&&typeof request=="object"&&"headers"in request){let requestHeaders=request.headers;for(let[key,value]of Object.entries(headers))isReservedHeader(key)||(requestHeaders[key]=value)}return next(args)};client.middlewareStack.add(middleware,{step:"build",name:"pi-ai-custom-headers",priority:"low"})}function isSmithyHttpResponse(response){if(!response||typeof response!="object")return!1;let candidate=response;return typeof candidate.statusCode=="number"&&!!candidate.headers&&typeof candidate.headers=="object"}function toProviderResponse(response){if(isSmithyHttpResponse(response))return{status:response.statusCode,headers:{...response.headers}}}function addResponseHeadersMiddleware(client,onResponse,model,onObserved){let middleware=next=>async args=>{let result=await next(args),providerResponse=toProviderResponse(result.response);return providerResponse&&(onObserved(),await onResponse(providerResponse,model)),result};client.middlewareStack.add(middleware,{step:"deserialize",name:"pi-ai-response-headers"})}var streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,reasoning:void 0});if(isAnthropicClaudeModel(model)){if(supportsAdaptiveThinking(model.id,model.name))return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets});let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,reasoning:options.reasoning,thinkingBudgets:{...options.thinkingBudgets||{},[clampReasoning(options.reasoning)]:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))}})}return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets})};function handleContentBlockStart(event,blocks,output,stream2){let index=event.contentBlockIndex,start=event.start;if(start?.toolUse){let block={type:"toolCall",id:start.toolUse.toolUseId||"",name:start.toolUse.name||"",arguments:{},partialJson:"",index};output.content.push(block),stream2.push({type:"toolcall_start",contentIndex:blocks.length-1,partial:output})}}function handleContentBlockDelta(event,blocks,output,stream2){let contentBlockIndex=event.contentBlockIndex,delta=event.delta,index=blocks.findIndex(b7=>b7.index===contentBlockIndex),block=blocks[index];if(delta?.text!==void 0){if(!block){let newBlock={type:"text",text:"",index:contentBlockIndex};output.content.push(newBlock),index=blocks.length-1,block=blocks[index],stream2.push({type:"text_start",contentIndex:index,partial:output})}block.type==="text"&&(block.text+=delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:delta.text,partial:output}))}else if(delta?.toolUse&&block?.type==="toolCall")block.partialJson=(block.partialJson||"")+(delta.toolUse.input||""),block.arguments=parseStreamingJson(block.partialJson),stream2.push({type:"toolcall_delta",contentIndex:index,delta:delta.toolUse.input||"",partial:output});else if(delta?.reasoningContent){let thinkingBlock=block,thinkingIndex=index;if(!thinkingBlock){let newBlock={type:"thinking",thinking:"",thinkingSignature:"",index:contentBlockIndex};output.content.push(newBlock),thinkingIndex=blocks.length-1,thinkingBlock=blocks[thinkingIndex],stream2.push({type:"thinking_start",contentIndex:thinkingIndex,partial:output})}thinkingBlock?.type==="thinking"&&(delta.reasoningContent.text&&(thinkingBlock.thinking+=delta.reasoningContent.text,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:delta.reasoningContent.text,partial:output})),delta.reasoningContent.signature&&!thinkingBlock.redacted&&(thinkingBlock.thinkingSignature=(thinkingBlock.thinkingSignature||"")+delta.reasoningContent.signature),delta.reasoningContent.redactedContent?.length&&(thinkingBlock.redacted||(thinkingBlock.redacted=!0,thinkingBlock.thinkingSignature="",thinkingBlock.thinking+=REDACTED_THINKING_PLACEHOLDER,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:REDACTED_THINKING_PLACEHOLDER,partial:output})),thinkingBlock.redactedChunks??=[],thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent)))}}function flushRedactedContent(block){block.type!=="thinking"||!block.redactedChunks||(block.thinkingSignature=bytesToBase64(block.redactedChunks),delete block.redactedChunks)}function finalizeStreamingBlock(block){delete block.index,delete block.partialJson,flushRedactedContent(block)}function handleMetadata(event,model,output){event.usage&&(output.usage.input=event.usage.inputTokens||0,output.usage.output=event.usage.outputTokens||0,output.usage.cacheRead=event.usage.cacheReadInputTokens||0,output.usage.cacheWrite=event.usage.cacheWriteInputTokens||0,output.usage.cacheWrite1h=event.usage.cacheDetails?.reduce((total,detail)=>total+(detail.ttl===import_client_bedrock_runtime.CacheTTL.ONE_HOUR?detail.inputTokens??0:0),0),output.usage.totalTokens=event.usage.totalTokens||output.usage.input+output.usage.output,calculateCost(model,output.usage))}function handleContentBlockStop(event,blocks,output,stream2){let index=blocks.findIndex(b7=>b7.index===event.contentBlockIndex),block=blocks[index];if(block)switch(delete block.index,block.type){case"text":stream2.push({type:"text_end",contentIndex:index,content:block.text,partial:output});break;case"thinking":flushRedactedContent(block),stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output});break;case"toolCall":Object.assign(block,parseToolCallArguments(block.partialJson)),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output});break}}function getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(value=>{let lower=value.toLowerCase();return[lower,lower.replace(/[\s_.:]+/g,"-")]})}function supportsAdaptiveThinking(modelId,modelName){return getModelMatchCandidates(modelId,modelName).some(s2=>s2.includes("opus-4-6")||s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-4-6")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsThinkingBlockBinding(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function mapThinkingLevelToEffort(model,level){if(level==="xhigh"&&supportsNativeXhighEffort(model))return"xhigh";let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}function resolveCacheRetention(cacheRetention,env9){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env9)==="long"?"long":"short")}function isAnthropicClaudeModel(model){let id=model.id.toLowerCase(),name=model.name?.toLowerCase()??"";return id.includes("anthropic.claude")||id.includes("anthropic/claude")||name.includes("anthropic.claude")||name.includes("anthropic/claude")||name.includes("claude")}function supportsPromptCaching(model,env9){let candidates=getModelMatchCandidates(model.id,model.name);return candidates.some(s2=>s2.includes("claude"))?!!(candidates.some(s2=>s2.includes("fable-5")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5"))||candidates.some(s2=>s2.includes("-4-"))||candidates.some(s2=>s2.includes("claude-3-7-sonnet"))||candidates.some(s2=>s2.includes("claude-3-5-haiku"))):getProviderEnvValue("AWS_BEDROCK_FORCE_CACHE",env9)==="1"}function supportsThinkingSignature(model){return isAnthropicClaudeModel(model)}function buildSystemPrompt(systemPrompt,model,cacheRetention,env9){if(!systemPrompt)return;let blocks=[{text:sanitizeSurrogates(systemPrompt)}];return cacheRetention!=="none"&&supportsPromptCaching(model,env9)&&blocks.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}}),blocks}function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");return sanitized.length>64?sanitized.slice(0,64):sanitized}function createNonBlankTextBlock(text){let sanitized=sanitizeSurrogates(text);return sanitized.trim().length===0?void 0:{text:sanitized}}function createRequiredTextBlock(text){return createNonBlankTextBlock(text)??{text:EMPTY_TEXT_PLACEHOLDER}}function sanitizeBedrockDocument(value){return Array.isArray(value)?value.map(sanitizeBedrockDocument):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).filter(([key])=>key.length>0).map(([key,nestedValue])=>[key,sanitizeBedrockDocument(nestedValue)])):value}function convertToolResultContent(content){let result=[];for(let c7 of content)if(c7.type==="image")result.push({image:createImageBlock(c7.mimeType,c7.data)});else{let textBlock=createNonBlankTextBlock(c7.text);textBlock&&result.push(textBlock)}return result.length===0&&result.push({text:EMPTY_TEXT_PLACEHOLDER}),result}function convertMessages(context,model,cacheRetention,env9){let result=[],transformedMessages=transformMessages(withoutInitialSystemMessage(context.messages),model,normalizeToolCallId);for(let i7=0;i7<transformedMessages.length;i7++){let m4=transformedMessages[i7];switch(m4.role){case"user":{let content=[];if(typeof m4.content=="string")content.push(createRequiredTextBlock(m4.content));else{for(let c7 of m4.content)switch(c7.type){case"text":{let textBlock=createNonBlankTextBlock(c7.text);textBlock&&content.push(textBlock);break}case"image":content.push({image:createImageBlock(c7.mimeType,c7.data)});break;default:continue}content.length===0&&content.push({text:EMPTY_TEXT_PLACEHOLDER})}result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content});break}case"assistant":{if(m4.content.length===0)continue;let contentBlocks=[];for(let c7 of m4.content)switch(c7.type){case"text":{let textBlock=createNonBlankTextBlock(c7.text);if(!textBlock)continue;contentBlocks.push(textBlock);break}case"toolCall":contentBlocks.push({toolUse:{toolUseId:c7.id,name:c7.name,input:sanitizeBedrockDocument(c7.arguments)}});break;case"thinking":{if(c7.redacted){let redactedContent=decodeRedactedContent(c7.thinkingSignature);redactedContent?.length&&contentBlocks.push({reasoningContent:{redactedContent}});continue}let thinking=sanitizeSurrogates(c7.thinking);if(thinking.trim().length===0)continue;supportsThinkingSignature(model)?!c7.thinkingSignature||c7.thinkingSignature.trim().length===0?contentBlocks.push({text:thinking}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking,signature:c7.thinkingSignature}}}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking}}});break}default:continue}if(contentBlocks.length===0)continue;result.push({role:import_client_bedrock_runtime.ConversationRole.ASSISTANT,content:contentBlocks});break}case"toolResult":{let toolResults=[],errorImages=[],j7=i7;for(;j7<transformedMessages.length&&transformedMessages[j7].role==="toolResult";){let toolMsg=transformedMessages[j7],split2=isAnthropicClaudeModel(model)?splitErrorToolResultImages(toolMsg):void 0;toolResults.push({toolResult:{toolUseId:toolMsg.toolCallId,content:convertToolResultContent(split2?.content??toolMsg.content),status:toolMsg.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}}),split2&&errorImages.push({text:split2.caption},...split2.images.map(image=>({image:createImageBlock(image.mimeType,image.data)}))),j7++}i7=j7-1,result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content:[...toolResults,...errorImages]});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,env9)&&result.length>0){let lastMessage=result[result.length-1];lastMessage.role===import_client_bedrock_runtime.ConversationRole.USER&&lastMessage.content&&lastMessage.content.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}})}return result}function convertToolConfig(tools,toolChoice,supportsStrictMode){if(!tools?.length||toolChoice==="none")return;let bedrockTools=tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode);return{toolSpec:{name:tool.name,description:tool.description,inputSchema:{json:getJsonSchemaToolParameters(tool,strict)},...strict===!0?{strict:!0}:{}}}}),bedrockToolChoice;switch(toolChoice){case"auto":bedrockToolChoice={auto:{}};break;case"any":bedrockToolChoice={any:{}};break;default:toolChoice?.type==="tool"&&(bedrockToolChoice={tool:{name:toolChoice.name}})}return{tools:bedrockTools,toolChoice:bedrockToolChoice}}function mapStopReason(reason){switch(reason){case import_client_bedrock_runtime.StopReason.END_TURN:case import_client_bedrock_runtime.StopReason.STOP_SEQUENCE:return{stopReason:"stop"};case import_client_bedrock_runtime.StopReason.MAX_TOKENS:case import_client_bedrock_runtime.StopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:return{stopReason:"length"};case import_client_bedrock_runtime.StopReason.TOOL_USE:return{stopReason:"toolUse"};default:return reason?{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}:{stopReason:"error"}}}function getConfiguredBedrockRegion(options){return options.region||getProviderEnvValue("AWS_REGION",options.env)||getProviderEnvValue("AWS_DEFAULT_REGION",options.env)||void 0}function getConfiguredBedrockCredentials(env9){let accessKeyId=getProviderEnvValue("AWS_ACCESS_KEY_ID",env9),secretAccessKey=getProviderEnvValue("AWS_SECRET_ACCESS_KEY",env9);if(!accessKeyId||!secretAccessKey)return;let sessionToken=getProviderEnvValue("AWS_SESSION_TOKEN",env9);return{accessKeyId,secretAccessKey,...sessionToken?{sessionToken}:{}}}function getStandardBedrockEndpointRegion(baseUrl){if(baseUrl)try{let{hostname}=new URL(baseUrl);return hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/)?.[1]}catch{return}}function shouldUseExplicitBedrockEndpoint(baseUrl,configuredRegion,hasAmbientConfiguredProfile){return getStandardBedrockEndpointRegion(baseUrl)?!configuredRegion&&!hasAmbientConfiguredProfile:!0}function isGovCloudBedrockTarget(model,options){if(getConfiguredBedrockRegion(options)?.toLowerCase().startsWith("us-gov-"))return!0;let modelId=model.id.toLowerCase();return modelId.startsWith("us-gov.")||modelId.startsWith("arn:aws-us-gov:")}function buildAdditionalModelRequestFields(model,options){if(!options.reasoning||!model.reasoning)return;if(isAnthropicClaudeModel(model)){let isGovCloud=isGovCloudBedrockTarget(model,options),display=isGovCloud?void 0:options.thinkingDisplay??"summarized",useBlockBinding=!isGovCloud&&supportsThinkingBlockBinding(model),result=supportsAdaptiveThinking(model.id,model.name)?{thinking:{type:"adaptive",...display!==void 0?{display}:{},...useBlockBinding?{block_binding:{prefix_mismatch_behavior:"drop_block"}}:{}},output_config:{effort:mapThinkingLevelToEffort(model,options.reasoning)},...useBlockBinding?{anthropic_beta:[THINKING_BINDING_CONTROLS_BETA]}:{}}:(()=>{let defaultBudgets={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384,max:16384},level=options.reasoning==="xhigh"||options.reasoning==="max"?"high":options.reasoning;return{thinking:{type:"enabled",budget_tokens:options.thinkingBudgets?.[level]??defaultBudgets[options.reasoning],...display!==void 0?{display}:{}}}})();return!supportsAdaptiveThinking(model.id,model.name)&&(options.interleavedThinking??!0)&&(result.anthropic_beta=["interleaved-thinking-2025-05-14"]),result}let candidates=getModelMatchCandidates(model.id,model.name);if(candidates.some(s2=>s2.includes("gpt-oss")))return{reasoning_effort:OPENAI_GPT_OSS_EFFORT[options.reasoning]};if(candidates.some(s2=>s2.includes("gpt-"))){let mapped=model.thinkingLevelMap?.[options.reasoning];return{reasoning:{effort:typeof mapped=="string"?mapped:OPENAI_GPT_EFFORT[options.reasoning]}}}}var OPENAI_GPT_EFFORT={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},OPENAI_GPT_OSS_EFFORT={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"};function createImageBlock(mimeType,data){let format2;switch(mimeType){case"image/jpeg":case"image/jpg":format2=import_client_bedrock_runtime.ImageFormat.JPEG;break;case"image/png":format2=import_client_bedrock_runtime.ImageFormat.PNG;break;case"image/gif":format2=import_client_bedrock_runtime.ImageFormat.GIF;break;case"image/webp":format2=import_client_bedrock_runtime.ImageFormat.WEBP;break;default:throw new Error(`Unknown image type: ${mimeType}`)}return{source:{bytes:base64ToBytes(data)},format:format2}}function base64ToBytes(data){let binaryString=atob(data),bytes=new Uint8Array(binaryString.length);for(let i7=0;i7<binaryString.length;i7++)bytes[i7]=binaryString.charCodeAt(i7);return bytes}function decodeRedactedContent(signature){if(signature)try{return base64ToBytes(signature)}catch{return}}function bytesToBase64(chunks){let binary="";for(let chunk of chunks)for(let i7=0;i7<chunk.length;i7+=32768)binary+=String.fromCharCode(...chunk.subarray(i7,i7+32768));return btoa(binary)}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __bkperCreateRequire } from "node:module"; const require = __bkperCreateRequire(import.meta.url);
|
|
2
|
-
var github_copilot_default={"anthropic-messages":{"chat:claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-5.5":{id:"claude-haiku-5.5",name:"Claude Haiku 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:1e5,input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-completions":{"chat:gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsMidConvoSystemMessages:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-responses":{"chat:gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},type:"chat"},"chat:mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};function flattenModelCatalog(groups,type){return Object.fromEntries(Object.values(groups).flatMap(models=>Object.values(models)).filter(model=>model.type===type).map(model=>[model.id,model]))}function flattenChatModelCatalog(_provider,groups){return flattenModelCatalog(groups,"chat")}function flattenImageModelCatalog(_provider,groups){return flattenModelCatalog(groups,"image")}function flattenClassifierModelCatalog(_provider,groups){return flattenModelCatalog(groups,"classifier")}var GITHUB_COPILOT_MODELS=flattenChatModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_IMAGE_MODELS=flattenImageModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_CLASSIFIER_MODELS=flattenClassifierModelCatalog("github-copilot",github_copilot_default);function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getBaseUrlFromToken(token){let match=token.match(/proxy-ep=([^;]+)/);return match?`https://${match[1].replace(/^proxy\./,"api.")}`:null}function getGitHubCopilotBaseUrl(token,enterpriseDomain){if(token){let urlFromToken=getBaseUrlFromToken(token);if(urlFromToken)return urlFromToken}return enterpriseDomain?`https://copilot-api.${enterpriseDomain}`:"https://api.individual.githubcopilot.com"}function asRecord(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord(item.capabilities);return asRecord(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord(item.policy)?.state}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id);return{availableModelIds,policyModelIds}}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain),allowPolicyFallback=baseUrl==="https://api.individual.githubcopilot.com",response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new Error(`${response.status} ${response.statusText}: ${text}`)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0});return{...credentials,availableModelIds}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3}),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])]}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential))}}};export{githubCopilotOAuth};
|
|
2
|
+
var github_copilot_default={"anthropic-messages":{"chat:claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-5.5":{id:"claude-haiku-5.5",name:"Claude Haiku 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:1e5,input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-completions":{"chat:gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-argon":{id:"gemini-4-argon",name:"Gemini 4 Argon",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsMidConvoSystemMessages:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-responses":{"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};function flattenModelCatalog(groups,type){return Object.fromEntries(Object.values(groups).flatMap(models=>Object.values(models)).filter(model=>model.type===type).map(model=>[model.id,model]))}function flattenChatModelCatalog(_provider,groups){return flattenModelCatalog(groups,"chat")}function flattenImageModelCatalog(_provider,groups){return flattenModelCatalog(groups,"image")}function flattenClassifierModelCatalog(_provider,groups){return flattenModelCatalog(groups,"classifier")}var GITHUB_COPILOT_MODELS=flattenChatModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_IMAGE_MODELS=flattenImageModelCatalog("github-copilot",github_copilot_default),GITHUB_COPILOT_CLASSIFIER_MODELS=flattenClassifierModelCatalog("github-copilot",github_copilot_default);function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getBaseUrlFromToken(token){let match=token.match(/proxy-ep=([^;]+)/);return match?`https://${match[1].replace(/^proxy\./,"api.")}`:null}function getGitHubCopilotBaseUrl(token,enterpriseDomain){if(token){let urlFromToken=getBaseUrlFromToken(token);if(urlFromToken)return urlFromToken}return enterpriseDomain?`https://copilot-api.${enterpriseDomain}`:"https://api.individual.githubcopilot.com"}function asRecord(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord(item.capabilities);return asRecord(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord(item.policy)?.state}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id);return{availableModelIds,policyModelIds}}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain),allowPolicyFallback=baseUrl==="https://api.individual.githubcopilot.com",response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new Error(`${response.status} ${response.statusText}: ${text}`)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0});return{...credentials,availableModelIds}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3}),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])]}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential))}}};export{githubCopilotOAuth};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bkper-ai-provider.d.ts","sourceRoot":"","sources":["../../../src/agent/extensions/bkper-ai-provider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACR,YAAY,EACZ,cAAc,EAEjB,MAAM,iCAAiC,CAAC;AAGzC,eAAO,MAAM,oBAAoB,UAAU,CAAC;AAC5C,eAAO,MAAM,4BAA4B,4BAA4B,CAAC;AAItE,QAAA,MAAM,eAAe,sEAAuE,CAAC;AAI7F,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpE,MAAM,WAAW,oBAAoB;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,yBAAyB,CAAC,EAAE,oBAAoB,CAAC;CACpD;
|
|
1
|
+
{"version":3,"file":"bkper-ai-provider.d.ts","sourceRoot":"","sources":["../../../src/agent/extensions/bkper-ai-provider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACR,YAAY,EACZ,cAAc,EAEjB,MAAM,iCAAiC,CAAC;AAGzC,eAAO,MAAM,oBAAoB,UAAU,CAAC;AAC5C,eAAO,MAAM,4BAA4B,4BAA4B,CAAC;AAItE,QAAA,MAAM,eAAe,sEAAuE,CAAC;AAI7F,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpE,MAAM,WAAW,oBAAoB;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,yBAAyB,CAAC,EAAE,oBAAoB,CAAC;CACpD;AAwED,wBAAgB,yBAAyB,CACrC,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACtD,MAAM,GAAG,SAAS,CA0BpB;AAgND,wBAAgB,uBAAuB,CAAC,MAAM,SAAS,oBAAoB,EACvE,MAAM,EAAE,SAAS,MAAM,EAAE,GAC1B,MAAM,GAAG,SAAS,CAMpB;AAED,wBAAgB,8BAA8B,CAC1C,KAAK,EAAE,oBAAoB,GAAG,SAAS,GACxC,oBAAoB,GAAG,SAAS,CAIlC;AAED,wBAAgB,wBAAwB,CACpC,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,EACrD,OAAO,GAAE,OAAO,KAAa,GAC9B,cAAc,CAkBhB;AAED,wBAAgB,uBAAuB,CACnC,EAAE,EAAE,IAAI,CAAC,YAAY,EAAE,kBAAkB,CAAC,EAC1C,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACtD,IAAI,CAEN"}
|
|
@@ -86,10 +86,15 @@ function getThinkingLevelMap(levels) {
|
|
|
86
86
|
function nanoUsdPerTokenToUsdPerMillion(value) {
|
|
87
87
|
return value / 1000;
|
|
88
88
|
}
|
|
89
|
+
/** The catalog modalities Pi understands; others are dropped. */
|
|
90
|
+
function getInputModalities(modalities) {
|
|
91
|
+
var _a;
|
|
92
|
+
return (_a = modalities === null || modalities === void 0 ? void 0 : modalities.filter((modality) => modality === 'text' || modality === 'image')) !== null && _a !== void 0 ? _a : [];
|
|
93
|
+
}
|
|
89
94
|
function toProviderModel(model, defaultModelId) {
|
|
90
|
-
var _a
|
|
91
|
-
const input = (
|
|
92
|
-
return Object.assign(Object.assign({ id: model.id, name: (
|
|
95
|
+
var _a;
|
|
96
|
+
const input = getInputModalities(model.input_modalities);
|
|
97
|
+
return Object.assign(Object.assign({ id: model.id, name: (_a = model.name) !== null && _a !== void 0 ? _a : model.id, reasoning: model.thinking_levels.some(level => level !== 'none'), thinkingLevelMap: getThinkingLevelMap(model.thinking_levels), input, cost: {
|
|
93
98
|
input: nanoUsdPerTokenToUsdPerMillion(model.pricing.inputNanoUsdPerToken),
|
|
94
99
|
output: nanoUsdPerTokenToUsdPerMillion(model.pricing.outputNanoUsdPerToken),
|
|
95
100
|
cacheRead: nanoUsdPerTokenToUsdPerMillion(model.pricing.cachedInputNanoUsdPerToken),
|
|
@@ -99,13 +104,14 @@ function toProviderModel(model, defaultModelId) {
|
|
|
99
104
|
: {})), bkperDefault: model.id === defaultModelId, bkperDefaultThinkingLevel: getDefaultThinkingLevel(model) });
|
|
100
105
|
}
|
|
101
106
|
function toClassifierModel(model) {
|
|
102
|
-
var _a;
|
|
107
|
+
var _a, _b;
|
|
103
108
|
return {
|
|
104
109
|
type: 'classifier',
|
|
105
110
|
id: model.id,
|
|
106
111
|
name: (_a = model.name) !== null && _a !== void 0 ? _a : model.id,
|
|
107
112
|
api: BKPER_AI_CLASSIFIER_API,
|
|
108
|
-
|
|
113
|
+
// The gateway accepts images as TypeSafe assets, Pi's default System One form.
|
|
114
|
+
input: getInputModalities((_b = model.input_modalities) !== null && _b !== void 0 ? _b : ['text']),
|
|
109
115
|
cost: {
|
|
110
116
|
input: nanoUsdPerTokenToUsdPerMillion(model.pricing.inputNanoUsdPerToken),
|
|
111
117
|
output: nanoUsdPerTokenToUsdPerMillion(model.pricing.outputNanoUsdPerToken),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bkper-ai-provider.js","sourceRoot":"","sources":["../../../src/agent/extensions/bkper-ai-provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAC,oBAAoB,EAAC,MAAM,yBAAyB,CAAC;AAE7D,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAC5C,MAAM,CAAC,MAAM,4BAA4B,GAAG,yBAAyB,CAAC;AAEtE,MAAM,yBAAyB,GAAG,mBAAmB,CAAC;AACtD,MAAM,2BAA2B,GAAG,0BAA0B,CAAC;AAC/D,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAU,CAAC;AAC7F,MAAM,uBAAuB,GAAG,qBAAqB,CAAC;AACtD,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"bkper-ai-provider.js","sourceRoot":"","sources":["../../../src/agent/extensions/bkper-ai-provider.ts"],"names":[],"mappings":"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"}
|