openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 11.1 kB
JavaScript
import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import"./io-Di_yuX3t.mjs";import{t as captureSessionActorStorageOwner}from"./session-actor-storage-binding-Bq_IHhu0.mjs";import{t as readRetainedSessionEntryFacts}from"./session-entry-read-facts-CX_VYSiw.mjs";import{t as logDebug}from"./logger-BHIcoxTH.mjs";import{n as captureSessionMutationRouting}from"./session-sharing-preparation-Bx3oY7gx.mjs";import{m as retainGatewayDeviceRevocation}from"./device-revocation-CZLiYG03.mjs";import{r as loadGatewaySessionEntryReadOnlyAsync}from"./session-utils-store-CbjJRFJe.mjs";import{i as getMcpAppViewLease}from"./mcp-ui-resource-C1InHjbh.mjs";import{n as WORKSPACE_PREVIEW_MAX_BYTES}from"./workspace-file-limits-gOB_58gm.mjs";import{h as updateWorkspaceFile,l as resolveWorkspacePath,s as readWorkspaceFile}from"./workspace-fs-jKJewXPd.mjs";import"./session-utils-Cd7daNqX.mjs";import{l as resolveMcpAppRequesterId,o as requireMcpAppInteraction}from"./mcp-app-operations-DJwJ400G.mjs";import{a as assertSessionFileReadPolicy,n as prepareLocalSessionWorkspaceRoot,s as sessionFileWorkspaceMatches}from"./session-files-root-qnYvd71D.mjs";import{t as retainSessionScopedRead}from"./session-scoped-read-B-4pX19a.mjs";import{stat,watch}from"node:fs";import path from"node:path";import{randomUUID}from"node:crypto";
//!src/gateway/mcp-app-host-files.ts
const fileSources=/* @__PURE__ */ new WeakMap;const writeAdmissions=/* @__PURE__ */ new WeakSet;const subscriptions=/* @__PURE__ */ new WeakMap;async function captureHostFileSession(e,t=readRuntimeConfig){const n={assertCurrent(){},authorize(){}};const r=captureSessionActorStorageOwner(e,n);const i=t();const a=captureSessionMutationRouting(i,void 0,[e]);const o=r?void 0:await loadGatewaySessionEntryReadOnlyAsync(e.sessionKey,{agentId:e.agentId,projection:[`skillsSnapshot`]},i);const readEntry=()=>r?r.owner?.readSession(e.sessionKey,n)?.entry:o&&readRetainedSessionEntryFacts({agentId:o.readSource?.agentId??o.agentId,path:o.readSource?.path??o.storePath},{sessionKeys:[o.canonicalKey],projection:`exact`,snapshotFields:[`skillsSnapshot`]})?.entries.find(e=>e.sessionKey===o.canonicalKey)?.entry;const s=readEntry();const c=await prepareLocalSessionWorkspaceRoot({...e,source:{entry:s,cfg:i}});return{assertCurrent(){a(t());const e=readEntry();if(!sessionFileWorkspaceMatches(s,e))throw new Error(`App file session workspace changed`)},readEntry,readRoot:n=>{const r=readEntry();if(!r)return;c?.assertCurrent(t(),r);if(n)assertSessionFileReadPolicy(n,{agentId:e.agentId,canonicalKey:e.sessionKey,entry:r,unscopedHostRoot:c?.unscopedHostRoot});return c?.root}}}async function prepareMcpAppHostFile(e,t){const n=await captureHostFileSession(t,()=>e.context.getRuntimeConfig());const r=await retainSessionScopedRead(e,t.sessionKey,t.agentId,{requireMaterialized:true});try{const i=n.readRoot(e);const a=n.readEntry();if(!i||!a?.sessionId)throw new Error(`Local workspace file access is unavailable`);const o=resolveMcpAppRequesterId(e.client);const s=a.sessionId;const assertCurrent=()=>{n.assertCurrent();r?.assertCurrent();if(e.hasCurrentClientAuthority?.()===false||resolveMcpAppRequesterId(e.client)!==o||n.readEntry()?.sessionId!==s||n.readRoot(e)!==i)throw new Error(`App file workspace authority changed`)};const c=resolveWorkspacePath(i,t.path);if(!c)throw new Error(`File is outside the session workspace`);const l=path.relative(i,c);const u=await readWorkspaceFile(i,l,{assertCurrent});assertCurrent();if(!u||u===`too-large`)throw new Error(`File is missing, unsafe, or too large`);const d={resourceUri:`openclaw-file://`+randomUUID(),name:path.basename(u.canonicalPath),rootDir:i,path:u.canonicalPath,sessionId:s,requesterId:o};fileSources.set(d,n);return d}finally{r?.release()}}async function withHostFile(e,t,n,r,i=false){const a=t.hostFile;const o=t.runtime.sessionKey;if(!a||a.resourceUri!==n||!o)throw new Error(`Resource is not the file opened by this App`);const s=fileSources.get(a)??await captureHostFileSession({sessionKey:o,agentId:t.agentId},()=>e.context.getRuntimeConfig());const c=await retainSessionScopedRead(e,o,t.agentId,{requireMaterialized:true});const assertCurrent=()=>{t.runtime.assertOwnerCurrent?.();s.assertCurrent();c?.assertCurrent();e.sessionMutationAuthorization?.assertCurrent();if(e.signal?.aborted||e.client?.connectionSignal?.aborted||e.hasCurrentClientAuthority?.()===false||getMcpAppViewLease(t.viewId,t.runtime)!==t||t.readOnly||t.allowedAppToolNames===void 0||resolveMcpAppRequesterId(e.client)!==a.requesterId||s.readEntry()?.sessionId!==a.sessionId||s.readRoot(e)!==a.rootDir)throw new Error(`MCP App file authority expired`);if(i&&t.authorizeAppInteraction){const e=t.authorizeAppInteraction();if(e!==true){if(e instanceof Promise)e.catch(()=>void 0);throw new Error(`MCP App file requires current synchronous interaction authority`)}}};try{await requireMcpAppInteraction(t);assertCurrent();const e=await r(a,assertCurrent);if(!i){await requireMcpAppInteraction(t);assertCurrent()}return e}finally{c?.release()}}async function readMcpAppHostFile(e,t,n){return withHostFile(e,t,n.uri,async(e,r)=>{const i=asOptionalRecord(n._meta?.[`openai/resource`])?.representation;if(i!==void 0&&i!==`text`&&i!==`blob`)throw new Error(`Invalid resource representation`);const a=await readWorkspaceFile(e.rootDir,e.path,{assertCurrent:r});r();if(!a||a===`too-large`)throw new Error(`File is missing, unsafe, or too large`);const o=a.readOnly!==true;const s=i===`text`?{text:new TextDecoder(`utf-8`,{fatal:true,ignoreBOM:true}).decode(a.buffer)}:{blob:a.buffer.toString(`base64`)};if(o)writeAdmissions.add(t);return{contents:[{uri:e.resourceUri,...s,_meta:{"openai/resource":{writable:o,etag:sha256Hex(a.buffer)}}}]}})}async function writeMcpAppHostFile(e,t,n){if(typeof n.uri!==`string`)throw new Error(`uri is required`);if(!t.hostFile||n.uri!==t.hostFile.resourceUri)throw new Error(`Resource is not the file opened by this App`);await requireMcpAppInteraction(t);if(typeof n.text===`string`===(typeof n.blob===`string`))throw new Error(`Provide exactly one of text or blob`);if(n.ifMatch!==void 0&&(typeof n.ifMatch!==`string`||!n.ifMatch))throw new Error(`ifMatch must be non-empty`);if(!writeAdmissions.has(t))throw new Error(`Read this resource with writable:true before writing`);let r;if(typeof n.text===`string`){if(Buffer.byteLength(n.text,`utf8`)>262144)return{outcome:`too-large`,maxBytes:WORKSPACE_PREVIEW_MAX_BYTES};r=Buffer.from(n.text,`utf8`)}else if(typeof n.blob===`string`){const e=n.blob;if(e.length>Math.ceil(262144/3)*4)return{outcome:`too-large`,maxBytes:WORKSPACE_PREVIEW_MAX_BYTES};r=Buffer.from(e,`base64`);if(r.toString(`base64`)!==e)throw new Error(`Invalid base64 resource content`)}else throw new Error(`Provide exactly one of text or blob`);if(r.length>262144)return{outcome:`too-large`,maxBytes:WORKSPACE_PREVIEW_MAX_BYTES};return withHostFile(e,t,n.uri,async(e,t)=>{const i=await updateWorkspaceFile(e.rootDir,e.path,r,typeof n.ifMatch===`string`?n.ifMatch:void 0,t);if(i.status===`unsafe`)throw new Error(`File could not be written safely`);return i.status===`conflict`?{outcome:`conflict`,etag:i.currentHash}:{outcome:`saved`,etag:i.hash}},true)}async function subscribeMcpAppHostFile(e,t,n,r){if(!r){const r=e.client;if(!r?.connId||t.hostFile?.resourceUri!==n||t.requesterId!==resolveMcpAppRequesterId(r))throw new Error(`Resource subscription is not owned by this requester`);subscriptions.get(t)?.get(r.connId)?.();return{}}return withHostFile(e,t,n,async(r,i)=>{const a=e.client;if(!a?.connId)throw new Error(`Resource subscriptions require a live client connection`);const o=a.connId;const s=t.runtime.sessionKey;if(!s)throw new Error(`App session is unavailable`);const c=subscriptions.get(t)??/* @__PURE__ */ new Map;c.get(o)?.();if(c.size>=32)throw new Error(`Resource subscription limit reached`);const l=await readWorkspaceFile(r.rootDir,r.path,{assertCurrent:i});i();if(!l||l===`too-large`)throw new Error(`Resource cannot be subscribed`);const u=fileSources.get(r)??await captureHostFileSession({sessionKey:s,agentId:t.agentId},()=>e.context.getRuntimeConfig());let d=false;let f=false;const isCurrent=()=>{u.assertCurrent();return!d&&!a.connectionSignal?.aborted&&e.hasCurrentClientAuthority?.()!==false&&getMcpAppViewLease(t.viewId,t.runtime)===t&&!t.readOnly&&t.allowedAppToolNames!==void 0&&resolveMcpAppRequesterId(a)===r.requesterId&&e.context.getRuntimeConfig().mcp?.apps?.enabled===true&&u.readEntry()?.sessionId===r.sessionId&&u.readRoot(e)===r.rootDir};const notify=async()=>{if(f)return;f=true;try{if(!isCurrent()){close(`view, session, requester, or connection authority changed`);return}await requireMcpAppInteraction(t);if(!isCurrent()){close(`authority changed while checking App interaction`);return}e.context.broadcastToConnIds(`mcp.app.resourceUpdated`,{viewId:t.viewId,uri:n},/* @__PURE__ */ new Set([o]))}catch(e){close(e)}finally{f=false}};const p=path.join(r.rootDir,r.path);let m=false;let h;const poll=()=>{stat(p,(e,t)=>{if(d||!m)return;if(!e&&t.isFile())rearm(true);else if(e&&!hasErrnoCode(e,`ENOENT`))close(e);else{h=setTimeout(()=>{h=void 0;poll()},250);h.unref()}})};const arm=()=>watch(p,{persistent:false},e=>{if(e===`rename`){_.close();rearm()}notify()}).on(`error`,close);const rearm=(e=false)=>{if(d||m&&!e)return;m=false;clearTimeout(h);h=void 0;try{_=arm();if(e)notify()}catch(e){if(hasErrnoCode(e,`ENOENT`)){m=true;poll()}else close(e)}};const close=(e=`subscription ended`)=>{if(d)return;d=true;logDebug(`mcp-app: file subscription closed view=${t.viewId}: ${formatErrorMessage(e)}`);g?.();_.close();clearTimeout(h);h=void 0;a.connectionSignal?.removeEventListener(`abort`,onDisconnect);if(c.get(o)===close)c.delete(o);t.disposeCallbacks?.delete(close)};const onDisconnect=()=>close(`connection closed`);const g=retainGatewayDeviceRevocation(e.hasCurrentClientAuthority);let _;try{_=arm()}catch(e){g?.();throw e}a.connectionSignal?.addEventListener(`abort`,onDisconnect,{once:true});c.set(o,close);subscriptions.set(t,c);t.disposeCallbacks??=/* @__PURE__ */ new Set;t.disposeCallbacks.add(close);if(!isCurrent())close(`authority changed while installing the subscription`);return{}})}async function canOpenMcpAppFiles(e){const t=e.runtime.sessionKey;if(!t)return false;const n=await captureHostFileSession({sessionKey:t,agentId:e.agentId});return Boolean(n.readRoot())}async function openMcpAppFile(e,t,n){if(!path.isAbsolute(n))throw new Error(`File opening requires an absolute execution-host path`);if(!t.runtime.sessionKey)throw new Error(`App session is unavailable`);await requireMcpAppInteraction(t);const r=await prepareMcpAppHostFile(e,{sessionKey:t.runtime.sessionKey,agentId:t.agentId,path:n});await requireMcpAppInteraction(t);return{path:r.path,name:r.name}}export{subscribeMcpAppHostFile as a,readMcpAppHostFile as i,openMcpAppFile as n,writeMcpAppHostFile as o,prepareMcpAppHostFile as r,canOpenMcpAppFiles as t};