UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 18.8 kB
import{i as e}from"./transcript-record-coerce-CPLgmAk9.mjs";import{r as t}from"./transcript-string-readers-HOXt1pkc.mjs";import{n}from"./transcript-state-dir-DEo0wD2Q.mjs";import{a as r,c as i,d as a,g as o,h as s,i as c,m as l,n as u,s as d,v as f}from"./transcript-schemas-C_W5KYqZ.mjs";import{createHash as p}from"node:crypto";const m={sm:{sizeW:3,sizeH:3},md:{sizeW:6,sizeH:4},lg:{sizeW:8,sizeH:6},xl:{sizeW:12,sizeH:8},full:{sizeW:12,sizeH:8}};var BoardValidationError=class extends Error{constructor(e,t){super(t),this.name=`BoardValidationError`,this.code=e}};function clampInteger(e,t,n){return Math.min(n,Math.max(t,Math.trunc(e)))}function comparePosition(e,t){return e.position-t.position}function normalizeBoardLayout(e){return normalizeOwnedBoardLayout(structuredClone(e))}function normalizeOwnedBoardLayout(e){let t=e.tabs.sort(comparePosition);t.forEach((e,t)=>{e.position=t});let n=new Map(t.map(e=>[e.tabId,e.position])),r=e.widgets.sort((e,t)=>(n.get(e.tabId)??2**53-1)-(n.get(t.tabId)??2**53-1)||e.position-t.position),i=/* @__PURE__ */ new Map;for(let e of r){let t=i.get(e.tabId)??0;e.position=t,i.set(e.tabId,t+1)}return{tabs:t,widgets:r}}function requireTab(e,t){let n=e.tabs.find(e=>e.tabId===t);if(!n)throw new BoardValidationError(`not_found`,`board tab not found: ${t}`);return n}function requireWidget(e,t){let n=e.widgets.find(e=>e.name===t);if(!n)throw new BoardValidationError(`not_found`,`board widget not found: ${t}`);return n}function moveTab(e,t,n){let r=e.tabs.filter(e=>e!==t).sort(comparePosition);r.splice(clampInteger(n,0,r.length),0,t),r.forEach((e,t)=>{e.position=t}),e.tabs=r}function moveWidget(e,t,n,r,i){if(requireTab(e,n),r!==void 0&&i!==void 0)throw new BoardValidationError(`invalid_operation`,`widget_move accepts either position or after, not both`);let a=e.widgets.filter(e=>e.tabId===n&&e!==t).sort(comparePosition),o=a.length;if(i!==void 0){if(i===t.name)throw new BoardValidationError(`invalid_operation`,`widget cannot be placed after itself`);let e=a.findIndex(e=>e.name===i);if(e<0)throw new BoardValidationError(`not_found`,`board widget anchor not found on tab ${n}: ${i}`);o=e+1}else r!==void 0&&(o=clampInteger(r,0,a.length));t.tabId=n,a.splice(o,0,t),a.forEach((e,t)=>{e.position=t}),e.widgets=[...e.widgets.filter(e=>e!==t&&e.tabId!==n),...a]}function applyBoardOp(e,t){switch(t.kind){case`tab_create`:if(e.tabs.some(e=>e.tabId===t.tabId))throw new BoardValidationError(`conflict`,`board tab already exists: ${t.tabId}`);e.tabs.push({tabId:t.tabId,title:t.title,position:e.tabs.length,chatDock:t.chatDock??`right`});return;case`tab_update`:{let n=requireTab(e,t.tabId);if(t.title===void 0&&t.chatDock===void 0&&t.position===void 0)throw new BoardValidationError(`invalid_operation`,`tab_update has no changes`);t.title!==void 0&&(n.title=t.title),t.chatDock!==void 0&&(n.chatDock=t.chatDock),t.position!==void 0&&moveTab(e,n,t.position);return}case`tab_delete`:{let n=requireTab(e,t.tabId),r=e.tabs.filter(e=>e!==n).sort(comparePosition),i=e.widgets.filter(e=>e.tabId===n.tabId).sort(comparePosition);if(r.length===0&&i.length>0)throw new BoardValidationError(`invalid_operation`,`cannot delete the last board tab while it contains widgets`);if(e.tabs=r,i.length>0){let e=r[0];for(let t of i)t.tabId=e.tabId,t.position=2**53-1}return}case`tabs_reorder`:{if(t.tabIds.length!==e.tabs.length||new Set(t.tabIds).size!==t.tabIds.length||t.tabIds.some(t=>!e.tabs.some(e=>e.tabId===t)))throw new BoardValidationError(`invalid_operation`,`tabs_reorder must contain every tab exactly once`);let n=new Map(e.tabs.map(e=>[e.tabId,e]));e.tabs=t.tabIds.map((e,t)=>{let r=n.get(e);return r.position=t,r});return}case`widget_move`:{let n=requireWidget(e,t.name);moveWidget(e,n,t.tabId??n.tabId,t.position,t.after);return}case`widget_resize`:{let n=requireWidget(e,t.name);n.sizeW=clampInteger(t.sizeW,1,12),n.sizeH=clampInteger(t.sizeH,1,20),n.heightMode=t.heightMode??`fixed`;return}case`widget_remove`:requireWidget(e,t.name),e.widgets=e.widgets.filter(e=>e.name!==t.name)}}function applyBoardOps(e,t){let n=structuredClone(e);for(let e of t)applyBoardOp(n,e),normalizeOwnedBoardLayout(n);return t.length>0?{tabs:n.tabs,widgets:n.widgets}:normalizeOwnedBoardLayout(n)}function insertBoardWidget(e,t,n){let r=structuredClone(e),i=r.widgets.findIndex(e=>e.name===t.name),a=r.widgets[i],o={...structuredClone(t),tabId:n.tabId};return a?(o.position=a.position,r.widgets[i]=o):r.widgets.push(o),(!a||n.move)&&moveWidget(r,o,n.tabId,void 0,n.after),normalizeOwnedBoardLayout(r)}Object.freeze([`https://cdnjs.cloudflare.com`,`https://cdn.jsdelivr.net`,`https://esm.sh`,`https://unpkg.com`,`https://fonts.googleapis.com`,`https://fonts.gstatic.com`,`https://fonts.bunny.net`]),Object.freeze([`https:`,`blob:`]);function createKeyboardShortcutMatcher(){let e={value:``,[Symbol.toPrimitive](){return this.value}},t=String.prototype.toLowerCase.bind(e),n=String.prototype.toUpperCase.bind(e),r=String.prototype.codePointAt.bind(e),i={lower(n){return e.value=n,t()},upper(t){return e.value=t,n()},codePointAt(t,n){return e.value=t,r(n)}},a={apple:/Mac|iPhone|iPad|iPod/u,asciiKey:/^[a-z0-9]$/,letterCode:/^Key([A-Z])$/,digitCode:/^Digit([0-9])$/,printableAscii:/^[\x20-\x7e]$/u},o=a.apple.exec.bind(a.apple),s=a.asciiKey.exec.bind(a.asciiKey),c=a.letterCode.exec.bind(a.letterCode),l=a.digitCode.exec.bind(a.digitCode),u=a.printableAscii.exec.bind(a.printableAscii),d=Function.prototype.call.bind(Array.prototype.includes);return{isApplePlatform(e=globalThis.navigator?.platform??``){return o(e)!==null},resolveAsciiShortcutKey(e){if(e.isComposing||e.keyCode===229)return null;let t=i.lower(e.key);if(s(t)!==null)return t;let n=i.codePointAt(e.key,0);if(e.altKey||e.key===`Dead`||e.key.length!==(n!==void 0&&n>65535?2:1))return null;let r=c(e.code)?.[1];return r?i.lower(r):e.shiftKey?null:l(e.code)?.[1]??null},matchesKeyboardShortcut(e,t,n,r){if(t.isComposing||t.key===`Dead`||t.keyCode===229)return!1;let a=d(e.modifiers,`mod`),o=d(e.modifiers,`ctrl`),s=a?t.metaKey!==t.ctrlKey&&(!e.platformSpecific||t.metaKey===n):!t.metaKey&&t.ctrlKey===o,c=e.key===`/`||e.key===`Backquote`;return!s||t.altKey!==d(e.modifiers,`alt`)||!c&&t.shiftKey!==d(e.modifiers,`shift`)?!1:e.key===`/`?t.key===`/`||t.key===`?`||t.code===`Slash`&&u(t.key)===null:e.key===`Backquote`||e.key===`Comma`?t.code===e.key:e.key===`Enter`||e.key===`Escape`||e.key===`ArrowUp`||e.key===`ArrowDown`||e.key===`ArrowLeft`||e.key===`ArrowRight`?t.key===e.key:r!==null||!t.metaKey||!t.altKey?r===e.key:t.code===`Key${i.upper(e.key)}`}}}const{isApplePlatform:h,resolveAsciiShortcutKey:g,matchesKeyboardShortcut:_}=createKeyboardShortcutMatcher();new n(64);function normalizeDomains(e,n){if(!Array.isArray(e))return;let r=n?.allowWebSocket?/* @__PURE__ */ new Set([`http:`,`https:`,`ws:`,`wss:`]):/* @__PURE__ */ new Set([`http:`,`https:`]),i=e.flatMap(e=>{if(typeof e!=`string`||e.length===0||e.length>2048||e!==e.trim()||t(e))return[];if(n?.allowMediaSchemes&&(e===`https:`||e===`blob:`))return[e];let i=URL.parse(e);return!i||!r.has(i.protocol)||i.username!==``||i.password!==``||i.pathname!==`/`||i.search!==``||i.hash!==``?[]:/^\[[0-9A-Fa-f:.]+\]$/u.test(i.hostname)||/^(?:\*\.)?[A-Za-z0-9.-]+$/u.test(i.hostname)?[i.origin]:[]});return i.length>0?i:void 0}function normalizeSandboxHostCsp(t){let n=e(t);if(!n)return;let r={connectDomains:normalizeDomains(n.connectDomains,{allowWebSocket:!0}),resourceDomains:normalizeDomains(n.resourceDomains),mediaDomains:normalizeDomains(n.mediaDomains,{allowMediaSchemes:!0}),frameDomains:normalizeDomains(n.frameDomains),baseUriDomains:normalizeDomains(n.baseUriDomains),blockDescendantFrames:n.blockDescendantFrames===!0||void 0};if(!Object.values(r).some(Boolean))return;let i=Buffer.byteLength(JSON.stringify(r),`utf8`),a=Buffer.byteLength(buildSandboxHostContentSecurityPolicy(r),`utf8`);if(i>5120||a>6144)throw Error(`MCP App CSP metadata exceeds safe HTTP limits`);return r}function buildSandboxHostContentSecurityPolicy(e,t){let n=e?.resourceDomains??[],r=e?.mediaDomains??n,i=e?.connectDomains??[],a=e?.frameDomains??[],o=e?.baseUriDomains??[],sources=e=>e.length>0?e.join(` `):`'none'`,s=[`default-src 'none'`,`script-src 'self' 'unsafe-inline' ${n.join(` `)}`.trim(),`style-src 'self' 'unsafe-inline' ${n.join(` `)}`.trim(),`img-src 'self' data: ${n.join(` `)}`.trim(),`media-src 'self' data: ${r.join(` `)}`.trim(),`connect-src ${sources(i)}`,`webrtc 'block'`,`frame-src ${sources(a)}`,`base-uri ${o.length>0?o.join(` `):`'self'`}`,`object-src 'none'`,`form-action 'none'`,`frame-ancestors ${t?t.length?t.join(` `):`'none'`:`http: https:`}`];return e&&s.splice(5,0,`font-src 'self' ${n.join(` `)}`.trim()),s.join(`; `)}const v=s().regex(/^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/u).refine(e=>![`.`,`..`].includes(e.split(`/`)[1])).transform(e=>e.toLowerCase()),y=`\\d{4}-\\d{2}-\\d{2}`,b=s().regex(RegExp(`^(?:[<>]=?)?${y}$|^${y}\\.\\.${y}$`,`u`)).refine(e=>(e.match(/\d{4}-\d{2}-\d{2}/gu)??[]).every(e=>{let t=/* @__PURE__ */ new Date(`${e}T00:00:00Z`);return Number.isFinite(t.getTime())&&t.toISOString().startsWith(e)}));l({repository:v,workflow:o([a().int().positive().max(2**53-1),s().max(255).regex(/^(?:[1-9]\d*|[A-Za-z0-9_.-]+\.ya?ml)$/u).refine(e=>!/^\d+$/u.test(e)||Number.isSafeInteger(Number(e)))]).optional(),perPage:a().int().min(1).max(30).default(20),branch:s().min(1).max(255).refine(e=>!t(e)).optional(),status:u([`completed`,`action_required`,`cancelled`,`failure`,`neutral`,`skipped`,`stale`,`success`,`timed_out`,`in_progress`,`queued`,`requested`,`waiting`,`pending`]).optional(),created:b.optional(),excludePullRequests:r().default(!0)});function normalizeGitHubActionsGrant(e){if(!e.startsWith(`github.actions.runs:`))return e;let t=v.safeParse(e.slice(20));if(!t.success)throw new BoardValidationError(`invalid_operation`,`GitHub Actions grant requires owner/repo`);return`github.actions.runs:${t.data}`}function invalidDeclaration(e){throw new BoardValidationError(`invalid_operation`,e)}function normalizeBoardNetOrigin(e){if(e!==e.trim()||e.length===0||e.length>2048)return invalidDeclaration(`invalid board widget network origin: ${e}`);let t=URL.parse(e);if(!t)return invalidDeclaration(`invalid board widget network origin: ${e}`);let n=/^\[[0-9A-Fa-f:.]+\]$/u.test(t.hostname)||/^[A-Za-z0-9.-]+$/u.test(t.hostname);return t.protocol!==`https:`||t.username!==``||t.password!==``||t.pathname!==`/`||t.search!==``||t.hash!==``||!n||t.hostname.includes(`*`)||t.hostname.endsWith(`.`)?invalidDeclaration(`board widget network origin must be an exact HTTPS origin: ${e}`):t.origin}function normalizeTool(e){let n=e.trim();return n.length===0||n.length>269||n!==e||t(n)?invalidDeclaration(`invalid board widget tool capability: ${e}`):normalizeGitHubActionsGrant(n)}function normalizeBoardWidgetDeclared(e){if(!e)return;if((e.netOrigins?.length??0)>32)return invalidDeclaration(`board widget cannot declare more than 32 network origins`);if((e.tools?.length??0)>64)return invalidDeclaration(`board widget cannot declare more than 64 tools`);let t=[...new Set((e.netOrigins??[]).map(normalizeBoardNetOrigin))].toSorted(),n=[...new Set((e.tools??[]).map(normalizeTool))].toSorted(),r;try{r=normalizeSandboxHostCsp({connectDomains:t})?.connectDomains}catch{return invalidDeclaration(`board widget network origins exceed safe CSP limits`)}if(t.length>0&&(r?.length!==t.length||t.some((e,t)=>r[t]!==e)))return invalidDeclaration(`board widget network origin is not supported by the sandbox host`);if(t.length!==0||n.length!==0)return{...t.length>0?{netOrigins:t}:{},...n.length>0?{tools:n}:{}}}function boardDeclarationIsSubset(e,t){let n=new Set(t?.netOrigins??[]),r=new Set(t?.tools??[]);return(e?.netOrigins??[]).every(e=>n.has(e))&&(e?.tools??[]).every(e=>r.has(e))}const x=s().min(1).max(120).optional(),S=s().min(1).max(160),C=s().max(240).optional(),w=s().max(500),T=l({type:i(`table`),title:x,columns:c(S).min(1).max(8),rows:c(c(w).max(8)).max(40)}).refine(e=>e.rows.every(t=>t.length===e.columns.length),{message:`Every table row must match the columns`}),E=l({blocks:c(d(`type`,[l({type:i(`text`),title:x,text:s().min(1).max(4e3)}),l({type:i(`metrics`),items:c(l({label:S,value:s().min(1).max(80),detail:C})).min(1).max(8)}),T,l({type:i(`chart`),title:x,style:u([`bar`,`line`]).optional(),points:c(l({label:S,value:a().min(-(2**53-1)).max(2**53-1)})).min(1).max(40)}),l({type:i(`links`),title:x,items:c(l({label:S,url:f({protocol:/^https?$/,normalize:!0}).max(2048),detail:C})).min(1).max(20)})])).min(1).max(24)});function parseBoardReport(e){if(new TextEncoder().encode(JSON.stringify(e)).byteLength>8192)throw new BoardValidationError(`invalid_operation`,`Report exceeds 8KB JSON budget`);let t=E.safeParse(e);if(!t.success){let e=t.error.issues[0];throw new BoardValidationError(`invalid_operation`,`Invalid report at ${e?.path.join(`.`)||`root`}: ${e?.message}`)}return t.data}const D=l({url:s().max(2048).pipe(f({protocol:/^https$/,normalize:!0}).max(2048))});function parseBoardWebsite(e){let t=D.safeParse(e);if(!t.success)throw new BoardValidationError(`invalid_operation`,`Website props must contain only a valid HTTPS url of at most 2048 characters`);let n=new URL(t.data.url);if(n.username||n.password)throw new BoardValidationError(`invalid_operation`,`Website URLs must not contain embedded credentials`);return t.data}function cloneBoardSnapshot(e){return structuredClone(e)}function createBoardDeclaredSummary(e){let t=[...(e?.netOrigins??[]).map(e=>`Network access: ${e}`),...(e?.tools??[]).map(e=>e.startsWith(`github.actions.runs:`)?`GitHub Actions metadata: ${e.slice(20)} (including private repository data accessible to the agent; shared with this widget/session audience)`:`Tool access: ${e}`)];return t.length>0?t:void 0}function resolveBoardWidgetPutParams(e,t,n){let r=t.generatedIdentity;if(!r)return t;if(r.fallbackName===t.name)throw new BoardValidationError(`invalid_operation`,`generated widget fallback name must differ from its preferred name`);let i=e.widgets.find(e=>{let t=n.get(e.name);return t?.kind===`generated`&&t.source===r.source&&t.key===r.key});if(i)return{...t,name:i.name};if(!e.widgets.find(e=>e.name===t.name))return t;if(e.widgets.find(e=>e.name===r.fallbackName))throw new BoardValidationError(`conflict`,`generated widget fallback name is already in use: ${r.fallbackName}`);return{...t,name:r.fallbackName}}function normalizeBoardWidgetPutParams(e,t=e.sessionKey){let n=normalizeBoardWidgetDeclared(e.declared),r={...e,sessionKey:t};return n?r.declared=n:delete r.declared,r}function createBoardWidgetPutResult(e,t){return{...cloneBoardSnapshot(e),resolvedWidgetName:t}}function validatePluginContent(e){if(e.content.kind===`plugin`){if(e.declared!==void 0)throw new BoardValidationError(`invalid_operation`,`trusted plugin widgets do not accept sandbox capability declarations`);if(e.content.pluginKind===`session:report`)parseBoardReport(e.content.props);else{if(Buffer.byteLength(JSON.stringify(e.content.props??{}),`utf8`)>8192)throw new BoardValidationError(`invalid_operation`,`board plugin widget props exceed 8192 UTF-8 bytes`);e.content.pluginKind===`session:website`&&parseBoardWebsite(e.content.props)}}}function createBoardWidgetPutSnapshot(e,t,n){if(validatePluginContent(t),t.content.kind===`html`&&Buffer.byteLength(t.content.html,`utf8`)>10485760)throw new BoardValidationError(`invalid_operation`,`board widget HTML exceeds 10485760 UTF-8 bytes`);let r=normalizeBoardLayout(e);r.tabs.length===0&&r.tabs.push({tabId:`main`,title:`Main`,position:0,chatDock:`right`});let i=r.widgets.find(e=>e.name===t.name);if(i&&(i.contentOwner!==t.content.kind||t.content.kind===`plugin`&&i.pluginKind!==t.content.pluginKind)){let e=t.content.kind===`plugin`?t.content.pluginKind:t.content.kind;throw new BoardValidationError(`invalid_operation`,`board widget ${t.name} contains ${i.pluginKind??i.contentOwner} content; update it with the same content kind or remove it before replacing it with ${e} content`)}if(!i&&r.widgets.length>=48)throw new BoardValidationError(`invalid_operation`,`board cannot contain more than 48 widgets`);let a=t.placement?.tabId??i?.tabId??r.tabs[0].tabId;if(!r.tabs.some(e=>e.tabId===a))throw new BoardValidationError(`not_found`,`board tab not found: ${a}`);let o=m[t.placement?.size??`md`],s=(i?.revision??0)+1,c=t.content.kind===`plugin`?void 0:normalizeBoardWidgetDeclared(t.declared),l=createBoardDeclaredSummary(c),u=t.content.kind===`html`?p(`sha256`).update(t.content.html).digest(`hex`):void 0,d=c!==void 0&&n.grantScopeMatches&&(t.content.kind!==`mcp-app`||t.content.interactive)&&i?.grantState===`granted`&&(t.content.kind!==`html`||u===n.grantedSha256)&&boardDeclarationIsSubset(c,i.declared);return r=insertBoardWidget(r,{name:t.name,tabId:a,...t.title===void 0?i?.title===void 0?{}:{title:i.title}:{title:t.title},contentKind:t.content.kind,contentOwner:t.content.kind,...t.presentation===void 0?i?.presentation===void 0?{}:{presentation:i.presentation}:{presentation:t.presentation},...t.heightMode===void 0?i?.heightMode===void 0?{}:{heightMode:i.heightMode}:{heightMode:t.heightMode},...t.content.kind===`plugin`?{pluginKind:t.content.pluginKind,...t.content.props===void 0?{}:{props:t.content.props}}:{},sizeW:t.placement?.size?o.sizeW:i?.sizeW??o.sizeW,sizeH:t.placement?.size?o.sizeH:i?.sizeH??o.sizeH,position:i?.position??r.widgets.length,grantState:t.content.kind===`plugin`?`none`:d?`granted`:t.content.kind===`mcp-app`&&!t.content.interactive?`none`:l||t.content.kind===`mcp-app`?`pending`:`none`,revision:s,instanceId:t.content.kind===`plugin`?i?.instanceId??n.instanceId:n.instanceId,...l?{declaredSummary:l}:{},...c?{declared:c}:{}},{tabId:a,...t.placement?.after?{after:t.placement.after}:{},move:t.placement?.tabId!==void 0||t.placement?.after!==void 0}),{sessionKey:t.sessionKey,revision:e.revision+1,...r}}function createBoardGrantSnapshot(e,t,n,r,i){let a=e.widgets.find(e=>e.name===t);if(!a)throw new BoardValidationError(`not_found`,`board widget not found: ${t}`);if(a.revision!==r)throw new BoardValidationError(`conflict`,`board widget revision changed: ${t} is revision ${a.revision}, not ${r}`);if(a.instanceId!==void 0&&a.instanceId!==i)throw new BoardValidationError(`conflict`,`board widget instance changed: ${t}`);if(a.grantState!==`pending`)throw new BoardValidationError(`invalid_operation`,`board widget grant is not pending: ${t}`);let o=cloneBoardSnapshot(e);return o.widgets.find(e=>e.name===t).grantState=n,o.revision+=1,o}export{normalizeBoardWidgetPutParams as a,BoardValidationError as c,createBoardWidgetPutSnapshot as i,applyBoardOps as l,createBoardGrantSnapshot as n,resolveBoardWidgetPutParams as o,createBoardWidgetPutResult as r,normalizeBoardWidgetDeclared as s,createBoardDeclaredSummary as t,normalizeOwnedBoardLayout as u};