@knightcodeai/cli 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/bundle/chunks/anthropic-messages-34POCEPV.js +6 -0
  3. package/dist/bundle/chunks/azure-openai-responses-ZZQJJY7B.js +2 -0
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  5. package/dist/bundle/chunks/{chunk-3PSTVJEH.js → chunk-2QXUEOVY.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-L2XRQUGK.js → chunk-3QKQRXCZ.js} +4 -4
  7. package/dist/bundle/chunks/chunk-AA6MLWWY.js +2 -0
  8. package/dist/bundle/chunks/{chunk-NGWSYXD5.js → chunk-BTRAS32C.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-GCXF7ZNR.js → chunk-C62RVFZT.js} +2 -2
  10. package/dist/bundle/chunks/{chunk-MXIWLMNT.js → chunk-CCP7VAJU.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-XILUO467.js → chunk-GPHSXYPT.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-FG6M5B3F.js → chunk-IIS4JDFO.js} +153 -119
  13. package/dist/bundle/chunks/{chunk-3B66IKOZ.js → chunk-JSLSFYBX.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-HRZGVTRM.js → chunk-KRDGPCZM.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-SLWTIEJK.js → chunk-OQHO44L6.js} +1 -1
  16. package/dist/bundle/chunks/chunk-R7X2RAGR.js +30 -0
  17. package/dist/bundle/chunks/{chunk-T6M3FJYR.js → chunk-RZDCZFG7.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-3VVG5HD5.js → chunk-T47GKPON.js} +2 -2
  19. package/dist/bundle/chunks/chunk-UU4A4NV5.js +2 -0
  20. package/dist/bundle/chunks/{cli-AMSWLH7A.js → cli-SIPOI5P3.js} +1 -1
  21. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-QHP5M5HC.js +2 -0
  22. package/dist/bundle/chunks/{easter-egg-3d-VH6SGOZS.js → easter-egg-3d-BVWLABZN.js} +1 -1
  23. package/dist/bundle/chunks/{execute-4UQWU4SD.js → execute-6UIHV2DR.js} +1 -1
  24. package/dist/bundle/chunks/github-copilot.js +1 -1
  25. package/dist/bundle/chunks/google-generative-ai-RFCCCXK6.js +2 -0
  26. package/dist/bundle/chunks/google-vertex-WN3JAZCD.js +2 -0
  27. package/dist/bundle/chunks/knightcode-messages-57CV36UV.js +8 -0
  28. package/dist/bundle/chunks/{llama-cpp-classify-HRPRKOZA.js → llama-cpp-classify-FEWC5ZIH.js} +2 -2
  29. package/dist/bundle/chunks/{mistral-conversations-NUSSE6NX.js → mistral-conversations-GIGX6BW6.js} +1 -1
  30. package/dist/bundle/chunks/openai-codex-responses-3Y7R752C.js +10 -0
  31. package/dist/bundle/chunks/openai-completions-HBXENZUJ.js +7 -0
  32. package/dist/bundle/chunks/{openai-decisions-ENPSYANO.js → openai-decisions-MLI3SMFN.js} +1 -1
  33. package/dist/bundle/chunks/openai-responses-BNRA5YTD.js +4 -0
  34. package/dist/bundle/chunks/openrouter-images-JWVDFQJ4.js +2 -0
  35. package/dist/bundle/chunks/{runtime-IU2Z5WWF.js → runtime-AROIXIAV.js} +1 -1
  36. package/dist/bundle/chunks/typesafe-system-one-5LELZY2F.js +2 -0
  37. package/dist/bundle/chunks/{virtual-modules-AK4BYDR6.js → virtual-modules-IYKQM2DL.js} +1 -1
  38. package/dist/bundle/cli-runtime.js +1 -1
  39. package/docs/app-server.md +288 -8
  40. package/docs/app-server.schema.json +5414 -1636
  41. package/docs/desktop.md +19 -4
  42. package/docs/settings.md +53 -0
  43. package/package.json +1 -1
  44. package/dist/bundle/chunks/anthropic-messages-VD2GN7C4.js +0 -6
  45. package/dist/bundle/chunks/azure-openai-responses-6IJ5JZ3Y.js +0 -2
  46. package/dist/bundle/chunks/chunk-4DOSUUX3.js +0 -30
  47. package/dist/bundle/chunks/chunk-CRLO4X52.js +0 -2
  48. package/dist/bundle/chunks/chunk-HHWP56PR.js +0 -2
  49. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-JBMTTHVI.js +0 -2
  50. package/dist/bundle/chunks/google-generative-ai-QBWYWMCA.js +0 -2
  51. package/dist/bundle/chunks/google-vertex-4KVZWEAI.js +0 -2
  52. package/dist/bundle/chunks/knightcode-messages-3GNOTMSI.js +0 -8
  53. package/dist/bundle/chunks/openai-codex-responses-66UQNGWB.js +0 -10
  54. package/dist/bundle/chunks/openai-completions-QTYKORY2.js +0 -7
  55. package/dist/bundle/chunks/openai-responses-JSX72BKV.js +0 -3
  56. package/dist/bundle/chunks/openrouter-images-ZI7LLZ4Y.js +0 -2
  57. package/dist/bundle/chunks/typesafe-system-one-ETHWOYKC.js +0 -2
