@memberjunction/server 5.40.2 → 5.42.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 +5 -0
- package/dist/agentSessions/index.d.ts.map +1 -0
- package/dist/agentSessions/index.js +31 -0
- package/dist/agentSessions/index.js.map +1 -0
- package/dist/agentSessions/remoteBrowserGoalEngine.d.ts +102 -0
- package/dist/agentSessions/remoteBrowserGoalEngine.d.ts.map +1 -0
- package/dist/agentSessions/remoteBrowserGoalEngine.js +164 -0
- package/dist/agentSessions/remoteBrowserGoalEngine.js.map +1 -0
- package/dist/agentSessions/remoteBrowserGoalRegistry.d.ts +66 -0
- package/dist/agentSessions/remoteBrowserGoalRegistry.d.ts.map +1 -0
- package/dist/agentSessions/remoteBrowserGoalRegistry.js +86 -0
- package/dist/agentSessions/remoteBrowserGoalRegistry.js.map +1 -0
- package/dist/auth/initializeProviders.d.ts.map +1 -1
- package/dist/auth/initializeProviders.js +4 -2
- package/dist/auth/initializeProviders.js.map +1 -1
- package/dist/config.d.ts +7 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +12 -2
- package/dist/config.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 +1296 -49
- package/dist/generated/generated.d.ts.map +1 -1
- package/dist/generated/generated.js +50343 -43421
- 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 +127 -54
- package/dist/index.js.map +1 -1
- package/dist/integration/CustomColumnPromoter.d.ts +108 -0
- package/dist/integration/CustomColumnPromoter.d.ts.map +1 -0
- package/dist/integration/CustomColumnPromoter.js +508 -0
- package/dist/integration/CustomColumnPromoter.js.map +1 -0
- package/dist/logging/StartupLogger.d.ts +177 -0
- package/dist/logging/StartupLogger.d.ts.map +1 -0
- package/dist/logging/StartupLogger.js +354 -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/ExecuteRemoteOperationResolver.d.ts +27 -0
- package/dist/resolvers/ExecuteRemoteOperationResolver.d.ts.map +1 -0
- package/dist/resolvers/ExecuteRemoteOperationResolver.js +136 -0
- package/dist/resolvers/ExecuteRemoteOperationResolver.js.map +1 -0
- package/dist/resolvers/IntegrationDiscoveryResolver.d.ts +101 -1
- package/dist/resolvers/IntegrationDiscoveryResolver.d.ts.map +1 -1
- package/dist/resolvers/IntegrationDiscoveryResolver.js +544 -42
- package/dist/resolvers/IntegrationDiscoveryResolver.js.map +1 -1
- package/dist/resolvers/RealtimeBridgeResolver.d.ts +121 -0
- package/dist/resolvers/RealtimeBridgeResolver.d.ts.map +1 -0
- package/dist/resolvers/RealtimeBridgeResolver.js +533 -0
- package/dist/resolvers/RealtimeBridgeResolver.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 +432 -0
- package/dist/resolvers/RemoteBrowserActionResolver.d.ts.map +1 -0
- package/dist/resolvers/RemoteBrowserActionResolver.js +1108 -0
- package/dist/resolvers/RemoteBrowserActionResolver.js.map +1 -0
- package/dist/resolvers/RunAIAgentResolver.d.ts.map +1 -1
- package/dist/resolvers/RunAIAgentResolver.js +0 -7
- package/dist/resolvers/RunAIAgentResolver.js.map +1 -1
- package/dist/rest/setupRESTEndpoints.d.ts.map +1 -1
- package/dist/rest/setupRESTEndpoints.js +5 -3
- package/dist/rest/setupRESTEndpoints.js.map +1 -1
- 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 +83 -74
- package/src/__tests__/RealtimeBridgeResolver.test.ts +100 -0
- package/src/__tests__/RealtimeClientSessionResolver.test.ts +2605 -0
- package/src/__tests__/RemoteBrowserAudioStream.test.ts +181 -0
- package/src/__tests__/RemoteBrowserGoalEngine.test.ts +144 -0
- package/src/__tests__/SessionJanitor.test.ts +234 -0
- package/src/__tests__/SessionManager.test.ts +465 -0
- package/src/__tests__/remoteBrowserGoalRegistry.test.ts +81 -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 +32 -0
- package/src/agentSessions/remoteBrowserGoalEngine.ts +191 -0
- package/src/agentSessions/remoteBrowserGoalRegistry.ts +122 -0
- package/src/auth/initializeProviders.ts +4 -2
- package/src/config.ts +13 -2
- package/src/context.ts +42 -7
- package/src/generated/generated.ts +33808 -29025
- package/src/generic/ResolverBase.ts +1 -1
- package/src/generic/RunViewResolver.ts +9 -9
- package/src/index.ts +128 -54
- package/src/integration/CustomColumnPromoter.ts +597 -0
- package/src/logging/StartupLogger.ts +441 -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/ExecuteRemoteOperationResolver.ts +108 -0
- package/src/resolvers/IntegrationDiscoveryResolver.ts +396 -37
- package/src/resolvers/RealtimeBridgeResolver.ts +450 -0
- package/src/resolvers/RealtimeClientSessionResolver.ts +2162 -0
- package/src/resolvers/RemoteBrowserActionResolver.ts +1122 -0
- package/src/resolvers/RunAIAgentResolver.ts +1 -9
- package/src/rest/setupRESTEndpoints.ts +5 -3
- 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,32 @@
|
|
|
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
|
+
import { BindRemoteBrowserGoalEngine } from './remoteBrowserGoalEngine.js';
|
|
14
|
+
|
|
15
|
+
// Tree-shaking prevention: force the server-side channel plugin registrations
|
|
16
|
+
// (`@RegisterClass(BaseRealtimeChannelServer, ...)`) to execute on any static path that touches
|
|
17
|
+
// the session lifecycle — `SessionManager.CreateSession` resolves them via the ClassFactory.
|
|
18
|
+
LoadWhiteboardChannelServer();
|
|
19
|
+
LoadMeetingControlsChannelServer();
|
|
20
|
+
// Remote Browser native channel (client-direct): the lifecycle-only server channel plugin + the
|
|
21
|
+
// Self-Hosted Chrome backend driver (whose default runner launches a local headless Chromium via
|
|
22
|
+
// Playwright — pulled in transitively through the SelfHost package, documented and acceptable).
|
|
23
|
+
LoadRemoteBrowserChannel();
|
|
24
|
+
LoadSelfHostRemoteBrowser();
|
|
25
|
+
// Bind goal-driven browser control to MJ's computer-use engine (vision-model auto-selection, prompt-run
|
|
26
|
+
// logging, credential resolution). Without this, RunComputerUseGoal falls back to the bare base engine.
|
|
27
|
+
BindRemoteBrowserGoalEngine();
|
|
28
|
+
|
|
29
|
+
export * from './remoteBrowserGoalEngine.js';
|
|
30
|
+
export * from './HostInstance.js';
|
|
31
|
+
export * from './SessionManager.js';
|
|
32
|
+
export * from './SessionJanitor.js';
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview **Production binding** of the Remote Browser goal-engine seam to MJ's computer-use engine.
|
|
3
|
+
*
|
|
4
|
+
* The CDP remote-browser session ({@link CdpRemoteBrowserSession}) runs goal-driven browser control through
|
|
5
|
+
* an injectable {@link ComputerUseGoalRun} factory. By default that factory yields a bare
|
|
6
|
+
* `ProgressComputerUseEngine` (base computer-use), which has no model auto-selection — so it can't run a goal
|
|
7
|
+
* unsupervised. This module binds the factory to {@link MJProgressComputerUseEngine}: an MJ-aware engine that
|
|
8
|
+
* routes controller/judge prompts through `AIPromptRunner`, auto-selects a vision-capable model from MJ
|
|
9
|
+
* metadata, persists step media, AND forwards per-step progress for live narration.
|
|
10
|
+
*
|
|
11
|
+
* Called once at server startup from `agentSessions/index.ts` (the realtime composition point), so every
|
|
12
|
+
* goal-driven run on this process uses the MJ engine. Kept here (an application package), not in any library,
|
|
13
|
+
* because it is the seam where the transport-neutral CDP layer is wired to MJ's AI stack.
|
|
14
|
+
*
|
|
15
|
+
* @module @memberjunction/server
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { UserInfo, LogError, IMetadataProvider, RunView } from '@memberjunction/core';
|
|
19
|
+
import { MJAIAgentRunStepEntity } from '@memberjunction/core-entities';
|
|
20
|
+
import { initAgentRunStep, finalizeAgentRunStep } from '@memberjunction/ai-core-plus';
|
|
21
|
+
import type { ComputerUseResult, RunComputerUseParams, StepRecord } from '@memberjunction/computer-use';
|
|
22
|
+
import { MJComputerUseEngine, MJRunComputerUseParams } from '@memberjunction/computer-use-engine';
|
|
23
|
+
import type { RemoteBrowserGoalResult } from '@memberjunction/remote-browser-base';
|
|
24
|
+
import { buildProgressNote, CdpRemoteBrowserSession, type ComputerUseGoalProgress, type ComputerUseGoalRun } from '@memberjunction/remote-browser-cdp';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Adapts the transport-neutral base computer-use params into {@link MJRunComputerUseParams}, injecting the
|
|
28
|
+
* acting user so the MJ engine can run its controller/judge prompts as that user. Pure + exported for unit
|
|
29
|
+
* testing; {@link MJProgressComputerUseEngine.Run} is a one-liner over it.
|
|
30
|
+
*
|
|
31
|
+
* @param params The base computer-use params the CDP session built (goal + step cap + start url).
|
|
32
|
+
* @param contextUser The acting MJ user (may be undefined; the MJ engine handles the unset case).
|
|
33
|
+
* @param agentRunID Optional parent agent-run id (links the goal's prompt runs to the realtime agent run).
|
|
34
|
+
* @param agentRunStepID Optional parent agent-run-step id (nests a child prompt step per prompt under it).
|
|
35
|
+
* @returns The MJ-aware params to hand to `MJComputerUseEngine.Run`.
|
|
36
|
+
*/
|
|
37
|
+
export function buildMJGoalParams(params: RunComputerUseParams, contextUser?: UserInfo, agentRunID?: string, agentRunStepID?: string): MJRunComputerUseParams {
|
|
38
|
+
const mjParams = Object.assign(new MJRunComputerUseParams(), params);
|
|
39
|
+
mjParams.ContextUser = contextUser;
|
|
40
|
+
mjParams.AgentRunId = agentRunID;
|
|
41
|
+
mjParams.AgentRunStepID = agentRunStepID;
|
|
42
|
+
return mjParams;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The MJ-aware goal engine bound in production. Extends {@link MJComputerUseEngine} (prompt-runner routing,
|
|
47
|
+
* vision-model auto-selection, credential resolution, media persistence) and satisfies the
|
|
48
|
+
* {@link ComputerUseGoalRun} seam:
|
|
49
|
+
*
|
|
50
|
+
* - {@link SetBrowserAdapter} / {@link Stop} are inherited from the base computer-use engine.
|
|
51
|
+
* - {@link OnProgress} + {@link ContextUser} are set by the CDP session before {@link Run}.
|
|
52
|
+
* - {@link Run} adapts the transport-neutral base params into {@link MJRunComputerUseParams} (injecting the
|
|
53
|
+
* acting user) so the MJ engine can run its prompts.
|
|
54
|
+
* - {@link onStepComplete} chains the MJ media-persistence behavior, then forwards a model-safe progress note.
|
|
55
|
+
*/
|
|
56
|
+
export class MJProgressComputerUseEngine extends MJComputerUseEngine implements ComputerUseGoalRun {
|
|
57
|
+
/** Per-step progress hook the CDP session sets before {@link Run} (drives live narration). */
|
|
58
|
+
public OnProgress?: (progress: ComputerUseGoalProgress) => void;
|
|
59
|
+
|
|
60
|
+
/** The MJ user the goal run executes as; the CDP session sets it from the session's context user. */
|
|
61
|
+
public ContextUser?: UserInfo;
|
|
62
|
+
|
|
63
|
+
/** Parent agent-run id the CDP session sets before {@link Run} (links the goal's prompt runs to it). */
|
|
64
|
+
public AgentRunID?: string;
|
|
65
|
+
|
|
66
|
+
/** Parent agent-run-step id the CDP session sets before {@link Run} (nests child prompt steps under it). */
|
|
67
|
+
public AgentRunStepID?: string;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Adapts the transport-neutral base params into {@link MJRunComputerUseParams} (carrying the acting user
|
|
71
|
+
* + the parent run/step linkage) and delegates to the MJ engine, which auto-selects a vision-capable
|
|
72
|
+
* controller model from MJ metadata and nests a child step per prompt when the linkage is present.
|
|
73
|
+
*
|
|
74
|
+
* @param params The base computer-use params the CDP session built (goal + step cap + start url).
|
|
75
|
+
* @returns The computer-use run result.
|
|
76
|
+
*/
|
|
77
|
+
public override async Run(params: RunComputerUseParams): Promise<ComputerUseResult> {
|
|
78
|
+
return super.Run(buildMJGoalParams(params, this.ContextUser, this.AgentRunID, this.AgentRunStepID));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
protected override onStepComplete(step: StepRecord, params: MJRunComputerUseParams): void {
|
|
82
|
+
super.onStepComplete(step, params); // keep MJ media persistence
|
|
83
|
+
this.OnProgress?.(buildProgressNote(step)); // shared note shape with the base ProgressComputerUseEngine
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Extracts the realtime co-agent observability run id from an `AIAgentSession.Config_` JSON blob (the
|
|
89
|
+
* `coAgentRunID` a voice session persists). Returns `undefined` for a missing/non-voice/un-parseable
|
|
90
|
+
* config — goal-run observability is best-effort and degrades to "no parent run" cleanly.
|
|
91
|
+
*
|
|
92
|
+
* @param configJson The session's `Config_` string.
|
|
93
|
+
* @returns The co-agent run id, or `undefined`.
|
|
94
|
+
*/
|
|
95
|
+
export function extractCoAgentRunID(configJson: string | null | undefined): string | undefined {
|
|
96
|
+
if (!configJson) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const parsed = JSON.parse(configJson) as { coAgentRunID?: unknown };
|
|
101
|
+
return typeof parsed.coAgentRunID === 'string' ? parsed.coAgentRunID : undefined;
|
|
102
|
+
} catch {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Truncates a goal to a step-name-friendly length. */
|
|
108
|
+
function goalStepName(goal: string): string {
|
|
109
|
+
const trimmed = goal.trim();
|
|
110
|
+
return `Browser goal: ${trimmed.length > 120 ? `${trimmed.slice(0, 120)}…` : trimmed}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Creates the parent `Tool` step ("Browser goal: …") on the realtime co-agent run for a goal-driven browser
|
|
115
|
+
* run — a single top-level timeline node the computer-use prompt steps then nest under. Best-effort: returns
|
|
116
|
+
* `null` (so the goal still runs, just unlinked) when there's no co-agent run to attach to, or on any error.
|
|
117
|
+
* Uses the shared {@link initAgentRunStep} helper so the field shape matches every other agent-run step.
|
|
118
|
+
*
|
|
119
|
+
* @param provider The metadata provider.
|
|
120
|
+
* @param contextUser The acting user.
|
|
121
|
+
* @param coAgentRunID The realtime co-agent run id (the parent run), or `undefined`.
|
|
122
|
+
* @param goal The natural-language goal (becomes the step name).
|
|
123
|
+
* @returns The saved parent step (to finalize + nest under), or `null`.
|
|
124
|
+
*/
|
|
125
|
+
export async function beginBrowserGoalStep(
|
|
126
|
+
provider: IMetadataProvider,
|
|
127
|
+
contextUser: UserInfo | undefined,
|
|
128
|
+
coAgentRunID: string | undefined,
|
|
129
|
+
goal: string,
|
|
130
|
+
): Promise<MJAIAgentRunStepEntity | null> {
|
|
131
|
+
if (!coAgentRunID) {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
const rv = new RunView();
|
|
136
|
+
const countResult = await rv.RunView(
|
|
137
|
+
{ EntityName: 'MJ: AI Agent Run Steps', ExtraFilter: `AgentRunID='${coAgentRunID.replace(/'/g, "''")}'`, Fields: ['ID'], ResultType: 'simple' },
|
|
138
|
+
contextUser,
|
|
139
|
+
);
|
|
140
|
+
const stepNumber = (countResult.Success ? (countResult.Results?.length ?? 0) : 0) + 1;
|
|
141
|
+
const step = await provider.GetEntityObject<MJAIAgentRunStepEntity>('MJ: AI Agent Run Steps', contextUser);
|
|
142
|
+
step.NewRecord();
|
|
143
|
+
initAgentRunStep(step, { AgentRunID: coAgentRunID, StepNumber: stepNumber, StepType: 'Tool', StepName: goalStepName(goal) });
|
|
144
|
+
if (await step.Save()) {
|
|
145
|
+
return step;
|
|
146
|
+
}
|
|
147
|
+
LogError(`[RemoteBrowserGoalEngine] beginBrowserGoalStep save failed: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
148
|
+
return null;
|
|
149
|
+
} catch (err) {
|
|
150
|
+
LogError(`[RemoteBrowserGoalEngine] beginBrowserGoalStep threw: ${err instanceof Error ? err.message : String(err)}`);
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Finalizes the parent browser-goal step from the goal outcome — `Completed`/`Failed` with an `OutputData`
|
|
157
|
+
* envelope of strategy/status/step-count/url. A no-op when `step` is `null`. Best-effort (logged, never thrown).
|
|
158
|
+
*
|
|
159
|
+
* @param step The parent step from {@link beginBrowserGoalStep} (or `null`).
|
|
160
|
+
* @param result The goal outcome.
|
|
161
|
+
*/
|
|
162
|
+
export async function finalizeBrowserGoalStep(step: MJAIAgentRunStepEntity | null, result: RemoteBrowserGoalResult): Promise<void> {
|
|
163
|
+
if (!step) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
finalizeAgentRunStep(step, {
|
|
168
|
+
success: result.Success,
|
|
169
|
+
errorMessage: result.Success ? undefined : result.Detail,
|
|
170
|
+
outputData: { strategy: result.Strategy, status: result.Status, stepCount: result.StepCount, currentUrl: result.CurrentUrl },
|
|
171
|
+
});
|
|
172
|
+
if (!(await step.Save())) {
|
|
173
|
+
LogError(`[RemoteBrowserGoalEngine] finalizeBrowserGoalStep save failed: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
174
|
+
}
|
|
175
|
+
} catch (err) {
|
|
176
|
+
LogError(`[RemoteBrowserGoalEngine] finalizeBrowserGoalStep threw: ${err instanceof Error ? err.message : String(err)}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Binds the CDP goal-engine factory to {@link MJProgressComputerUseEngine}. Idempotent and safe to call at
|
|
182
|
+
* startup; failures are logged (never thrown) so a binding hiccup can't abort server boot — goal runs would
|
|
183
|
+
* simply fall back to the base engine.
|
|
184
|
+
*/
|
|
185
|
+
export function BindRemoteBrowserGoalEngine(): void {
|
|
186
|
+
try {
|
|
187
|
+
CdpRemoteBrowserSession.SetGoalEngineFactory(() => new MJProgressComputerUseEngine());
|
|
188
|
+
} catch (err) {
|
|
189
|
+
LogError(`[RemoteBrowserGoalEngine] Failed to bind MJ computer-use goal engine: ${err instanceof Error ? err.message : String(err)}`);
|
|
190
|
+
}
|
|
191
|
+
}
|