@memberjunction/server 5.40.2 → 5.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agentSessions/HostInstance.d.ts +19 -0
- package/dist/agentSessions/HostInstance.d.ts.map +1 -0
- package/dist/agentSessions/HostInstance.js +48 -0
- package/dist/agentSessions/HostInstance.js.map +1 -0
- package/dist/agentSessions/SessionJanitor.d.ts +97 -0
- package/dist/agentSessions/SessionJanitor.d.ts.map +1 -0
- package/dist/agentSessions/SessionJanitor.js +222 -0
- package/dist/agentSessions/SessionJanitor.js.map +1 -0
- package/dist/agentSessions/SessionManager.d.ts +142 -0
- package/dist/agentSessions/SessionManager.d.ts.map +1 -0
- package/dist/agentSessions/SessionManager.js +308 -0
- package/dist/agentSessions/SessionManager.js.map +1 -0
- package/dist/agentSessions/index.d.ts +4 -0
- package/dist/agentSessions/index.d.ts.map +1 -0
- package/dist/agentSessions/index.js +26 -0
- package/dist/agentSessions/index.js.map +1 -0
- package/dist/auth/initializeProviders.d.ts.map +1 -1
- package/dist/auth/initializeProviders.js +6 -1
- package/dist/auth/initializeProviders.js.map +1 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +41 -7
- package/dist/context.js.map +1 -1
- package/dist/generated/generated.d.ts +659 -3
- package/dist/generated/generated.d.ts.map +1 -1
- package/dist/generated/generated.js +5459 -1759
- package/dist/generated/generated.js.map +1 -1
- package/dist/generic/ResolverBase.js +1 -1
- package/dist/generic/ResolverBase.js.map +1 -1
- package/dist/generic/RunViewResolver.js +9 -10
- package/dist/generic/RunViewResolver.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +97 -41
- package/dist/index.js.map +1 -1
- package/dist/logging/StartupLogger.d.ts +121 -0
- package/dist/logging/StartupLogger.d.ts.map +1 -0
- package/dist/logging/StartupLogger.js +245 -0
- package/dist/logging/StartupLogger.js.map +1 -0
- package/dist/logging/variablesLoggingMiddleware.d.ts.map +1 -1
- package/dist/logging/variablesLoggingMiddleware.js +21 -2
- package/dist/logging/variablesLoggingMiddleware.js.map +1 -1
- package/dist/resolvers/AgentSessionResolver.d.ts +42 -0
- package/dist/resolvers/AgentSessionResolver.d.ts.map +1 -0
- package/dist/resolvers/AgentSessionResolver.js +152 -0
- package/dist/resolvers/AgentSessionResolver.js.map +1 -0
- package/dist/resolvers/EntityPermissionResolver.d.ts +16 -0
- package/dist/resolvers/EntityPermissionResolver.d.ts.map +1 -0
- package/dist/resolvers/EntityPermissionResolver.js +95 -0
- package/dist/resolvers/EntityPermissionResolver.js.map +1 -0
- package/dist/resolvers/RealtimeClientSessionResolver.d.ts +688 -0
- package/dist/resolvers/RealtimeClientSessionResolver.d.ts.map +1 -0
- package/dist/resolvers/RealtimeClientSessionResolver.js +1774 -0
- package/dist/resolvers/RealtimeClientSessionResolver.js.map +1 -0
- package/dist/resolvers/RemoteBrowserActionResolver.d.ts +359 -0
- package/dist/resolvers/RemoteBrowserActionResolver.d.ts.map +1 -0
- package/dist/resolvers/RemoteBrowserActionResolver.js +896 -0
- package/dist/resolvers/RemoteBrowserActionResolver.js.map +1 -0
- package/dist/services/ScheduledJobsService.d.ts.map +1 -1
- package/dist/services/ScheduledJobsService.js +6 -5
- package/dist/services/ScheduledJobsService.js.map +1 -1
- package/package.json +78 -74
- package/src/__tests__/RealtimeClientSessionResolver.test.ts +2605 -0
- package/src/__tests__/RemoteBrowserAudioStream.test.ts +174 -0
- package/src/__tests__/SessionJanitor.test.ts +234 -0
- package/src/__tests__/SessionManager.test.ts +465 -0
- package/src/__tests__/subscriptionRedaction.test.ts +5 -0
- package/src/agentSessions/HostInstance.ts +53 -0
- package/src/agentSessions/SessionJanitor.ts +267 -0
- package/src/agentSessions/SessionManager.ts +446 -0
- package/src/agentSessions/index.ts +27 -0
- package/src/auth/initializeProviders.ts +6 -1
- package/src/context.ts +42 -7
- package/src/generated/generated.ts +3111 -567
- package/src/generic/ResolverBase.ts +1 -1
- package/src/generic/RunViewResolver.ts +9 -9
- package/src/index.ts +98 -41
- package/src/logging/StartupLogger.ts +317 -0
- package/src/logging/variablesLoggingMiddleware.ts +25 -5
- package/src/resolvers/AgentSessionResolver.ts +138 -0
- package/src/resolvers/EntityPermissionResolver.ts +73 -0
- package/src/resolvers/RealtimeClientSessionResolver.ts +2162 -0
- package/src/resolvers/RemoteBrowserActionResolver.ts +907 -0
- package/src/services/ScheduledJobsService.ts +6 -5
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { IMetadataProvider, UserInfo, LogError, RunView } from '@memberjunction/core';
|
|
2
|
+
import {
|
|
3
|
+
MJAIAgentSessionEntity,
|
|
4
|
+
MJAIAgentSessionChannelEntity,
|
|
5
|
+
MJConversationEntity,
|
|
6
|
+
} from '@memberjunction/core-entities';
|
|
7
|
+
import { AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';
|
|
8
|
+
import { RealtimeClientSessionService, RealtimeChannelServerHost } from '@memberjunction/ai-agents';
|
|
9
|
+
import { GetHostInstanceID } from './HostInstance.js';
|
|
10
|
+
|
|
11
|
+
/** Entity names — centralised so the `MJ:`-prefix convention is applied in exactly one place. */
|
|
12
|
+
const SESSION_ENTITY = 'MJ: AI Agent Sessions';
|
|
13
|
+
const SESSION_CHANNEL_ENTITY = 'MJ: AI Agent Session Channels';
|
|
14
|
+
const CONVERSATION_ENTITY = 'MJ: Conversations';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Shape of the observability run ids a realtime voice session persists in `AIAgentSession.Config_`.
|
|
18
|
+
* Read on {@link SessionManager.CloseSession} to finalize the co-agent runs. All fields optional —
|
|
19
|
+
* a non-voice session (or one whose run creation was skipped) carries none of them.
|
|
20
|
+
*/
|
|
21
|
+
interface SessionRunConfig {
|
|
22
|
+
coAgentRunID?: string;
|
|
23
|
+
promptRunID?: string;
|
|
24
|
+
/** The co-agent run's single system-prompt `MJ: AI Agent Run Steps` row id (its Timeline entry). */
|
|
25
|
+
coAgentRunStepID?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Inputs for {@link SessionManager.CreateSession}. `conversationID`/`lastSessionID`/`config`
|
|
30
|
+
* are optional — when no `conversationID` is supplied a fresh Conversation is created and linked.
|
|
31
|
+
*/
|
|
32
|
+
export interface CreateSessionInput {
|
|
33
|
+
/** The agent the session will run. Authorized via `CanRun` before any row is written. */
|
|
34
|
+
agentID: string;
|
|
35
|
+
/** The owning user. Persisted as `AIAgentSession.UserID`; enforced on every inbound envelope. */
|
|
36
|
+
userID: string;
|
|
37
|
+
/** Existing conversation to attach to. If omitted, a new one is created and linked. */
|
|
38
|
+
conversationID?: string;
|
|
39
|
+
/** Prior (closed) session being resumed — chained via `LastSessionID`. */
|
|
40
|
+
lastSessionID?: string;
|
|
41
|
+
/** Free-form, low-traffic session state. Serialized verbatim into `AIAgentSession.Config`. */
|
|
42
|
+
config?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Why a session was closed — persisted to `AIAgentSession.CloseReason` alongside the
|
|
47
|
+
* `Status = 'Closed'` transition so the admin dashboards can distinguish a user hanging up
|
|
48
|
+
* (`Explicit`) from janitor reconciliation (`Janitor`), a graceful host drain (`Shutdown`),
|
|
49
|
+
* or a failure-path teardown (`Error`). `NULL` in the column means "legacy/unknown" — rows
|
|
50
|
+
* closed before this column existed.
|
|
51
|
+
*/
|
|
52
|
+
export type SessionCloseReason = 'Explicit' | 'Janitor' | 'Shutdown' | 'Error';
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Thrown by {@link SessionManager.CreateSession} when the caller lacks `CanRun` on the target
|
|
56
|
+
* agent. No session row is created — denial happens before any write. Distinct error type so the
|
|
57
|
+
* resolver layer can map it to an authorization-shaped GraphQL error rather than a generic failure.
|
|
58
|
+
*/
|
|
59
|
+
export class SessionAuthorizationError extends Error {
|
|
60
|
+
constructor(message: string) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.name = 'SessionAuthorizationError';
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Minimum interval between persisted `LastActiveAt` writes for a single session. A chatty channel
|
|
68
|
+
* (e.g. an audio heartbeat every ~200ms) must not turn into a DB write storm — heartbeats inside
|
|
69
|
+
* this window are coalesced in-memory and dropped. Mirrors the `SetSettingDebounced` philosophy.
|
|
70
|
+
*/
|
|
71
|
+
const HEARTBEAT_MIN_WRITE_INTERVAL_MS = 3_000;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Server-side lifecycle manager for `AIAgentSession` **records** (not the media/socket transport —
|
|
75
|
+
* that arrives in P5). Stateless with respect to the caller: every method takes the request's
|
|
76
|
+
* `contextUser` and request-scoped `IMetadataProvider` so all entity operations run under the
|
|
77
|
+
* correct identity/provider and never pin the process-global provider.
|
|
78
|
+
*
|
|
79
|
+
* The only in-memory state it holds is a small per-session last-heartbeat-write timestamp map used
|
|
80
|
+
* purely to coalesce {@link Heartbeat} writes; it carries no user or provider state across calls.
|
|
81
|
+
*
|
|
82
|
+
* Responsibilities:
|
|
83
|
+
* - **Create** — authorize (`CanRun`), optionally mint a Conversation, persist an `Active` session.
|
|
84
|
+
* - **Close** — terminal transition; disconnect channels; idempotent.
|
|
85
|
+
* - **Heartbeat** — coalesced `LastActiveAt` bump; reactivates `Idle → Active`.
|
|
86
|
+
* - **MarkIdle** — `Active → Idle` transition when the last channel goes quiet.
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* P5 will extend {@link CloseSession} to also abort any in-flight `AIAgentRun` (via its cancellation
|
|
90
|
+
* token) and call `ClientToolRequestManager.ClearSession(...)`; those resources don't exist yet at
|
|
91
|
+
* this layer, so close here only reconciles the durable record + channel rows.
|
|
92
|
+
*/
|
|
93
|
+
export class SessionManager {
|
|
94
|
+
/** session ID (lowercased) → epoch ms of its last persisted `LastActiveAt` write. */
|
|
95
|
+
private heartbeatLastWrite = new Map<string, number>();
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Authorize and create a new session. Flow:
|
|
99
|
+
* 1. `CanRun` check on the agent — denied → {@link SessionAuthorizationError}, no row written.
|
|
100
|
+
* 2. Resolve the conversation (use the supplied one, or create+link a fresh Conversation).
|
|
101
|
+
* 3. Persist the `AIAgentSession` as `Active`, stamped with this host and `LastActiveAt = now`.
|
|
102
|
+
*
|
|
103
|
+
* @returns the saved {@link MJAIAgentSessionEntity}.
|
|
104
|
+
* @throws {SessionAuthorizationError} when the user may not run the agent.
|
|
105
|
+
* @throws {Error} when conversation creation or session save fails.
|
|
106
|
+
*/
|
|
107
|
+
public async CreateSession(
|
|
108
|
+
input: CreateSessionInput,
|
|
109
|
+
contextUser: UserInfo,
|
|
110
|
+
provider: IMetadataProvider,
|
|
111
|
+
): Promise<MJAIAgentSessionEntity> {
|
|
112
|
+
await this.assertCanRun(input.agentID, contextUser);
|
|
113
|
+
|
|
114
|
+
const conversationID = input.conversationID
|
|
115
|
+
?? await this.createConversation(input, contextUser, provider);
|
|
116
|
+
|
|
117
|
+
const session = await this.persistNewSession(input, conversationID, contextUser, provider);
|
|
118
|
+
await this.notifyChannelPluginsSessionStarted(session, contextUser, provider);
|
|
119
|
+
return session;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Close a session (terminal). Sets `Status = 'Closed'` + `ClosedAt = now` + `CloseReason`, then
|
|
124
|
+
* disconnects all of its channel rows. Idempotent: closing an already-`Closed` session is a
|
|
125
|
+
* no-op that returns `true` (and never overwrites the original `CloseReason`). A
|
|
126
|
+
* missing/unloadable session returns `false`.
|
|
127
|
+
*
|
|
128
|
+
* @param closeReason Why the session is being closed. **Defaults to `'Explicit'`** so existing
|
|
129
|
+
* call sites (the user-initiated close mutations) stamp the common case without modification;
|
|
130
|
+
* background callers (janitor sweeps, shutdown drain, error teardowns) must pass their reason
|
|
131
|
+
* explicitly. `NULL` rows remain only for legacy data closed before the column existed.
|
|
132
|
+
*
|
|
133
|
+
* @remarks P5 adds in-flight-run abort + `ClientToolRequestManager.ClearSession` here.
|
|
134
|
+
*/
|
|
135
|
+
public async CloseSession(
|
|
136
|
+
agentSessionID: string,
|
|
137
|
+
contextUser: UserInfo,
|
|
138
|
+
provider: IMetadataProvider,
|
|
139
|
+
closeReason: SessionCloseReason = 'Explicit',
|
|
140
|
+
): Promise<boolean> {
|
|
141
|
+
const session = await this.loadSession(agentSessionID, contextUser, provider);
|
|
142
|
+
if (!session) {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
this.heartbeatLastWrite.delete(agentSessionID.toLowerCase());
|
|
146
|
+
|
|
147
|
+
if (session.Status === 'Closed') {
|
|
148
|
+
// Idempotent — already terminal. Still notify the channel-plugin host so a session
|
|
149
|
+
// whose plugin instances live in THIS process is cleaned up even when another host
|
|
150
|
+
// instance won the close race (the host no-ops for sessions it doesn't hold).
|
|
151
|
+
await this.notifyChannelPluginsSessionClosed(agentSessionID, session.CloseReason ?? null);
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const closed = await this.markSessionClosed(session, closeReason);
|
|
156
|
+
if (!closed) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
await this.disconnectChannels(agentSessionID, contextUser, provider);
|
|
160
|
+
await this.finalizeObservabilityRuns(session, contextUser, provider);
|
|
161
|
+
await this.notifyChannelPluginsSessionClosed(agentSessionID, closeReason);
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Notifies the server-side channel-plugin host that a session started, so it can resolve the
|
|
167
|
+
* ACTIVE `MJ: AI Agent Channels` rows' `ServerPluginClass` plugins (one fresh instance per
|
|
168
|
+
* channel, per session) and fire their start hooks. Strictly best-effort: the host itself
|
|
169
|
+
* never throws, and this guard makes session creation immune to any plugin-layer surprise.
|
|
170
|
+
*/
|
|
171
|
+
private async notifyChannelPluginsSessionStarted(
|
|
172
|
+
session: MJAIAgentSessionEntity,
|
|
173
|
+
contextUser: UserInfo,
|
|
174
|
+
provider: IMetadataProvider,
|
|
175
|
+
): Promise<void> {
|
|
176
|
+
try {
|
|
177
|
+
await RealtimeChannelServerHost.Instance.OnSessionStarted(
|
|
178
|
+
{
|
|
179
|
+
AgentSessionID: session.ID,
|
|
180
|
+
AgentID: session.AgentID,
|
|
181
|
+
UserID: session.UserID,
|
|
182
|
+
ConversationID: session.ConversationID ?? null,
|
|
183
|
+
},
|
|
184
|
+
contextUser,
|
|
185
|
+
provider,
|
|
186
|
+
);
|
|
187
|
+
} catch (e) {
|
|
188
|
+
LogError(`SessionManager.notifyChannelPluginsSessionStarted failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Notifies the server-side channel-plugin host that a session closed (fires each plugin's
|
|
194
|
+
* `OnSessionClosed` hook and schedules disposal). Invoked from EVERY close provenance —
|
|
195
|
+
* explicit hang-up, janitor sweeps, shutdown drain, and error teardowns all funnel through
|
|
196
|
+
* {@link CloseSession}. Strictly best-effort, same posture as the start notification.
|
|
197
|
+
*/
|
|
198
|
+
private async notifyChannelPluginsSessionClosed(
|
|
199
|
+
agentSessionID: string,
|
|
200
|
+
closeReason: SessionCloseReason | null,
|
|
201
|
+
): Promise<void> {
|
|
202
|
+
try {
|
|
203
|
+
await RealtimeChannelServerHost.Instance.OnSessionClosed(agentSessionID, closeReason);
|
|
204
|
+
} catch (e) {
|
|
205
|
+
LogError(`SessionManager.notifyChannelPluginsSessionClosed failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Finalizes the co-agent observability runs a realtime voice session stored in its `Config_`
|
|
211
|
+
* (see `RealtimeClientSessionResolver`). No-op when the config carries no run ids. Tolerant: a
|
|
212
|
+
* malformed config or a finalize failure is swallowed so it can never break session close.
|
|
213
|
+
*/
|
|
214
|
+
private async finalizeObservabilityRuns(
|
|
215
|
+
session: MJAIAgentSessionEntity,
|
|
216
|
+
contextUser: UserInfo,
|
|
217
|
+
provider: IMetadataProvider,
|
|
218
|
+
): Promise<void> {
|
|
219
|
+
const config = this.parseSessionRunConfig(session.Config_);
|
|
220
|
+
if (!config.coAgentRunID && !config.promptRunID && !config.coAgentRunStepID) {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
await new RealtimeClientSessionService().FinalizeCoAgentRun(
|
|
225
|
+
config.coAgentRunID ?? null,
|
|
226
|
+
config.promptRunID ?? null,
|
|
227
|
+
contextUser,
|
|
228
|
+
provider,
|
|
229
|
+
true,
|
|
230
|
+
config.coAgentRunStepID ?? null,
|
|
231
|
+
);
|
|
232
|
+
} catch (e) {
|
|
233
|
+
LogError(`SessionManager.finalizeObservabilityRuns failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Parses the session's `Config_` for observability run ids; returns an empty config on any error. */
|
|
238
|
+
private parseSessionRunConfig(raw: string | null): SessionRunConfig {
|
|
239
|
+
if (!raw) {
|
|
240
|
+
return {};
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
const parsed = JSON.parse(raw) as Partial<SessionRunConfig>;
|
|
244
|
+
return {
|
|
245
|
+
coAgentRunID: typeof parsed.coAgentRunID === 'string' ? parsed.coAgentRunID : undefined,
|
|
246
|
+
promptRunID: typeof parsed.promptRunID === 'string' ? parsed.promptRunID : undefined,
|
|
247
|
+
coAgentRunStepID: typeof parsed.coAgentRunStepID === 'string' ? parsed.coAgentRunStepID : undefined,
|
|
248
|
+
};
|
|
249
|
+
} catch {
|
|
250
|
+
return {};
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Record activity on a session. Coalesces persisted writes so at most one `LastActiveAt` update
|
|
256
|
+
* lands per session per {@link HEARTBEAT_MIN_WRITE_INTERVAL_MS}; intervening calls return `true`
|
|
257
|
+
* without touching the DB. Reactivates an `Idle` session to `Active`. A `Closed` session is not
|
|
258
|
+
* reactivated (returns `false`).
|
|
259
|
+
*/
|
|
260
|
+
public async Heartbeat(
|
|
261
|
+
agentSessionID: string,
|
|
262
|
+
contextUser: UserInfo,
|
|
263
|
+
provider: IMetadataProvider,
|
|
264
|
+
): Promise<boolean> {
|
|
265
|
+
const key = agentSessionID.toLowerCase();
|
|
266
|
+
const reactivating = this.shouldForceWrite(key, provider);
|
|
267
|
+
if (!reactivating && !this.heartbeatWriteDue(key)) {
|
|
268
|
+
return true; // coalesced — skip the DB round-trip
|
|
269
|
+
}
|
|
270
|
+
return this.persistHeartbeat(agentSessionID, contextUser, provider);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Transition an `Active` session to `Idle` (e.g. when its last channel disconnects). No-op when
|
|
275
|
+
* the session is already `Idle` or `Closed`. Returns `true` on success / no-op-needed.
|
|
276
|
+
*/
|
|
277
|
+
public async MarkIdle(
|
|
278
|
+
agentSessionID: string,
|
|
279
|
+
contextUser: UserInfo,
|
|
280
|
+
provider: IMetadataProvider,
|
|
281
|
+
): Promise<boolean> {
|
|
282
|
+
const session = await this.loadSession(agentSessionID, contextUser, provider);
|
|
283
|
+
if (!session) {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
if (session.Status !== 'Active') {
|
|
287
|
+
return true; // only Active → Idle is meaningful
|
|
288
|
+
}
|
|
289
|
+
session.Status = 'Idle';
|
|
290
|
+
return this.saveOrLog(session, 'MarkIdle');
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ----- internals -------------------------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
/** Throws {@link SessionAuthorizationError} unless the user has `CanRun` on the agent. */
|
|
296
|
+
private async assertCanRun(agentID: string, contextUser: UserInfo): Promise<void> {
|
|
297
|
+
const canRun = await AIAgentPermissionHelper.HasPermission(agentID, contextUser, 'run');
|
|
298
|
+
if (!canRun) {
|
|
299
|
+
throw new SessionAuthorizationError(
|
|
300
|
+
`User ${contextUser.Email} is not permitted to open a session for agent ${agentID}`,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Creates and links a new Conversation for the session, returning its ID. */
|
|
306
|
+
private async createConversation(
|
|
307
|
+
input: CreateSessionInput,
|
|
308
|
+
contextUser: UserInfo,
|
|
309
|
+
provider: IMetadataProvider,
|
|
310
|
+
): Promise<string> {
|
|
311
|
+
const conversation = await provider.GetEntityObject<MJConversationEntity>(CONVERSATION_ENTITY, contextUser);
|
|
312
|
+
conversation.NewRecord();
|
|
313
|
+
conversation.UserID = input.userID;
|
|
314
|
+
conversation.Name = 'Agent Session';
|
|
315
|
+
|
|
316
|
+
const saved = await conversation.Save();
|
|
317
|
+
if (!saved) {
|
|
318
|
+
throw new Error(
|
|
319
|
+
`Failed to create Conversation for agent session: ${conversation.LatestResult?.CompleteMessage ?? 'unknown error'}`,
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
return conversation.ID;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Persists the new session row as `Active` and returns the saved entity. */
|
|
326
|
+
private async persistNewSession(
|
|
327
|
+
input: CreateSessionInput,
|
|
328
|
+
conversationID: string,
|
|
329
|
+
contextUser: UserInfo,
|
|
330
|
+
provider: IMetadataProvider,
|
|
331
|
+
): Promise<MJAIAgentSessionEntity> {
|
|
332
|
+
const session = await provider.GetEntityObject<MJAIAgentSessionEntity>(SESSION_ENTITY, contextUser);
|
|
333
|
+
session.NewRecord();
|
|
334
|
+
session.AgentID = input.agentID;
|
|
335
|
+
session.UserID = input.userID;
|
|
336
|
+
session.Status = 'Active';
|
|
337
|
+
session.ConversationID = conversationID;
|
|
338
|
+
session.LastSessionID = input.lastSessionID ?? null;
|
|
339
|
+
session.HostInstanceID = GetHostInstanceID();
|
|
340
|
+
session.Config_ = input.config ?? null;
|
|
341
|
+
session.LastActiveAt = new Date();
|
|
342
|
+
|
|
343
|
+
const saved = await session.Save();
|
|
344
|
+
if (!saved) {
|
|
345
|
+
throw new Error(
|
|
346
|
+
`Failed to create agent session: ${session.LatestResult?.CompleteMessage ?? 'unknown error'}`,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
return session;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Loads a session entity by ID, returning null when it cannot be loaded. */
|
|
353
|
+
private async loadSession(
|
|
354
|
+
agentSessionID: string,
|
|
355
|
+
contextUser: UserInfo,
|
|
356
|
+
provider: IMetadataProvider,
|
|
357
|
+
): Promise<MJAIAgentSessionEntity | null> {
|
|
358
|
+
const session = await provider.GetEntityObject<MJAIAgentSessionEntity>(SESSION_ENTITY, contextUser);
|
|
359
|
+
const loaded = await session.Load(agentSessionID);
|
|
360
|
+
return loaded ? session : null;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Sets `Closed` + `ClosedAt` + `CloseReason` and saves. Returns the save result. */
|
|
364
|
+
private async markSessionClosed(
|
|
365
|
+
session: MJAIAgentSessionEntity,
|
|
366
|
+
closeReason: SessionCloseReason,
|
|
367
|
+
): Promise<boolean> {
|
|
368
|
+
session.Status = 'Closed';
|
|
369
|
+
session.ClosedAt = new Date();
|
|
370
|
+
session.CloseReason = closeReason;
|
|
371
|
+
return this.saveOrLog(session, 'CloseSession');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Marks every channel row of the session `Disconnected` (with `DisconnectedAt`), if not already. */
|
|
375
|
+
private async disconnectChannels(
|
|
376
|
+
agentSessionID: string,
|
|
377
|
+
contextUser: UserInfo,
|
|
378
|
+
provider: IMetadataProvider,
|
|
379
|
+
): Promise<void> {
|
|
380
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
381
|
+
const result = await rv.RunView<MJAIAgentSessionChannelEntity>({
|
|
382
|
+
EntityName: SESSION_CHANNEL_ENTITY,
|
|
383
|
+
ExtraFilter: `AgentSessionID='${agentSessionID}' AND Status <> 'Disconnected'`,
|
|
384
|
+
ResultType: 'entity_object',
|
|
385
|
+
}, contextUser);
|
|
386
|
+
|
|
387
|
+
if (!result.Success) {
|
|
388
|
+
LogError(`SessionManager.disconnectChannels failed to load channels: ${result.ErrorMessage}`);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const now = new Date();
|
|
392
|
+
for (const channel of result.Results) {
|
|
393
|
+
channel.Status = 'Disconnected';
|
|
394
|
+
channel.DisconnectedAt = now;
|
|
395
|
+
await this.saveOrLog(channel, 'disconnectChannels');
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** True once the per-session coalescing window has elapsed since the last persisted write. */
|
|
400
|
+
private heartbeatWriteDue(key: string): boolean {
|
|
401
|
+
const last = this.heartbeatLastWrite.get(key);
|
|
402
|
+
return last == null || (Date.now() - last) >= HEARTBEAT_MIN_WRITE_INTERVAL_MS;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Whether this heartbeat must write regardless of the coalescing window. We force a write the
|
|
407
|
+
* first time we see a session (no cached timestamp) so an `Idle → Active` reactivation is never
|
|
408
|
+
* swallowed by coalescing.
|
|
409
|
+
*/
|
|
410
|
+
private shouldForceWrite(key: string, _provider: IMetadataProvider): boolean {
|
|
411
|
+
return !this.heartbeatLastWrite.has(key);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Loads, bumps `LastActiveAt`, reactivates `Idle → Active`, saves, and records the write time. */
|
|
415
|
+
private async persistHeartbeat(
|
|
416
|
+
agentSessionID: string,
|
|
417
|
+
contextUser: UserInfo,
|
|
418
|
+
provider: IMetadataProvider,
|
|
419
|
+
): Promise<boolean> {
|
|
420
|
+
const session = await this.loadSession(agentSessionID, contextUser, provider);
|
|
421
|
+
if (!session || session.Status === 'Closed') {
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
session.LastActiveAt = new Date();
|
|
425
|
+
if (session.Status === 'Idle') {
|
|
426
|
+
session.Status = 'Active';
|
|
427
|
+
}
|
|
428
|
+
const saved = await this.saveOrLog(session, 'Heartbeat');
|
|
429
|
+
if (saved) {
|
|
430
|
+
this.heartbeatLastWrite.set(agentSessionID.toLowerCase(), Date.now());
|
|
431
|
+
}
|
|
432
|
+
return saved;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Saves an entity, logging `CompleteMessage` on failure. Returns the boolean save result. */
|
|
436
|
+
private async saveOrLog(
|
|
437
|
+
entity: MJAIAgentSessionEntity | MJAIAgentSessionChannelEntity,
|
|
438
|
+
op: string,
|
|
439
|
+
): Promise<boolean> {
|
|
440
|
+
const saved = await entity.Save();
|
|
441
|
+
if (!saved) {
|
|
442
|
+
LogError(`SessionManager.${op} save failed: ${entity.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
443
|
+
}
|
|
444
|
+
return saved;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview AI Agent Session lifecycle substrate (server-side, record + janitor layer).
|
|
3
|
+
*
|
|
4
|
+
* Exposes the session-record lifecycle manager, the orphan-reconciliation janitor, and the
|
|
5
|
+
* per-process host identity helpers. The audio/media (WebRTC) transport and the long-lived
|
|
6
|
+
* realtime agent run are deliberately **not** part of this layer — they arrive in P5.
|
|
7
|
+
*
|
|
8
|
+
* @module @memberjunction/server
|
|
9
|
+
*/
|
|
10
|
+
import { LoadWhiteboardChannelServer, LoadMeetingControlsChannelServer } from '@memberjunction/ai-agents';
|
|
11
|
+
import { LoadRemoteBrowserChannel } from '@memberjunction/remote-browser-server';
|
|
12
|
+
import { LoadSelfHostRemoteBrowser } from '@memberjunction/remote-browser-selfhost';
|
|
13
|
+
|
|
14
|
+
// Tree-shaking prevention: force the server-side channel plugin registrations
|
|
15
|
+
// (`@RegisterClass(BaseRealtimeChannelServer, ...)`) to execute on any static path that touches
|
|
16
|
+
// the session lifecycle — `SessionManager.CreateSession` resolves them via the ClassFactory.
|
|
17
|
+
LoadWhiteboardChannelServer();
|
|
18
|
+
LoadMeetingControlsChannelServer();
|
|
19
|
+
// Remote Browser native channel (client-direct): the lifecycle-only server channel plugin + the
|
|
20
|
+
// Self-Hosted Chrome backend driver (whose default runner launches a local headless Chromium via
|
|
21
|
+
// Playwright — pulled in transitively through the SelfHost package, documented and acceptable).
|
|
22
|
+
LoadRemoteBrowserChannel();
|
|
23
|
+
LoadSelfHostRemoteBrowser();
|
|
24
|
+
|
|
25
|
+
export * from './HostInstance.js';
|
|
26
|
+
export * from './SessionManager.js';
|
|
27
|
+
export * from './SessionJanitor.js';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { configInfo } from '../config.js';
|
|
2
2
|
import { AuthProviderConfig, LogError, LogStatus } from '@memberjunction/core';
|
|
3
3
|
import { AuthProviderFactory } from '@memberjunction/auth-providers';
|
|
4
|
+
import { StartupLogger } from '../logging/StartupLogger.js';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Initialize authentication providers from configuration
|
|
@@ -17,7 +18,11 @@ export function initializeAuthProviders(): void {
|
|
|
17
18
|
try {
|
|
18
19
|
const provider = AuthProviderFactory.createProvider(providerConfig as AuthProviderConfig);
|
|
19
20
|
factory.register(provider);
|
|
20
|
-
|
|
21
|
+
// Per-provider registration detail — verbose-only. The provider NAMES are
|
|
22
|
+
// surfaced compactly in the startup summary `Auth` line at `standard`.
|
|
23
|
+
if (new StartupLogger().IsAtLeast('verbose')) {
|
|
24
|
+
LogStatus(`Registered auth provider: ${provider.name} (type: ${providerConfig.type})`);
|
|
25
|
+
}
|
|
21
26
|
} catch (error) {
|
|
22
27
|
LogError(`Failed to initialize auth provider ${providerConfig.name}: ${error}`);
|
|
23
28
|
}
|
package/src/context.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { IncomingMessage } from 'http';
|
|
2
|
-
import * as url from 'url';
|
|
3
2
|
import { default as jwt } from 'jsonwebtoken';
|
|
4
3
|
import 'reflect-metadata';
|
|
5
4
|
import { Subject, firstValueFrom } from 'rxjs';
|
|
@@ -10,6 +9,7 @@ import { TokenExpiredError, AuthProviderFactory } from '@memberjunction/auth-pro
|
|
|
10
9
|
import { authCache } from './cache.js';
|
|
11
10
|
import { userEmailMap, apiKey, mj_core_schema } from './config.js';
|
|
12
11
|
import { buildBoundaryLogPayload } from './logging/boundaryLogPayload.js';
|
|
12
|
+
import { StartupLogger } from './logging/StartupLogger.js';
|
|
13
13
|
import { DataSourceInfo, UserPayload } from './types.js';
|
|
14
14
|
import { GetReadOnlyDataSource, GetReadWriteDataSource } from './util.js';
|
|
15
15
|
import { v4 as uuidv4 } from 'uuid';
|
|
@@ -30,6 +30,20 @@ import { GetAPIKeyEngine } from '@memberjunction/api-keys';
|
|
|
30
30
|
// long-lived sessions every hour.) Reviewers asked to audit all user access with
|
|
31
31
|
// timestamp/IP/browser — that payload lives in the Details JSON; the table has no
|
|
32
32
|
// dedicated columns. Best-effort throughout: an audit failure NEVER blocks auth.
|
|
33
|
+
/**
|
|
34
|
+
* Memoized "is the server log level `debug`?" check for the per-request log
|
|
35
|
+
* gates below. Resolved once from `telemetry.level` (the single log-level knob)
|
|
36
|
+
* — config is immutable after boot, so caching is safe and keeps the hot request
|
|
37
|
+
* path free of repeated config reads.
|
|
38
|
+
*/
|
|
39
|
+
let isDebugLevelCache: boolean | undefined;
|
|
40
|
+
function isDebugLogLevel(): boolean {
|
|
41
|
+
if (isDebugLevelCache === undefined) {
|
|
42
|
+
isDebugLevelCache = StartupLogger.resolveLevelFromConfig() === 'debug';
|
|
43
|
+
}
|
|
44
|
+
return isDebugLevelCache;
|
|
45
|
+
}
|
|
46
|
+
|
|
33
47
|
const SESSION_AUDIT_TYPE = 'Session Established';
|
|
34
48
|
const LOGIN_FAILED_AUDIT_TYPE = 'Login Failed';
|
|
35
49
|
const SESSION_AUDIT_CACHE_MAX = 50_000;
|
|
@@ -269,9 +283,12 @@ const verifyAsync = async (issuer: string, token: string): Promise<jwt.JwtPayloa
|
|
|
269
283
|
if (jwt && typeof jwt !== 'string' && !err) {
|
|
270
284
|
const payload = jwt.payload ?? jwt;
|
|
271
285
|
|
|
272
|
-
//
|
|
273
|
-
|
|
274
|
-
|
|
286
|
+
// Per-request token confirmation — debug-only (one of the worst
|
|
287
|
+
// "constantly on" offenders on an authenticated server).
|
|
288
|
+
if (isDebugLogLevel()) {
|
|
289
|
+
const userInfo = extractUserInfoFromPayload(payload);
|
|
290
|
+
console.log(`Valid token: ${userInfo.fullName || 'Unknown'} (${userInfo.email || userInfo.preferredUsername || 'Unknown'})`);
|
|
291
|
+
}
|
|
275
292
|
resolve(payload);
|
|
276
293
|
} else {
|
|
277
294
|
console.warn('Invalid token');
|
|
@@ -462,6 +479,22 @@ export const getUserPayload = async (
|
|
|
462
479
|
* Extracts auth headers and builds a RequestContext from an Express request.
|
|
463
480
|
* Shared by both the unified auth middleware and the WebSocket context.
|
|
464
481
|
*/
|
|
482
|
+
/**
|
|
483
|
+
* Extracts the hostname from a request `Origin` header using the WHATWG `URL` API (replacing the
|
|
484
|
+
* deprecated, security-flagged `url.parse()` — Node DEP0169). Returns `undefined` for a missing,
|
|
485
|
+
* empty, or unparseable origin, matching the prior `url.parse().hostname ?? undefined` semantics.
|
|
486
|
+
*/
|
|
487
|
+
function parseRequestHostname(origin: string | undefined): string | undefined {
|
|
488
|
+
if (!origin) {
|
|
489
|
+
return undefined;
|
|
490
|
+
}
|
|
491
|
+
try {
|
|
492
|
+
return new URL(origin).hostname || undefined;
|
|
493
|
+
} catch {
|
|
494
|
+
return undefined;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
465
498
|
function extractAuthInputs(req: IncomingMessage): {
|
|
466
499
|
bearerToken: string;
|
|
467
500
|
sessionId: string;
|
|
@@ -471,7 +504,7 @@ function extractAuthInputs(req: IncomingMessage): {
|
|
|
471
504
|
requestContext: RequestContext;
|
|
472
505
|
} {
|
|
473
506
|
const sessionIdRaw = req.headers['x-session-id'];
|
|
474
|
-
const requestDomain =
|
|
507
|
+
const requestDomain = parseRequestHostname(req.headers.origin);
|
|
475
508
|
const sessionId = sessionIdRaw ? sessionIdRaw.toString() : '';
|
|
476
509
|
const bearerToken = req.headers.authorization ?? '';
|
|
477
510
|
const systemApiKey = String(req.headers['x-mj-api-key']);
|
|
@@ -489,7 +522,7 @@ function extractAuthInputs(req: IncomingMessage): {
|
|
|
489
522
|
return {
|
|
490
523
|
bearerToken,
|
|
491
524
|
sessionId,
|
|
492
|
-
requestDomain
|
|
525
|
+
requestDomain,
|
|
493
526
|
systemApiKey,
|
|
494
527
|
userApiKey,
|
|
495
528
|
requestContext,
|
|
@@ -573,7 +606,9 @@ export const contextFunction =
|
|
|
573
606
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
574
607
|
const reqAny = req as any;
|
|
575
608
|
const operationName: string | undefined = reqAny.body?.operationName;
|
|
576
|
-
|
|
609
|
+
// Per-request GraphQL boundary line — debug-only. Kept (not deleted) so the
|
|
610
|
+
// data is available when an operator opts into debug, but off by default.
|
|
611
|
+
if (operationName !== 'IntrospectionQuery' && isDebugLogLevel()) {
|
|
577
612
|
console.dir(buildBoundaryLogPayload(operationName), { depth: null, breakLength: 200 });
|
|
578
613
|
}
|
|
579
614
|
|