@knightcodeai/cli 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/bundle/chunks/{anthropic-messages-A2IH2IY3.js → anthropic-messages-QIZAJBTA.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-XZILQZOG.js → azure-openai-responses-7R44RRTC.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +22 -22
  5. package/dist/bundle/chunks/chunk-2QXPCKUQ.js +9 -0
  6. package/dist/bundle/chunks/{chunk-AFR2OW6S.js → chunk-3B66IKOZ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-NCIBB66G.js → chunk-55AAX2FB.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-FO7CEQB3.js → chunk-76TARFPL.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-M5GCRGV6.js → chunk-7CWBI3GL.js} +9 -9
  10. package/dist/bundle/chunks/{chunk-NNCIIYD6.js → chunk-BPNRVFVQ.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-XIRAUXOE.js → chunk-HNZSETB2.js} +2 -2
  12. package/dist/bundle/chunks/{chunk-OFST7FDG.js → chunk-IGNYWP4P.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-GHVXUCGU.js → chunk-LA7DDYYM.js} +2 -2
  14. package/dist/bundle/chunks/{chunk-ACHHEROF.js → chunk-NGWSYXD5.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-U5XE4RWR.js → chunk-R2XYMDTS.js} +1 -1
  16. package/dist/bundle/chunks/chunk-T7XWBYOA.js +11 -0
  17. package/dist/bundle/chunks/chunk-XZJICKQ6.js +30 -0
  18. package/dist/bundle/chunks/{chunk-A5LJINMT.js → chunk-YQ26QP2R.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-FHM6KUY3.js → chunk-ZB5LGRB5.js} +1 -1
  20. package/dist/bundle/chunks/{cli-6ZTWO6GL.js → cli-66ZLURJW.js} +1 -1
  21. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-6E2UM7IG.js → cloudflare-workers-ai-system-one-LA7TF5LV.js} +1 -1
  22. package/dist/bundle/chunks/{easter-egg-3d-FDCGDUF3.js → easter-egg-3d-DQYQIGP2.js} +1 -1
  23. package/dist/bundle/chunks/{execute-VSDU5VSN.js → execute-KJDH5JWX.js} +1 -1
  24. package/dist/bundle/chunks/{google-generative-ai-CSWR3ORZ.js → google-generative-ai-GEBPSQBJ.js} +1 -1
  25. package/dist/bundle/chunks/{google-vertex-QIDRFOFB.js → google-vertex-BRMU44TN.js} +1 -1
  26. package/dist/bundle/chunks/{mistral-conversations-46TK5OBA.js → mistral-conversations-FKYKJV7R.js} +1 -1
  27. package/dist/bundle/chunks/{openai-codex-responses-IT7VEKUU.js → openai-codex-responses-DAZKF6IV.js} +1 -1
  28. package/dist/bundle/chunks/{openai-completions-LOKIW33V.js → openai-completions-A6RD26ED.js} +1 -1
  29. package/dist/bundle/chunks/{openai-decisions-4F3LWHMG.js → openai-decisions-OBTJNBTE.js} +1 -1
  30. package/dist/bundle/chunks/{openai-responses-OK36GJXP.js → openai-responses-L3QPK3MQ.js} +1 -1
  31. package/dist/bundle/chunks/{runtime-RMPIV5AR.js → runtime-IU2Z5WWF.js} +1 -1
  32. package/dist/bundle/chunks/{typesafe-system-one-J2CJBWEH.js → typesafe-system-one-FZHRNG67.js} +1 -1
  33. package/dist/bundle/chunks/{virtual-modules-EGJP3AJA.js → virtual-modules-IKIDAUHO.js} +1 -1
  34. package/dist/bundle/cli-runtime.js +1 -1
  35. package/dist/bundle/cli.js +14 -3
  36. package/docs/custom-provider.md +53 -1
  37. package/docs/extensions.md +116 -10
  38. package/docs/tui.md +70 -0
  39. package/docs/windows.md +16 -2
  40. package/package.json +1 -1
  41. package/dist/bundle/chunks/chunk-EPYT326Y.js +0 -30
  42. package/dist/bundle/chunks/chunk-MB4QRS7Y.js +0 -9
  43. package/dist/bundle/chunks/chunk-V5ANFNKF.js +0 -11
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{combineAbortSignals}from"./chunk-UZWP3NHW.js";import{registerSessionResourceCleanup,uuidv7}from"./chunk-NDQ5OW6U.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-FO7CEQB3.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import"./chunk-HUQB436V.js";import{buildBaseOptions,createGrammarToolInputProperties}from"./chunk-NCIBB66G.js";import"./chunk-B2FT7RH5.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import{getKnightcodeUserAgent}from"./chunk-HHWP56PR.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,resolveTranscriptTools}from"./chunk-V5ANFNKF.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[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,env){let noProxy=getProxyEnv("no_proxy",env).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,env){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,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);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,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",JWT_CLAIM_PATH="https://api.openai.com/auth",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE=1009,WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}function getRetryAfterDelayMs(headers){let retryAfterMs=headers.get("retry-after-ms");if(retryAfterMs!==null){let millis=Number(retryAfterMs);if(Number.isFinite(millis))return Math.max(0,millis)}let retryAfter=headers.get("retry-after");if(!retryAfter)return;let seconds=Number(retryAfter);if(Number.isFinite(seconds))return Math.max(0,seconds*1e3);let date=Date.parse(retryAfter);if(!Number.isNaN(date))return Math.max(0,date-Date.now())}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return new Uint8Array(compressed)}catch{return null}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",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()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,normalizedContext,options,codexSessionId,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart||(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,...websocketStarted?{}:{fallbackTransport:"sse"},eventsEmitted:websocketStarted,phase:websocketStarted?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error),websocketStarted))throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody??bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=getRetryAfterDelayMs(response.headers),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse);throw new Error(info.friendlyMessage||info.message)}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function buildRequestBody(model,context,options,cacheSessionId,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,supportsAdditionalTools||supportsToolSearch),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),initialSystemMessage=getInitialSystemMessage(context.messages),instructions=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",body={model:model.id,store:!1,stream:!0,instructions:instructions||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:cacheSessionId,tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};if(options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),transcriptTools.requestTools.length>0&&(body.tools=convertResponsesTools(transcriptTools.requestTools,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools})),options?.reasoningEffort!==void 0){let effort=options.reasoningEffort==="none"?model.thinkingLevelMap?.off===void 0?"none":model.thinkingLevelMap.off:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;effort!==null&&(body.reasoning={effort,summary:options.reasoningSummary??"auto"})}else model.reasoning&&model.thinkingLevelMap?.off!==null&&(body.reasoning={effort:model.thinkingLevelMap?.off??"none"});return body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output,model,options?.onProviderStreamEvent),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{code;payload;constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{payload;constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}},ProviderStreamEventCallbackError=class extends Error{constructor(cause){super(formatThrownValue(cause)),this.name="ProviderStreamEventCallbackError",this.cause=cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError||error instanceof ProviderStreamEventCallbackError}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function extractCodexEventError(event){let nested=event.error&&typeof event.error=="object"?event.error:void 0;return{code:typeof event.code=="string"?event.code:typeof nested?.code=="string"?nested.code:void 0,message:typeof event.message=="string"?event.message:typeof nested?.message=="string"?nested.message:void 0}}async function*mapCodexEvents(events,output,model,onProviderStreamEvent){for await(let event of events){try{await onProviderStreamEvent?.(event,model)}catch(error){throw new ProviderStreamEventCallbackError(error)}let type=typeof event.type=="string"?event.type:void 0;if(type){if(type==="error"){let{code,message}=extractCodexEventError(event);throw new CodexApiError(`Codex error: ${message||code||JSON.stringify(event)}`,{code,payload:event})}if(type==="response.failed"){let response=event.response,code=response?.error?.code,message=response?.error?.message;throw new CodexApiError(message||"Codex response failed",{code,payload:event})}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield event}}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
2
+ import{combineAbortSignals}from"./chunk-UZWP3NHW.js";import{registerSessionResourceCleanup,uuidv7}from"./chunk-NDQ5OW6U.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-76TARFPL.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import"./chunk-HUQB436V.js";import{buildBaseOptions,createGrammarToolInputProperties}from"./chunk-55AAX2FB.js";import"./chunk-B2FT7RH5.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import{getKnightcodeUserAgent}from"./chunk-HHWP56PR.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{clampThinkingLevel,getDeclaredTools,getInitialSystemMessage,getSystemMessageText,normalizeContext,resolveTranscript,resolveTranscriptTools}from"./chunk-T7XWBYOA.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[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,env){let noProxy=getProxyEnv("no_proxy",env).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,env){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,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);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,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",JWT_CLAIM_PATH="https://api.openai.com/auth",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE=1009,WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}function getRetryAfterDelayMs(headers){let retryAfterMs=headers.get("retry-after-ms");if(retryAfterMs!==null){let millis=Number(retryAfterMs);if(Number.isFinite(millis))return Math.max(0,millis)}let retryAfter=headers.get("retry-after");if(!retryAfter)return;let seconds=Number(retryAfter);if(Number.isFinite(seconds))return Math.max(0,seconds*1e3);let date=Date.parse(retryAfter);if(!Number.isNaN(date))return Math.max(0,date-Date.now())}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return new Uint8Array(compressed)}catch{return null}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",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()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,normalizedContext,options,codexSessionId,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart||(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,...websocketStarted?{}:{fallbackTransport:"sse"},eventsEmitted:websocketStarted,phase:websocketStarted?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error),websocketStarted))throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody??bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=getRetryAfterDelayMs(response.headers),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse);throw new Error(info.friendlyMessage||info.message)}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function buildRequestBody(model,context,options,cacheSessionId,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,supportsAdditionalTools||supportsToolSearch),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),initialSystemMessage=getInitialSystemMessage(context.messages),instructions=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",body={model:model.id,store:!1,stream:!0,instructions:instructions||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:cacheSessionId,tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};if(options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),transcriptTools.requestTools.length>0&&(body.tools=convertResponsesTools(transcriptTools.requestTools,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools})),options?.reasoningEffort!==void 0){let effort=options.reasoningEffort==="none"?model.thinkingLevelMap?.off===void 0?"none":model.thinkingLevelMap.off:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;effort!==null&&(body.reasoning={effort,summary:options.reasoningSummary??"auto"})}else model.reasoning&&model.thinkingLevelMap?.off!==null&&(body.reasoning={effort:model.thinkingLevelMap?.off??"none"});return body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output,model,options?.onProviderStreamEvent),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{code;payload;constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{payload;constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}},ProviderStreamEventCallbackError=class extends Error{constructor(cause){super(formatThrownValue(cause)),this.name="ProviderStreamEventCallbackError",this.cause=cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError||error instanceof ProviderStreamEventCallbackError}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function extractCodexEventError(event){let nested=event.error&&typeof event.error=="object"?event.error:void 0;return{code:typeof event.code=="string"?event.code:typeof nested?.code=="string"?nested.code:void 0,message:typeof event.message=="string"?event.message:typeof nested?.message=="string"?nested.message:void 0}}async function*mapCodexEvents(events,output,model,onProviderStreamEvent){for await(let event of events){try{await onProviderStreamEvent?.(event,model)}catch(error){throw new ProviderStreamEventCallbackError(error)}let type=typeof event.type=="string"?event.type:void 0;if(type){if(type==="error"){let{code,message}=extractCodexEventError(event);throw new CodexApiError(`Codex error: ${message||code||JSON.stringify(event)}`,{code,payload:event})}if(type==="response.failed"){let response=event.response,code=response?.error?.code,message=response?.error?.message;throw new CodexApiError(message||"Codex response failed",{code,payload:event})}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield event}}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
3
3
 
