openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
13 lines • 28.7 kB
JavaScript
import{s as asFiniteNumber}from"../../number-coercion-B3CfI447.mjs";import{l as isRecord}from"../../record-coerce-BTbqdJ3-.mjs";import{r as truncateUtf16Safe}from"../../utf16-slice-DA3Mllbx.mjs";import{o as racePromiseWithAbortSignal}from"../../src-De06gkOi.mjs";import{i as clampNumber}from"../../utils-Dlk0IYAa.mjs";import{t as pruneMapToMaxSize}from"../../map-size-DLQqorvK.mjs";import{o as getPluginRuntimeGatewayRequestScope}from"../../gateway-request-scope-7deHmsb_.mjs";import{w as resolveSessionAgentIdsStrict}from"../../agent-scope-config-CG9CFpGX.mjs";import{i as readResponseWithLimit}from"../../http-response-body-BJ35MG8h.mjs";import{g as ssrfPolicyFromHttpBaseUrlAllowedOrigin}from"../../ssrf-BzkUH7oD.mjs";import{i as fetchWithSsrFGuard,n as GuardedFetchRedirectError}from"../../fetch-guard-B_7-F5Lc.mjs";import{n as sendJsonNoStore}from"../../http-json-g_k96dZ_.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../ssrf-runtime-Dx9DKr_m.mjs";import"../../text-utility-runtime-CDtGqkrl.mjs";import{s as createFixedWindowRateLimiter}from"../../webhook-ingress-HlX1K-r7.mjs";import{a as createWebhookInFlightLimiter,i as beginWebhookRequestPipelineOrReject,s as readJsonWebhookBodyOrReject}from"../../webhook-request-guards-DdSp767W.mjs";import"../../time-runtime-SSNrsaM_.mjs";import"../../response-limit-runtime-uUJhFwkj.mjs";import{r as preparePluginStateGuard}from"../../plugin-state-runtime-ShRrbbGy.mjs";import"../../agent-scope-runtime-DKb8jQZx.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import"../../plugin-runtime-9UCtHEMr.mjs";import{n as buildControlUiCatalogSharePath,r as isControlUiCatalogShareId,t as listActiveSessionCatalogs}from"../../session-catalog-runtime-Blyn7TKK.mjs";import{a as BEAM_SESSION_SHARE_ROUTE,i as BEAM_RETENTION_MS,n as BEAM_MAX_BODY_BYTES,o as parseBeamUpload,r as BEAM_MAX_ITEM_CHARS,t as BEAM_HOST_ID}from"../../types-BLKNQ8kJ.mjs";import{createHash,randomUUID}from"node:crypto";
//!extensions/beam/src/http.ts
function currentRequestClient(e){const t=getPluginRuntimeGatewayRequestScope()?.client;const n=t?.internal?.operatorAccessAuthority;return{clientIp:t?.clientIp??e.socket.remoteAddress??`unknown`,scopes:t?.connect?.scopes??[],profileId:t?.authenticatedUserProfile?.profileId,...n?.requiredPolicyPlugin===`visitor-access`&&n.gatewayAccessGrant?.pluginId===`visitor-access`?{visitorGrant:n}:{}}}function canPublish(e){return e.includes(`operator.write`)||e.includes(`operator.admin`)}function createBeamRequestHandler(e){const t=createFixedWindowRateLimiter({windowMs:6e4,maxRequests:60,maxTrackedKeys:2048});const n=createWebhookInFlightLimiter({maxInFlightPerKey:2,maxTrackedKeys:2048});return async(r,i)=>{const a=getPluginRuntimeGatewayRequestScope();const o=e.resolveClient?.(r)??currentRequestClient(r);const s=canPublish(o.scopes)?{kind:`staff`,profileId:o.profileId}:o.scopes.includes(`operator.sessions.write`)&&o.profileId&&o.visitorGrant?{kind:`guest`,profileId:o.profileId}:void 0;if(!s){sendJsonNoStore(i,403,{ok:false,error:`Beam requires operator.write or an active verified Visitor publisher`});return true}const assertCurrent=()=>{if(a?.signal?.aborted||a?.hasCurrentClientAuthority?.()===false||i.writableEnded||i.destroyed){if(!i.writableEnded&&!i.destroyed)sendJsonNoStore(i,401,{ok:false,error:`Beam publisher authority expired`});throw new Error(`Beam publisher authority expired`)}o.visitorGrant?.assertCurrent()};assertCurrent();const c=beginWebhookRequestPipelineOrReject({req:r,res:i,allowMethods:[`POST`],requireJsonContentType:true,rateLimiter:t,rateLimitKey:o.clientIp,inFlightLimiter:n,inFlightKey:o.clientIp});if(!c.ok)return true;try{const t=await readJsonWebhookBodyOrReject({req:r,res:i,maxBytes:BEAM_MAX_BODY_BYTES,timeoutMs:1e4,emptyObjectOnEmpty:false,invalidJsonMessage:`invalid Beam request body`});if(!t.ok)return true;const n=parseBeamUpload(t.value);if(!n.ok){sendJsonNoStore(i,400,{ok:false,error:n.error});return true}await a?.revalidate?.();assertCurrent();const o=e.now?.()??Date.now();const c=await e.store.upload(n.value,{receivedAt:o,publisher:s,assertCurrent});assertCurrent();if(c===`forbidden`){sendJsonNoStore(i,403,{ok:false,error:`Beam is not owned by this publisher. Publish a new source session (new Beam ID) or ask a Gateway operator whether the retained snapshot can be removed.`});return true}if(c===`publisher-full`||c===`catalog-full`){sendJsonNoStore(i,429,{ok:false,error:c===`publisher-full`?`Beam publisher limit reached (20 live snapshots); refresh an existing Beam or wait for expiry`:`Beam catalog is full; refresh an existing Beam or ask a Gateway operator to free space`});return true}if(c===`handoff-conflict`){sendJsonNoStore(i,409,{ok:false,error:`This source snapshot cannot establish a handoff. Reconcile the current Beam publication before releasing it; no destination was created.`});return true}const l=typeof c===`object`&&c.kind===`handoff`?c:void 0;sendJsonNoStore(i,l?.accepted===false?409:200,{...s.kind===`guest`?{canView:true}:{},ok:l?.accepted!==false,...typeof c===`object`&&c.kind===`published`&&c.id?{publicationId:c.id}:{},...l?{handoff:{id:l.id,owner:`gateway`,access:s.kind===`guest`?`owned`:`shared`},...l.accepted?{}:{error:`This conversation moved to Team. The local snapshot was not accepted; continue through the Beam client's read/continue commands or the returned link.`}}:{},beamId:n.value.beamId,url:buildControlUiCatalogSharePath({shareRoute:BEAM_SESSION_SHARE_ROUTE,threadId:n.value.beamId,displayName:n.value.title,basePath:e.resolveControlUiBasePath()})});return true}finally{c.release()}}}
//!extensions/beam/src/mirror.ts
const MIRROR_CONFIG_PATH=`plugins.entries.beam.config.mirror`;const MIRROR_TOKEN_PATH=`${MIRROR_CONFIG_PATH}.token`;const DEFAULT_POLL_SECONDS=30;const DEFAULT_ACTIVE_WINDOW_MINUTES=180;const MIRROR_LIST_LIMIT=100;const MIRROR_READ_LIMIT=50;const MIRROR_MAX_SESSIONS=32;const MIRROR_RETRY_CAP=2*500;const MIRROR_BODY_BUDGET_BYTES=BEAM_MAX_BODY_BYTES-2048;const MIRROR_WARN_INTERVAL_MS=3e5;const MIRROR_UPLOAD_TIMEOUT_MS=15e3;function isLoopbackHostname(e){const t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`}const MIRROR_KEYS=/* @__PURE__ */ new Set([`endpoint`,`token`,`catalogs`,`pollSeconds`,`activeWindowMinutes`]);function parseBeamMirrorConfig(e){const t=e.plugins?.entries?.beam?.config?.mirror;if(t===void 0)return;if(!isRecord(t)||!Object.keys(t).every(e=>MIRROR_KEYS.has(e)))return`${MIRROR_CONFIG_PATH} must be a closed object with endpoint/token/catalogs/pollSeconds/activeWindowMinutes`;const n=typeof t.endpoint===`string`?t.endpoint.trim():``;const r=URL.parse(n);if(!r)return`${MIRROR_CONFIG_PATH}.endpoint must be an absolute URL`;if(r.protocol===`http:`){if(!isLoopbackHostname(r.hostname))return`${MIRROR_CONFIG_PATH}.endpoint must use https for non-loopback hosts`}else if(r.protocol!==`https:`)return`${MIRROR_CONFIG_PATH}.endpoint must use http(s)`;if(!Array.isArray(t.catalogs)||t.catalogs.length===0||!t.catalogs.every(e=>typeof e===`string`&&e.trim().length>0))return`${MIRROR_CONFIG_PATH}.catalogs must explicitly list the catalog ids to mirror`;return{endpoint:n,token:t.token===void 0?void 0:typeof t.token===`string`&&t.token.trim()?t.token.trim():null,catalogs:t.catalogs.map(e=>e.trim().toLowerCase()),pollSeconds:clampNumber(asFiniteNumber(t.pollSeconds)??DEFAULT_POLL_SECONDS,10,3600),activeWindowMinutes:clampNumber(asFiniteNumber(t.activeWindowMinutes)??DEFAULT_ACTIVE_WINDOW_MINUTES,1,10080)}}function beamMirrorId(e,t,n){return createHash(`sha256`).update(`${e}\0${t}\0${n}`).digest(`hex`).slice(0,32)}function buildBeamMirrorItems(e){const t=[];const n=/* @__PURE__ */ new Map;let r=e.some(e=>e.truncated);const flush=()=>{if(n.size>0){const e=[...n].map(([e,t])=>`${t} ${e}`).join(`, `);t.push({type:`other`,text:`${e}; raw content dropped`});n.clear()}};const i={toolCall:`tool calls`,toolResult:`tool results`,reasoning:`reasoning items`};for(const a of e.toReversed()){const e=a.text?.trim();if((a.type===`userMessage`||a.type===`agentMessage`)&&e){flush();const n=truncateUtf16Safe(e,BEAM_MAX_ITEM_CHARS);r||=n.length<e.length;t.push({type:a.type,text:n});continue}const o=i[a.type]??`other entries`;n.set(o,(n.get(o)??0)+1)}flush();return{items:t,truncated:r}}function fitBeamMirrorUpload(e){const t=e.items.slice(-200);const n={...e,items:t};let r=Buffer.byteLength(JSON.stringify(n),`utf8`);if(t.length<e.items.length||r>MIRROR_BODY_BUDGET_BYTES){n.truncated=true;r=Buffer.byteLength(JSON.stringify(n),`utf8`)}let i=0;while(i+1<t.length&&r>MIRROR_BODY_BUDGET_BYTES)r-=Buffer.byteLength(JSON.stringify(t[i++]),`utf8`)+1;return{...n,items:t.slice(i)}}function sourceModelForMirror(e,t){const n=e?.trim().toLowerCase();const r=t.find(e=>e.type===`agentMessage`&&e.model?.trim())?.model;if(!n||!/^[a-z0-9._-]+$/i.test(n)||!r)return;const i=r.trim();const a=truncateUtf16Safe(i.startsWith(`${n}/`)?i.slice(n.length+1):i,256).trim();return a&&/^\S+$/u.test(a)?{provider:n,model:a}:void 0}function mirrorCandidateKey(e){return`${e.catalogId}\0${e.hostId}\0${e.threadId}`}function createBeamMirrorRunner(e){const t=e.now??Date.now;const n=/* @__PURE__ */ new Map;const{signal:r}=e;let i=0;let a=false;let o=``;let s=false;const c=/* @__PURE__ */ new Error(`Beam mirror stopped`);const raceCatalog=e=>racePromiseWithAbortSignal(e,r,()=>c);const trackSuccessfulUpload=(e,r,i,a=false)=>{n.delete(e);n.set(e,{candidate:r,fingerprint:i,expiresAt:t()+BEAM_RETENTION_MS,...a?{retired:true}:{}});pruneMapToMaxSize(n,MIRROR_RETRY_CAP)};const warnThrottled=n=>{if(t()-i>=MIRROR_WARN_INTERVAL_MS){i=t();e.logger.warn(n)}};const upload=async t=>{if(r.aborted||s)return false;const n=parseBeamMirrorConfig(e.runtime.config.current());if(!n||typeof n===`string`||n.token===null||n.endpoint!==o)return false;const i=n.token;let a;try{a=await fetchWithSsrFGuard({url:o,timeoutMs:MIRROR_UPLOAD_TIMEOUT_MS,signal:r,policy:ssrfPolicyFromHttpBaseUrlAllowedOrigin(o),auditContext:`beam.mirror_upload`,maxRedirects:0,init:{method:`POST`,headers:{"Content-Type":`application/json`,...i?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify(t)}})}catch(n){r.throwIfAborted();if(n instanceof GuardedFetchRedirectError){s=true;e.logger.warn(`beam mirror upload blocked for ${t.source}: receiver returned redirect (${n.status}); redirects are not followed; configure the final endpoint`);return false}throw n}const{response:c,release:l}=a;try{r.throwIfAborted();if(c.status===409){const n=JSON.parse((await readResponseWithLimit(c,4096,{signal:r,timeoutMs:MIRROR_UPLOAD_TIMEOUT_MS})).toString(`utf8`));if(isRecord(n)&&n.beamId===t.beamId&&isRecord(n.handoff)&&n.handoff.owner===`gateway`&&typeof n.handoff.id===`string`&&/^[a-f0-9]{32}$/.test(n.handoff.id)){e.logger.info(`Beam source retired at the receiver; continue its logical conversation in Team.`);return`retired`}}if(!c.ok)warnThrottled(`beam mirror upload failed (${c.status}) for ${t.source}`);return c.ok}finally{await c.body?.cancel().catch(()=>void 0);await l()}};const buildUpload=async(e,n,i,a)=>{const o=await raceCatalog(n.read({agentId:e,hostId:i.hostId,threadId:i.threadId,limit:MIRROR_READ_LIMIT}));r.throwIfAborted();const s=buildBeamMirrorItems(o.items);const c=sourceModelForMirror(i.modelProvider,o.items);const l=s.items.length?s.items:[{type:`other`,text:`no shareable messages yet`}];return fitBeamMirrorUpload({version:1,beamId:beamMirrorId(i.catalogId,i.hostId,i.threadId),source:i.catalogId,title:truncateUtf16Safe(i.title,160),updatedAt:new Date(i.recencyAt||t()).toISOString(),completed:a,...c?{sourceModel:c}:{},...s.truncated||o.nextCursor?{truncated:true}:{},items:l})};const mirrorFingerprint=({updatedAt:e,...t})=>createHash(`sha256`).update(JSON.stringify(t)).digest(`hex`);const scan=async()=>{try{r.throwIfAborted();const i=e.runtime.config.current();const c=parseBeamMirrorConfig(i);if(c===void 0)return;if(typeof c===`string`){warnThrottled(`beam mirror disabled: ${c}`);return}if(o!==c.endpoint){o=c.endpoint;n.clear();s=false}let l;try{l=resolveSessionAgentIdsStrict({config:i}).defaultAgentId}catch(e){warnThrottled(`beam mirror disabled: ${String(e)}`);return}if(c.token===null){warnThrottled(`beam mirror paused: ${MIRROR_TOKEN_PATH} credential unavailable; restore it and run openclaw secrets reload`);return}const u=t()-c.activeWindowMinutes*6e4;const d=listActiveSessionCatalogs().filter(e=>e.id!==`beam`&&c.catalogs.includes(e.id));if(!a&&d.some(e=>!e.processHomeFallbackAllowed)){a=true;e.logger.warn(`beam mirror process-HOME fallback disabled: isolated state; only explicit catalog roots can be mirrored`)}const f=new Map(d.map(e=>[e.id,e]));const p=/* @__PURE__ */ new Map;const m=/* @__PURE__ */ new Set;for(const e of d){r.throwIfAborted();try{const t=await raceCatalog(e.list({agentId:l,limitPerHost:MIRROR_LIST_LIMIT}));r.throwIfAborted();for(const n of t){if(n.kind!==`gateway`||!n.connected||n.error)continue;if(n.nextCursor===void 0)m.add(`${e.id}\0${n.hostId}`);for(const t of n.sessions){const r={catalogId:e.id,hostId:n.hostId,modelProvider:t.modelProvider,threadId:t.threadId,title:t.name?.trim()||`${e.id} session`,recencyAt:t.recencyAt??t.updatedAt??0};p.set(mirrorCandidateKey(r),r)}}}catch(t){r.throwIfAborted();warnThrottled(`beam mirror list failed for ${e.id}: ${String(t)}`)}}const h=[...p.values()].filter(e=>e.recencyAt>=u).toSorted((e,t)=>t.recencyAt-e.recencyAt).slice(0,MIRROR_MAX_SESSIONS);for(const e of h){r.throwIfAborted();const i=mirrorCandidateKey(e);const a=n.get(i);if(a?.retired&&a.expiresAt>t())continue;const o=f.get(e.catalogId);if(!o)continue;try{const t=await buildUpload(l,o,e,false);r.throwIfAborted();const a=mirrorFingerprint(t);if(n.get(i)?.fingerprint===a)continue;const s=await upload(t);r.throwIfAborted();if(s)trackSuccessfulUpload(i,e,a,s===`retired`)}catch(t){r.throwIfAborted();warnThrottled(`beam mirror upload failed for ${e.catalogId}: ${String(t)}`)}}const g=t();const _=[];for(const[e,t]of n){r.throwIfAborted();if(t.retired){if(t.expiresAt<=g)n.delete(e);continue}const i=p.get(e);if(!(i?i.recencyAt<u:m.has(`${t.candidate.catalogId}\0${t.candidate.hostId}`)))continue;if(t.expiresAt<=g)n.delete(e);else if(_.length<MIRROR_MAX_SESSIONS)_.push([e,i?{...t,candidate:i}:t])}for(const[e,t]of _){r.throwIfAborted();let i=false;const a=f.get(t.candidate.catalogId);if(a)try{const e=await buildUpload(l,a,t.candidate,true);r.throwIfAborted();i=await upload(e)!==false;r.throwIfAborted()}catch{r.throwIfAborted()}n.delete(e);if(!i)n.set(e,t)}}catch(e){if(!r.aborted)throw e}};return{tick:scan}}function createBeamMirrorService(e){return{id:`beam-mirror`,apiVersion:2,start(t){const n=parseBeamMirrorConfig(e.runtime.config.current());if(n===void 0)return;if(typeof n===`string`){t.logger.warn(`beam mirror disabled: ${n}`);return}const r=createBeamMirrorRunner({runtime:e.runtime,logger:t.logger,signal:t.scheduler.signal});t.scheduler.schedule({id:`mirror`,delayMs:0,everyMs:n.pollSeconds*1e3,run:()=>r.tick()});if(n.token===null)t.logger.warn(`beam mirror paused: ${MIRROR_TOKEN_PATH} credential unavailable; restore it and run openclaw secrets reload`);else t.logger.info(`beam mirror active: ${n.catalogs.join(`, `)} -> ${new URL(n.endpoint).origin}`)}}}
//!extensions/beam/src/session-catalog.ts
const DEFAULT_LIMIT=50;const MAX_LIMIT=100;function boundedLimit(e){return Math.min(MAX_LIMIT,Math.max(1,e??DEFAULT_LIMIT))}function cursorOffset(e){if(!e||!/^\d+$/.test(e))return 0;const t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:0}var BeamTranscriptCursorError=class extends Error{constructor(e){super(`${e} Beam chat history cursor`);this.kind=e}};function transcriptRevision(e){return createHash(`sha256`).update(JSON.stringify(e.items)).digest(`base64url`)}function encodeTranscriptCursor(e){return Buffer.from(JSON.stringify(e),`utf8`).toString(`base64url`)}function decodeTranscriptCursor(e){try{const t=JSON.parse(Buffer.from(e,`base64url`).toString(`utf8`));if(isRecord(t)&&typeof t.revision===`string`&&/^[A-Za-z0-9_-]{43}$/.test(t.revision)&&typeof t.end===`number`&&Number.isSafeInteger(t.end)&&t.end>=0)return{revision:t.revision,end:t.end}}catch{}throw new BeamTranscriptCursorError(`invalid`)}function readBeamSession(e,t){const n=t.cursor===void 0?void 0:decodeTranscriptCursor(t.cursor);const r=Math.min(e.items.length,n?.end??e.items.length);const i=Math.max(0,r-boundedLimit(t.limit));let a;if(n||i>0){const t=transcriptRevision(e);if(n&&n.revision!==t)throw new BeamTranscriptCursorError(`stale`);if(i>0)a=encodeTranscriptCursor({revision:t,end:i})}return{hostId:BEAM_HOST_ID,label:e.title,threadId:e.beamId,items:e.items.slice(i,r).map((t,n)=>({id:`${e.beamId}:${i+n}`,type:t.type,text:t.text,timestamp:e.updatedAt,sender:t.type===`userMessage`&&e.uploaderProfileId?{identity:{type:`profile`,id:e.uploaderProfileId}}:void 0})).toReversed(),...a?{nextCursor:a}:{}}}function createBeamSessionCatalog(e){async function requireSession(t,n){if(t!==`gateway`)throw new Error(`unknown Beam host: ${t}`);const r=await e.get(n);if(!r)throw new Error(`unknown Beam session: ${n}`);return r}return{id:`beam`,label:`Beam`,audience:`gateway-operators`,shareRoute:BEAM_SESSION_SHARE_ROUTE,supportsProcessHomeIsolation:true,async list(t){const n=t.search?.trim().toLowerCase().normalize(`NFC`);const r=n&&isControlUiCatalogShareId(BEAM_SESSION_SHARE_ROUTE,n)?n:void 0;const i=(await e.list(r)).filter(e=>!n||(r?e.beamId.startsWith(r):`${e.title}\n${e.source}`.toLowerCase().normalize(`NFC`).includes(n))).toSorted((e,t)=>t.receivedAt-e.receivedAt||e.beamId.localeCompare(t.beamId));const a=cursorOffset(t.cursors?.[BEAM_HOST_ID]);const o=boundedLimit(t.limitPerHost);const s=i.slice(a,a+o);return[{hostId:BEAM_HOST_ID,label:`Beamed sessions`,kind:`gateway`,connected:true,sessions:s.map(e=>({threadId:e.beamId,name:e.title,status:e.completed?`completed`:`live`,createdAt:e.createdAt,updatedAt:e.receivedAt,recencyAt:e.receivedAt,source:e.source,archived:false,canContinue:Boolean(e.handoffId),...!e.handoffId?{continuationUnavailableReasonCode:`source-handoff-required`,continuationUnavailableReason:`This Beam is a read-only snapshot. Its authenticated original publisher must run beam handoff before you can continue here.`}:{},...e.continuation?.ready||e.continuation?.creating?{sessionKey:e.continuation.sessionKey}:{},canArchive:true})),...a+s.length<i.length?{nextCursor:String(a+s.length)}:{}}]},async read(e){return readBeamSession(await requireSession(e.hostId,e.threadId),e)},async resolveGatewayConversation(t){const n=await requireSession(t.hostId,t.threadId);if(!n.continuation?.ready&&!n.continuation?.creating)return;if(!t.assertCurrent)throw new Error(`Beam resolution requires current request authority`);const r=await e.reserveContinuation(n,n.continuation.agentId,t.assertCurrent);return{...n.continuation,assertCurrent:r.assertCurrent,release:r.release}},async archive(t){if(t.hostId!==`gateway`)throw new Error(`unknown Beam host: ${t.hostId}`);if(!await e.delete(t.threadId))throw new Error(`unknown Beam session: ${t.threadId}`);return{ok:true}},async copyToGatewaySession(t){const n=await requireSession(t.hostId,t.threadId);if(!t.agentId||!t.assertCurrent)throw new Error(`Beam continuation requires a destination and current request authority`);const r=await e.reserveContinuation(n,t.agentId,t.assertCurrent);return{continuation:{...r.session.continuation,reservedNow:r.reservedNow,assertCurrent:r.assertCurrent,release:r.release,complete:r.complete,beginCreate:r.beginCreate,rollback:r.rollback,read:async e=>{r.assertCurrent();return readBeamSession(r.session,e)}},displayName:r.session.title,...r.session.sourceModel?{preferredModel:`${r.session.sourceModel.provider}/${r.session.sourceModel.model}`}:{}}}}}
//!extensions/beam/src/store.ts
var BeamSourceOwnershipError=class extends Error{constructor(){super(`The source still owns this Beam. Use the updated Beam client's handoff command before continuing.`)}};function createBeamStore(e){const t=e.state.openKeyedStoreV2({namespace:`sessions`,maxEntries:500,overflowPolicy:`evict-oldest`,defaultTtlMs:BEAM_RETENTION_MS});const n=e.state.openKeyedStoreV2({namespace:`handoffs`,retention:`retained`});let r;let i;let a;const o=/* @__PURE__ */ new Map;const invalidate=()=>{r=void 0};const refresh=()=>{if(a?.aborted)return Promise.reject(/* @__PURE__ */ new Error(`Beam catalog inventory is stopped`));i??=(async()=>{const e=await t.entries();if(a?.aborted)return;r=e.map(({value:e,expiresAt:t})=>({value:{beamId:e.beamId,title:e.title,source:e.source,completed:e.completed,createdAt:e.createdAt,receivedAt:e.receivedAt,publisherProfileId:e.publisherProfileId,continuation:e.continuation,handoffId:e.handoffId},expiresAt:t}))})().finally(()=>{i=void 0});return i};return{catalogService:{id:`beam-catalog`,apiVersion:2,async start(e){a=e.scheduler.signal;const update=()=>refresh().catch(t=>{invalidate();e.logger.warn(`beam catalog inventory refresh failed: ${String(t)}`)});e.scheduler.schedule({id:`inventory`,delayMs:3e4,everyMs:3e4,run:update});await update()},async stop(){invalidate();await i?.catch(()=>{})}},async upload(e,{receivedAt:r,publisher:i,assertCurrent:a}){if(!t.createOperation)throw new Error(`Beam requires worker-owned plugin state operations`);const o=t.createOperation([t,n],{moduleName:`upload-operation-api.js`,exportName:`executeBeamUpload`},{assertCurrent:a});try{return(await o.execute({type:`upload`,input:{upload:e,receivedAt:r,publisher:i}},{writeStores:[0,1]})).value}finally{invalidate()}},async get(e){const r=await t.lookup(e);if(r)return r;const i=await n.lookup(e);return i?.continuation?{...i,items:[]}:void 0},async reserveContinuation(e,r,i){if(!e.handoffId)throw new BeamSourceOwnershipError;const execute=async(a,o,s,c)=>{if(!t.createOperation)throw new Error(`Beam requires worker-owned plugin state operations`);const l=await t.createOperation([t,n],{moduleName:`upload-operation-api.js`,exportName:`executeBeamUpload`},{assertCurrent:()=>{if(o!==`rollback`)i();s?.()}}).execute({type:`reserveContinuation`,input:{beamId:e.beamId,agentId:r,publisherProfileId:e.publisherProfileId,createdAt:e.createdAt,handoffId:e.handoffId,...a?{completeId:a,action:o,creationId:c}:{}}},{writeStores:[0,1]});invalidate();return l.value};const a=o.get(e.beamId);let s;if(a)s={...await a,reservedNow:false};else if(e.continuation)s={session:e,reservedNow:false};else{const t=execute();o.set(e.beamId,t);try{s=await t}finally{o.delete(e.beamId)}}i();const c=s.session.continuation;const l=await preparePluginStateGuard(n,e.beamId,t=>{if(!t||t.publisherProfileId!==e.publisherProfileId||t.createdAt!==e.createdAt||t.handoffId!==e.handoffId||t.continuation?.id!==c.id||t.continuation.agentId!==c.agentId||t.continuation.sessionKey!==c.sessionKey)throw new Error(`Beam handoff publication is no longer available`)});if(!l)throw new Error(`Beam handoff requires a native publication guard`);let u=false;let d;return{...s,reservedNow:!c.creating&&!c.ready,assertCurrent:()=>{i();l.assertCurrent()},release:l.release,beginCreate:async e=>{if(u)return false;u=true;const t=randomUUID();const n=(await execute(c.id,`begin`,e,t)).reservedNow;if(n)d=t;return n},rollback:async()=>{if(!d)throw new Error(`This lease did not create the destination`);l.assertCurrent();await execute(c.id,`rollback`,void 0,d)},complete:async e=>{if(!c.ready)await execute(c.id,`complete`,e,d??c.creating)}}},async delete(e){try{return await t.delete(e)}finally{invalidate()}},async list(e){for(;;){if(r){const t=Date.now();const i=r.filter(e=>e.expiresAt===void 0||e.expiresAt>t).map(({value:e})=>e);if(!e)return i;const a=await n.entriesInKeyRange({keyStartInclusive:e,keyEndExclusive:`${e}g`,limit:101});const o=new Set(i.map(e=>e.beamId));return[...i,...a.filter(({value:e})=>e.continuation&&!o.has(e.beamId)).map(({value:e})=>e)]}await refresh()}}}}
//!extensions/beam/src/owned-view.ts
var BeamOwnedViewForbiddenError=class extends Error{};function limit(e){if(e===void 0)return;if(typeof e!==`number`||!Number.isInteger(e)||e<1||e>100)throw new Error(`invalid limit`);return e}function parseRequest(e,t){const n=t===`list`?[`agentId`,`catalogId`,`search`,`hostIds`,`limitPerHost`,`cursors`]:t===`read`?[`agentId`,`catalogId`,`hostId`,`threadId`,`limit`,`cursor`]:[`agentId`,`catalogId`,`hostId`,`threadId`];if(Object.keys(e).some(e=>!n.includes(e))||e.catalogId!==void 0&&e.catalogId!==`beam`||e.agentId!==void 0&&typeof e.agentId!==`string`)throw new Error(`invalid target`);if(t!==`list`){if(e.hostId!==`gateway`||typeof e.threadId!==`string`||!/^[a-f0-9]{32}$/.test(e.threadId)||e.cursor!==void 0&&(typeof e.cursor!==`string`||e.cursor.length>256))throw new Error(`invalid read`);if(t===`continue`||t===`resolve`)return{kind:`continue`,request:{catalogId:`beam`,hostId:`gateway`,threadId:e.threadId,...typeof e.agentId===`string`?{agentId:e.agentId}:{}}};return{kind:`read`,request:{hostId:`gateway`,threadId:e.threadId,cursor:e.cursor,limit:limit(e.limit)}}}if(e.search!==void 0&&(typeof e.search!==`string`||e.search.length>500)||e.hostIds!==void 0&&(!Array.isArray(e.hostIds)||e.hostIds.length!==1||e.hostIds[0]!==`gateway`))throw new Error(`invalid list`);let r;if(e.cursors!==void 0){if(!isRecord(e.cursors)||Object.keys(e.cursors).some(e=>e!==`gateway`)||typeof e.cursors.gateway!==`string`||!/^\d{1,6}$/.test(e.cursors.gateway))throw new Error(`invalid cursor`);r={gateway:e.cursors.gateway}}return{kind:`list`,request:{search:e.search,limitPerHost:limit(e.limitPerHost),cursors:r}}}function createBeamOwnedViewHandler(e,t){return async n=>{const{params:r,client:i,respond:a,signal:o,hasCurrentClientAuthority:s,sessionMutationAuthorization:c}=n;const l=i?.internal?.operatorAccessAuthority;const u=i?.authenticatedUserProfile?.profileId;const assertCurrent=()=>{if(!c||!u||!i?.connect.scopes?.includes(`operator.sessions.write`)||l?.requiredPolicyPlugin!==`visitor-access`||l.gatewayAccessGrant?.pluginId!==`visitor-access`||o?.aborted||s?.()===false)throw new BeamOwnedViewForbiddenError(`Beam requires an active verified Visitor publisher`);try{c.assertCurrent();l.assertCurrent()}catch{throw new BeamOwnedViewForbiddenError(`Beam publisher authority expired`)}};try{assertCurrent();let i;try{i=parseRequest(r,t)}catch{a(false,void 0,{code:`INVALID_REQUEST`,message:`invalid owned Beam request`});return}const o=createBeamSessionCatalog({...e,async reserveContinuation(t,n,r){assertCurrent();const i=await e.reserveContinuation(t,n,r);const{uploaderProfileId:a,...o}=i.session;return{...i,session:o}},async list(t){const n=await e.list(t);assertCurrent();return n.filter(e=>e.publisherProfileId===u)},async get(t){const n=await e.get(t);assertCurrent();if(!n||n.publisherProfileId!==u)throw new BeamOwnedViewForbiddenError(`Beam is not available to this publisher`);const{uploaderProfileId:r,...i}=n;return i}});if(i.kind===`continue`){if(!n.copySessionCatalogToGateway)throw new Error(`Gateway catalog adoption is unavailable`);await n.copySessionCatalogToGateway({provider:o,request:i.request,assertCurrent,...t===`resolve`?{resolveOnly:true}:{}});return}let s;if(i.kind===`list`){const e=await o.list(i.request);for(const t of e)for(const e of t.sessions)e.canArchive=false;s={catalogs:[{id:o.id,label:o.label,capabilities:{continueSession:true,archive:false},shareRoute:o.shareRoute,hosts:e}]}}else s=await o.read(i.request);assertCurrent();a(true,s)}catch(e){let t={code:`FORBIDDEN`,message:`Beam is not available to this publisher; sign in with the current publishing Visitor account`};try{assertCurrent();if(!(e instanceof BeamOwnedViewForbiddenError))t=e instanceof BeamSourceOwnershipError?{code:`INVALID_REQUEST`,message:e.message}:e instanceof BeamTranscriptCursorError?{code:`INVALID_REQUEST`,message:e.kind===`stale`?`This Beam changed while you were reading it. Reload the snapshot to continue.`:`Invalid Beam page cursor. Reload the snapshot to continue.`}:{code:`UNAVAILABLE`,message:`Could not load this Beam. Refresh and try again.`}}catch{}a(false,void 0,t)}}}
//!extensions/beam/index.ts
var beam_default=definePluginEntry({id:`beam`,name:`Beam`,description:`Receive redacted coding-session snapshots for review or Team continuation`,register(e){const t=createBeamStore(e.runtime);e.registerSessionCatalog(createBeamSessionCatalog(t));for(const n of[`list`,`read`,`resolve`,`continue`])e.registerGatewayMethod(`beam.owned.${n}`,createBeamOwnedViewHandler(t,n),{scope:`operator.sessions.write`,profileAccess:`required`});e.registerService(t.catalogService);e.registerHttpRoute({path:`/api/v1/beam/sessions`,auth:`gateway`,match:`exact`,handler:createBeamRequestHandler({store:t,resolveControlUiBasePath:()=>e.runtime.config.current().gateway?.controlUi?.basePath})});e.registerService(createBeamMirrorService({runtime:e.runtime}))}});export{beam_default as default};