@@ -0,0 +1,7 @@
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{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{shortHash}from"./chunk-HUQB436V.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-GPHSXYPT.js";import{sanitizeSurrogates}from"./chunk-B2FT7RH5.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-T47GKPON.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import{parseStreamingJson,parseToolCallArguments}from"./chunk-FA32X2UJ.js";import{AssistantMessageEventStream}from"./chunk-ETOMYYZC.js";import{getIdentityHeaders}from"./chunk-UU4A4NV5.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?.identity,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
+ ${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,identity,fetch,sessionId,compat=getCompat(model)){let headers={...getIdentityHeaders(model,identity),...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?"additions":"none"),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?"additions":"none"),instructionRole=model.reasoning&&compat.supportsDeveloperRole?"developer":"system",lastRole=null,systemIndex=0;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=systemIndex++>=transcriptTools.foldedSystemMessages?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
+
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(`
6
+ `))}}else assistantText.length>0&&(assistantMsg.content=assistantText);toolCalls.length>0&&(assistantMsg.tool_calls=toolCalls.map(tc=>{let customInputProperty=options?.grammarToolInputProperties?.get(tc.name);return customInputProperty!==void 0?{id:tc.id,type:"custom",custom:{name:tc.name,input:sanitizeSurrogates(getGrammarToolInput(tc.name,tc.arguments,customInputProperty))}}:{id:tc.id,type:"function",function:{name:tc.name,arguments:JSON.stringify(tc.arguments)}}})),preservedReasoningDetails&&(assistantMsg.reasoning_details=preservedReasoningDetails),compat.requiresReasoningContentOnAssistantMessages&&model.reasoning&&assistantMsg.reasoning_content===void 0&&(assistantMsg.reasoning_content="");let content=assistantMsg.content;if(!(content!=null&&content.length>0)&&!assistantMsg.tool_calls)continue;params.push(assistantMsg)}else if(msg.role==="toolResult"){let imageBlocks=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";j++){let toolMsg=transformedMessages[j],textResult=toolMsg.content.filter(isTextContentBlock).map(block=>block.text).join(`
7
+ `),hasImages=toolMsg.content.some(c=>c.type==="image"),toolResultText=textResult.trim().length>0?textResult:hasImages?"(see attached image)":"(no tool output)",toolResultMsg={role:"tool",content:sanitizeSurrogates(toolResultText),tool_call_id:toolMsg.toolCallId};if(compat.requiresToolResultName&&toolMsg.toolName&&(toolResultMsg.name=toolMsg.toolName),params.push(toolResultMsg),hasImages&&model.input.includes("image"))for(let block of toolMsg.content)isImageContentBlock(block)&&imageBlocks.push({type:"image_url",image_url:{url:`data:${block.mimeType};base64,${block.data}`}})}i=j-1,imageBlocks.length>0?(compat.requiresAssistantAfterToolResult&&params.push({role:"assistant",content:"I have processed the tool results."}),params.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...imageBlocks]}),lastRole="user"):lastRole="toolResult";continue}lastRole=msg.role}return params}function convertTools(tools,compat){return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,compat.supportsOpenAIGrammarTools);if(grammar)return{type:"custom",custom:{name:tool.name,description:tool.description,format:{type:"grammar",grammar:{syntax:grammar.format,definition:grammar.definition}}}};let strict=resolveJsonSchemaStrictSampling(tool,compat.supportsStrictMode!==!1);return{type:"function",function:{name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict),...compat.supportsStrictMode!==!1&&{strict:strict??!1}}}})}function parseChunkUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,cacheReadTokens=rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.prompt_cache_hit_tokens??rawUsage.cached_tokens??0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens||0,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),outputTokens=rawUsage.completion_tokens||0,usage={input,output:outputTokens,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens,reasoning:rawUsage.completion_tokens_details?.reasoning_tokens||0,totalTokens:input+outputTokens+cacheReadTokens+cacheWriteTokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}function mapStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${reason}`}}}function detectCompat(model){let provider=model.provider,baseUrl=model.baseUrl,isZai=provider==="zai"||provider==="zai-coding-cn"||baseUrl.includes("api.z.ai")||baseUrl.includes("open.bigmodel.cn"),isTogether=provider==="together"||baseUrl.includes("api.together.ai")||baseUrl.includes("api.together.xyz"),isMoonshot=provider==="moonshotai"||provider==="moonshotai-cn"||baseUrl.includes("api.moonshot."),isOpenRouter=provider==="openrouter"||baseUrl.includes("openrouter.ai"),isCloudflareWorkersAI=provider==="cloudflare-workers-ai"||baseUrl.includes("api.cloudflare.com"),isCloudflareAiGateway=provider==="cloudflare-ai-gateway"||baseUrl.includes("gateway.ai.cloudflare.com"),isNvidia=provider==="nvidia"||baseUrl.includes("integrate.api.nvidia.com"),isAntLing=provider==="ant-ling"||baseUrl.includes("api.ant-ling.com"),isCerebras=provider==="cerebras"||baseUrl.includes("cerebras.ai"),isDeepSeek=provider==="deepseek"||baseUrl.toLowerCase().includes("deepseek.com"),isNonStandard=isNvidia||isCerebras||provider==="xai"||baseUrl.includes("api.x.ai")||isTogether||baseUrl.includes("chutes.ai")||isDeepSeek||isZai||isMoonshot||provider==="opencode"||baseUrl.includes("opencode.ai")||isCloudflareWorkersAI||isCloudflareAiGateway||isAntLing,useMaxTokens=baseUrl.includes("chutes.ai")||isDeepSeek||isMoonshot||isCloudflareAiGateway||isTogether||isNvidia||isAntLing||isZai,isGrok=provider==="xai"||baseUrl.includes("api.x.ai"),isOpenRouterDeveloperRoleModel=isOpenRouter&&(model.id.startsWith("anthropic/")||model.id.startsWith("openai/")),cacheControlFormat=provider==="openrouter"&&model.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!isNonStandard,supportsDeveloperRole:isOpenRouterDeveloperRoleModel||!isNonStandard&&!isOpenRouter,supportsReasoningEffort:!isGrok&&!isZai&&!isMoonshot&&!isTogether&&!isCloudflareAiGateway&&!isNvidia&&!isAntLing,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:useMaxTokens?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:isDeepSeek,thinkingFormat:isDeepSeek?"deepseek":isZai?"zai":isTogether?"together":isAntLing?"ant-ling":isOpenRouter?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat,sendSessionAffinityHeaders:isOpenRouter,sessionAffinityFormat:isOpenRouter?"openrouter":"openai",supportsLongCacheRetention:!(isTogether||isCloudflareWorkersAI||isCloudflareAiGateway||isNvidia||isAntLing)}}function getCompat(model){let detected=detectCompat(model);return model.compat?{supportsStore:model.compat.supportsStore??detected.supportsStore,supportsDeveloperRole:model.compat.supportsDeveloperRole??detected.supportsDeveloperRole,supportsReasoningEffort:model.compat.supportsReasoningEffort??detected.supportsReasoningEffort,supportsUsageInStreaming:model.compat.supportsUsageInStreaming??detected.supportsUsageInStreaming,supportsFinishReason:model.compat.supportsFinishReason??detected.supportsFinishReason,maxTokensField:model.compat.maxTokensField??detected.maxTokensField,requiresToolResultName:model.compat.requiresToolResultName??detected.requiresToolResultName,requiresAssistantAfterToolResult:model.compat.requiresAssistantAfterToolResult??detected.requiresAssistantAfterToolResult,requiresThinkingAsText:model.compat.requiresThinkingAsText??detected.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:model.compat.requiresReasoningContentOnAssistantMessages??detected.requiresReasoningContentOnAssistantMessages,thinkingFormat:model.compat.thinkingFormat??detected.thinkingFormat,openRouterRouting:model.compat.openRouterRouting??{},vercelGatewayRouting:model.compat.vercelGatewayRouting??detected.vercelGatewayRouting,chatTemplateKwargs:model.compat.chatTemplateKwargs??detected.chatTemplateKwargs,chatTemplateArgs:model.compat.chatTemplateArgs??detected.chatTemplateArgs,zaiToolStream:model.compat.zaiToolStream??detected.zaiToolStream,supportsThinkingTokenBudget:model.compat.supportsThinkingTokenBudget??detected.supportsThinkingTokenBudget,thinkingTokenBudgetField:model.compat.thinkingTokenBudgetField??detected.thinkingTokenBudgetField,supportsStrictMode:model.compat.supportsStrictMode??detected.supportsStrictMode,supportsOpenAIGrammarTools:model.compat.supportsOpenAIGrammarTools??detected.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:model.compat.supportsMidConvoSystemMessages??detected.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:model.compat.supportsMidConvoToolAdditions??detected.supportsMidConvoToolAdditions,cacheControlFormat:model.compat.cacheControlFormat??detected.cacheControlFormat,sendSessionAffinityHeaders:model.compat.sendSessionAffinityHeaders??detected.sendSessionAffinityHeaders,sessionAffinityFormat:model.compat.sessionAffinityFormat??detected.sessionAffinityFormat,supportsLongCacheRetention:model.compat.supportsLongCacheRetention??detected.supportsLongCacheRetention,vllmPriority:model.compat.vllmPriority}:detected}export{convertMessages,stream,streamSimple};
@@ -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-CRLO4X52.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-3VVG5HD5.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-AA6MLWWY.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-T47GKPON.js";import"./chunk-ETOMYYZC.js";import"./chunk-UU4A4NV5.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};
@@ -0,0 +1,4 @@
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,getResponsesToolSupport,processResponsesStream}from"./chunk-OQHO44L6.js";import{OpenAI}from"./chunk-ZW7FVRHT.js";import{clampOpenAIPromptCacheKey}from"./chunk-N6VDWLND.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import"./chunk-HUQB436V.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-GPHSXYPT.js";import"./chunk-B2FT7RH5.js";import{headersToRecord}from"./chunk-DVFCXHT4.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-T47GKPON.js";import{getProviderEnvValue}from"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import{AssistantMessageEventStream}from"./chunk-ETOMYYZC.js";import{getIdentityHeaders}from"./chunk-UU4A4NV5.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",CHATGPT_WORKSPACE_LIMIT_HINT="You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com \u2192 Workspace \u2192 Usage limits.",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?.identity,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`);errorMessage.includes("subscription_sharing_usage_limit_exceeded")?output.errorMessage=`${errorMessage}
3
+ Check your ChatGPT usage: ${CHATGPT_USAGE_URL}`:errorMessage.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?output.errorMessage=`${errorMessage}
4
+ ${CHATGPT_WORKSPACE_LIMIT_HINT}`:output.errorMessage=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,identity,fetch,sessionId){let compat=getCompat(model),headers={...getIdentityHeaders(model,identity),...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,getResponsesToolSupport(compat)),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};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
+ import{OpenAI}from"./chunk-ZW7FVRHT.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{sanitizeSurrogates}from"./chunk-B2FT7RH5.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-DVFCXHT4.js";import{getIdentityHeaders}from"./chunk-UU4A4NV5.js";import"./chunk-AHB7JV5B.js";var generateImages=async(model,context,options)=>{let output={api:model.api,provider:model.provider,model:model.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers,options?.fetch,options?.identity),params=buildParams(model,context),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:response,response:rawResponse}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:rawResponse.status,headers:headersToRecord(rawResponse.headers)},model);let imageResponse=response;output.responseId=imageResponse.id,imageResponse.usage&&(output.usage=parseUsage(imageResponse.usage,model));let choice=imageResponse.choices[0];if(choice){let content=choice.message.content;typeof content=="string"&&content.length>0&&output.output.push({type:"text",text:content});for(let image of choice.message.images??[]){let imageUrl=typeof image.image_url=="string"?image.image_url:image.image_url?.url;if(!imageUrl?.startsWith("data:"))continue;let matches=imageUrl.match(/^data:([^;]+);base64,(.+)$/);matches&&output.output.push({type:"image",mimeType:matches[1],data:matches[2]})}}return output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),output}};function createClient(model,apiKey,optionsHeaders,fetch,identity){return new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:providerHeadersToRecord(getIdentityHeaders(model,identity),model.headers,optionsHeaders)})}function buildParams(model,context){let content=context.input.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});return{model:model.id,messages:[{role:"user",content}],stream:!1,modalities:model.output.includes("text")?["image","text"]:["image"]}}function parseUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,reportedCachedTokens=rawUsage.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens||0,cacheReadTokens=cacheWriteTokens>0?Math.max(0,reportedCachedTokens-cacheWriteTokens):reportedCachedTokens,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),output=rawUsage.completion_tokens||0,usage={input,output,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens,totalTokens:input+output+cacheReadTokens+cacheWriteTokens,cost:{input:model.cost.input/1e6*input,output:model.cost.output/1e6*output,cacheRead:model.cost.cacheRead/1e6*cacheReadTokens,cacheWrite:model.cost.cacheWrite/1e6*cacheWriteTokens,total:0}};return usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage}export{generateImages};
@@ -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-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};
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-JSLSFYBX.js";import"./chunk-BTRAS32C.js";import"./chunk-2QXPCKUQ.js";import"./chunk-BPNRVFVQ.js";import"./chunk-AHB7JV5B.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
2
+ import{classifySystemOne}from"./chunk-2QXUEOVY.js";import{isRecord}from"./chunk-AA6MLWWY.js";import"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-T47GKPON.js";import"./chunk-ETOMYYZC.js";import"./chunk-UU4A4NV5.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-FG6M5B3F.js";import"./chunk-T6M3FJYR.js";import{all_exports,compat_exports,compile_exports,value_exports}from"./chunk-4DOSUUX3.js";import"./chunk-L2XRQUGK.js";import{src_exports}from"./chunk-GCXF7ZNR.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{models_exports}from"./chunk-3VVG5HD5.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/models":models_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-IIS4JDFO.js";import"./chunk-RZDCZFG7.js";import{all_exports,compat_exports,compile_exports,value_exports}from"./chunk-R7X2RAGR.js";import"./chunk-BTRAS32C.js";import"./chunk-3QKQRXCZ.js";import{src_exports}from"./chunk-C62RVFZT.js";import{build_exports}from"./chunk-CCP7VAJU.js";import"./chunk-2QXPCKUQ.js";import"./chunk-KQKUEQJA.js";import"./chunk-BPNRVFVQ.js";import"./chunk-NDQ5OW6U.js";import"./chunk-O6JSP6YG.js";import"./chunk-HSL72VZI.js";import"./chunk-AANBXVWQ.js";import{models_exports}from"./chunk-T47GKPON.js";import"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import"./chunk-ETOMYYZC.js";import"./chunk-UU4A4NV5.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/models":models_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-FG6M5B3F.js";import"./chunks/chunk-T6M3FJYR.js";import"./chunks/chunk-4DOSUUX3.js";import"./chunks/chunk-L2XRQUGK.js";import"./chunks/chunk-GCXF7ZNR.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-3VVG5HD5.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-IIS4JDFO.js";import"./chunks/chunk-RZDCZFG7.js";import"./chunks/chunk-R7X2RAGR.js";import"./chunks/chunk-BTRAS32C.js";import"./chunks/chunk-3QKQRXCZ.js";import"./chunks/chunk-C62RVFZT.js";import"./chunks/chunk-CCP7VAJU.js";import"./chunks/chunk-2QXPCKUQ.js";import"./chunks/chunk-KQKUEQJA.js";import{APP_NAME}from"./chunks/chunk-BPNRVFVQ.js";import"./chunks/chunk-NDQ5OW6U.js";import"./chunks/chunk-O6JSP6YG.js";import"./chunks/chunk-HSL72VZI.js";import"./chunks/chunk-AANBXVWQ.js";import"./chunks/chunk-T47GKPON.js";import"./chunks/chunk-BRKUE2MD.js";import"./chunks/chunk-FA32X2UJ.js";import"./chunks/chunk-ETOMYYZC.js";import"./chunks/chunk-UU4A4NV5.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));
@@ -72,9 +72,10 @@ send a subscriber-only `warning` with `threadId`.
72
72
 
73
73
  Threads and list summaries include `createdAt` (header creation time) and
74
74
  optional `forkedFromId` (the parent's header ID, not a UUID inferred from its
75
- filename). List summaries use file modification time for `updatedAt`; loaded
76
- threads use the latest entry time, falling back to the header. Their `status`
77
- is one of:
75
+ filename). A loaded thread also carries `sessionFile`, the session file's path,
76
+ once it has been saved. List summaries use file modification time for
77
+ `updatedAt`; loaded threads use the latest entry time, falling back to the
78
+ header. Their `status` is one of:
78
79
 
79
80
  - `{type: "notLoaded"}`
80
81
  - `{type: "idle"}`
@@ -159,9 +160,12 @@ lands in a later turn. A steer cannot be taken back once accepted.
159
160
  input starts a turn of its own once the thread is idle, oldest first; on an idle
160
161
  thread it starts at once. Until it starts it is removable with
161
162
  `turn/queue/remove`. A queued input that fails to start (no model, signed out) is
162
- dropped with an `error` notification. `turn/queue/updated` sends
163
- `{threadId, steering: [text], followUp: [{id, text}]}`: steers the agent has not
164
- delivered yet, and the queued inputs.
163
+ dropped with an `error` notification carrying its `clientMessageId`, if it had
164
+ one. `turn/queue/updated` sends
165
+ `{threadId, steering: [text], followUp: [{id, text, attachments?}]}`: steers the
166
+ agent has not delivered yet, and the queued inputs. `text` is the user's own (not
167
+ a prompt composed with review comments); `attachments` counts the images and
168
+ review comments an input carries that its text alone does not.
165
169
 
166
170
  `turn/interrupt` accepts optional `turnId`; a supplied stale ID returns
167
171
  `turnMismatch`, while omitting it retains interrupt-current behavior. It drops
@@ -281,6 +285,86 @@ The most recent initiating subscriber is asked first. Disconnect or unsubscribe
281
285
  cancels that attempt and migrates it to another subscriber; no subscribers means
282
286
  cancel. `serverRequest/cancelled` withdraws an outstanding request.
283
287
 
288
+ ## Dialogs
289
+
290
+ What KnightCode asks the user mid-turn reaches a desktop connection as a server
291
+ request, asked the way approvals are; the thread reports `waitingOn: ["dialog"]`
292
+ meanwhile.
293
+
294
+ `item/toolCall/requestUserInput` carries `ask_user`'s questions, all at once,
295
+ with the `itemId` of the call asking, so a client can move back and forth
296
+ between them before answering. Each question has an `id`, its text and its
297
+ options (`label`, `description`); a label ending in `(Recommended)` is the
298
+ recommended one. Reply `{"answers": {"<id>": {"label": "..."}}}` with the
299
+ chosen option's exact label and an optional `note`, or `{"other": "..."}` for
300
+ the user's own answer; leave out a skipped question. `{}` dismisses the
301
+ questions and stops the turn.
302
+
303
+ `ui/dialog` carries the rest, such as the classifier gate's confirmation of a
304
+ risky call and plan mode's review. `kind` says which: a select carries
305
+ `options`, a confirm its `message`, an input its `placeholder`, an editor its
306
+ `prefill`. Reply with `{"value": "..."}` for a select, input or editor,
307
+ `{"confirmed": true}` for a confirm, or `{}` to cancel.
308
+
309
+ Notices such as "Downloaded model" arrive as the notification `ui/notify` with
310
+ a `level` of `info`, `warning` or `error`. Widgets, status, header, footer
311
+ and custom components draw only in the terminal and do nothing here. Threads a
312
+ terminal-mode connection loads have no dialogs yet.
313
+
314
+ ## Workspaces, diffs and git
315
+
316
+ A thread runs in a workspace: the user's checkout (`{mode: "local"}`), or a git
317
+ worktree of its own (`{mode: "worktree"}`), as in the Codex desktop app.
318
+
319
+ `thread/start {cwd, workspace: {mode: "worktree", baseRef?, carryLocalChanges?, environment?}}`
320
+ creates a worktree on a **detached `HEAD`** at `baseRef` (default:
321
+ the checkout's `HEAD`) under `<worktrees.root>/<4 hex digits>/<repository name>`
322
+ and runs the thread there, in the same subdirectory the `cwd` had. No branch is
323
+ created until `git/branch/create` or a handoff makes one. `carryLocalChanges`
324
+ brings the checkout's uncommitted changes (untracked files included, ignored
325
+ files not) along as uncommitted edits. Creation runs no hook, filter or user
326
+ code, so a failed creation leaves nothing behind. A start whose `cwd` is inside
327
+ a managed worktree is a new thread in that worktree.
328
+
329
+ `thread/workspace/progress {threadId, phase, output}` streams the output of an
330
+ environment's setup or cleanup script to the connection that asked. Every
331
+ `Thread` carries `workspace`; `ThreadSummary.workspaceMode` marks worktree
332
+ threads in listings.
333
+
334
+ Diffs come in Codex's Changes scopes: `lastTurn`, `uncommitted` (the default),
335
+ `unstaged`, `staged`, `committed` and `branch`. Each hunk has a content-hash id;
336
+ an action naming a hunk that changed since it was read answers `gitConflict`
337
+ with `data.reason: "diffChanged"`. Files changed while a turn ran are reported
338
+ by `turn/diff/updated {threadId, turnId, files}` after `turn/completed`, each
339
+ file as `{path, additions, deletions}`: the net line totals between the working
340
+ tree before and after the turn. A read-back turn carries the same list as
341
+ `Turn.files`. This
342
+ means "changed while the turn ran", not "changed by the turn": an edit another
343
+ local thread or an editor made meanwhile is in the list too. A worktree thread
344
+ is the only writer in its worktree, so its list is its own.
345
+
346
+ Review comments are drafts the client keeps. They travel with the next
347
+ `turn/start` or `turn/queue/add` as `comments`; the server quotes the commented
348
+ lines from the diff the user reviewed, and the user item shows the comments
349
+ next to the typed text.
350
+
351
+ **Reverting an added file deletes it**, an untracked one included. Clients
352
+ confirm with the user before a revert that removes files.
353
+
354
+ `thread/handoff` moves a chat and its uncommitted changes between its worktree
355
+ and the main checkout. The destination must be clean: "Stash or commit your
356
+ local changes to hand off." Archiving a thread deletes its worktree after a
357
+ snapshot, kept as `refs/knightcode/snapshots/<bucket>/<time>`, and
358
+ `thread/worktree/restore` rebuilds it. Past `worktrees.keep` worktrees, the
359
+ least recently used are pruned the same way. Outside a git repository, diff and
360
+ git methods answer `notGitRepo`.
361
+
362
+ `gitConflict` errors carry `data.reason`: `diffChanged`, `patchFailed`,
363
+ `concurrentChange`, `pushRejected`, `localChanges`, `operationInProgress`,
364
+ `branchExists`, `recoveryRequired`, `worktreeDeleted`, `worktreeMissing`,
365
+ `worktreeInUse` or `submodules`, with `paths`, `output` or
366
+ `recoveryInstructions` where they apply.
367
+
284
368
  ## Method reference
285
369
 
286
370
  All methods require the handshake. Common errors are `notInitialized`,
@@ -300,12 +384,13 @@ Errors: `threadNotFound`.
300
384
 
301
385
  ### `config/read`
302
386
 
303
- Params: optional `{cwd}`. Result: `{settings, origins, versions, errors}`.
387
+ Params: optional `{cwd}`. Result: `{settings, defaults, origins, versions, paths, errors}`.
304
388
  Without cwd, only global settings are read. With cwd, trusted project settings
305
389
  merge over global settings; untrusted project files are not read. `origins`
306
390
  maps dotted leaf keys to `global` or `project`. `versions.global` and optional
307
391
  `versions.project` are SHA-256 hashes of raw file contents, or `"none"` for an
308
- absent or unread untrusted scope. Settings, origins, versions, and parse errors
392
+ absent or unread untrusted scope. `defaults` is what an unset key means, in the
393
+ shape of `settings`; `paths` names the global and, with cwd, the project file. Settings, origins, versions, and parse errors
309
394
  come from the same scope reads, not cached settings paired with fresh versions.
310
395
  Parse errors appear as structured `source: "settings"` warnings with an
311
396
  optional path and available one-based line/column; unaffected scopes still read.
@@ -336,6 +421,71 @@ malformed keys, and prototype-pollution segments (`__proto__`, `constructor`,
336
421
  {"id":12,"method":"config/write","params":{"scope":"global","key":"theme","value":"dark","expectedVersion":"none"}}
337
422
  ```
