@knightcodeai/cli 0.19.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +106 -0
- package/dist/bundle/chunks/anthropic-messages-EY2CGNFR.js +6 -0
- package/dist/bundle/chunks/azure-openai-responses-KGI5F27P.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +8 -5
- package/dist/bundle/chunks/chunk-424HQSAU.js +10 -0
- package/dist/bundle/chunks/{chunk-3QKQRXCZ.js → chunk-5O4LFJS7.js} +4 -4
- package/dist/bundle/chunks/chunk-5ZES34QN.js +2 -0
- package/dist/bundle/chunks/chunk-BLHRVYHG.js +9 -0
- package/dist/bundle/chunks/{chunk-RZDCZFG7.js → chunk-EJS73Z3L.js} +1 -1
- package/dist/bundle/chunks/chunk-F22TYE3W.js +7 -0
- package/dist/bundle/chunks/{chunk-C62RVFZT.js → chunk-FSAHEI7P.js} +6 -6
- package/dist/bundle/chunks/chunk-K6AEXKBA.js +30 -0
- package/dist/bundle/chunks/chunk-O2HKRIDR.js +16 -0
- package/dist/bundle/chunks/{chunk-KRDGPCZM.js → chunk-OLW2IS5G.js} +2 -2
- package/dist/bundle/chunks/chunk-QEVQ7EIS.js +2 -0
- package/dist/bundle/chunks/chunk-RRNUW65U.js +4 -0
- package/dist/bundle/chunks/{chunk-AA6MLWWY.js → chunk-TOEFTX4C.js} +1 -1
- package/dist/bundle/chunks/{chunk-IIS4JDFO.js → chunk-TOGJI36I.js} +147 -134
- package/dist/bundle/chunks/chunk-VLP4ZJF6.js +2 -0
- package/dist/bundle/chunks/{chunk-2QXPCKUQ.js → chunk-VQBEVSZH.js} +1 -1
- package/dist/bundle/chunks/chunk-XDEOVQPJ.js +108 -0
- package/dist/bundle/chunks/chunk-YDO6TXKD.js +2 -0
- package/dist/bundle/chunks/{cli-SIPOI5P3.js → cli-CIRIEG66.js} +1 -1
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-H3D4RYQQ.js +2 -0
- package/dist/bundle/chunks/{easter-egg-3d-BVWLABZN.js → easter-egg-3d-YLN6ACWS.js} +1 -1
- package/dist/bundle/chunks/{execute-6UIHV2DR.js → execute-P6HIB6ET.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-RFCCCXK6.js → google-generative-ai-C3FLXY47.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-WN3JAZCD.js → google-vertex-AXIPR47C.js} +1 -1
- package/dist/bundle/chunks/knightcode-messages-LTLKDRGW.js +8 -0
- package/dist/bundle/chunks/{llama-cpp-classify-FEWC5ZIH.js → llama-cpp-classify-J2EJVDIZ.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-N2UBIKKR.js +5 -0
- package/dist/bundle/chunks/{openai-codex-responses-3Y7R752C.js → openai-codex-responses-REOHLPAA.js} +1 -1
- package/dist/bundle/chunks/openai-completions-XONAGXPC.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-MLI3SMFN.js → openai-decisions-ACB7F6SS.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-BNRA5YTD.js → openai-responses-OHJS7C73.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-JWVDFQJ4.js → openrouter-images-SMNBEOPV.js} +1 -1
- package/dist/bundle/chunks/{runtime-AROIXIAV.js → runtime-WNZGA67H.js} +1 -1
- package/dist/bundle/chunks/typesafe-system-one-KB2F2YGV.js +2 -0
- package/dist/bundle/chunks/{virtual-modules-IYKQM2DL.js → virtual-modules-EU3BUTGN.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +165 -45
- package/docs/app-server.md +168 -14
- package/docs/app-server.schema.json +7505 -1860
- package/docs/cli.md +3 -3
- package/docs/containerization.md +2 -2
- package/docs/custom-provider.md +2 -0
- package/docs/declarative-views.md +118 -0
- package/docs/desktop.md +109 -4
- package/docs/docs.json +4 -0
- package/docs/environment-variables.md +1 -0
- package/docs/extensions.md +7 -3
- package/docs/keybindings.md +1 -0
- package/docs/mcp.md +16 -2
- package/docs/message-types.md +1 -1
- package/docs/models-configuration.md +9 -0
- package/docs/models.md +8 -4
- package/docs/packages.md +2 -0
- package/docs/plan-mode.md +4 -0
- package/docs/settings.md +3 -3
- package/docs/slash-commands.md +2 -0
- package/docs/usage.md +23 -0
- package/examples/extensions/README.md +1 -0
- package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/examples/extensions/desktop-view.ts +72 -0
- package/examples/extensions/gondolin/index.ts +8 -10
- package/examples/extensions/gondolin/package-lock.json +20 -30
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/todo.ts +3 -0
- package/examples/mcp-app/server.mjs +177 -0
- package/package.json +1 -1
- package/dist/bundle/chunks/anthropic-messages-34POCEPV.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-ZZQJJY7B.js +0 -2
- package/dist/bundle/chunks/chunk-2QXUEOVY.js +0 -2
- package/dist/bundle/chunks/chunk-4CRI7BMY.js +0 -2
- package/dist/bundle/chunks/chunk-BTRAS32C.js +0 -7
- package/dist/bundle/chunks/chunk-FA32X2UJ.js +0 -7
- package/dist/bundle/chunks/chunk-GPHSXYPT.js +0 -2
- package/dist/bundle/chunks/chunk-JSLSFYBX.js +0 -108
- package/dist/bundle/chunks/chunk-OQHO44L6.js +0 -16
- package/dist/bundle/chunks/chunk-R7X2RAGR.js +0 -30
- package/dist/bundle/chunks/chunk-T47GKPON.js +0 -11
- package/dist/bundle/chunks/chunk-UU4A4NV5.js +0 -2
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-QHP5M5HC.js +0 -2
- package/dist/bundle/chunks/knightcode-messages-57CV36UV.js +0 -8
- package/dist/bundle/chunks/mistral-conversations-GIGX6BW6.js +0 -5
- package/dist/bundle/chunks/openai-completions-HBXENZUJ.js +0 -7
- package/dist/bundle/chunks/typesafe-system-one-5LELZY2F.js +0 -2
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
-
import{shortHash}from"./chunk-HUQB436V.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-GPHSXYPT.js";import{sanitizeSurrogates}from"./chunk-B2FT7RH5.js";import{calculateCost,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-T47GKPON.js";import{parseStreamingJson,parseToolCallArguments}from"./chunk-FA32X2UJ.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
3
|
-
`),images=content.filter(c=>c.type==="image"),hasText=textResult.trim().length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function getResponsesToolSupport(options){return options.supportsMidConvoSystemMessages&&options.supportsAdditionalTools?"changes":options.supportsToolSearch?"additions":"none"}function renderIncrementalToolsNotice(unavailable){let notice="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return unavailable.size>0?`${notice}
|
|
4
|
-
Still unavailable: ${[...unavailable].join(", ")}.`:notice}function renderToolRemovalNotice(names){return`The following tools are no longer available. Do not call them:
|
|
5
|
-
${names.map(name=>`- ${name}`).join(`
|
|
6
|
-
`)}`}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!allowedToolCallProviders.has(model.provider)||!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId),normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId),toolSupport=getResponsesToolSupport(options??{}),transcriptTools=resolveTranscriptTools(normalizedContext.messages,toolSupport),declaredAdditionalTools=!1,unavailableTools=new Set,appendSystemToolAdditions=(message,seed)=>{let tools=message.toolsAdded??[];for(let tool of tools)unavailableTools.delete(tool.name);if(tools.length===0)return;if(toolSupport==="changes"){declaredAdditionalTools&&messages.push({role:instructionRole,content:renderIncrementalToolsNotice(unavailableTools)}),declaredAdditionalTools=!0,messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options?.toolOptions)});return}if(toolSupport!=="additions")return;let names=tools.map(tool=>tool.name),callId=`knightcode_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options?.toolOptions,toolSearchResult:!0})})},includeInitialSystemMessage=options?.includeSystemPrompt??!0,pushConfigurationUpdate=effort=>{messages.push({type:"configuration_update",reasoning:{effort}})},compat=model.compat,instructionRole=model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0,systemIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="system"){let anchorsToolChanges=systemIndex++>=transcriptTools.foldedSystemMessages;if(anchorsToolChanges&&appendSystemToolAdditions(msg,`system:${msgIndex}`),!isLeadingSystemMessage||includeInitialSystemMessage){let parts=[isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg)];if(anchorsToolChanges){let added=new Set((msg.toolsAdded??[]).map(tool=>tool.name)),removed=(msg.toolsRemoved??[]).map(tool=>tool.name).filter(name=>!added.has(name));removed.length>0&&parts.push(renderToolRemovalNotice(removed));for(let name of removed)unavailableTools.add(name)}let text=parts.filter(part=>part.length>0).join(`
|
|
7
|
-
|
|
8
|
-
`);text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}}else if(msg.role==="user")if(typeof msg.content=="string")messages.push({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]});else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push({role:"user",content})}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0;for(let block of msg.content)if(block.type==="thinking"){if(block.thinkingSignature){let reasoningItem=JSON.parse(block.thinkingSignature);output.push(reasoningItem)}}else if(block.type==="text"){let textBlock=block,parsedSignature=parseTextSignature(textBlock.textSignature),fallbackMessageId=textBlockIndex===0?`msg_kc_${msgIndex}`:`msg_kc_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(textBlock.text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),itemId=itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0),customInputProperty!==void 0?output.push({type:"custom_tool_call",id:itemId,call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",id:itemId,call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;options?.configurationUpdateEffort!==void 0&&isSameModel&&msg.providerThinkingLevel!==void 0&&pushConfigurationUpdate(msg.providerThinkingLevel),messages.push(...output)}else if(msg.role==="toolResult"){let[callId]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content);options?.grammarToolInputProperties?.has(msg.toolName)?messages.push({type:"custom_tool_call_output",call_id:callId,output}):messages.push({type:"function_call_output",call_id:callId,output})}isLeadingSystemMessage||msgIndex++}return options?.configurationUpdateEffort!==void 0&&pushConfigurationUpdate(options.configurationUpdateEffort),messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function 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}async function processResponsesStream(openaiStream,output,stream,model,options){let sawTerminalResponseEvent=!1,outputSlots=new Map,reasoningBlocksById=new Map,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block={type:"thinking",thinking:""};output.content.push(block);let slot={type:"thinking",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"thinking_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="message"){applyMessagePhaseStopReason(item);let block={type:"text",text:""};output.content.push(block);let slot={type:"text",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"text_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="function_call"){let block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="custom_tool_call"){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item),backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=JSON.parse(block.thinkingSignature);storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{if(sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),response?.id&&(output.responseId=response.id),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens||0;output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,reasoning:response.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of openaiStream)if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
9
|
-
|
|
10
|
-
`,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
|
|
11
|
-
|
|
12
|
-
`,partial:output})}else if(event.type==="response.reasoning_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.output_text.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.refusal.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.function_call_arguments.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;slot.block.partialJson+=event.delta,slot.block.arguments=parseStreamingJson(slot.block.partialJson),pushToolCallDelta(slot,event.delta)}else if(event.type==="response.function_call_arguments.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;let previousPartialJson=slot.block.partialJson;if(slot.block.partialJson=event.arguments,slot.block.arguments=parseStreamingJson(slot.block.partialJson),event.arguments.startsWith(previousPartialJson)){let delta=event.arguments.slice(previousPartialJson.length);delta.length>0&&pushToolCallDelta(slot,delta)}}else if(event.type==="response.custom_tool_call_input.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot||!slot.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,getCustomToolCallInput(slot.block)+event.delta,!1))}else if(event.type==="response.custom_tool_call_input.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot||!slot.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,event.input,!0))}else if(event.type==="response.output_item.done"){let item=event.item;applyMessagePhaseStopReason(item);let slot=getOrCreateSlot(event.output_index,item);if(item.type==="reasoning"&&slot?.type==="thinking"){let summaryText=item.summary?.map(s=>s.text).join(`
|
|
13
|
-
|
|
14
|
-
`)||"",contentText=item.content?.map(c=>c.text).join(`
|
|
15
|
-
|
|
16
|
-
`)||"";slot.block.thinking=summaryText||contentText||slot.block.thinking,slot.block.thinkingSignature=JSON.stringify(item),reasoningBlocksById.set(item.id,slot.block),stream.push({type:"thinking_end",contentIndex:slot.contentIndex,content:slot.block.thinking,partial:output}),outputSlots.delete(event.output_index)}else item.type==="message"&&slot?.type==="text"?(slot.block.text=item.content?.map(c=>c.type==="output_text"?c.text:c.refusal).join("")||"",slot.block.textSignature=encodeTextSignatureV1(item.id,item.phase??void 0),stream.push({type:"text_end",contentIndex:slot.contentIndex,content:slot.block.text,partial:output}),outputSlots.delete(event.output_index)):item.type==="function_call"&&slot?.type==="toolCall"&&slot.block.partialJson!==void 0?(Object.assign(slot.block,parseToolCallArguments(item.arguments||slot.block.partialJson)),item.namespace!==void 0&&(slot.block.namespace=item.namespace),delete slot.block.partialJson,stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index)):item.type==="custom_tool_call"&&slot?.type==="toolCall"&&slot.block.customInput&&(pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,item.input??getCustomToolCallInput(slot.block),!0)),item.namespace!==void 0&&(slot.block.namespace=item.namespace),delete slot.block.customInput,stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index))}else if(event.type==="response.completed"||event.type==="response.incomplete")finalizeResponse(event.response);else{if(event.type==="error")throw new Error(`Error Code ${event.code}: ${event.message}`||"Unknown error");if(event.type==="response.failed"){sawTerminalResponseEvent=!0,output.rawStopReason=event.response?.status;let error=event.response?.error,details=event.response?.incomplete_details,msg=error?`${error.code||"unknown"}: ${error.message||"no message"}`:details?.reason?`incomplete: ${details.reason}`:"Unknown error (no error details in response)";throw new Error(msg)}}if(!sawTerminalResponseEvent)throw new Error("OpenAI Responses stream ended before a terminal response event");if(output.stopReason==="toolUse")for(let block of output.content){if(block.type!=="toolCall")continue;let toolCall=block;if(toolCall.partialJson!==void 0||toolCall.customInput!==void 0)throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`)}}function mapStopReason(status,incompleteReason){if(!status)return{stopReason:"stop"};switch(status){case"completed":return{stopReason:"stop"};case"incomplete":return incompleteReason==="max_output_tokens"?{stopReason:"length"}:{stopReason:"error",errorMessage:incompleteReason?`Response incomplete: ${incompleteReason}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:{let _exhaustive=status;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}export{getResponsesToolSupport,convertResponsesMessages,convertResponsesTools,processResponsesStream};
|