@beepflow/mcp 2026.7.0 → 2026.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ var tR=Object.create;var nh=Object.defineProperty;var nR=Object.getOwnPropertyDe
11
11
  `)}catch{}}}function s(p){for(i+=p;;){let m=i.indexOf(`
12
12
  `);if(m===-1)return;let g=i.slice(0,m).trim();if(i=i.slice(m+1),!g)continue;let b;try{b=JSON.parse(g)}catch{continue}c(b)}}async function c(p){if(r)return;let m=p.id===void 0,g=p.id??null;try{switch(p.method){case"initialize":{let w={protocolVersion:(p.params??{}).protocolVersion??"2024-11-05",serverInfo:{name:e.serverName,version:e.serverVersion},capabilities:{tools:{},resources:{}},...e.instructions?{instructions:e.instructions}:{}};if(m)return;d({jsonrpc:"2.0",id:g,result:w});return}case"notifications/initialized":{e.onInitialized?.();return}case"notifications/cancelled":return;case"logging/setLevel":{if(m)return;d({jsonrpc:"2.0",id:g,result:{}});return}case"ping":{if(m)return;d({jsonrpc:"2.0",id:g,result:{}});return}case"tools/list":{if(m)return;let b=e.tools.map(h=>({name:h.name,description:h.description,inputSchema:h.inputSchema}));d({jsonrpc:"2.0",id:g,result:{tools:b}});return}case"tools/call":{if(m)return;let b=p.params??{},h=typeof b.name=="string"?b.name:"",w=t.get(h);if(!w){d({jsonrpc:"2.0",id:g,error:{code:-32601,message:`unknown tool: ${h}`}});return}let l=await w.call(b.arguments);d({jsonrpc:"2.0",id:g,result:l});return}case"resources/list":{if(m)return;let b=(e.resources??[]).map(h=>({uri:h.uri,name:h.name,description:h.description,mimeType:h.mimeType}));d({jsonrpc:"2.0",id:g,result:{resources:b}});return}case"resources/read":{if(m)return;let b=p.params??{},h=typeof b.uri=="string"?b.uri:"",w=n.get(h);if(!w){d({jsonrpc:"2.0",id:g,error:{code:-32602,message:`unknown resource: ${h}`}});return}let l=await w.read();d({jsonrpc:"2.0",id:g,result:l});return}case"prompts/list":{if(m)return;d({jsonrpc:"2.0",id:g,result:{prompts:[]}});return}default:{if(m)return;d({jsonrpc:"2.0",id:g,error:{code:-32601,message:`method not found: ${p.method}`}})}}}catch(b){if(m)return;d({jsonrpc:"2.0",id:g,error:{code:-32603,message:b?.message??"internal error"}})}}function d(p){r||ih.write(JSON.stringify(p)+`
13
13
  `)}return{server:o,closeServer:a}}import{createHash as f4}from"node:crypto";import uh from"node:os";import ps from"node:path";var sR={dev:{name:"dev",frontendUrl:"http://localhost:21073",backendUrl:"http://localhost:2451/api",authUrl:"https://auth.beepflow.com",fileUrl:"https://file.fewlogs.com",authDomain:"beepflow.com"},live:{name:"live",frontendUrl:"https://beepflow.com",backendUrl:"https://beepflow.com/api",authUrl:"https://auth.beepflow.com",fileUrl:"https://file.fewlogs.com",authDomain:"beepflow.com"}};function uR(e){let n=ah(e,"--env")??ah(e,"--environment")??process.env.BEEPFLOW_ENV??"live";if(n==="dev"||n==="live")return n;throw new Error(`invalid BEEPFLOW_ENV: ${n}`)}function sh(e){let t=uR(e);return sR[t]}function ah(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];if(r===t){let o=e[n+1];if(!o)throw new Error(`missing value for ${t}`);return o}let i=`${t}=`;if(r&&r.startsWith(i)){let o=r.slice(i.length);if(!o)throw new Error(`missing value for ${t}`);return o}}}function Ht(){let e=process.argv.slice(2),t=sh(e),n=pu("backend url",[Wo(e,"--backend-url"),process.env.BEEPFLOW_BACKEND_URL,t.backendUrl]),r=pu("frontend url",[Wo(e,"--frontend-url"),process.env.BEEPFLOW_FRONTEND_URL,t.frontendUrl]),i=pu("auth url",[Wo(e,"--auth-url"),process.env.BEEPFLOW_AUTH_URL,t.authUrl]),o=pu("file url",[Wo(e,"--file-url"),process.env.BEEPFLOW_FILE_URL,t.fileUrl]),a=pu("auth domain",[Wo(e,"--auth-domain"),process.env.BEEPFLOW_AUTH_DOMAIN,t.authDomain]),s=Wo(e,"--token-store-path")??process.env.BEEPFLOW_TOKEN_STORE_PATH??cR(),c=Wo(e,"--replicated-state-db-path")??process.env.BEEPFLOW_REPLICATED_STATE_DB_PATH??lR();return{environmentName:t.name,frontendUrl:r.replace(/\/+$/,""),backendUrl:n.replace(/\/+$/,""),authUrl:i.replace(/\/+$/,""),fileUrl:o.replace(/\/+$/,""),authDomain:a,jwtFromEnvironment:Wo(e,"--jwt")??process.env.BEEPFLOW_JWT,tokenStorePath:s,replicatedStateDatabasePath:c}}function Wo(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];if(r===t){let o=e[n+1];if(!o)throw new Error(`missing value for ${t}`);return o}let i=`${t}=`;if(r&&r.startsWith(i)){let o=r.slice(i.length);if(!o)throw new Error(`missing value for ${t}`);return o}}}function cR(){let e=process.env.APPDATA;if(e)return ps.join(e,"beepflow-mcp","backend-access-token.json");let t=process.env.XDG_CONFIG_HOME;return t?ps.join(t,"beepflow-mcp","backend-access-token.json"):ps.join(uh.homedir(),".config","beepflow-mcp","backend-access-token.json")}function lR(){let e=process.env.LOCALAPPDATA;if(e)return ps.join(e,"beepflow-mcp","replicated-state.sqlite");let t=process.env.XDG_CACHE_HOME;return t?ps.join(t,"beepflow-mcp","replicated-state.sqlite"):ps.join(uh.homedir(),".cache","beepflow-mcp","replicated-state.sqlite")}function pu(e,t){for(let n of t)if(typeof n=="string"&&n.trim())return n;throw new Error(`missing ${e}`)}import Ic from"node:fs/promises";import pR from"node:path";import fR from"node:crypto";function Oo(e){let t=e.split(".");if(t.length<2)return{accessToken:e,email:void 0,exp:void 0,provider:void 0};let n=dR(t[1]??"");if(!n)return{accessToken:e,email:void 0,exp:void 0,provider:void 0};let r;try{r=JSON.parse(n)}catch{return{accessToken:e,email:void 0,exp:void 0,provider:void 0}}let i=typeof r.email=="string"?r.email.toLowerCase():void 0,o=typeof r.exp=="number"?r.exp:void 0,a=typeof r.provider=="string"?r.provider:void 0;return{accessToken:e,email:i,exp:o,provider:a}}function ch(e){return e?e.length<=12?`${e.slice(0,4)}\u2026`:`${e.slice(0,6)}\u2026${e.slice(-4)}`:""}function xc(){return fR.randomBytes(9).toString("base64url")}function dR(e){if(!e)return;let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,r=t+"=".repeat(n);try{return Buffer.from(r,"base64").toString("utf8")}catch{return}}async function fi(){let e=Ht();return e.jwtFromEnvironment?e.jwtFromEnvironment:(await fh(e.tokenStorePath))?.accessToken}async function ms(e){let t=Ht(),n=Oo(e),r={accessToken:e,email:n.email,provider:n.provider,exp:n.exp};return await mR(t.tokenStorePath,r),r}async function lh(){let e=Ht(),t=await fh(e.tokenStorePath)!==void 0;return await Ic.rm(e.tokenStorePath,{force:!0}),{backendUrl:e.backendUrl,deleted:t}}function Pc(e){return{email:e.email,provider:e.provider,exp:e.exp,accessToken:ch(e.accessToken)}}async function fh(e){try{let t=await Ic.readFile(e,"utf8"),n=JSON.parse(t);return!n||typeof n!="object"||typeof n.accessToken!="string"?void 0:n}catch{return}}async function mR(e,t){await Ic.mkdir(pR.dirname(e),{recursive:!0}),await Ic.writeFile(e,JSON.stringify(t,null,2)+`
14
- `,"utf8")}async function dh(e){let t=Ht(),n=await fetch(`${t.authUrl}/email/request-code`,{method:"POST",headers:{"content-type":"application/json",domain:t.authDomain},body:JSON.stringify({email:e})});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`email/request-code failed: ${n.status} ${r}`.trim())}}async function ph(e,t){let n=Ht(),r=await fetch(`${n.authUrl}/email/verify-code`,{method:"POST",headers:{"content-type":"application/json",domain:n.authDomain},body:JSON.stringify({email:e,code:t})}),i=await r.json().catch(()=>{});if(!r.ok)throw new Error(`email/verify-code failed: ${r.status}`);let o=typeof i?.access_token=="string"?i.access_token:"";if(!o)throw new Error("email/verify-code failed: missing access_token");let a=await ms(o);return{backendUrl:n.backendUrl,...Pc(a)}}import hR from"node:crypto";import{spawn as _R}from"node:child_process";import{setTimeout as gR}from"node:timers/promises";async function mh(){let e=await bR(),t=Date.now()+12e4;for(;Date.now()<t;){let n=await vR(e.requestId);if(n.status!=="pending")return{...e,...n};await gR(1500)}return{...e,status:"pending",message:"Timed out waiting for Google sign-in. Run auth_google_sign_in again to retry."}}async function bR(){let e=Ht(),t=hR.randomUUID(),n=new URL(`${e.authUrl}/google-form`);return n.searchParams.set("requestId",t),n.searchParams.set("scopes","openid email profile"),n.searchParams.set("domain",e.authDomain),{requestId:t,url:n.toString(),browserOpened:SR(n.toString())}}async function vR(e){let t=Ht(),n=new URL(`${t.authUrl}/google-auth-token`);n.searchParams.set("id",e);let r=await fetch(n.toString(),{headers:{domain:t.authDomain}}),i=await r.json().catch(()=>{});if(r.status===400&&i?.error==="Token not found")return{status:"pending",requestId:e};if(!r.ok)return{status:"failed",requestId:e,message:`google-auth-token failed: ${r.status}`};let o=typeof i?.access_token=="string"?i.access_token:"";if(!o)return{status:"pending",requestId:e};let a=await ms(o);return{status:"authenticated",requestId:e,backendUrl:t.backendUrl,...Pc(a)}}function SR(e){let t="xdg-open",n=[e];switch(process.platform){case"darwin":t="open";break;case"win32":t="rundll32",n=["url.dll,FileProtocolHandler",e];break}try{let r=_R(t,n,{detached:!0,stdio:"ignore"});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}async function di(e){let t=Oo(e);if(t.provider!=="google"||!t.exp)return e;let n=Date.now(),r=t.exp*1e3,i=300*1e3;if(r-n>=i)return e;let o=Ht(),a=await fetch(`${o.authUrl}/google-refresh`,{method:"GET",headers:{Authorization:`Bearer ${e}`,domain:o.authDomain}}),s=await a.json().catch(()=>{});if(!a.ok)return e;let c=typeof s?.access_token=="string"?s.access_token:"";return c?(await ms(c),c):e}var hh={allowedConnectionTypes:["BaseEvent","BaseLookup","BaseVector","BaseWarehouse","DiscordChannelWebhook","Gorgias","GoogleDrive","GoogleSheets","JudgeMe","LMStudio","OpenRouter","DiscordBot","Shopify"],allowedBlueprintResourceTypes:["BaseEventCollection","BaseLookupCollection","BaseVectorCollection","BaseWarehouseCollection","GoogleDriveFile","GorgiasEvent","GorgiasTicket","JudgeMeReview"],hasFullWorkspaceAccess:!1},yR={allowedConnectionTypes:"all",allowedBlueprintResourceTypes:"all",hasFullWorkspaceAccess:!0},ER={"javioverflow@gmail.com":yR};function Gf(e){return e?ER[e.toLowerCase()]??hh:hh}function hs(e,t){return e.allowedConnectionTypes==="all"?!0:e.allowedConnectionTypes.includes(t)}function Nc(e,t){return t==="ManualTick"||e.allowedBlueprintResourceTypes==="all"?!0:e.allowedBlueprintResourceTypes.includes(t)}async function _h(){let e=await fi();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let t=await di(e),n=Oo(t).email;if(!n)throw new Error("current jwt does not include email");return n}async function po(){let e=await fi();if(!e)return Gf(void 0);let t=await di(e);return Gf(Oo(t).email)}async function wa(e){if(!hs(await po(),e))throw new Error(`integration type is not enabled for current user: ${e}`)}async function Fc(e){if(!Nc(await po(),e))throw new Error(`blueprint resource type is not enabled for current user: ${e}`)}async function gh(e){if(!(await po()).hasFullWorkspaceAccess)throw new Error(`full workspace access is required for resource: ${e}`)}function Mc(e,t){let n=t.split("/")[0];return n==="Base"||hs(e,n)}async function bh(e){let t=Ht(),n=await fetch(`${t.backendUrl}/users/is-member`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`users/is-member failed: ${n.status} ${i}`.trim())}if((await n.json().catch(()=>{}))?.isMember!==!0)throw new Error("user not member of workspace")}import{isDeepStrictEqual as JR}from"node:util";import TR from"node:crypto";import AR from"node:fs";import RR from"node:path";import{DatabaseSync as wR}from"node:sqlite";var Lc=class{database;databasePath;scope;constructor(t,n){this.databasePath=t,this.scope=n}async loadItems(t){let n=this.getDatabase().prepare("select key, value_json from replicated_items where scope = ? and resource = ?").all(this.scope,t),r={};for(let i of n)r[i.key]=JSON.parse(i.value_json);return n.length>0?r:null}async persistItem(t,n,r){this.getDatabase().prepare(`insert into replicated_items (scope, resource, key, value_json, saved_at_ms)
14
+ `,"utf8")}async function dh(e){let t=Ht(),n=await fetch(`${t.authUrl}/email/request-code`,{method:"POST",headers:{"content-type":"application/json",domain:t.authDomain},body:JSON.stringify({email:e})});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`email/request-code failed: ${n.status} ${r}`.trim())}}async function ph(e,t){let n=Ht(),r=await fetch(`${n.authUrl}/email/verify-code`,{method:"POST",headers:{"content-type":"application/json",domain:n.authDomain},body:JSON.stringify({email:e,code:t})}),i=await r.json().catch(()=>{});if(!r.ok)throw new Error(`email/verify-code failed: ${r.status}`);let o=typeof i?.access_token=="string"?i.access_token:"";if(!o)throw new Error("email/verify-code failed: missing access_token");let a=await ms(o);return{backendUrl:n.backendUrl,...Pc(a)}}import hR from"node:crypto";import{spawn as _R}from"node:child_process";import{setTimeout as gR}from"node:timers/promises";async function mh(){let e=await bR(),t=Date.now()+12e4;for(;Date.now()<t;){let n=await vR(e.requestId);if(n.status!=="pending")return{...e,...n};await gR(1500)}return{...e,status:"pending",message:"Timed out waiting for Google sign-in. Run auth_google_sign_in again to retry."}}async function bR(){let e=Ht(),t=hR.randomUUID(),n=new URL(`${e.authUrl}/google-form`);return n.searchParams.set("requestId",t),n.searchParams.set("scopes","openid email profile"),n.searchParams.set("domain",e.authDomain),{requestId:t,url:n.toString(),browserOpened:SR(n.toString())}}async function vR(e){let t=Ht(),n=new URL(`${t.authUrl}/google-auth-token`);n.searchParams.set("id",e);let r=await fetch(n.toString(),{headers:{domain:t.authDomain}}),i=await r.json().catch(()=>{});if(r.status===400&&i?.error==="Token not found")return{status:"pending",requestId:e};if(!r.ok)return{status:"failed",requestId:e,message:`google-auth-token failed: ${r.status}`};let o=typeof i?.access_token=="string"?i.access_token:"";if(!o)return{status:"pending",requestId:e};let a=await ms(o);return{status:"authenticated",requestId:e,backendUrl:t.backendUrl,...Pc(a)}}function SR(e){let t="xdg-open",n=[e];switch(process.platform){case"darwin":t="open";break;case"win32":t="rundll32",n=["url.dll,FileProtocolHandler",e];break}try{let r=_R(t,n,{detached:!0,stdio:"ignore"});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}async function di(e){let t=Oo(e);if(t.provider!=="google"||!t.exp)return e;let n=Date.now(),r=t.exp*1e3,i=300*1e3;if(r-n>=i)return e;let o=Ht(),a=await fetch(`${o.authUrl}/google-refresh`,{method:"GET",headers:{Authorization:`Bearer ${e}`,domain:o.authDomain}}),s=await a.json().catch(()=>{});if(!a.ok)return e;let c=typeof s?.access_token=="string"?s.access_token:"";return c?(await ms(c),c):e}var hh={allowedConnectionTypes:["BaseEvent","BaseLookup","BaseVector","BaseWarehouse","DiscordChannelWebhook","Gorgias","GoogleDrive","GoogleSheets","JudgeMe","LMStudio","OpenRouter","DiscordBot","Shopify"],allowedBlueprintResourceTypes:["BaseEventCollection","BaseLookupCollection","BaseVectorCollection","BaseWarehouseCollection","DiscordBotCommand","DiscordBotCommandOptionAutocomplete","DiscordBotMessageComponent","DiscordBotModalSubmit","GoogleDriveFile","GorgiasEvent","GorgiasTicket","JudgeMeReview"],hasFullWorkspaceAccess:!1},yR={allowedConnectionTypes:"all",allowedBlueprintResourceTypes:"all",hasFullWorkspaceAccess:!0},ER={"javioverflow@gmail.com":yR};function Gf(e){return e?ER[e.toLowerCase()]??hh:hh}function hs(e,t){return e.allowedConnectionTypes==="all"?!0:e.allowedConnectionTypes.includes(t)}function Nc(e,t){return t==="ManualTick"||e.allowedBlueprintResourceTypes==="all"?!0:e.allowedBlueprintResourceTypes.includes(t)}async function _h(){let e=await fi();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let t=await di(e),n=Oo(t).email;if(!n)throw new Error("current jwt does not include email");return n}async function po(){let e=await fi();if(!e)return Gf(void 0);let t=await di(e);return Gf(Oo(t).email)}async function wa(e){if(!hs(await po(),e))throw new Error(`integration type is not enabled for current user: ${e}`)}async function Fc(e){if(!Nc(await po(),e))throw new Error(`blueprint resource type is not enabled for current user: ${e}`)}async function gh(e){if(!(await po()).hasFullWorkspaceAccess)throw new Error(`full workspace access is required for resource: ${e}`)}function Mc(e,t){let n=t.split("/")[0];return n==="Base"||hs(e,n)}async function bh(e){let t=Ht(),n=await fetch(`${t.backendUrl}/users/is-member`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`users/is-member failed: ${n.status} ${i}`.trim())}if((await n.json().catch(()=>{}))?.isMember!==!0)throw new Error("user not member of workspace")}import{isDeepStrictEqual as JR}from"node:util";import TR from"node:crypto";import AR from"node:fs";import RR from"node:path";import{DatabaseSync as wR}from"node:sqlite";var Lc=class{database;databasePath;scope;constructor(t,n){this.databasePath=t,this.scope=n}async loadItems(t){let n=this.getDatabase().prepare("select key, value_json from replicated_items where scope = ? and resource = ?").all(this.scope,t),r={};for(let i of n)r[i.key]=JSON.parse(i.value_json);return n.length>0?r:null}async persistItem(t,n,r){this.getDatabase().prepare(`insert into replicated_items (scope, resource, key, value_json, saved_at_ms)
15
15
  values (?, ?, ?, ?, ?)
16
16
  on conflict(scope, resource, key) do update set
17
17
  value_json = excluded.value_json,
@@ -24,7 +24,7 @@ var tR=Object.create;var nh=Object.defineProperty;var nR=Object.getOwnPropertyDe
24
24
  saved_at_ms integer not null,
25
25
  primary key (scope, resource, key)
26
26
  )
