@langgraph-js/ui 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -51,7 +51,7 @@ Error generating stack: `+y.message+`
|
|
|
51
51
|
]))`;continue}else if(r[c]==="$"){i+=`($|(?=[\r
|
|
52
52
|
]))`;continue}}if(n.s&&r[c]==="."){i+=o?`${r[c]}\r
|
|
53
53
|
`:`[${r[c]}\r
|
|
54
|
-
]`;continue}i+=r[c],r[c]==="\\"?a=!0:o&&r[c]==="]"?o=!1:!o&&r[c]==="["&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function _5(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===Ee.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,i)=>({...r,[i]:yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??{}}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===Ee.ZodString&&e.keyType._def.checks?.length){const{type:r,...i}=v5(e.keyType._def,t);return{...n,propertyNames:i}}else{if(e.keyType?._def.typeName===Ee.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Ee.ZodBranded&&e.keyType._def.type._def.typeName===Ee.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...i}=y5(e.keyType._def,t);return{...n,propertyNames:i}}}return n}function LF(e,t){if(t.mapStrategy==="record")return _5(e,t);const n=yt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},r=yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function qF(e){const t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),i=Array.from(new Set(r.map(a=>typeof a)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:r}}function FF(){return{not:{}}}function BF(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Hh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function UF(e,t){if(t.target==="openApi3")return lT(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Hh&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((i,a)=>{const o=Hh[a._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((i,a)=>{const o=typeof a._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":if(a._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(r.length===n.length){const i=r.filter((a,o,l)=>l.indexOf(a)===o);return{type:i.length>1?i:i[0],enum:n.reduce((a,o)=>a.includes(o._def.value)?a:[...a,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,i)=>[...r,...i._def.values.filter(a=>!r.includes(a))],[])};return lT(e,t)}const lT=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,i)=>yt(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function HF(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Hh[e.innerType._def.typeName],nullable:!0}:{type:[Hh[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=yt(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=yt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function VF(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",g5(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?Et(n,"minimum",r.value,r.message,t):Et(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Et(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?Et(n,"maximum",r.value,r.message,t):Et(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Et(n,"maximum",r.value,r.message,t));break;case"multipleOf":Et(n,"multipleOf",r.value,r.message,t);break}return n}function GF(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},i=[],a=e.shape();for(const l in a){let c=a[l];if(c===void 0||c._def===void 0)continue;let f=YF(c);f&&n&&(c instanceof Di&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),f=!1);const d=yt(c._def,{...t,currentPath:[...t.currentPath,"properties",l],propertyPath:[...t.currentPath,"properties",l]});d!==void 0&&(r.properties[l]=d,f||i.push(l))}i.length&&(r.required=i);const o=ZF(e,t);return o!==void 0&&(r.additionalProperties=o),r}function ZF(e,t){if(e.catchall._def.typeName!=="ZodNever")return yt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function YF(e){try{return e.isOptional()}catch{return!0}}const KF=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return yt(e.innerType._def,t);const n=yt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},XF=(e,t)=>{if(t.pipeStrategy==="input")return yt(e.in._def,t);if(t.pipeStrategy==="output")return yt(e.out._def,t);const n=yt(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=yt(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(i=>i!==void 0)}};function WF(e,t){return yt(e.type._def,t)}function QF(e,t){const r={type:"array",uniqueItems:!0,items:yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Et(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Et(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function JF(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>yt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:yt(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>yt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function e7(){return{not:{}}}function t7(){return{}}const n7=(e,t)=>yt(e.innerType._def,t),r7=(e,t,n)=>{switch(t){case Ee.ZodString:return v5(e,n);case Ee.ZodNumber:return VF(e,n);case Ee.ZodObject:return GF(e,n);case Ee.ZodBigInt:return AF(e,n);case Ee.ZodBoolean:return TF();case Ee.ZodDate:return b5(e,n);case Ee.ZodUndefined:return e7();case Ee.ZodNull:return BF(n);case Ee.ZodArray:return CF(e,n);case Ee.ZodUnion:case Ee.ZodDiscriminatedUnion:return UF(e,n);case Ee.ZodIntersection:return DF(e,n);case Ee.ZodTuple:return JF(e,n);case Ee.ZodRecord:return _5(e,n);case Ee.ZodLiteral:return IF(e,n);case Ee.ZodEnum:return MF(e);case Ee.ZodNativeEnum:return qF(e);case Ee.ZodNullable:return HF(e,n);case Ee.ZodOptional:return KF(e,n);case Ee.ZodMap:return LF(e,n);case Ee.ZodSet:return QF(e,n);case Ee.ZodLazy:return()=>e.getter()._def;case Ee.ZodPromise:return WF(e,n);case Ee.ZodNaN:case Ee.ZodNever:return FF();case Ee.ZodEffects:return jF(e,n);case Ee.ZodAny:return kF();case Ee.ZodUnknown:return t7();case Ee.ZodDefault:return RF(e,n);case Ee.ZodBranded:return y5(e,n);case Ee.ZodReadonly:return n7(e,n);case Ee.ZodCatch:return NF(e,n);case Ee.ZodPipeline:return XF(e,n);case Ee.ZodFunction:case Ee.ZodVoid:case Ee.ZodSymbol:return;default:return(r=>{})()}};function yt(e,t,n=!1){const r=t.seen.get(e);if(t.override){const l=t.override?.(e,t,r,n);if(l!==xF)return l}if(r&&!n){const l=i7(r,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=r7(e,e.typeName,t),o=typeof a=="function"?yt(a(),t):a;if(o&&s7(e,t,o),t.postProcess){const l=t.postProcess(o,e,t);return i.jsonSchema=o,l}return i.jsonSchema=o,o}const i7=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:a7(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},a7=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},s7=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),o7=(e,t)=>{const n=EF(t),r=void 0,i=t?.name,a=yt(e._def,n,!1)??{},o=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...r,[i]:a}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o},x5=e=>{const t=e.execute||(async(n,r)=>{try{const i=await e.handler?.(n,r);return typeof i=="string"?[{type:"text",text:i}]:[{type:"text",text:JSON.stringify(i)}]}catch(i){return[{type:"text",text:`Error: ${i}`}]}});return{...e,execute:t}},l7=e=>({render:e.render,onlyRender:e.onlyRender,name:e.name,description:e.description||"",parameters:_F(vF(e.parameters||[])),returnDirect:e.returnDirect,callbackMessage:e.callbackMessage,allowAgent:e.allowAgent,allowGraph:e.allowGraph,async execute(t,n){try{const r=await e.handler?.(t,n);return typeof r=="string"?[{type:"text",text:r}]:[{type:"text",text:JSON.stringify(r)}]}catch(r){return[{type:"text",text:`Error: ${r}`}]}}}),u7=e=>({name:e.name,description:e.description,parameters:e.isPureParams?e.parameters:o7(Eh(e.parameters))}),uT=l7;class w5{constructor(){this.tools=new Map,this.waitingMap=new Map}bindTool(t){if(this.tools.has(t.name))throw new Error(`Tool with name ${t.name} already exists`);this.tools.set(t.name,t)}bindTools(t){t.forEach(n=>this.bindTool(n))}getAllTools(){return Array.from(this.tools.values())}getTool(t){return this.tools.get(t)}removeTool(t){return this.tools.delete(t)}clearTools(){this.tools.clear()}reset(){this.clearTools(),this.clearWaiting()}clearWaiting(){this.waitingMap.clear()}async callTool(t,n,r){const i=this.getTool(t);if(!i)throw new Error(`Tool with name ${t} not found`);return await i.execute?.(n,r)}async toJSON(t,n=!0){return Array.from(this.tools.values()).filter(r=>n?!r.onlyRender:!0).filter(r=>!r.allowGraph||r.allowGraph.includes(t)).map(r=>u7(r))}doneWaiting(t,n){return this.waitingMap.has(t)?(this.waitingMap.get(t)(n),this.waitingMap.delete(t),!0):(console.warn(`Waiting for tool ${t} not found`),!1)}waitForDone(t){return this.waitingMap.has(t)?this.waitingMap.get(t):new Promise((r,i)=>{this.waitingMap.set(t,r)})}static waitForUIDone(t,n){return n.client.tools.waitForDone(n.message.id)}}class Gy{static isTool(t){return t.type==="tool"}static isToolAssistant(t){return t.type==="ai"&&(t.tool_calls?.length||t.tool_call_chunks?.length)}}class c7{constructor(t="task_store"){this.streamingMessage=[],this.graphMessages=[],this.subAgentsKey=t}getStreamingMessages(){return[...this.streamingMessage]}setStreamingMessages(t){this.streamingMessage=t}clearStreamingMessages(){this.streamingMessage=[]}getGraphMessages(){return[...this.graphMessages]}setGraphMessages(t){this.graphMessages=t}updateStreamingMessage(t){const n=this.streamingMessage[this.streamingMessage.length-1];if(!n?.id||t.id!==n.id){this.streamingMessage.push(t);return}this.streamingMessage[this.streamingMessage.length-1]=t}combineGraphMessagesWithStreamingMessages(){const t=new Map(this.streamingMessage.map(n=>[n.id,n]));return[...this.graphMessages.map(n=>{if(t.has(n.id)){const r=t.get(n.id);return t.delete(n.id),r}return n}),...t.values()]}mergeSubGraphMessagesToStreamingMessages(t){const n=new Map(t.filter(r=>r.id).map(r=>[r.id,r]));this.streamingMessage.forEach(r=>{if(n.has(r.id)){const i=n.get(r.id);Object.assign(r,i),n.delete(r.id)}}),n.forEach(r=>{r.type==="tool"&&r.tool_call_id&&this.streamingMessage.push(r)})}cloneMessage(t){return JSON.parse(JSON.stringify(t))}attachInfoForMessage(t){let n=null;const r=[...t];for(const i of r){const a=i.response_metadata?.create_time||"";if(i.unique_id=i.tool_call_id||i.id,i.spend_time=new Date(a).getTime()-new Date(n?.response_metadata?.create_time||a).getTime(),!i.usage_metadata&&i.response_metadata?.usage){const o=i.response_metadata.usage;i.usage_metadata={...o,input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens}}n=i}return r}composeToolMessages(t){const n=[],r=new Map,i=new Map;for(const a of t)if(!(Gy.isToolAssistant(a)&&((a.tool_calls||a.tool_call_chunks)?.forEach(o=>{r.set(o.id,o),i.set(o.id,a)}),!a.content))){if(Gy.isTool(a)&&!a.tool_input){const o=r.get(a.tool_call_id),l=i.get(a.tool_call_id);o&&(a.tool_input=typeof o.args!="string"?JSON.stringify(o.args):o.args,a.additional_kwargs?(a.additional_kwargs.done=!0,a.done=!0):(a.done=!0,a.additional_kwargs={done:!0})),l&&(a.usage_metadata=l.usage_metadata,a.node_name=l.name,a.name||(a.name=l.tool_calls.find(c=>c.id===a.tool_call_id)?.name))}n.push(a)}return n}convertSubAgentMessages(t,n){const r=n[this.subAgentsKey];if(!r)return t;const i=JSON.parse(JSON.stringify(r));t.filter(l=>l.node_name?.startsWith("subagent_")).forEach(l=>{const c=l.node_name.replace("subagent_",""),f=i[c];f?f.messages.some(p=>p.id===l.id)||f.messages.push(l):i[c]={messages:[l]}});const a=new Set;Object.values(i).forEach(l=>{l.messages.forEach(c=>{a.add(c.id)})});const o=[];for(const l of t){if(l.type==="tool"&&l.tool_call_id){const c=i[l.tool_call_id];c&&(l.sub_agent_messages=this.processMessages(c.messages))}l.id&&a.has(l.id)||o.push(l)}return o}renderMessages(t,n){const r=new Map,i=new Set,a=[],o=this.combineGraphMessagesWithStreamingMessages();for(let l=o.length-1;l>=0;l--){const c=this.cloneMessage(o[l]);if(!c.id){a.unshift(c);continue}if(c.type==="ai"&&(c.name||(c.name=n().name)),Gy.isToolAssistant(c)){const f=c;r.set(c.id,f);const p=(f.tool_calls?.length?f.tool_calls:f.tool_call_chunks).filter(m=>!i.has(m.id)).map((m,g)=>({type:"tool",additional_kwargs:{},tool_input:f.additional_kwargs?.tool_calls?.[g]?.function?.arguments,id:m.id,name:m.name,response_metadata:{},tool_call_id:m.id,content:""}));for(const m of p)r.has(m.id)||(a.unshift(m),r.set(m.id,m));a.unshift(f)}else c.type==="tool"&&c.tool_call_id&&i.add(c.tool_call_id),r.set(c.id,c),a.unshift(c)}return this.processMessages(a,t)}processMessages(t,n){const r=this.composeToolMessages(t),i=this.attachInfoForMessage(r);return n?this.convertSubAgentMessages(i,n):i}}async function f7(e,t,n){const r=await e.threads.get(t),i=r.values.messages,a=i.findIndex(f=>f.id===n);if(a===-1)throw new Error(`Message id ${n} not found`);const o=i.slice(a+1),l={...r.values,messages:o.map(f=>({type:"remove",id:f.id}))},c=await e.threads.updateState(t,{values:l});return{state:{messages:i.slice(0,a+1)},checkpoint:c}}class d7 extends Fq{constructor(t){super(),this.currentAssistant=null,this.currentThread=null,this.tools=new w5,this.availableAssistants=[],this.graphState={},this.stopController=null,this.subAgentsKey="task_store",this.graphPosition="",this.extraParams={},this.client=t.client,this.messageProcessor=new c7(this.subAgentsKey)}get assistants(){return this.client.assistants}get threads(){return this.client.threads}get runs(){return this.client.runs}listAssistants(){return this.assistants.search({metadata:null,offset:0,limit:100})}async initAssistant(t){try{const n=await this.listAssistants();if(this.availableAssistants=n,n.length>0)if(t){if(this.currentAssistant=n.find(r=>r.graph_id===t)||null,!this.currentAssistant)throw new Error("Agent not found: "+t)}else this.currentAssistant=n[0];else throw new Error("No assistants found")}catch(n){throw console.error("Failed to initialize LangGraphClient:",n),n}}async createThread({threadId:t,graphId:n}={}){try{return this.currentThread=await this.threads.create({threadId:t,graphId:n}),this.currentThread}catch(r){throw console.error("Failed to create new thread:",r),r}}graphVisualize(){return this.assistants.getGraph(this.currentAssistant?.assistant_id,{xray:!0})}async listThreads(){return this.threads.search({sortOrder:"desc"})}async deleteThread(t){return this.threads.delete(t)}async resetThread(t,n){await this.initAssistant(t),this.currentThread=await this.threads.get(n),this.graphState=this.currentThread.values;const r=this.graphState?.messages||[];return this.messageProcessor.setGraphMessages(r),this.emit("value",{event:"messages/partial",data:{messages:this.messageProcessor.getGraphMessages()}}),this.currentThread}async resetStream(){const n=(await this.runs.list(this.currentThread.thread_id))?.find(r=>r.status==="running"||r.status==="pending");n&&await this.sendMessage([],{joinRunId:n.run_id})}cloneMessage(t){return this.messageProcessor.cloneMessage(t)}get renderMessage(){return this.messageProcessor.renderMessages(this.graphState,()=>this.getGraphNodeNow())}get tokenCounter(){return this.messageProcessor.getGraphMessages().reduce((t,n)=>{if(n.usage_metadata)t.total_tokens+=n.usage_metadata?.total_tokens||0,t.input_tokens+=n.usage_metadata?.input_tokens||0,t.output_tokens+=n.usage_metadata?.output_tokens||0;else if(n.response_metadata?.usage){const r=n.response_metadata?.usage;t.total_tokens+=r.total_tokens||0,t.input_tokens+=r.prompt_tokens||0,t.output_tokens+=r.completion_tokens||0}return t},{total_tokens:0,input_tokens:0,output_tokens:0})}isFELocking(t){const n=t[t.length-1];if(!n)return!1;const r=this.tools.getTool(n?.name);return r&&r.render&&n?.type==="tool"&&!n?.additional_kwargs?.done}cancelRun(){this.currentThread?.thread_id&&this.currentRun?.run_id&&this.runs.cancel(this.currentThread.thread_id,this.currentRun.run_id)}async revertChatTo(t){const{state:n,checkpoint:r}=await f7(this.client,this.currentThread.thread_id,t);return this.graphState=n,this.messageProcessor.clearStreamingMessages(),this.messageProcessor.setGraphMessages(n.messages),n}async sendMessage(t,{joinRunId:n,extraParams:r,_debug:i,command:a}={}){if(!this.currentAssistant)throw new Error("Thread or Assistant not initialized");this.currentThread||(await this.createThread({graphId:this.currentAssistant.graph_id}),this.emit("thread",{event:"thread/create",data:{thread:this.currentThread}}));const o=Array.isArray(t)?t:[{type:"human",content:t}],c=await(async()=>i?.streamResponse?i.streamResponse:n?this.runs.joinStream(this.currentThread.thread_id,n):this.runs.stream(this.currentThread.thread_id,this.currentAssistant.assistant_id,{input:{...this.graphState,...this.extraParams,...r||{},messages:o,fe_tools:await this.tools.toJSON(this.currentAssistant.graph_id)},streamMode:["messages","values"],streamSubgraphs:!0,command:a}))(),f=[];this.emit("start",{event:"start"});for await(const p of c)if(f.push(p),p.event==="metadata")this.currentRun=p.data;else if(p.event==="error"||p.event==="Error"||p.event==="__stream_error__")this.emit("error",p);else if(p.event==="messages/partial"){for(const m of p.data)this.messageProcessor.updateStreamingMessage(m);this.emit("message",p);continue}else if(p.event==="values"){const m=p.data;if(m.messages){const g=!!a?.resume,_=m.messages.length>=this.messageProcessor.getGraphMessages().length;(!g||g&&_)&&(this.messageProcessor.setGraphMessages(m.messages),this.emit("value",p)),this.graphState=p.data}continue}else p.event.startsWith("values|")&&(p.data?.messages&&this.messageProcessor.mergeSubGraphMessagesToStreamingMessages(p.data.messages),this.graphPosition=p.event.split("|")[1]);const d=await this.runFETool();return d&&f.push(...d),this.emit("done",{event:"done"}),this.messageProcessor.clearStreamingMessages(),f}getGraphPosition(){return this.graphPosition.split("|").map(t=>{const[n,r]=t.split(":");return{id:r,name:n}})}getGraphNodeNow(){const t=this.getGraphPosition();return t[t.length-1]}runFETool(){const t=this.messageProcessor.getStreamingMessages(),n=t[t.length-1];if(n&&n.type==="ai"&&n.tool_calls?.length){const r=n.tool_calls.map(i=>{if(this.tools.getTool(i.name)){const a={...i,tool_call_id:i.id,tool_input:JSON.stringify(i.args),additional_kwargs:{}};return this.callFETool(a,i.args)}});return this.currentThread.status="interrupted",Promise.all(r)}}async callFETool(t,n){const r=this,i=await this.tools.callTool(t.name,n,{client:r,message:t});if(i)return this.resume(i)}resume(t){return this.sendMessage([],{command:{resume:t}})}doneFEToolWaiting(t,n){!this.tools.doneWaiting(t,n)&&this.currentThread?.status==="interrupted"&&this.resume(n)}getCurrentThread(){return this.currentThread}getCurrentAssistant(){return this.currentAssistant}async reset(){await this.initAssistant(this.currentAssistant?.graph_id),this.currentThread=null,this.graphState={},this.messageProcessor.setGraphMessages([]),this.messageProcessor.clearStreamingMessages(),this.currentRun=void 0,this.tools.clearWaiting(),this.emit("value",{event:"messages/partial",data:{messages:[]}})}}let Tr=[],_a=0;const gd=4;let An=e=>{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},lc:0,listen(r){return n.lc=t.push(r),()=>{for(let a=_a+gd;a<Tr.length;)Tr[a]===r?Tr.splice(a,gd):a+=gd;let i=t.indexOf(r);~i&&(t.splice(i,1),--n.lc||n.off())}},notify(r,i){let a=!Tr.length;for(let o of t)Tr.push(o,n.value,r,i);if(a){for(_a=0;_a<Tr.length;_a+=gd)Tr[_a](Tr[_a+1],Tr[_a+2],Tr[_a+3]);Tr.length=0}},off(){},set(r){let i=n.value;i!==r&&(n.value=r,n.notify(i))},subscribe(r){let i=n.listen(r);return r(n.value),i},value:e};return n};function h7(e,t,n){let r=new Set(t).add(void 0);return e.listen((i,a,o)=>{r.has(o)&&n(i,a,o)})}function p7(e,t,n){var r,i,a;n===void 0&&(n={});var o=(r=n.isImmediate)!=null&&r,l=(i=n.callback)!=null&&i,c=n.maxWait,f=Date.now(),d=[];function p(){if(c!==void 0){var g=Date.now()-f;if(g+t>=c)return c-g}return t}var m=function(){var g=[].slice.call(arguments),_=this;return new Promise(function(S,b){var x=o&&a===void 0;if(a!==void 0&&clearTimeout(a),a=setTimeout(function(){if(a=void 0,f=Date.now(),!o){var v=e.apply(_,g);l&&l(v),d.forEach(function(k){return(0,k.resolve)(v)}),d=[]}},p()),x){var w=e.apply(_,g);return l&&l(w),S(w)}d.push({resolve:S,reject:b})})};return m.cancel=function(g){a!==void 0&&clearTimeout(a),d.forEach(function(_){return(0,_.reject)(g)}),d=[]},m}const m7="modulepreload",g7=function(e){return"/"+e},cT={},y7=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let f=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};var o=f;document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");i=f(n.map(d=>{if(d=g7(d),d in cT)return;cT[d]=!0;const p=d.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const g=document.createElement("link");if(g.rel=p?"stylesheet":m7,p||(g.as="script"),g.crossOrigin="",g.href=d,c&&g.setAttribute("nonce",c),document.head.appendChild(g),p)return new Promise((_,S)=>{g.addEventListener("load",_),g.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return i.then(l=>{for(const c of l||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})},b7=async e=>{const{Client:t}=await y7(async()=>{const{Client:n}=await Promise.resolve().then(()=>wB);return{Client:n}},void 0);return new t(e)},v7=e=>e.toLocaleTimeString("en-US"),_7=e=>e.toLocaleString("en"),Vh=e=>typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t.type==="text"?t.text:t.type==="image_url"?"[图片]":JSON.stringify(t)).join(""):JSON.stringify(e),x7=e=>{const t=e?.values?.messages?.[0]?.content;return t&&Array.isArray(t)?t.map(n=>{if(n.type==="text")return n.text}):typeof t=="string"?t:""},w7=(e,t,n={})=>{const r=An(null),i=An([]),a=An(""),o=An(!1),l=An([]),c=An(null),f=An(n.showHistory??!1),d=An(e),p=An(null),m=An("__start__"),g=An([]),_=async()=>{const F=r.get();F&&(F.tools.clearTools(),F.tools.bindTools(g.get()))},S=An(n.showGraph??!1),b=An(null),x=async()=>{S.get()&&b.set(await r.get()?.graphVisualize()||null)},w=p7(F=>{const B=F.renderMessage,I=B[B.length-1];m.set(I?.node_name||I?.name||"__start__"),i.set(B)},10);async function v(){const F=new d7({...t,client:t.client??await b7(t)});return await F.initAssistant(d.get()),d.set(F.getCurrentAssistant().graph_id),c.set(null),F.on("start",()=>{o.set(!0)}),F.on("thread",()=>{p.set(F.getCurrentThread()?.thread_id||null),m.set("__start__"),$()}),F.on("done",()=>{o.set(!1),w(F)}),F.on("error",B=>{o.set(!1),c.set(B.data)}),F.on("message",()=>{p.set(F.getCurrentThread()?.thread_id||null),w(F)}),F.on("value",()=>{p.set(F.getCurrentThread()?.thread_id||null),w(F)}),n.onInit?.(F),F.graphState={},r.set(F),S.get()&&x(),_(),F}const k=async(F,B,I=!1)=>{if(!(!I&&!a.get().trim()&&!F?.length||o.get()||!r.get())){o.set(!0),c.set(null);try{await r.get()?.sendMessage(F||a.get(),B)}catch(V){if(V.message.includes("422"))await r.get()?.resetStream();else throw V}finally{a.set(""),o.set(!1)}}},C=()=>{r.get()?.cancelRun()},T=F=>{const B=l.get();l.set(B.includes(F)?B.filter(I=>I!==F):[...B,F])},N=()=>{f.set(!f.get()),f.get()&&$()},j=An([]),$=async()=>{if(!(!r.get()||!f.get()))try{const F=await r.get()?.listThreads();j.set(F||[])}catch(F){console.error("Failed to fetch threads:",F)}};return{data:{client:r,renderMessages:i,userInput:a,loading:o,inChatError:c,currentAgent:d,collapsedTools:l,showHistory:f,historyList:j,currentChatId:p,showGraph:S,graphVisualize:b,currentNodeName:m,tools:g},mutations:{refreshTools:_,setTools(F){g.set(F),_()},isFELocking(){return r.get()?.isFELocking(i.get())},initClient:v,sendMessage:k,stopGeneration:C,toggleToolCollapse:T,toggleHistoryVisible:N,refreshHistoryList:$,addToHistory:F=>{const B=j.get();j.set([F,...B])},async revertChatTo(F,B=!1,I){if(await r.get()?.revertChatTo(F),B)return k([],I,!0);w(r.get())},setUserInput(F){a.set(F)},setCurrentAgent(F){return d.set(F),v().then(()=>{f.get()&&$()})},toggleGraphVisible(){S.set(!S.get()),S.get()&&x()},refreshGraph:x,createNewChat(){r.get()?.reset(),c.set(null),o.set(!1)},async toHistoryChat(F){c.set(null),o.set(!1);const B=await r.get()?.resetThread(F.metadata?.graph_id,F.thread_id);return B&&r.get()?.resetStream(),B},async deleteHistoryChat(F){await r.get()?.deleteThread(F.thread_id),await $()},getToolUIRender:F=>{const I=r.get().tools.getAllTools().find(V=>V.name===F)?.render;return I?V=>I(new B7(V,r.get())):null}}}};class Oo extends Error{constructor(t,n){super("".concat(t," at position ").concat(n)),this.position=n}}const S5=32,S7=10,E5=9,k5=13,E7=160,k7=8192,C7=8202,A7=8239,T7=8287,N7=12288;function O7(e){return/^[0-9A-Fa-f]$/.test(e)}function ls(e){return e>="0"&&e<="9"}function R7(e){return e>=" "}function yd(e){return`,:[]/{}()
|
|
54
|
+
]`;continue}i+=r[c],r[c]==="\\"?a=!0:o&&r[c]==="]"?o=!1:!o&&r[c]==="["&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function _5(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===Ee.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,i)=>({...r,[i]:yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??{}}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===Ee.ZodString&&e.keyType._def.checks?.length){const{type:r,...i}=v5(e.keyType._def,t);return{...n,propertyNames:i}}else{if(e.keyType?._def.typeName===Ee.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Ee.ZodBranded&&e.keyType._def.type._def.typeName===Ee.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...i}=y5(e.keyType._def,t);return{...n,propertyNames:i}}}return n}function LF(e,t){if(t.mapStrategy==="record")return _5(e,t);const n=yt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},r=yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function qF(e){const t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),i=Array.from(new Set(r.map(a=>typeof a)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:r}}function FF(){return{not:{}}}function BF(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Hh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function UF(e,t){if(t.target==="openApi3")return lT(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Hh&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((i,a)=>{const o=Hh[a._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((i,a)=>{const o=typeof a._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":if(a._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(r.length===n.length){const i=r.filter((a,o,l)=>l.indexOf(a)===o);return{type:i.length>1?i:i[0],enum:n.reduce((a,o)=>a.includes(o._def.value)?a:[...a,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,i)=>[...r,...i._def.values.filter(a=>!r.includes(a))],[])};return lT(e,t)}const lT=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,i)=>yt(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function HF(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Hh[e.innerType._def.typeName],nullable:!0}:{type:[Hh[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=yt(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=yt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function VF(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",g5(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?Et(n,"minimum",r.value,r.message,t):Et(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Et(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?Et(n,"maximum",r.value,r.message,t):Et(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Et(n,"maximum",r.value,r.message,t));break;case"multipleOf":Et(n,"multipleOf",r.value,r.message,t);break}return n}function GF(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},i=[],a=e.shape();for(const l in a){let c=a[l];if(c===void 0||c._def===void 0)continue;let f=YF(c);f&&n&&(c instanceof Di&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),f=!1);const d=yt(c._def,{...t,currentPath:[...t.currentPath,"properties",l],propertyPath:[...t.currentPath,"properties",l]});d!==void 0&&(r.properties[l]=d,f||i.push(l))}i.length&&(r.required=i);const o=ZF(e,t);return o!==void 0&&(r.additionalProperties=o),r}function ZF(e,t){if(e.catchall._def.typeName!=="ZodNever")return yt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function YF(e){try{return e.isOptional()}catch{return!0}}const KF=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return yt(e.innerType._def,t);const n=yt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},XF=(e,t)=>{if(t.pipeStrategy==="input")return yt(e.in._def,t);if(t.pipeStrategy==="output")return yt(e.out._def,t);const n=yt(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=yt(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(i=>i!==void 0)}};function WF(e,t){return yt(e.type._def,t)}function QF(e,t){const r={type:"array",uniqueItems:!0,items:yt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Et(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Et(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function JF(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>yt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:yt(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>yt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function e7(){return{not:{}}}function t7(){return{}}const n7=(e,t)=>yt(e.innerType._def,t),r7=(e,t,n)=>{switch(t){case Ee.ZodString:return v5(e,n);case Ee.ZodNumber:return VF(e,n);case Ee.ZodObject:return GF(e,n);case Ee.ZodBigInt:return AF(e,n);case Ee.ZodBoolean:return TF();case Ee.ZodDate:return b5(e,n);case Ee.ZodUndefined:return e7();case Ee.ZodNull:return BF(n);case Ee.ZodArray:return CF(e,n);case Ee.ZodUnion:case Ee.ZodDiscriminatedUnion:return UF(e,n);case Ee.ZodIntersection:return DF(e,n);case Ee.ZodTuple:return JF(e,n);case Ee.ZodRecord:return _5(e,n);case Ee.ZodLiteral:return IF(e,n);case Ee.ZodEnum:return MF(e);case Ee.ZodNativeEnum:return qF(e);case Ee.ZodNullable:return HF(e,n);case Ee.ZodOptional:return KF(e,n);case Ee.ZodMap:return LF(e,n);case Ee.ZodSet:return QF(e,n);case Ee.ZodLazy:return()=>e.getter()._def;case Ee.ZodPromise:return WF(e,n);case Ee.ZodNaN:case Ee.ZodNever:return FF();case Ee.ZodEffects:return jF(e,n);case Ee.ZodAny:return kF();case Ee.ZodUnknown:return t7();case Ee.ZodDefault:return RF(e,n);case Ee.ZodBranded:return y5(e,n);case Ee.ZodReadonly:return n7(e,n);case Ee.ZodCatch:return NF(e,n);case Ee.ZodPipeline:return XF(e,n);case Ee.ZodFunction:case Ee.ZodVoid:case Ee.ZodSymbol:return;default:return(r=>{})()}};function yt(e,t,n=!1){const r=t.seen.get(e);if(t.override){const l=t.override?.(e,t,r,n);if(l!==xF)return l}if(r&&!n){const l=i7(r,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=r7(e,e.typeName,t),o=typeof a=="function"?yt(a(),t):a;if(o&&s7(e,t,o),t.postProcess){const l=t.postProcess(o,e,t);return i.jsonSchema=o,l}return i.jsonSchema=o,o}const i7=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:a7(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},a7=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},s7=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),o7=(e,t)=>{const n=EF(t),r=void 0,i=t?.name,a=yt(e._def,n,!1)??{},o=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...r,[i]:a}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o},x5=e=>{const t=e.execute||(async(n,r)=>{try{const i=await e.handler?.(n,r);return typeof i=="string"?[{type:"text",text:i}]:[{type:"text",text:JSON.stringify(i)}]}catch(i){return[{type:"text",text:`Error: ${i}`}]}});return{...e,execute:t}},l7=e=>({render:e.render,onlyRender:e.onlyRender,name:e.name,description:e.description||"",parameters:_F(vF(e.parameters||[])),returnDirect:e.returnDirect,callbackMessage:e.callbackMessage,allowAgent:e.allowAgent,allowGraph:e.allowGraph,async execute(t,n){try{const r=await e.handler?.(t,n);return typeof r=="string"?[{type:"text",text:r}]:[{type:"text",text:JSON.stringify(r)}]}catch(r){return[{type:"text",text:`Error: ${r}`}]}}}),u7=e=>({name:e.name,description:e.description,parameters:e.isPureParams?e.parameters:o7(Eh(e.parameters))}),uT=l7;class w5{constructor(){this.tools=new Map,this.waitingMap=new Map}bindTool(t){if(this.tools.has(t.name))throw new Error(`Tool with name ${t.name} already exists`);this.tools.set(t.name,t)}bindTools(t){t.forEach(n=>this.bindTool(n))}getAllTools(){return Array.from(this.tools.values())}getTool(t){return this.tools.get(t)}removeTool(t){return this.tools.delete(t)}clearTools(){this.tools.clear()}reset(){this.clearTools(),this.clearWaiting()}clearWaiting(){this.waitingMap.clear()}async callTool(t,n,r){const i=this.getTool(t);if(!i)throw new Error(`Tool with name ${t} not found`);return await i.execute?.(n,r)}async toJSON(t,n=!0){return Array.from(this.tools.values()).filter(r=>n?!r.onlyRender:!0).filter(r=>!r.allowGraph||r.allowGraph.includes(t)).map(r=>u7(r))}doneWaiting(t,n){return this.waitingMap.has(t)?(this.waitingMap.get(t)(n),this.waitingMap.delete(t),!0):(console.warn(`Waiting for tool ${t} not found`),!1)}waitForDone(t){return this.waitingMap.has(t)?this.waitingMap.get(t):new Promise((r,i)=>{this.waitingMap.set(t,r)})}static waitForUIDone(t,n){return n.client.tools.waitForDone(n.message.id)}}class Gy{static isTool(t){return t.type==="tool"}static isToolAssistant(t){return t.type==="ai"&&(t.tool_calls?.length||t.tool_call_chunks?.length)}}class c7{constructor(t="task_store"){this.streamingMessage=[],this.graphMessages=[],this.subAgentsKey=t}getStreamingMessages(){return[...this.streamingMessage]}setStreamingMessages(t){this.streamingMessage=t}clearStreamingMessages(){this.streamingMessage=[]}getGraphMessages(){return[...this.graphMessages]}setGraphMessages(t){this.graphMessages=t}updateStreamingMessage(t){const n=this.streamingMessage[this.streamingMessage.length-1];if(!n?.id||t.id!==n.id){this.streamingMessage.push(t);return}this.streamingMessage[this.streamingMessage.length-1]=t}combineGraphMessagesWithStreamingMessages(){const t=new Map(this.streamingMessage.map(n=>[n.id,n]));return[...this.graphMessages.map(n=>{if(t.has(n.id)){const r=t.get(n.id);return t.delete(n.id),r}return n}),...t.values()]}mergeSubGraphMessagesToStreamingMessages(t){const n=new Map(t.filter(r=>r.id).map(r=>[r.id,r]));this.streamingMessage.forEach(r=>{if(n.has(r.id)){const i=n.get(r.id);Object.assign(r,i),n.delete(r.id)}}),n.forEach(r=>{r.type==="tool"&&r.tool_call_id&&this.streamingMessage.push(r)})}cloneMessage(t){return JSON.parse(JSON.stringify(t))}attachInfoForMessage(t){let n=null;const r=[...t];for(const i of r){const a=i.response_metadata?.create_time||"";if(i.unique_id=i.tool_call_id||i.id,i.spend_time=new Date(a).getTime()-new Date(n?.response_metadata?.create_time||a).getTime(),!i.usage_metadata&&i.response_metadata?.usage){const o=i.response_metadata.usage;i.usage_metadata={...o,input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens}}n=i}return r}composeToolMessages(t){const n=[],r=new Map,i=new Map;for(const a of t)if(!(Gy.isToolAssistant(a)&&((a.tool_calls||a.tool_call_chunks)?.forEach(o=>{r.set(o.id,o),i.set(o.id,a)}),!a.content))){if(Gy.isTool(a)&&!a.tool_input){const o=r.get(a.tool_call_id),l=i.get(a.tool_call_id);o&&(a.tool_input=typeof o.args!="string"?JSON.stringify(o.args):o.args,a.additional_kwargs?(a.additional_kwargs.done=!0,a.done=!0):(a.done=!0,a.additional_kwargs={done:!0})),l&&(a.usage_metadata=l.usage_metadata,a.node_name=l.name,a.name||(a.name=l.tool_calls.find(c=>c.id===a.tool_call_id)?.name))}n.push(a)}return n}convertSubAgentMessages(t,n){const r=n[this.subAgentsKey];if(!r)return t;const i=JSON.parse(JSON.stringify(r));t.filter(l=>l.node_name?.startsWith("subagent_")).forEach(l=>{const c=l.node_name.replace("subagent_",""),f=i[c];f?f.messages.some(p=>p.id===l.id)||f.messages.push(l):i[c]={messages:[l]}});const a=new Set;Object.values(i).forEach(l=>{l.messages.forEach(c=>{a.add(c.id)})});const o=[];for(const l of t){if(l.type==="tool"&&l.tool_call_id){const c=i[l.tool_call_id];c&&(l.sub_agent_messages=this.processMessages(c.messages))}l.id&&a.has(l.id)||o.push(l)}return o}renderMessages(t,n){const r=new Map,i=new Set,a=[],o=this.combineGraphMessagesWithStreamingMessages();for(let l=o.length-1;l>=0;l--){const c=this.cloneMessage(o[l]);if(!c.id){a.unshift(c);continue}if(c.type==="ai"&&(c.name||(c.name=n().name)),Gy.isToolAssistant(c)){const f=c;r.set(c.id,f);const p=(f.tool_calls?.length?f.tool_calls:f.tool_call_chunks).filter(m=>!i.has(m.id)).map((m,g)=>({type:"tool",additional_kwargs:{},tool_input:f.additional_kwargs?.tool_calls?.[g]?.function?.arguments,id:m.id,name:m.name,response_metadata:{},tool_call_id:m.id,content:""}));for(const m of p)r.has(m.id)||(a.unshift(m),r.set(m.id,m));a.unshift(f)}else c.type==="tool"&&c.tool_call_id&&i.add(c.tool_call_id),r.set(c.id,c),a.unshift(c)}return this.processMessages(a,t)}processMessages(t,n){const r=this.composeToolMessages(t),i=this.attachInfoForMessage(r);return n?this.convertSubAgentMessages(i,n):i}}async function f7(e,t,n){const r=await e.threads.get(t),i=r.values.messages,a=i.findIndex(f=>f.id===n);if(a===-1)throw new Error(`Message id ${n} not found`);const o=i.slice(a+1),l={...r.values,messages:o.map(f=>({type:"remove",id:f.id}))},c=await e.threads.updateState(t,{values:l});return{state:{messages:i.slice(0,a+1)},checkpoint:c}}class d7 extends Fq{constructor(t){super(),this.currentAssistant=null,this.currentThread=null,this.tools=new w5,this.availableAssistants=[],this.graphState={},this.stopController=null,this.subAgentsKey="task_store",this.graphPosition="",this.extraParams={},this.client=t.client,this.messageProcessor=new c7(this.subAgentsKey)}get assistants(){return this.client.assistants}get threads(){return this.client.threads}get runs(){return this.client.runs}listAssistants(){return this.assistants.search({metadata:null,offset:0,limit:100})}async initAssistant(t){try{const n=await this.listAssistants();if(this.availableAssistants=n,n.length>0)if(t){if(this.currentAssistant=n.find(r=>r.graph_id===t)||null,!this.currentAssistant)throw new Error("Agent not found: "+t)}else this.currentAssistant=n[0];else throw new Error("No assistants found")}catch(n){throw console.error("Failed to initialize LangGraphClient:",n),n}}async createThread({threadId:t,graphId:n}={}){try{return this.currentThread=await this.threads.create({threadId:t,graphId:n}),this.currentThread}catch(r){throw console.error("Failed to create new thread:",r),r}}graphVisualize(){return this.assistants.getGraph(this.currentAssistant?.assistant_id,{xray:!0})}async listThreads(){return this.threads.search({sortOrder:"desc"})}async deleteThread(t){return this.threads.delete(t)}async resetThread(t,n){await this.initAssistant(t),this.currentThread=await this.threads.get(n),this.graphState=this.currentThread.values;const r=this.graphState?.messages||[];return this.messageProcessor.setGraphMessages(r),this.emit("value",{event:"messages/partial",data:{messages:this.messageProcessor.getGraphMessages()}}),this.currentThread}async resetStream(){const n=(await this.runs.list(this.currentThread.thread_id))?.find(r=>r.status==="running"||r.status==="pending");n&&await this.sendMessage([],{joinRunId:n.run_id})}cloneMessage(t){return this.messageProcessor.cloneMessage(t)}get renderMessage(){return this.messageProcessor.renderMessages(this.graphState,()=>this.getGraphNodeNow())}get tokenCounter(){return this.messageProcessor.getGraphMessages().reduce((t,n)=>{if(n.usage_metadata)t.total_tokens+=n.usage_metadata?.total_tokens||0,t.input_tokens+=n.usage_metadata?.input_tokens||0,t.output_tokens+=n.usage_metadata?.output_tokens||0;else if(n.response_metadata?.usage){const r=n.response_metadata?.usage;t.total_tokens+=r.total_tokens||0,t.input_tokens+=r.prompt_tokens||0,t.output_tokens+=r.completion_tokens||0}return t},{total_tokens:0,input_tokens:0,output_tokens:0})}isFELocking(t){const n=t[t.length-1];if(!n)return!1;const r=this.tools.getTool(n?.name);return r&&r.render&&n?.type==="tool"&&!n?.additional_kwargs?.done}cancelRun(){this.currentThread?.thread_id&&this.currentRun?.run_id&&this.runs.cancel(this.currentThread.thread_id,this.currentRun.run_id)}async revertChatTo(t){const{state:n,checkpoint:r}=await f7(this.client,this.currentThread.thread_id,t);return this.graphState=n,this.messageProcessor.clearStreamingMessages(),this.messageProcessor.setGraphMessages(n.messages),n}async sendMessage(t,{joinRunId:n,extraParams:r,_debug:i,command:a}={}){if(!this.currentAssistant)throw new Error("Thread or Assistant not initialized");this.currentThread||(await this.createThread({graphId:this.currentAssistant.graph_id}),this.emit("thread",{event:"thread/create",data:{thread:this.currentThread}}));const o=Array.isArray(t)?t:[{type:"human",content:t}],c=await(async()=>i?.streamResponse?i.streamResponse:n?this.runs.joinStream(this.currentThread.thread_id,n):this.runs.stream(this.currentThread.thread_id,this.currentAssistant.assistant_id,{input:{...this.graphState,...this.extraParams,...r||{},messages:o,fe_tools:await this.tools.toJSON(this.currentAssistant.graph_id)},streamMode:["messages","values"],streamSubgraphs:!0,command:a}))(),f=[];this.emit("start",{event:"start"});for await(const p of c)if(f.push(p),p.event==="metadata")this.currentRun=p.data;else if(p.event==="error"||p.event==="Error"||p.event==="__stream_error__")this.emit("error",p);else if(p.event==="messages/partial"){for(const m of p.data)this.messageProcessor.updateStreamingMessage(m);this.emit("message",p);continue}else if(p.event==="values"){const m=p.data;if(m.messages){const g=!!a?.resume,_=m.messages.length>=this.messageProcessor.getGraphMessages().length;(!g||g&&_)&&(this.messageProcessor.setGraphMessages(m.messages),this.emit("value",p)),this.graphState=p.data}continue}else p.event.startsWith("values|")&&(p.data?.messages&&this.messageProcessor.mergeSubGraphMessagesToStreamingMessages(p.data.messages),this.graphPosition=p.event.split("|")[1]);const d=await this.runFETool();return d&&f.push(...d),this.emit("done",{event:"done"}),this.messageProcessor.clearStreamingMessages(),f}getGraphPosition(){return this.graphPosition.split("|").map(t=>{const[n,r]=t.split(":");return{id:r,name:n}})}getGraphNodeNow(){const t=this.getGraphPosition();return t[t.length-1]}runFETool(){const t=this.messageProcessor.getStreamingMessages(),n=t[t.length-1];if(n&&n.type==="ai"&&n.tool_calls?.length){const r=n.tool_calls.map(i=>{if(this.tools.getTool(i.name)){const a={...i,tool_call_id:i.id,tool_input:JSON.stringify(i.args),additional_kwargs:{}};return this.callFETool(a,i.args)}});return this.currentThread.status="interrupted",Promise.all(r)}}async callFETool(t,n){const r=this,i=await this.tools.callTool(t.name,n,{client:r,message:t});if(i)return this.resume(i)}resume(t){return this.sendMessage([],{command:{resume:t}})}doneFEToolWaiting(t,n){!this.tools.doneWaiting(t,n)&&this.currentThread?.status==="interrupted"&&this.resume(n)}getCurrentThread(){return this.currentThread}getCurrentAssistant(){return this.currentAssistant}async reset(){await this.initAssistant(this.currentAssistant?.graph_id),this.currentThread=null,this.graphState={},this.messageProcessor.setGraphMessages([]),this.messageProcessor.clearStreamingMessages(),this.currentRun=void 0,this.tools.clearWaiting(),this.emit("value",{event:"messages/partial",data:{messages:[]}})}}let Tr=[],_a=0;const gd=4;let An=e=>{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},lc:0,listen(r){return n.lc=t.push(r),()=>{for(let a=_a+gd;a<Tr.length;)Tr[a]===r?Tr.splice(a,gd):a+=gd;let i=t.indexOf(r);~i&&(t.splice(i,1),--n.lc||n.off())}},notify(r,i){let a=!Tr.length;for(let o of t)Tr.push(o,n.value,r,i);if(a){for(_a=0;_a<Tr.length;_a+=gd)Tr[_a](Tr[_a+1],Tr[_a+2],Tr[_a+3]);Tr.length=0}},off(){},set(r){let i=n.value;i!==r&&(n.value=r,n.notify(i))},subscribe(r){let i=n.listen(r);return r(n.value),i},value:e};return n};function h7(e,t,n){let r=new Set(t).add(void 0);return e.listen((i,a,o)=>{r.has(o)&&n(i,a,o)})}function p7(e,t,n){var r,i,a;n===void 0&&(n={});var o=(r=n.isImmediate)!=null&&r,l=(i=n.callback)!=null&&i,c=n.maxWait,f=Date.now(),d=[];function p(){if(c!==void 0){var g=Date.now()-f;if(g+t>=c)return c-g}return t}var m=function(){var g=[].slice.call(arguments),_=this;return new Promise(function(S,b){var x=o&&a===void 0;if(a!==void 0&&clearTimeout(a),a=setTimeout(function(){if(a=void 0,f=Date.now(),!o){var v=e.apply(_,g);l&&l(v),d.forEach(function(k){return(0,k.resolve)(v)}),d=[]}},p()),x){var w=e.apply(_,g);return l&&l(w),S(w)}d.push({resolve:S,reject:b})})};return m.cancel=function(g){a!==void 0&&clearTimeout(a),d.forEach(function(_){return(0,_.reject)(g)}),d=[]},m}const m7="modulepreload",g7=function(e){return"/"+e},cT={},y7=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let f=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};var o=f;document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");i=f(n.map(d=>{if(d=g7(d),d in cT)return;cT[d]=!0;const p=d.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const g=document.createElement("link");if(g.rel=p?"stylesheet":m7,p||(g.as="script"),g.crossOrigin="",g.href=d,c&&g.setAttribute("nonce",c),document.head.appendChild(g),p)return new Promise((_,S)=>{g.addEventListener("load",_),g.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return i.then(l=>{for(const c of l||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})},b7=async e=>{const{Client:t}=await y7(async()=>{const{Client:n}=await Promise.resolve().then(()=>wB);return{Client:n}},void 0);return new t(e)},v7=e=>e.toLocaleTimeString("en-US"),_7=e=>e.toLocaleString("en"),Vh=e=>typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t.type==="text"?t.text:t.type==="image_url"?"[图片]":JSON.stringify(t)).join(""):JSON.stringify(e),x7=e=>{const t=e?.values?.messages?.[0]?.content;return t&&Array.isArray(t)?t.map(n=>{if(n.type==="text")return n.text}):typeof t=="string"?t:""},w7=(e,t,n={})=>{const r=An(null),i=An([]),a=An(""),o=An(!1),l=An([]),c=An(null),f=An(n.showHistory??!1),d=An(e),p=An(null),m=An("__start__"),g=An([]),_=async()=>{const F=r.get();F&&(F.tools.clearTools(),F.tools.bindTools(g.get()))},S=An(n.showGraph??!1),b=An(null),x=async()=>{S.get()&&b.set(await r.get()?.graphVisualize()||null)},w=p7(F=>{const B=F.renderMessage,I=B[B.length-1];m.set(I?.node_name||I?.name||"__start__"),i.set(B)},10);async function v(){const F=new d7({...t,client:t.client??await b7(t)});return await F.initAssistant(d.get()),d.set(F.getCurrentAssistant().graph_id),c.set(null),F.on("start",()=>{o.set(!0)}),F.on("thread",()=>{p.set(F.getCurrentThread()?.thread_id||null),m.set("__start__"),$()}),F.on("done",()=>{o.set(!1),w(F)}),F.on("error",B=>{o.set(!1),c.set(B.data)}),F.on("message",()=>{p.set(F.getCurrentThread()?.thread_id||null),w(F)}),F.on("value",()=>{p.set(F.getCurrentThread()?.thread_id||null),w(F)}),n.onInit?.(F),F.graphState={},r.set(F),S.get()&&x(),_(),F}const k=async(F,B,I=!1)=>{if(!(!I&&!a.get().trim()&&!F?.length||o.get()||!r.get())){o.set(!0),c.set(null);try{await r.get()?.sendMessage(F||a.get(),B)}catch(V){if(V.message.includes("422"))await r.get()?.resetStream();else throw V}finally{a.set(""),o.set(!1)}}},C=()=>{r.get()?.cancelRun()},T=F=>{const B=l.get();l.set(B.includes(F)?B.filter(I=>I!==F):[...B,F])},N=()=>{f.set(!f.get()),f.get()&&$()},j=An([]),$=async()=>{if(!(!r.get()||!f.get()))try{const F=await r.get()?.listThreads();j.set(F||[])}catch(F){console.error("Failed to fetch threads:",F)}};return{data:{client:r,renderMessages:i,userInput:a,loading:o,inChatError:c,currentAgent:d,collapsedTools:l,showHistory:f,historyList:j,currentChatId:p,showGraph:S,graphVisualize:b,currentNodeName:m,tools:g},mutations:{refreshTools:_,setTools(F){g.set(F),_()},isFELocking(){return r.get()?.isFELocking(i.get())},getClient(){return r.get()},initClient:v,sendMessage:k,stopGeneration:C,toggleToolCollapse:T,toggleHistoryVisible:N,refreshHistoryList:$,addToHistory:F=>{const B=j.get();j.set([F,...B])},async revertChatTo(F,B=!1,I){if(await r.get()?.revertChatTo(F),B)return k([],I,!0);w(r.get())},setUserInput(F){a.set(F)},setCurrentAgent(F){return d.set(F),v().then(()=>{f.get()&&$()})},toggleGraphVisible(){S.set(!S.get()),S.get()&&x()},refreshGraph:x,createNewChat(){r.get()?.reset(),c.set(null),o.set(!1)},async toHistoryChat(F){c.set(null),o.set(!1);const B=await r.get()?.resetThread(F.metadata?.graph_id,F.thread_id);return B&&r.get()?.resetStream(),B},async deleteHistoryChat(F){await r.get()?.deleteThread(F.thread_id),await $()},getToolUIRender:F=>{const I=r.get().tools.getAllTools().find(V=>V.name===F)?.render;return I?V=>I(new B7(V,r.get())):null}}}};class Oo extends Error{constructor(t,n){super("".concat(t," at position ").concat(n)),this.position=n}}const S5=32,S7=10,E5=9,k5=13,E7=160,k7=8192,C7=8202,A7=8239,T7=8287,N7=12288;function O7(e){return/^[0-9A-Fa-f]$/.test(e)}function ls(e){return e>="0"&&e<="9"}function R7(e){return e>=" "}function yd(e){return`,:[]/{}()
|
|
55
55
|
+`.includes(e)}function fT(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"}function dT(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"||e>="0"&&e<="9"}const hT=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,pT=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function mT(e){return`,[]/{}
|
|
56
56
|
+`.includes(e)}function gT(e){return kh(e)||j7.test(e)}const j7=/^[[{\w-]$/;function M7(e){return e===`
|
|
57
57
|
`||e==="\r"||e===" "||e==="\b"||e==="\f"}function ms(e,t){const n=e.charCodeAt(t);return n===S5||n===S7||n===E5||n===k5}function $7(e,t){const n=e.charCodeAt(t);return n===S5||n===E5||n===k5}function D7(e,t){const n=e.charCodeAt(t);return n===E7||n>=k7&&n<=C7||n===A7||n===T7||n===N7}function kh(e){return C5(e)||hw(e)}function C5(e){return e==='"'||e==="“"||e==="”"}function yT(e){return e==='"'}function hw(e){return e==="'"||e==="‘"||e==="’"||e==="`"||e==="´"}function bT(e){return e==="'"}function vu(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const r=e.lastIndexOf(t);return r!==-1?e.substring(0,r)+(n?"":e.substring(r+1)):e}function Nr(e,t){let n=e.length;if(!ms(e,n-1))return e+t;for(;ms(e,n-1);)n--;return e.substring(0,n)+t+e.substring(n)}function I7(e,t,n){return e.substring(0,t)+e.substring(t+n)}function P7(e){return/[,\n][ \t\r]*$/.test(e)}const z7={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},L7={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
package/dist/index.html
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
padding: 0;
|
|
13
13
|
}
|
|
14
14
|
</style>
|
|
15
|
-
<script type="module" crossorigin src="/assets/index-
|
|
15
|
+
<script type="module" crossorigin src="/assets/index-IirYMaE5.js"></script>
|
|
16
16
|
<link rel="stylesheet" crossorigin href="/assets/index-CRq7a-Q4.css">
|
|
17
17
|
</head>
|
|
18
18
|
<body>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langgraph-js/ui",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"registry": "https://registry.npmjs.org/",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"unocss": "^66.5.3",
|
|
39
39
|
"vite": "^7",
|
|
40
40
|
"zod": "^3.25.56",
|
|
41
|
-
"@langgraph-js/sdk": "3.0.
|
|
41
|
+
"@langgraph-js/sdk": "3.0.4"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/react": "^19.0.10",
|