338
423
 
424
+ ### `tool/list`
425
+
426
+ Params: optional `{cwd}`. Result: `{tools: [{name, description, source}], defaultTools}`.
427
+ The tools a new thread in `cwd` would register (without cwd, a
428
+ project-less one), from an in-memory session like `command/list`'s; hidden tools
429
+ are left out, and MCP tools appear only once a thread connects. `defaultTools` is
430
+ the global `defaultTools` setting resolved (`+name` and `-name` applied), or the
431
+ built-in default `read`, `bash`, `edit`, `write`. Change it with `config/write`.
432
+
433
+ ```json
434
+ {"id":26,"method":"tool/list","params":{}}
435
+ ```
436
+
437
+ ### `tool/settings/read` and `tool/settings/write`
438
+
439
+ The KnightCode tools `/tools` manages, stored in `tools.json` in the agent
440
+ directory. `tool/settings/read {}` returns
441
+ `{tools: [{name, enabled, settings}], classifiers: [{provider, id, name}]}`: each tool's state (its default when the
442
+ file does not set it) and its own settings, with values of keys ending in `Key`
443
+ masked to their last four characters; `classifiers` are the classifier models
444
+ with credentials, for the classifier gate's `model`.
445
+ `tool/settings/write {name, key, value}` sets one setting; `enabled` takes a boolean, other keys a string,
446
+ and `null` deletes the key. An unknown tool or a malformed key is
447
+ `invalidParams`.
448
+
449
+ ```json
450
+ {"id":27,"method":"tool/settings/write","params":{"name":"websearch","key":"provider","value":"brave"}}
451
+ ```
452
+
453
+ ### `mcp/list`, `mcp/update`, `mcp/add` and `mcp/remove`
454
+
455
+ The servers of the global `mcp.json` and, for an explicitly trusted project, its
456
+ `.knightcode/mcp.json` ([MCP](mcp.md)). `mcp/list {cwd?}` returns
457
+ `{servers, errors, paths}`: each server's `name`, `scope`, defining file (`source`), the
458
+ project file that overrides it (`override`), `transport` (`stdio` or `http`),
459
+ `target` (command line or URL), `description`, `enabled` and `exposure`.
460
+ `mcp/update {cwd?, name, enabled?, exposure?}` saves the change where `/mcp`
461
+ would: in the project override when there is one, else in the defining file.
462
+ `mcp/add {scope, cwd?, name, config}` validates `config` as an `mcpServers` entry
463
+ and adds or replaces it (result `{replaced}`); `auth` is refused in a project
464
+ file. `mcp/remove {scope, cwd?, name}` returns `{removed}`. Project writes need
465
+ cwd and a trusted project (`invalidParams`, `data.reason: "untrusted"`).
466
+ Connections, sign-in and status belong to the MCP extension in each thread
467
+ (`/mcp`); loaded threads pick up file changes when they next load.
468
+
469
+ ```json
470
+ {"id":28,"method":"mcp/add","params":{"scope":"global","name":"docs","config":{"url":"https://example.com/mcp"}}}
471
+ ```
472
+
473
+ ### `resource/list` and `resource/set`
474
+
475
+ Extensions, skills, prompt templates and themes as `knightcode config` lists them.
476
+ `resource/list {cwd?}` returns
477
+ `{resources: [{type, path, name, enabled, scope, origin, source}]}` for what a thread in `cwd` (or with no project) would find,
478
+ installing nothing. Built-in extensions are left out: they are always on, so
479
+ `resource/set` refuses them like any unknown path. `resource/set {cwd?, type, path, enabled}` loads or
480
+ skips one resource with a `+` or `-` pattern in the settings of the scope that
481
+ defines it: a top-level resource in that scope's `extensions`, `skills`,
482
+ `prompts` or `themes`, a package's in that package's filter. Project resources
483
+ need a trusted project; an unknown path is `invalidParams`.
484
+
485
+ ```json
486
+ {"id":29,"method":"resource/set","params":{"type":"skills","path":"/home/u/.knightcode/agent/skills/review/SKILL.md","enabled":false}}
487
+ ```
488
+
339
489
  ### `project/trust/read`
