@memberjunction/core-actions 6.3.0-edge.0 → 6.3.0-edge.2

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 (200) hide show
  1. package/README.md +13 -0
  2. package/dist/custom/ai/agent-channel.action.d.ts +29 -0
  3. package/dist/custom/ai/agent-channel.action.d.ts.map +1 -0
  4. package/dist/custom/ai/agent-channel.action.js +843 -0
  5. package/dist/custom/ai/agent-channel.action.js.map +1 -0
  6. package/dist/custom/ai/chief-of-staff-approval-helper.d.ts +16 -0
  7. package/dist/custom/ai/chief-of-staff-approval-helper.d.ts.map +1 -0
  8. package/dist/custom/ai/chief-of-staff-approval-helper.js +63 -0
  9. package/dist/custom/ai/chief-of-staff-approval-helper.js.map +1 -0
  10. package/dist/custom/ai/chief-of-staff-core-reads.action.d.ts +64 -0
  11. package/dist/custom/ai/chief-of-staff-core-reads.action.d.ts.map +1 -0
  12. package/dist/custom/ai/chief-of-staff-core-reads.action.js +1097 -0
  13. package/dist/custom/ai/chief-of-staff-core-reads.action.js.map +1 -0
  14. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.d.ts +28 -0
  15. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.d.ts.map +1 -0
  16. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.js +817 -0
  17. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.js.map +1 -0
  18. package/dist/custom/ai/configure-agent-user-policy.action.d.ts +1 -0
  19. package/dist/custom/ai/configure-agent-user-policy.action.d.ts.map +1 -1
  20. package/dist/custom/ai/configure-agent-user-policy.action.js +5 -1
  21. package/dist/custom/ai/configure-agent-user-policy.action.js.map +1 -1
  22. package/dist/custom/ai/manage-my-agent-instance.action.d.ts +39 -0
  23. package/dist/custom/ai/manage-my-agent-instance.action.d.ts.map +1 -0
  24. package/dist/custom/ai/manage-my-agent-instance.action.js +752 -0
  25. package/dist/custom/ai/manage-my-agent-instance.action.js.map +1 -0
  26. package/dist/custom/ai/prepare-outbound-call-brief.action.js +1 -1
  27. package/dist/custom/ai/prepare-outbound-call-brief.action.js.map +1 -1
  28. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts +2 -0
  29. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts.map +1 -1
  30. package/dist/custom/ai/schedule-next-agent-wake.action.js +105 -2
  31. package/dist/custom/ai/schedule-next-agent-wake.action.js.map +1 -1
  32. package/dist/custom/ai/send-inter-agent-request.action.d.ts +1 -0
  33. package/dist/custom/ai/send-inter-agent-request.action.d.ts.map +1 -1
  34. package/dist/custom/ai/send-inter-agent-request.action.js +72 -18
  35. package/dist/custom/ai/send-inter-agent-request.action.js.map +1 -1
  36. package/dist/custom/ai/test-runtime-action.action.d.ts.map +1 -1
  37. package/dist/custom/ai/test-runtime-action.action.js +6 -1
  38. package/dist/custom/ai/test-runtime-action.action.js.map +1 -1
  39. package/dist/custom/ai/trigger-agent-wake.action.d.ts +1 -0
  40. package/dist/custom/ai/trigger-agent-wake.action.d.ts.map +1 -1
  41. package/dist/custom/ai/trigger-agent-wake.action.js +3 -0
  42. package/dist/custom/ai/trigger-agent-wake.action.js.map +1 -1
  43. package/dist/custom/ai/user-scoped-communication.action.d.ts +20 -0
  44. package/dist/custom/ai/user-scoped-communication.action.d.ts.map +1 -1
  45. package/dist/custom/ai/user-scoped-communication.action.js +140 -23
  46. package/dist/custom/ai/user-scoped-communication.action.js.map +1 -1
  47. package/dist/custom/artifacts/base-governed-artifact.action.d.ts +30 -0
  48. package/dist/custom/artifacts/base-governed-artifact.action.d.ts.map +1 -0
  49. package/dist/custom/artifacts/base-governed-artifact.action.js +201 -0
  50. package/dist/custom/artifacts/base-governed-artifact.action.js.map +1 -0
  51. package/dist/custom/artifacts/create-governed-artifact.action.d.ts +11 -0
  52. package/dist/custom/artifacts/create-governed-artifact.action.d.ts.map +1 -0
  53. package/dist/custom/artifacts/create-governed-artifact.action.js +104 -0
  54. package/dist/custom/artifacts/create-governed-artifact.action.js.map +1 -0
  55. package/dist/custom/artifacts/index.d.ts +6 -0
  56. package/dist/custom/artifacts/index.d.ts.map +1 -0
  57. package/dist/custom/artifacts/index.js +6 -0
  58. package/dist/custom/artifacts/index.js.map +1 -0
  59. package/dist/custom/artifacts/inspect-governed-artifact.action.d.ts +11 -0
  60. package/dist/custom/artifacts/inspect-governed-artifact.action.d.ts.map +1 -0
  61. package/dist/custom/artifacts/inspect-governed-artifact.action.js +84 -0
  62. package/dist/custom/artifacts/inspect-governed-artifact.action.js.map +1 -0
  63. package/dist/custom/artifacts/list-workspace-artifacts.action.d.ts +11 -0
  64. package/dist/custom/artifacts/list-workspace-artifacts.action.d.ts.map +1 -0
  65. package/dist/custom/artifacts/list-workspace-artifacts.action.js +63 -0
  66. package/dist/custom/artifacts/list-workspace-artifacts.action.js.map +1 -0
  67. package/dist/custom/artifacts/mutate-governed-artifact.action.d.ts +12 -0
  68. package/dist/custom/artifacts/mutate-governed-artifact.action.d.ts.map +1 -0
  69. package/dist/custom/artifacts/mutate-governed-artifact.action.js +110 -0
  70. package/dist/custom/artifacts/mutate-governed-artifact.action.js.map +1 -0
  71. package/dist/custom/crud/agent-data-policy-guard.d.ts +9 -1
  72. package/dist/custom/crud/agent-data-policy-guard.d.ts.map +1 -1
  73. package/dist/custom/crud/agent-data-policy-guard.js +49 -16
  74. package/dist/custom/crud/agent-data-policy-guard.js.map +1 -1
  75. package/dist/custom/data/adhoc-sql-gate.d.ts +40 -0
  76. package/dist/custom/data/adhoc-sql-gate.d.ts.map +1 -0
  77. package/dist/custom/data/adhoc-sql-gate.js +102 -0
  78. package/dist/custom/data/adhoc-sql-gate.js.map +1 -0
  79. package/dist/custom/data/data-mapper.action.d.ts +8 -0
  80. package/dist/custom/data/data-mapper.action.d.ts.map +1 -1
  81. package/dist/custom/data/data-mapper.action.js +21 -3
  82. package/dist/custom/data/data-mapper.action.js.map +1 -1
  83. package/dist/custom/data/find-graph-path.action.d.ts +37 -0
  84. package/dist/custom/data/find-graph-path.action.d.ts.map +1 -0
  85. package/dist/custom/data/find-graph-path.action.js +114 -0
  86. package/dist/custom/data/find-graph-path.action.js.map +1 -0
  87. package/dist/custom/data/get-graph-context.action.d.ts +22 -12
  88. package/dist/custom/data/get-graph-context.action.d.ts.map +1 -1
  89. package/dist/custom/data/get-graph-context.action.js +102 -239
  90. package/dist/custom/data/get-graph-context.action.js.map +1 -1
  91. package/dist/custom/data/graph-action-params.d.ts +51 -0
  92. package/dist/custom/data/graph-action-params.d.ts.map +1 -0
  93. package/dist/custom/data/graph-action-params.js +164 -0
  94. package/dist/custom/data/graph-action-params.js.map +1 -0
  95. package/dist/custom/data/mapping-template-guard.d.ts +18 -0
  96. package/dist/custom/data/mapping-template-guard.d.ts.map +1 -0
  97. package/dist/custom/data/mapping-template-guard.js +106 -0
  98. package/dist/custom/data/mapping-template-guard.js.map +1 -0
  99. package/dist/custom/data/propose-canon-domains.action.d.ts +26 -0
  100. package/dist/custom/data/propose-canon-domains.action.d.ts.map +1 -0
  101. package/dist/custom/data/propose-canon-domains.action.js +105 -0
  102. package/dist/custom/data/propose-canon-domains.action.js.map +1 -0
  103. package/dist/custom/data/run-adhoc-query.action.d.ts +4 -21
  104. package/dist/custom/data/run-adhoc-query.action.d.ts.map +1 -1
  105. package/dist/custom/data/run-adhoc-query.action.js +15 -105
  106. package/dist/custom/data/run-adhoc-query.action.js.map +1 -1
  107. package/dist/custom/demo/text-analyzer.action.d.ts +8 -0
  108. package/dist/custom/demo/text-analyzer.action.d.ts.map +1 -1
  109. package/dist/custom/demo/text-analyzer.action.js +34 -2
  110. package/dist/custom/demo/text-analyzer.action.js.map +1 -1
  111. package/dist/custom/files/excel-reader.action.d.ts +14 -0
  112. package/dist/custom/files/excel-reader.action.d.ts.map +1 -1
  113. package/dist/custom/files/excel-reader.action.js +51 -6
  114. package/dist/custom/files/excel-reader.action.js.map +1 -1
  115. package/dist/custom/github/github-client.d.ts.map +1 -1
  116. package/dist/custom/github/github-client.js +72 -11
  117. package/dist/custom/github/github-client.js.map +1 -1
  118. package/dist/custom/integration/http-request.action.d.ts.map +1 -1
  119. package/dist/custom/integration/http-request.action.js +5 -1
  120. package/dist/custom/integration/http-request.action.js.map +1 -1
  121. package/dist/custom/lists/create-list-from-query.action.d.ts +39 -0
  122. package/dist/custom/lists/create-list-from-query.action.d.ts.map +1 -0
  123. package/dist/custom/lists/create-list-from-query.action.js +179 -0
  124. package/dist/custom/lists/create-list-from-query.action.js.map +1 -0
  125. package/dist/custom/lists/index.d.ts +2 -0
  126. package/dist/custom/lists/index.d.ts.map +1 -1
  127. package/dist/custom/lists/index.js +2 -0
  128. package/dist/custom/lists/index.js.map +1 -1
  129. package/dist/custom/lists/refresh-list-from-source.action.d.ts.map +1 -1
  130. package/dist/custom/lists/refresh-list-from-source.action.js +3 -2
  131. package/dist/custom/lists/refresh-list-from-source.action.js.map +1 -1
  132. package/dist/custom/search/scoped-search.action.d.ts +12 -1
  133. package/dist/custom/search/scoped-search.action.d.ts.map +1 -1
  134. package/dist/custom/search/scoped-search.action.js +44 -6
  135. package/dist/custom/search/scoped-search.action.js.map +1 -1
  136. package/dist/custom/search/search-query.util.d.ts +24 -0
  137. package/dist/custom/search/search-query.util.d.ts.map +1 -0
  138. package/dist/custom/search/search-query.util.js +211 -0
  139. package/dist/custom/search/search-query.util.js.map +1 -0
  140. package/dist/custom/search/search.action.js +2 -2
  141. package/dist/custom/search/search.action.js.map +1 -1
  142. package/dist/custom/user-management/validate-email-unique.action.d.ts.map +1 -1
  143. package/dist/custom/user-management/validate-email-unique.action.js +2 -3
  144. package/dist/custom/user-management/validate-email-unique.action.js.map +1 -1
  145. package/dist/custom/utilities/refresh-and-snapshot-artifact.action.d.ts +48 -0
  146. package/dist/custom/utilities/refresh-and-snapshot-artifact.action.d.ts.map +1 -0
  147. package/dist/custom/utilities/refresh-and-snapshot-artifact.action.js +248 -0
  148. package/dist/custom/utilities/refresh-and-snapshot-artifact.action.js.map +1 -0
  149. package/dist/custom/web/rss-feed-parsing.d.ts.map +1 -1
  150. package/dist/custom/web/rss-feed-parsing.js +80 -6
  151. package/dist/custom/web/rss-feed-parsing.js.map +1 -1
  152. package/dist/custom/web/url-link-validator.action.d.ts.map +1 -1
  153. package/dist/custom/web/url-link-validator.action.js +3 -1
  154. package/dist/custom/web/url-link-validator.action.js.map +1 -1
  155. package/dist/custom/web/web-content-transforms.d.ts +35 -0
  156. package/dist/custom/web/web-content-transforms.d.ts.map +1 -0
  157. package/dist/custom/web/web-content-transforms.js +157 -0
  158. package/dist/custom/web/web-content-transforms.js.map +1 -0
  159. package/dist/custom/web/web-page-content.action.d.ts +4 -20
  160. package/dist/custom/web/web-page-content.action.d.ts.map +1 -1
  161. package/dist/custom/web/web-page-content.action.js +23 -168
  162. package/dist/custom/web/web-page-content.action.js.map +1 -1
  163. package/dist/custom/web/worker/ServeWorkerRequests.d.ts +26 -0
  164. package/dist/custom/web/worker/ServeWorkerRequests.d.ts.map +1 -0
  165. package/dist/custom/web/worker/ServeWorkerRequests.js +33 -0
  166. package/dist/custom/web/worker/ServeWorkerRequests.js.map +1 -0
  167. package/dist/custom/web/worker/WebContentWorker.d.ts +9 -0
  168. package/dist/custom/web/worker/WebContentWorker.d.ts.map +1 -0
  169. package/dist/custom/web/worker/WebContentWorker.js +11 -0
  170. package/dist/custom/web/worker/WebContentWorker.js.map +1 -0
  171. package/dist/custom/web/worker/WebContentWorkerHandler.d.ts +11 -0
  172. package/dist/custom/web/worker/WebContentWorkerHandler.d.ts.map +1 -0
  173. package/dist/custom/web/worker/WebContentWorkerHandler.js +19 -0
  174. package/dist/custom/web/worker/WebContentWorkerHandler.js.map +1 -0
  175. package/dist/custom/web/worker/WebContentWorkerHost.d.ts +26 -0
  176. package/dist/custom/web/worker/WebContentWorkerHost.d.ts.map +1 -0
  177. package/dist/custom/web/worker/WebContentWorkerHost.js +37 -0
  178. package/dist/custom/web/worker/WebContentWorkerHost.js.map +1 -0
  179. package/dist/custom/web/worker/WebContentWorkerProtocol.d.ts +23 -0
  180. package/dist/custom/web/worker/WebContentWorkerProtocol.d.ts.map +1 -0
  181. package/dist/custom/web/worker/WebContentWorkerProtocol.js +8 -0
  182. package/dist/custom/web/worker/WebContentWorkerProtocol.js.map +1 -0
  183. package/dist/custom/web/worker/WorkerProtocol.d.ts +36 -0
  184. package/dist/custom/web/worker/WorkerProtocol.d.ts.map +1 -0
  185. package/dist/custom/web/worker/WorkerProtocol.js +9 -0
  186. package/dist/custom/web/worker/WorkerProtocol.js.map +1 -0
  187. package/dist/custom/web/worker/WorkerThreadHost.d.ts +88 -0
  188. package/dist/custom/web/worker/WorkerThreadHost.d.ts.map +1 -0
  189. package/dist/custom/web/worker/WorkerThreadHost.js +174 -0
  190. package/dist/custom/web/worker/WorkerThreadHost.js.map +1 -0
  191. package/dist/custom/workflow/loop.action.d.ts +8 -0
  192. package/dist/custom/workflow/loop.action.d.ts.map +1 -1
  193. package/dist/custom/workflow/loop.action.js +36 -4
  194. package/dist/custom/workflow/loop.action.js.map +1 -1
  195. package/dist/index.d.ts +9 -1
  196. package/dist/index.d.ts.map +1 -1
  197. package/dist/index.js +10 -2
  198. package/dist/index.js.map +1 -1
  199. package/dist/tsconfig.tsbuildinfo +1 -0
  200. package/package.json +45 -45
