openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 22.9 kB
JavaScript
import{a as asOptionalRecord,l as isRecord}from"../../record-coerce-BTbqdJ3-.mjs";import{w as isSubagentSessionKey}from"../../session-key-BPgKfU2m.mjs";import{t as areDiagnosticsEnabledForProcess}from"../../diagnostic-events-BYBrlAdF.mjs";import{t as createSubsystemLogger}from"../../subsystem-DLCDFvCH.mjs";import{t as createPermitPool}from"../../permit-pool-bvWhofXE.mjs";import{n as validateJsonSchemaValue}from"../../schema-validator-_8KiTdxO.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../concurrency-runtime-A2TPGCdf.mjs";import"../../routing-BMFcTEzQ.mjs";import{t as listAgentIdsCompatibility}from"../../agent-scope-runtime-DKb8jQZx.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import"../../json-schema-runtime-2xhM839K.mjs";import"../../diagnostic-runtime-CjeXdjZk.mjs";import{C as prepareSessionCatalogGitHubLinker,b as readSessionTranscriptCatalogTitleAsync,w as prepareSessionCatalogSourceActorProjector,y as readSessionTranscriptCatalogPage}from"../../session-transcript-runtime-VsBjF9FD.mjs";import"../../session-catalog-iUSOBPcG.mjs";import{n as sessionCatalogPaging,t as publishSessionCatalogHost}from"../../session-catalog-paging-C-mqKUCo.mjs";
//!extensions/session-share/src/config.ts
function sessionShareConfig(e){const t=e.plugins?.entries?.[`session-share`]?.config;return isRecord(t)?t:{}}function sessionShareSelection(e){const t=sessionShareConfig(e).share;if(!isRecord(t))return;const{groups:n,involvingProfileId:r}=t;if(!Array.isArray(n)||n.length===0||!n.every(e=>typeof e===`string`&&e.length>0)||r!==void 0&&(typeof r!==`string`||!/^\S+$/.test(r)))return;return{groups:n,...r!==void 0?{involvingProfileId:r}:{}}}function sessionShareNodeBinding(e,t){const n=sessionShareConfig(e).nodes;const r=isRecord(n)?n[t]:void 0;return{...isRecord(r)&&typeof r.owner===`string`?{owner:r.owner}:{},linkGitHubIdentities:isRecord(r)&&r.linkGitHubIdentities===true}}
//!extensions/session-share/src/node-commands.ts
const SESSION_SHARE_LIST_COMMAND=`openclaw.sessions.list.v1`;const SESSION_SHARE_READ_COMMAND=`openclaw.sessions.read.v1`;const SESSION_SHARE_COMMANDS=[SESSION_SHARE_LIST_COMMAND,SESSION_SHARE_READ_COMMAND];const parameterMessages={listNotObject:`Session list parameters must be an object`,unknownListParameter:e=>`Unknown session list parameter: ${e}`,invalidSearchTerm:`searchTerm must be a non-empty string of at most 500 characters`,readNotObject:`Session read parameters must be an object`,unknownReadParameter:e=>`Unknown session read parameter: ${e}`,invalidThreadId:`threadId must be a non-empty session key of at most 512 characters`};function parseNodeParams(e){return e?JSON.parse(e):void 0}function isSharedEntry(e,{sessionKey:t,entry:n}){return n.category!==void 0&&e.has(n.category)&&n.incognito!==true&&n.visibility!==`draft`&&!isSubagentSessionKey(t)&&n.createdVia!==`spawn`&&!n.spawnedBy?.trim()&&!/^agent:[^:]+:catalog:/i.test(t)}function withSharedEntries(e,t,n){const r=e.runtime.config.current();const i=sessionShareSelection(r);const a=JSON.stringify(i);const o=new Set(i?.groups??[]);const s=(i?listAgentIdsCompatibility(r):[]).filter(e=>t.some(t=>t.agentId===e)).toSorted().flatMap(n=>{const i=e.runtime.agent.session.resolveStorePath(r.session?.store,{agentId:n});const a=t.filter(e=>e.agentId===n&&e.storePath===i).map(e=>e.sessionKey);return a.length?[{agentId:n,storePath:i,sessionKeys:a}]:[]});return e.runtime.agent.session.withSessionEntriesAsync({stores:s,involvingProfileId:i?.involvingProfileId},t=>{const i=e.runtime.config.current();if(i!==r||JSON.stringify(sessionShareSelection(i))!==a||s.some(({agentId:t,storePath:n})=>!listAgentIdsCompatibility(i).includes(t)||e.runtime.agent.session.resolveStorePath(i.session?.store,{agentId:t})!==n))throw new Error(`Session is no longer shared. Refresh the session catalog.`);return n(t.filter(e=>isSharedEntry(o,e)))})}function createSessionShareNodeCommands(e){const t={pluginId:`session-share`,sourceDomain:`openclaw`};let n;const r=/* @__PURE__ */ new Map;async function readSharedEntries(){const t=e.runtime.config.current();if(t!==n){r.clear();n=t}const i=sessionShareSelection(t);const a=JSON.stringify(i);const o=new Set(i?.groups??[]);const s=[];const c=/* @__PURE__ */ new Set;for(const n of o.size?listAgentIdsCompatibility(t).toSorted():[]){const i=e.runtime.agent.session.resolveStorePath(t.session?.store,{agentId:n});const l=JSON.stringify([n,i]);c.add(l);let u=r.get(l);if(!u){u=e.runtime.agent.session.createSessionEntryListReader({agentId:n,storePath:i});r.set(l,u)}const d=await(await u)();const f=e.runtime.config.current();if(f!==t||JSON.stringify(sessionShareSelection(f))!==a||!listAgentIdsCompatibility(f).includes(n)||e.runtime.agent.session.resolveStorePath(f.session?.store,{agentId:n})!==i)throw new Error(`Session sharing configuration changed. Refresh the session catalog.`);for(const e of d.entries)if(isSharedEntry(o,e))s.push({...e,agentId:n,storePath:i,assertSourceCurrent:d.assertCurrent})}for(const e of r.keys())if(!c.has(e))r.delete(e);if(i?.involvingProfileId===void 0)return s;return withSharedEntries(e,s,e=>{s.forEach(e=>e.assertSourceCurrent());const t=new Set(e.map(({agentId:e,storePath:t,sessionKey:n,entry:r})=>JSON.stringify([e,t,n,r.sessionId])));return s.filter(({agentId:e,storePath:n,sessionKey:r,entry:i})=>t.has(JSON.stringify([e,n,r,i.sessionId])))})}return[{command:SESSION_SHARE_LIST_COMMAND,hasActiveWork:()=>false,cap:`openclaw-sessions`,dangerous:false,isAvailable:({config:e})=>sessionShareSelection(e)!==void 0,async handle(n){const r=sessionCatalogPaging.parseListParams(parseNodeParams(n),{searchMaxLength:500,messages:parameterMessages});const i=sessionCatalogPaging.decodeCursor(r.cursor);const a=r.searchTerm?.toLowerCase().normalize(`NFC`);const o=[];for(const{agentId:e,sessionKey:t,storePath:n,entry:r,assertSourceCurrent:i}of await readSharedEntries()){const s=a?await readSessionTranscriptCatalogTitleAsync({agentId:e,sessionKey:t,storePath:n,entry:r}):void 0;if(a&&!s?.toLowerCase().normalize(`NFC`).includes(a)&&!t.toLowerCase().normalize(`NFC`).includes(a))continue;o.push({agentId:e,storePath:n,threadId:t,name:s,entry:r,assertSourceCurrent:i,recencyAt:Math.max(r.updatedAt,r.lastInteractionAt??0,r.lastActivityAt??0)})}o.sort((e,t)=>t.recencyAt-e.recencyAt||e.threadId.localeCompare(t.threadId));const s=o.slice(i,i+r.limit);if(!a)for(const e of s)e.name=await readSessionTranscriptCatalogTitleAsync({agentId:e.agentId,sessionKey:e.threadId,storePath:e.storePath,entry:e.entry});const c=new Set(s.map(e=>e.assertSourceCurrent));const l=await prepareSessionCatalogSourceActorProjector({...t,actors:s.map(({entry:e})=>e.createdActor)});c.forEach(e=>e());return withSharedEntries(e,s.map(e=>({agentId:e.agentId,storePath:e.storePath,sessionKey:e.threadId})),e=>{c.forEach(e=>e());if(s.some(t=>!e.some(({agentId:e,sessionKey:n,storePath:r,entry:i})=>e===t.agentId&&n===t.threadId&&r===t.storePath&&i.sessionId===t.entry.sessionId)))throw new Error(`Session is no longer shared. Refresh the session catalog.`);const t=s.map(({threadId:e,name:t,entry:n,recencyAt:r})=>{const i=n.archivedAt!==void 0;const a=n.execCwd??n.spawnedCwd??n.spawnedWorkspaceDir??n.worktree?.canonicalWorkspaceDir??n.worktree?.repoRoot;return{threadId:e,name:t,color:n.color,cwd:a?a.slice(0,6e3):void 0,status:i?`archived`:`idle`,createdAt:n.createdAt,updatedAt:n.updatedAt,recencyAt:r,gitBranch:n.worktree?.branch?n.worktree.branch.slice(0,6e3):void 0,archived:i,canContinue:false,canArchive:false,canOpenTerminal:false,createdActor:l(n.createdActor)}});return JSON.stringify({sessions:t,...i+t.length<o.length?{nextCursor:sessionCatalogPaging.encodeCursor(i+t.length)}:{}})})}},{command:SESSION_SHARE_READ_COMMAND,hasActiveWork:()=>false,cap:`openclaw-sessions`,dangerous:false,isAvailable:({config:e})=>sessionShareSelection(e)!==void 0,async handle(n){const r=sessionCatalogPaging.parseReadParams(parseNodeParams(n),{threadIdMaxLength:512,threadIdPattern:/^[^\0\r\n]+$/,cursorMaxLength:1200,messages:parameterMessages});const i=(await readSharedEntries()).find(({sessionKey:e})=>e===r.threadId);if(!i)throw new Error(`Session is not shared. The session must match the source operator's filters and stay eligible.`);i.assertSourceCurrent();let assertActorsCurrent=()=>{};const a=await readSessionTranscriptCatalogPage({...t,agentId:i.agentId,sessionKey:i.sessionKey,storePath:i.storePath,limit:r.limit,cursor:r.cursor},e=>{assertActorsCurrent=e});i.assertSourceCurrent();return withSharedEntries(e,[i],e=>{i.assertSourceCurrent();if(!e.some(({agentId:e,sessionKey:t,storePath:n,entry:r})=>e===i.agentId&&t===i.sessionKey&&n===i.storePath&&r.sessionId===i.entry.sessionId))throw new Error(`Session is no longer shared. Refresh the session catalog.`);assertActorsCurrent();return JSON.stringify({threadId:r.threadId,...a})})}}]}
//!extensions/session-share/src/wire.ts
const shortString={type:`string`,minLength:1,maxLength:512};const label={type:`string`,minLength:1,maxLength:200};const text={type:`string`,maxLength:6e3};const cursor={type:`string`,minLength:1,maxLength:2048,pattern:`^[A-Za-z0-9_-]+$`};const identity={oneOf:[{type:`object`,additionalProperties:false,required:[`type`,`pluginId`,`domain`,`idKind`,`id`],properties:{type:{const:`remote`},pluginId:shortString,domain:shortString,idKind:shortString,id:shortString}},{type:`object`,additionalProperties:false,required:[`type`,`pluginId`,`accountId`,`senderKind`,`id`],properties:{type:{const:`observation`},pluginId:{anyOf:[shortString,{type:`null`}]},accountId:{anyOf:[shortString,{type:`null`}]},senderKind:{enum:[`human`,`bot`,`unknown`]},id:shortString}},{type:`object`,additionalProperties:false,required:[`type`,`id`],properties:{type:{const:`agent`},id:shortString}},{type:`object`,additionalProperties:false,required:[`type`,`actorType`,`source`,`id`],properties:{type:{const:`legacy`},actorType:shortString,source:{anyOf:[shortString,{type:`null`}]},id:text}}]};const participant={type:`object`,additionalProperties:false,required:[`identity`],properties:{identity,label,avatarUrl:shortString}};const sessionPageSchema={type:`object`,additionalProperties:false,required:[`sessions`],properties:{nextCursor:cursor,sessions:{type:`array`,maxItems:100,items:{type:`object`,additionalProperties:false,required:[`threadId`,`status`,`archived`,`canContinue`,`canArchive`],properties:{threadId:shortString,name:text,color:shortString,cwd:text,status:{enum:[`live`,`idle`,`archived`]},createdAt:{type:`number`},updatedAt:{type:`number`},recencyAt:{type:`number`},gitBranch:text,archived:{type:`boolean`},createdActor:{type:`object`,additionalProperties:false,required:[`type`],properties:{type:{enum:[`human`,`agent`,`system`]},id:shortString,identity,label,avatarUrl:shortString}},canContinue:{const:false},canArchive:{const:false},canOpenTerminal:{const:false}}}}}};const transcriptPageSchema={type:`object`,additionalProperties:false,required:[`threadId`,`items`],properties:{threadId:shortString,nextCursor:cursor,items:{type:`array`,maxItems:100,items:{type:`object`,additionalProperties:false,required:[`type`],properties:{type:{enum:[`userMessage`,`agentMessage`,`reasoning`,`toolCall`,`toolResult`,`other`]},id:shortString,text,timestamp:shortString,model:shortString,sender:participant,truncated:{type:`boolean`}}}}}};function isSessionPage(e){return validateJsonSchemaValue({schema:sessionPageSchema,cacheKey:`session-share.sessions.v1`,value:e}).ok}function isTranscriptPage(e){return validateJsonSchemaValue({schema:transcriptPageSchema,cacheKey:`session-share.transcript.v1`,value:e}).ok}function unwrapPayload(e){if(isRecord(e)&&typeof e.payloadJSON===`string`){if(e.payloadJSON.length>2097152)throw new Error(`Session catalog response exceeded the page limit`);return JSON.parse(e.payloadJSON)}return e}function parseSessionSharePage(e){const t=unwrapPayload(e);if(!isSessionPage(t)||t.nextCursor!==void 0&&!sessionCatalogPaging.isExactCursor(t.nextCursor))throw new Error(`Invalid OpenClaw session page from paired node`);return t}function parseSessionShareTranscriptPage(e,t){const n=unwrapPayload(e);if(!isTranscriptPage(n)||n.threadId!==t)throw new Error(`Invalid OpenClaw chat history page from paired node`);return n}
//!extensions/session-share/src/session-catalog.ts
const REFRESH_MS=3e4;const MAX_STALENESS_MS=6e4;const REFRESH_BUDGET_MS=3e5;const MAX_SNAPSHOTS=32;const MAX_REFRESHES=4;const MAX_SNAPSHOT_ROWS=1e4;const MAX_SNAPSHOT_BYTES=16777216;var SnapshotLimitError=class extends Error{constructor(){super(`Shared catalog exceeds the snapshot limit (10,000 sessions or 16 MiB). Reduce the shared groups on the source node.`)}};const log=createSubsystemLogger(`gateway/session-catalog`);const nodeErrorCodes=/* @__PURE__ */ new Set([`TIMEOUT`,`NOT_CONNECTED`,`PAIRING_CHANGED`,`ROUTE_CHANGED`,`ABORTED`,`UNAVAILABLE`,`POLICY_CHANGED`,`APPROVAL_AUTHORITY_CLOSED`]);async function observeCatalogRefresh(e,t){if(!areDiagnosticsEnabledForProcess()||!log.isEnabled(`warn`))return e();const n=performance.now();const finish=(e,r)=>{try{if(!areDiagnosticsEnabledForProcess()||!log.isEnabled(`warn`))return;const i=performance.now()-n;if(i<1e3||!t())return;const a=asOptionalRecord(asOptionalRecord(r)?.details);const o=asOptionalRecord(a?.nodeError);const s=o?.code;log.warn(`slow Session Share catalog refresh`,{elapsedMs:Math.round(i),outcome:e,...o?{nodeErrorCode:typeof s===`string`&&nodeErrorCodes.has(s)?s:`unknown`}:{},...typeof a?.nodeCommandDispatched===`boolean`?{nodeCommandDispatched:a.nodeCommandDispatched}:{}})}catch{}};try{const t=await e();finish(`resolved`);return t}catch(e){finish(`rejected`,e);throw e}}function namespaceIdentity(e,t){return e.type===`remote`&&e.pluginId===`session-share`?{...e,domain:t}:e}function nodeLabel(e){return e.displayName?.trim()||e.remoteIp?.trim()||e.nodeId}function isSessionHost(e){return SESSION_SHARE_COMMANDS.every(t=>e.commands?.includes(t))}function bindSession(e,t,n,r){const i=e.createdActor;const a=i?.type===`human`&&(i.identity?.type===`remote`||i.identity?.type===`observation`);const o=!a&&n?n:i;if(!o?.identity)return o?{...e,createdActor:o}:e;const s={identity:namespaceIdentity(o.identity,t),label:o.label,avatarUrl:o.avatarUrl};const c=a&&r?r(s):s;return{...e,createdActor:{...o,...c,...c.identity.type===`profile`?{id:c.identity.id}:{}}}}function createSessionShareCatalog(e){const t=/* @__PURE__ */ new Map;const n=/* @__PURE__ */ new WeakMap;let r;let i=0;const a=createPermitPool(MAX_REFRESHES);const bindingFor=t=>sessionShareNodeBinding(e.runtime.config.current(),t);const current=n=>!n.scope.signal.aborted&&e.runtime.config.current()===n.config&&t.get(n.node.nodeId)===n;const retire=e=>{t.delete(e.node.nodeId);e.sessions=void 0;e.scope.stop()};const sameConnection=(e,t)=>t?.connected&&isSessionHost(t)&&t.connectedAtMs===e.node.connectedAtMs;function refresh(t,n){if(t.pending)return;t.sessions=void 0;const r=Promise.withResolvers();t.pending=r.promise;const o=t.scope.signal;const release=()=>r.resolve();o.addEventListener(`abort`,release,{once:true});t.scope.schedule({id:`refresh`,delayMs:0,async run(){const s=await a.acquire({signal:o});try{if(!s||!current(t))return;const r=await observeCatalogRefresh(async()=>{const e=performance.now()+REFRESH_BUDGET_MS;const r=[];let i;let a=0;do{if(!current(t)||!n.invokeNode)throw new Error(`Session Share catalog owner retired`);const s=Math.min(REFRESH_MS,Math.ceil(e-performance.now()));if(s<=0)throw new Error(`Session Share catalog refresh timed out`);const c=parseSessionSharePage(await n.invokeNode({nodeId:t.node.nodeId,command:SESSION_SHARE_LIST_COMMAND,params:{limit:100,...i?{cursor:i}:{}},timeoutMs:s,signal:o}));a+=Buffer.byteLength(JSON.stringify(c));if(r.length+c.sessions.length>MAX_SNAPSHOT_ROWS||a>MAX_SNAPSHOT_BYTES)throw new SnapshotLimitError;r.push(...c.sessions);if(c.nextCursor!==void 0&&sessionCatalogPaging.decodeCursor(c.nextCursor)<=sessionCatalogPaging.decodeCursor(i))throw new Error(`Session Share catalog cursor did not advance`);i=c.nextCursor}while(i);return r},()=>{const e=performance.now();if(e<i)return false;i=e+MAX_STALENESS_MS;return true});const a=(await e.runtime.nodes.list()).nodes.find(e=>e.nodeId===t.node.nodeId);if(!current(t))return;if(!sameConnection(t,a)){retire(t);return}t.sessions=r;t.refreshedAt=performance.now();t.retryMs=REFRESH_MS;t.error=void 0}catch(e){t.retryMs=t.error?Math.min(t.retryMs*2,3e5):REFRESH_MS;t.error=e instanceof SnapshotLimitError?{code:`CATALOG_TOO_LARGE`,message:e.message}:{code:`NODE_INVOKE_FAILED`,message:`Cannot refresh OpenClaw sessions. Check the paired node's session-share configuration and connection.`}}finally{s?.();t.pending=void 0;o.removeEventListener(`abort`,release);r.resolve();if(current(t))t.scope.schedule({id:`next-refresh`,delayMs:t.retryMs,run:()=>refresh(t,n)})}}})}function reconcile(n){const i=r;if(!i||i.scheduler.signal.aborted)return;const a=e.runtime.config.current();for(const e of t.values())if(e.config!==a||!sameConnection(e,n.find(t=>t.nodeId===e.node.nodeId)))retire(e)}function admit(n){const i=r;if(!i||i.scheduler.signal.aborted)return;const a=e.runtime.config.current();const o=new Set(n.map(e=>e.nodeId));for(const e of n.filter(e=>e.connected)){const n=t.get(e.nodeId);if(n){t.delete(e.nodeId);t.set(e.nodeId,n);refresh(n,i);continue}if(t.size>=MAX_SNAPSHOTS){const e=Array.from(t.values()).find(e=>!e.pending&&!o.has(e.node.nodeId));if(!e)continue;retire(e)}const r={node:e,config:a,scope:i.scheduler.scope(),refreshedAt:0,retryMs:REFRESH_MS};t.set(e.nodeId,r);refresh(r,i)}}e.registerService({id:`session-share-catalog`,apiVersion:2,start(n){r=n;n.scheduler.schedule({id:`nodes`,delayMs:0,everyMs:REFRESH_MS,async run(){if(!t.size)return;const{nodes:i}=await e.runtime.nodes.list();if(r===n)reconcile(i)}})},stop(){r=void 0;t.clear()}});async function listNode(e,i){const a=`node:${e.nodeId}`;const{onHost:o,waitUntil:s,signal:c,allowPartialResults:l}=i;const u=i.search?.trim().toLowerCase().normalize(`NFC`);const d=i.cursors?.[a];const f=sessionCatalogPaging.boundedLimit(i.limitPerHost);const p={hostId:a,label:nodeLabel(e),kind:`node`,nodeId:e.nodeId,connected:e.connected===true};const failed=(e,t)=>({...p,sessions:[],error:{code:e,message:t}});if(!e.connected)return failed(`NODE_OFFLINE`,`Paired node is offline`);const m=t.get(e.nodeId);const project=async()=>{if(!m)return failed(r?`CATALOG_LOADING`:`NODE_INVOKE_FAILED`,`Session Share is unavailable or busy. Refresh the catalog.`);if(!current(m))return failed(`NODE_INVOKE_FAILED`,`Session Share is unavailable. Refresh the catalog.`);if(!m.sessions||performance.now()-m.refreshedAt>=MAX_STALENESS_MS)return m.error?{...p,sessions:[],error:m.error}:failed(`CATALOG_LOADING`,`Session Share catalog is still loading. Refresh the catalog.`);const t=m.sessions;const i=u?m.sessions.filter(e=>e.name?.toLowerCase().normalize(`NFC`).includes(u)||e.threadId.toLowerCase().normalize(`NFC`).includes(u)):m.sessions;const o=sessionCatalogPaging.decodeCursor(d);const s=bindingFor(e.nodeId);const l=i.slice(o,o+f);const h=s.owner||s.linkGitHubIdentities?await prepareSessionCatalogGitHubLinker({owners:s.owner?[s.owner]:[],participants:s.linkGitHubIdentities?l.flatMap(({createdActor:e})=>e?.identity?[{identity:e.identity}]:[]):[]}):void 0;if(!current(m)||m.sessions!==t||c?.aborted)return failed(`NODE_INVOKE_FAILED`,`Session Share is unavailable. Refresh the catalog.`);const g=s.owner?h?.resolveOwner(s.owner):void 0;const _=s.linkGitHubIdentities?h?.linkParticipant:void 0;const v={...p,sessions:l.map(e=>bindSession(e,a,g,_)),...o+f<i.length?{nextCursor:sessionCatalogPaging.encodeCursor(o+f)}:{}};n.set(v,()=>{if(!current(m)||m.sessions!==t||c?.aborted)throw new Error(`Session Share is unavailable. Refresh the catalog.`)});return v};if(m?.pending&&!(l===true&&o&&s)){c?.throwIfAborted();let e;try{await Promise.race([m.pending,new Promise(t=>{e=t;c?.addEventListener(`abort`,e,{once:true})})])}finally{if(e)c?.removeEventListener(`abort`,e)}c?.throwIfAborted()}const h=await project();if(m&&!current(m)||c?.aborted)return failed(`NODE_INVOKE_FAILED`,`Session Share is unavailable. Refresh the catalog.`);if(m?.pending&&l===true&&o&&s){publishSessionCatalogHost({waitUntil:s,onHost:e=>{if(e&¤t(m)&&!c?.aborted){n.get(e)?.();o(e)}}},m.pending.then(()=>c?.aborted?void 0:project()));if(!m.error)return{...p,sessions:[],pending:true}}n.get(h)?.();o?.(h);return h}return{id:`openclaw`,label:`OpenClaw sessions`,supportsProcessHomeIsolation:true,audience:`session-viewers`,requiresFreshList:true,async list(t){t.signal?.throwIfAborted();const i=e.runtime.config.current();let a;try{a=(await(t.listNodes?.()??e.runtime.nodes.list())).nodes}catch{t.signal?.throwIfAborted();if(e.runtime.config.current()!==i)return[];throw new Error(`Cannot discover OpenClaw session sources. Refresh the catalog to retry.`)}t.signal?.throwIfAborted();if(e.runtime.config.current()!==i)return[];reconcile(a);const o=t.hostIds?new Set(t.hostIds):void 0;const s=a.filter(e=>isSessionHost(e)&&(!o||o.has(`node:${e.nodeId}`))).toSorted((e,t)=>nodeLabel(e).localeCompare(nodeLabel(t))||e.nodeId.localeCompare(t.nodeId)).slice(0,MAX_SNAPSHOTS);admit(s);const c=r;const l=await Promise.all(s.map(e=>{t.signal?.throwIfAborted();return listNode(e,t)}));t.signal?.throwIfAborted();if(r!==c)return[];for(const e of l)n.get(e)?.();return l},async read(t){if(!t.hostId.startsWith(`node:`)||!t.hostId.slice(5))throw new Error(`Select a paired node host to read an OpenClaw session`);const n=t.hostId.slice(5);const r=(await e.runtime.nodes.list()).nodes.find(e=>e.nodeId===n&&e.connected&&isSessionHost(e));if(!r)throw new Error(`OpenClaw session node is unavailable. Reconnect it and refresh the catalog.`);const i=await e.runtime.nodes.invoke({nodeId:n,command:SESSION_SHARE_READ_COMMAND,timeoutMs:3e4,scopes:[`operator.write`],params:{threadId:t.threadId,limit:sessionCatalogPaging.boundedLimit(t.limit),...t.cursor!==void 0?{cursor:t.cursor}:{}}});const a=parseSessionShareTranscriptPage(i,t.threadId);const o=bindingFor(n).linkGitHubIdentities?(await prepareSessionCatalogGitHubLinker({participants:a.items.flatMap(e=>e.sender?[e.sender]:[])})).linkParticipant:void 0;return{...a,hostId:t.hostId,label:nodeLabel(r),items:a.items.map(e=>{if(!e.sender)return e;const n={...e.sender,identity:namespaceIdentity(e.sender.identity,t.hostId)};return Object.assign({},e,{sender:o?.(n)??n})})}}}}
//!extensions/session-share/index.ts
var session_share_default=definePluginEntry({id:`session-share`,name:`Session Share`,description:`Read-only OpenClaw sessions on paired gateways`,register(e){e.registerSessionCatalog(createSessionShareCatalog(e));for(const t of createSessionShareNodeCommands(e))e.registerNodeHostCommand(t);e.registerNodeInvokePolicy({commands:SESSION_SHARE_COMMANDS,defaultPlatforms:[`macos`,`linux`,`windows`],handle:e=>e.invokeNode()})}});export{session_share_default as default};