340
490
 
341
491
  Params: `{cwd}`. Result: `{trusted, needsTrust}`. `trusted` is true, false, or
@@ -425,6 +575,136 @@ Diagnostics observe the shared server, not only this connection.
425
575
  {"id":18,"method":"server/diagnostics","params":{}}
426
576
  ```
427
577
 
578
+ ### `thread/diff/read`
579
+
580
+ Params: `{threadId, scope?, against?, commit?, context?, ignoreWhitespace?}`.
581
+ Result: `{scope, root, files, filesOmitted?, untrackedSkipped?, turnId?, stale?, against?}`.
582
+ `files` are `{path, oldPath?, status, binary, additions, deletions, tooLarge?, hunks}`,
583
+ their paths relative to the repository's `root` (not the thread's cwd, which can
584
+ be a subdirectory of it); each hunk keeps its lines with their `" "`, `"+"`, `"-"` or
585
+ `"\"` prefix. `committed` needs `commit`; `branch` compares with `against`,
586
+ else the worktree's base, the upstream or the default branch, and echoes it.
587
+ More than 500 untracked files are counted in `untrackedSkipped` and left out.
588
+ Files past the response budget come without hunks (`tooLarge`) or are only
589
+ counted (`filesOmitted`). A hunk id hashes the file's header (its blob ids) and
590
+ the hunk at the read's `context`: an action must pass the same `context` (a
591
+ `context: 0` id matches no action), and after an action changes a file, read it
592
+ again, as its other hunks' ids change too. A hunk id from an `ignoreWhitespace` read matches no
593
+ action. Reads take no lock and never write the user's index.
594
+ Errors: `threadNotFound`, `notGitRepo`; `invalidParams` for a missing `commit`
595
+ or no branch to compare with.
596
+
597
+ ```json
598
+ {"id":20,"method":"thread/diff/read","params":{"threadId":"THREAD_ID","scope":"uncommitted","context":3}}
599
+ ```
600
+
601
+ ### `thread/diff/revert`
602
+
603
+ Params: `{threadId, scope?, against?, commit?, path?, hunkId?, context?, reapply?, turnId?}`.
604
+ With `turnId` (`lastTurn` only), a last turn other than that one answers
605
+ `gitConflict` `diffChanged`, so an Undo shown on one turn never reverts a newer one.
606
+ Result: `{paths}`. Reverse-applies one hunk, one file, or the whole scope to the
607
+ working tree; `lastTurn` without a path undoes the turn, and only while every
608
+ affected file is exactly as the turn left it. With `reapply` (`lastTurn` only,
609
+ no hunk), the turn's changes apply again instead, and only while every affected
610
+ file is exactly as the turn found it. Hunks of renamed, added, deleted,
611
+ binary or mode-changed files revert as whole files only. Refused while a turn
612
+ runs in the checkout; no turn starts and no tool runs there until it ends.
613
+ Errors: `turnInProgress`; `invalidParams` for `staged` and `committed` or a
614
+ path outside the diff; `gitConflict` with `diffChanged` or `patchFailed`.
615
+
616
+ ```json
617
+ {"id":21,"method":"thread/diff/revert","params":{"threadId":"THREAD_ID","path":"src/a.ts","hunkId":"HUNK_ID"}}
618
+ ```
619
+
620
+ ### `thread/handoff`
621
+
622
+ Params: `{threadId, to: "local" | "worktree", branch?, environment?}`. Result:
623
+ `{thread, branch?, warnings}`. To the main checkout: the worktree's `HEAD`
624
+ becomes a branch checked out there (the worktree's own branch, else `branch`,
625
+ else the previous handoff's branch fast-forwarded, else
626
+ `<worktrees.branchPrefix><title>`), the uncommitted changes move, and the
627
+ worktree stays, detached and clean. Back: the worktree is detached at the main
628
+ checkout's `HEAD` and the changes move into it; a thread born in the main
629
+ checkout gets a worktree. The changes are saved under `<agentDir>/handoff/`
630
+ before anything moves and leave the source only after they landed. The thread
631
+ is reloaded where it now runs: subscribers receive `thread/replaced` with the
632
+ same id, and queued inputs follow it.
633
+ Errors: `turnInProgress`; `invalidParams` for a thread with no message yet or
634
+ already on that side; `gitConflict` with `localChanges`,
635
+ `operationInProgress`, `branchExists`, `recoveryRequired` (with `data.patch`)
636
+ or `worktreeDeleted`.
637
+
638
+ ```json
639
+ {"id":22,"method":"thread/handoff","params":{"threadId":"THREAD_ID","to":"local"}}
640
+ ```
641
+
642
+ ### `thread/worktree/restore`
643
+
644
+ Params: `{threadId}`. Result: `{thread}`. Rebuilds a deleted worktree at its
645
+ old path from its snapshot: detached at the old `HEAD`, with the working files
646
+ and the staged state as they were (ignored files were not kept). Then the
647
+ thread loads there.
648
+ Errors: `threadNotFound`; `invalidParams` when the worktree is not deleted;
649
+ `gitConflict` with `worktreeMissing` (deleted without a snapshot: fork the chat
650
+ into a new worktree instead) or `submodules`.
651
+
652
+ ```json
653
+ {"id":23,"method":"thread/worktree/restore","params":{"threadId":"THREAD_ID"}}
654
+ ```
655
+
656
+ ### `worktree/list` and `worktree/delete`
657
+
658
+ `worktree/list {cwd?}` →
659
+ `{worktrees: [{path, projectCwd, head?, branch?, threadIds, lastUsedAt, deleted}]}`,
660
+ the managed worktrees (of `cwd`'s project
661
+ when given). `worktree/delete {path}` → `{snapshot?}` deletes one after its
662
+ snapshot. A worktree a thread is loaded in, or one holding a nested repository
663
+ (an initialized submodule or a repository inside it), is never deleted: archive
664
+ and pruning skip it, and `worktree/delete` answers `gitConflict` with
665
+ `worktreeInUse` or `submodules`. Only registrations in the managed layout are
666
+ removed; the user's own worktrees are never touched.
667
+
668
+ ```json
669
+ {"id":24,"method":"worktree/delete","params":{"path":"/home/u/.knightcode/agent/worktrees/ab12/project"}}
670
+ ```
671
+
672
+ ### `environment/list` and `environment/save`
673
+
674
+ `environment/list {cwd}` → `{environments, trusted}` reads the project's
675
+ `.knightcode/environments.json`; `environment/save {cwd, environments}` writes
676
+ it (names unique, at most 50). An untrusted project's scripts never run. See
677
+ [Settings](settings.md#worktrees).
678
+
679
+ ```json
680
+ {"id":25,"method":"environment/save","params":{"cwd":"/p","environments":[{"name":"node","setup":{"default":"cd \"$KNIGHTCODE_WORKTREE_PATH\" && npm ci"}}]}}
681
+ ```
682
+
683
+ ### `git/*`
684
+
685
+ Each acts on the thread's own checkout: its worktree, or the user's checkout.
686
+ `git/status` → branch, upstream, ahead/behind, staged/unstaged/untracked/
687
+ conflicted counts and an operation in progress. `git/stage` and `git/unstage`
688
+ take `{threadId, path?, hunkId?, context?}`: no path is everything; paths are
689
+ literal. `git/commit {threadId, message?, includeUnstaged?}` stages everything
690
+ first unless `includeUnstaged: false`; an empty message is written by the
691
+ thread's model from the staged diff, outside the conversation, and the commit
692
+ answers `concurrentChange` when the checkout changed meanwhile. The user's
693
+ hooks run. `git/push` pushes the current branch with one explicit,
694
+ non-forcing refspec and sets the upstream the first time.
695
+ `git/pr/create {threadId, title?, body?, draft?}` runs `gh pr create` (`toolMissing` without
696
+ `gh`). `git/branches`, `git/branch/create {name}` ("Create branch here"),
697
+ `git/branch/switch {name}` (refused when it would overwrite local changes or an
698
+ ignored file the branch tracks) and `git/log {limit?}` (the commits since the
699
+ base, for the `committed` scope) complete the set.
700
+ Errors: `notGitRepo`, `invalidParams`, `authRequired`, `toolMissing`;
701
+ `gitConflict` with `diffChanged`, `patchFailed`, `concurrentChange`,
702
+ `pushRejected`, `branchExists` or `localChanges`.
703
+
704
+ ```json
705
+ {"id":26,"method":"git/commit","params":{"threadId":"THREAD_ID","includeUnstaged":true}}
706
+ ```
707
+
428
708
  ## Ownership, unloading, and shutdown
429
709
 
430
710
  Only one process may own a persisted session file. Symlink/junction aliases share