@memberjunction/conversations-runtime 0.0.1 → 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.
Files changed (50) hide show
  1. package/README.md +99 -43
  2. package/dist/ConversationsRuntime.d.ts +193 -0
  3. package/dist/ConversationsRuntime.d.ts.map +1 -0
  4. package/dist/ConversationsRuntime.js +268 -0
  5. package/dist/ConversationsRuntime.js.map +1 -0
  6. package/dist/adapters/IActiveTaskTracker.d.ts +49 -0
  7. package/dist/adapters/IActiveTaskTracker.d.ts.map +1 -0
  8. package/dist/adapters/IActiveTaskTracker.js +26 -0
  9. package/dist/adapters/IActiveTaskTracker.js.map +1 -0
  10. package/dist/adapters/INotificationAdapter.d.ts +60 -0
  11. package/dist/adapters/INotificationAdapter.d.ts.map +1 -0
  12. package/dist/adapters/INotificationAdapter.js +45 -0
  13. package/dist/adapters/INotificationAdapter.js.map +1 -0
  14. package/dist/adapters/ISessionsAdapter.d.ts +124 -0
  15. package/dist/adapters/ISessionsAdapter.d.ts.map +1 -0
  16. package/dist/adapters/ISessionsAdapter.js +44 -0
  17. package/dist/adapters/ISessionsAdapter.js.map +1 -0
  18. package/dist/agent-runner/ConversationAgentRunner.d.ts +121 -0
  19. package/dist/agent-runner/ConversationAgentRunner.d.ts.map +1 -0
  20. package/dist/agent-runner/ConversationAgentRunner.js +191 -0
  21. package/dist/agent-runner/ConversationAgentRunner.js.map +1 -0
  22. package/dist/bridge/ConversationBridge.d.ts +93 -0
  23. package/dist/bridge/ConversationBridge.d.ts.map +1 -0
  24. package/dist/bridge/ConversationBridge.js +105 -0
  25. package/dist/bridge/ConversationBridge.js.map +1 -0
  26. package/dist/context/IConversationsRuntimeContext.d.ts +29 -0
  27. package/dist/context/IConversationsRuntimeContext.d.ts.map +1 -0
  28. package/dist/context/IConversationsRuntimeContext.js +21 -0
  29. package/dist/context/IConversationsRuntimeContext.js.map +1 -0
  30. package/dist/default-agent/DefaultAgentResolver.d.ts +87 -0
  31. package/dist/default-agent/DefaultAgentResolver.d.ts.map +1 -0
  32. package/dist/default-agent/DefaultAgentResolver.js +103 -0
  33. package/dist/default-agent/DefaultAgentResolver.js.map +1 -0
  34. package/dist/index.d.ts +22 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +28 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/mentions/MentionParser.d.ts +109 -0
  39. package/dist/mentions/MentionParser.d.ts.map +1 -0
  40. package/dist/mentions/MentionParser.js +276 -0
  41. package/dist/mentions/MentionParser.js.map +1 -0
  42. package/dist/sessions/SessionsObserver.d.ts +87 -0
  43. package/dist/sessions/SessionsObserver.d.ts.map +1 -0
  44. package/dist/sessions/SessionsObserver.js +103 -0
  45. package/dist/sessions/SessionsObserver.js.map +1 -0
  46. package/dist/streaming/ConversationStreaming.d.ts +169 -0
  47. package/dist/streaming/ConversationStreaming.d.ts.map +1 -0
  48. package/dist/streaming/ConversationStreaming.js +355 -0
  49. package/dist/streaming/ConversationStreaming.js.map +1 -0
  50. package/package.json +33 -7
