@memberjunction/ng-conversations 6.3.0-edge.0 → 6.3.0-edge.1
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/README.md +47 -22
- package/dist/assets/edge-ai.worker.js +32515 -0
- package/dist/lib/components/artifact/artifact-share-modal.component.d.ts +39 -6
- package/dist/lib/components/artifact/artifact-share-modal.component.d.ts.map +1 -1
- package/dist/lib/components/artifact/artifact-share-modal.component.js +620 -74
- package/dist/lib/components/artifact/artifact-share-modal.component.js.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-tree.component.js +19 -18
- package/dist/lib/components/collection/collection-tree.component.js.map +1 -1
- package/dist/lib/components/collection/collection-view.component.d.ts +6 -4
- package/dist/lib/components/collection/collection-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collection-view.component.js +35 -17
- package/dist/lib/components/collection/collection-view.component.js.map +1 -1
- package/dist/lib/components/collection/collections-full-view.component.d.ts +1 -0
- package/dist/lib/components/collection/collections-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/collection/collections-full-view.component.js +108 -106
- package/dist/lib/components/collection/collections-full-view.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +36 -10
- package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-chat-area.component.js +101 -37
- package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
- package/dist/lib/components/conversation/conversation-list.component.d.ts +14 -0
- package/dist/lib/components/conversation/conversation-list.component.d.ts.map +1 -1
- package/dist/lib/components/conversation/conversation-list.component.js +93 -42
- package/dist/lib/components/conversation/conversation-list.component.js.map +1 -1
- package/dist/lib/components/export/export-modal.component.d.ts +7 -2
- package/dist/lib/components/export/export-modal.component.d.ts.map +1 -1
- package/dist/lib/components/export/export-modal.component.js +13 -2
- package/dist/lib/components/export/export-modal.component.js.map +1 -1
- package/dist/lib/components/library/library-create-dialog.component.d.ts +136 -0
- package/dist/lib/components/library/library-create-dialog.component.d.ts.map +1 -0
- package/dist/lib/components/library/library-create-dialog.component.js +1620 -0
- package/dist/lib/components/library/library-create-dialog.component.js.map +1 -0
- package/dist/lib/components/library/library-full-view.component.d.ts +10 -4
- package/dist/lib/components/library/library-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/library/library-full-view.component.js +216 -40
- package/dist/lib/components/library/library-full-view.component.js.map +1 -1
- package/dist/lib/components/library/library-remote-drive-pane.component.d.ts +97 -0
- package/dist/lib/components/library/library-remote-drive-pane.component.d.ts.map +1 -0
- package/dist/lib/components/library/library-remote-drive-pane.component.js +1229 -0
- package/dist/lib/components/library/library-remote-drive-pane.component.js.map +1 -0
- package/dist/lib/components/library/library-workspace.component.d.ts +265 -0
- package/dist/lib/components/library/library-workspace.component.d.ts.map +1 -0
- package/dist/lib/components/library/library-workspace.component.js +4420 -0
- package/dist/lib/components/library/library-workspace.component.js.map +1 -0
- package/dist/lib/components/library/library.models.d.ts +162 -0
- package/dist/lib/components/library/library.models.d.ts.map +1 -0
- package/dist/lib/components/library/library.models.js +2 -0
- package/dist/lib/components/library/library.models.js.map +1 -0
- package/dist/lib/components/message/conversation-message-rating.component.d.ts +5 -0
- package/dist/lib/components/message/conversation-message-rating.component.d.ts.map +1 -1
- package/dist/lib/components/message/conversation-message-rating.component.js +72 -16
- package/dist/lib/components/message/conversation-message-rating.component.js.map +1 -1
- package/dist/lib/components/message/message-input.component.d.ts +26 -14
- package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-input.component.js +91 -56
- package/dist/lib/components/message/message-input.component.js.map +1 -1
- package/dist/lib/components/message/message-item.component.d.ts +35 -1
- package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-item.component.js +583 -392
- package/dist/lib/components/message/message-item.component.js.map +1 -1
- package/dist/lib/components/message/message-list.component.d.ts.map +1 -1
- package/dist/lib/components/message/message-list.component.js +2 -0
- package/dist/lib/components/message/message-list.component.js.map +1 -1
- package/dist/lib/components/navigation/conversation-navigation.component.js +9 -9
- package/dist/lib/components/navigation/conversation-navigation.component.js.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.d.ts +94 -6
- package/dist/lib/components/overlay/chat-overlay.component.d.ts.map +1 -1
- package/dist/lib/components/overlay/chat-overlay.component.js +249 -59
- package/dist/lib/components/overlay/chat-overlay.component.js.map +1 -1
- package/dist/lib/components/project/project-form-modal.component.d.ts +6 -0
- package/dist/lib/components/project/project-form-modal.component.d.ts.map +1 -1
- package/dist/lib/components/project/project-form-modal.component.js +81 -61
- package/dist/lib/components/project/project-form-modal.component.js.map +1 -1
- package/dist/lib/components/project/project-selector.component.d.ts +5 -0
- package/dist/lib/components/project/project-selector.component.d.ts.map +1 -1
- package/dist/lib/components/project/project-selector.component.js +11 -4
- package/dist/lib/components/project/project-selector.component.js.map +1 -1
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.d.ts +55 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.js +944 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-channel.js.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.d.ts +66 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.js +253 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-engine.js.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.d.ts +80 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.js +49 -0
- package/dist/lib/components/realtime/artifact-workspace/artifact-workspace-types.js.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.d.ts +54 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.d.ts.map +1 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.js +386 -0
- package/dist/lib/components/realtime/artifact-workspace/realtime-artifact-workspace-surface.component.js.map +1 -0
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.d.ts +1 -0
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.js +15 -2
- package/dist/lib/components/realtime/interactive-component/interactive-component-channel.js.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-banner.component.js +2 -2
- package/dist/lib/components/realtime/realtime-agent-banner.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-agent-picker.component.js +3 -3
- package/dist/lib/components/realtime/realtime-agent-picker.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-composer.component.js +5 -3
- package/dist/lib/components/realtime/realtime-composer.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-session-overlay.component.d.ts +81 -32
- package/dist/lib/components/realtime/realtime-session-overlay.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-session-overlay.component.js +506 -185
- package/dist/lib/components/realtime/realtime-session-overlay.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-session-thread.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-session-thread.component.js +89 -4
- package/dist/lib/components/realtime/realtime-session-thread.component.js.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-stage.model.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-stage.model.js +2 -1
- package/dist/lib/components/realtime/realtime-surface-stage.model.js.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tab-style.d.ts +4 -4
- package/dist/lib/components/realtime/realtime-surface-tab-style.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tab-style.js +5 -5
- package/dist/lib/components/realtime/realtime-surface-tab-style.js.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tabs.model.d.ts +7 -9
- package/dist/lib/components/realtime/realtime-surface-tabs.model.d.ts.map +1 -1
- package/dist/lib/components/realtime/realtime-surface-tabs.model.js +12 -13
- package/dist/lib/components/realtime/realtime-surface-tabs.model.js.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts +27 -0
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js +141 -2
- package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.d.ts +101 -3
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.js +503 -55
- package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.js.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.d.ts +48 -5
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.d.ts.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.js +249 -53
- package/dist/lib/components/realtime/whiteboard/whiteboard-artifact-viewer.component.js.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-channel.d.ts.map +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-channel.js +1 -1
- package/dist/lib/components/realtime/whiteboard/whiteboard-channel.js.map +1 -1
- package/dist/lib/components/search/search-panel.component.d.ts +10 -0
- package/dist/lib/components/search/search-panel.component.d.ts.map +1 -1
- package/dist/lib/components/search/search-panel.component.js +25 -3
- package/dist/lib/components/search/search-panel.component.js.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.d.ts +31 -8
- package/dist/lib/components/task/tasks-full-view.component.d.ts.map +1 -1
- package/dist/lib/components/task/tasks-full-view.component.js +692 -497
- package/dist/lib/components/task/tasks-full-view.component.js.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
- package/dist/lib/components/workspace/conversation-workspace.component.js +15 -2
- package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
- package/dist/lib/conversations.module.d.ts +66 -61
- package/dist/lib/conversations.module.d.ts.map +1 -1
- package/dist/lib/conversations.module.js +60 -1
- package/dist/lib/conversations.module.js.map +1 -1
- package/dist/lib/models/agent-turn.model.d.ts +7 -1
- package/dist/lib/models/agent-turn.model.d.ts.map +1 -1
- package/dist/lib/models/agent-turn.model.js.map +1 -1
- package/dist/lib/services/agent-state.service.d.ts.map +1 -1
- package/dist/lib/services/agent-state.service.js +14 -3
- package/dist/lib/services/agent-state.service.js.map +1 -1
- package/dist/lib/services/artifact-permission.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-permission.service.js +14 -3
- package/dist/lib/services/artifact-permission.service.js.map +1 -1
- package/dist/lib/services/artifact-state.service.d.ts.map +1 -1
- package/dist/lib/services/artifact-state.service.js +43 -11
- package/dist/lib/services/artifact-state.service.js.map +1 -1
- package/dist/lib/services/conversation-agent.service.d.ts +8 -3
- package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
- package/dist/lib/services/conversation-agent.service.js +9 -3
- package/dist/lib/services/conversation-agent.service.js.map +1 -1
- package/dist/lib/services/conversation-tasks-filter.d.ts +59 -2
- package/dist/lib/services/conversation-tasks-filter.d.ts.map +1 -1
- package/dist/lib/services/conversation-tasks-filter.js +222 -18
- package/dist/lib/services/conversation-tasks-filter.js.map +1 -1
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.d.ts +85 -0
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.js +257 -0
- package/dist/lib/services/edge-ai/edge-agent-pre-discovery.service.js.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.d.ts +85 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.js +10 -0
- package/dist/lib/services/edge-ai/edge-ai-protocol.js.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.d.ts +90 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.js +386 -0
- package/dist/lib/services/edge-ai/edge-ai-worker-host.js.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.d.ts +13 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.d.ts.map +1 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.js +201 -0
- package/dist/lib/services/edge-ai/edge-ai.worker.js.map +1 -0
- package/dist/lib/services/export.service.d.ts +64 -0
- package/dist/lib/services/export.service.d.ts.map +1 -1
- package/dist/lib/services/export.service.js +185 -6
- package/dist/lib/services/export.service.js.map +1 -1
- package/dist/lib/services/library-creation.service.d.ts +304 -0
- package/dist/lib/services/library-creation.service.d.ts.map +1 -0
- package/dist/lib/services/library-creation.service.js +1244 -0
- package/dist/lib/services/library-creation.service.js.map +1 -0
- package/dist/lib/services/realtime-pairing.d.ts +3 -3
- package/dist/lib/services/realtime-pairing.js +4 -4
- package/dist/lib/services/realtime-pairing.js.map +1 -1
- package/dist/lib/services/realtime-session-review.service.d.ts +14 -0
- package/dist/lib/services/realtime-session-review.service.d.ts.map +1 -1
- package/dist/lib/services/realtime-session-review.service.js +46 -4
- package/dist/lib/services/realtime-session-review.service.js.map +1 -1
- package/dist/lib/services/search.service.d.ts +19 -2
- package/dist/lib/services/search.service.d.ts.map +1 -1
- package/dist/lib/services/search.service.js +99 -36
- package/dist/lib/services/search.service.js.map +1 -1
- package/dist/lib/utils/decision-routing.d.ts +5 -2
- package/dist/lib/utils/decision-routing.d.ts.map +1 -1
- package/dist/lib/utils/decision-routing.js +9 -4
- package/dist/lib/utils/decision-routing.js.map +1 -1
- package/dist/public-api.d.ts +13 -0
- package/dist/public-api.d.ts.map +1 -1
- package/dist/public-api.js +15 -1
- package/dist/public-api.js.map +1 -1
- package/package.json +42 -37
|
@@ -1,9 +1,141 @@
|
|
|
1
1
|
import { RunView } from '@memberjunction/core';
|
|
2
|
-
import { EscapeSQLString } from '@memberjunction/global';
|
|
2
|
+
import { EscapeSQLString, NormalizeUUID } from '@memberjunction/global';
|
|
3
|
+
import { UserHoldsAuthorization } from './user-authorization';
|
|
4
|
+
/**
|
|
5
|
+
* Seeded MJ Authorization name granting non-owner roles access to the
|
|
6
|
+
* "All Users" UX scope toggle in Agent Activity.
|
|
7
|
+
*/
|
|
8
|
+
export const AGENT_ACTIVITY_VIEW_ALL_USERS_AUTHORIZATION = 'Agent Activity: View All Users';
|
|
9
|
+
/** Short TTL (30 seconds) for cached `{ conversationIds, detailIds }` per user in Agent Activity polling. */
|
|
10
|
+
export const AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS = 30_000;
|
|
11
|
+
let globalScopeCacheEpoch = 0;
|
|
12
|
+
const userScopeCacheEpochs = new Map();
|
|
13
|
+
const scopeCacheByProvider = new WeakMap();
|
|
14
|
+
const inFlightScopeByProvider = new WeakMap();
|
|
15
|
+
const authCacheByProvider = new WeakMap();
|
|
16
|
+
const defaultProviderAuthCache = new Map();
|
|
17
|
+
/**
|
|
18
|
+
* Invalidates cached `{ conversationIds, detailIds }` scope and authorization entries used by
|
|
19
|
+
* {@link BuildConversationTasksFilter}, {@link BuildAgentActivityTasksFilter}, and {@link CanUserViewAllAgentTasks}.
|
|
20
|
+
*
|
|
21
|
+
* Pass `userId` to invalidate a single user's cached scope, or omit `userId` to clear all users.
|
|
22
|
+
*/
|
|
23
|
+
export function InvalidateAgentActivityScopeCache(userId) {
|
|
24
|
+
if (userId && userId.trim().length > 0) {
|
|
25
|
+
const normId = NormalizeUUID(userId);
|
|
26
|
+
userScopeCacheEpochs.set(normId, (userScopeCacheEpochs.get(normId) ?? 0) + 1);
|
|
27
|
+
defaultProviderAuthCache.delete(normId);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
globalScopeCacheEpoch += 1;
|
|
31
|
+
userScopeCacheEpochs.clear();
|
|
32
|
+
defaultProviderAuthCache.clear();
|
|
33
|
+
}
|
|
3
34
|
/** The ExtraFilter for the top-level tasks a user owns. */
|
|
4
35
|
export function OwnTasksFilter(user) {
|
|
5
36
|
return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}'`;
|
|
6
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Returns `true` only when `user` is authorized to switch Agent Activity from personal/conversation
|
|
40
|
+
* scope to the organization-wide "All Users" scope (`User.Type === 'Owner'` or the seeded
|
|
41
|
+
* `Agent Activity: View All Users` authorization via `AuthorizationEngine`).
|
|
42
|
+
*
|
|
43
|
+
* Results are cached per `(provider, userId)` for {@link AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS} (30s)
|
|
44
|
+
* so 4-second polling does not repeatedly scan authorization metadata.
|
|
45
|
+
*
|
|
46
|
+
* Note: `MJ: Tasks` has no server-side RLS filter in a default install, so this check gates the
|
|
47
|
+
* Agent Activity UX scope control rather than enforcing database-level row security.
|
|
48
|
+
*/
|
|
49
|
+
export function CanUserViewAllAgentTasks(user, provider) {
|
|
50
|
+
if (!user) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
if ((user.Type ?? '').trim().toLowerCase() === 'owner') {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
const userKey = NormalizeUUID(user.ID);
|
|
57
|
+
const currentGlobalEpoch = globalScopeCacheEpoch;
|
|
58
|
+
const currentUserEpoch = userScopeCacheEpochs.get(userKey) ?? 0;
|
|
59
|
+
const now = Date.now();
|
|
60
|
+
let authCache;
|
|
61
|
+
if (provider) {
|
|
62
|
+
const existing = authCacheByProvider.get(provider);
|
|
63
|
+
if (existing) {
|
|
64
|
+
authCache = existing;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
authCache = new Map();
|
|
68
|
+
authCacheByProvider.set(provider, authCache);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
authCache = defaultProviderAuthCache;
|
|
73
|
+
}
|
|
74
|
+
const cached = authCache.get(userKey);
|
|
75
|
+
if (cached &&
|
|
76
|
+
cached.globalEpoch === currentGlobalEpoch &&
|
|
77
|
+
cached.userEpoch === currentUserEpoch &&
|
|
78
|
+
now < cached.expiresAt) {
|
|
79
|
+
return cached.allowed;
|
|
80
|
+
}
|
|
81
|
+
const allowed = UserHoldsAuthorization(user, AGENT_ACTIVITY_VIEW_ALL_USERS_AUTHORIZATION, provider ?? undefined);
|
|
82
|
+
authCache.set(userKey, {
|
|
83
|
+
allowed,
|
|
84
|
+
expiresAt: now + AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS,
|
|
85
|
+
globalEpoch: currentGlobalEpoch,
|
|
86
|
+
userEpoch: currentUserEpoch,
|
|
87
|
+
});
|
|
88
|
+
return allowed;
|
|
89
|
+
}
|
|
90
|
+
function buildAgentBackedClause(provider) {
|
|
91
|
+
const tasksEntity = provider?.EntityByName('MJ: Tasks');
|
|
92
|
+
const schemaName = tasksEntity?.SchemaName || '__mj';
|
|
93
|
+
const tasksView = tasksEntity?.BaseView || 'vwTasks';
|
|
94
|
+
return (`(` +
|
|
95
|
+
`[AgentRunID] IS NOT NULL ` +
|
|
96
|
+
`OR [AgentID] IS NOT NULL ` +
|
|
97
|
+
`OR [ConversationDetailID] IS NOT NULL ` +
|
|
98
|
+
`OR [ID] IN (SELECT [ParentID] FROM [${schemaName}].[${tasksView}] WHERE ([AgentRunID] IS NOT NULL OR [AgentID] IS NOT NULL OR [ConversationDetailID] IS NOT NULL) AND [ParentID] IS NOT NULL)` +
|
|
99
|
+
`)`);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Server-side SQL `ExtraFilter` for Agent Activity (`MJ: Tasks`), excluding non-agent human
|
|
103
|
+
* deliverables.
|
|
104
|
+
*
|
|
105
|
+
* When `user` is supplied, restricts to `UserID = '<user.ID>'` unless `options?.includeAllUsers`
|
|
106
|
+
* is `true` AND {@link CanUserViewAllAgentTasks} authorizes organization-wide visibility.
|
|
107
|
+
*/
|
|
108
|
+
export function BuildAgentBackedTaskExtraFilter(provider, user, options) {
|
|
109
|
+
const agentClause = buildAgentBackedClause(provider);
|
|
110
|
+
const allowAllUsers = Boolean(options?.includeAllUsers && CanUserViewAllAgentTasks(user, provider));
|
|
111
|
+
if (user && !allowAllUsers) {
|
|
112
|
+
return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}' AND ${agentClause}`;
|
|
113
|
+
}
|
|
114
|
+
if (!user && !options?.includeAllUsers) {
|
|
115
|
+
return `1 = 0`;
|
|
116
|
+
}
|
|
117
|
+
return `ParentID IS NULL AND ${agentClause}`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Builds the default user-scoped Agent Activity `ExtraFilter` by combining
|
|
121
|
+
* {@link BuildConversationTasksFilter} (the user's own tasks plus tasks linked to messages in
|
|
122
|
+
* conversations the user owns or wrote) with the agent-backed task predicate.
|
|
123
|
+
*
|
|
124
|
+
* When `options?.includeAllUsers` is `true` and {@link CanUserViewAllAgentTasks} is satisfied,
|
|
125
|
+
* returns the organization-wide agent-backed task filter. Note that `MJ: Tasks` has no server RLS
|
|
126
|
+
* filter by default, so this toggle is a UX scope control gated by `Agent Activity: View All Users`
|
|
127
|
+
* (or `User.Type === 'Owner'`).
|
|
128
|
+
*/
|
|
129
|
+
export async function BuildAgentActivityTasksFilter(provider, user, options) {
|
|
130
|
+
if (options?.includeAllUsers && CanUserViewAllAgentTasks(user, provider)) {
|
|
131
|
+
return BuildAgentBackedTaskExtraFilter(provider, user, { includeAllUsers: true });
|
|
132
|
+
}
|
|
133
|
+
const conversationScopedFilter = await BuildConversationTasksFilter(provider, user, {
|
|
134
|
+
useCache: options?.bypassCache !== true,
|
|
135
|
+
});
|
|
136
|
+
const agentClause = buildAgentBackedClause(provider);
|
|
137
|
+
return `(${conversationScopedFilter}) AND ${agentClause}`;
|
|
138
|
+
}
|
|
7
139
|
/**
|
|
8
140
|
* The ExtraFilter for the top-level tasks the conversations UI shows a user: the tasks the user
|
|
9
141
|
* owns, and the tasks linked to a message the user wrote or that is in a conversation the user
|
|
@@ -12,32 +144,104 @@ export function OwnTasksFilter(user) {
|
|
|
12
144
|
* The conversation and message IDs are read with their own RunView, so the row-level security on
|
|
13
145
|
* those entities applies. A subquery over their views would skip it, and the server refuses one
|
|
14
146
|
* for a user whose read of them is row-filtered. When a read fails, the result is the user's own
|
|
15
|
-
* tasks.
|
|
147
|
+
* tasks. By default (`options?.useCache !== false` and `options?.bypassCache !== true`), resolved
|
|
148
|
+
* `{ conversationIds, detailIds }` are cached per user with a 30-second TTL and concurrent
|
|
149
|
+
* in-flight deduplication so 4-second polling (including `ConversationWorkspaceComponent.TasksFilterResolver`)
|
|
150
|
+
* and `TaskGraphEvents$` bursts do not repeatedly query `MJ: Conversations` and
|
|
151
|
+
* `MJ: Conversation Details` with `IgnoreMaxRows: true`.
|
|
16
152
|
*/
|
|
17
|
-
export async function BuildConversationTasksFilter(provider, user) {
|
|
153
|
+
export async function BuildConversationTasksFilter(provider, user, options) {
|
|
18
154
|
const ownTasks = OwnTasksFilter(user);
|
|
19
155
|
const tasks = provider.EntityByName('MJ: Tasks');
|
|
20
156
|
if (!tasks) {
|
|
21
157
|
return ownTasks;
|
|
22
158
|
}
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
ExtraFilter: `UserID = '${EscapeSQLString(user.ID)}'`,
|
|
27
|
-
Fields: ['ID'],
|
|
28
|
-
});
|
|
29
|
-
if (conversationIds == null) {
|
|
159
|
+
const shouldUseCache = options?.bypassCache !== true && options?.useCache !== false;
|
|
160
|
+
const scope = await resolveUserActivityScope(provider, user, tasks, shouldUseCache);
|
|
161
|
+
if (scope == null || scope.detailIds.length === 0) {
|
|
30
162
|
return ownTasks;
|
|
31
163
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
164
|
+
return `ParentID IS NULL AND (UserID = '${EscapeSQLString(user.ID)}' OR ConversationDetailID IN (${sqlInList(scope.detailIds)}))`;
|
|
165
|
+
}
|
|
166
|
+
async function resolveUserActivityScope(provider, user, tasks, useCache) {
|
|
167
|
+
const userKey = NormalizeUUID(user.ID);
|
|
168
|
+
const currentGlobalEpoch = globalScopeCacheEpoch;
|
|
169
|
+
const currentUserEpoch = userScopeCacheEpochs.get(userKey) ?? 0;
|
|
170
|
+
const now = Date.now();
|
|
171
|
+
let providerCache = scopeCacheByProvider.get(provider);
|
|
172
|
+
if (!providerCache) {
|
|
173
|
+
providerCache = new Map();
|
|
174
|
+
scopeCacheByProvider.set(provider, providerCache);
|
|
39
175
|
}
|
|
40
|
-
|
|
176
|
+
if (useCache) {
|
|
177
|
+
const cached = providerCache.get(userKey);
|
|
178
|
+
if (cached &&
|
|
179
|
+
cached.globalEpoch === currentGlobalEpoch &&
|
|
180
|
+
cached.userEpoch === currentUserEpoch &&
|
|
181
|
+
now < cached.expiresAt) {
|
|
182
|
+
return { conversationIds: cached.conversationIds, detailIds: cached.detailIds };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
let providerInFlight = inFlightScopeByProvider.get(provider);
|
|
186
|
+
if (!providerInFlight) {
|
|
187
|
+
providerInFlight = new Map();
|
|
188
|
+
inFlightScopeByProvider.set(provider, providerInFlight);
|
|
189
|
+
}
|
|
190
|
+
if (useCache) {
|
|
191
|
+
const existingInFlight = providerInFlight.get(userKey);
|
|
192
|
+
if (existingInFlight &&
|
|
193
|
+
existingInFlight.globalEpoch === currentGlobalEpoch &&
|
|
194
|
+
existingInFlight.userEpoch === currentUserEpoch) {
|
|
195
|
+
return existingInFlight.promise;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const inFlightToken = {};
|
|
199
|
+
const runFetch = async () => {
|
|
200
|
+
try {
|
|
201
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
202
|
+
const conversationIds = await readIds(rv, user, {
|
|
203
|
+
EntityName: 'MJ: Conversations',
|
|
204
|
+
ExtraFilter: `UserID = '${EscapeSQLString(user.ID)}'`,
|
|
205
|
+
Fields: ['ID'],
|
|
206
|
+
});
|
|
207
|
+
if (conversationIds == null) {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
const detailIds = await readIds(rv, user, {
|
|
211
|
+
EntityName: 'MJ: Conversation Details',
|
|
212
|
+
ExtraFilter: taskMessagesFilter(user, conversationIds, tasks),
|
|
213
|
+
Fields: ['ID'],
|
|
214
|
+
});
|
|
215
|
+
if (detailIds == null) {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
const latestUserEpoch = userScopeCacheEpochs.get(userKey) ?? 0;
|
|
219
|
+
if (globalScopeCacheEpoch === currentGlobalEpoch && latestUserEpoch === currentUserEpoch) {
|
|
220
|
+
providerCache.set(userKey, {
|
|
221
|
+
conversationIds,
|
|
222
|
+
detailIds,
|
|
223
|
+
expiresAt: Date.now() + AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS,
|
|
224
|
+
globalEpoch: currentGlobalEpoch,
|
|
225
|
+
userEpoch: currentUserEpoch,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return { conversationIds, detailIds };
|
|
229
|
+
}
|
|
230
|
+
finally {
|
|
231
|
+
const activeEntry = providerInFlight.get(userKey);
|
|
232
|
+
if (activeEntry?.token === inFlightToken) {
|
|
233
|
+
providerInFlight.delete(userKey);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
const fetchPromise = runFetch();
|
|
238
|
+
providerInFlight.set(userKey, {
|
|
239
|
+
token: inFlightToken,
|
|
240
|
+
promise: fetchPromise,
|
|
241
|
+
globalEpoch: currentGlobalEpoch,
|
|
242
|
+
userEpoch: currentUserEpoch,
|
|
243
|
+
});
|
|
244
|
+
return fetchPromise;
|
|
41
245
|
}
|
|
42
246
|
/**
|
|
43
247
|
* The messages that have a top-level task and that the user wrote or that are in one of the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-tasks-filter.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-tasks-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA8E,MAAM,sBAAsB,CAAC;AAC3H,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,2DAA2D;AAC3D,MAAM,UAAU,cAAc,CAAC,IAAc;IAC3C,OAAO,kCAAkC,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC;AACvE,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,QAA2B,EAAE,IAAc;IAC5F,MAAM,QAAQ,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;IACtC,MAAM,KAAK,GAAG,QAAQ,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC;IACjD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IAClD,MAAM,eAAe,GAAG,MAAM,OAAO,CAAC,EAAE,EAAE,IAAI,EAAE;QAC9C,UAAU,EAAE,mBAAmB;QAC/B,WAAW,EAAE,aAAa,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG;QACrD,MAAM,EAAE,CAAC,IAAI,CAAC;KACf,CAAC,CAAC;IACH,IAAI,eAAe,IAAI,IAAI,EAAE,CAAC;QAC5B,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,OAAO,CAAC,EAAE,EAAE,IAAI,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,OAAO,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AACnD,CAAC;AAED,8DAA8D;AAC9D,SAAS,SAAS,CAAC,GAAsB;IACvC,OAAO,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { RunView, type EntityInfo, type IMetadataProvider, type RunViewParams, type UserInfo } from '@memberjunction/core';\nimport { EscapeSQLString } from '@memberjunction/global';\n\n/** The ExtraFilter for the top-level tasks a user owns. */\nexport function OwnTasksFilter(user: UserInfo): string {\n return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}'`;\n}\n\n/**\n * The ExtraFilter for the top-level tasks the conversations UI shows a user: the tasks the user\n * owns, and the tasks linked to a message the user wrote or that is in a conversation the user\n * owns.\n *\n * The conversation and message IDs are read with their own RunView, so the row-level security on\n * those entities applies. A subquery over their views would skip it, and the server refuses one\n * for a user whose read of them is row-filtered. When a read fails, the result is the user's own\n * tasks.\n */\nexport async function BuildConversationTasksFilter(provider: IMetadataProvider, user: UserInfo): Promise<string> {\n const ownTasks = OwnTasksFilter(user);\n const tasks = provider.EntityByName('MJ: Tasks');\n if (!tasks) {\n return ownTasks;\n }\n const rv = RunView.FromMetadataProvider(provider);\n const conversationIds = await readIds(rv, user, {\n EntityName: 'MJ: Conversations',\n ExtraFilter: `UserID = '${EscapeSQLString(user.ID)}'`,\n Fields: ['ID'],\n });\n if (conversationIds == null) {\n return ownTasks;\n }\n const messageIds = await readIds(rv, user, {\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: taskMessagesFilter(user, conversationIds, tasks),\n Fields: ['ID'],\n });\n if (messageIds == null || messageIds.length === 0) {\n return ownTasks;\n }\n return `ParentID IS NULL AND (UserID = '${EscapeSQLString(user.ID)}' OR ConversationDetailID IN (${sqlInList(messageIds)}))`;\n}\n\n/**\n * The messages that have a top-level task and that the user wrote or that are in one of the\n * user's conversations. The task subquery reads Tasks, which has no row filter in a default\n * install. Its identifiers are bracketed so the PostgreSQL provider quotes them.\n */\nfunction taskMessagesFilter(user: UserInfo, conversationIds: readonly string[], tasks: EntityInfo): string {\n const inConversations = conversationIds.length > 0 ? ` OR ConversationID IN (${sqlInList(conversationIds)})` : '';\n const taskView = `[${tasks.SchemaName}].[${tasks.BaseView}]`;\n return (\n `(UserID = '${EscapeSQLString(user.ID)}'${inConversations}) AND ID IN ` +\n `(SELECT [ConversationDetailID] FROM ${taskView} WHERE [ParentID] IS NULL AND [ConversationDetailID] IS NOT NULL)`\n );\n}\n\n/**\n * The IDs of the rows `read` selects, with no row cap; null when the read fails. Each caller names\n * an MJ core entity in `read`, so its key column is `ID`.\n */\nasync function readIds(rv: RunView, user: UserInfo, read: Pick<RunViewParams, 'EntityName' | 'ExtraFilter' | 'Fields'>): Promise<string[] | null> {\n const result = await rv.RunView<{ ID: string }>({ ...read, ResultType: 'simple', IgnoreMaxRows: true }, user);\n if (!result.Success) {\n console.error(`Failed to read ${read.EntityName} for the tasks filter:`, result.ErrorMessage);\n return null;\n }\n return (result.Results ?? []).map(row => row.ID);\n}\n\n/** A quoted, comma-separated list of IDs for an IN clause. */\nfunction sqlInList(ids: readonly string[]): string {\n return ids.map(id => `'${EscapeSQLString(id)}'`).join(',');\n}\n"]}
|
|
1
|
+
{"version":3,"file":"conversation-tasks-filter.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-tasks-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA8E,MAAM,sBAAsB,CAAC;AAC3H,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D;;;GAGG;AACH,MAAM,CAAC,MAAM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C;QAC9F,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AACnD,CAAC;AAED,8DAA8D;AAC9D,SAAS,SAAS,CAAC,GAAsB;IACvC,OAAO,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { RunView, type EntityInfo, type IMetadataProvider, type RunViewParams, type UserInfo } from '@memberjunction/core';\nimport { EscapeSQLString, NormalizeUUID } from '@memberjunction/global';\nimport { UserHoldsAuthorization } from './user-authorization';\n\n/**\n * Seeded MJ Authorization name granting non-owner roles access to the\n * \"All Users\" UX scope toggle in Agent Activity.\n */\nexport const AGENT_ACTIVITY_VIEW_ALL_USERS_AUTHORIZATION = 'Agent Activity: View All Users';\n\n/** Short TTL (30 seconds) for cached `{ conversationIds, detailIds }` per user in Agent Activity polling. */\nexport const AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS = 30_000;\n\ninterface AgentActivityScopeIds {\n conversationIds: string[];\n detailIds: string[];\n}\n\ninterface CachedAgentActivityScope extends AgentActivityScopeIds {\n expiresAt: number;\n globalEpoch: number;\n userEpoch: number;\n}\n\ninterface InFlightAgentActivityScope {\n token: object;\n promise: Promise<AgentActivityScopeIds | null>;\n globalEpoch: number;\n userEpoch: number;\n}\n\ninterface CachedAgentActivityAuthorization {\n allowed: boolean;\n expiresAt: number;\n globalEpoch: number;\n userEpoch: number;\n}\n\nlet globalScopeCacheEpoch = 0;\nconst userScopeCacheEpochs = new Map<string, number>();\nconst scopeCacheByProvider = new WeakMap<IMetadataProvider, Map<string, CachedAgentActivityScope>>();\nconst inFlightScopeByProvider = new WeakMap<IMetadataProvider, Map<string, InFlightAgentActivityScope>>();\nconst authCacheByProvider = new WeakMap<IMetadataProvider, Map<string, CachedAgentActivityAuthorization>>();\nconst defaultProviderAuthCache = new Map<string, CachedAgentActivityAuthorization>();\n\n/**\n * Invalidates cached `{ conversationIds, detailIds }` scope and authorization entries used by\n * {@link BuildConversationTasksFilter}, {@link BuildAgentActivityTasksFilter}, and {@link CanUserViewAllAgentTasks}.\n *\n * Pass `userId` to invalidate a single user's cached scope, or omit `userId` to clear all users.\n */\nexport function InvalidateAgentActivityScopeCache(userId?: string): void {\n if (userId && userId.trim().length > 0) {\n const normId = NormalizeUUID(userId);\n userScopeCacheEpochs.set(normId, (userScopeCacheEpochs.get(normId) ?? 0) + 1);\n defaultProviderAuthCache.delete(normId);\n return;\n }\n globalScopeCacheEpoch += 1;\n userScopeCacheEpochs.clear();\n defaultProviderAuthCache.clear();\n}\n\n/** The ExtraFilter for the top-level tasks a user owns. */\nexport function OwnTasksFilter(user: UserInfo): string {\n return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}'`;\n}\n\n/**\n * Returns `true` only when `user` is authorized to switch Agent Activity from personal/conversation\n * scope to the organization-wide \"All Users\" scope (`User.Type === 'Owner'` or the seeded\n * `Agent Activity: View All Users` authorization via `AuthorizationEngine`).\n *\n * Results are cached per `(provider, userId)` for {@link AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS} (30s)\n * so 4-second polling does not repeatedly scan authorization metadata.\n *\n * Note: `MJ: Tasks` has no server-side RLS filter in a default install, so this check gates the\n * Agent Activity UX scope control rather than enforcing database-level row security.\n */\nexport function CanUserViewAllAgentTasks(\n user: UserInfo | null | undefined,\n provider?: IMetadataProvider | null,\n): boolean {\n if (!user) {\n return false;\n }\n if ((user.Type ?? '').trim().toLowerCase() === 'owner') {\n return true;\n }\n\n const userKey = NormalizeUUID(user.ID);\n const currentGlobalEpoch = globalScopeCacheEpoch;\n const currentUserEpoch = userScopeCacheEpochs.get(userKey) ?? 0;\n const now = Date.now();\n\n let authCache: Map<string, CachedAgentActivityAuthorization>;\n if (provider) {\n const existing = authCacheByProvider.get(provider);\n if (existing) {\n authCache = existing;\n } else {\n authCache = new Map<string, CachedAgentActivityAuthorization>();\n authCacheByProvider.set(provider, authCache);\n }\n } else {\n authCache = defaultProviderAuthCache;\n }\n\n const cached = authCache.get(userKey);\n if (\n cached &&\n cached.globalEpoch === currentGlobalEpoch &&\n cached.userEpoch === currentUserEpoch &&\n now < cached.expiresAt\n ) {\n return cached.allowed;\n }\n\n const allowed = UserHoldsAuthorization(\n user,\n AGENT_ACTIVITY_VIEW_ALL_USERS_AUTHORIZATION,\n provider ?? undefined,\n );\n authCache.set(userKey, {\n allowed,\n expiresAt: now + AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS,\n globalEpoch: currentGlobalEpoch,\n userEpoch: currentUserEpoch,\n });\n return allowed;\n}\n\nfunction buildAgentBackedClause(provider?: IMetadataProvider | null): string {\n const tasksEntity = provider?.EntityByName('MJ: Tasks');\n const schemaName = tasksEntity?.SchemaName || '__mj';\n const tasksView = tasksEntity?.BaseView || 'vwTasks';\n\n return (\n `(` +\n `[AgentRunID] IS NOT NULL ` +\n `OR [AgentID] IS NOT NULL ` +\n `OR [ConversationDetailID] IS NOT NULL ` +\n `OR [ID] IN (SELECT [ParentID] FROM [${schemaName}].[${tasksView}] WHERE ([AgentRunID] IS NOT NULL OR [AgentID] IS NOT NULL OR [ConversationDetailID] IS NOT NULL) AND [ParentID] IS NOT NULL)` +\n `)`\n );\n}\n\n/**\n * Server-side SQL `ExtraFilter` for Agent Activity (`MJ: Tasks`), excluding non-agent human\n * deliverables.\n *\n * When `user` is supplied, restricts to `UserID = '<user.ID>'` unless `options?.includeAllUsers`\n * is `true` AND {@link CanUserViewAllAgentTasks} authorizes organization-wide visibility.\n */\nexport function BuildAgentBackedTaskExtraFilter(\n provider?: IMetadataProvider | null,\n user?: UserInfo | null,\n options?: { includeAllUsers?: boolean },\n): string {\n const agentClause = buildAgentBackedClause(provider);\n const allowAllUsers = Boolean(options?.includeAllUsers && CanUserViewAllAgentTasks(user, provider));\n if (user && !allowAllUsers) {\n return `ParentID IS NULL AND UserID = '${EscapeSQLString(user.ID)}' AND ${agentClause}`;\n }\n if (!user && !options?.includeAllUsers) {\n return `1 = 0`;\n }\n return `ParentID IS NULL AND ${agentClause}`;\n}\n\n/**\n * Builds the default user-scoped Agent Activity `ExtraFilter` by combining\n * {@link BuildConversationTasksFilter} (the user's own tasks plus tasks linked to messages in\n * conversations the user owns or wrote) with the agent-backed task predicate.\n *\n * When `options?.includeAllUsers` is `true` and {@link CanUserViewAllAgentTasks} is satisfied,\n * returns the organization-wide agent-backed task filter. Note that `MJ: Tasks` has no server RLS\n * filter by default, so this toggle is a UX scope control gated by `Agent Activity: View All Users`\n * (or `User.Type === 'Owner'`).\n */\nexport async function BuildAgentActivityTasksFilter(\n provider: IMetadataProvider,\n user: UserInfo,\n options?: { includeAllUsers?: boolean; bypassCache?: boolean },\n): Promise<string> {\n if (options?.includeAllUsers && CanUserViewAllAgentTasks(user, provider)) {\n return BuildAgentBackedTaskExtraFilter(provider, user, { includeAllUsers: true });\n }\n const conversationScopedFilter = await BuildConversationTasksFilter(provider, user, {\n useCache: options?.bypassCache !== true,\n });\n const agentClause = buildAgentBackedClause(provider);\n return `(${conversationScopedFilter}) AND ${agentClause}`;\n}\n\n/**\n * The ExtraFilter for the top-level tasks the conversations UI shows a user: the tasks the user\n * owns, and the tasks linked to a message the user wrote or that is in a conversation the user\n * owns.\n *\n * The conversation and message IDs are read with their own RunView, so the row-level security on\n * those entities applies. A subquery over their views would skip it, and the server refuses one\n * for a user whose read of them is row-filtered. When a read fails, the result is the user's own\n * tasks. By default (`options?.useCache !== false` and `options?.bypassCache !== true`), resolved\n * `{ conversationIds, detailIds }` are cached per user with a 30-second TTL and concurrent\n * in-flight deduplication so 4-second polling (including `ConversationWorkspaceComponent.TasksFilterResolver`)\n * and `TaskGraphEvents$` bursts do not repeatedly query `MJ: Conversations` and\n * `MJ: Conversation Details` with `IgnoreMaxRows: true`.\n */\nexport async function BuildConversationTasksFilter(\n provider: IMetadataProvider,\n user: UserInfo,\n options?: { useCache?: boolean; bypassCache?: boolean },\n): Promise<string> {\n const ownTasks = OwnTasksFilter(user);\n const tasks = provider.EntityByName('MJ: Tasks');\n if (!tasks) {\n return ownTasks;\n }\n const shouldUseCache = options?.bypassCache !== true && options?.useCache !== false;\n const scope = await resolveUserActivityScope(provider, user, tasks, shouldUseCache);\n if (scope == null || scope.detailIds.length === 0) {\n return ownTasks;\n }\n return `ParentID IS NULL AND (UserID = '${EscapeSQLString(user.ID)}' OR ConversationDetailID IN (${sqlInList(scope.detailIds)}))`;\n}\n\nasync function resolveUserActivityScope(\n provider: IMetadataProvider,\n user: UserInfo,\n tasks: EntityInfo,\n useCache: boolean,\n): Promise<AgentActivityScopeIds | null> {\n const userKey = NormalizeUUID(user.ID);\n const currentGlobalEpoch = globalScopeCacheEpoch;\n const currentUserEpoch = userScopeCacheEpochs.get(userKey) ?? 0;\n const now = Date.now();\n\n let providerCache = scopeCacheByProvider.get(provider);\n if (!providerCache) {\n providerCache = new Map<string, CachedAgentActivityScope>();\n scopeCacheByProvider.set(provider, providerCache);\n }\n\n if (useCache) {\n const cached = providerCache.get(userKey);\n if (\n cached &&\n cached.globalEpoch === currentGlobalEpoch &&\n cached.userEpoch === currentUserEpoch &&\n now < cached.expiresAt\n ) {\n return { conversationIds: cached.conversationIds, detailIds: cached.detailIds };\n }\n }\n\n let providerInFlight = inFlightScopeByProvider.get(provider);\n if (!providerInFlight) {\n providerInFlight = new Map<string, InFlightAgentActivityScope>();\n inFlightScopeByProvider.set(provider, providerInFlight);\n }\n\n if (useCache) {\n const existingInFlight = providerInFlight.get(userKey);\n if (\n existingInFlight &&\n existingInFlight.globalEpoch === currentGlobalEpoch &&\n existingInFlight.userEpoch === currentUserEpoch\n ) {\n return existingInFlight.promise;\n }\n }\n\n const inFlightToken = {};\n const runFetch = async (): Promise<AgentActivityScopeIds | null> => {\n try {\n const rv = RunView.FromMetadataProvider(provider);\n const conversationIds = await readIds(rv, user, {\n EntityName: 'MJ: Conversations',\n ExtraFilter: `UserID = '${EscapeSQLString(user.ID)}'`,\n Fields: ['ID'],\n });\n if (conversationIds == null) {\n return null;\n }\n const detailIds = await readIds(rv, user, {\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: taskMessagesFilter(user, conversationIds, tasks),\n Fields: ['ID'],\n });\n if (detailIds == null) {\n return null;\n }\n const latestUserEpoch = userScopeCacheEpochs.get(userKey) ?? 0;\n if (globalScopeCacheEpoch === currentGlobalEpoch && latestUserEpoch === currentUserEpoch) {\n providerCache.set(userKey, {\n conversationIds,\n detailIds,\n expiresAt: Date.now() + AGENT_ACTIVITY_SCOPE_CACHE_TTL_MS,\n globalEpoch: currentGlobalEpoch,\n userEpoch: currentUserEpoch,\n });\n }\n return { conversationIds, detailIds };\n } finally {\n const activeEntry = providerInFlight.get(userKey);\n if (activeEntry?.token === inFlightToken) {\n providerInFlight.delete(userKey);\n }\n }\n };\n\n const fetchPromise = runFetch();\n providerInFlight.set(userKey, {\n token: inFlightToken,\n promise: fetchPromise,\n globalEpoch: currentGlobalEpoch,\n userEpoch: currentUserEpoch,\n });\n\n return fetchPromise;\n}\n\n/**\n * The messages that have a top-level task and that the user wrote or that are in one of the\n * user's conversations. The task subquery reads Tasks, which has no row filter in a default\n * install. Its identifiers are bracketed so the PostgreSQL provider quotes them.\n */\nfunction taskMessagesFilter(user: UserInfo, conversationIds: readonly string[], tasks: EntityInfo): string {\n const inConversations = conversationIds.length > 0 ? ` OR ConversationID IN (${sqlInList(conversationIds)})` : '';\n const taskView = `[${tasks.SchemaName}].[${tasks.BaseView}]`;\n return (\n `(UserID = '${EscapeSQLString(user.ID)}'${inConversations}) AND ID IN ` +\n `(SELECT [ConversationDetailID] FROM ${taskView} WHERE [ParentID] IS NULL AND [ConversationDetailID] IS NOT NULL)`\n );\n}\n\n/**\n * The IDs of the rows `read` selects, with no row cap; null when the read fails. Each caller names\n * an MJ core entity in `read`, so its key column is `ID`.\n */\nasync function readIds(rv: RunView, user: UserInfo, read: Pick<RunViewParams, 'EntityName' | 'ExtraFilter' | 'Fields'>): Promise<string[] | null> {\n const result = await rv.RunView<{ ID: string }>({ ...read, ResultType: 'simple', IgnoreMaxRows: true }, user);\n if (!result.Success) {\n console.error(`Failed to read ${read.EntityName} for the tasks filter:`, result.ErrorMessage);\n return null;\n }\n return (result.Results ?? []).map(row => row.ID);\n}\n\n/** A quoted, comma-separated list of IDs for an IN clause. */\nfunction sqlInList(ids: readonly string[]): string {\n return ids.map(id => `'${EscapeSQLString(id)}'`).join(',');\n}\n"]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Client-side Edge Agent Pre-Discovery service (Stage 6C.1).
|
|
3
|
+
*
|
|
4
|
+
* Uses the shared lazy WASM worker ({@link EdgeAIWorkerHost}) and a float32
|
|
5
|
+
* {@link SimpleVectorService} catalog cache to compute an untrusted advisory
|
|
6
|
+
* {@link EdgePreDiscoveryHint}:
|
|
7
|
+
* 1. Bi-encoder (`Xenova/bge-small-en-v1.5`) cosine top-5 candidate narrowing.
|
|
8
|
+
* 2. Cross-encoder (`Xenova/ms-marco-MiniLM-L-6-v2`) batch=5 reranking +
|
|
9
|
+
* `logit >= -2.0` confidence gating.
|
|
10
|
+
*
|
|
11
|
+
* Never blocks UI mount or message sending when cold/offline/errored.
|
|
12
|
+
*
|
|
13
|
+
* @module @memberjunction/ng-conversations
|
|
14
|
+
*/
|
|
15
|
+
import { BaseSingleton } from '@memberjunction/global';
|
|
16
|
+
import { type EdgePreDiscoveryHint } from '@memberjunction/ai-core-plus';
|
|
17
|
+
/** Minimal agent descriptor needed for client pre-discovery indexing. */
|
|
18
|
+
export interface EdgeDiscoveryAgentDescriptor {
|
|
19
|
+
ID: string;
|
|
20
|
+
Name: string | null;
|
|
21
|
+
Description: string | null;
|
|
22
|
+
Status?: string | null;
|
|
23
|
+
InvocationMode?: string | null;
|
|
24
|
+
ParentID?: string | null;
|
|
25
|
+
}
|
|
26
|
+
/** Options controlling {@link EdgeAgentPreDiscoveryService.PreDiscover}. */
|
|
27
|
+
export interface EdgePreDiscoveryOptions {
|
|
28
|
+
/** Per-user/session cache key isolating cached catalog vectors. */
|
|
29
|
+
UserId?: string;
|
|
30
|
+
/** Optional host allow-list narrowing the searchable catalog. */
|
|
31
|
+
AllowedAgentIDs?: ReadonlyArray<string> | null;
|
|
32
|
+
/** Optional running manager agent ID to exclude from candidate targets. */
|
|
33
|
+
ExcludedAgentID?: string | null;
|
|
34
|
+
/** Maximum number of candidate IDs returned in `CandidateAgentIds` (default 5). */
|
|
35
|
+
TopK?: number;
|
|
36
|
+
/** Hard query deadline in ms (default 150ms when warm). */
|
|
37
|
+
TimeoutMs?: number;
|
|
38
|
+
/**
|
|
39
|
+
* When true, awaits cold model initialization if the worker is not yet warm.
|
|
40
|
+
* Defaults to `false` so live message sends never block on cold model downloads.
|
|
41
|
+
*/
|
|
42
|
+
WaitForColdLoad?: boolean;
|
|
43
|
+
/** Cross-encoder logit threshold for setting `SuggestedAgentId` (default `-2.0`). */
|
|
44
|
+
LogitThreshold?: number;
|
|
45
|
+
}
|
|
46
|
+
/** Default deadline for live pre-discovery on message submit. */
|
|
47
|
+
export declare const EDGE_PRE_DISCOVERY_QUERY_DEADLINE_MS = 150;
|
|
48
|
+
/**
|
|
49
|
+
* Formats an agent entry identically to the verified PoC (`Name: Description`).
|
|
50
|
+
*/
|
|
51
|
+
export declare function FormatEdgeAgentDocument(agent: Pick<EdgeDiscoveryAgentDescriptor, 'Name' | 'Description'>): string;
|
|
52
|
+
/**
|
|
53
|
+
* Filters a client agent list to discoverable top-level active specialists with descriptions,
|
|
54
|
+
* honoring any host `AllowedAgentIDs` and excluding the conversation manager itself.
|
|
55
|
+
*/
|
|
56
|
+
export declare function FilterDiscoverableEdgeAgents<T extends EdgeDiscoveryAgentDescriptor>(agents: ReadonlyArray<T>, options?: Pick<EdgePreDiscoveryOptions, 'AllowedAgentIDs' | 'ExcludedAgentID'>): T[];
|
|
57
|
+
/**
|
|
58
|
+
* Client-side Edge Agent Pre-Discovery engine.
|
|
59
|
+
*/
|
|
60
|
+
export declare class EdgeAgentPreDiscoveryService extends BaseSingleton<EdgeAgentPreDiscoveryService> {
|
|
61
|
+
private readonly catalogCaches;
|
|
62
|
+
private readonly warmUpsInFlight;
|
|
63
|
+
protected constructor();
|
|
64
|
+
static get Instance(): EdgeAgentPreDiscoveryService;
|
|
65
|
+
/** Clears all cached user/session agent vector indexes (e.g., on sign-out or tests). */
|
|
66
|
+
ClearCache(userId?: string): void;
|
|
67
|
+
/**
|
|
68
|
+
* Non-blocking post-mount warm-up: loads both `bge-small-en-v1.5` and
|
|
69
|
+
* `ms-marco-MiniLM-L-6-v2` in the lazy Web Worker and pre-embeds the user's
|
|
70
|
+
* discoverable agent catalog into a float32 {@link SimpleVectorService}.
|
|
71
|
+
* Never throws; returns `false` on offline/CSP/timeout.
|
|
72
|
+
*/
|
|
73
|
+
WarmUpCatalog(agents: ReadonlyArray<EdgeDiscoveryAgentDescriptor>, userId?: string, timeoutMs?: number): Promise<boolean>;
|
|
74
|
+
/**
|
|
75
|
+
* Computes an untrusted {@link EdgePreDiscoveryHint} for `query` over `agents`.
|
|
76
|
+
*
|
|
77
|
+
* By default (`WaitForColdLoad: false`), returns `null` immediately if the worker
|
|
78
|
+
* or catalog cache is not yet warm so sending a chat message is never delayed.
|
|
79
|
+
* Enforces `TimeoutMs` strictly via deadline racing and fails open to `null`.
|
|
80
|
+
*/
|
|
81
|
+
PreDiscover(query: string, agents: ReadonlyArray<EdgeDiscoveryAgentDescriptor>, options?: EdgePreDiscoveryOptions): Promise<EdgePreDiscoveryHint | null>;
|
|
82
|
+
private buildCatalogCache;
|
|
83
|
+
private computeFingerprint;
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=edge-agent-pre-discovery.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edge-agent-pre-discovery.service.d.ts","sourceRoot":"","sources":["../../../../src/lib/services/edge-ai/edge-agent-pre-discovery.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,aAAa,EAAuB,MAAM,wBAAwB,CAAC;AAE5E,OAAO,EAMH,KAAK,oBAAoB,EAC5B,MAAM,8BAA8B,CAAC;AAGtC,yEAAyE;AACzE,MAAM,WAAW,4BAA4B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,4EAA4E;AAC5E,MAAM,WAAW,uBAAuB;IACpC,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iEAAiE;IACjE,eAAe,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAC/C,2EAA2E;IAC3E,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,mFAAmF;IACnF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2DAA2D;IAC3D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,qFAAqF;IACrF,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B;AAeD,iEAAiE;AACjE,eAAO,MAAM,oCAAoC,MAAM,CAAC;AAExD;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,IAAI,CAAC,4BAA4B,EAAE,MAAM,GAAG,aAAa,CAAC,GAAG,MAAM,CAIjH;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAAC,C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