File size: 5,445 Bytes
4c76b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Channel runtime context helpers build plugin runtime context for channel execution.
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import type {
  ChannelRuntimeContextEvent,
  ChannelRuntimeContextKey,
  ChannelRuntimeContextRegistry,
} from "../../channels/plugins/channel-runtime-surface.types.js";
import { createSubsystemLogger } from "../../logging.js";

type StoredRuntimeContext = {
  token: symbol;
  context: unknown;
  normalizedKey: {
    channelId: string;
    accountId?: string;
    capability: string;
  };
};

const log = createSubsystemLogger("plugins/runtime-channel");

function normalizeRuntimeContextString(value: string | null | undefined): string {
  return normalizeOptionalString(value) ?? "";
}

function normalizeRuntimeContextKey(params: ChannelRuntimeContextKey): {
  mapKey: string;
  normalizedKey: {
    channelId: string;
    accountId?: string;
    capability: string;
  };
} | null {
  const channelId = normalizeRuntimeContextString(params.channelId);
  const capability = normalizeRuntimeContextString(params.capability);
  const accountId = normalizeRuntimeContextString(params.accountId);
  if (!channelId || !capability) {
    return null;
  }
  return {
    mapKey: `${channelId}\u0000${accountId}\u0000${capability}`,
    normalizedKey: {
      channelId,
      capability,
      ...(accountId ? { accountId } : {}),
    },
  };
}

function doesRuntimeContextWatcherMatch(params: {
  watcher: {
    channelId?: string;
    accountId?: string;
    capability?: string;
  };
  event: ChannelRuntimeContextEvent;
}): boolean {
  if (params.watcher.channelId && params.watcher.channelId !== params.event.key.channelId) {
    return false;
  }
  if (
    params.watcher.accountId !== undefined &&
    params.watcher.accountId !== (params.event.key.accountId ?? "")
  ) {
    return false;
  }
  if (params.watcher.capability && params.watcher.capability !== params.event.key.capability) {
    return false;
  }
  return true;
}

/** Creates the in-memory channel runtime context registry used by plugin runtime surfaces. */
export function createChannelRuntimeContextRegistry(): ChannelRuntimeContextRegistry {
  const runtimeContexts = new Map<string, StoredRuntimeContext>();
  const runtimeContextWatchers = new Set<{
    filter: {
      channelId?: string;
      accountId?: string;
      capability?: string;
    };
    onEvent: (event: ChannelRuntimeContextEvent) => void;
  }>();
  const emitRuntimeContextEvent = (event: ChannelRuntimeContextEvent) => {
    for (const watcher of runtimeContextWatchers) {
      if (!doesRuntimeContextWatcherMatch({ watcher: watcher.filter, event })) {
        continue;
      }
      try {
        watcher.onEvent(event);
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        log.error(
          `runtime context watcher failed during ${event.type} ` +
            `channel=${event.key.channelId} capability=${event.key.capability}` +
            (event.key.accountId ? ` account=${event.key.accountId}` : "") +
            `: ${message}`,
        );
      }
    }
  };
  return {
    register: (params) => {
      const normalized = normalizeRuntimeContextKey(params);
      if (!normalized) {
        return { dispose: () => {} };
      }
      if (params.abortSignal?.aborted) {
        return { dispose: () => {} };
      }
      const token = Symbol(normalized.mapKey);
      let disposed = false;
      const dispose = () => {
        if (disposed) {
          return;
        }
        disposed = true;
        // Detach before the token check: stale leases disposed after a replacement
        // registered must still release their listener on long-lived signals.
        params.abortSignal?.removeEventListener("abort", dispose);
        const current = runtimeContexts.get(normalized.mapKey);
        if (!current || current.token !== token) {
          return;
        }
        runtimeContexts.delete(normalized.mapKey);
        emitRuntimeContextEvent({
          type: "unregistered",
          key: normalized.normalizedKey,
        });
      };
      params.abortSignal?.addEventListener("abort", dispose, { once: true });
      if (params.abortSignal?.aborted) {
        dispose();
        return { dispose };
      }
      runtimeContexts.set(normalized.mapKey, {
        token,
        context: params.context,
        normalizedKey: normalized.normalizedKey,
      });
      if (disposed) {
        return { dispose };
      }
      emitRuntimeContextEvent({
        type: "registered",
        key: normalized.normalizedKey,
        context: params.context,
      });
      return { dispose };
    },
    get: (params) => {
      const normalized = normalizeRuntimeContextKey(params);
      if (!normalized) {
        return undefined;
      }
      return runtimeContexts.get(normalized.mapKey)?.context as never;
    },
    watch: (params) => {
      const watcher = {
        filter: {
          ...(params.channelId?.trim() ? { channelId: params.channelId.trim() } : {}),
          ...(params.accountId != null ? { accountId: params.accountId.trim() } : {}),
          ...(params.capability?.trim() ? { capability: params.capability.trim() } : {}),
        },
        onEvent: params.onEvent,
      };
      runtimeContextWatchers.add(watcher);
      return () => {
        runtimeContextWatchers.delete(watcher);
      };
    },
  };
}