@diffra-ai/cli 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/bundle/chunks/{anthropic-messages-UM2LSKVG.js → anthropic-messages-VPHYDMHB.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-LLULQ6UR.js → azure-openai-responses-JYJ2VXQ2.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-I6QEKFFB.js → chunk-2IABWVGX.js} +1 -1
- package/dist/bundle/chunks/{chunk-6NW7EDTU.js → chunk-6RV2XP5B.js} +6 -6
- package/dist/bundle/chunks/{chunk-Y5LGEDHU.js → chunk-FCSMMPE4.js} +1 -1
- package/dist/bundle/chunks/{chunk-MAMCTGRH.js → chunk-JEYYTVUX.js} +1 -1
- package/dist/bundle/chunks/chunk-NPHITI73.js +30 -0
- package/dist/bundle/chunks/{chunk-UBBD6YWP.js → chunk-QQYLP3HG.js} +1 -1
- package/dist/bundle/chunks/{chunk-J2CQ7AOB.js → chunk-QY4GYLLA.js} +1 -1
- package/dist/bundle/chunks/{chunk-MWJ5PWKE.js → chunk-REVASUCD.js} +1 -1
- package/dist/bundle/chunks/{chunk-BSCVN57O.js → chunk-S7OTLWTF.js} +1 -1
- package/dist/bundle/chunks/{chunk-QCEU5NDS.js → chunk-TOBZDLTR.js} +1 -1
- package/dist/bundle/chunks/{chunk-37INV3TW.js → chunk-Z4BBBJG4.js} +1 -1
- package/dist/bundle/chunks/{cli-VEFNOOXB.js → cli-I4RCHKMY.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-VQHACWH5.js → cloudflare-workers-ai-system-one-OTYUASP3.js} +1 -1
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-YFRD2UAD.js → google-generative-ai-DI3FOC25.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-7EWCT4BL.js → google-vertex-VBHHROPU.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-D5PC6EEP.js → llama-cpp-classify-MUFWIFOW.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-ILNLXCLF.js → mistral-conversations-Q2PGF352.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-YESP5ZRN.js → openai-codex-responses-WWZAXEPG.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-BKYCRYVB.js → openai-completions-4C7QTL2T.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-OZVDLRU3.js → openai-decisions-NYOT2XIF.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-GSXMBGMK.js → openai-responses-R5MW34FB.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-TK5PJTOE.js → openrouter-images-FBKW4PD4.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-AHAEGVU4.js → pi-messages-LJZPZBQY.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-XHINCFVH.js → typesafe-system-one-7MCWBLJY.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-7F3I52A6.js → virtual-modules-J4Z2IMRZ.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/cli.js +0 -0
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli.js +0 -0
- package/dist/core/model-resolver.js +3 -3
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/extensions/skills/bundled/find-skills/LICENSE +21 -0
- package/dist/extensions/skills/bundled/find-skills/SKILL.md +117 -0
- package/dist/extensions/skills/bundled/grill-me/LICENSE +21 -0
- package/dist/extensions/skills/bundled/grill-me/SKILL.md +44 -0
- package/dist/extensions/skills/bundled/handoff/LICENSE +21 -0
- package/dist/extensions/skills/bundled/handoff/SKILL.md +31 -0
- package/dist/extensions/skills/bundled/mcp-builder/LICENSE.txt +202 -0
- package/dist/extensions/skills/bundled/mcp-builder/SKILL.md +260 -0
- package/dist/extensions/skills/bundled/mcp-builder/reference/evaluation.md +432 -0
- package/dist/extensions/skills/bundled/mcp-builder/reference/mcp_best_practices.md +249 -0
- package/dist/extensions/skills/bundled/mcp-builder/reference/node_mcp_server.md +972 -0
- package/dist/extensions/skills/bundled/mcp-builder/reference/node_mcp_server_v2.md +747 -0
- package/dist/extensions/skills/bundled/mcp-builder/reference/python_mcp_server.md +719 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/LICENSE +21 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/SKILL.md +251 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/app-interface.csv +33 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/charts.csv +26 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/colors.csv +195 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/google-fonts.csv +1935 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/icons.csv +106 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/landing.csv +35 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/motion.csv +21 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/products.csv +195 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/react-performance.csv +45 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/angular.csv +51 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/astro.csv +54 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/avalonia.csv +57 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/html-tailwind.csv +60 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/javafx.csv +76 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/nextjs.csv +62 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/nuxt-ui.csv +84 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/nuxtjs.csv +68 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/pyside6-qss.csv +103 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/react.csv +67 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/shadcn.csv +69 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/svelte.csv +56 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/uno.csv +60 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/uwp.csv +56 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/vue.csv +50 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/winui.csv +60 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/wpf.csv +57 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/styles.csv +90 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/typography.csv +75 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/ui-reasoning.csv +195 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/data/ux-guidelines.csv +142 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/references/pro-rules.md +117 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/references/quick-reference.md +275 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/core.py +1111 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/design_system.py +1922 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/preview.py +557 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/reasoning_contract.py +123 -0
- package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/search.py +257 -0
- package/dist/extensions/skills/index.d.ts +4 -4
- package/dist/extensions/skills/index.d.ts.map +1 -1
- package/dist/extensions/skills/index.js +9 -4
- package/dist/extensions/skills/index.js.map +1 -1
- package/dist/rpc-entry.js +0 -0
- package/docs/builtin-skills.md +46 -3
- package/docs/docs.json +1 -1
- package/docs/skills.md +1 -1
- package/docs/slash-commands.md +2 -0
- package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
- package/examples/extensions/doom-overlay/doom/build.sh +0 -0
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-UIVU7TEF.js +0 -30
package/dist/bundle/chunks/{openai-completions-BKYCRYVB.js → openai-completions-4C7QTL2T.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-P7FPUEYA.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-LWG2CUTI.js";import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,closeGrammarToolInputJson,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-I6QEKFFB.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-MAMCTGRH.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-MWJ5PWKE.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-J2CQ7AOB.js";import"./chunk-JXWJOIH4.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("DIFFRA_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,toolCallStates=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),customInput=property=>({kind:"custom",property,buffer:{input:"",started:!1,closed:!1}}),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"){let input=toolCallStates.get(block).input;if(toolCallStates.delete(block),input.kind==="custom"){let delta=closeGrammarToolInputJson(input.buffer,input.property,void 0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else Object.assign(block,input.arguments.finish());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;block={type:"toolCall",id:toolCall.id||"",name,arguments:customInputProperty!==void 0?{[customInputProperty]:""}:{}},toolCallStates.set(block,{streamIndex,input:customInputProperty!==void 0?customInput(customInputProperty):{kind:"json",arguments:new ToolCallArgumentsStream}}),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})}let state=toolCallStates.get(block);if(streamIndex!==void 0&&state.streamIndex===void 0&&(state.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&state.input.kind!=="custom"){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},state.input=customInput(customInputProperty)}return{block,state}};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,state}=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="",input=state.input;toolCall.function?.arguments&&input.kind==="json"?(delta=toolCall.function.arguments,block.arguments=input.arguments.append(delta)):toolCall.custom?.input&&input.kind==="custom"&&(delta=appendGrammarToolInputJsonDelta(input.buffer,input.property,toolCall.custom.input)??"",block.arguments={[input.property]:input.buffer.input}),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);output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
2
|
+
import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-P7FPUEYA.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-LWG2CUTI.js";import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,closeGrammarToolInputJson,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,resolveSamplingParams,thinkingBudgetForLevel,transformMessages}from"./chunk-2IABWVGX.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-JEYYTVUX.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-REVASUCD.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.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("DIFFRA_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,toolCallStates=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),customInput=property=>({kind:"custom",property,buffer:{input:"",started:!1,closed:!1}}),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"){let input=toolCallStates.get(block).input;if(toolCallStates.delete(block),input.kind==="custom"){let delta=closeGrammarToolInputJson(input.buffer,input.property,void 0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else Object.assign(block,input.arguments.finish());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;block={type:"toolCall",id:toolCall.id||"",name,arguments:customInputProperty!==void 0?{[customInputProperty]:""}:{}},toolCallStates.set(block,{streamIndex,input:customInputProperty!==void 0?customInput(customInputProperty):{kind:"json",arguments:new ToolCallArgumentsStream}}),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})}let state=toolCallStates.get(block);if(streamIndex!==void 0&&state.streamIndex===void 0&&(state.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&state.input.kind!=="custom"){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},state.input=customInput(customInputProperty)}return{block,state}};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,state}=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="",input=state.input;toolCall.function?.arguments&&input.kind==="json"?(delta=toolCall.function.arguments,block.arguments=input.arguments.append(delta)):toolCall.custom?.input&&input.kind==="custom"&&(delta=appendGrammarToolInputJsonDelta(input.buffer,input.property,toolCall.custom.input)??"",block.arguments={[input.property]:input.buffer.input}),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);output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
3
|
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,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),promptCacheKeyMode=compat.promptCacheKeyMode??"auto",supportsPromptCacheKey=promptCacheKeyMode==="enabled"||promptCacheKeyMode==="auto"&&(model.baseUrl.includes("api.openai.com")||cacheRetention==="long"&&compat.supportsLongCacheRetention),params={model:model.id,messages,stream:!0,prompt_cache_key:cacheRetention!=="none"&&supportsPromptCacheKey?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)):compat.requiresToolsWithToolHistory&&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"&¶ms.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&¶ms.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||compat.requiresNonNullAssistantContent?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0){if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else if(assistantText.length>0&&(assistantMsg.content=assistantText),!preservedReasoningDetails){let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature&&isOpenAICompletionsReasoningField(signature)&&(assistantMsg[signature]=nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-
|
|
2
|
+
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-FCSMMPE4.js";import"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-JEYYTVUX.js";import"./chunk-UTB4DTYQ.js";import"./chunk-REVASUCD.js";import"./chunk-LPXNMA2W.js";import"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.js";var LABEL="OpenAI Decisions",MAX_IMAGES=128;function predicateInstructions(question){let meanings=[question.criteria.true?`True means: ${question.criteria.true}`:"",question.criteria.false?`False means: ${question.criteria.false}`:""].filter(Boolean);return meanings.length>0?`${question.instructions}
|
|
3
3
|
|
|
4
4
|
${meanings.join(`
|
|
5
5
|
`)}`:question.instructions}function wireQuestion(name,question){return question.type==="choice"?{type:"choice",name,instructions:question.instructions,choices:Object.entries(question.criteria).map(([value,description])=>description?{value,description}:{value})}:question.type==="score"?{type:"score",name,instructions:question.instructions,levels:question.criteria.map(label=>({label}))}:{type:"predicate",name,instructions:predicateInstructions(question)}}function wireInput(context){let state=JSON.stringify(context.state),images=context.images??[];if(images.length===0)return state;if(images.length>MAX_IMAGES)throw new Error(`${LABEL} accepts at most ${MAX_IMAGES} images, got ${images.length}`);return[{role:"user",content:[{type:"input_text",text:state},...images.map(image=>({type:"input_image",image_url:`data:${image.mimeType};base64,${image.data}`}))]}]}function choiceProbabilities(value,id){if(!Array.isArray(value))throw new Error(`${LABEL} returned invalid probabilities for ${id}`);return Object.fromEntries(value.map(entry=>{if(!isRecord(entry)||typeof entry.value!="string")throw new Error(`${LABEL} returned invalid probabilities for ${id}`);return[entry.value,requiredNumber(LABEL,entry.probability,`probability for ${id}.${entry.value}`)]}))}function parseAnswer(id,question,answer){if(answer.type==="refusal")throw new Error(`${LABEL} refused to answer ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${LABEL} did not return a choice answer for ${id}`);return{type:"choice",choice:answer.choice,probabilities:choiceProbabilities(answer.probabilities,id),confidence:requiredNumber(LABEL,answer.confidence,`confidence for ${id}`)}}if(question.type==="score"){if(answer.type!=="score")throw new Error(`${LABEL} did not return a score answer for ${id}`);return{type:"score",score:requiredNumber(LABEL,answer.score,`score for ${id}`),confidence:requiredNumber(LABEL,answer.confidence,`confidence for ${id}`)}}if(answer.type!=="predicate")throw new Error(`${LABEL} did not return a predicate answer for ${id}`);return{type:"bool",probability:requiredNumber(LABEL,answer.probability,`probability for ${id}`)}}function parseAnswers(value,context){if(!Array.isArray(value))throw new Error(`${LABEL} returned an unexpected response`);let byName=new Map;for(let answer of value)isRecord(answer)&&typeof answer.name=="string"&&byName.set(answer.name,answer);return Object.fromEntries(Object.entries(context.questions).map(([id,question])=>{let answer=byName.get(id);if(!answer)throw new Error(`${LABEL} did not return an answer for ${id}`);return[id,parseAnswer(id,question,answer)]}))}var NO_RETRY_STATUSES=[504];function errorMessage(error){return error.status===504?`${LABEL} error (504): the request timed out at the gateway. Very large inputs (above roughly 600K tokens) currently exceed its time limit.`:formatProviderError(normalizeProviderError(error),`${LABEL} error`)}var classify=async(model,context,options)=>{let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!=="openai-decisions")throw new Error(`Unsupported classifier API: ${model.api}`);let body=await postClassifierRequest(LABEL,new URL("decisions",`${model.baseUrl.replace(/\/+$/u,"")}/`),model,{model:model.id,input:wireInput(context),questions:Object.entries(context.questions).map(([id,question])=>wireQuestion(id,question))},options,NO_RETRY_STATUSES);if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);let usage=parseClassifierUsage(body.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(body.answers,context),output}catch(error){return output.answers={},output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=errorMessage(error),output}};export{classify};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-
|
|
2
|
+
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-S7OTLWTF.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-LWG2CUTI.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-2IABWVGX.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-JEYYTVUX.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-REVASUCD.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.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("DIFFRA_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),promptCacheKeyMode:model.compat?.promptCacheKeyMode??"auto",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){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
3
|
Check your ChatGPT usage: ${CHATGPT_USAGE_URL}`:errorMessage.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?output.errorMessage=`${errorMessage}
|
|
4
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),sendPromptCacheKey=cacheRetention!=="none"&&compat.promptCacheKeyMode!=="disabled",omitUnsupportedFields=isChatGPTSignIn(model,options?.apiKey),params={model:model.id,input:messages,stream:!0,prompt_cache_key:sendPromptCacheKey?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:omitUnsupportedFields?void 0:getPromptCacheRetention(compat,cacheRetention),prompt_cache_options:omitUnsupportedFields?void 0:getPromptCacheOptions(compat,cacheRetention),store:!1};options?.maxTokens&&compat.supportsMaxOutputTokens&&!omitUnsupportedFields&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&!omitUnsupportedFields&&(params.temperature=options?.temperature),options?.serviceTier!==void 0&&(params.service_tier=options.serviceTier),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:compat.supportsStrictMode,supportsOpenAIGrammarTools:compat.supportsOpenAIGrammarTools})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning){if(reasoningEffort){let requestedEffort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort,effort=configurationUpdateEffort===void 0?requestedEffort:CONFIGURATION_UPDATE_REQUEST_EFFORT;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.provider!=="github-copilot"&&model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});model.provider==="xai"&&(params.include=["reasoning.encrypted_content"])}let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":case"fast":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{OpenAI}from"./chunk-LWG2CUTI.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-
|
|
2
|
+
import{OpenAI}from"./chunk-LWG2CUTI.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-JEYYTVUX.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getIdentityHeaders}from"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.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,totalFromProvider:!1}};return usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage}export{generateImages};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{headersToRecord,providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,ownedSlice}from"./chunk-
|
|
2
|
+
import{headersToRecord,providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,ownedSlice}from"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.js";var PiMessagesResponseError=class extends Error{code;diagnosticDetails;constructor(message,code,diagnosticDetails){super(message),this.name="PiMessagesResponseError",this.code=code,this.diagnosticDetails=diagnosticDetails}};function parseDiffraMessagesErrorBody(body){try{let parsed=JSON.parse(body),error=parsed?.error;return parsed&&typeof error=="object"&&error!==null&&!Array.isArray(error)?parsed:void 0}catch{return}}function truncateDiagnosticString(value){return value.length>8192?`${ownedSlice(value,0,8192)}\u2026`:value}function formatDiffraMessagesResponseError(response,body,errorBody){let message=typeof errorBody?.error?.message=="string"?errorBody.error.message:void 0,code=typeof errorBody?.error?.code=="string"?errorBody.error.code:void 0,suffix=message??body,codeSuffix=code?` (${code})`:"";return`${response.status} ${response.statusText}: ${suffix}${codeSuffix}`}function createDiffraMessagesResponseError(model,url,response,body){let errorBody=parseDiffraMessagesErrorBody(body),code=typeof errorBody?.error?.code=="string"?errorBody.error.code:void 0;return new PiMessagesResponseError(formatDiffraMessagesResponseError(response,body,errorBody),code,{version:1,provider:model.provider,model:model.id,url:url.toString(),status:response.status,statusText:response.statusText,...errorBody?.error===void 0?{}:{error:errorBody.error},...errorBody?{}:{body:truncateDiagnosticString(body)},timestampMs:Date.now()})}function createEmptyUsage(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function appendRewriteDiagnostic(message,rewrite){rewrite&&appendAssistantMessageDiagnostic(message,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...rewrite}})}function createEventConverter(model){let partial={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:createEmptyUsage(),stopReason:"pending",timestamp:Date.now()},toolArguments=new Map;return event=>{if("contentIndex"in event){let index=event.contentIndex,limit=event.type.endsWith("_start")?partial.content.length:partial.content.length-1;if(typeof index!="number"||!Number.isInteger(index)||index<0||index>limit)throw new Error(`Invalid contentIndex ${JSON.stringify(index)} in pi-messages ${event.type} event`)}switch(event.type){case"done":return Object.assign(partial,{stopReason:event.reason,usage:event.usage,responseId:event.responseId}),event.responseModel!==void 0&&(partial.responseModel=event.responseModel),event.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=event.providerThinkingLevel),appendRewriteDiagnostic(partial,event.rewrite),{type:"done",reason:event.reason,message:partial};case"error":return Object.assign(partial,{stopReason:event.reason,usage:event.usage,errorMessage:event.errorMessage,responseId:event.responseId}),event.responseModel!==void 0&&(partial.responseModel=event.responseModel),event.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=event.providerThinkingLevel),appendRewriteDiagnostic(partial,event.rewrite),{type:"error",reason:event.reason,error:partial};case"start":break;case"text_start":partial.content[event.contentIndex]={type:"text",text:""};break;case"text_delta":partial.content[event.contentIndex].text+=event.delta;break;case"text_end":Object.assign(partial.content[event.contentIndex],{text:event.content,textSignature:event.contentSignature});break;case"thinking_start":partial.content[event.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":partial.content[event.contentIndex].thinking+=event.delta;break;case"thinking_end":Object.assign(partial.content[event.contentIndex],{thinking:event.content,thinkingSignature:event.contentSignature,redacted:event.redacted});break;case"toolcall_start":partial.content[event.contentIndex]={type:"toolCall",id:event.id,name:event.toolName,arguments:{}},toolArguments.set(event.contentIndex,new ToolCallArgumentsStream);break;case"toolcall_delta":{let args=toolArguments.get(event.contentIndex);args!==void 0&&(partial.content[event.contentIndex].arguments=args.append(event.delta));break}case"toolcall_end":return Object.assign(partial.content[event.contentIndex],event.toolCall),toolArguments.delete(event.contentIndex),{type:"toolcall_end",contentIndex:event.contentIndex,toolCall:partial.content[event.contentIndex],partial}}return{...event,partial}}}async function*readDiffraMessagesEvents(stream2){let decoder=new TextDecoder,reader=stream2.getReader(),buffer="";try{for(;;){let{done,value}=await reader.read();buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),buffer=buffer.replace(/\r\n/g,`
|
|
3
3
|
`);let split=buffer.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);for(;split!==-1;){let event=parseDiffraMessagesEvent(buffer.slice(0,split));event&&(yield event),buffer=buffer.slice(split+2),split=buffer.indexOf(`
|
package/dist/bundle/chunks/{typesafe-system-one-XHINCFVH.js → typesafe-system-one-7MCWBLJY.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{classifySystemOne}from"./chunk-
|
|
2
|
+
import{classifySystemOne}from"./chunk-Z4BBBJG4.js";import{isRecord}from"./chunk-FCSMMPE4.js";import"./chunk-PMRZO46Y.js";import"./chunk-JEYYTVUX.js";import"./chunk-UTB4DTYQ.js";import"./chunk-REVASUCD.js";import"./chunk-LPXNMA2W.js";import"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.js";var transport={api:"typesafe-system-one",label:"System One API",detectCompat:model=>model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai")?{imageInput:"state-image-urls",sendImageOptInHeader:!1}:{imageInput:"assets",sendImageOptInHeader:!0},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 __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{dist_exports as dist_exports3}from"./chunk-
|
|
2
|
+
import{dist_exports as dist_exports3}from"./chunk-TOBZDLTR.js";import{diffra_ai_extension_view_exports,dist_exports as dist_exports2}from"./chunk-6RV2XP5B.js";import"./chunk-J3RI6JJL.js";import"./chunk-6ZD23B2R.js";import{dist_exports}from"./chunk-4NMBWIZG.js";import{all_exports,compile_exports,value_exports}from"./chunk-NPHITI73.js";import{build_exports}from"./chunk-4KBADZRL.js";import"./chunk-65DC2T66.js";import"./chunk-GRYHVZSI.js";import"./chunk-6QGV3IWD.js";import"./chunk-XAA355T2.js";import"./chunk-IEBK4HQA.js";import"./chunk-5AGIVGSV.js";import"./chunk-INODY4DR.js";import"./chunk-ZG74NES2.js";import"./chunk-TMTOQ7H7.js";import"./chunk-FFMDRXC4.js";import"./chunk-7DDKXS2Q.js";import{models_exports}from"./chunk-REVASUCD.js";import"./chunk-LPXNMA2W.js";import"./chunk-QY4GYLLA.js";import"./chunk-JXWJOIH4.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,"@diffra-ai/agent-core":dist_exports2,"@diffra-ai/tui":dist_exports,"@diffra-ai/ai":diffra_ai_extension_view_exports,"@diffra-ai/ai/compat":diffra_ai_extension_view_exports,"@diffra-ai/ai/models":models_exports,"@diffra-ai/ai/oauth":oauth_exports,"@diffra-ai/ai/providers/all":all_exports,"@diffra-ai/cli":dist_exports3};export{VIRTUAL_MODULES};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-6RV2XP5B.js";import"./chunks/chunk-J3RI6JJL.js";import"./chunks/chunk-6ZD23B2R.js";import"./chunks/chunk-4NMBWIZG.js";import"./chunks/chunk-NPHITI73.js";import"./chunks/chunk-4KBADZRL.js";import"./chunks/chunk-65DC2T66.js";import"./chunks/chunk-GRYHVZSI.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-XAA355T2.js";import"./chunks/chunk-IEBK4HQA.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-INODY4DR.js";import"./chunks/chunk-ZG74NES2.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-FFMDRXC4.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-REVASUCD.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-QY4GYLLA.js";import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_NAME,process.env.DIFFRA_CODING_AGENT="true",process.env.AI_AGENT="diffra",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
|
package/dist/bundle/cli.js
CHANGED
|
File without changes
|
package/dist/bundle/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-
|
|
2
|
+
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-TOBZDLTR.js";import{APPROVAL_MODES,APPROVAL_MODE_INFO,ASK_USER_QUESTION_TOOL_NAME,AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildSessionContext,buildSessionProjection,builtInExtensions,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createQuestionsExtension,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,explainToolCall,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-6RV2XP5B.js";import{formatReadLineRange,truncateToVisualLines}from"./chunks/chunk-J3RI6JJL.js";import{ArminComponent}from"./chunks/chunk-6ZD23B2R.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint,theme}from"./chunks/chunk-4NMBWIZG.js";import{CredentialSynchronizationError,ModelRuntime,ProjectTrustStore,VIRTUAL_MODEL_STATE_ENTRY,findTrustRequiringProjectResources,getProjectTrustOptions,getProjectTrustParentPath,hasTrustRequiringProjectResources}from"./chunks/chunk-NPHITI73.js";import"./chunks/chunk-4KBADZRL.js";import{readStoredCredential}from"./chunks/chunk-65DC2T66.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail}from"./chunks/chunk-GRYHVZSI.js";import"./chunks/chunk-6QGV3IWD.js";import{CONFIG_DIR_NAME,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-XAA355T2.js";import"./chunks/chunk-IEBK4HQA.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-INODY4DR.js";import"./chunks/chunk-ZG74NES2.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-FFMDRXC4.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-REVASUCD.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-QY4GYLLA.js";import"./chunks/chunk-JXWJOIH4.js";export{APPROVAL_MODES,APPROVAL_MODE_INFO,ASK_USER_QUESTION_TOOL_NAME,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,builtInExtensions,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createQuestionsExtension,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,explainToolCall,findCutPoint,findTrustRequiringProjectResources,findTurnStartIndex,formatDimensionNote,formatReadLineRange,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getProjectTrustOptions,getProjectTrustParentPath,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,theme,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-6RV2XP5B.js";import"./chunks/chunk-J3RI6JJL.js";import"./chunks/chunk-6ZD23B2R.js";import"./chunks/chunk-4NMBWIZG.js";import"./chunks/chunk-NPHITI73.js";import"./chunks/chunk-4KBADZRL.js";import"./chunks/chunk-65DC2T66.js";import"./chunks/chunk-GRYHVZSI.js";import"./chunks/chunk-6QGV3IWD.js";import{APP_NAME}from"./chunks/chunk-XAA355T2.js";import"./chunks/chunk-IEBK4HQA.js";import"./chunks/chunk-5AGIVGSV.js";import"./chunks/chunk-INODY4DR.js";import"./chunks/chunk-ZG74NES2.js";import"./chunks/chunk-TMTOQ7H7.js";import"./chunks/chunk-FFMDRXC4.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-REVASUCD.js";import"./chunks/chunk-LPXNMA2W.js";import"./chunks/chunk-QY4GYLLA.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.DIFFRA_CODING_AGENT="true";process.env.AI_AGENT="diffra";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
package/dist/cli.js
CHANGED
|
File without changes
|
|
@@ -26,7 +26,7 @@ export const defaultModelPerProvider = {
|
|
|
26
26
|
cerebras: "gpt-oss-120b",
|
|
27
27
|
zai: "glm-5.3",
|
|
28
28
|
"zai-coding-cn": "glm-5.3",
|
|
29
|
-
mistral: "
|
|
29
|
+
mistral: "mistral-medium-latest",
|
|
30
30
|
minimax: "MiniMax-M3",
|
|
31
31
|
"minimax-cn": "MiniMax-M3",
|
|
32
32
|
moonshotai: "kimi-k2.7-code",
|
|
@@ -39,8 +39,8 @@ export const defaultModelPerProvider = {
|
|
|
39
39
|
"opencode-go": "kimi-k3.1-pro",
|
|
40
40
|
"kimi-coding": "kimi-for-coding",
|
|
41
41
|
meta: "muse-spark-1.3",
|
|
42
|
-
"cloudflare-workers-ai": "@cf/
|
|
43
|
-
"cloudflare-ai-gateway": "workers-ai/@cf/
|
|
42
|
+
"cloudflare-workers-ai": "@cf/zai-org/glm-5.3",
|
|
43
|
+
"cloudflare-ai-gateway": "workers-ai/@cf/zai-org/glm-5.3",
|
|
44
44
|
"qwen-token-plan": "qwen3.8-max",
|
|
45
45
|
"qwen-token-plan-cn": "qwen3.8-max",
|
|
46
46
|
"qwen-token-plan-individual": "qwen3.8-max",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAuE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAGvD,sEAAsE;AACtE,MAAM,CAAC,MAAM,uBAAuB,GAA2C;IAC9E,gBAAgB,EAAE,8BAA8B;IAChD,UAAU,EAAE,aAAa;IACzB,SAAS,EAAE,iBAAiB;IAC5B,MAAM,EAAE,aAAa;IACrB,KAAK,EAAE,aAAa;IACpB,cAAc,EAAE,aAAa;IAC7B,MAAM,EAAE,UAAU;IAClB,MAAM,EAAE,wCAAwC;IAChD,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,gBAAgB;IACxB,eAAe,EAAE,gBAAgB;IACjC,gBAAgB,EAAE,aAAa;IAC/B,UAAU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AAI,MAAM,CAAC,IAAI,CAAC,uBAAuB,CAAoB,EAAE,CAAC;YAChF,MAAM,SAAS,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC;YACpD,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC;YACzF,IAAI,KAAK,EAAE,CAAC;gBACX,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;YAC5F,CAAC;QACF,CAAC;QAED,2CAA2C;QAC3C,OAAO,EAAE,KAAK,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;IACzG,CAAC;IAED,oBAAoB;IACpB,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAChG,CAAC","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nimport type { ThinkingLevel } from \"@diffra-ai/agent-core\";\nimport { type Api, type AuthOperationOptions, type KnownProvider, type Model, modelsAreEqual } from \"@diffra-ai/ai\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\n\n/** Default chat model IDs for providers with built-in chat models. */\nexport const defaultModelPerProvider: Partial<Record<KnownProvider, string>> = {\n\t\"amazon-bedrock\": \"us.anthropic.claude-opus-5-5\",\n\t\"ant-ling\": \"Ring-2.6-1T\",\n\tanthropic: \"claude-opus-5-5\",\n\topenai: \"gpt-6.2-sol\",\n\tazure: \"gpt-6.2-sol\",\n\t\"openai-codex\": \"gpt-6.2-sol\",\n\tradius: \"balanced\",\n\tnvidia: \"nvidia/nemotron-3.5-super-vl-120b-a12b\",\n\tdeepseek: \"deepseek-v4-pro\",\n\tgoogle: \"gemini-4-argon\",\n\t\"google-vertex\": \"gemini-4-argon\",\n\t\"github-copilot\": \"gpt-6.1-sol\",\n\topenrouter: \"moonshotai/kimi-k2.7-code\",\n\t\"vercel-ai-gateway\": \"zai/glm-5.3\",\n\txai: \"grok-4.7\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"gpt-oss-120b\",\n\tzai: \"glm-5.3\",\n\t\"zai-coding-cn\": \"glm-5.3\",\n\tmistral: \"devstral-medium-latest\",\n\tminimax: \"MiniMax-M3\",\n\t\"minimax-cn\": \"MiniMax-M3\",\n\tmoonshotai: \"kimi-k2.7-code\",\n\t\"moonshotai-cn\": \"kimi-k2.7-code\",\n\thuggingface: \"moonshotai/Kimi-K2.7-Code\",\n\tfireworks: \"accounts/fireworks/models/kimi-k3\",\n\ttogether: \"moonshotai/Kimi-K3\",\n\tbaseten: \"zai-org/GLM-5.3\",\n\topencode: \"kimi-k2.7-code\",\n\t\"opencode-go\": \"kimi-k3.1-pro\",\n\t\"kimi-coding\": \"kimi-for-coding\",\n\tmeta: \"muse-spark-1.3\",\n\t\"cloudflare-workers-ai\": \"@cf/moonshotai/kimi-k2.7-code\",\n\t\"cloudflare-ai-gateway\": \"workers-ai/@cf/moonshotai/kimi-k2.7-code\",\n\t\"qwen-token-plan\": \"qwen3.8-max\",\n\t\"qwen-token-plan-cn\": \"qwen3.8-max\",\n\t\"qwen-token-plan-individual\": \"qwen3.8-max\",\n\t\"qwen-token-plan-individual-cn\": \"qwen3.8-max\",\n\txiaomi: \"mimo-v2.6-pro\",\n\t\"xiaomi-token-plan-cn\": \"mimo-v2.6-pro\",\n\t\"xiaomi-token-plan-ams\": \"mimo-v2.6-pro\",\n\t\"xiaomi-token-plan-sgp\": \"mimo-v2.6-pro\",\n};\n\nexport interface ScopedModel {\n\tmodel: Model<Api>;\n\t/** Thinking level if explicitly specified in pattern (e.g., \"model:high\"), undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/*\n * Model reference resolution. Candidates are collected before a provider is chosen, so catalog order\n * never decides the provider and an ambiguous match is reported instead of falling through to a\n * weaker one.\n */\n\nexport interface ModelReferenceRequest {\n\t/** Bare model id or `provider/id`, optionally followed by `:<thinking>`. */\n\ttext: string;\n\t/** Only consider models from this provider. */\n\tprovider?: string;\n\t/**\n\t * A trailing `:<suffix>` is only considered when the full text matches no model, since ids such as\n\t * OpenRouter's `qwen/qwen3-coder:exacto` contain colons.\n\t * - `none`: the suffix stays part of the id\n\t * - `strict`: a valid thinking level is parsed; any other suffix stays part of the id\n\t * - `lenient`: like `strict`, but an invalid suffix is dropped with a warning\n\t */\n\tthinkingSuffix: \"none\" | \"strict\" | \"lenient\";\n\t/** Match id and name substrings when no exact match exists. */\n\tfuzzy: boolean;\n}\n\nexport type ModelReferenceResult =\n\t| { status: \"resolved\"; model: Model<Api>; thinkingLevel?: ThinkingLevel; warning?: string }\n\t| {\n\t\t\tstatus: \"ambiguous\";\n\t\t\tcandidates: Model<Api>[];\n\t\t\tusableCount: number;\n\t\t\tthinkingLevel?: ThinkingLevel;\n\t\t\twarning?: string;\n\t }\n\t| {\n\t\t\tstatus: \"not-found\";\n\t\t\t/** Set when a provider is explicit or named by a `provider/` prefix, for building a custom model id. */\n\t\t\ttarget?: ModelReferenceTarget;\n\t };\n\nexport interface ModelReferenceTarget {\n\tprovider: string;\n\tproviderModels: [Model<Api>, ...Model<Api>[]];\n\t/** Text after the provider prefix as typed, including any `:<suffix>`. */\n\tmodelText: string;\n\t/** `modelText` without a valid thinking suffix (unless `thinkingSuffix` is `none`). */\n\tmodelId: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\ntype ResolvedOrAmbiguous = Exclude<ModelReferenceResult, { status: \"not-found\" }>;\n\nfunction splitThinkingSuffix(text: string): { base: string; thinkingLevel: ThinkingLevel } | undefined {\n\tconst colonIndex = text.lastIndexOf(\":\");\n\tconst suffix = text.substring(colonIndex + 1);\n\tif (colonIndex === -1 || !isValidThinkingLevel(suffix)) return undefined;\n\treturn { base: text.substring(0, colonIndex), thinkingLevel: suffix };\n}\n\nfunction splitProviderPrefix(\n\ttext: string,\n\tmodels: readonly Model<Api>[],\n): { provider: string; modelText: string } | undefined {\n\t// Provider ids may contain \"/\" themselves (e.g. URL-derived ids), so match known ids, longest first\n\tconst lowerText = text.toLowerCase();\n\tlet best: { provider: string; modelText: string } | undefined;\n\tfor (const { provider } of models) {\n\t\tconst prefix = provider.trim().toLowerCase();\n\t\tif (!prefix || (best && best.provider.length >= provider.length)) continue;\n\t\tconst slashIndex = lowerText.indexOf(\"/\", prefix.length);\n\t\tif (slashIndex === -1 || lowerText.substring(0, slashIndex).trim() !== prefix) continue;\n\t\tconst modelText = text.substring(slashIndex + 1).trim();\n\t\tif (modelText) best = { provider, modelText };\n\t}\n\treturn best;\n}\n\n/**\n * `usable` only breaks ties between providers, so a unique match resolves even without credentials\n * (`--api-key` first-time setup).\n */\nexport function resolveModelReference(\n\trequest: ModelReferenceRequest,\n\tmodels: readonly Model<Api>[],\n\tusable: (provider: string) => boolean,\n): ModelReferenceResult {\n\tconst text = request.text.trim();\n\tif (!text) return { status: \"not-found\" };\n\tconst constraint = request.provider?.toLowerCase();\n\tconst pool = constraint ? models.filter((model) => model.provider.toLowerCase() === constraint) : models;\n\tconst result = resolveText(text, request, pool, usable);\n\tif (result.status !== \"not-found\") return result;\n\n\tconst split = splitProviderPrefix(text, pool);\n\tconst anchor = constraint ? pool[0] : pool.find((model) => model.provider === split?.provider);\n\tif (!anchor) return result;\n\tconst modelText = split?.modelText ?? text;\n\tconst suffix = request.thinkingSuffix === \"none\" ? undefined : splitThinkingSuffix(modelText);\n\treturn {\n\t\tstatus: \"not-found\",\n\t\ttarget: {\n\t\t\tprovider: anchor.provider,\n\t\t\tproviderModels: [anchor, ...pool.filter((model) => model.provider === anchor.provider && model !== anchor)],\n\t\t\tmodelText,\n\t\t\tmodelId: suffix?.base ?? modelText,\n\t\t\tthinkingLevel: suffix?.thinkingLevel,\n\t\t},\n\t};\n}\n\n/** Exact `provider/id` or bare id lookup without thinking suffixes or fuzzy matching. */\nexport function findExactModelReferenceMatch(\n\tmodelReference: string,\n\tmodels: readonly Model<Api>[],\n): Model<Api> | undefined {\n\tconst result = resolveModelReference(\n\t\t{ text: modelReference, thinkingSuffix: \"none\", fuzzy: false },\n\t\tmodels,\n\t\t() => true,\n\t);\n\treturn result.status === \"resolved\" ? result.model : undefined;\n}\n\nfunction resolveText(\n\ttext: string,\n\trequest: ModelReferenceRequest,\n\tpool: readonly Model<Api>[],\n\tusable: (provider: string) => boolean,\n): ModelReferenceResult {\n\tconst reference = selectReference(text, pool, request.fuzzy, usable);\n\tif (reference) return reference;\n\n\tif (request.fuzzy) {\n\t\tconst fuzzy = selectFuzzy(fuzzyMatches(text, pool), usable);\n\t\tif (fuzzy) return fuzzy;\n\t}\n\n\tif (request.thinkingSuffix === \"none\") return { status: \"not-found\" };\n\tconst thinking = splitThinkingSuffix(text);\n\tif (thinking) {\n\t\tconst inner = resolveText(thinking.base, request, pool, usable);\n\t\tif (inner.status === \"not-found\") return inner;\n\t\t// Only use this thinking level if no warning from inner recursion\n\t\treturn { ...inner, thinkingLevel: inner.warning ? undefined : thinking.thinkingLevel };\n\t}\n\t// Keep an invalid suffix as part of the id and fail, rather than resolve a different model\n\tif (request.thinkingSuffix === \"strict\") return { status: \"not-found\" };\n\tconst colonIndex = text.lastIndexOf(\":\");\n\tif (colonIndex === -1) return { status: \"not-found\" };\n\n\tconst suffix = text.substring(colonIndex + 1);\n\tconst inner = resolveText(text.substring(0, colonIndex), request, pool, usable);\n\tif (inner.status === \"not-found\") return inner;\n\treturn {\n\t\t...inner,\n\t\tthinkingLevel: undefined,\n\t\twarning: `Invalid thinking level \"${suffix}\" in pattern \"${text}\". Using default instead.`,\n\t};\n}\n\n/**\n * `provider/rest` is only a hint: the whole text may also be a model id on another provider, such as\n * gateway id `zai/glm-5` or commandcode id `xiaomi/mimo-v2.6-pro`. The named provider wins when usable,\n * since that is what the syntax usually means; otherwise a sole usable raw match wins, since the named\n * provider could not serve the request. An unusable named match is still preferred over unusable raw\n * matches, so `--api-key` can set up the named provider.\n */\nfunction selectReference(\n\ttext: string,\n\tpool: readonly Model<Api>[],\n\tfuzzy: boolean,\n\tusable: (provider: string) => boolean,\n): ResolvedOrAmbiguous | undefined {\n\tconst lowerText = text.toLowerCase();\n\tconst raw = pool.filter((model) => model.id.toLowerCase() === lowerText);\n\tconst split = splitProviderPrefix(text, pool);\n\tlet named: Model<Api> | undefined;\n\tif (split) {\n\t\tconst providerModels = pool.filter((model) => model.provider === split.provider);\n\t\tconst lowerModelText = split.modelText.toLowerCase();\n\t\t// The provider's own literal id (OpenRouter's `openrouter/free`) beats its fuzzy matches\n\t\tnamed =\n\t\t\tproviderModels.find((model) => model.id.toLowerCase() === lowerModelText) ??\n\t\t\traw.find((model) => model.provider === split.provider) ??\n\t\t\t(fuzzy ? bestFuzzyMatch(fuzzyMatches(split.modelText, providerModels)) : undefined);\n\t}\n\n\tconst others = raw.filter((model) => model !== named);\n\tconst candidates = named ? [named, ...others] : others;\n\tif (candidates.length === 0) return undefined;\n\tif (new Set(candidates.map((model) => model.provider)).size === 1)\n\t\treturn { status: \"resolved\", model: candidates[0] };\n\tif (named && usable(named.provider)) return { status: \"resolved\", model: named };\n\tconst usableOthers = others.filter((model) => usable(model.provider));\n\tif (usableOthers.length === 1) return { status: \"resolved\", model: usableOthers[0] };\n\tif (usableOthers.length === 0 && named) return { status: \"resolved\", model: named };\n\treturn { status: \"ambiguous\", candidates, usableCount: usableOthers.length };\n}\n\nfunction fuzzyMatches(text: string, models: readonly Model<Api>[]): Model<Api>[] {\n\tconst lowerText = text.toLowerCase();\n\treturn models.filter(\n\t\t(model) => model.id.toLowerCase().includes(lowerText) || model.name?.toLowerCase().includes(lowerText),\n\t);\n}\n\nfunction selectFuzzy(matches: Model<Api>[], usable: (provider: string) => boolean): ResolvedOrAmbiguous | undefined {\n\tif (matches.length === 0) return undefined;\n\tconst multipleProviders = new Set(matches.map((model) => model.provider)).size > 1;\n\tconst usableMatches = multipleProviders ? matches.filter((model) => usable(model.provider)) : [];\n\tconst pool = usableMatches.length > 0 ? usableMatches : matches;\n\tconst best = bestFuzzyMatch(pool);\n\tif (!best) return undefined;\n\t// The same id on several providers would otherwise be decided by catalog order\n\tconst tied = pool.filter((model) => model.id === best.id);\n\tif (new Set(tied.map((model) => model.provider)).size === 1) return { status: \"resolved\", model: best };\n\treturn {\n\t\tstatus: \"ambiguous\",\n\t\tcandidates: tied,\n\t\tusableCount: usableMatches.length > 0 ? tied.length : 0,\n\t};\n}\n\n/** Prefer aliases (`claude-sonnet-4-5`) over dated versions (`claude-sonnet-4-5-20250929`), then the latest. */\nfunction bestFuzzyMatch(matches: readonly Model<Api>[]): Model<Api> | undefined {\n\tconst aliases = matches.filter((model) => isAlias(model.id));\n\treturn [...(aliases.length > 0 ? aliases : matches)].sort((a, b) => b.id.localeCompare(a.id))[0];\n}\n\nfunction isAlias(id: string): boolean {\n\treturn id.endsWith(\"-latest\") || !/-\\d{8}$/.test(id);\n}\n\nfunction buildFallbackModel(providerModels: [Model<Api>, ...Model<Api>[]], modelId: string): Model<Api> {\n\tconst defaultId = defaultModelPerProvider[providerModels[0].provider as KnownProvider];\n\tconst baseModel = defaultId\n\t\t? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])\n\t\t: providerModels[0];\n\n\treturn {\n\t\t...baseModel,\n\t\tid: modelId,\n\t\tname: modelId,\n\t};\n}\n\nexport interface ModelScopeDiagnostic {\n\ttype: \"warning\";\n\tcode: \"no-match\" | \"invalid-thinking-level\" | \"ambiguous\";\n\tmessage: string;\n\tpattern: string;\n}\n\nexport interface ResolveModelScopeResult {\n\tscopedModels: ScopedModel[];\n\tdiagnostics: ModelScopeDiagnostic[];\n}\n\n/**\n * Resolve scope patterns (`--models`, `enabledModels`) to models with optional thinking levels.\n *\n * Every model in `models` is usable, so credentials cannot choose between providers offering the same\n * id. All of them are added, with a warning so the user can pick one with `provider/id`.\n */\nexport function resolveModelScopeFromModels(\n\tpatterns: string[],\n\tmodels: readonly Model<Api>[],\n): ResolveModelScopeResult {\n\tconst scopedModels: ScopedModel[] = [];\n\tconst diagnostics: ModelScopeDiagnostic[] = [];\n\tconst add = (model: Model<Api>, thinkingLevel: ThinkingLevel | undefined) => {\n\t\tif (!scopedModels.some((scoped) => modelsAreEqual(scoped.model, model))) {\n\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t}\n\t};\n\tconst noMatch = (pattern: string) =>\n\t\tdiagnostics.push({ type: \"warning\", code: \"no-match\", message: `No models match pattern \"${pattern}\"`, pattern });\n\tconst ambiguous = (pattern: string, candidates: readonly Model<Api>[]) => {\n\t\tconst providers = [...new Set(candidates.map((m) => m.provider))].sort((a, b) => a.localeCompare(b));\n\t\tdiagnostics.push({\n\t\t\ttype: \"warning\",\n\t\t\tcode: \"ambiguous\",\n\t\t\tmessage: `Pattern \"${pattern}\" matches several providers: ${providers.join(\", \")}. Use provider/id to choose one.`,\n\t\t\tpattern,\n\t\t});\n\t};\n\n\tfor (const pattern of patterns) {\n\t\t// Check if pattern contains glob characters\n\t\tif (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\")) {\n\t\t\t// Extract optional thinking level suffix (e.g., \"provider/*:high\")\n\t\t\tconst thinking = splitThinkingSuffix(pattern);\n\t\t\tconst globPattern = thinking?.base ?? pattern;\n\t\t\tconst thinkingLevel = thinking?.thinkingLevel;\n\n\t\t\t// Ids such as `bracketed-model[1m]` are not globs\n\t\t\tconst exact = resolveModelReference(\n\t\t\t\t{ text: globPattern, thinkingSuffix: \"none\", fuzzy: false },\n\t\t\t\tmodels,\n\t\t\t\t() => true,\n\t\t\t);\n\t\t\tlet matches: readonly Model<Api>[] = [];\n\t\t\tif (exact.status === \"resolved\") matches = [exact.model];\n\t\t\telse if (exact.status === \"ambiguous\") {\n\t\t\t\tmatches = exact.candidates;\n\t\t\t\tambiguous(pattern, matches);\n\t\t\t} else {\n\t\t\t\t// Match against \"provider/modelId\" format OR just model ID\n\t\t\t\t// This allows \"*sonnet*\" to match without requiring \"anthropic/*sonnet*\"\n\t\t\t\tmatches = models.filter(\n\t\t\t\t\t(m) =>\n\t\t\t\t\t\tminimatch(`${m.provider}/${m.id}`, globPattern, { nocase: true }) ||\n\t\t\t\t\t\tminimatch(m.id, globPattern, { nocase: true }),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (matches.length === 0) noMatch(pattern);\n\t\t\tfor (const model of matches) add(model, thinkingLevel);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst result = resolveModelReference(\n\t\t\t{ text: pattern, thinkingSuffix: \"lenient\", fuzzy: true },\n\t\t\tmodels,\n\t\t\t() => true,\n\t\t);\n\t\tif (result.status === \"not-found\") {\n\t\t\tnoMatch(pattern);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"invalid-thinking-level\", message: result.warning, pattern });\n\t\t}\n\t\tif (result.status === \"ambiguous\") ambiguous(pattern, result.candidates);\n\t\tconst matches = result.status === \"resolved\" ? [result.model] : result.candidates;\n\t\tfor (const model of matches) add(model, result.thinkingLevel);\n\t}\n\n\treturn { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScopeWithDiagnostics(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n\toptions?: AuthOperationOptions,\n): Promise<ResolveModelScopeResult> {\n\treturn resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options));\n}\n\nexport interface ResolveCliModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n\t/**\n\t * Error message suitable for CLI display.\n\t * When set, model will be undefined.\n\t */\n\terror: string | undefined;\n}\n\n/**\n * Resolve a single model from CLI flags.\n *\n * Supports:\n * - --provider <provider> --model <pattern>\n * - --model <provider>/<pattern>\n * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)\n *\n * Note: This does not apply the thinking level by itself, but it may *parse* and\n * return a thinking level from \"<pattern>:<thinking>\" so the caller can apply it.\n */\nexport function resolveCliModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tcliThinking?: ThinkingLevel;\n\t/** `--api-key` was supplied for the selected provider. */\n\tinlineApiKey?: boolean;\n\tmodelRuntime: ModelRuntime;\n}): ResolveCliModelResult {\n\tconst { cliProvider, cliModel, cliThinking, inlineApiKey, modelRuntime } = options;\n\n\tif (!cliModel) {\n\t\treturn { model: undefined, warning: undefined, error: undefined };\n\t}\n\n\t// Important: use *all* models here, not just models with pre-configured auth.\n\t// This allows \"--api-key\" to be used for first-time setup.\n\tconst models = [...modelRuntime.getModels()];\n\tif (models.length === 0) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: \"No models available. Check your installation or add models to models.json.\",\n\t\t};\n\t}\n\n\tconst provider = cliProvider\n\t\t? models.find((m) => m.provider.toLowerCase() === cliProvider.toLowerCase())?.provider\n\t\t: undefined;\n\tif (cliProvider && !provider) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Unknown provider \"${cliProvider}\". Use --list-models to see available providers/models.`,\n\t\t};\n\t}\n\n\tconst result = resolveModelReference(\n\t\t{ text: cliModel, provider, thinkingSuffix: \"strict\", fuzzy: true },\n\t\tmodels,\n\t\t// An inline key goes to whichever provider is selected, so stored credentials must not choose it\n\t\tinlineApiKey ? () => false : (providerId) => modelRuntime.hasConfiguredAuth(providerId),\n\t);\n\tif (result.status === \"resolved\") {\n\t\treturn { model: result.model, thinkingLevel: result.thinkingLevel, warning: result.warning, error: undefined };\n\t}\n\tif (result.status === \"ambiguous\") {\n\t\tconst matches = result.candidates\n\t\t\t.map((m) => `${m.provider}/${m.id}`)\n\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t.join(\", \");\n\t\tconst authHint = inlineApiKey\n\t\t\t? \"--api-key does not choose a provider.\"\n\t\t\t: result.usableCount === 0\n\t\t\t\t? \"No matching provider is authenticated.\"\n\t\t\t\t: \"More than one matching provider is authenticated.\";\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Model \"${cliModel}\" is ambiguous across providers: ${matches}. ${authHint} Use --provider or provider/model.`,\n\t\t};\n\t}\n\n\tconst { target } = result;\n\tif (!target) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Model \"${cliModel}\" not found. Use --list-models to see available models.`,\n\t\t};\n\t}\n\n\t// Use the thinking level suffix only when --thinking is not explicitly provided; otherwise it\n\t// stays part of the custom model id.\n\t// e.g. \"zai-org/GLM-5.1-FP8:high\" → modelId=\"zai-org/GLM-5.1-FP8\", fallbackThinking=\"high\"\n\tconst modelId = cliThinking ? target.modelText : target.modelId;\n\tconst fallbackThinking = cliThinking ? undefined : target.thinkingLevel;\n\tconst fallbackModel = buildFallbackModel(target.providerModels, modelId);\n\tconst requestedThinking = cliThinking ?? fallbackThinking;\n\treturn {\n\t\tmodel: requestedThinking && requestedThinking !== \"off\" ? { ...fallbackModel, reasoning: true } : fallbackModel,\n\t\tthinkingLevel: fallbackThinking,\n\t\twarning: `Model \"${modelId}\" not found for provider \"${target.provider}\". Using custom model id.`,\n\t\terror: undefined,\n\t};\n}\n\nexport interface InitialModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel: ThinkingLevel;\n\tfallbackMessage: string | undefined;\n}\n\n/**\n * Find the initial model to use based on priority:\n * 1. First model from scoped models (if not continuing/resuming)\n * 2. Saved default from settings\n * 3. First available model with valid API key\n */\nexport async function findInitialModel(options: {\n\tscopedModels: ScopedModel[];\n\tisContinuing: boolean;\n\tdefaultProvider?: string;\n\tdefaultModelId?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tmodelThinkingLevels?: Record<string, ThinkingLevel>;\n\tmodelRuntime: ModelRuntime;\n}): Promise<InitialModelResult> {\n\tconst {\n\t\tscopedModels,\n\t\tisContinuing,\n\t\tdefaultProvider,\n\t\tdefaultModelId,\n\t\tdefaultThinkingLevel,\n\t\tmodelThinkingLevels,\n\t\tmodelRuntime,\n\t} = options;\n\n\tlet model: Model<Api> | undefined;\n\tlet thinkingLevel: ThinkingLevel = DEFAULT_THINKING_LEVEL;\n\n\t// 1. Use first model from scoped models (skip if continuing/resuming)\n\tif (scopedModels.length > 0 && !isContinuing) {\n\t\tconst scopedModel = scopedModels[0];\n\t\tconst perModel = modelThinkingLevels?.[`${scopedModel.model.provider}/${scopedModel.model.id}`];\n\t\treturn {\n\t\t\tmodel: scopedModel.model,\n\t\t\tthinkingLevel: scopedModel.thinkingLevel ?? perModel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t\tfallbackMessage: undefined,\n\t\t};\n\t}\n\n\t// 2. Try saved default from settings if auth is configured.\n\tif (defaultProvider && defaultModelId) {\n\t\tconst found = modelRuntime.getModel(defaultProvider, defaultModelId);\n\t\tif (found && modelRuntime.hasConfiguredAuth(found.provider)) {\n\t\t\tmodel = found;\n\t\t\tconst perModel = modelThinkingLevels?.[`${defaultProvider}/${defaultModelId}`];\n\t\t\tif (perModel) {\n\t\t\t\tthinkingLevel = perModel;\n\t\t\t} else if (defaultThinkingLevel) {\n\t\t\t\tthinkingLevel = defaultThinkingLevel;\n\t\t\t}\n\t\t\treturn { model, thinkingLevel, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 3. Try first available model with valid API key\n\tconst availableModels = [...modelRuntime.getAvailableSnapshot()];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\treturn { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\treturn { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t}\n\n\t// 4. No model found\n\treturn { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAuE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAGvD,sEAAsE;AACtE,MAAM,CAAC,MAAM,uBAAuB,GAA2C;IAC9E,gBAAgB,EAAE,8BAA8B;IAChD,UAAU,EAAE,aAAa;IACzB,SAAS,EAAE,iBAAiB;IAC5B,MAAM,EAAE,aAAa;IACrB,KAAK,EAAE,aAAa;IACpB,cAAc,EAAE,aAAa;IAC7B,MAAM,EAAE,UAAU;IAClB,MAAM,EAAE,wCAAwC;IAChD,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,gBAAgB;IACxB,eAAe,EAAE,gBAAgB;IACjC,gBAAgB,EAAE,aAAa;IAC/B,UAAU,EAAE,2BAA2B;IACvC,mBAAmB,EAAE,aAAa;IAClC,GAAG,EAAE,UAAU;IACf,IAAI,EAAE,qBAAqB;IAC3B,QAAQ,EAAE,cAAc;IACxB,GAAG,EAAE,SAAS;IACd,eAAe,EAAE,SAAS;IAC1B,OAAO,EAAE,uBAAuB;IAChC,OAAO,EAAE,YAAY;IACrB,YAAY,EAAE,YAAY;IAC1B,UAAU,EAAE,gB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CAAC,CAAC;YACzF,IAAI,KAAK,EAAE,CAAC;gBACX,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;YAC5F,CAAC;QACF,CAAC;QAED,2CAA2C;QAC3C,OAAO,EAAE,KAAK,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;IACzG,CAAC;IAED,oBAAoB;IACpB,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAChG,CAAC","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nimport type { ThinkingLevel } from \"@diffra-ai/agent-core\";\nimport { type Api, type AuthOperationOptions, type KnownProvider, type Model, modelsAreEqual } from \"@diffra-ai/ai\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\n\n/** Default chat model IDs for providers with built-in chat models. */\nexport const defaultModelPerProvider: Partial<Record<KnownProvider, string>> = {\n\t\"amazon-bedrock\": \"us.anthropic.claude-opus-5-5\",\n\t\"ant-ling\": \"Ring-2.6-1T\",\n\tanthropic: \"claude-opus-5-5\",\n\topenai: \"gpt-6.2-sol\",\n\tazure: \"gpt-6.2-sol\",\n\t\"openai-codex\": \"gpt-6.2-sol\",\n\tradius: \"balanced\",\n\tnvidia: \"nvidia/nemotron-3.5-super-vl-120b-a12b\",\n\tdeepseek: \"deepseek-v4-pro\",\n\tgoogle: \"gemini-4-argon\",\n\t\"google-vertex\": \"gemini-4-argon\",\n\t\"github-copilot\": \"gpt-6.1-sol\",\n\topenrouter: \"moonshotai/kimi-k2.7-code\",\n\t\"vercel-ai-gateway\": \"zai/glm-5.3\",\n\txai: \"grok-4.7\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"gpt-oss-120b\",\n\tzai: \"glm-5.3\",\n\t\"zai-coding-cn\": \"glm-5.3\",\n\tmistral: \"mistral-medium-latest\",\n\tminimax: \"MiniMax-M3\",\n\t\"minimax-cn\": \"MiniMax-M3\",\n\tmoonshotai: \"kimi-k2.7-code\",\n\t\"moonshotai-cn\": \"kimi-k2.7-code\",\n\thuggingface: \"moonshotai/Kimi-K2.7-Code\",\n\tfireworks: \"accounts/fireworks/models/kimi-k3\",\n\ttogether: \"moonshotai/Kimi-K3\",\n\tbaseten: \"zai-org/GLM-5.3\",\n\topencode: \"kimi-k2.7-code\",\n\t\"opencode-go\": \"kimi-k3.1-pro\",\n\t\"kimi-coding\": \"kimi-for-coding\",\n\tmeta: \"muse-spark-1.3\",\n\t\"cloudflare-workers-ai\": \"@cf/zai-org/glm-5.3\",\n\t\"cloudflare-ai-gateway\": \"workers-ai/@cf/zai-org/glm-5.3\",\n\t\"qwen-token-plan\": \"qwen3.8-max\",\n\t\"qwen-token-plan-cn\": \"qwen3.8-max\",\n\t\"qwen-token-plan-individual\": \"qwen3.8-max\",\n\t\"qwen-token-plan-individual-cn\": \"qwen3.8-max\",\n\txiaomi: \"mimo-v2.6-pro\",\n\t\"xiaomi-token-plan-cn\": \"mimo-v2.6-pro\",\n\t\"xiaomi-token-plan-ams\": \"mimo-v2.6-pro\",\n\t\"xiaomi-token-plan-sgp\": \"mimo-v2.6-pro\",\n};\n\nexport interface ScopedModel {\n\tmodel: Model<Api>;\n\t/** Thinking level if explicitly specified in pattern (e.g., \"model:high\"), undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/*\n * Model reference resolution. Candidates are collected before a provider is chosen, so catalog order\n * never decides the provider and an ambiguous match is reported instead of falling through to a\n * weaker one.\n */\n\nexport interface ModelReferenceRequest {\n\t/** Bare model id or `provider/id`, optionally followed by `:<thinking>`. */\n\ttext: string;\n\t/** Only consider models from this provider. */\n\tprovider?: string;\n\t/**\n\t * A trailing `:<suffix>` is only considered when the full text matches no model, since ids such as\n\t * OpenRouter's `qwen/qwen3-coder:exacto` contain colons.\n\t * - `none`: the suffix stays part of the id\n\t * - `strict`: a valid thinking level is parsed; any other suffix stays part of the id\n\t * - `lenient`: like `strict`, but an invalid suffix is dropped with a warning\n\t */\n\tthinkingSuffix: \"none\" | \"strict\" | \"lenient\";\n\t/** Match id and name substrings when no exact match exists. */\n\tfuzzy: boolean;\n}\n\nexport type ModelReferenceResult =\n\t| { status: \"resolved\"; model: Model<Api>; thinkingLevel?: ThinkingLevel; warning?: string }\n\t| {\n\t\t\tstatus: \"ambiguous\";\n\t\t\tcandidates: Model<Api>[];\n\t\t\tusableCount: number;\n\t\t\tthinkingLevel?: ThinkingLevel;\n\t\t\twarning?: string;\n\t }\n\t| {\n\t\t\tstatus: \"not-found\";\n\t\t\t/** Set when a provider is explicit or named by a `provider/` prefix, for building a custom model id. */\n\t\t\ttarget?: ModelReferenceTarget;\n\t };\n\nexport interface ModelReferenceTarget {\n\tprovider: string;\n\tproviderModels: [Model<Api>, ...Model<Api>[]];\n\t/** Text after the provider prefix as typed, including any `:<suffix>`. */\n\tmodelText: string;\n\t/** `modelText` without a valid thinking suffix (unless `thinkingSuffix` is `none`). */\n\tmodelId: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\ntype ResolvedOrAmbiguous = Exclude<ModelReferenceResult, { status: \"not-found\" }>;\n\nfunction splitThinkingSuffix(text: string): { base: string; thinkingLevel: ThinkingLevel } | undefined {\n\tconst colonIndex = text.lastIndexOf(\":\");\n\tconst suffix = text.substring(colonIndex + 1);\n\tif (colonIndex === -1 || !isValidThinkingLevel(suffix)) return undefined;\n\treturn { base: text.substring(0, colonIndex), thinkingLevel: suffix };\n}\n\nfunction splitProviderPrefix(\n\ttext: string,\n\tmodels: readonly Model<Api>[],\n): { provider: string; modelText: string } | undefined {\n\t// Provider ids may contain \"/\" themselves (e.g. URL-derived ids), so match known ids, longest first\n\tconst lowerText = text.toLowerCase();\n\tlet best: { provider: string; modelText: string } | undefined;\n\tfor (const { provider } of models) {\n\t\tconst prefix = provider.trim().toLowerCase();\n\t\tif (!prefix || (best && best.provider.length >= provider.length)) continue;\n\t\tconst slashIndex = lowerText.indexOf(\"/\", prefix.length);\n\t\tif (slashIndex === -1 || lowerText.substring(0, slashIndex).trim() !== prefix) continue;\n\t\tconst modelText = text.substring(slashIndex + 1).trim();\n\t\tif (modelText) best = { provider, modelText };\n\t}\n\treturn best;\n}\n\n/**\n * `usable` only breaks ties between providers, so a unique match resolves even without credentials\n * (`--api-key` first-time setup).\n */\nexport function resolveModelReference(\n\trequest: ModelReferenceRequest,\n\tmodels: readonly Model<Api>[],\n\tusable: (provider: string) => boolean,\n): ModelReferenceResult {\n\tconst text = request.text.trim();\n\tif (!text) return { status: \"not-found\" };\n\tconst constraint = request.provider?.toLowerCase();\n\tconst pool = constraint ? models.filter((model) => model.provider.toLowerCase() === constraint) : models;\n\tconst result = resolveText(text, request, pool, usable);\n\tif (result.status !== \"not-found\") return result;\n\n\tconst split = splitProviderPrefix(text, pool);\n\tconst anchor = constraint ? pool[0] : pool.find((model) => model.provider === split?.provider);\n\tif (!anchor) return result;\n\tconst modelText = split?.modelText ?? text;\n\tconst suffix = request.thinkingSuffix === \"none\" ? undefined : splitThinkingSuffix(modelText);\n\treturn {\n\t\tstatus: \"not-found\",\n\t\ttarget: {\n\t\t\tprovider: anchor.provider,\n\t\t\tproviderModels: [anchor, ...pool.filter((model) => model.provider === anchor.provider && model !== anchor)],\n\t\t\tmodelText,\n\t\t\tmodelId: suffix?.base ?? modelText,\n\t\t\tthinkingLevel: suffix?.thinkingLevel,\n\t\t},\n\t};\n}\n\n/** Exact `provider/id` or bare id lookup without thinking suffixes or fuzzy matching. */\nexport function findExactModelReferenceMatch(\n\tmodelReference: string,\n\tmodels: readonly Model<Api>[],\n): Model<Api> | undefined {\n\tconst result = resolveModelReference(\n\t\t{ text: modelReference, thinkingSuffix: \"none\", fuzzy: false },\n\t\tmodels,\n\t\t() => true,\n\t);\n\treturn result.status === \"resolved\" ? result.model : undefined;\n}\n\nfunction resolveText(\n\ttext: string,\n\trequest: ModelReferenceRequest,\n\tpool: readonly Model<Api>[],\n\tusable: (provider: string) => boolean,\n): ModelReferenceResult {\n\tconst reference = selectReference(text, pool, request.fuzzy, usable);\n\tif (reference) return reference;\n\n\tif (request.fuzzy) {\n\t\tconst fuzzy = selectFuzzy(fuzzyMatches(text, pool), usable);\n\t\tif (fuzzy) return fuzzy;\n\t}\n\n\tif (request.thinkingSuffix === \"none\") return { status: \"not-found\" };\n\tconst thinking = splitThinkingSuffix(text);\n\tif (thinking) {\n\t\tconst inner = resolveText(thinking.base, request, pool, usable);\n\t\tif (inner.status === \"not-found\") return inner;\n\t\t// Only use this thinking level if no warning from inner recursion\n\t\treturn { ...inner, thinkingLevel: inner.warning ? undefined : thinking.thinkingLevel };\n\t}\n\t// Keep an invalid suffix as part of the id and fail, rather than resolve a different model\n\tif (request.thinkingSuffix === \"strict\") return { status: \"not-found\" };\n\tconst colonIndex = text.lastIndexOf(\":\");\n\tif (colonIndex === -1) return { status: \"not-found\" };\n\n\tconst suffix = text.substring(colonIndex + 1);\n\tconst inner = resolveText(text.substring(0, colonIndex), request, pool, usable);\n\tif (inner.status === \"not-found\") return inner;\n\treturn {\n\t\t...inner,\n\t\tthinkingLevel: undefined,\n\t\twarning: `Invalid thinking level \"${suffix}\" in pattern \"${text}\". Using default instead.`,\n\t};\n}\n\n/**\n * `provider/rest` is only a hint: the whole text may also be a model id on another provider, such as\n * gateway id `zai/glm-5` or commandcode id `xiaomi/mimo-v2.6-pro`. The named provider wins when usable,\n * since that is what the syntax usually means; otherwise a sole usable raw match wins, since the named\n * provider could not serve the request. An unusable named match is still preferred over unusable raw\n * matches, so `--api-key` can set up the named provider.\n */\nfunction selectReference(\n\ttext: string,\n\tpool: readonly Model<Api>[],\n\tfuzzy: boolean,\n\tusable: (provider: string) => boolean,\n): ResolvedOrAmbiguous | undefined {\n\tconst lowerText = text.toLowerCase();\n\tconst raw = pool.filter((model) => model.id.toLowerCase() === lowerText);\n\tconst split = splitProviderPrefix(text, pool);\n\tlet named: Model<Api> | undefined;\n\tif (split) {\n\t\tconst providerModels = pool.filter((model) => model.provider === split.provider);\n\t\tconst lowerModelText = split.modelText.toLowerCase();\n\t\t// The provider's own literal id (OpenRouter's `openrouter/free`) beats its fuzzy matches\n\t\tnamed =\n\t\t\tproviderModels.find((model) => model.id.toLowerCase() === lowerModelText) ??\n\t\t\traw.find((model) => model.provider === split.provider) ??\n\t\t\t(fuzzy ? bestFuzzyMatch(fuzzyMatches(split.modelText, providerModels)) : undefined);\n\t}\n\n\tconst others = raw.filter((model) => model !== named);\n\tconst candidates = named ? [named, ...others] : others;\n\tif (candidates.length === 0) return undefined;\n\tif (new Set(candidates.map((model) => model.provider)).size === 1)\n\t\treturn { status: \"resolved\", model: candidates[0] };\n\tif (named && usable(named.provider)) return { status: \"resolved\", model: named };\n\tconst usableOthers = others.filter((model) => usable(model.provider));\n\tif (usableOthers.length === 1) return { status: \"resolved\", model: usableOthers[0] };\n\tif (usableOthers.length === 0 && named) return { status: \"resolved\", model: named };\n\treturn { status: \"ambiguous\", candidates, usableCount: usableOthers.length };\n}\n\nfunction fuzzyMatches(text: string, models: readonly Model<Api>[]): Model<Api>[] {\n\tconst lowerText = text.toLowerCase();\n\treturn models.filter(\n\t\t(model) => model.id.toLowerCase().includes(lowerText) || model.name?.toLowerCase().includes(lowerText),\n\t);\n}\n\nfunction selectFuzzy(matches: Model<Api>[], usable: (provider: string) => boolean): ResolvedOrAmbiguous | undefined {\n\tif (matches.length === 0) return undefined;\n\tconst multipleProviders = new Set(matches.map((model) => model.provider)).size > 1;\n\tconst usableMatches = multipleProviders ? matches.filter((model) => usable(model.provider)) : [];\n\tconst pool = usableMatches.length > 0 ? usableMatches : matches;\n\tconst best = bestFuzzyMatch(pool);\n\tif (!best) return undefined;\n\t// The same id on several providers would otherwise be decided by catalog order\n\tconst tied = pool.filter((model) => model.id === best.id);\n\tif (new Set(tied.map((model) => model.provider)).size === 1) return { status: \"resolved\", model: best };\n\treturn {\n\t\tstatus: \"ambiguous\",\n\t\tcandidates: tied,\n\t\tusableCount: usableMatches.length > 0 ? tied.length : 0,\n\t};\n}\n\n/** Prefer aliases (`claude-sonnet-4-5`) over dated versions (`claude-sonnet-4-5-20250929`), then the latest. */\nfunction bestFuzzyMatch(matches: readonly Model<Api>[]): Model<Api> | undefined {\n\tconst aliases = matches.filter((model) => isAlias(model.id));\n\treturn [...(aliases.length > 0 ? aliases : matches)].sort((a, b) => b.id.localeCompare(a.id))[0];\n}\n\nfunction isAlias(id: string): boolean {\n\treturn id.endsWith(\"-latest\") || !/-\\d{8}$/.test(id);\n}\n\nfunction buildFallbackModel(providerModels: [Model<Api>, ...Model<Api>[]], modelId: string): Model<Api> {\n\tconst defaultId = defaultModelPerProvider[providerModels[0].provider as KnownProvider];\n\tconst baseModel = defaultId\n\t\t? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])\n\t\t: providerModels[0];\n\n\treturn {\n\t\t...baseModel,\n\t\tid: modelId,\n\t\tname: modelId,\n\t};\n}\n\nexport interface ModelScopeDiagnostic {\n\ttype: \"warning\";\n\tcode: \"no-match\" | \"invalid-thinking-level\" | \"ambiguous\";\n\tmessage: string;\n\tpattern: string;\n}\n\nexport interface ResolveModelScopeResult {\n\tscopedModels: ScopedModel[];\n\tdiagnostics: ModelScopeDiagnostic[];\n}\n\n/**\n * Resolve scope patterns (`--models`, `enabledModels`) to models with optional thinking levels.\n *\n * Every model in `models` is usable, so credentials cannot choose between providers offering the same\n * id. All of them are added, with a warning so the user can pick one with `provider/id`.\n */\nexport function resolveModelScopeFromModels(\n\tpatterns: string[],\n\tmodels: readonly Model<Api>[],\n): ResolveModelScopeResult {\n\tconst scopedModels: ScopedModel[] = [];\n\tconst diagnostics: ModelScopeDiagnostic[] = [];\n\tconst add = (model: Model<Api>, thinkingLevel: ThinkingLevel | undefined) => {\n\t\tif (!scopedModels.some((scoped) => modelsAreEqual(scoped.model, model))) {\n\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t}\n\t};\n\tconst noMatch = (pattern: string) =>\n\t\tdiagnostics.push({ type: \"warning\", code: \"no-match\", message: `No models match pattern \"${pattern}\"`, pattern });\n\tconst ambiguous = (pattern: string, candidates: readonly Model<Api>[]) => {\n\t\tconst providers = [...new Set(candidates.map((m) => m.provider))].sort((a, b) => a.localeCompare(b));\n\t\tdiagnostics.push({\n\t\t\ttype: \"warning\",\n\t\t\tcode: \"ambiguous\",\n\t\t\tmessage: `Pattern \"${pattern}\" matches several providers: ${providers.join(\", \")}. Use provider/id to choose one.`,\n\t\t\tpattern,\n\t\t});\n\t};\n\n\tfor (const pattern of patterns) {\n\t\t// Check if pattern contains glob characters\n\t\tif (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\")) {\n\t\t\t// Extract optional thinking level suffix (e.g., \"provider/*:high\")\n\t\t\tconst thinking = splitThinkingSuffix(pattern);\n\t\t\tconst globPattern = thinking?.base ?? pattern;\n\t\t\tconst thinkingLevel = thinking?.thinkingLevel;\n\n\t\t\t// Ids such as `bracketed-model[1m]` are not globs\n\t\t\tconst exact = resolveModelReference(\n\t\t\t\t{ text: globPattern, thinkingSuffix: \"none\", fuzzy: false },\n\t\t\t\tmodels,\n\t\t\t\t() => true,\n\t\t\t);\n\t\t\tlet matches: readonly Model<Api>[] = [];\n\t\t\tif (exact.status === \"resolved\") matches = [exact.model];\n\t\t\telse if (exact.status === \"ambiguous\") {\n\t\t\t\tmatches = exact.candidates;\n\t\t\t\tambiguous(pattern, matches);\n\t\t\t} else {\n\t\t\t\t// Match against \"provider/modelId\" format OR just model ID\n\t\t\t\t// This allows \"*sonnet*\" to match without requiring \"anthropic/*sonnet*\"\n\t\t\t\tmatches = models.filter(\n\t\t\t\t\t(m) =>\n\t\t\t\t\t\tminimatch(`${m.provider}/${m.id}`, globPattern, { nocase: true }) ||\n\t\t\t\t\t\tminimatch(m.id, globPattern, { nocase: true }),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (matches.length === 0) noMatch(pattern);\n\t\t\tfor (const model of matches) add(model, thinkingLevel);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst result = resolveModelReference(\n\t\t\t{ text: pattern, thinkingSuffix: \"lenient\", fuzzy: true },\n\t\t\tmodels,\n\t\t\t() => true,\n\t\t);\n\t\tif (result.status === \"not-found\") {\n\t\t\tnoMatch(pattern);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"invalid-thinking-level\", message: result.warning, pattern });\n\t\t}\n\t\tif (result.status === \"ambiguous\") ambiguous(pattern, result.candidates);\n\t\tconst matches = result.status === \"resolved\" ? [result.model] : result.candidates;\n\t\tfor (const model of matches) add(model, result.thinkingLevel);\n\t}\n\n\treturn { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScopeWithDiagnostics(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n\toptions?: AuthOperationOptions,\n): Promise<ResolveModelScopeResult> {\n\treturn resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options));\n}\n\nexport interface ResolveCliModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n\t/**\n\t * Error message suitable for CLI display.\n\t * When set, model will be undefined.\n\t */\n\terror: string | undefined;\n}\n\n/**\n * Resolve a single model from CLI flags.\n *\n * Supports:\n * - --provider <provider> --model <pattern>\n * - --model <provider>/<pattern>\n * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)\n *\n * Note: This does not apply the thinking level by itself, but it may *parse* and\n * return a thinking level from \"<pattern>:<thinking>\" so the caller can apply it.\n */\nexport function resolveCliModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tcliThinking?: ThinkingLevel;\n\t/** `--api-key` was supplied for the selected provider. */\n\tinlineApiKey?: boolean;\n\tmodelRuntime: ModelRuntime;\n}): ResolveCliModelResult {\n\tconst { cliProvider, cliModel, cliThinking, inlineApiKey, modelRuntime } = options;\n\n\tif (!cliModel) {\n\t\treturn { model: undefined, warning: undefined, error: undefined };\n\t}\n\n\t// Important: use *all* models here, not just models with pre-configured auth.\n\t// This allows \"--api-key\" to be used for first-time setup.\n\tconst models = [...modelRuntime.getModels()];\n\tif (models.length === 0) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: \"No models available. Check your installation or add models to models.json.\",\n\t\t};\n\t}\n\n\tconst provider = cliProvider\n\t\t? models.find((m) => m.provider.toLowerCase() === cliProvider.toLowerCase())?.provider\n\t\t: undefined;\n\tif (cliProvider && !provider) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Unknown provider \"${cliProvider}\". Use --list-models to see available providers/models.`,\n\t\t};\n\t}\n\n\tconst result = resolveModelReference(\n\t\t{ text: cliModel, provider, thinkingSuffix: \"strict\", fuzzy: true },\n\t\tmodels,\n\t\t// An inline key goes to whichever provider is selected, so stored credentials must not choose it\n\t\tinlineApiKey ? () => false : (providerId) => modelRuntime.hasConfiguredAuth(providerId),\n\t);\n\tif (result.status === \"resolved\") {\n\t\treturn { model: result.model, thinkingLevel: result.thinkingLevel, warning: result.warning, error: undefined };\n\t}\n\tif (result.status === \"ambiguous\") {\n\t\tconst matches = result.candidates\n\t\t\t.map((m) => `${m.provider}/${m.id}`)\n\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t.join(\", \");\n\t\tconst authHint = inlineApiKey\n\t\t\t? \"--api-key does not choose a provider.\"\n\t\t\t: result.usableCount === 0\n\t\t\t\t? \"No matching provider is authenticated.\"\n\t\t\t\t: \"More than one matching provider is authenticated.\";\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Model \"${cliModel}\" is ambiguous across providers: ${matches}. ${authHint} Use --provider or provider/model.`,\n\t\t};\n\t}\n\n\tconst { target } = result;\n\tif (!target) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Model \"${cliModel}\" not found. Use --list-models to see available models.`,\n\t\t};\n\t}\n\n\t// Use the thinking level suffix only when --thinking is not explicitly provided; otherwise it\n\t// stays part of the custom model id.\n\t// e.g. \"zai-org/GLM-5.1-FP8:high\" → modelId=\"zai-org/GLM-5.1-FP8\", fallbackThinking=\"high\"\n\tconst modelId = cliThinking ? target.modelText : target.modelId;\n\tconst fallbackThinking = cliThinking ? undefined : target.thinkingLevel;\n\tconst fallbackModel = buildFallbackModel(target.providerModels, modelId);\n\tconst requestedThinking = cliThinking ?? fallbackThinking;\n\treturn {\n\t\tmodel: requestedThinking && requestedThinking !== \"off\" ? { ...fallbackModel, reasoning: true } : fallbackModel,\n\t\tthinkingLevel: fallbackThinking,\n\t\twarning: `Model \"${modelId}\" not found for provider \"${target.provider}\". Using custom model id.`,\n\t\terror: undefined,\n\t};\n}\n\nexport interface InitialModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel: ThinkingLevel;\n\tfallbackMessage: string | undefined;\n}\n\n/**\n * Find the initial model to use based on priority:\n * 1. First model from scoped models (if not continuing/resuming)\n * 2. Saved default from settings\n * 3. First available model with valid API key\n */\nexport async function findInitialModel(options: {\n\tscopedModels: ScopedModel[];\n\tisContinuing: boolean;\n\tdefaultProvider?: string;\n\tdefaultModelId?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tmodelThinkingLevels?: Record<string, ThinkingLevel>;\n\tmodelRuntime: ModelRuntime;\n}): Promise<InitialModelResult> {\n\tconst {\n\t\tscopedModels,\n\t\tisContinuing,\n\t\tdefaultProvider,\n\t\tdefaultModelId,\n\t\tdefaultThinkingLevel,\n\t\tmodelThinkingLevels,\n\t\tmodelRuntime,\n\t} = options;\n\n\tlet model: Model<Api> | undefined;\n\tlet thinkingLevel: ThinkingLevel = DEFAULT_THINKING_LEVEL;\n\n\t// 1. Use first model from scoped models (skip if continuing/resuming)\n\tif (scopedModels.length > 0 && !isContinuing) {\n\t\tconst scopedModel = scopedModels[0];\n\t\tconst perModel = modelThinkingLevels?.[`${scopedModel.model.provider}/${scopedModel.model.id}`];\n\t\treturn {\n\t\t\tmodel: scopedModel.model,\n\t\t\tthinkingLevel: scopedModel.thinkingLevel ?? perModel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t\tfallbackMessage: undefined,\n\t\t};\n\t}\n\n\t// 2. Try saved default from settings if auth is configured.\n\tif (defaultProvider && defaultModelId) {\n\t\tconst found = modelRuntime.getModel(defaultProvider, defaultModelId);\n\t\tif (found && modelRuntime.hasConfiguredAuth(found.provider)) {\n\t\t\tmodel = found;\n\t\t\tconst perModel = modelThinkingLevels?.[`${defaultProvider}/${defaultModelId}`];\n\t\t\tif (perModel) {\n\t\t\t\tthinkingLevel = perModel;\n\t\t\t} else if (defaultThinkingLevel) {\n\t\t\t\tthinkingLevel = defaultThinkingLevel;\n\t\t\t}\n\t\t\treturn { model, thinkingLevel, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 3. Try first available model with valid API key\n\tconst availableModels = [...modelRuntime.getAvailableSnapshot()];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\treturn { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\treturn { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t}\n\n\t// 4. No model found\n\treturn { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n}\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vercel, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|