27
- `),this.database)}};function vh(e){let t=e??"unknown-user";return TR.createHash("sha256").update(t).digest("hex")}function Sh(e,t,n){let r=e.replace(/^http/,"ws"),i=encodeURIComponent(t),o=encodeURIComponent(n);return`${r}/base/${i}/${o}`}var Bc=class{websocket;sessionId=xc();backendUrl;accessToken;channelListeners=new Map;disconnectListeners=new Set;ackWaiters=new Map;intentionallyClosed=!1;constructor(t,n){this.backendUrl=t,this.accessToken=n}async connect(t){this.intentionallyClosed=!1,this.sessionId=xc();let n=Sh(this.backendUrl,this.accessToken,this.sessionId),r=new WebSocket(n,"echo");this.websocket=r,await new Promise((i,o)=>{let a=setTimeout(()=>o(new Error("websocket open timeout")),t);r.onopen=()=>{clearTimeout(a),i()},r.onerror=()=>{clearTimeout(a),o(new Error("websocket open failed"))}}),r.onmessage=i=>this.processMessage(i.data),r.onclose=()=>this.processClose(),r.onerror=()=>this.processClose()}getSessionId(){return this.sessionId}send(t,n){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("gateway websocket not connected");this.websocket.send(`${t};${JSON.stringify(n)}`)}sendWithAck(t,n,r=5e3){let i=xc(),o={...n,eventId:i};return new Promise(a=>{let s=setTimeout(()=>{this.ackWaiters.delete(i),a({ok:!1,reason:"timeout"})},r);this.ackWaiters.set(i,{resolve:a,timeout:s}),this.send(t,o)})}onChannel(t,n){return this.channelListeners.has(t)||this.channelListeners.set(t,new Set),this.channelListeners.get(t).add(n),()=>this.channelListeners.get(t)?.delete(n)}onDisconnected(t){return this.disconnectListeners.add(t),()=>this.disconnectListeners.delete(t)}waitForChannelEvent(t,n,r){return new Promise((i,o)=>{let a=setTimeout(()=>{s(),o(new Error(`channel event timeout: ${t}`))},r),s=this.onChannel(t,c=>{n(c)&&(clearTimeout(a),s(),i(c))})})}collectChannelEvents(t,n,r,i){return new Promise((o,a)=>{let s=[],c,d=setTimeout(()=>{m(),c&&clearTimeout(c),a(new Error(`channel event timeout: ${t}`))},r),p=()=>{clearTimeout(d),m(),o(s)},m=this.onChannel(t,g=>{n(g)&&(s.push(g),c&&clearTimeout(c),c=setTimeout(p,i))})})}close(){this.intentionallyClosed=!0,this.websocket?.close(),this.websocket=void 0;for(let t of this.ackWaiters.values())clearTimeout(t.timeout),t.resolve({ok:!1,reason:"closed"});this.ackWaiters.clear()}processMessage(t){let n=typeof t=="string"?t:"",r=n.indexOf(";");if(r===-1)return;let i=n.slice(0,r),o=n.slice(r+1),a;try{a=JSON.parse(o)}catch{return}if(i.startsWith("ack:")){this.resolveAck(i.slice(4),a);return}a=DR(a);let s=this.channelListeners.get(i);if(s)for(let c of s)c(a)}resolveAck(t,n){let r=this.ackWaiters.get(t);r&&(this.ackWaiters.delete(t),clearTimeout(r.timeout),r.resolve(n.value??{ok:!1}))}processClose(){if(!this.intentionallyClosed)for(let t of this.disconnectListeners)t()}};function DR(e){if(e.resource!=="connections")return e;switch(e.action){case"snapshot":return{...e,value:CR(e.value)};case"delta":return{...e,value:OR(e.value)};default:return e}}function CR(e){if(!Wf(e))return e;let t={};for(let n in e)t[n]=Eh(e[n]);return t}function OR(e){return Wf(e)?{...e,pre:yh(e.pre),post:yh(e.post)}:e}function yh(e){return e===null?null:Eh(e)}function Eh(e){if(!Wf(e))return e;let t={...e};return delete t.config,t}function Wf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Hf="beepflow://resource-schemas/",nn={type:"number",description:"Nanoseconds since Unix epoch. Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."},_e={type:"string"},Ho={type:"number"},Th={type:"integer"},Pr={type:"boolean"};var Ah={type:"object",additionalProperties:_e},Xf={type:"object",additionalProperties:Pr},Uc={type:"object",additionalProperties:{type:"object",additionalProperties:Pr,properties:{list:Pr,detail:Pr,create:Pr,edit:Pr,delete:Pr,authorize:Pr}}},Da=["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"],Rh=["ManualTick","AerospikeSet","ApacheKafkaTopic","MQTTTopic","KaggleFile","RabbitMQQueue","RabbitMQStream","QdrantCollection","BaseVectorCollection","BaseEventCollection","BaseLookupCollection","GorgiasEvent","GorgiasTicket","GoogleDriveFile","GmailMessage","GmailThread","GmailEvent"],Ca={anyOf:[Pr,{type:"null"}]},kR=["Use resource_query first when editing existing items; upsert sends whole item state, not a JSON patch. Preserve unchanged fields.","Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."];function rn(e,t,n){let r=`${Hf}${e}`;return{resource:e,uri:r,sourceType:t,notes:kR,itemSchema:{$schema:"https://json-schema.org/draft/2020-12/schema",title:`Beepflow ${e} item`,type:"object",additionalProperties:!1,required:n.required,properties:n.properties,...n.defs?{$defs:n.defs}:{}}}}var $f={$ref:"#/$defs/operatorType"},xR={type:"object",additionalProperties:!1,required:["value"],properties:{value:{description:"Raw option value written to node input literal when selected."},label:{..._e,description:"Optional label shown in operator input dropdowns."}}},IR={type:"object",additionalProperties:!1,required:["type"],properties:{type:{type:"string",enum:Da,description:'Blueprint value type name. Use "list of X" for lists, never "list".'},options:{anyOf:[{type:"array",items:xR},{type:"null"}],description:"Allowed literal values for dropdown-style widgets."},isArray:{type:"boolean",description:"Whether this pin accepts multiple values."},allowedTypes:{anyOf:[{type:"array",items:$f},{type:"null"}],description:"Allowed concrete types for wildcard pins."},linkType:{..._e,description:"Type-linking group used to propagate wildcard types across pins."},widgetType:{..._e,description:'Frontend input widget id. Supports built-in widgets, integration selectors, and "<IntegrationType>-connection" connection dropdowns.'},defaultValue:{description:"Default literal value used when node input omits a value."},defaultValueForArrayElement:{description:"Default literal value for newly added array input elements."}}},PR={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{..._e,description:"Output pin name."},doc:{..._e,description:"Operator output documentation shown to users."},type:$f}},NR={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{..._e,description:"Input pin name; node inputs are keyed by this value."},doc:{..._e,description:"Operator input documentation shown to users."},type:$f,isLiteral:{...Pr,description:"Whether this input must be edited as literal value instead of upstream connection."}}},wh=rn("blueprint-operators","frontend/src/tabs/blueprint/types.ts:Operator",{required:["id","type","name","doc","categoryPath","inputs"],properties:{id:{..._e,description:"Stable registered operator id referenced by blueprint nodes."},type:{..._e,description:"Operator kind, usually function, variable, or localVariable."},name:{..._e,description:"Display name used in operator search and node labels."},aliases:{type:"array",items:_e,description:"Additional search terms for this operator."},doc:{..._e,description:"Operator documentation shown to users."},categoryPath:{type:"array",items:_e,description:"Menu category path segments."},inputs:{type:"array",items:NR,description:"Input pins in display order."},output:{anyOf:[PR,{type:"null"}],description:"Output pin definition, or null for side-effect-only operators."},isDeprecated:{...Pr,description:"Whether operator is deprecated and hidden from default search."},hidden:{...Pr,description:"Whether operator is hidden from menus and search."},canMock:{...Pr,description:"Whether test mode can mock this operator."},updatedAt:nn},defs:{operatorType:IR}});var FR={type:"object",additionalProperties:!1,properties:{x:{...Ho,description:"Optional node world x coordinate in blueprint editor. For new nodes, never specify style.x; omit it so the frontend can place nodes after measuring dimensions."},y:{...Ho,description:"Optional node world y coordinate in blueprint editor. For new nodes, never specify style.y; omit it so the frontend can place nodes after measuring dimensions."},title:{..._e,description:"Optional display title shown on node."},comment:{..._e,description:"Optional user-authored node comment."}}},MR={type:"object",additionalProperties:!0,description:"Blueprint view node. For new nodes, never specify style.x or style.y; omit coordinates so the frontend can place nodes after measuring dimensions. Known visualization blocks are intentionally accepted as additional properties.",required:["id"],properties:{id:{..._e,description:"Node id; must match key in blueprint view nodes record."},style:FR}},Dh=rn("blueprint-views","frontend/src/tabs/blueprint/types.ts:BlueprintView",{required:["id","nodes"],properties:{id:{..._e,description:"Blueprint tab id; must match tabs and blueprints resource id."},updatedAt:nn,nodes:{type:"object",additionalProperties:MR,description:"Editor view state keyed by node id."}}});var qc={type:"string",description:"Integration resource type processed by this blueprint, such as ApacheKafkaTopic or QdrantCollection. Call integration_blueprint_contexts_list first; use only resource types returned by that tool. The returned executionKind determines trigger choice: managed resources use executor, finite resources use manual/cron/loop/blueprint/webhook based on user intent."},zc={type:"object",additionalProperties:!0,description:"Integration-specific config for context.type. Start from contextTemplate.config returned by integration_blueprint_contexts_list, fill every configFields item where required=true, and preserve optional defaults such as consumerGroupId, clientId, parser, offsetResetStrategy, orderBy, or webhook topic maps when provided."},Kc={type:"object",additionalProperties:!1,required:["enabled"],properties:{enabled:{type:"boolean",description:"Must be true. Backend ignores this trigger branch when enabled is false."}}},jf={...Kc.properties.enabled,enum:[!0]},LR=["auto","application/json","text/plain","text/html","application/xml","application/x-www-form-urlencoded","multipart/form-data","application/octet-stream"],BR={type:"object",additionalProperties:!1,required:["count"],description:"Run immediately when explore runtime starts or restarts. Use for finite resource sampling, one-shot imports, and ad hoc reads.",properties:{count:{type:"integer",minimum:1,description:"Number of executions to run back-to-back. Frontend default is 1; backend coerces values below 1 to 1."}}},UR={type:"object",additionalProperties:!1,required:["expression"],description:"Run on a seconds-field cron schedule while explore runtime is active. Use for scheduled finite-resource refreshes.",properties:{expression:{type:"string",description:"Cron expression with six fields including seconds, parsed by robfig/cron. Example: 0 */5 * * * * runs every five minutes."},timezone:{type:"string",description:"Optional IANA timezone name such as UTC or America/New_York. Backend uses UTC when omitted or empty."}}},VR={type:"object",additionalProperties:!1,required:["delayMs"],description:"Run immediately, then wait delayMs before repeating while explore runtime is active. Use only for deliberate fixed-delay polling.",properties:{delayMs:{type:"integer",minimum:1,description:"Delay between executions in milliseconds. Must be positive to avoid a hot loop."}}},Ch={...Kc,description:"Wait while active until another blueprint or Trigger Self operator invokes this blueprint. Trigger argument is available through Get Trigger Argument."},Yf={type:"object",additionalProperties:!1,required:["enabled"],description:"Wait while active for generic GET/POST /:tabId/trigger HTTP calls. Request method, URL, parsed body, headers, and timestamp become trigger argument. Webhook URL is `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger` and runs only while blueprint is active in explore mode.",properties:{enabled:Kc.properties.enabled,timeoutMs:{type:"integer",minimum:1,description:"Maximum synchronous webhook execution time in milliseconds. Backend uses 30000 when omitted or below 1."},contentType:{type:"string",enum:LR,description:"Request body parser. Omit or use auto to infer from incoming Content-Type, then fall back to JSON sniffing, UTF-8 text, then binary. Not for integration webhook resources such as GorgiasEvent; those use executor."}}},Oh={...Kc,description:"Use for managed integration resources where runtime owns stream, event, webhook, or poll lifecycle, such as ApacheKafkaTopic, RabbitMQStream, GorgiasEvent, GmailMessage, GmailThread, GmailEvent, BaseEventCollection, and MQTTTopic."},Vc={type:"object",additionalProperties:!1,minProperties:1,maxProperties:1,description:"Exactly one trigger branch. For executionKind=managed from integration_blueprint_contexts_list, use executor. For executionKind=finite, choose manual for ad hoc/sample/start-once runs, cron for scheduled refresh, loop for fixed-delay polling, blueprint for invocation by another blueprint, or webhook for generic GET/POST /:tabId/trigger HTTP calls.",properties:{manual:BR,cron:UR,loop:VR,blueprint:Ch,webhook:Yf,executor:Oh},oneOf:[{required:["manual"]},{required:["cron"]},{required:["loop"]},{required:["blueprint"]},{required:["webhook"]},{required:["executor"]}]},kh={...Vc,properties:{...Vc.properties,blueprint:{...Ch,properties:{enabled:jf}},webhook:{...Yf,properties:{...Yf.properties,enabled:jf}},executor:{...Oh,properties:{enabled:jf}}}};var qR={type:"object",additionalProperties:!1,required:["literal"],properties:{literal:{description:"Literal JSON value for this input element; null is valid when connected upstream."},nodeId:{..._e,description:"Upstream node id when this value is connected to another node output."},operatorInputId:{..._e,description:"Upstream output pin name used by this connection."},nodeInputIndex:{..._e,description:'CRDT list index of upstream output value. Use "0.5" for any connected node output.'}}},zR={type:"object",additionalProperties:!1,required:["values"],properties:{isArray:{...Ca,description:"Whether input accepts multiple values for one operator input."},values:{type:"object",additionalProperties:qR,description:"Input values keyed by CRDT list index strings."},type:{type:"string",enum:Da,description:"Resolved input type override."},forceZipping:{...Ca,description:"Force list zipping behavior for multiple upstream values."}}},KR={type:"object",additionalProperties:!1,required:["id","operatorId","inputs"],properties:{id:{..._e,description:"Stable node id; must match key in blueprint nodes record."},operatorId:{..._e,description:"Id of registered blueprint operator this node executes."},inputs:{type:"object",additionalProperties:zR,description:"Node inputs keyed by operator input name."},mockNever:{...Ca,description:"Disable mocking for this node while testing."},skipBehavior:{type:"string",enum:["skip","null"],description:"Behavior when upstream value is skipped."},disabled:{...Ca,description:"Whether this node and downstream dependent nodes are disabled."},outputType:{type:"string",enum:Da,description:"Resolved output type for wildcard operators."}}},GR={type:"object",additionalProperties:!1,required:["type","trigger"],properties:{type:qc,trigger:kh,config:zc}},xh=rn("blueprints","frontend/src/tabs/blueprint/types.ts:Blueprint",{required:["id","mode","nodes","context"],properties:{id:{..._e,description:"Blueprint tab id; must match tabs resource id."},updatedAt:nn,mode:{type:"string",enum:["test","explore"],description:'Execution mode; result id is blueprint id plus "-test" or "-explore".'},nodes:{type:"object",additionalProperties:KR,description:"Blueprint nodes keyed by node id."},context:GR,testRecordsAmount:{...Th,description:"Target number of test records to keep for test mode."},recomputeOnChange:{type:"string",enum:["always","manual"],description:"Whether edits automatically restart execution."},mockNever:{...Pr,description:"Global flag to disable node mocking while testing."},desiredState:{type:"string",enum:["active","inactive"],description:"Requested runtime state for test or explore mode."}}});var WR=["Aerospike","ApacheKafka","MQTT","Kaggle","FacebookAds","RabbitMQ","Shopify","YouTube","Webshare","Playwright","AWS","Qdrant","OpenAI","BaseVector","BaseEvent","BaseLookup","Gorgias","LMStudio","OpenRouter","VoyageAI","GoogleDrive","GoogleSheets","Gmail","DiscordChannelWebhook"],Ih=rn("connections","frontend/src/integrations/types.ts:Connection",{required:["id","label","type","spaceId"],properties:{id:_e,updatedAt:nn,label:_e,type:{type:"string",enum:WR},spaceId:_e}});var Ph=rn("roles","frontend/src/auth/roles/types.ts:Role",{required:["id","label","authorizations"],properties:{id:_e,updatedAt:nn,label:_e,authorizations:Uc}});var Nh=rn("pages","frontend/src/tabs/types.ts:Page",{required:["id","sourceUrl","distUrl"],properties:{id:{..._e,description:"Page tab id; must match tabs resource id."},updatedAt:nn,sourceUrl:{..._e,description:"File-service URL for raw source HTML."},distUrl:{..._e,description:"File-service URL for optimized HTML rendered in a sandbox iframe."}}});var Fh=rn("schemas","frontend/src/integrations/types.ts:Schema",{required:["id","type","connectionId","path","schema"],properties:{id:_e,updatedAt:nn,type:{type:"string",enum:Rh},connectionId:_e,path:Ah,schema:{type:"object",additionalProperties:{type:"string",enum:Da}},keySerdeType:{type:"string"},valueSerdeType:{type:"string"}}});var Mh=rn("space-join-requests","frontend/src/spaces/space-join-requests/types.ts:SpaceJoinRequest",{required:["id","createdAt","requestedBy","kind","status","spaceId","userId"],properties:{id:_e,createdAt:{type:"number",description:"Nanoseconds since Unix epoch."},updatedAt:nn,requestedBy:_e,kind:{type:"string",enum:["invite","request"]},status:{type:"string",enum:["pending","granted","denied"]},spaceId:_e,userId:_e}});var Lh=rn("spaces","frontend/src/spaces/types.ts:Space",{required:["id","label"],properties:{id:_e,updatedAt:nn,label:_e,thumbnailUrl:_e,description:_e,isUserSpace:Ca}});var Bh=rn("tabs","frontend/src/tabs/types.ts:Tab",{required:["id","name","order","type","parent","spaceId"],properties:{id:{..._e,description:"Stable tab id. Blueprint and page tabs normally have matching records keyed by this id."},updatedAt:nn,name:_e,order:Ho,type:{type:"string",enum:["blueprint","folder","page"],description:"Navigation item kind; blueprint and page tabs normally have matching records."},parent:_e,spaceId:_e}});var Uh=rn("user-locations","frontend/src/workspace/user-location/types.ts:UserLocation",{required:["id"],properties:{id:_e,updatedAt:nn,tab:{type:"object",additionalProperties:!1,required:["id"],properties:{id:_e}},blueprint:{type:"object",additionalProperties:!1,required:["id"],properties:{id:_e,worldPosition:{type:"object",additionalProperties:!1,required:["x","y"],properties:{x:Ho,y:Ho}}}}}});var Vh=rn("users","frontend/src/auth/users/types.ts:User",{required:["id","displayName","roleIds","authorizations","spaces"],properties:{id:_e,updatedAt:nn,displayName:_e,avatarUrl:_e,roleIds:Xf,authorizations:Uc,spaces:Xf}});var Gc=[Vh,Ph,Lh,Bh,Nh,Ih,Fh,xh,Dh,wh,Uh,Mh];function Wc(e){return Gc.find(t=>t.resource===e)}var Qf=[xi("users","Workspace users and authorizations.",!0),xi("roles","Workspace roles and resource authorizations.",!0),xi("spaces","Workspace spaces.",!0),xi("tabs","Tabs and folders visible to authorized user; blueprint and page tabs normally share ids with matching records.",!0),xi("pages","Untrusted single-page HTML source and optimized file URLs keyed by matching page tab id.",!0),xi("connections","Read-only integration connections without secret-bearing config; config is redacted and cannot be read through MCP.",!1),xi("schemas","Integration schema metadata.",!0),xi("blueprints","Blueprint definitions keyed by matching blueprint tab id.",!0),xi("blueprint-views","Blueprint editor view state keyed by matching blueprint tab id.",!0),xi("blueprint-operators","Registered blueprint operator definitions.",!1),xi("user-locations","Live user location records.",!0),xi("space-join-requests","Space invitation and join requests.",!0)],HR=["tabs","pages","blueprints","blueprint-views"],Jf=new Set(HR),Oa=Qf.filter(e=>!Jf.has(e.name)),mu=Oa.map(e=>e.name),qh=Qf.map(e=>e.name);function XR(e){return Qf.find(t=>t.name===e)}function zh(e){return Oa.find(t=>t.name===e)}function Kh(e){if(XR(e))return e;throw new Error(`unsupported resource: ${e}`)}function Zf(e){if(Jf.has(e))throw new Error(`dedicated resource ${e}: use tab and blueprint intent tools instead of generic resource_* tools`);if(zh(e))return e;throw new Error(`unsupported resource: ${e}`)}function ed(e){let t=zh(e);if(Jf.has(e))throw new Error(`dedicated resource ${e}: use tab and blueprint intent tools instead of generic resource_* tools`);if(!t)throw new Error(`unsupported resource: ${e}`);if(!t.writable)throw new Error(`resource is read-only: ${e}`);return t.name}function xi(e,t,n){return{name:e,description:t,writable:n,schemaUri:`${Hf}${e}`}}function Nr(){return Date.now()*1e6}function nd(e,t){if(e===null&&t===null)return{pre:null,post:null};if(e===null&&t!==null)return{pre:null,post:t};if(e!==null&&t===null)return{pre:e,post:null};if(typeof e!="object"||typeof t!="object")return e!==t?{pre:e,post:t}:{pre:null,post:null};if(Array.isArray(e)||Array.isArray(t))return{pre:null,post:null};let{pre:n,post:r}=Gh(e,t);return n===null&&r===null?{pre:null,post:null}:{pre:n,post:r}}function Gh(e,t){let n={},r={},i=!1,o=new Set([...mo(e),...mo(t)]);for(let a of o){if(a==="updatedAt")continue;let s=e[a],c=t[a];if(Array.isArray(s)||Array.isArray(c))continue;let d=Xo(s),p=Xo(c);if(!(a in t))d||(n[a]=s,r[a]=null,i=!0);else if(!(a in e))p||(n[a]=null,r[a]=c,i=!0);else{if(d&&p)continue;if(d&&!p)n[a]=null,r[a]=c,i=!0;else if(!d&&p)n[a]=s,r[a]=null,i=!0;else{let{pre:m,post:g}=$R(s,c);(m!==void 0||g!==void 0)&&(m!==void 0&&(n[a]=td(m)),g!==void 0&&(r[a]=td(g)),i=!0)}}}return i?mo(n).length===0&&mo(r).length===0?{pre:null,post:null}:mo(n).length===0?{pre:null,post:r}:mo(r).length===0?{pre:n,post:null}:{pre:n,post:r}:{pre:null,post:null}}function $R(e,t){if(jR(e,t))return{pre:void 0,post:void 0};let n=Xo(e),r=Xo(t);if(n&&r)return{pre:void 0,post:void 0};if(n)return{pre:null,post:t};if(r)return{pre:e,post:null};if(Array.isArray(e)||Array.isArray(t))return{pre:void 0,post:void 0};if(typeof e!=typeof t)return{pre:e,post:t};if(typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null){let{pre:i,post:o}=Gh(e,t);return i===null&&o===null?{pre:void 0,post:void 0}:{pre:i===null?void 0:i,post:o===null?void 0:o}}return{pre:e,post:t}}function Xo(e){return e==null?!0:typeof e=="object"&&e!==null?Array.isArray(e)?e.length===0:mo(e).length===0:!1}function jR(e,t){return Xo(e)&&Xo(t)?!0:rd(e,t)}function rd(e,t){if(e===t)return!0;if(e==null||t==null||typeof e!="object"||typeof t!="object")return!1;let n=mo(e),r=mo(t);if(n.length!==r.length)return!1;for(let i of n)if(!(i in t)||!rd(e[i],t[i]))return!1;return!0}function Hc(e,t){return t.pre===null?e===null:e===null||typeof e!="object"||Array.isArray(e)?!1:Wh(e,t.pre)}function Wh(e,t){for(let n in t)if(n!=="updatedAt"&&!YR(e[n],t[n]))return!1;return!0}function YR(e,t){return t===null||QR(t)?Xo(e):e===void 0?!1:typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof e=="object"&&e!==null&&!Array.isArray(e)?Wh(e,t):rd(e,t)}function QR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&mo(e).length===0}function td(e){if(e==null)return null;if(typeof e=="object"&&e!==null){if(Array.isArray(e)&&e.length===0)return null;if(!Array.isArray(e)){let t={},n=!1;for(let r in e)t[r]=td(e[r]),t[r]!==void 0&&(n=!0);return n?t:null}}return e}function id(e,t){let n=od(e,t);return n!==null&&typeof n=="object"&&!Array.isArray(n)&&(n.updatedAt=t.updatedAt),n}function od(e,t){return t.post===null?null:e===null?t.post:typeof e!="object"||Array.isArray(e)?t.post:Hh(e,t.post)}function Hh(e,t){let n={};for(let r in e)if(r in t){let i=t[r];if(i===null)continue;typeof i=="object"&&!Array.isArray(i)&&typeof e[r]=="object"&&!Array.isArray(e[r])&&e[r]!==null?n[r]=Hh(e[r],i):n[r]=i}else n[r]=e[r];for(let r in t)!(r in e)&&t[r]!==null&&(n[r]=t[r]);return n}function mo(e){let t=[];for(let n in e)t.push(n);return t}var Xh="replicated-state",Xc=class{ackedResources={};dirtyResources={};unauthorizedKeys={};loadingResources={};loadingPromises=new Map;loadedResources=new Set;registeredResources=new Set;resourceChangeListeners=new Set;snapshotWaiters=new Map;storage;socketSession;logger;inflightItems=new Map;constructor(t,n,r){this.storage=t,this.socketSession=n,this.logger=r}onResourceChange(t){return this.resourceChangeListeners.add(t),()=>this.resourceChangeListeners.delete(t)}registerResource(t){this.registeredResources.add(t),this.initializeResource(t)}isResourceRegistered(t){return this.registeredResources.has(t)}getRegisteredResources(){return Array.from(this.registeredResources)}setDirtyItems(t,n){this.registerResource(t),this.dirtyResources[t]=Yr(n)}setDirtyItem(t,n,r){if(this.registerResource(t),r===void 0){delete this.dirtyResources[t][n];return}this.dirtyResources[t][n]=Yr(r)}clearSessionState(){this.ackedResources={},this.loadingResources={},this.loadingPromises.clear(),this.loadedResources.clear(),this.inflightItems.clear();for(let t of this.registeredResources)this.dirtyResources[t]={},this.unauthorizedKeys[t]={},this.loadingResources[t]=!0,this.emitResourceChange(t)}async loadRegisteredResourcesFromStorage(){await Promise.all(Array.from(this.registeredResources,t=>this.loadResourceFromStorage(t)))}async hydrate(t,n){this.registerResource(t),await this.loadResourceFromStorage(t),this.logger.info(`Calculating lastUpdatedAtSeen from ${jh(this.ackedResources[t])} items`);let r=this.prepareSnapshotQuery(t,n);this.logger.info(`\u{1F4F8} ${t} requested with query:`,r),this.socketSession.send(Xh,{resource:t,action:"snapshot",value:r})}hydrateAll(t){return this.hydrate(t,{all:!0})}async waitForSnapshot(t,n){await new Promise((r,i)=>{let o,a=()=>{clearTimeout(o),r()};o=setTimeout(()=>{this.snapshotWaiters.get(t)?.delete(a),i(new Error(`snapshot timeout for ${t}`))},n),this.snapshotWaiters.has(t)||this.snapshotWaiters.set(t,new Set),this.snapshotWaiters.get(t).add(a)})}processSocketEvent(t){switch(t.action){case"snapshot":this.applySnapshot(t.resource,t.value??{});break;case"delta":this.applyRemoteDelta(t);break}}async upsertItem(t,n){this.registerResource(t);let r=this.getAckedValue(t,n.id),i=nd(r,n);return i.pre===null&&i.post===null?!0:this.sendDelta(t,n.id,i,n)}async deleteItem(t,n){this.registerResource(t);let r=this.getAckedValue(t,n),i=nd(r,null);return i.pre===null&&i.post===null?!0:this.sendDelta(t,n,i,null)}isItemInflight(t,n){return this.inflightItems.get(t)?.has(n)===!0}async sendDelta(t,n,r,i){this.registerResource(t),this.inflightItems.has(t)||this.inflightItems.set(t,new Set);let o=this.inflightItems.get(t);if(o.has(n))return!1;let a=this.getDirtyValue(t,n);Hc(a,r)&&(arguments.length>=4?this.setDirtyValue(t,n,Yr(i)):this.setDirtyValue(t,n,od(a,Yr(r))),this.emitResourceChange(t)),o.add(n);let s;try{s=await this.socketSession.sendWithAck(Xh,{resource:t,action:"delta",key:n,value:r})}catch(c){s={ok:!1,reason:c instanceof Error?c.message:"error"}}return o.delete(n),s.ok?!0:(this.revertDirtyToAckedValue(t,n),this.emitResourceChange(t),this.logger.error(`!ack[${t}] Reverting to acked state for ${t}:${n}`,s.reason),!1)}getAckedValue(t,n){return this.initializeResource(t),this.ackedResources[t][n]??null}getDirtyValue(t,n){return this.initializeResource(t),this.dirtyResources[t][n]??null}getVisibleItems(t){this.initializeResource(t);let n={};for(let r in this.dirtyResources[t]){let i=this.dirtyResources[t][r];i!=null&&(n[r]=i)}return n}getRawItems(t){return this.initializeResource(t),Yr(this.dirtyResources[t])}getAckedItems(t){return this.initializeResource(t),Yr(this.ackedResources[t])}getUnauthorizedKeys(t){return this.initializeResource(t),Yr(this.unauthorizedKeys[t])}isResourceLoading(t){return this.initializeResource(t),this.loadingResources[t]}initializeResource(t){this.ackedResources[t]===void 0&&(this.ackedResources[t]={}),this.dirtyResources[t]===void 0&&(this.dirtyResources[t]={}),this.unauthorizedKeys[t]===void 0&&(this.unauthorizedKeys[t]={}),this.loadingResources[t]===void 0&&(this.loadingResources[t]=!0)}prepareSnapshotQuery(t,n){this.initializeResource(t);let r=Yr(n);if(r.lastUpdatedAtSeen!==void 0)return r;let i=this.buildLastUpdatedAtSeen(t,r);return $h(i)||(r.lastUpdatedAtSeen=i),r}async loadResourceFromStorage(t){if(this.initializeResource(t),this.loadedResources.has(t))return;if(this.loadingPromises.has(t))return this.loadingPromises.get(t);let n=this.loadResourceItemsFromStorage(t);this.loadingPromises.set(t,n);try{await n}finally{this.loadingPromises.delete(t),this.loadedResources.add(t)}}async loadResourceItemsFromStorage(t){let n=!1,r=0;try{let i=await this.storage.loadItems(t);if(i&&$h(this.ackedResources[t])){n=!0;for(let o in i)this.applyCachedItem(t,o,i[o])&&(r+=1)}}catch(i){this.logger.warn(`Failed to load cached ${t}: ${String(i)}`)}finally{this.loadingResources[t]=!1,this.emitResourceChange(t),n?this.logger.info(`\u{1F4C2} ${r}x ${t} from cache`):this.logger.info(`\u{1F4C2} no cached data for ${t}`)}}applyCachedItem(t,n,r){return r===null?(this.ackedResources[t][n]=null,this.dirtyResources[t][n]=null,!0):r==="unauthorized"?(this.unauthorizedKeys[t][n]=!0,!1):(this.ackedResources[t][n]=Yr(r),this.dirtyResources[t][n]=Yr(r),!0)}applySnapshot(t,n){this.initializeResource(t);for(let r in n){let i=n[r];i===null?(this.ackedResources[t][r]=null,(!this.isItemInflight(t,r)||this.getDirtyValue(t,r)==null)&&(this.dirtyResources[t][r]=null),delete this.unauthorizedKeys[t][r]):i==="unauthorized"?(delete this.ackedResources[t][r],delete this.dirtyResources[t][r],this.unauthorizedKeys[t][r]=!0):(this.ackedResources[t][r]=Yr(i),this.dirtyResources[t][r]=Yr(i),delete this.unauthorizedKeys[t][r]),this.storage.persistItem(t,r,i).catch(o=>{this.logger.warn(`Failed to persist ${t}:${r}: ${String(o)}`)})}this.loadingResources[t]=!1,this.emitResourceChange(t),this.logger.info(`\u{1F4F8} ${jh(n)}x ${t} `),this.resolveSnapshotWaiters(t)}applyRemoteDelta(t){let n=t.resource,r=t.key;if(!r)return;this.initializeResource(n);let i=t.value,o={pre:i.pre,post:i.post},a=this.getAckedValue(n,r);if(!Hc(a,o))this.logger.error(`\u{1D6AB}S precondition invalid on last acked for ${n}:${r}`,{pre:o.pre,post:o.post,current:a});else{let c=id(a,Yr(i));this.ackedResources[n][r]=c,this.storage.persistItem(n,r,c).catch(d=>{this.logger.warn(`Failed to persist ${n}:${r}: ${String(d)}`)}),this.logger.info(ad(`\u{1D6AB}S[${n}] acked`,o))}let s=this.getDirtyValue(n,r);t.by!==this.socketSession.getSessionId()?Hc(s,o)?o.post===null?(this.dirtyResources[n][r]=null,this.logger.info(ad(`\u{1D6AB}S[${n}] dirty`,o))):(this.dirtyResources[n][r]=id(s,Yr(i)),this.logger.info(ad(`\u{1D6AB}S[${n}] dirty`,o))):(this.logger.warn(`Skip delta on dirty for ${n}:${r}`,{pre:o.pre,post:o.post,current:a}),this.revertDirtyToAckedValue(n,r)):o.post!=null&&s!=null&&typeof s=="object"&&(s.updatedAt=i.updatedAt,this.dirtyResources[n][r]=s,this.logger.info(`\u{1D6AB}S[${n}] dirty updatedAt for ${r}`)),this.emitResourceChange(n)}buildLastUpdatedAtSeen(t,n){let r=this.ackedResources[t],i={};if(n.all){for(let o in r)this.copyItemUpdatedAt(r[o],o,i);return i}if(n.keys&&n.keys.length>0)for(let o of n.keys)this.copyItemUpdatedAt(r[o],o,i);return i}copyItemUpdatedAt(t,n,r){t&&typeof t=="object"&&typeof t.updatedAt=="number"&&(r[n]=t.updatedAt)}setDirtyValue(t,n,r){if(r===null){this.dirtyResources[t][n]=null;return}this.dirtyResources[t][n]=r}revertDirtyToAckedValue(t,n){let r=this.ackedResources[t][n];if(r===void 0){delete this.dirtyResources[t][n];return}if(r===null){this.dirtyResources[t][n]=null;return}this.dirtyResources[t][n]=Yr(r)}emitResourceChange(t){let n={resource:t,acked:this.getAckedItems(t),dirty:this.getRawItems(t),unauthorized:this.getUnauthorizedKeys(t),loading:this.loadingResources[t]};for(let r of this.resourceChangeListeners)r(n)}resolveSnapshotWaiters(t){let n=this.snapshotWaiters.get(t);if(n){this.snapshotWaiters.delete(t);for(let r of n)r()}}};function Yr(e){if(e===void 0)return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}function $h(e){for(let t in e)return!1;return!0}function jh(e){let t=0;for(let n in e)t+=1;return t}function ad(e,t){return`${e}
27
+ `),this.database)}};function vh(e){let t=e??"unknown-user";return TR.createHash("sha256").update(t).digest("hex")}function Sh(e,t,n){let r=e.replace(/^http/,"ws"),i=encodeURIComponent(t),o=encodeURIComponent(n);return`${r}/base/${i}/${o}`}var Bc=class{websocket;sessionId=xc();backendUrl;accessToken;channelListeners=new Map;disconnectListeners=new Set;ackWaiters=new Map;intentionallyClosed=!1;constructor(t,n){this.backendUrl=t,this.accessToken=n}async connect(t){this.intentionallyClosed=!1,this.sessionId=xc();let n=Sh(this.backendUrl,this.accessToken,this.sessionId),r=new WebSocket(n,"echo");this.websocket=r,await new Promise((i,o)=>{let a=setTimeout(()=>o(new Error("websocket open timeout")),t);r.onopen=()=>{clearTimeout(a),i()},r.onerror=()=>{clearTimeout(a),o(new Error("websocket open failed"))}}),r.onmessage=i=>this.processMessage(i.data),r.onclose=()=>this.processClose(),r.onerror=()=>this.processClose()}getSessionId(){return this.sessionId}send(t,n){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("gateway websocket not connected");this.websocket.send(`${t};${JSON.stringify(n)}`)}sendWithAck(t,n,r=5e3){let i=xc(),o={...n,eventId:i};return new Promise(a=>{let s=setTimeout(()=>{this.ackWaiters.delete(i),a({ok:!1,reason:"timeout"})},r);this.ackWaiters.set(i,{resolve:a,timeout:s}),this.send(t,o)})}onChannel(t,n){return this.channelListeners.has(t)||this.channelListeners.set(t,new Set),this.channelListeners.get(t).add(n),()=>this.channelListeners.get(t)?.delete(n)}onDisconnected(t){return this.disconnectListeners.add(t),()=>this.disconnectListeners.delete(t)}waitForChannelEvent(t,n,r){return new Promise((i,o)=>{let a=setTimeout(()=>{s(),o(new Error(`channel event timeout: ${t}`))},r),s=this.onChannel(t,c=>{n(c)&&(clearTimeout(a),s(),i(c))})})}collectChannelEvents(t,n,r,i){return new Promise((o,a)=>{let s=[],c,d=setTimeout(()=>{m(),c&&clearTimeout(c),a(new Error(`channel event timeout: ${t}`))},r),p=()=>{clearTimeout(d),m(),o(s)},m=this.onChannel(t,g=>{n(g)&&(s.push(g),c&&clearTimeout(c),c=setTimeout(p,i))})})}close(){this.intentionallyClosed=!0,this.websocket?.close(),this.websocket=void 0;for(let t of this.ackWaiters.values())clearTimeout(t.timeout),t.resolve({ok:!1,reason:"closed"});this.ackWaiters.clear()}processMessage(t){let n=typeof t=="string"?t:"",r=n.indexOf(";");if(r===-1)return;let i=n.slice(0,r),o=n.slice(r+1),a;try{a=JSON.parse(o)}catch{return}if(i.startsWith("ack:")){this.resolveAck(i.slice(4),a);return}a=DR(a);let s=this.channelListeners.get(i);if(s)for(let c of s)c(a)}resolveAck(t,n){let r=this.ackWaiters.get(t);r&&(this.ackWaiters.delete(t),clearTimeout(r.timeout),r.resolve(n.value??{ok:!1}))}processClose(){if(!this.intentionallyClosed)for(let t of this.disconnectListeners)t()}};function DR(e){if(e.resource!=="connections")return e;switch(e.action){case"snapshot":return{...e,value:CR(e.value)};case"delta":return{...e,value:OR(e.value)};default:return e}}function CR(e){if(!Wf(e))return e;let t={};for(let n in e)t[n]=Eh(e[n]);return t}function OR(e){return Wf(e)?{...e,pre:yh(e.pre),post:yh(e.post)}:e}function yh(e){return e===null?null:Eh(e)}function Eh(e){if(!Wf(e))return e;let t={...e};return delete t.config,t}function Wf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Hf="beepflow://resource-schemas/",nn={type:"number",description:"Nanoseconds since Unix epoch. Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."},_e={type:"string"},Ho={type:"number"},Th={type:"integer"},Pr={type:"boolean"};var Ah={type:"object",additionalProperties:_e},Xf={type:"object",additionalProperties:Pr},Uc={type:"object",additionalProperties:{type:"object",additionalProperties:Pr,properties:{list:Pr,detail:Pr,create:Pr,edit:Pr,delete:Pr,authorize:Pr}}},Da=["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"],Rh=["ManualTick","AerospikeSet","ApacheKafkaTopic","MQTTTopic","KaggleFile","RabbitMQQueue","RabbitMQStream","QdrantCollection","BaseVectorCollection","BaseEventCollection","BaseLookupCollection","GorgiasEvent","GorgiasTicket","GoogleDriveFile","GmailMessage","GmailThread","GmailEvent"],Ca={anyOf:[Pr,{type:"null"}]},kR=["Use resource_query first when editing existing items; upsert sends whole item state, not a JSON patch. Preserve unchanged fields.","Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."];function rn(e,t,n){let r=`${Hf}${e}`;return{resource:e,uri:r,sourceType:t,notes:kR,itemSchema:{$schema:"https://json-schema.org/draft/2020-12/schema",title:`Beepflow ${e} item`,type:"object",additionalProperties:!1,required:n.required,properties:n.properties,...n.defs?{$defs:n.defs}:{}}}}var $f={$ref:"#/$defs/operatorType"},xR={type:"object",additionalProperties:!1,required:["value"],properties:{value:{description:"Raw option value written to node input literal when selected."},label:{..._e,description:"Optional label shown in operator input dropdowns."}}},IR={type:"object",additionalProperties:!1,required:["type"],properties:{type:{type:"string",enum:Da,description:'Blueprint value type name. Use "list of X" for lists, never "list".'},options:{anyOf:[{type:"array",items:xR},{type:"null"}],description:"Allowed literal values for dropdown-style widgets."},isArray:{type:"boolean",description:"Whether this pin accepts multiple values."},allowedTypes:{anyOf:[{type:"array",items:$f},{type:"null"}],description:"Allowed concrete types for wildcard pins."},linkType:{..._e,description:"Type-linking group used to propagate wildcard types across pins."},widgetType:{..._e,description:'Frontend input widget id. Supports built-in widgets, integration selectors, and "<IntegrationType>-connection" connection dropdowns.'},defaultValue:{description:"Default literal value used when node input omits a value."},defaultValueForArrayElement:{description:"Default literal value for newly added array input elements."}}},PR={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{..._e,description:"Output pin name."},doc:{..._e,description:"Operator output documentation shown to users."},type:$f}},NR={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{..._e,description:"Input pin name; node inputs are keyed by this value."},doc:{..._e,description:"Operator input documentation shown to users."},type:$f,isLiteral:{...Pr,description:"Whether this input must be edited as literal value instead of upstream connection."}}},wh=rn("blueprint-operators","frontend/src/tabs/blueprint/types.ts:Operator",{required:["id","type","name","doc","categoryPath","inputs"],properties:{id:{..._e,description:"Stable registered operator id referenced by blueprint nodes."},type:{..._e,description:"Operator kind, usually function, variable, or localVariable."},name:{..._e,description:"Display name used in operator search and node labels."},aliases:{type:"array",items:_e,description:"Additional search terms for this operator."},doc:{..._e,description:"Operator documentation shown to users."},categoryPath:{type:"array",items:_e,description:"Menu category path segments."},inputs:{type:"array",items:NR,description:"Input pins in display order."},output:{anyOf:[PR,{type:"null"}],description:"Output pin definition, or null for side-effect-only operators."},isDeprecated:{...Pr,description:"Whether operator is deprecated and hidden from default search."},hidden:{...Pr,description:"Whether operator is hidden from menus and search."},canMock:{...Pr,description:"Whether test mode can mock this operator."},updatedAt:nn},defs:{operatorType:IR}});var FR={type:"object",additionalProperties:!1,properties:{x:{...Ho,description:"Optional node world x coordinate in blueprint editor. For new nodes, never specify style.x; omit it so the frontend can place nodes after measuring dimensions."},y:{...Ho,description:"Optional node world y coordinate in blueprint editor. For new nodes, never specify style.y; omit it so the frontend can place nodes after measuring dimensions."},title:{..._e,description:"Optional display title shown on node."},comment:{..._e,description:"Optional user-authored node comment."}}},MR={type:"object",additionalProperties:!0,description:"Blueprint view node. For new nodes, never specify style.x or style.y; omit coordinates so the frontend can place nodes after measuring dimensions. Known visualization blocks are intentionally accepted as additional properties.",required:["id"],properties:{id:{..._e,description:"Node id; must match key in blueprint view nodes record."},style:FR}},Dh=rn("blueprint-views","frontend/src/tabs/blueprint/types.ts:BlueprintView",{required:["id","nodes"],properties:{id:{..._e,description:"Blueprint tab id; must match tabs and blueprints resource id."},updatedAt:nn,nodes:{type:"object",additionalProperties:MR,description:"Editor view state keyed by node id."}}});var qc={type:"string",description:"Integration resource type processed by this blueprint, such as ApacheKafkaTopic or QdrantCollection. Call integration_blueprint_contexts_list first; use only resource types returned by that tool. The returned executionKind determines trigger choice: managed resources use executor, finite resources use manual/cron/loop/blueprint/webhook based on user intent."},zc={type:"object",additionalProperties:!0,description:"Integration-specific config for context.type. Start from contextTemplate.config returned by integration_blueprint_contexts_list, fill every configFields item where required=true, and preserve optional defaults such as consumerGroupId, clientId, parser, offsetResetStrategy, orderBy, or webhook topic maps when provided."},Kc={type:"object",additionalProperties:!1,required:["enabled"],properties:{enabled:{type:"boolean",description:"Must be true. Backend ignores this trigger branch when enabled is false."}}},jf={...Kc.properties.enabled,enum:[!0]},LR=["auto","application/json","text/plain","text/html","application/xml","application/x-www-form-urlencoded","multipart/form-data","application/octet-stream"],BR={type:"object",additionalProperties:!1,required:["count"],description:"Run immediately when explore runtime starts or restarts. Use for finite resource sampling, one-shot imports, and ad hoc reads.",properties:{count:{type:"integer",minimum:1,description:"Number of executions to run back-to-back. Frontend default is 1; backend coerces values below 1 to 1."}}},UR={type:"object",additionalProperties:!1,required:["expression"],description:"Run on a seconds-field cron schedule while explore runtime is active. Use for scheduled finite-resource refreshes.",properties:{expression:{type:"string",description:"Cron expression with six fields including seconds, parsed by robfig/cron. Example: 0 */5 * * * * runs every five minutes."},timezone:{type:"string",description:"Optional IANA timezone name such as UTC or America/New_York. Backend uses UTC when omitted or empty."}}},VR={type:"object",additionalProperties:!1,required:["delayMs"],description:"Run immediately, then wait delayMs before repeating while explore runtime is active. Use only for deliberate fixed-delay polling.",properties:{delayMs:{type:"integer",minimum:1,description:"Delay between executions in milliseconds. Must be positive to avoid a hot loop."}}},Ch={...Kc,description:"Wait while active until another blueprint or Trigger Self operator invokes this blueprint. Trigger argument is available through Get Trigger Argument."},Yf={type:"object",additionalProperties:!1,required:["enabled"],description:"Wait while active for generic GET/POST /:tabId/trigger HTTP calls. Request method, URL, parsed body, headers, and timestamp become trigger argument. Webhook URL is `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger` and runs only while blueprint is active in explore mode.",properties:{enabled:Kc.properties.enabled,timeoutMs:{type:"integer",minimum:1,description:"Maximum synchronous webhook execution time in milliseconds. Backend uses 30000 when omitted or below 1."},contentType:{type:"string",enum:LR,description:"Request body parser. Omit or use auto to infer from incoming Content-Type, then fall back to JSON sniffing, UTF-8 text, then binary. Not for integration webhook resources such as GorgiasEvent; those use executor."}}},Oh={...Kc,description:"Use for managed integration resources where runtime owns stream, event, webhook, or poll lifecycle, such as ApacheKafkaTopic, RabbitMQStream, GorgiasEvent, GmailMessage, GmailThread, GmailEvent, BaseEventCollection, and MQTTTopic."},Vc={type:"object",additionalProperties:!1,minProperties:1,maxProperties:1,description:"Exactly one trigger branch. For executionKind=managed from integration_blueprint_contexts_list, use executor. For executionKind=finite, choose manual for ad hoc/sample/start-once runs, cron for scheduled refresh, loop for fixed-delay polling, blueprint for invocation by another blueprint, or webhook for generic GET/POST /:tabId/trigger HTTP calls.",properties:{manual:BR,cron:UR,loop:VR,blueprint:Ch,webhook:Yf,executor:Oh},oneOf:[{required:["manual"]},{required:["cron"]},{required:["loop"]},{required:["blueprint"]},{required:["webhook"]},{required:["executor"]}]},kh={...Vc,properties:{...Vc.properties,blueprint:{...Ch,properties:{enabled:jf}},webhook:{...Yf,properties:{...Yf.properties,enabled:jf}},executor:{...Oh,properties:{enabled:jf}}}};var qR={type:"object",additionalProperties:!1,required:["literal"],properties:{literal:{description:"Literal JSON value for this input element; null is valid when connected upstream."},nodeId:{..._e,description:"Upstream node id when this value is connected to another node output."},operatorInputId:{..._e,description:"Upstream output pin name used by this connection."},nodeInputIndex:{..._e,description:'CRDT list index of upstream output value. Use "0.5" for any connected node output.'}}},zR={type:"object",additionalProperties:!1,required:["values"],properties:{isArray:{...Ca,description:"Whether input accepts multiple values for one operator input."},values:{type:"object",additionalProperties:qR,description:"Input values keyed by CRDT list index strings."},type:{type:"string",enum:Da,description:"Resolved input type override."},forceZipping:{...Ca,description:"Force list zipping behavior for multiple upstream values."},listInputMode:{type:"string",enum:["list","items"],description:"Whether this input receives one whole list value or assembles a list from item values."}}},KR={type:"object",additionalProperties:!1,required:["id","operatorId","inputs"],properties:{id:{..._e,description:"Stable node id; must match key in blueprint nodes record."},operatorId:{..._e,description:"Id of registered blueprint operator this node executes."},inputs:{type:"object",additionalProperties:zR,description:"Node inputs keyed by operator input name."},mockNever:{...Ca,description:"Disable mocking for this node while testing."},skipBehavior:{type:"string",enum:["skip","null"],description:"Behavior when upstream value is skipped."},disabled:{...Ca,description:"Whether this node and downstream dependent nodes are disabled."},outputType:{type:"string",enum:Da,description:"Resolved output type for wildcard operators."}}},GR={type:"object",additionalProperties:!1,required:["type","trigger"],properties:{type:qc,trigger:kh,config:zc}},xh=rn("blueprints","frontend/src/tabs/blueprint/types.ts:Blueprint",{required:["id","mode","nodes","context"],properties:{id:{..._e,description:"Blueprint tab id; must match tabs resource id."},updatedAt:nn,mode:{type:"string",enum:["test","explore"],description:'Execution mode; result id is blueprint id plus "-test" or "-explore".'},nodes:{type:"object",additionalProperties:KR,description:"Blueprint nodes keyed by node id."},context:GR,testRecordsAmount:{...Th,description:"Target number of test records to keep for test mode."},recomputeOnChange:{type:"string",enum:["always","manual"],description:"Whether edits automatically restart execution."},mockNever:{...Pr,description:"Global flag to disable node mocking while testing."},desiredState:{type:"string",enum:["active","inactive"],description:"Requested runtime state for test or explore mode."}}});var WR=["Aerospike","ApacheKafka","MQTT","Kaggle","FacebookAds","RabbitMQ","Shopify","YouTube","Webshare","Playwright","AWS","Qdrant","OpenAI","BaseVector","BaseEvent","BaseLookup","Gorgias","LMStudio","OpenRouter","VoyageAI","GoogleDrive","GoogleSheets","Gmail","DiscordChannelWebhook"],Ih=rn("connections","frontend/src/integrations/types.ts:Connection",{required:["id","label","type","spaceId"],properties:{id:_e,updatedAt:nn,label:_e,type:{type:"string",enum:WR},spaceId:_e}});var Ph=rn("roles","frontend/src/auth/roles/types.ts:Role",{required:["id","label","authorizations"],properties:{id:_e,updatedAt:nn,label:_e,authorizations:Uc}});var Nh=rn("pages","frontend/src/tabs/types.ts:Page",{required:["id","sourceUrl","distUrl"],properties:{id:{..._e,description:"Page tab id; must match tabs resource id."},updatedAt:nn,sourceUrl:{..._e,description:"File-service URL for raw source HTML."},distUrl:{..._e,description:"File-service URL for optimized HTML rendered in a sandbox iframe."}}});var Fh=rn("schemas","frontend/src/integrations/types.ts:Schema",{required:["id","type","connectionId","path","schema"],properties:{id:_e,updatedAt:nn,type:{type:"string",enum:Rh},connectionId:_e,path:Ah,schema:{type:"object",additionalProperties:{type:"string",enum:Da}},keySerdeType:{type:"string"},valueSerdeType:{type:"string"}}});var Mh=rn("space-join-requests","frontend/src/spaces/space-join-requests/types.ts:SpaceJoinRequest",{required:["id","createdAt","requestedBy","kind","status","spaceId","userId"],properties:{id:_e,createdAt:{type:"number",description:"Nanoseconds since Unix epoch."},updatedAt:nn,requestedBy:_e,kind:{type:"string",enum:["invite","request"]},status:{type:"string",enum:["pending","granted","denied"]},spaceId:_e,userId:_e}});var Lh=rn("spaces","frontend/src/spaces/types.ts:Space",{required:["id","label"],properties:{id:_e,updatedAt:nn,label:_e,thumbnailUrl:_e,description:_e,isUserSpace:Ca}});var Bh=rn("tabs","frontend/src/tabs/types.ts:Tab",{required:["id","name","order","type","parent","spaceId"],properties:{id:{..._e,description:"Stable tab id. Blueprint and page tabs normally have matching records keyed by this id."},updatedAt:nn,name:_e,order:Ho,type:{type:"string",enum:["blueprint","folder","page"],description:"Navigation item kind; blueprint and page tabs normally have matching records."},parent:_e,spaceId:_e}});var Uh=rn("user-locations","frontend/src/workspace/user-location/types.ts:UserLocation",{required:["id"],properties:{id:_e,updatedAt:nn,tab:{type:"object",additionalProperties:!1,required:["id"],properties:{id:_e}},blueprint:{type:"object",additionalProperties:!1,required:["id"],properties:{id:_e,worldPosition:{type:"object",additionalProperties:!1,required:["x","y"],properties:{x:Ho,y:Ho}}}}}});var Vh=rn("users","frontend/src/auth/users/types.ts:User",{required:["id","displayName","roleIds","authorizations","spaces"],properties:{id:_e,updatedAt:nn,displayName:_e,avatarUrl:_e,roleIds:Xf,authorizations:Uc,spaces:Xf}});var Gc=[Vh,Ph,Lh,Bh,Nh,Ih,Fh,xh,Dh,wh,Uh,Mh];function Wc(e){return Gc.find(t=>t.resource===e)}var Qf=[xi("users","Workspace users and authorizations.",!0),xi("roles","Workspace roles and resource authorizations.",!0),xi("spaces","Workspace spaces.",!0),xi("tabs","Tabs and folders visible to authorized user; blueprint and page tabs normally share ids with matching records.",!0),xi("pages","Untrusted single-page HTML source and optimized file URLs keyed by matching page tab id.",!0),xi("connections","Read-only integration connections without secret-bearing config; config is redacted and cannot be read through MCP.",!1),xi("schemas","Integration schema metadata.",!0),xi("blueprints","Blueprint definitions keyed by matching blueprint tab id.",!0),xi("blueprint-views","Blueprint editor view state keyed by matching blueprint tab id.",!0),xi("blueprint-operators","Registered blueprint operator definitions.",!1),xi("user-locations","Live user location records.",!0),xi("space-join-requests","Space invitation and join requests.",!0)],HR=["tabs","pages","blueprints","blueprint-views"],Jf=new Set(HR),Oa=Qf.filter(e=>!Jf.has(e.name)),mu=Oa.map(e=>e.name),qh=Qf.map(e=>e.name);function XR(e){return Qf.find(t=>t.name===e)}function zh(e){return Oa.find(t=>t.name===e)}function Kh(e){if(XR(e))return e;throw new Error(`unsupported resource: ${e}`)}function Zf(e){if(Jf.has(e))throw new Error(`dedicated resource ${e}: use tab and blueprint intent tools instead of generic resource_* tools`);if(zh(e))return e;throw new Error(`unsupported resource: ${e}`)}function ed(e){let t=zh(e);if(Jf.has(e))throw new Error(`dedicated resource ${e}: use tab and blueprint intent tools instead of generic resource_* tools`);if(!t)throw new Error(`unsupported resource: ${e}`);if(!t.writable)throw new Error(`resource is read-only: ${e}`);return t.name}function xi(e,t,n){return{name:e,description:t,writable:n,schemaUri:`${Hf}${e}`}}function Nr(){return Date.now()*1e6}function nd(e,t){if(e===null&&t===null)return{pre:null,post:null};if(e===null&&t!==null)return{pre:null,post:t};if(e!==null&&t===null)return{pre:e,post:null};if(typeof e!="object"||typeof t!="object")return e!==t?{pre:e,post:t}:{pre:null,post:null};if(Array.isArray(e)||Array.isArray(t))return{pre:null,post:null};let{pre:n,post:r}=Gh(e,t);return n===null&&r===null?{pre:null,post:null}:{pre:n,post:r}}function Gh(e,t){let n={},r={},i=!1,o=new Set([...mo(e),...mo(t)]);for(let a of o){if(a==="updatedAt")continue;let s=e[a],c=t[a];if(Array.isArray(s)||Array.isArray(c))continue;let d=Xo(s),p=Xo(c);if(!(a in t))d||(n[a]=s,r[a]=null,i=!0);else if(!(a in e))p||(n[a]=null,r[a]=c,i=!0);else{if(d&&p)continue;if(d&&!p)n[a]=null,r[a]=c,i=!0;else if(!d&&p)n[a]=s,r[a]=null,i=!0;else{let{pre:m,post:g}=$R(s,c);(m!==void 0||g!==void 0)&&(m!==void 0&&(n[a]=td(m)),g!==void 0&&(r[a]=td(g)),i=!0)}}}return i?mo(n).length===0&&mo(r).length===0?{pre:null,post:null}:mo(n).length===0?{pre:null,post:r}:mo(r).length===0?{pre:n,post:null}:{pre:n,post:r}:{pre:null,post:null}}function $R(e,t){if(jR(e,t))return{pre:void 0,post:void 0};let n=Xo(e),r=Xo(t);if(n&&r)return{pre:void 0,post:void 0};if(n)return{pre:null,post:t};if(r)return{pre:e,post:null};if(Array.isArray(e)||Array.isArray(t))return{pre:void 0,post:void 0};if(typeof e!=typeof t)return{pre:e,post:t};if(typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null){let{pre:i,post:o}=Gh(e,t);return i===null&&o===null?{pre:void 0,post:void 0}:{pre:i===null?void 0:i,post:o===null?void 0:o}}return{pre:e,post:t}}function Xo(e){return e==null?!0:typeof e=="object"&&e!==null?Array.isArray(e)?e.length===0:mo(e).length===0:!1}function jR(e,t){return Xo(e)&&Xo(t)?!0:rd(e,t)}function rd(e,t){if(e===t)return!0;if(e==null||t==null||typeof e!="object"||typeof t!="object")return!1;let n=mo(e),r=mo(t);if(n.length!==r.length)return!1;for(let i of n)if(!(i in t)||!rd(e[i],t[i]))return!1;return!0}function Hc(e,t){return t.pre===null?e===null:e===null||typeof e!="object"||Array.isArray(e)?!1:Wh(e,t.pre)}function Wh(e,t){for(let n in t)if(n!=="updatedAt"&&!YR(e[n],t[n]))return!1;return!0}function YR(e,t){return t===null||QR(t)?Xo(e):e===void 0?!1:typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof e=="object"&&e!==null&&!Array.isArray(e)?Wh(e,t):rd(e,t)}function QR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&mo(e).length===0}function td(e){if(e==null)return null;if(typeof e=="object"&&e!==null){if(Array.isArray(e)&&e.length===0)return null;if(!Array.isArray(e)){let t={},n=!1;for(let r in e)t[r]=td(e[r]),t[r]!==void 0&&(n=!0);return n?t:null}}return e}function id(e,t){let n=od(e,t);return n!==null&&typeof n=="object"&&!Array.isArray(n)&&(n.updatedAt=t.updatedAt),n}function od(e,t){return t.post===null?null:e===null?t.post:typeof e!="object"||Array.isArray(e)?t.post:Hh(e,t.post)}function Hh(e,t){let n={};for(let r in e)if(r in t){let i=t[r];if(i===null)continue;typeof i=="object"&&!Array.isArray(i)&&typeof e[r]=="object"&&!Array.isArray(e[r])&&e[r]!==null?n[r]=Hh(e[r],i):n[r]=i}else n[r]=e[r];for(let r in t)!(r in e)&&t[r]!==null&&(n[r]=t[r]);return n}function mo(e){let t=[];for(let n in e)t.push(n);return t}var Xh="replicated-state",Xc=class{ackedResources={};dirtyResources={};unauthorizedKeys={};loadingResources={};loadingPromises=new Map;loadedResources=new Set;registeredResources=new Set;resourceChangeListeners=new Set;snapshotWaiters=new Map;storage;socketSession;logger;inflightItems=new Map;constructor(t,n,r){this.storage=t,this.socketSession=n,this.logger=r}onResourceChange(t){return this.resourceChangeListeners.add(t),()=>this.resourceChangeListeners.delete(t)}registerResource(t){this.registeredResources.add(t),this.initializeResource(t)}isResourceRegistered(t){return this.registeredResources.has(t)}getRegisteredResources(){return Array.from(this.registeredResources)}setDirtyItems(t,n){this.registerResource(t),this.dirtyResources[t]=Yr(n)}setDirtyItem(t,n,r){if(this.registerResource(t),r===void 0){delete this.dirtyResources[t][n];return}this.dirtyResources[t][n]=Yr(r)}clearSessionState(){this.ackedResources={},this.loadingResources={},this.loadingPromises.clear(),this.loadedResources.clear(),this.inflightItems.clear();for(let t of this.registeredResources)this.dirtyResources[t]={},this.unauthorizedKeys[t]={},this.loadingResources[t]=!0,this.emitResourceChange(t)}async loadRegisteredResourcesFromStorage(){await Promise.all(Array.from(this.registeredResources,t=>this.loadResourceFromStorage(t)))}async hydrate(t,n){this.registerResource(t),await this.loadResourceFromStorage(t),this.logger.info(`Calculating lastUpdatedAtSeen from ${jh(this.ackedResources[t])} items`);let r=this.prepareSnapshotQuery(t,n);this.logger.info(`\u{1F4F8} ${t} requested with query:`,r),this.socketSession.send(Xh,{resource:t,action:"snapshot",value:r})}hydrateAll(t){return this.hydrate(t,{all:!0})}async waitForSnapshot(t,n){await new Promise((r,i)=>{let o,a=()=>{clearTimeout(o),r()};o=setTimeout(()=>{this.snapshotWaiters.get(t)?.delete(a),i(new Error(`snapshot timeout for ${t}`))},n),this.snapshotWaiters.has(t)||this.snapshotWaiters.set(t,new Set),this.snapshotWaiters.get(t).add(a)})}processSocketEvent(t){switch(t.action){case"snapshot":this.applySnapshot(t.resource,t.value??{});break;case"delta":this.applyRemoteDelta(t);break}}async upsertItem(t,n){this.registerResource(t);let r=this.getAckedValue(t,n.id),i=nd(r,n);return i.pre===null&&i.post===null?!0:this.sendDelta(t,n.id,i,n)}async deleteItem(t,n){this.registerResource(t);let r=this.getAckedValue(t,n),i=nd(r,null);return i.pre===null&&i.post===null?!0:this.sendDelta(t,n,i,null)}isItemInflight(t,n){return this.inflightItems.get(t)?.has(n)===!0}async sendDelta(t,n,r,i){this.registerResource(t),this.inflightItems.has(t)||this.inflightItems.set(t,new Set);let o=this.inflightItems.get(t);if(o.has(n))return!1;let a=this.getDirtyValue(t,n);Hc(a,r)&&(arguments.length>=4?this.setDirtyValue(t,n,Yr(i)):this.setDirtyValue(t,n,od(a,Yr(r))),this.emitResourceChange(t)),o.add(n);let s;try{s=await this.socketSession.sendWithAck(Xh,{resource:t,action:"delta",key:n,value:r})}catch(c){s={ok:!1,reason:c instanceof Error?c.message:"error"}}return o.delete(n),s.ok?!0:(this.revertDirtyToAckedValue(t,n),this.emitResourceChange(t),this.logger.error(`!ack[${t}] Reverting to acked state for ${t}:${n}`,s.reason),!1)}getAckedValue(t,n){return this.initializeResource(t),this.ackedResources[t][n]??null}getDirtyValue(t,n){return this.initializeResource(t),this.dirtyResources[t][n]??null}getVisibleItems(t){this.initializeResource(t);let n={};for(let r in this.dirtyResources[t]){let i=this.dirtyResources[t][r];i!=null&&(n[r]=i)}return n}getRawItems(t){return this.initializeResource(t),Yr(this.dirtyResources[t])}getAckedItems(t){return this.initializeResource(t),Yr(this.ackedResources[t])}getUnauthorizedKeys(t){return this.initializeResource(t),Yr(this.unauthorizedKeys[t])}isResourceLoading(t){return this.initializeResource(t),this.loadingResources[t]}initializeResource(t){this.ackedResources[t]===void 0&&(this.ackedResources[t]={}),this.dirtyResources[t]===void 0&&(this.dirtyResources[t]={}),this.unauthorizedKeys[t]===void 0&&(this.unauthorizedKeys[t]={}),this.loadingResources[t]===void 0&&(this.loadingResources[t]=!0)}prepareSnapshotQuery(t,n){this.initializeResource(t);let r=Yr(n);if(r.lastUpdatedAtSeen!==void 0)return r;let i=this.buildLastUpdatedAtSeen(t,r);return $h(i)||(r.lastUpdatedAtSeen=i),r}async loadResourceFromStorage(t){if(this.initializeResource(t),this.loadedResources.has(t))return;if(this.loadingPromises.has(t))return this.loadingPromises.get(t);let n=this.loadResourceItemsFromStorage(t);this.loadingPromises.set(t,n);try{await n}finally{this.loadingPromises.delete(t),this.loadedResources.add(t)}}async loadResourceItemsFromStorage(t){let n=!1,r=0;try{let i=await this.storage.loadItems(t);if(i&&$h(this.ackedResources[t])){n=!0;for(let o in i)this.applyCachedItem(t,o,i[o])&&(r+=1)}}catch(i){this.logger.warn(`Failed to load cached ${t}: ${String(i)}`)}finally{this.loadingResources[t]=!1,this.emitResourceChange(t),n?this.logger.info(`\u{1F4C2} ${r}x ${t} from cache`):this.logger.info(`\u{1F4C2} no cached data for ${t}`)}}applyCachedItem(t,n,r){return r===null?(this.ackedResources[t][n]=null,this.dirtyResources[t][n]=null,!0):r==="unauthorized"?(this.unauthorizedKeys[t][n]=!0,!1):(this.ackedResources[t][n]=Yr(r),this.dirtyResources[t][n]=Yr(r),!0)}applySnapshot(t,n){this.initializeResource(t);for(let r in n){let i=n[r];i===null?(this.ackedResources[t][r]=null,(!this.isItemInflight(t,r)||this.getDirtyValue(t,r)==null)&&(this.dirtyResources[t][r]=null),delete this.unauthorizedKeys[t][r]):i==="unauthorized"?(delete this.ackedResources[t][r],delete this.dirtyResources[t][r],this.unauthorizedKeys[t][r]=!0):(this.ackedResources[t][r]=Yr(i),this.dirtyResources[t][r]=Yr(i),delete this.unauthorizedKeys[t][r]),this.storage.persistItem(t,r,i).catch(o=>{this.logger.warn(`Failed to persist ${t}:${r}: ${String(o)}`)})}this.loadingResources[t]=!1,this.emitResourceChange(t),this.logger.info(`\u{1F4F8} ${jh(n)}x ${t} `),this.resolveSnapshotWaiters(t)}applyRemoteDelta(t){let n=t.resource,r=t.key;if(!r)return;this.initializeResource(n);let i=t.value,o={pre:i.pre,post:i.post},a=this.getAckedValue(n,r);if(!Hc(a,o))this.logger.error(`\u{1D6AB}S precondition invalid on last acked for ${n}:${r}`,{pre:o.pre,post:o.post,current:a});else{let c=id(a,Yr(i));this.ackedResources[n][r]=c,this.storage.persistItem(n,r,c).catch(d=>{this.logger.warn(`Failed to persist ${n}:${r}: ${String(d)}`)}),this.logger.info(ad(`\u{1D6AB}S[${n}] acked`,o))}let s=this.getDirtyValue(n,r);t.by!==this.socketSession.getSessionId()?Hc(s,o)?o.post===null?(this.dirtyResources[n][r]=null,this.logger.info(ad(`\u{1D6AB}S[${n}] dirty`,o))):(this.dirtyResources[n][r]=id(s,Yr(i)),this.logger.info(ad(`\u{1D6AB}S[${n}] dirty`,o))):(this.logger.warn(`Skip delta on dirty for ${n}:${r}`,{pre:o.pre,post:o.post,current:a}),this.revertDirtyToAckedValue(n,r)):o.post!=null&&s!=null&&typeof s=="object"&&(s.updatedAt=i.updatedAt,this.dirtyResources[n][r]=s,this.logger.info(`\u{1D6AB}S[${n}] dirty updatedAt for ${r}`)),this.emitResourceChange(n)}buildLastUpdatedAtSeen(t,n){let r=this.ackedResources[t],i={};if(n.all){for(let o in r)this.copyItemUpdatedAt(r[o],o,i);return i}if(n.keys&&n.keys.length>0)for(let o of n.keys)this.copyItemUpdatedAt(r[o],o,i);return i}copyItemUpdatedAt(t,n,r){t&&typeof t=="object"&&typeof t.updatedAt=="number"&&(r[n]=t.updatedAt)}setDirtyValue(t,n,r){if(r===null){this.dirtyResources[t][n]=null;return}this.dirtyResources[t][n]=r}revertDirtyToAckedValue(t,n){let r=this.ackedResources[t][n];if(r===void 0){delete this.dirtyResources[t][n];return}if(r===null){this.dirtyResources[t][n]=null;return}this.dirtyResources[t][n]=Yr(r)}emitResourceChange(t){let n={resource:t,acked:this.getAckedItems(t),dirty:this.getRawItems(t),unauthorized:this.getUnauthorizedKeys(t),loading:this.loadingResources[t]};for(let r of this.resourceChangeListeners)r(n)}resolveSnapshotWaiters(t){let n=this.snapshotWaiters.get(t);if(n){this.snapshotWaiters.delete(t);for(let r of n)r()}}};function Yr(e){if(e===void 0)return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}function $h(e){for(let t in e)return!1;return!0}function jh(e){let t=0;for(let n in e)t+=1;return t}function ad(e,t){return`${e}
28
28
  delta.pre: ${JSON.stringify(t.pre)}
