blade-code 0.5.6 → 0.5.7

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.
@@ -1,2 +1,2 @@
1
- var e={name:"blade-code",version:"0.5.6",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
1
+ var e={name:"blade-code",version:"0.5.7",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/ready.ts","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function d(){return`v${e.version}`}function a(){return`v${e.version} © 2025 Blade Code`}
2
2
  export{r as aa,n as ba,o as ca,c as da,d as ea,a as fa};
@@ -1,4 +1,4 @@
1
- import{N as l,O as c,P as m,S as g,U as d}from"./chunk-vczer7sc.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
1
+ import{N as l,O as c,P as m,S as g,U as d}from"./chunk-tjzyqsnc.js";import{xb as u}from"./chunk-7ycmx7c2.js";async function C(){if((await l().initialize(u(),[])).plugins.length>0)await c()}async function h(t){let e=t.message||t._?.[0];if(typeof e==="string"&&e.trim())return e;let n=t.stdin??process.stdin;if(!n.isTTY){let a=[];for await(let i of n)a.push(i);return Buffer.concat(a).toString("utf-8").trim()}if(t.defaultMessage!==void 0)return t.defaultMessage;throw Error("No input provided")}async function R(t){if(!g(t))return{mode:"agent",content:t};let e=await d(t,{cwd:u(),workspaceRoot:u()});if(!e.success)return{mode:"output",content:`Error: ${e.error||"未知错误"}`,exitCode:1};let n=e.data;if(n?.action==="invoke_skill"){let{skillName:a,skillArgs:i}=n;return{mode:"agent",content:i?`Please use the "${a}" skill to help me with: ${i}`:`Please use the "${a}" skill.`}}if(n?.action==="invoke_custom_command"||n?.action==="invoke_plugin_command"){let a=n.processedContent;return{mode:"agent",content:`# Custom Command: /${n.commandName}
2
2
 
3
3
  ${a}`}}return{mode:"output",content:e.content||e.message||"",exitCode:0}}function r(t){if(!(t instanceof Error))return!1;return t.message.includes("未找到会话")||t.message.includes("ENOENT")||t.message.includes("no such file")}async function s(t){try{return await m.loadSession(t,u())}catch(e){if(r(e))return null;throw e}}async function N(t){if(t.resume===!0||t.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof t.resume==="string"&&t.resume.length>0)return{sessionId:t.resume,messages:await m.loadSession(t.resume)};if(t.continue){let e=await m.listSessions();if(e.length>0){let n=e[0].sessionId;return{sessionId:n,messages:await m.loadSession(n)}}}if(t.sessionId)return{sessionId:t.sessionId,messages:await s(t.sessionId)??[]};return{sessionId:`${t.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{C as p,h as q,R as r,N as s};
@@ -1 +1 @@
1
- import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-9d7yjmfz.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f}from"./chunk-vppcvxzd.js";import"./chunk-j2ag7hh6.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{rb as a}from"./chunk-9rz6rpcc.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as createChatServiceAsync};
1
+ import{rb as a}from"./chunk-37rethcy.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{a as createChatServiceAsync};
@@ -1 +1 @@
1
- import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-ss9qx677.js";import"./chunk-yddnm9n2.js";import"./chunk-p3znznzd.js";import"./chunk-9rz6rpcc.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
1
+ import{$a as l,Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f,Wa as g,Xa as h,Ya as i,Za as j,_a as k,ab as m,bb as n,cb as o,fb as p,gb as q,hb as r}from"./chunk-10js1kwp.js";import"./chunk-yddnm9n2.js";import"./chunk-1e2phnbj.js";import"./chunk-37rethcy.js";import"./chunk-7ycmx7c2.js";import"./chunk-set7v1rf.js";import"./chunk-j2ag7hh6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,a as isRootSystemPrompt,l as handleTaskListUpdate,m as handleSkillActivation,n as extractModelSwitch,r as executeLoopGenerator,c as drainLoop,f as checkStopHook,d as checkOutputRecovery,e as checkIncompleteIntent,q as checkAndCompactInLoop,o as applyToolDomainEffects,p as StreamingToolExecutor,b as ConversationState};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.5.6",
3
+ "version": "0.5.7",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-x1fbv16h.js";import"./chunk-9d7yjmfz.js";import"./chunk-j2ag7hh6.js";export{a as globalOptions,b as cliConfig};
@@ -1,8 +0,0 @@
1
- import{Bb as S}from"./chunk-set7v1rf.js";var f=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],u={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},c={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},T={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},H=(Q)=>{return T[Q]||{}};import{createAnthropic as A}from"@ai-sdk/anthropic";import{createAzure as K}from"@ai-sdk/azure";import{createDeepSeek as I}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as E}from"@ai-sdk/google";import{createOpenAI as y}from"@ai-sdk/openai";import{createOpenAICompatible as V}from"@ai-sdk/openai-compatible";import{generateText as U,jsonSchema as x,streamText as M}from"ai";var j=S("Chat");function O(Q){let q=new Set;for(let Y of Q)if(Y.role==="assistant"&&Y.tool_calls)for(let W of Y.tool_calls)q.add(W.id);return Q.filter((Y)=>{if(Y.role==="tool"){if(!Y.tool_call_id)return!1;return q.has(Y.tool_call_id)}return!0})}function L(Q){if(typeof Q==="string")return Q;return Q.filter((q)=>q.type==="text").map((q)=>q.text).join(`
2
- `)}function h(Q){let q=Q;return q.text??q.textDelta??q.delta}function C(Q,q={}){try{return JSON.parse(Q)}catch{return j.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:Q}),q}}class R{model;config;constructor(Q){this.config=Q,this.model=this.createModel(Q),j.debug("[VercelAIChatService] Initialized",{provider:Q.provider,model:Q.model})}createModel(Q){let{provider:q,apiKey:Y,baseUrl:W,model:X,customHeaders:Z,apiVersion:J}=Q;switch(q){case"openai":return y({apiKey:Y,baseURL:W||void 0,headers:Z})(X);case"anthropic":return A({apiKey:Y,baseURL:W||void 0,headers:Z})(X);case"gemini":{if(W&&!this.isGeminiOfficialUrl(W))return V({name:"gemini",apiKey:Y,baseURL:W,headers:Z})(X);return E({apiKey:Y,baseURL:W||void 0})(X)}case"google":case"google-generative-ai":case"google-vertex":{if(W&&!this.isGeminiOfficialUrl(W))return V({name:q,apiKey:Y,baseURL:W,headers:Z})(X);return E({apiKey:Y,baseURL:W||void 0})(X)}case"azure-openai":{let $=this.extractAzureResourceName(W);if($)return K({apiKey:Y,resourceName:$,apiVersion:J||"2024-08-01-preview"})(X);let _=this.buildAzureBaseUrl(W,X);return V({name:"azure-openai",apiKey:Y,baseURL:_,headers:{...Z,"api-key":Y},queryParams:{"api-version":J||"2024-08-01-preview"}})(X)}case"azure":{let $=this.extractAzureResourceName(W);if($)return K({apiKey:Y,resourceName:$,apiVersion:J||"2024-08-01-preview"})(X);let _=this.buildAzureBaseUrl(W,X);return V({name:"azure-openai",apiKey:Y,baseURL:_,headers:{...Z,"api-key":Y},queryParams:{"api-version":J||"2024-08-01-preview"}})(X)}case"deepseek":return I({apiKey:Y,baseURL:W||void 0,headers:Z})(X);default:return V({name:q,apiKey:Y,baseURL:W,headers:Z})(X)}}extractAzureResourceName(Q){if(!Q)return;let q=Q.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return q?q[1]:void 0}buildAzureBaseUrl(Q,q){if(!Q)return"";let Y=Q.replace(/\/$/,"").replace(/\?.*$/,"");if(Y.includes("/openai/deployments/"))return Y;return`${Y}/openai/deployments/${q}`}isGeminiOfficialUrl(Q){return Q.includes("generativelanguage.googleapis.com")||Q.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(Q){let q=Q?.trim();if(!q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}flattenDeepSeekThinkingToolHistory(Q){let q=[],Y,W=()=>{if(!Y)return;q.push({role:"assistant",content:L(Y.content).trim()||"I will use the requested tool and continue from its result."}),Y=void 0};for(let X of Q){if(X.role==="system"){W(),q.push({role:"user",content:`<system>
3
- ${L(X.content)}
4
- </system>`});continue}if(X.role==="assistant"&&X.tool_calls&&X.tool_calls.length>0&&X.reasoningContent?.trim()){W(),Y=X;continue}if(X.role==="tool"&&Y){let Z=Y.tool_calls?.find(($)=>$.id===X.tool_call_id),J=Z?.type==="function"?Z.function:void 0;q.push({role:"user",content:`Tool result for ${X.name||J?.name||"tool"}${J?.arguments?`(${J.arguments})`:""}:
5
- ${L(X.content)}
6
-
7
- Continue from this tool result.`});continue}W(),q.push(X)}return W(),q}convertMessages(Q){let q=[],Y=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(Q):Q;for(let W of Y)if(W.role==="system")if(Array.isArray(W.content)){let X=W.content.find((J)=>J.type==="text"),Z={role:"system",content:L(W.content)};if(X?.providerOptions)Z.providerOptions=X.providerOptions;q.push(Z)}else q.push({role:"system",content:W.content});else if(W.role==="user")if(Array.isArray(W.content)){let X=W.content.map((Z)=>{if(Z.type==="text"){let J={type:"text",text:Z.text};if(Z.providerOptions)J.providerOptions=Z.providerOptions;return J}return{type:"image",image:Z.image_url.url}});q.push({role:"user",content:X})}else q.push({role:"user",content:W.content});else if(W.role==="assistant")if(W.tool_calls&&W.tool_calls.length>0){let X=W.tool_calls.map((_)=>{let w=_.function;return{type:"tool-call",toolCallId:_.id,toolName:w?.name||"",input:C(w?.arguments||"{}",{})}}),Z=L(W.content),J=W.reasoningContent?.trim()?[{type:"reasoning",text:W.reasoningContent}]:[],$=this.getThinkingReplayProviderOptions(W.reasoningContent);if(Z){let _={role:"assistant",content:[...J,{type:"text",text:Z},...X]};if($)_.providerOptions=$;q.push(_)}else if(J.length>0){let _={role:"assistant",content:[...J,...X]};if($)_.providerOptions=$;q.push(_)}else q.push({role:"assistant",content:X})}else if(W.reasoningContent?.trim()){let X=L(W.content),Z=[{type:"reasoning",text:W.reasoningContent}];if(X)Z.push({type:"text",text:X});let J={role:"assistant",content:Z},$=this.getThinkingReplayProviderOptions(W.reasoningContent);if($)J.providerOptions=$;q.push(J)}else q.push({role:"assistant",content:L(W.content)});else if(W.role==="tool")q.push({role:"tool",content:[{type:"tool-result",toolCallId:W.tool_call_id,toolName:W.name||"unknown",output:{type:"text",value:L(W.content)}}]});if(this.config.enablePromptCaching&&this.config.provider==="anthropic"){let W=0;for(let X of q)if(X.role==="system"&&W<2)X.providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}},W++;for(let X=q.length-1;X>=0;X--)if(q[X].role==="user"){q[X].providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}};break}}return q}convertTools(Q){if(!Q||Q.length===0)return;let q={};for(let Y of Q)q[Y.name]={description:Y.description,inputSchema:x(Y.parameters)};return q}convertToolCalls(Q){return Q.map((q)=>({id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.args??q.input??{})}}))}convertUsage(Q,q){if(!Q)return;let Y=Q.promptTokens??Q.inputTokens??0,W=Q.completionTokens??Q.outputTokens??0,X={promptTokens:Y,completionTokens:W,totalTokens:Q.totalTokens??Y+W};if(Q.reasoningTokens)X.reasoningTokens=Q.reasoningTokens;if(q?.anthropic){if(q.anthropic.cacheCreationInputTokens!==void 0)X.cacheCreationInputTokens=q.anthropic.cacheCreationInputTokens;if(q.anthropic.cacheReadInputTokens!==void 0)X.cacheReadInputTokens=q.anthropic.cacheReadInputTokens}return X}isFallbackableError(Q){if(!(Q instanceof Error))return!1;let q=Q.message.toLowerCase();if(q.includes("timeout")||q.includes("econnrefused")||q.includes("enotfound"))return!0;let Y=q.match(/status[:\s]*(\d{3})/),W=Y?parseInt(Y[1],10):Q.status;return W!==void 0&&[429,529,503,502,500].includes(W)}async retryWithBackoff(Q,q,Y=2,W=1000){let X;for(let Z=0;Z<=Y;Z++)try{return await Q()}catch(J){if(X=J,Z>=Y)break;if(!this.isFallbackableError(J))throw J;if(q?.aborted)throw J;let $=W*Math.pow(2,Z);j.debug(`[VercelAIChatService] Retry ${Z+1}/${Y} after ${$}ms`),await new Promise((_)=>setTimeout(_,$))}throw X}getFallbackModelIds(){let Q=[];if(this.config.fallbackModels&&this.config.fallbackModels.length>0)Q.push(...this.config.fallbackModels);else if(this.config.fallbackModel)Q.push(this.config.fallbackModel);return Q}getThinkingProviderOptions(){if(!this.config.supportsThinking)return;let Q=this.config.thinkingBudget??1e4;if(this.config.provider==="anthropic")return{anthropic:{thinking:{type:"enabled",budgetTokens:Q}}};if(this.config.provider==="deepseek"||/deepseek/i.test(this.config.model))return{deepseek:{thinking:{type:"enabled",budgetTokens:Q}}};return}getStreamTextOptions(Q,q,Y,W){let X=W;if(this.config.timeout&&this.config.timeout>0){let $=AbortSignal.timeout(this.config.timeout);if(W)X=AbortSignal.any([W,$]);else X=$}let Z={model:Q,messages:q,tools:Y,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature??0,abortSignal:X,allowSystemInMessages:!0},J=this.getThinkingProviderOptions();if(J)Z.providerOptions=J;return Z}async chat(Q,q,Y){let W=Date.now();j.debug("[VercelAIChatService] Starting chat request");let X=O(Q),Z=this.convertMessages(X),J=this.convertTools(q),$=async(_)=>{let w=await U(this.getStreamTextOptions(_,Z,J,Y)),N=w.toolCalls&&w.toolCalls.length>0?this.convertToolCalls(w.toolCalls):void 0,z=Array.isArray(w.reasoning)?w.reasoning.map((B)=>B.text).join(""):void 0;return{content:w.text,reasoningContent:z,toolCalls:N,usage:this.convertUsage(w.usage,w.providerMetadata),finishReason:w.finishReason}};try{return await this.retryWithBackoff(()=>$(this.model),Y,this.config.maxRetries)}catch(_){let w=Date.now()-W;if(j.error("[VercelAIChatService] Chat failed after",w,"ms"),!this.isFallbackableError(_))throw _;let N=this.getFallbackModelIds();if(N.length===0)throw _;for(let z of N){j.warn(`[VercelAIChatService] Trying fallback model: ${z}`);let B=this.createModel({...this.config,model:z});try{return await $(B)}catch(F){if(j.warn(`[VercelAIChatService] Fallback ${z} failed: ${F instanceof Error?F.message:F}`),!this.isFallbackableError(F))throw F}}throw _}}async*streamChat(Q,q,Y){let W=Date.now();j.debug("[VercelAIChatService] Starting stream request");let X=O(Q),Z=this.convertMessages(X),J=this.convertTools(q),$=async function*(B,F){let D=M(B.getStreamTextOptions(F,Z,J,Y)),P=0;for await(let G of D.fullStream)switch(G.type){case"text-delta":yield{content:h(G)};break;case"reasoning-delta":yield{reasoningContent:h(G)};break;case"tool-call":yield{toolCalls:[{index:P++,id:G.toolCallId,type:"function",function:{name:G.toolName,arguments:JSON.stringify(G.args??G.input??{})}}]};break;case"finish":yield{finishReason:G.finishReason,usage:B.convertUsage(G.totalUsage,G.providerMetadata)};break}},_=this.config.maxRetries??2,w;for(let B=0;B<=_;B++)try{yield*$(this,this.model);let F=Date.now()-W;j.debug("[VercelAIChatService] Stream completed in",F,"ms");return}catch(F){if(w=F,!this.isFallbackableError(F))throw F;if(B<_){let D=1000*Math.pow(2,B);j.debug(`[VercelAIChatService] Stream retry ${B+1}/${_} after ${D}ms`),await new Promise((P)=>setTimeout(P,D));continue}}let N=Date.now()-W;j.error("[VercelAIChatService] Stream failed after",N,"ms");let z=this.getFallbackModelIds();if(z.length===0)throw w;for(let B of z){j.warn(`[VercelAIChatService] Stream fallback: ${B}`),yield{modelFallback:!0};let F=this.createModel({...this.config,model:B});try{yield*$(this,F);return}catch(D){if(j.warn(`[VercelAIChatService] Stream fallback ${B} failed`),!this.isFallbackableError(D))throw D}}throw w}getConfig(){return{...this.config}}updateConfig(Q){j.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...Q},this.model=this.createModel(this.config),j.debug("[VercelAIChatService] Configuration updated")}}var v=S("Service");async function qq(Q){let q=Q;if(q.provider){let Y=H(q.provider);if(Object.keys(Y).length>0)q={...q,customHeaders:{...Y,...q.customHeaders}},v.debug(`Injected ${q.provider} specific headers:`,Object.keys(Y))}return b(q)}function b(Q){return new R(Q)}
8
- export{f as ob,u as pb,c as qb,qq as rb};