package/README.md CHANGED
@@ -1,45 +1,101 @@
1
1
  # @memberjunction/conversations-runtime
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
4
-
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
-
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@memberjunction/conversations-runtime`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
3
+ Framework-agnostic runtime layer for MemberJunction conversational AI experiences.
4
+
5
+ ## What this package is
6
+
7
+ The pure-TypeScript orchestration layer that sits beneath every chat surface in MJ — overlay, embedded panel, full-page Chat workspace, and any future custom UX. **Zero UX dependencies**, **client + server consumable**.
8
+
9
+ ```
10
+ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐
11
+ │ ANGULAR APPS │ │ NON-ANGULAR JS APPS │
12
+ │ (MJ Explorer, Angular widgets) │ │ (React, Vue, Node workers, CLI) │
13
+ └──────────────────────────────────────┘ └──────────────────────────────────────┘
14
+ │ │
15
+ ▼ │
16
+ @memberjunction/ng-conversations │
17
+ (Angular widget wrapper) │
18
+ │ │
19
+ └──────────────────┬─────────────────────────┘
20
+ ▼
21
+ @memberjunction/conversations-runtime ★ this package
22
+ │
23
+ ▼
24
+ @memberjunction/core-entities (ConversationEngine — data layer)
25
+ ```
26
+
27
+ ## What it provides
28
+
29
+ | Sub-component | Purpose |
30
+ |---|---|
31
+ | `Mentions` | Parse `@`-mentions out of message text (JSON + legacy formats). Pure string logic. |
32
+ | `Bridge` | Coordinate active-conversation state between the corner overlay and the full-page workspace. |
33
+ | `DefaultAgent` | Resolve which agent handles a conversation turn via Application-Settings-driven chain (explicit → app-scoped → global → code-const Sage fallback). |
34
+ | `Tools` | The shared `ClientToolRegistry` from `@memberjunction/ai-agent-client` — register tools the agent can invoke on the client. |
35
+ | `AgentRunner` | Orchestrates `processMessage` — resolves the target agent, filters candidates, dispatches via `AgentClientSession`. |
36
+ | `Streaming` | Routes per-message progress + completion events from the server's PubSub channel to consumer callbacks. |
37
+ | `Sessions` | Observability over the AI Agent Sessions/Channels infrastructure from PR #2787. Hosts register an `ISessionsAdapter` at bootstrap; the runtime re-broadcasts session lifecycle events as `'session-started' \| 'session-channel' \| 'session-ended'`. |
38
+
39
+ ## Adapter slots (the host-runtime boundary)
40
+
41
+ The runtime needs UI affordances (toasts, active-task indicators, session lifecycle observability) but cannot import any framework. Hosts implement small interfaces and register them at bootstrap:
42
+
43
+ | Interface | What the runtime calls | Default (no host wiring) |
44
+ |---|---|---|
45
+ | `INotificationAdapter` | `Notify(level, message, ttlMs?)` | `ConsoleNotificationAdapter` (console.log/warn/error) |
46
+ | `IActiveTaskTracker` | `RemoveByAgentRunId(agentRunId)` | `NoOpActiveTaskTracker` |
47
+ | `ISessionsAdapter` | (observable) `SessionLifecycle$` | `NoOpSessionsAdapter` (EMPTY observable) |
48
+
49
+ Registration:
50
+ ```typescript
51
+ ConversationsRuntime.Instance.UseNotificationAdapter({ Notify: (...) => {} });
52
+ ConversationsRuntime.Instance.UseActiveTaskTracker({ RemoveByAgentRunId: (...) => {} });
53
+ ConversationsRuntime.Instance.UseSessionsAdapter(myAdapter);
54
+ ```
55
+
56
+ In `@memberjunction/ng-conversations`, `ConversationsRuntimeBootstrap` registers all three automatically on first DI injection.
57
+
58
+ ## Pre-warming
59
+
60
+ `ConversationsRuntime` is decorated with `@RegisterForStartup({ deferred: true, deferredDelay: 5000, severity: 'warn' })`. 5 seconds after app boot, the MJ startup manager fires `HandleStartup()`, which calls `Config(false)` — pre-loading dependent engines in the background. Non-blocking; failures log as warnings.
61
+
62
+ ## Quick start
63
+
64
+ ```typescript
65
+ import { ConversationsRuntime } from '@memberjunction/conversations-runtime';
66
+
67
+ // At app boot — lazy, idempotent, no penalty if called per entry point
68
+ await ConversationsRuntime.Instance.Config(false, contextUser);
69
+
70
+ // Parse a mention out of user text
71
+ const mentions = ConversationsRuntime.Instance.Mentions.parseMentions(
72
+ '@Sage help me',
73
+ AIEngineBase.Instance.Agents
74
+ );
75
+
76
+ // Resolve the default agent for the current application
77
+ const agent = await ConversationsRuntime.Instance.DefaultAgent.resolve({
78
+ applicationId: currentAppId,
79
+ });
80
+
81
+ // Register a client tool the agent can invoke
82
+ ConversationsRuntime.Instance.Tools.Register({
83
+ Name: 'NavigateToRecord',
84
+ Description: 'Open an entity record in the UI',
85
+ ParameterSchema: { type: 'object', properties: { EntityName: { type: 'string' } } },
86
+ Handler: async (params) => {
87
+ // ... your navigation code ...
88
+ return { Success: true };
89
+ },
90
+ });
91
+ ```
92
+
93
+ ## Multi-provider support
94
+
95
+ Every API accepts an optional `provider?: IMetadataProvider` parameter and falls back to `Metadata.Provider` when omitted. Apps connecting to multiple MJ servers in parallel should pass an explicit provider to scope the runtime to that server.
96
+
97
+ ## Documentation
98
+
99
+ - See [`guides/CONVERSATIONS_UX_STACK_GUIDE.md`](../../guides/CONVERSATIONS_UX_STACK_GUIDE.md) for the full three-layer stack reference — slots, events, tokens, default-agent resolution, sessions adapter, multi-provider considerations, recipes.
100
+ - See [`guides/REALTIME_CO_AGENTS_GUIDE.md`](../../guides/REALTIME_CO_AGENTS_GUIDE.md) (PR #2787) for the Sessions/Channels/realtime infrastructure this runtime bridges to.
101
+ - See [`plans/conversations-runtime-extraction.md`](../../plans/conversations-runtime-extraction.md) for the design rationale.
@@ -0,0 +1,193 @@
1
+ /**
2
+ * @fileoverview Top-level runtime singleton for the conversations stack.
3
+ *
4
+ * `ConversationsRuntime` is the single composition root for the orchestration concerns of
5
+ * MJ's conversational AI experiences. It holds and exposes the sub-components (mentions,
6
+ * bridge, default-agent resolver, client-tool registry, sessions observer, streaming,
7
+ * agent runner) and provides a lazy `Config()` for boot-time loading of the engines
8
+ * it depends on.
9
+ *
10
+ * It follows MJ's established `BaseEngine` / `BaseSingleton` idiom — singleton via the
11
+ * global object store, idempotent lazy `Config()`, and an explicit `Instance` accessor.
12
+ *
13
+ * **Two engines, two concerns.** This runtime is NOT a wrapper around `ConversationEngine`
14
+ * (data layer in `@memberjunction/core-entities`). Data CRUD goes through
15
+ * `ConversationEngine.Instance`; orchestration goes through `ConversationsRuntime.Instance`.
16
+ * The runtime delegates to the data engine where needed but does not re-export its API.
17
+ *
18
+ * **Adapter pattern.** The runtime is framework-agnostic but needs to surface
19
+ * notifications and clear running tasks in the host's UI. Hosts inject adapters via
20
+ * {@link UseNotificationAdapter} / {@link UseActiveTaskTracker} at bootstrap. Defaults
21
+ * (`ConsoleNotificationAdapter`, `NoOpActiveTaskTracker`) keep the runtime usable
22
+ * out of the box for server-side / headless callers.
23
+ *
24
+ * @module @memberjunction/conversations-runtime
25
+ */
26
+ import { BaseEngine, IMetadataProvider, IStartupSink, UserInfo } from '@memberjunction/core';
27
+ import { ClientToolRegistry } from '@memberjunction/ai-agent-client';
28
+ import { MentionParser } from './mentions/MentionParser.js';
29
+ import { ConversationBridge } from './bridge/ConversationBridge.js';
30
+ import { DefaultAgentResolver } from './default-agent/DefaultAgentResolver.js';
31
+ import { SessionsObserver } from './sessions/SessionsObserver.js';
32
+ import { ConversationStreaming } from './streaming/ConversationStreaming.js';
33
+ import { ConversationAgentRunner } from './agent-runner/ConversationAgentRunner.js';
34
+ import { INotificationAdapter } from './adapters/INotificationAdapter.js';
35
+ import { IActiveTaskTracker } from './adapters/IActiveTaskTracker.js';
36
+ import { ISessionsAdapter } from './adapters/ISessionsAdapter.js';
37
+ import { IConversationsRuntimeContext } from './context/IConversationsRuntimeContext.js';
38
+ /**
39
+ * The framework-agnostic conversations runtime.
40
+ *
41
+ * **Lifecycle:** call `Config(false, contextUser, provider)` at every entry point that
42
+ * uses the runtime — it's idempotent, so only the first caller pays the load cost. The
43
+ * rest are O(1) cache hits.
44
+ *
45
+ * **Adapters:** at host bootstrap, supply UI adapters via
46
+ * {@link UseNotificationAdapter} / {@link UseActiveTaskTracker}. Until you do, the
47
+ * defaults log to the console and no-op respectively.
48
+ *
49
+ * **Multi-provider:** when an explicit provider is passed to `Config()`, the runtime
50
+ * scopes its dependent engines (`AIEngineBase`, `ApplicationSettingEngine`,
51
+ * `ConversationEngine`) to that provider. Single-provider apps omit the parameter and
52
+ * get the global default.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * import { ConversationsRuntime } from '@memberjunction/conversations-runtime';
57
+ *
58
+ * // At every entry point (no-op after the first call)
59
+ * await ConversationsRuntime.Instance.Config(false, contextUser);
60
+ *
61
+ * // Wire UI adapters once at bootstrap
62
+ * ConversationsRuntime.Instance.UseNotificationAdapter({
63
+ * Notify: (level, msg, ttl) =>
64
+ * MJNotificationService.Instance.CreateSimpleNotification(msg, level, ttl ?? 5000),
65
+ * });
66
+ *
67
+ * // Process a message through the default conversation manager agent
68
+ * const result = await ConversationsRuntime.Instance.AgentRunner.processMessage({
69
+ * conversationId,
70
+ * message,
71
+ * conversationDetailId,
72
+ * applicationId,
73
+ * });
74
+ * ```
75
+ */
76
+ export declare class ConversationsRuntime extends BaseEngine<ConversationsRuntime> implements IConversationsRuntimeContext, IStartupSink {
77
+ /**
78
+ * The singleton instance. Backed by the Global Object Store so the same instance is
79
+ * shared even when bundlers duplicate this module across code splits.
80
+ */
81
+ static get Instance(): ConversationsRuntime;
82
+ private _notification;
83
+ private _tasks;
84
+ /**
85
+ * Currently registered notification adapter — used by sub-components to surface
86
+ * user-visible messages. Defaults to {@link ConsoleNotificationAdapter}.
87
+ *
88
+ * Implements {@link IConversationsRuntimeContext.Notification}.
89
+ */
90
+ get Notification(): INotificationAdapter;
91
+ /**
92
+ * Currently registered active-task tracker — used by `ConversationStreaming` to
93
+ * clear running tasks when an agent run completes. Defaults to
94
+ * {@link NoOpActiveTaskTracker}.
95
+ *
96
+ * Implements {@link IConversationsRuntimeContext.Tasks}.
97
+ */
98
+ get Tasks(): IActiveTaskTracker;
99
+ /**
100
+ * Register a notification adapter — typically called once at host bootstrap.
101
+ * The new adapter takes effect immediately; sub-components read it from the
102
+ * context on every call.
103
+ */
104
+ UseNotificationAdapter(adapter: INotificationAdapter): void;
105
+ /**
106
+ * Register an active-task tracker — typically called once at host bootstrap.
107
+ * The new tracker takes effect immediately.
108
+ */
109
+ UseActiveTaskTracker(tracker: IActiveTaskTracker): void;
110
+ /**
111
+ * Register a sessions adapter — bridges the host's realtime session source
112
+ * (e.g., Angular's `RealtimeSessionService`) to the framework-agnostic runtime
113
+ * `Sessions` observer. Typically called once at host bootstrap; multiple
114
+ * swaps are supported (test harnesses, modality additions).
115
+ *
116
+ * Delegates to {@link SessionsObserver.UseSessionsAdapter}, which cleanly
117
+ * tears down any prior adapter subscription before subscribing to the new
118
+ * one. The new adapter takes effect immediately for all subscribers of
119
+ * `Sessions.SessionLifecycle$`.
120
+ */
121
+ UseSessionsAdapter(adapter: ISessionsAdapter): void;
122
+ private readonly _mentions;
123
+ private readonly _bridge;
124
+ private readonly _tools;
125
+ private readonly _defaultAgent;
126
+ private readonly _sessions;
127
+ private _streaming?;
128
+ private _agentRunner?;
129
+ /** Mention parser — pure string logic. See {@link MentionParser}. */
130
+ get Mentions(): MentionParser;
131
+ /** Overlay ⇄ workspace coordination bus. See {@link ConversationBridge}. */
132
+ get Bridge(): ConversationBridge;
133
+ /**
134
+ * Shared client-tool registry — the same `ClientToolRegistry` from
135
+ * `@memberjunction/ai-agent-client` that `AgentClientSession` consumes. Apps register
136
+ * tools here once at startup; every session sees them.
137
+ */
138
+ get Tools(): ClientToolRegistry;
139
+ /** Default-agent resolution chain. See {@link DefaultAgentResolver}. */
140
+ get DefaultAgent(): DefaultAgentResolver;
141
+ /**
142
+ * Sessions/Channels lifecycle observer — surfaces realtime session lifecycle
143
+ * events from the registered {@link ISessionsAdapter}. Defaults to a no-op
144
+ * adapter so headless consumers still construct cleanly; the Angular host's
145
+ * `ConversationsRuntimeBootstrap` swaps in a `RealtimeSessionsAdapter` that
146
+ * bridges `RealtimeSessionService` from PR #2787.
147
+ *
148
+ * Subscribe to `Sessions.SessionLifecycle$` for `session-started` /
149
+ * `session-channel` / `session-ended` events. See {@link SessionsObserver}.
150
+ */
151
+ get Sessions(): SessionsObserver;
152
+ /**
153
+ * PubSub streaming layer — routes progress and completion events from the server
154
+ * to per-message callbacks. See {@link ConversationStreaming}.
155
+ *
156
+ * Hosts must call `.initialize()` once after `Config()` to open the subscription.
157
+ */
158
+ get Streaming(): ConversationStreaming;
159
+ /**
160
+ * Agent-run orchestrator — wraps `AgentClientSession.RunAgentFromConversationDetail`
161
+ * with default-agent resolution and permission-filtered candidate lists. See
162
+ * {@link ConversationAgentRunner}.
163
+ */
164
+ get AgentRunner(): ConversationAgentRunner;
165
+ /**
166
+ * Lazy-load the engines this runtime depends on (`AIEngineBase`,
167
+ * `ApplicationSettingEngine`, `ConversationEngine`). Safe to call from every entry
168
+ * point — only the first invocation pays the load cost.
169
+ *
170
+ * The runtime itself currently has no `BaseEnginePropertyConfig` entries — the data
171
+ * lives in the dependent engines. We override `Config()` rather than delegating to
172
+ * `super.Load()` because we're a composition root, not a data cache.
173
+ *
174
+ * @param forceRefresh Refresh the dependent engines' caches.
175
+ * @param contextUser Required on the server; ignored when omitted on the browser.
176
+ * @param provider Bind to a specific metadata provider; falls back to `Metadata.Provider`.
177
+ */
178
+ Config(forceRefresh?: boolean, contextUser?: UserInfo, provider?: IMetadataProvider): Promise<void>;
179
+ /**
180
+ * {@link IStartupSink} entry point fired by the MJ startup manager when this class
181
+ * is registered via `@RegisterForStartup`. Pre-warms the runtime so the first user
182
+ * to open a conversations surface doesn't pay the load cost. Deferred + non-blocking
183
+ * per the decorator config — failures are logged (`severity: 'warn'`) but never
184
+ * block app boot.
185
+ */
186
+ HandleStartup(contextUser?: UserInfo, provider?: IMetadataProvider): Promise<void>;
187
+ /**
188
+ * Tear down sub-components that hold subscriptions. Safe to call at app shutdown or
189
+ * in tests between cases.
190
+ */
191
+ Dispose(): void;
192
+ }
193
+ //# sourceMappingURL=ConversationsRuntime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConversationsRuntime.d.ts","sourceRoot":"","sources":["../src/ConversationsRuntime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,YAAY,EAAsB,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAGjH,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EACH,oBAAoB,EAEvB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACH,kBAAkB,EAErB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACH,gBAAgB,EACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,qBAMa,oBACT,SAAQ,UAAU,CAAC,oBAAoB,CACvC,YAAW,4BAA4B,EAAE,YAAY;IAErD;;;OAGG;IACH,WAAkB,QAAQ,IAAI,oBAAoB,CAEjD;IAMD,OAAO,CAAC,aAAa,CAA0D;IAC/E,OAAO,CAAC,MAAM,CAAmD;IAEjE;;;;;OAKG;IACH,IAAW,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G,OAAO,CAAC,IAAI,CAAC;IAI/F;;;OAGG;IACI,OAAO,IAAI,IAAI;CAQzB"}
@@ -0,0 +1,268 @@
1
+ /**
2
+ * @fileoverview Top-level runtime singleton for the conversations stack.
3
+ *
4
+ * `ConversationsRuntime` is the single composition root for the orchestration concerns of
5
+ * MJ's conversational AI experiences. It holds and exposes the sub-components (mentions,
6
+ * bridge, default-agent resolver, client-tool registry, sessions observer, streaming,
7
+ * agent runner) and provides a lazy `Config()` for boot-time loading of the engines
8
+ * it depends on.
9
+ *
10
+ * It follows MJ's established `BaseEngine` / `BaseSingleton` idiom — singleton via the
11
+ * global object store, idempotent lazy `Config()`, and an explicit `Instance` accessor.
12
+ *
13
+ * **Two engines, two concerns.** This runtime is NOT a wrapper around `ConversationEngine`
14
+ * (data layer in `@memberjunction/core-entities`). Data CRUD goes through
15
+ * `ConversationEngine.Instance`; orchestration goes through `ConversationsRuntime.Instance`.
16
+ * The runtime delegates to the data engine where needed but does not re-export its API.
17
+ *
18
+ * **Adapter pattern.** The runtime is framework-agnostic but needs to surface
19
+ * notifications and clear running tasks in the host's UI. Hosts inject adapters via
20
+ * {@link UseNotificationAdapter} / {@link UseActiveTaskTracker} at bootstrap. Defaults
21
+ * (`ConsoleNotificationAdapter`, `NoOpActiveTaskTracker`) keep the runtime usable
22
+ * out of the box for server-side / headless callers.
23
+ *
24
+ * @module @memberjunction/conversations-runtime
25
+ */
26
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
27
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
28
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
29
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
30
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
31
+ };
32
+ import { BaseEngine, RegisterForStartup } from '@memberjunction/core';
33
+ import { AIEngineBase } from '@memberjunction/ai-engine-base';
34
+ import { ApplicationSettingEngine, ConversationEngine } from '@memberjunction/core-entities';
35
+ import { ClientToolRegistry } from '@memberjunction/ai-agent-client';
36
+ import { MentionParser } from './mentions/MentionParser.js';
37
+ import { ConversationBridge } from './bridge/ConversationBridge.js';
38
+ import { DefaultAgentResolver } from './default-agent/DefaultAgentResolver.js';
39
+ import { SessionsObserver } from './sessions/SessionsObserver.js';
40
+ import { ConversationStreaming } from './streaming/ConversationStreaming.js';
41
+ import { ConversationAgentRunner } from './agent-runner/ConversationAgentRunner.js';
42
+ import { ConsoleNotificationAdapter, } from './adapters/INotificationAdapter.js';
43
+ import { NoOpActiveTaskTracker, } from './adapters/IActiveTaskTracker.js';
44
+ /**
45
+ * The framework-agnostic conversations runtime.
46
+ *
47
+ * **Lifecycle:** call `Config(false, contextUser, provider)` at every entry point that
48
+ * uses the runtime — it's idempotent, so only the first caller pays the load cost. The
49
+ * rest are O(1) cache hits.
50
+ *
51
+ * **Adapters:** at host bootstrap, supply UI adapters via
52
+ * {@link UseNotificationAdapter} / {@link UseActiveTaskTracker}. Until you do, the
53
+ * defaults log to the console and no-op respectively.
54
+ *
55
+ * **Multi-provider:** when an explicit provider is passed to `Config()`, the runtime
56
+ * scopes its dependent engines (`AIEngineBase`, `ApplicationSettingEngine`,
57
+ * `ConversationEngine`) to that provider. Single-provider apps omit the parameter and
58
+ * get the global default.
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * import { ConversationsRuntime } from '@memberjunction/conversations-runtime';
63
+ *
64
+ * // At every entry point (no-op after the first call)
65
+ * await ConversationsRuntime.Instance.Config(false, contextUser);
66
+ *
67
+ * // Wire UI adapters once at bootstrap
68
+ * ConversationsRuntime.Instance.UseNotificationAdapter({
69
+ * Notify: (level, msg, ttl) =>
70
+ * MJNotificationService.Instance.CreateSimpleNotification(msg, level, ttl ?? 5000),
71
+ * });
72
+ *
73
+ * // Process a message through the default conversation manager agent
74
+ * const result = await ConversationsRuntime.Instance.AgentRunner.processMessage({
75
+ * conversationId,
76
+ * message,
77
+ * conversationDetailId,
78
+ * applicationId,
79
+ * });
80
+ * ```
81
+ */
82
+ let ConversationsRuntime = class ConversationsRuntime extends BaseEngine {
83
+ constructor() {
84
+ super(...arguments);
85
+ // ────────────────────────────────────────────────────────────────────
86
+ // Adapter slots — replaceable at host bootstrap. Defaults below.
87
+ // ────────────────────────────────────────────────────────────────────
88
+ this._notification = new ConsoleNotificationAdapter();
89
+ this._tasks = new NoOpActiveTaskTracker();
90
+ // ────────────────────────────────────────────────────────────────────
91
+ // Sub-components — eagerly constructed (cheap) so the Instance accessor
92
+ // always returns a ready runtime.
93
+ // ────────────────────────────────────────────────────────────────────
94
+ this._mentions = new MentionParser();
95
+ this._bridge = new ConversationBridge();
96
+ this._tools = new ClientToolRegistry();
97
+ this._defaultAgent = new DefaultAgentResolver();
98
+ this._sessions = new SessionsObserver();
99
+ }
100
+ /**
101
+ * The singleton instance. Backed by the Global Object Store so the same instance is
102
+ * shared even when bundlers duplicate this module across code splits.
103
+ */
104
+ static get Instance() {
105
+ return super.getInstance();
106
+ }
107
+ /**
108
+ * Currently registered notification adapter — used by sub-components to surface
109
+ * user-visible messages. Defaults to {@link ConsoleNotificationAdapter}.
110
+ *
111
+ * Implements {@link IConversationsRuntimeContext.Notification}.
112
+ */
113
+ get Notification() {
114
+ return this._notification;
115
+ }
116
+ /**
117
+ * Currently registered active-task tracker — used by `ConversationStreaming` to
118
+ * clear running tasks when an agent run completes. Defaults to
119
+ * {@link NoOpActiveTaskTracker}.
120
+ *
121
+ * Implements {@link IConversationsRuntimeContext.Tasks}.
122
+ */
123
+ get Tasks() {
124
+ return this._tasks;
125
+ }
126
+ /**
127
+ * Register a notification adapter — typically called once at host bootstrap.
128
+ * The new adapter takes effect immediately; sub-components read it from the
129
+ * context on every call.
130
+ */
131
+ UseNotificationAdapter(adapter) {
132
+ this._notification = adapter;
133
+ }
134
+ /**
135
+ * Register an active-task tracker — typically called once at host bootstrap.
136
+ * The new tracker takes effect immediately.
137
+ */
138
+ UseActiveTaskTracker(tracker) {
139
+ this._tasks = tracker;
140
+ }
141
+ /**
142
+ * Register a sessions adapter — bridges the host's realtime session source
143
+ * (e.g., Angular's `RealtimeSessionService`) to the framework-agnostic runtime
144
+ * `Sessions` observer. Typically called once at host bootstrap; multiple
145
+ * swaps are supported (test harnesses, modality additions).
146
+ *
147
+ * Delegates to {@link SessionsObserver.UseSessionsAdapter}, which cleanly
148
+ * tears down any prior adapter subscription before subscribing to the new
149
+ * one. The new adapter takes effect immediately for all subscribers of
150
+ * `Sessions.SessionLifecycle$`.
151
+ */
152
+ UseSessionsAdapter(adapter) {
153
+ this._sessions.UseSessionsAdapter(adapter);
154
+ }
155
+ /** Mention parser — pure string logic. See {@link MentionParser}. */
156
+ get Mentions() {
157
+ return this._mentions;
158
+ }
159
+ /** Overlay ⇄ workspace coordination bus. See {@link ConversationBridge}. */
160
+ get Bridge() {
161
+ return this._bridge;
162
+ }
163
+ /**
164
+ * Shared client-tool registry — the same `ClientToolRegistry` from
165
+ * `@memberjunction/ai-agent-client` that `AgentClientSession` consumes. Apps register
166
+ * tools here once at startup; every session sees them.
167
+ */
168
+ get Tools() {
169
+ return this._tools;
170
+ }
171
+ /** Default-agent resolution chain. See {@link DefaultAgentResolver}. */
172
+ get DefaultAgent() {
173
+ return this._defaultAgent;
174
+ }
175
+ /**
176
+ * Sessions/Channels lifecycle observer — surfaces realtime session lifecycle
177
+ * events from the registered {@link ISessionsAdapter}. Defaults to a no-op
178
+ * adapter so headless consumers still construct cleanly; the Angular host's
179
+ * `ConversationsRuntimeBootstrap` swaps in a `RealtimeSessionsAdapter` that
180
+ * bridges `RealtimeSessionService` from PR #2787.
181
+ *
182
+ * Subscribe to `Sessions.SessionLifecycle$` for `session-started` /
183
+ * `session-channel` / `session-ended` events. See {@link SessionsObserver}.
184
+ */
185
+ get Sessions() {
186
+ return this._sessions;
187
+ }
188
+ /**
189
+ * PubSub streaming layer — routes progress and completion events from the server
190
+ * to per-message callbacks. See {@link ConversationStreaming}.
191
+ *
192
+ * Hosts must call `.initialize()` once after `Config()` to open the subscription.
193
+ */
194
+ get Streaming() {
195
+ if (!this._streaming) {
196
+ this._streaming = new ConversationStreaming(this);
197
+ }
198
+ return this._streaming;
199
+ }
200
+ /**
201
+ * Agent-run orchestrator — wraps `AgentClientSession.RunAgentFromConversationDetail`
202
+ * with default-agent resolution and permission-filtered candidate lists. See
203
+ * {@link ConversationAgentRunner}.
204
+ */
205
+ get AgentRunner() {
206
+ if (!this._agentRunner) {
207
+ this._agentRunner = new ConversationAgentRunner(this, this._tools, this._defaultAgent);
208
+ }
209
+ return this._agentRunner;
210
+ }
211
+ // ────────────────────────────────────────────────────────────────────
212
+ // Lifecycle
213
+ // ────────────────────────────────────────────────────────────────────
214
+ /**
215
+ * Lazy-load the engines this runtime depends on (`AIEngineBase`,
216
+ * `ApplicationSettingEngine`, `ConversationEngine`). Safe to call from every entry
217
+ * point — only the first invocation pays the load cost.
218
+ *
219
+ * The runtime itself currently has no `BaseEnginePropertyConfig` entries — the data
220
+ * lives in the dependent engines. We override `Config()` rather than delegating to
221
+ * `super.Load()` because we're a composition root, not a data cache.
222
+ *
223
+ * @param forceRefresh Refresh the dependent engines' caches.
224
+ * @param contextUser Required on the server; ignored when omitted on the browser.
225
+ * @param provider Bind to a specific metadata provider; falls back to `Metadata.Provider`.
226
+ */
227
+ async Config(forceRefresh, contextUser, provider) {
228
+ // Run dependent-engine configs in parallel — they're independent, and the first
229
+ // call to each is what pays the cost. Subsequent calls are no-ops.
230
+ await Promise.all([
231
+ AIEngineBase.Instance.Config(forceRefresh, contextUser, provider),
232
+ ApplicationSettingEngine.Instance.Config(forceRefresh, contextUser, provider),
233
+ ConversationEngine.Instance.Config(forceRefresh, contextUser, provider),
234
+ ]);
235
+ }
236
+ /**
237
+ * {@link IStartupSink} entry point fired by the MJ startup manager when this class
238
+ * is registered via `@RegisterForStartup`. Pre-warms the runtime so the first user
239
+ * to open a conversations surface doesn't pay the load cost. Deferred + non-blocking
240
+ * per the decorator config — failures are logged (`severity: 'warn'`) but never
241
+ * block app boot.
242
+ */
243
+ async HandleStartup(contextUser, provider) {
244
+ await this.Config(false, contextUser, provider);
245
+ }
246
+ /**
247
+ * Tear down sub-components that hold subscriptions. Safe to call at app shutdown or
248
+ * in tests between cases.
249
+ */
250
+ Dispose() {
251
+ this._sessions.Dispose();
252
+ if (this._streaming) {
253
+ this._streaming.Dispose();
254
+ this._streaming = undefined;
255
+ }
256
+ this._agentRunner = undefined;
257
+ }
258
+ };
259
+ ConversationsRuntime = __decorate([
260
+ RegisterForStartup({
261
+ deferred: true,
262
+ deferredDelay: 5000,
263
+ severity: 'warn',
264
+ description: 'Conversations runtime (mentions, default-agent, agent runner) pre-warming'
265
+ })
266
+ ], ConversationsRuntime);
267
+ export { ConversationsRuntime };
268
+ //# sourceMappingURL=ConversationsRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConversationsRuntime.js","sourceRoot":"","sources":["../src/ConversationsRuntime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;;;;;;;AAEH,OAAO,EAAE,UAAU,EAAmC,kBAAkB,EAAY,MAAM,sBAAsB,CAAC;AACjH,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM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