29
29
  delta.post: ${JSON.stringify(t.post)}`}var $c=15e3,ZR=2e3,cd=class{replicatedState;recordStorage;gatewaySocketSession;startPromise;reconnectTimer;registeredResources=new Set(qh);closed=!1;start(){return this.startPromise?this.startPromise:(this.closed=!1,this.startPromise=this.connectAndHydrate().catch(t=>{throw this.startPromise=void 0,t}),this.startPromise)}async hydrateResource(t,n={all:!0}){this.registerResource(t),await this.start(),await this.hydrateConnectedResource(t,n)}async readResourceItems(t,n={all:!0}){return this.registerResource(t),await this.start(),this.filterVisibleItems(t,n)}async readResourceItem(t,n){this.registerResource(t),await this.start();let r=this.replicatedState?.getVisibleItems(t)[n]??null;return Yh(t,r)}async upsertResourceItem(t,n){if(this.registerResource(t),await this.start(),!this.replicatedState)throw new Error("replicated state not initialized");return this.replicatedState.upsertItem(t,n)}async deleteResourceItem(t,n){if(this.registerResource(t),await this.start(),!this.replicatedState)throw new Error("replicated state not initialized");return this.replicatedState.deleteItem(t,n)}waitForChannelEvent(t,n,r=$c){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");return this.gatewaySocketSession.waitForChannelEvent(t,i=>n(i),r)}collectChannelEvents(t,n,r=$c,i=250){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");return this.gatewaySocketSession.collectChannelEvents(t,o=>n(o),r,i)}sendChannelEvent(t,n){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");this.gatewaySocketSession.send(t,n)}close(){this.closed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.startPromise=void 0,this.gatewaySocketSession?.close(),this.recordStorage?.close(),this.gatewaySocketSession=void 0,this.recordStorage=void 0,this.replicatedState=void 0}registerResource(t){Kh(t),this.registeredResources.add(t),this.replicatedState?.registerResource(t)}async connectAndHydrate(){let t=await fi();if(!t)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let n=await di(t);await bh(n);let r=Ht(),i=Oo(n),o=vh(i.email);this.gatewaySocketSession?.close(),this.recordStorage?.close(),this.recordStorage=new Lc(r.replicatedStateDatabasePath,o),this.gatewaySocketSession=new Bc(r.backendUrl,n),this.replicatedState=new Xc(this.recordStorage,this.gatewaySocketSession,rw),this.gatewaySocketSession.onChannel("replicated-state",a=>this.replicatedState?.processSocketEvent(a)),this.gatewaySocketSession.onDisconnected(()=>this.scheduleReconnect());for(let a of this.registeredResources)this.replicatedState.registerResource(a);await this.gatewaySocketSession.connect($c),await this.replicatedState.loadRegisteredResourcesFromStorage(),await this.hydrateRegisteredResources()}async hydrateRegisteredResources(){await Promise.all(Array.from(this.registeredResources,t=>this.hydrateConnectedResource(t,{all:!0})))}async hydrateConnectedResource(t,n){if(!this.replicatedState)throw new Error("replicated state not initialized");let r=this.replicatedState.waitForSnapshot(t,$c);await this.replicatedState.hydrate(t,n),await r}filterVisibleItems(t,n){let r=this.replicatedState?.getVisibleItems(t)??{},i={};for(let o in r)ew(o,r[o],n)&&(i[o]=Yh(t,r[o]));return i}scheduleReconnect(){this.closed||this.reconnectTimer||(this.startPromise=void 0,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.start().catch(()=>this.scheduleReconnect())},ZR))}};function ew(e,t,n){return tw(e,t,n.lastUpdatedAtSeen)?!!(n.all||n.keys?.includes(e)||nw(t,n.fieldEqualTo)):!1}function Yh(e,t){if(e!=="connections"||!t||typeof t!="object"||Array.isArray(t))return t;let n={...t};return delete n.config,n}function tw(e,t,n){let r=n?.[e];if(r===void 0||!t||typeof t!="object")return!0;let i=t.updatedAt;return typeof i!="number"||i>r}function nw(e,t){if(!t||!e||typeof e!="object")return!1;let n=e,r=!1;for(let i in t)if(r=!0,!JR(n[i],t[i]))return!1;return r}var rw={info(e,t){sd("info",e,t)},warn(e,t){sd("warn",e,t)},error(e,t){sd("error",e,t)}};function sd(e,t,n){let r=n===void 0?"":` ${JSON.stringify(n)}`;process.stderr.write(`[replicated-state:${e}] ${t}${r}
