flujo-ai 3.15.0 → 3.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-build-manifest.json +58 -58
- package/.next/app-path-routes-manifest.json +13 -13
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +6 -6
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/api/backup/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/browse/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/cwd/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/encryption/secure/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/env/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/flow/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/flow/compile/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/flow/generate/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/flow/prompt-renderer/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/flow/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/git/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/init/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/local-models/capability/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/local-models/pull/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/local-models/suggest/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/cancel/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/prompts/get/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/prompts/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/resources/read/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/resources/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/status/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/tools/[toolName]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/[name]/tools/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/servers/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/test-connection/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp/test-connection/stream/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp-registry/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/mcp-registry/spotlight/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/model/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/model/provider/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/model/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/model/test/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/oauth/callback/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/oauth/initiate/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/oauth/reset/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/planned-executions/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/planned-executions/[id]/run/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/planned-executions/[id]/runs/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/planned-executions/preview-schedule/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/planned-executions/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/restore/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/storage/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/update/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/webhooks/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/chat/page_client-reference-manifest.js +1 -1
- package/.next/server/app/chat.html +1 -1
- package/.next/server/app/chat.rsc +1 -1
- package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
- package/.next/server/app/docs.html +1 -1
- package/.next/server/app/docs.rsc +1 -1
- package/.next/server/app/executions/page_client-reference-manifest.js +1 -1
- package/.next/server/app/executions.html +1 -1
- package/.next/server/app/executions.rsc +1 -1
- package/.next/server/app/flows/page_client-reference-manifest.js +1 -1
- package/.next/server/app/flows.html +1 -1
- package/.next/server/app/flows.rsc +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +1 -1
- package/.next/server/app/mcp/page_client-reference-manifest.js +1 -1
- package/.next/server/app/mcp-flows/route.js +1 -1
- package/.next/server/app/mcp-flows/route_client-reference-manifest.js +1 -1
- package/.next/server/app/mcp-proxy/[server]/route.js +1 -1
- package/.next/server/app/mcp-proxy/[server]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/mcp.html +1 -1
- package/.next/server/app/mcp.rsc +1 -1
- package/.next/server/app/models/page_client-reference-manifest.js +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/server/app/settings.html +1 -1
- package/.next/server/app/settings.rsc +1 -1
- package/.next/server/app/v1/chat/completions/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/breakpoints/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/cancel/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/debug/continue/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/debug/step/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/edit-state/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/events/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/respond/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/[conversationId]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/chat/conversations/route_client-reference-manifest.js +1 -1
- package/.next/server/app/v1/models/route_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +13 -13
- package/.next/server/chunks/2859.js +3 -1
- package/.next/server/chunks/5504.js +1 -1
- package/.next/server/chunks/6195.js +6 -4
- package/.next/server/chunks/7362.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/pages-manifest.json +1 -1
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/trace +7 -7
- package/README.md +1 -1
- package/package.json +1 -1
- /package/.next/static/{5bnHIDHGn1uWHUQhpqe6Z → z7fsG7kblb_yxkUhOxn-G}/_buildManifest.js +0 -0
- /package/.next/static/{5bnHIDHGn1uWHUQhpqe6Z → z7fsG7kblb_yxkUhOxn-G}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";exports.id=6195,exports.ids=[6195],exports.modules={76195:(a,b,c)=>{c.d(b,{internalCallTool:()=>
|
|
1
|
+
"use strict";exports.id=6195,exports.ids=[6195],exports.modules={76195:(a,b,c)=>{c.d(b,{internalCallTool:()=>ac,internalToolDefinitions:()=>R});var d=c(33873),e=c.n(d),f=c(79646),g=c(18230),h=c(72440),i=c(12763),j=c(71188),k=c(67463),l=c(63129);let m=`A FlowSpec is a JSON object describing a FLUJO flow semantically — node keys and edges, no coordinates, no ids, no layout:
|
|
2
2
|
{
|
|
3
3
|
"name": "short_flow_name", // letters/digits/_/- only
|
|
4
4
|
"description": "what the flow does",
|
|
@@ -28,8 +28,10 @@ RULES:
|
|
|
28
28
|
4. Do not embed \${tool:...} or \${resource:...} references in prompts — tools are wired through "servers".
|
|
29
29
|
5. Branching: give a process node multiple outgoing edges; its model decides where to hand off at runtime. "bidirectional": true lets the target hand back to the source (agent <-> agent).
|
|
30
30
|
6. A subflow node may have only ONE outgoing edge, and its "flow" must name an existing flow.
|
|
31
|
-
7. Keep flows minimal — only the steps the task needs. Write clear, specific prompts and labels; fill "description" on process nodes.`;var j=c(89850),k=c(8336);let l={type:"arrowclosed",width:20,height:20,color:"#1976d2"},m={stroke:"#1976d2",strokeWidth:2},n=new Set(["full-history","latest-message","isolated"]),o=new Set(["steps","final-only"]);function p(a){let b=(0,k.A$)(a);if(0===b.length)return{text:a,stripped:!1};let c="",d=0;for(let e of b)c+=a.slice(d,e.index)+e.name,d=e.index+e.fullMatch.length;return{text:c+=a.slice(d),stripped:!0}}function q(a,b){let c=b.filter(a=>"error"===a.severity).length;return{flow:a,issues:b,errorCount:c,warningCount:b.length-c}}var r=c(54898),s=c(99924);let t=(0,d.h)("backend/services/flow/generationContext");function u(a,b){let c=String(a).replace(/\s+/g," ").trim();return c.length<=b?c:`${c.slice(0,b).trimEnd()}…`}async function v(){let a=await f.modelService.loadModels(),b=a.map(a=>({id:a.id,name:a.name,...a.displayName?{displayName:a.displayName}:{},...a.description?{description:u(a.description,100)}:{}})),c=[],d={};try{let a=await s.mcpService.loadServerConfigs();if(Array.isArray(a))for(let b of a){if(b.disabled)continue;let a=!1;try{let c=await s.mcpService.getServerStatus(b.name);a=c?.status==="connected"}catch(a){t.debug(`getServerStatus failed for ${b.name}; listing name only`,a)}if(!a){c.push({name:b.name,connected:!1});continue}let{tools:e}=await s.mcpService.listServerTools(b.name),f=(e??[]).filter(a=>a.name).map(a=>({name:a.name,...a.description?{description:u(a.description,100)}:{}}));d[b.name]=f.map(a=>a.name),c.push({name:b.name,connected:!0,tools:f})}}catch(a){t.warn("Could not load MCP servers for the authoring context",a)}let g=[];try{g=await e.flowService.loadFlows()}catch(a){t.warn("Could not load flows for the authoring context",a)}let h={models:b,servers:c,flows:g.map(a=>({id:a.id,name:a.name,...a.description?{description:u(a.description,300)}:{},nodeCount:a.nodes?.length??0}))};return{blocks:h,compile:{models:a.map(a=>({id:a.id,name:a.name,displayName:a.displayName})),servers:c.map(a=>({name:a.name})),serverTools:d,flows:g.map(a=>({id:a.id,name:a.name}))},catalog:function(a){let b=[];for(let c of(b.push("AVAILABLE MODELS (reference by id or name):"),0===a.models.length&&b.push(" (none configured)"),a.models)){let a=c.displayName&&c.displayName!==c.name?`"${c.displayName}" (${c.name})`:c.name,d=c.description?` — ${c.description}`:"";b.push(` - id: ${c.id} — ${a}${d}`)}for(let c of(b.push("",'AVAILABLE MCP SERVERS (attach to process nodes via "servers"):'),0===a.servers.length&&b.push(" (none configured)"),a.servers)){if(!c.connected){b.push(` - ${c.name} (offline — tools unknown; may still be used)`);continue}b.push(` - ${c.name}:`);let a=(c.tools??[]).slice(0,20);for(let c of a){let a=c.description?` — ${c.description}`:"";b.push(` - ${c.name}${a}`)}let d=(c.tools?.length??0)-a.length;d>0&&b.push(` - …and ${d} more`)}for(let c of(b.push("",'EXISTING FLOWS (usable as subflow targets via "flow"):'),0===a.flows.length&&b.push(" (none)"),a.flows.slice(0,15))){let a=c.description?` — ${c.description}`:` — ${c.nodeCount} nodes`;b.push(` - "${c.name}"${a}`)}return a.flows.length>15&&b.push(` - …and ${a.flows.length-15} more`),b.join("\n")}(h),validatorServers:c.map(a=>({name:a.name,status:a.connected?"connected":"disconnected"}))}}let w=(0,d.h)("backend/services/flow/compileFlow");async function x(a,b={}){if(!a||"object"!=typeof a||Array.isArray(a))return{success:!1,error:"The spec must be a JSON object (a FlowSpec)",statusCode:400};let c=await v(),d=function(a,b={}){let c=[],d=(a,b,d)=>c.push({severity:"error",code:a,message:b,nodeKey:d}),e=(a,b,d)=>c.push({severity:"warning",code:a,message:b,nodeKey:d}),f=b.models??[],g=new Set((b.servers??[]).map(a=>a.name)),h=b.serverTools??{},i=b.flows??[],k=Array.isArray(a?.nodes)?a.nodes:[],r=Array.isArray(a?.edges)?a.edges:[],s=new Map,t=[],u=[];for(let a of k){let b=a?.key;if(!b||"string"!=typeof b){d("node-missing-key",'A node is missing its "key" — every node needs a unique key.');continue}if(s.has(b)){d("node-duplicate-key",`Duplicate node key "${b}" — keys must be unique; the later node was dropped.`,b);continue}let c=a.type;if("mcp"===c){d("mcp-node-not-allowed",`Node "${b}": do not emit "mcp" nodes — attach servers to a process node via its "servers" list instead.`,b);continue}if("start"!==c&&"process"!==c&&"finish"!==c&&"subflow"!==c){d("unknown-node-type",`Node "${b}" has unknown type "${String(c)}".`,b);continue}let k={},l="string"==typeof a.prompt?a.prompt:void 0;if("start"===c){let{text:a,stripped:c}=p(l??"");c&&e("pill-stripped",`Node "${b}": binding pills are not supported in generated prompts and were replaced with plain names.`,b),k.promptTemplate=a}else if("process"===c){let{text:c,stripped:d}=p(l??"");if(d&&e("pill-stripped",`Node "${b}": binding pills are not supported in generated prompts and were replaced with plain names.`,b),k.promptTemplate=c,a.model){let c=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.displayName?.toLowerCase()===c);if(d)return d.id;let e=b.find(a=>a.name?.toLowerCase()===c);return e?e.id:null}(a.model,f);c?k.boundModel=c:(k.boundModel=a.model,e("model-unresolved",`Node "${b}": model "${a.model}" does not match any configured model (by id, display name, or name).`,b))}void 0!==a.inputMode&&(n.has(a.inputMode)?(k.inputMode=a.inputMode,"isolated"===a.inputMode&&"string"==typeof a.isolatedPrompt&&(k.isolatedPrompt=a.isolatedPrompt)):e("invalid-input-mode",`Node "${b}": inputMode "${String(a.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,b))}else if("subflow"===c){if(a.flow){let c=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.name.toLowerCase()===c);return d?d.id:null}(a.flow,i);c?k.subflowId=c:d("subflow-unresolved",`Node "${b}": flow "${a.flow}" does not match any existing flow (by id or name).`,b)}else d("subflow-missing-flow",`Node "${b}": subflow nodes need a "flow" (name or id of an existing flow).`,b);if(void 0!==a.inputMode&&(n.has(a.inputMode)?k.inputMode=a.inputMode:e("invalid-input-mode",`Node "${b}": inputMode "${String(a.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,b)),void 0!==a.outputMode&&(o.has(a.outputMode)?k.outputMode=a.outputMode:e("invalid-output-mode",`Node "${b}": outputMode "${String(a.outputMode)}" is not valid (steps | final-only); omitted.`,b)),void 0!==l){let{text:a,stripped:c}=p(l);c&&e("pill-stripped",`Node "${b}": binding pills are not supported in generated prompts and were replaced with plain names.`,b),k.promptTemplate=a}}let m={id:(0,j.A)(),type:c,position:{x:0,y:0},data:{label:a.label||`${c.charAt(0).toUpperCase()}${c.slice(1)} Node`,type:c,...a.description?{description:a.description}:{},properties:k}};if(s.set(b,m),t.push(m),"process"===c&&Array.isArray(a.servers)){let c=new Set;for(let d of a.servers){let a,f=d?.name;if(!f||"string"!=typeof f){e("server-missing-name",`Node "${b}": a server reference is missing its "name"; skipped.`,b);continue}if(c.has(f))continue;c.add(f),g.has(f)||e("server-unknown",`Node "${b}": MCP server "${f}" is not configured in FLUJO.`,b);let i=h[f];if(Array.isArray(d.tools)){if(a=d.tools.filter(a=>"string"==typeof a&&a),i){let c=a.filter(a=>!i.includes(a));c.length>0&&e("tool-unknown",`Node "${b}": server "${f}" does not report tool(s): ${c.join(", ")}.`,b)}}else a=i?[...i]:[];let k={id:(0,j.A)(),type:"mcp",position:{x:0,y:0},data:{label:f,type:"mcp",properties:{boundServer:f,enabledTools:a}}};t.push(k),u.push({processKey:b,mcpNode:k})}}else"process"!==c&&Array.isArray(a.servers)&&a.servers.length>0&&e("servers-on-non-process",`Node "${b}": only process nodes can have "servers"; ignored.`,b)}if(0===s.size)return d("no-usable-nodes","No usable nodes — the spec must contain at least a start node and one step."),q(null,c);let v=[],w=new Set;for(let a of r){let b=a?.from,c=a?.to,f=b?s.get(b):void 0,g=c?s.get(c):void 0;if(!f||!g){d("edge-unknown-node",`Edge "${String(b)}" -> "${String(c)}" references a node key that does not exist (or was dropped).`);continue}if(f===g){d("edge-self-loop",`Edge "${b}" -> "${c}": a node cannot connect to itself.`);continue}if("start"===g.type){d("edge-into-start",`Edge "${b}" -> "${c}": nothing may connect INTO a start node.`);continue}if("finish"===f.type){d("edge-out-of-finish",`Edge "${b}" -> "${c}": nothing may connect OUT OF a finish node.`);continue}let h=`${b}->${c}`;if(w.has(h)){e("edge-duplicate",`Edge "${b}" -> "${c}" appears more than once; kept the first.`);continue}w.add(h);let i=!0===a.bidirectional;i&&("start"===f.type||"finish"===g.type)&&(e("bidirectional-illegal",`Edge "${b}" -> "${c}" cannot be bidirectional; downgraded to one-way.`),i=!1),v.push(function(a,b,c){let d=`${a.type}-bottom`,e=`${b.type}-top`;return{id:`${a.id}:${d}->${b.id}:${e}`,source:a.id,sourceHandle:d,target:b.id,targetHandle:e,type:"custom",data:{edgeType:"standard",...c?{bidirectional:!0}:{}},animated:!0}}(f,g,i))}for(let{processKey:a,mcpNode:b}of u){let c=s.get(a);v.push(function(a,b){let c="process-right-mcp",d="mcp-left";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"mcpEdge",data:{edgeType:"mcp"},animated:!1,markerEnd:{...l},markerStart:{...l},style:{...m}}}(c,b))}!function(a,b,c,d){let e=new Map;for(let a of c)a.data?.edgeType!=="mcp"&&(e.has(a.source)||e.set(a.source,[]),e.get(a.source).push(a.target));let f=[...b.values()],g=f.filter(a=>"start"===a.type),h=g.length>0?g:f.slice(0,1),i=new Map,j=h.map(a=>({id:a.id,depth:0}));for(let a of j)i.set(a.id,0);for(;j.length;){let{id:a,depth:b}=j.shift();for(let c of e.get(a)??[])i.has(c)||(i.set(c,b+1),j.push({id:c,depth:b+1}))}let k=0;for(let a of i.values())k=Math.max(k,a);for(let a of f)i.has(a.id)||i.set(a.id,k+1);let l=new Map;for(let a of f){let b=i.get(a.id),c=l.get(b)??0;l.set(b,c+1),a.position={x:250+280*c,y:150+170*b}}let m=new Map;for(let{processKey:a,mcpNode:c}of d){let d=b.get(a),e=m.get(a)??0;m.set(a,e+1),c.position={x:d.position.x+320,y:d.position.y+150*e}}}(0,s,v,u);let x=i.map(a=>a.name);return q({id:(0,j.A)(),name:function(a,b){let c=(a??"").trim().replace(/[^\w-]+/g,"_").replace(/^_+|_+$/g,"");c||(c="generated_flow");let d=new Set(b.map(a=>a.toLowerCase()));if(!d.has(c.toLowerCase()))return c;for(let a=2;;a++){let b=`${c}_${a}`;if(!d.has(b.toLowerCase()))return b}}(a?.name,x),...a?.description?{description:a.description}:{},nodes:t,edges:v},c)}(a,c.compile);if(!d.flow)return{success:!1,error:"The spec could not be compiled into a flow",statusCode:422,issues:d.issues.map(a=>({severity:a.severity,code:a.code,message:a.message}))};let f=function(a,b){let c=[...a.map(a=>({severity:a.severity,code:a.code,message:a.message})),...b.issues],d=c.filter(a=>"error"===a.severity).length;return{issues:c,errorCount:d,warningCount:c.length-d,isRunnable:0===d}}(d.issues,(0,r.nC)(d.flow,{models:c.compile.models,servers:c.validatorServers,serverTools:c.compile.serverTools})),g=!1;return b.save&&0===f.errorCount?(await e.flowService.saveFlow(d.flow),g=!0,w.info(`Compiled and saved flow "${d.flow.name}" (${d.flow.id})`)):b.save&&w.info(`Compiled flow "${d.flow.name}" has ${f.errorCount} error(s); NOT saved`),{success:!0,flow:d.flow,validation:f,saved:g}}var y=c(12700),z=c(79861);let A=(0,d.h)("backend/services/mcp/registryInstall"),B="/v0.1/servers";async function C(a,b=8){let c=new URL(y.jD+B);c.searchParams.set("version","latest"),c.searchParams.set("limit",String(Math.min(Math.max(b,1),30))),a&&c.searchParams.set("search",a);let d=await (0,y.Ws)(c,15e3);return(Array.isArray(d?.servers)?d.servers:[]).map(a=>(function(a){let b=(0,z.AH)(a),c=b[0];return{name:a.name,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{},installable:b.length>0,requiredEnv:c?(0,z.jg)(c):[]}})(a.server))}async function D(a){let b=new URL(y.jD+B);b.searchParams.set("version","latest"),b.searchParams.set("limit","10"),b.searchParams.set("search",a);let c=await (0,y.Ws)(b,15e3),d=Array.isArray(c?.servers)?c.servers:[],e=d.find(b=>b.server?.name===a);return(e??d[0])?.server??null}async function E(a,b){let c;if(!a||"string"!=typeof a)return{installed:!1,error:"A registry server name is required"};try{c=await D(a)}catch(a){return{installed:!1,error:`Registry lookup failed: ${a instanceof Error?a.message:String(a)}`}}if(!c)return{installed:!1,error:`No registry entry found for "${a}"`};let d=(0,z.AH)(c)[0];if(!d)return{installed:!1,error:`"${c.name}" has no install method FLUJO supports (stdio package or HTTP remote)`};let e=(0,z.jg)(d,b);if(e.length>0)return{installed:!1,needsEnv:e,error:`"${c.name}" requires values for: ${e.join(", ")}`};let f=(0,z.cy)((0,z.Yr)(c,d),b),g=f.name,h=await s.mcpService.loadServerConfigs();if(Array.isArray(h)&&h.some(a=>a.name===g)){A.info(`installRegistryServer: "${g}" already configured; reusing`);let{tools:a,error:b}=await s.mcpService.listServerTools(g);return{installed:!0,alreadyExisted:!0,serverName:g,tools:(a??[]).map(a=>({name:a.name,...a.description?{description:a.description}:{}})),...b?{error:b}:{}}}A.info(`installRegistryServer: installing "${c.name}" as "${g}" (${d.kind})`);let i=await s.mcpService.updateServerConfig(g,f);if(!Array.isArray(i)&&i&&"success"in i&&!1===i.success)return{installed:!1,error:`Saving the server failed: ${i.error??"unknown error"}`};let{tools:j,error:k}=await s.mcpService.listServerTools(g);return{installed:!0,serverName:g,tools:(j??[]).map(a=>({name:a.name,...a.description?{description:a.description}:{}})),...k?{error:k}:{}}}let F=(0,d.h)("backend/services/mcp/flowAuthoringTools"),G=["list_flow_building_blocks","validate_flow_spec","create_flow","search_mcp_marketplace","install_mcp_server"];function H(){return{type:"object",properties:{spec:{type:"object",description:"The FlowSpec object (see the tool description for the format)."}},required:["spec"]}}function I(a,b=!1){return{content:[{type:"text",text:JSON.stringify(a,null,2)}],...b?{isError:!0}:{}}}async function J(a,b){try{if("list_flow_building_blocks"===a){let a=await v();return I(a.blocks)}if("search_mcp_marketplace"===a){let a="string"==typeof b?.query?b.query:"",c=await C(a);return I(c)}if("install_mcp_server"===a){let a="string"==typeof b?.name?b.name:"",c=b?.env&&"object"==typeof b.env&&!Array.isArray(b.env)?b.env:void 0,d=await E(a,c);return I(d,!d.installed)}if("validate_flow_spec"===a||"create_flow"===a){let c=function(a){let b=a?.spec;if("string"==typeof b)try{return JSON.parse(b)}catch{return null}return b??null}(b);if(!c)return I({error:'Provide a "spec" argument: a FlowSpec object (or a JSON string of one).'},!0);let d=await x(c,{save:"create_flow"===a});if(!d.success)return I({error:d.error,issues:d.issues??[]},!0);let e={flowId:d.flow.id,flowName:d.flow.name,nodeCount:d.flow.nodes.length,edgeCount:d.flow.edges.length,validation:d.validation,..."create_flow"===a?{saved:d.saved,...d.saved?{note:`Flow "${d.flow.name}" was created. It is callable as a tool on this MCP server (after a fresh tools/list) and as model "flow-${d.flow.name}" on the OpenAI-compatible endpoint.`}:{note:"NOT saved: validation found errors. Fix the issues and call create_flow again."}}:{}};return I(e,"create_flow"===a&&!d.saved)}return I({error:`Unknown authoring tool: ${a}`},!0)}catch(b){return F.error("authoringCallTool failed",{toolName:a,err:b}),I({error:`Authoring tool failed: ${b instanceof Error?b.message:String(b)}`},!0)}}var K=c(92018);let L=(0,d.h)("backend/services/mcp/internalTools");function M(a,b=!1){return{content:[{type:"text",text:"string"==typeof a?a:JSON.stringify(a,null,2)}],...b?{isError:!0}:{}}}function N(){return[{name:"list_flow_building_blocks",description:'List everything a FlowSpec may reference in this FLUJO instance: configured models (bind to process steps), MCP servers and their tools (attach via "servers"), and existing flows (usable as subflow targets). Call this before authoring a spec.',inputSchema:{type:"object",properties:{}}},{name:"validate_flow_spec",description:`Compile and validate a FlowSpec WITHOUT saving. Returns the compiled flow's validation result (errors block saving; warnings are advisory) so you can iterate until clean, then call create_flow.
|
|
31
|
+
7. Keep flows minimal — only the steps the task needs. Write clear, specific prompts and labels; fill "description" on process nodes.`;var n=c(89850),o=c(8336);let p={type:"arrowclosed",width:20,height:20,color:"#1976d2"},q={stroke:"#1976d2",strokeWidth:2},r=new Set(["full-history","latest-message","isolated"]),s=new Set(["steps","final-only"]);function t(a){let b=(0,o.A$)(a);if(0===b.length)return{text:a,stripped:!1};let c="",d=0;for(let e of b)c+=a.slice(d,e.index)+e.name,d=e.index+e.fullMatch.length;return{text:c+=a.slice(d),stripped:!0}}function u(a,b){let c=b.filter(a=>"error"===a.severity).length;return{flow:a,issues:b,errorCount:c,warningCount:b.length-c}}var v=c(54898),w=c(99924);let x=(0,g.h)("backend/services/flow/generationContext");function y(a,b){let c=String(a).replace(/\s+/g," ").trim();return c.length<=b?c:`${c.slice(0,b).trimEnd()}…`}async function z(){let a=await i.modelService.loadModels(),b=a.map(a=>({id:a.id,name:a.name,...a.displayName?{displayName:a.displayName}:{},...a.description?{description:y(a.description,100)}:{}})),c=[],d={};try{let a=await w.mcpService.loadServerConfigs();if(Array.isArray(a))for(let b of a){if(b.disabled)continue;let a=!1;try{let c=await w.mcpService.getServerStatus(b.name);a=c?.status==="connected"}catch(a){x.debug(`getServerStatus failed for ${b.name}; listing name only`,a)}if(!a){c.push({name:b.name,connected:!1});continue}let{tools:e}=await w.mcpService.listServerTools(b.name),f=(e??[]).filter(a=>a.name).map(a=>({name:a.name,...a.description?{description:y(a.description,100)}:{}}));d[b.name]=f.map(a=>a.name),c.push({name:b.name,connected:!0,tools:f})}}catch(a){x.warn("Could not load MCP servers for the authoring context",a)}let e=[];try{e=await h.flowService.loadFlows()}catch(a){x.warn("Could not load flows for the authoring context",a)}let f={models:b,servers:c,flows:e.map(a=>({id:a.id,name:a.name,...a.description?{description:y(a.description,300)}:{},nodeCount:a.nodes?.length??0}))};return{blocks:f,compile:{models:a.map(a=>({id:a.id,name:a.name,displayName:a.displayName})),servers:c.map(a=>({name:a.name})),serverTools:d,flows:e.map(a=>({id:a.id,name:a.name}))},catalog:function(a){let b=[];for(let c of(b.push("AVAILABLE MODELS (reference by id or name):"),0===a.models.length&&b.push(" (none configured)"),a.models)){let a=c.displayName&&c.displayName!==c.name?`"${c.displayName}" (${c.name})`:c.name,d=c.description?` — ${c.description}`:"";b.push(` - id: ${c.id} — ${a}${d}`)}for(let c of(b.push("",'AVAILABLE MCP SERVERS (attach to process nodes via "servers"):'),0===a.servers.length&&b.push(" (none configured)"),a.servers)){if(!c.connected){b.push(` - ${c.name} (offline — tools unknown; may still be used)`);continue}b.push(` - ${c.name}:`);let a=(c.tools??[]).slice(0,20);for(let c of a){let a=c.description?` — ${c.description}`:"";b.push(` - ${c.name}${a}`)}let d=(c.tools?.length??0)-a.length;d>0&&b.push(` - …and ${d} more`)}for(let c of(b.push("",'EXISTING FLOWS (usable as subflow targets via "flow"):'),0===a.flows.length&&b.push(" (none)"),a.flows.slice(0,15))){let a=c.description?` — ${c.description}`:` — ${c.nodeCount} nodes`;b.push(` - "${c.name}"${a}`)}return a.flows.length>15&&b.push(` - …and ${a.flows.length-15} more`),b.join("\n")}(f),validatorServers:c.map(a=>({name:a.name,status:a.connected?"connected":"disconnected"}))}}let A=(0,g.h)("backend/services/flow/compileFlow");async function B(a,b={}){if(!a||"object"!=typeof a||Array.isArray(a))return{success:!1,error:"The spec must be a JSON object (a FlowSpec)",statusCode:400};let c=await z(),d=function(a,b={}){let c=[],d=(a,b,d)=>c.push({severity:"error",code:a,message:b,nodeKey:d}),e=(a,b,d)=>c.push({severity:"warning",code:a,message:b,nodeKey:d}),f=b.models??[],g=new Set((b.servers??[]).map(a=>a.name)),h=b.serverTools??{},i=b.flows??[],j=Array.isArray(a?.nodes)?a.nodes:[],k=Array.isArray(a?.edges)?a.edges:[],l=new Map,m=[],o=[];for(let a of j){let b=a?.key;if(!b||"string"!=typeof b){d("node-missing-key",'A node is missing its "key" — every node needs a unique key.');continue}if(l.has(b)){d("node-duplicate-key",`Duplicate node key "${b}" — keys must be unique; the later node was dropped.`,b);continue}let c=a.type;if("mcp"===c){d("mcp-node-not-allowed",`Node "${b}": do not emit "mcp" nodes — attach servers to a process node via its "servers" list instead.`,b);continue}if("start"!==c&&"process"!==c&&"finish"!==c&&"subflow"!==c){d("unknown-node-type",`Node "${b}" has unknown type "${String(c)}".`,b);continue}let j={},k="string"==typeof a.prompt?a.prompt:void 0;if("start"===c){let{text:a,stripped:c}=t(k??"");c&&e("pill-stripped",`Node "${b}": binding pills are not supported in generated prompts and were replaced with plain names.`,b),j.promptTemplate=a}else if("process"===c){let{text:c,stripped:d}=t(k??"");if(d&&e("pill-stripped",`Node "${b}": binding pills are not supported in generated prompts and were replaced with plain names.`,b),j.promptTemplate=c,a.model){let c=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.displayName?.toLowerCase()===c);if(d)return d.id;let e=b.find(a=>a.name?.toLowerCase()===c);return e?e.id:null}(a.model,f);c?j.boundModel=c:(j.boundModel=a.model,e("model-unresolved",`Node "${b}": model "${a.model}" does not match any configured model (by id, display name, or name).`,b))}void 0!==a.inputMode&&(r.has(a.inputMode)?(j.inputMode=a.inputMode,"isolated"===a.inputMode&&"string"==typeof a.isolatedPrompt&&(j.isolatedPrompt=a.isolatedPrompt)):e("invalid-input-mode",`Node "${b}": inputMode "${String(a.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,b))}else if("subflow"===c){if(a.flow){let c=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.name.toLowerCase()===c);return d?d.id:null}(a.flow,i);c?j.subflowId=c:d("subflow-unresolved",`Node "${b}": flow "${a.flow}" does not match any existing flow (by id or name).`,b)}else d("subflow-missing-flow",`Node "${b}": subflow nodes need a "flow" (name or id of an existing flow).`,b);if(void 0!==a.inputMode&&(r.has(a.inputMode)?j.inputMode=a.inputMode:e("invalid-input-mode",`Node "${b}": inputMode "${String(a.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,b)),void 0!==a.outputMode&&(s.has(a.outputMode)?j.outputMode=a.outputMode:e("invalid-output-mode",`Node "${b}": outputMode "${String(a.outputMode)}" is not valid (steps | final-only); omitted.`,b)),void 0!==k){let{text:a,stripped:c}=t(k);c&&e("pill-stripped",`Node "${b}": binding pills are not supported in generated prompts and were replaced with plain names.`,b),j.promptTemplate=a}}let p={id:(0,n.A)(),type:c,position:{x:0,y:0},data:{label:a.label||`${c.charAt(0).toUpperCase()}${c.slice(1)} Node`,type:c,...a.description?{description:a.description}:{},properties:j}};if(l.set(b,p),m.push(p),"process"===c&&Array.isArray(a.servers)){let c=new Set;for(let d of a.servers){let a,f=d?.name;if(!f||"string"!=typeof f){e("server-missing-name",`Node "${b}": a server reference is missing its "name"; skipped.`,b);continue}if(c.has(f))continue;c.add(f),g.has(f)||e("server-unknown",`Node "${b}": MCP server "${f}" is not configured in FLUJO.`,b);let i=h[f];if(Array.isArray(d.tools)){if(a=d.tools.filter(a=>"string"==typeof a&&a),i){let c=a.filter(a=>!i.includes(a));c.length>0&&e("tool-unknown",`Node "${b}": server "${f}" does not report tool(s): ${c.join(", ")}.`,b)}}else a=i?[...i]:[];let j={id:(0,n.A)(),type:"mcp",position:{x:0,y:0},data:{label:f,type:"mcp",properties:{boundServer:f,enabledTools:a}}};m.push(j),o.push({processKey:b,mcpNode:j})}}else"process"!==c&&Array.isArray(a.servers)&&a.servers.length>0&&e("servers-on-non-process",`Node "${b}": only process nodes can have "servers"; ignored.`,b)}if(0===l.size)return d("no-usable-nodes","No usable nodes — the spec must contain at least a start node and one step."),u(null,c);let v=[],w=new Set;for(let a of k){let b=a?.from,c=a?.to,f=b?l.get(b):void 0,g=c?l.get(c):void 0;if(!f||!g){d("edge-unknown-node",`Edge "${String(b)}" -> "${String(c)}" references a node key that does not exist (or was dropped).`);continue}if(f===g){d("edge-self-loop",`Edge "${b}" -> "${c}": a node cannot connect to itself.`);continue}if("start"===g.type){d("edge-into-start",`Edge "${b}" -> "${c}": nothing may connect INTO a start node.`);continue}if("finish"===f.type){d("edge-out-of-finish",`Edge "${b}" -> "${c}": nothing may connect OUT OF a finish node.`);continue}let h=`${b}->${c}`;if(w.has(h)){e("edge-duplicate",`Edge "${b}" -> "${c}" appears more than once; kept the first.`);continue}w.add(h);let i=!0===a.bidirectional;i&&("start"===f.type||"finish"===g.type)&&(e("bidirectional-illegal",`Edge "${b}" -> "${c}" cannot be bidirectional; downgraded to one-way.`),i=!1),v.push(function(a,b,c){let d=`${a.type}-bottom`,e=`${b.type}-top`;return{id:`${a.id}:${d}->${b.id}:${e}`,source:a.id,sourceHandle:d,target:b.id,targetHandle:e,type:"custom",data:{edgeType:"standard",...c?{bidirectional:!0}:{}},animated:!0}}(f,g,i))}for(let{processKey:a,mcpNode:b}of o){let c=l.get(a);v.push(function(a,b){let c="process-right-mcp",d="mcp-left";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"mcpEdge",data:{edgeType:"mcp"},animated:!1,markerEnd:{...p},markerStart:{...p},style:{...q}}}(c,b))}!function(a,b,c,d){let e=new Map;for(let a of c)a.data?.edgeType!=="mcp"&&(e.has(a.source)||e.set(a.source,[]),e.get(a.source).push(a.target));let f=[...b.values()],g=f.filter(a=>"start"===a.type),h=g.length>0?g:f.slice(0,1),i=new Map,j=h.map(a=>({id:a.id,depth:0}));for(let a of j)i.set(a.id,0);for(;j.length;){let{id:a,depth:b}=j.shift();for(let c of e.get(a)??[])i.has(c)||(i.set(c,b+1),j.push({id:c,depth:b+1}))}let k=0;for(let a of i.values())k=Math.max(k,a);for(let a of f)i.has(a.id)||i.set(a.id,k+1);let l=new Map;for(let a of f){let b=i.get(a.id),c=l.get(b)??0;l.set(b,c+1),a.position={x:250+280*c,y:150+170*b}}let m=new Map;for(let{processKey:a,mcpNode:c}of d){let d=b.get(a),e=m.get(a)??0;m.set(a,e+1),c.position={x:d.position.x+320,y:d.position.y+150*e}}}(0,l,v,o);let x=i.map(a=>a.name);return u({id:(0,n.A)(),name:function(a,b){let c=(a??"").trim().replace(/[^\w-]+/g,"_").replace(/^_+|_+$/g,"");c||(c="generated_flow");let d=new Set(b.map(a=>a.toLowerCase()));if(!d.has(c.toLowerCase()))return c;for(let a=2;;a++){let b=`${c}_${a}`;if(!d.has(b.toLowerCase()))return b}}(a?.name,x),...a?.description?{description:a.description}:{},nodes:m,edges:v},c)}(a,c.compile);if(!d.flow)return{success:!1,error:"The spec could not be compiled into a flow",statusCode:422,issues:d.issues.map(a=>({severity:a.severity,code:a.code,message:a.message}))};let e=function(a,b){let c=[...a.map(a=>({severity:a.severity,code:a.code,message:a.message})),...b.issues],d=c.filter(a=>"error"===a.severity).length;return{issues:c,errorCount:d,warningCount:c.length-d,isRunnable:0===d}}(d.issues,(0,v.nC)(d.flow,{models:c.compile.models,servers:c.validatorServers,serverTools:c.compile.serverTools})),f=!1;return b.save&&0===e.errorCount?(await h.flowService.saveFlow(d.flow),f=!0,A.info(`Compiled and saved flow "${d.flow.name}" (${d.flow.id})`)):b.save&&A.info(`Compiled flow "${d.flow.name}" has ${e.errorCount} error(s); NOT saved`),{success:!0,flow:d.flow,validation:e,saved:f}}var C=c(12700),D=c(79861);let E=(0,g.h)("backend/services/mcp/registryInstall"),F="/v0.1/servers";async function G(a,b=8){let c=new URL(C.jD+F);c.searchParams.set("version","latest"),c.searchParams.set("limit",String(Math.min(Math.max(b,1),30))),a&&c.searchParams.set("search",a);let d=await (0,C.Ws)(c,15e3);return(Array.isArray(d?.servers)?d.servers:[]).map(a=>(function(a){let b=(0,D.AH)(a),c=b[0];return{name:a.name,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{},installable:b.length>0,requiredEnv:c?(0,D.jg)(c):[]}})(a.server))}async function H(a){let b=new URL(C.jD+F);b.searchParams.set("version","latest"),b.searchParams.set("limit","10"),b.searchParams.set("search",a);let c=await (0,C.Ws)(b,15e3),d=Array.isArray(c?.servers)?c.servers:[],e=d.find(b=>b.server?.name===a);return(e??d[0])?.server??null}async function I(a,b){let c;if(!a||"string"!=typeof a)return{installed:!1,error:"A registry server name is required"};try{c=await H(a)}catch(a){return{installed:!1,error:`Registry lookup failed: ${a instanceof Error?a.message:String(a)}`}}if(!c)return{installed:!1,error:`No registry entry found for "${a}"`};let d=(0,D.AH)(c)[0];if(!d)return{installed:!1,error:`"${c.name}" has no install method FLUJO supports (stdio package or HTTP remote)`};let e=(0,D.jg)(d,b);if(e.length>0)return{installed:!1,needsEnv:e,error:`"${c.name}" requires values for: ${e.join(", ")}`};let f=(0,D.cy)((0,D.Yr)(c,d),b),g=f.name,h=await w.mcpService.loadServerConfigs();if(Array.isArray(h)&&h.some(a=>a.name===g)){E.info(`installRegistryServer: "${g}" already configured; reusing`);let{tools:a,error:b}=await w.mcpService.listServerTools(g);return{installed:!0,alreadyExisted:!0,serverName:g,tools:(a??[]).map(a=>({name:a.name,...a.description?{description:a.description}:{}})),...b?{error:b}:{}}}E.info(`installRegistryServer: installing "${c.name}" as "${g}" (${d.kind})`);let i=await w.mcpService.updateServerConfig(g,f);if(!Array.isArray(i)&&i&&"success"in i&&!1===i.success)return{installed:!1,error:`Saving the server failed: ${i.error??"unknown error"}`};let{tools:j,error:k}=await w.mcpService.listServerTools(g);return{installed:!0,serverName:g,tools:(j??[]).map(a=>({name:a.name,...a.description?{description:a.description}:{}})),...k?{error:k}:{}}}let J=(0,g.h)("backend/services/mcp/flowAuthoringTools"),K=["list_flow_building_blocks","validate_flow_spec","create_flow","search_mcp_marketplace","install_mcp_server"];function L(){return{type:"object",properties:{spec:{type:"object",description:"The FlowSpec object (see the tool description for the format)."}},required:["spec"]}}function M(a,b=!1){return{content:[{type:"text",text:JSON.stringify(a,null,2)}],...b?{isError:!0}:{}}}async function N(a,b){try{if("list_flow_building_blocks"===a){let a=await z();return M(a.blocks)}if("search_mcp_marketplace"===a){let a="string"==typeof b?.query?b.query:"",c=await G(a);return M(c)}if("install_mcp_server"===a){let a="string"==typeof b?.name?b.name:"",c=b?.env&&"object"==typeof b.env&&!Array.isArray(b.env)?b.env:void 0,d=await I(a,c);return M(d,!d.installed)}if("validate_flow_spec"===a||"create_flow"===a){let c=function(a){let b=a?.spec;if("string"==typeof b)try{return JSON.parse(b)}catch{return null}return b??null}(b);if(!c)return M({error:'Provide a "spec" argument: a FlowSpec object (or a JSON string of one).'},!0);let d=await B(c,{save:"create_flow"===a});if(!d.success)return M({error:d.error,issues:d.issues??[]},!0);let e={flowId:d.flow.id,flowName:d.flow.name,nodeCount:d.flow.nodes.length,edgeCount:d.flow.edges.length,validation:d.validation,..."create_flow"===a?{saved:d.saved,...d.saved?{note:`Flow "${d.flow.name}" was created. It is callable as a tool on this MCP server (after a fresh tools/list) and as model "flow-${d.flow.name}" on the OpenAI-compatible endpoint.`}:{note:"NOT saved: validation found errors. Fix the issues and call create_flow again."}}:{}};return M(e,"create_flow"===a&&!d.saved)}return M({error:`Unknown authoring tool: ${a}`},!0)}catch(b){return J.error("authoringCallTool failed",{toolName:a,err:b}),M({error:`Authoring tool failed: ${b instanceof Error?b.message:String(b)}`},!0)}}var O=c(92018);let P=(0,g.h)("backend/services/mcp/internalTools");function Q(a,b=!1){return{content:[{type:"text",text:"string"==typeof a?a:JSON.stringify(a,null,2)}],...b?{isError:!0}:{}}}function R(){return[{name:"list_flow_building_blocks",description:'List everything a FlowSpec may reference in this FLUJO instance: configured models (bind to process steps), MCP servers and their tools (attach via "servers"), and existing flows (usable as subflow targets). Call this before authoring a spec.',inputSchema:{type:"object",properties:{}}},{name:"validate_flow_spec",description:`Compile and validate a FlowSpec WITHOUT saving. Returns the compiled flow's validation result (errors block saving; warnings are advisory) so you can iterate until clean, then call create_flow.
|
|
32
32
|
|
|
33
|
-
${
|
|
33
|
+
${m}`,inputSchema:L()},{name:"create_flow",description:`Create a new FLUJO flow from a FlowSpec. The spec is compiled deterministically (layout, ids, and wiring are generated for you) and saved ONLY when validation finds zero errors — otherwise the issues are returned to fix. Use list_flow_building_blocks first to see the models, MCP servers/tools, and existing flows you may reference.
|
|
34
34
|
|
|
35
|
-
${i}`,inputSchema:H()},{name:"search_mcp_marketplace",description:"Search the public MCP server registry for new capabilities (voice, browsing, files, email, vision, …). The registry matches the query against server NAMES only (substring) — use short single terms and try several. Returns name, description, whether FLUJO can install it, and which env vars/keys it would require.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Short search term matched against server names."}},required:["query"]}},{name:"install_mcp_server",description:'Install an MCP server from the public registry (by the exact name returned by search_mcp_marketplace) and connect it — this DOWNLOADS AND RUNS a third-party package on the FLUJO host. Returns the FLUJO server name (reference it in FlowSpec "servers") and the tools it provides, or needsEnv when required keys are missing (supply values via the optional "env" argument, or pick a keyless alternative). First install can take minutes (package download).',inputSchema:{type:"object",properties:{name:{type:"string",description:'Exact registry name from search results, e.g. "ai.keenable/web-search".'},env:{type:"object",description:"Optional env var values for the server (e.g. required API keys).",additionalProperties:{type:"string"}}},required:["name"]}},{name:"execute_flow",description:"Run another FLUJO flow (by name or id) with the given input and return its final output. The run is ephemeral (no chat conversation is created). Use list_flow_building_blocks to see the available flows. Nested runs are limited in depth — a flow cannot recurse through itself indefinitely.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."},input:{type:"string",description:"The message to send to the flow as the user turn."}},required:["flow","input"]}},{name:"delete_flow",description:"PERMANENTLY delete a FLUJO flow (by name or id). This cannot be undone. Verify the target with list_flow_building_blocks first.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."}},required:["flow"]}},{name:"list_mcp_servers",description:"List the MCP servers configured in this FLUJO instance with their transport, enabled/disabled state and live connection status. Config details (env vars, headers, credentials) are never included.",inputSchema:{type:"object",properties:{}}},{name:"list_mcp_server_tools",description:"List the tools of one configured MCP server (name, description, input schema). Use together with call_mcp_tool for servers that are not bound to this flow.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name (see list_mcp_servers)."}},required:["server"]}},{name:"call_mcp_tool",description:"Call a tool on any configured MCP server by server name + tool name. This lets you use servers that are not bound to the current flow. Check the tool's input schema with list_mcp_server_tools first.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."},tool:{type:"string",description:"The tool name on that server."},args:{type:"object",description:"Arguments for the tool (per its input schema)."},timeout:{type:"number",description:"Optional timeout in seconds."}},required:["server","tool"]}},{name:"restart_mcp_server",description:"Force-reconnect a configured MCP server (tears the connection down and rebuilds it). Useful when a server is in an error state after a config or environment change.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."}},required:["server"]}},{name:"set_mcp_server_enabled",description:"Enable or disable a configured MCP server. Disabling disconnects it and prevents any further use; enabling connects it.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."},enabled:{type:"boolean",description:"true to enable + connect, false to disable + disconnect."}},required:["server","enabled"]}},{name:"list_models",description:"List the models configured in this FLUJO instance (id, name, display name, description, provider, base URL, context window). API keys are never included. Reference models by id or name in FlowSpecs.",inputSchema:{type:"object",properties:{}}},{name:"list_planned_executions",description:"List the planned (scheduled/triggered) executions in this FLUJO instance with their trigger type, enabled state, armed status and last run outcome.",inputSchema:{type:"object",properties:{}}},{name:"run_planned_execution",description:"Fire a planned execution immediately (by id, see list_planned_executions) and return the run record with its output.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The planned execution id."}},required:["id"]}}]}async function O(a){let b=await e.flowService.loadFlows();return b.find(b=>b.id===a)??b.find(b=>b.name===a)}async function P(a){let b=String(a?.flow??"").trim();if(!b)return M({error:'Provide "flow": a flow name or id.'},!0);let c=await O(b);if(!c)return M({error:`No flow named or with id "${b}". Use list_flow_building_blocks to see the available flows.`},!0);let d=global.__flujo_internal_flow_depth??0;if(d>=4)return M({error:`execute_flow nesting limit (4) reached — refusing to start "${c.name}" to prevent runaway recursion.`},!0);global.__flujo_internal_flow_depth=d+1;try{let b=await (0,h.runFlow)({flowId:c.id,prompt:String(a?.input??""),mode:"ephemeral",flujo:!0,requireApproval:!1});if(b.flowNotFound)return M({error:`Flow not found: ${b.flowNotFound.name}`},!0);if("error"===b.status)return M({error:b.error?.message??"Unknown error during flow execution."},!0);return M(b.outputText??"")}finally{global.__flujo_internal_flow_depth=d}}async function Q(a){let b=String(a?.flow??"").trim();if(!b)return M({error:'Provide "flow": a flow name or id.'},!0);let c=await O(b);if(!c)return M({error:`No flow named or with id "${b}".`},!0);let d=await e.flowService.deleteFlow(c.id);return d.success?M({deleted:!0,flowId:c.id,flowName:c.name}):M({error:d.error??`Failed to delete flow "${c.name}".`},!0)}async function R(a){let b=await a.loadServerConfigs();return Array.isArray(b)?M(await Promise.all(b.map(async b=>{let c="unknown";try{c=(await a.getServerStatus(b.name)).status}catch(a){L.debug(`list_mcp_servers: getServerStatus failed for ${b.name}`,a)}return{name:b.name,transport:b.transport,enabled:!b.disabled,status:c,...b.builtIn?{builtIn:!0}:{}}}))):M({error:b.error??"Failed to load server configs."},!0)}async function S(a,b){let c=String(b?.server??"").trim();if(!c)return M({error:'Provide "server": a FLUJO server name.'},!0);if(c===K._)return M(N().map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})));let{tools:d,error:e}=await a.listServerTools(c);return e?M({error:e},!0):M(d.map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})))}async function T(a,b){let c=String(b?.server??"").trim(),d=String(b?.tool??"").trim();if(!c||!d)return M({error:'Provide "server" and "tool".'},!0);if(c===K._)return M({error:`"${K._}" is this server — call its tools directly instead of through call_mcp_tool.`},!0);let e=b?.args&&"object"==typeof b.args&&!Array.isArray(b.args)?b.args:{},f="number"==typeof b?.timeout?b.timeout:void 0,g=await a.callTool(c,d,e,f);if(!g.success)return M({error:g.error??`Tool call failed on ${c}.`},!0);let h=g.data;return h&&Array.isArray(h.content)?h:M(h??{ok:!0})}async function U(a,b){let c=String(b?.server??"").trim();if(!c)return M({error:'Provide "server": a FLUJO server name.'},!0);if(c===K._)return M({ok:!0,note:`"${K._}" is the built-in server — it is always running.`});let d=await a.forceReconnect(c);if(!d.success)return M({error:d.error??`Failed to restart ${c}.`},!0);let e=await a.getServerStatus(c);return M({restarted:!0,server:c,status:e.status})}async function V(a,b){let c=String(b?.server??"").trim(),d=b?.enabled;if(!c||"boolean"!=typeof d)return M({error:'Provide "server" (string) and "enabled" (boolean).'},!0);if(c===K._)return M({error:`The built-in "${K._}" server cannot be disabled.`},!0);let e=await a.updateServerConfig(c,{disabled:!d});return"error"in e?M({error:e.error},!0):M({server:c,enabled:d})}async function W(){return M((await f.modelService.loadModels()).map(a=>({id:a.id,name:a.name,...a.displayName?{displayName:a.displayName}:{},...a.description?{description:a.description}:{},...a.provider?{provider:a.provider}:{},...a.baseUrl?{baseUrl:a.baseUrl}:{},...a.contextWindow?{contextWindow:a.contextWindow}:{}})))}async function X(){return M((await (0,g.z)().list()).map(({execution:a,status:b,lastRun:c})=>({id:a.id,name:a.name,enabled:a.enabled,flowId:a.flowId,triggerType:a.trigger?.type,armed:b?.armed??!1,...c?{lastRun:{status:c.status,firedAt:c.firedAt,...c.error?{error:c.error}:{}}}:{}})))}async function Y(a){let b=String(a?.id??"").trim();if(!b)return M({error:'Provide "id": a planned execution id (see list_planned_executions).'},!0);let{record:c,error:d}=await (0,g.z)().runNow(b);return d||!c?M({error:d??"Run failed."},!0):M({runId:c.runId,status:c.status,firedAt:c.firedAt,...c.finishedAt?{finishedAt:c.finishedAt}:{},...c.outputText?{outputText:c.outputText}:{},...c.error?{error:c.error}:{}})}async function Z(a,b,c){try{if(G.includes(b))return await J(b,c);switch(b){case"execute_flow":return await P(c);case"delete_flow":return await Q(c);case"list_mcp_servers":return await R(a);case"list_mcp_server_tools":return await S(a,c);case"call_mcp_tool":return await T(a,c);case"restart_mcp_server":return await U(a,c);case"set_mcp_server_enabled":return await V(a,c);case"list_models":return await W();case"list_planned_executions":return await X();case"run_planned_execution":return await Y(c);default:return M({error:`Unknown tool on the built-in FLUJO server: ${b}`},!0)}}catch(a){return L.error("internalCallTool failed",{toolName:b,err:a}),M({error:`Tool failed: ${a instanceof Error?a.message:String(a)}`},!0)}}}};
|
|
35
|
+
${m}`,inputSchema:L()},{name:"search_mcp_marketplace",description:"Search the public MCP server registry for new capabilities (voice, browsing, files, email, vision, …). The registry matches the query against server NAMES only (substring) — use short single terms and try several. Returns name, description, whether FLUJO can install it, and which env vars/keys it would require.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Short search term matched against server names."}},required:["query"]}},{name:"install_mcp_server",description:'Install an MCP server from the public registry (by the exact name returned by search_mcp_marketplace) and connect it — this DOWNLOADS AND RUNS a third-party package on the FLUJO host. Returns the FLUJO server name (reference it in FlowSpec "servers") and the tools it provides, or needsEnv when required keys are missing (supply values via the optional "env" argument, or pick a keyless alternative). First install can take minutes (package download).',inputSchema:{type:"object",properties:{name:{type:"string",description:'Exact registry name from search results, e.g. "ai.keenable/web-search".'},env:{type:"object",description:"Optional env var values for the server (e.g. required API keys).",additionalProperties:{type:"string"}}},required:["name"]}},{name:"execute_flow",description:"Run another FLUJO flow (by name or id) with the given input and return its final output. The run is ephemeral (no chat conversation is created). Use list_flow_building_blocks to see the available flows. Nested runs are limited in depth — a flow cannot recurse through itself indefinitely.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."},input:{type:"string",description:"The message to send to the flow as the user turn."}},required:["flow","input"]}},{name:"delete_flow",description:"PERMANENTLY delete a FLUJO flow (by name or id). This cannot be undone. Verify the target with list_flow_building_blocks first.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."}},required:["flow"]}},{name:"list_mcp_servers",description:"List the MCP servers configured in this FLUJO instance with their transport, enabled/disabled state and live connection status. Config details (env vars, headers, credentials) are never included.",inputSchema:{type:"object",properties:{}}},{name:"list_mcp_server_tools",description:"List the tools of one configured MCP server (name, description, input schema). Use together with call_mcp_tool for servers that are not bound to this flow.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name (see list_mcp_servers)."}},required:["server"]}},{name:"call_mcp_tool",description:"Call a tool on any configured MCP server by server name + tool name. This lets you use servers that are not bound to the current flow. Check the tool's input schema with list_mcp_server_tools first.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."},tool:{type:"string",description:"The tool name on that server."},args:{type:"object",description:"Arguments for the tool (per its input schema)."},timeout:{type:"number",description:"Optional timeout in seconds."}},required:["server","tool"]}},{name:"restart_mcp_server",description:"Force-reconnect a configured MCP server (tears the connection down and rebuilds it). Useful when a server is in an error state after a config or environment change.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."}},required:["server"]}},{name:"set_mcp_server_enabled",description:"Enable or disable a configured MCP server. Disabling disconnects it and prevents any further use; enabling connects it.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."},enabled:{type:"boolean",description:"true to enable + connect, false to disable + disconnect."}},required:["server","enabled"]}},{name:"list_models",description:"List the models configured in this FLUJO instance (id, name, display name, description, provider, base URL, context window). API keys are never included. Reference models by id or name in FlowSpecs.",inputSchema:{type:"object",properties:{}}},{name:"list_planned_executions",description:"List the planned (scheduled/triggered) executions in this FLUJO instance with their trigger type, enabled state, armed status and last run outcome.",inputSchema:{type:"object",properties:{}}},{name:"run_planned_execution",description:"Fire a planned execution immediately (by id, see list_planned_executions) and return the run record with its output.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The planned execution id."}},required:["id"]}},{name:"terminal",description:'Run a shell command on the FLUJO host and return its combined stdout/stderr plus exit code. Runs through a shell, so pipes and chained commands (e.g. "npm install && npm run build") work. Use it to install dependencies, build a cloned MCP server, inspect the filesystem, or run diagnostics. Working directory defaults to the FLUJO data directory (where cloned servers live under mcp-servers/); pass "cwd" to run elsewhere. The command is killed if it exceeds the timeout, and very large output is truncated.',inputSchema:{type:"object",properties:{command:{type:"string",description:'The shell command line to execute, e.g. "npm install && npm run build".'},cwd:{type:"string",description:"Optional working directory. Relative paths resolve against the FLUJO data directory. Defaults to the data directory."},timeout:{type:"number",description:"Optional timeout in seconds (default 60, max 600). The command is killed if it runs longer."}},required:["command"]}}]}async function S(a){let b=await h.flowService.loadFlows();return b.find(b=>b.id===a)??b.find(b=>b.name===a)}async function T(a){let b=String(a?.flow??"").trim();if(!b)return Q({error:'Provide "flow": a flow name or id.'},!0);let c=await S(b);if(!c)return Q({error:`No flow named or with id "${b}". Use list_flow_building_blocks to see the available flows.`},!0);let d=global.__flujo_internal_flow_depth??0;if(d>=4)return Q({error:`execute_flow nesting limit (4) reached — refusing to start "${c.name}" to prevent runaway recursion.`},!0);global.__flujo_internal_flow_depth=d+1;try{let b=await (0,k.runFlow)({flowId:c.id,prompt:String(a?.input??""),mode:"ephemeral",flujo:!0,requireApproval:!1});if(b.flowNotFound)return Q({error:`Flow not found: ${b.flowNotFound.name}`},!0);if("error"===b.status)return Q({error:b.error?.message??"Unknown error during flow execution."},!0);return Q(b.outputText??"")}finally{global.__flujo_internal_flow_depth=d}}async function U(a){let b=String(a?.flow??"").trim();if(!b)return Q({error:'Provide "flow": a flow name or id.'},!0);let c=await S(b);if(!c)return Q({error:`No flow named or with id "${b}".`},!0);let d=await h.flowService.deleteFlow(c.id);return d.success?Q({deleted:!0,flowId:c.id,flowName:c.name}):Q({error:d.error??`Failed to delete flow "${c.name}".`},!0)}async function V(a){let b=await a.loadServerConfigs();return Array.isArray(b)?Q(await Promise.all(b.map(async b=>{let c="unknown";try{c=(await a.getServerStatus(b.name)).status}catch(a){P.debug(`list_mcp_servers: getServerStatus failed for ${b.name}`,a)}return{name:b.name,transport:b.transport,enabled:!b.disabled,status:c,...b.builtIn?{builtIn:!0}:{}}}))):Q({error:b.error??"Failed to load server configs."},!0)}async function W(a,b){let c=String(b?.server??"").trim();if(!c)return Q({error:'Provide "server": a FLUJO server name.'},!0);if(c===O._)return Q(R().map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})));let{tools:d,error:e}=await a.listServerTools(c);return e?Q({error:e},!0):Q(d.map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})))}async function X(a,b){let c=String(b?.server??"").trim(),d=String(b?.tool??"").trim();if(!c||!d)return Q({error:'Provide "server" and "tool".'},!0);if(c===O._)return Q({error:`"${O._}" is this server — call its tools directly instead of through call_mcp_tool.`},!0);let e=b?.args&&"object"==typeof b.args&&!Array.isArray(b.args)?b.args:{},f="number"==typeof b?.timeout?b.timeout:void 0,g=await a.callTool(c,d,e,f);if(!g.success)return Q({error:g.error??`Tool call failed on ${c}.`},!0);let h=g.data;return h&&Array.isArray(h.content)?h:Q(h??{ok:!0})}async function Y(a,b){let c=String(b?.server??"").trim();if(!c)return Q({error:'Provide "server": a FLUJO server name.'},!0);if(c===O._)return Q({ok:!0,note:`"${O._}" is the built-in server — it is always running.`});let d=await a.forceReconnect(c);if(!d.success)return Q({error:d.error??`Failed to restart ${c}.`},!0);let e=await a.getServerStatus(c);return Q({restarted:!0,server:c,status:e.status})}async function Z(a,b){let c=String(b?.server??"").trim(),d=b?.enabled;if(!c||"boolean"!=typeof d)return Q({error:'Provide "server" (string) and "enabled" (boolean).'},!0);if(c===O._)return Q({error:`The built-in "${O._}" server cannot be disabled.`},!0);let e=await a.updateServerConfig(c,{disabled:!d});return"error"in e?Q({error:e.error},!0):Q({server:c,enabled:d})}async function $(){return Q((await i.modelService.loadModels()).map(a=>({id:a.id,name:a.name,...a.displayName?{displayName:a.displayName}:{},...a.description?{description:a.description}:{},...a.provider?{provider:a.provider}:{},...a.baseUrl?{baseUrl:a.baseUrl}:{},...a.contextWindow?{contextWindow:a.contextWindow}:{}})))}async function _(){return Q((await (0,j.z)().list()).map(({execution:a,status:b,lastRun:c})=>({id:a.id,name:a.name,enabled:a.enabled,flowId:a.flowId,triggerType:a.trigger?.type,armed:b?.armed??!1,...c?{lastRun:{status:c.status,firedAt:c.firedAt,...c.error?{error:c.error}:{}}}:{}})))}async function aa(a){let b=String(a?.id??"").trim();if(!b)return Q({error:'Provide "id": a planned execution id (see list_planned_executions).'},!0);let{record:c,error:d}=await (0,j.z)().runNow(b);return d||!c?Q({error:d??"Run failed."},!0):Q({runId:c.runId,status:c.status,firedAt:c.firedAt,...c.finishedAt?{finishedAt:c.finishedAt}:{},...c.outputText?{outputText:c.outputText}:{},...c.error?{error:c.error}:{}})}async function ab(a){let b=String(a?.command??"").trim();if(!b)return Q({error:'Provide "command": a shell command line to run.'},!0);let c=(0,l.ok)(),d="string"==typeof a?.cwd?a.cwd.trim():"",g=d?e().isAbsolute(d)?d:e().join(c,d):c,h=Math.min(1e3*("number"==typeof a?.timeout&&a.timeout>0?a.timeout:60),6e5);return await new Promise(a=>{let c,d="",e=!1,i=!1,j=!1,k=a=>{!e&&(d+=a).length>1e5&&(d=d.slice(0,1e5)+"\n…[output truncated]",e=!0)};try{c=(0,f.spawn)(b,{cwd:g,shell:!0,env:process.env})}catch(b){a(Q({error:`Failed to start command: ${b instanceof Error?b.message:String(b)}`,cwd:g},!0));return}let l=setTimeout(()=>{j=!0;try{c.kill()}catch{}},h),m=b=>{i||(i=!0,clearTimeout(l),a(b))};c.stdout?.on("data",a=>k(a.toString())),c.stderr?.on("data",a=>k(a.toString())),c.on("error",a=>{k(`
|
|
36
|
+
${a.message}`),m(Q({error:`Command failed to start: ${a.message}`,cwd:g,output:d},!0))}),c.on("close",a=>{if(j)return void m(Q({timedOut:!0,cwd:g,exitCode:a,output:`${d}
|
|
37
|
+
[killed after ${h/1e3}s timeout]`},!0));m(Q({exitCode:a,cwd:g,output:d},0!==a))})})}async function ac(a,b,c){try{if(K.includes(b))return await N(b,c);switch(b){case"execute_flow":return await T(c);case"delete_flow":return await U(c);case"list_mcp_servers":return await V(a);case"list_mcp_server_tools":return await W(a,c);case"call_mcp_tool":return await X(a,c);case"restart_mcp_server":return await Y(a,c);case"set_mcp_server_enabled":return await Z(a,c);case"list_models":return await $();case"list_planned_executions":return await _();case"run_planned_execution":return await aa(c);case"terminal":return await ab(c);default:return Q({error:`Unknown tool on the built-in FLUJO server: ${b}`},!0)}}catch(a){return P.error("internalCallTool failed",{toolName:b,err:a}),Q({error:`Tool failed: ${a instanceof Error?a.message:String(a)}`},!0)}}}};
|
|
@@ -151,4 +151,4 @@ ${d}`:f}let cl=["OAuth authentication required","UnauthorizedError","invalid_tok
|
|
|
151
151
|
`)?i.slice(0,-1):i}),h=void 0,i="",j="");if(a.startsWith(":")){e&&e(a.slice(a.startsWith(": ")?2:1));return}let c=a.indexOf(":");if(-1!==c){let b=a.slice(0,c),d=" "===a[c+1]?2:1;l(b,a.slice(c+d),a);return}l(a,"",a)}function l(a,b,e){switch(a){case"event":j=b;break;case"data":i=`${i}${b}
|
|
152
152
|
`;break;case"id":h=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?d(parseInt(b,10)):c(new dI(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:e}));break;default:c(new dI(`Unknown field "${a.length>20?`${a.slice(0,20)}\u2026`:a}"`,{type:"unknown-field",field:a,value:b,line:e}))}}return{feed:function(a){let b=g?a.replace(/^\xEF\xBB\xBF/,""):a,[c,d]=function(a){let b=[],c="",d=0;for(;d<a.length;){let e=a.indexOf("\r",d),f=a.indexOf(`
|
|
153
153
|
`,d),g=-1;if(-1!==e&&-1!==f?g=Math.min(e,f):-1!==e?g=e===a.length-1?-1:e:-1!==f&&(g=f),-1===g){c=a.slice(d);break}{let c=a.slice(d,g);b.push(c),"\r"===a[(d=g+1)-1]&&a[d]===`
|
|
154
|
-
`&&d++}}return[b,c]}(`${f}${b}`);for(let a of c)k(a);f=d,g=!1},reset:function(a={}){f&&a.consume&&k(f),g=!0,h=void 0,i="",j="",f=""}}}class dL extends TransformStream{constructor({onError:a,onRetry:b,onComment:c}={}){let d;super({start(e){d=dK({onEvent:a=>{e.enqueue(a)},onError(b){"terminate"===a?e.error(b):"function"==typeof a&&a(b)},onRetry:b,onComment:c})},transform(a){d.feed(a)}})}}let dM={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class dN extends Error{constructor(a,b){super(`Streamable HTTP error: ${b}`),this.code=a}}class dO{constructor(a,b){this._hasCompletedAuthFlow=!1,this._url=a,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=b?.requestInit,this._authProvider=b?.authProvider,this._fetch=b?.fetch,this._fetchWithInit=cM(b?.fetch,b?.requestInit),this._sessionId=b?.sessionId,this._reconnectionOptions=b?.reconnectionOptions??dM}async _authThenStart(){let a;if(!this._authProvider)throw new dn("No auth provider");try{a=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw this.onerror?.(a),a}if("AUTHORIZED"!==a)throw new dn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let a={};if(this._authProvider){let b=await this._authProvider.tokens();b&&(a.Authorization=`Bearer ${b.access_token}`)}this._sessionId&&(a["mcp-session-id"]=this._sessionId),this._protocolVersion&&(a["mcp-protocol-version"]=this._protocolVersion);let b=cL(this._requestInit?.headers);return new Headers({...a,...b})}async _startOrAuthSse(a){let{resumptionToken:b}=a;try{let c=await this._commonHeaders();c.set("Accept","text/event-stream"),b&&c.set("last-event-id",b);let d=await (this._fetch??fetch)(this._url,{method:"GET",headers:c,signal:this._abortController?.signal});if(!d.ok){if(await d.body?.cancel(),401===d.status&&this._authProvider)return await this._authThenStart();if(405===d.status)return;throw new dN(d.status,`Failed to open SSE stream: ${d.statusText}`)}this._handleSseStream(d.body,a,!0)}catch(a){throw this.onerror?.(a),a}}_getNextReconnectionDelay(a){if(void 0!==this._serverRetryMs)return this._serverRetryMs;let b=this._reconnectionOptions.initialReconnectionDelay;return Math.min(b*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,a),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(a,b=0){let c=this._reconnectionOptions.maxRetries;if(b>=c)return void this.onerror?.(Error(`Maximum reconnection attempts (${c}) exceeded.`));let d=this._getNextReconnectionDelay(b);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(a).catch(c=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${c instanceof Error?c.message:String(c)}`)),this._scheduleReconnection(a,b+1)})},d)}_handleSseStream(a,b,c){let d;if(!a)return;let{onresumptiontoken:e,replayMessageId:f}=b,g=!1,h=!1;(async()=>{try{let b=a.pipeThrough(new TextDecoderStream).pipeThrough(new dL({onRetry:a=>{this._serverRetryMs=a}})).getReader();for(;;){let{value:a,done:c}=await b.read();if(c)break;if((a.id&&(d=a.id,g=!0,e?.(a.id)),a.data)&&(!a.event||"message"===a.event))try{let b=F.parse(JSON.parse(a.data));D(b)&&(h=!0,void 0!==f&&(b.id=f)),this.onmessage?.(b)}catch(a){this.onerror?.(a)}}(c||g)&&!h&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:d,onresumptiontoken:e,replayMessageId:f},0)}catch(a){if(this.onerror?.(Error(`SSE stream disconnected: ${a}`)),(c||g)&&!h&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:d,onresumptiontoken:e,replayMessageId:f},0)}catch(a){this.onerror?.(Error(`Failed to reconnect: ${a instanceof Error?a.message:String(a)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(a){if(!this._authProvider)throw new dn("No auth provider");if("AUTHORIZED"!==await ds(this._authProvider,{serverUrl:this._url,authorizationCode:a,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new dn("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(a,b){try{let{resumptionToken:c,onresumptiontoken:d}=b||{};if(c)return void this._startOrAuthSse({resumptionToken:c,replayMessageId:A(a)?a.id:void 0}).catch(a=>this.onerror?.(a));let e=await this._commonHeaders();e.set("content-type","application/json"),e.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:e,body:JSON.stringify(a),signal:this._abortController?.signal},g=await (this._fetch??fetch)(this._url,f),h=g.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!g.ok){let b=await g.text().catch(()=>null);if(401===g.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new dN(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:b,scope:c}=dv(g);this._resourceMetadataUrl=b,this._scope=c;let d=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==d)throw new dn;return this._hasCompletedAuthFlow=!0,this.send(a)}if(403===g.status&&this._authProvider){let{resourceMetadataUrl:b,scope:c,error:d}=dv(g);if("insufficient_scope"===d){let d=g.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===d)throw new dN(403,"Server returned 403 after trying upscoping");c&&(this._scope=c),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=d??void 0;let e=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch});if("AUTHORIZED"!==e)throw new dn;return this.send(a)}}throw new dN(g.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===g.status){await g.body?.cancel(),W.safeParse(a).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(a=>this.onerror?.(a));return}let i=(Array.isArray(a)?a:[a]).filter(a=>"method"in a&&"id"in a&&void 0!==a.id).length>0,j=g.headers.get("content-type");if(i)if(j?.includes("text/event-stream"))this._handleSseStream(g.body,{onresumptiontoken:d},!1);else if(j?.includes("application/json")){let a=await g.json();for(let b of Array.isArray(a)?a.map(a=>F.parse(a)):[F.parse(a)])this.onmessage?.(b)}else throw await g.body?.cancel(),new dN(-1,`Unexpected content type: ${j}`);else await g.body?.cancel()}catch(a){throw this.onerror?.(a),a}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let a=await this._commonHeaders(),b={...this._requestInit,method:"DELETE",headers:a,signal:this._abortController?.signal},c=await (this._fetch??fetch)(this._url,b);if(await c.body?.cancel(),!c.ok&&405!==c.status)throw new dN(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(a){throw this.onerror?.(a),a}}setProtocolVersion(a){this._protocolVersion=a}get protocolVersion(){return this._protocolVersion}async resumeStream(a,b){await this._startOrAuthSse({resumptionToken:a,onresumptiontoken:b?.onresumptiontoken})}}class dP extends Event{constructor(a,b){var c,d;super(a),this.code=null!=(c=null==b?void 0:b.code)?c:void 0,this.message=null!=(d=null==b?void 0:b.message)?d:void 0}[Symbol.for("nodejs.util.inspect.custom")](a,b,c){return c(dQ(this),b)}[Symbol.for("Deno.customInspect")](a,b){return a(dQ(this),b)}}function dQ(a){return{type:a.type,message:a.message,code:a.code,defaultPrevented:a.defaultPrevented,cancelable:a.cancelable,timeStamp:a.timeStamp}}var dR,dS,dT,dU,dV,dW,dX,dY,dZ,d$,d_,d0,d1,d2,d3,d4,d5,d6,d7,d8,d9,ea,eb,ec,ed,ee=a=>{throw TypeError(a)},ef=(a,b,c)=>b.has(a)||ee("Cannot "+c),eg=(a,b,c)=>(ef(a,b,"read from private field"),c?c.call(a):b.get(a)),eh=(a,b,c)=>b.has(a)?ee("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c),ei=(a,b,c,d)=>(ef(a,b,"write to private field"),b.set(a,c),c),ej=(a,b,c)=>(ef(a,b,"access private method"),c);class ek extends EventTarget{constructor(a,b){var c,d;super(),eh(this,d4),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eh(this,dT),eh(this,dU),eh(this,dV),eh(this,dW),eh(this,dX),eh(this,dY),eh(this,dZ),eh(this,d$,null),eh(this,d_),eh(this,d0),eh(this,d1,null),eh(this,d2,null),eh(this,d3,null),eh(this,d6,async a=>{var b;eg(this,d0).reset();let{body:c,redirected:d,status:e,headers:f}=a;if(204===e){ej(this,d4,eb).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(d?ei(this,dV,new URL(a.url)):ei(this,dV,void 0),200!==e)return void ej(this,d4,eb).call(this,`Non-200 status code (${e})`,e);if(!(f.get("content-type")||"").startsWith("text/event-stream"))return void ej(this,d4,eb).call(this,'Invalid content type, expected "text/event-stream"',e);if(eg(this,dT)===this.CLOSED)return;ei(this,dT,this.OPEN);let g=new Event("open");if(null==(b=eg(this,d3))||b.call(this,g),this.dispatchEvent(g),"object"!=typeof c||!c||!("getReader"in c)){ej(this,d4,eb).call(this,"Invalid response body, expected a web ReadableStream",e),this.close();return}let h=new TextDecoder,i=c.getReader(),j=!0;do{let{done:a,value:b}=await i.read();b&&eg(this,d0).feed(h.decode(b,{stream:!a})),a&&(j=!1,eg(this,d0).reset(),ej(this,d4,ec).call(this))}while(j)}),eh(this,d7,a=>{ei(this,d_,void 0),"AbortError"!==a.name&&"aborted"!==a.type&&ej(this,d4,ec).call(this,function a(b){return b instanceof Error?"errors"in b&&Array.isArray(b.errors)?b.errors.map(a).join(", "):"cause"in b&&b.cause instanceof Error?`${b}: ${a(b.cause)}`:b.message:`${b}`}(a))}),eh(this,d9,a=>{"string"==typeof a.id&&ei(this,d$,a.id);let b=new MessageEvent(a.event||"message",{data:a.data,origin:eg(this,dV)?eg(this,dV).origin:eg(this,dU).origin,lastEventId:a.id||""});eg(this,d2)&&(!a.event||"message"===a.event)&&eg(this,d2).call(this,b),this.dispatchEvent(b)}),eh(this,ea,a=>{ei(this,dY,a)}),eh(this,ed,()=>{ei(this,dZ,void 0),eg(this,dT)===this.CONNECTING&&ej(this,d4,d5).call(this)});try{if(a instanceof URL)ei(this,dU,a);else if("string"==typeof a)ei(this,dU,new URL(a,function(){let a="document"in globalThis?globalThis.document:void 0;return a&&"object"==typeof a&&"baseURI"in a&&"string"==typeof a.baseURI?a.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(a){let b=globalThis.DOMException;return"function"==typeof b?new b(a,"SyntaxError"):SyntaxError(a)}("An invalid or illegal string was specified")}ei(this,d0,dK({onEvent:eg(this,d9),onRetry:eg(this,ea)})),ei(this,dT,this.CONNECTING),ei(this,dY,3e3),ei(this,dX,null!=(c=null==b?void 0:b.fetch)?c:globalThis.fetch),ei(this,dW,null!=(d=null==b?void 0:b.withCredentials)&&d),ej(this,d4,d5).call(this)}get readyState(){return eg(this,dT)}get url(){return eg(this,dU).href}get withCredentials(){return eg(this,dW)}get onerror(){return eg(this,d1)}set onerror(a){ei(this,d1,a)}get onmessage(){return eg(this,d2)}set onmessage(a){ei(this,d2,a)}get onopen(){return eg(this,d3)}set onopen(a){ei(this,d3,a)}addEventListener(a,b,c){super.addEventListener(a,b,c)}removeEventListener(a,b,c){super.removeEventListener(a,b,c)}close(){eg(this,dZ)&&clearTimeout(eg(this,dZ)),eg(this,dT)!==this.CLOSED&&(eg(this,d_)&&eg(this,d_).abort(),ei(this,dT,this.CLOSED),ei(this,d_,void 0))}}dT=new WeakMap,dU=new WeakMap,dV=new WeakMap,dW=new WeakMap,dX=new WeakMap,dY=new WeakMap,dZ=new WeakMap,d$=new WeakMap,d_=new WeakMap,d0=new WeakMap,d1=new WeakMap,d2=new WeakMap,d3=new WeakMap,d4=new WeakSet,d5=function(){ei(this,dT,this.CONNECTING),ei(this,d_,new AbortController),eg(this,dX)(eg(this,dU),ej(this,d4,d8).call(this)).then(eg(this,d6)).catch(eg(this,d7))},d6=new WeakMap,d7=new WeakMap,d8=function(){var a;let b={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...eg(this,d$)?{"Last-Event-ID":eg(this,d$)}:void 0},cache:"no-store",signal:null==(a=eg(this,d_))?void 0:a.signal};return"window"in globalThis&&(b.credentials=this.withCredentials?"include":"same-origin"),b},d9=new WeakMap,ea=new WeakMap,eb=function(a,b){var c;eg(this,dT)!==this.CLOSED&&ei(this,dT,this.CLOSED);let d=new dP("error",{code:b,message:a});null==(c=eg(this,d1))||c.call(this,d),this.dispatchEvent(d)},ec=function(a,b){var c;if(eg(this,dT)===this.CLOSED)return;ei(this,dT,this.CONNECTING);let d=new dP("error",{code:b,message:a});null==(c=eg(this,d1))||c.call(this,d),this.dispatchEvent(d),ei(this,dZ,setTimeout(eg(this,ed),eg(this,dY)))},ed=new WeakMap,ek.CONNECTING=0,ek.OPEN=1,ek.CLOSED=2;class el extends Error{constructor(a,b,c){super(`SSE error: ${b}`),this.code=a,this.event=c}}class em{constructor(a,b){this._url=a,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=b?.eventSourceInit,this._requestInit=b?.requestInit,this._authProvider=b?.authProvider,this._fetch=b?.fetch,this._fetchWithInit=cM(b?.fetch,b?.requestInit)}async _authThenStart(){let a;if(!this._authProvider)throw new dn("No auth provider");try{a=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw this.onerror?.(a),a}if("AUTHORIZED"!==a)throw new dn;return await this._startOrAuth()}async _commonHeaders(){let a={};if(this._authProvider){let b=await this._authProvider.tokens();b&&(a.Authorization=`Bearer ${b.access_token}`)}this._protocolVersion&&(a["mcp-protocol-version"]=this._protocolVersion);let b=cL(this._requestInit?.headers);return new Headers({...a,...b})}_startOrAuth(){let a=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((b,c)=>{this._eventSource=new ek(this._url.href,{...this._eventSourceInit,fetch:async(b,c)=>{let d=await this._commonHeaders();d.set("Accept","text/event-stream");let e=await a(b,{...c,headers:d});if(401===e.status&&e.headers.has("www-authenticate")){let{resourceMetadataUrl:a,scope:b}=dv(e);this._resourceMetadataUrl=a,this._scope=b}return e}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{if(401===a.code&&this._authProvider)return void this._authThenStart().then(b,c);let d=new el(a.code,a.message,a);c(d),this.onerror?.(d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{try{if(this._endpoint=new URL(a.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){c(a),this.onerror?.(a),this.close();return}b()}),this._eventSource.onmessage=a=>{let b;try{b=F.parse(JSON.parse(a.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(b)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(a){if(!this._authProvider)throw new dn("No auth provider");if("AUTHORIZED"!==await ds(this._authProvider,{serverUrl:this._url,authorizationCode:a,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new dn("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(a){if(!this._endpoint)throw Error("Not connected");try{let b=await this._commonHeaders();b.set("content-type","application/json");let c={...this._requestInit,method:"POST",headers:b,body:JSON.stringify(a),signal:this._abortController?.signal},d=await (this._fetch??fetch)(this._endpoint,c);if(!d.ok){let b=await d.text().catch(()=>null);if(401===d.status&&this._authProvider){let{resourceMetadataUrl:b,scope:c}=dv(d);this._resourceMetadataUrl=b,this._scope=c;let e=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==e)throw new dn;return this.send(a)}throw Error(`Error POSTing to endpoint (HTTP ${d.status}): ${b}`)}await d.body?.cancel()}catch(a){throw this.onerror?.(a),a}}setProtocolVersion(a){this._protocolVersion=a}}let en=(0,bY.h)("backend/services/mcp/oauth");class eo{constructor(a,b){this.config=a,this._redirectUrl=b,this._clientMetadata={redirect_uris:[b],client_name:`FLUJO MCP Client - ${a.name}`,client_uri:"https://github.com/mario-andreschak/FLUJO",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post",scope:a.oauthScopes?.join(" ")||"read"},en.info(`Created OAuth client provider for ${a.name}`),en.verbose("OAuth client metadata",JSON.stringify(this._clientMetadata))}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return encodeURIComponent(JSON.stringify({serverName:this.config.name}))}async clientInformation(){if(this.config.oauthClientInformation)return en.debug(`Returning stored client information for ${this.config.name}`),this.config.oauthClientInformation;if(this.config.oauthClientId){let a=this.config.oauthClientSecret?await (0,b_.G)(this.config.oauthClientSecret)??void 0:void 0;return en.debug(`Created client information from config for ${this.config.name}`),{client_id:this.config.oauthClientId,client_secret:a}}en.debug(`No client information available for ${this.config.name}`)}async persist(){let a=await (0,b$.loadServerConfigs)();if(!Array.isArray(a))return void en.warn(`persist: failed to load server configs for ${this.config.name}, cannot persist OAuth state`);let b=new Map(a.map(a=>[a.name,a]));b.set(this.config.name,this.config);let c=await (0,b$.q)(b);c.success||en.warn(`persist: failed to save OAuth state for ${this.config.name}: ${c.error}`)}async invalidateCredentials(a){en.info(`Invalidating OAuth credentials for ${this.config.name} (scope: ${a})`),("all"===a||"tokens"===a)&&(this.config.oauthTokens=void 0),("all"===a||"client"===a)&&(this.config.oauthClientInformation=void 0,this.config.oauthClientMetadata=void 0),("all"===a||"verifier"===a)&&(this.config.oauthCodeVerifier=void 0),await this.persist()}async saveClientInformation(a){en.info(`Saving client information for ${this.config.name}`),en.verbose("Client information to save",JSON.stringify(a)),this.config.oauthClientInformation={client_id:a.client_id,client_secret:a.client_secret,client_id_issued_at:a.client_id_issued_at,client_secret_expires_at:a.client_secret_expires_at},this.config.oauthClientMetadata={redirect_uris:a.redirect_uris,client_name:a.client_name,client_uri:a.client_uri,grant_types:a.grant_types,response_types:a.response_types,token_endpoint_auth_method:a.token_endpoint_auth_method,scope:a.scope,contacts:a.contacts,tos_uri:a.tos_uri,policy_uri:a.policy_uri,jwks_uri:a.jwks_uri,jwks:a.jwks,software_id:a.software_id,software_version:a.software_version},await this.persist(),en.info(`Client information saved for ${this.config.name}`)}async tokens(){if(this.config.oauthTokens){if(en.debug(`Returning stored tokens for ${this.config.name}`),this.config.oauthTokens.expires_in&&this.config.oauthTokens.issued_at){let a=this.config.oauthTokens.issued_at,b=this.config.oauthTokens.expires_in,c=Math.floor(Date.now()/1e3),d=a+b;c>=d?en.info(`Access token for ${this.config.name} has expired (issued: ${a}, expires: ${d}, current: ${c}); SDK will refresh via refresh_token`):en.debug(`Tokens for ${this.config.name} are valid (expires in ${d-c} seconds)`)}return this.config.oauthTokens}en.debug(`No tokens available for ${this.config.name}`)}async saveTokens(a){en.info(`Saving OAuth tokens for ${this.config.name}`),en.verbose("Tokens to save",JSON.stringify({...a,access_token:a.access_token?"[REDACTED]":void 0,refresh_token:a.refresh_token?"[REDACTED]":void 0}));let b={...a,issued_at:Math.floor(Date.now()/1e3)};this.config.oauthTokens=b,await this.persist(),en.info(`OAuth tokens saved for ${this.config.name}`)}async redirectToAuthorization(a){en.info(`Authorization required for ${this.config.name}`),en.info(`Authorization URL: ${a.toString()}`),this.config.authorizationUrl=a.toString();let b=Error(`OAuth authentication required for ${this.config.name}. Please complete the OAuth flow.`);throw b.name="OAuthAuthenticationRequired",b}async saveCodeVerifier(a){en.debug(`Saving code verifier for ${this.config.name}`),this.config.oauthCodeVerifier=a,await this.persist(),en.debug(`Code verifier saved for ${this.config.name}`)}async codeVerifier(){if(!this.config.oauthCodeVerifier){let a=`No code verifier found for ${this.config.name}`;throw en.error(a),Error(a)}return en.debug(`Returning code verifier for ${this.config.name}`),this.config.oauthCodeVerifier}}let ep=new Set(["node","npm","npx"]);var eq=c(79551);let er=(0,bY.h)("backend/services/mcp/roots");function es(){return global.__mcp_node_roots}function et(a){let b=[];for(let c of es().values())if(c.serverName===a)for(let a of c.roots)b.includes(a)||b.push(a);return b}async function eu(a){let b=function(a){let b=a.trim();if(!b)return null;if(b.startsWith("file://"))return b;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(b))return er.warn(`Ignoring non-file root URI: ${b}`),null;try{return(0,eq.pathToFileURL)(b).href}catch(a){return er.warn(`Could not convert root "${b}" to a file URI:`,a),null}}(await (0,b_.c)(a));return b?{uri:b,name:function(a){try{let b=new URL(a).pathname.replace(/\/+$/,"").split("/").pop();return b?decodeURIComponent(b):void 0}catch{return}}(b)}:null}async function ev(a){let b=a.roots,c=[...Array.isArray(b)?b:[],...et(a.name)],d=[],e=new Set;for(let a of c){if("string"!=typeof a||!a.trim())continue;let b=await eu(a);b&&!e.has(b.uri)&&(e.add(b.uri),d.push(b))}if(0===d.length&&"string"==typeof a.rootPath&&a.rootPath.trim()){let b=await eu(a.rootPath);if(b)return[b]}return d}async function ew(a){try{let{loadServerConfigs:b}=await Promise.resolve().then(c.bind(c,6544)),d=await b();if(Array.isArray(d)){let b=d.find(b=>b.name===a.name);if(b)return b}}catch(b){er.warn(`Could not re-load config for ${a.name}, using connect-time config:`,b)}return a}void 0===global.__mcp_node_roots&&(global.__mcp_node_roots=new Map);var ex=c(12763),ey=c(31351);let ez=(0,bY.h)("backend/services/mcp/sampling");function eA(a){return a.sampling}function eB(a){let b=eA(a);return b?.enabled?JSON.stringify({m:b.modelId,t:b.maxTokens,r:b.maxCallsPerMinute}):""}let eC=(0,bY.h)("backend/services/mcp/connection");async function eD(a){if("streamable"!==a.transport&&"sse"!==a.transport||!a.headers||"object"!=typeof a.headers)return a;let b={};for(let[c,d]of Object.entries(a.headers)){if(!c)continue;let{value:a}=cq(d,c);if(!a)continue;let e=await (0,b_.G)(a);e&&(b[c]=e)}return{...a,headers:b}}function eE(a){let b={};for(let[c,d]of Object.entries(a)){if(!c)continue;let{value:a}=cq(d,c);"string"==typeof a&&a.length>0&&(b[c]=a)}return b}function eF(a){let b={};if(a)for(let[c,d]of Object.entries(a))d&&"object"==typeof d&&"value"in d?b[c]=d.value:b[c]=d;return b}function eG(a){return JSON.stringify({command:a.command,args:a.args??[],env:eF(a.env),cwd:String(a.cwd??""),rootPath:a.rootPath??""})}function eH(a){return JSON.stringify({transport:a.transport,url:a.serverUrl??"",headers:a.headers??{},requestInit:a.requestInit??{},eventSourceInit:a.eventSourceInit??{},reconnectionOptions:a.reconnectionOptions??{},sessionId:a.sessionId??"",oauthClientId:a.oauthClientId??"",oauthClientInformation:a.oauthClientInformation??{},oauthClientSecret:a.oauthClientSecret??"",oauthTokens:a.oauthTokens??{}})}function eI(a){eC.debug("Entering createNewClient method");let b=function(a){let b=eA(a);return!!(b?.enabled&&b.modelId)}(a),c=new cJ({name:`flujo-${a.name}-client`,version:"3.15.0"},{capabilities:{experimental:{},roots:{listChanged:!0},...b?{sampling:{}}:{}}});return c.setRequestHandler(bL,async()=>{let b=await ev(await ew(a));return er.debug(`roots/list for ${a.name}: ${b.length} root(s)`),{roots:b}}),b&&function(a,b){let c=[];a.setRequestHandler(bj,async a=>{let d=eA(b);if(!d?.enabled||!d.modelId)throw new bO(dR.InvalidRequest,"Sampling is not enabled for this server");let e=d.maxCallsPerMinute??10,f=Date.now(),g=f-6e4;for(;c.length>0&&c[0]<g;)c.shift();if(c.length>=e)throw ez.warn(`Sampling rate limit (${e}/min) hit for ${b.name}`),new bO(dR.InvalidRequest,`Sampling rate limit of ${e}/min exceeded`);c.push(f);let h=await ex.modelService.getModel(d.modelId);if(!h)throw new bO(dR.InternalError,`Sampling model not found: ${d.modelId}`);let i=await ex.modelService.resolveAndDecryptApiKey(h.ApiKey);if(!i)throw new bO(dR.InternalError,"Could not resolve the sampling model API key");let j=a.params,k=function(a){let b=[];for(let c of(a.systemPrompt&&b.push({role:"system",content:a.systemPrompt}),a.messages||[])){let a=c.content,d=a?.type==="text"&&"string"==typeof a.text?a.text:`[unsupported ${a?.type||"non-text"} content omitted]`;b.push({role:c.role,content:d})}return b}(j),l="number"==typeof j.temperature?j.temperature:.7;ez.info(`Sampling for ${b.name} via model ${h.name} (${k.length} messages)`);let m=(0,ey.getCompletionAdapter)(h),{completion:n}=await m.createCompletion({model:h,apiKey:i,messages:k,temperature:l}),o=n.choices?.[0]?.message?.content;return{role:"assistant",content:{type:"text",text:"string"==typeof o?o:""},model:h.name,stopReason:"endTurn"}})}(c,a),c.__flujoCapKey=eB(a),c}function eJ(a){if(eC.debug("Entering createTransport method"),"streamable"===a.transport){eC.info(`Creating streamable http transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.reconnectionOptions&&"object"==typeof a.reconnectionOptions&&(b.reconnectionOptions=a.reconnectionOptions),"string"==typeof a.sessionId&&a.sessionId.length>0&&(b.sessionId=a.sessionId),a.headers&&"object"==typeof a.headers){let c=eE(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},eC.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}a.oauthClientId||a.oauthClientInformation?(eC.info(`Setting up OAuth authentication for ${a.name}`),b.authProvider=function(a,b="http://localhost:4200/api/oauth/callback"){return new eo(a,b)}(a),a.oauthTokens?.access_token?(eC.debug(`OAuth provider configured for ${a.name} with existing tokens`),eC.debug(`Token expires in: ${a.oauthTokens.expires_in} seconds`)):eC.debug(`OAuth provider configured for ${a.name} - will initiate OAuth flow if needed`)):eC.debug(`No OAuth configuration found for ${a.name}`);let c=new dO(new URL(a.serverUrl),b);return c.__flujoHttpKey=eH(a),c}if("sse"===a.transport){eC.info(`Creating legacy sse transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.eventSourceInit&&"object"==typeof a.eventSourceInit&&(b.eventSourceInit=a.eventSourceInit),a.headers&&"object"==typeof a.headers){let c=eE(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},eC.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}let c=new em(new URL(a.serverUrl),b);return c.__flujoHttpKey=eH(a),c}return"websocket"===a.transport?(eC.info(`Creating WebSocket transport for server ${a.name} with URL ${a.websocketUrl}`),new cK(new URL(a.websocketUrl))):function(a){if(eC.debug("Entering createStdioTransport method"),"stdio"!==a.transport)throw Error("Cannot create stdio transport for non-stdio config");let b=a.command,c=a.args?[...a.args]:[],d=`${cd.VL}/${a.name}`;eC.info(`Creating stdio transport for server ${a.name}`),eC.debug(`Original command: ${b}`),eC.debug(`Original args: ${JSON.stringify(c)}`),eC.debug(`Server directory: ${d}`);let e=!bW.isAbsolute(b)&&(b.includes("/")||b.includes("\\")),f=!b.includes("/")&&!b.includes("\\");if(eC.debug(`Is relative path: ${e}`),eC.debug(`Is just filename: ${f}`),"win32"===cc.platform()&&b.toLowerCase().endsWith(".bat"))if(eC.debug(`Detected .bat file on Windows: ${b}`),f){let a=bW.join((0,bZ.ok)(),d,b);eC.debug(`Checking if file exists at: ${a}`);let e=cb.existsSync(a);eC.debug(`File exists: ${e}`),e?(eC.debug(`Using full path to .bat file: ${a}`),c=["/c",a,...c]):(eC.warn(`WARNING: .bat file not found at ${a}`),c=["/c",b,...c]),b="cmd.exe"}else eC.debug(`Using cmd.exe with path as provided: ${b}`),c=["/c",b,...c],b="cmd.exe";let g=function(a,b){if(!a||!(!a.includes("/")&&!a.includes("\\")))return a;let c=a.toLowerCase();if(!ep.has(c))return a;if("node"===c)return b.execPath||a;if(!b.execPath)return a;let d=b.dirname(b.execPath);for(let a of"win32"===b.platform?[`${c}.cmd`,`${c}.exe`,c]:[c]){let c=b.joinPath(d,a);if(b.fileExists(c))return c}return a}(b,{execPath:process.execPath,platform:cc.platform(),dirname:bW.dirname,joinPath:bW.join,fileExists:cb.existsSync});g!==b&&(eC.debug(`Resolved Node toolchain command "${b}" to absolute path: ${g}`),b=g),eC.debug(`Final command: ${b}`),eC.debug(`Final args: ${JSON.stringify(c)}`);let h=function({command:a,args:b=[],rootPath:c,cwd:d,serverName:e,defaultCwd:f}){let g=c||d||f;return e&&cu(a,b)&&(g.split(/[\\/]/).filter(Boolean).pop()||"")===e&&function(a){let b=a.match(/^(.*[\\/])[^\\/]+[\\/]*$/);return b?b[1].replace(/[\\/]+$/,""):""}(g)||g}({command:a.command,args:a.args,rootPath:a.rootPath,cwd:a.cwd,serverName:a.name,defaultCwd:`${cd.VL}/${a.name}`}),i=bW.isAbsolute(h)?h:bW.join((0,bZ.ok)(),h);eC.debug(`cwd: ${i}`),eC.debug(`env: ${JSON.stringify(a.env)}`),eC.info(`Creating StdioClientTransport for ${a.name} with stderr: 'pipe'`);let j=eF(a.env);eC.verbose("Transformed environment variables",JSON.stringify(j));let k=new bS({command:b,args:c,env:j,cwd:i,stderr:"pipe"});return k.__flujoStdioKey=eG(a),k.stderr?eC.info(`Stderr stream is available for ${a.name}`):eC.warn(`Stderr stream is NOT available for ${a.name}`),k}(a)}function eK(a,b){return null!==a.exitCode||null!==a.signalCode?Promise.resolve(!0):new Promise(c=>{let d=()=>{clearTimeout(e),c(!0)},e=setTimeout(()=>{a.removeListener("exit",d),c(!1)},b);e.unref?.(),a.once("exit",d)})}async function eL(a,b,c,d){eC.debug("Entering safelyCloseClient method");let e=d?.gracePeriodMs??15e3,f=d?.killEscalationMs??5e3;try{if(a.transport instanceof bS){let c=a.transport._process;if(c&&null===c.exitCode&&null===c.signalCode){try{c.stdin&&!c.stdin.destroyed&&(c.stdin.end(),eC.debug(`Closed stdin for graceful shutdown for ${b}`))}catch(a){eC.warn(`Error closing stdin for ${b}:`,a)}let a=await eK(c,e);if(!a){eC.warn(`Process did not exit within ${e}ms after stdin close, sending SIGTERM for ${b}`);try{c.kill("SIGTERM")}catch(a){eC.error(`Error sending SIGTERM for ${b}:`,a)}a=await eK(c,f)}if(a)eC.info(`Process exited gracefully for ${b}`);else{eC.warn(`Process did not respond to SIGTERM, sending SIGKILL for ${b}`);try{c.kill("SIGKILL")}catch(a){eC.error(`Error sending SIGKILL for ${b}:`,a)}}}}await a.close(),eC.info(`Client closed successfully for ${b}`)}catch(a){eC.warn(`Error closing client for ${b}:`,a)}}var eM=c(92018);void 0===global.__mcp_clients&&(global.__mcp_clients=new Map),void 0===global.__mcp_connecting&&(global.__mcp_connecting=new Set),void 0===global.__mcp_starting_up&&(global.__mcp_starting_up=!0),void 0===global.__mcp_active_transports&&(global.__mcp_active_transports=new Map);let eN=(0,bY.h)("backend/services/mcp/index");class eO{get clients(){return global.__mcp_clients}get connectingServers(){return global.__mcp_connecting}get activeTransports(){return global.__mcp_active_transports}static{this.MAX_STDERR_LOG_ENTRIES=200}appendStderrLog(a,b){let c=this.stderrLogs.get(a)||[];c.push(b),c.length>eO.MAX_STDERR_LOG_ENTRIES&&c.splice(0,c.length-eO.MAX_STDERR_LOG_ENTRIES),this.stderrLogs.set(a,c)}deregisterClient(a){this.clients.delete(a),this.activeTransports.delete(a)}clearRetryTimer(a){let b=this.connectionRetryTimers.get(a);b&&(clearTimeout(b),this.connectionRetryTimers.delete(a),eN.debug(`Cleared retry timer for server ${a}`))}scheduleConnectionRetry(a,b){this.clearRetryTimer(a);let c=this.connectionRetryAttempts.get(a)||0;if(c>=5){eN.warn(`Maximum retry attempts (5) reached for server ${a}, stopping retries`),this.connectionRetryAttempts.delete(a);return}let d=Math.min(5e3*Math.pow(2,c),3e5);eN.info(`Scheduling connection retry for server ${a} in ${d}ms (attempt ${c+1}/5)`);let e=setTimeout(async()=>{eN.info(`Attempting to reconnect server ${a} (attempt ${c+1}/5)`);let b=await this.getServerConfig(a);if(!b){eN.info(`Server ${a} configuration not found, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}if(b.disabled){eN.info(`Server ${a} is now disabled, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}let d=this.getClient(a);if(d)try{await d.ping({timeout:5e3}),eN.info(`Server ${a} is already connected and responsive, cancelling retry`),this.connectionRetryAttempts.delete(a);return}catch(b){eN.warn(`Server ${a} has a registered client but ping failed (${b instanceof Error?b.message:String(b)}); reconnecting from scratch`)}this.connectionRetryAttempts.set(a,c+1);try{let e=d?await this.forceReconnect(a):await this.connectServer(b);if(e.success)eN.info(`Successfully reconnected server ${a} after ${c+1} attempts`),this.connectionRetryAttempts.delete(a);else{if(eN.warn(`Failed to reconnect server ${a}: ${e.error}`),e.requiresAuthentication){eN.info(`Server ${a} requires authentication, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}this.scheduleConnectionRetry(a,b)}}catch(c){eN.error(`Error during retry connection for server ${a}:`,c),this.scheduleConnectionRetry(a,b)}},d);this.connectionRetryTimers.set(a,e)}isStartingUp(){return!0===global.__mcp_starting_up}setStartingUp(a){global.__mcp_starting_up=a,eN.info(`Backend startup state set to: ${a?"starting":"complete"}`)}getClient(a){let b=this.clients.get(a);if(b&&cf(b)){eN.warn(`getClient: client for ${a} has a closed/aborted connection — evicting it`),this.clients.delete(a);return}return eN.debug(`getClient: Looking for client: ${a}`,b?"Found":"Not found"),b}async loadServerConfigs(){eN.debug("loadServerConfigs: Entering method");try{let a=await (0,b$.loadServerConfigs)();if(!Array.isArray(a))return eN.warn("loadServerConfigs: Received non-array response",a),a;return a.some(a=>a.name===eM._)?eN.warn(`loadServerConfigs: A stored server is named "${eM._}" — it shadows FLUJO's built-in server`):a.push((0,eM.z)()),eN.debug(`loadServerConfigs: Loaded ${a.length} server configs`),a}catch(a){return eN.warn("loadServerConfigs: Failed to load server configs:",a),{success:!1,error:`Failed to load server configs: ${a instanceof Error?a.message:"Unknown error"}`}}}async getServerConfig(a){eN.debug(`getServerConfig: Looking up config for server ${a}`);let b=await this.loadServerConfigs();if(!Array.isArray(b))return eN.warn(`getServerConfig: Failed to load configs for ${a}:`,b.error),null;let c=b.find(b=>b.name===a);return c||(eN.warn(`getServerConfig: Server ${a} not found in configs`),null)}async isServerDisabled(a){let b=await this.getServerConfig(a);return b?.disabled===!0}async isInternalServer(a){if(a!==eM._)return!1;let b=await (0,b$.loadServerConfigs)();return!Array.isArray(b)||!b.some(a=>a.name===eM._)}async connectServer(a){let b="string"==typeof a?a:a.name;if(b===eM._&&("string"!=typeof a?!0===a.builtIn:await this.isInternalServer(b)))return this.connectingServers.delete(b),{success:!0};let c=this.inFlightConnects.get(b);if(c)return eN.debug(`connectServer: reusing in-flight connection attempt for ${b}`),c;let d=this.connectServerInternal(a).finally(()=>{this.inFlightConnects.delete(b)});return this.inFlightConnects.set(b,d),d}async connectServerInternal(a){let b;if("string"==typeof a){eN.info(`connectServer: Looking up config for server ${a}`);let c=await this.getServerConfig(a);if(!c)return eN.warn(`connectServer: Server ${a} not found in configs`),{success:!1,error:`Server configuration for "${a}" not found. The server may have been deleted or not properly configured.`};b=c}else b=a;if((("string"==typeof a?b:await this.getServerConfig(b.name))??b).disabled)return eN.info(`connectServer: Server ${b.name} is disabled — refusing to create a client/transport`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),{success:!1,error:`Server '${b.name}' is disabled. Enable it on the MCP page to use it.`};let c=(0,bT.A)();eN.info(`connectServer: Starting connection for server ${b.name} [RequestID: ${c}]`),this.connectingServers.add(b.name);try{this.stderrLogs.set(b.name,[]),b=await eD(b);let a=this.clients.get(b.name);if(a){let{needsNewClient:c,reason:d}=function(a,b){if(eC.debug("Entering shouldRecreateClient method"),cf(a))return{needsNewClient:!0,reason:"Existing connection is closed"};if((a.__flujoCapKey??"")!==eB(b))return{needsNewClient:!0,reason:"Client capabilities (sampling) changed"};if("websocket"===b.transport){if(!(a.transport instanceof cK))return{needsNewClient:!0,reason:"Transport type changed to websocket"}}else if("streamable"===b.transport){if(!(a.transport instanceof dO))return{needsNewClient:!0,reason:"Transport type changed to streamable"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"Streamable server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing streamable transport has no config key"};if(e!==eH(b))return{needsNewClient:!0,reason:"Streamable auth/connection parameters changed"}}else if("sse"===b.transport){if(!(a.transport instanceof em))return{needsNewClient:!0,reason:"Transport type changed to sse"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"SSE server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing sse transport has no config key"};if(e!==eH(b))return{needsNewClient:!0,reason:"SSE auth/connection parameters changed"}}else{if(!(a.transport instanceof bS))return{needsNewClient:!0,reason:"Transport type changed to stdio"};if("stdio"!==b.transport)return{needsNewClient:!0,reason:"Transport type changed from stdio"};let c=a.transport.__flujoStdioKey;if(!c)return{needsNewClient:!0,reason:"Existing stdio transport has no config key"};if(c!==eG(b))return{needsNewClient:!0,reason:"Connection parameters changed"}}return{needsNewClient:!1}}(a,b);if(!c)return eN.info(`connectServer: Server ${b.name} is already connected`),this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),{success:!0};eN.info(`connectServer: Existing client for ${b.name} is stale (${d}), recreating`),this.deregisterClient(b.name);try{await eL(a,b.name,b)}catch(a){eN.debug(`connectServer: error closing stale client for ${b.name}: ${a instanceof Error?a.message:String(a)}`)}a=void 0}a=eI(b);let c=eJ(b);if(c instanceof bS&&c.stderr){let a=b.name;c.stderr.on("data",b=>{let c=b.toString();eN.warn(`stderr: [${a}]: ${c}`),this.appendStderrLog(a,c)})}return c.onclose=()=>{if(this.activeTransports.get(b.name)!==c)return void eN.debug(`connectServer: ignoring close event from a stale/deregistered transport for ${b.name}`);eN.warn(`connectServer: Connection closed for server ${b.name}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{if(!a||a.disabled)return void eN.info(`Server ${b.name} is now disabled, skipping reconnection logic`);eN.info(`Connection closed for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a)}).catch(a=>{eN.warn(`Error checking server config for ${b.name} during onclose:`,a)})},c.onerror=a=>{if(function(a){let b=a instanceof Error?a.message:String(a);return b.includes("SSE stream disconnected")||b.includes("Failed to reconnect SSE stream")||b.includes("Maximum reconnection attempts")||/\bterminated\b/i.test(b)}(a))return void eN.debug(`connectServer: transient SSE stream disconnect for ${b.name} (self-healing, ignored): ${a instanceof Error?a.message:String(a)}`);if(this.activeTransports.get(b.name)!==c)return void eN.debug(`connectServer: ignoring error event from a stale/deregistered transport for ${b.name}`);if(eN.error(`connectServer: Transport error for server ${b.name}:`),a instanceof Error){eN.error(`Error name: ${a.name}`),eN.error(`Error message: ${a.message}`),eN.error(`Error stack: ${a.stack}`);let b=a.code;void 0!==b&&eN.error(`Error code: ${b}`),eN.error(`Error chain: ${cj(a)}`)}else if(a&&"object"==typeof a){eN.error(`Error type: ${typeof a}`),eN.error(`Error constructor: ${a.constructor?.name||"Unknown"}`);let b=Object.getOwnPropertyNames(a);b.length>0?(eN.error(`Error properties: ${b.join(", ")}`),b.forEach(b=>{try{let c=a[b];eN.error(` ${b}: ${"function"==typeof c?"[Function]":JSON.stringify(c)}`)}catch(a){eN.error(` ${b}: [Unable to serialize: ${a}]`)}})):eN.error("Error object has no enumerable properties");try{let b=JSON.stringify(a);eN.error(`JSON stringified error: ${b}`)}catch(a){eN.error(`Cannot JSON stringify error: ${a}`)}}else eN.error(`Error value: ${String(a)} (type: ${typeof a})`);this.appendStderrLog(b.name,`Transport error: ${cj(a)}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{if(!a||a.disabled)return void eN.info(`Server ${b.name} is now disabled, skipping reconnection after transport error`);eN.info(`Transport error for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a)}).catch(a=>{eN.warn(`Error checking server config for ${b.name} during onerror:`,a)})},await a.connect(c),this.clients.set(b.name,a),this.activeTransports.set(b.name,c),this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),eN.info(`connectServer: Successfully connected to ${b.name}`),{success:!0}}catch(f){eN.error(`connectServer: Failed to connect to server ${b.name}:`,f);let a=f instanceof Error?f.message:String(f),c=f instanceof Error?f.name:"";if(a.includes("OAuth authentication required")||"OAuthAuthenticationRequired"===c){if(eN.info(`OAuth authentication required for server ${b.name}`),"streamable"===b.transport){let a=b;a.authorizationUrl&&eN.info(`Authorization URL available for ${b.name}: ${a.authorizationUrl}`)}return{success:!1,error:a,requiresAuthentication:!0}}if(cm(f)){if(eN.info(`OAuth authentication error detected for server ${b.name}: ${a}`),"streamable"===b.transport){let a=b;if(!a.oauthScopes||0===a.oauthScopes.length){eN.info(`Dynamically enabling OAuth for server ${b.name} due to authentication error`);try{let c={...a,oauthScopes:["read"]},d=await this.loadServerConfigs();if(Array.isArray(d)){let a=d.findIndex(a=>a.name===b.name);-1!==a&&(d[a]=c,await (0,b$.q)(new Map(d.map(a=>[a.name,a]))),eN.info(`Updated config for ${b.name} to enable OAuth`))}}catch(a){eN.warn(`Failed to update config for ${b.name} to enable OAuth:`,a)}}}return{success:!1,error:"OAuth authentication failed or tokens have expired. Please re-authenticate.",requiresAuthentication:!0}}let d=this.stderrLogs.get(b.name)||[],e=ck(f,b,d);return this.lastConnectionError.set(b.name,e),{success:!1,error:e}}finally{this.connectingServers.delete(b.name)}}async testConnection(a,b){eN.info(`testConnection: Testing connection to ${a.name||"(unnamed)"} via ${a.transport} transport`);let c=a=>{try{b?.(a)}catch{}},d=[],e=null,f=null;try{let b,g=await eD(a);e=eI(g),(f=eJ(g))instanceof bS&&f.stderr&&f.stderr.on("data",a=>{let b=a.toString();d.push(b),c({type:"stderr",data:b})}),f.onerror=a=>{let b=`Transport error: ${cj(a)}`;d.push(b),c({type:"stderr",data:b+"\n"})},c({type:"status",phase:"spawning",message:"Starting server / opening transport..."});let h=cv(a)?9e4:15e3,i=cv(a),j=new Promise((a,c)=>{b=setTimeout(()=>c(Error(`Connection timeout after ${h/1e3}s`+(i?" — the package may still be downloading via npx/uvx. Try running the Test again (the package is cached after the first download), or verify the command and network access.":""))),h)});c({type:"status",phase:"handshaking",message:"Performing MCP handshake..."});try{await Promise.race([e.connect(f),j])}finally{b&&clearTimeout(b)}c({type:"status",phase:"listing-tools",message:"Handshake OK — listing tools..."});let k=0;try{let a=await e.listTools();k=Array.isArray(a?.tools)?a.tools.length:0}catch(b){eN.debug(`testConnection: connected to ${a.name} but listTools failed: ${b instanceof Error?b.message:String(b)}`)}return eN.info(`testConnection: Successfully connected to ${a.name} (${k} tools)`),c({type:"result",success:!0,data:{toolCount:k}}),{success:!0,data:{toolCount:k}}}catch(f){eN.warn(`testConnection: Failed to connect to ${a.name}:`,f);let b=cm(f),e=ck(f,a,d);return c({type:"result",success:!1,error:e,requiresAuthentication:b}),{success:!1,error:e,requiresAuthentication:b}}finally{if(e)try{await eL(e,a.name,a,{gracePeriodMs:3e3,killEscalationMs:2e3})}catch(b){eN.debug(`testConnection: error closing test client for ${a.name}: ${b instanceof Error?b.message:String(b)}`)}}}setNodeRoots(a,b,c){for(let d of function(a,b,c){let d=(c??[]).filter(a=>"string"==typeof a&&a.trim().length>0),e=es().get(b),f=new Set([a]);e&&f.add(e.serverName);let g=new Map;for(let a of f)g.set(a,et(a));0===d.length?es().delete(b)&&er.debug(`Cleared node roots for node ${b}`):(es().set(b,{serverName:a,roots:d}),er.debug(`Registered ${d.length} node root(s) for node ${b} on server ${a}`));let h=[];for(let a of f){let b=et(a),c=g.get(a)??[];(b.length!==c.length||b.some((a,b)=>a!==c[b]))&&h.push(a)}return h}(a,b,c))this.notifyRootsChanged(d)}notifyRootsChanged(a){let b=this.getClient(a);if(!b)return void eN.debug(`notifyRootsChanged: ${a} not connected, skipping notification`);try{b.sendRootsListChanged().catch(b=>{eN.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}),eN.debug(`notifyRootsChanged: sent roots/list_changed to ${a}`)}catch(b){eN.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}}async disconnectServer(a){if(eN.debug(`disconnectServer: Entering method for server ${a}`),await this.isInternalServer(a))return{success:!0};this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a);let b=this.getClient(a);if(!b)return eN.warn(`disconnectServer: Server ${a} not found in clients map`),this.deregisterClient(a),{success:!1,error:`Server ${a} not found`};this.deregisterClient(a);try{let c=await this.getServerConfig(a);return await eL(b,a,c||void 0),eN.info(`disconnectServer: Disconnected server ${a}`),{success:!0}}catch(b){return eN.warn(`disconnectServer: Failed to disconnect server ${a}:`,b),{success:!1,error:`Failed to disconnect server: ${b instanceof Error?b.message:"Unknown error"}`}}}async forceReconnect(a){if(eN.info(`forceReconnect: Forcing fresh connection for server ${a}`),await this.isInternalServer(a))return{success:!0};let b=this.clients.get(a);if(b){this.deregisterClient(a);let c=await this.getServerConfig(a);try{await eL(b,a,c||void 0)}catch(b){eN.debug(`forceReconnect: error closing stale client for ${a}: ${b instanceof Error?b.message:String(b)}`)}}return this.connectServer(a)}async listServerTools(a){if(eN.debug(`listServerTools: Entering method for server ${a}`),await this.isInternalServer(a)){let{internalToolDefinitions:a}=await Promise.all([c.e(3304),c.e(6936),c.e(6195)]).then(c.bind(c,76195));return{tools:a()}}if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return eN.warn(`listServerTools: ${b}`),{tools:[],error:b}}let b=this.getClient(a);b||eN.warn(`listServerTools: Client not found for ${a}`);let d=await b2(b,a);if(d.error){eN.warn(`listServerTools: Listing tools for ${a} failed (${d.error}); forcing reconnect and retrying once`);let c=await this.forceReconnect(a);if(!c.success)return eN.warn(`listServerTools: Reconnect for ${a} failed: ${c.error}`),{tools:[],error:c.error||d.error};b=this.clients.get(a),(d=await b2(b,a)).error?eN.warn(`listServerTools: Retry after reconnect still failed for ${a}:`,d.error):eN.info(`listServerTools: Recovered after reconnect for ${a}; listed ${d.tools.length} tools`)}else eN.info(`listServerTools: Listed ${d.tools.length} tools for ${a}`);return d}async callTool(a,b,d,e,f){if(eN.debug(`callTool: Entering method for server ${a}, tool ${b}`),await this.isInternalServer(a)){let{internalCallTool:a}=await Promise.all([c.e(3304),c.e(6936),c.e(6195)]).then(c.bind(c,76195)),e=await a(this,b,d);return eN.info(`callTool: Dispatched internal tool ${b}`),{success:!0,data:e}}if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return eN.warn(`callTool: ${b}`),{success:!1,error:b}}let g=this.getClient(a);if(!g){eN.warn(`callTool: No client for ${a}; forcing reconnect before calling ${b}`);let c=await this.forceReconnect(a);c.success?g=this.clients.get(a):eN.warn(`callTool: Reconnect for ${a} failed: ${c.error}`)}let h=await b3(g,a,b,d,e,f);return eN.info(`callTool: Called tool ${b} on ${a}`),h}async listWithReconnect(a,b,c){if(await this.isInternalServer(a))return c;if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return eN.warn(`listWithReconnect: ${b}`),{...c,error:b}}let d=this.getClient(a);d||eN.warn(`listWithReconnect: Client not found for ${a}`);let e=await b(d,a);if(!e.error)return e;eN.warn(`listWithReconnect: Listing for ${a} failed (${e.error}); forcing reconnect and retrying once`);let f=await this.forceReconnect(a);return f.success?(d=this.clients.get(a),(e=await b(d,a)).error?eN.warn(`listWithReconnect: Retry after reconnect still failed for ${a}:`,e.error):eN.info(`listWithReconnect: Recovered after reconnect for ${a}`),e):(eN.warn(`listWithReconnect: Reconnect for ${a} failed: ${f.error}`),{...c,error:f.error||e.error})}async listServerResources(a){return eN.debug(`listServerResources: Entering method for server ${a}`),this.listWithReconnect(a,b5,{resources:[]})}async listServerResourceTemplates(a){return eN.debug(`listServerResourceTemplates: Entering method for server ${a}`),this.listWithReconnect(a,b6,{resourceTemplates:[]})}async readResource(a,b){eN.debug(`readResource: Entering method for server ${a}, uri ${b}`);let c=this.getClient(a);c||eN.warn(`readResource: Client not found for ${a}`);let d=await b7(c,a,b);return eN.info(`readResource: Read resource ${b} on ${a}`),d}async listServerPrompts(a){return eN.debug(`listServerPrompts: Entering method for server ${a}`),this.listWithReconnect(a,b9,{prompts:[]})}async getPrompt(a,b,c){eN.debug(`getPrompt: Entering method for server ${a}, prompt ${b}`);let d=this.getClient(a);d||eN.warn(`getPrompt: Client not found for ${a}`);let e=await ca(d,a,b,c);return eN.info(`getPrompt: Got prompt ${b} on ${a}`),e}async resolveOAuthSecretForSave(a,b){return a===co.RJ?b??"":a?a.startsWith("${global:")||a.startsWith("encrypted:")||a.startsWith("encrypted_failed:")?a:await (0,cn.Rs)(a):""}async resolveHeadersForSave(a,b){let c={};for(let[d,e]of Object.entries(a||{})){if(!d)continue;let{value:a,isSecret:f}=cq(e,d);if(!f){""!==a&&(c[d]={value:a,metadata:{isSecret:!1}});continue}if(a===co.RJ||a===co.gF){let a=b?.[d];void 0!==a&&(c[d]=a);continue}if(a){if("string"==typeof a&&a.startsWith("${global:")||a.startsWith("encrypted:")||a.startsWith("encrypted_failed:")){c[d]={value:a,metadata:{isSecret:!0}};continue}c[d]={value:await (0,cn.Rs)(a),metadata:{isSecret:!0}}}}return c}async ensureRemoteServerRootDir(a){try{if(!["streamable","sse","websocket"].includes(a.transport))return;let b=(a.rootPath||"").trim();if(!b)return;let c=bX().resolve((0,bZ.ok)(),b);if(bX().dirname(c)===c)return;await bV().mkdir(c,{recursive:!0}),eN.debug(`ensureRemoteServerRootDir: ensured ${c} for ${a.name}`)}catch(b){eN.warn(`ensureRemoteServerRootDir: could not create root dir for ${a.name}:`,b)}}async updateServerConfig(a,b){if(eN.debug(`updateServerConfig: Entering method for server ${a}`),await this.isInternalServer(a))return{success:!1,error:`"${eM._}" is FLUJO's built-in server and cannot be created or edited.`};let c=await this.loadServerConfigs();if(!Array.isArray(c))return eN.warn("updateServerConfig: Failed to load configs:",c.error),c;let d=c.find(b=>b.name===a),e=!!d&&"string"==typeof b.name&&b.name!==a;if(e&&c.some(a=>a.name===b.name))return eN.warn(`updateServerConfig: Refusing to rename ${a} -> ${b.name}: name already in use`),{success:!1,error:`A server named "${b.name}" already exists`};if(!d&&b.name)eN.info(`updateServerConfig: Creating new server config for ${b.name}`),d={name:b.name,transport:"stdio",command:"",args:[],env:{},disabled:!1,autoApprove:[],_buildCommand:"",_installCommand:"",rootPath:""},c.push(d);else if(!d)return eN.warn(`updateServerConfig: Server ${a} not found`),{success:!1,error:`Server ${a} not found`};if(b.env){eN.debug(`updateServerConfig: Resolving global variables in env for ${a}`);try{eN.debug(`Original env variables for ${a}:`,JSON.stringify(b.env,null,2)),b.env=await (0,b_.c)(b.env),eN.debug(`Resolved env variables for ${a}:`,JSON.stringify(b.env,null,2)),eN.debug(`updateServerConfig: Successfully resolved global variables for ${a}`)}catch(b){eN.warn(`updateServerConfig: Error resolving global variables for ${a}:`,b)}}let f=b.oauthClientSecret;if(void 0!==f){let a=d.oauthClientSecret;b.oauthClientSecret=await this.resolveOAuthSecretForSave(f,a)}let g=b.headers;if(void 0!==g){let a=d.headers;b.headers=await this.resolveHeadersForSave(g,a)}let h={...d};h={...d,...b};let i=JSON.stringify(d.roots??[])!==JSON.stringify(h.roots??[])||(d.rootPath??"")!==(h.rootPath??""),j=c.findIndex(b=>b.name===a);-1!==j?c[j]=h:h.name&&c.push(h);let k=await (0,b$.q)(new Map(c.map(a=>[a.name,a])));return k.success?(await this.ensureRemoteServerRootDir(h),e?(this.clients.has(a)?await this.disconnectServer(a):(this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a)),this.stderrLogs.delete(a),this.lastConnectionError.delete(a),await this.handleConnectionStateChange(h.name,h)):await this.handleConnectionStateChange(a,h),i&&this.notifyRootsChanged(h.name),eN.info(`updateServerConfig: Successfully updated config for ${a}${e?` (renamed to ${h.name})`:""}`),h):(eN.warn(`updateServerConfig: Failed to save config for ${a}:`,k.error),k)}async handleConnectionStateChange(a,b){eN.debug(`handleConnectionStateChange: Entering method for server ${a}`);let c=!!this.getClient(a),d=!b.disabled;if(c&&!d){eN.info(`handleConnectionStateChange: Disconnecting disabled server ${a}`);try{await this.disconnectServer(a)}catch(b){eN.warn(`handleConnectionStateChange: Failed to disconnect server ${a} during update:`,b)}}else!c&&d?(eN.info(`handleConnectionStateChange: Connecting previously disabled server ${a}`),await this.connectServer(b)):c&&d?(eN.info(`handleConnectionStateChange: Re-applying config to connected server ${a}`),await this.connectServer(b)):d||(eN.info(`handleConnectionStateChange: Clearing retry timers for disabled server ${a}`),this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a))}async clearRetryTimersForDisabledServers(){eN.debug("clearRetryTimersForDisabledServers: Checking for disabled servers with active retry timers");try{let a=await this.loadServerConfigs();if(!Array.isArray(a))return void eN.warn("clearRetryTimersForDisabledServers: Failed to load server configs");for(let b of a.filter(a=>a.disabled))this.connectionRetryTimers.has(b.name)&&(eN.info(`clearRetryTimersForDisabledServers: Clearing retry timer for disabled server ${b.name}`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name))}catch(a){eN.error("clearRetryTimersForDisabledServers: Error clearing retry timers:",a)}}async deleteServerConfig(a){if(eN.debug(`deleteServerConfig: Entering method for server ${a}`),await this.isInternalServer(a))return{success:!1,error:`"${eM._}" is FLUJO's built-in server and cannot be deleted.`};this.clients.has(a)&&(eN.info(`deleteServerConfig: Disconnecting server ${a} before deletion`),await this.disconnectServer(a));let b=await this.loadServerConfigs();if(!Array.isArray(b))return eN.warn("deleteServerConfig: Failed to load configs:",b.error),b;let c=b.findIndex(b=>b.name===a);if(-1===c)return eN.warn(`deleteServerConfig: Server ${a} not found in configs`),{success:!1,error:`Server ${a} not found`};b.splice(c,1),eN.debug(`deleteServerConfig: Saving updated configs after deleting ${a}`);let d=await (0,b$.q)(new Map(b.map(a=>[a.name,a])));return d.success?eN.info(`deleteServerConfig: Successfully deleted server ${a}`):eN.warn(`deleteServerConfig: Error saving configs after deleting ${a}:`,d.error),d}async getServerStatus(a){if(await this.isInternalServer(a))return{status:"connected"};let b=await this.getServerConfig(a);if(!b)return eN.warn(`getServerStatus: Server ${a} not found`),{status:"error",message:`Server ${a} configuration not found. The server may have been deleted or not properly configured.`};if(b.disabled)return eN.debug(`getServerStatus: Server ${a} is disabled`),{status:"disconnected"};if("streamable"===b.transport&&b.oauthScopes&&b.oauthScopes.length>0){if(!b.oauthTokens||!b.oauthTokens.access_token)return eN.info(`getServerStatus: Server ${a} requires OAuth authentication but has no valid tokens`),{status:"requires_authentication",message:"OAuth authentication required. Click the authenticate button to complete the OAuth flow."};if(!b.oauthTokens.refresh_token&&b.oauthTokens.expires_in&&b.oauthTokens.issued_at){let c=b.oauthTokens.issued_at,d=b.oauthTokens.expires_in;if(Math.floor(Date.now()/1e3)>=c+d)return eN.info(`getServerStatus: OAuth tokens for ${a} have expired and no refresh token is available`),{status:"requires_authentication",message:"OAuth tokens have expired. Please re-authenticate."}}}let c=(this.stderrLogs.get(a)||[]).join("\n").trim(),d=this.lastConnectionError.get(a);if(this.getClient(a))return eN.info(`getServerStatus: Server ${a} is connected`),{status:"connected",stderrOutput:c||void 0};{let b=this.isStartingUp()&&!this.lastConnectionError.has(a);if(this.connectingServers.has(a)||b)return eN.info(`getServerStatus: Server ${a} is still connecting`),{status:"connecting",message:"Server is starting up. This may take a few moments."};if(c&&(c.includes("OAuth authentication required")||c.includes("invalid_token")))return eN.info(`getServerStatus: OAuth authentication error detected for ${a}`),{status:"requires_authentication",message:"OAuth authentication required. Please complete the OAuth flow.",stderrOutput:c};let e=c||d;return e?(eN.info(`getServerStatus: Using ${c?"stderr output":"persisted connection error"} as error message for ${a}`),{status:"error",message:e,stderrOutput:c||void 0}):(eN.info(`getServerStatus: No specific error details available for ${a}`),{status:"error",message:`Server ${a} is configured but not connected. The server process may have crashed or been terminated.`,stderrOutput:void 0})}}async startEnabledServers(){eN.info("Starting all enabled servers"),this.setStartingUp(!0);try{await this.clearRetryTimersForDisabledServers();let a=await this.loadServerConfigs();if(!Array.isArray(a))return void eN.warn("Failed to load server configs, cannot start servers");let b=a.filter(a=>!a.disabled);eN.info(`Found ${b.length} enabled servers to start`),eN.debug(`${b}`),b.forEach(a=>this.connectingServers.add(a.name)),await Promise.all(b.map(a=>(eN.info(`Starting server: ${a.name}`),this.connectServer(a).catch(b=>{eN.error(`Failed to start server ${a.name}:`,b)}))))}finally{this.setStartingUp(!1)}}async getAvailableClients(){try{let a=await this.loadServerConfigs();if(!a||"error"in a)return eN.warn("getAvailableClients: Failed to load server configs:",a?.error),[];return(await Promise.all(a.map(async a=>{try{let b=await this.getServerStatus(a.name);return{name:a.name,status:"string"==typeof b?b:b.status,connected:"string"==typeof b?"connected"===b:"connected"===b.status}}catch(b){return eN.warn(`getAvailableClients: Error getting status for ${a.name}:`,b),{name:a.name,status:"error",connected:!1}}}))).map(a=>`${a.name} (${a.status})`)}catch(a){return eN.error("getAvailableClients: Error getting available clients:",a),[]}}constructor(){this.stderrLogs=new Map,this.lastConnectionError=new Map,this.inFlightConnects=new Map,this.connectionRetryTimers=new Map,this.connectionRetryAttempts=new Map}}let eP=new eO},99925:(a,b,c)=>{"use strict";let d=c(67729),e=c(97161),f=c(24860),g=e.implSymbol;function h(b){if(!this||this[g]||!(this instanceof h))throw TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");if(arguments.length<1)throw TypeError("Failed to construct 'URL': 1 argument required, but only "+arguments.length+" present.");let c=[];for(let a=0;a<arguments.length&&a<2;++a)c[a]=arguments[a];c[0]=d.USVString(c[0]),void 0!==c[1]&&(c[1]=d.USVString(c[1])),a.exports.setup(this,c)}h.prototype.toJSON=function(){if(!this||!a.exports.is(this))throw TypeError("Illegal invocation");let b=[];for(let a=0;a<arguments.length&&a<0;++a)b[a]=arguments[a];return this[g].toJSON.apply(this[g],b)},Object.defineProperty(h.prototype,"href",{get(){return this[g].href},set(a){a=d.USVString(a),this[g].href=a},enumerable:!0,configurable:!0}),h.prototype.toString=function(){if(!this||!a.exports.is(this))throw TypeError("Illegal invocation");return this.href},Object.defineProperty(h.prototype,"origin",{get(){return this[g].origin},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"protocol",{get(){return this[g].protocol},set(a){a=d.USVString(a),this[g].protocol=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"username",{get(){return this[g].username},set(a){a=d.USVString(a),this[g].username=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"password",{get(){return this[g].password},set(a){a=d.USVString(a),this[g].password=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"host",{get(){return this[g].host},set(a){a=d.USVString(a),this[g].host=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"hostname",{get(){return this[g].hostname},set(a){a=d.USVString(a),this[g].hostname=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"port",{get(){return this[g].port},set(a){a=d.USVString(a),this[g].port=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"pathname",{get(){return this[g].pathname},set(a){a=d.USVString(a),this[g].pathname=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"search",{get(){return this[g].search},set(a){a=d.USVString(a),this[g].search=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"hash",{get(){return this[g].hash},set(a){a=d.USVString(a),this[g].hash=a},enumerable:!0,configurable:!0}),a.exports={is:a=>!!a&&a[g]instanceof f.implementation,create(a,b){let c=Object.create(h.prototype);return this.setup(c,a,b),c},setup(a,b,c){c||(c={}),c.wrapper=a,a[g]=new f.implementation(b,c),a[g][e.wrapperSymbol]=a},interface:h,expose:{Window:{URL:h},Worker:{URL:h}}}}};
|
|
154
|
+
`&&d++}}return[b,c]}(`${f}${b}`);for(let a of c)k(a);f=d,g=!1},reset:function(a={}){f&&a.consume&&k(f),g=!0,h=void 0,i="",j="",f=""}}}class dL extends TransformStream{constructor({onError:a,onRetry:b,onComment:c}={}){let d;super({start(e){d=dK({onEvent:a=>{e.enqueue(a)},onError(b){"terminate"===a?e.error(b):"function"==typeof a&&a(b)},onRetry:b,onComment:c})},transform(a){d.feed(a)}})}}let dM={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class dN extends Error{constructor(a,b){super(`Streamable HTTP error: ${b}`),this.code=a}}class dO{constructor(a,b){this._hasCompletedAuthFlow=!1,this._url=a,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=b?.requestInit,this._authProvider=b?.authProvider,this._fetch=b?.fetch,this._fetchWithInit=cM(b?.fetch,b?.requestInit),this._sessionId=b?.sessionId,this._reconnectionOptions=b?.reconnectionOptions??dM}async _authThenStart(){let a;if(!this._authProvider)throw new dn("No auth provider");try{a=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw this.onerror?.(a),a}if("AUTHORIZED"!==a)throw new dn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let a={};if(this._authProvider){let b=await this._authProvider.tokens();b&&(a.Authorization=`Bearer ${b.access_token}`)}this._sessionId&&(a["mcp-session-id"]=this._sessionId),this._protocolVersion&&(a["mcp-protocol-version"]=this._protocolVersion);let b=cL(this._requestInit?.headers);return new Headers({...a,...b})}async _startOrAuthSse(a){let{resumptionToken:b}=a;try{let c=await this._commonHeaders();c.set("Accept","text/event-stream"),b&&c.set("last-event-id",b);let d=await (this._fetch??fetch)(this._url,{method:"GET",headers:c,signal:this._abortController?.signal});if(!d.ok){if(await d.body?.cancel(),401===d.status&&this._authProvider)return await this._authThenStart();if(405===d.status)return;throw new dN(d.status,`Failed to open SSE stream: ${d.statusText}`)}this._handleSseStream(d.body,a,!0)}catch(a){throw this.onerror?.(a),a}}_getNextReconnectionDelay(a){if(void 0!==this._serverRetryMs)return this._serverRetryMs;let b=this._reconnectionOptions.initialReconnectionDelay;return Math.min(b*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,a),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(a,b=0){let c=this._reconnectionOptions.maxRetries;if(b>=c)return void this.onerror?.(Error(`Maximum reconnection attempts (${c}) exceeded.`));let d=this._getNextReconnectionDelay(b);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(a).catch(c=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${c instanceof Error?c.message:String(c)}`)),this._scheduleReconnection(a,b+1)})},d)}_handleSseStream(a,b,c){let d;if(!a)return;let{onresumptiontoken:e,replayMessageId:f}=b,g=!1,h=!1;(async()=>{try{let b=a.pipeThrough(new TextDecoderStream).pipeThrough(new dL({onRetry:a=>{this._serverRetryMs=a}})).getReader();for(;;){let{value:a,done:c}=await b.read();if(c)break;if((a.id&&(d=a.id,g=!0,e?.(a.id)),a.data)&&(!a.event||"message"===a.event))try{let b=F.parse(JSON.parse(a.data));D(b)&&(h=!0,void 0!==f&&(b.id=f)),this.onmessage?.(b)}catch(a){this.onerror?.(a)}}(c||g)&&!h&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:d,onresumptiontoken:e,replayMessageId:f},0)}catch(a){if(this.onerror?.(Error(`SSE stream disconnected: ${a}`)),(c||g)&&!h&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:d,onresumptiontoken:e,replayMessageId:f},0)}catch(a){this.onerror?.(Error(`Failed to reconnect: ${a instanceof Error?a.message:String(a)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(a){if(!this._authProvider)throw new dn("No auth provider");if("AUTHORIZED"!==await ds(this._authProvider,{serverUrl:this._url,authorizationCode:a,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new dn("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(a,b){try{let{resumptionToken:c,onresumptiontoken:d}=b||{};if(c)return void this._startOrAuthSse({resumptionToken:c,replayMessageId:A(a)?a.id:void 0}).catch(a=>this.onerror?.(a));let e=await this._commonHeaders();e.set("content-type","application/json"),e.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:e,body:JSON.stringify(a),signal:this._abortController?.signal},g=await (this._fetch??fetch)(this._url,f),h=g.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!g.ok){let b=await g.text().catch(()=>null);if(401===g.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new dN(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:b,scope:c}=dv(g);this._resourceMetadataUrl=b,this._scope=c;let d=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==d)throw new dn;return this._hasCompletedAuthFlow=!0,this.send(a)}if(403===g.status&&this._authProvider){let{resourceMetadataUrl:b,scope:c,error:d}=dv(g);if("insufficient_scope"===d){let d=g.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===d)throw new dN(403,"Server returned 403 after trying upscoping");c&&(this._scope=c),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=d??void 0;let e=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch});if("AUTHORIZED"!==e)throw new dn;return this.send(a)}}throw new dN(g.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===g.status){await g.body?.cancel(),W.safeParse(a).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(a=>this.onerror?.(a));return}let i=(Array.isArray(a)?a:[a]).filter(a=>"method"in a&&"id"in a&&void 0!==a.id).length>0,j=g.headers.get("content-type");if(i)if(j?.includes("text/event-stream"))this._handleSseStream(g.body,{onresumptiontoken:d},!1);else if(j?.includes("application/json")){let a=await g.json();for(let b of Array.isArray(a)?a.map(a=>F.parse(a)):[F.parse(a)])this.onmessage?.(b)}else throw await g.body?.cancel(),new dN(-1,`Unexpected content type: ${j}`);else await g.body?.cancel()}catch(a){throw this.onerror?.(a),a}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let a=await this._commonHeaders(),b={...this._requestInit,method:"DELETE",headers:a,signal:this._abortController?.signal},c=await (this._fetch??fetch)(this._url,b);if(await c.body?.cancel(),!c.ok&&405!==c.status)throw new dN(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(a){throw this.onerror?.(a),a}}setProtocolVersion(a){this._protocolVersion=a}get protocolVersion(){return this._protocolVersion}async resumeStream(a,b){await this._startOrAuthSse({resumptionToken:a,onresumptiontoken:b?.onresumptiontoken})}}class dP extends Event{constructor(a,b){var c,d;super(a),this.code=null!=(c=null==b?void 0:b.code)?c:void 0,this.message=null!=(d=null==b?void 0:b.message)?d:void 0}[Symbol.for("nodejs.util.inspect.custom")](a,b,c){return c(dQ(this),b)}[Symbol.for("Deno.customInspect")](a,b){return a(dQ(this),b)}}function dQ(a){return{type:a.type,message:a.message,code:a.code,defaultPrevented:a.defaultPrevented,cancelable:a.cancelable,timeStamp:a.timeStamp}}var dR,dS,dT,dU,dV,dW,dX,dY,dZ,d$,d_,d0,d1,d2,d3,d4,d5,d6,d7,d8,d9,ea,eb,ec,ed,ee=a=>{throw TypeError(a)},ef=(a,b,c)=>b.has(a)||ee("Cannot "+c),eg=(a,b,c)=>(ef(a,b,"read from private field"),c?c.call(a):b.get(a)),eh=(a,b,c)=>b.has(a)?ee("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c),ei=(a,b,c,d)=>(ef(a,b,"write to private field"),b.set(a,c),c),ej=(a,b,c)=>(ef(a,b,"access private method"),c);class ek extends EventTarget{constructor(a,b){var c,d;super(),eh(this,d4),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eh(this,dT),eh(this,dU),eh(this,dV),eh(this,dW),eh(this,dX),eh(this,dY),eh(this,dZ),eh(this,d$,null),eh(this,d_),eh(this,d0),eh(this,d1,null),eh(this,d2,null),eh(this,d3,null),eh(this,d6,async a=>{var b;eg(this,d0).reset();let{body:c,redirected:d,status:e,headers:f}=a;if(204===e){ej(this,d4,eb).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(d?ei(this,dV,new URL(a.url)):ei(this,dV,void 0),200!==e)return void ej(this,d4,eb).call(this,`Non-200 status code (${e})`,e);if(!(f.get("content-type")||"").startsWith("text/event-stream"))return void ej(this,d4,eb).call(this,'Invalid content type, expected "text/event-stream"',e);if(eg(this,dT)===this.CLOSED)return;ei(this,dT,this.OPEN);let g=new Event("open");if(null==(b=eg(this,d3))||b.call(this,g),this.dispatchEvent(g),"object"!=typeof c||!c||!("getReader"in c)){ej(this,d4,eb).call(this,"Invalid response body, expected a web ReadableStream",e),this.close();return}let h=new TextDecoder,i=c.getReader(),j=!0;do{let{done:a,value:b}=await i.read();b&&eg(this,d0).feed(h.decode(b,{stream:!a})),a&&(j=!1,eg(this,d0).reset(),ej(this,d4,ec).call(this))}while(j)}),eh(this,d7,a=>{ei(this,d_,void 0),"AbortError"!==a.name&&"aborted"!==a.type&&ej(this,d4,ec).call(this,function a(b){return b instanceof Error?"errors"in b&&Array.isArray(b.errors)?b.errors.map(a).join(", "):"cause"in b&&b.cause instanceof Error?`${b}: ${a(b.cause)}`:b.message:`${b}`}(a))}),eh(this,d9,a=>{"string"==typeof a.id&&ei(this,d$,a.id);let b=new MessageEvent(a.event||"message",{data:a.data,origin:eg(this,dV)?eg(this,dV).origin:eg(this,dU).origin,lastEventId:a.id||""});eg(this,d2)&&(!a.event||"message"===a.event)&&eg(this,d2).call(this,b),this.dispatchEvent(b)}),eh(this,ea,a=>{ei(this,dY,a)}),eh(this,ed,()=>{ei(this,dZ,void 0),eg(this,dT)===this.CONNECTING&&ej(this,d4,d5).call(this)});try{if(a instanceof URL)ei(this,dU,a);else if("string"==typeof a)ei(this,dU,new URL(a,function(){let a="document"in globalThis?globalThis.document:void 0;return a&&"object"==typeof a&&"baseURI"in a&&"string"==typeof a.baseURI?a.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(a){let b=globalThis.DOMException;return"function"==typeof b?new b(a,"SyntaxError"):SyntaxError(a)}("An invalid or illegal string was specified")}ei(this,d0,dK({onEvent:eg(this,d9),onRetry:eg(this,ea)})),ei(this,dT,this.CONNECTING),ei(this,dY,3e3),ei(this,dX,null!=(c=null==b?void 0:b.fetch)?c:globalThis.fetch),ei(this,dW,null!=(d=null==b?void 0:b.withCredentials)&&d),ej(this,d4,d5).call(this)}get readyState(){return eg(this,dT)}get url(){return eg(this,dU).href}get withCredentials(){return eg(this,dW)}get onerror(){return eg(this,d1)}set onerror(a){ei(this,d1,a)}get onmessage(){return eg(this,d2)}set onmessage(a){ei(this,d2,a)}get onopen(){return eg(this,d3)}set onopen(a){ei(this,d3,a)}addEventListener(a,b,c){super.addEventListener(a,b,c)}removeEventListener(a,b,c){super.removeEventListener(a,b,c)}close(){eg(this,dZ)&&clearTimeout(eg(this,dZ)),eg(this,dT)!==this.CLOSED&&(eg(this,d_)&&eg(this,d_).abort(),ei(this,dT,this.CLOSED),ei(this,d_,void 0))}}dT=new WeakMap,dU=new WeakMap,dV=new WeakMap,dW=new WeakMap,dX=new WeakMap,dY=new WeakMap,dZ=new WeakMap,d$=new WeakMap,d_=new WeakMap,d0=new WeakMap,d1=new WeakMap,d2=new WeakMap,d3=new WeakMap,d4=new WeakSet,d5=function(){ei(this,dT,this.CONNECTING),ei(this,d_,new AbortController),eg(this,dX)(eg(this,dU),ej(this,d4,d8).call(this)).then(eg(this,d6)).catch(eg(this,d7))},d6=new WeakMap,d7=new WeakMap,d8=function(){var a;let b={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...eg(this,d$)?{"Last-Event-ID":eg(this,d$)}:void 0},cache:"no-store",signal:null==(a=eg(this,d_))?void 0:a.signal};return"window"in globalThis&&(b.credentials=this.withCredentials?"include":"same-origin"),b},d9=new WeakMap,ea=new WeakMap,eb=function(a,b){var c;eg(this,dT)!==this.CLOSED&&ei(this,dT,this.CLOSED);let d=new dP("error",{code:b,message:a});null==(c=eg(this,d1))||c.call(this,d),this.dispatchEvent(d)},ec=function(a,b){var c;if(eg(this,dT)===this.CLOSED)return;ei(this,dT,this.CONNECTING);let d=new dP("error",{code:b,message:a});null==(c=eg(this,d1))||c.call(this,d),this.dispatchEvent(d),ei(this,dZ,setTimeout(eg(this,ed),eg(this,dY)))},ed=new WeakMap,ek.CONNECTING=0,ek.OPEN=1,ek.CLOSED=2;class el extends Error{constructor(a,b,c){super(`SSE error: ${b}`),this.code=a,this.event=c}}class em{constructor(a,b){this._url=a,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=b?.eventSourceInit,this._requestInit=b?.requestInit,this._authProvider=b?.authProvider,this._fetch=b?.fetch,this._fetchWithInit=cM(b?.fetch,b?.requestInit)}async _authThenStart(){let a;if(!this._authProvider)throw new dn("No auth provider");try{a=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw this.onerror?.(a),a}if("AUTHORIZED"!==a)throw new dn;return await this._startOrAuth()}async _commonHeaders(){let a={};if(this._authProvider){let b=await this._authProvider.tokens();b&&(a.Authorization=`Bearer ${b.access_token}`)}this._protocolVersion&&(a["mcp-protocol-version"]=this._protocolVersion);let b=cL(this._requestInit?.headers);return new Headers({...a,...b})}_startOrAuth(){let a=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((b,c)=>{this._eventSource=new ek(this._url.href,{...this._eventSourceInit,fetch:async(b,c)=>{let d=await this._commonHeaders();d.set("Accept","text/event-stream");let e=await a(b,{...c,headers:d});if(401===e.status&&e.headers.has("www-authenticate")){let{resourceMetadataUrl:a,scope:b}=dv(e);this._resourceMetadataUrl=a,this._scope=b}return e}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{if(401===a.code&&this._authProvider)return void this._authThenStart().then(b,c);let d=new el(a.code,a.message,a);c(d),this.onerror?.(d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{try{if(this._endpoint=new URL(a.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){c(a),this.onerror?.(a),this.close();return}b()}),this._eventSource.onmessage=a=>{let b;try{b=F.parse(JSON.parse(a.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(b)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(a){if(!this._authProvider)throw new dn("No auth provider");if("AUTHORIZED"!==await ds(this._authProvider,{serverUrl:this._url,authorizationCode:a,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new dn("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(a){if(!this._endpoint)throw Error("Not connected");try{let b=await this._commonHeaders();b.set("content-type","application/json");let c={...this._requestInit,method:"POST",headers:b,body:JSON.stringify(a),signal:this._abortController?.signal},d=await (this._fetch??fetch)(this._endpoint,c);if(!d.ok){let b=await d.text().catch(()=>null);if(401===d.status&&this._authProvider){let{resourceMetadataUrl:b,scope:c}=dv(d);this._resourceMetadataUrl=b,this._scope=c;let e=await ds(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==e)throw new dn;return this.send(a)}throw Error(`Error POSTing to endpoint (HTTP ${d.status}): ${b}`)}await d.body?.cancel()}catch(a){throw this.onerror?.(a),a}}setProtocolVersion(a){this._protocolVersion=a}}let en=(0,bY.h)("backend/services/mcp/oauth");class eo{constructor(a,b){this.config=a,this._redirectUrl=b,this._clientMetadata={redirect_uris:[b],client_name:`FLUJO MCP Client - ${a.name}`,client_uri:"https://github.com/mario-andreschak/FLUJO",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post",scope:a.oauthScopes?.join(" ")||"read"},en.info(`Created OAuth client provider for ${a.name}`),en.verbose("OAuth client metadata",JSON.stringify(this._clientMetadata))}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return encodeURIComponent(JSON.stringify({serverName:this.config.name}))}async clientInformation(){if(this.config.oauthClientInformation)return en.debug(`Returning stored client information for ${this.config.name}`),this.config.oauthClientInformation;if(this.config.oauthClientId){let a=this.config.oauthClientSecret?await (0,b_.G)(this.config.oauthClientSecret)??void 0:void 0;return en.debug(`Created client information from config for ${this.config.name}`),{client_id:this.config.oauthClientId,client_secret:a}}en.debug(`No client information available for ${this.config.name}`)}async persist(){let a=await (0,b$.loadServerConfigs)();if(!Array.isArray(a))return void en.warn(`persist: failed to load server configs for ${this.config.name}, cannot persist OAuth state`);let b=new Map(a.map(a=>[a.name,a]));b.set(this.config.name,this.config);let c=await (0,b$.q)(b);c.success||en.warn(`persist: failed to save OAuth state for ${this.config.name}: ${c.error}`)}async invalidateCredentials(a){en.info(`Invalidating OAuth credentials for ${this.config.name} (scope: ${a})`),("all"===a||"tokens"===a)&&(this.config.oauthTokens=void 0),("all"===a||"client"===a)&&(this.config.oauthClientInformation=void 0,this.config.oauthClientMetadata=void 0),("all"===a||"verifier"===a)&&(this.config.oauthCodeVerifier=void 0),await this.persist()}async saveClientInformation(a){en.info(`Saving client information for ${this.config.name}`),en.verbose("Client information to save",JSON.stringify(a)),this.config.oauthClientInformation={client_id:a.client_id,client_secret:a.client_secret,client_id_issued_at:a.client_id_issued_at,client_secret_expires_at:a.client_secret_expires_at},this.config.oauthClientMetadata={redirect_uris:a.redirect_uris,client_name:a.client_name,client_uri:a.client_uri,grant_types:a.grant_types,response_types:a.response_types,token_endpoint_auth_method:a.token_endpoint_auth_method,scope:a.scope,contacts:a.contacts,tos_uri:a.tos_uri,policy_uri:a.policy_uri,jwks_uri:a.jwks_uri,jwks:a.jwks,software_id:a.software_id,software_version:a.software_version},await this.persist(),en.info(`Client information saved for ${this.config.name}`)}async tokens(){if(this.config.oauthTokens){if(en.debug(`Returning stored tokens for ${this.config.name}`),this.config.oauthTokens.expires_in&&this.config.oauthTokens.issued_at){let a=this.config.oauthTokens.issued_at,b=this.config.oauthTokens.expires_in,c=Math.floor(Date.now()/1e3),d=a+b;c>=d?en.info(`Access token for ${this.config.name} has expired (issued: ${a}, expires: ${d}, current: ${c}); SDK will refresh via refresh_token`):en.debug(`Tokens for ${this.config.name} are valid (expires in ${d-c} seconds)`)}return this.config.oauthTokens}en.debug(`No tokens available for ${this.config.name}`)}async saveTokens(a){en.info(`Saving OAuth tokens for ${this.config.name}`),en.verbose("Tokens to save",JSON.stringify({...a,access_token:a.access_token?"[REDACTED]":void 0,refresh_token:a.refresh_token?"[REDACTED]":void 0}));let b={...a,issued_at:Math.floor(Date.now()/1e3)};this.config.oauthTokens=b,await this.persist(),en.info(`OAuth tokens saved for ${this.config.name}`)}async redirectToAuthorization(a){en.info(`Authorization required for ${this.config.name}`),en.info(`Authorization URL: ${a.toString()}`),this.config.authorizationUrl=a.toString();let b=Error(`OAuth authentication required for ${this.config.name}. Please complete the OAuth flow.`);throw b.name="OAuthAuthenticationRequired",b}async saveCodeVerifier(a){en.debug(`Saving code verifier for ${this.config.name}`),this.config.oauthCodeVerifier=a,await this.persist(),en.debug(`Code verifier saved for ${this.config.name}`)}async codeVerifier(){if(!this.config.oauthCodeVerifier){let a=`No code verifier found for ${this.config.name}`;throw en.error(a),Error(a)}return en.debug(`Returning code verifier for ${this.config.name}`),this.config.oauthCodeVerifier}}let ep=new Set(["node","npm","npx"]);var eq=c(79551);let er=(0,bY.h)("backend/services/mcp/roots");function es(){return global.__mcp_node_roots}function et(a){let b=[];for(let c of es().values())if(c.serverName===a)for(let a of c.roots)b.includes(a)||b.push(a);return b}async function eu(a){let b=function(a){let b=a.trim();if(!b)return null;if(b.startsWith("file://"))return b;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(b))return er.warn(`Ignoring non-file root URI: ${b}`),null;try{return(0,eq.pathToFileURL)(b).href}catch(a){return er.warn(`Could not convert root "${b}" to a file URI:`,a),null}}(await (0,b_.c)(a));return b?{uri:b,name:function(a){try{let b=new URL(a).pathname.replace(/\/+$/,"").split("/").pop();return b?decodeURIComponent(b):void 0}catch{return}}(b)}:null}async function ev(a){let b=a.roots,c=[...Array.isArray(b)?b:[],...et(a.name)],d=[],e=new Set;for(let a of c){if("string"!=typeof a||!a.trim())continue;let b=await eu(a);b&&!e.has(b.uri)&&(e.add(b.uri),d.push(b))}if(0===d.length&&"string"==typeof a.rootPath&&a.rootPath.trim()){let b=await eu(a.rootPath);if(b)return[b]}return d}async function ew(a){try{let{loadServerConfigs:b}=await Promise.resolve().then(c.bind(c,6544)),d=await b();if(Array.isArray(d)){let b=d.find(b=>b.name===a.name);if(b)return b}}catch(b){er.warn(`Could not re-load config for ${a.name}, using connect-time config:`,b)}return a}void 0===global.__mcp_node_roots&&(global.__mcp_node_roots=new Map);var ex=c(12763),ey=c(31351);let ez=(0,bY.h)("backend/services/mcp/sampling");function eA(a){return a.sampling}function eB(a){let b=eA(a);return b?.enabled?JSON.stringify({m:b.modelId,t:b.maxTokens,r:b.maxCallsPerMinute}):""}let eC=(0,bY.h)("backend/services/mcp/connection");async function eD(a){if("streamable"!==a.transport&&"sse"!==a.transport||!a.headers||"object"!=typeof a.headers)return a;let b={};for(let[c,d]of Object.entries(a.headers)){if(!c)continue;let{value:a}=cq(d,c);if(!a)continue;let e=await (0,b_.G)(a);e&&(b[c]=e)}return{...a,headers:b}}function eE(a){let b={};for(let[c,d]of Object.entries(a)){if(!c)continue;let{value:a}=cq(d,c);"string"==typeof a&&a.length>0&&(b[c]=a)}return b}function eF(a){let b={};if(a)for(let[c,d]of Object.entries(a))d&&"object"==typeof d&&"value"in d?b[c]=d.value:b[c]=d;return b}function eG(a){return JSON.stringify({command:a.command,args:a.args??[],env:eF(a.env),cwd:String(a.cwd??""),rootPath:a.rootPath??""})}function eH(a){return JSON.stringify({transport:a.transport,url:a.serverUrl??"",headers:a.headers??{},requestInit:a.requestInit??{},eventSourceInit:a.eventSourceInit??{},reconnectionOptions:a.reconnectionOptions??{},sessionId:a.sessionId??"",oauthClientId:a.oauthClientId??"",oauthClientInformation:a.oauthClientInformation??{},oauthClientSecret:a.oauthClientSecret??"",oauthTokens:a.oauthTokens??{}})}function eI(a){eC.debug("Entering createNewClient method");let b=function(a){let b=eA(a);return!!(b?.enabled&&b.modelId)}(a),c=new cJ({name:`flujo-${a.name}-client`,version:"3.16.0"},{capabilities:{experimental:{},roots:{listChanged:!0},...b?{sampling:{}}:{}}});return c.setRequestHandler(bL,async()=>{let b=await ev(await ew(a));return er.debug(`roots/list for ${a.name}: ${b.length} root(s)`),{roots:b}}),b&&function(a,b){let c=[];a.setRequestHandler(bj,async a=>{let d=eA(b);if(!d?.enabled||!d.modelId)throw new bO(dR.InvalidRequest,"Sampling is not enabled for this server");let e=d.maxCallsPerMinute??10,f=Date.now(),g=f-6e4;for(;c.length>0&&c[0]<g;)c.shift();if(c.length>=e)throw ez.warn(`Sampling rate limit (${e}/min) hit for ${b.name}`),new bO(dR.InvalidRequest,`Sampling rate limit of ${e}/min exceeded`);c.push(f);let h=await ex.modelService.getModel(d.modelId);if(!h)throw new bO(dR.InternalError,`Sampling model not found: ${d.modelId}`);let i=await ex.modelService.resolveAndDecryptApiKey(h.ApiKey);if(!i)throw new bO(dR.InternalError,"Could not resolve the sampling model API key");let j=a.params,k=function(a){let b=[];for(let c of(a.systemPrompt&&b.push({role:"system",content:a.systemPrompt}),a.messages||[])){let a=c.content,d=a?.type==="text"&&"string"==typeof a.text?a.text:`[unsupported ${a?.type||"non-text"} content omitted]`;b.push({role:c.role,content:d})}return b}(j),l="number"==typeof j.temperature?j.temperature:.7;ez.info(`Sampling for ${b.name} via model ${h.name} (${k.length} messages)`);let m=(0,ey.getCompletionAdapter)(h),{completion:n}=await m.createCompletion({model:h,apiKey:i,messages:k,temperature:l}),o=n.choices?.[0]?.message?.content;return{role:"assistant",content:{type:"text",text:"string"==typeof o?o:""},model:h.name,stopReason:"endTurn"}})}(c,a),c.__flujoCapKey=eB(a),c}function eJ(a){if(eC.debug("Entering createTransport method"),"streamable"===a.transport){eC.info(`Creating streamable http transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.reconnectionOptions&&"object"==typeof a.reconnectionOptions&&(b.reconnectionOptions=a.reconnectionOptions),"string"==typeof a.sessionId&&a.sessionId.length>0&&(b.sessionId=a.sessionId),a.headers&&"object"==typeof a.headers){let c=eE(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},eC.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}a.oauthClientId||a.oauthClientInformation?(eC.info(`Setting up OAuth authentication for ${a.name}`),b.authProvider=function(a,b="http://localhost:4200/api/oauth/callback"){return new eo(a,b)}(a),a.oauthTokens?.access_token?(eC.debug(`OAuth provider configured for ${a.name} with existing tokens`),eC.debug(`Token expires in: ${a.oauthTokens.expires_in} seconds`)):eC.debug(`OAuth provider configured for ${a.name} - will initiate OAuth flow if needed`)):eC.debug(`No OAuth configuration found for ${a.name}`);let c=new dO(new URL(a.serverUrl),b);return c.__flujoHttpKey=eH(a),c}if("sse"===a.transport){eC.info(`Creating legacy sse transport for server ${a.name} with URL ${a.serverUrl}`);let b={};if(a.requestInit&&"object"==typeof a.requestInit&&(b.requestInit=a.requestInit),a.eventSourceInit&&"object"==typeof a.eventSourceInit&&(b.eventSourceInit=a.eventSourceInit),a.headers&&"object"==typeof a.headers){let c=eE(a.headers);Object.keys(c).length>0&&(b.requestInit={...b.requestInit||{},headers:{...b.requestInit?.headers||{},...c}},eC.info(`Applied ${Object.keys(c).length} custom header(s) for ${a.name}: ${Object.keys(c).join(", ")}`))}let c=new em(new URL(a.serverUrl),b);return c.__flujoHttpKey=eH(a),c}return"websocket"===a.transport?(eC.info(`Creating WebSocket transport for server ${a.name} with URL ${a.websocketUrl}`),new cK(new URL(a.websocketUrl))):function(a){if(eC.debug("Entering createStdioTransport method"),"stdio"!==a.transport)throw Error("Cannot create stdio transport for non-stdio config");let b=a.command,c=a.args?[...a.args]:[],d=`${cd.VL}/${a.name}`;eC.info(`Creating stdio transport for server ${a.name}`),eC.debug(`Original command: ${b}`),eC.debug(`Original args: ${JSON.stringify(c)}`),eC.debug(`Server directory: ${d}`);let e=!bW.isAbsolute(b)&&(b.includes("/")||b.includes("\\")),f=!b.includes("/")&&!b.includes("\\");if(eC.debug(`Is relative path: ${e}`),eC.debug(`Is just filename: ${f}`),"win32"===cc.platform()&&b.toLowerCase().endsWith(".bat"))if(eC.debug(`Detected .bat file on Windows: ${b}`),f){let a=bW.join((0,bZ.ok)(),d,b);eC.debug(`Checking if file exists at: ${a}`);let e=cb.existsSync(a);eC.debug(`File exists: ${e}`),e?(eC.debug(`Using full path to .bat file: ${a}`),c=["/c",a,...c]):(eC.warn(`WARNING: .bat file not found at ${a}`),c=["/c",b,...c]),b="cmd.exe"}else eC.debug(`Using cmd.exe with path as provided: ${b}`),c=["/c",b,...c],b="cmd.exe";let g=function(a,b){if(!a||!(!a.includes("/")&&!a.includes("\\")))return a;let c=a.toLowerCase();if(!ep.has(c))return a;if("node"===c)return b.execPath||a;if(!b.execPath)return a;let d=b.dirname(b.execPath);for(let a of"win32"===b.platform?[`${c}.cmd`,`${c}.exe`,c]:[c]){let c=b.joinPath(d,a);if(b.fileExists(c))return c}return a}(b,{execPath:process.execPath,platform:cc.platform(),dirname:bW.dirname,joinPath:bW.join,fileExists:cb.existsSync});g!==b&&(eC.debug(`Resolved Node toolchain command "${b}" to absolute path: ${g}`),b=g),eC.debug(`Final command: ${b}`),eC.debug(`Final args: ${JSON.stringify(c)}`);let h=function({command:a,args:b=[],rootPath:c,cwd:d,serverName:e,defaultCwd:f}){let g=c||d||f;return e&&cu(a,b)&&(g.split(/[\\/]/).filter(Boolean).pop()||"")===e&&function(a){let b=a.match(/^(.*[\\/])[^\\/]+[\\/]*$/);return b?b[1].replace(/[\\/]+$/,""):""}(g)||g}({command:a.command,args:a.args,rootPath:a.rootPath,cwd:a.cwd,serverName:a.name,defaultCwd:`${cd.VL}/${a.name}`}),i=bW.isAbsolute(h)?h:bW.join((0,bZ.ok)(),h);eC.debug(`cwd: ${i}`),eC.debug(`env: ${JSON.stringify(a.env)}`),eC.info(`Creating StdioClientTransport for ${a.name} with stderr: 'pipe'`);let j=eF(a.env);eC.verbose("Transformed environment variables",JSON.stringify(j));let k=new bS({command:b,args:c,env:j,cwd:i,stderr:"pipe"});return k.__flujoStdioKey=eG(a),k.stderr?eC.info(`Stderr stream is available for ${a.name}`):eC.warn(`Stderr stream is NOT available for ${a.name}`),k}(a)}function eK(a,b){return null!==a.exitCode||null!==a.signalCode?Promise.resolve(!0):new Promise(c=>{let d=()=>{clearTimeout(e),c(!0)},e=setTimeout(()=>{a.removeListener("exit",d),c(!1)},b);e.unref?.(),a.once("exit",d)})}async function eL(a,b,c,d){eC.debug("Entering safelyCloseClient method");let e=d?.gracePeriodMs??15e3,f=d?.killEscalationMs??5e3;try{if(a.transport instanceof bS){let c=a.transport._process;if(c&&null===c.exitCode&&null===c.signalCode){try{c.stdin&&!c.stdin.destroyed&&(c.stdin.end(),eC.debug(`Closed stdin for graceful shutdown for ${b}`))}catch(a){eC.warn(`Error closing stdin for ${b}:`,a)}let a=await eK(c,e);if(!a){eC.warn(`Process did not exit within ${e}ms after stdin close, sending SIGTERM for ${b}`);try{c.kill("SIGTERM")}catch(a){eC.error(`Error sending SIGTERM for ${b}:`,a)}a=await eK(c,f)}if(a)eC.info(`Process exited gracefully for ${b}`);else{eC.warn(`Process did not respond to SIGTERM, sending SIGKILL for ${b}`);try{c.kill("SIGKILL")}catch(a){eC.error(`Error sending SIGKILL for ${b}:`,a)}}}}await a.close(),eC.info(`Client closed successfully for ${b}`)}catch(a){eC.warn(`Error closing client for ${b}:`,a)}}var eM=c(92018);void 0===global.__mcp_clients&&(global.__mcp_clients=new Map),void 0===global.__mcp_connecting&&(global.__mcp_connecting=new Set),void 0===global.__mcp_starting_up&&(global.__mcp_starting_up=!0),void 0===global.__mcp_active_transports&&(global.__mcp_active_transports=new Map);let eN=(0,bY.h)("backend/services/mcp/index");class eO{get clients(){return global.__mcp_clients}get connectingServers(){return global.__mcp_connecting}get activeTransports(){return global.__mcp_active_transports}static{this.MAX_STDERR_LOG_ENTRIES=200}appendStderrLog(a,b){let c=this.stderrLogs.get(a)||[];c.push(b),c.length>eO.MAX_STDERR_LOG_ENTRIES&&c.splice(0,c.length-eO.MAX_STDERR_LOG_ENTRIES),this.stderrLogs.set(a,c)}deregisterClient(a){this.clients.delete(a),this.activeTransports.delete(a)}clearRetryTimer(a){let b=this.connectionRetryTimers.get(a);b&&(clearTimeout(b),this.connectionRetryTimers.delete(a),eN.debug(`Cleared retry timer for server ${a}`))}scheduleConnectionRetry(a,b){this.clearRetryTimer(a);let c=this.connectionRetryAttempts.get(a)||0;if(c>=5){eN.warn(`Maximum retry attempts (5) reached for server ${a}, stopping retries`),this.connectionRetryAttempts.delete(a);return}let d=Math.min(5e3*Math.pow(2,c),3e5);eN.info(`Scheduling connection retry for server ${a} in ${d}ms (attempt ${c+1}/5)`);let e=setTimeout(async()=>{eN.info(`Attempting to reconnect server ${a} (attempt ${c+1}/5)`);let b=await this.getServerConfig(a);if(!b){eN.info(`Server ${a} configuration not found, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}if(b.disabled){eN.info(`Server ${a} is now disabled, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}let d=this.getClient(a);if(d)try{await d.ping({timeout:5e3}),eN.info(`Server ${a} is already connected and responsive, cancelling retry`),this.connectionRetryAttempts.delete(a);return}catch(b){eN.warn(`Server ${a} has a registered client but ping failed (${b instanceof Error?b.message:String(b)}); reconnecting from scratch`)}this.connectionRetryAttempts.set(a,c+1);try{let e=d?await this.forceReconnect(a):await this.connectServer(b);if(e.success)eN.info(`Successfully reconnected server ${a} after ${c+1} attempts`),this.connectionRetryAttempts.delete(a);else{if(eN.warn(`Failed to reconnect server ${a}: ${e.error}`),e.requiresAuthentication){eN.info(`Server ${a} requires authentication, stopping retry attempts`),this.connectionRetryAttempts.delete(a);return}this.scheduleConnectionRetry(a,b)}}catch(c){eN.error(`Error during retry connection for server ${a}:`,c),this.scheduleConnectionRetry(a,b)}},d);this.connectionRetryTimers.set(a,e)}isStartingUp(){return!0===global.__mcp_starting_up}setStartingUp(a){global.__mcp_starting_up=a,eN.info(`Backend startup state set to: ${a?"starting":"complete"}`)}getClient(a){let b=this.clients.get(a);if(b&&cf(b)){eN.warn(`getClient: client for ${a} has a closed/aborted connection — evicting it`),this.clients.delete(a);return}return eN.debug(`getClient: Looking for client: ${a}`,b?"Found":"Not found"),b}async loadServerConfigs(){eN.debug("loadServerConfigs: Entering method");try{let a=await (0,b$.loadServerConfigs)();if(!Array.isArray(a))return eN.warn("loadServerConfigs: Received non-array response",a),a;return a.some(a=>a.name===eM._)?eN.warn(`loadServerConfigs: A stored server is named "${eM._}" — it shadows FLUJO's built-in server`):a.push((0,eM.z)()),eN.debug(`loadServerConfigs: Loaded ${a.length} server configs`),a}catch(a){return eN.warn("loadServerConfigs: Failed to load server configs:",a),{success:!1,error:`Failed to load server configs: ${a instanceof Error?a.message:"Unknown error"}`}}}async getServerConfig(a){eN.debug(`getServerConfig: Looking up config for server ${a}`);let b=await this.loadServerConfigs();if(!Array.isArray(b))return eN.warn(`getServerConfig: Failed to load configs for ${a}:`,b.error),null;let c=b.find(b=>b.name===a);return c||(eN.warn(`getServerConfig: Server ${a} not found in configs`),null)}async isServerDisabled(a){let b=await this.getServerConfig(a);return b?.disabled===!0}async isInternalServer(a){if(a!==eM._)return!1;let b=await (0,b$.loadServerConfigs)();return!Array.isArray(b)||!b.some(a=>a.name===eM._)}async connectServer(a){let b="string"==typeof a?a:a.name;if(b===eM._&&("string"!=typeof a?!0===a.builtIn:await this.isInternalServer(b)))return this.connectingServers.delete(b),{success:!0};let c=this.inFlightConnects.get(b);if(c)return eN.debug(`connectServer: reusing in-flight connection attempt for ${b}`),c;let d=this.connectServerInternal(a).finally(()=>{this.inFlightConnects.delete(b)});return this.inFlightConnects.set(b,d),d}async connectServerInternal(a){let b;if("string"==typeof a){eN.info(`connectServer: Looking up config for server ${a}`);let c=await this.getServerConfig(a);if(!c)return eN.warn(`connectServer: Server ${a} not found in configs`),{success:!1,error:`Server configuration for "${a}" not found. The server may have been deleted or not properly configured.`};b=c}else b=a;if((("string"==typeof a?b:await this.getServerConfig(b.name))??b).disabled)return eN.info(`connectServer: Server ${b.name} is disabled — refusing to create a client/transport`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),{success:!1,error:`Server '${b.name}' is disabled. Enable it on the MCP page to use it.`};let c=(0,bT.A)();eN.info(`connectServer: Starting connection for server ${b.name} [RequestID: ${c}]`),this.connectingServers.add(b.name);try{this.stderrLogs.set(b.name,[]),b=await eD(b);let a=this.clients.get(b.name);if(a){let{needsNewClient:c,reason:d}=function(a,b){if(eC.debug("Entering shouldRecreateClient method"),cf(a))return{needsNewClient:!0,reason:"Existing connection is closed"};if((a.__flujoCapKey??"")!==eB(b))return{needsNewClient:!0,reason:"Client capabilities (sampling) changed"};if("websocket"===b.transport){if(!(a.transport instanceof cK))return{needsNewClient:!0,reason:"Transport type changed to websocket"}}else if("streamable"===b.transport){if(!(a.transport instanceof dO))return{needsNewClient:!0,reason:"Transport type changed to streamable"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"Streamable server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing streamable transport has no config key"};if(e!==eH(b))return{needsNewClient:!0,reason:"Streamable auth/connection parameters changed"}}else if("sse"===b.transport){if(!(a.transport instanceof em))return{needsNewClient:!0,reason:"Transport type changed to sse"};let c=a.transport,d=c._url?.toString();if(void 0!==d&&d!==new URL(b.serverUrl).toString())return{needsNewClient:!0,reason:"SSE server URL changed"};let e=c.__flujoHttpKey;if(!e)return{needsNewClient:!0,reason:"Existing sse transport has no config key"};if(e!==eH(b))return{needsNewClient:!0,reason:"SSE auth/connection parameters changed"}}else{if(!(a.transport instanceof bS))return{needsNewClient:!0,reason:"Transport type changed to stdio"};if("stdio"!==b.transport)return{needsNewClient:!0,reason:"Transport type changed from stdio"};let c=a.transport.__flujoStdioKey;if(!c)return{needsNewClient:!0,reason:"Existing stdio transport has no config key"};if(c!==eG(b))return{needsNewClient:!0,reason:"Connection parameters changed"}}return{needsNewClient:!1}}(a,b);if(!c)return eN.info(`connectServer: Server ${b.name} is already connected`),this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),{success:!0};eN.info(`connectServer: Existing client for ${b.name} is stale (${d}), recreating`),this.deregisterClient(b.name);try{await eL(a,b.name,b)}catch(a){eN.debug(`connectServer: error closing stale client for ${b.name}: ${a instanceof Error?a.message:String(a)}`)}a=void 0}a=eI(b);let c=eJ(b);if(c instanceof bS&&c.stderr){let a=b.name;c.stderr.on("data",b=>{let c=b.toString();eN.warn(`stderr: [${a}]: ${c}`),this.appendStderrLog(a,c)})}return c.onclose=()=>{if(this.activeTransports.get(b.name)!==c)return void eN.debug(`connectServer: ignoring close event from a stale/deregistered transport for ${b.name}`);eN.warn(`connectServer: Connection closed for server ${b.name}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{if(!a||a.disabled)return void eN.info(`Server ${b.name} is now disabled, skipping reconnection logic`);eN.info(`Connection closed for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a)}).catch(a=>{eN.warn(`Error checking server config for ${b.name} during onclose:`,a)})},c.onerror=a=>{if(function(a){let b=a instanceof Error?a.message:String(a);return b.includes("SSE stream disconnected")||b.includes("Failed to reconnect SSE stream")||b.includes("Maximum reconnection attempts")||/\bterminated\b/i.test(b)}(a))return void eN.debug(`connectServer: transient SSE stream disconnect for ${b.name} (self-healing, ignored): ${a instanceof Error?a.message:String(a)}`);if(this.activeTransports.get(b.name)!==c)return void eN.debug(`connectServer: ignoring error event from a stale/deregistered transport for ${b.name}`);if(eN.error(`connectServer: Transport error for server ${b.name}:`),a instanceof Error){eN.error(`Error name: ${a.name}`),eN.error(`Error message: ${a.message}`),eN.error(`Error stack: ${a.stack}`);let b=a.code;void 0!==b&&eN.error(`Error code: ${b}`),eN.error(`Error chain: ${cj(a)}`)}else if(a&&"object"==typeof a){eN.error(`Error type: ${typeof a}`),eN.error(`Error constructor: ${a.constructor?.name||"Unknown"}`);let b=Object.getOwnPropertyNames(a);b.length>0?(eN.error(`Error properties: ${b.join(", ")}`),b.forEach(b=>{try{let c=a[b];eN.error(` ${b}: ${"function"==typeof c?"[Function]":JSON.stringify(c)}`)}catch(a){eN.error(` ${b}: [Unable to serialize: ${a}]`)}})):eN.error("Error object has no enumerable properties");try{let b=JSON.stringify(a);eN.error(`JSON stringified error: ${b}`)}catch(a){eN.error(`Cannot JSON stringify error: ${a}`)}}else eN.error(`Error value: ${String(a)} (type: ${typeof a})`);this.appendStderrLog(b.name,`Transport error: ${cj(a)}`),this.deregisterClient(b.name),this.getServerConfig(b.name).then(a=>{if(!a||a.disabled)return void eN.info(`Server ${b.name} is now disabled, skipping reconnection after transport error`);eN.info(`Transport error for enabled server ${b.name}, scheduling reconnection`),this.scheduleConnectionRetry(b.name,a)}).catch(a=>{eN.warn(`Error checking server config for ${b.name} during onerror:`,a)})},await a.connect(c),this.clients.set(b.name,a),this.activeTransports.set(b.name,c),this.lastConnectionError.delete(b.name),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name),eN.info(`connectServer: Successfully connected to ${b.name}`),{success:!0}}catch(f){eN.error(`connectServer: Failed to connect to server ${b.name}:`,f);let a=f instanceof Error?f.message:String(f),c=f instanceof Error?f.name:"";if(a.includes("OAuth authentication required")||"OAuthAuthenticationRequired"===c){if(eN.info(`OAuth authentication required for server ${b.name}`),"streamable"===b.transport){let a=b;a.authorizationUrl&&eN.info(`Authorization URL available for ${b.name}: ${a.authorizationUrl}`)}return{success:!1,error:a,requiresAuthentication:!0}}if(cm(f)){if(eN.info(`OAuth authentication error detected for server ${b.name}: ${a}`),"streamable"===b.transport){let a=b;if(!a.oauthScopes||0===a.oauthScopes.length){eN.info(`Dynamically enabling OAuth for server ${b.name} due to authentication error`);try{let c={...a,oauthScopes:["read"]},d=await this.loadServerConfigs();if(Array.isArray(d)){let a=d.findIndex(a=>a.name===b.name);-1!==a&&(d[a]=c,await (0,b$.q)(new Map(d.map(a=>[a.name,a]))),eN.info(`Updated config for ${b.name} to enable OAuth`))}}catch(a){eN.warn(`Failed to update config for ${b.name} to enable OAuth:`,a)}}}return{success:!1,error:"OAuth authentication failed or tokens have expired. Please re-authenticate.",requiresAuthentication:!0}}let d=this.stderrLogs.get(b.name)||[],e=ck(f,b,d);return this.lastConnectionError.set(b.name,e),{success:!1,error:e}}finally{this.connectingServers.delete(b.name)}}async testConnection(a,b){eN.info(`testConnection: Testing connection to ${a.name||"(unnamed)"} via ${a.transport} transport`);let c=a=>{try{b?.(a)}catch{}},d=[],e=null,f=null;try{let b,g=await eD(a);e=eI(g),(f=eJ(g))instanceof bS&&f.stderr&&f.stderr.on("data",a=>{let b=a.toString();d.push(b),c({type:"stderr",data:b})}),f.onerror=a=>{let b=`Transport error: ${cj(a)}`;d.push(b),c({type:"stderr",data:b+"\n"})},c({type:"status",phase:"spawning",message:"Starting server / opening transport..."});let h=cv(a)?9e4:15e3,i=cv(a),j=new Promise((a,c)=>{b=setTimeout(()=>c(Error(`Connection timeout after ${h/1e3}s`+(i?" — the package may still be downloading via npx/uvx. Try running the Test again (the package is cached after the first download), or verify the command and network access.":""))),h)});c({type:"status",phase:"handshaking",message:"Performing MCP handshake..."});try{await Promise.race([e.connect(f),j])}finally{b&&clearTimeout(b)}c({type:"status",phase:"listing-tools",message:"Handshake OK — listing tools..."});let k=0;try{let a=await e.listTools();k=Array.isArray(a?.tools)?a.tools.length:0}catch(b){eN.debug(`testConnection: connected to ${a.name} but listTools failed: ${b instanceof Error?b.message:String(b)}`)}return eN.info(`testConnection: Successfully connected to ${a.name} (${k} tools)`),c({type:"result",success:!0,data:{toolCount:k}}),{success:!0,data:{toolCount:k}}}catch(f){eN.warn(`testConnection: Failed to connect to ${a.name}:`,f);let b=cm(f),e=ck(f,a,d);return c({type:"result",success:!1,error:e,requiresAuthentication:b}),{success:!1,error:e,requiresAuthentication:b}}finally{if(e)try{await eL(e,a.name,a,{gracePeriodMs:3e3,killEscalationMs:2e3})}catch(b){eN.debug(`testConnection: error closing test client for ${a.name}: ${b instanceof Error?b.message:String(b)}`)}}}setNodeRoots(a,b,c){for(let d of function(a,b,c){let d=(c??[]).filter(a=>"string"==typeof a&&a.trim().length>0),e=es().get(b),f=new Set([a]);e&&f.add(e.serverName);let g=new Map;for(let a of f)g.set(a,et(a));0===d.length?es().delete(b)&&er.debug(`Cleared node roots for node ${b}`):(es().set(b,{serverName:a,roots:d}),er.debug(`Registered ${d.length} node root(s) for node ${b} on server ${a}`));let h=[];for(let a of f){let b=et(a),c=g.get(a)??[];(b.length!==c.length||b.some((a,b)=>a!==c[b]))&&h.push(a)}return h}(a,b,c))this.notifyRootsChanged(d)}notifyRootsChanged(a){let b=this.getClient(a);if(!b)return void eN.debug(`notifyRootsChanged: ${a} not connected, skipping notification`);try{b.sendRootsListChanged().catch(b=>{eN.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}),eN.debug(`notifyRootsChanged: sent roots/list_changed to ${a}`)}catch(b){eN.warn(`notifyRootsChanged: failed to notify ${a}:`,b)}}async disconnectServer(a){if(eN.debug(`disconnectServer: Entering method for server ${a}`),await this.isInternalServer(a))return{success:!0};this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a);let b=this.getClient(a);if(!b)return eN.warn(`disconnectServer: Server ${a} not found in clients map`),this.deregisterClient(a),{success:!1,error:`Server ${a} not found`};this.deregisterClient(a);try{let c=await this.getServerConfig(a);return await eL(b,a,c||void 0),eN.info(`disconnectServer: Disconnected server ${a}`),{success:!0}}catch(b){return eN.warn(`disconnectServer: Failed to disconnect server ${a}:`,b),{success:!1,error:`Failed to disconnect server: ${b instanceof Error?b.message:"Unknown error"}`}}}async forceReconnect(a){if(eN.info(`forceReconnect: Forcing fresh connection for server ${a}`),await this.isInternalServer(a))return{success:!0};let b=this.clients.get(a);if(b){this.deregisterClient(a);let c=await this.getServerConfig(a);try{await eL(b,a,c||void 0)}catch(b){eN.debug(`forceReconnect: error closing stale client for ${a}: ${b instanceof Error?b.message:String(b)}`)}}return this.connectServer(a)}async listServerTools(a){if(eN.debug(`listServerTools: Entering method for server ${a}`),await this.isInternalServer(a)){let{internalToolDefinitions:a}=await Promise.all([c.e(3304),c.e(6936),c.e(6195)]).then(c.bind(c,76195));return{tools:a()}}if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return eN.warn(`listServerTools: ${b}`),{tools:[],error:b}}let b=this.getClient(a);b||eN.warn(`listServerTools: Client not found for ${a}`);let d=await b2(b,a);if(d.error){eN.warn(`listServerTools: Listing tools for ${a} failed (${d.error}); forcing reconnect and retrying once`);let c=await this.forceReconnect(a);if(!c.success)return eN.warn(`listServerTools: Reconnect for ${a} failed: ${c.error}`),{tools:[],error:c.error||d.error};b=this.clients.get(a),(d=await b2(b,a)).error?eN.warn(`listServerTools: Retry after reconnect still failed for ${a}:`,d.error):eN.info(`listServerTools: Recovered after reconnect for ${a}; listed ${d.tools.length} tools`)}else eN.info(`listServerTools: Listed ${d.tools.length} tools for ${a}`);return d}async callTool(a,b,d,e,f){if(eN.debug(`callTool: Entering method for server ${a}, tool ${b}`),await this.isInternalServer(a)){let{internalCallTool:a}=await Promise.all([c.e(3304),c.e(6936),c.e(6195)]).then(c.bind(c,76195)),e=await a(this,b,d);return eN.info(`callTool: Dispatched internal tool ${b}`),{success:!0,data:e}}if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return eN.warn(`callTool: ${b}`),{success:!1,error:b}}let g=this.getClient(a);if(!g){eN.warn(`callTool: No client for ${a}; forcing reconnect before calling ${b}`);let c=await this.forceReconnect(a);c.success?g=this.clients.get(a):eN.warn(`callTool: Reconnect for ${a} failed: ${c.error}`)}let h=await b3(g,a,b,d,e,f);return eN.info(`callTool: Called tool ${b} on ${a}`),h}async listWithReconnect(a,b,c){if(await this.isInternalServer(a))return c;if(await this.isServerDisabled(a)){let b=`Server '${a}' is disabled. Enable it on the MCP page to use it.`;return eN.warn(`listWithReconnect: ${b}`),{...c,error:b}}let d=this.getClient(a);d||eN.warn(`listWithReconnect: Client not found for ${a}`);let e=await b(d,a);if(!e.error)return e;eN.warn(`listWithReconnect: Listing for ${a} failed (${e.error}); forcing reconnect and retrying once`);let f=await this.forceReconnect(a);return f.success?(d=this.clients.get(a),(e=await b(d,a)).error?eN.warn(`listWithReconnect: Retry after reconnect still failed for ${a}:`,e.error):eN.info(`listWithReconnect: Recovered after reconnect for ${a}`),e):(eN.warn(`listWithReconnect: Reconnect for ${a} failed: ${f.error}`),{...c,error:f.error||e.error})}async listServerResources(a){return eN.debug(`listServerResources: Entering method for server ${a}`),this.listWithReconnect(a,b5,{resources:[]})}async listServerResourceTemplates(a){return eN.debug(`listServerResourceTemplates: Entering method for server ${a}`),this.listWithReconnect(a,b6,{resourceTemplates:[]})}async readResource(a,b){eN.debug(`readResource: Entering method for server ${a}, uri ${b}`);let c=this.getClient(a);c||eN.warn(`readResource: Client not found for ${a}`);let d=await b7(c,a,b);return eN.info(`readResource: Read resource ${b} on ${a}`),d}async listServerPrompts(a){return eN.debug(`listServerPrompts: Entering method for server ${a}`),this.listWithReconnect(a,b9,{prompts:[]})}async getPrompt(a,b,c){eN.debug(`getPrompt: Entering method for server ${a}, prompt ${b}`);let d=this.getClient(a);d||eN.warn(`getPrompt: Client not found for ${a}`);let e=await ca(d,a,b,c);return eN.info(`getPrompt: Got prompt ${b} on ${a}`),e}async resolveOAuthSecretForSave(a,b){return a===co.RJ?b??"":a?a.startsWith("${global:")||a.startsWith("encrypted:")||a.startsWith("encrypted_failed:")?a:await (0,cn.Rs)(a):""}async resolveHeadersForSave(a,b){let c={};for(let[d,e]of Object.entries(a||{})){if(!d)continue;let{value:a,isSecret:f}=cq(e,d);if(!f){""!==a&&(c[d]={value:a,metadata:{isSecret:!1}});continue}if(a===co.RJ||a===co.gF){let a=b?.[d];void 0!==a&&(c[d]=a);continue}if(a){if("string"==typeof a&&a.startsWith("${global:")||a.startsWith("encrypted:")||a.startsWith("encrypted_failed:")){c[d]={value:a,metadata:{isSecret:!0}};continue}c[d]={value:await (0,cn.Rs)(a),metadata:{isSecret:!0}}}}return c}async ensureRemoteServerRootDir(a){try{if(!["streamable","sse","websocket"].includes(a.transport))return;let b=(a.rootPath||"").trim();if(!b)return;let c=bX().resolve((0,bZ.ok)(),b);if(bX().dirname(c)===c)return;await bV().mkdir(c,{recursive:!0}),eN.debug(`ensureRemoteServerRootDir: ensured ${c} for ${a.name}`)}catch(b){eN.warn(`ensureRemoteServerRootDir: could not create root dir for ${a.name}:`,b)}}async updateServerConfig(a,b){if(eN.debug(`updateServerConfig: Entering method for server ${a}`),await this.isInternalServer(a))return{success:!1,error:`"${eM._}" is FLUJO's built-in server and cannot be created or edited.`};let c=await this.loadServerConfigs();if(!Array.isArray(c))return eN.warn("updateServerConfig: Failed to load configs:",c.error),c;let d=c.find(b=>b.name===a),e=!!d&&"string"==typeof b.name&&b.name!==a;if(e&&c.some(a=>a.name===b.name))return eN.warn(`updateServerConfig: Refusing to rename ${a} -> ${b.name}: name already in use`),{success:!1,error:`A server named "${b.name}" already exists`};if(!d&&b.name)eN.info(`updateServerConfig: Creating new server config for ${b.name}`),d={name:b.name,transport:"stdio",command:"",args:[],env:{},disabled:!1,autoApprove:[],_buildCommand:"",_installCommand:"",rootPath:""},c.push(d);else if(!d)return eN.warn(`updateServerConfig: Server ${a} not found`),{success:!1,error:`Server ${a} not found`};if(b.env){eN.debug(`updateServerConfig: Resolving global variables in env for ${a}`);try{eN.debug(`Original env variables for ${a}:`,JSON.stringify(b.env,null,2)),b.env=await (0,b_.c)(b.env),eN.debug(`Resolved env variables for ${a}:`,JSON.stringify(b.env,null,2)),eN.debug(`updateServerConfig: Successfully resolved global variables for ${a}`)}catch(b){eN.warn(`updateServerConfig: Error resolving global variables for ${a}:`,b)}}let f=b.oauthClientSecret;if(void 0!==f){let a=d.oauthClientSecret;b.oauthClientSecret=await this.resolveOAuthSecretForSave(f,a)}let g=b.headers;if(void 0!==g){let a=d.headers;b.headers=await this.resolveHeadersForSave(g,a)}let h={...d};h={...d,...b};let i=JSON.stringify(d.roots??[])!==JSON.stringify(h.roots??[])||(d.rootPath??"")!==(h.rootPath??""),j=c.findIndex(b=>b.name===a);-1!==j?c[j]=h:h.name&&c.push(h);let k=await (0,b$.q)(new Map(c.map(a=>[a.name,a])));return k.success?(await this.ensureRemoteServerRootDir(h),e?(this.clients.has(a)?await this.disconnectServer(a):(this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a)),this.stderrLogs.delete(a),this.lastConnectionError.delete(a),await this.handleConnectionStateChange(h.name,h)):await this.handleConnectionStateChange(a,h),i&&this.notifyRootsChanged(h.name),eN.info(`updateServerConfig: Successfully updated config for ${a}${e?` (renamed to ${h.name})`:""}`),h):(eN.warn(`updateServerConfig: Failed to save config for ${a}:`,k.error),k)}async handleConnectionStateChange(a,b){eN.debug(`handleConnectionStateChange: Entering method for server ${a}`);let c=!!this.getClient(a),d=!b.disabled;if(c&&!d){eN.info(`handleConnectionStateChange: Disconnecting disabled server ${a}`);try{await this.disconnectServer(a)}catch(b){eN.warn(`handleConnectionStateChange: Failed to disconnect server ${a} during update:`,b)}}else!c&&d?(eN.info(`handleConnectionStateChange: Connecting previously disabled server ${a}`),await this.connectServer(b)):c&&d?(eN.info(`handleConnectionStateChange: Re-applying config to connected server ${a}`),await this.connectServer(b)):d||(eN.info(`handleConnectionStateChange: Clearing retry timers for disabled server ${a}`),this.clearRetryTimer(a),this.connectionRetryAttempts.delete(a))}async clearRetryTimersForDisabledServers(){eN.debug("clearRetryTimersForDisabledServers: Checking for disabled servers with active retry timers");try{let a=await this.loadServerConfigs();if(!Array.isArray(a))return void eN.warn("clearRetryTimersForDisabledServers: Failed to load server configs");for(let b of a.filter(a=>a.disabled))this.connectionRetryTimers.has(b.name)&&(eN.info(`clearRetryTimersForDisabledServers: Clearing retry timer for disabled server ${b.name}`),this.clearRetryTimer(b.name),this.connectionRetryAttempts.delete(b.name))}catch(a){eN.error("clearRetryTimersForDisabledServers: Error clearing retry timers:",a)}}async deleteServerConfig(a){if(eN.debug(`deleteServerConfig: Entering method for server ${a}`),await this.isInternalServer(a))return{success:!1,error:`"${eM._}" is FLUJO's built-in server and cannot be deleted.`};this.clients.has(a)&&(eN.info(`deleteServerConfig: Disconnecting server ${a} before deletion`),await this.disconnectServer(a));let b=await this.loadServerConfigs();if(!Array.isArray(b))return eN.warn("deleteServerConfig: Failed to load configs:",b.error),b;let c=b.findIndex(b=>b.name===a);if(-1===c)return eN.warn(`deleteServerConfig: Server ${a} not found in configs`),{success:!1,error:`Server ${a} not found`};b.splice(c,1),eN.debug(`deleteServerConfig: Saving updated configs after deleting ${a}`);let d=await (0,b$.q)(new Map(b.map(a=>[a.name,a])));return d.success?eN.info(`deleteServerConfig: Successfully deleted server ${a}`):eN.warn(`deleteServerConfig: Error saving configs after deleting ${a}:`,d.error),d}async getServerStatus(a){if(await this.isInternalServer(a))return{status:"connected"};let b=await this.getServerConfig(a);if(!b)return eN.warn(`getServerStatus: Server ${a} not found`),{status:"error",message:`Server ${a} configuration not found. The server may have been deleted or not properly configured.`};if(b.disabled)return eN.debug(`getServerStatus: Server ${a} is disabled`),{status:"disconnected"};if("streamable"===b.transport&&b.oauthScopes&&b.oauthScopes.length>0){if(!b.oauthTokens||!b.oauthTokens.access_token)return eN.info(`getServerStatus: Server ${a} requires OAuth authentication but has no valid tokens`),{status:"requires_authentication",message:"OAuth authentication required. Click the authenticate button to complete the OAuth flow."};if(!b.oauthTokens.refresh_token&&b.oauthTokens.expires_in&&b.oauthTokens.issued_at){let c=b.oauthTokens.issued_at,d=b.oauthTokens.expires_in;if(Math.floor(Date.now()/1e3)>=c+d)return eN.info(`getServerStatus: OAuth tokens for ${a} have expired and no refresh token is available`),{status:"requires_authentication",message:"OAuth tokens have expired. Please re-authenticate."}}}let c=(this.stderrLogs.get(a)||[]).join("\n").trim(),d=this.lastConnectionError.get(a);if(this.getClient(a))return eN.info(`getServerStatus: Server ${a} is connected`),{status:"connected",stderrOutput:c||void 0};{let b=this.isStartingUp()&&!this.lastConnectionError.has(a);if(this.connectingServers.has(a)||b)return eN.info(`getServerStatus: Server ${a} is still connecting`),{status:"connecting",message:"Server is starting up. This may take a few moments."};if(c&&(c.includes("OAuth authentication required")||c.includes("invalid_token")))return eN.info(`getServerStatus: OAuth authentication error detected for ${a}`),{status:"requires_authentication",message:"OAuth authentication required. Please complete the OAuth flow.",stderrOutput:c};let e=c||d;return e?(eN.info(`getServerStatus: Using ${c?"stderr output":"persisted connection error"} as error message for ${a}`),{status:"error",message:e,stderrOutput:c||void 0}):(eN.info(`getServerStatus: No specific error details available for ${a}`),{status:"error",message:`Server ${a} is configured but not connected. The server process may have crashed or been terminated.`,stderrOutput:void 0})}}async startEnabledServers(){eN.info("Starting all enabled servers"),this.setStartingUp(!0);try{await this.clearRetryTimersForDisabledServers();let a=await this.loadServerConfigs();if(!Array.isArray(a))return void eN.warn("Failed to load server configs, cannot start servers");let b=a.filter(a=>!a.disabled);eN.info(`Found ${b.length} enabled servers to start`),eN.debug(`${b}`),b.forEach(a=>this.connectingServers.add(a.name)),await Promise.all(b.map(a=>(eN.info(`Starting server: ${a.name}`),this.connectServer(a).catch(b=>{eN.error(`Failed to start server ${a.name}:`,b)}))))}finally{this.setStartingUp(!1)}}async getAvailableClients(){try{let a=await this.loadServerConfigs();if(!a||"error"in a)return eN.warn("getAvailableClients: Failed to load server configs:",a?.error),[];return(await Promise.all(a.map(async a=>{try{let b=await this.getServerStatus(a.name);return{name:a.name,status:"string"==typeof b?b:b.status,connected:"string"==typeof b?"connected"===b:"connected"===b.status}}catch(b){return eN.warn(`getAvailableClients: Error getting status for ${a.name}:`,b),{name:a.name,status:"error",connected:!1}}}))).map(a=>`${a.name} (${a.status})`)}catch(a){return eN.error("getAvailableClients: Error getting available clients:",a),[]}}constructor(){this.stderrLogs=new Map,this.lastConnectionError=new Map,this.inFlightConnects=new Map,this.connectionRetryTimers=new Map,this.connectionRetryAttempts=new Map}}let eP=new eO},99925:(a,b,c)=>{"use strict";let d=c(67729),e=c(97161),f=c(24860),g=e.implSymbol;function h(b){if(!this||this[g]||!(this instanceof h))throw TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");if(arguments.length<1)throw TypeError("Failed to construct 'URL': 1 argument required, but only "+arguments.length+" present.");let c=[];for(let a=0;a<arguments.length&&a<2;++a)c[a]=arguments[a];c[0]=d.USVString(c[0]),void 0!==c[1]&&(c[1]=d.USVString(c[1])),a.exports.setup(this,c)}h.prototype.toJSON=function(){if(!this||!a.exports.is(this))throw TypeError("Illegal invocation");let b=[];for(let a=0;a<arguments.length&&a<0;++a)b[a]=arguments[a];return this[g].toJSON.apply(this[g],b)},Object.defineProperty(h.prototype,"href",{get(){return this[g].href},set(a){a=d.USVString(a),this[g].href=a},enumerable:!0,configurable:!0}),h.prototype.toString=function(){if(!this||!a.exports.is(this))throw TypeError("Illegal invocation");return this.href},Object.defineProperty(h.prototype,"origin",{get(){return this[g].origin},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"protocol",{get(){return this[g].protocol},set(a){a=d.USVString(a),this[g].protocol=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"username",{get(){return this[g].username},set(a){a=d.USVString(a),this[g].username=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"password",{get(){return this[g].password},set(a){a=d.USVString(a),this[g].password=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"host",{get(){return this[g].host},set(a){a=d.USVString(a),this[g].host=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"hostname",{get(){return this[g].hostname},set(a){a=d.USVString(a),this[g].hostname=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"port",{get(){return this[g].port},set(a){a=d.USVString(a),this[g].port=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"pathname",{get(){return this[g].pathname},set(a){a=d.USVString(a),this[g].pathname=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"search",{get(){return this[g].search},set(a){a=d.USVString(a),this[g].search=a},enumerable:!0,configurable:!0}),Object.defineProperty(h.prototype,"hash",{get(){return this[g].hash},set(a){a=d.USVString(a),this[g].hash=a},enumerable:!0,configurable:!0}),a.exports={is:a=>!!a&&a[g]instanceof f.implementation,create(a,b){let c=Object.create(h.prototype);return this.setup(c,a,b),c},setup(a,b,c){c||(c={}),c.wrapper=a,a[g]=new f.implementation(b,c),a[g][e.wrapperSymbol]=a},interface:h,expose:{Window:{URL:h},Worker:{URL:h}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<!DOCTYPE html><!--
|
|
1
|
+
<!DOCTYPE html><!--z7fsG7kblb_yxkUhOxn_G--><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/css/d1484588c616b291.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-4015bd6f241940a1.js"/><script src="/_next/static/chunks/4bd1b696-182b6b13bdad92e3.js" async=""></script><script src="/_next/static/chunks/1255-13d973e0759ea6d6.js" async=""></script><script src="/_next/static/chunks/main-app-faff38c77cb00119.js" async=""></script><script src="/_next/static/chunks/app/layout-2878f13d7e253503.js" async=""></script><meta name="robots" content="noindex"/><title>FLUJO</title><meta name="description" content="A browser-based application for managing models, MCP servers, flows and chat interactions"/><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body class="__variable_246ccd __variable_c29908 antialiased"><div hidden=""><!--$--><!--/$--></div><!--$--><!--$!--><template data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING"></template><div>Loading theme...</div><!--/$--><!--/$--><script src="/_next/static/chunks/webpack-4015bd6f241940a1.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[72403,[\"7177\",\"static/chunks/app/layout-2878f13d7e253503.js\"],\"default\"]\n3:I[9766,[],\"\"]\n4:I[98924,[],\"\"]\n5:I[24431,[],\"OutletBoundary\"]\n7:I[15278,[],\"AsyncMetadataOutlet\"]\n9:I[24431,[],\"ViewportBoundary\"]\nb:I[24431,[],\"MetadataBoundary\"]\nc:\"$Sreact.suspense\"\ne:I[57150,[],\"\"]\n:HL[\"/_next/static/css/d1484588c616b291.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"b\":\"z7fsG7kblb_yxkUhOxn-G\",\"p\":\"\",\"c\":[\"\",\"_not-found\"],\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],[\"\",[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/css/d1484588c616b291.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__variable_246ccd __variable_c29908 antialiased\",\"children\":[\"$\",\"$L2\",null,{\"children\":[\"$\",\"$L3\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L4\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]}]}]]}],{\"children\":[\"/_not-found\",[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L3\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L4\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[\"__PAGE__\",[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L5\",null,{\"children\":[\"$L6\",[\"$\",\"$L7\",null,{\"promise\":\"$@8\"}]]}]]}],{},null,false]},null,false]},null,false],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[[\"$\",\"$L9\",null,{\"children\":\"$La\"}],null],[\"$\",\"$Lb\",null,{\"children\":[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$c\",null,{\"fallback\":null,\"children\":\"$Ld\"}]}]}]]}],false]],\"m\":\"$undefined\",\"G\":[\"$e\",[]],\"s\":false,\"S\":true}\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n6:null\n"])</script><script>self.__next_f.push([1,"8:{\"metadata\":[[\"$\",\"title\",\"0\",{\"children\":\"FLUJO\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"A browser-based application for managing models, MCP servers, flows and chat interactions\"}]],\"error\":null,\"digest\":\"$undefined\"}\n"])</script><script>self.__next_f.push([1,"d:\"$8:metadata\"\n"])</script></body></html>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<!DOCTYPE html><html><head><meta charSet="utf-8" data-next-head=""/><meta name="viewport" content="width=device-width" data-next-head=""/><title data-next-head="">500: Internal Server Error</title><noscript data-n-css=""></noscript><script defer="" noModule="" src="/_next/static/chunks/polyfills-42372ed130431b0a.js"></script><script src="/_next/static/chunks/webpack-4015bd6f241940a1.js" defer=""></script><script src="/_next/static/chunks/framework-1548034a53843b9f.js" defer=""></script><script src="/_next/static/chunks/main-be8e823624954fab.js" defer=""></script><script src="/_next/static/chunks/pages/_app-e8b861c87f6f033c.js" defer=""></script><script src="/_next/static/chunks/pages/_error-c8f84f7bd11d43d4.js" defer=""></script><script src="/_next/static/
|
|
1
|
+
<!DOCTYPE html><html><head><meta charSet="utf-8" data-next-head=""/><meta name="viewport" content="width=device-width" data-next-head=""/><title data-next-head="">500: Internal Server Error</title><noscript data-n-css=""></noscript><script defer="" noModule="" src="/_next/static/chunks/polyfills-42372ed130431b0a.js"></script><script src="/_next/static/chunks/webpack-4015bd6f241940a1.js" defer=""></script><script src="/_next/static/chunks/framework-1548034a53843b9f.js" defer=""></script><script src="/_next/static/chunks/main-be8e823624954fab.js" defer=""></script><script src="/_next/static/chunks/pages/_app-e8b861c87f6f033c.js" defer=""></script><script src="/_next/static/chunks/pages/_error-c8f84f7bd11d43d4.js" defer=""></script><script src="/_next/static/z7fsG7kblb_yxkUhOxn-G/_buildManifest.js" defer=""></script><script src="/_next/static/z7fsG7kblb_yxkUhOxn-G/_ssgManifest.js" defer=""></script></head><body><div id="__next"><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div style="line-height:48px"><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding-right:23px;font-size:24px;font-weight:500;vertical-align:top">500</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:28px">Internal Server Error<!-- -->.</h2></div></div></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{},"buildId":"z7fsG7kblb_yxkUhOxn-G","nextExport":true,"isFallback":false,"gip":true,"scriptLoader":[]}</script></body></html>
|