@@ -0,0 +1,843 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ 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;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseAction } from '@memberjunction/actions';
8
+ import { EscapeSQLString, RegisterClass, SafeJSONParse, UUIDsEqual } from '@memberjunction/global';
9
+ import { LogError, Metadata, RunView } from '@memberjunction/core';
10
+ import { BUILT_IN_CONVERSATION_TYPE_IDS, CONVERSATION_TYPE_CODES, ConversationEngine, } from '@memberjunction/core-entities';
11
+ import { AgentUserPolicyEngine, ResolveAgentRunLimits, TypedActionPolicyGuard, } from '@memberjunction/ai-core-plus';
12
+ import { AIEngine } from '@memberjunction/aiengine';
13
+ import { AgentWakeTriggerService } from '@memberjunction/ai-agents';
14
+ import { UserCache } from '@memberjunction/generic-database-provider';
15
+ const DEFAULT_AGENT_NAME = 'Chief of Staff';
16
+ const MY_AGENTS_APPLICATION_ID = 'C05A8E01-4C11-4E8A-9B01-1A2B3C4D5E70';
17
+ /**
18
+ * A new entity object, or an error that names the entity. `GetEntityObject` logs and returns null
19
+ * when the entity cannot be created (for example, a database whose migration for it has not run),
20
+ * and dereferencing that null hides the cause behind "Cannot read properties of null".
21
+ */
22
+ async function newEntityObject(md, entityName, user) {
23
+ const entity = await md.GetEntityObject(entityName, user);
24
+ if (!entity) {
25
+ throw new Error(`Entity ${entityName} not found in metadata or could not be created`);
26
+ }
27
+ return entity;
28
+ }
29
+ function resolveMyAgentsApplicationId(md) {
30
+ const apps = md.Applications;
31
+ if (!Array.isArray(apps)) {
32
+ return MY_AGENTS_APPLICATION_ID;
33
+ }
34
+ const found = apps.find((a) => UUIDsEqual(a.ID, MY_AGENTS_APPLICATION_ID)) ??
35
+ apps.find((a) => {
36
+ const name = a.Name?.trim().toLowerCase();
37
+ return name === 'my agents' || name === 'chief of staff';
38
+ });
39
+ return found?.ID ?? null;
40
+ }
41
+ function readStringParam(params, name) {
42
+ const found = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase());
43
+ if (found?.Value == null) {
44
+ return undefined;
45
+ }
46
+ const str = String(found.Value).trim();
47
+ return str.length > 0 ? str : undefined;
48
+ }
49
+ function readNumberParam(params, name, fallback, min, max) {
50
+ const raw = readStringParam(params, name);
51
+ if (!raw) {
52
+ return fallback;
53
+ }
54
+ const parsed = Number(raw);
55
+ if (!Number.isFinite(parsed)) {
56
+ return fallback;
57
+ }
58
+ return Math.min(max, Math.max(min, Math.trunc(parsed)));
59
+ }
60
+ function readOptionalPositiveIntParam(params, name) {
61
+ const raw = readStringParam(params, name);
62
+ if (!raw) {
63
+ return undefined;
64
+ }
65
+ const parsed = Number(raw);
66
+ if (!Number.isFinite(parsed)) {
67
+ return undefined;
68
+ }
69
+ return Math.max(1, Math.trunc(parsed));
70
+ }
71
+ function readBooleanParam(params, name, fallback) {
72
+ const found = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase());
73
+ if (found?.Value == null) {
74
+ return fallback;
75
+ }
76
+ if (typeof found.Value === 'boolean') {
77
+ return found.Value;
78
+ }
79
+ const normalized = String(found.Value).trim().toLowerCase();
80
+ if (normalized === 'true' || normalized === '1' || normalized === 'yes') {
81
+ return true;
82
+ }
83
+ if (normalized === 'false' || normalized === '0' || normalized === 'no') {
84
+ return false;
85
+ }
86
+ return fallback;
87
+ }
88
+ function readStringArrayParam(params, name) {
89
+ const found = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase());
90
+ if (found?.Value == null) {
91
+ return [];
92
+ }
93
+ if (Array.isArray(found.Value)) {
94
+ return found.Value.map((v) => String(v).trim()).filter(Boolean);
95
+ }
96
+ const raw = String(found.Value).trim();
97
+ if (!raw) {
98
+ return [];
99
+ }
100
+ if (raw.startsWith('[')) {
101
+ const parsed = SafeJSONParse(raw);
102
+ if (Array.isArray(parsed)) {
103
+ return parsed.map((v) => String(v).trim()).filter(Boolean);
104
+ }
105
+ }
106
+ return raw
107
+ .split(',')
108
+ .map((s) => s.trim())
109
+ .filter(Boolean);
110
+ }
111
+ function extractContextAgentId(context) {
112
+ if (!context || typeof context !== 'object') {
113
+ return undefined;
114
+ }
115
+ const val = context.AgentID;
116
+ return typeof val === 'string' && val.trim().length > 0 ? val.trim() : undefined;
117
+ }
118
+ function resolveAgent(params, idParam, nameParam) {
119
+ const explicitId = readStringParam(params, idParam);
120
+ if (explicitId) {
121
+ return AIEngine.Instance.Agents.find((a) => UUIDsEqual(a.ID, explicitId)) ?? null;
122
+ }
123
+ const contextId = idParam === 'AgentID' ? extractContextAgentId(params.Context) : undefined;
124
+ if (contextId) {
125
+ return AIEngine.Instance.Agents.find((a) => UUIDsEqual(a.ID, contextId)) ?? null;
126
+ }
127
+ const explicitName = readStringParam(params, nameParam) ?? DEFAULT_AGENT_NAME;
128
+ const callerUserId = params.ContextUser?.ID ?? null;
129
+ const matches = AIEngine.Instance.Agents.filter((a) => a.Name.trim().toLowerCase() === explicitName.toLowerCase() && (a.Status == null || a.Status === 'Active'));
130
+ if (callerUserId && matches.length > 1) {
131
+ const ownedMatch = matches.find((a) => a.OwnerUserID && UUIDsEqual(a.OwnerUserID, callerUserId));
132
+ if (ownedMatch) {
133
+ return ownedMatch;
134
+ }
135
+ }
136
+ return (matches[0] ??
137
+ AIEngine.Instance.Agents.find((a) => a.Name.trim().toLowerCase() === explicitName.toLowerCase()) ??
138
+ null);
139
+ }
140
+ function setOutputParam(params, name, value) {
141
+ const existing = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase() && p.Type === 'Output');
142
+ if (existing) {
143
+ existing.Value = value;
144
+ return params.Params;
145
+ }
146
+ return [...params.Params, { Name: name, Type: 'Output', Value: value }];
147
+ }
148
+ async function verifyApprovedRequest(approvalRequestId, ownerUserId, contextUser, md) {
149
+ const rv = RunView.FromMetadataProvider(md);
150
+ const res = await rv.RunView({
151
+ EntityName: 'MJ: AI Agent Requests',
152
+ ExtraFilter: `ID='${EscapeSQLString(approvalRequestId)}' AND RequestForUserID='${EscapeSQLString(ownerUserId)}' AND Status='Approved'`,
153
+ MaxRows: 1,
154
+ ResultType: 'entity_object',
155
+ }, contextUser);
156
+ return Boolean(res.Success && res.Results.length > 0);
157
+ }
158
+ /**
159
+ * Opens a shared, observable `AGENT_CHANNEL` conversation (`MJ: Agent Channels` IS-A
160
+ * `MJ: Conversations`) between the caller's agent and one or more colleagues' agents,
161
+ * enforcing `CoordinationMode` (`Observer` blocked, `Coordinator` requires approval when run
162
+ * autonomously, `Autonomous` allowed) and waking peer agents under loop-guard / rate-limit bounds.
163
+ */
164
+ let OpenAgentChannelAction = class OpenAgentChannelAction extends BaseAction {
165
+ static { this.AuthorizesCaller = true; }
166
+ async InternalRunAction(params) {
167
+ try {
168
+ const contextUser = params.ContextUser;
169
+ if (!contextUser?.ID) {
170
+ return {
171
+ Success: false,
172
+ ResultCode: 'MISSING_USER_CONTEXT',
173
+ Message: 'Open Agent Channel requires a valid ContextUser.',
174
+ Params: params.Params,
175
+ };
176
+ }
177
+ const topic = readStringParam(params, 'Topic');
178
+ const initialMessage = readStringParam(params, 'InitialMessage');
179
+ const targetUserIds = Array.from(new Set([
180
+ ...readStringArrayParam(params, 'TargetUserIDs'),
181
+ ...readStringArrayParam(params, 'TargetUserID'),
182
+ ])).filter((id) => !UUIDsEqual(id, contextUser.ID));
183
+ const explicitTargetAgentRef = Boolean(readStringParam(params, 'TargetAgentID') || readStringParam(params, 'TargetAgentName'));
184
+ if (!topic || !initialMessage || (targetUserIds.length === 0 && !explicitTargetAgentRef)) {
185
+ return {
186
+ Success: false,
187
+ ResultCode: 'VALIDATION_ERROR',
188
+ Message: 'Topic, InitialMessage, and either colleague TargetUserID/TargetUserIDs or a sibling TargetAgentID/TargetAgentName are required.',
189
+ Params: params.Params,
190
+ };
191
+ }
192
+ const createGuard = await TypedActionPolicyGuard.CheckEntityAccess({
193
+ entityName: 'MJ: Agent Channels',
194
+ operation: 'Create',
195
+ contextUser,
196
+ actionContext: params.Context,
197
+ provider: params.Provider,
198
+ });
199
+ if (!createGuard.Allowed) {
200
+ return {
201
+ Success: false,
202
+ ResultCode: createGuard.ResultCode,
203
+ Message: createGuard.Message,
204
+ Params: params.Params,
205
+ };
206
+ }
207
+ await AIEngine.Instance.Config(false, contextUser);
208
+ const senderAgent = resolveAgent(params, 'AgentID', 'AgentName');
209
+ if (!senderAgent) {
210
+ return {
211
+ Success: false,
212
+ ResultCode: 'AGENT_NOT_FOUND',
213
+ Message: 'Could not resolve sender AI Agent.',
214
+ Params: params.Params,
215
+ };
216
+ }
217
+ const resolvedTargetAgent = explicitTargetAgentRef
218
+ ? resolveAgent(params, 'TargetAgentID', 'TargetAgentName')
219
+ : senderAgent;
220
+ if (!resolvedTargetAgent) {
221
+ const requestedRef = readStringParam(params, 'TargetAgentName') ??
222
+ readStringParam(params, 'TargetAgentID') ??
223
+ 'unknown';
224
+ return {
225
+ Success: false,
226
+ ResultCode: 'AGENT_NOT_FOUND',
227
+ Message: `Target agent "${requestedRef}" was not found.`,
228
+ Params: params.Params,
229
+ };
230
+ }
231
+ const targetAgent = resolvedTargetAgent;
232
+ if (targetUserIds.length === 0 && UUIDsEqual(targetAgent.ID, senderAgent.ID)) {
233
+ return {
234
+ Success: false,
235
+ ResultCode: 'VALIDATION_ERROR',
236
+ Message: `Agent "${senderAgent.Name}" cannot open an Agent Channel with itself without another colleague participant.`,
237
+ Params: params.Params,
238
+ };
239
+ }
240
+ // Same-user sibling channel (e.g., Pepper <-> Cato owned by or accessible to contextUser)
241
+ const sameUserPeerUserId = targetUserIds.length === 0
242
+ ? targetAgent.OwnerUserID && !UUIDsEqual(targetAgent.OwnerUserID, contextUser.ID)
243
+ ? targetAgent.OwnerUserID
244
+ : contextUser.ID
245
+ : null;
246
+ if (sameUserPeerUserId &&
247
+ UUIDsEqual(sameUserPeerUserId, contextUser.ID) &&
248
+ !AIEngine.Instance.CanUserViewAgent(targetAgent.ID, contextUser)) {
249
+ return {
250
+ Success: false,
251
+ ResultCode: 'POLICY_DENIED',
252
+ Message: `You do not have permission to include agent "${targetAgent.Name}" in an Agent Channel.`,
253
+ Params: params.Params,
254
+ };
255
+ }
256
+ const effectiveCrossUserIds = sameUserPeerUserId && !UUIDsEqual(sameUserPeerUserId, contextUser.ID)
257
+ ? [sameUserPeerUserId]
258
+ : targetUserIds;
259
+ const hasCrossUserTargets = effectiveCrossUserIds.length > 0;
260
+ const md = params.Provider ?? Metadata.Provider;
261
+ const senderPolicyLookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(senderAgent.ID, contextUser.ID, contextUser, { provider: md });
262
+ if (senderPolicyLookup.status === 'error') {
263
+ return {
264
+ Success: false,
265
+ ResultCode: 'POLICY_DENIED',
266
+ Message: `Unable to verify sender agent policy: ${senderPolicyLookup.errorMessage}`,
267
+ Params: params.Params,
268
+ };
269
+ }
270
+ const senderPolicy = senderPolicyLookup.policy;
271
+ if (senderPolicy) {
272
+ if (senderPolicy.Status === 'Disabled' || senderPolicy.Status === 'Paused') {
273
+ return {
274
+ Success: false,
275
+ ResultCode: 'POLICY_DENIED',
276
+ Message: `Agent policy is ${senderPolicy.Status}; opening an Agent Channel is not permitted.`,
277
+ Params: params.Params,
278
+ };
279
+ }
280
+ if (senderPolicy.AllowInterAgentCoordination === false) {
281
+ return {
282
+ Success: false,
283
+ ResultCode: 'POLICY_DENIED',
284
+ Message: 'Inter-agent coordination is disabled in your agent policy.',
285
+ Params: params.Params,
286
+ };
287
+ }
288
+ if (hasCrossUserTargets && senderPolicy.CoordinationMode === 'Observer') {
289
+ return {
290
+ Success: false,
291
+ ResultCode: 'POLICY_DENIED',
292
+ Message: 'CoordinationMode is Observer; agent cannot initiate peer channels.',
293
+ Params: params.Params,
294
+ };
295
+ }
296
+ const isAgentCall = Boolean(extractContextAgentId(params.Context));
297
+ if (hasCrossUserTargets && isAgentCall && senderPolicy.CoordinationMode === 'Coordinator') {
298
+ const approvalId = readStringParam(params, 'ConfirmedApprovalRequestID');
299
+ const approved = approvalId
300
+ ? await verifyApprovedRequest(approvalId, contextUser.ID, contextUser, md)
301
+ : false;
302
+ if (!approved) {
303
+ return {
304
+ Success: false,
305
+ ResultCode: 'APPROVAL_REQUIRED',
306
+ Message: 'CoordinationMode is Coordinator: user confirmation (ConfirmedApprovalRequestID) is required before opening a peer Agent Channel.',
307
+ Params: params.Params,
308
+ };
309
+ }
310
+ }
311
+ }
312
+ const systemUser = UserCache.Instance.GetSystemUser() ?? contextUser;
313
+ const rv = RunView.FromMetadataProvider(md);
314
+ // Validate every cross-user target is active
315
+ let activeTargets = [];
316
+ if (effectiveCrossUserIds.length > 0) {
317
+ const targetUsersRes = await rv.RunView({
318
+ EntityName: 'MJ: Users',
319
+ ExtraFilter: `IsActive=1 AND ID IN (${effectiveCrossUserIds
320
+ .map((id) => `'${EscapeSQLString(id)}'`)
321
+ .join(',')})`,
322
+ ResultType: 'entity_object',
323
+ }, systemUser);
324
+ activeTargets = targetUsersRes.Success ? targetUsersRes.Results : [];
325
+ if (activeTargets.length !== effectiveCrossUserIds.length) {
326
+ return {
327
+ Success: false,
328
+ ResultCode: 'VALIDATION_ERROR',
329
+ Message: 'One or more TargetUserIDs do not match an active MJ user.',
330
+ Params: params.Params,
331
+ };
332
+ }
333
+ }
334
+ const requestedMaxTurns = readOptionalPositiveIntParam(params, 'MaxConsecutiveAgentTurns');
335
+ const requestedMaxHourlyWakes = readOptionalPositiveIntParam(params, 'MaxHourlyWakes');
336
+ const channelRunOverride = {};
337
+ if (requestedMaxTurns !== undefined) {
338
+ channelRunOverride.AgentChannelConsecutiveTurns = requestedMaxTurns;
339
+ }
340
+ if (requestedMaxHourlyWakes !== undefined) {
341
+ channelRunOverride.AgentChannelWakesPerHour = requestedMaxHourlyWakes;
342
+ }
343
+ const limitsResolution = ResolveAgentRunLimits({
344
+ Agent: senderAgent,
345
+ UserPolicy: senderPolicy,
346
+ RunOverride: Object.keys(channelRunOverride).length > 0 ? channelRunOverride : null,
347
+ ContextUser: contextUser,
348
+ Provider: md,
349
+ Options: {
350
+ EnforceUserPolicyAsCeiling: Boolean(senderPolicy),
351
+ EnforceConfiguredCeilings: true,
352
+ AllowAuthorizedCeilingOverride: true,
353
+ },
354
+ });
355
+ const maxTurns = limitsResolution.Limits.AgentChannelConsecutiveTurns;
356
+ const maxHourlyWakes = limitsResolution.Limits.AgentChannelWakesPerHour;
357
+ const replyByRaw = readStringParam(params, 'ReplyByISO');
358
+ const replyByDate = replyByRaw ? new Date(replyByRaw) : null;
359
+ if (replyByDate && Number.isNaN(replyByDate.getTime())) {
360
+ return {
361
+ Success: false,
362
+ ResultCode: 'VALIDATION_ERROR',
363
+ Message: `Invalid ReplyByISO timestamp "${replyByRaw}".`,
364
+ Params: params.Params,
365
+ };
366
+ }
367
+ const agentChannelTypeId = ConversationEngine.Instance.ResolveConversationTypeID(CONVERSATION_TYPE_CODES.AGENT_CHANNEL) ??
368
+ BUILT_IN_CONVERSATION_TYPE_IDS.AGENT_CHANNEL;
369
+ const myAgentsAppId = resolveMyAgentsApplicationId(md);
370
+ const channel = await newEntityObject(md, 'MJ: Agent Channels', systemUser);
371
+ channel.NewRecord();
372
+ channel.Name = topic.slice(0, 255);
373
+ channel.UserID = contextUser.ID;
374
+ channel.TypeID = agentChannelTypeId;
375
+ if (myAgentsAppId) {
376
+ channel.ApplicationScope = 'Application';
377
+ channel.ApplicationID = myAgentsAppId;
378
+ }
379
+ else {
380
+ channel.ApplicationScope = 'Global';
381
+ }
382
+ channel.Topic = topic;
383
+ channel.ChannelStatus = 'Open';
384
+ channel.ReplyBy = replyByDate;
385
+ channel.ConsecutiveAgentTurns = 0;
386
+ channel.MaxConsecutiveAgentTurns = maxTurns;
387
+ channel.HourlyWakeCount = 0;
388
+ channel.MaxHourlyWakes = maxHourlyWakes;
389
+ const channelSaved = await channel.Save();
390
+ if (!channelSaved) {
391
+ return {
392
+ Success: false,
393
+ ResultCode: 'SAVE_FAILED',
394
+ Message: channel.LatestResult?.CompleteMessage || 'Failed to create Agent Channel.',
395
+ Params: params.Params,
396
+ };
397
+ }
398
+ // Create participant records (initiator + all peers).
399
+ // Preserve explicit derived instances (e.g., Cato); only redirect root templates (e.g., Chief of Staff) to the peer's primary instance.
400
+ const resolvePeerAgentId = (baseTarget, userId) => {
401
+ if (baseTarget.BaseAgentID) {
402
+ return baseTarget.ID;
403
+ }
404
+ if (typeof AIEngine.Instance.ResolvePrimaryUserAgentInstance === 'function') {
405
+ const resolved = AIEngine.Instance.ResolvePrimaryUserAgentInstance(baseTarget.ID, userId);
406
+ if (resolved) {
407
+ return resolved.ID;
408
+ }
409
+ }
410
+ return baseTarget.ID;
411
+ };
412
+ const participantSpecs = [
413
+ { userId: contextUser.ID, agentId: senderAgent.ID, role: 'Initiator' },
414
+ ...(activeTargets.length > 0
415
+ ? activeTargets.map((u) => ({
416
+ userId: u.ID,
417
+ agentId: resolvePeerAgentId(targetAgent, u.ID),
418
+ role: 'Participant',
419
+ }))
420
+ : [
421
+ {
422
+ userId: contextUser.ID,
423
+ agentId: targetAgent.ID,
424
+ role: 'Participant',
425
+ },
426
+ ]),
427
+ ];
428
+ for (const spec of participantSpecs) {
429
+ const participant = await newEntityObject(md, 'MJ: Agent Channel Participants', systemUser);
430
+ participant.NewRecord();
431
+ participant.AgentChannelID = channel.ID;
432
+ participant.UserID = spec.userId;
433
+ participant.AgentID = spec.agentId;
434
+ participant.Role = spec.role;
435
+ participant.JoinedAt = new Date();
436
+ const savedPart = await participant.Save();
437
+ if (!savedPart) {
438
+ return {
439
+ Success: false,
440
+ ResultCode: 'SAVE_FAILED',
441
+ Message: participant.LatestResult?.CompleteMessage ||
442
+ `Failed to add participant "${spec.userId}" to Agent Channel.`,
443
+ Params: params.Params,
444
+ };
445
+ }
446
+ }
447
+ // Post opening message as contextUser (channel initiator/participant); mark server-authored when an agent posts.
448
+ const callingAgentId = extractContextAgentId(params.Context);
449
+ const detail = await newEntityObject(md, 'MJ: Conversation Details', contextUser);
450
+ detail.NewRecord();
451
+ detail.ConversationID = channel.ID;
452
+ detail.UserID = contextUser.ID;
453
+ detail.AgentID = callingAgentId ?? null;
454
+ detail.Role = callingAgentId ? 'AI' : 'User';
455
+ detail.Message = initialMessage;
456
+ if (callingAgentId && typeof detail.MarkServerAuthoredReply === 'function') {
457
+ detail.MarkServerAuthoredReply();
458
+ }
459
+ const detailSaved = await detail.Save();
460
+ if (!detailSaved) {
461
+ return {
462
+ Success: false,
463
+ ResultCode: 'SAVE_FAILED',
464
+ Message: detail.LatestResult?.CompleteMessage || 'Failed to save opening Agent Channel message.',
465
+ Params: params.Params,
466
+ };
467
+ }
468
+ const wakeOutcome = await AgentWakeTriggerService.Instance.TriggerWakeOnAgentChannelMessage({
469
+ channelID: channel.ID,
470
+ conversationDetailID: detail.ID,
471
+ senderUserID: contextUser.ID,
472
+ senderAgentID: callingAgentId ?? null,
473
+ messagePreview: initialMessage,
474
+ contextUser,
475
+ metadataProvider: md,
476
+ });
477
+ const payload = {
478
+ ChannelID: channel.ID,
479
+ ConversationDetailID: detail.ID,
480
+ Topic: channel.Topic,
481
+ ChannelStatus: wakeOutcome.channelStatus,
482
+ Participants: participantSpecs,
483
+ WakeResults: wakeOutcome.results,
484
+ };
485
+ return {
486
+ Success: true,
487
+ ResultCode: 'SUCCESS',
488
+ Message: JSON.stringify(payload),
489
+ Params: setOutputParam(params, 'ChannelID', channel.ID),
490
+ };
491
+ }
492
+ catch (error) {
493
+ const msg = error instanceof Error ? error.message : String(error);
494
+ LogError(`[OpenAgentChannelAction] ${msg}`);
495
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
496
+ }
497
+ }
498
+ };
499
+ OpenAgentChannelAction = __decorate([
500
+ RegisterClass(BaseAction, 'Open Agent Channel')
501
+ ], OpenAgentChannelAction);
502
+ export { OpenAgentChannelAction };
503
+ /**
504
+ * Posts a reply into an existing `AGENT_CHANNEL` conversation, enforcing participant
505
+ * membership, loop-guard / hourly wake caps, and optional channel resolution.
506
+ */
507
+ let ReplyInAgentChannelAction = class ReplyInAgentChannelAction extends BaseAction {
508
+ static { this.AuthorizesCaller = true; }
509
+ async InternalRunAction(params) {
510
+ try {
511
+ const contextUser = params.ContextUser;
512
+ if (!contextUser?.ID) {
513
+ return {
514
+ Success: false,
515
+ ResultCode: 'MISSING_USER_CONTEXT',
516
+ Message: 'Reply In Agent Channel requires a valid ContextUser.',
517
+ Params: params.Params,
518
+ };
519
+ }
520
+ const channelId = readStringParam(params, 'ChannelID');
521
+ const message = readStringParam(params, 'Message');
522
+ const resolveChannel = readBooleanParam(params, 'ResolveChannel', false);
523
+ if (!channelId || !message) {
524
+ return {
525
+ Success: false,
526
+ ResultCode: 'VALIDATION_ERROR',
527
+ Message: 'ChannelID and Message are required.',
528
+ Params: params.Params,
529
+ };
530
+ }
531
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
532
+ entityName: 'MJ: Agent Channels',
533
+ operation: 'Update',
534
+ writeFields: ['ChannelStatus', 'ConsecutiveAgentTurns', 'HourlyWakeCount'],
535
+ contextUser,
536
+ actionContext: params.Context,
537
+ provider: params.Provider,
538
+ });
539
+ if (!guard.Allowed) {
540
+ return {
541
+ Success: false,
542
+ ResultCode: guard.ResultCode,
543
+ Message: guard.Message,
544
+ Params: params.Params,
545
+ };
546
+ }
547
+ const md = params.Provider ?? Metadata.Provider;
548
+ const systemUser = UserCache.Instance.GetSystemUser() ?? contextUser;
549
+ const channel = await newEntityObject(md, 'MJ: Agent Channels', systemUser);
550
+ const loaded = await channel.Load(channelId);
551
+ if (!loaded) {
552
+ return {
553
+ Success: false,
554
+ ResultCode: 'NOT_FOUND',
555
+ Message: `Agent Channel "${channelId}" was not found.`,
556
+ Params: params.Params,
557
+ };
558
+ }
559
+ const rv = RunView.FromMetadataProvider(md);
560
+ const partRes = await rv.RunView({
561
+ EntityName: 'MJ: Agent Channel Participants',
562
+ ExtraFilter: `AgentChannelID='${EscapeSQLString(channel.ID)}' AND UserID='${EscapeSQLString(contextUser.ID)}'`,
563
+ MaxRows: 1,
564
+ ResultType: 'entity_object',
565
+ }, systemUser);
566
+ const isParticipant = partRes.Success && partRes.Results.length > 0;
567
+ if (!isParticipant && contextUser.Type?.trim().toLowerCase() !== 'owner') {
568
+ return {
569
+ Success: false,
570
+ ResultCode: 'POLICY_DENIED',
571
+ Message: 'You are not a participant in this Agent Channel.',
572
+ Params: params.Params,
573
+ };
574
+ }
575
+ if (channel.ChannelStatus === 'Resolved') {
576
+ return {
577
+ Success: false,
578
+ ResultCode: 'CHANNEL_RESOLVED',
579
+ Message: `Agent Channel "${channel.Topic}" is already Resolved.`,
580
+ Params: params.Params,
581
+ };
582
+ }
583
+ const callingAgentId = extractContextAgentId(params.Context);
584
+ if (callingAgentId && channel.ChannelStatus === 'Paused For Human') {
585
+ return {
586
+ Success: false,
587
+ ResultCode: 'CHANNEL_PAUSED_LOOP_GUARD',
588
+ Message: `Agent Channel "${channel.Topic}" is paused awaiting human intervention; an agent cannot post until a human replies.`,
589
+ Params: params.Params,
590
+ };
591
+ }
592
+ const detail = await newEntityObject(md, 'MJ: Conversation Details', contextUser);
593
+ detail.NewRecord();
594
+ detail.ConversationID = channel.ID;
595
+ detail.UserID = contextUser.ID;
596
+ detail.AgentID = callingAgentId ?? null;
597
+ detail.Role = callingAgentId ? 'AI' : 'User';
598
+ detail.Message = message;
599
+ if (callingAgentId && typeof detail.MarkServerAuthoredReply === 'function') {
600
+ detail.MarkServerAuthoredReply();
601
+ }
602
+ const savedDetail = await detail.Save();
603
+ if (!savedDetail) {
604
+ return {
605
+ Success: false,
606
+ ResultCode: 'SAVE_FAILED',
607
+ Message: detail.LatestResult?.CompleteMessage || 'Failed to save Agent Channel reply.',
608
+ Params: params.Params,
609
+ };
610
+ }
611
+ if (resolveChannel) {
612
+ channel.ChannelStatus = 'Resolved';
613
+ channel.ResolvedAt = new Date();
614
+ const resolvedSaved = await channel.Save();
615
+ if (!resolvedSaved) {
616
+ return {
617
+ Success: false,
618
+ ResultCode: 'SAVE_FAILED',
619
+ Message: channel.LatestResult?.CompleteMessage ||
620
+ 'Failed to mark Agent Channel as Resolved.',
621
+ Params: params.Params,
622
+ };
623
+ }
624
+ const resolvedPayload = {
625
+ ChannelID: channel.ID,
626
+ ConversationDetailID: detail.ID,
627
+ ChannelStatus: 'Resolved',
628
+ PausedByGuard: false,
629
+ PauseReason: null,
630
+ WakeResults: [],
631
+ };
632
+ return {
633
+ Success: true,
634
+ ResultCode: 'SUCCESS',
635
+ Message: JSON.stringify(resolvedPayload),
636
+ Params: setOutputParam(params, 'ConversationDetailID', detail.ID),
637
+ };
638
+ }
639
+ const wakeOutcome = await AgentWakeTriggerService.Instance.TriggerWakeOnAgentChannelMessage({
640
+ channelID: channel.ID,
641
+ conversationDetailID: detail.ID,
642
+ senderUserID: contextUser.ID,
643
+ senderAgentID: callingAgentId ?? null,
644
+ messagePreview: message,
645
+ contextUser,
646
+ metadataProvider: md,
647
+ });
648
+ const payload = {
649
+ ChannelID: channel.ID,
650
+ ConversationDetailID: detail.ID,
651
+ ChannelStatus: wakeOutcome.channelStatus,
652
+ PausedByGuard: wakeOutcome.pausedByGuard,
653
+ PauseReason: wakeOutcome.pauseReason,
654
+ WakeResults: wakeOutcome.results,
655
+ };
656
+ return {
657
+ Success: true,
658
+ ResultCode: wakeOutcome.pausedByGuard ? 'CHANNEL_PAUSED_LOOP_GUARD' : 'SUCCESS',
659
+ Message: JSON.stringify(payload),
660
+ Params: setOutputParam(params, 'ConversationDetailID', detail.ID),
661
+ };
662
+ }
663
+ catch (error) {
664
+ const msg = error instanceof Error ? error.message : String(error);
665
+ LogError(`[ReplyInAgentChannelAction] ${msg}`);
666
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
667
+ }
668
+ }
669
+ };
670
+ ReplyInAgentChannelAction = __decorate([
671
+ RegisterClass(BaseAction, 'Reply In Agent Channel')
672
+ ], ReplyInAgentChannelAction);
673
+ export { ReplyInAgentChannelAction };
674
+ /**
675
+ * Reads an `AGENT_CHANNEL` conversation (metadata, participants, guard counters, and messages)
676
+ * or lists the calling user's Agent Channels when `ChannelID` is omitted.
677
+ */
678
+ let GetAgentChannelAction = class GetAgentChannelAction extends BaseAction {
679
+ static { this.AuthorizesCaller = true; }
680
+ async InternalRunAction(params) {
681
+ try {
682
+ const contextUser = params.ContextUser;
683
+ if (!contextUser?.ID) {
684
+ return {
685
+ Success: false,
686
+ ResultCode: 'MISSING_USER_CONTEXT',
687
+ Message: 'Get Agent Channel requires a valid ContextUser.',
688
+ Params: params.Params,
689
+ };
690
+ }
691
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
692
+ entityName: 'MJ: Agent Channels',
693
+ operation: 'Read',
694
+ contextUser,
695
+ actionContext: params.Context,
696
+ provider: params.Provider,
697
+ });
698
+ if (!guard.Allowed) {
699
+ return {
700
+ Success: false,
701
+ ResultCode: guard.ResultCode,
702
+ Message: guard.Message,
703
+ Params: params.Params,
704
+ };
705
+ }
706
+ const channelId = readStringParam(params, 'ChannelID');
707
+ const statusFilter = readStringParam(params, 'Status');
708
+ const maxMessages = readNumberParam(params, 'MaxMessages', 30, 1, 100);
709
+ const md = params.Provider ?? Metadata.Provider;
710
+ const rv = RunView.FromMetadataProvider(md);
711
+ const systemUser = UserCache.Instance.GetSystemUser() ?? contextUser;
712
+ const isOwner = contextUser.Type?.trim().toLowerCase() === 'owner';
713
+ if (!channelId) {
714
+ const myPartsRes = await rv.RunView({
715
+ EntityName: 'MJ: Agent Channel Participants',
716
+ ExtraFilter: `UserID='${EscapeSQLString(contextUser.ID)}'`,
717
+ ResultType: 'entity_object',
718
+ }, systemUser);
719
+ const myChannelIds = Array.from(new Set((myPartsRes.Success ? myPartsRes.Results : []).map((p) => p.AgentChannelID)));
720
+ if (myChannelIds.length === 0) {
721
+ const empty = { Count: 0, Channels: [] };
722
+ return {
723
+ Success: true,
724
+ ResultCode: 'SUCCESS',
725
+ Message: JSON.stringify(empty),
726
+ Params: setOutputParam(params, 'ChannelJSON', JSON.stringify(empty)),
727
+ };
728
+ }
729
+ const clauses = [
730
+ `ID IN (${myChannelIds.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`,
731
+ ];
732
+ if (statusFilter && statusFilter.toLowerCase() !== 'all') {
733
+ clauses.push(`ChannelStatus='${EscapeSQLString(statusFilter)}'`);
734
+ }
735
+ const channelsRes = await rv.RunView({
736
+ EntityName: 'MJ: Agent Channels',
737
+ ExtraFilter: clauses.join(' AND '),
738
+ OrderBy: '__mj_UpdatedAt DESC',
739
+ MaxRows: 50,
740
+ ResultType: 'entity_object',
741
+ }, systemUser);
742
+ const rows = TypedActionPolicyGuard.MaskRows((channelsRes.Success ? channelsRes.Results : []).map((c) => ({
743
+ ChannelID: c.ID,
744
+ Topic: c.Topic,
745
+ ChannelStatus: c.ChannelStatus,
746
+ ConsecutiveAgentTurns: c.ConsecutiveAgentTurns,
747
+ MaxConsecutiveAgentTurns: c.MaxConsecutiveAgentTurns,
748
+ HourlyWakeCount: c.HourlyWakeCount,
749
+ MaxHourlyWakes: c.MaxHourlyWakes,
750
+ ReplyBy: c.ReplyBy?.toISOString() ?? null,
751
+ LastHumanMessageAt: c.LastHumanMessageAt?.toISOString() ?? null,
752
+ })), guard.DeniedFieldPatterns);
753
+ const payload = { Count: rows.length, Channels: rows };
754
+ return {
755
+ Success: true,
756
+ ResultCode: 'SUCCESS',
757
+ Message: JSON.stringify(payload),
758
+ Params: setOutputParam(params, 'ChannelJSON', JSON.stringify(payload)),
759
+ };
760
+ }
761
+ const participantsRes = await rv.RunView({
762
+ EntityName: 'MJ: Agent Channel Participants',
763
+ ExtraFilter: `AgentChannelID='${EscapeSQLString(channelId)}'`,
764
+ OrderBy: 'JoinedAt ASC',
765
+ ResultType: 'entity_object',
766
+ }, systemUser);
767
+ const participants = participantsRes.Success ? participantsRes.Results : [];
768
+ const callerIsParticipant = participants.some((p) => UUIDsEqual(p.UserID, contextUser.ID));
769
+ if (!callerIsParticipant && !isOwner) {
770
+ return {
771
+ Success: false,
772
+ ResultCode: 'POLICY_DENIED',
773
+ Message: 'You do not have access to this Agent Channel.',
774
+ Params: params.Params,
775
+ };
776
+ }
777
+ const channel = await newEntityObject(md, 'MJ: Agent Channels', systemUser);
778
+ const loaded = await channel.Load(channelId);
779
+ if (!loaded) {
780
+ return {
781
+ Success: false,
782
+ ResultCode: 'NOT_FOUND',
783
+ Message: `Agent Channel "${channelId}" was not found.`,
784
+ Params: params.Params,
785
+ };
786
+ }
787
+ const messagesRes = await rv.RunView({
788
+ EntityName: 'MJ: Conversation Details',
789
+ ExtraFilter: `ConversationID='${EscapeSQLString(channel.ID)}'`,
790
+ OrderBy: '__mj_CreatedAt ASC',
791
+ MaxRows: maxMessages,
792
+ ResultType: 'entity_object',
793
+ }, systemUser);
794
+ const payload = {
795
+ Channel: TypedActionPolicyGuard.MaskRecord({
796
+ ChannelID: channel.ID,
797
+ Topic: channel.Topic,
798
+ ChannelStatus: channel.ChannelStatus,
799
+ ConsecutiveAgentTurns: channel.ConsecutiveAgentTurns,
800
+ MaxConsecutiveAgentTurns: channel.MaxConsecutiveAgentTurns,
801
+ HourlyWakeCount: channel.HourlyWakeCount,
802
+ MaxHourlyWakes: channel.MaxHourlyWakes,
803
+ ReplyBy: channel.ReplyBy?.toISOString() ?? null,
804
+ LastHumanMessageAt: channel.LastHumanMessageAt?.toISOString() ?? null,
805
+ ResolvedAt: channel.ResolvedAt?.toISOString() ?? null,
806
+ }, guard.DeniedFieldPatterns),
807
+ Participants: participants.map((p) => ({
808
+ ParticipantID: p.ID,
809
+ UserID: p.UserID,
810
+ UserName: p.User,
811
+ AgentID: p.AgentID,
812
+ AgentName: p.Agent,
813
+ Role: p.Role,
814
+ JoinedAt: p.JoinedAt?.toISOString() ?? null,
815
+ })),
816
+ Messages: (messagesRes.Success ? messagesRes.Results : []).map((m) => ({
817
+ DetailID: m.ID,
818
+ Role: m.Role,
819
+ UserID: m.UserID,
820
+ AgentID: m.AgentID,
821
+ Message: m.Message,
822
+ CreatedAt: m.__mj_CreatedAt?.toISOString() ?? null,
823
+ })),
824
+ };
825
+ return {
826
+ Success: true,
827
+ ResultCode: 'SUCCESS',
828
+ Message: JSON.stringify(payload),
829
+ Params: setOutputParam(params, 'ChannelJSON', JSON.stringify(payload)),
830
+ };
831
+ }
832
+ catch (error) {
833
+ const msg = error instanceof Error ? error.message : String(error);
834
+ LogError(`[GetAgentChannelAction] ${msg}`);
835
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
836
+ }
837
+ }
838
+ };
839
+ GetAgentChannelAction = __decorate([
840
+ RegisterClass(BaseAction, 'Get Agent Channel')
841
+ ], GetAgentChannelAction);
842
+ export { GetAgentChannelAction };
843
+ //# sourceMappingURL=agent-channel.action.js.map