30
30
  `)}var ud;function _s(){return ud||(ud=new cd),ud}import{isDeepStrictEqual as iw}from"node:util";function dn(e,t){let n=Wc(e);if(!n)throw new Error(`missing schema for resource: ${e}`);let r={failures:[],rootSchema:n.itemSchema};if(gs(n.itemSchema,t,"$",r),r.failures.length===0)return;let i=r.failures.slice(0,5).map(o=>`${o.path} ${o.message}`).join("; ");throw new Error(`item does not match ${e} schema: ${i}`)}function gs(e,t,n,r){if(e===!0)return;if(e===!1)return ho(r,n,"is not allowed");if(!hw(e))return;let i=e.$ref;if(typeof i=="string"){gs(pw(i,r.rootSchema),t,n,r);return}ow(e,t,n,r)&&(aw(e,t,n,r),sw(e,t,n,r),uw(e,t,n,r),lw(e,t,n,r))}function ow(e,t,n,r){if(!Array.isArray(e.anyOf))return!0;for(let i of e.anyOf){let o={failures:[],rootSchema:r.rootSchema};if(gs(i,t,n,o),o.failures.length===0)return!1}return ho(r,n,"does not match any allowed schema"),!1}function aw(e,t,n,r){let i=e.enum;if(Array.isArray(i)){for(let o of i)if(iw(t,o))return;ho(r,n,`must be one of ${i.map(String).join(", ")}`)}}function sw(e,t,n,r){let i=e.type;if(typeof i=="string"&&!Qh(t,i)){ho(r,n,`must be ${i}`);return}if(Array.isArray(i)){for(let o of i)if(typeof o=="string"&&Qh(t,o))return;ho(r,n,`must be ${i.map(String).join(" or ")}`)}}function uw(e,t,n,r){if(e.type!=="object"||!hu(t))return;let i=hu(e.properties)?e.properties:{};cw(e,t,n,r);for(let o of dw(e))(!(o in t)||t[o]===void 0)&&ho(r,`${n}.${o}`,"is required");for(let o in t){if(t[o]===void 0){ho(r,`${n}.${o}`,"must not be undefined");continue}if(o in i){gs(i[o],t[o],`${n}.${o}`,r);continue}fw(e,t[o],`${n}.${o}`,r)}}function cw(e,t,n,r){let i=0;for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&i++;let o=e.minProperties;typeof o=="number"&&i<o&&ho(r,n,`must have at least ${o} properties`);let a=e.maxProperties;typeof a=="number"&&i>a&&ho(r,n,`must have at most ${a} properties`)}function lw(e,t,n,r){if(e.type!=="array"||!Array.isArray(t))return;let i=e.items;if(i!==void 0)for(let o=0;o<t.length;o++)gs(i,t[o],`${n}[${o}]`,r)}function fw(e,t,n,r){let i=e.additionalProperties;if(i===!1){ho(r,n,"is not allowed");return}i===void 0||i===!0||gs(i,t,n,r)}function dw(e){return Array.isArray(e.required)?e.required.filter(t=>typeof t=="string"):[]}function pw(e,t){if(!e.startsWith("#/"))return!1;let n=t,r=e.slice(2).split("/").map(mw);for(let i of r){if(!hu(n)||!(i in n))return!1;n=n[i]}return n}function mw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Qh(e,t){switch(t){case"array":return Array.isArray(e);case"boolean":return typeof e=="boolean";case"integer":return Number.isInteger(e);case"null":return e===null;case"number":return typeof e=="number"&&Number.isFinite(e);case"object":return hu(e);case"string":return typeof e=="string";default:return!0}}function hw(e){return hu(e)}function hu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ho(e,t,n){e.failures.push({path:t,message:n})}import ld from"node:fs/promises";import _w from"node:os";import Jh from"node:path";var gw=15e3;async function jc(e){let t=await e0({method:"GET",path:e});if(!t.ok)throw await t0(e,t);return await t.json()}async function Zh(e){let t=await e0(e),n={status:t.status,statusText:t.statusText,headers:Tw(t.headers)};if(t.status>=300&&t.status<400)return{...n,location:t.headers.get("location")};if(!t.ok)throw await t0(e.path,t);return e.responseMode==="binary"?await Dw(t,e,n):(t.headers.get("content-type")??"").includes("application/json")?{...n,body:await t.json().catch(()=>null)}:{...n,body:await t.text().catch(()=>"")}}async function e0(e){let t=await vw(),n=yw(e.path,e.query),r=new Headers({Authorization:`Bearer ${t}`}),i=e.timeoutMs??gw;Sw(r,e.headers);let o={method:e.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(i)};e.requestMode==="multipart"?o.body=await Aw(e):e.requestMode==="form"?(o.body=ww(e.body),r.set("Content-Type","application/x-www-form-urlencoded")):e.body!==void 0&&e.method!=="GET"&&e.method!=="HEAD"&&(r.set("Content-Type","application/json"),o.body=JSON.stringify(e.body));try{return await fetch(n,o)}catch(a){throw bw(a)?new Error(`backend endpoint timed out after ${i}ms: ${e.path}`):a}}function bw(e){return e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError")}async function vw(){let e=await fi();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");return await di(e)}function Sw(e,t){if(t)for(let n in t){let r=t[n];r!=null&&e.set(n,String(r))}}function yw(e,t){if(!e.startsWith("/"))throw new Error(`backend endpoint path must start with /: ${e}`);let n=Ht(),r=new URL(`${n.backendUrl}${e}`);return Ew(r,t),r.toString()}function Ew(e,t){if(t)for(let n in t){let r=t[n];if(r!=null){if(Array.isArray(r)){for(let i of r)e.searchParams.append(n,String(i));continue}e.searchParams.set(n,String(r))}}}function Tw(e){let t={};return e.forEach((n,r)=>{t[r]=n}),t}async function Aw(e){let t=new FormData,n=e.body;if(n&&typeof n=="object"&&!Array.isArray(n))for(let i in n){let o=n[i];o!=null&&t.set(i,String(o))}let r=e.files??{};for(let i in r)t.set(i,await Rw(r[i]),r[i].fileName??i);return t}async function Rw(e){if(e.filePath)return new Blob([await ld.readFile(e.filePath)],{type:e.contentType});if(e.base64)return new Blob([Buffer.from(e.base64,"base64")],{type:e.contentType});throw new Error("multipart file input must include filePath or base64")}function ww(e){let t=new URLSearchParams;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let n in e){let r=e[n];r!=null&&t.set(n,String(r))}return t}async function Dw(e,t,n){let r=Buffer.from(await e.arrayBuffer()),i=t.outputFilePath??Cw(e);return await ld.mkdir(Jh.dirname(i),{recursive:!0}),await ld.writeFile(i,r),{...n,filePath:i,sizeBytes:r.byteLength,contentType:e.headers.get("content-type")}}function Cw(e){let t=e.headers.get("content-disposition")??"",r=/filename="?([^";]+)"?/i.exec(t)?.[1]?.replace(/[^A-Za-z0-9._-]/g,"_")||`beepflow-download-${Date.now()}.bin`;return Jh.join(_w.tmpdir(),"beepflow-mcp-downloads",r)}async function t0(e,t){let n=await t.text().catch(()=>"");return new Error(`${e} failed: ${t.status} ${n}`.trim())}async function fd(e){return xw(await dd(e))}async function r0(){return await jc("/integrations")}async function i0(e,t){return await jc(`/integrations/blueprint-contexts${Ow(e,t)}`)}async function dd(e){return kw(await jc(`/integrations/${encodeURIComponent(e)}/openapi`))}function Ow(e,t){let n=new URLSearchParams;e&&n.set("integrationType",e),t&&n.set("resourceType",t);let r=n.toString();return r?`?${r}`:""}async function o0(e){let n=(await fd(e.integrationType)).find(i=>i.operationId===e.operationId);if(!n)throw new Error(`unsupported integration endpoint: ${e.operationId}`);Bw(n,e.confirm);let r=Uw(n,e.payload);if(n.requestMode==="none"&&r.body!==void 0)throw new Error(`integration endpoint ${n.operationId} has requestBody=null; remove body-only fields from payload`);return await Zh({method:n.method,path:Gw(n,r.path),query:r.query,headers:r.headers,body:r.body,requestMode:n.requestMode,responseMode:n.responseMode,files:r.files,outputFilePath:e.outputFilePath})}function kw(e){let t=_u(e,"paths");for(let n in t){let r=t[n];if(pn(r))for(let i in r){let o=r[i];pn(o)&&(o.payloadSchema=a0(o))}}return e}function xw(e){let t=_u(e,"paths"),n=[];for(let r in t){let i=t[r];if(pn(i))for(let o in i){let a=i[o];pn(a)&&n.push(Iw(o.toUpperCase(),r,a))}}return n}function Iw(e,t,n){let r=_u(n,"x-beepflow");return{operationId:ka(n,"operationId"),integrationType:ka(r,"integrationType"),resourceType:Hw(r,"resourceType"),method:e,path:t,originalPath:ka(r,"originalPath"),summary:ka(n,"summary"),access:ka(r,"access"),sideEffect:ka(r,"sideEffect"),mcpExposure:ka(r,"mcpExposure"),requestMode:c0(n),responseMode:Mw(n),pathParameters:Ww(t),parameters:u0(n),payloadSchema:a0(n),requestBody:pi(n,"requestBody"),responses:_u(n,"responses"),runtimeUse:"mcp-only",externalAppUse:"forbidden",externalAppAlternative:"Create/use a blueprint with webhook trigger and call /api/:tabId/trigger."}}function a0(e){let t=c0(e),n=Fw(e,t),r={type:"object",additionalProperties:!1,properties:{}},i=r.properties,o=[];for(let a of u0(e))!pn(a)||typeof a.name!="string"||!pn(a.schema)||(i[a.name]=a.schema,a.required===!0&&o.push(a.name));return Pw(r,i,o,n,t),o.length&&(r.required=o),r}function Pw(e,t,n,r,i){if(!r)return;let o=pi(r,"properties");if(!o){e.additionalProperties=r.additionalProperties??!0;return}for(let s in o)t[s]=Nw(o[s],i);r.additionalProperties!==void 0&&r.additionalProperties!==!1&&(e.additionalProperties=r.additionalProperties);let a=r.required;if(Array.isArray(a))for(let s of a)typeof s=="string"&&n.push(s)}function Nw(e,t){return t!=="multipart"||!pn(e)||e.format!=="binary"?e:{type:"object",additionalProperties:!1,description:"Multipart file input. Provide filePath or base64 content.",properties:{filePath:{type:"string",description:"Local file path to read and upload."},base64:{type:"string",description:"Base64-encoded file content."},fileName:{type:"string",description:"File name to send for base64 content."},contentType:{type:"string",description:"MIME type for uploaded content."}}}}function Fw(e,t){let n=pi(e,"requestBody");if(!n)return null;let r=pi(n,"content");if(!r)return null;let i=s0(t),o=pi(r,i);return o?pi(o,"schema"):null}function s0(e){switch(e){case"multipart":return"multipart/form-data";case"form":return"application/x-www-form-urlencoded";default:return"application/json"}}function u0(e){let t=e.parameters;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid integration OpenAPI schema: parameters must be array");return t}function c0(e){let t=pi(e,"requestBody");if(!t)return"none";let n=pi(t,"content");return n?pn(n["multipart/form-data"])?"multipart":pn(n["application/x-www-form-urlencoded"])?"form":(pn(n["application/json"]),"json"):"none"}function Mw(e){let t=_u(e,"responses");for(let i in t)if(i.startsWith("3")&&pn(t[i]))return"redirect";let n=Lw(t);if(!n)return"empty";let r=pi(n,"content");return r?pn(r["application/octet-stream"])?"binary":pn(r["text/plain"])?"text":(pn(r["application/json"]),"json"):"empty"}function Lw(e){if(pn(e[200]))return e[200];for(let t in e)if(t.startsWith("2")&&pn(e[t]))return e[t];return null}function Bw(e,t){if(!(e.mcpExposure==="safe"&&e.sideEffect!=="destructive")&&t!==!0)throw new Error(`integration endpoint requires confirm=true: ${e.operationId}`)}function Uw(e,t){let n={path:{},query:{},headers:{}},r=t??{},i=Kw(e);for(let o of e.parameters){if(!pn(o)||typeof o.name!="string"||typeof o.in!="string")continue;let a=r[o.name];a!==void 0&&(o.in==="path"&&(n.path[o.name]=a),o.in==="query"&&(n.query[o.name]=a),o.in==="header"&&(n.headers[o.name]=a))}if(e.requestMode!=="none")Vw(e,r,i,n);else for(let o in r)i.has(o)||(n.body={[o]:r[o]});return n}function Vw(e,t,n,r){let i=zw(e),o=i?pi(i,"properties"):null,a={},s={};if(o){for(let c in o)qw(e,c,t[c],a,s);if(i?.additionalProperties!==void 0&&i.additionalProperties!==!1)for(let c in t)!n.has(c)&&o[c]===void 0&&(a[c]=t[c])}else if(i?.additionalProperties!==!1)for(let c in t)n.has(c)||(a[c]=t[c]);n0(a)&&(r.body=a),n0(s)&&(r.files=s)}function qw(e,t,n,r,i){if(n!==void 0){if(e.requestMode==="multipart"&&pn(n)&&(typeof n.filePath=="string"||typeof n.base64=="string")){i[t]=n;return}r[t]=n}}function zw(e){if(!e.requestBody)return null;let t=pi(e.requestBody,"content"),n=t?pi(t,s0(e.requestMode)):null;return n?pi(n,"schema"):null}function Kw(e){let t=new Set;for(let n of e.parameters)pn(n)&&typeof n.name=="string"&&t.add(n.name);return t}function n0(e){for(let t in e)if(e[t]!==void 0)return!0;return!1}function Gw(e,t){let n=e.path;for(let r of e.pathParameters){let i=t?.[r];if(typeof i!="string"&&typeof i!="number")throw new Error(`integration endpoint path parameter required: ${r}`);n=n.replace(`{${r}}`,encodeURIComponent(String(i)))}return n}function Ww(e){let t=[];for(let n of e.matchAll(/\{([^}]+)\}/g))n[1]&&t.push(n[1]);return t}function _u(e,t){if(!pn(e)||!pn(e[t]))throw new Error(`invalid integration OpenAPI schema: ${t} must be object`);return e[t]}function pi(e,t){if(!pn(e)||e[t]===void 0||e[t]===null)return null;if(!pn(e[t]))throw new Error(`invalid integration OpenAPI schema: ${t} must be object`);return e[t]}function ka(e,t){if(typeof e[t]!="string")throw new Error(`invalid integration OpenAPI schema: ${t} must be string`);return e[t]}function Hw(e,t){if(e[t]===void 0||e[t]===null)return null;if(typeof e[t]!="string")throw new Error(`invalid integration OpenAPI schema: ${t} must be string`);return e[t]}function pn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var l0="For Beepflow tasks, call status first and follow the instructions field returned in the status response. Treat client-saved tool outputs as historical logs; verify resource ids with live MCP queries.",bs=`
@@ -98,7 +98,7 @@ Input files:
98
98
  `,""}).replace(/[ \n\r\t\f]*?[\n\r][ \n\r\t\f]*$/,function(){return a=`