4
4
  `);let idx=buffer.indexOf(`
5
5
 
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-HWXGL4YB.js";import{OpenAI}from"./chunk-ZW7FVRHT.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import{shortHash}from"./chunk-HUQB436V.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-NCIBB66G.js";import{sanitizeSurrogates}from"./chunk-B2FT7RH5.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import{parseStreamingJson,parseToolCallArguments}from"./chunk-FA32X2UJ.js";import{getKnightcodeUserAgent}from"./chunk-HHWP56PR.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-V5ANFNKF.js";import{AssistantMessageEventStream}from"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(field){return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("KNIGHTCODE_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,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()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,apiKey,options?.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,hasFinishReason=!1,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else Object.assign(block,parseToolCallArguments(block.partialArgs));delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},ensureTextBlock=()=>(textBlock||(textBlock={type:"text",text:""},blocks.push(textBlock),stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output})),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output})),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output})}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(choice){if(!chunk.usage&&choice.usage&&(output.usage=parseChunkUsage(choice.usage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)isOpenAIReasoningDetail(detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail));if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
2
+ import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-HWXGL4YB.js";import{OpenAI}from"./chunk-ZW7FVRHT.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import{shortHash}from"./chunk-HUQB436V.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-55AAX2FB.js";import{sanitizeSurrogates}from"./chunk-B2FT7RH5.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import{parseStreamingJson,parseToolCallArguments}from"./chunk-FA32X2UJ.js";import{getKnightcodeUserAgent}from"./chunk-HHWP56PR.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-T7XWBYOA.js";import{AssistantMessageEventStream}from"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(field){return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("KNIGHTCODE_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,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()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,apiKey,options?.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,hasFinishReason=!1,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else Object.assign(block,parseToolCallArguments(block.partialArgs));delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},ensureTextBlock=()=>(textBlock||(textBlock={type:"text",text:""},blocks.push(textBlock),stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output})),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output})),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output})}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(choice){if(!chunk.usage&&choice.usage&&(output.usage=parseChunkUsage(choice.usage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)isOpenAIReasoningDetail(detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail));if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
3
3
  ${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getCompat(model)){let headers={"User-Agent":getKnightcodeUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),compat.supportsOpenAIGrammarTools)){let transcriptTools=resolveTranscriptTools(context.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),messages=convertMessages(model,context,compat,{grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),params={model:model.id,messages,stream:!0,prompt_cache_key:model.baseUrl.includes("api.openai.com")&&cacheRetention!=="none"||cacheRetention==="long"&&compat.supportsLongCacheRetention?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature),transcriptTools.requestTools.length>0?(params.tools=convertTools(transcriptTools.requestTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice),compat.vllmPriority!==void 0&&(params.priority=compat.vllmPriority);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let mappedEffort=model.thinkingLevelMap?.[options.reasoningEffort],effort=mappedEffort===void 0?options.reasoningEffort:mappedEffort;typeof effort=="string"&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;typeof effort=="string"&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat.chatTemplateArgs,thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?model.thinkingLevelMap?.[requestedEffort]:model.thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)options?.reasoningEffort?params.thinking={type:"enabled"}:model.thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"}),options?.reasoningEffort&&compat.supportsReasoningEffort&&(params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort);else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;options?.reasoningEffort?openRouterParams.reasoning={effort:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort}:model.thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:model.thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort&&(togetherParams.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort)}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning){let stringThinkingParams=params;options?.reasoningEffort?stringThinkingParams.thinking=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:model.thinkingLevelMap?.off!==null&&(stringThinkingParams.thinking=model.thinkingLevelMap?.off??"none")}else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort)params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=model.thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}let samplingParams=resolveSamplingParams(model,options?.reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let mappedValue=reasoningEffort?model.thinkingLevelMap?.[reasoningEffort]:model.thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function convertMessages(model,context,compat,options){let normalizedContext=resolveTranscript(context,compat.supportsMidConvoSystemMessages),params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`}return model.provider==="openai"&&id.length>40?id.slice(0,40):id},transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeToolCallId(id)),transcriptTools=resolveTranscriptTools(normalizedContext.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),instructionRole=model.reasoning&&compat.supportsDeveloperRole?"developer":"system",lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&&params.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="system"){let addedTools=i>0&&transcriptTools.anchorsAdditions?msg.toolsAdded??[]:[];if(addedTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(addedTools,compat)};params.push(kimiToolMessage)}let text=i===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&params.push({role:instructionRole,content:sanitizeSurrogates(text)})}else if(msg.role==="user")if(typeof msg.content=="string")params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let content=msg.content.filter(item=>item.type!=="text"||item.text.length>0).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;params.push({role:"user",content})}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0){if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
4
4
 
5
5
  `);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else if(assistantText.length>0&&(assistantMsg.content=assistantText),!preservedReasoningDetails){let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature&&isOpenAICompletionsReasoningField(signature)&&(assistantMsg[signature]=nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-A5LJINMT.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-V5ANFNKF.js";import"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var LABEL="OpenAI Decisions",MAX_IMAGES=128;function predicateInstructions(question){let meanings=[question.criteria.true?`True means: ${question.criteria.true}`:"",question.criteria.false?`False means: ${question.criteria.false}`:""].filter(Boolean);return meanings.length>0?`${question.instructions}
2
+ import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-YQ26QP2R.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-T7XWBYOA.js";import"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var LABEL="OpenAI Decisions",MAX_IMAGES=128;function predicateInstructions(question){let meanings=[question.criteria.true?`True means: ${question.criteria.true}`:"",question.criteria.false?`False means: ${question.criteria.false}`:""].filter(Boolean);return meanings.length>0?`${question.instructions}
3
3
 
4
4
  ${meanings.join(`
5
5
  `)}`:question.instructions}function wireQuestion(name,question){return question.type==="choice"?{type:"choice",name,instructions:question.instructions,choices:Object.entries(question.criteria).map(([value,description])=>description?{value,description}:{value})}:question.type==="score"?{type:"score",name,instructions:question.instructions,levels:question.criteria.map(label=>({label}))}:{type:"predicate",name,instructions:predicateInstructions(question)}}function wireInput(context){let state=JSON.stringify(context.state),images=context.images??[];if(images.length===0)return state;if(images.length>MAX_IMAGES)throw new Error(`${LABEL} accepts at most ${MAX_IMAGES} images, got ${images.length}`);return[{role:"user",content:[{type:"input_text",text:state},...images.map(image=>({type:"input_image",image_url:`data:${image.mimeType};base64,${image.data}`}))]}]}function choiceProbabilities(value,id){if(!Array.isArray(value))throw new Error(`${LABEL} returned invalid probabilities for ${id}`);return Object.fromEntries(value.map(entry=>{if(!isRecord(entry)||typeof entry.value!="string")throw new Error(`${LABEL} returned invalid probabilities for ${id}`);return[entry.value,requiredNumber(LABEL,entry.probability,`probability for ${id}.${entry.value}`)]}))}function parseAnswer(id,question,answer){if(answer.type==="refusal")throw new Error(`${LABEL} refused to answer ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${LABEL} did not return a choice answer for ${id}`);return{type:"choice",choice:answer.choice,probabilities:choiceProbabilities(answer.probabilities,id),confidence:requiredNumber(LABEL,answer.confidence,`confidence for ${id}`)}}if(question.type==="score"){if(answer.type!=="score")throw new Error(`${LABEL} did not return a score answer for ${id}`);return{type:"score",score:requiredNumber(LABEL,answer.score,`score for ${id}`),confidence:requiredNumber(LABEL,answer.confidence,`confidence for ${id}`)}}if(answer.type!=="predicate")throw new Error(`${LABEL} did not return a predicate answer for ${id}`);return{type:"bool",probability:requiredNumber(LABEL,answer.probability,`probability for ${id}`)}}function parseAnswers(value,context){if(!Array.isArray(value))throw new Error(`${LABEL} returned an unexpected response`);let byName=new Map;for(let answer of value)isRecord(answer)&&typeof answer.name=="string"&&byName.set(answer.name,answer);return Object.fromEntries(Object.entries(context.questions).map(([id,question])=>{let answer=byName.get(id);if(!answer)throw new Error(`${LABEL} did not return an answer for ${id}`);return[id,parseAnswer(id,question,answer)]}))}var NO_RETRY_STATUSES=[504];function errorMessage(error){return error.status===504?`${LABEL} error (504): the request timed out at the gateway. Very large inputs (above roughly 600K tokens) currently exceed its time limit.`:formatProviderError(normalizeProviderError(error),`${LABEL} error`)}var classify=async(model,context,options)=>{let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!=="openai-decisions")throw new Error(`Unsupported classifier API: ${model.api}`);let body=await postClassifierRequest(LABEL,new URL("decisions",`${model.baseUrl.replace(/\/+$/u,"")}/`),model,{model:model.id,input:wireInput(context),questions:Object.entries(context.questions).map(([id,question])=>wireQuestion(id,question))},options,NO_RETRY_STATUSES);if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);let usage=parseClassifierUsage(body.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(body.answers,context),output}catch(error){return output.answers={},output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=errorMessage(error),output}};export{classify};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-HWXGL4YB.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-FO7CEQB3.js";import{OpenAI}from"./chunk-ZW7FVRHT.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import"./chunk-HUQB436V.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-NCIBB66G.js";import"./chunk-B2FT7RH5.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import{getKnightcodeUserAgent}from"./chunk-HHWP56PR.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-V5ANFNKF.js";import{AssistantMessageEventStream}from"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var OPENAI_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16,CHATGPT_USAGE_URL="https://chatgpt.com/settings/usage",CONFIGURATION_UPDATE_REQUEST_EFFORT="medium";function isChatGPTSignIn(model,apiKey){return model.provider==="openai"&&model.baseUrl==="https://api.openai.com/v1"&&apiKey!==void 0&&!apiKey.startsWith("sk-")}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function detectSessionAffinityFormat(model){return model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("KNIGHTCODE_CACHE_RETENTION",env)==="long"?"long":"short")}function getCompat(model){return{supportsDeveloperRole:model.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:model.compat?.sessionAffinityFormat??detectSessionAffinityFormat(model),supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,supportsStrictMode:model.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:model.compat?.supportsAdditionalTools??!1,supportsToolSearch:model.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:model.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:model.compat?.supportsMaxOutputTokens??!0,supportsMidConvoEffort:model.compat?.supportsMidConvoEffort??!1}}function getConfigurationUpdateEffort(model,options,compat){if(!(!compat.supportsMidConvoEffort||!options?.reasoningEffort||isChatGPTSignIn(model,options.apiKey)))return model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort}function getPromptCacheRetention(compat,cacheRetention){return cacheRetention==="long"&&compat.supportsLongCacheRetention&&!compat.supportsExplicitPromptCacheMode?"24h":void 0}function getPromptCacheOptions(compat,cacheRetention){if(compat.supportsExplicitPromptCacheMode){if(cacheRetention==="none")return{mode:"explicit"};if(cacheRetention==="long"&&compat.supportsLongCacheRetention)return{ttl:"30m"}}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getCompat(model).supportsMidConvoSystemMessages);return(async()=>{let compat=getCompat(model),configurationUpdateEffort=getConfigurationUpdateEffort(model,options,compat),output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,...configurationUpdateEffort===void 0?{}:{providerThinkingLevel:configurationUpdateEffort},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()};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),client=createClient(model,normalizedContext,apiKey,options?.headers,options?.fetch,cacheSessionId),params=buildParams(model,normalizedContext,options,compat,grammarToolInputProperties,configurationUpdateEffort),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,serviceTier:options?.serviceTier,grammarToolInputProperties,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error";let errorMessage=formatProviderError(normalizeProviderError(error),`${model.provider==="openai"?"OpenAI":model.provider} API error`);output.errorMessage=errorMessage.includes("subscription_sharing_usage_limit_exceeded")?`${errorMessage}
2
+ import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-HWXGL4YB.js";import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-76TARFPL.js";import{OpenAI}from"./chunk-ZW7FVRHT.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import"./chunk-HUQB436V.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-55AAX2FB.js";import"./chunk-B2FT7RH5.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import{getKnightcodeUserAgent}from"./chunk-HHWP56PR.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-T7XWBYOA.js";import{AssistantMessageEventStream}from"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var OPENAI_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16,CHATGPT_USAGE_URL="https://chatgpt.com/settings/usage",CONFIGURATION_UPDATE_REQUEST_EFFORT="medium";function isChatGPTSignIn(model,apiKey){return model.provider==="openai"&&model.baseUrl==="https://api.openai.com/v1"&&apiKey!==void 0&&!apiKey.startsWith("sk-")}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function detectSessionAffinityFormat(model){return model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("KNIGHTCODE_CACHE_RETENTION",env)==="long"?"long":"short")}function getCompat(model){return{supportsDeveloperRole:model.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:model.compat?.sessionAffinityFormat??detectSessionAffinityFormat(model),supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,supportsStrictMode:model.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:model.compat?.supportsAdditionalTools??!1,supportsToolSearch:model.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:model.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:model.compat?.supportsMaxOutputTokens??!0,supportsMidConvoEffort:model.compat?.supportsMidConvoEffort??!1}}function getConfigurationUpdateEffort(model,options,compat){if(!(!compat.supportsMidConvoEffort||!options?.reasoningEffort||isChatGPTSignIn(model,options.apiKey)))return model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort}function getPromptCacheRetention(compat,cacheRetention){return cacheRetention==="long"&&compat.supportsLongCacheRetention&&!compat.supportsExplicitPromptCacheMode?"24h":void 0}function getPromptCacheOptions(compat,cacheRetention){if(compat.supportsExplicitPromptCacheMode){if(cacheRetention==="none")return{mode:"explicit"};if(cacheRetention==="long"&&compat.supportsLongCacheRetention)return{ttl:"30m"}}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getCompat(model).supportsMidConvoSystemMessages);return(async()=>{let compat=getCompat(model),configurationUpdateEffort=getConfigurationUpdateEffort(model,options,compat),output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,...configurationUpdateEffort===void 0?{}:{providerThinkingLevel:configurationUpdateEffort},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()};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),client=createClient(model,normalizedContext,apiKey,options?.headers,options?.fetch,cacheSessionId),params=buildParams(model,normalizedContext,options,compat,grammarToolInputProperties,configurationUpdateEffort),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,serviceTier:options?.serviceTier,grammarToolInputProperties,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error";let errorMessage=formatProviderError(normalizeProviderError(error),`${model.provider==="openai"?"OpenAI":model.provider} API error`);output.errorMessage=errorMessage.includes("subscription_sharing_usage_limit_exceeded")?`${errorMessage}
3
3
  Check your ChatGPT usage: ${CHATGPT_USAGE_URL}`:errorMessage,stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId){let compat=getCompat(model),headers={"User-Agent":getKnightcodeUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat,grammarToolInputProperties,configurationUpdateEffort){let transcriptTools=resolveTranscriptTools(context.messages,compat.supportsAdditionalTools||compat.supportsToolSearch),messages=convertResponsesMessages(model,context,OPENAI_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:compat.supportsMidConvoSystemMessages,supportsAdditionalTools:compat.supportsAdditionalTools,supportsToolSearch:compat.supportsToolSearch,toolOptions:{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools},configurationUpdateEffort}),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),omitUnsupportedFields=isChatGPTSignIn(model,options?.apiKey),params={model:model.id,input:messages,stream:!0,prompt_cache_key:cacheRetention==="none"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),prompt_cache_retention:omitUnsupportedFields?void 0:getPromptCacheRetention(compat,cacheRetention),prompt_cache_options:omitUnsupportedFields?void 0:getPromptCacheOptions(compat,cacheRetention),store:!1};options?.maxTokens&&compat.supportsMaxOutputTokens&&!omitUnsupportedFields&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&!omitUnsupportedFields&&(params.temperature=options?.temperature),options?.serviceTier!==void 0&&(params.service_tier=options.serviceTier),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning){if(reasoningEffort){let requestedEffort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort,effort=configurationUpdateEffort===void 0?requestedEffort:CONFIGURATION_UPDATE_REQUEST_EFFORT;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.provider!=="github-copilot"&&model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});model.provider==="xai"&&(params.include=["reasoning.encrypted_content"])}let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":case"fast":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}export{stream,streamSimple};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-AFR2OW6S.js";import"./chunk-ACHHEROF.js";import"./chunk-MB4QRS7Y.js";import"./chunk-NNCIIYD6.js";import"./chunk-AHB7JV5B.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-3B66IKOZ.js";import"./chunk-NGWSYXD5.js";import"./chunk-2QXPCKUQ.js";import"./chunk-BPNRVFVQ.js";import"./chunk-AHB7JV5B.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{classifySystemOne}from"./chunk-OFST7FDG.js";import{isRecord}from"./chunk-A5LJINMT.js";import"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-V5ANFNKF.js";import"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var transport={api:"typesafe-system-one",label:"System One API",url:model=>new URL("systemone",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,...request}),output:body=>{if(!isRecord(body))throw new Error("System One API returned an unexpected response");return body}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
2
+ import{classifySystemOne}from"./chunk-IGNYWP4P.js";import{isRecord}from"./chunk-YQ26QP2R.js";import"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-T7XWBYOA.js";import"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var transport={api:"typesafe-system-one",label:"System One API",url:model=>new URL("systemone",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,...request}),output:body=>{if(!isRecord(body))throw new Error("System One API returned an unexpected response");return body}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
- import{src_exports as src_exports2,src_exports2 as src_exports3}from"./chunk-M5GCRGV6.js";import"./chunk-U5XE4RWR.js";import{all_exports,compat_exports,compile_exports,value_exports}from"./chunk-EPYT326Y.js";import"./chunk-XIRAUXOE.js";import{src_exports}from"./chunk-GHVXUCGU.js";import{build_exports}from"./chunk-MXIWLMNT.js";import"./chunk-KQKUEQJA.js";import"./chunk-O6JSP6YG.js";import"./chunk-ACHHEROF.js";import"./chunk-MB4QRS7Y.js";import"./chunk-NNCIIYD6.js";import"./chunk-NDQ5OW6U.js";import"./chunk-HSL72VZI.js";import"./chunk-AANBXVWQ.js";import"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import"./chunk-HHWP56PR.js";import"./chunk-V5ANFNKF.js";import"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@knightcode/agent":src_exports2,"@knightcode/tui":src_exports,"@knightcode/ai":compat_exports,"@knightcode/ai/compat":compat_exports,"@knightcode/ai/oauth":oauth_exports,"@knightcode/ai/providers/all":all_exports,"@knightcodeai/cli":src_exports3};export{VIRTUAL_MODULES};
2
+ import{src_exports as src_exports2,src_exports2 as src_exports3}from"./chunk-7CWBI3GL.js";import"./chunk-R2XYMDTS.js";import{all_exports,compat_exports,compile_exports,value_exports}from"./chunk-XZJICKQ6.js";import"./chunk-HNZSETB2.js";import{src_exports}from"./chunk-LA7DDYYM.js";import{build_exports}from"./chunk-MXIWLMNT.js";import"./chunk-KQKUEQJA.js";import"./chunk-O6JSP6YG.js";import"./chunk-NGWSYXD5.js";import"./chunk-2QXPCKUQ.js";import"./chunk-BPNRVFVQ.js";import"./chunk-NDQ5OW6U.js";import"./chunk-HSL72VZI.js";import"./chunk-AANBXVWQ.js";import"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import"./chunk-HHWP56PR.js";import"./chunk-T7XWBYOA.js";import"./chunk-ETOMYYZC.js";import"./chunk-AHB7JV5B.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@knightcode/agent":src_exports2,"@knightcode/tui":src_exports,"@knightcode/ai":compat_exports,"@knightcode/ai/compat":compat_exports,"@knightcode/ai/oauth":oauth_exports,"@knightcode/ai/providers/all":all_exports,"@knightcodeai/cli":src_exports3};export{VIRTUAL_MODULES};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-M5GCRGV6.js";import"./chunks/chunk-U5XE4RWR.js";import"./chunks/chunk-EPYT326Y.js";import"./chunks/chunk-XIRAUXOE.js";import"./chunks/chunk-GHVXUCGU.js";import"./chunks/chunk-MXIWLMNT.js";import"./chunks/chunk-KQKUEQJA.js";import"./chunks/chunk-O6JSP6YG.js";import"./chunks/chunk-ACHHEROF.js";import"./chunks/chunk-MB4QRS7Y.js";import{APP_NAME}from"./chunks/chunk-NNCIIYD6.js";import"./chunks/chunk-NDQ5OW6U.js";import"./chunks/chunk-HSL72VZI.js";import"./chunks/chunk-AANBXVWQ.js";import"./chunks/chunk-BRKUE2MD.js";import"./chunks/chunk-FA32X2UJ.js";import"./chunks/chunk-HHWP56PR.js";import"./chunks/chunk-V5ANFNKF.js";import"./chunks/chunk-ETOMYYZC.js";import"./chunks/chunk-AHB7JV5B.js";process.title=APP_NAME;process.env.KNIGHTCODE_CODING_AGENT="true";process.env.AI_AGENT="knightcode";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-7CWBI3GL.js";import"./chunks/chunk-R2XYMDTS.js";import"./chunks/chunk-XZJICKQ6.js";import"./chunks/chunk-HNZSETB2.js";import"./chunks/chunk-LA7DDYYM.js";import"./chunks/chunk-MXIWLMNT.js";import"./chunks/chunk-KQKUEQJA.js";import"./chunks/chunk-O6JSP6YG.js";import"./chunks/chunk-NGWSYXD5.js";import"./chunks/chunk-2QXPCKUQ.js";import{APP_NAME}from"./chunks/chunk-BPNRVFVQ.js";import"./chunks/chunk-NDQ5OW6U.js";import"./chunks/chunk-HSL72VZI.js";import"./chunks/chunk-AANBXVWQ.js";import"./chunks/chunk-BRKUE2MD.js";import"./chunks/chunk-FA32X2UJ.js";import"./chunks/chunk-HHWP56PR.js";import"./chunks/chunk-T7XWBYOA.js";import"./chunks/chunk-ETOMYYZC.js";import"./chunks/chunk-AHB7JV5B.js";process.title=APP_NAME;process.env.KNIGHTCODE_CODING_AGENT="true";process.env.AI_AGENT="knightcode";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
@@ -1,5 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire, enableCompileCache } from "node:module";
2
+ import module from "node:module";
3
3
 
4
- enableCompileCache?.();
5
- createRequire(import.meta.url)("./cli-runtime.js");
4
+ const required = [22, 19, 0];
5
+ const current = process.versions.node.split(".").map(Number);
6
+ const differs = required.findIndex((part, index) => current[index] !== part);
7
+ if (differs !== -1 && current[differs] < required[differs]) {
8
+ process.stderr.write(
9
+ "KnightCode requires Node.js 22.19.0 or newer, but " + process.execPath + " is Node.js " + process.versions.node + ".\n" +
10
+ "Update Node.js from https://nodejs.org, or use a standalone binary from https://github.com/KnightCodeAI/knightcode/releases.\n",
11
+ );
12
+ process.exitCode = 1;
13
+ } else {
14
+ if (module.enableCompileCache) module.enableCompileCache();
15
+ module.createRequire(import.meta.url)("./cli-runtime.js");
16
+ }
@@ -29,7 +29,59 @@ Prefer a complete provider for new integrations that own more than static endpoi
29
29
 
30
30
  Registering only `baseUrl` or `headers` for an existing provider preserves its built-in models. Supplying `models` in the legacy form replaces that provider's models across chat, image, and classifier operations. An omitted `type` means `"chat"`; image and classifier models require explicit discriminants and implementations keyed by their `api` values through the `images` and `classifiers` fields.
31
31
 
32
- For example, a mixed-operation provider can register non-chat models and their implementations together:
32
+ ### Redirect an existing provider
33
+
34
+ Register only the fields that should change. This keeps the provider's built-in catalog, authentication, API implementation, and compatibility settings:
35
+
36
+ ```typescript
37
+ import type { ExtensionAPI } from "@knightcodeai/cli";
38
+
39
+ export default function (knightcode: ExtensionAPI) {
40
+ knightcode.registerProvider("anthropic", {
41
+ baseUrl: "https://gateway.example.com/anthropic",
42
+ headers: {
43
+ "X-Gateway-Key": "$GATEWAY_API_KEY",
44
+ },
45
+ });
46
+ }
47
+ ```
48
+
49
+ Use this form for a proxy or gateway that preserves the provider's protocol. Do not copy the built-in model list into the extension because doing so turns a small endpoint override into a catalog replacement that can drift.
50
+
51
+ ### Register a compatible endpoint
52
+
53
+ When a service implements a supported protocol but has its own model catalog, register the endpoint and only the models the service actually exposes:
54
+
55
+ ```typescript
56
+ import type { ExtensionAPI } from "@knightcodeai/cli";
57
+
58
+ export default function (knightcode: ExtensionAPI) {
59
+ knightcode.registerProvider("acme", {
60
+ name: "Acme AI",
61
+ baseUrl: "https://api.acme.example/v1",
62
+ apiKey: "$ACME_API_KEY",
63
+ api: "openai-completions",
64
+ models: [
65
+ {
66
+ type: "chat",
67
+ id: "acme-chat",
68
+ name: "Acme Chat",
69
+ reasoning: false,
70
+ input: ["text"],
71
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
72
+ contextWindow: 128000,
73
+ maxTokens: 8192,
74
+ },
75
+ ],
76
+ });
77
+ }
78
+ ```
79
+
80
+ Prefer `models.json` for this case when no executable extension behavior is needed. Use an extension when registration depends on runtime discovery, custom authentication, or code shared with other extension features.
81
+
82
+ ### Register mixed-operation models
83
+
84
+ A mixed-operation provider can register non-chat models and their implementations together:
33
85
 
34
86
  ```typescript
35
87
  knightcode.registerProvider("media-tools", {
@@ -51,7 +51,7 @@ Reload replaces the extension runtime, so code after `await ctx.reload()` must n
51
51
 
52
52
  <a id="understand-the-lifecycle"></a>
53
53
 
54
- ## Respect the runtime lifecycle
54
+ ## Understand the runtime lifecycle
55
55
 
56
56
  The factory can be synchronous or asynchronous. KnightCode waits for an asynchronous factory before startup continues, allowing it to fetch configuration or register providers needed during startup.
57
57
 
@@ -59,13 +59,95 @@ Do not start processes, sockets, watchers, or timers in the factory because some
59
59
  Start long-lived resources from `session_start` or from the command or tool that needs them.
60
60
  Close session-scoped resources from an idempotent `session_shutdown` handler.
61
61
 
62
- A run proceeds from input and `before_agent_start`, through model, message, and tool events, to `agent_end`.
63
- KnightCode counts as busy while a run starts, including the compaction check and `before_agent_start`, so messages sent meanwhile go into the starting run.
64
- Automatic retries, recovery, compaction, or queued work can continue afterward.
62
+ A normal prompt follows this hook sequence:
63
+
64
+ ```mermaid
65
+ flowchart TD
66
+ Input["input"] --> Before["before_agent_start"]
67
+ Before --> AgentStart["agent_start"]
68
+ AgentStart --> TurnStart["turn_start"]
69
+ TurnStart --> Context["context"]
70
+ Context --> ContextSystem["context_with_system"]
71
+ ContextSystem --> Headers["before_provider_headers"]
72
+ Headers --> Request["before_provider_request"]
73
+ Request --> Response["after_provider_response"]
74
+ Response --> Stream["provider_stream_event and assistant message events"]
75
+ Stream --> ToolDecision{"Assistant requested tools?"}
76
+ ToolDecision -->|yes| ToolStart["tool_execution_start"]
77
+ ToolStart --> ToolCall["tool_call"]
78
+ ToolCall --> Execute["execute and tool_execution_update"]
79
+ Execute --> ToolResult["tool_result"]
80
+ ToolResult --> ToolEnd["tool_execution_end"]
81
+ ToolEnd --> TurnEnd["turn_end"]
82
+ ToolDecision -->|no| TurnEnd
83
+ TurnEnd --> MoreTurns{"Another model turn required?"}
84
+ MoreTurns -->|yes| TurnStart
85
+ MoreTurns -->|no| AgentEnd["agent_end"]
86
+ AgentEnd --> MoreRuns{"Retry, recovery, compaction retry, or queued work?"}
87
+ MoreRuns -->|yes| AgentStart
88
+ MoreRuns -->|no| BeforeSettle["agent_before_settle"]
89
+ BeforeSettle --> Continue{"Continuation requested?"}
90
+ Continue -->|yes| AgentStart
91
+ Continue -->|no| Settled["agent_settled"]
92
+ ```
93
+
94
+ The lifecycle involves these event groups:
95
+
96
+ | Area | Events |
97
+ |---|---|
98
+ | Input preparation | `input`, `before_agent_start` |
99
+ | Agent run | `agent_start`, `agent_end` |
100
+ | Model turn | `turn_start`, `context`, `context_with_system`, `turn_end` |
101
+ | Provider call | `before_provider_headers`, `before_provider_request`, `after_provider_response`, `provider_stream_event` |
102
+ | Message lifecycle | `message_start`, `message_update`, `message_end` |
103
+ | Tool execution | `tool_execution_start`, `tool_call`, `tool_execution_update`, `tool_result`, `tool_execution_end` |
104
+ | Settlement | `agent_before_settle`, `agent_settled` |
105
+
106
+ KnightCode counts as busy while a run starts, including the compaction check and `before_agent_start`, so messages sent meanwhile go into the starting run. Message lifecycle events also cover user and tool-result messages; the diagram places only the assistant stream where it occurs in each model turn.
107
+
108
+ Tool hooks run for each tool call, and one assistant response can start another turn by returning tool calls. Provider hooks run only when that transport exposes the corresponding stage. See the exported declarations in [`extensions/types.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/extensions/types.ts) for exact event payloads and result types.
109
+
110
+ Session startup and replacement follow a separate lifecycle:
111
+
112
+ ```mermaid
113
+ flowchart TD
114
+ Startup["Process startup"] --> Trust["project_trust when needed"]
115
+ Trust --> SessionStart["session_start"]
116
+ Switch["/new or /resume"] --> BeforeSwitch["session_before_switch"]
117
+ Fork["/fork or /clone"] --> BeforeFork["session_before_fork"]
118
+ BeforeSwitch --> Shutdown["session_shutdown"]
119
+ BeforeFork --> Shutdown
120
+ Reload["reload"] --> Shutdown
121
+ Shutdown --> Replacing{"Replacing the runtime?"}
122
+ Replacing -->|yes| Replacement["load replacement extension runtime"]
123
+ Replacement --> SessionStart
124
+ Replacing -->|no| Stop["process exits"]
125
+ SessionStart --> Discover["resources_discover"]
126
+ ```
127
+
128
+ `project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory. Retries, recovery, compaction, and queued messages can start another agent run after `agent_end`, so `agent_end` is not a final-idle signal. Reload and session replacement invalidate the old runtime. Code after `await ctx.reload()` still belongs to the old runtime and must not reuse its session-bound state.
129
+
130
+ ### Choose an event by intent
131
+
132
+ | Goal | Event |
133
+ |---|---|
134
+ | Inspect, transform, or consume raw user input | `input` |
135
+ | Change prompt sections, active tools, or add context before a run | `before_agent_start` |
136
+ | Observe one low-level agent run | `agent_start`, `agent_end` |
137
+ | Act after one model response and its tool calls | `turn_end` |
138
+ | Filter conversation messages for one provider request | `context` |
139
+ | Transform the complete transcript, including system messages | `context_with_system` |
140
+ | Change request headers or the serialized provider payload | `before_provider_headers`, `before_provider_request` |
141
+ | Observe provider response metadata or parsed stream events | `after_provider_response`, `provider_stream_event` |
142
+ | Authorize or modify a tool call | `tool_call` |
143
+ | Redact, annotate, or replace a tool result | `tool_result` |
144
+ | Append final entries or request one last continuation | `agent_before_settle` |
145
+ | Run notification work after automatic processing has stopped | `agent_settled` |
146
+ | Initialize or release session-scoped resources | `session_start`, `session_shutdown` |
147
+
65
148
  <a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
66
149
 
67
- `agent_before_settle` is the final actionable boundary: it can append entries and request one continuation.
68
- `agent_settled` is final and notification-only; use it when an integration needs to know KnightCode will not continue automatically.
150
+ Use `agent_before_settle` when an extension must append entries or request one final continuation. Use `agent_settled` for notification-only work that should run after KnightCode has no automatic continuation remaining.
69
151
 
70
152
  <a id="extensionapi-methods"></a>
71
153
 
@@ -101,6 +183,19 @@ Use each event’s declared result type rather than assuming every return value
101
183
 
102
184
  Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
103
185
 
186
+ #### Understand handler composition
187
+
188
+ | Pattern | Behavior |
189
+ |---|---|
190
+ | Notification | Return values are ignored. Use the event for observation only. |
191
+ | In-place mutation | Later handlers see changes to values such as `before_provider_headers.headers`, `before_agent_start.systemPromptOptions`, and `tool_call.input`. |
192
+ | Chained transformation | Later handlers receive the value returned by earlier `input`, `context`, `context_with_system`, `message_end`, `tool_result`, and `before_provider_request` handlers. |
193
+ | Gate | A handled input, blocked tool call, cancelled session operation, or handled `user_bash` command stops that operation's normal fallback path. |
194
+ | Actionable boundary | Each `turn_end` or `agent_before_settle` handler sees the entries and continuation decision proposed so far. |
195
+ | Last override | The last `cache_warming_decision` handler that returns an action wins. |
196
+
197
+ Notification handlers should not perform slow work on a streaming event. Transform handlers should preserve fields they do not intentionally own, and gate handlers should fail closed when their safety decision cannot be made.
198
+
104
199
  `before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. `event.messageType` says what started the run: `"user"` for a prompt or `knightcode.sendUserMessage()`, with `prompt` and `images`; `"custom"` for `knightcode.sendMessage(..., { triggerTurn: true })`, with the starting `message` and no `prompt`. A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages. Prefer changing prompt sections, selected tools, or guidelines so KnightCode can append a transcript delta. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for that run while the transcript continues recording the structured sections. Providers receive the forced text as their leading system prompt.
105
200
 
106
201
  `message_end` can replace a finalized message while preserving its role. `tool_call` can mutate input or block execution. `tool_result` handlers compose, with each handler seeing prior changes.
@@ -308,7 +403,18 @@ Use `ctx.shutdown()` to request an orderly process shutdown.
308
403
 
309
404
  ## Examples and reference
310
405
 
311
- The checked [extension examples](../examples/extensions/) cover tools, lifecycle events, commands, flags, shortcuts, state, rendering, providers, OAuth, remote execution, and terminal components.
312
- Start with the smallest example matching your integration point.
313
-
314
- Use [Custom Providers](custom-provider.md) for model-service integrations, [Terminal UI](tui.md) for custom components, and [KnightCode Packages](packages.md) to install or distribute extensions with other resources.
406
+ The checked [extension examples](../examples/extensions/) are the implementation reference. Start with the smallest example matching the behavior you need:
407
+
408
+ | Goal | Start with | Why |
409
+ |---|---|---|
410
+ | Confirm or block tool calls | [`permission-gate.ts`](../examples/extensions/permission-gate.ts) | Combines `tool_call`, mode-aware UI, and fail-closed behavior. |
411
+ | Modify prompt sections for a run | [`prompt-customizer.ts`](../examples/extensions/prompt-customizer.ts) | Uses structured prompt options instead of replacing the complete prompt. |
412
+ | Keep branch-aware tool state | [`todo.ts`](../examples/extensions/todo.ts) | Reconstructs state from persisted entries and renders it in the TUI. |
413
+ | Register tools after startup | [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts) | Shares registration logic between lifecycle and command handlers. |
414
+ | Run cancellable model work from a command | [`qna.ts`](../examples/extensions/qna.ts) | Combines nested model calls, cancellation, and custom UI. |
415
+ | Replace the main editor | [`modal-editor.ts`](../examples/extensions/modal-editor.ts) | Extends `CustomEditor` while preserving application controls. |
416
+ | Run finalization at shutdown | [`auto-commit-on-exit.ts`](../examples/extensions/auto-commit-on-exit.ts) | Uses the session shutdown hook for finalization work. |
417
+ | Route built-in tools to another machine | [`ssh.ts`](../examples/extensions/ssh.ts) | Reuses tool operation interfaces instead of recreating tool contracts. |
418
+ | Add OAuth and provider-specific streaming | [`custom-provider-gitlab-duo/`](../examples/extensions/custom-provider-gitlab-duo/) | Shows a complete provider integration while delegating supported protocols. |
419
+
420
+ Use [Custom Providers](custom-provider.md) for model-service integrations, [Terminal UI](tui.md) for custom components, and [KnightCode Packages](packages.md) to install or distribute extensions with other resources. Use the exported declarations for exact signatures, payloads, and result schemas; this guide focuses on lifecycle choices, composition, and durable implementation patterns.