@memberjunction/core 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 (104) hide show
  1. package/dist/generic/QueryCache.d.ts +2 -2
  2. package/dist/generic/QueryCache.d.ts.map +1 -1
  3. package/dist/generic/QueryCache.js +12 -7
  4. package/dist/generic/QueryCache.js.map +1 -1
  5. package/dist/generic/baseEngine.d.ts +9 -0
  6. package/dist/generic/baseEngine.d.ts.map +1 -1
  7. package/dist/generic/baseEngine.js +23 -1
  8. package/dist/generic/baseEngine.js.map +1 -1
  9. package/dist/generic/baseEngineRegistry.d.ts +8 -0
  10. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  11. package/dist/generic/baseEngineRegistry.js +28 -10
  12. package/dist/generic/baseEngineRegistry.js.map +1 -1
  13. package/dist/generic/baseEntity.d.ts +69 -3
  14. package/dist/generic/baseEntity.d.ts.map +1 -1
  15. package/dist/generic/baseEntity.js +141 -53
  16. package/dist/generic/baseEntity.js.map +1 -1
  17. package/dist/generic/baseRemotableOperation.d.ts +17 -0
  18. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  19. package/dist/generic/baseRemotableOperation.js +18 -0
  20. package/dist/generic/baseRemotableOperation.js.map +1 -1
  21. package/dist/generic/constraintErrorRedaction.d.ts +26 -0
  22. package/dist/generic/constraintErrorRedaction.d.ts.map +1 -0
  23. package/dist/generic/constraintErrorRedaction.js +166 -0
  24. package/dist/generic/constraintErrorRedaction.js.map +1 -0
  25. package/dist/generic/dataHooks.d.ts +27 -3
  26. package/dist/generic/dataHooks.d.ts.map +1 -1
  27. package/dist/generic/dataHooks.js +82 -0
  28. package/dist/generic/dataHooks.js.map +1 -1
  29. package/dist/generic/databaseProviderBase.d.ts +69 -7
  30. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  31. package/dist/generic/databaseProviderBase.js +230 -38
  32. package/dist/generic/databaseProviderBase.js.map +1 -1
  33. package/dist/generic/entityInfo.d.ts +56 -6
  34. package/dist/generic/entityInfo.d.ts.map +1 -1
  35. package/dist/generic/entityInfo.js +200 -50
  36. package/dist/generic/entityInfo.js.map +1 -1
  37. package/dist/generic/entitySavePlan.d.ts +6 -0
  38. package/dist/generic/entitySavePlan.d.ts.map +1 -1
  39. package/dist/generic/entitySavePlan.js +145 -1
  40. package/dist/generic/entitySavePlan.js.map +1 -1
  41. package/dist/generic/entityValueFieldSecurity.d.ts.map +1 -1
  42. package/dist/generic/entityValueFieldSecurity.js +1 -0
  43. package/dist/generic/entityValueFieldSecurity.js.map +1 -1
  44. package/dist/generic/interfaces.d.ts +69 -18
  45. package/dist/generic/interfaces.d.ts.map +1 -1
  46. package/dist/generic/interfaces.js +9 -9
  47. package/dist/generic/interfaces.js.map +1 -1
  48. package/dist/generic/limitsConfig.d.ts +577 -0
  49. package/dist/generic/limitsConfig.d.ts.map +1 -0
  50. package/dist/generic/limitsConfig.js +1126 -0
  51. package/dist/generic/limitsConfig.js.map +1 -0
  52. package/dist/generic/localCacheManager.d.ts +10 -13
  53. package/dist/generic/localCacheManager.d.ts.map +1 -1
  54. package/dist/generic/localCacheManager.js +189 -67
  55. package/dist/generic/localCacheManager.js.map +1 -1
  56. package/dist/generic/metadata.d.ts +4 -4
  57. package/dist/generic/metadata.d.ts.map +1 -1
  58. package/dist/generic/metadata.js +4 -4
  59. package/dist/generic/metadata.js.map +1 -1
  60. package/dist/generic/providerBase.d.ts +242 -12
  61. package/dist/generic/providerBase.d.ts.map +1 -1
  62. package/dist/generic/providerBase.js +744 -101
  63. package/dist/generic/providerBase.js.map +1 -1
  64. package/dist/generic/queryResultEnricher.d.ts +4 -1
  65. package/dist/generic/queryResultEnricher.d.ts.map +1 -1
  66. package/dist/generic/queryResultEnricher.js.map +1 -1
  67. package/dist/generic/queryTemplateContext.d.ts.map +1 -1
  68. package/dist/generic/queryTemplateContext.js +38 -3
  69. package/dist/generic/queryTemplateContext.js.map +1 -1
  70. package/dist/generic/relatedRecordCollection.d.ts +20 -0
  71. package/dist/generic/relatedRecordCollection.d.ts.map +1 -1
  72. package/dist/generic/relatedRecordCollection.js +257 -22
  73. package/dist/generic/relatedRecordCollection.js.map +1 -1
  74. package/dist/generic/securityInfo.d.ts +56 -2
  75. package/dist/generic/securityInfo.d.ts.map +1 -1
  76. package/dist/generic/securityInfo.js +141 -12
  77. package/dist/generic/securityInfo.js.map +1 -1
  78. package/dist/generic/telemetryManager.d.ts +40 -4
  79. package/dist/generic/telemetryManager.d.ts.map +1 -1
  80. package/dist/generic/telemetryManager.js +68 -15
  81. package/dist/generic/telemetryManager.js.map +1 -1
  82. package/dist/generic/transactionGroup.d.ts +41 -23
  83. package/dist/generic/transactionGroup.d.ts.map +1 -1
  84. package/dist/generic/transactionGroup.js +133 -70
  85. package/dist/generic/transactionGroup.js.map +1 -1
  86. package/dist/index.d.ts +3 -1
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +3 -1
  89. package/dist/index.js.map +1 -1
  90. package/dist/tsconfig.tsbuildinfo +1 -0
  91. package/dist/views/decisionReadGuard.d.ts +143 -0
  92. package/dist/views/decisionReadGuard.d.ts.map +1 -0
  93. package/dist/views/decisionReadGuard.js +220 -0
  94. package/dist/views/decisionReadGuard.js.map +1 -0
  95. package/dist/views/runView.d.ts +8 -0
  96. package/dist/views/runView.d.ts.map +1 -1
  97. package/dist/views/runView.js +20 -3
  98. package/dist/views/runView.js.map +1 -1
  99. package/package.json +3 -3
  100. package/readme.md +6 -5
  101. package/dist/generic/typedQuery.d.ts +0 -151
  102. package/dist/generic/typedQuery.d.ts.map +0 -1
  103. package/dist/generic/typedQuery.js +0 -286
  104. package/dist/generic/typedQuery.js.map +0 -1
