@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,1097 @@
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 { ActionEngineServer, BaseAction } from '@memberjunction/actions';
8
+ import { EscapeSQLString, IndexByUUID, RegisterClass, SafeJSONParse, UUIDsEqual } from '@memberjunction/global';
9
+ import { LimitsConfigResolver, LogError, Metadata, RunView } from '@memberjunction/core';
10
+ import { AgentUserPolicyEngine, TypedActionPolicyGuard, } from '@memberjunction/ai-core-plus';
11
+ import { AssembleChiefOfStaffBriefingEnvelope, BuildTeamBriefingSection, } from '@memberjunction/ai-agents';
12
+ import { AIEngine } from '@memberjunction/aiengine';
13
+ import { UserCache } from '@memberjunction/generic-database-provider';
14
+ const DEFAULT_AGENT_NAME = 'Chief of Staff';
15
+ function readStringParam(params, name) {
16
+ const found = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase());
17
+ if (found?.Value == null) {
18
+ return undefined;
19
+ }
20
+ const str = String(found.Value).trim();
21
+ return str.length > 0 ? str : undefined;
22
+ }
23
+ function readNumberParam(params, name, fallback, min, max) {
24
+ const raw = readStringParam(params, name);
25
+ if (!raw) {
26
+ return fallback;
27
+ }
28
+ const parsed = Number(raw);
29
+ if (!Number.isFinite(parsed)) {
30
+ return fallback;
31
+ }
32
+ return Math.min(max, Math.max(min, Math.trunc(parsed)));
33
+ }
34
+ function readBooleanParam(params, name, fallback) {
35
+ const found = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase());
36
+ if (found?.Value == null) {
37
+ return fallback;
38
+ }
39
+ if (typeof found.Value === 'boolean') {
40
+ return found.Value;
41
+ }
42
+ const normalized = String(found.Value).trim().toLowerCase();
43
+ if (normalized === 'true' || normalized === '1' || normalized === 'yes') {
44
+ return true;
45
+ }
46
+ if (normalized === 'false' || normalized === '0' || normalized === 'no') {
47
+ return false;
48
+ }
49
+ return fallback;
50
+ }
51
+ function extractContextAgentId(context) {
52
+ if (!context || typeof context !== 'object') {
53
+ return undefined;
54
+ }
55
+ const val = context.AgentID;
56
+ if (typeof val === 'string' && val.trim().length > 0) {
57
+ return val.trim();
58
+ }
59
+ return undefined;
60
+ }
61
+ function resolveTargetAgent(params) {
62
+ const explicitId = readStringParam(params, 'AgentID') ?? extractContextAgentId(params.Context);
63
+ if (explicitId) {
64
+ return AIEngine.Instance.Agents.find((a) => UUIDsEqual(a.ID, explicitId)) ?? null;
65
+ }
66
+ const explicitName = readStringParam(params, 'AgentName') ?? DEFAULT_AGENT_NAME;
67
+ return (AIEngine.Instance.Agents.find((a) => a.Name.trim().toLowerCase() === explicitName.toLowerCase()) ??
68
+ null);
69
+ }
70
+ function setOutputParam(params, name, value) {
71
+ const existing = params.Params.find((p) => p.Name.trim().toLowerCase() === name.toLowerCase() && p.Type === 'Output');
72
+ if (existing) {
73
+ existing.Value = value;
74
+ return params.Params;
75
+ }
76
+ return [
77
+ ...params.Params,
78
+ {
79
+ Name: name,
80
+ Type: 'Output',
81
+ Value: value,
82
+ },
83
+ ];
84
+ }
85
+ /**
86
+ * Returns the calling user's identity, active `MJ: AI Agent User Policies` posture,
87
+ * granted AI skills (filtered by skill permissions), and active routine counts.
88
+ */
89
+ let GetMyAgentContextAction = class GetMyAgentContextAction extends BaseAction {
90
+ static { this.AuthorizesCaller = true; }
91
+ async InternalRunAction(params) {
92
+ try {
93
+ const contextUser = params.ContextUser;
94
+ if (!contextUser?.ID) {
95
+ return {
96
+ Success: false,
97
+ ResultCode: 'MISSING_USER_CONTEXT',
98
+ Message: 'Get My Agent Context requires a valid ContextUser.',
99
+ Params: params.Params,
100
+ };
101
+ }
102
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
103
+ entityName: 'MJ: AI Agent User Policies',
104
+ operation: 'Read',
105
+ contextUser,
106
+ actionContext: params.Context,
107
+ provider: params.Provider,
108
+ });
109
+ if (!guard.Allowed) {
110
+ return {
111
+ Success: false,
112
+ ResultCode: guard.ResultCode,
113
+ Message: guard.Message,
114
+ Params: params.Params,
115
+ };
116
+ }
117
+ await AIEngine.Instance.Config(false, contextUser);
118
+ const agent = resolveTargetAgent(params);
119
+ if (!agent) {
120
+ return {
121
+ Success: false,
122
+ ResultCode: 'AGENT_NOT_FOUND',
123
+ Message: 'Could not resolve target AI Agent.',
124
+ Params: params.Params,
125
+ };
126
+ }
127
+ const md = params.Provider ?? Metadata.Provider;
128
+ const policyLookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(agent.ID, contextUser.ID, contextUser, { provider: md });
129
+ const policy = policyLookup.status === 'found' ? policyLookup.policy : null;
130
+ const skillsById = IndexByUUID(AIEngine.Instance.Skills, (s) => s.ID);
131
+ const agentSkillLinks = AIEngine.Instance.AgentSkills.filter((link) => UUIDsEqual(link.AgentID, agent.ID) && link.Status === 'Active');
132
+ const grantedSkills = agentSkillLinks
133
+ .map((link) => {
134
+ const skill = skillsById.Get(link.SkillID);
135
+ if (!skill || skill.Status !== 'Active') {
136
+ return null;
137
+ }
138
+ return {
139
+ SkillID: skill.ID,
140
+ Name: skill.Name,
141
+ Description: skill.Description,
142
+ Status: link.Status,
143
+ };
144
+ })
145
+ .filter((s) => s !== null);
146
+ const rv = RunView.FromMetadataProvider(md);
147
+ const routinesResult = await rv.RunView({
148
+ EntityName: 'MJ: User Routines',
149
+ ExtraFilter: `UserID='${EscapeSQLString(contextUser.ID)}' AND TargetID='${EscapeSQLString(agent.ID)}'`,
150
+ Fields: ['ID', 'Status'],
151
+ ResultType: 'simple',
152
+ }, contextUser);
153
+ const routines = routinesResult.Success ? routinesResult.Results : [];
154
+ const activeRoutineCount = routines.filter((r) => r.Status === 'Active').length;
155
+ const policySummary = policy
156
+ ? TypedActionPolicyGuard.MaskRecord({
157
+ PolicyID: policy.ID,
158
+ Status: policy.Status,
159
+ OnboardingStatus: policy.OnboardingStatus,
160
+ DisplayNameOverride: policy.DisplayNameOverride,
161
+ PreferredPersonaID: policy.PreferredPersonaID,
162
+ PreferredPersona: policy.PreferredPersona,
163
+ CoordinationMode: policy.CoordinationMode,
164
+ DefaultDataAccessMode: policy.DefaultDataAccessMode,
165
+ EmailChannelMode: policy.EmailChannelMode,
166
+ PhoneChannelMode: policy.PhoneChannelMode,
167
+ MessagingChannelMode: policy.MessagingChannelMode,
168
+ CalendarChannelMode: policy.CalendarChannelMode,
169
+ AllowInterAgentCoordination: policy.AllowInterAgentCoordination,
170
+ RequireApprovalForExternalComms: policy.RequireApprovalForExternalComms,
171
+ RequireApprovalForFinancials: policy.RequireApprovalForFinancials,
172
+ RequireApprovalForDestructiveActions: policy.RequireApprovalForDestructiveActions,
173
+ HasInstructionsOverride: Boolean(policy.InstructionsOverride?.trim()),
174
+ InstructionsOverrideLength: policy.InstructionsOverride?.length ?? 0,
175
+ }, guard.DeniedFieldPatterns)
176
+ : null;
177
+ const payload = {
178
+ User: {
179
+ UserID: contextUser.ID,
180
+ Name: contextUser.Name,
181
+ Email: contextUser.Email,
182
+ FirstName: contextUser.FirstName,
183
+ LastName: contextUser.LastName,
184
+ },
185
+ Agent: {
186
+ AgentID: agent.ID,
187
+ Name: agent.Name,
188
+ },
189
+ Policy: policySummary,
190
+ GrantedSkills: grantedSkills,
191
+ Routines: {
192
+ TotalCount: routines.length,
193
+ ActiveCount: activeRoutineCount,
194
+ },
195
+ };
196
+ const outParams = setOutputParam(params, 'ContextJSON', JSON.stringify(payload));
197
+ return {
198
+ Success: true,
199
+ ResultCode: 'SUCCESS',
200
+ Message: JSON.stringify(payload),
201
+ Params: outParams,
202
+ };
203
+ }
204
+ catch (error) {
205
+ const msg = error instanceof Error ? error.message : String(error);
206
+ LogError(`[GetMyAgentContextAction] ${msg}`);
207
+ return {
208
+ Success: false,
209
+ ResultCode: 'ERROR',
210
+ Message: msg,
211
+ Params: params.Params,
212
+ };
213
+ }
214
+ }
215
+ };
216
+ GetMyAgentContextAction = __decorate([
217
+ RegisterClass(BaseAction, 'Get My Agent Context')
218
+ ], GetMyAgentContextAction);
219
+ export { GetMyAgentContextAction };
220
+ /**
221
+ * Deterministic single-call briefing assembler.
222
+ *
223
+ * Reads `AIEngine.Instance.GetBriefingActionsForAgent(agent, contextUser)` — every action
224
+ * bound with `AISkillAction.Role IN ('Briefing', 'Both')` on the agent's active granted skills
225
+ * that the user is permitted to use — executes them in parallel as `ContextUser`, and combines
226
+ * their payloads with core Chief of Staff state (pending approvals, active routines, open/paused
227
+ * Agent Channels, and offered suggestions).
228
+ */
229
+ let AssembleMyBriefingAction = class AssembleMyBriefingAction extends BaseAction {
230
+ static { this.AuthorizesCaller = true; }
231
+ async InternalRunAction(params) {
232
+ try {
233
+ const contextUser = params.ContextUser;
234
+ if (!contextUser?.ID) {
235
+ return {
236
+ Success: false,
237
+ ResultCode: 'MISSING_USER_CONTEXT',
238
+ Message: 'Assemble My Briefing requires a valid ContextUser.',
239
+ Params: params.Params,
240
+ };
241
+ }
242
+ const resolvedLimits = LimitsConfigResolver.Resolve().Limits;
243
+ const horizonDays = readNumberParam(params, 'HorizonDays', 7, 1, 30);
244
+ const contributorTimeoutMs = readNumberParam(params, 'ContributorTimeoutMs', resolvedLimits.BriefingContributorTimeoutMs, 20, 60_000);
245
+ const maxContributorChars = readNumberParam(params, 'MaxContributorChars', resolvedLimits.BriefingMaxContributorChars, 100, 524_288);
246
+ const includeSkillNamesRaw = readStringParam(params, 'IncludeSkillNames');
247
+ const includeSkillSet = includeSkillNamesRaw
248
+ ? new Set(includeSkillNamesRaw
249
+ .split(',')
250
+ .map((s) => s.trim().toLowerCase())
251
+ .filter(Boolean))
252
+ : null;
253
+ await Promise.all([
254
+ AIEngine.Instance.Config(false, contextUser),
255
+ ActionEngineServer.Instance.Config(false, contextUser),
256
+ ]);
257
+ const agent = resolveTargetAgent(params);
258
+ if (!agent) {
259
+ return {
260
+ Success: false,
261
+ ResultCode: 'AGENT_NOT_FOUND',
262
+ Message: 'Could not resolve target AI Agent for Assemble My Briefing.',
263
+ Params: params.Params,
264
+ };
265
+ }
266
+ const md = params.Provider ?? Metadata.Provider;
267
+ const briefingEntries = AIEngine.Instance.GetBriefingActionsForAgent(agent, contextUser).filter((entry) => !includeSkillSet || includeSkillSet.has(entry.skill.Name.trim().toLowerCase()));
268
+ const [coreState, teamSection, skillBriefings] = await Promise.all([
269
+ this.loadCoreBriefingState(agent.ID, contextUser, params.Context, md),
270
+ this.loadTeamBriefingSection(contextUser, params.Context, md),
271
+ Promise.all(briefingEntries.map((entry) => this.runBriefingContributor(entry.skill.Name, entry.actionID, agent.ID, horizonDays, contributorTimeoutMs, maxContributorChars, params))),
272
+ ]);
273
+ const payload = AssembleChiefOfStaffBriefingEnvelope({
274
+ HorizonDays: horizonDays,
275
+ Agent: { AgentID: agent.ID, Name: agent.Name },
276
+ User: { UserID: contextUser.ID, Name: contextUser.Name, Email: contextUser.Email },
277
+ Core: coreState,
278
+ SkillBriefings: skillBriefings,
279
+ Team: teamSection,
280
+ });
281
+ const outParams = setOutputParam(params, 'BriefingJSON', JSON.stringify(payload));
282
+ return {
283
+ Success: true,
284
+ ResultCode: 'SUCCESS',
285
+ Message: JSON.stringify(payload),
286
+ Params: outParams,
287
+ };
288
+ }
289
+ catch (error) {
290
+ const msg = error instanceof Error ? error.message : String(error);
291
+ LogError(`[AssembleMyBriefingAction] ${msg}`);
292
+ return {
293
+ Success: false,
294
+ ResultCode: 'ERROR',
295
+ Message: msg,
296
+ Params: params.Params,
297
+ };
298
+ }
299
+ }
300
+ async loadCoreBriefingState(agentId, contextUser, actionContext, md) {
301
+ const rv = RunView.FromMetadataProvider(md);
302
+ const safeUserId = EscapeSQLString(contextUser.ID);
303
+ const safeAgentId = EscapeSQLString(agentId);
304
+ const [approvalsGuard, routinesGuard, channelsGuard, suggestionsGuard] = await Promise.all([
305
+ TypedActionPolicyGuard.CheckEntityAccess({
306
+ entityName: 'MJ: AI Agent Requests',
307
+ operation: 'Read',
308
+ contextUser,
309
+ actionContext,
310
+ provider: md,
311
+ }),
312
+ TypedActionPolicyGuard.CheckEntityAccess({
313
+ entityName: 'MJ: User Routines',
314
+ operation: 'Read',
315
+ contextUser,
316
+ actionContext,
317
+ provider: md,
318
+ }),
319
+ TypedActionPolicyGuard.CheckEntityAccess({
320
+ entityName: 'MJ: Agent Channels',
321
+ operation: 'Read',
322
+ contextUser,
323
+ actionContext,
324
+ provider: md,
325
+ }),
326
+ TypedActionPolicyGuard.CheckEntityAccess({
327
+ entityName: 'MJ: AI Agent Suggestions',
328
+ operation: 'Read',
329
+ contextUser,
330
+ actionContext,
331
+ provider: md,
332
+ }),
333
+ ]);
334
+ const [approvalsRes, routinesRes, participantRes, suggestionsRes] = await Promise.all([
335
+ approvalsGuard.Allowed
336
+ ? rv.RunView({
337
+ EntityName: 'MJ: AI Agent Requests',
338
+ ExtraFilter: `RequestForUserID='${safeUserId}' AND Status='Requested'`,
339
+ OrderBy: '__mj_CreatedAt DESC',
340
+ MaxRows: 25,
341
+ ResultType: 'entity_object',
342
+ }, contextUser)
343
+ : Promise.resolve({ Success: false, Results: [] }),
344
+ routinesGuard.Allowed
345
+ ? rv.RunView({
346
+ EntityName: 'MJ: User Routines',
347
+ ExtraFilter: `UserID='${safeUserId}' AND TargetID='${safeAgentId}' AND Status='Active'`,
348
+ OrderBy: 'NextRunAt ASC',
349
+ MaxRows: 25,
350
+ ResultType: 'entity_object',
351
+ }, contextUser)
352
+ : Promise.resolve({ Success: false, Results: [] }),
353
+ channelsGuard.Allowed
354
+ ? rv.RunView({
355
+ EntityName: 'MJ: Agent Channel Participants',
356
+ ExtraFilter: `UserID='${safeUserId}'`,
357
+ MaxRows: 25,
358
+ ResultType: 'entity_object',
359
+ }, contextUser)
360
+ : Promise.resolve({ Success: false, Results: [] }),
361
+ suggestionsGuard.Allowed
362
+ ? rv.RunView({
363
+ EntityName: 'MJ: AI Agent Suggestions',
364
+ ExtraFilter: `UserID='${safeUserId}' AND AgentID='${safeAgentId}' AND Status='Offered'`,
365
+ OrderBy: 'OfferedAt DESC',
366
+ MaxRows: 10,
367
+ ResultType: 'entity_object',
368
+ }, contextUser)
369
+ : Promise.resolve({ Success: false, Results: [] }),
370
+ ]);
371
+ let activeChannels = [];
372
+ if (channelsGuard.Allowed && participantRes.Success && participantRes.Results.length > 0) {
373
+ const channelIds = participantRes.Results.map((p) => `'${EscapeSQLString(p.AgentChannelID)}'`).join(',');
374
+ const chanRes = await rv.RunView({
375
+ EntityName: 'MJ: Agent Channels',
376
+ ExtraFilter: `ID IN (${channelIds}) AND ChannelStatus IN ('Open', 'Paused For Human')`,
377
+ OrderBy: '__mj_UpdatedAt DESC',
378
+ MaxRows: 25,
379
+ ResultType: 'entity_object',
380
+ }, contextUser);
381
+ if (chanRes.Success) {
382
+ activeChannels = TypedActionPolicyGuard.MaskRows(chanRes.Results.map((c) => ({
383
+ ChannelID: c.ID,
384
+ Topic: c.Topic,
385
+ ChannelStatus: c.ChannelStatus,
386
+ ConsecutiveAgentTurns: c.ConsecutiveAgentTurns,
387
+ MaxConsecutiveAgentTurns: c.MaxConsecutiveAgentTurns,
388
+ ReplyBy: c.ReplyBy?.toISOString() ?? null,
389
+ })), channelsGuard.DeniedFieldPatterns);
390
+ }
391
+ }
392
+ const pendingApprovals = approvalsGuard.Allowed && approvalsRes.Success
393
+ ? TypedActionPolicyGuard.MaskRows(approvalsRes.Results.map((r) => ({
394
+ RequestID: r.ID,
395
+ Status: r.Status,
396
+ Priority: r.Priority,
397
+ Request: r.Request,
398
+ ExpiresAt: r.ExpiresAt?.toISOString() ?? null,
399
+ CreatedAt: r.__mj_CreatedAt?.toISOString() ?? null,
400
+ })), approvalsGuard.DeniedFieldPatterns)
401
+ : [];
402
+ const activeRoutines = routinesGuard.Allowed && routinesRes.Success
403
+ ? TypedActionPolicyGuard.MaskRows(routinesRes.Results.map((r) => ({
404
+ RoutineID: r.ID,
405
+ Name: r.Name,
406
+ ScheduleMode: r.ScheduleMode,
407
+ CronExpression: r.CronExpression,
408
+ NextRunAt: r.NextRunAt?.toISOString() ?? null,
409
+ WorkstreamKey: r.WakeConfigurationObject?.workstreamKey ?? null,
410
+ })), routinesGuard.DeniedFieldPatterns)
411
+ : [];
412
+ const openSuggestions = suggestionsGuard.Allowed && suggestionsRes.Success
413
+ ? TypedActionPolicyGuard.MaskRows(suggestionsRes.Results.map((s) => ({
414
+ SuggestionID: s.ID,
415
+ Kind: s.Kind,
416
+ TargetKey: s.TargetKey,
417
+ Summary: s.Summary,
418
+ OfferedAt: s.OfferedAt?.toISOString() ?? null,
419
+ })), suggestionsGuard.DeniedFieldPatterns)
420
+ : [];
421
+ return {
422
+ PendingApprovals: pendingApprovals,
423
+ ActiveRoutines: activeRoutines,
424
+ AgentChannels: activeChannels,
425
+ OpenSuggestions: openSuggestions,
426
+ };
427
+ }
428
+ async loadTeamBriefingSection(contextUser, actionContext, md) {
429
+ const empGuard = await TypedActionPolicyGuard.CheckEntityAccess({
430
+ entityName: 'MJ: Employees',
431
+ operation: 'Read',
432
+ contextUser,
433
+ actionContext,
434
+ provider: md,
435
+ });
436
+ if (!empGuard.Allowed) {
437
+ return null;
438
+ }
439
+ const team = await BuildTeamBriefingSection({
440
+ ContextUser: contextUser,
441
+ MetadataProvider: md,
442
+ });
443
+ if (!team) {
444
+ return null;
445
+ }
446
+ const maskedReports = TypedActionPolicyGuard.MaskRows(team.DirectReports.map((r) => ({
447
+ EmployeeID: r.EmployeeID,
448
+ UserID: r.UserID,
449
+ Name: r.Name,
450
+ Email: r.Email,
451
+ Title: r.Title,
452
+ })), empGuard.DeniedFieldPatterns).map((masked) => ({
453
+ EmployeeID: masked.EmployeeID ?? '',
454
+ UserID: masked.UserID ?? null,
455
+ Name: masked.Name ?? '',
456
+ Email: masked.Email ?? '',
457
+ Title: masked.Title ?? null,
458
+ }));
459
+ return {
460
+ ...team,
461
+ DirectReports: maskedReports,
462
+ };
463
+ }
464
+ async runBriefingContributor(skillName, actionId, agentId, horizonDays, contributorTimeoutMs, maxContributorChars, parentParams) {
465
+ const action = ActionEngineServer.Instance.Actions.find((a) => UUIDsEqual(a.ID, actionId));
466
+ if (!action) {
467
+ return {
468
+ SkillName: skillName,
469
+ ActionID: actionId,
470
+ ActionName: null,
471
+ Success: false,
472
+ ResultCode: 'ACTION_NOT_FOUND',
473
+ Data: null,
474
+ Error: `Briefing action ${actionId} is not registered in ActionEngineServer.`,
475
+ };
476
+ }
477
+ const timeoutSentinel = Symbol('BRIEFING_CONTRIBUTOR_TIMEOUT');
478
+ let timeoutHandle = null;
479
+ try {
480
+ const runPromise = ActionEngineServer.Instance.RunAction({
481
+ Action: action,
482
+ Params: [
483
+ { Name: 'HorizonDays', Type: 'Input', Value: horizonDays },
484
+ { Name: 'AgentID', Type: 'Input', Value: agentId },
485
+ ],
486
+ Filters: [],
487
+ ContextUser: parentParams.ContextUser,
488
+ Context: parentParams.Context,
489
+ Provider: parentParams.Provider,
490
+ SkipActionLog: false,
491
+ });
492
+ // Prevent unhandled rejection if the action rejects after the timeout has already won the race.
493
+ runPromise.catch(() => undefined);
494
+ const timeoutPromise = new Promise((resolve) => {
495
+ timeoutHandle = setTimeout(() => resolve(timeoutSentinel), contributorTimeoutMs);
496
+ });
497
+ const raced = await Promise.race([runPromise, timeoutPromise]);
498
+ if (raced === timeoutSentinel) {
499
+ return {
500
+ SkillName: skillName,
501
+ ActionID: action.ID,
502
+ ActionName: action.Name,
503
+ Success: false,
504
+ ResultCode: 'TIMEOUT',
505
+ Data: null,
506
+ Error: `Briefing contributor "${action.Name}" timed out after ${contributorTimeoutMs}ms.`,
507
+ };
508
+ }
509
+ const result = raced;
510
+ const parsedData = result.Message && (result.Message.trim().startsWith('{') || result.Message.trim().startsWith('['))
511
+ ? SafeJSONParse(result.Message)
512
+ : null;
513
+ const outputParams = {};
514
+ for (const p of result.Params ?? []) {
515
+ if ((p.Type === 'Output' || p.Type === 'Both') && p.Value !== undefined && p.Value !== null) {
516
+ if (typeof p.Value === 'string') {
517
+ const trimmed = p.Value.trim();
518
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
519
+ const parsed = SafeJSONParse(trimmed);
520
+ outputParams[p.Name] = parsed ?? p.Value;
521
+ continue;
522
+ }
523
+ }
524
+ outputParams[p.Name] = p.Value;
525
+ }
526
+ }
527
+ const hasOutputs = Object.keys(outputParams).length > 0;
528
+ const rawContributorData = parsedData
529
+ ? hasOutputs
530
+ ? { ...parsedData, Outputs: outputParams }
531
+ : parsedData
532
+ : hasOutputs
533
+ ? { Summary: result.Message ?? null, ...outputParams }
534
+ : result.Message ?? null;
535
+ const contributorData = this.capContributorPayload(rawContributorData, maxContributorChars);
536
+ return {
537
+ SkillName: skillName,
538
+ ActionID: action.ID,
539
+ ActionName: action.Name,
540
+ Success: result.Success,
541
+ ResultCode: result.Result?.ResultCode ?? (result.Success ? 'SUCCESS' : 'ERROR'),
542
+ Data: contributorData,
543
+ Error: result.Success ? null : result.Message ?? 'Briefing contributor failed.',
544
+ };
545
+ }
546
+ catch (error) {
547
+ const msg = error instanceof Error ? error.message : String(error);
548
+ LogError(`[AssembleMyBriefingAction] Contributor "${action.Name}" failed: ${msg}`);
549
+ return {
550
+ SkillName: skillName,
551
+ ActionID: action.ID,
552
+ ActionName: action.Name,
553
+ Success: false,
554
+ ResultCode: 'ERROR',
555
+ Data: null,
556
+ Error: msg,
557
+ };
558
+ }
559
+ finally {
560
+ if (timeoutHandle !== null) {
561
+ clearTimeout(timeoutHandle);
562
+ }
563
+ }
564
+ }
565
+ capContributorPayload(data, maxChars) {
566
+ if (data === null || data === undefined) {
567
+ return data;
568
+ }
569
+ const serialized = typeof data === 'string' ? data : JSON.stringify(data);
570
+ if (typeof serialized !== 'string' || serialized.length <= maxChars) {
571
+ return data;
572
+ }
573
+ return {
574
+ Truncated: true,
575
+ OriginalChars: serialized.length,
576
+ Preview: serialized.slice(0, maxChars),
577
+ };
578
+ }
579
+ };
580
+ AssembleMyBriefingAction = __decorate([
581
+ RegisterClass(BaseAction, 'Assemble My Briefing')
582
+ ], AssembleMyBriefingAction);
583
+ export { AssembleMyBriefingAction };
584
+ /**
585
+ * Lists the calling user's `MJ: User Routines` for the active agent.
586
+ */
587
+ let ListMyAgentRoutinesAction = class ListMyAgentRoutinesAction extends BaseAction {
588
+ static { this.AuthorizesCaller = true; }
589
+ async InternalRunAction(params) {
590
+ try {
591
+ const contextUser = params.ContextUser;
592
+ if (!contextUser?.ID) {
593
+ return {
594
+ Success: false,
595
+ ResultCode: 'MISSING_USER_CONTEXT',
596
+ Message: 'List My Agent Routines requires a valid ContextUser.',
597
+ Params: params.Params,
598
+ };
599
+ }
600
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
601
+ entityName: 'MJ: User Routines',
602
+ operation: 'Read',
603
+ contextUser,
604
+ actionContext: params.Context,
605
+ provider: params.Provider,
606
+ });
607
+ if (!guard.Allowed) {
608
+ return {
609
+ Success: false,
610
+ ResultCode: guard.ResultCode,
611
+ Message: guard.Message,
612
+ Params: params.Params,
613
+ };
614
+ }
615
+ await AIEngine.Instance.Config(false, contextUser);
616
+ const agent = resolveTargetAgent(params);
617
+ const statusFilter = readStringParam(params, 'Status');
618
+ const workstreamFilter = readStringParam(params, 'WorkstreamKey')?.toLowerCase();
619
+ const maxRows = readNumberParam(params, 'MaxRows', 50, 1, 100);
620
+ const clauses = [`UserID='${EscapeSQLString(contextUser.ID)}'`];
621
+ if (agent) {
622
+ clauses.push(`TargetID='${EscapeSQLString(agent.ID)}'`);
623
+ }
624
+ if (statusFilter && statusFilter.toLowerCase() !== 'all') {
625
+ clauses.push(`Status='${EscapeSQLString(statusFilter)}'`);
626
+ }
627
+ const md = params.Provider ?? Metadata.Provider;
628
+ const rv = RunView.FromMetadataProvider(md);
629
+ const res = await rv.RunView({
630
+ EntityName: 'MJ: User Routines',
631
+ ExtraFilter: clauses.join(' AND '),
632
+ OrderBy: 'NextRunAt ASC, __mj_UpdatedAt DESC',
633
+ MaxRows: maxRows,
634
+ ResultType: 'entity_object',
635
+ }, contextUser);
636
+ if (!res.Success) {
637
+ return {
638
+ Success: false,
639
+ ResultCode: 'QUERY_FAILED',
640
+ Message: res.ErrorMessage || 'Failed to load user routines.',
641
+ Params: params.Params,
642
+ };
643
+ }
644
+ const rows = res.Results.map((r) => {
645
+ const cfg = r.WakeConfigurationObject ??
646
+ (r.WakeConfiguration
647
+ ? SafeJSONParse(r.WakeConfiguration) ?? {}
648
+ : {});
649
+ return {
650
+ RoutineID: r.ID,
651
+ Name: r.Name,
652
+ RoutineType: r.RoutineType,
653
+ ScheduleMode: r.ScheduleMode,
654
+ Status: r.Status,
655
+ CronExpression: r.CronExpression,
656
+ Timezone: r.Timezone,
657
+ NextRunAt: r.NextRunAt?.toISOString() ?? null,
658
+ LastRunAt: r.LastRunAt?.toISOString() ?? null,
659
+ WorkstreamKey: cfg.workstreamKey ?? null,
660
+ WakeReason: cfg.wakeReason ?? null,
661
+ Description: r.Description,
662
+ AgentConfigurationID: r.AgentConfigurationID ?? null,
663
+ AgentConfiguration: r.AgentConfiguration ?? null,
664
+ };
665
+ }).filter((row) => !workstreamFilter || (row.WorkstreamKey ?? '').toLowerCase() === workstreamFilter);
666
+ const masked = TypedActionPolicyGuard.MaskRows(rows, guard.DeniedFieldPatterns);
667
+ const payload = { Count: masked.length, Routines: masked };
668
+ return {
669
+ Success: true,
670
+ ResultCode: 'SUCCESS',
671
+ Message: JSON.stringify(payload),
672
+ Params: setOutputParam(params, 'RoutinesJSON', JSON.stringify(payload)),
673
+ };
674
+ }
675
+ catch (error) {
676
+ const msg = error instanceof Error ? error.message : String(error);
677
+ LogError(`[ListMyAgentRoutinesAction] ${msg}`);
678
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
679
+ }
680
+ }
681
+ };
682
+ ListMyAgentRoutinesAction = __decorate([
683
+ RegisterClass(BaseAction, 'List My Agent Routines')
684
+ ], ListMyAgentRoutinesAction);
685
+ export { ListMyAgentRoutinesAction };
686
+ /**
687
+ * Retrieves recent run history (`MJ: User Routine Runs`) for the caller's routines.
688
+ */
689
+ let GetRoutineRunResultsAction = class GetRoutineRunResultsAction extends BaseAction {
690
+ static { this.AuthorizesCaller = true; }
691
+ async InternalRunAction(params) {
692
+ try {
693
+ const contextUser = params.ContextUser;
694
+ if (!contextUser?.ID) {
695
+ return {
696
+ Success: false,
697
+ ResultCode: 'MISSING_USER_CONTEXT',
698
+ Message: 'Get Routine Run Results requires a valid ContextUser.',
699
+ Params: params.Params,
700
+ };
701
+ }
702
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
703
+ entityName: 'MJ: User Routine Runs',
704
+ operation: 'Read',
705
+ contextUser,
706
+ actionContext: params.Context,
707
+ provider: params.Provider,
708
+ });
709
+ if (!guard.Allowed) {
710
+ return {
711
+ Success: false,
712
+ ResultCode: guard.ResultCode,
713
+ Message: guard.Message,
714
+ Params: params.Params,
715
+ };
716
+ }
717
+ const routineId = readStringParam(params, 'RoutineID');
718
+ const workstreamKey = readStringParam(params, 'WorkstreamKey')?.toLowerCase();
719
+ const maxRows = readNumberParam(params, 'MaxRows', 10, 1, 50);
720
+ const md = params.Provider ?? Metadata.Provider;
721
+ const rv = RunView.FromMetadataProvider(md);
722
+ // Always verify routine ownership against ContextUser first
723
+ const routineClauses = [`UserID='${EscapeSQLString(contextUser.ID)}'`];
724
+ if (routineId) {
725
+ routineClauses.push(`ID='${EscapeSQLString(routineId)}'`);
726
+ }
727
+ const routinesRes = await rv.RunView({
728
+ EntityName: 'MJ: User Routines',
729
+ ExtraFilter: routineClauses.join(' AND '),
730
+ MaxRows: 50,
731
+ ResultType: 'entity_object',
732
+ }, contextUser);
733
+ const ownedRoutines = (routinesRes.Success ? routinesRes.Results : []).filter((r) => {
734
+ if (!workstreamKey) {
735
+ return true;
736
+ }
737
+ const key = r.WakeConfigurationObject?.workstreamKey?.toLowerCase();
738
+ return key === workstreamKey;
739
+ });
740
+ if (ownedRoutines.length === 0) {
741
+ const empty = { Count: 0, Runs: [] };
742
+ return {
743
+ Success: true,
744
+ ResultCode: 'SUCCESS',
745
+ Message: JSON.stringify(empty),
746
+ Params: setOutputParam(params, 'RunsJSON', JSON.stringify(empty)),
747
+ };
748
+ }
749
+ const inClause = ownedRoutines.map((r) => `'${EscapeSQLString(r.ID)}'`).join(',');
750
+ const runsRes = await rv.RunView({
751
+ EntityName: 'MJ: User Routine Runs',
752
+ ExtraFilter: `RoutineID IN (${inClause})`,
753
+ OrderBy: 'StartedAt DESC',
754
+ MaxRows: maxRows,
755
+ ResultType: 'entity_object',
756
+ }, contextUser);
757
+ if (!runsRes.Success) {
758
+ return {
759
+ Success: false,
760
+ ResultCode: 'QUERY_FAILED',
761
+ Message: runsRes.ErrorMessage || 'Failed to load routine runs.',
762
+ Params: params.Params,
763
+ };
764
+ }
765
+ const rows = TypedActionPolicyGuard.MaskRows(runsRes.Results.map((run) => ({
766
+ RunID: run.ID,
767
+ RoutineID: run.RoutineID,
768
+ RoutineName: run.Routine,
769
+ Status: run.Status,
770
+ StartedAt: run.StartedAt?.toISOString() ?? null,
771
+ CompletedAt: run.CompletedAt?.toISOString() ?? null,
772
+ AgentRunID: run.AgentRunID,
773
+ ResultSummary: run.ResultSummary,
774
+ NotificationSent: run.NotificationSent,
775
+ ErrorMessage: run.ErrorMessage,
776
+ })), guard.DeniedFieldPatterns);
777
+ const payload = { Count: rows.length, Runs: rows };
778
+ return {
779
+ Success: true,
780
+ ResultCode: 'SUCCESS',
781
+ Message: JSON.stringify(payload),
782
+ Params: setOutputParam(params, 'RunsJSON', JSON.stringify(payload)),
783
+ };
784
+ }
785
+ catch (error) {
786
+ const msg = error instanceof Error ? error.message : String(error);
787
+ LogError(`[GetRoutineRunResultsAction] ${msg}`);
788
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
789
+ }
790
+ }
791
+ };
792
+ GetRoutineRunResultsAction = __decorate([
793
+ RegisterClass(BaseAction, 'Get Routine Run Results')
794
+ ], GetRoutineRunResultsAction);
795
+ export { GetRoutineRunResultsAction };
796
+ /**
797
+ * Lists pending (or filtered-status) `MJ: AI Agent Requests` for the calling user.
798
+ */
799
+ let ListMyPendingApprovalsAction = class ListMyPendingApprovalsAction extends BaseAction {
800
+ static { this.AuthorizesCaller = true; }
801
+ async InternalRunAction(params) {
802
+ try {
803
+ const contextUser = params.ContextUser;
804
+ if (!contextUser?.ID) {
805
+ return {
806
+ Success: false,
807
+ ResultCode: 'MISSING_USER_CONTEXT',
808
+ Message: 'List My Pending Approvals requires a valid ContextUser.',
809
+ Params: params.Params,
810
+ };
811
+ }
812
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
813
+ entityName: 'MJ: AI Agent Requests',
814
+ operation: 'Read',
815
+ contextUser,
816
+ actionContext: params.Context,
817
+ provider: params.Provider,
818
+ });
819
+ if (!guard.Allowed) {
820
+ return {
821
+ Success: false,
822
+ ResultCode: guard.ResultCode,
823
+ Message: guard.Message,
824
+ Params: params.Params,
825
+ };
826
+ }
827
+ const status = readStringParam(params, 'Status') ?? 'Requested';
828
+ const maxRows = readNumberParam(params, 'MaxRows', 50, 1, 100);
829
+ const clauses = [`RequestForUserID='${EscapeSQLString(contextUser.ID)}'`];
830
+ if (status.toLowerCase() !== 'all') {
831
+ clauses.push(`Status='${EscapeSQLString(status)}'`);
832
+ }
833
+ const md = params.Provider ?? Metadata.Provider;
834
+ const rv = RunView.FromMetadataProvider(md);
835
+ const res = await rv.RunView({
836
+ EntityName: 'MJ: AI Agent Requests',
837
+ ExtraFilter: clauses.join(' AND '),
838
+ OrderBy: 'Priority DESC, __mj_CreatedAt DESC',
839
+ MaxRows: maxRows,
840
+ ResultType: 'entity_object',
841
+ }, contextUser);
842
+ if (!res.Success) {
843
+ return {
844
+ Success: false,
845
+ ResultCode: 'QUERY_FAILED',
846
+ Message: res.ErrorMessage || 'Failed to load pending approvals.',
847
+ Params: params.Params,
848
+ };
849
+ }
850
+ const rows = TypedActionPolicyGuard.MaskRows(res.Results.map((r) => ({
851
+ RequestID: r.ID,
852
+ AgentID: r.AgentID,
853
+ Status: r.Status,
854
+ Priority: r.Priority,
855
+ Request: r.Request,
856
+ Response: r.Response,
857
+ Comments: r.Comments,
858
+ ExpiresAt: r.ExpiresAt?.toISOString() ?? null,
859
+ CreatedAt: r.__mj_CreatedAt?.toISOString() ?? null,
860
+ RespondedAt: r.RespondedAt?.toISOString() ?? null,
861
+ })), guard.DeniedFieldPatterns);
862
+ const payload = { Count: rows.length, Approvals: rows };
863
+ return {
864
+ Success: true,
865
+ ResultCode: 'SUCCESS',
866
+ Message: JSON.stringify(payload),
867
+ Params: setOutputParam(params, 'ApprovalsJSON', JSON.stringify(payload)),
868
+ };
869
+ }
870
+ catch (error) {
871
+ const msg = error instanceof Error ? error.message : String(error);
872
+ LogError(`[ListMyPendingApprovalsAction] ${msg}`);
873
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
874
+ }
875
+ }
876
+ };
877
+ ListMyPendingApprovalsAction = __decorate([
878
+ RegisterClass(BaseAction, 'List My Pending Approvals')
879
+ ], ListMyPendingApprovalsAction);
880
+ export { ListMyPendingApprovalsAction };
881
+ /**
882
+ * Disables/cancels an active wake routine owned by `ContextUser` by `RoutineID` or `WorkstreamKey`.
883
+ */
884
+ let CancelAgentWakeAction = class CancelAgentWakeAction extends BaseAction {
885
+ static { this.AuthorizesCaller = true; }
886
+ async InternalRunAction(params) {
887
+ try {
888
+ const contextUser = params.ContextUser;
889
+ if (!contextUser?.ID) {
890
+ return {
891
+ Success: false,
892
+ ResultCode: 'MISSING_USER_CONTEXT',
893
+ Message: 'Cancel Agent Wake requires a valid ContextUser.',
894
+ Params: params.Params,
895
+ };
896
+ }
897
+ const routineId = readStringParam(params, 'RoutineID');
898
+ const workstreamKey = readStringParam(params, 'WorkstreamKey');
899
+ if (!routineId && !workstreamKey) {
900
+ return {
901
+ Success: false,
902
+ ResultCode: 'VALIDATION_ERROR',
903
+ Message: 'Provide either RoutineID or WorkstreamKey to cancel an agent wake.',
904
+ Params: params.Params,
905
+ };
906
+ }
907
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
908
+ entityName: 'MJ: User Routines',
909
+ operation: 'Update',
910
+ writeFields: ['Status', 'NextRunAt', 'Description'],
911
+ contextUser,
912
+ actionContext: params.Context,
913
+ provider: params.Provider,
914
+ });
915
+ if (!guard.Allowed) {
916
+ return {
917
+ Success: false,
918
+ ResultCode: guard.ResultCode,
919
+ Message: guard.Message,
920
+ Params: params.Params,
921
+ };
922
+ }
923
+ await AIEngine.Instance.Config(false, contextUser);
924
+ const agent = resolveTargetAgent(params);
925
+ const md = params.Provider ?? Metadata.Provider;
926
+ const rv = RunView.FromMetadataProvider(md);
927
+ const clauses = [`UserID='${EscapeSQLString(contextUser.ID)}'`];
928
+ if (routineId) {
929
+ clauses.push(`ID='${EscapeSQLString(routineId)}'`);
930
+ }
931
+ else if (agent) {
932
+ clauses.push(`TargetID='${EscapeSQLString(agent.ID)}'`);
933
+ }
934
+ const res = await rv.RunView({
935
+ EntityName: 'MJ: User Routines',
936
+ ExtraFilter: clauses.join(' AND '),
937
+ MaxRows: 50,
938
+ ResultType: 'entity_object',
939
+ }, contextUser);
940
+ const candidates = res.Success ? res.Results : [];
941
+ const target = routineId
942
+ ? candidates[0] ?? null
943
+ : candidates.find((r) => (r.WakeConfigurationObject?.workstreamKey ?? '').toLowerCase() ===
944
+ workstreamKey.toLowerCase()) ?? null;
945
+ if (!target) {
946
+ return {
947
+ Success: false,
948
+ ResultCode: 'NOT_FOUND',
949
+ Message: `No routine found for ${routineId ? `RoutineID "${routineId}"` : `WorkstreamKey "${workstreamKey}"`}.`,
950
+ Params: params.Params,
951
+ };
952
+ }
953
+ const reason = readStringParam(params, 'Reason');
954
+ target.Status = 'Disabled';
955
+ target.NextRunAt = null;
956
+ if (reason) {
957
+ target.Description = reason;
958
+ }
959
+ const saved = await target.Save();
960
+ if (!saved) {
961
+ return {
962
+ Success: false,
963
+ ResultCode: 'SAVE_FAILED',
964
+ Message: target.LatestResult?.CompleteMessage || 'Failed to cancel agent wake routine.',
965
+ Params: params.Params,
966
+ };
967
+ }
968
+ const payload = {
969
+ RoutineID: target.ID,
970
+ Name: target.Name,
971
+ WorkstreamKey: target.WakeConfigurationObject?.workstreamKey ?? workstreamKey ?? null,
972
+ Status: target.Status,
973
+ };
974
+ return {
975
+ Success: true,
976
+ ResultCode: 'SUCCESS',
977
+ Message: JSON.stringify(payload),
978
+ Params: setOutputParam(params, 'RoutineID', target.ID),
979
+ };
980
+ }
981
+ catch (error) {
982
+ const msg = error instanceof Error ? error.message : String(error);
983
+ LogError(`[CancelAgentWakeAction] ${msg}`);
984
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
985
+ }
986
+ }
987
+ };
988
+ CancelAgentWakeAction = __decorate([
989
+ RegisterClass(BaseAction, 'Cancel Agent Wake')
990
+ ], CancelAgentWakeAction);
991
+ export { CancelAgentWakeAction };
992
+ /**
993
+ * Searches active internal colleagues (`MJ: Users`) by name or email, returning non-sensitive
994
+ * directory info and whether each colleague accepts inter-agent coordination.
995
+ */
996
+ let FindColleagueAction = class FindColleagueAction extends BaseAction {
997
+ static { this.AuthorizesCaller = true; }
998
+ async InternalRunAction(params) {
999
+ try {
1000
+ const contextUser = params.ContextUser;
1001
+ if (!contextUser?.ID) {
1002
+ return {
1003
+ Success: false,
1004
+ ResultCode: 'MISSING_USER_CONTEXT',
1005
+ Message: 'Find Colleague requires a valid ContextUser.',
1006
+ Params: params.Params,
1007
+ };
1008
+ }
1009
+ const query = readStringParam(params, 'Query');
1010
+ if (!query) {
1011
+ return {
1012
+ Success: false,
1013
+ ResultCode: 'VALIDATION_ERROR',
1014
+ Message: 'Query (name or email) is required for Find Colleague.',
1015
+ Params: params.Params,
1016
+ };
1017
+ }
1018
+ const guard = await TypedActionPolicyGuard.CheckEntityAccess({
1019
+ entityName: 'MJ: Users',
1020
+ operation: 'Read',
1021
+ contextUser,
1022
+ actionContext: params.Context,
1023
+ provider: params.Provider,
1024
+ });
1025
+ if (!guard.Allowed) {
1026
+ return {
1027
+ Success: false,
1028
+ ResultCode: guard.ResultCode,
1029
+ Message: guard.Message,
1030
+ Params: params.Params,
1031
+ };
1032
+ }
1033
+ const maxRows = readNumberParam(params, 'MaxRows', 10, 1, 25);
1034
+ const includeSelf = readBooleanParam(params, 'IncludeSelf', false);
1035
+ const safeLike = EscapeSQLString(query);
1036
+ const md = params.Provider ?? Metadata.Provider;
1037
+ const rv = RunView.FromMetadataProvider(md);
1038
+ const res = await rv.RunView({
1039
+ EntityName: 'MJ: Users',
1040
+ ExtraFilter: `IsActive=1 AND (Name LIKE '%${safeLike}%' OR FirstName LIKE '%${safeLike}%'` +
1041
+ ` OR LastName LIKE '%${safeLike}%' OR Email LIKE '%${safeLike}%')`,
1042
+ OrderBy: 'Name ASC',
1043
+ MaxRows: maxRows,
1044
+ ResultType: 'entity_object',
1045
+ }, contextUser);
1046
+ if (!res.Success) {
1047
+ return {
1048
+ Success: false,
1049
+ ResultCode: 'QUERY_FAILED',
1050
+ Message: res.ErrorMessage || 'Failed to search colleagues.',
1051
+ Params: params.Params,
1052
+ };
1053
+ }
1054
+ await AIEngine.Instance.Config(false, contextUser);
1055
+ const cosAgent = resolveTargetAgent(params);
1056
+ const systemUser = UserCache.Instance.GetSystemUser() ?? contextUser;
1057
+ const filteredUsers = res.Results.filter((u) => includeSelf || !UUIDsEqual(u.ID, contextUser.ID));
1058
+ const colleagues = await Promise.all(filteredUsers.map(async (u) => {
1059
+ let acceptsInterAgent = false;
1060
+ if (cosAgent) {
1061
+ const pol = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(cosAgent.ID, u.ID, systemUser, { provider: md });
1062
+ if (pol.status === 'found' && pol.policy) {
1063
+ acceptsInterAgent =
1064
+ pol.policy.Status === 'Active' && pol.policy.AllowInterAgentCoordination !== false;
1065
+ }
1066
+ }
1067
+ return {
1068
+ UserID: u.ID,
1069
+ Name: u.Name,
1070
+ FirstName: u.FirstName,
1071
+ LastName: u.LastName,
1072
+ Email: u.Email,
1073
+ Title: u.Title,
1074
+ AcceptsInterAgentCoordination: acceptsInterAgent,
1075
+ };
1076
+ }));
1077
+ const masked = TypedActionPolicyGuard.MaskRows(colleagues, guard.DeniedFieldPatterns);
1078
+ const payload = { Count: masked.length, Colleagues: masked };
1079
+ return {
1080
+ Success: true,
1081
+ ResultCode: 'SUCCESS',
1082
+ Message: JSON.stringify(payload),
1083
+ Params: setOutputParam(params, 'ColleaguesJSON', JSON.stringify(payload)),
1084
+ };
1085
+ }
1086
+ catch (error) {
1087
+ const msg = error instanceof Error ? error.message : String(error);
1088
+ LogError(`[FindColleagueAction] ${msg}`);
1089
+ return { Success: false, ResultCode: 'ERROR', Message: msg, Params: params.Params };
1090
+ }
1091
+ }
1092
+ };
1093
+ FindColleagueAction = __decorate([
1094
+ RegisterClass(BaseAction, 'Find Colleague')
1095
+ ], FindColleagueAction);
1096
+ export { FindColleagueAction };
1097
+ //# sourceMappingURL=chief-of-staff-core-reads.action.js.map