99
99
  `,""})),n&&(e=e.replace(/^[ \n\r\t\f\xA0]+/,function(s){let c=!o&&t.conservativeCollapse;return c&&s===" "?" ":s.replace(/^[^\xA0]+/,"").replace(/(\xA0+)[^\xA0]+/g,"$1 ")||(c?" ":"")})),r&&(e=e.replace(/[ \n\r\t\f\xA0]+$/,function(s){let c=!a&&t.conservativeCollapse;return c&&s===" "?" ":s.replace(/[^\xA0]+(\xA0+)/g," $1").replace(/[^\xA0]+$/,"")||(c?" ":"")})),i&&(e=Of(e)),o+e+a}var qm=new Set(["a","abbr","acronym","b","bdi","bdo","big","button","cite","code","del","dfn","em","font","i","ins","kbd","label","mark","math","nobr","object","q","rp","rt","rtc","ruby","s","samp","select","small","span","strike","strong","sub","sup","svg","textarea","time","tt","u","var"]),kf=new Set(["a","abbr","acronym","b","big","del","em","font","i","ins","kbd","mark","nobr","rp","s","samp","small","span","strike","strong","sub","sup","time","tt","u","var"]),VA=new Set(["comment","img","input","wbr"]);function qA(e,t,n,r){let i=t&&!VA.has(t);i&&!r.collapseInlineTagWhitespace&&(i=t.charAt(0)==="/"?!qm.has(t.slice(1)):!kf.has(t));let o=n&&!VA.has(n);return o&&!r.collapseInlineTagWhitespace&&(o=n.charAt(0)==="/"?!kf.has(n.slice(1)):!qm.has(n)),cs(e,r,i,o,t&&n)}function P8(e){return/^\[if\s[^\]]+]|\[endif]$/.test(e)}function N8(e,t){for(let n=0,r=t.ignoreCustomComments.length;n<r;n++)if(t.ignoreCustomComments[n].test(e))return!0;return!1}function F8(e,t){let n=t.customEventAttributes;if(n){for(let r=n.length;r--;)if(n[r].test(e))return!0;return!1}return/^on[a-z]{3,}$/.test(e)}function M8(e){return/^[^ \t\n\f\r"'`=<>]+$/.test(e)}function zA(e,t){for(let n=e.length;n--;)if(e[n].name.toLowerCase()===t)return!0;return!1}function L8(e,t,n,r){return n=n?li(n.toLowerCase()):"",e==="script"&&t==="language"&&n==="javascript"||e==="form"&&t==="method"&&n==="get"||e==="input"&&t==="type"&&n==="text"||e==="script"&&t==="charset"&&!zA(r,"src")||e==="a"&&t==="name"&&zA(r,"id")||e==="area"&&t==="shape"&&n==="rect"}var B8=new Set(["text/javascript","text/ecmascript","text/jscript","application/javascript","application/x-javascript","application/ecmascript","module"]),U8=new Set(["module"]);function jA(e=""){return e=li(e.split(/;/,2)[0]).toLowerCase(),e===""||B8.has(e)}function V8(e=""){return e=li(e.split(/;/,2)[0]).toLowerCase(),U8.has(e)}function q8(e,t){if(e!=="script")return!1;for(let n=0,r=t.length;n<r;n++)if(t[n].name.toLowerCase()==="type")return jA(t[n].value);return!0}function YA(e=""){return e=li(e).toLowerCase(),e===""||e==="text/css"}function QA(e,t){if(e!=="style")return!1;for(let n=0,r=t.length;n<r;n++)if(t[n].name.toLowerCase()==="type")return YA(t[n].value);return!0}var z8=new Set(["allowfullscreen","async","autofocus","autoplay","checked","compact","controls","declare","default","defaultchecked","defaultmuted","defaultselected","defer","disabled","enabled","formnovalidate","hidden","indeterminate","inert","ismap","itemscope","loop","multiple","muted","nohref","noresize","noshade","novalidate","nowrap","open","pauseonexit","readonly","required","reversed","scoped","seamless","selected","sortable","truespeed","typemustmatch","visible"]),K8=new Set(["true","false"]);function G8(e,t){return z8.has(e)||e==="draggable"&&!K8.has(t)}function W8(e,t){return/^(?:a|area|link|base)$/.test(t)&&e==="href"||t==="img"&&/^(?:src|longdesc|usemap)$/.test(e)||t==="object"&&/^(?:classid|codebase|data|usemap)$/.test(e)||t==="q"&&e==="cite"||t==="blockquote"&&e==="cite"||(t==="ins"||t==="del")&&e==="cite"||t==="form"&&e==="action"||t==="input"&&(e==="src"||e==="usemap")||t==="head"&&e==="profile"||t==="script"&&(e==="src"||e==="for")}function H8(e,t){return/^(?:a|area|object|button)$/.test(t)&&e==="tabindex"||t==="input"&&(e==="maxlength"||e==="tabindex")||t==="select"&&(e==="size"||e==="tabindex")||t==="textarea"&&/^(?:rows|cols|tabindex)$/.test(e)||t==="colgroup"&&e==="span"||t==="col"&&e==="span"||(t==="th"||t==="td")&&(e==="rowspan"||e==="colspan")}function JA(e,t,n){if(e!=="link")return!1;for(let r=0,i=t.length;r<i;r++)if(t[r].name==="rel"&&t[r].value===n)return!0}function X8(e,t,n){return n==="media"&&(JA(e,t,"stylesheet")||QA(e,t))}var $8=new Set(["img","source"]);function j8(e,t){return e==="srcset"&&$8.has(t)}async function Y8(e,t,n,r,i){if(F8(t,r))return n=li(n).replace(/^javascript:\s*/i,""),r.minifyJS(n,!0);if(t==="class")return n=li(n),r.sortClassName?n=r.sortClassName(n):n=Of(n),n;if(W8(t,e))return n=li(n),JA(e,i,"canonical")?n:r.minifyURLs(n);if(H8(t,e))return li(n);if(t==="style")return n=li(n),n&&(/;$/.test(n)&&!/&#?[0-9a-zA-Z]+;$/.test(n)&&(n=n.replace(/\s*;$/,";")),n=await r.minifyCSS(n,"inline")),n;if(j8(t,e))n=li(n).split(/\s+,\s*|\s*,\s+/).map(function(o){let a=o,s="",c=o.match(/\s+([1-9][0-9]*w|[0-9]+(?:\.[0-9]+)?x)$/);if(c){a=a.slice(0,-c[0].length);let d=+c[1].slice(0,-1),p=c[1].slice(-1);(d!==1||p!=="x")&&(s=" "+d+p)}return r.minifyURLs(a)+s}).join(", ");else if(Q8(e,i)&&t==="content")n=n.replace(/\s+/g,"").replace(/[0-9]+\.[0-9]+/g,function(o){return(+o).toString()});else{if(J8(e,i)&&t.toLowerCase()==="content")return Of(n);if(r.customAttrCollapse&&r.customAttrCollapse.test(t))n=li(n.replace(/ ?[\n\r]+ ?/g,"").replace(/\s{2,}/g,r.conservativeCollapse?" ":""));else if(e==="script"&&t==="type")n=li(n.replace(/\s*;\s*/g,";"));else if(X8(e,i,t))return n=li(n),r.minifyCSS(n,"media")}return n}function Q8(e,t){if(e!=="meta")return!1;for(let n=0,r=t.length;n<r;n++)if(t[n].name==="name"&&t[n].value==="viewport")return!0}function J8(e,t){if(e!=="meta")return!1;for(let n=0,r=t.length;n<r;n++)if(t[n].name.toLowerCase()==="http-equiv"&&t[n].value.toLowerCase()==="content-security-policy")return!0}function KA(e){return"/* clean-css ignore:start */"+e+"/* clean-css ignore:end */"}function ZA(e,t){switch(t){case"inline":return"*{"+e+"}";case"media":return"@media "+e+"{a{top:0}}";default:return e}}function Z8(e,t){let n;switch(t){case"inline":n=e.match(/^\*\{([\s\S]*)\}$/);break;case"media":n=e.match(/^@media ([\s\S]*?)\s*{[\s\S]*}$/);break}return n?n[1]:e}async function eU(e,t){return t.processConditionalComments?await _c(e,/^(\[if\s[^\]]+]>)([\s\S]*?)(<!\[endif])$/,async function(n,r,i,o){return r+await xf(i,t,!0)+o}):e}async function tU(e,t,n){for(let r=0,i=n.length;r<i;r++)if(n[r].name.toLowerCase()==="type"&&t.processScripts.indexOf(n[r].value)>-1)return await xf(e,t);return e}var nU=new Set(["html","head","body","colgroup","tbody"]),rU=new Set(["html","head","body","li","dt","dd","p","rb","rt","rtc","rp","optgroup","option","colgroup","caption","thead","tbody","tfoot","tr","td","th"]),iU=new Set(["meta","link","script","style","template","noscript"]),oU=new Set(["dt","dd"]),aU=new Set(["address","article","aside","blockquote","details","div","dl","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","main","menu","nav","ol","p","pre","section","table","ul"]),sU=new Set(["a","audio","del","ins","map","noscript","video"]),uU=new Set(["rb","rt","rtc","rp"]),cU=new Set(["rb","rtc","rp"]),lU=new Set(["option","optgroup"]),fU=new Set(["tbody","tfoot"]),dU=new Set(["thead","tbody","tfoot"]),pU=new Set(["td","th"]),GA=new Set(["html","head","body"]),mU=new Set(["html","body"]),hU=new Set(["head","colgroup","caption"]),WA=new Set(["dt","thead"]),HA=new Set(["a","abbr","acronym","address","applet","area","article","aside","audio","b","base","basefont","bdi","bdo","bgsound","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","command","content","data","datalist","dd","del","details","dfn","dialog","dir","div","dl","dt","element","em","embed","fieldset","figcaption","figure","font","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","image","img","input","ins","isindex","kbd","keygen","label","legend","li","link","listing","main","map","mark","marquee","menu","menuitem","meta","meter","multicol","nav","nobr","noembed","noframes","noscript","object","ol","optgroup","option","output","p","param","picture","plaintext","pre","progress","q","rb","rp","rt","rtc","ruby","s","samp","script","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr","xmp"]);function _U(e,t){switch(e){case"html":case"head":return!0;case"body":return!iU.has(t);case"colgroup":return t==="col";case"tbody":return t==="tr"}return!1}function gU(e,t){switch(t){case"colgroup":return e==="colgroup";case"tbody":return dU.has(e)}return!1}function bU(e,t){switch(e){case"html":case"head":case"body":case"colgroup":case"caption":return!0;case"li":case"optgroup":case"tr":return t===e;case"dt":case"dd":return oU.has(t);case"p":return aU.has(t);case"rb":case"rt":case"rp":return uU.has(t);case"rtc":return cU.has(t);case"option":return lU.has(t);case"thead":case"tbody":return fU.has(t);case"tfoot":return t==="tbody";case"td":case"th":return pU.has(t)}return!1}var vU=new RegExp("^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(?:down|up|over|move|out)|key(?:press|down|up)))$");function SU(e,t,n,r){return!n||/^\s*$/.test(n)?typeof r.removeEmptyAttributes=="function"?r.removeEmptyAttributes(t,e):e==="input"&&t==="value"||vU.test(t):!1}function vc(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].name===e)return!0;return!1}function yU(e,t){switch(e){case"textarea":return!1;case"audio":case"script":case"video":if(vc("src",t))return!1;break;case"iframe":if(vc("src",t)||vc("srcdoc",t))return!1;break;case"object":if(vc("data",t))return!1;break;case"applet":if(vc("code",t))return!1;break}return!0}function e1(e){return!/^(?:script|style|pre|textarea)$/.test(e)}function t1(e){return!/^(?:pre|textarea)$/.test(e)}async function EU(e,t,n,r){let i=r.name(e.name),o=e.value;if(r.decodeEntities&&o&&(o=ju(o)),!(r.removeRedundantAttributes&&L8(n,i,o,t)||r.removeScriptTypeAttributes&&n==="script"&&i==="type"&&jA(o)&&!V8(o)||r.removeStyleLinkTypeAttributes&&(n==="style"||n==="link")&&i==="type"&&YA(o))&&(o&&(o=await Y8(n,i,o,r,t)),!(r.removeEmptyAttributes&&SU(n,i,o,r))))return r.decodeEntities&&o&&(o=o.replace(/&(#?[0-9a-zA-Z]+;)/g,"&amp;$1")),{attr:e,name:i,value:o}}function TU(e,t,n,r,i){let o=e.name,a=e.value,s=e.attr,c=s.quote,d,p;if(typeof a<"u"&&(!n.removeAttributeQuotes||~a.indexOf(i)||!M8(a))){if(!n.preventAttributesEscaping){if(typeof n.quoteCharacter>"u"){let m=(a.match(/'/g)||[]).length,g=(a.match(/"/g)||[]).length;c=m<g?"'":'"'}else c=n.quoteCharacter==="'"?"'":'"';c==='"'?a=a.replace(/"/g,"&#34;"):a=a.replace(/'/g,"&#39;")}p=c+a+c,!r&&!n.removeTagWhitespace&&(p+=" ")}else r&&!t&&!/\/$/.test(a)?p=a:p=a+" ";return typeof a>"u"||n.collapseBooleanAttributes&&G8(o.toLowerCase(),a.toLowerCase())?(d=o,r||(d+=" ")):d=o+s.customAssign+p,s.customOpen+d+s.customClose}function Sa(e){return e}function AU(e){return Promise.resolve(e)}var RU=e=>{let t={name:function(n){return n.toLowerCase()},canCollapseWhitespace:e1,canTrimWhitespace:t1,html5:!0,ignoreCustomComments:[/^!/,/^\s*#/],ignoreCustomFragments:[/<%[\s\S]*?%>/,/<\?[\s\S]*?\?>/],includeAutoGeneratedTags:!0,log:Sa,minifyCSS:AU,minifyJS:Sa,minifyURLs:Sa};return Object.keys(e).forEach(function(n){let r=e[n];if(n==="caseSensitive")r&&(t.name=Sa);else if(n==="log")typeof r=="function"&&(t.log=r);else if(n==="minifyCSS"&&typeof r!="function"){if(!r)return;let i=typeof r=="object"?r:{};t.minifyCSS=async function(o,a){o=o.replace(/(url\s*\(\s*)("|'|)(.*?)\2(\s*\))/ig,function(c,d,p,m,g){return d+p+t.minifyURLs(m)+p+g});let s=ZA(o,a);return new Promise(c=>{new zm.default(i).minify(s,(d,p)=>{p.errors.length>0&&(p.errors.forEach(t.log),c(o));let m=Z8(p.styles,a);c(m)})})}}else if(n==="minifyJS"&&typeof r!="function"){if(!r)return;let i=typeof r=="object"?r:{};i.parse={...i.parse,bare_returns:!1},t.minifyJS=async function(o,a){let s=o.match(/^\s*<!--.*/),c=s?o.slice(s[0].length).replace(/\n\s*-->\s*$/,""):o;i.parse.bare_returns=a;try{return(await hc(c,i)).code.replace(/;$/,"")}catch(d){return t.log(d),o}}}else if(n==="minifyURLs"&&typeof r!="function"){if(!r)return;let i=r;typeof r=="string"?i={site:r}:typeof r!="object"&&(i={}),t.minifyURLs=function(o){try{return $A.default.relate(o,i)}catch(a){return t.log(a),o}}}else t[n]=r}),t};function XA(e){let t;do t=Math.random().toString(36).replace(/^0\.[0-9]*/,"");while(~e.indexOf(t));return t}var Cf=new Set(["script","style"]);async function wU(e,t,n,r){let i=t.sortAttributes&&Object.create(null),o=t.sortClassName&&new Vm;function a(m){return m.map(function(g){return t.name(g.name)})}function s(m,g){return!g||m.indexOf(g)===-1}function c(m){return s(m,n)&&s(m,r)}async function d(m){let g,b;await new bc(m,{start:function(w,l){i&&(i[w]||(i[w]=new Vm),i[w].add(a(l).filter(c)));for(let u=0,v=l.length;u<v;u++){let y=l[u];o&&y.value&&t.name(y.name)==="class"?o.add(li(y.value).split(/[ \t\n\f\r]+/).filter(c)):t.processScripts&&y.name.toLowerCase()==="type"&&(g=w,b=y.value)}},end:function(){g=""},chars:async function(w){t.processScripts&&Cf.has(g)&&t.processScripts.indexOf(b)>-1&&await d(w)}}).parse()}let p=t.log;if(t.log=Sa,t.sortAttributes=!1,t.sortClassName=!1,await d(await xf(e,t)),t.log=p,i){let m=Object.create(null);for(let g in i)m[g]=i[g].createSorter();t.sortAttributes=function(g,b){let h=m[g];if(h){let w=Object.create(null),l=a(b);l.forEach(function(u,v){(w[u]||(w[u]=[])).push(b[v])}),h.sort(l).forEach(function(u,v){b[v]=w[u].shift()})}}}if(o){let m=o.createSorter();t.sortClassName=function(g){return m.sort(g.split(/[ \n\f\r]+/)).join(" ")}}}async function xf(e,t,n){t.collapseWhitespace&&(e=cs(e,t,!0,!0));let r=[],i,o="",a,s="",c=[],d=[],p=[],m="",g="",b=[],h=[],w,l,u;e=e.replace(/<!-- htmlmin:ignore -->([\s\S]*?)<!-- htmlmin:ignore -->/g,function(A,N){if(!w){w=XA(e);let L=new RegExp("^"+w+"([0-9]+)$");t.ignoreCustomComments?t.ignoreCustomComments=t.ignoreCustomComments.slice():t.ignoreCustomComments=[],t.ignoreCustomComments.push(L)}let P="<!--"+w+b.length+"-->";return b.push(N),P});let v=t.ignoreCustomFragments.map(function(A){return A.source});if(v.length){let A=new RegExp("\\s*(?:"+v.join("|")+")+\\s*","g");e=e.replace(A,function(N){l||(l=XA(e),u=new RegExp("(\\s*)"+l+"([0-9]+)"+l+"(\\s*)","g"),t.minifyCSS&&(t.minifyCSS=(function(L){return function(W,ae){W=W.replace(u,function(ke,Ve,Be){let ge=h[+Be];return ge[1]+l+Be+l+ge[2]});let Z=[];return new zm.default().minify(ZA(W,ae)).warnings.forEach(function(ke){let Ve=u.exec(ke);if(Ve){let Be=l+Ve[2]+l;W=W.replace(Be,KA(Be)),Z.push(Be)}}),L(W,ae).then(ke=>(Z.forEach(function(Ve){ke=ke.replace(KA(Ve),Ve)}),ke))}})(t.minifyCSS)),t.minifyJS&&(t.minifyJS=(function(L){return function(W,ae){return L(W.replace(u,function(Z,ke,Ve){let Be=h[+Ve];return Be[1]+l+Ve+l+Be[2]}),ae)}})(t.minifyJS)));let P=l+h.length+l;return h.push(/^(\s*)[\s\S]*?(\s*)$/.exec(N))," "+P+" "})}(t.sortAttributes&&typeof t.sortAttributes!="function"||t.sortClassName&&typeof t.sortClassName!="function")&&await wU(e,t,w,l);function y(A,N){return t.canCollapseWhitespace(A,N,e1)}function S(A,N){return t.canTrimWhitespace(A,N,t1)}function C(){let A=r.length-1;for(;A>0&&!/^<[^/!]/.test(r[A]);)A--;r.length=Math.max(0,A)}function f(){let A=r.length-1;for(;A>0&&!/^<\//.test(r[A]);)A--;r.length=Math.max(0,A)}function _(A,N){for(let P=null;A>=0&&S(P);A--){let L=r[A],W=L.match(/^<\/([\w:-]+)>$/);if(W)P=W[1];else if(/>$/.test(L)||(r[A]=qA(L,null,N,t)))break}}function T(A){let N=r.length-1;if(r.length>1){let P=r[r.length-1];/^(?:<!|$)/.test(P)&&P.indexOf(w)===-1&&N--}_(N,A)}return await new bc(e,{partialMarkup:n,continueOnParseError:t.continueOnParseError,customAttrAssign:t.customAttrAssign,customAttrSurround:t.customAttrSurround,html5:t.html5,start:async function(A,N,P,L,W){A.toLowerCase()==="svg"&&(t=Object.create(t),t.caseSensitive=!0,t.keepClosingSlash=!0,t.name=Sa),A=t.name(A),s=A,i=A,kf.has(A)||(o=""),a=!1,c=N;let ae=t.removeOptionalTags;if(ae){let Be=HA.has(A);Be&&_U(m,A)&&C(),m="",Be&&bU(g,A)&&(f(),ae=!gU(g,A)),g=""}t.collapseWhitespace&&(d.length||T(A),P||((!S(A,N)||d.length)&&d.push(A),(!y(A,N)||p.length)&&p.push(A)));let Z="<"+A,ke=L&&t.keepClosingSlash;r.push(Z),t.sortAttributes&&t.sortAttributes(A,N);let Ve=[];for(let Be=N.length,ge=!0;--Be>=0;){let Qt=await EU(N[Be],N,A,t);Qt&&(Ve.unshift(TU(Qt,ke,t,ge,l)),ge=!1)}Ve.length>0?(r.push(" "),r.push.apply(r,Ve)):ae&&nU.has(A)&&(m=A),r.push(r.pop()+(ke?"/":"")+">"),W&&!t.includeAutoGeneratedTags&&(C(),m="")},end:function(A,N,P){A.toLowerCase()==="svg"&&(t=Object.getPrototypeOf(t)),A=t.name(A),t.collapseWhitespace&&(d.length?A===d[d.length-1]&&d.pop():T("/"+A),p.length&&A===p[p.length-1]&&p.pop());let L=!1;A===s&&(s="",L=!a),t.removeOptionalTags&&(L&&GA.has(m)&&C(),m="",HA.has(A)&&g&&!WA.has(g)&&(g!=="p"||!sU.has(A))&&f(),g=rU.has(A)?A:""),t.removeEmptyElements&&L&&yU(A,N)?(C(),m="",g=""):(P&&!t.includeAutoGeneratedTags?g="":r.push("</"+A+">"),i="/"+A,qm.has(A)?L&&(o+="|"):o="")},chars:async function(A,N,P){if(N=N===""?"comment":N,P=P===""?"comment":P,t.decodeEntities&&A&&!Cf.has(s)&&(A=Ws(A)),t.collapseWhitespace){if(!d.length){if(N==="comment"){let L=r[r.length-1];if(L.indexOf(w)===-1&&(L||(N=i),r.length>1&&(!L||!t.conservativeCollapse&&/ $/.test(o)))){let W=r.length-2;r[W]=r[W].replace(/\s+$/,function(ae){return A=ae+A,""})}}if(N)if(N==="/nobr"||N==="wbr"){if(/^\s/.test(A)){let L=r.length-1;for(;L>0&&r[L].lastIndexOf("<"+N)!==0;)L--;_(L-1,"br")}}else kf.has(N.charAt(0)==="/"?N.slice(1):N)&&(A=cs(A,t,/(?:^|\s)$/.test(o)));N||P?A=qA(A,N,P,t):A=cs(A,t,!0,!0),!A&&/\s$/.test(o)&&N&&N.charAt(0)==="/"&&_(r.length-1,P)}!p.length&&P!=="html"&&!(N&&P)&&(A=cs(A,t,!1,!1,!0))}t.processScripts&&Cf.has(s)&&(A=await tU(A,t,c)),q8(s,c)&&(A=await t.minifyJS(A)),QA(s,c)&&(A=await t.minifyCSS(A)),t.removeOptionalTags&&A&&((m==="html"||m==="body"&&!/^\s/.test(A))&&C(),m="",(mU.has(g)||hU.has(g)&&!/^\s/.test(A))&&f(),g=""),i=/^\s*$/.test(A)?N:"comment",t.decodeEntities&&A&&!Cf.has(s)&&(A=A.replace(/&((?:Iacute|aacute|uacute|plusmn|Otilde|otilde|agrave|Agrave|Yacute|yacute|Oslash|oslash|atilde|Atilde|brvbar|ccedil|Ccedil|Ograve|curren|divide|eacute|Eacute|ograve|Oacute|egrave|Egrave|Ugrave|frac12|frac14|frac34|ugrave|oacute|iacute|Ntilde|ntilde|Uacute|middot|igrave|Igrave|iquest|Aacute|cedil|laquo|micro|iexcl|Icirc|icirc|acirc|Ucirc|Ecirc|ocirc|Ocirc|ecirc|ucirc|Aring|aring|AElig|aelig|acute|pound|raquo|Acirc|times|THORN|szlig|thorn|COPY|auml|ordf|ordm|Uuml|macr|uuml|Auml|ouml|Ouml|para|nbsp|euml|quot|QUOT|Euml|yuml|cent|sect|copy|sup1|sup2|sup3|iuml|Iuml|ETH|shy|reg|not|yen|amp|AMP|REG|uml|eth|deg|gt|GT|LT|lt)(?!;)|(?:#?[0-9a-zA-Z]+;))/g,"&amp$1").replace(/</g,"&lt;")),u&&t.collapseWhitespace&&d.length&&(A=A.replace(u,function(L,W,ae){return h[+ae][0]})),o+=A,A&&(a=!0),r.push(A)},comment:async function(A,N){let P=N?"<!":"<!--",L=N?">":"-->";P8(A)?A=P+await eU(A,t)+L:t.removeComments?N8(A,t)?A="<!--"+A+"-->":A="":A=P+A+L,t.removeOptionalTags&&A&&(m="",g=""),r.push(A)},doctype:function(A){r.push(t.useShortDoctype?"<!doctype"+(t.removeTagWhitespace?"":" ")+"html>":Of(A))}}).parse(),t.removeOptionalTags&&(GA.has(m)&&C(),g&&!WA.has(g)&&f()),t.collapseWhitespace&&T("br"),DU(r,t,u?function(A){return A.replace(u,function(N,P,L,W){let ae=h[+L][0];return t.collapseWhitespace?(P!==" "&&(ae=P+ae),W!==" "&&(ae+=W),cs(ae,{preserveLineBreaks:t.preserveLineBreaks,conservativeCollapse:!t.trimCustomFragments},/^[ \n\r\t\f]/.test(ae),/[ \n\r\t\f]$/.test(ae))):ae})}:Sa,w?function(A){return A.replace(new RegExp("<!--"+w+"([0-9]+)-->","g"),function(N,P){return b[+P]})}:Sa)}function DU(e,t,n,r){let i,o=t.maxLineLength,a=t.noNewlinesBeforeTagClose;if(o){let s="",c=[];for(;e.length;){let d=s.length,p=e[0].indexOf(`
100
100
  `),m=!!e[0].match(gc),g=a&&m;p<0?s+=r(n(e.shift())):(s+=r(n(e[0].slice(0,p))),e[0]=e[0].slice(p+1)),d>0&&s.length>o&&!g?(c.push(s.slice(0,d)),s=s.slice(d)):p>=0&&(c.push(s),s="")}s&&c.push(s),i=c.join(`
101
- `)}else i=r(n(e.join("")));return t.collapseWhitespace?cs(i,t,!0,!0):i}var n1=async function(e,t){let n=Date.now();t=RU(t||{});let r=await xf(e,t);return t.log("minified in: "+(Date.now()-n)+"ms"),r};var r1=8*1024*1024;function i1(e){return{name:"page_tabs_query",description:"Query page tabs and matching source/dist HTML file URLs. Use ids for exact page tabs or fieldEqualTo for exact top-level tab field matches.",inputSchema:Es("Page tab ids to read."),call:async t=>Me(await u1(e,ys(t),vs(t,"fieldEqualTo")))}}function o1(e){return{name:"page_tab_create",description:"Upload local UTF-8 HTML source and optimized dist files, then create a page tab. After create, tell user page URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`.",inputSchema:{type:"object",additionalProperties:!1,required:["htmlFilePath"],properties:{htmlFilePath:{type:"string",description:"Local UTF-8 HTML file to upload as page content. Maximum 8 MiB."},parent:{type:"string",description:"Parent id, normally spaces:<spaceId> or tabs:<folderId>. Optional only when existing tabs can provide a default."},name:{type:"string",description:"Tab name. Defaults to Untitled page."},insertAfterTabId:{type:"string",description:"Optional tab id after which to insert."}}},call:async t=>{let n=await c1(re(t,"htmlFilePath"));return Me(await kU(e,{...n,parent:bt(t,"parent"),name:bt(t,"name"),insertAfterTabId:bt(t,"insertAfterTabId")}))}}}function a1(e){return{name:"page_tab_html_set",description:"Upload local UTF-8 HTML source and optimized dist files, then replace URLs for an existing page tab. Frontend renders dist as untrusted sandbox iframe src.",inputSchema:rt({htmlFilePath:{type:"string",description:"Local UTF-8 HTML file to upload as replacement content. Maximum 8 MiB."}},["id","htmlFilePath"]),call:async t=>Me(await xU(e,re(t,"id"),await c1(re(t,"htmlFilePath"))))}}function s1(e){return{name:"page_tab_duplicate",description:"Duplicate a page tab by cloning tab metadata and HTML with a new shared id. After duplicate, tell user page URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`.",inputSchema:rt({name:{type:"string",description:"Optional duplicated tab name. Defaults to source name plus *."}}),call:async t=>Me(await IU(e,re(t,"id"),bt(t,"name")))}}async function u1(e,t,n){let r=t?n:{...n??{},type:"page"},i=await Fr(e,t,r),o={},a=[];for(let d in i)i[d].type==="page"&&(o[d]=i[d],a.push(d));let s=await e.readResourceItems("pages",{keys:a}),c={};for(let d in o)c[d]={tab:o[d],page:s[d]??null};return c}async function kU(e,t){Sc(t.sourceUrl,"sourceUrl"),Sc(t.distUrl,"distUrl");let n=await Fr(e),r=hi(),i=Rs(n,t.parent),o=Yo(n,i),a={id:r,updatedAt:Nr(),name:t.name??"Untitled page",order:As(n,{parent:i,insertAfterTabId:t.insertAfterTabId}),type:"page",parent:i,spaceId:o},s={id:r,updatedAt:Nr(),sourceUrl:t.sourceUrl,distUrl:t.distUrl};return dn("tabs",a),dn("pages",s),await Promise.all([e.upsertResourceItem("tabs",a),e.upsertResourceItem("pages",s)]),{tab:a,page:s}}async function xU(e,t,n){if(Sc(n.sourceUrl,"sourceUrl"),Sc(n.distUrl,"distUrl"),(await el(e,t)).type!=="page")throw new Error(`tab is not a page: ${t}`);let i={id:t,updatedAt:Nr(),...n};return dn("pages",i),await e.upsertResourceItem("pages",i),i}async function IU(e,t,n){let r=await Fr(e),i=(await u1(e,[t]))[t];if(!i)throw new Error(`page tab not found: ${t}`);if(!i.page)throw new Error(`page content not found: ${t}`);let o=hi(),a=structuredClone(i.tab);a.id=o,a.updatedAt=Nr(),a.name=n??`${i.tab.name}*`,a.order=xa(r,i.tab);let s={...structuredClone(i.page),id:o,updatedAt:Nr()};return dn("tabs",a),dn("pages",s),await Promise.all([e.upsertResourceItem("tabs",a),e.upsertResourceItem("pages",s)]),{tab:a,page:s}}async function PU(e){let t=await CU(e,"utf8");return FU(t),t}async function c1(e){let t=await PU(e),n=OU.basename(e)||"page.html",[r,i]=await Promise.all([l1(t,n),NU(t,n)]);return{sourceUrl:r,distUrl:i}}async function NU(e,t){let n=await n1(e,{collapseBooleanAttributes:!0,collapseWhitespace:!0,minifyCSS:!0,minifyJS:!0,removeComments:!0,removeRedundantAttributes:!0,removeScriptTypeAttributes:!0,removeStyleLinkTypeAttributes:!0,sortAttributes:!0,sortClassName:!0,useShortDoctype:!0});return l1(n,t)}async function l1(e,t,n){let r=new FormData;r.set("file",new Blob([e],{type:"text/html; charset=utf-8"}),t);let i=Ht(),o=await MU(),a=new URL(`${i.fileUrl}/upload`);a.searchParams.set("location","pages"),n&&a.searchParams.set("contentEncoding",n);let s=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:r});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`file upload failed: ${s.status} ${d}`.trim())}let c=await s.json().catch(()=>{});if(typeof c?.url!="string")throw new Error("file upload response missing url");return Sc(c.url,"url"),c.url}function FU(e){if(new TextEncoder().encode(e).length>r1)throw new Error(`html exceeds ${r1} bytes`)}async function MU(){let e=await fi();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");return await di(e)}function Sc(e,t){if(!e)throw new Error(`${t} must be non-empty string`)}async function yr(e,t){return Km(t),dn("blueprints",t),e.upsertResourceItem("blueprints",t)}function Km(e){for(let t in e.nodes){let n=e.nodes[t];for(let r in n.inputs){let i=n.inputs[r];for(let o in i.values)LU(i.values[o])}}}function LU(e){(!Object.prototype.hasOwnProperty.call(e,"literal")||e.literal===void 0)&&(e.literal=null)}function f1(e){return{name:"blueprint_context_update",description:"Replace blueprint context as one unit, including type, config, and exactly one trigger branch. When integrating external apps, set webhook trigger and tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger`.",inputSchema:rt({context:{...Jc,description:"Full replacement context with type, trigger, and optional config. Trigger must have exactly one branch."}},["id","context"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id")),r=nl(Qc(t,"context"));return await Fc(r.type),n.context=r,await yr(e,n),Me(n)}}}async function ya(e,t,n){let r=await fi();if(!r)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let i=await di(r),o=Ht(),a=await fetch(`${o.backendUrl}/blueprints/${e}/modes/${t}/${n}`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!a.ok){let s=await a.text().catch(()=>"");throw new Error(`blueprint runtime action failed: ${a.status} ${s}`.trim())}return{ok:!0,status:a.status,blueprintId:e,mode:t,action:n}}function Ea(e,t,n,r,i){return{name:t,description:n,inputSchema:rt({mode:{type:"string",enum:["test","explore"],description:r?"Target mode.":"Mode to use. Defaults to current blueprint mode."}},r?["id","mode"]:["id"]),call:async o=>{let a=re(o,"id"),c=Ss(o,"mode",["test","explore"])??(await Tt(e,a)).blueprint.mode;return Me(await i(a,c))}}}function d1(e){return Ea(e,"blueprint_mode_set","Switch blueprint mode through backend runtime endpoint to preserve side effects.",!0,async(t,n)=>ya(t,n,"switch-mode"))}function p1(e){return{name:"blueprint_test_records_set",description:"Set blueprint testRecordsAmount for test mode data generation. Uses replicated blueprint upsert; value must be at least 1.",inputSchema:rt({amount:{type:"integer",minimum:1,description:"Number of test records."}},["id","amount"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id"));return n.testRecordsAmount=d0(t,"amount"),await yr(e,n),Me(n)}}}function m1(e){return Ea(e,"blueprint_test_records_shuffle","Regenerate test records through backend /modes/test/shuffle-records endpoint.",!1,async t=>ya(t,"test","shuffle-records"))}function h1(e){return Ea(e,"blueprint_runtime_start","Start blueprint runtime for supplied mode or current blueprint mode through backend endpoint. When starting webhook trigger blueprint, tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(id)}/trigger`. Webhook runs only while blueprint is active in explore mode. External apps integrate by calling this blueprint webhook endpoint.",!1,async(t,n)=>ya(t,n,"start"))}function _1(e){return Ea(e,"blueprint_runtime_stop","Stop blueprint runtime for supplied mode or current blueprint mode through backend endpoint.",!1,async(t,n)=>ya(t,n,"stop"))}function g1(e){return{name:"blueprint_recompute_on_change_set",description:"Set recomputeOnChange to always or manual. Frontend treats undefined as always; this tool stores explicit value for clarity.",inputSchema:rt({value:{type:"string",enum:["always","manual"],description:"Recompute behavior."}},["id","value"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id"));return n.recomputeOnChange=Ii(t,"value",["always","manual"]),await yr(e,n),Me(n)}}}function b1(e){return{name:"blueprint_mock_never_set",description:"Set or clear blueprint-level mockNever. enabled=true stores true; enabled=false clears the optional field like frontend toggle.",inputSchema:rt({enabled:{type:"boolean",description:"Whether to disable mocking for all nodes."}},["id","enabled"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id"));return $o(t,"enabled")?n.mockNever=!0:delete n.mockNever,await yr(e,n),Me(n)}}}async function Do(e,t){let n=await e.readResourceItems("blueprint-operators"),r={};for(let i in t.nodes){let o=n[t.nodes[i].operatorId];o&&(r[o.id]=o)}return{...n,...r}}function Gm(e){if(Object.keys(e).length===0)return;let t=null,n=null;for(let r in e)isNaN(parseFloat(r))||(n===null||parseFloat(r)<n)&&(t=r,n=parseFloat(r));return n!==null?e[t]:void 0}function v1(e){let t=Object.keys(e).filter(o=>!isNaN(parseFloat(o))).sort((o,a)=>parseFloat(o)-parseFloat(a));if(t.length===0)return"0.5";let n=t[t.length-1],r=parseFloat(n);return((r+(Math.floor(r)+1))/2).toPrecision(15).replace(/0+$/,"").replace(/\.$/,"")}function Ta(e,t){let n=v1(e);return e[n]=t,n}var S1=new Set(["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"]);function tn(e,t){let n=e.nodes[t];if(!n)throw new Error(`blueprint node not found: ${t}`);return n}function Oi(e,t){let n=e.inputs[t];if(!n)throw new Error(`node input not found: ${e.id}.${t}`);return n.values??={},n}function If(e,t,n,r){let o=Oi(tn(e,t),n).values[r];if(!o)throw new Error(`input value not found: ${t}.${n}[${r}]`);return o}function yc(e,t){let n=e[t];if(!n)throw new Error(`blueprint operator not found: ${t}`);return n}function lu(e,t){let n=e.inputs.find(r=>r.name===t);if(!n)throw new Error(`operator input not found: ${e.id}.${t}`);return n}function Pf(e,t){let n=e.output;if(!n||n.name!==t)throw new Error(`operator output not found: ${e.id}.${t}`);return n}function Ui(e){delete e.nodeId,delete e.operatorInputId,delete e.nodeInputIndex}function y1(e,t){e.nodeId=t.nodeId,e.operatorInputId=t.operatorInputId,e.nodeInputIndex=t.nodeInputIndex}function fu(e,t,n,r,i){let o=tn(e,n.nodeId),a=tn(e,r.nodeId),s=yc(t,o.operatorId),c=yc(t,a.operatorId);Pf(s,n.pinName);let d=lu(c,r.pinName),p=Oi(a,r.pinName),m=n.index??"0.5",g=BU(p,d,r.index,i),b=p.values[g];return b.nodeId=o.id,b.operatorInputId=n.pinName,b.nodeInputIndex=m,g}function E1(e,t){let n=tn(e,t.nodeId),r=t.index??"0.5";if(t.pinPosition==="input"){let i=If(e,n.id,t.pinName,r);Ui(i);return}for(let i in e.nodes)for(let o in e.nodes[i].inputs)for(let a in e.nodes[i].inputs[o].values){let s=e.nodes[i].inputs[o].values[a];s.nodeId===n.id&&s.operatorInputId===t.pinName&&s.nodeInputIndex===r&&Ui(s)}}function BU(e,t,n,r){if(r)return n?(e.values[n]??={literal:null},n):Ta(e.values,{literal:null});if(n){if(!(n in e.values))throw new Error(`input value not found: ${t.name}[${n}]`);return n}return t.type.isArray?Ta(e.values,{literal:null}):"0.5"in e.values?"0.5":(e.values["0.5"]={literal:null},"0.5")}function T1(e){return{name:"blueprint_pins_connect",description:"Connect one output pin to one input pin by writing pointer fields on target input value. Validates nodes and pin names; can create target array element. For newly created operator nodes, prefer passing inputConnections to blueprint_operator_node_add instead of calling this after creation, so layout sees graph edges before assigning coordinates.",inputSchema:rt({sourceNodeId:{type:"string"},sourceOutputName:{type:"string"},sourceIndex:mi(),targetNodeId:{type:"string"},targetInputName:{type:"string"},targetIndex:mi(),createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}},["id","sourceNodeId","sourceOutputName","targetNodeId","targetInputName"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=fu(n.blueprint,await Do(e,n.blueprint),{nodeId:re(t,"sourceNodeId"),pinName:re(t,"sourceOutputName"),index:bt(t,"sourceIndex")},{nodeId:re(t,"targetNodeId"),pinName:re(t,"targetInputName"),index:bt(t,"targetIndex")},Yc(t,"createTargetArrayElement")??!1);return await yr(e,n.blueprint),Me({targetIndex:r,blueprint:n.blueprint})}}}function $r(e,t,n,r,i){return{name:e,description:t,inputSchema:n,call:async o=>{let{blueprint:a}=await Tt(r,re(o,"id"));return i(a,o),await yr(r,a),Me(a)}}}function A1(e){return $r("blueprint_pin_unlink","Unlink an input pin value or all downstream links from an output pin.",rt({nodeId:{type:"string"},pinName:{type:"string"},pinPosition:{type:"string",enum:["input","output"]},index:mi()},["id","nodeId","pinName","pinPosition"]),e,(t,n)=>E1(t,{nodeId:re(n,"nodeId"),pinName:re(n,"pinName"),pinPosition:Ii(n,"pinPosition",["input","output"]),index:bt(n,"index")}))}async function Go(e,t){let n=await e.readResourceItem("blueprint-operators",t);if(!n)throw new Error(`blueprint operator not found: ${t}`);if(!Array.isArray(n.inputs))throw new Error(`blueprint operator has invalid inputs: ${t}`);return n}async function Co(e,t,n){Km(t),dn("blueprints",t),dn("blueprint-views",n);let[r,i]=await Promise.all([e.upsertResourceItem("blueprints",t),e.upsertResourceItem("blueprint-views",n)]);return{blueprintOk:r,blueprintViewOk:i}}function UU(e,t=hi()){let n={id:t,operatorId:e.id,inputs:{}};for(let r of e.inputs)r.type.isArray?n.inputs[r.name]={isArray:!0,values:{}}:n.inputs[r.name]={values:{"0.5":{literal:null}}};return n}function du(e,t,n){let r=UU(n);return e.nodes[r.id]=r,t.nodes[r.id]={id:r.id},r}function R1(e){return{name:"blueprint_node_input_literal_set",description:"Set a node input literal at a CRDT value index. Defaults index to 0.5. With disconnect=true, clears upstream pointer fields first. For newly created operator nodes, prefer inputLiterals on blueprint_operator_node_add instead of setting literals afterward.",inputSchema:_o({literal:{description:"JSON literal value to set."},index:mi(),disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}},["id","nodeId","inputName","literal"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id")),r=Wm(n,re(t,"nodeId"),re(t,"inputName"),bt(t,"index")??"0.5",Tr(t).literal,Yc(t,"disconnect")??!1);return await yr(e,n),Me({value:r,blueprint:n})}}}function Wm(e,t,n,r,i,o){let a=If(e,t,n,r);return a.literal=i,o&&Ui(a),a}function Ff(e,t,n,r,i,o){if(o!==void 0&&!S1.has(o))throw new Error(`unsupported type: ${o}`);let a=tn(e,n),s=yc(t,a.operatorId);r==="output"?VU(e,t,a,s,i,o):zU(e,t,a,s,i,o)}function Xm(e,t){return e.outputType??t.output?.type.type}function VU(e,t,n,r,i,o){let a=Pf(r,i);o===void 0||o===a.type.type?delete n.outputType:n.outputType=o;let s=o??a.type.type;for(let c in e.nodes)qU(e.nodes[c],t,n,i,s)}function qU(e,t,n,r,i){let o=t[e.operatorId];if(o)for(let a in e.inputs){let s=o.inputs.find(c=>c.name===a);if(s)for(let c in e.inputs[a].values){let d=e.inputs[a].values[c];d.nodeId!==n.id||d.operatorInputId!==r||(GU(i,e.inputs[a].type??s.type.type,s.type)?e.inputs[a].type=i:Ui(d))}}}function zU(e,t,n,r,i,o){let a=lu(r,i),s=Oi(n,i);o===void 0||o===a.type.type?delete s.type:s.type=o;let c=o??a.type.type;for(let d in s.values){let p=s.values[d];if(!p.nodeId||!p.operatorInputId)continue;let m=e.nodes[p.nodeId],g=m?t[m.operatorId]:void 0;if(!m||!g?.output)continue;let b=Xm(m,g);WU(b,c)||Ui(p)}KU(n,r,a.type,o)}function KU(e,t,n,r){let i=Hm(n);if(i){for(let o of t.inputs)Hm(o.type)===i&&(r?e.inputs[o.name].type=r:delete e.inputs[o.name].type);t.output&&Hm(t.output.type)===i&&(r?e.outputType=r:delete e.outputType)}}function GU(e,t,n){return Nf(t)?!n.allowedTypes||n.allowedTypes.length===0?!0:n.allowedTypes.some(r=>Ec(e)?e.includes(r.type):r.type===e):Ec(e)?e.includes(t):e===t}function WU(e,t){return!e||!t?!1:e==="list of wildcard"||t==="list of wildcard"?Ec(e)&&Ec(t):!Nf(e)&&!Nf(t)?Ec(e)?e.includes(t):e===t:!0}function Ec(e){return e?.startsWith("list of ")??!1}function Nf(e){return e==="wildcard"||e==="list of wildcard"}function Hm(e){if(e&&Nf(e.type))return e.linkType??"_"}function w1(e){return{name:"blueprint_operator_node_add",description:"Add an operator node using frontend default input creation. Leaves view position unset so frontend can place it after measuring dimensions. When creating connected or configured nodes, set inputConnections, inputLiterals, and inputTypeOverrides in this same call. Set inputTypeOverrides to list of X when connecting list output into scalar input so auto zipping runs. Prefer this over separate connect/literal/type calls immediately after creation because frontend layout sees first-write graph edges.",inputSchema:Ts({operatorId:{type:"string",description:"Registered blueprint operator id."},inputConnections:{type:"array",description:"Input connections to apply before first write. Use for all known input links when creating a node; prefer this over blueprint_pins_connect after creation because frontend layout uses these connections before assigning coordinates.",items:{type:"object",additionalProperties:!1,required:["inputName","sourceNodeId","sourceOutputName","sourceIndex"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},sourceNodeId:{type:"string",description:"Existing source node id."},sourceOutputName:{type:"string",description:"Source output pin name."},sourceIndex:{type:"string",description:"Source output CRDT index."},targetIndex:{type:"string",description:"Target input CRDT index. Defaults to 0.5 for scalar inputs."},createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}}}},inputLiterals:{type:"array",description:"Input literals to apply before first write. Use for all known literal inputs when creating a node; prefer this over blueprint_node_input_literal_set immediately after creation. Same behavior as blueprint_node_input_literal_set.",items:{type:"object",additionalProperties:!1,required:["inputName","literal"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},literal:{description:"JSON literal value to set."},index:{type:"string",description:"Target input CRDT index. Defaults to 0.5."},disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}}}},inputTypeOverrides:{type:"array",description:"Resolved input types to apply before first write. Use list of X on scalar inputs receiving list outputs to trigger auto zipping.",items:{type:"object",additionalProperties:!1,required:["inputName","type"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},type:{type:"string",enum:xo,description:"Resolved input type override."}}}}},["id","operatorId"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=re(t,"operatorId");if(!Mc(await po(),r))throw new Error(`blueprint operator is not enabled for current user: ${r}`);let i=await Go(e,r),o=du(n.blueprint,n.blueprintView,i);HU(n.blueprint,o.id,jU(t));let a=$U(t),s=YU(t),c=await Do(e,n.blueprint);a.length>0&&XU(n.blueprint,c,o.id,a);for(let d of s)Ff(n.blueprint,c,o.id,"input",d.inputName,d.type);return await Co(e,n.blueprint,n.blueprintView),Me({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function HU(e,t,n){for(let r of n){let i=e.nodes[t].inputs[r.inputName];i?.isArray&&r.index&&(i.values[r.index]??={literal:null});let o=i?.isArray?r.index??Ta(i.values,{literal:null}):r.index??"0.5";Wm(e,t,r.inputName,o,r.literal,r.disconnect??!1)}}function XU(e,t,n,r){for(let i of r){let o=t[e.nodes[n].operatorId].inputs.find(a=>a.name===i.inputName);fu(e,t,{nodeId:i.sourceNodeId,pinName:i.sourceOutputName,index:i.sourceIndex},{nodeId:n,pinName:i.inputName,index:i.targetIndex},i.createTargetArrayElement??!!o?.type.isArray)}}function $U(e){let t=Tr(e).inputConnections;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid tool arguments: inputConnections must be array");let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!ko(i))throw new Error(`invalid tool arguments: inputConnections[${r}] must be object`);let o=i.inputName,a=i.sourceNodeId,s=i.sourceOutputName,c=i.sourceIndex,d=i.targetIndex,p=i.createTargetArrayElement;if(typeof o!="string"||!o.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].inputName must be non-empty string`);if(typeof a!="string"||!a.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceNodeId must be non-empty string`);if(typeof s!="string"||!s.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceOutputName must be non-empty string`);if(typeof c!="string"||!c.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceIndex must be non-empty string`);if(d!==void 0&&typeof d!="string")throw new Error(`invalid tool arguments: inputConnections[${r}].targetIndex must be string`);if(p!==void 0&&typeof p!="boolean")throw new Error(`invalid tool arguments: inputConnections[${r}].createTargetArrayElement must be boolean`);n.push({inputName:o,sourceNodeId:a,sourceOutputName:s,sourceIndex:c,targetIndex:d,createTargetArrayElement:p})}return n}function jU(e){let t=Tr(e).inputLiterals;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid tool arguments: inputLiterals must be array");let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!ko(i))throw new Error(`invalid tool arguments: inputLiterals[${r}] must be object`);let o=i.inputName,a=i.literal,s=i.index,c=i.disconnect;if(typeof o!="string"||!o.trim())throw new Error(`invalid tool arguments: inputLiterals[${r}].inputName must be non-empty string`);if(!("literal"in i))throw new Error(`invalid tool arguments: inputLiterals[${r}].literal is required`);if(s!==void 0&&typeof s!="string")throw new Error(`invalid tool arguments: inputLiterals[${r}].index must be string`);if(c!==void 0&&typeof c!="boolean")throw new Error(`invalid tool arguments: inputLiterals[${r}].disconnect must be boolean`);n.push({inputName:o,literal:a,index:s,disconnect:c})}return n}function YU(e){let t=Tr(e).inputTypeOverrides;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid tool arguments: inputTypeOverrides must be array");let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!ko(i))throw new Error(`invalid tool arguments: inputTypeOverrides[${r}] must be object`);let o=i.inputName,a=i.type;if(typeof o!="string"||!o.trim())throw new Error(`invalid tool arguments: inputTypeOverrides[${r}].inputName must be non-empty string`);if(typeof a!="string"||!xo.includes(a))throw new Error(`invalid tool arguments: inputTypeOverrides[${r}].type must be supported type`);n.push({inputName:o,type:a})}return n}function D1(e){return{name:"blueprint_context_field_node_add",description:"Add a context field getter node using Base/function/blueprint/field-wildcard, setting outputType and Path literal. Apache Kafka context config is initialized from field connection/path when unset.",inputSchema:Ts({connectionId:{type:"string",description:"Context field connection id."},path:{type:"string",description:"Context field path such as topic or collection."},field:{type:"string",description:"Field name to store in Path literal."},type:{type:"string",enum:xo,description:"Field output type."}},["id","connectionId","path","field","type"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=re(t,"connectionId"),i=await e.readResourceItem("connections",r);i?.type&&await wa(i.type);let o=await Go(e,"Base/function/blueprint/field-wildcard"),a=du(n.blueprint,n.blueprintView,o);return a.outputType=Ii(t,"type",xo),a.inputs.Path.values["0.5"]={literal:re(t,"field")},QU(n.blueprint.context,r,re(t,"path")),await Co(e,n.blueprint,n.blueprintView),Me({node:a,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function QU(e,t,n){e.type==="ApacheKafkaTopic"&&(e.config??={},e.config.topicName===void 0&&(e.config.connectionId=t,e.config.topicName=n))}function C1(e){return{name:"blueprint_node_result_field_node_add",description:"Add a map/get node for a field inferred from an upstream node result. Sets Path literal and optionally connects source output to Target input.",inputSchema:Ts({path:{type:"string",description:"Result field path to store in Path literal."},sourceNodeId:{type:"string",description:"Optional upstream source node id to connect into Target."},sourceOutputName:{type:"string",description:"Optional upstream output name. Defaults to source operator output."}},["id","path"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=await Go(e,"Base/function/map/get"),i=du(n.blueprint,n.blueprintView,r);i.inputs.Path.values["0.5"]={literal:re(t,"path")};let o=bt(t,"sourceNodeId");return o&&fu(n.blueprint,await Do(e,n.blueprint),{nodeId:o,pinName:bt(t,"sourceOutputName")??await JU(e,n.blueprint,o)},{nodeId:i.id,pinName:"Target",index:"0.5"},!1),await Co(e,n.blueprint,n.blueprintView),Me({node:i,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}async function JU(e,t,n){let r=t.nodes[n];if(!r)throw new Error(`source node not found: ${n}`);let i=await Go(e,r.operatorId);if(!i.output?.name)throw new Error(`source node operator has no output: ${r.operatorId}`);return i.output.name}function O1(e){return{name:"blueprint_node_array_input_add",description:"Append an element to an array input using frontend CRDT list index generation. Returns new index.",inputSchema:_o({literal:{description:"Optional initial literal value. Defaults to null."}},["id","nodeId","inputName"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=n.blueprint.nodes[re(t,"nodeId")];if(!r)throw new Error("node not found");let i=await Go(e,r.operatorId),o=Tr(t),a=Object.prototype.hasOwnProperty.call(o,"literal")?o.literal:null,s=ZU(n.blueprint,i,r.id,re(t,"inputName"),a);return await yr(e,n.blueprint),Me({index:s,blueprint:n.blueprint})}}}function ZU(e,t,n,r,i){let o=tn(e,n);if(!lu(t,r).type.isArray)throw new Error(`operator input is not an array: ${r}`);let s=Oi(o,r);return Ta(s.values,{literal:i===void 0?null:i})}function k1(e){return $r("blueprint_node_array_input_remove","Remove one CRDT-indexed value from a node array input.",_o({index:mi()},["id","nodeId","inputName","index"]),e,(t,n)=>e4(t,re(n,"nodeId"),re(n,"inputName"),re(n,"index")))}function e4(e,t,n,r){let i=Oi(tn(e,t),n);if(!(r in i.values))throw new Error(`input value not found: ${t}.${n}[${r}]`);delete i.values[r]}function x1(e){return $r("blueprint_node_array_input_move","Move array input values by swapping two CRDT entries. Provide indexA/indexB or index plus direction up/down.",_o({indexA:mi(),indexB:mi(),index:mi(),direction:{type:"string",enum:["up","down"],description:"Adjacent move direction when indexA/indexB are omitted."}},["id","nodeId","inputName"]),e,(t,n)=>{let r=re(n,"inputName"),i=t.nodes[re(n,"nodeId")];if(!i)throw new Error("node not found");let o=bt(n,"indexA")??re(n,"index"),a=bt(n,"indexB")??n4(i.inputs[r]?.values??{},o,Ii(n,"direction",["up","down"]));t4(t,i.id,r,o,a)})}function t4(e,t,n,r,i){let o=Oi(tn(e,t),n);if(!(r in o.values))throw new Error(`input value not found: ${t}.${n}[${r}]`);if(!(i in o.values))throw new Error(`input value not found: ${t}.${n}[${i}]`);let a=o.values[r];o.values[r]=o.values[i],o.values[i]=a}function n4(e,t,n){let r=[];for(let a in e)Number.isNaN(parseFloat(a))||r.push(a);r.sort((a,s)=>parseFloat(a)-parseFloat(s));let i=r.indexOf(t),o=n==="up"?r[i-1]:r[i+1];if(!o)throw new Error(`no adjacent input value ${n} from index ${t}`);return o}function I1(e){return $r("blueprint_node_input_zipping_set","Set or clear forceZipping on a node input. Use enabled=true when connected list output should run element-by-element even if input expects a list. enabled=false clears the optional field like frontend. Cache operators never zip.",_o({enabled:{type:"boolean",description:"Whether to force zipping; false clears stored field."}},["id","nodeId","inputName","enabled"]),e,(t,n)=>r4(t,re(n,"nodeId"),re(n,"inputName"),$o(n,"enabled")))}function r4(e,t,n,r){let i=Oi(tn(e,t),n);r?i.forceZipping=!0:delete i.forceZipping}function P1(e,t){let n=new Set(t);for(let r of n)i4(e,r);for(let r in e.nodes){let i=e.nodes[r];for(let o in i.inputs)for(let a in i.inputs[o].values){let s=i.inputs[o].values[a];(n.has(i.id)||s.nodeId&&n.has(s.nodeId))&&Ui(s)}}}function N1(e,t,n){let r={};for(let i of n){let o=e.nodes[i],a=o?t[o.operatorId]:void 0,s=a?.inputs[0];if(!o||!a?.output||!s)continue;let c=Xm(o,a),d=o.inputs[s.name]?.type??s.type.type;if(c!==d)continue;let p=Gm(o.inputs[s.name]?.values??{});p?.nodeId&&(r[o.id]=structuredClone(p))}return r}function F1(e,t,n){for(let r in e.inputs)for(let i in e.inputs[r].values){let o=e.inputs[r].values[i];o.nodeId&&(t[o.nodeId]?o.nodeId=t[o.nodeId]:n.has(o.nodeId)||Ui(o))}}function M1(e,t){t?y1(e,t):Ui(e)}function i4(e,t){if(!e.nodes[t])throw new Error(`blueprint node not found: ${t}`)}function L1(e){return $r("blueprint_node_connections_remove","Remove selected nodes input links and downstream links pointing to selected nodes.",rt({nodeIds:Io("Node ids whose connections should be removed.")},["id","nodeIds"]),e,(t,n)=>P1(t,jo(n,"nodeIds")))}function B1(e){return{name:"blueprint_node_type_set",description:"Set or clear an input/output resolved type. Omitting type or setting base type clears override; incompatible existing links are disconnected.",inputSchema:rt({nodeId:{type:"string"},xputType:{type:"string",enum:["input","output"]},pinName:{type:"string"},type:{type:"string",enum:xo,description:"Resolved type override. Omit to reset to operator base type."}},["id","nodeId","xputType","pinName"]),call:async t=>{let n=await Tt(e,re(t,"id"));return Ff(n.blueprint,await Do(e,n.blueprint),re(t,"nodeId"),Ii(t,"xputType",["input","output"]),re(t,"pinName"),Ss(t,"type",xo)),await yr(e,n.blueprint),Me(n.blueprint)}}}function U1(e){return $r("blueprint_nodes_disabled_set","Set or clear disabled on selected nodes. disabled=false clears optional field like frontend.",rt({nodeIds:Io("Node ids to update."),disabled:{type:"boolean",description:"Whether nodes should be disabled."}},["id","nodeIds","disabled"]),e,(t,n)=>o4(t,jo(n,"nodeIds"),$o(n,"disabled")))}function o4(e,t,n){for(let r of t){let i=tn(e,r);n?i.disabled=!0:delete i.disabled}}function V1(e){return $r("blueprint_node_mock_never_set","Set or clear node-level mockNever. enabled=false clears optional field like frontend.",rt({nodeId:{type:"string"},enabled:{type:"boolean"}},["id","nodeId","enabled"]),e,(t,n)=>a4(t,re(n,"nodeId"),$o(n,"enabled")))}function a4(e,t,n){let r=tn(e,t);n?r.mockNever=!0:delete r.mockNever}function q1(e){return $r("blueprint_node_skip_behavior_set","Set On Skip behavior. behavior=skip clears stored value because frontend default skip is undefined; behavior=null stores string null.",rt({nodeId:{type:"string"},behavior:{type:"string",enum:["skip","null"]}},["id","nodeId","behavior"]),e,(t,n)=>s4(t,re(n,"nodeId"),Ii(n,"behavior",["skip","null"])))}function s4(e,t,n){let r=tn(e,t);n==="skip"?delete r.skipBehavior:r.skipBehavior="null"}function z1(e){return{name:"blueprint_nodes_delete",description:"Delete blueprint nodes and view nodes. Mirrors frontend rewire behavior for deleted nodes whose first input type matches output type.",inputSchema:rt({nodeIds:Io("Node ids to delete.")},["id","nodeIds"]),call:async t=>{let n=await Tt(e,re(t,"id"));return u4(n.blueprint,n.blueprintView,await Do(e,n.blueprint),jo(t,"nodeIds")),await Co(e,n.blueprint,n.blueprintView),Me({blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function u4(e,t,n,r){let i=new Set(r);for(let a of i)tn(e,a);let o=N1(e,n,i);for(let a in e.nodes)for(let s in e.nodes[a].inputs)for(let c in e.nodes[a].inputs[s].values){let d=e.nodes[a].inputs[s].values[c];!d.nodeId||!i.has(d.nodeId)||M1(d,o[d.nodeId])}for(let a of i)delete e.nodes[a],delete t.nodes[a]}function K1(e){return{name:"blueprint_nodes_duplicate",description:"Duplicate selected nodes and view nodes. Remaps internal copied-node references, drops missing-node references, and leaves new node positions for the frontend layout pass.",inputSchema:rt({nodeIds:Io("Node ids to duplicate.")},["id","nodeIds"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=c4(n.blueprint,n.blueprintView,jo(t,"nodeIds"));return await Co(e,n.blueprint,n.blueprintView),Me({nodeIds:r,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function c4(e,t,n){let r=new Set(n);for(let s of r)tn(e,s);let i={},o=n.map(s=>structuredClone(e.nodes[s])),a=new Set;for(let s in e.nodes)a.add(s);for(let s of o){let c=hi();i[s.id]=c,s.id=c}for(let s of o)F1(s,i,a);for(let s of o)e.nodes[s.id]=s;for(let s of n){let c=structuredClone(t.nodes[s]??{id:s}),d=i[s];c.id=d,l4(c),t.nodes[d]=c}return n.map(s=>i[s])}function l4(e){if(!e.style)return;let t={...e.style};delete t.x,delete t.y;for(let n in t){e.style=t;return}delete e.style}function G1(e){return[m0(e),i1(e),T0(e),g0(e),b0(e),v0(e),S0(e),A0(e),R0(e),o1(e),s1(e),a1(e),f1(e),d1(e),p1(e),m1(e),h1(e),_1(e),g1(e),b1(e),w1(e),D1(e),C1(e),R1(e),O1(e),k1(e),x1(e),I1(e),T1(e),A1(e),L1(e),B1(e),U1(e),V1(e),q1(e),z1(e),K1(e)]}var Ac={type:"object",additionalProperties:!0},Rc={type:"object",additionalProperties:!1,properties:{}},X1=["kafka-topic:offset-extents","rabbitmq-stream:offset-extents","base-event-collection:offset-extents","shopify-webhook:offset-extents"],d4=["ticket-message-created","ticket-message-failed"];function $1(e=_s()){return[...p4(e),...m4(e),...h4(e),...G1(e),..._4(e),...g4(e),...v4(e)]}function p4(e){return[{name:"resources_list",description:"Discover Beepflow resources supported by this MCP server, including writable flags and item schema URIs.",inputSchema:Rc,call:async()=>Yt({resources:Oa,note:"tabs, pages, blueprints, and blueprint-views are dedicated resources; use tabs_query, page_tabs_query, blueprints_query, and tab intent tools instead of generic resource_* tools."})},{name:"resource_schema_get",description:"Read JSON Schema and mutation notes for one Beepflow resource item. Use before constructing an upsert item unless modifying an item read from the same resource.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:mu,description:"Resource whose item JSON Schema and mutation notes should be read."}}},call:async t=>{let n=Zf(Zn(t,"resource"));return Yt(Wc(n))}},{name:"resource_query",description:"Query a Beepflow resource with all, keys, or fieldEqualTo snapshot filters. Returns an item map. Use before editing existing resource items.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:mu,description:"Resource collection to query."},all:{type:"boolean",description:"Return whole resource collection."},keys:{type:"array",items:{type:"string"},description:"Return items with these ids."},fieldEqualTo:{...Ac,description:"Return items whose fields equal these exact values."}}},call:async t=>{let n=Zf(Zn(t,"resource"));await $m(n);let r=H4(t),i=await e.readResourceItems(n,r);return Yt(i)}},{name:"resource_upsert",description:"Create or update one writable Beepflow resource item. Mandatory: before calling resource_upsert, first call resource_schema_get for the same resource and ensure item matches that resource schema. Send full item state, not JSON patches; preserve unchanged fields.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","item"],properties:{resource:{type:"string",enum:mu,description:"Writable resource collection to create or update."},item:{...Ac,description:"Full item state with non-empty id; not a JSON patch."}}},call:async t=>{let n=ed(Zn(t,"resource"));await $m(n);let r=jm(t,"item"),i=r.id;if(typeof i!="string"||!i)throw new Error("item.id must be non-empty string");dn(n,r);let o=await e.upsertResourceItem(n,r);return Yt({ok:o})}},{name:"resource_delete",description:"Delete one writable Beepflow resource item by key. Destructive; use only when user intent is explicit.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","key"],properties:{resource:{type:"string",enum:mu,description:"Writable resource collection to delete from."},key:{type:"string",description:"Item id to delete."}}},call:async t=>{let n=ed(Zn(t,"resource"));await $m(n);let r=Zn(t,"key"),i=await e.deleteResourceItem(n,r);return Yt({ok:i})}}]}function m4(e){return[{name:"status",description:"Mandatory first call before any Beepflow task. Call status at least once whenever user wants to inspect, edit, debug, or operate Beepflow, so agent has latest user status and MCP instructions. Returns MCP instructions, frontendUrl, backendUrl, current authenticated user location, current tab id, tab, page file URL, blueprint, blueprint view, used operator definitions, and context fields when on a blueprint tab.",inputSchema:Rc,call:async()=>E4(e)}]}async function $m(e){e!=="users"&&e!=="roles"||await gh(e)}function h4(e){return[{name:"results_read",description:"Read current blueprint result events for a result id such as tabId-test or tabId-explore. Blueprint result ids are tabId-test and tabId-explore.",inputSchema:e5(),call:async t=>V4(e,t)},{name:"results_delete_state",description:"Stop and delete persisted result state for a result id. State-changing; use only when user intent is explicit.",inputSchema:t5(),call:async t=>K4(e,t)},{name:"results_set_offsets",description:"Set current stream offsets for a result id. State-changing; use only when user intent is explicit.",inputSchema:n5(),call:async t=>G4(e,t)},{name:"stream_offset_extents_read",description:"Read stream partition offset extents from supported frontend live channels for runtime diagnostics.",inputSchema:r5(),call:async t=>W4(e,t)}]}function _4(e){return[{name:"blueprint_operators_search",description:"Search blueprint operators with the same vector endpoint used by the editor menu. Use to find valid operator ids plus input/output metadata before editing blueprint nodes.",inputSchema:Q4(),call:async t=>S4(e,t)},{name:"blueprint_context_fields_search",description:"Search contextual fields available to a blueprint using the editor menu field matching rules. Use to find fields available from blueprint context schemas.",inputSchema:J4(),call:async t=>y4(e,t)}]}function g4(e){return[{name:"integrations_list",description:"List integration types available from the backend integration API. Use before listing endpoints for an integration type.",inputSchema:Rc,call:async()=>{let t=await po();return Yt((await r0()).filter(n=>hs(t,n)))}},{name:"integration_blueprint_contexts_list",description:"List backend-defined blueprint context resource types, including executionKind, config fields, and type/config templates. If a resource type is absent, do not use it for blueprint context. Use before blueprint_tab_create or blueprint_context_update when choosing context.type, context.trigger, and context.config. executionKind=managed means choose trigger { executor: { enabled: true } } because integration runtime owns stream/event/poll lifecycle. executionKind=finite means choose trigger from user intent: manual for ad hoc/sample/start-once execution, cron for scheduled refresh, loop for fixed-delay repeated polling, blueprint for upstream blueprint invocation, and webhook only for generic GET/POST /:tabId/trigger HTTP calls, not integration webhooks.",inputSchema:{type:"object",additionalProperties:!1,properties:{integrationType:{type:"string",description:"Optional integration type from integrations_list; omit to return all blueprint context resource definitions including ManualTick."},resourceType:{type:"string",description:"Optional integration resource type to return one matching blueprint context definition."}}},call:async t=>{let n=await po();return Yt((await i0(wc(t,"integrationType"),wc(t,"resourceType"))).filter(r=>Nc(n,r.resourceType)))}},{name:"integration_endpoints_list",description:"List backend integration endpoints for one integration type from workspace OpenAPI metadata, including access, side effect, request, response, confirmation metadata, parameters, requestBody, and payloadSchema for integration_endpoint_call. If payloadSchema includes connectionId, use integration_connections_list before integration_endpoint_call. MCP-only; external apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list."}}},call:async t=>{let n=Zn(t,"integrationType");return await wa(n),Yt(await fd(n))}},{name:"integration_connections_list",description:"List redacted workspace connections for one integration type. Use this to find connectionId before integration_endpoint_call when endpoint payloadSchema declares connectionId. Use status only to disambiguate by current space when multiple matching connections exist. External apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose connections should be listed."},spaceId:{type:"string",description:"Optional space id to restrict connection matches."}}},call:async t=>b4(e,t)},{name:"integration_endpoint_schema_get",description:"MCP-only; not for external app data sources. Read OpenAPI 3.1 schema for one integration type. Use before integration_endpoint_call when full request/response schema details are needed. External apps must call blueprint webhook endpoints.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose OpenAPI schema should be read."}}},call:async t=>{let n=Zn(t,"integrationType");return await wa(n),Yt(await dd(n))}},{name:"integration_endpoint_call",description:"Call one allowlisted backend integration endpoint by integrationType and operationId. First call integration_endpoints_list or integration_endpoint_schema_get, then pass one payload object matching the exposed payloadSchema. For endpoints with connectionId in payloadSchema, first call integration_connections_list. Can cause external reads or writes, read local files for multipart uploads, and write binary downloads to disk. Mutating or destructive endpoints require confirm=true. Supports JSON, form, multipart files, request headers, redirects, and binary downloads. MCP-only; not an external app runtime integration path. External apps must call blueprint webhook endpoints.",inputSchema:Z4(),call:async t=>{let n=Y4(t);return await wa(n.integrationType),Yt(await o0(n))}}]}async function b4(e,t){let n={type:Zn(t,"integrationType")};await wa(n.type);let r=wc(t,"spaceId");return r&&(n.spaceId=r),Yt(await e.readResourceItems("connections",{fieldEqualTo:n}))}function v4(e){return[{name:"auth_email_request_code",description:"Request email login code via Beepflow auth service.",inputSchema:{type:"object",additionalProperties:!1,required:["email"],properties:{email:{type:"string"}}},call:async t=>{let n=Zn(t,"email");return await dh(n),$4(`code sent to ${n}`)}},{name:"auth_email_verify_code",description:"Verify email login code and persist JWT for backend. Modifies stored credentials.",inputSchema:{type:"object",additionalProperties:!1,required:["email","code"],properties:{email:{type:"string"},code:{type:"string"}}},call:async t=>{let n=await ph(Zn(t,"email"),Zn(t,"code"));return e.close(),Yt(n)}},{name:"auth_google_sign_in",description:"Open Google OAuth login, wait for completion, and persist JWT for backend. Modifies stored credentials.",inputSchema:Rc,call:async()=>{let t=await mh();return t.status==="authenticated"&&e.close(),Yt(t)}},{name:"auth_sign_out",description:"Delete stored backend JWT. Modifies stored credentials.",inputSchema:Rc,call:async()=>(e.close(),Yt(await lh()))}]}async function S4(e,t){let n=Zn(t,"query"),r=Dc(t,"limit")??25,i=Ym(t,"includeDeprecated")??!1,o=await po(),[a,s]=await Promise.all([w4(n,r),e.readResourceItems("blueprint-operators")]),c=[];for(let d of a){let p=s[d.operatorId];p?.hidden!==!0&&(!i&&p?.isDeprecated===!0||Mc(o,d.operatorId)&&c.push(D4(d,p)))}return Yt({results:c})}async function y4(e,t){let n=Zn(t,"blueprintId"),r=Zn(t,"query"),i=Dc(t,"limit")??25,o=wc(t,"connectionId"),[a,s,c]=await Promise.all([e.readResourceItem("blueprints",n),e.readResourceItems("schemas"),e.readResourceItems("connections")]);if(!a)return Yt({results:[]});let d=await po(),p=j1(a,s,c,o).filter(g=>{let b=c[g.connectionId]?.type;return!b||hs(d,b)}),m=k4(p,r,i);return Yt({results:m})}async function E4(e){let t=await _h(),n=Ht(),r=await e.readResourceItem("user-locations",t),i=R4(r);if(!i)return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:null,location:r,tab:null,page:null,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let o=await e.readResourceItem("tabs",i);if(o?.type==="page"){let g=await e.readResourceItem("pages",i);return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:g,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]})}if(o?.type!=="blueprint")return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:null,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let[a,s]=await Promise.all([e.readResourceItem("blueprints",i),e.readResourceItem("blueprint-views",i)]);if(!a)return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:null,blueprint:null,blueprintView:s,blueprintOperators:{},contextFields:[]});let[c,d,p]=await Promise.all([T4(e,a),e.readResourceItems("schemas"),e.readResourceItems("connections")]),m=j1(a,d,p,void 0);return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:null,blueprint:a,blueprintView:s,blueprintOperators:c,contextFields:m})}async function T4(e,t){let n=A4(t),r=await e.readResourceItems("blueprint-operators"),i={};for(let o in n)i[o]=r[o]??null;return i}function A4(e){let t=e.nodes,n={};if(!lo(t))return n;for(let r in t){let i=t[r];if(!lo(i))continue;let o=i.operatorId;typeof o=="string"&&o.trim()&&(n[o]=!0)}return n}function R4(e){let t=e?.tab;if(lo(t)){let i=t.id;if(typeof i=="string"&&i.trim())return i}let n=e?.blueprint;if(!lo(n))return;let r=n.id;return typeof r=="string"&&r.trim()?r:void 0}async function w4(e,t){let n=await fi();if(!n)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let r=await di(n),i=Ht(),o=await fetch(`${i.backendUrl}/blueprint/operators/search`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({query:e,limit:t})});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`blueprint/operators/search failed: ${o.status} ${c}`.trim())}let a=await o.json().catch(()=>{});if(!Array.isArray(a))throw new Error("blueprint/operators/search returned invalid payload");let s=[];for(let c of a){if(!lo(c))continue;let d=c.operatorId,p=c.score;typeof d!="string"||typeof p!="number"||s.push({operatorId:d,score:p})}return s}function D4(e,t){return{kind:"operator",id:e.operatorId,name:Tc(t,"name"),categoryPath:H1(t,"categoryPath"),aliases:H1(t,"aliases"),doc:Tc(t,"doc"),inputs:B4(t),output:U4(t),score:e.score}}function j1(e,t,n,r){let i=C4(e.context,t),o=[];for(let a of i){if(!a.connectionId||r&&a.connectionId!==r)continue;let s=n[a.connectionId],c=M4(a.path);for(let d in a.schema)o.push({kind:"contextField",connectionId:a.connectionId,connectionLabel:s?.label??"???",path:c,field:d,type:a.schema[d]??"wildcard",score:0})}return o}function C4(e,t){if(!e?.type)return[];let n=O4(e);if(n){let o=t[n];return o?[o]:[]}let r=co(e.config,"connectionId"),i=[];for(let o in t){let a=t[o];if(a)switch(!0){case!!r:a.connectionId===r&&i.push(a);break;case a.type===e.type:i.push(a);break}}return i}function O4(e){let t=e.config,n=co(t,"connectionId");if(n)switch(e.type){case"ApacheKafkaTopic":return uo(n,{topicName:co(t,"topicName")});case"RabbitMQStream":case"MQTTTopic":return uo(n,{streamPattern:co(t,"streamPattern")});case"QdrantCollection":case"BaseVectorCollection":case"BaseLookupCollection":case"BaseEventCollection":return uo(n,{collectionName:co(t,"collectionName")});case"AerospikeSet":return uo(n,{namespace:co(t,"namespace"),setName:co(t,"setName")});case"KaggleFile":return uo(n,{datasetRef:co(t,"datasetRef"),fileName:co(t,"filePath")});case"GoogleDriveFile":return uo(n,{fileId:co(t,"fileId"),parser:co(t,"parser")});case"GmailMessage":return uo(n,{resource:"message"});case"GmailThread":return uo(n,{resource:"thread"});case"GmailEvent":return uo(n,{resource:"event"});case"GorgiasEvent":return uo(n,{resource:"event",variant:L4(t)?"message":"ticket"});case"GorgiasTicket":return uo(n,{resource:"ticket"})}}function k4(e,t,n){let r=[];return e.forEach((i,o)=>{let a=I4(t,x4(i));a!==void 0&&r.push({field:{...i,score:a},index:o})}),r.sort((i,o)=>o.field.score-i.field.score||i.index-o.index).slice(0,n).map(i=>i.field)}function x4(e){return[e.connectionLabel,e.path,e.field,e.type].join(" ")}function I4(e,t){let n=W1(e);if(n.length===0)return;let r=t.toLowerCase(),i=W1(t),o=0;for(let a of n){let s=P4(a,i),c=Math.max(s,r.includes(a)?.82:0);if(c<=0)return;o+=c}return Number((o/n.length).toFixed(4))}function P4(e,t){let n=0;for(let r of t)switch(!0){case r===e:n=Math.max(n,1);break;case r.startsWith(e):n=Math.max(n,.92);break;case r.includes(e):n=Math.max(n,.82);break;case(e.length>=3&&r.length>=3):n=Math.max(n,N4(e,r));break}return n}function N4(e,t){let n=Math.max(e.length,t.length);if(n===0)return 0;let r=1-F4(e,t)/n;return r>=.72?r*.7:0}function F4(e,t){let n=Array.from({length:t.length+1},(i,o)=>o),r=Array.from({length:t.length+1},()=>0);for(let i=1;i<=e.length;i+=1){r[0]=i;for(let o=1;o<=t.length;o+=1){let a=e[i-1]===t[o-1]?0:1;r[o]=Math.min(n[o]+1,r[o-1]+1,n[o-1]+a)}for(let o=0;o<n.length;o+=1)n[o]=r[o]??0}return n[t.length]??0}function W1(e){return e.toLowerCase().split(/[^a-z0-9]+/).map(t=>t.trim()).filter(Boolean)}function uo(e,t){let n="";for(let r in t){let i=t[r];if(!i)return;n+=`${r} = ${i} `}if(n=n.trim(),!!n)return f4("md5").update(`${e} ${n}`).digest("hex")}function M4(e){if(!e)return"";let t=[];for(let n in e)t.push(e[n]??"");return t.filter(Boolean).join("/")}function L4(e){let t=e?.webhookTriggers;if(!lo(t))return!1;for(let n in t)if(t[n]===!0&&d4.includes(n))return!0;return!1}function co(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function Tc(e,t){let n=e?.[t];return typeof n=="string"?n:void 0}function H1(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function B4(e){return Array.isArray(e?.inputs)?e.inputs.map(t=>Y1(t)).filter(t=>t.name):[]}function U4(e){let t=e?.output;if(!lo(t))return;let n=Y1(t);return n.name?n:void 0}function Y1(e){let t=lo(e)?e:void 0,n=lo(t?.type)?t.type:void 0;return{name:Tc(t,"name")??"",type:Tc(n,"type")??"",doc:Tc(t,"doc")}}async function V4(e,t){let n=Zn(t,"resultId"),r=Dc(t,"timeoutMs")??15e3,i=Dc(t,"quietMs")??250;await q4(e,n);let o=`${n}:events`,a=`results:${o}`;await e.start();let s=e.collectChannelEvents(a,c=>c.key===o,r,i);e.sendChannelEvent("results",{resource:"results",key:o,action:"subscribe-key"});try{return Yt(X4(await s))}finally{e.sendChannelEvent("results",{resource:"results",key:o,action:"unsubscribe-key"})}}async function q4(e,t){let n=z4(t);if(!n)throw new Error(`invalid result id: ${t}; expected blueprintId-test or blueprintId-explore`);let[r,i]=await Promise.all([e.readResourceItem("tabs",n.blueprintId),e.readResourceItem("blueprints",n.blueprintId)]);if(!r)throw new Error(`tab not found for result: ${n.blueprintId}`);if(r.type!=="blueprint")throw new Error(`tab is not a blueprint: ${n.blueprintId}`);if(!i)throw new Error(`blueprint not found for result: ${n.blueprintId}`);if(i.mode!==n.mode)throw new Error(`blueprint mode mismatch for result: requested ${n.mode}, blueprint is ${i.mode}`)}function z4(e){for(let t of["test","explore"]){let n=`-${t}`;if(e.endsWith(n)&&e.length>n.length)return{blueprintId:e.slice(0,-n.length),mode:t}}}async function K4(e,t){let n=Zn(t,"resultId");return await e.start(),e.sendChannelEvent("results",{resource:"results",key:n,action:"delete-state"}),Yt({ok:!0})}async function G4(e,t){let n=Zn(t,"resultId"),r=jm(t,"offsets");return await e.start(),e.sendChannelEvent("results",{resource:"results",key:n,action:"set-offsets",value:r}),Yt({ok:!0})}async function W4(e,t){let n=Zn(t,"channel");if(!X1.includes(n))throw new Error(`unsupported offset extent channel: ${n}`);let r=jm(t,"key"),i=Dc(t,"timeoutMs")??15e3;await e.start();let o=e.waitForChannelEvent(n,a=>JSON.stringify(a.key)===JSON.stringify(r),i);e.sendChannelEvent(n,{resource:n,key:r,action:"on"});try{return Yt(await o)}finally{e.sendChannelEvent(n,{resource:n,key:r,action:"off"})}}function H4(e){let t=j4(e,"keys"),n=Q1(e,"fieldEqualTo"),r=Ym(e,"all")??(!t&&!n),i={};return r&&(i.all=!0),t&&(i.keys=t),n&&(i.fieldEqualTo=n),i}function X4(e){let t={},n;for(let r of e){let i=r.value;switch(i?.kind){case"blueprint":n=i.value;break;case"node":{let o=i.nodeId;typeof o=="string"&&(t[o]=i.value);break}case"reset":n=void 0;for(let o in t)delete t[o];break}}return{public:n,publicByNode:t,events:e}}function Yt(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function $4(e){return{content:[{type:"text",text:e}]}}function Zn(e,t){let n=Aa(e)[t];if(typeof n!="string"||!n.trim())throw new Error(`invalid tool arguments: ${t} must be non-empty string`);return n}function wc(e,t){if(e===void 0)return;let n=Aa(e)[t];if(n!=null){if(typeof n!="string")throw new Error(`invalid tool arguments: ${t} must be string`);return n}}function jm(e,t){let n=Aa(e)[t];if(!lo(n))throw new Error(`invalid tool arguments: ${t} must be object`);return n}function Q1(e,t){let n=Aa(e)[t];if(n!=null){if(!lo(n))throw new Error(`invalid tool arguments: ${t} must be object`);return n}}function j4(e,t){let n=Aa(e)[t];if(n!=null){if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`invalid tool arguments: ${t} must be string array`);return n}}function Ym(e,t){let n=Aa(e)[t];if(n!=null){if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${t} must be boolean`);return n}}function Dc(e,t){let n=Aa(e)[t];if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error(`invalid tool arguments: ${t} must be positive integer`);return n}}function Y4(e){let t=Aa(e);for(let n of["path","query","headers","body","files"])if(t[n]!==void 0)throw new Error(`invalid tool arguments: use payload instead of ${n}`);return{integrationType:Zn(e,"integrationType"),operationId:Zn(e,"operationId"),payload:Q1(e,"payload"),outputFilePath:wc(e,"outputFilePath"),confirm:Ym(e,"confirm")}}function Aa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid tool arguments: expected object");return e}function lo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Q4(){return{type:"object",additionalProperties:!1,required:["query"],properties:{query:{type:"string",description:"Operator name, alias, category, or behavior to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of operator matches to return."},includeDeprecated:{type:"boolean",description:"Include deprecated operators in results when true."}}}}function J4(){return{type:"object",additionalProperties:!1,required:["blueprintId","query"],properties:{blueprintId:{type:"string",description:"Blueprint id whose context schemas should be searched."},query:{type:"string",description:"Field name, path, connection label, or type to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of context fields to return."},connectionId:{type:"string",description:"Optional connection id to restrict context field matches."}}}}function Z4(){return{type:"object",additionalProperties:!1,required:["integrationType","operationId"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list. MCP-only; not for external app data sources."},operationId:{type:"string",description:"Operation id from integration_endpoints_list or integration_endpoint_schema_get. MCP-only; not for external app data sources."},payload:{...Ac,description:"Single payload object matching payloadSchema from integration_endpoints_list or integration_endpoint_schema_get."},outputFilePath:{type:"string",description:"Local path where binary response downloads should be written."},confirm:{type:"boolean",description:"Required true for mutating or destructive endpoints after explicit user intent."}}}}function e5(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."},quietMs:{type:"integer",minimum:1,description:"Quiet period before returning collected events."}}}}function t5(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."}}}}function n5(){return{type:"object",additionalProperties:!1,required:["resultId","offsets"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},offsets:{...Ac,description:"Stream offsets to set for current result state."}}}}function r5(){return{type:"object",additionalProperties:!1,required:["channel","key"],properties:{channel:{type:"string",enum:X1,description:"Offset extent live channel to read."},key:{...Ac,description:"Stream partition key to read extents for."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."}}}}var Cc="application/json";function J1(e=_s()){return[{uri:"beepflow://resources",name:"Beepflow workspace resource registry",description:"Resource registry supported by this MCP server, including item schema URIs.",mimeType:Cc,read:async()=>Mf("beepflow://resources",Oa)},{uri:"beepflow://resource-schemas",name:"Beepflow workspace resource schema registry",description:"JSON Schema registry for resource items supported by this MCP server.",mimeType:Cc,read:async()=>Mf("beepflow://resource-schemas",Gc)},...Gc.map(t=>({uri:t.uri,name:`Beepflow ${t.resource} item schema`,description:`JSON Schema for ${t.resource} resource items.`,mimeType:Cc,read:async()=>Mf(t.uri,t)})),...Oa.map(t=>({uri:`beepflow://resources/${t.name}`,name:`Beepflow ${t.name}`,description:t.description,mimeType:Cc,read:async()=>{let n=await e.readResourceItems(t.name);return Mf(`beepflow://resources/${t.name}`,n)}}))]}function Mf(e,t){return{contents:[{uri:e,mimeType:Cc,text:JSON.stringify(t,null,2)}]}}var Lf=_s(),{server:i5,closeServer:o5}=oh({serverName:"mcp",serverVersion:"0.1.0",instructions:l0,tools:$1(Lf),resources:J1(Lf),onInitialized:()=>{Lf.start().catch(()=>{})}});process.on("SIGINT",()=>Z1("SIGINT"));process.on("SIGTERM",()=>Z1("SIGTERM"));i5.start();function Z1(e){Lf.close(),o5(e)}
101
+ `)}else i=r(n(e.join("")));return t.collapseWhitespace?cs(i,t,!0,!0):i}var n1=async function(e,t){let n=Date.now();t=RU(t||{});let r=await xf(e,t);return t.log("minified in: "+(Date.now()-n)+"ms"),r};var r1=8*1024*1024;function i1(e){return{name:"page_tabs_query",description:"Query page tabs and matching source/dist HTML file URLs. Use ids for exact page tabs or fieldEqualTo for exact top-level tab field matches.",inputSchema:Es("Page tab ids to read."),call:async t=>Me(await u1(e,ys(t),vs(t,"fieldEqualTo")))}}function o1(e){return{name:"page_tab_create",description:"Upload local UTF-8 HTML source and optimized dist files, then create a page tab. After create, tell user page URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`.",inputSchema:{type:"object",additionalProperties:!1,required:["htmlFilePath"],properties:{htmlFilePath:{type:"string",description:"Local UTF-8 HTML file to upload as page content. Maximum 8 MiB."},parent:{type:"string",description:"Parent id, normally spaces:<spaceId> or tabs:<folderId>. Optional only when existing tabs can provide a default."},name:{type:"string",description:"Tab name. Defaults to Untitled page."},insertAfterTabId:{type:"string",description:"Optional tab id after which to insert."}}},call:async t=>{let n=await c1(re(t,"htmlFilePath"));return Me(await kU(e,{...n,parent:bt(t,"parent"),name:bt(t,"name"),insertAfterTabId:bt(t,"insertAfterTabId")}))}}}function a1(e){return{name:"page_tab_html_set",description:"Upload local UTF-8 HTML source and optimized dist files, then replace URLs for an existing page tab. Frontend renders dist as untrusted sandbox iframe src.",inputSchema:rt({htmlFilePath:{type:"string",description:"Local UTF-8 HTML file to upload as replacement content. Maximum 8 MiB."}},["id","htmlFilePath"]),call:async t=>Me(await xU(e,re(t,"id"),await c1(re(t,"htmlFilePath"))))}}function s1(e){return{name:"page_tab_duplicate",description:"Duplicate a page tab by cloning tab metadata and HTML with a new shared id. After duplicate, tell user page URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`.",inputSchema:rt({name:{type:"string",description:"Optional duplicated tab name. Defaults to source name plus *."}}),call:async t=>Me(await IU(e,re(t,"id"),bt(t,"name")))}}async function u1(e,t,n){let r=t?n:{...n??{},type:"page"},i=await Fr(e,t,r),o={},a=[];for(let d in i)i[d].type==="page"&&(o[d]=i[d],a.push(d));let s=await e.readResourceItems("pages",{keys:a}),c={};for(let d in o)c[d]={tab:o[d],page:s[d]??null};return c}async function kU(e,t){Sc(t.sourceUrl,"sourceUrl"),Sc(t.distUrl,"distUrl");let n=await Fr(e),r=hi(),i=Rs(n,t.parent),o=Yo(n,i),a={id:r,updatedAt:Nr(),name:t.name??"Untitled page",order:As(n,{parent:i,insertAfterTabId:t.insertAfterTabId}),type:"page",parent:i,spaceId:o},s={id:r,updatedAt:Nr(),sourceUrl:t.sourceUrl,distUrl:t.distUrl};return dn("tabs",a),dn("pages",s),await Promise.all([e.upsertResourceItem("tabs",a),e.upsertResourceItem("pages",s)]),{tab:a,page:s}}async function xU(e,t,n){if(Sc(n.sourceUrl,"sourceUrl"),Sc(n.distUrl,"distUrl"),(await el(e,t)).type!=="page")throw new Error(`tab is not a page: ${t}`);let i={id:t,updatedAt:Nr(),...n};return dn("pages",i),await e.upsertResourceItem("pages",i),i}async function IU(e,t,n){let r=await Fr(e),i=(await u1(e,[t]))[t];if(!i)throw new Error(`page tab not found: ${t}`);if(!i.page)throw new Error(`page content not found: ${t}`);let o=hi(),a=structuredClone(i.tab);a.id=o,a.updatedAt=Nr(),a.name=n??`${i.tab.name}*`,a.order=xa(r,i.tab);let s={...structuredClone(i.page),id:o,updatedAt:Nr()};return dn("tabs",a),dn("pages",s),await Promise.all([e.upsertResourceItem("tabs",a),e.upsertResourceItem("pages",s)]),{tab:a,page:s}}async function PU(e){let t=await CU(e,"utf8");return FU(t),t}async function c1(e){let t=await PU(e),n=OU.basename(e)||"page.html",[r,i]=await Promise.all([l1(t,n),NU(t,n)]);return{sourceUrl:r,distUrl:i}}async function NU(e,t){let n=await n1(e,{collapseBooleanAttributes:!0,collapseWhitespace:!0,minifyCSS:!0,minifyJS:!0,removeComments:!0,removeRedundantAttributes:!0,removeScriptTypeAttributes:!0,removeStyleLinkTypeAttributes:!0,sortAttributes:!0,sortClassName:!0,useShortDoctype:!0});return l1(n,t)}async function l1(e,t,n){let r=new FormData;r.set("file",new Blob([e],{type:"text/html; charset=utf-8"}),t);let i=Ht(),o=await MU(),a=new URL(`${i.fileUrl}/upload`);a.searchParams.set("location","pages"),n&&a.searchParams.set("contentEncoding",n);let s=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:r});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`file upload failed: ${s.status} ${d}`.trim())}let c=await s.json().catch(()=>{});if(typeof c?.url!="string")throw new Error("file upload response missing url");return Sc(c.url,"url"),c.url}function FU(e){if(new TextEncoder().encode(e).length>r1)throw new Error(`html exceeds ${r1} bytes`)}async function MU(){let e=await fi();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");return await di(e)}function Sc(e,t){if(!e)throw new Error(`${t} must be non-empty string`)}async function yr(e,t){return Km(t),dn("blueprints",t),e.upsertResourceItem("blueprints",t)}function Km(e){for(let t in e.nodes){let n=e.nodes[t];for(let r in n.inputs){let i=n.inputs[r];for(let o in i.values)LU(i.values[o])}}}function LU(e){(!Object.prototype.hasOwnProperty.call(e,"literal")||e.literal===void 0)&&(e.literal=null)}function f1(e){return{name:"blueprint_context_update",description:"Replace blueprint context as one unit, including type, config, and exactly one trigger branch. When integrating external apps, set webhook trigger and tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger`.",inputSchema:rt({context:{...Jc,description:"Full replacement context with type, trigger, and optional config. Trigger must have exactly one branch."}},["id","context"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id")),r=nl(Qc(t,"context"));return await Fc(r.type),n.context=r,await yr(e,n),Me(n)}}}async function ya(e,t,n){let r=await fi();if(!r)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let i=await di(r),o=Ht(),a=await fetch(`${o.backendUrl}/blueprints/${e}/modes/${t}/${n}`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!a.ok){let s=await a.text().catch(()=>"");throw new Error(`blueprint runtime action failed: ${a.status} ${s}`.trim())}return{ok:!0,status:a.status,blueprintId:e,mode:t,action:n}}function Ea(e,t,n,r,i){return{name:t,description:n,inputSchema:rt({mode:{type:"string",enum:["test","explore"],description:r?"Target mode.":"Mode to use. Defaults to current blueprint mode."}},r?["id","mode"]:["id"]),call:async o=>{let a=re(o,"id"),c=Ss(o,"mode",["test","explore"])??(await Tt(e,a)).blueprint.mode;return Me(await i(a,c))}}}function d1(e){return Ea(e,"blueprint_mode_set","Switch blueprint mode through backend runtime endpoint to preserve side effects.",!0,async(t,n)=>ya(t,n,"switch-mode"))}function p1(e){return{name:"blueprint_test_records_set",description:"Set blueprint testRecordsAmount for test mode data generation. Uses replicated blueprint upsert; value must be at least 1.",inputSchema:rt({amount:{type:"integer",minimum:1,description:"Number of test records."}},["id","amount"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id"));return n.testRecordsAmount=d0(t,"amount"),await yr(e,n),Me(n)}}}function m1(e){return Ea(e,"blueprint_test_records_shuffle","Regenerate test records through backend /modes/test/shuffle-records endpoint.",!1,async t=>ya(t,"test","shuffle-records"))}function h1(e){return Ea(e,"blueprint_runtime_start","Start blueprint runtime for supplied mode or current blueprint mode through backend endpoint. When starting webhook trigger blueprint, tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(id)}/trigger`. Webhook runs only while blueprint is active in explore mode. External apps integrate by calling this blueprint webhook endpoint.",!1,async(t,n)=>ya(t,n,"start"))}function _1(e){return Ea(e,"blueprint_runtime_stop","Stop blueprint runtime for supplied mode or current blueprint mode through backend endpoint.",!1,async(t,n)=>ya(t,n,"stop"))}function g1(e){return{name:"blueprint_recompute_on_change_set",description:"Set recomputeOnChange to always or manual. Frontend treats undefined as always; this tool stores explicit value for clarity.",inputSchema:rt({value:{type:"string",enum:["always","manual"],description:"Recompute behavior."}},["id","value"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id"));return n.recomputeOnChange=Ii(t,"value",["always","manual"]),await yr(e,n),Me(n)}}}function b1(e){return{name:"blueprint_mock_never_set",description:"Set or clear blueprint-level mockNever. enabled=true stores true; enabled=false clears the optional field like frontend toggle.",inputSchema:rt({enabled:{type:"boolean",description:"Whether to disable mocking for all nodes."}},["id","enabled"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id"));return $o(t,"enabled")?n.mockNever=!0:delete n.mockNever,await yr(e,n),Me(n)}}}async function Do(e,t){let n=await e.readResourceItems("blueprint-operators"),r={};for(let i in t.nodes){let o=n[t.nodes[i].operatorId];o&&(r[o.id]=o)}return{...n,...r}}function Gm(e){if(Object.keys(e).length===0)return;let t=null,n=null;for(let r in e)isNaN(parseFloat(r))||(n===null||parseFloat(r)<n)&&(t=r,n=parseFloat(r));return n!==null?e[t]:void 0}function v1(e){let t=Object.keys(e).filter(o=>!isNaN(parseFloat(o))).sort((o,a)=>parseFloat(o)-parseFloat(a));if(t.length===0)return"0.5";let n=t[t.length-1],r=parseFloat(n);return((r+(Math.floor(r)+1))/2).toPrecision(15).replace(/0+$/,"").replace(/\.$/,"")}function Ta(e,t){let n=v1(e);return e[n]=t,n}var S1=new Set(["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"]);function tn(e,t){let n=e.nodes[t];if(!n)throw new Error(`blueprint node not found: ${t}`);return n}function Oi(e,t){let n=e.inputs[t];if(!n)throw new Error(`node input not found: ${e.id}.${t}`);return n.values??={},n}function If(e,t,n,r){let o=Oi(tn(e,t),n).values[r];if(!o)throw new Error(`input value not found: ${t}.${n}[${r}]`);return o}function yc(e,t){let n=e[t];if(!n)throw new Error(`blueprint operator not found: ${t}`);return n}function lu(e,t){let n=e.inputs.find(r=>r.name===t);if(!n)throw new Error(`operator input not found: ${e.id}.${t}`);return n}function Pf(e,t){let n=e.output;if(!n||n.name!==t)throw new Error(`operator output not found: ${e.id}.${t}`);return n}function Ui(e){delete e.nodeId,delete e.operatorInputId,delete e.nodeInputIndex}function y1(e,t){e.nodeId=t.nodeId,e.operatorInputId=t.operatorInputId,e.nodeInputIndex=t.nodeInputIndex}function fu(e,t,n,r,i){let o=tn(e,n.nodeId),a=tn(e,r.nodeId),s=yc(t,o.operatorId),c=yc(t,a.operatorId);Pf(s,n.pinName);let d=lu(c,r.pinName),p=Oi(a,r.pinName),m=n.index??"0.5",g=BU(p,d,r.index,i),b=p.values[g];return b.nodeId=o.id,b.operatorInputId=n.pinName,b.nodeInputIndex=m,g}function E1(e,t){let n=tn(e,t.nodeId),r=t.index??"0.5";if(t.pinPosition==="input"){let i=If(e,n.id,t.pinName,r);Ui(i);return}for(let i in e.nodes)for(let o in e.nodes[i].inputs)for(let a in e.nodes[i].inputs[o].values){let s=e.nodes[i].inputs[o].values[a];s.nodeId===n.id&&s.operatorInputId===t.pinName&&s.nodeInputIndex===r&&Ui(s)}}function BU(e,t,n,r){if(r)return n?(e.values[n]??={literal:null},n):Ta(e.values,{literal:null});if(n){if(!(n in e.values))throw new Error(`input value not found: ${t.name}[${n}]`);return n}return e.listInputMode==="items"||e.listInputMode===void 0&&t.type.isArray?Ta(e.values,{literal:null}):"0.5"in e.values?"0.5":(e.values["0.5"]={literal:null},"0.5")}function T1(e){return{name:"blueprint_pins_connect",description:"Connect one output pin to one input pin by writing pointer fields on target input value. Validates nodes and pin names; can create target array element. For newly created operator nodes, prefer passing inputConnections to blueprint_operator_node_add instead of calling this after creation, so layout sees graph edges before assigning coordinates.",inputSchema:rt({sourceNodeId:{type:"string"},sourceOutputName:{type:"string"},sourceIndex:mi(),targetNodeId:{type:"string"},targetInputName:{type:"string"},targetIndex:mi(),createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}},["id","sourceNodeId","sourceOutputName","targetNodeId","targetInputName"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=fu(n.blueprint,await Do(e,n.blueprint),{nodeId:re(t,"sourceNodeId"),pinName:re(t,"sourceOutputName"),index:bt(t,"sourceIndex")},{nodeId:re(t,"targetNodeId"),pinName:re(t,"targetInputName"),index:bt(t,"targetIndex")},Yc(t,"createTargetArrayElement")??!1);return await yr(e,n.blueprint),Me({targetIndex:r,blueprint:n.blueprint})}}}function $r(e,t,n,r,i){return{name:e,description:t,inputSchema:n,call:async o=>{let{blueprint:a}=await Tt(r,re(o,"id"));return i(a,o),await yr(r,a),Me(a)}}}function A1(e){return $r("blueprint_pin_unlink","Unlink an input pin value or all downstream links from an output pin.",rt({nodeId:{type:"string"},pinName:{type:"string"},pinPosition:{type:"string",enum:["input","output"]},index:mi()},["id","nodeId","pinName","pinPosition"]),e,(t,n)=>E1(t,{nodeId:re(n,"nodeId"),pinName:re(n,"pinName"),pinPosition:Ii(n,"pinPosition",["input","output"]),index:bt(n,"index")}))}async function Go(e,t){let n=await e.readResourceItem("blueprint-operators",t);if(!n)throw new Error(`blueprint operator not found: ${t}`);if(!Array.isArray(n.inputs))throw new Error(`blueprint operator has invalid inputs: ${t}`);return n}async function Co(e,t,n){Km(t),dn("blueprints",t),dn("blueprint-views",n);let[r,i]=await Promise.all([e.upsertResourceItem("blueprints",t),e.upsertResourceItem("blueprint-views",n)]);return{blueprintOk:r,blueprintViewOk:i}}function UU(e,t=hi()){let n={id:t,operatorId:e.id,inputs:{}};for(let r of e.inputs)r.type.isArray?n.inputs[r.name]={isArray:!0,listInputMode:"items",values:{}}:n.inputs[r.name]={listInputMode:r.type.type.startsWith("list of ")?"list":void 0,values:{"0.5":{literal:null}}};return n}function du(e,t,n){let r=UU(n);return e.nodes[r.id]=r,t.nodes[r.id]={id:r.id},r}function R1(e){return{name:"blueprint_node_input_literal_set",description:"Set a node input literal at a CRDT value index. Defaults index to 0.5. With disconnect=true, clears upstream pointer fields first. For newly created operator nodes, prefer inputLiterals on blueprint_operator_node_add instead of setting literals afterward.",inputSchema:_o({literal:{description:"JSON literal value to set."},index:mi(),disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}},["id","nodeId","inputName","literal"]),call:async t=>{let{blueprint:n}=await Tt(e,re(t,"id")),r=Wm(n,re(t,"nodeId"),re(t,"inputName"),bt(t,"index")??"0.5",Tr(t).literal,Yc(t,"disconnect")??!1);return await yr(e,n),Me({value:r,blueprint:n})}}}function Wm(e,t,n,r,i,o){let a=If(e,t,n,r);return a.literal=i,o&&Ui(a),a}function Ff(e,t,n,r,i,o){if(o!==void 0&&!S1.has(o))throw new Error(`unsupported type: ${o}`);let a=tn(e,n),s=yc(t,a.operatorId);r==="output"?VU(e,t,a,s,i,o):zU(e,t,a,s,i,o)}function Xm(e,t){return e.outputType??t.output?.type.type}function VU(e,t,n,r,i,o){let a=Pf(r,i);o===void 0||o===a.type.type?delete n.outputType:n.outputType=o;let s=o??a.type.type;for(let c in e.nodes)qU(e.nodes[c],t,n,i,s)}function qU(e,t,n,r,i){let o=t[e.operatorId];if(o)for(let a in e.inputs){let s=o.inputs.find(c=>c.name===a);if(s)for(let c in e.inputs[a].values){let d=e.inputs[a].values[c];d.nodeId!==n.id||d.operatorInputId!==r||(GU(i,e.inputs[a].type??s.type.type,s.type)?e.inputs[a].type=i:Ui(d))}}}function zU(e,t,n,r,i,o){let a=lu(r,i),s=Oi(n,i);o===void 0||o===a.type.type?delete s.type:s.type=o;let c=o??a.type.type;for(let d in s.values){let p=s.values[d];if(!p.nodeId||!p.operatorInputId)continue;let m=e.nodes[p.nodeId],g=m?t[m.operatorId]:void 0;if(!m||!g?.output)continue;let b=Xm(m,g);WU(b,c)||Ui(p)}KU(n,r,a.type,o)}function KU(e,t,n,r){let i=Hm(n);if(i){for(let o of t.inputs)Hm(o.type)===i&&(r?e.inputs[o.name].type=r:delete e.inputs[o.name].type);t.output&&Hm(t.output.type)===i&&(r?e.outputType=r:delete e.outputType)}}function GU(e,t,n){return Nf(t)?!n.allowedTypes||n.allowedTypes.length===0?!0:n.allowedTypes.some(r=>Ec(e)?e.includes(r.type):r.type===e):Ec(e)?e.includes(t):e===t}function WU(e,t){return!e||!t?!1:e==="list of wildcard"||t==="list of wildcard"?Ec(e)&&Ec(t):!Nf(e)&&!Nf(t)?Ec(e)?e.includes(t):e===t:!0}function Ec(e){return e?.startsWith("list of ")??!1}function Nf(e){return e==="wildcard"||e==="list of wildcard"}function Hm(e){if(e&&Nf(e.type))return e.linkType??"_"}function w1(e){return{name:"blueprint_operator_node_add",description:"Add an operator node using frontend default input creation. Leaves view position unset so frontend can place it after measuring dimensions. When creating connected or configured nodes, set inputConnections, inputLiterals, and inputTypeOverrides in this same call. Set inputTypeOverrides to list of X when connecting list output into scalar input so auto zipping runs. Prefer this over separate connect/literal/type calls immediately after creation because frontend layout sees first-write graph edges.",inputSchema:Ts({operatorId:{type:"string",description:"Registered blueprint operator id."},inputConnections:{type:"array",description:"Input connections to apply before first write. Use for all known input links when creating a node; prefer this over blueprint_pins_connect after creation because frontend layout uses these connections before assigning coordinates.",items:{type:"object",additionalProperties:!1,required:["inputName","sourceNodeId","sourceOutputName","sourceIndex"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},sourceNodeId:{type:"string",description:"Existing source node id."},sourceOutputName:{type:"string",description:"Source output pin name."},sourceIndex:{type:"string",description:"Source output CRDT index."},targetIndex:{type:"string",description:"Target input CRDT index. Defaults to 0.5 for scalar inputs."},createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}}}},inputLiterals:{type:"array",description:"Input literals to apply before first write. Use for all known literal inputs when creating a node; prefer this over blueprint_node_input_literal_set immediately after creation. Same behavior as blueprint_node_input_literal_set.",items:{type:"object",additionalProperties:!1,required:["inputName","literal"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},literal:{description:"JSON literal value to set."},index:{type:"string",description:"Target input CRDT index. Defaults to 0.5."},disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}}}},inputTypeOverrides:{type:"array",description:"Resolved input types to apply before first write. Use list of X on scalar inputs receiving list outputs to trigger auto zipping.",items:{type:"object",additionalProperties:!1,required:["inputName","type"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},type:{type:"string",enum:xo,description:"Resolved input type override."}}}}},["id","operatorId"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=re(t,"operatorId");if(!Mc(await po(),r))throw new Error(`blueprint operator is not enabled for current user: ${r}`);let i=await Go(e,r),o=du(n.blueprint,n.blueprintView,i);HU(n.blueprint,o.id,jU(t));let a=$U(t),s=YU(t),c=await Do(e,n.blueprint);a.length>0&&XU(n.blueprint,c,o.id,a);for(let d of s)Ff(n.blueprint,c,o.id,"input",d.inputName,d.type);return await Co(e,n.blueprint,n.blueprintView),Me({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function HU(e,t,n){for(let r of n){let i=e.nodes[t].inputs[r.inputName],o=i?.listInputMode==="items"||i?.listInputMode===void 0&&i?.isArray;o&&r.index&&(i.values[r.index]??={literal:null});let a=o?r.index??Ta(i.values,{literal:null}):r.index??"0.5";Wm(e,t,r.inputName,a,r.literal,r.disconnect??!1)}}function XU(e,t,n,r){for(let i of r){let o=e.nodes[n].inputs[i.inputName],a=o?.listInputMode==="items"||o?.listInputMode===void 0&&o?.isArray;fu(e,t,{nodeId:i.sourceNodeId,pinName:i.sourceOutputName,index:i.sourceIndex},{nodeId:n,pinName:i.inputName,index:i.targetIndex},i.createTargetArrayElement??!!a)}}function $U(e){let t=Tr(e).inputConnections;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid tool arguments: inputConnections must be array");let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!ko(i))throw new Error(`invalid tool arguments: inputConnections[${r}] must be object`);let o=i.inputName,a=i.sourceNodeId,s=i.sourceOutputName,c=i.sourceIndex,d=i.targetIndex,p=i.createTargetArrayElement;if(typeof o!="string"||!o.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].inputName must be non-empty string`);if(typeof a!="string"||!a.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceNodeId must be non-empty string`);if(typeof s!="string"||!s.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceOutputName must be non-empty string`);if(typeof c!="string"||!c.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceIndex must be non-empty string`);if(d!==void 0&&typeof d!="string")throw new Error(`invalid tool arguments: inputConnections[${r}].targetIndex must be string`);if(p!==void 0&&typeof p!="boolean")throw new Error(`invalid tool arguments: inputConnections[${r}].createTargetArrayElement must be boolean`);n.push({inputName:o,sourceNodeId:a,sourceOutputName:s,sourceIndex:c,targetIndex:d,createTargetArrayElement:p})}return n}function jU(e){let t=Tr(e).inputLiterals;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid tool arguments: inputLiterals must be array");let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!ko(i))throw new Error(`invalid tool arguments: inputLiterals[${r}] must be object`);let o=i.inputName,a=i.literal,s=i.index,c=i.disconnect;if(typeof o!="string"||!o.trim())throw new Error(`invalid tool arguments: inputLiterals[${r}].inputName must be non-empty string`);if(!("literal"in i))throw new Error(`invalid tool arguments: inputLiterals[${r}].literal is required`);if(s!==void 0&&typeof s!="string")throw new Error(`invalid tool arguments: inputLiterals[${r}].index must be string`);if(c!==void 0&&typeof c!="boolean")throw new Error(`invalid tool arguments: inputLiterals[${r}].disconnect must be boolean`);n.push({inputName:o,literal:a,index:s,disconnect:c})}return n}function YU(e){let t=Tr(e).inputTypeOverrides;if(t==null)return[];if(!Array.isArray(t))throw new Error("invalid tool arguments: inputTypeOverrides must be array");let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!ko(i))throw new Error(`invalid tool arguments: inputTypeOverrides[${r}] must be object`);let o=i.inputName,a=i.type;if(typeof o!="string"||!o.trim())throw new Error(`invalid tool arguments: inputTypeOverrides[${r}].inputName must be non-empty string`);if(typeof a!="string"||!xo.includes(a))throw new Error(`invalid tool arguments: inputTypeOverrides[${r}].type must be supported type`);n.push({inputName:o,type:a})}return n}function D1(e){return{name:"blueprint_context_field_node_add",description:"Add a context field getter node using Base/function/blueprint/field-wildcard, setting outputType and Path literal. Apache Kafka context config is initialized from field connection/path when unset.",inputSchema:Ts({connectionId:{type:"string",description:"Context field connection id."},path:{type:"string",description:"Context field path such as topic or collection."},field:{type:"string",description:"Field name to store in Path literal."},type:{type:"string",enum:xo,description:"Field output type."}},["id","connectionId","path","field","type"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=re(t,"connectionId"),i=await e.readResourceItem("connections",r);i?.type&&await wa(i.type);let o=await Go(e,"Base/function/blueprint/field-wildcard"),a=du(n.blueprint,n.blueprintView,o);return a.outputType=Ii(t,"type",xo),a.inputs.Path.values["0.5"]={literal:re(t,"field")},QU(n.blueprint.context,r,re(t,"path")),await Co(e,n.blueprint,n.blueprintView),Me({node:a,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function QU(e,t,n){e.type==="ApacheKafkaTopic"&&(e.config??={},e.config.topicName===void 0&&(e.config.connectionId=t,e.config.topicName=n))}function C1(e){return{name:"blueprint_node_result_field_node_add",description:"Add a map/get node for a field inferred from an upstream node result. Sets Path literal and optionally connects source output to Target input.",inputSchema:Ts({path:{type:"string",description:"Result field path to store in Path literal."},sourceNodeId:{type:"string",description:"Optional upstream source node id to connect into Target."},sourceOutputName:{type:"string",description:"Optional upstream output name. Defaults to source operator output."}},["id","path"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=await Go(e,"Base/function/map/get"),i=du(n.blueprint,n.blueprintView,r);i.inputs.Path.values["0.5"]={literal:re(t,"path")};let o=bt(t,"sourceNodeId");return o&&fu(n.blueprint,await Do(e,n.blueprint),{nodeId:o,pinName:bt(t,"sourceOutputName")??await JU(e,n.blueprint,o)},{nodeId:i.id,pinName:"Target",index:"0.5"},!1),await Co(e,n.blueprint,n.blueprintView),Me({node:i,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}async function JU(e,t,n){let r=t.nodes[n];if(!r)throw new Error(`source node not found: ${n}`);let i=await Go(e,r.operatorId);if(!i.output?.name)throw new Error(`source node operator has no output: ${r.operatorId}`);return i.output.name}function O1(e){return{name:"blueprint_node_array_input_add",description:"Append an element to an array input using frontend CRDT list index generation. Returns new index.",inputSchema:_o({literal:{description:"Optional initial literal value. Defaults to null."}},["id","nodeId","inputName"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=n.blueprint.nodes[re(t,"nodeId")];if(!r)throw new Error("node not found");let i=await Go(e,r.operatorId),o=Tr(t),a=Object.prototype.hasOwnProperty.call(o,"literal")?o.literal:null,s=ZU(n.blueprint,i,r.id,re(t,"inputName"),a);return await yr(e,n.blueprint),Me({index:s,blueprint:n.blueprint})}}}function ZU(e,t,n,r,i){let o=tn(e,n),a=lu(t,r),s=Oi(o,r);if(s.listInputMode!=="items"&&(s.listInputMode!==void 0||!a.type.isArray))throw new Error(`operator input is not an item list: ${r}`);return Ta(s.values,{literal:i===void 0?null:i})}function k1(e){return $r("blueprint_node_array_input_remove","Remove one CRDT-indexed value from a node array input.",_o({index:mi()},["id","nodeId","inputName","index"]),e,(t,n)=>e4(t,re(n,"nodeId"),re(n,"inputName"),re(n,"index")))}function e4(e,t,n,r){let i=Oi(tn(e,t),n);if(!(r in i.values))throw new Error(`input value not found: ${t}.${n}[${r}]`);delete i.values[r]}function x1(e){return $r("blueprint_node_array_input_move","Move array input values by swapping two CRDT entries. Provide indexA/indexB or index plus direction up/down.",_o({indexA:mi(),indexB:mi(),index:mi(),direction:{type:"string",enum:["up","down"],description:"Adjacent move direction when indexA/indexB are omitted."}},["id","nodeId","inputName"]),e,(t,n)=>{let r=re(n,"inputName"),i=t.nodes[re(n,"nodeId")];if(!i)throw new Error("node not found");let o=bt(n,"indexA")??re(n,"index"),a=bt(n,"indexB")??n4(i.inputs[r]?.values??{},o,Ii(n,"direction",["up","down"]));t4(t,i.id,r,o,a)})}function t4(e,t,n,r,i){let o=Oi(tn(e,t),n);if(!(r in o.values))throw new Error(`input value not found: ${t}.${n}[${r}]`);if(!(i in o.values))throw new Error(`input value not found: ${t}.${n}[${i}]`);let a=o.values[r];o.values[r]=o.values[i],o.values[i]=a}function n4(e,t,n){let r=[];for(let a in e)Number.isNaN(parseFloat(a))||r.push(a);r.sort((a,s)=>parseFloat(a)-parseFloat(s));let i=r.indexOf(t),o=n==="up"?r[i-1]:r[i+1];if(!o)throw new Error(`no adjacent input value ${n} from index ${t}`);return o}function I1(e){return $r("blueprint_node_input_zipping_set","Set or clear forceZipping on a node input. Use enabled=true when connected list output should run element-by-element even if input expects a list. enabled=false clears the optional field like frontend. Cache operators never zip.",_o({enabled:{type:"boolean",description:"Whether to force zipping; false clears stored field."}},["id","nodeId","inputName","enabled"]),e,(t,n)=>r4(t,re(n,"nodeId"),re(n,"inputName"),$o(n,"enabled")))}function r4(e,t,n,r){let i=Oi(tn(e,t),n);r?i.forceZipping=!0:delete i.forceZipping}function P1(e,t){let n=new Set(t);for(let r of n)i4(e,r);for(let r in e.nodes){let i=e.nodes[r];for(let o in i.inputs)for(let a in i.inputs[o].values){let s=i.inputs[o].values[a];(n.has(i.id)||s.nodeId&&n.has(s.nodeId))&&Ui(s)}}}function N1(e,t,n){let r={};for(let i of n){let o=e.nodes[i],a=o?t[o.operatorId]:void 0,s=a?.inputs[0];if(!o||!a?.output||!s)continue;let c=Xm(o,a),d=o.inputs[s.name]?.type??s.type.type;if(c!==d)continue;let p=Gm(o.inputs[s.name]?.values??{});p?.nodeId&&(r[o.id]=structuredClone(p))}return r}function F1(e,t,n){for(let r in e.inputs)for(let i in e.inputs[r].values){let o=e.inputs[r].values[i];o.nodeId&&(t[o.nodeId]?o.nodeId=t[o.nodeId]:n.has(o.nodeId)||Ui(o))}}function M1(e,t){t?y1(e,t):Ui(e)}function i4(e,t){if(!e.nodes[t])throw new Error(`blueprint node not found: ${t}`)}function L1(e){return $r("blueprint_node_connections_remove","Remove selected nodes input links and downstream links pointing to selected nodes.",rt({nodeIds:Io("Node ids whose connections should be removed.")},["id","nodeIds"]),e,(t,n)=>P1(t,jo(n,"nodeIds")))}function B1(e){return{name:"blueprint_node_type_set",description:"Set or clear an input/output resolved type. Omitting type or setting base type clears override; incompatible existing links are disconnected.",inputSchema:rt({nodeId:{type:"string"},xputType:{type:"string",enum:["input","output"]},pinName:{type:"string"},type:{type:"string",enum:xo,description:"Resolved type override. Omit to reset to operator base type."}},["id","nodeId","xputType","pinName"]),call:async t=>{let n=await Tt(e,re(t,"id"));return Ff(n.blueprint,await Do(e,n.blueprint),re(t,"nodeId"),Ii(t,"xputType",["input","output"]),re(t,"pinName"),Ss(t,"type",xo)),await yr(e,n.blueprint),Me(n.blueprint)}}}function U1(e){return $r("blueprint_nodes_disabled_set","Set or clear disabled on selected nodes. disabled=false clears optional field like frontend.",rt({nodeIds:Io("Node ids to update."),disabled:{type:"boolean",description:"Whether nodes should be disabled."}},["id","nodeIds","disabled"]),e,(t,n)=>o4(t,jo(n,"nodeIds"),$o(n,"disabled")))}function o4(e,t,n){for(let r of t){let i=tn(e,r);n?i.disabled=!0:delete i.disabled}}function V1(e){return $r("blueprint_node_mock_never_set","Set or clear node-level mockNever. enabled=false clears optional field like frontend.",rt({nodeId:{type:"string"},enabled:{type:"boolean"}},["id","nodeId","enabled"]),e,(t,n)=>a4(t,re(n,"nodeId"),$o(n,"enabled")))}function a4(e,t,n){let r=tn(e,t);n?r.mockNever=!0:delete r.mockNever}function q1(e){return $r("blueprint_node_skip_behavior_set","Set On Skip behavior. behavior=skip clears stored value because frontend default skip is undefined; behavior=null stores string null.",rt({nodeId:{type:"string"},behavior:{type:"string",enum:["skip","null"]}},["id","nodeId","behavior"]),e,(t,n)=>s4(t,re(n,"nodeId"),Ii(n,"behavior",["skip","null"])))}function s4(e,t,n){let r=tn(e,t);n==="skip"?delete r.skipBehavior:r.skipBehavior="null"}function z1(e){return{name:"blueprint_nodes_delete",description:"Delete blueprint nodes and view nodes. Mirrors frontend rewire behavior for deleted nodes whose first input type matches output type.",inputSchema:rt({nodeIds:Io("Node ids to delete.")},["id","nodeIds"]),call:async t=>{let n=await Tt(e,re(t,"id"));return u4(n.blueprint,n.blueprintView,await Do(e,n.blueprint),jo(t,"nodeIds")),await Co(e,n.blueprint,n.blueprintView),Me({blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function u4(e,t,n,r){let i=new Set(r);for(let a of i)tn(e,a);let o=N1(e,n,i);for(let a in e.nodes)for(let s in e.nodes[a].inputs)for(let c in e.nodes[a].inputs[s].values){let d=e.nodes[a].inputs[s].values[c];!d.nodeId||!i.has(d.nodeId)||M1(d,o[d.nodeId])}for(let a of i)delete e.nodes[a],delete t.nodes[a]}function K1(e){return{name:"blueprint_nodes_duplicate",description:"Duplicate selected nodes and view nodes. Remaps internal copied-node references, drops missing-node references, and leaves new node positions for the frontend layout pass.",inputSchema:rt({nodeIds:Io("Node ids to duplicate.")},["id","nodeIds"]),call:async t=>{let n=await Tt(e,re(t,"id")),r=c4(n.blueprint,n.blueprintView,jo(t,"nodeIds"));return await Co(e,n.blueprint,n.blueprintView),Me({nodeIds:r,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function c4(e,t,n){let r=new Set(n);for(let s of r)tn(e,s);let i={},o=n.map(s=>structuredClone(e.nodes[s])),a=new Set;for(let s in e.nodes)a.add(s);for(let s of o){let c=hi();i[s.id]=c,s.id=c}for(let s of o)F1(s,i,a);for(let s of o)e.nodes[s.id]=s;for(let s of n){let c=structuredClone(t.nodes[s]??{id:s}),d=i[s];c.id=d,l4(c),t.nodes[d]=c}return n.map(s=>i[s])}function l4(e){if(!e.style)return;let t={...e.style};delete t.x,delete t.y;for(let n in t){e.style=t;return}delete e.style}function G1(e){return[m0(e),i1(e),T0(e),g0(e),b0(e),v0(e),S0(e),A0(e),R0(e),o1(e),s1(e),a1(e),f1(e),d1(e),p1(e),m1(e),h1(e),_1(e),g1(e),b1(e),w1(e),D1(e),C1(e),R1(e),O1(e),k1(e),x1(e),I1(e),T1(e),A1(e),L1(e),B1(e),U1(e),V1(e),q1(e),z1(e),K1(e)]}var Ac={type:"object",additionalProperties:!0},Rc={type:"object",additionalProperties:!1,properties:{}},X1=["kafka-topic:offset-extents","rabbitmq-stream:offset-extents","base-event-collection:offset-extents","shopify-webhook:offset-extents"],d4=["ticket-message-created","ticket-message-failed"];function $1(e=_s()){return[...p4(e),...m4(e),...h4(e),...G1(e),..._4(e),...g4(e),...v4(e)]}function p4(e){return[{name:"resources_list",description:"Discover Beepflow resources supported by this MCP server, including writable flags and item schema URIs.",inputSchema:Rc,call:async()=>Yt({resources:Oa,note:"tabs, pages, blueprints, and blueprint-views are dedicated resources; use tabs_query, page_tabs_query, blueprints_query, and tab intent tools instead of generic resource_* tools."})},{name:"resource_schema_get",description:"Read JSON Schema and mutation notes for one Beepflow resource item. Use before constructing an upsert item unless modifying an item read from the same resource.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:mu,description:"Resource whose item JSON Schema and mutation notes should be read."}}},call:async t=>{let n=Zf(Zn(t,"resource"));return Yt(Wc(n))}},{name:"resource_query",description:"Query a Beepflow resource with all, keys, or fieldEqualTo snapshot filters. Returns an item map. Use before editing existing resource items.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:mu,description:"Resource collection to query."},all:{type:"boolean",description:"Return whole resource collection."},keys:{type:"array",items:{type:"string"},description:"Return items with these ids."},fieldEqualTo:{...Ac,description:"Return items whose fields equal these exact values."}}},call:async t=>{let n=Zf(Zn(t,"resource"));await $m(n);let r=H4(t),i=await e.readResourceItems(n,r);return Yt(i)}},{name:"resource_upsert",description:"Create or update one writable Beepflow resource item. Mandatory: before calling resource_upsert, first call resource_schema_get for the same resource and ensure item matches that resource schema. Send full item state, not JSON patches; preserve unchanged fields.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","item"],properties:{resource:{type:"string",enum:mu,description:"Writable resource collection to create or update."},item:{...Ac,description:"Full item state with non-empty id; not a JSON patch."}}},call:async t=>{let n=ed(Zn(t,"resource"));await $m(n);let r=jm(t,"item"),i=r.id;if(typeof i!="string"||!i)throw new Error("item.id must be non-empty string");dn(n,r);let o=await e.upsertResourceItem(n,r);return Yt({ok:o})}},{name:"resource_delete",description:"Delete one writable Beepflow resource item by key. Destructive; use only when user intent is explicit.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","key"],properties:{resource:{type:"string",enum:mu,description:"Writable resource collection to delete from."},key:{type:"string",description:"Item id to delete."}}},call:async t=>{let n=ed(Zn(t,"resource"));await $m(n);let r=Zn(t,"key"),i=await e.deleteResourceItem(n,r);return Yt({ok:i})}}]}function m4(e){return[{name:"status",description:"Mandatory first call before any Beepflow task. Call status at least once whenever user wants to inspect, edit, debug, or operate Beepflow, so agent has latest user status and MCP instructions. Returns MCP instructions, frontendUrl, backendUrl, current authenticated user location, current tab id, tab, page file URL, blueprint, blueprint view, used operator definitions, and context fields when on a blueprint tab.",inputSchema:Rc,call:async()=>E4(e)}]}async function $m(e){e!=="users"&&e!=="roles"||await gh(e)}function h4(e){return[{name:"results_read",description:"Read current blueprint result events for a result id such as tabId-test or tabId-explore. Blueprint result ids are tabId-test and tabId-explore.",inputSchema:e5(),call:async t=>V4(e,t)},{name:"results_delete_state",description:"Stop and delete persisted result state for a result id. State-changing; use only when user intent is explicit.",inputSchema:t5(),call:async t=>K4(e,t)},{name:"results_set_offsets",description:"Set current stream offsets for a result id. State-changing; use only when user intent is explicit.",inputSchema:n5(),call:async t=>G4(e,t)},{name:"stream_offset_extents_read",description:"Read stream partition offset extents from supported frontend live channels for runtime diagnostics.",inputSchema:r5(),call:async t=>W4(e,t)}]}function _4(e){return[{name:"blueprint_operators_search",description:"Search blueprint operators with the same vector endpoint used by the editor menu. Use to find valid operator ids plus input/output metadata before editing blueprint nodes.",inputSchema:Q4(),call:async t=>S4(e,t)},{name:"blueprint_context_fields_search",description:"Search contextual fields available to a blueprint using the editor menu field matching rules. Use to find fields available from blueprint context schemas.",inputSchema:J4(),call:async t=>y4(e,t)}]}function g4(e){return[{name:"integrations_list",description:"List integration types available from the backend integration API. Use before listing endpoints for an integration type.",inputSchema:Rc,call:async()=>{let t=await po();return Yt((await r0()).filter(n=>hs(t,n)))}},{name:"integration_blueprint_contexts_list",description:"List backend-defined blueprint context resource types, including executionKind, config fields, and type/config templates. If a resource type is absent, do not use it for blueprint context. Use before blueprint_tab_create or blueprint_context_update when choosing context.type, context.trigger, and context.config. executionKind=managed means choose trigger { executor: { enabled: true } } because integration runtime owns stream/event/poll lifecycle. executionKind=finite means choose trigger from user intent: manual for ad hoc/sample/start-once execution, cron for scheduled refresh, loop for fixed-delay repeated polling, blueprint for upstream blueprint invocation, and webhook only for generic GET/POST /:tabId/trigger HTTP calls, not integration webhooks.",inputSchema:{type:"object",additionalProperties:!1,properties:{integrationType:{type:"string",description:"Optional integration type from integrations_list; omit to return all blueprint context resource definitions including ManualTick."},resourceType:{type:"string",description:"Optional integration resource type to return one matching blueprint context definition."}}},call:async t=>{let n=await po();return Yt((await i0(wc(t,"integrationType"),wc(t,"resourceType"))).filter(r=>Nc(n,r.resourceType)))}},{name:"integration_endpoints_list",description:"List backend integration endpoints for one integration type from workspace OpenAPI metadata, including access, side effect, request, response, confirmation metadata, parameters, requestBody, and payloadSchema for integration_endpoint_call. If payloadSchema includes connectionId, use integration_connections_list before integration_endpoint_call. MCP-only; external apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list."}}},call:async t=>{let n=Zn(t,"integrationType");return await wa(n),Yt(await fd(n))}},{name:"integration_connections_list",description:"List redacted workspace connections for one integration type. Use this to find connectionId before integration_endpoint_call when endpoint payloadSchema declares connectionId. Use status only to disambiguate by current space when multiple matching connections exist. External apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose connections should be listed."},spaceId:{type:"string",description:"Optional space id to restrict connection matches."}}},call:async t=>b4(e,t)},{name:"integration_endpoint_schema_get",description:"MCP-only; not for external app data sources. Read OpenAPI 3.1 schema for one integration type. Use before integration_endpoint_call when full request/response schema details are needed. External apps must call blueprint webhook endpoints.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose OpenAPI schema should be read."}}},call:async t=>{let n=Zn(t,"integrationType");return await wa(n),Yt(await dd(n))}},{name:"integration_endpoint_call",description:"Call one allowlisted backend integration endpoint by integrationType and operationId. First call integration_endpoints_list or integration_endpoint_schema_get, then pass one payload object matching the exposed payloadSchema. For endpoints with connectionId in payloadSchema, first call integration_connections_list. Can cause external reads or writes, read local files for multipart uploads, and write binary downloads to disk. Mutating or destructive endpoints require confirm=true. Supports JSON, form, multipart files, request headers, redirects, and binary downloads. MCP-only; not an external app runtime integration path. External apps must call blueprint webhook endpoints.",inputSchema:Z4(),call:async t=>{let n=Y4(t);return await wa(n.integrationType),Yt(await o0(n))}}]}async function b4(e,t){let n={type:Zn(t,"integrationType")};await wa(n.type);let r=wc(t,"spaceId");return r&&(n.spaceId=r),Yt(await e.readResourceItems("connections",{fieldEqualTo:n}))}function v4(e){return[{name:"auth_email_request_code",description:"Request email login code via Beepflow auth service.",inputSchema:{type:"object",additionalProperties:!1,required:["email"],properties:{email:{type:"string"}}},call:async t=>{let n=Zn(t,"email");return await dh(n),$4(`code sent to ${n}`)}},{name:"auth_email_verify_code",description:"Verify email login code and persist JWT for backend. Modifies stored credentials.",inputSchema:{type:"object",additionalProperties:!1,required:["email","code"],properties:{email:{type:"string"},code:{type:"string"}}},call:async t=>{let n=await ph(Zn(t,"email"),Zn(t,"code"));return e.close(),Yt(n)}},{name:"auth_google_sign_in",description:"Open Google OAuth login, wait for completion, and persist JWT for backend. Modifies stored credentials.",inputSchema:Rc,call:async()=>{let t=await mh();return t.status==="authenticated"&&e.close(),Yt(t)}},{name:"auth_sign_out",description:"Delete stored backend JWT. Modifies stored credentials.",inputSchema:Rc,call:async()=>(e.close(),Yt(await lh()))}]}async function S4(e,t){let n=Zn(t,"query"),r=Dc(t,"limit")??25,i=Ym(t,"includeDeprecated")??!1,o=await po(),[a,s]=await Promise.all([w4(n,r),e.readResourceItems("blueprint-operators")]),c=[];for(let d of a){let p=s[d.operatorId];p?.hidden!==!0&&(!i&&p?.isDeprecated===!0||Mc(o,d.operatorId)&&c.push(D4(d,p)))}return Yt({results:c})}async function y4(e,t){let n=Zn(t,"blueprintId"),r=Zn(t,"query"),i=Dc(t,"limit")??25,o=wc(t,"connectionId"),[a,s,c]=await Promise.all([e.readResourceItem("blueprints",n),e.readResourceItems("schemas"),e.readResourceItems("connections")]);if(!a)return Yt({results:[]});let d=await po(),p=j1(a,s,c,o).filter(g=>{let b=c[g.connectionId]?.type;return!b||hs(d,b)}),m=k4(p,r,i);return Yt({results:m})}async function E4(e){let t=await _h(),n=Ht(),r=await e.readResourceItem("user-locations",t),i=R4(r);if(!i)return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:null,location:r,tab:null,page:null,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let o=await e.readResourceItem("tabs",i);if(o?.type==="page"){let g=await e.readResourceItem("pages",i);return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:g,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]})}if(o?.type!=="blueprint")return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:null,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let[a,s]=await Promise.all([e.readResourceItem("blueprints",i),e.readResourceItem("blueprint-views",i)]);if(!a)return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:null,blueprint:null,blueprintView:s,blueprintOperators:{},contextFields:[]});let[c,d,p]=await Promise.all([T4(e,a),e.readResourceItems("schemas"),e.readResourceItems("connections")]),m=j1(a,d,p,void 0);return Yt({instructions:bs,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:t,tabId:i,location:r,tab:o,page:null,blueprint:a,blueprintView:s,blueprintOperators:c,contextFields:m})}async function T4(e,t){let n=A4(t),r=await e.readResourceItems("blueprint-operators"),i={};for(let o in n)i[o]=r[o]??null;return i}function A4(e){let t=e.nodes,n={};if(!lo(t))return n;for(let r in t){let i=t[r];if(!lo(i))continue;let o=i.operatorId;typeof o=="string"&&o.trim()&&(n[o]=!0)}return n}function R4(e){let t=e?.tab;if(lo(t)){let i=t.id;if(typeof i=="string"&&i.trim())return i}let n=e?.blueprint;if(!lo(n))return;let r=n.id;return typeof r=="string"&&r.trim()?r:void 0}async function w4(e,t){let n=await fi();if(!n)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let r=await di(n),i=Ht(),o=await fetch(`${i.backendUrl}/blueprint/operators/search`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({query:e,limit:t})});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`blueprint/operators/search failed: ${o.status} ${c}`.trim())}let a=await o.json().catch(()=>{});if(!Array.isArray(a))throw new Error("blueprint/operators/search returned invalid payload");let s=[];for(let c of a){if(!lo(c))continue;let d=c.operatorId,p=c.score;typeof d!="string"||typeof p!="number"||s.push({operatorId:d,score:p})}return s}function D4(e,t){return{kind:"operator",id:e.operatorId,name:Tc(t,"name"),categoryPath:H1(t,"categoryPath"),aliases:H1(t,"aliases"),doc:Tc(t,"doc"),inputs:B4(t),output:U4(t),score:e.score}}function j1(e,t,n,r){let i=C4(e.context,t),o=[];for(let a of i){if(!a.connectionId||r&&a.connectionId!==r)continue;let s=n[a.connectionId],c=M4(a.path);for(let d in a.schema)o.push({kind:"contextField",connectionId:a.connectionId,connectionLabel:s?.label??"???",path:c,field:d,type:a.schema[d]??"wildcard",score:0})}return o}function C4(e,t){if(!e?.type)return[];let n=O4(e);if(n){let o=t[n];return o?[o]:[]}let r=co(e.config,"connectionId"),i=[];for(let o in t){let a=t[o];if(a)switch(!0){case!!r:a.connectionId===r&&i.push(a);break;case a.type===e.type:i.push(a);break}}return i}function O4(e){let t=e.config,n=co(t,"connectionId");if(n)switch(e.type){case"ApacheKafkaTopic":return uo(n,{topicName:co(t,"topicName")});case"RabbitMQStream":case"MQTTTopic":return uo(n,{streamPattern:co(t,"streamPattern")});case"QdrantCollection":case"BaseVectorCollection":case"BaseLookupCollection":case"BaseEventCollection":return uo(n,{collectionName:co(t,"collectionName")});case"AerospikeSet":return uo(n,{namespace:co(t,"namespace"),setName:co(t,"setName")});case"KaggleFile":return uo(n,{datasetRef:co(t,"datasetRef"),fileName:co(t,"filePath")});case"GoogleDriveFile":return uo(n,{fileId:co(t,"fileId"),parser:co(t,"parser")});case"GmailMessage":return uo(n,{resource:"message"});case"GmailThread":return uo(n,{resource:"thread"});case"GmailEvent":return uo(n,{resource:"event"});case"GorgiasEvent":return uo(n,{resource:"event",variant:L4(t)?"message":"ticket"});case"GorgiasTicket":return uo(n,{resource:"ticket"})}}function k4(e,t,n){let r=[];return e.forEach((i,o)=>{let a=I4(t,x4(i));a!==void 0&&r.push({field:{...i,score:a},index:o})}),r.sort((i,o)=>o.field.score-i.field.score||i.index-o.index).slice(0,n).map(i=>i.field)}function x4(e){return[e.connectionLabel,e.path,e.field,e.type].join(" ")}function I4(e,t){let n=W1(e);if(n.length===0)return;let r=t.toLowerCase(),i=W1(t),o=0;for(let a of n){let s=P4(a,i),c=Math.max(s,r.includes(a)?.82:0);if(c<=0)return;o+=c}return Number((o/n.length).toFixed(4))}function P4(e,t){let n=0;for(let r of t)switch(!0){case r===e:n=Math.max(n,1);break;case r.startsWith(e):n=Math.max(n,.92);break;case r.includes(e):n=Math.max(n,.82);break;case(e.length>=3&&r.length>=3):n=Math.max(n,N4(e,r));break}return n}function N4(e,t){let n=Math.max(e.length,t.length);if(n===0)return 0;let r=1-F4(e,t)/n;return r>=.72?r*.7:0}function F4(e,t){let n=Array.from({length:t.length+1},(i,o)=>o),r=Array.from({length:t.length+1},()=>0);for(let i=1;i<=e.length;i+=1){r[0]=i;for(let o=1;o<=t.length;o+=1){let a=e[i-1]===t[o-1]?0:1;r[o]=Math.min(n[o]+1,r[o-1]+1,n[o-1]+a)}for(let o=0;o<n.length;o+=1)n[o]=r[o]??0}return n[t.length]??0}function W1(e){return e.toLowerCase().split(/[^a-z0-9]+/).map(t=>t.trim()).filter(Boolean)}function uo(e,t){let n="";for(let r in t){let i=t[r];if(!i)return;n+=`${r} = ${i} `}if(n=n.trim(),!!n)return f4("md5").update(`${e} ${n}`).digest("hex")}function M4(e){if(!e)return"";let t=[];for(let n in e)t.push(e[n]??"");return t.filter(Boolean).join("/")}function L4(e){let t=e?.webhookTriggers;if(!lo(t))return!1;for(let n in t)if(t[n]===!0&&d4.includes(n))return!0;return!1}function co(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n:void 0}function Tc(e,t){let n=e?.[t];return typeof n=="string"?n:void 0}function H1(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function B4(e){return Array.isArray(e?.inputs)?e.inputs.map(t=>Y1(t)).filter(t=>t.name):[]}function U4(e){let t=e?.output;if(!lo(t))return;let n=Y1(t);return n.name?n:void 0}function Y1(e){let t=lo(e)?e:void 0,n=lo(t?.type)?t.type:void 0;return{name:Tc(t,"name")??"",type:Tc(n,"type")??"",doc:Tc(t,"doc")}}async function V4(e,t){let n=Zn(t,"resultId"),r=Dc(t,"timeoutMs")??15e3,i=Dc(t,"quietMs")??250;await q4(e,n);let o=`${n}:events`,a=`results:${o}`;await e.start();let s=e.collectChannelEvents(a,c=>c.key===o,r,i);e.sendChannelEvent("results",{resource:"results",key:o,action:"subscribe-key"});try{return Yt(X4(await s))}finally{e.sendChannelEvent("results",{resource:"results",key:o,action:"unsubscribe-key"})}}async function q4(e,t){let n=z4(t);if(!n)throw new Error(`invalid result id: ${t}; expected blueprintId-test or blueprintId-explore`);let[r,i]=await Promise.all([e.readResourceItem("tabs",n.blueprintId),e.readResourceItem("blueprints",n.blueprintId)]);if(!r)throw new Error(`tab not found for result: ${n.blueprintId}`);if(r.type!=="blueprint")throw new Error(`tab is not a blueprint: ${n.blueprintId}`);if(!i)throw new Error(`blueprint not found for result: ${n.blueprintId}`);if(i.mode!==n.mode)throw new Error(`blueprint mode mismatch for result: requested ${n.mode}, blueprint is ${i.mode}`)}function z4(e){for(let t of["test","explore"]){let n=`-${t}`;if(e.endsWith(n)&&e.length>n.length)return{blueprintId:e.slice(0,-n.length),mode:t}}}async function K4(e,t){let n=Zn(t,"resultId");return await e.start(),e.sendChannelEvent("results",{resource:"results",key:n,action:"delete-state"}),Yt({ok:!0})}async function G4(e,t){let n=Zn(t,"resultId"),r=jm(t,"offsets");return await e.start(),e.sendChannelEvent("results",{resource:"results",key:n,action:"set-offsets",value:r}),Yt({ok:!0})}async function W4(e,t){let n=Zn(t,"channel");if(!X1.includes(n))throw new Error(`unsupported offset extent channel: ${n}`);let r=jm(t,"key"),i=Dc(t,"timeoutMs")??15e3;await e.start();let o=e.waitForChannelEvent(n,a=>JSON.stringify(a.key)===JSON.stringify(r),i);e.sendChannelEvent(n,{resource:n,key:r,action:"on"});try{return Yt(await o)}finally{e.sendChannelEvent(n,{resource:n,key:r,action:"off"})}}function H4(e){let t=j4(e,"keys"),n=Q1(e,"fieldEqualTo"),r=Ym(e,"all")??(!t&&!n),i={};return r&&(i.all=!0),t&&(i.keys=t),n&&(i.fieldEqualTo=n),i}function X4(e){let t={},n;for(let r of e){let i=r.value;switch(i?.kind){case"blueprint":n=i.value;break;case"node":{let o=i.nodeId;typeof o=="string"&&(t[o]=i.value);break}case"reset":n=void 0;for(let o in t)delete t[o];break}}return{public:n,publicByNode:t,events:e}}function Yt(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function $4(e){return{content:[{type:"text",text:e}]}}function Zn(e,t){let n=Aa(e)[t];if(typeof n!="string"||!n.trim())throw new Error(`invalid tool arguments: ${t} must be non-empty string`);return n}function wc(e,t){if(e===void 0)return;let n=Aa(e)[t];if(n!=null){if(typeof n!="string")throw new Error(`invalid tool arguments: ${t} must be string`);return n}}function jm(e,t){let n=Aa(e)[t];if(!lo(n))throw new Error(`invalid tool arguments: ${t} must be object`);return n}function Q1(e,t){let n=Aa(e)[t];if(n!=null){if(!lo(n))throw new Error(`invalid tool arguments: ${t} must be object`);return n}}function j4(e,t){let n=Aa(e)[t];if(n!=null){if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`invalid tool arguments: ${t} must be string array`);return n}}function Ym(e,t){let n=Aa(e)[t];if(n!=null){if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${t} must be boolean`);return n}}function Dc(e,t){let n=Aa(e)[t];if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error(`invalid tool arguments: ${t} must be positive integer`);return n}}function Y4(e){let t=Aa(e);for(let n of["path","query","headers","body","files"])if(t[n]!==void 0)throw new Error(`invalid tool arguments: use payload instead of ${n}`);return{integrationType:Zn(e,"integrationType"),operationId:Zn(e,"operationId"),payload:Q1(e,"payload"),outputFilePath:wc(e,"outputFilePath"),confirm:Ym(e,"confirm")}}function Aa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid tool arguments: expected object");return e}function lo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Q4(){return{type:"object",additionalProperties:!1,required:["query"],properties:{query:{type:"string",description:"Operator name, alias, category, or behavior to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of operator matches to return."},includeDeprecated:{type:"boolean",description:"Include deprecated operators in results when true."}}}}function J4(){return{type:"object",additionalProperties:!1,required:["blueprintId","query"],properties:{blueprintId:{type:"string",description:"Blueprint id whose context schemas should be searched."},query:{type:"string",description:"Field name, path, connection label, or type to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of context fields to return."},connectionId:{type:"string",description:"Optional connection id to restrict context field matches."}}}}function Z4(){return{type:"object",additionalProperties:!1,required:["integrationType","operationId"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list. MCP-only; not for external app data sources."},operationId:{type:"string",description:"Operation id from integration_endpoints_list or integration_endpoint_schema_get. MCP-only; not for external app data sources."},payload:{...Ac,description:"Single payload object matching payloadSchema from integration_endpoints_list or integration_endpoint_schema_get."},outputFilePath:{type:"string",description:"Local path where binary response downloads should be written."},confirm:{type:"boolean",description:"Required true for mutating or destructive endpoints after explicit user intent."}}}}function e5(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."},quietMs:{type:"integer",minimum:1,description:"Quiet period before returning collected events."}}}}function t5(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."}}}}function n5(){return{type:"object",additionalProperties:!1,required:["resultId","offsets"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},offsets:{...Ac,description:"Stream offsets to set for current result state."}}}}function r5(){return{type:"object",additionalProperties:!1,required:["channel","key"],properties:{channel:{type:"string",enum:X1,description:"Offset extent live channel to read."},key:{...Ac,description:"Stream partition key to read extents for."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."}}}}var Cc="application/json";function J1(e=_s()){return[{uri:"beepflow://resources",name:"Beepflow workspace resource registry",description:"Resource registry supported by this MCP server, including item schema URIs.",mimeType:Cc,read:async()=>Mf("beepflow://resources",Oa)},{uri:"beepflow://resource-schemas",name:"Beepflow workspace resource schema registry",description:"JSON Schema registry for resource items supported by this MCP server.",mimeType:Cc,read:async()=>Mf("beepflow://resource-schemas",Gc)},...Gc.map(t=>({uri:t.uri,name:`Beepflow ${t.resource} item schema`,description:`JSON Schema for ${t.resource} resource items.`,mimeType:Cc,read:async()=>Mf(t.uri,t)})),...Oa.map(t=>({uri:`beepflow://resources/${t.name}`,name:`Beepflow ${t.name}`,description:t.description,mimeType:Cc,read:async()=>{let n=await e.readResourceItems(t.name);return Mf(`beepflow://resources/${t.name}`,n)}}))]}function Mf(e,t){return{contents:[{uri:e,mimeType:Cc,text:JSON.stringify(t,null,2)}]}}var Lf=_s(),{server:i5,closeServer:o5}=oh({serverName:"mcp",serverVersion:"0.1.0",instructions:l0,tools:$1(Lf),resources:J1(Lf),onInitialized:()=>{Lf.start().catch(()=>{})}});process.on("SIGINT",()=>Z1("SIGINT"));process.on("SIGTERM",()=>Z1("SIGTERM"));i5.start();function Z1(e){Lf.close(),o5(e)}
102
102
  /*! Bundled license information:
103
103
 
104
104
  html-minifier-terser/src/htmlparser.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beepflow/mcp",
3
- "version": "2026.7.0",
3
+ "version": "2026.7.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.6.0"