@@ -0,0 +1,1126 @@
1
+ /**
2
+ * @fileoverview Centralized, strongly-typed `limits` configuration contract and 5-tier
3
+ * hierarchical resolver (`LimitsConfigResolver`).
4
+ *
5
+ * Pure and browser-safe (no Node-specific `fs` / `cosmiconfig` imports): hosts load `mj.config.cjs`
6
+ * outside `@memberjunction/core` and pass its `limits` object into {@link LimitsConfigResolver.Resolve}
7
+ * or register it once at startup via {@link LimitsConfigResolver.RegisterMjConfigLimits}.
8
+ *
9
+ * Precedence order (lowest -> highest):
10
+ * 1. `CodeFallback`
11
+ * 2. `MjConfig` (`mj.config.cjs` `limits` section)
12
+ * 3. `AgentOrWorkflowMetadata` (Agent or workflow metadata overrides)
13
+ * 4. `UserAgentPolicy` (User's agent policy overrides)
14
+ * 5. `RunOverride` (Individual run overrides)
15
+ *
16
+ * @module @memberjunction/core
17
+ */
18
+ import { BaseSingleton, IsPlainObject } from '@memberjunction/global';
19
+ import { AuthorizationEvaluator } from './authEvaluator.js';
20
+ /**
21
+ * Canonical 5-tier precedence chain from lowest to highest priority.
22
+ */
23
+ export const LIMITS_TIER_PRECEDENCE = [
24
+ 'CodeFallback',
25
+ 'MjConfig',
26
+ 'AgentOrWorkflowMetadata',
27
+ 'UserAgentPolicy',
28
+ 'RunOverride',
29
+ ];
30
+ /**
31
+ * Ordered list of valid {@link TaskGraphIsolationLevel} values.
32
+ */
33
+ export const TASK_GRAPH_ISOLATION_LEVELS = [
34
+ 'InProcess',
35
+ 'Worker',
36
+ 'Process',
37
+ 'Container',
38
+ ];
39
+ /**
40
+ * Runtime type guard verifying whether an untyped value is a valid {@link TaskGraphIsolationLevel}.
41
+ */
42
+ export function IsTaskGraphIsolationLevel(value) {
43
+ return value === 'InProcess' || value === 'Worker' || value === 'Process' || value === 'Container';
44
+ }
45
+ /**
46
+ * Canonical approved code fallback defaults for all MemberJunction limits and backstops.
47
+ */
48
+ export const CODE_FALLBACK_LIMITS = {
49
+ AgentChannelConsecutiveTurns: 1000,
50
+ AgentChannelWakesPerHour: 600,
51
+ AgentAbsoluteIterations: 100_000,
52
+ MaxTasksPerAgentGraph: 10_000,
53
+ WhileLoopMaxIterations: 1_000_000,
54
+ ForEachMaxIterations: 1_000_000,
55
+ MaxTasksPerGraph: 100_000,
56
+ BriefingContributorTimeoutMs: 10_000,
57
+ BriefingMaxContributorChars: 32_768,
58
+ Budgets: {
59
+ PerRun: {
60
+ MaxCostUsd: null,
61
+ MaxWallClockMs: 7_200_000,
62
+ MaxTokens: null,
63
+ },
64
+ PerRoutine: {
65
+ MaxCostUsd: null,
66
+ MaxWallClockMs: null,
67
+ },
68
+ PerUserPerDay: {
69
+ MaxCostUsd: null,
70
+ MaxWallClockMs: null,
71
+ DayBoundaryTimezone: 'UTC',
72
+ },
73
+ CountPausedTimeTowardsWallClock: false,
74
+ AllowedInFlightOvershootUsd: 0,
75
+ AllowedInFlightOvershootMs: 0,
76
+ },
77
+ ProgressDetector: {
78
+ Enabled: true,
79
+ WindowSize: 10,
80
+ MinIterationsBeforeCheck: 6,
81
+ DuplicateStepRatioThreshold: 0.75,
82
+ NoPayloadDeltaWindowCount: 5,
83
+ RepeatingErrorWindowCount: 4,
84
+ AmbiguityLowScoreThreshold: 0.25,
85
+ AmbiguityHighScoreThreshold: 0.65,
86
+ FastJudgeEnabled: true,
87
+ FastJudgeTimeoutMs: 200,
88
+ FastJudgeMinIntervalIterations: 5,
89
+ FastJudgeMaxInputChars: 8192,
90
+ FastJudgeFailureFallback: 'ContinueWithWarning',
91
+ },
92
+ ResourceGuards: {
93
+ MaxValidationRetries: 10,
94
+ MaxConsecutiveFailedSteps: 10,
95
+ MaxConsecutiveUnproductiveRetries: 10,
96
+ MaxRepeatedFailingStep: 3,
97
+ MaxConsecutiveReadToolPreemptions: 3,
98
+ FinalPayloadValidationMaxRetries: 3,
99
+ MaxRunChainLength: 1000,
100
+ MaxAgentRunTreeDepth: 100,
101
+ MaxHandoffHops: 3,
102
+ MaxSubAgentConsultRounds: 3,
103
+ MaxDecisionRequestsPerTurn: 8,
104
+ MaxDecisionCallsPerTurn: 100,
105
+ MaxConversationToolCallsPerTurn: 8,
106
+ MaxSettlementRetryPasses: 20,
107
+ MaxReinvokeDepth: 5,
108
+ MaxProviderRaiseAttempts: 3,
109
+ ClientToolTimeoutMs: 30_000,
110
+ PipelineDeadlineMs: 120_000,
111
+ MaxPipelineStages: 20,
112
+ MaxMapElements: 1000,
113
+ MaxLoopConcurrency: 10,
114
+ MaxRealtimeConsecutiveAgentTurns: 8,
115
+ },
116
+ Tuning: {
117
+ MaxPerAgentCacheEntries: 200,
118
+ MaxClientToolSessions: 1000,
119
+ MaxToolsPerSession: 200,
120
+ CompactionDefaultContextTokens: 8000,
121
+ CompactionDefaultTriggerPercent: 75,
122
+ CompactionDefaultTargetPercent: 30,
123
+ CompactionMinGainTokens: 500,
124
+ CompactionMinMessages: 4,
125
+ CompactionMaxDeltaMessageChars: 10_000,
126
+ MaxSkillDecisionCandidates: 30,
127
+ MaxHandoffCandidates: 20,
128
+ QueryCacheDefaultMaxSize: 1000,
129
+ QueryCacheDefaultTtlMinutes: 60,
130
+ ScratchpadMaxTasks: 50,
131
+ DecisionsMaxItems: 100,
132
+ MaxInitialArtifactOperations: 100,
133
+ MaxDirectInIds: 2500,
134
+ MaxAgentsOfferedInDraft: 40,
135
+ MaxStepsPerSignal: 1000,
136
+ },
137
+ Isolation: {
138
+ DefaultIsolation: 'InProcess',
139
+ DraftDefaultIsolation: 'Worker',
140
+ WorkerMaxOldGenerationSizeMb: 256,
141
+ WorkerMaxYoungGenerationSizeMb: 64,
142
+ WorkerTimeoutMs: 120_000,
143
+ ProcessMaxMemoryMb: 512,
144
+ ProcessTimeoutMs: 300_000,
145
+ ContainerMemoryMb: 512,
146
+ ContainerCpuQuota: 1,
147
+ ContainerTimeoutMs: 300_000,
148
+ ContainerImage: 'node:20-alpine',
149
+ ContainerRuntime: 'docker',
150
+ },
151
+ TaskGraphQueue: {
152
+ GraphDispatchTopicName: 'mj.taskgraph.runs',
153
+ DefaultEnqueueTopicName: 'mj.taskgraph.steps',
154
+ MaxEnqueuePublishConcurrency: 25,
155
+ EnqueuePublishBatchSize: 100,
156
+ MaxConcurrentIsolatedRunners: 16,
157
+ MaxEnqueueItemsPerFanOut: 100_000,
158
+ MaxEnqueueRedeliveryAttempts: 5,
159
+ EnqueuePublishRetryAttempts: 3,
160
+ CallerNotificationRetentionMs: 86_400_000,
161
+ },
162
+ };
163
+ /**
164
+ * Alias for {@link CODE_FALLBACK_LIMITS} representing the default MemberJunction limits
165
+ * configuration used when `mj.config.cjs` omits a `limits` block.
166
+ */
167
+ export const DEFAULT_MJ_LIMITS_CONFIG = CODE_FALLBACK_LIMITS;
168
+ const RESOURCE_GUARD_KEYS = [
169
+ 'MaxValidationRetries',
170
+ 'MaxConsecutiveFailedSteps',
171
+ 'MaxConsecutiveUnproductiveRetries',
172
+ 'MaxRepeatedFailingStep',
173
+ 'MaxConsecutiveReadToolPreemptions',
174
+ 'FinalPayloadValidationMaxRetries',
175
+ 'MaxRunChainLength',
176
+ 'MaxAgentRunTreeDepth',
177
+ 'MaxHandoffHops',
178
+ 'MaxSubAgentConsultRounds',
179
+ 'MaxDecisionRequestsPerTurn',
180
+ 'MaxDecisionCallsPerTurn',
181
+ 'MaxConversationToolCallsPerTurn',
182
+ 'MaxSettlementRetryPasses',
183
+ 'MaxReinvokeDepth',
184
+ 'MaxProviderRaiseAttempts',
185
+ 'ClientToolTimeoutMs',
186
+ 'PipelineDeadlineMs',
187
+ 'MaxPipelineStages',
188
+ 'MaxMapElements',
189
+ 'MaxLoopConcurrency',
190
+ 'MaxRealtimeConsecutiveAgentTurns',
191
+ ];
192
+ const TUNING_KEYS = [
193
+ 'MaxPerAgentCacheEntries',
194
+ 'MaxClientToolSessions',
195
+ 'MaxToolsPerSession',
196
+ 'CompactionDefaultContextTokens',
197
+ 'CompactionDefaultTriggerPercent',
198
+ 'CompactionDefaultTargetPercent',
199
+ 'CompactionMinGainTokens',
200
+ 'CompactionMinMessages',
201
+ 'CompactionMaxDeltaMessageChars',
202
+ 'MaxSkillDecisionCandidates',
203
+ 'MaxHandoffCandidates',
204
+ 'QueryCacheDefaultMaxSize',
205
+ 'QueryCacheDefaultTtlMinutes',
206
+ 'ScratchpadMaxTasks',
207
+ 'DecisionsMaxItems',
208
+ 'MaxInitialArtifactOperations',
209
+ 'MaxDirectInIds',
210
+ 'MaxAgentsOfferedInDraft',
211
+ 'MaxStepsPerSignal',
212
+ ];
213
+ const ISOLATION_NUMERIC_KEYS = [
214
+ 'WorkerMaxOldGenerationSizeMb',
215
+ 'WorkerMaxYoungGenerationSizeMb',
216
+ 'WorkerTimeoutMs',
217
+ 'ProcessMaxMemoryMb',
218
+ 'ProcessTimeoutMs',
219
+ 'ContainerMemoryMb',
220
+ 'ContainerCpuQuota',
221
+ 'ContainerTimeoutMs',
222
+ ];
223
+ const ISOLATION_KEYS = [
224
+ 'DefaultIsolation',
225
+ 'DraftDefaultIsolation',
226
+ ...ISOLATION_NUMERIC_KEYS,
227
+ 'ContainerImage',
228
+ 'ContainerRuntime',
229
+ ];
230
+ const TASK_GRAPH_QUEUE_NUMERIC_KEYS = [
231
+ 'MaxEnqueuePublishConcurrency',
232
+ 'EnqueuePublishBatchSize',
233
+ 'MaxConcurrentIsolatedRunners',
234
+ 'MaxEnqueueItemsPerFanOut',
235
+ 'MaxEnqueueRedeliveryAttempts',
236
+ 'EnqueuePublishRetryAttempts',
237
+ 'CallerNotificationRetentionMs',
238
+ ];
239
+ const TASK_GRAPH_QUEUE_KEYS = [
240
+ 'GraphDispatchTopicName',
241
+ 'DefaultEnqueueTopicName',
242
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS,
243
+ ];
244
+ /**
245
+ * Ordered list of every {@link LimitsKeyPath} covered by {@link LimitsConfigResolver}.
246
+ */
247
+ export const LIMITS_KEY_PATHS = [
248
+ 'AgentChannelConsecutiveTurns',
249
+ 'AgentChannelWakesPerHour',
250
+ 'AgentAbsoluteIterations',
251
+ 'MaxTasksPerAgentGraph',
252
+ 'WhileLoopMaxIterations',
253
+ 'ForEachMaxIterations',
254
+ 'MaxTasksPerGraph',
255
+ 'BriefingContributorTimeoutMs',
256
+ 'BriefingMaxContributorChars',
257
+ 'Budgets.PerRun.MaxCostUsd',
258
+ 'Budgets.PerRun.MaxWallClockMs',
259
+ 'Budgets.PerRun.MaxTokens',
260
+ 'Budgets.PerRoutine.MaxCostUsd',
261
+ 'Budgets.PerRoutine.MaxWallClockMs',
262
+ 'Budgets.PerUserPerDay.MaxCostUsd',
263
+ 'Budgets.PerUserPerDay.MaxWallClockMs',
264
+ 'Budgets.PerUserPerDay.DayBoundaryTimezone',
265
+ 'Budgets.CountPausedTimeTowardsWallClock',
266
+ 'Budgets.AllowedInFlightOvershootUsd',
267
+ 'Budgets.AllowedInFlightOvershootMs',
268
+ 'ProgressDetector.Enabled',
269
+ 'ProgressDetector.WindowSize',
270
+ 'ProgressDetector.MinIterationsBeforeCheck',
271
+ 'ProgressDetector.DuplicateStepRatioThreshold',
272
+ 'ProgressDetector.NoPayloadDeltaWindowCount',
273
+ 'ProgressDetector.RepeatingErrorWindowCount',
274
+ 'ProgressDetector.AmbiguityLowScoreThreshold',
275
+ 'ProgressDetector.AmbiguityHighScoreThreshold',
276
+ 'ProgressDetector.FastJudgeEnabled',
277
+ 'ProgressDetector.FastJudgeTimeoutMs',
278
+ 'ProgressDetector.FastJudgeMinIntervalIterations',
279
+ 'ProgressDetector.FastJudgeMaxInputChars',
280
+ 'ProgressDetector.FastJudgeFailureFallback',
281
+ ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
282
+ ...TUNING_KEYS.map((k) => `Tuning.${k}`),
283
+ ...ISOLATION_KEYS.map((k) => `Isolation.${k}`),
284
+ ...TASK_GRAPH_QUEUE_KEYS.map((k) => `TaskGraphQueue.${k}`),
285
+ ];
286
+ const NUMERIC_CEILING_KEYS = new Set([
287
+ 'AgentChannelConsecutiveTurns',
288
+ 'AgentChannelWakesPerHour',
289
+ 'AgentAbsoluteIterations',
290
+ 'MaxTasksPerAgentGraph',
291
+ 'WhileLoopMaxIterations',
292
+ 'ForEachMaxIterations',
293
+ 'MaxTasksPerGraph',
294
+ 'BriefingContributorTimeoutMs',
295
+ 'BriefingMaxContributorChars',
296
+ 'Budgets.PerRun.MaxCostUsd',
297
+ 'Budgets.PerRun.MaxWallClockMs',
298
+ 'Budgets.PerRun.MaxTokens',
299
+ 'Budgets.PerRoutine.MaxCostUsd',
300
+ 'Budgets.PerRoutine.MaxWallClockMs',
301
+ 'Budgets.PerUserPerDay.MaxCostUsd',
302
+ 'Budgets.PerUserPerDay.MaxWallClockMs',
303
+ 'Budgets.AllowedInFlightOvershootUsd',
304
+ 'Budgets.AllowedInFlightOvershootMs',
305
+ 'ProgressDetector.FastJudgeMaxInputChars',
306
+ ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
307
+ ...ISOLATION_NUMERIC_KEYS.map((k) => `Isolation.${k}`),
308
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => `TaskGraphQueue.${k}`),
309
+ ]);
310
+ /**
311
+ * Explicit classification of every {@link LimitsKeyPath} into `'PolicyCeiling'` (cannot be raised
312
+ * above an enforced ceiling without authorization) vs `'OverridableDefault'` (operational default
313
+ * or tuning setting).
314
+ */
315
+ export const LIMITS_KEY_ROLES = Object.fromEntries(LIMITS_KEY_PATHS.map((key) => [
316
+ key,
317
+ NUMERIC_CEILING_KEYS.has(key) ? 'PolicyCeiling' : 'OverridableDefault',
318
+ ]));
319
+ /**
320
+ * Returns the governance role (`'PolicyCeiling'` vs `'OverridableDefault'`) for a canonical limit key.
321
+ */
322
+ export function GetLimitsKeyRole(key) {
323
+ return LIMITS_KEY_ROLES[key];
324
+ }
325
+ /**
326
+ * Returns `true` when {@link key} is a numeric policy ceiling that requires authorization to raise
327
+ * above an enforced lower-tier ceiling.
328
+ */
329
+ export function IsPolicyCeilingKey(key) {
330
+ return LIMITS_KEY_ROLES[key] === 'PolicyCeiling';
331
+ }
332
+ /**
333
+ * Named MJ Authorizations permitted to raise enforced `PolicyCeiling` limits or approve
334
+ * governance pause overrides.
335
+ */
336
+ export const LIMITS_CEILING_OVERRIDE_AUTHORIZATIONS = [
337
+ 'System Administrator',
338
+ 'AI: Manage Agents',
339
+ ];
340
+ /**
341
+ * Evaluates whether a server-side `ContextUser` is authorized to raise enforced limits ceilings
342
+ * (`Owner` user type or holding `'System Administrator'` / `'AI: Manage Agents'` authorization).
343
+ * Fails closed (`false`) when `user` is missing or lacks required authorization.
344
+ */
345
+ export function CanUserRaiseEnforcedLimitsCeilings(user, provider) {
346
+ if (!user) {
347
+ return false;
348
+ }
349
+ const userType = typeof user.Type === 'string' ? user.Type.trim().toLowerCase() : '';
350
+ if (userType === 'owner') {
351
+ return true;
352
+ }
353
+ const authorizations = provider?.Authorizations ?? [];
354
+ const allowedSet = new Set(LIMITS_CEILING_OVERRIDE_AUTHORIZATIONS.map((name) => name.toLowerCase()));
355
+ const evaluator = new AuthorizationEvaluator();
356
+ for (const auth of authorizations) {
357
+ const name = auth.Name?.trim().toLowerCase();
358
+ if (name && allowedSet.has(name) && evaluator.UserCanExecuteWithAncestors(auth, user, authorizations)) {
359
+ return true;
360
+ }
361
+ }
362
+ return false;
363
+ }
364
+ function isLimitsInputObject(raw) {
365
+ return IsPlainObject(raw);
366
+ }
367
+ function readObjectProperty(obj, keys) {
368
+ for (const key of keys) {
369
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
370
+ return obj[key];
371
+ }
372
+ }
373
+ return undefined;
374
+ }
375
+ function readFiniteNonNegativeNumber(raw) {
376
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {
377
+ return undefined;
378
+ }
379
+ return raw;
380
+ }
381
+ function readPositiveInteger(raw) {
382
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 1) {
383
+ return undefined;
384
+ }
385
+ return Math.trunc(raw);
386
+ }
387
+ function readNullableNonNegativeNumber(raw) {
388
+ if (raw === null) {
389
+ return null;
390
+ }
391
+ return readFiniteNonNegativeNumber(raw);
392
+ }
393
+ function readNullablePositiveInteger(raw) {
394
+ if (raw === null) {
395
+ return null;
396
+ }
397
+ return readPositiveInteger(raw);
398
+ }
399
+ function readUnitIntervalNumber(raw) {
400
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0 || raw > 1) {
401
+ return undefined;
402
+ }
403
+ return raw;
404
+ }
405
+ function readBoolean(raw) {
406
+ return typeof raw === 'boolean' ? raw : undefined;
407
+ }
408
+ function readNonEmptyString(raw) {
409
+ if (typeof raw !== 'string') {
410
+ return undefined;
411
+ }
412
+ const trimmed = raw.trim();
413
+ return trimmed.length > 0 ? trimmed : undefined;
414
+ }
415
+ function readFastJudgeFallback(raw) {
416
+ if (raw === 'ContinueWithWarning' || raw === 'PauseForHuman') {
417
+ return raw;
418
+ }
419
+ return undefined;
420
+ }
421
+ function readIsolationLevel(raw) {
422
+ return IsTaskGraphIsolationLevel(raw) ? raw : undefined;
423
+ }
424
+ function normalizeIsolationOverride(raw) {
425
+ if (!isLimitsInputObject(raw)) {
426
+ return undefined;
427
+ }
428
+ const out = {};
429
+ const defaultIso = readIsolationLevel(readObjectProperty(raw, ['DefaultIsolation', 'defaultIsolation']));
430
+ if (defaultIso !== undefined)
431
+ out.DefaultIsolation = defaultIso;
432
+ const draftIso = readIsolationLevel(readObjectProperty(raw, ['DraftDefaultIsolation', 'draftDefaultIsolation']));
433
+ if (draftIso !== undefined)
434
+ out.DraftDefaultIsolation = draftIso;
435
+ const numeric = normalizePositiveIntSection(raw, ISOLATION_NUMERIC_KEYS);
436
+ if (numeric) {
437
+ Object.assign(out, numeric);
438
+ }
439
+ const containerImage = readNonEmptyString(readObjectProperty(raw, ['ContainerImage', 'containerImage']));
440
+ if (containerImage !== undefined)
441
+ out.ContainerImage = containerImage;
442
+ const containerRuntime = readNonEmptyString(readObjectProperty(raw, ['ContainerRuntime', 'containerRuntime']));
443
+ if (containerRuntime !== undefined)
444
+ out.ContainerRuntime = containerRuntime;
445
+ return Object.keys(out).length > 0 ? out : undefined;
446
+ }
447
+ function normalizeTaskGraphQueueOverride(raw) {
448
+ if (!isLimitsInputObject(raw)) {
449
+ return undefined;
450
+ }
451
+ const out = {};
452
+ const graphTopic = readNonEmptyString(readObjectProperty(raw, ['GraphDispatchTopicName', 'graphDispatchTopicName']));
453
+ if (graphTopic !== undefined)
454
+ out.GraphDispatchTopicName = graphTopic;
455
+ const stepTopic = readNonEmptyString(readObjectProperty(raw, ['DefaultEnqueueTopicName', 'defaultEnqueueTopicName']));
456
+ if (stepTopic !== undefined)
457
+ out.DefaultEnqueueTopicName = stepTopic;
458
+ const numeric = normalizePositiveIntSection(raw, TASK_GRAPH_QUEUE_NUMERIC_KEYS);
459
+ if (numeric) {
460
+ Object.assign(out, numeric);
461
+ }
462
+ return Object.keys(out).length > 0 ? out : undefined;
463
+ }
464
+ function normalizeScopeBudgetOverride(raw) {
465
+ if (!isLimitsInputObject(raw)) {
466
+ return undefined;
467
+ }
468
+ const out = {};
469
+ const maxCost = readNullableNonNegativeNumber(readObjectProperty(raw, ['MaxCostUsd', 'maxCostUsd']));
470
+ if (maxCost !== undefined) {
471
+ out.MaxCostUsd = maxCost;
472
+ }
473
+ const maxWall = readNullablePositiveInteger(readObjectProperty(raw, ['MaxWallClockMs', 'maxWallClockMs']));
474
+ if (maxWall !== undefined) {
475
+ out.MaxWallClockMs = maxWall;
476
+ }
477
+ return Object.keys(out).length > 0 ? out : undefined;
478
+ }
479
+ function normalizeRunScopeBudgetOverride(raw) {
480
+ if (!isLimitsInputObject(raw)) {
481
+ return undefined;
482
+ }
483
+ const base = normalizeScopeBudgetOverride(raw) ?? {};
484
+ const out = { ...base };
485
+ const maxTokens = readNullablePositiveInteger(readObjectProperty(raw, ['MaxTokens', 'maxTokens']));
486
+ if (maxTokens !== undefined) {
487
+ out.MaxTokens = maxTokens;
488
+ }
489
+ return Object.keys(out).length > 0 ? out : undefined;
490
+ }
491
+ function normalizeUserDailyScopeBudgetOverride(raw) {
492
+ if (!isLimitsInputObject(raw)) {
493
+ return undefined;
494
+ }
495
+ const base = normalizeScopeBudgetOverride(raw) ?? {};
496
+ const out = { ...base };
497
+ const tz = readNonEmptyString(readObjectProperty(raw, ['DayBoundaryTimezone', 'dayBoundaryTimezone']));
498
+ if (tz !== undefined) {
499
+ out.DayBoundaryTimezone = tz;
500
+ }
501
+ return Object.keys(out).length > 0 ? out : undefined;
502
+ }
503
+ function normalizeBudgetsOverride(raw) {
504
+ if (!isLimitsInputObject(raw)) {
505
+ return undefined;
506
+ }
507
+ const out = {};
508
+ const perRun = normalizeRunScopeBudgetOverride(readObjectProperty(raw, ['PerRun', 'perRun']));
509
+ if (perRun) {
510
+ out.PerRun = perRun;
511
+ }
512
+ const perRoutine = normalizeScopeBudgetOverride(readObjectProperty(raw, ['PerRoutine', 'perRoutine']));
513
+ if (perRoutine) {
514
+ out.PerRoutine = perRoutine;
515
+ }
516
+ const perUserPerDay = normalizeUserDailyScopeBudgetOverride(readObjectProperty(raw, ['PerUserPerDay', 'perUserPerDay']));
517
+ if (perUserPerDay) {
518
+ out.PerUserPerDay = perUserPerDay;
519
+ }
520
+ const countPaused = readBoolean(readObjectProperty(raw, ['CountPausedTimeTowardsWallClock', 'countPausedTimeTowardsWallClock']));
521
+ if (countPaused !== undefined) {
522
+ out.CountPausedTimeTowardsWallClock = countPaused;
523
+ }
524
+ const overshootUsd = readFiniteNonNegativeNumber(readObjectProperty(raw, ['AllowedInFlightOvershootUsd', 'allowedInFlightOvershootUsd']));
525
+ if (overshootUsd !== undefined) {
526
+ out.AllowedInFlightOvershootUsd = overshootUsd;
527
+ }
528
+ const overshootMs = readFiniteNonNegativeNumber(readObjectProperty(raw, ['AllowedInFlightOvershootMs', 'allowedInFlightOvershootMs']));
529
+ if (overshootMs !== undefined) {
530
+ out.AllowedInFlightOvershootMs = overshootMs;
531
+ }
532
+ return Object.keys(out).length > 0 ? out : undefined;
533
+ }
534
+ function normalizeProgressDetectorOverride(raw) {
535
+ if (!isLimitsInputObject(raw)) {
536
+ return undefined;
537
+ }
538
+ const out = {};
539
+ const enabled = readBoolean(readObjectProperty(raw, ['Enabled', 'enabled']));
540
+ if (enabled !== undefined)
541
+ out.Enabled = enabled;
542
+ const windowSize = readPositiveInteger(readObjectProperty(raw, ['WindowSize', 'windowSize']));
543
+ if (windowSize !== undefined)
544
+ out.WindowSize = windowSize;
545
+ const minIterations = readPositiveInteger(readObjectProperty(raw, ['MinIterationsBeforeCheck', 'minIterationsBeforeCheck']));
546
+ if (minIterations !== undefined)
547
+ out.MinIterationsBeforeCheck = minIterations;
548
+ const dupRatio = readUnitIntervalNumber(readObjectProperty(raw, ['DuplicateStepRatioThreshold', 'duplicateStepRatioThreshold']));
549
+ if (dupRatio !== undefined)
550
+ out.DuplicateStepRatioThreshold = dupRatio;
551
+ const noDelta = readPositiveInteger(readObjectProperty(raw, ['NoPayloadDeltaWindowCount', 'noPayloadDeltaWindowCount']));
552
+ if (noDelta !== undefined)
553
+ out.NoPayloadDeltaWindowCount = noDelta;
554
+ const repErr = readPositiveInteger(readObjectProperty(raw, ['RepeatingErrorWindowCount', 'repeatingErrorWindowCount']));
555
+ if (repErr !== undefined)
556
+ out.RepeatingErrorWindowCount = repErr;
557
+ const lowScore = readUnitIntervalNumber(readObjectProperty(raw, ['AmbiguityLowScoreThreshold', 'ambiguityLowScoreThreshold']));
558
+ if (lowScore !== undefined)
559
+ out.AmbiguityLowScoreThreshold = lowScore;
560
+ const highScore = readUnitIntervalNumber(readObjectProperty(raw, ['AmbiguityHighScoreThreshold', 'ambiguityHighScoreThreshold']));
561
+ if (highScore !== undefined)
562
+ out.AmbiguityHighScoreThreshold = highScore;
563
+ const fastJudgeEnabled = readBoolean(readObjectProperty(raw, ['FastJudgeEnabled', 'fastJudgeEnabled']));
564
+ if (fastJudgeEnabled !== undefined)
565
+ out.FastJudgeEnabled = fastJudgeEnabled;
566
+ const fastJudgeTimeoutMs = readPositiveInteger(readObjectProperty(raw, ['FastJudgeTimeoutMs', 'fastJudgeTimeoutMs']));
567
+ if (fastJudgeTimeoutMs !== undefined)
568
+ out.FastJudgeTimeoutMs = fastJudgeTimeoutMs;
569
+ const minInterval = readPositiveInteger(readObjectProperty(raw, ['FastJudgeMinIntervalIterations', 'fastJudgeMinIntervalIterations']));
570
+ if (minInterval !== undefined)
571
+ out.FastJudgeMinIntervalIterations = minInterval;
572
+ const maxInputChars = readPositiveInteger(readObjectProperty(raw, ['FastJudgeMaxInputChars', 'fastJudgeMaxInputChars']));
573
+ if (maxInputChars !== undefined)
574
+ out.FastJudgeMaxInputChars = maxInputChars;
575
+ const fallback = readFastJudgeFallback(readObjectProperty(raw, ['FastJudgeFailureFallback', 'fastJudgeFailureFallback']));
576
+ if (fallback !== undefined)
577
+ out.FastJudgeFailureFallback = fallback;
578
+ return Object.keys(out).length > 0 ? out : undefined;
579
+ }
580
+ function normalizePositiveIntSection(raw, keys) {
581
+ if (!isLimitsInputObject(raw)) {
582
+ return undefined;
583
+ }
584
+ const out = {};
585
+ for (const key of keys) {
586
+ const camel = key.charAt(0).toLowerCase() + key.slice(1);
587
+ const val = readPositiveInteger(readObjectProperty(raw, [key, camel]));
588
+ if (val !== undefined) {
589
+ out[key] = val;
590
+ }
591
+ }
592
+ return Object.keys(out).length > 0 ? out : undefined;
593
+ }
594
+ /**
595
+ * Tolerantly normalizes an untyped `limits` object (from `mj.config.cjs`, agent metadata JSON,
596
+ * or API payloads) into a strongly-typed {@link MJLimitsOverride}. Accepts both PascalCase and
597
+ * camelCase field names plus standard legacy aliases (`ContributorTimeoutMs`, `MaxContributorChars`,
598
+ * `MaxConsecutiveAgentTurns`, `MaxHourlyWakes`, `MAX_TASKS_PER_AGENT_GRAPH`, `MAX_TASKS_PER_GRAPH`,
599
+ * `absoluteMaxIterations`). Invalid or out-of-range values are omitted rather than throwing.
600
+ *
601
+ * @param raw - Raw input object (typically from `mj.config.cjs` `limits` or parsed JSON).
602
+ * @returns Normalized {@link MJLimitsOverride} containing only valid fields.
603
+ */
604
+ export function NormalizeLimitsInput(raw) {
605
+ if (!isLimitsInputObject(raw)) {
606
+ return {};
607
+ }
608
+ const out = {};
609
+ const turns = readPositiveInteger(readObjectProperty(raw, ['AgentChannelConsecutiveTurns', 'agentChannelConsecutiveTurns', 'MaxConsecutiveAgentTurns', 'maxConsecutiveAgentTurns']));
610
+ if (turns !== undefined)
611
+ out.AgentChannelConsecutiveTurns = turns;
612
+ const wakes = readPositiveInteger(readObjectProperty(raw, ['AgentChannelWakesPerHour', 'agentChannelWakesPerHour', 'MaxHourlyWakes', 'maxHourlyWakes']));
613
+ if (wakes !== undefined)
614
+ out.AgentChannelWakesPerHour = wakes;
615
+ const iterations = readPositiveInteger(readObjectProperty(raw, ['AgentAbsoluteIterations', 'agentAbsoluteIterations', 'absoluteMaxIterations']));
616
+ if (iterations !== undefined)
617
+ out.AgentAbsoluteIterations = iterations;
618
+ const agentGraph = readPositiveInteger(readObjectProperty(raw, ['MaxTasksPerAgentGraph', 'maxTasksPerAgentGraph', 'MAX_TASKS_PER_AGENT_GRAPH']));
619
+ if (agentGraph !== undefined)
620
+ out.MaxTasksPerAgentGraph = agentGraph;
621
+ const whileMax = readPositiveInteger(readObjectProperty(raw, ['WhileLoopMaxIterations', 'whileLoopMaxIterations']));
622
+ if (whileMax !== undefined)
623
+ out.WhileLoopMaxIterations = whileMax;
624
+ const forEachMax = readPositiveInteger(readObjectProperty(raw, ['ForEachMaxIterations', 'forEachMaxIterations']));
625
+ if (forEachMax !== undefined)
626
+ out.ForEachMaxIterations = forEachMax;
627
+ const graphCeiling = readPositiveInteger(readObjectProperty(raw, ['MaxTasksPerGraph', 'maxTasksPerGraph', 'MAX_TASKS_PER_GRAPH']));
628
+ if (graphCeiling !== undefined)
629
+ out.MaxTasksPerGraph = graphCeiling;
630
+ const briefingTimeout = readPositiveInteger(readObjectProperty(raw, ['BriefingContributorTimeoutMs', 'briefingContributorTimeoutMs', 'ContributorTimeoutMs']));
631
+ if (briefingTimeout !== undefined)
632
+ out.BriefingContributorTimeoutMs = briefingTimeout;
633
+ const briefingChars = readPositiveInteger(readObjectProperty(raw, ['BriefingMaxContributorChars', 'briefingMaxContributorChars', 'MaxContributorChars']));
634
+ if (briefingChars !== undefined)
635
+ out.BriefingMaxContributorChars = briefingChars;
636
+ const budgets = normalizeBudgetsOverride(readObjectProperty(raw, ['Budgets', 'budgets']));
637
+ if (budgets)
638
+ out.Budgets = budgets;
639
+ const progressDetector = normalizeProgressDetectorOverride(readObjectProperty(raw, ['ProgressDetector', 'progressDetector']));
640
+ if (progressDetector)
641
+ out.ProgressDetector = progressDetector;
642
+ const resourceGuards = normalizePositiveIntSection(readObjectProperty(raw, ['ResourceGuards', 'resourceGuards']), RESOURCE_GUARD_KEYS);
643
+ if (resourceGuards)
644
+ out.ResourceGuards = resourceGuards;
645
+ const tuning = normalizePositiveIntSection(readObjectProperty(raw, ['Tuning', 'tuning']), TUNING_KEYS);
646
+ if (tuning)
647
+ out.Tuning = tuning;
648
+ const isolation = normalizeIsolationOverride(readObjectProperty(raw, ['Isolation', 'isolation']));
649
+ if (isolation)
650
+ out.Isolation = isolation;
651
+ const taskGraphQueue = normalizeTaskGraphQueueOverride(readObjectProperty(raw, ['TaskGraphQueue', 'taskGraphQueue']));
652
+ if (taskGraphQueue)
653
+ out.TaskGraphQueue = taskGraphQueue;
654
+ return out;
655
+ }
656
+ function cloneDefaultLimits() {
657
+ return {
658
+ ...CODE_FALLBACK_LIMITS,
659
+ Budgets: {
660
+ PerRun: { ...CODE_FALLBACK_LIMITS.Budgets.PerRun },
661
+ PerRoutine: { ...CODE_FALLBACK_LIMITS.Budgets.PerRoutine },
662
+ PerUserPerDay: { ...CODE_FALLBACK_LIMITS.Budgets.PerUserPerDay },
663
+ CountPausedTimeTowardsWallClock: CODE_FALLBACK_LIMITS.Budgets.CountPausedTimeTowardsWallClock,
664
+ AllowedInFlightOvershootUsd: CODE_FALLBACK_LIMITS.Budgets.AllowedInFlightOvershootUsd,
665
+ AllowedInFlightOvershootMs: CODE_FALLBACK_LIMITS.Budgets.AllowedInFlightOvershootMs,
666
+ },
667
+ ProgressDetector: { ...CODE_FALLBACK_LIMITS.ProgressDetector },
668
+ ResourceGuards: { ...CODE_FALLBACK_LIMITS.ResourceGuards },
669
+ Tuning: { ...CODE_FALLBACK_LIMITS.Tuning },
670
+ Isolation: { ...CODE_FALLBACK_LIMITS.Isolation },
671
+ TaskGraphQueue: { ...CODE_FALLBACK_LIMITS.TaskGraphQueue },
672
+ };
673
+ }
674
+ function extractTierValue(layer, key) {
675
+ if (key.startsWith('ResourceGuards.')) {
676
+ const subKey = key.slice('ResourceGuards.'.length);
677
+ return layer.ResourceGuards?.[subKey];
678
+ }
679
+ if (key.startsWith('Tuning.')) {
680
+ const subKey = key.slice('Tuning.'.length);
681
+ return layer.Tuning?.[subKey];
682
+ }
683
+ if (key.startsWith('Isolation.')) {
684
+ const subKey = key.slice('Isolation.'.length);
685
+ return layer.Isolation?.[subKey];
686
+ }
687
+ if (key.startsWith('TaskGraphQueue.')) {
688
+ const subKey = key.slice('TaskGraphQueue.'.length);
689
+ return layer.TaskGraphQueue?.[subKey];
690
+ }
691
+ switch (key) {
692
+ case 'AgentChannelConsecutiveTurns': return layer.AgentChannelConsecutiveTurns;
693
+ case 'AgentChannelWakesPerHour': return layer.AgentChannelWakesPerHour;
694
+ case 'AgentAbsoluteIterations': return layer.AgentAbsoluteIterations;
695
+ case 'MaxTasksPerAgentGraph': return layer.MaxTasksPerAgentGraph;
696
+ case 'WhileLoopMaxIterations': return layer.WhileLoopMaxIterations;
697
+ case 'ForEachMaxIterations': return layer.ForEachMaxIterations;
698
+ case 'MaxTasksPerGraph': return layer.MaxTasksPerGraph;
699
+ case 'BriefingContributorTimeoutMs': return layer.BriefingContributorTimeoutMs;
700
+ case 'BriefingMaxContributorChars': return layer.BriefingMaxContributorChars;
701
+ case 'Budgets.PerRun.MaxCostUsd': return layer.Budgets?.PerRun?.MaxCostUsd;
702
+ case 'Budgets.PerRun.MaxWallClockMs': return layer.Budgets?.PerRun?.MaxWallClockMs;
703
+ case 'Budgets.PerRun.MaxTokens': return layer.Budgets?.PerRun?.MaxTokens;
704
+ case 'Budgets.PerRoutine.MaxCostUsd': return layer.Budgets?.PerRoutine?.MaxCostUsd;
705
+ case 'Budgets.PerRoutine.MaxWallClockMs': return layer.Budgets?.PerRoutine?.MaxWallClockMs;
706
+ case 'Budgets.PerUserPerDay.MaxCostUsd': return layer.Budgets?.PerUserPerDay?.MaxCostUsd;
707
+ case 'Budgets.PerUserPerDay.MaxWallClockMs': return layer.Budgets?.PerUserPerDay?.MaxWallClockMs;
708
+ case 'Budgets.PerUserPerDay.DayBoundaryTimezone': return layer.Budgets?.PerUserPerDay?.DayBoundaryTimezone;
709
+ case 'Budgets.CountPausedTimeTowardsWallClock': return layer.Budgets?.CountPausedTimeTowardsWallClock;
710
+ case 'Budgets.AllowedInFlightOvershootUsd': return layer.Budgets?.AllowedInFlightOvershootUsd;
711
+ case 'Budgets.AllowedInFlightOvershootMs': return layer.Budgets?.AllowedInFlightOvershootMs;
712
+ case 'ProgressDetector.Enabled': return layer.ProgressDetector?.Enabled;
713
+ case 'ProgressDetector.WindowSize': return layer.ProgressDetector?.WindowSize;
714
+ case 'ProgressDetector.MinIterationsBeforeCheck': return layer.ProgressDetector?.MinIterationsBeforeCheck;
715
+ case 'ProgressDetector.DuplicateStepRatioThreshold': return layer.ProgressDetector?.DuplicateStepRatioThreshold;
716
+ case 'ProgressDetector.NoPayloadDeltaWindowCount': return layer.ProgressDetector?.NoPayloadDeltaWindowCount;
717
+ case 'ProgressDetector.RepeatingErrorWindowCount': return layer.ProgressDetector?.RepeatingErrorWindowCount;
718
+ case 'ProgressDetector.AmbiguityLowScoreThreshold': return layer.ProgressDetector?.AmbiguityLowScoreThreshold;
719
+ case 'ProgressDetector.AmbiguityHighScoreThreshold': return layer.ProgressDetector?.AmbiguityHighScoreThreshold;
720
+ case 'ProgressDetector.FastJudgeEnabled': return layer.ProgressDetector?.FastJudgeEnabled;
721
+ case 'ProgressDetector.FastJudgeTimeoutMs': return layer.ProgressDetector?.FastJudgeTimeoutMs;
722
+ case 'ProgressDetector.FastJudgeMinIntervalIterations': return layer.ProgressDetector?.FastJudgeMinIntervalIterations;
723
+ case 'ProgressDetector.FastJudgeMaxInputChars': return layer.ProgressDetector?.FastJudgeMaxInputChars;
724
+ case 'ProgressDetector.FastJudgeFailureFallback': return layer.ProgressDetector?.FastJudgeFailureFallback;
725
+ }
726
+ }
727
+ function assignResolvedValue(target, key, value) {
728
+ if (key.startsWith('ResourceGuards.')) {
729
+ const subKey = key.slice('ResourceGuards.'.length);
730
+ target.ResourceGuards[subKey] = value;
731
+ return;
732
+ }
733
+ if (key.startsWith('Tuning.')) {
734
+ const subKey = key.slice('Tuning.'.length);
735
+ target.Tuning[subKey] = value;
736
+ return;
737
+ }
738
+ if (key.startsWith('Isolation.')) {
739
+ const subKey = key.slice('Isolation.'.length);
740
+ if (subKey === 'ContainerImage' || subKey === 'ContainerRuntime') {
741
+ target.Isolation[subKey] = value;
742
+ }
743
+ else if (subKey === 'DefaultIsolation' || subKey === 'DraftDefaultIsolation') {
744
+ target.Isolation[subKey] = value;
745
+ }
746
+ else {
747
+ target.Isolation[subKey] = value;
748
+ }
749
+ return;
750
+ }
751
+ if (key.startsWith('TaskGraphQueue.')) {
752
+ const subKey = key.slice('TaskGraphQueue.'.length);
753
+ if (subKey === 'GraphDispatchTopicName' || subKey === 'DefaultEnqueueTopicName') {
754
+ target.TaskGraphQueue[subKey] = value;
755
+ }
756
+ else {
757
+ target.TaskGraphQueue[subKey] = value;
758
+ }
759
+ return;
760
+ }
761
+ switch (key) {
762
+ case 'AgentChannelConsecutiveTurns':
763
+ target.AgentChannelConsecutiveTurns = value;
764
+ break;
765
+ case 'AgentChannelWakesPerHour':
766
+ target.AgentChannelWakesPerHour = value;
767
+ break;
768
+ case 'AgentAbsoluteIterations':
769
+ target.AgentAbsoluteIterations = value;
770
+ break;
771
+ case 'MaxTasksPerAgentGraph':
772
+ target.MaxTasksPerAgentGraph = value;
773
+ break;
774
+ case 'WhileLoopMaxIterations':
775
+ target.WhileLoopMaxIterations = value;
776
+ break;
777
+ case 'ForEachMaxIterations':
778
+ target.ForEachMaxIterations = value;
779
+ break;
780
+ case 'MaxTasksPerGraph':
781
+ target.MaxTasksPerGraph = value;
782
+ break;
783
+ case 'BriefingContributorTimeoutMs':
784
+ target.BriefingContributorTimeoutMs = value;
785
+ break;
786
+ case 'BriefingMaxContributorChars':
787
+ target.BriefingMaxContributorChars = value;
788
+ break;
789
+ case 'Budgets.PerRun.MaxCostUsd':
790
+ target.Budgets.PerRun.MaxCostUsd = value;
791
+ break;
792
+ case 'Budgets.PerRun.MaxWallClockMs':
793
+ target.Budgets.PerRun.MaxWallClockMs = value;
794
+ break;
795
+ case 'Budgets.PerRun.MaxTokens':
796
+ target.Budgets.PerRun.MaxTokens = value;
797
+ break;
798
+ case 'Budgets.PerRoutine.MaxCostUsd':
799
+ target.Budgets.PerRoutine.MaxCostUsd = value;
800
+ break;
801
+ case 'Budgets.PerRoutine.MaxWallClockMs':
802
+ target.Budgets.PerRoutine.MaxWallClockMs = value;
803
+ break;
804
+ case 'Budgets.PerUserPerDay.MaxCostUsd':
805
+ target.Budgets.PerUserPerDay.MaxCostUsd = value;
806
+ break;
807
+ case 'Budgets.PerUserPerDay.MaxWallClockMs':
808
+ target.Budgets.PerUserPerDay.MaxWallClockMs = value;
809
+ break;
810
+ case 'Budgets.PerUserPerDay.DayBoundaryTimezone':
811
+ target.Budgets.PerUserPerDay.DayBoundaryTimezone = value;
812
+ break;
813
+ case 'Budgets.CountPausedTimeTowardsWallClock':
814
+ target.Budgets.CountPausedTimeTowardsWallClock = value;
815
+ break;
816
+ case 'Budgets.AllowedInFlightOvershootUsd':
817
+ target.Budgets.AllowedInFlightOvershootUsd = value;
818
+ break;
819
+ case 'Budgets.AllowedInFlightOvershootMs':
820
+ target.Budgets.AllowedInFlightOvershootMs = value;
821
+ break;
822
+ case 'ProgressDetector.Enabled':
823
+ target.ProgressDetector.Enabled = value;
824
+ break;
825
+ case 'ProgressDetector.WindowSize':
826
+ target.ProgressDetector.WindowSize = value;
827
+ break;
828
+ case 'ProgressDetector.MinIterationsBeforeCheck':
829
+ target.ProgressDetector.MinIterationsBeforeCheck = value;
830
+ break;
831
+ case 'ProgressDetector.DuplicateStepRatioThreshold':
832
+ target.ProgressDetector.DuplicateStepRatioThreshold = value;
833
+ break;
834
+ case 'ProgressDetector.NoPayloadDeltaWindowCount':
835
+ target.ProgressDetector.NoPayloadDeltaWindowCount = value;
836
+ break;
837
+ case 'ProgressDetector.RepeatingErrorWindowCount':
838
+ target.ProgressDetector.RepeatingErrorWindowCount = value;
839
+ break;
840
+ case 'ProgressDetector.AmbiguityLowScoreThreshold':
841
+ target.ProgressDetector.AmbiguityLowScoreThreshold = value;
842
+ break;
843
+ case 'ProgressDetector.AmbiguityHighScoreThreshold':
844
+ target.ProgressDetector.AmbiguityHighScoreThreshold = value;
845
+ break;
846
+ case 'ProgressDetector.FastJudgeEnabled':
847
+ target.ProgressDetector.FastJudgeEnabled = value;
848
+ break;
849
+ case 'ProgressDetector.FastJudgeTimeoutMs':
850
+ target.ProgressDetector.FastJudgeTimeoutMs = value;
851
+ break;
852
+ case 'ProgressDetector.FastJudgeMinIntervalIterations':
853
+ target.ProgressDetector.FastJudgeMinIntervalIterations = value;
854
+ break;
855
+ case 'ProgressDetector.FastJudgeMaxInputChars':
856
+ target.ProgressDetector.FastJudgeMaxInputChars = value;
857
+ break;
858
+ case 'ProgressDetector.FastJudgeFailureFallback':
859
+ target.ProgressDetector.FastJudgeFailureFallback = value;
860
+ break;
861
+ }
862
+ }
863
+ function shouldClampToPolicyCeiling(key, runVal, policyVal) {
864
+ if (!NUMERIC_CEILING_KEYS.has(key) || typeof policyVal !== 'number' || !Number.isFinite(policyVal)) {
865
+ return false;
866
+ }
867
+ if (runVal === null) {
868
+ return true;
869
+ }
870
+ return typeof runVal === 'number' && Number.isFinite(runVal) && runVal > policyVal;
871
+ }
872
+ function resolveSingleKey(key, defaults, tiers, enforceUserPolicyCeiling, enforceConfiguredCeilings, callerCanRaiseCeilings) {
873
+ const codeFallbackBase = extractTierValue(defaults, key) ?? null;
874
+ const tierValues = {
875
+ CodeFallback: codeFallbackBase,
876
+ };
877
+ let preRunValue = codeFallbackBase;
878
+ let preRunTier = 'CodeFallback';
879
+ let wasClamped = false;
880
+ for (const tier of LIMITS_TIER_PRECEDENCE) {
881
+ if (tier === 'RunOverride') {
882
+ continue;
883
+ }
884
+ const layer = tiers[tier];
885
+ if (!layer) {
886
+ continue;
887
+ }
888
+ const candidate = extractTierValue(layer, key);
889
+ if (candidate !== undefined) {
890
+ tierValues[tier] = candidate;
891
+ if (tier === 'UserAgentPolicy' && !callerCanRaiseCeilings) {
892
+ // F1 org-ceiling invariant: `mj.config.cjs` (MjConfig) sits at the root ceiling
893
+ // of user agent policies; a user's personal policy may only narrow, never raise
894
+ // (or clear to null/unlimited), org ceilings — and when configured ceilings are
895
+ // enforced, cannot raise Agent/Workflow ceilings either.
896
+ const mjConfigVal = tierValues.MjConfig;
897
+ const clampAgainstPreRun = enforceConfiguredCeilings && shouldClampToPolicyCeiling(key, candidate, preRunValue);
898
+ const clampAgainstMjConfig = (enforceConfiguredCeilings || enforceUserPolicyCeiling) &&
899
+ shouldClampToPolicyCeiling(key, candidate, mjConfigVal);
900
+ if (clampAgainstPreRun || clampAgainstMjConfig) {
901
+ if (clampAgainstMjConfig &&
902
+ (!clampAgainstPreRun ||
903
+ (typeof mjConfigVal === 'number' &&
904
+ typeof preRunValue === 'number' &&
905
+ mjConfigVal <= preRunValue))) {
906
+ preRunValue = mjConfigVal;
907
+ preRunTier = 'MjConfig';
908
+ }
909
+ wasClamped = true;
910
+ continue;
911
+ }
912
+ }
913
+ preRunValue = candidate;
914
+ preRunTier = tier;
915
+ }
916
+ }
917
+ let winningValue = preRunValue;
918
+ let sourceTier = preRunTier;
919
+ const runLayer = tiers.RunOverride;
920
+ const runCandidate = runLayer ? extractTierValue(runLayer, key) : undefined;
921
+ if (runCandidate !== undefined) {
922
+ tierValues.RunOverride = runCandidate;
923
+ winningValue = runCandidate;
924
+ sourceTier = 'RunOverride';
925
+ if (!callerCanRaiseCeilings) {
926
+ if (enforceConfiguredCeilings && shouldClampToPolicyCeiling(key, winningValue, preRunValue)) {
927
+ winningValue = preRunValue;
928
+ sourceTier = preRunTier;
929
+ wasClamped = true;
930
+ }
931
+ else if (enforceUserPolicyCeiling && tierValues.UserAgentPolicy !== undefined) {
932
+ // Use the effective (possibly MjConfig-clamped) policy ceiling, never the raw unclamped policy value
933
+ const effectivePolicyCeiling = preRunTier === 'MjConfig' || preRunTier === 'UserAgentPolicy'
934
+ ? preRunValue
935
+ : tierValues.UserAgentPolicy;
936
+ if (shouldClampToPolicyCeiling(key, winningValue, effectivePolicyCeiling)) {
937
+ winningValue = effectivePolicyCeiling;
938
+ sourceTier = preRunTier === 'MjConfig' ? 'MjConfig' : 'UserAgentPolicy';
939
+ wasClamped = true;
940
+ }
941
+ }
942
+ }
943
+ }
944
+ return {
945
+ Key: key,
946
+ KeyRole: GetLimitsKeyRole(key),
947
+ Value: winningValue,
948
+ SourceTier: sourceTier,
949
+ IsOverridden: sourceTier !== 'CodeFallback',
950
+ TierValues: tierValues,
951
+ WasClampedByPolicyCeiling: wasClamped,
952
+ };
953
+ }
954
+ /**
955
+ * Validates a resolved {@link MJLimitsConfig} for structural and range invariants.
956
+ *
957
+ * @param config - Resolved limits config to inspect.
958
+ * @returns Validation result with any violated limit keys and descriptions.
959
+ */
960
+ export function ValidateLimitsConfig(config) {
961
+ const issues = [];
962
+ const positiveIntChecks = [
963
+ ['AgentChannelConsecutiveTurns', config.AgentChannelConsecutiveTurns],
964
+ ['AgentChannelWakesPerHour', config.AgentChannelWakesPerHour],
965
+ ['AgentAbsoluteIterations', config.AgentAbsoluteIterations],
966
+ ['MaxTasksPerAgentGraph', config.MaxTasksPerAgentGraph],
967
+ ['WhileLoopMaxIterations', config.WhileLoopMaxIterations],
968
+ ['ForEachMaxIterations', config.ForEachMaxIterations],
969
+ ['MaxTasksPerGraph', config.MaxTasksPerGraph],
970
+ ['BriefingContributorTimeoutMs', config.BriefingContributorTimeoutMs],
971
+ ['BriefingMaxContributorChars', config.BriefingMaxContributorChars],
972
+ ['ProgressDetector.WindowSize', config.ProgressDetector.WindowSize],
973
+ ['ProgressDetector.MinIterationsBeforeCheck', config.ProgressDetector.MinIterationsBeforeCheck],
974
+ ['ProgressDetector.NoPayloadDeltaWindowCount', config.ProgressDetector.NoPayloadDeltaWindowCount],
975
+ ['ProgressDetector.RepeatingErrorWindowCount', config.ProgressDetector.RepeatingErrorWindowCount],
976
+ ['ProgressDetector.FastJudgeTimeoutMs', config.ProgressDetector.FastJudgeTimeoutMs],
977
+ ['ProgressDetector.FastJudgeMinIntervalIterations', config.ProgressDetector.FastJudgeMinIntervalIterations],
978
+ ['ProgressDetector.FastJudgeMaxInputChars', config.ProgressDetector.FastJudgeMaxInputChars],
979
+ ...RESOURCE_GUARD_KEYS.map((k) => [`ResourceGuards.${k}`, config.ResourceGuards[k]]),
980
+ ...TUNING_KEYS.map((k) => [`Tuning.${k}`, config.Tuning[k]]),
981
+ ...ISOLATION_NUMERIC_KEYS.map((k) => [`Isolation.${k}`, config.Isolation[k]]),
982
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => [`TaskGraphQueue.${k}`, config.TaskGraphQueue[k]]),
983
+ ];
984
+ for (const [key, val] of positiveIntChecks) {
985
+ if (!Number.isFinite(val) || val < 1) {
986
+ issues.push({ Key: key, Message: `${key} must be a positive number >= 1.` });
987
+ }
988
+ }
989
+ if (!IsTaskGraphIsolationLevel(config.Isolation.DefaultIsolation)) {
990
+ issues.push({
991
+ Key: 'Isolation.DefaultIsolation',
992
+ Message: 'Isolation.DefaultIsolation must be one of InProcess, Worker, Process, or Container.',
993
+ });
994
+ }
995
+ if (!IsTaskGraphIsolationLevel(config.Isolation.DraftDefaultIsolation)) {
996
+ issues.push({
997
+ Key: 'Isolation.DraftDefaultIsolation',
998
+ Message: 'Isolation.DraftDefaultIsolation must be one of InProcess, Worker, Process, or Container.',
999
+ });
1000
+ }
1001
+ if (!config.Isolation.ContainerImage || !config.Isolation.ContainerImage.trim()) {
1002
+ issues.push({
1003
+ Key: 'Isolation.ContainerImage',
1004
+ Message: 'Isolation.ContainerImage must be a non-empty string.',
1005
+ });
1006
+ }
1007
+ if (!config.Isolation.ContainerRuntime || !config.Isolation.ContainerRuntime.trim()) {
1008
+ issues.push({
1009
+ Key: 'Isolation.ContainerRuntime',
1010
+ Message: 'Isolation.ContainerRuntime must be a non-empty string.',
1011
+ });
1012
+ }
1013
+ if (!config.TaskGraphQueue.GraphDispatchTopicName || !config.TaskGraphQueue.GraphDispatchTopicName.trim()) {
1014
+ issues.push({
1015
+ Key: 'TaskGraphQueue.GraphDispatchTopicName',
1016
+ Message: 'TaskGraphQueue.GraphDispatchTopicName must be a non-empty string.',
1017
+ });
1018
+ }
1019
+ if (!config.TaskGraphQueue.DefaultEnqueueTopicName || !config.TaskGraphQueue.DefaultEnqueueTopicName.trim()) {
1020
+ issues.push({
1021
+ Key: 'TaskGraphQueue.DefaultEnqueueTopicName',
1022
+ Message: 'TaskGraphQueue.DefaultEnqueueTopicName must be a non-empty string.',
1023
+ });
1024
+ }
1025
+ if (config.MaxTasksPerAgentGraph > config.MaxTasksPerGraph) {
1026
+ issues.push({
1027
+ Key: 'MaxTasksPerAgentGraph',
1028
+ Message: 'MaxTasksPerAgentGraph cannot exceed MaxTasksPerGraph.',
1029
+ });
1030
+ }
1031
+ if (config.ProgressDetector.AmbiguityLowScoreThreshold > config.ProgressDetector.AmbiguityHighScoreThreshold) {
1032
+ issues.push({
1033
+ Key: 'ProgressDetector.AmbiguityLowScoreThreshold',
1034
+ Message: 'AmbiguityLowScoreThreshold cannot exceed AmbiguityHighScoreThreshold.',
1035
+ });
1036
+ }
1037
+ return { Valid: issues.length === 0, Issues: issues };
1038
+ }
1039
+ /**
1040
+ * 5-tier hierarchical resolver for {@link MJLimitsConfig} backed by `BaseSingleton` so server
1041
+ * bootstrap can register `mj.config.cjs` `limits` once across the process without adding Node
1042
+ * dependencies to `@memberjunction/core`.
1043
+ */
1044
+ export class LimitsConfigResolver extends BaseSingleton {
1045
+ constructor() {
1046
+ super();
1047
+ this.registeredMjConfigLimits = null;
1048
+ }
1049
+ /** Returns the process-wide singleton {@link LimitsConfigResolver}. */
1050
+ static get Instance() {
1051
+ return LimitsConfigResolver.getInstance();
1052
+ }
1053
+ /**
1054
+ * Convenience static entry point delegating to {@link LimitsConfigResolver.Instance.Resolve}.
1055
+ */
1056
+ static Resolve(input, options) {
1057
+ return LimitsConfigResolver.Instance.Resolve(input, options);
1058
+ }
1059
+ /**
1060
+ * Registers Tier 2 (`MjConfig`) limits loaded from `mj.config.cjs` by a host bootstrapper.
1061
+ * Pass `null` to clear any registered config.
1062
+ */
1063
+ RegisterMjConfigLimits(limits) {
1064
+ if (limits === null) {
1065
+ this.registeredMjConfigLimits = null;
1066
+ return;
1067
+ }
1068
+ this.registeredMjConfigLimits = NormalizeLimitsInput(limits);
1069
+ }
1070
+ /** Returns the currently registered Tier 2 (`MjConfig`) override, or `null` when unset. */
1071
+ GetMjConfigLimits() {
1072
+ return this.registeredMjConfigLimits;
1073
+ }
1074
+ /** Clears any registered Tier 2 (`MjConfig`) override (primarily for unit test isolation). */
1075
+ ClearMjConfigLimits() {
1076
+ this.registeredMjConfigLimits = null;
1077
+ }
1078
+ /**
1079
+ * Resolves all limit keys across the 5 precedence tiers (`CodeFallback` -> `MjConfig` ->
1080
+ * `AgentOrWorkflowMetadata` -> `UserAgentPolicy` -> `RunOverride`), tracking full provenance.
1081
+ */
1082
+ Resolve(input = {}, options = {}) {
1083
+ const defaults = cloneDefaultLimits();
1084
+ const mjConfigTier = input.MjConfig !== undefined ? input.MjConfig : this.registeredMjConfigLimits;
1085
+ const tiers = {
1086
+ CodeFallback: input.CodeFallback ?? null,
1087
+ MjConfig: mjConfigTier ?? null,
1088
+ AgentOrWorkflowMetadata: input.AgentOrWorkflowMetadata ?? null,
1089
+ UserAgentPolicy: input.UserAgentPolicy ?? null,
1090
+ RunOverride: input.RunOverride ?? null,
1091
+ };
1092
+ const resolvedLimits = cloneDefaultLimits();
1093
+ const provenanceEntries = [];
1094
+ const overriddenKeys = [];
1095
+ const clampedKeys = [];
1096
+ const enforceUserPolicyCeiling = options.EnforceUserPolicyAsCeiling === true;
1097
+ const enforceConfiguredCeilings = options.EnforceConfiguredCeilings === true;
1098
+ const callerCanRaiseCeilings = options.AllowAuthorizedCeilingOverride === true &&
1099
+ CanUserRaiseEnforcedLimitsCeilings(options.ContextUser, options.Provider);
1100
+ for (const key of LIMITS_KEY_PATHS) {
1101
+ const keyProvenance = resolveSingleKey(key, defaults, tiers, enforceUserPolicyCeiling, enforceConfiguredCeilings, callerCanRaiseCeilings);
1102
+ assignResolvedValue(resolvedLimits, key, keyProvenance.Value);
1103
+ provenanceEntries.push([key, keyProvenance]);
1104
+ if (keyProvenance.IsOverridden) {
1105
+ overriddenKeys.push(key);
1106
+ }
1107
+ if (keyProvenance.WasClampedByPolicyCeiling) {
1108
+ clampedKeys.push(key);
1109
+ }
1110
+ }
1111
+ return {
1112
+ Limits: resolvedLimits,
1113
+ Provenance: Object.fromEntries(provenanceEntries),
1114
+ ResolvedAtISO: options.ResolvedAtISO ?? new Date().toISOString(),
1115
+ OverriddenKeys: overriddenKeys,
1116
+ ClampedKeys: clampedKeys,
1117
+ };
1118
+ }
1119
+ /**
1120
+ * Reads a single resolved limit value from a resolution result by canonical key path.
1121
+ */
1122
+ GetLimitValue(result, key) {
1123
+ return result.Provenance[key].Value;
1124
+ }
1125
+ }
1126
+ //# sourceMappingURL=limitsConfig.js.map