zen-code 4.8.3 → 4.8.4

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,4 +1,4 @@
1
- import{yb as _}from"./chunk-mrkf2b3t.js";import{Bb as T,Cb as V,Db as x,Eb as R,zb as G}from"./chunk-pnhf6jtr.js";function Z($,f="Human",J="AI"){let q=[];for(let B of $){let U;if(B.type==="human")U=f;else if(B.type==="ai")U=J;else if(B.type==="system")U="System";else if(B.type==="tool")U="Tool";else if(B.type==="generic")U=B.role;else throw Error(`Got unsupported message type: ${B.type}`);let O=B.name?`${B.name}, `:"",Q=typeof B.content==="string"?B.content:JSON.stringify(B.content,null,2);q.push(`${U}: ${O}${Q}`)}return q.join(`
1
+ import{yb as _}from"./chunk-zf08x9b0.js";import{Bb as T,Cb as V,Db as x,Eb as R,zb as G}from"./chunk-cp9xkgbn.js";function Z($,f="Human",J="AI"){let q=[];for(let B of $){let U;if(B.type==="human")U=f;else if(B.type==="ai")U=J;else if(B.type==="system")U="System";else if(B.type==="tool")U="Tool";else if(B.type==="generic")U=B.role;else throw Error(`Got unsupported message type: ${B.type}`);let O=B.name?`${B.name}, `:"",Q=typeof B.content==="string"?B.content:JSON.stringify(B.content,null,2);q.push(`${U}: ${O}${Q}`)}return q.join(`
2
2
  `)}import{REMOVE_ALL_MESSAGES as j,START as I,StateGraph as S}from"@langchain/langgraph";import{AIMessage as v,RemoveMessage as u}from"@langchain/core/messages";import{HumanMessage as b}from"@langchain/core/messages";import{z as K}from"zod";import{promises as W}from"fs";import X from"path";import N from"yaml";var H=($)=>{return $?.replace(process.cwd(),".")||$||""};import{createAgent as P,toolStrategy as p}from"langchain";var E=K.object({summary_of_chat:K.string().describe("对话总结(300-500字):1) 完整复现对话的核心过程(任务背景→关键决策→解决方案→最终结果);2) 明确说明接下来要做什么(后续行动、待完成任务、需要用户确认的事项);3) 突出关键成果和交付物"),name:K.string().describe("记忆名称(kebab-case 格式)"),description:K.string().describe("对于这个记忆的中等长度描述(索引综述,200-500字符,包含背景、关键点、适用场景)"),tags:K.array(K.string()).describe("记忆标签"),category:K.enum(["architecture","bug-fix","workflow","configuration","optimization"]).describe("记忆分类"),created:K.string().describe("创建日期(ISO 格式:YYYY-MM-DD)"),last_updated:K.string().describe("最后更新日期(ISO 格式:YYYY-MM-DD)"),priority:K.enum(["high","medium","low"]).describe("优先级"),context_scope:K.enum(["user","project"]).describe("上下文范围"),content:K.string().describe("记忆内容(详细说明,包含代码示例)")}),k=`你是一个负责分析对话并提取关键信息的智能助手。
3
3
 
4
4
  ## 任务
@@ -1 +1 @@
1
- import{nb as a,ob as b,pb as c}from"./chunk-rxxn6qxm.js";import"./chunk-pnhf6jtr.js";import"./chunk-y5pf2d0x.js";import"./chunk-v28dexnx.js";import"./chunk-4n978rje.js";import"./chunk-wtwgpw9g.js";import"./chunk-vkfhjhhh.js";import"./chunk-0gpa9n28.js";import"./chunk-feptb1bb.js";export{c as getAgentListFromPackage,a as createSubAgentsMiddleware,b as SubAgentsMiddleware};
1
+ import{nb as a,ob as b,pb as c}from"./chunk-qejfdzc7.js";import"./chunk-cp9xkgbn.js";import"./chunk-y5pf2d0x.js";import"./chunk-v28dexnx.js";import"./chunk-4n978rje.js";import"./chunk-wtwgpw9g.js";import"./chunk-vkfhjhhh.js";import"./chunk-0gpa9n28.js";import"./chunk-feptb1bb.js";export{c as getAgentListFromPackage,a as createSubAgentsMiddleware,b as SubAgentsMiddleware};
@@ -1,4 +1,4 @@
1
- import{Gb as a}from"./chunk-y5pf2d0x.js";import{dc as s}from"./chunk-wtwgpw9g.js";import{Annotation as S}from"@langchain/langgraph";var _=(...G)=>{return{build:(U={})=>{return S.Root(Object.assign({},...G.map((L)=>L.spec),U))}}},H=(G)=>S({reducer:(U,L)=>L,default:G});import{tool as G1}from"@langchain/core/tools";import{z as P}from"zod";var U1=P.object({thought:P.string().describe("Your current thinking step"),nextThoughtNeeded:P.boolean().describe("Whether another thought step is needed"),thoughtNumber:P.number().min(1).describe("Current thought number"),totalThoughts:P.number().min(1).describe("Estimated total thoughts needed"),isRevision:P.boolean().optional().describe("Whether this revises previous thinking"),revisesThought:P.number().min(1).optional().describe("Which thought is being reconsidered"),branchFromThought:P.number().min(1).optional().describe("Branching point thought number"),branchId:P.string().optional().describe("Branch identifier"),needsMoreThoughts:P.boolean().optional().describe("If more thoughts are needed")}),w=[],I={},g1=G1(async(G)=>{try{if(G.thoughtNumber>G.totalThoughts)G.totalThoughts=G.thoughtNumber;if(w.push(G),G.branchFromThought&&G.branchId){if(!I[G.branchId])I[G.branchId]=[];I[G.branchId].push(G)}return JSON.stringify({thoughtNumber:G.thoughtNumber,totalThoughts:G.totalThoughts,nextThoughtNeeded:G.nextThoughtNeeded,branches:Object.keys(I),thoughtHistoryLength:w.length},null,2)}catch(U){return JSON.stringify({error:U instanceof Error?U.message:String(U),status:"failed"},null,2)}},{name:"sequential-thinking",description:`A detailed tool for dynamic and reflective problem-solving through thoughts.
1
+ import{Gb as a}from"./chunk-y5pf2d0x.js";import{dc as s}from"./chunk-wtwgpw9g.js";import{Annotation as S}from"@langchain/langgraph";var _=(...G)=>{return{build:(U={})=>{return S.Root(Object.assign({},...G.map((L)=>L.spec),U))}}},q=(G)=>S({reducer:(U,L)=>L,default:G});import{tool as G1}from"@langchain/core/tools";import{z as P}from"zod";var U1=P.object({thought:P.string().describe("Your current thinking step"),nextThoughtNeeded:P.boolean().describe("Whether another thought step is needed"),thoughtNumber:P.number().min(1).describe("Current thought number"),totalThoughts:P.number().min(1).describe("Estimated total thoughts needed"),isRevision:P.boolean().optional().describe("Whether this revises previous thinking"),revisesThought:P.number().min(1).optional().describe("Which thought is being reconsidered"),branchFromThought:P.number().min(1).optional().describe("Branching point thought number"),branchId:P.string().optional().describe("Branch identifier"),needsMoreThoughts:P.boolean().optional().describe("If more thoughts are needed")}),w=[],I={},g1=G1(async(G)=>{try{if(G.thoughtNumber>G.totalThoughts)G.totalThoughts=G.thoughtNumber;if(w.push(G),G.branchFromThought&&G.branchId){if(!I[G.branchId])I[G.branchId]=[];I[G.branchId].push(G)}return JSON.stringify({thoughtNumber:G.thoughtNumber,totalThoughts:G.totalThoughts,nextThoughtNeeded:G.nextThoughtNeeded,branches:Object.keys(I),thoughtHistoryLength:w.length},null,2)}catch(U){return JSON.stringify({error:U instanceof Error?U.message:String(U),status:"failed"},null,2)}},{name:"sequential-thinking",description:`A detailed tool for dynamic and reflective problem-solving through thoughts.
2
2
  This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
3
3
  Each thought can build on, question, or revise previous insights as understanding deepens.
4
4
 
@@ -20,7 +20,7 @@ Key features:
20
20
  - Generates a solution hypothesis
21
21
  - Verifies the hypothesis based on the Chain of Thought steps
22
22
  - Repeats the process until satisfied
23
- - Provides a correct answer`,schema:U1});import{tool as f}from"@langchain/core/tools";import{z as q}from"zod";var L1=q.object({url:q.string().url().describe("the url to crawl"),raw:q.boolean().optional().default(!1).describe("return raw html")}),W1=q.object({query:q.string().describe("the query to search"),engines:q.array(q.enum(["basic","npm","juejin","anthropic","github"])).default(["basic"]).describe("the engines to use"),returnType:q.enum(["json","markdown"]).default("json").describe("the content type to return"),withMetadata:q.boolean().default(!0).describe("whether to include metadata in the search results")}),t1=f(async({url:G})=>{if(!G)return{status:"error",error:"URL is required"};let U=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/extract`,{method:"POST",body:JSON.stringify({url:G})});if(!U.ok)throw Error(`HTTP error! status: ${U.status}`);return await U.text()},{name:"read_web_page",description:"A powerful web content extraction tool that retrieves and processes raw content from specified URLs, ideal for data collection, content analysis, and research tasks.",schema:q.object(L1.shape)}),s1=f(async({query:G,engines:U})=>{let L=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/search`,{method:"POST",body:JSON.stringify({query:G,engines:U,returnType:"json",withMetadata:!0})});if(!L.ok)throw Error(`HTTP error! status: ${L.status}`);return await L.text()},{name:"web_search",description:"A powerful web search tool that provides comprehensive, real-time results using search engine. Returns relevant web content with customizable parameters for result count, content type, and domain filtering. Ideal for gathering current information, news, and detailed web content analysis.",schema:q.object(W1.shape)});import{AIMessage as Y0,ToolMessage as Z0}from"@langchain/core/messages";import{AIMessage as L0,HumanMessage as W0,SystemMessage as X0,ToolMessage as B0}from"@langchain/core/messages";var V0=(G)=>{return G?.configurable?.thread_id};import{Command as $0,getCurrentTaskInput as H0}from"@langchain/langgraph";import{z as O0}from"zod";import{ToolMessage as F0}from"@langchain/core/messages";import{tool as z0}from"@langchain/core/tools";import{Annotation as N,MessagesAnnotation as B1,START as _0,StateGraph as D0}from"@langchain/langgraph";var A=N.Root({...B1.spec,activeAgent:N});import{z as M0}from"zod";import{ToolMessage as u0}from"@langchain/core/messages";import{tool as r0}from"@langchain/core/tools";import{Command as p0,getCurrentTaskInput as i0}from"@langchain/langgraph";import{Command as m0}from"@langchain/langgraph";import{ChatOpenAI as GG}from"@langchain/openai";import{SystemMessage as WG,HumanMessage as XG,AIMessageChunk as BG,ToolMessage as JG}from"@langchain/core/messages";import{z as b}from"zod";import{withLangGraph as K1}from"@langchain/langgraph/zod";import{MessagesZodMeta as Y1}from"@langchain/langgraph";var T=b.object({messages:K1(b.custom(),Y1).default([])});import{AIMessage as I1,AIMessageChunk as h1,isAIMessage as _1}from"@langchain/core/messages";import{ChatGenerationChunk as n}from"@langchain/core/outputs";import{wrapOpenAIClientError as D1}from"@langchain/openai";import{convertToOpenAITool as QG,isLangChainTool as jG}from"@langchain/core/utils/function_calling";import{isInteropZodSchema as $G}from"@langchain/core/utils/types";import{toJsonSchema as PG}from"@langchain/core/utils/json_schema";function M(G){if(!G)return;else if(G==="any"||G==="required")return"required";else if(G==="auto")return"auto";else if(G==="none")return"none";else if(typeof G==="string")return{type:"function",function:{name:G}};else return G}import{BaseChatOpenAI as S1}from"@langchain/openai";import{AIMessage as d,AIMessageChunk as Z1,ChatMessage as x1,ChatMessageChunk as V1,FunctionMessageChunk as Q1,HumanMessageChunk as j1,SystemMessageChunk as u,ToolMessage as p,ToolMessageChunk as q1,parseBase64DataUrl as k,parseMimeType as r,isDataContentBlock as $1,iife as H1,convertToProviderContentBlock as P1}from"@langchain/core/messages";import{convertLangChainToolCallToOpenAI as O1,makeInvalidToolCall as E1,parseToolCall as F1}from"@langchain/core/output_parsers/openai_tools";import{isZodSchemaV3 as FG,isZodSchemaV4 as yG}from"@langchain/core/utils/types";import{toJSONSchema as RG,parse as IG}from"zod/v4/core";import{zodResponseFormat as _G}from"openai/helpers/zod";function C(G,U){if(U&&typeof U==="object"&&"images"in U&&Array.isArray(U.images)){let L=U.images.filter((W)=>typeof W?.image_url?.url==="string").map((W)=>({type:"image",url:W.image_url.url}));return[{type:"text",text:G},...L]}return G}import{messageToOpenAIRole as i}from"@langchain/openai";var y1={providerName:"ChatOpenAI",fromStandardTextBlock(G){return{type:"text",text:G.text}},fromStandardImageBlock(G){if(G.source_type==="url")return{type:"image_url",image_url:{url:G.url,...G.metadata?.detail?{detail:G.metadata.detail}:{}}};if(G.source_type==="base64")return{type:"image_url",image_url:{url:`data:${G.mime_type??""};base64,${G.data}`,...G.metadata?.detail?{detail:G.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(G){if(G.source_type==="url"){let U=k({dataUrl:G.url});if(!U)throw Error(`URL audio blocks with source_type ${G.source_type} must be formatted as a data URL for ChatOpenAI`);let L=U.mime_type||G.mime_type||"",W;try{W=r(L)}catch{throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`)}if(W.type!=="audio"||W.subtype!=="wav"&&W.subtype!=="mp3")throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:W.subtype,data:U.data}}}if(G.source_type==="base64"){let U;try{U=r(G.mime_type??"")}catch{throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`)}if(U.type!=="audio"||U.subtype!=="wav"&&U.subtype!=="mp3")throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:U.subtype,data:G.data}}}throw Error(`Audio content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(G){if(G.source_type==="url"){if(!k({dataUrl:G.url}))throw Error(`URL file blocks with source_type ${G.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:G.url,...G.metadata?.filename||G.metadata?.name?{filename:G.metadata?.filename||G.metadata?.name}:{}}}}if(G.source_type==="base64")return{type:"file",file:{file_data:`data:${G.mime_type??""};base64,${G.data}`,...G.metadata?.filename||G.metadata?.name||G.metadata?.title?{filename:G.metadata?.filename||G.metadata?.name||G.metadata?.title}:{}}};if(G.source_type==="id")return{type:"file",file:{file_id:G.id}};throw Error(`File content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)}},c=({message:G,rawResponse:U,includeRawResponse:L})=>{let W=G.tool_calls;switch(G.role){case"assistant":{let X=[],B=[];for(let K of W??[])try{X.push(F1(K,{returnId:!0}))}catch(Q){B.push(E1(K,Q.message))}let J={function_call:G.function_call,tool_calls:W};if(L!==void 0)J.__raw_response=U;let v={model_provider:"openai",model_name:U.model,...U.system_fingerprint?{usage:{...U.usage},system_fingerprint:U.system_fingerprint}:{}};if(G.audio)J.audio=G.audio;let Z=C(G.content||"",U.choices?.[0]?.message);return new d({content:Z,tool_calls:X,invalid_tool_calls:B,additional_kwargs:J,response_metadata:v,id:U.id})}default:return new x1(G.content||"",G.role??"unknown")}},g=({delta:G,rawResponse:U,includeRawResponse:L,defaultRole:W})=>{let X=G.role??W,B=G.content??"",J;if(G.function_call)J={function_call:G.function_call};else if(G.tool_calls)J={tool_calls:G.tool_calls};else J={};if(L)J.__raw_response=U;if(G.audio)J.audio={...G.audio,index:U.choices[0].index};let v={model_provider:"openai",usage:{...U.usage}};if(X==="user")return new j1({content:B,response_metadata:v});else if(X==="assistant"){let Z=[];if(Array.isArray(G.tool_calls))for(let K of G.tool_calls)Z.push({name:K.function?.name,args:K.function?.arguments,id:K.id,index:K.index,type:"tool_call_chunk"});return new Z1({content:B,tool_call_chunks:Z,additional_kwargs:J,id:U.id,response_metadata:v})}else if(X==="system")return new u({content:B,response_metadata:v});else if(X==="developer")return new u({content:B,response_metadata:v,additional_kwargs:{__openai_role__:"developer"}});else if(X==="function")return new Q1({content:B,additional_kwargs:J,name:G.name,response_metadata:v});else if(X==="tool")return new q1({content:B,additional_kwargs:J,tool_call_id:G.tool_call_id,response_metadata:v});else return new V1({content:B,role:X,response_metadata:v})},z1=(G)=>{if(G.type==="image"){if(G.url)return{type:"image_url",image_url:{url:G.url}};else if(G.data)return{type:"image_url",image_url:{url:`data:${G.mimeType};base64,${G.data}`}}}if(G.type==="audio"){if(G.data){let U=H1(()=>{let[,L]=G.mimeType.split("/");if(L==="wav"||L==="mp3")return L;return"wav"});return{type:"input_audio",input_audio:{data:G.data.toString(),format:U}}}}if(G.type==="file"){if(G.data)return{type:"file",file:{file_data:G.data.toString()}};if(G.fileId)return{type:"file",file:{file_id:G.fileId}}}return};function m(G){if(!G)return!1;if(/^o\d/.test(G??""))return!0;if(G.startsWith("gpt-5")&&!G.startsWith("gpt-5-chat"))return!0;return!1}var R1=({message:G,model:U})=>{let L=i(G);if(L==="system"&&m(U))L="developer";if(L==="developer")return{role:"developer",content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="system")return{role:"system",content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="assistant")return{role:"assistant",content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="tool"&&p.isInstance(G))return{role:"tool",tool_call_id:G.tool_call_id,content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="function")return{role:"function",name:G.name??"",content:G.contentBlocks.filter((X)=>X.type==="text").join("")};function*W(X){for(let B of X){if(B.type==="text")yield{type:"text",text:B.text};let J=z1(B);if(J)yield J}}return{role:"user",content:Array.from(W(G.contentBlocks))}},D=({messages:G,model:U})=>{return G.flatMap((L)=>{if("output_version"in L.response_metadata&&L.response_metadata?.output_version==="v1")return R1({message:L});let W=i(L);if(W==="system"&&m(U))W="developer";let X=typeof L.content==="string"?L.content:L.content.map((J)=>{if($1(J))return P1(J,y1);return J}),B={role:W,content:X};if(L.name!=null)B.name=L.name;if(L.additional_kwargs.function_call!=null)B.function_call=L.additional_kwargs.function_call,B.content="";if(L.additional_kwargs?.reasoning_content&&U?.includes("deepseek"))B.reasoning_content=L.additional_kwargs.reasoning_content;if(d.isInstance(L)&&!!L.tool_calls?.length)B.tool_calls=L.tool_calls.map(O1),B.content="";else{if(L.additional_kwargs.tool_calls!=null)B.tool_calls=L.additional_kwargs.tool_calls;if(p.isInstance(L)&&L.tool_call_id!=null)B.tool_call_id=L.tool_call_id}if(L.additional_kwargs.audio&&typeof L.additional_kwargs.audio==="object"&&"id"in L.additional_kwargs.audio){let J={role:"assistant",audio:{id:L.additional_kwargs.audio.id}};return[B,J]}return B})};class R extends S1{invocationParams(G,U){let L;if(G?.strict!==void 0)L=G.strict;else if(this.supportsStrictToolCalling!==void 0)L=this.supportsStrictToolCalling;let W={};if(G?.stream_options!==void 0)W={stream_options:G.stream_options};else if(this.streamUsage&&(this.streaming||U?.streaming))W={stream_options:{include_usage:!0}};let X={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:G?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:G?.functions,function_call:G?.function_call,tools:G?.tools?.length?G.tools.map((J)=>this._convertChatOpenAIToolToCompletionsTool(J,{strict:L})):void 0,tool_choice:M(G?.tool_choice),response_format:this._getResponseFormat(G?.response_format),seed:G?.seed,...W,parallel_tool_calls:G?.parallel_tool_calls,...this.audio||G?.audio?{audio:this.audio||G?.audio}:{},...this.modalities||G?.modalities?{modalities:this.modalities||G?.modalities}:{},...this.modelKwargs,prompt_cache_key:G?.promptCacheKey??this.promptCacheKey,verbosity:G?.verbosity??this.verbosity};if(G?.prediction!==void 0)X.prediction=G.prediction;if(this.service_tier!==void 0)X.service_tier=this.service_tier;if(G?.service_tier!==void 0)X.service_tier=G.service_tier;let B=this._getReasoningParams(G);if(B!==void 0&&B.effort!==void 0)X.reasoning_effort=B.effort;if(this.reasoning)X.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens;else X.max_tokens=this.maxTokens===-1?void 0:this.maxTokens;return X}async _generate(G,U,L){let W={},X=this.invocationParams(U),B=D({messages:G,model:this.model});if(X.stream){let J=this._streamResponseChunks(G,U,L),v={};for await(let Y of J){Y.message.response_metadata={...Y.generationInfo,...Y.message.response_metadata};let V=Y.generationInfo?.completion??0;if(v[V]===void 0)v[V]=Y;else v[V]=v[V].concat(Y)}let Z=Object.entries(v).sort(([Y],[V])=>parseInt(Y,10)-parseInt(V,10)).map(([Y,V])=>V),{functions:K,function_call:Q}=this.invocationParams(U),x=await this._getEstimatedTokenCountFromPrompt(G,K,Q),$=await this._getNumTokensFromGenerations(Z);return W.input_tokens=x,W.output_tokens=$,W.total_tokens=x+$,{generations:Z,llmOutput:{estimatedTokenUsage:{promptTokens:W.input_tokens,completionTokens:W.output_tokens,totalTokens:W.total_tokens}}}}else{let J=await this.completionWithRetry({...X,stream:!1,messages:B},{signal:U?.signal,...U?.options}),{completion_tokens:v,prompt_tokens:Z,total_tokens:K,prompt_tokens_details:Q,completion_tokens_details:x}=J?.usage??{};if(v)W.output_tokens=(W.output_tokens??0)+v;if(Z)W.input_tokens=(W.input_tokens??0)+Z;if(K)W.total_tokens=(W.total_tokens??0)+K;if(Q?.audio_tokens!==null||Q?.cached_tokens!==null)W.input_token_details={...Q?.audio_tokens!==null&&{audio:Q?.audio_tokens},...Q?.cached_tokens!==null&&{cache_read:Q?.cached_tokens}};if(x?.audio_tokens!==null||x?.reasoning_tokens!==null)W.output_token_details={...x?.audio_tokens!==null&&{audio:x?.audio_tokens},...x?.reasoning_tokens!==null&&{reasoning:x?.reasoning_tokens}};let $=[];for(let Y of J?.choices??[]){let V=Y.message?.content??"",F=Y.message?.reasoning_content??Y.message?.reasoning??"",j={text:V,message:this._convertCompletionsMessageToBaseMessage(Y.message??{role:"assistant"},J)};if(j.message.additional_kwargs={...j.message.additional_kwargs,reasoning_content:F},j.generationInfo={...Y.finish_reason?{finish_reason:Y.finish_reason}:{},...Y.logprobs?{logprobs:Y.logprobs}:{}},_1(j.message))j.message.usage_metadata=W;j.message=new I1(Object.fromEntries(Object.entries(j.message).filter(([y])=>!y.startsWith("lc_")))),$.push(j)}return{generations:$,llmOutput:{tokenUsage:{promptTokens:W.input_tokens,completionTokens:W.output_tokens,totalTokens:W.total_tokens}}}}}async*_streamResponseChunks(G,U,L){let W=D({messages:G,model:this.model}),X={...this.invocationParams(U,{streaming:!0}),messages:W,stream:!0},B,J=await this.completionWithRetry(X,U),v;for await(let Z of J){let K=Z?.choices?.[0];if(Z.usage)v=Z.usage;if(!K)continue;let{delta:Q}=K;if(!Q)continue;let x=this._convertCompletionsDeltaToBaseMessageChunk(Q,Z,B),$=Q.reasoning_content??Q.reasoning??"";if($)x.additional_kwargs={...x.additional_kwargs,reasoning_content:$};B=Q.role??B;let Y={prompt:U.promptIndex??0,completion:K.index??0};if(typeof x.content!=="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let V={...Y};if(K.finish_reason!=null)V.finish_reason=K.finish_reason,V.system_fingerprint=Z.system_fingerprint,V.model_name=Z.model,V.service_tier=Z.service_tier;if(this.logprobs)V.logprobs=K.logprobs;let F=new n({message:x,text:x.content,generationInfo:V});yield F,await L?.handleLLMNewToken(F.text??"",Y,void 0,void 0,void 0,{chunk:F})}if(v){let Z={...v.prompt_tokens_details?.audio_tokens!==null&&{audio:v.prompt_tokens_details?.audio_tokens},...v.prompt_tokens_details?.cached_tokens!==null&&{cache_read:v.prompt_tokens_details?.cached_tokens}},K={...v.completion_tokens_details?.audio_tokens!==null&&{audio:v.completion_tokens_details?.audio_tokens},...v.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:v.completion_tokens_details?.reasoning_tokens}};yield new n({message:new h1({content:"",response_metadata:{usage:{...v}},usage_metadata:{input_tokens:v.prompt_tokens,output_tokens:v.completion_tokens,total_tokens:v.total_tokens,...Object.keys(Z).length>0&&{input_token_details:Z},...Object.keys(K).length>0&&{output_token_details:K}}}),text:""})}if(U.signal?.aborted)throw Error("AbortError")}async completionWithRetry(G,U){let L=this._getClientOptions(U),W=G.response_format&&G.response_format.type==="json_schema";return this.caller.call(async()=>{try{if(W&&!G.stream)return await this.client.chat.completions.parse(G,L);else return await this.client.chat.completions.create(G,L)}catch(X){throw D1(X)}})}_convertCompletionsDeltaToBaseMessageChunk(G,U,L){return g({delta:G,rawResponse:U,includeRawResponse:this.__includeRawResponse,defaultRole:L})}_convertCompletionsMessageToBaseMessage(G,U){return c({message:G,rawResponse:U,includeRawResponse:this.__includeRawResponse})}}import{createMiddleware as iG}from"langchain";import{z as E}from"zod";import{MessagesAnnotation as w1}from"@langchain/langgraph";import{SubAgentAnnotation as f1,SubAgentStateSchema as N1}from"@langgraph-js/standard-agent";var vU=T.extend(N1.shape).extend({provider_id:E.string().default("openai"),provider_type:E.string().default("openai"),model_id:E.string().default("qwen-plus"),agent_name:E.string().default("Code Agent"),switch_command:E.string().optional(),enable_thinking:E.boolean().default(!0),user_id:E.string().optional(),thread_id:E.string().optional()}),l=_(f1,w1).build({provider_id:H(()=>"openai"),provider_type:H(()=>"openai"),model_id:H(()=>"qwen-plus"),agent_name:H(()=>"Code Agent"),switch_command:H(()=>null),enable_thinking:H(()=>!0),user_id:H(()=>""),thread_id:H(()=>"")});import{ChatAnthropic as A1}from"@langchain/anthropic";import{ChatGoogleGenerativeAI as b1}from"@langchain/google-genai";var t=async(G,U={})=>{let{modelProvider:L,enableThinking:W=!0}=U,X="v1",B;if(L==="anthropic")B=new A1({model:G,streamUsage:!0,streaming:!0,maxRetries:1,maxTokens:64000,thinking:W?{budget_tokens:1024,type:"enabled"}:void 0,apiKey:U.apiKey,anthropicApiUrl:U.baseURL,metadata:U.metadata,outputVersion:"v1"});else if(L==="gemini"||L==="google")console.log(process.env.GOOGLE_BASE_URL),B=new b1({model:G,apiKey:U.apiKey,baseUrl:U.baseURL||process.env.GOOGLE_BASE_URL,maxRetries:1,streaming:!0,streamUsage:!0,thinkingConfig:{},metadata:U.metadata,outputVersion:"v1"});else B=new R({model:G,configuration:{baseURL:U.baseURL,apiKey:U.apiKey},streamUsage:!0,maxRetries:1,modelKwargs:W?{thinking:{type:"enabled"}}:void 0,metadata:U.metadata,outputVersion:"v1"});return B};import{createAgent as M1,tool as C1}from"langchain";import{anthropicPromptCachingMiddleware as u1}from"@langgraph-js/standard-agent";import{MCPMiddleware as T1}from"@langgraph-js/standard-agent";class h extends T1{constructor(G){super({configProvider:async()=>h.loadConfigFromStore(),cache:G})}static async loadConfigFromStore(){try{let G=new s;await G.initialize();let U=await G.getConfig();if(!U.mcp_config||Object.keys(U.mcp_config).length===0)return null;return{servers:U.mcp_config}}catch(G){return console.error("Failed to load MCP config from store:",G),null}}}import{humanInTheLoopMiddleware as k1}from"@langgraph-js/standard-agent";var r1={ask_user_questions:{allowedDecisions:["respond","approve","reject","edit"]}};async function SU(G,U,L,W,X){let B=!!X?.parent_id,J=await U.getAgent(G);if(!J)throw Error(`Agent not found: ${G}`);let v=await U.validateAgent(G);if(!v.valid)throw Error(`Agent validation failed: ${JSON.stringify(v.errors)}`);let Z=await t(L.model_id,{modelProvider:L.provider_id,streamUsage:!0,enableThinking:L.enable_thinking,metadata:{parent_id:X?.parent_id}}),K=[],Q=U.tools;for(let[j,y]of Object.entries(J.tools)){let O=Q.getImplementation(j);if(!O){console.warn(`Tool ${j} not found in registry`);continue}if(!O.name||!y)continue;let o=C1(async(e)=>{let z=await O.execute(e);if(z&&typeof z==="object"&&"content"in z)return z.content;return z},{name:O.name,description:O.description,schema:O.paramsSchema});K.push(o)}let x=[];for(let[j,y]of Object.entries(J.middleware)){if(j==="subagents"&&B)continue;let O=U.middlewares.getImplementation(j);if(!y)break;x.push(await O.execute(y.customParams||{}))}let $=new h;x.push($);let Y={...r1};if(process.env.YOLO_MODE!=="true")Object.assign(Y,{terminal:{allowedDecisions:["approve","reject","edit"]}});if(x.push(k1({interruptOn:Y})),process.env.MODEL_PROVIDER==="anthropic")x.push(u1());let V=await U.getPrompt(J.systemPromptId);if(!V)throw Error(`Prompt not found: ${J.systemPromptId}`);let F=V.content+`
23
+ - Provides a correct answer`,schema:U1});import{tool as f}from"@langchain/core/tools";import{z as $}from"zod";var L1=$.object({url:$.string().url().describe("the url to crawl"),raw:$.boolean().optional().default(!1).describe("return raw html")}),W1=$.object({query:$.string().describe("the query to search"),engines:$.array($.enum(["basic","npm","juejin","anthropic","github"])).default(["basic"]).describe("the engines to use"),returnType:$.enum(["json","markdown"]).default("json").describe("the content type to return"),withMetadata:$.boolean().default(!0).describe("whether to include metadata in the search results")}),t1=f(async({url:G})=>{if(!G)return{status:"error",error:"URL is required"};let U=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/extract`,{method:"POST",body:JSON.stringify({url:G})});if(!U.ok)throw Error(`HTTP error! status: ${U.status}`);return await U.text()},{name:"read_web_page",description:"A powerful web content extraction tool that retrieves and processes raw content from specified URLs, ideal for data collection, content analysis, and research tasks.",schema:$.object(L1.shape)}),s1=f(async({query:G,engines:U})=>{let L=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/search`,{method:"POST",body:JSON.stringify({query:G,engines:U,returnType:"json",withMetadata:!0})});if(!L.ok)throw Error(`HTTP error! status: ${L.status}`);return await L.text()},{name:"web_search",description:"A powerful web search tool that provides comprehensive, real-time results using search engine. Returns relevant web content with customizable parameters for result count, content type, and domain filtering. Ideal for gathering current information, news, and detailed web content analysis.",schema:$.object(W1.shape)});import{AIMessage as Y0,ToolMessage as Z0}from"@langchain/core/messages";import{AIMessage as L0,HumanMessage as W0,SystemMessage as X0,ToolMessage as B0}from"@langchain/core/messages";var V0=(G)=>{return G?.configurable?.thread_id};import{Command as $0,getCurrentTaskInput as H0}from"@langchain/langgraph";import{z as O0}from"zod";import{ToolMessage as F0}from"@langchain/core/messages";import{tool as z0}from"@langchain/core/tools";import{Annotation as N,MessagesAnnotation as B1,START as _0,StateGraph as D0}from"@langchain/langgraph";var A=N.Root({...B1.spec,activeAgent:N});import{z as M0}from"zod";import{ToolMessage as u0}from"@langchain/core/messages";import{tool as r0}from"@langchain/core/tools";import{Command as p0,getCurrentTaskInput as i0}from"@langchain/langgraph";import{Command as m0}from"@langchain/langgraph";import{ChatOpenAI as GG}from"@langchain/openai";import{SystemMessage as WG,HumanMessage as XG,AIMessageChunk as BG,ToolMessage as JG}from"@langchain/core/messages";import{z as b}from"zod";import{withLangGraph as K1}from"@langchain/langgraph/zod";import{MessagesZodMeta as Y1}from"@langchain/langgraph";var T=b.object({messages:K1(b.custom(),Y1).default([])});import{AIMessage as I1,AIMessageChunk as h1,isAIMessage as _1}from"@langchain/core/messages";import{ChatGenerationChunk as n}from"@langchain/core/outputs";import{wrapOpenAIClientError as D1}from"@langchain/openai";import{convertToOpenAITool as QG,isLangChainTool as jG}from"@langchain/core/utils/function_calling";import{isInteropZodSchema as $G}from"@langchain/core/utils/types";import{toJsonSchema as PG}from"@langchain/core/utils/json_schema";function M(G){if(!G)return;else if(G==="any"||G==="required")return"required";else if(G==="auto")return"auto";else if(G==="none")return"none";else if(typeof G==="string")return{type:"function",function:{name:G}};else return G}import{BaseChatOpenAI as S1}from"@langchain/openai";import{AIMessage as d,AIMessageChunk as Z1,ChatMessage as x1,ChatMessageChunk as V1,FunctionMessageChunk as Q1,HumanMessageChunk as j1,SystemMessageChunk as u,ToolMessage as p,ToolMessageChunk as q1,parseBase64DataUrl as k,parseMimeType as r,isDataContentBlock as $1,iife as H1,convertToProviderContentBlock as P1}from"@langchain/core/messages";import{convertLangChainToolCallToOpenAI as O1,makeInvalidToolCall as E1,parseToolCall as F1}from"@langchain/core/output_parsers/openai_tools";import{isZodSchemaV3 as FG,isZodSchemaV4 as yG}from"@langchain/core/utils/types";import{toJSONSchema as RG,parse as IG}from"zod/v4/core";import{zodResponseFormat as _G}from"openai/helpers/zod";function C(G,U){if(U&&typeof U==="object"&&"images"in U&&Array.isArray(U.images)){let L=U.images.filter((W)=>typeof W?.image_url?.url==="string").map((W)=>({type:"image",url:W.image_url.url}));return[{type:"text",text:G},...L]}return G}import{messageToOpenAIRole as i}from"@langchain/openai";var y1={providerName:"ChatOpenAI",fromStandardTextBlock(G){return{type:"text",text:G.text}},fromStandardImageBlock(G){if(G.source_type==="url")return{type:"image_url",image_url:{url:G.url,...G.metadata?.detail?{detail:G.metadata.detail}:{}}};if(G.source_type==="base64")return{type:"image_url",image_url:{url:`data:${G.mime_type??""};base64,${G.data}`,...G.metadata?.detail?{detail:G.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(G){if(G.source_type==="url"){let U=k({dataUrl:G.url});if(!U)throw Error(`URL audio blocks with source_type ${G.source_type} must be formatted as a data URL for ChatOpenAI`);let L=U.mime_type||G.mime_type||"",W;try{W=r(L)}catch{throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`)}if(W.type!=="audio"||W.subtype!=="wav"&&W.subtype!=="mp3")throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:W.subtype,data:U.data}}}if(G.source_type==="base64"){let U;try{U=r(G.mime_type??"")}catch{throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`)}if(U.type!=="audio"||U.subtype!=="wav"&&U.subtype!=="mp3")throw Error(`Audio blocks with source_type ${G.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:U.subtype,data:G.data}}}throw Error(`Audio content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(G){if(G.source_type==="url"){if(!k({dataUrl:G.url}))throw Error(`URL file blocks with source_type ${G.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:G.url,...G.metadata?.filename||G.metadata?.name?{filename:G.metadata?.filename||G.metadata?.name}:{}}}}if(G.source_type==="base64")return{type:"file",file:{file_data:`data:${G.mime_type??""};base64,${G.data}`,...G.metadata?.filename||G.metadata?.name||G.metadata?.title?{filename:G.metadata?.filename||G.metadata?.name||G.metadata?.title}:{}}};if(G.source_type==="id")return{type:"file",file:{file_id:G.id}};throw Error(`File content blocks with source_type ${G.source_type} are not supported for ChatOpenAI`)}},c=({message:G,rawResponse:U,includeRawResponse:L})=>{let W=G.tool_calls;switch(G.role){case"assistant":{let X=[],B=[];for(let K of W??[])try{X.push(F1(K,{returnId:!0}))}catch(Q){B.push(E1(K,Q.message))}let J={function_call:G.function_call,tool_calls:W};if(L!==void 0)J.__raw_response=U;let v={model_provider:"openai",model_name:U.model,...U.system_fingerprint?{usage:{...U.usage},system_fingerprint:U.system_fingerprint}:{}};if(G.audio)J.audio=G.audio;let Z=C(G.content||"",U.choices?.[0]?.message);return new d({content:Z,tool_calls:X,invalid_tool_calls:B,additional_kwargs:J,response_metadata:v,id:U.id})}default:return new x1(G.content||"",G.role??"unknown")}},g=({delta:G,rawResponse:U,includeRawResponse:L,defaultRole:W})=>{let X=G.role??W,B=G.content??"",J;if(G.function_call)J={function_call:G.function_call};else if(G.tool_calls)J={tool_calls:G.tool_calls};else J={};if(L)J.__raw_response=U;if(G.audio)J.audio={...G.audio,index:U.choices[0].index};let v={model_provider:"openai",usage:{...U.usage}};if(X==="user")return new j1({content:B,response_metadata:v});else if(X==="assistant"){let Z=[];if(Array.isArray(G.tool_calls))for(let K of G.tool_calls)Z.push({name:K.function?.name,args:K.function?.arguments,id:K.id,index:K.index,type:"tool_call_chunk"});return new Z1({content:B,tool_call_chunks:Z,additional_kwargs:J,id:U.id,response_metadata:v})}else if(X==="system")return new u({content:B,response_metadata:v});else if(X==="developer")return new u({content:B,response_metadata:v,additional_kwargs:{__openai_role__:"developer"}});else if(X==="function")return new Q1({content:B,additional_kwargs:J,name:G.name,response_metadata:v});else if(X==="tool")return new q1({content:B,additional_kwargs:J,tool_call_id:G.tool_call_id,response_metadata:v});else return new V1({content:B,role:X,response_metadata:v})},z1=(G)=>{if(G.type==="image"){if(G.url)return{type:"image_url",image_url:{url:G.url}};else if(G.data)return{type:"image_url",image_url:{url:`data:${G.mimeType};base64,${G.data}`}}}if(G.type==="audio"){if(G.data){let U=H1(()=>{let[,L]=G.mimeType.split("/");if(L==="wav"||L==="mp3")return L;return"wav"});return{type:"input_audio",input_audio:{data:G.data.toString(),format:U}}}}if(G.type==="file"){if(G.data)return{type:"file",file:{file_data:G.data.toString()}};if(G.fileId)return{type:"file",file:{file_id:G.fileId}}}return};function m(G){if(!G)return!1;if(/^o\d/.test(G??""))return!0;if(G.startsWith("gpt-5")&&!G.startsWith("gpt-5-chat"))return!0;return!1}var R1=({message:G,model:U})=>{let L=i(G);if(L==="system"&&m(U))L="developer";if(L==="developer")return{role:"developer",content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="system")return{role:"system",content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="assistant")return{role:"assistant",content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="tool"&&p.isInstance(G))return{role:"tool",tool_call_id:G.tool_call_id,content:G.contentBlocks.filter((X)=>X.type==="text")};else if(L==="function")return{role:"function",name:G.name??"",content:G.contentBlocks.filter((X)=>X.type==="text").join("")};function*W(X){for(let B of X){if(B.type==="text")yield{type:"text",text:B.text};let J=z1(B);if(J)yield J}}return{role:"user",content:Array.from(W(G.contentBlocks))}},D=({messages:G,model:U})=>{return G.flatMap((L)=>{if("output_version"in L.response_metadata&&L.response_metadata?.output_version==="v1")return R1({message:L});let W=i(L);if(W==="system"&&m(U))W="developer";let X=typeof L.content==="string"?L.content:L.content.map((J)=>{if($1(J))return P1(J,y1);return J}),B={role:W,content:X};if(L.name!=null)B.name=L.name;if(L.additional_kwargs.function_call!=null)B.function_call=L.additional_kwargs.function_call,B.content="";if(L.additional_kwargs?.reasoning_content&&U?.includes("deepseek"))B.reasoning_content=L.additional_kwargs.reasoning_content;if(d.isInstance(L)&&!!L.tool_calls?.length)B.tool_calls=L.tool_calls.map(O1),B.content="";else{if(L.additional_kwargs.tool_calls!=null)B.tool_calls=L.additional_kwargs.tool_calls;if(p.isInstance(L)&&L.tool_call_id!=null)B.tool_call_id=L.tool_call_id}if(L.additional_kwargs.audio&&typeof L.additional_kwargs.audio==="object"&&"id"in L.additional_kwargs.audio){let J={role:"assistant",audio:{id:L.additional_kwargs.audio.id}};return[B,J]}return B})};class R extends S1{invocationParams(G,U){let L;if(G?.strict!==void 0)L=G.strict;else if(this.supportsStrictToolCalling!==void 0)L=this.supportsStrictToolCalling;let W={};if(G?.stream_options!==void 0)W={stream_options:G.stream_options};else if(this.streamUsage&&(this.streaming||U?.streaming))W={stream_options:{include_usage:!0}};let X={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:G?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:G?.functions,function_call:G?.function_call,tools:G?.tools?.length?G.tools.map((J)=>this._convertChatOpenAIToolToCompletionsTool(J,{strict:L})):void 0,tool_choice:M(G?.tool_choice),response_format:this._getResponseFormat(G?.response_format),seed:G?.seed,...W,parallel_tool_calls:G?.parallel_tool_calls,...this.audio||G?.audio?{audio:this.audio||G?.audio}:{},...this.modalities||G?.modalities?{modalities:this.modalities||G?.modalities}:{},...this.modelKwargs,prompt_cache_key:G?.promptCacheKey??this.promptCacheKey,verbosity:G?.verbosity??this.verbosity};if(G?.prediction!==void 0)X.prediction=G.prediction;if(this.service_tier!==void 0)X.service_tier=this.service_tier;if(G?.service_tier!==void 0)X.service_tier=G.service_tier;let B=this._getReasoningParams(G);if(B!==void 0&&B.effort!==void 0)X.reasoning_effort=B.effort;if(this.reasoning)X.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens;else X.max_tokens=this.maxTokens===-1?void 0:this.maxTokens;return X}async _generate(G,U,L){let W={},X=this.invocationParams(U),B=D({messages:G,model:this.model});if(X.stream){let J=this._streamResponseChunks(G,U,L),v={};for await(let Y of J){Y.message.response_metadata={...Y.generationInfo,...Y.message.response_metadata};let V=Y.generationInfo?.completion??0;if(v[V]===void 0)v[V]=Y;else v[V]=v[V].concat(Y)}let Z=Object.entries(v).sort(([Y],[V])=>parseInt(Y,10)-parseInt(V,10)).map(([Y,V])=>V),{functions:K,function_call:Q}=this.invocationParams(U),x=await this._getEstimatedTokenCountFromPrompt(G,K,Q),H=await this._getNumTokensFromGenerations(Z);return W.input_tokens=x,W.output_tokens=H,W.total_tokens=x+H,{generations:Z,llmOutput:{estimatedTokenUsage:{promptTokens:W.input_tokens,completionTokens:W.output_tokens,totalTokens:W.total_tokens}}}}else{let J=await this.completionWithRetry({...X,stream:!1,messages:B},{signal:U?.signal,...U?.options}),{completion_tokens:v,prompt_tokens:Z,total_tokens:K,prompt_tokens_details:Q,completion_tokens_details:x}=J?.usage??{};if(v)W.output_tokens=(W.output_tokens??0)+v;if(Z)W.input_tokens=(W.input_tokens??0)+Z;if(K)W.total_tokens=(W.total_tokens??0)+K;if(Q?.audio_tokens!==null||Q?.cached_tokens!==null)W.input_token_details={...Q?.audio_tokens!==null&&{audio:Q?.audio_tokens},...Q?.cached_tokens!==null&&{cache_read:Q?.cached_tokens}};if(x?.audio_tokens!==null||x?.reasoning_tokens!==null)W.output_token_details={...x?.audio_tokens!==null&&{audio:x?.audio_tokens},...x?.reasoning_tokens!==null&&{reasoning:x?.reasoning_tokens}};let H=[];for(let Y of J?.choices??[]){let V=Y.message?.content??"",F=Y.message?.reasoning_content??Y.message?.reasoning??"",j={text:V,message:this._convertCompletionsMessageToBaseMessage(Y.message??{role:"assistant"},J)};if(j.message.additional_kwargs={...j.message.additional_kwargs,reasoning_content:F},j.generationInfo={...Y.finish_reason?{finish_reason:Y.finish_reason}:{},...Y.logprobs?{logprobs:Y.logprobs}:{}},_1(j.message))j.message.usage_metadata=W;j.message=new I1(Object.fromEntries(Object.entries(j.message).filter(([y])=>!y.startsWith("lc_")))),H.push(j)}return{generations:H,llmOutput:{tokenUsage:{promptTokens:W.input_tokens,completionTokens:W.output_tokens,totalTokens:W.total_tokens}}}}}async*_streamResponseChunks(G,U,L){let W=D({messages:G,model:this.model}),X={...this.invocationParams(U,{streaming:!0}),messages:W,stream:!0},B,J=await this.completionWithRetry(X,U),v;for await(let Z of J){let K=Z?.choices?.[0];if(Z.usage)v=Z.usage;if(!K)continue;let{delta:Q}=K;if(!Q)continue;let x=this._convertCompletionsDeltaToBaseMessageChunk(Q,Z,B),H=Q.reasoning_content??Q.reasoning??"";if(H)x.additional_kwargs={...x.additional_kwargs,reasoning_content:H};B=Q.role??B;let Y={prompt:U.promptIndex??0,completion:K.index??0};if(typeof x.content!=="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let V={...Y};if(K.finish_reason!=null)V.finish_reason=K.finish_reason,V.system_fingerprint=Z.system_fingerprint,V.model_name=Z.model,V.service_tier=Z.service_tier;if(this.logprobs)V.logprobs=K.logprobs;let F=new n({message:x,text:x.content,generationInfo:V});yield F,await L?.handleLLMNewToken(F.text??"",Y,void 0,void 0,void 0,{chunk:F})}if(v){let Z={...v.prompt_tokens_details?.audio_tokens!==null&&{audio:v.prompt_tokens_details?.audio_tokens},...v.prompt_tokens_details?.cached_tokens!==null&&{cache_read:v.prompt_tokens_details?.cached_tokens}},K={...v.completion_tokens_details?.audio_tokens!==null&&{audio:v.completion_tokens_details?.audio_tokens},...v.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:v.completion_tokens_details?.reasoning_tokens}};yield new n({message:new h1({content:"",response_metadata:{usage:{...v}},usage_metadata:{input_tokens:v.prompt_tokens,output_tokens:v.completion_tokens,total_tokens:v.total_tokens,...Object.keys(Z).length>0&&{input_token_details:Z},...Object.keys(K).length>0&&{output_token_details:K}}}),text:""})}if(U.signal?.aborted)throw Error("AbortError")}async completionWithRetry(G,U){let L=this._getClientOptions(U),W=G.response_format&&G.response_format.type==="json_schema";return this.caller.call(async()=>{try{if(W&&!G.stream)return await this.client.chat.completions.parse(G,L);else return await this.client.chat.completions.create(G,L)}catch(X){throw D1(X)}})}_convertCompletionsDeltaToBaseMessageChunk(G,U,L){return g({delta:G,rawResponse:U,includeRawResponse:this.__includeRawResponse,defaultRole:L})}_convertCompletionsMessageToBaseMessage(G,U){return c({message:G,rawResponse:U,includeRawResponse:this.__includeRawResponse})}}import{createMiddleware as iG}from"langchain";import{z as O}from"zod";import{MessagesAnnotation as w1}from"@langchain/langgraph";import{SubAgentAnnotation as f1,SubAgentStateSchema as N1}from"@langgraph-js/standard-agent";var vU=T.extend(N1.shape).extend({provider_id:O.string().default("openai"),provider_type:O.string().default("openai"),model_id:O.string().default("qwen-plus"),agent_name:O.string().default("Code Agent"),switch_command:O.string().optional(),enable_thinking:O.boolean().default(!0),user_id:O.string().optional(),thread_id:O.string().optional(),cwd:O.string().default(process.cwd())}),l=_(f1,w1).build({provider_id:q(()=>"openai"),provider_type:q(()=>"openai"),model_id:q(()=>"qwen-plus"),agent_name:q(()=>"Code Agent"),switch_command:q(()=>null),enable_thinking:q(()=>!0),user_id:q(()=>""),thread_id:q(()=>""),cwd:q(()=>process.cwd())});import{ChatAnthropic as A1}from"@langchain/anthropic";import{ChatGoogleGenerativeAI as b1}from"@langchain/google-genai";var t=async(G,U={})=>{let{modelProvider:L,enableThinking:W=!0}=U,X="v1",B;if(L==="anthropic")B=new A1({model:G,streamUsage:!0,streaming:!0,maxRetries:1,maxTokens:64000,thinking:W?{budget_tokens:1024,type:"enabled"}:void 0,apiKey:U.apiKey,anthropicApiUrl:U.baseURL,metadata:U.metadata,outputVersion:"v1"});else if(L==="gemini"||L==="google")console.log(process.env.GOOGLE_BASE_URL),B=new b1({model:G,apiKey:U.apiKey,baseUrl:U.baseURL||process.env.GOOGLE_BASE_URL,maxRetries:1,streaming:!0,streamUsage:!0,thinkingConfig:{},metadata:U.metadata,outputVersion:"v1"});else B=new R({model:G,configuration:{baseURL:U.baseURL,apiKey:U.apiKey},streamUsage:!0,maxRetries:1,modelKwargs:W?{thinking:{type:"enabled"}}:void 0,metadata:U.metadata,outputVersion:"v1"});return B};import{createAgent as M1,tool as C1}from"langchain";import{anthropicPromptCachingMiddleware as u1}from"@langgraph-js/standard-agent";import{MCPMiddleware as T1}from"@langgraph-js/standard-agent";class h extends T1{constructor(G){super({configProvider:async()=>h.loadConfigFromStore(),cache:G})}static async loadConfigFromStore(){try{let G=new s;await G.initialize();let U=await G.getConfig();if(!U.mcp_config||Object.keys(U.mcp_config).length===0)return null;return{servers:U.mcp_config}}catch(G){return console.error("Failed to load MCP config from store:",G),null}}}import{humanInTheLoopMiddleware as k1}from"@langgraph-js/standard-agent";var r1={ask_user_questions:{allowedDecisions:["respond","approve","reject","edit"]}};async function SU(G,U,L,W,X){let B=!!X?.parent_id,J=await U.getAgent(G);if(!J)throw Error(`Agent not found: ${G}`);let v=await U.validateAgent(G);if(!v.valid)throw Error(`Agent validation failed: ${JSON.stringify(v.errors)}`);let Z=await t(L.model_id,{modelProvider:L.provider_id,streamUsage:!0,enableThinking:L.enable_thinking,metadata:{parent_id:X?.parent_id}}),K=[],Q=U.tools;for(let[j,y]of Object.entries(J.tools)){let E=Q.getImplementation(j);if(!E){console.warn(`Tool ${j} not found in registry`);continue}if(!E.name||!y)continue;let o=C1(async(e)=>{let z=await E.execute(e);if(z&&typeof z==="object"&&"content"in z)return z.content;return z},{name:E.name,description:E.description,schema:E.paramsSchema});K.push(o)}let x=[];for(let[j,y]of Object.entries(J.middleware)){if(j==="subagents"&&B)continue;let E=U.middlewares.getImplementation(j);if(!y)break;x.push(await E.execute(y.customParams||{}))}let H=new h;x.push(H);let Y={...r1};if(process.env.YOLO_MODE!=="true")Object.assign(Y,{terminal:{allowedDecisions:["approve","reject","edit"]}});if(x.push(k1({interruptOn:Y})),process.env.MODEL_PROVIDER==="anthropic")x.push(u1());let V=await U.getPrompt(J.systemPromptId);if(!V)throw Error(`Prompt not found: ${J.systemPromptId}`);let F=V.content+`
24
24
 
25
25
  ${await a(L)}`;return M1({name:B?`subagent_${X.parent_id}`:J.name,model:Z,systemPrompt:F,tools:K,stateSchema:l,middleware:x})}async function wU(G){return(await G.listAgents()).map((L)=>L.id)}
26
26
  export{V0 as zb,vU as Ab,l as Bb,t as Cb,SU as Db,wU as Eb};
@@ -1,2 +1,2 @@
1
- import{Ab as x,Db as z}from"./chunk-pnhf6jtr.js";import{SubAgentsMiddleware as H,getAgentListFromPackage as J}from"@langgraph-js/standard-agent";import{SubAgentsMiddleware as U,getAgentListFromPackage as W}from"@langgraph-js/standard-agent";async function Q(q){let B=await J(q);return new H({agents:B,stateSchema:x,async createAgent(D,E,G){return await z(E.subagent_id,q,G,{},{parent_id:D})}})}
1
+ import{Ab as x,Db as z}from"./chunk-cp9xkgbn.js";import{SubAgentsMiddleware as H,getAgentListFromPackage as J}from"@langgraph-js/standard-agent";import{SubAgentsMiddleware as U,getAgentListFromPackage as W}from"@langgraph-js/standard-agent";async function Q(q){let B=await J(q);return new H({agents:B,stateSchema:x,async createAgent(D,E,G){return await z(E.subagent_id,q,G,{},{parent_id:D})}})}
2
2
  export{Q as nb,U as ob,W as pb};
@@ -1 +1 @@
1
- import{wa as M}from"./chunk-k1kzp019.js";import"./chunk-vyfvrrc8.js";import{Ya as T,_a as G,bb as Z,fb as Y,hb as _,jb as $}from"./chunk-04kzaj7h.js";import{mb as L}from"./chunk-98x8wkt6.js";import{yb as w}from"./chunk-mrkf2b3t.js";import"./chunk-y5pf2d0x.js";import"./chunk-v28dexnx.js";import"./chunk-4n978rje.js";import"./chunk-wtwgpw9g.js";import"./chunk-vkfhjhhh.js";import"./chunk-0gpa9n28.js";import{gc as K}from"./chunk-feptb1bb.js";var z=K(T(),1);var y=K(Y(),1),h=({onClose:H})=>{let{config:U,updateConfig:N}=M(),B=U?.switch_command||"default",O=z.useCallback(async()=>{let q=await L(w);return Object.values(q)},[]),Q=z.useCallback((q,F,J)=>{let P=q.id===B;return y.jsxDEV(_,{isSelected:J,isCurrent:P,children:[y.jsxDEV(G,{bold:!0,children:[F+1,". ",q.id]},void 0,!0,void 0,this),y.jsxDEV(Z,{},void 0,!1,void 0,this),y.jsxDEV(G,{dimColor:!0,children:q.description},void 0,!1,void 0,this)]},`agent-${q.id}`,!0,void 0,this)},[B]),R=z.useCallback((q)=>{return q.id===B},[B]),W=z.useCallback(async(q)=>{let F=q.id==="default"?"":q.id;N({switch_command:F}),H()},[N,H]),X=z.useCallback((q)=>{let F=q.find((J)=>J.id===B);return F?y.jsxDEV(G,{color:"gray",dimColor:!0,children:["当前 Agent: ",y.jsxDEV(G,{color:"green",children:F.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null},[B]),v=z.useMemo(()=>({id:"agent",title:"Agent 选择",icon:"\uD83E\uDD16",dataSource:O,searchable:!0,searchFields:["id","name","description"],searchPlaceholder:"搜索 agent (名称/描述)...",filterable:!0,filters:[{id:"default",label:"默认",predicate:(q)=>q.id==="default"},{id:"custom",label:"自定义",predicate:(q)=>q.id!=="default"}],defaultFilter:"all",itemHeight:3,visibleCount:15,renderItem:Q,isSelected:R,onSelect:W,showCount:!0,statusInfo:X}),[O,Q,R,W,X]);return y.jsxDEV($,{config:v,onClose:H},void 0,!1,void 0,this)},m=h;export{m as default};
1
+ import{wa as M}from"./chunk-k1kzp019.js";import"./chunk-vyfvrrc8.js";import{Ya as T,_a as G,bb as Z,fb as Y,hb as _,jb as $}from"./chunk-04kzaj7h.js";import{mb as L}from"./chunk-98x8wkt6.js";import{yb as w}from"./chunk-zf08x9b0.js";import"./chunk-y5pf2d0x.js";import"./chunk-v28dexnx.js";import"./chunk-4n978rje.js";import"./chunk-wtwgpw9g.js";import"./chunk-vkfhjhhh.js";import"./chunk-0gpa9n28.js";import{gc as K}from"./chunk-feptb1bb.js";var z=K(T(),1);var y=K(Y(),1),h=({onClose:H})=>{let{config:U,updateConfig:N}=M(),B=U?.switch_command||"default",O=z.useCallback(async()=>{let q=await L(w);return Object.values(q)},[]),Q=z.useCallback((q,F,J)=>{let P=q.id===B;return y.jsxDEV(_,{isSelected:J,isCurrent:P,children:[y.jsxDEV(G,{bold:!0,children:[F+1,". ",q.id]},void 0,!0,void 0,this),y.jsxDEV(Z,{},void 0,!1,void 0,this),y.jsxDEV(G,{dimColor:!0,children:q.description},void 0,!1,void 0,this)]},`agent-${q.id}`,!0,void 0,this)},[B]),R=z.useCallback((q)=>{return q.id===B},[B]),W=z.useCallback(async(q)=>{let F=q.id==="default"?"":q.id;N({switch_command:F}),H()},[N,H]),X=z.useCallback((q)=>{let F=q.find((J)=>J.id===B);return F?y.jsxDEV(G,{color:"gray",dimColor:!0,children:["当前 Agent: ",y.jsxDEV(G,{color:"green",children:F.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null},[B]),v=z.useMemo(()=>({id:"agent",title:"Agent 选择",icon:"\uD83E\uDD16",dataSource:O,searchable:!0,searchFields:["id","name","description"],searchPlaceholder:"搜索 agent (名称/描述)...",filterable:!0,filters:[{id:"default",label:"默认",predicate:(q)=>q.id==="default"},{id:"custom",label:"自定义",predicate:(q)=>q.id!=="default"}],defaultFilter:"all",itemHeight:3,visibleCount:15,renderItem:Q,isSelected:R,onSelect:W,showCount:!0,statusInfo:X}),[O,Q,R,W,X]);return y.jsxDEV($,{config:v,onClose:H},void 0,!1,void 0,this)},m=h;export{m as default};