@memberjunction/realtime-widget 6.3.0-edge.1 → 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.
@@ -13,6 +13,7 @@ import {
13
13
  GetGlobalObjectStore,
14
14
  IndexByUUID,
15
15
  IsMemberOverridden,
16
+ IsPlainObject,
16
17
  IsValidBase64,
17
18
  IsValidUUID,
18
19
  IsValueEncrypted,
@@ -2945,6 +2946,14 @@ var SQLDialect = class extends QueryDialect {
2945
2946
  get MaxColumnCount() {
2946
2947
  return this.DDL.MaxColumnCount;
2947
2948
  }
2949
+ /**
2950
+ * Maximum UTF-16 code units allowed in object/column comment values, or `null` when effectively
2951
+ * unbounded. SQL Server caps `sp_addextendedproperty`'s `sql_variant` `@value` at 7,500 bytes
2952
+ * (3,700 UTF-16 code units with margin); PostgreSQL `COMMENT ON` (`text`) has no practical cap.
2953
+ */
2954
+ get MaxCommentLength() {
2955
+ return this.DDL.MaxCommentLength;
2956
+ }
2948
2957
  /**
2949
2958
  * Minimum in-row byte footprint of a column of the given raw SQL type. Off-row-capable
2950
2959
  * variable-length / LOB types contribute only their in-row pointer; fixed-length types contribute
@@ -3129,18 +3138,25 @@ var SQLDialect = class extends QueryDialect {
3129
3138
  return this.DDL.BatchSeparator();
3130
3139
  }
3131
3140
  /**
3132
- * Splits an oversized SQL batch into individual statements on `;`+EOL
3141
+ * Splits a SQL script on standalone batch separator lines (e.g., `GO` on SQL Server) while
3142
+ * respecting string literals, quoted identifiers, comments, and dollar-quoted blocks per
3143
+ * {@link Lexical} so a separator word inside a description, identifier, or comment never
3144
+ * splits mid-token. On dialects with no batch separator (PostgreSQL), returns the non-empty
3145
+ * script as a single batch.
3146
+ */
3147
+ SplitBatches(sql) {
3148
+ return this.DDL.SplitBatches(sql);
3149
+ }
3150
+ /**
3151
+ * Splits an oversized SQL batch into individual statements on top-level `;`+EOL
3133
3152
  * boundaries so a caller (e.g. the RSU migration executor) can re-group
3134
3153
  * them into smaller chunks that each fit under a client request timeout.
3135
3154
  *
3136
- * Base implementation = the naive `split(/;\s*\n/g)` semantics: split on a
3137
- * `;` followed by optional inline whitespace and a newline, trim each
3138
- * fragment, drop empties, and ensure each returned statement ends with `;`.
3139
- * This is correct for SQL Server (no dollar-quoted blocks).
3140
- *
3141
- * PostgreSQL overrides this with a dollar-quote-aware split that never
3142
- * tears apart `DO $$ … $$` / `$tag$ … $tag$` blocks whose bodies
3143
- * legitimately contain `;`+newline.
3155
+ * Respects string literals (`'...'` with `''` escapes, plus PostgreSQL `E'...'` escape
3156
+ * strings and `$$…$$` / `$tag$…$tag$` dollar-quoted blocks), quoted identifiers (`"..."`,
3157
+ * `[...]`), and line/block comments per {@link Lexical} so `;`+newline inside descriptions,
3158
+ * identifiers, defaults, or procedural bodies never splits mid-statement. Each returned
3159
+ * statement ends with `;`.
3144
3160
  */
3145
3161
  SplitStatements(batch) {
3146
3162
  return this.DDL.SplitStatements(batch);
@@ -3738,8 +3754,9 @@ var AnsiQueryDialect = class extends QueryDialect {
3738
3754
 
3739
3755
  // ../../SQLDialect/dist/dialects/baseSchemaDDL.js
3740
3756
  var BaseSchemaDDL = class {
3741
- constructor(Writer) {
3757
+ constructor(Writer, Lexical = ANSI_LEXICAL) {
3742
3758
  this.Writer = Writer;
3759
+ this.Lexical = Lexical;
3743
3760
  }
3744
3761
  /** No practical declare-time cap on an index key string; a platform overrides it where one exists. */
3745
3762
  get MaxKeyStringLength() {
@@ -3753,6 +3770,19 @@ var BaseSchemaDDL = class {
3753
3770
  get MaxColumnCount() {
3754
3771
  return null;
3755
3772
  }
3773
+ /** No comment-length cap by default (override where the platform enforces one, e.g. SQL Server `sql_variant`). */
3774
+ get MaxCommentLength() {
3775
+ return null;
3776
+ }
3777
+ /**
3778
+ * Strip NUL bytes, cap to {@link MaxCommentLength} UTF-16 code units (surrogate-pair safe)
3779
+ * when the dialect declares a limit, and escape single quotes for SQL string literals.
3780
+ */
3781
+ EscapeComment(comment) {
3782
+ const withoutNulls = comment.replace(/\0/g, "");
3783
+ const capped = this.MaxCommentLength != null ? this.truncateComment(withoutNulls, this.MaxCommentLength) : withoutNulls;
3784
+ return EscapeSQLString(capped);
3785
+ }
3756
3786
  /** A conservative off-row-pointer floor of 24 bytes. */
3757
3787
  EstimateInRowBytes(_rawSqlType) {
3758
3788
  return 24;
@@ -3771,11 +3801,255 @@ var BaseSchemaDDL = class {
3771
3801
  return rawSqlType;
3772
3802
  }
3773
3803
  /**
3774
- * Splits on a `;` followed by optional inline whitespace and a newline, trims each fragment,
3775
- * drops empties, and ends each statement with `;`.
3804
+ * Splits a SQL script on standalone batch separator lines (e.g. `GO` on SQL Server) while
3805
+ * skipping strings, quoted identifiers, comments, and dollar-quoted blocks per {@link Lexical}.
3806
+ * Returns the non-empty script as a single batch when the dialect defines no batch separator.
3807
+ */
3808
+ SplitBatches(sql) {
3809
+ const separator = this.BatchSeparator().trim();
3810
+ if (separator.length === 0) {
3811
+ const trimmed = sql.trim();
3812
+ return trimmed.length > 0 ? [trimmed] : [];
3813
+ }
3814
+ return this.splitOnSeparatorLines(sql, separator);
3815
+ }
3816
+ /**
3817
+ * Splits an oversized SQL batch into individual statements on top-level `;` + end-of-line
3818
+ * boundaries, skipping string literals, quoted identifiers, line/block comments, and
3819
+ * dollar-quoted blocks per {@link Lexical}. Trims each fragment, drops empties, and ensures
3820
+ * every returned statement ends with `;`.
3776
3821
  */
3777
3822
  SplitStatements(batch) {
3778
- return batch.split(/;\s*\n/g).map((s) => s.trim()).filter((s) => s.length > 0).map((s) => s.endsWith(";") ? s : s + ";");
3823
+ const statements = [];
3824
+ let stmtStart = 0;
3825
+ let i = 0;
3826
+ while (i < batch.length) {
3827
+ const tokenEnd = this.scanProtectedTokenEnd(batch, i);
3828
+ if (tokenEnd !== null) {
3829
+ i = tokenEnd;
3830
+ continue;
3831
+ }
3832
+ if (batch[i] === ";") {
3833
+ const boundaryEnd = this.findSemicolonNewlineEnd(batch, i);
3834
+ if (boundaryEnd !== null) {
3835
+ const trimmed = batch.slice(stmtStart, i).trim();
3836
+ if (trimmed.length > 0)
3837
+ statements.push(`${trimmed};`);
3838
+ stmtStart = boundaryEnd;
3839
+ i = boundaryEnd;
3840
+ continue;
3841
+ }
3842
+ }
3843
+ i++;
3844
+ }
3845
+ const tail = batch.slice(stmtStart).trim();
3846
+ if (tail.length > 0) {
3847
+ statements.push(tail.endsWith(";") ? tail : `${tail};`);
3848
+ }
3849
+ return statements;
3850
+ }
3851
+ splitOnSeparatorLines(sql, separator) {
3852
+ const batches = [];
3853
+ let batchStart = 0;
3854
+ let i = 0;
3855
+ let atLineStart = true;
3856
+ while (i < sql.length) {
3857
+ if (atLineStart) {
3858
+ const sepEnd = this.matchBatchSeparatorLine(sql, i, separator);
3859
+ if (sepEnd !== null) {
3860
+ const trimmed = sql.slice(batchStart, i).trim();
3861
+ if (trimmed.length > 0)
3862
+ batches.push(trimmed);
3863
+ batchStart = sepEnd;
3864
+ i = sepEnd;
3865
+ atLineStart = true;
3866
+ continue;
3867
+ }
3868
+ }
3869
+ const tokenEnd = this.scanProtectedTokenEnd(sql, i);
3870
+ if (tokenEnd !== null) {
3871
+ atLineStart = sql[tokenEnd - 1] === "\n";
3872
+ i = tokenEnd;
3873
+ continue;
3874
+ }
3875
+ atLineStart = sql[i] === "\n";
3876
+ i++;
3877
+ }
3878
+ const tail = sql.slice(batchStart).trim();
3879
+ if (tail.length > 0)
3880
+ batches.push(tail);
3881
+ return batches;
3882
+ }
3883
+ scanProtectedTokenEnd(sql, i) {
3884
+ const lineCommentEnd = this.scanLineCommentEnd(sql, i);
3885
+ if (lineCommentEnd !== null)
3886
+ return lineCommentEnd;
3887
+ if (sql[i] === "/" && sql[i + 1] === "*") {
3888
+ return this.scanBlockCommentEnd(sql, i);
3889
+ }
3890
+ const quotedIdEnd = this.scanQuotedIdentifierEnd(sql, i);
3891
+ if (quotedIdEnd !== null)
3892
+ return quotedIdEnd;
3893
+ const stringEnd = this.scanStringLiteralEnd(sql, i);
3894
+ if (stringEnd !== null)
3895
+ return stringEnd;
3896
+ if (this.Lexical.DollarQuotedStrings !== "none" && sql[i] === "$") {
3897
+ return this.scanDollarQuotedEnd(sql, i);
3898
+ }
3899
+ return null;
3900
+ }
3901
+ scanLineCommentEnd(sql, start) {
3902
+ for (const form of this.Lexical.LineComments) {
3903
+ if (!sql.startsWith(form.Opener, start))
3904
+ continue;
3905
+ if (form.RequiresWhitespaceAfter) {
3906
+ const nextCode = sql.charCodeAt(start + form.Opener.length);
3907
+ if (!Number.isNaN(nextCode) && nextCode > 32 && nextCode !== 127)
3908
+ continue;
3909
+ }
3910
+ let i = start + form.Opener.length;
3911
+ while (i < sql.length && sql[i] !== "\n")
3912
+ i++;
3913
+ return i < sql.length ? i + 1 : i;
3914
+ }
3915
+ return null;
3916
+ }
3917
+ scanBlockCommentEnd(sql, start) {
3918
+ const nested = this.Lexical.BlockComments.Nested;
3919
+ let i = start + 2;
3920
+ let depth = 1;
3921
+ while (i < sql.length && depth > 0) {
3922
+ if (nested && sql[i] === "/" && sql[i + 1] === "*") {
3923
+ depth++;
3924
+ i += 2;
3925
+ } else if (sql[i] === "*" && sql[i + 1] === "/") {
3926
+ depth--;
3927
+ i += 2;
3928
+ } else {
3929
+ i++;
3930
+ }
3931
+ }
3932
+ return i;
3933
+ }
3934
+ scanQuotedIdentifierEnd(sql, start) {
3935
+ const ch = sql[start];
3936
+ for (const form of this.Lexical.IdentifierQuotes) {
3937
+ if (ch === form.Open) {
3938
+ return this.scanDelimitedSpan(sql, start, form.Close, form.DoubledCloseEscape, false);
3939
+ }
3940
+ }
3941
+ return null;
3942
+ }
3943
+ scanStringLiteralEnd(sql, quoteIndex) {
3944
+ const form = this.matchStringLiteralForm(sql, quoteIndex, sql[quoteIndex]);
3945
+ if (!form)
3946
+ return null;
3947
+ return this.scanDelimitedSpan(sql, quoteIndex, form.Quote, form.DoubledQuoteEscape, form.BackslashEscape);
3948
+ }
3949
+ matchStringLiteralForm(sql, quoteIndex, quoteChar) {
3950
+ let bestForm = null;
3951
+ let bestPrefixLen = -1;
3952
+ for (const form of this.Lexical.StringLiterals) {
3953
+ if (form.Quote !== quoteChar)
3954
+ continue;
3955
+ for (const prefix of form.Prefixes) {
3956
+ if (prefix.length > bestPrefixLen && this.hasPrefixBefore(sql, quoteIndex, prefix)) {
3957
+ bestPrefixLen = prefix.length;
3958
+ bestForm = form;
3959
+ }
3960
+ }
3961
+ }
3962
+ return bestForm;
3963
+ }
3964
+ hasPrefixBefore(sql, quoteIndex, prefix) {
3965
+ if (prefix.length === 0)
3966
+ return true;
3967
+ const start = quoteIndex - prefix.length;
3968
+ if (start < 0)
3969
+ return false;
3970
+ if (sql.slice(start, quoteIndex).toUpperCase() !== prefix.toUpperCase())
3971
+ return false;
3972
+ return start === 0 || !this.isIdentifierContinueChar(sql[start - 1]);
3973
+ }
3974
+ scanDelimitedSpan(sql, openIndex, closeChar, doubledCloseEscape, backslashEscape) {
3975
+ let i = openIndex + 1;
3976
+ while (i < sql.length) {
3977
+ if (backslashEscape && sql[i] === "\\" && i + 1 < sql.length) {
3978
+ i += 2;
3979
+ continue;
3980
+ }
3981
+ if (sql[i] === closeChar) {
3982
+ if (doubledCloseEscape && sql[i + 1] === closeChar) {
3983
+ i += 2;
3984
+ continue;
3985
+ }
3986
+ return i + 1;
3987
+ }
3988
+ i++;
3989
+ }
3990
+ return sql.length;
3991
+ }
3992
+ scanDollarQuotedEnd(sql, start) {
3993
+ if (start > 0 && this.isIdentifierContinueChar(sql[start - 1]))
3994
+ return null;
3995
+ let j = start + 1;
3996
+ if (this.Lexical.DollarQuotedStrings === "tagged" && j < sql.length && sql[j] !== "$") {
3997
+ if (!this.isTagStartChar(sql[j]))
3998
+ return null;
3999
+ j++;
4000
+ while (j < sql.length && this.isTagContinueChar(sql[j]))
4001
+ j++;
4002
+ }
4003
+ if (j >= sql.length || sql[j] !== "$")
4004
+ return null;
4005
+ const tag = sql.slice(start, j + 1);
4006
+ const closeIdx = sql.indexOf(tag, j + 1);
4007
+ return closeIdx === -1 ? sql.length : closeIdx + tag.length;
4008
+ }
4009
+ findSemicolonNewlineEnd(sql, semiIndex) {
4010
+ let j = semiIndex + 1;
4011
+ while (j < sql.length && (sql[j] === " " || sql[j] === " " || sql[j] === "\r"))
4012
+ j++;
4013
+ return j < sql.length && sql[j] === "\n" ? j + 1 : null;
4014
+ }
4015
+ matchBatchSeparatorLine(sql, lineStart, separator) {
4016
+ let j = lineStart;
4017
+ while (j < sql.length && (sql[j] === " " || sql[j] === " "))
4018
+ j++;
4019
+ if (sql.slice(j, j + separator.length).toUpperCase() !== separator.toUpperCase()) {
4020
+ return null;
4021
+ }
4022
+ j += separator.length;
4023
+ while (j < sql.length && (sql[j] === " " || sql[j] === " " || sql[j] === "\r"))
4024
+ j++;
4025
+ if (j === sql.length)
4026
+ return j;
4027
+ return sql[j] === "\n" ? j + 1 : null;
4028
+ }
4029
+ isTagStartChar(ch) {
4030
+ const code = ch.charCodeAt(0);
4031
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_" || code >= 128;
4032
+ }
4033
+ isTagContinueChar(ch) {
4034
+ return this.isTagStartChar(ch) || ch >= "0" && ch <= "9";
4035
+ }
4036
+ isIdentifierContinueChar(ch) {
4037
+ return this.isTagContinueChar(ch) || ch === "$";
4038
+ }
4039
+ truncateComment(value, maxChars) {
4040
+ if (value.length <= maxChars) {
4041
+ return value;
4042
+ }
4043
+ const ellipsis = "...";
4044
+ if (maxChars <= ellipsis.length) {
4045
+ return value.slice(0, Math.max(0, maxChars));
4046
+ }
4047
+ let cut = maxChars - ellipsis.length;
4048
+ const lastCode = value.charCodeAt(cut - 1);
4049
+ if (lastCode >= 55296 && lastCode <= 56319) {
4050
+ cut--;
4051
+ }
4052
+ return value.slice(0, cut) + ellipsis;
3779
4053
  }
3780
4054
  /** `CREATE TABLE IF NOT EXISTS <fullTable> (...);` as a single statement. */
3781
4055
  CreateTableIfAbsent(fullTable, columnsBody) {
@@ -3924,6 +4198,15 @@ SELECT @@ROWCOUNT AS ${this.Writer.QuoteColumnAlias(alias)}`;
3924
4198
  get MaxColumnCount() {
3925
4199
  return 1024;
3926
4200
  }
4201
+ /**
4202
+ * SQL Server `sp_addextendedproperty` types `@value` as `sql_variant`, which caps payloads at
4203
+ * 7,500 bytes (3,750 UTF-16 code units for `N'...'` literals; >4,000 code units also promotes
4204
+ * the literal to `nvarchar(max)`, which SQL Server refuses to implicitly convert to `sql_variant`).
4205
+ * Cap at 3,700 UTF-16 code units (7,400 bytes) to stay safely under both limits.
4206
+ */
4207
+ get MaxCommentLength() {
4208
+ return 3700;
4209
+ }
3927
4210
  /**
3928
4211
  * Minimum in-row byte footprint of a column. Off-row-capable variable-length / LOB types
3929
4212
  * (incl. `(N)VARCHAR(MAX)`) contribute only a 24-byte in-row pointer; fixed-length types
@@ -4128,7 +4411,7 @@ GO`;
4128
4411
  ALTER COLUMN [${options.columnName}] ${options.newType} ${nullable};`;
4129
4412
  }
4130
4413
  CommentOnColumn(schema, table, column, comment) {
4131
- const escaped = comment.replace(/'/g, "''");
4414
+ const escaped = this.EscapeComment(comment);
4132
4415
  return [
4133
4416
  `EXEC sp_addextendedproperty`,
4134
4417
  ` @name = N'MS_Description',`,
@@ -4168,7 +4451,7 @@ GO`;
4168
4451
  return `GRANT ${permission} ON [${schema}].[${object}] TO [${role}]`;
4169
4452
  }
4170
4453
  CommentOnObject(objectType, schema, name, comment) {
4171
- const escapedComment = comment.replace(/'/g, "''");
4454
+ const escapedComment = this.EscapeComment(comment);
4172
4455
  const level1Type = this.objectTypeToLevel1Type(objectType);
4173
4456
  return [
4174
4457
  `EXEC sp_addextendedproperty`,
@@ -4520,7 +4803,7 @@ var SQLServerDialect = class extends SQLDialect {
4520
4803
  super(...arguments);
4521
4804
  this.writer = Object.freeze(new SQLServerWriter());
4522
4805
  this.binding = Object.freeze(new SQLServerBinding());
4523
- this.ddl = Object.freeze(new SQLServerSchemaDDL(this.writer));
4806
+ this.ddl = Object.freeze(new SQLServerSchemaDDL(this.writer, SQL_SERVER_LEXICAL));
4524
4807
  }
4525
4808
  get PlatformKey() {
4526
4809
  return "sqlserver";
@@ -4775,59 +5058,6 @@ SELECT COUNT(*)::int AS ${this.Writer.QuoteColumnAlias(alias)} FROM ${this.Write
4775
5058
  RollbackToSavepointSQL(name) {
4776
5059
  return `ROLLBACK TO SAVEPOINT ${name}`;
4777
5060
  }
4778
- /**
4779
- * Splits an oversized SQL batch into individual statements on `;`+EOL
4780
- * boundaries — but NEVER inside a PostgreSQL dollar-quoted block
4781
- * (`$$ … $$` or `$tag$ … $tag$`), whose body legitimately contains
4782
- * `;`+newline (DO blocks, PL/pgSQL function bodies, the integration
4783
- * view-drop guard `$mj_dropviews$`). A naive `split(/;\s*\n/g)` tears
4784
- * those apart. Outside dollar blocks the boundary semantics mirror the
4785
- * base `split(/;\s*\n/g)` (a `;` then optional inline whitespace then a
4786
- * newline). Each returned statement ends with `;`.
4787
- */
4788
- SplitStatements(batch) {
4789
- const statements = [];
4790
- let current = "";
4791
- let dollarTag = null;
4792
- const isTagChar = (c) => c >= "A" && c <= "Z" || c >= "a" && c <= "z" || c >= "0" && c <= "9" || c === "_";
4793
- for (let i = 0; i < batch.length; i++) {
4794
- const ch = batch[i];
4795
- if (ch === "$") {
4796
- let j = i + 1;
4797
- while (j < batch.length && isTagChar(batch[j]))
4798
- j++;
4799
- if (batch[j] === "$") {
4800
- const tag = batch.slice(i, j + 1);
4801
- if (dollarTag === null)
4802
- dollarTag = tag;
4803
- else if (dollarTag === tag)
4804
- dollarTag = null;
4805
- current += tag;
4806
- i = j;
4807
- continue;
4808
- }
4809
- }
4810
- if (ch === ";" && dollarTag === null) {
4811
- let j = i + 1;
4812
- while (j < batch.length && (batch[j] === " " || batch[j] === " " || batch[j] === "\r"))
4813
- j++;
4814
- if (j < batch.length && batch[j] === "\n") {
4815
- current += ";";
4816
- const trimmed = current.trim();
4817
- if (trimmed.length > 0)
4818
- statements.push(trimmed);
4819
- current = "";
4820
- i = j;
4821
- continue;
4822
- }
4823
- }
4824
- current += ch;
4825
- }
4826
- const tail = current.trim();
4827
- if (tail.length > 0)
4828
- statements.push(tail);
4829
- return statements.map((s) => s.endsWith(";") ? s : s + ";");
4830
- }
4831
5061
  ExistenceCheckSQL(objectType, schema, name) {
4832
5062
  const normalizedType = objectType.toUpperCase();
4833
5063
  switch (normalizedType) {
@@ -4926,8 +5156,8 @@ SELECT COUNT(*)::int AS ${this.Writer.QuoteColumnAlias(alias)} FROM ${this.Write
4926
5156
  ALTER COLUMN ${col} ${options.newNullable ? "DROP NOT NULL" : "SET NOT NULL"};`;
4927
5157
  }
4928
5158
  CommentOnColumn(schema, table, column, comment) {
4929
- const escaped = comment.replace(/'/g, "''");
4930
- return `COMMENT ON COLUMN "${schema}"."${table}"."${column}" IS '${escaped}';`;
5159
+ const escaped = this.EscapeComment(comment);
5160
+ return `COMMENT ON COLUMN ${this.Writer.QuoteSchema(schema, table)}.${this.Writer.QuoteIdentifier(column)} IS '${escaped}';`;
4931
5161
  }
4932
5162
  FallbackType() {
4933
5163
  return "TEXT";
@@ -4965,9 +5195,9 @@ SELECT COUNT(*)::int AS ${this.Writer.QuoteColumnAlias(alias)} FROM ${this.Write
4965
5195
  return `GRANT ${permission} ON ${schema}."${object}" TO "${role}"`;
4966
5196
  }
4967
5197
  CommentOnObject(objectType, schema, name, comment) {
4968
- const escapedComment = comment.replace(/'/g, "''");
5198
+ const escapedComment = this.EscapeComment(comment);
4969
5199
  const normalizedType = objectType.toUpperCase();
4970
- return `COMMENT ON ${normalizedType} ${schema}."${name}" IS '${escapedComment}'`;
5200
+ return `COMMENT ON ${normalizedType} ${this.Writer.QuoteSchema(schema, name)} IS '${escapedComment}'`;
4971
5201
  }
4972
5202
  SchemaIntrospectionQueries() {
4973
5203
  return {
@@ -5277,7 +5507,7 @@ var PostgreSQLDialect = class extends SQLDialect {
5277
5507
  super(...arguments);
5278
5508
  this.writer = Object.freeze(new PostgreSQLWriter());
5279
5509
  this.binding = Object.freeze(new PostgreSQLBinding());
5280
- this.ddl = Object.freeze(new PostgreSQLSchemaDDL(this.writer));
5510
+ this.ddl = Object.freeze(new PostgreSQLSchemaDDL(this.writer, POSTGRESQL_LEXICAL));
5281
5511
  }
5282
5512
  get PlatformKey() {
5283
5513
  return "postgresql";
@@ -7091,14 +7321,15 @@ var RowLevelSecurityFilterInfo = class _RowLevelSecurityFilterInfo extends BaseI
7091
7321
  * @returns {string} The filter text with all user tokens replaced with actual values
7092
7322
  */
7093
7323
  MarkupFilterText(user, options) {
7094
- const ret = this.substituteTokens(this.FilterText, user);
7324
+ const rawFilterText = options?.platform ? this.GetPlatformFilterText(options.platform) : this.FilterText;
7325
+ const ret = this.substituteTokens(rawFilterText, user);
7095
7326
  const unresolvedMatch = ret.match(/\{\{(?:User|Acting)\w+\}\}/);
7096
7327
  if (unresolvedMatch) {
7097
7328
  if (options?.unresolvedBehavior === "match-nothing") {
7098
- LogError("Row filter has unresolved token after markup \u2014 resolving filter to (1=0): " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7329
+ LogError("Row filter has unresolved token after markup \u2014 resolving filter to (1=0): " + unresolvedMatch[0] + " in filter: " + rawFilterText);
7099
7330
  return "(1=0)";
7100
7331
  }
7101
- LogError("RLS filter has unresolved token after markup: " + unresolvedMatch[0] + " in filter: " + this.FilterText);
7332
+ LogError("RLS filter has unresolved token after markup: " + unresolvedMatch[0] + " in filter: " + rawFilterText);
7102
7333
  }
7103
7334
  return ret;
7104
7335
  }
@@ -7120,7 +7351,8 @@ var RowLevelSecurityFilterInfo = class _RowLevelSecurityFilterInfo extends BaseI
7120
7351
  if (!user || literal === "(1=0)" && options?.unresolvedBehavior === "match-nothing") {
7121
7352
  return literal;
7122
7353
  }
7123
- return this.substituteTokens(this.bindWholeLiteralTokens(this.FilterText, user, binder), user);
7354
+ const rawFilterText = options?.platform ? this.GetPlatformFilterText(options.platform) : this.FilterText;
7355
+ return this.substituteTokens(this.bindWholeLiteralTokens(rawFilterText, user, binder), user);
7124
7356
  }
7125
7357
  /** Substitutes every token the user resolves as escaped literal text; unresolved tokens are left in place. */
7126
7358
  substituteTokens(text, user) {
@@ -13794,27 +14026,41 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13794
14026
  * @param returnPrefix
13795
14027
  * @returns
13796
14028
  */
13797
- GetUserRowLevelSecurityWhereClause(user, type, returnPrefix) {
14029
+ GetUserRowLevelSecurityWhereClause(user, type, returnPrefix, platform) {
13798
14030
  if (this.UserExemptFromRowLevelSecurity(user, type)) {
13799
14031
  return "";
13800
14032
  }
13801
- const sRLSSQL = this.roleRowFilterClause(user, type, null);
14033
+ const sRLSSQL = this.roleRowFilterClause(user, type, null, platform);
13802
14034
  if (sRLSSQL.length === 0) {
13803
14035
  return "";
13804
14036
  }
13805
14037
  return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sRLSSQL}`;
13806
14038
  }
14039
+ /**
14040
+ * Resolves the database platform for RLS filter variant selection: uses an explicit
14041
+ * caller-supplied platform when provided, otherwise reads `PlatformKey` from the
14042
+ * entity's owning metadata provider when available.
14043
+ */
14044
+ resolveRLSPlatform(explicitPlatform) {
14045
+ if (explicitPlatform) {
14046
+ return explicitPlatform;
14047
+ }
14048
+ const provider = MetadataProviderFor(this);
14049
+ return provider?.PlatformKey;
14050
+ }
13807
14051
  /**
13808
14052
  * The role layer of the row filter, '' when no role filter applies. Callers check the
13809
14053
  * role-RLS exemption first. With a `binder`, user values bind as parameters
13810
14054
  * ({@link RowLevelSecurityFilterInfo.MarkupFilterParameterized}).
13811
14055
  */
13812
- roleRowFilterClause(user, type, binder) {
14056
+ roleRowFilterClause(user, type, binder, platform) {
13813
14057
  const userRLS = this.GetUserRowLevelSecurityInfo(user, type);
13814
14058
  if (!userRLS || userRLS.length === 0) {
13815
14059
  return "";
13816
14060
  }
13817
- const terms = userRLS.map((rls) => `(${binder ? rls.MarkupFilterParameterized(user, binder) : rls.MarkupFilterText(user)})`);
14061
+ const resolvedPlatform = this.resolveRLSPlatform(platform);
14062
+ const options = resolvedPlatform ? { platform: resolvedPlatform } : void 0;
14063
+ const terms = userRLS.map((rls) => `(${binder ? rls.MarkupFilterParameterized(user, binder, options) : rls.MarkupFilterText(user, options)})`);
13818
14064
  return terms.length > 1 ? `(${terms.join(" OR ")})` : terms[0];
13819
14065
  }
13820
14066
  /**
@@ -13844,21 +14090,21 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13844
14090
  * must call this without a binder: the literal clause is what keeps two users from sharing
13845
14091
  * a cached result.
13846
14092
  */
13847
- GetEffectiveRowFilterWhereClause(user, type, returnPrefix, binder) {
13848
- const sql = this.effectiveRowFilterClause(user, type, binder ?? null);
14093
+ GetEffectiveRowFilterWhereClause(user, type, returnPrefix, binder, platform) {
14094
+ const sql = this.effectiveRowFilterClause(user, type, binder ?? null, platform);
13849
14095
  if (sql.length === 0) {
13850
14096
  return "";
13851
14097
  }
13852
14098
  return `${returnPrefix && returnPrefix.length > 0 ? returnPrefix + " " : ""}${sql}`;
13853
14099
  }
13854
14100
  /** The composed row-filter clause without a prefix; literal when `binder` is null. */
13855
- effectiveRowFilterClause(user, type, binder) {
14101
+ effectiveRowFilterClause(user, type, binder, platform) {
13856
14102
  const layers = [];
13857
- const roleClause = binder === null ? this.GetUserRowLevelSecurityWhereClause(user, type, "") : this.UserExemptFromRowLevelSecurity(user, type) ? "" : this.roleRowFilterClause(user, type, binder);
14103
+ const roleClause = binder === null ? this.GetUserRowLevelSecurityWhereClause(user, type, "", platform) : this.UserExemptFromRowLevelSecurity(user, type) ? "" : this.roleRowFilterClause(user, type, binder, platform);
13858
14104
  if (roleClause && roleClause.length > 0) {
13859
14105
  layers.push(`(${roleClause})`);
13860
14106
  }
13861
- const keyClause = this.getAPIKeyRowFilterClause(user, type, binder);
14107
+ const keyClause = this.getAPIKeyRowFilterClause(user, type, binder, platform);
13862
14108
  if (keyClause && keyClause.length > 0) {
13863
14109
  layers.push(`(${keyClause})`);
13864
14110
  }
@@ -13872,7 +14118,7 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13872
14118
  * or unloaded) contributes `(1=0)`, and unresolved tokens inside a filter collapse it
13873
14119
  * to `(1=0)` via the match-nothing markup mode.
13874
14120
  */
13875
- getAPIKeyRowFilterClause(user, type, binder) {
14121
+ getAPIKeyRowFilterClause(user, type, binder, platform) {
13876
14122
  const bindings = user?.APIKeyRowFilters;
13877
14123
  if (!bindings || bindings.length === 0) {
13878
14124
  return "";
@@ -13881,13 +14127,17 @@ var EntityInfo = class _EntityInfo extends BaseInfo {
13881
14127
  if (mine.length === 0) {
13882
14128
  return "";
13883
14129
  }
14130
+ const resolvedPlatform = this.resolveRLSPlatform(platform);
13884
14131
  const clauses = [...mine].sort((a, b) => a.FilterID.localeCompare(b.FilterID)).map((b) => {
13885
14132
  const filter2 = MetadataProviderFor(this)?.RowLevelSecurityFilters?.find((f) => UUIDsEqual(f.ID, b.FilterID));
13886
14133
  if (!filter2) {
13887
14134
  LogError(`API-key row filter ${b.FilterID} for entity ${this.Name} not found in metadata \u2014 resolving to (1=0)`);
13888
14135
  return "(1=0)";
13889
14136
  }
13890
- const options = { unresolvedBehavior: "match-nothing" };
14137
+ const options = {
14138
+ unresolvedBehavior: "match-nothing",
14139
+ ...resolvedPlatform ? { platform: resolvedPlatform } : {}
14140
+ };
13891
14141
  return `(${binder ? filter2.MarkupFilterParameterized(user, binder, options) : filter2.MarkupFilterText(user, options)})`;
13892
14142
  });
13893
14143
  return clauses.join(" AND ");
@@ -16741,6 +16991,7 @@ var ClientInputTransportKeys = [
16741
16991
  ReadableFieldsTransportKey,
16742
16992
  "RestoreContext___",
16743
16993
  "CloneContext___",
16994
+ "SyncContext___",
16744
16995
  // The companion payload key, spelled out rather than imported: the module that defines it
16745
16996
  // imports BaseEntity, which imports this module, and this array is built at load time.
16746
16997
  "Companions___",
@@ -19800,6 +20051,19 @@ EntityField = EntityField_1 = __decorate4([
19800
20051
  function SerializeCloneChangeContext(context) {
19801
20052
  return JSON.stringify({ Version: 1, Kind: "Clone", Clone: context });
19802
20053
  }
20054
+ function SerializeSyncChangeContext(context) {
20055
+ return JSON.stringify({
20056
+ Version: 1,
20057
+ Kind: "Sync",
20058
+ Sync: {
20059
+ OriginDeploymentID: context.OriginDeploymentID,
20060
+ PairingID: context.PairingID,
20061
+ RunID: context.RunID,
20062
+ OriginChangeIDs: [...context.OriginChangeIDs],
20063
+ ...context.OriginUserEmail ? { OriginUserEmail: context.OriginUserEmail } : {}
20064
+ }
20065
+ });
20066
+ }
19803
20067
  var DataObjectParams = class {
19804
20068
  constructor(oldValues = false, omitNullValues = false, omitEmptyStrings = false, excludeFields = [], includeRelatedEntityData = false, relatedEntityList = []) {
19805
20069
  this.oldValues = oldValues;
@@ -19992,6 +20256,7 @@ var BaseEntity = class _BaseEntity {
19992
20256
  this._compositeKey = null;
19993
20257
  this._restoreContext = null;
19994
20258
  this._cloneContext = null;
20259
+ this._syncContext = null;
19995
20260
  this._pendingSave$ = null;
19996
20261
  this._isValidating = false;
19997
20262
  this._inSaveValidation = false;
@@ -23632,6 +23897,37 @@ var BaseEntity = class _BaseEntity {
23632
23897
  ClearCloneContext() {
23633
23898
  this._cloneContext = null;
23634
23899
  }
23900
+ /**
23901
+ * Returns the active sync context for the next save or delete, if any.
23902
+ *
23903
+ * Read by the data provider when generating the RecordChange SQL: when
23904
+ * non-null, the resulting RecordChange row is written with
23905
+ * `Source='Sync'`, `IntegrationID` (when provided), and `ChangeContext`
23906
+ * populated with structured JSON provenance. Returns null for ordinary saves.
23907
+ */
23908
+ get SyncContext() {
23909
+ return this._syncContext;
23910
+ }
23911
+ /**
23912
+ * Marks the next Save() or Delete() as part of an MJ Peer Sync operation.
23913
+ *
23914
+ * The provider will write a new RecordChange entry with `Source='Sync'`
23915
+ * and `ChangeContext` populated with structured JSON provenance.
23916
+ *
23917
+ * @param context Structured sync context. Throws if missing required fields.
23918
+ */
23919
+ SetSyncContext(context) {
23920
+ if (!context || !context.OriginDeploymentID || !context.PairingID || !context.RunID || !Array.isArray(context.OriginChangeIDs)) {
23921
+ throw new Error("BaseEntity.SetSyncContext: context is required with OriginDeploymentID, PairingID, RunID, and OriginChangeIDs");
23922
+ }
23923
+ this._syncContext = context;
23924
+ }
23925
+ /**
23926
+ * Clears any pending sync context. Safe to call when no context is set.
23927
+ */
23928
+ ClearSyncContext() {
23929
+ this._syncContext = null;
23930
+ }
23635
23931
  /**
23636
23932
  * Saves the current state of the object to the database. Uses the active provider to handle the actual saving of the record.
23637
23933
  * If the record is new, it will be created, if it already exists, it will be updated.
@@ -33067,6 +33363,7 @@ var ProviderBase = class _ProviderBase {
33067
33363
  this._peerMetadataNoticeFirstAt = null;
33068
33364
  this._peerMetadataNoticeRetries = 0;
33069
33365
  this._peerMetadataNoticeTimer = null;
33366
+ this._metadataRefreshStampsFresh = false;
33070
33367
  this._metadataWriteEventPending = false;
33071
33368
  this._metadataFullReloadRequested = false;
33072
33369
  this._metadataMemberRefreshWaits = 0;
@@ -33708,6 +34005,17 @@ var ProviderBase = class _ProviderBase {
33708
34005
  IsMetadataChangeNotice(event) {
33709
34006
  return (event.Action === "set" || event.Action === "removed") && (event.Category || CacheCategory.Default) === CacheCategory.Default && event.CacheKey === this.LocalStoragePrefix + _ProviderBase.localStorageTimestampsKey;
33710
34007
  }
34008
+ /**
34009
+ * True while a peer metadata notice check must wait rather than run immediately.
34010
+ * Defaults to {@link MetadataMemberRefreshMustWait} for providers whose metadata reads
34011
+ * cannot bypass an open transaction. Database providers whose `MJ_Metadata` reads run on
34012
+ * the connection pool regardless of unrelated ambient transactions (#4514) override this
34013
+ * to `false` unless {@link MetadataReadsJoinTransaction} is set, so unrelated background
34014
+ * writes on the global provider (such as scheduled jobs) do not defer peer metadata sync.
34015
+ */
34016
+ get PeerMetadataNoticeMustWait() {
34017
+ return this.MetadataMemberRefreshMustWait;
34018
+ }
33711
34019
  /**
33712
34020
  * Reacts to another server saving its metadata snapshot: after a short debounce, runs the
33713
34021
  * normal staleness check ({@link RefreshIfNeeded}, bypassing the check throttle). The check
@@ -33716,6 +34024,11 @@ var ProviderBase = class _ProviderBase {
33716
34024
  * poll. A server that is already current does no refresh and saves nothing, so notices do not
33717
34025
  * echo around the fleet.
33718
34026
  *
34027
+ * Random thundering-herd jitter ({@link PeerMetadataNoticeJitterMs}) applies only to `removed`
34028
+ * notices (e.g. `mj migrate` clearing the shared snapshot so every server would otherwise query
34029
+ * the database together). On a `set` notice the peer's updated snapshot is already in shared
34030
+ * storage, so only {@link MetadataDatasetRefreshDebounceMs} is waited.
34031
+ *
33719
34032
  * @returns true when the event was a metadata notice (and a check was scheduled)
33720
34033
  */
33721
34034
  HandlePeerMetadataNotice(event) {
@@ -33730,14 +34043,15 @@ var ProviderBase = class _ProviderBase {
33730
34043
  if (this._peerMetadataNoticeTimer) {
33731
34044
  clearTimeout(this._peerMetadataNoticeTimer);
33732
34045
  }
34046
+ const jitterMs = event.Action === "removed" ? Math.floor(Math.random() * _ProviderBase.PeerMetadataNoticeJitterMs) : 0;
33733
34047
  const timer = setTimeout(() => {
33734
34048
  this._peerMetadataNoticeTimer = null;
33735
- if (this.MetadataMemberRefreshMustWait) {
34049
+ if (this.PeerMetadataNoticeMustWait) {
33736
34050
  this.handlePeerMetadataNoticeRetry();
33737
34051
  return;
33738
34052
  }
33739
34053
  this.runPeerMetadataCheck();
33740
- }, _ProviderBase.MetadataDatasetRefreshDebounceMs + Math.floor(Math.random() * _ProviderBase.PeerMetadataNoticeJitterMs));
34054
+ }, _ProviderBase.MetadataDatasetRefreshDebounceMs + jitterMs);
33741
34055
  if (typeof timer === "object" && timer !== null && "unref" in timer) {
33742
34056
  timer.unref();
33743
34057
  }
@@ -33776,7 +34090,7 @@ var ProviderBase = class _ProviderBase {
33776
34090
  }
33777
34091
  const timer = setTimeout(() => {
33778
34092
  this._peerMetadataNoticeTimer = null;
33779
- if (this.MetadataMemberRefreshMustWait) {
34093
+ if (this.PeerMetadataNoticeMustWait) {
33780
34094
  this.handlePeerMetadataNoticeRetry();
33781
34095
  return;
33782
34096
  }
@@ -33851,7 +34165,12 @@ var ProviderBase = class _ProviderBase {
33851
34165
  return this.ReloadMetadata(true, void 0, true, true);
33852
34166
  }
33853
34167
  LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
33854
- return this.Refresh();
34168
+ this._metadataRefreshStampsFresh = true;
34169
+ try {
34170
+ return await this.Refresh();
34171
+ } finally {
34172
+ this._metadataRefreshStampsFresh = false;
34173
+ }
33855
34174
  }
33856
34175
  /**
33857
34176
  * The write-event rule: a refresh prompted by a member-entity write knows something changed, so
@@ -33947,6 +34266,20 @@ var ProviderBase = class _ProviderBase {
33947
34266
  get TrustLocalCacheCompletely() {
33948
34267
  return false;
33949
34268
  }
34269
+ /**
34270
+ * Whether {@link CheckToSeeIfRefreshNeeded} may inspect remote timestamps and adopt a newer
34271
+ * snapshot from shared storage. Defaults to {@link AllowRefresh}.
34272
+ *
34273
+ * Providers that transiently suspend {@link AllowRefresh} while a save is running SQL
34274
+ * (such as `SQLServerDataProvider`) can override this to `true`: metadata status queries run
34275
+ * on the connection pool (`ignoreAmbientTransaction`), and adopting a peer's snapshot from
34276
+ * shared storage atomically replaces `_localMetadata` without mutating any `EntityInfo` held
34277
+ * by an in-flight save. Suspending checks on in-flight saves caused peer metadata notices
34278
+ * arriving during background writes (e.g. scheduled jobs) to be silently dropped.
34279
+ */
34280
+ get AllowRefreshCheck() {
34281
+ return this.AllowRefresh;
34282
+ }
33950
34283
  /**
33951
34284
  * Returns a record's name for synchronous display code, or `undefined` when it is not at hand.
33952
34285
  *
@@ -34109,6 +34442,9 @@ var ProviderBase = class _ProviderBase {
34109
34442
  return this.enqueueCoalescedRunViews(params, contextUser);
34110
34443
  }
34111
34444
  const key = this.generateDedupKey(params, contextUser);
34445
+ if (key === null) {
34446
+ return this.executeRunViewsPipeline(params, contextUser);
34447
+ }
34112
34448
  const existing = this._inflightViews.get(key);
34113
34449
  if (existing?.resolvedResults && existing.resolvedAt) {
34114
34450
  const age = Date.now() - existing.resolvedAt;
@@ -34328,6 +34664,11 @@ var ProviderBase = class _ProviderBase {
34328
34664
  const entryIndices = [];
34329
34665
  for (const param of entry.params) {
34330
34666
  const key = this.generateDedupKey([param], contextUser);
34667
+ if (key === null) {
34668
+ entryIndices.push(uniqueParams.length);
34669
+ uniqueParams.push(param);
34670
+ continue;
34671
+ }
34331
34672
  let idx = uniqueKeys.get(key);
34332
34673
  if (idx === void 0) {
34333
34674
  idx = uniqueParams.length;
@@ -34471,6 +34812,9 @@ var ProviderBase = class _ProviderBase {
34471
34812
  }
34472
34813
  async runViewsUncoalesced(params, contextUser) {
34473
34814
  const key = this.generateDedupKey(params, contextUser);
34815
+ if (key === null) {
34816
+ return this.executeRunViewsPipeline(params, contextUser);
34817
+ }
34474
34818
  const existing = this._inflightViews.get(key);
34475
34819
  if (existing?.resolvedResults && existing.resolvedAt) {
34476
34820
  const age = Date.now() - existing.resolvedAt;
@@ -34686,7 +35030,20 @@ var ProviderBase = class _ProviderBase {
34686
35030
  }
34687
35031
  return result;
34688
35032
  }
35033
+ static {
35034
+ this.UUID_VALUE_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35035
+ }
35036
+ static normalizeDedupScalarString(value) {
35037
+ const trimmed = value.trim();
35038
+ return _ProviderBase.UUID_VALUE_REGEX.test(trimmed) ? NormalizeUUID(trimmed) : trimmed;
35039
+ }
34689
35040
  generateDedupKey(params, contextUser) {
35041
+ const effectiveUser = contextUser ?? this.CurrentUser;
35042
+ const contextScope = this.ComputeRunViewDedupContextScope(effectiveUser);
35043
+ if (contextScope === null) {
35044
+ return null;
35045
+ }
35046
+ const userIdSegment = contextUser?.ID ? NormalizeUUID(contextUser.ID) : "";
34690
35047
  const parts = params.map((p) => {
34691
35048
  const base = LocalCacheManager.Instance.GenerateRunViewFingerprint(p, this.InstanceConnectionString);
34692
35049
  const extras = [
@@ -34697,11 +35054,81 @@ var ProviderBase = class _ProviderBase {
34697
35054
  p.ViewName ?? "",
34698
35055
  IsExplicitBaseViewOverride(p) ? "abv_override:base" : "",
34699
35056
  p.TimeZone ?? "",
34700
- contextUser?.ID ?? ""
35057
+ userIdSegment
34701
35058
  ].join("|");
34702
35059
  return `${base}|${extras}`;
34703
35060
  });
34704
- return `${parts.join("||")}|||${this.RunViewDedupScope}`;
35061
+ const baseScope = this.RunViewDedupScope;
35062
+ const combinedScope = contextScope ? baseScope ? `${baseScope}|${contextScope}` : contextScope : baseScope;
35063
+ return `${parts.join("||")}|||${combinedScope}`;
35064
+ }
35065
+ /**
35066
+ * Per-call security and tenant scope appended to the RunView dedup key alongside
35067
+ * {@link RunViewDedupScope}. Because request deduplication and the linger window run
35068
+ * before `PreRunView` hooks (which inject tenant filters from `contextUser.TenantContext`)
35069
+ * and before RLS evaluation, two callers sharing the same `contextUser.ID` under different
35070
+ * tenant, magic-link, widget-guest, or API-key scopes must never share an in-flight or
35071
+ * lingering dedup slot.
35072
+ *
35073
+ * Returns `''` when the user carries no per-request isolation context, keeping unscoped
35074
+ * dedup keys unchanged. Returns `null` to bypass deduplication for the call when an
35075
+ * unknown / non-primitive `TenantContext` field shape (e.g. a nested object or array of
35076
+ * objects) is present so isolation is never silently weakened. Subclasses may override
35077
+ * this (calling `super`) to fold in additional per-call scope such as async-local tenant state.
35078
+ */
35079
+ ComputeRunViewDedupContextScope(contextUser) {
35080
+ if (!contextUser)
35081
+ return "";
35082
+ const segments = [];
35083
+ if (contextUser.TenantContext) {
35084
+ const scalarEntries = [];
35085
+ for (const [key, value] of Object.entries(contextUser.TenantContext)) {
35086
+ if (value === void 0 || value === null) {
35087
+ continue;
35088
+ }
35089
+ if (typeof value === "string") {
35090
+ scalarEntries.push(`${key}=${_ProviderBase.normalizeDedupScalarString(value)}`);
35091
+ } else if (typeof value === "number" || typeof value === "boolean") {
35092
+ scalarEntries.push(`${key}=${String(value)}`);
35093
+ } else if (Array.isArray(value) && value.every((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean")) {
35094
+ const serialized = value.map((v) => typeof v === "string" ? _ProviderBase.normalizeDedupScalarString(v) : String(v)).sort().join(",");
35095
+ scalarEntries.push(`${key}=[${serialized}]`);
35096
+ } else {
35097
+ return null;
35098
+ }
35099
+ }
35100
+ scalarEntries.sort();
35101
+ segments.push(`tc:${scalarEntries.join(",")}`);
35102
+ }
35103
+ if (contextUser.MagicLinkScope) {
35104
+ const rt = (contextUser.MagicLinkScope.ResourceType ?? "").trim().toLowerCase();
35105
+ const rid = contextUser.MagicLinkScope.ResourceID ? NormalizeUUID(contextUser.MagicLinkScope.ResourceID) : "";
35106
+ segments.push(`ml:${rt}:${rid}`);
35107
+ }
35108
+ if (contextUser.APIKeyActingContext) {
35109
+ const ak = contextUser.APIKeyActingContext;
35110
+ const orgId = ak.ActingOrganizationID ? NormalizeUUID(ak.ActingOrganizationID) : "";
35111
+ const personId = ak.ActingPersonID ? NormalizeUUID(ak.ActingPersonID) : "";
35112
+ const scopeId = (ak.ActingScopeID ?? "").trim().toLowerCase();
35113
+ const companies = (ak.ActingCompanyIDs ?? []).map((id) => NormalizeUUID(id)).sort().join(",");
35114
+ segments.push(`ak:${orgId}:${personId}:${scopeId}:${companies}`);
35115
+ }
35116
+ if (contextUser.APIKeyRowFilters && contextUser.APIKeyRowFilters.length > 0) {
35117
+ const filters = contextUser.APIKeyRowFilters.map((f) => `${NormalizeUUID(f.EntityID)}:${f.PermissionType}:${NormalizeUUID(f.FilterID)}`).sort().join(",");
35118
+ segments.push(`akf:${filters}`);
35119
+ }
35120
+ if (contextUser.WidgetGuestContext) {
35121
+ const widgetId = contextUser.WidgetGuestContext.WidgetID ? NormalizeUUID(contextUser.WidgetGuestContext.WidgetID) : "";
35122
+ segments.push(`wg:${widgetId}`);
35123
+ }
35124
+ if (contextUser.AnonymousVisitorID) {
35125
+ segments.push(`av:${contextUser.AnonymousVisitorID.trim().toLowerCase()}`);
35126
+ }
35127
+ if (contextUser.IsMagicLinkAnonymous) {
35128
+ const roles = (contextUser.UserRoles ?? []).map((r) => r.RoleID ? NormalizeUUID(r.RoleID) : "").filter(Boolean).sort().join(",");
35129
+ segments.push(`mla:1:${roles}`);
35130
+ }
35131
+ return segments.join("|");
34705
35132
  }
34706
35133
  /**
34707
35134
  * What, besides the request itself and the user, decides whether two identical RunViews may
@@ -37271,10 +37698,12 @@ var ProviderBase = class _ProviderBase {
37271
37698
  await this._metadataReloadInFlight;
37272
37699
  return true;
37273
37700
  }
37701
+ const initialStampsFresh = stampsFresh || this._metadataRefreshStampsFresh;
37702
+ this._metadataRefreshStampsFresh = false;
37274
37703
  this._metadataReloadInFlight = (async () => {
37275
37704
  let effectiveHardRefresh = hardRefresh;
37276
37705
  let tryScoped = scopedFirst;
37277
- let timestampsFresh = stampsFresh;
37706
+ let timestampsFresh = initialStampsFresh;
37278
37707
  do {
37279
37708
  this._metadataReloadQueued = false;
37280
37709
  let timestampsRead = true;
@@ -38323,7 +38752,7 @@ var ProviderBase = class _ProviderBase {
38323
38752
  * {@link preValidateAndRefresh}) already caught it; {@link Config} did not.
38324
38753
  */
38325
38754
  async CheckToSeeIfRefreshNeeded(providerToUse, bypassMinCheckInterval) {
38326
- if (!this.AllowRefresh)
38755
+ if (!this.AllowRefreshCheck)
38327
38756
  return false;
38328
38757
  if (!bypassMinCheckInterval && this._refreshCheckInFlight) {
38329
38758
  LogStatusEx({ message: `[RefreshCheck] Skipped \u2014 a check is already in flight; its caller acts on the answer`, verboseOnly: true });
@@ -41250,7 +41679,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
41250
41679
  async OnSaveCompleted(entity, saveSQLResult, user, options, _context) {
41251
41680
  const overlappingChangeData = saveSQLResult.extraData?.overlappingChangeData;
41252
41681
  if (overlappingChangeData && entity.EntityInfo.AllowMultipleSubtypes && entity.EntityInfo.TrackRecordChanges) {
41253
- await this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? "", options.ISAActiveChildEntityName, void 0, entity.CloneContext ? "Clone" : "Internal", entity.CloneContext ? SerializeCloneChangeContext(entity.CloneContext) : null);
41682
+ await this.PropagateRecordChangesToSiblings(entity.EntityInfo, overlappingChangeData, entity.PrimaryKey.Values(), user?.ID ?? "", options.ISAActiveChildEntityName, void 0, entity.CloneContext ? "Clone" : entity.SyncContext ? "Sync" : "Internal", entity.CloneContext ? SerializeCloneChangeContext(entity.CloneContext) : entity.SyncContext ? SerializeSyncChangeContext(entity.SyncContext) : null, entity.SyncContext?.IntegrationID ?? null);
41254
41683
  }
41255
41684
  return null;
41256
41685
  }
@@ -42376,8 +42805,8 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42376
42805
  * @param type The change type
42377
42806
  * @param user The acting user
42378
42807
  */
42379
- async LogRecordChange(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext) {
42380
- const sqlResult = this.BuildRecordChangeSQL(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext);
42808
+ async LogRecordChange(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext, syncContext) {
42809
+ const sqlResult = this.BuildRecordChangeSQL(newData, oldData, entityName, recordID, entityInfo, type, user, restoreContext, cloneContext, syncContext);
42381
42810
  if (sqlResult) {
42382
42811
  return await this.ExecuteSQL(sqlResult.sql, sqlResult.parameters ?? void 0, void 0, user);
42383
42812
  }
@@ -42397,7 +42826,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42397
42826
  }
42398
42827
  /**
42399
42828
  * Builds the dialect-agnostic payload for a RecordChange row from the
42400
- * entity's old/new data and an optional restore or clone context. Concrete
42829
+ * entity's old/new data and an optional restore, clone, or sync context. Concrete
42401
42830
  * providers consume the returned payload to render their dialect-specific
42402
42831
  * SQL (SQL Server EXEC, PostgreSQL INSERT, etc.).
42403
42832
  *
@@ -42426,10 +42855,13 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42426
42855
  * @param skipFullRecordJSON When true (because the dialect builds `FullRecordJSON` in SQL
42427
42856
  * from the returned row), skips `EscapeQuotesInProperties` and `JSON.stringify` for
42428
42857
  * `fullRecordJSON`, returning `''`.
42858
+ * @param syncContext When non-null, populates `source='Sync'`, `integrationID`,
42859
+ * and the structured `changeContext` JSON payload.
42429
42860
  */
42430
- BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false) {
42431
- if (restoreContext && cloneContext) {
42432
- throw new Error("BuildRecordChangePayload: both restoreContext and cloneContext were provided; an operation cannot be both a restore and a clone");
42861
+ BuildRecordChangePayload(newData, oldData, recordID, entityInfo, type, user, restoreContext, quoteToEscape = "'", cloneContext, skipFullRecordJSON = false, syncContext) {
42862
+ const activeContexts = [restoreContext, cloneContext, syncContext].filter(Boolean).length;
42863
+ if (activeContexts > 1) {
42864
+ throw new Error("BuildRecordChangePayload: restoreContext, cloneContext, and syncContext are mutually exclusive; at most one may be provided");
42433
42865
  }
42434
42866
  const isCreateOrDelete = oldData === null || newData === null;
42435
42867
  const changes = this.DiffObjects(oldData, newData, entityInfo, quoteToEscape);
@@ -42443,8 +42875,8 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42443
42875
  }
42444
42876
  const changesJSON = changes !== null ? JSON.stringify(changes) : "";
42445
42877
  const changesDescription = oldData && newData ? this.CreateUserDescriptionOfChanges(changes) : !oldData ? "Record Created" : "Record Deleted";
42446
- const source = restoreContext ? "Restore" : cloneContext ? "Clone" : "Internal";
42447
- const changeContext = cloneContext ? SerializeCloneChangeContext(cloneContext) : null;
42878
+ const source = restoreContext ? "Restore" : cloneContext ? "Clone" : syncContext ? "Sync" : "Internal";
42879
+ const changeContext = cloneContext ? SerializeCloneChangeContext(cloneContext) : syncContext ? SerializeSyncChangeContext(syncContext) : null;
42448
42880
  return {
42449
42881
  entityID: entityInfo.ID,
42450
42882
  recordID,
@@ -42456,7 +42888,8 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42456
42888
  fullRecordJSON,
42457
42889
  restoredFromID: restoreContext?.SourceChangeID ?? null,
42458
42890
  restoreReason: restoreContext?.Reason ?? null,
42459
- changeContext
42891
+ changeContext,
42892
+ integrationID: syncContext?.IntegrationID ?? null
42460
42893
  };
42461
42894
  }
42462
42895
  /**
@@ -42473,7 +42906,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42473
42906
  * @param source The source discriminator for the record change row ('Internal' or 'Clone')
42474
42907
  * @param changeContext Optional serialized JSON provenance for clone operations
42475
42908
  */
42476
- async PropagateRecordChangesToSiblings(parentInfo, changeData, pkValue, userId, activeChildEntityName, extraExecOptions, source = "Internal", changeContext = null) {
42909
+ async PropagateRecordChangesToSiblings(parentInfo, changeData, pkValue, userId, activeChildEntityName, extraExecOptions, source = "Internal", changeContext = null, integrationID = null) {
42477
42910
  const sqlParts = [];
42478
42911
  const safePKValue = pkValue.replace(/'/g, "''");
42479
42912
  const safeUserId = userId.replace(/'/g, "''");
@@ -42488,7 +42921,7 @@ var DatabaseProviderBase = class _DatabaseProviderBase extends ProviderBase {
42488
42921
  if (!entityInTree.TrackRecordChanges)
42489
42922
  continue;
42490
42923
  const varName = `@_rc_prop_${varIndex++}`;
42491
- sqlParts.push(this.BuildSiblingRecordChangeSQL(varName, entityInTree, safeChangesJSON, safeChangesDesc, safePKValue, safeUserId, source, changeContext));
42924
+ sqlParts.push(this.BuildSiblingRecordChangeSQL(varName, entityInTree, safeChangesJSON, safeChangesDesc, safePKValue, safeUserId, source, changeContext, integrationID));
42492
42925
  }
42493
42926
  }
42494
42927
  if (sqlParts.length > 0) {
@@ -46922,6 +47355,1059 @@ var AuthorizationEvaluator = class _AuthorizationEvaluator {
46922
47355
  }
46923
47356
  };
46924
47357
 
47358
+ // ../../MJCore/dist/generic/limitsConfig.js
47359
+ var LIMITS_TIER_PRECEDENCE = [
47360
+ "CodeFallback",
47361
+ "MjConfig",
47362
+ "AgentOrWorkflowMetadata",
47363
+ "UserAgentPolicy",
47364
+ "RunOverride"
47365
+ ];
47366
+ function IsTaskGraphIsolationLevel(value) {
47367
+ return value === "InProcess" || value === "Worker" || value === "Process" || value === "Container";
47368
+ }
47369
+ var CODE_FALLBACK_LIMITS = {
47370
+ AgentChannelConsecutiveTurns: 1e3,
47371
+ AgentChannelWakesPerHour: 600,
47372
+ AgentAbsoluteIterations: 1e5,
47373
+ MaxTasksPerAgentGraph: 1e4,
47374
+ WhileLoopMaxIterations: 1e6,
47375
+ ForEachMaxIterations: 1e6,
47376
+ MaxTasksPerGraph: 1e5,
47377
+ BriefingContributorTimeoutMs: 1e4,
47378
+ BriefingMaxContributorChars: 32768,
47379
+ Budgets: {
47380
+ PerRun: {
47381
+ MaxCostUsd: null,
47382
+ MaxWallClockMs: 72e5,
47383
+ MaxTokens: null
47384
+ },
47385
+ PerRoutine: {
47386
+ MaxCostUsd: null,
47387
+ MaxWallClockMs: null
47388
+ },
47389
+ PerUserPerDay: {
47390
+ MaxCostUsd: null,
47391
+ MaxWallClockMs: null,
47392
+ DayBoundaryTimezone: "UTC"
47393
+ },
47394
+ CountPausedTimeTowardsWallClock: false,
47395
+ AllowedInFlightOvershootUsd: 0,
47396
+ AllowedInFlightOvershootMs: 0
47397
+ },
47398
+ ProgressDetector: {
47399
+ Enabled: true,
47400
+ WindowSize: 10,
47401
+ MinIterationsBeforeCheck: 6,
47402
+ DuplicateStepRatioThreshold: 0.75,
47403
+ NoPayloadDeltaWindowCount: 5,
47404
+ RepeatingErrorWindowCount: 4,
47405
+ AmbiguityLowScoreThreshold: 0.25,
47406
+ AmbiguityHighScoreThreshold: 0.65,
47407
+ FastJudgeEnabled: true,
47408
+ FastJudgeTimeoutMs: 200,
47409
+ FastJudgeMinIntervalIterations: 5,
47410
+ FastJudgeMaxInputChars: 8192,
47411
+ FastJudgeFailureFallback: "ContinueWithWarning"
47412
+ },
47413
+ ResourceGuards: {
47414
+ MaxValidationRetries: 10,
47415
+ MaxConsecutiveFailedSteps: 10,
47416
+ MaxConsecutiveUnproductiveRetries: 10,
47417
+ MaxRepeatedFailingStep: 3,
47418
+ MaxConsecutiveReadToolPreemptions: 3,
47419
+ FinalPayloadValidationMaxRetries: 3,
47420
+ MaxRunChainLength: 1e3,
47421
+ MaxAgentRunTreeDepth: 100,
47422
+ MaxHandoffHops: 3,
47423
+ MaxSubAgentConsultRounds: 3,
47424
+ MaxDecisionRequestsPerTurn: 8,
47425
+ MaxDecisionCallsPerTurn: 100,
47426
+ MaxConversationToolCallsPerTurn: 8,
47427
+ MaxSettlementRetryPasses: 20,
47428
+ MaxReinvokeDepth: 5,
47429
+ MaxProviderRaiseAttempts: 3,
47430
+ ClientToolTimeoutMs: 3e4,
47431
+ PipelineDeadlineMs: 12e4,
47432
+ MaxPipelineStages: 20,
47433
+ MaxMapElements: 1e3,
47434
+ MaxLoopConcurrency: 10,
47435
+ MaxRealtimeConsecutiveAgentTurns: 8
47436
+ },
47437
+ Tuning: {
47438
+ MaxPerAgentCacheEntries: 200,
47439
+ MaxClientToolSessions: 1e3,
47440
+ MaxToolsPerSession: 200,
47441
+ CompactionDefaultContextTokens: 8e3,
47442
+ CompactionDefaultTriggerPercent: 75,
47443
+ CompactionDefaultTargetPercent: 30,
47444
+ CompactionMinGainTokens: 500,
47445
+ CompactionMinMessages: 4,
47446
+ CompactionMaxDeltaMessageChars: 1e4,
47447
+ MaxSkillDecisionCandidates: 30,
47448
+ MaxHandoffCandidates: 20,
47449
+ QueryCacheDefaultMaxSize: 1e3,
47450
+ QueryCacheDefaultTtlMinutes: 60,
47451
+ ScratchpadMaxTasks: 50,
47452
+ DecisionsMaxItems: 100,
47453
+ MaxInitialArtifactOperations: 100,
47454
+ MaxDirectInIds: 2500,
47455
+ MaxAgentsOfferedInDraft: 40,
47456
+ MaxStepsPerSignal: 1e3
47457
+ },
47458
+ Isolation: {
47459
+ DefaultIsolation: "InProcess",
47460
+ DraftDefaultIsolation: "Worker",
47461
+ WorkerMaxOldGenerationSizeMb: 256,
47462
+ WorkerMaxYoungGenerationSizeMb: 64,
47463
+ WorkerTimeoutMs: 12e4,
47464
+ ProcessMaxMemoryMb: 512,
47465
+ ProcessTimeoutMs: 3e5,
47466
+ ContainerMemoryMb: 512,
47467
+ ContainerCpuQuota: 1,
47468
+ ContainerTimeoutMs: 3e5,
47469
+ ContainerImage: "node:20-alpine",
47470
+ ContainerRuntime: "docker"
47471
+ },
47472
+ TaskGraphQueue: {
47473
+ GraphDispatchTopicName: "mj.taskgraph.runs",
47474
+ DefaultEnqueueTopicName: "mj.taskgraph.steps",
47475
+ MaxEnqueuePublishConcurrency: 25,
47476
+ EnqueuePublishBatchSize: 100,
47477
+ MaxConcurrentIsolatedRunners: 16,
47478
+ MaxEnqueueItemsPerFanOut: 1e5,
47479
+ MaxEnqueueRedeliveryAttempts: 5,
47480
+ EnqueuePublishRetryAttempts: 3,
47481
+ CallerNotificationRetentionMs: 864e5
47482
+ }
47483
+ };
47484
+ var RESOURCE_GUARD_KEYS = [
47485
+ "MaxValidationRetries",
47486
+ "MaxConsecutiveFailedSteps",
47487
+ "MaxConsecutiveUnproductiveRetries",
47488
+ "MaxRepeatedFailingStep",
47489
+ "MaxConsecutiveReadToolPreemptions",
47490
+ "FinalPayloadValidationMaxRetries",
47491
+ "MaxRunChainLength",
47492
+ "MaxAgentRunTreeDepth",
47493
+ "MaxHandoffHops",
47494
+ "MaxSubAgentConsultRounds",
47495
+ "MaxDecisionRequestsPerTurn",
47496
+ "MaxDecisionCallsPerTurn",
47497
+ "MaxConversationToolCallsPerTurn",
47498
+ "MaxSettlementRetryPasses",
47499
+ "MaxReinvokeDepth",
47500
+ "MaxProviderRaiseAttempts",
47501
+ "ClientToolTimeoutMs",
47502
+ "PipelineDeadlineMs",
47503
+ "MaxPipelineStages",
47504
+ "MaxMapElements",
47505
+ "MaxLoopConcurrency",
47506
+ "MaxRealtimeConsecutiveAgentTurns"
47507
+ ];
47508
+ var TUNING_KEYS = [
47509
+ "MaxPerAgentCacheEntries",
47510
+ "MaxClientToolSessions",
47511
+ "MaxToolsPerSession",
47512
+ "CompactionDefaultContextTokens",
47513
+ "CompactionDefaultTriggerPercent",
47514
+ "CompactionDefaultTargetPercent",
47515
+ "CompactionMinGainTokens",
47516
+ "CompactionMinMessages",
47517
+ "CompactionMaxDeltaMessageChars",
47518
+ "MaxSkillDecisionCandidates",
47519
+ "MaxHandoffCandidates",
47520
+ "QueryCacheDefaultMaxSize",
47521
+ "QueryCacheDefaultTtlMinutes",
47522
+ "ScratchpadMaxTasks",
47523
+ "DecisionsMaxItems",
47524
+ "MaxInitialArtifactOperations",
47525
+ "MaxDirectInIds",
47526
+ "MaxAgentsOfferedInDraft",
47527
+ "MaxStepsPerSignal"
47528
+ ];
47529
+ var ISOLATION_NUMERIC_KEYS = [
47530
+ "WorkerMaxOldGenerationSizeMb",
47531
+ "WorkerMaxYoungGenerationSizeMb",
47532
+ "WorkerTimeoutMs",
47533
+ "ProcessMaxMemoryMb",
47534
+ "ProcessTimeoutMs",
47535
+ "ContainerMemoryMb",
47536
+ "ContainerCpuQuota",
47537
+ "ContainerTimeoutMs"
47538
+ ];
47539
+ var ISOLATION_KEYS = [
47540
+ "DefaultIsolation",
47541
+ "DraftDefaultIsolation",
47542
+ ...ISOLATION_NUMERIC_KEYS,
47543
+ "ContainerImage",
47544
+ "ContainerRuntime"
47545
+ ];
47546
+ var TASK_GRAPH_QUEUE_NUMERIC_KEYS = [
47547
+ "MaxEnqueuePublishConcurrency",
47548
+ "EnqueuePublishBatchSize",
47549
+ "MaxConcurrentIsolatedRunners",
47550
+ "MaxEnqueueItemsPerFanOut",
47551
+ "MaxEnqueueRedeliveryAttempts",
47552
+ "EnqueuePublishRetryAttempts",
47553
+ "CallerNotificationRetentionMs"
47554
+ ];
47555
+ var TASK_GRAPH_QUEUE_KEYS = [
47556
+ "GraphDispatchTopicName",
47557
+ "DefaultEnqueueTopicName",
47558
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS
47559
+ ];
47560
+ var LIMITS_KEY_PATHS = [
47561
+ "AgentChannelConsecutiveTurns",
47562
+ "AgentChannelWakesPerHour",
47563
+ "AgentAbsoluteIterations",
47564
+ "MaxTasksPerAgentGraph",
47565
+ "WhileLoopMaxIterations",
47566
+ "ForEachMaxIterations",
47567
+ "MaxTasksPerGraph",
47568
+ "BriefingContributorTimeoutMs",
47569
+ "BriefingMaxContributorChars",
47570
+ "Budgets.PerRun.MaxCostUsd",
47571
+ "Budgets.PerRun.MaxWallClockMs",
47572
+ "Budgets.PerRun.MaxTokens",
47573
+ "Budgets.PerRoutine.MaxCostUsd",
47574
+ "Budgets.PerRoutine.MaxWallClockMs",
47575
+ "Budgets.PerUserPerDay.MaxCostUsd",
47576
+ "Budgets.PerUserPerDay.MaxWallClockMs",
47577
+ "Budgets.PerUserPerDay.DayBoundaryTimezone",
47578
+ "Budgets.CountPausedTimeTowardsWallClock",
47579
+ "Budgets.AllowedInFlightOvershootUsd",
47580
+ "Budgets.AllowedInFlightOvershootMs",
47581
+ "ProgressDetector.Enabled",
47582
+ "ProgressDetector.WindowSize",
47583
+ "ProgressDetector.MinIterationsBeforeCheck",
47584
+ "ProgressDetector.DuplicateStepRatioThreshold",
47585
+ "ProgressDetector.NoPayloadDeltaWindowCount",
47586
+ "ProgressDetector.RepeatingErrorWindowCount",
47587
+ "ProgressDetector.AmbiguityLowScoreThreshold",
47588
+ "ProgressDetector.AmbiguityHighScoreThreshold",
47589
+ "ProgressDetector.FastJudgeEnabled",
47590
+ "ProgressDetector.FastJudgeTimeoutMs",
47591
+ "ProgressDetector.FastJudgeMinIntervalIterations",
47592
+ "ProgressDetector.FastJudgeMaxInputChars",
47593
+ "ProgressDetector.FastJudgeFailureFallback",
47594
+ ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
47595
+ ...TUNING_KEYS.map((k) => `Tuning.${k}`),
47596
+ ...ISOLATION_KEYS.map((k) => `Isolation.${k}`),
47597
+ ...TASK_GRAPH_QUEUE_KEYS.map((k) => `TaskGraphQueue.${k}`)
47598
+ ];
47599
+ var NUMERIC_CEILING_KEYS = /* @__PURE__ */ new Set([
47600
+ "AgentChannelConsecutiveTurns",
47601
+ "AgentChannelWakesPerHour",
47602
+ "AgentAbsoluteIterations",
47603
+ "MaxTasksPerAgentGraph",
47604
+ "WhileLoopMaxIterations",
47605
+ "ForEachMaxIterations",
47606
+ "MaxTasksPerGraph",
47607
+ "BriefingContributorTimeoutMs",
47608
+ "BriefingMaxContributorChars",
47609
+ "Budgets.PerRun.MaxCostUsd",
47610
+ "Budgets.PerRun.MaxWallClockMs",
47611
+ "Budgets.PerRun.MaxTokens",
47612
+ "Budgets.PerRoutine.MaxCostUsd",
47613
+ "Budgets.PerRoutine.MaxWallClockMs",
47614
+ "Budgets.PerUserPerDay.MaxCostUsd",
47615
+ "Budgets.PerUserPerDay.MaxWallClockMs",
47616
+ "Budgets.AllowedInFlightOvershootUsd",
47617
+ "Budgets.AllowedInFlightOvershootMs",
47618
+ "ProgressDetector.FastJudgeMaxInputChars",
47619
+ ...RESOURCE_GUARD_KEYS.map((k) => `ResourceGuards.${k}`),
47620
+ ...ISOLATION_NUMERIC_KEYS.map((k) => `Isolation.${k}`),
47621
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => `TaskGraphQueue.${k}`)
47622
+ ]);
47623
+ var LIMITS_KEY_ROLES = Object.fromEntries(LIMITS_KEY_PATHS.map((key) => [
47624
+ key,
47625
+ NUMERIC_CEILING_KEYS.has(key) ? "PolicyCeiling" : "OverridableDefault"
47626
+ ]));
47627
+ function GetLimitsKeyRole(key) {
47628
+ return LIMITS_KEY_ROLES[key];
47629
+ }
47630
+ var LIMITS_CEILING_OVERRIDE_AUTHORIZATIONS = [
47631
+ "System Administrator",
47632
+ "AI: Manage Agents"
47633
+ ];
47634
+ function CanUserRaiseEnforcedLimitsCeilings(user, provider) {
47635
+ if (!user) {
47636
+ return false;
47637
+ }
47638
+ const userType = typeof user.Type === "string" ? user.Type.trim().toLowerCase() : "";
47639
+ if (userType === "owner") {
47640
+ return true;
47641
+ }
47642
+ const authorizations = provider?.Authorizations ?? [];
47643
+ const allowedSet = new Set(LIMITS_CEILING_OVERRIDE_AUTHORIZATIONS.map((name) => name.toLowerCase()));
47644
+ const evaluator = new AuthorizationEvaluator();
47645
+ for (const auth of authorizations) {
47646
+ const name = auth.Name?.trim().toLowerCase();
47647
+ if (name && allowedSet.has(name) && evaluator.UserCanExecuteWithAncestors(auth, user, authorizations)) {
47648
+ return true;
47649
+ }
47650
+ }
47651
+ return false;
47652
+ }
47653
+ function isLimitsInputObject(raw) {
47654
+ return IsPlainObject(raw);
47655
+ }
47656
+ function readObjectProperty(obj, keys) {
47657
+ for (const key of keys) {
47658
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
47659
+ return obj[key];
47660
+ }
47661
+ }
47662
+ return void 0;
47663
+ }
47664
+ function readFiniteNonNegativeNumber(raw) {
47665
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {
47666
+ return void 0;
47667
+ }
47668
+ return raw;
47669
+ }
47670
+ function readPositiveInteger(raw) {
47671
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 1) {
47672
+ return void 0;
47673
+ }
47674
+ return Math.trunc(raw);
47675
+ }
47676
+ function readNullableNonNegativeNumber(raw) {
47677
+ if (raw === null) {
47678
+ return null;
47679
+ }
47680
+ return readFiniteNonNegativeNumber(raw);
47681
+ }
47682
+ function readNullablePositiveInteger(raw) {
47683
+ if (raw === null) {
47684
+ return null;
47685
+ }
47686
+ return readPositiveInteger(raw);
47687
+ }
47688
+ function readUnitIntervalNumber(raw) {
47689
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || raw > 1) {
47690
+ return void 0;
47691
+ }
47692
+ return raw;
47693
+ }
47694
+ function readBoolean(raw) {
47695
+ return typeof raw === "boolean" ? raw : void 0;
47696
+ }
47697
+ function readNonEmptyString(raw) {
47698
+ if (typeof raw !== "string") {
47699
+ return void 0;
47700
+ }
47701
+ const trimmed = raw.trim();
47702
+ return trimmed.length > 0 ? trimmed : void 0;
47703
+ }
47704
+ function readFastJudgeFallback(raw) {
47705
+ if (raw === "ContinueWithWarning" || raw === "PauseForHuman") {
47706
+ return raw;
47707
+ }
47708
+ return void 0;
47709
+ }
47710
+ function readIsolationLevel(raw) {
47711
+ return IsTaskGraphIsolationLevel(raw) ? raw : void 0;
47712
+ }
47713
+ function normalizeIsolationOverride(raw) {
47714
+ if (!isLimitsInputObject(raw)) {
47715
+ return void 0;
47716
+ }
47717
+ const out = {};
47718
+ const defaultIso = readIsolationLevel(readObjectProperty(raw, ["DefaultIsolation", "defaultIsolation"]));
47719
+ if (defaultIso !== void 0)
47720
+ out.DefaultIsolation = defaultIso;
47721
+ const draftIso = readIsolationLevel(readObjectProperty(raw, ["DraftDefaultIsolation", "draftDefaultIsolation"]));
47722
+ if (draftIso !== void 0)
47723
+ out.DraftDefaultIsolation = draftIso;
47724
+ const numeric = normalizePositiveIntSection(raw, ISOLATION_NUMERIC_KEYS);
47725
+ if (numeric) {
47726
+ Object.assign(out, numeric);
47727
+ }
47728
+ const containerImage = readNonEmptyString(readObjectProperty(raw, ["ContainerImage", "containerImage"]));
47729
+ if (containerImage !== void 0)
47730
+ out.ContainerImage = containerImage;
47731
+ const containerRuntime = readNonEmptyString(readObjectProperty(raw, ["ContainerRuntime", "containerRuntime"]));
47732
+ if (containerRuntime !== void 0)
47733
+ out.ContainerRuntime = containerRuntime;
47734
+ return Object.keys(out).length > 0 ? out : void 0;
47735
+ }
47736
+ function normalizeTaskGraphQueueOverride(raw) {
47737
+ if (!isLimitsInputObject(raw)) {
47738
+ return void 0;
47739
+ }
47740
+ const out = {};
47741
+ const graphTopic = readNonEmptyString(readObjectProperty(raw, ["GraphDispatchTopicName", "graphDispatchTopicName"]));
47742
+ if (graphTopic !== void 0)
47743
+ out.GraphDispatchTopicName = graphTopic;
47744
+ const stepTopic = readNonEmptyString(readObjectProperty(raw, ["DefaultEnqueueTopicName", "defaultEnqueueTopicName"]));
47745
+ if (stepTopic !== void 0)
47746
+ out.DefaultEnqueueTopicName = stepTopic;
47747
+ const numeric = normalizePositiveIntSection(raw, TASK_GRAPH_QUEUE_NUMERIC_KEYS);
47748
+ if (numeric) {
47749
+ Object.assign(out, numeric);
47750
+ }
47751
+ return Object.keys(out).length > 0 ? out : void 0;
47752
+ }
47753
+ function normalizeScopeBudgetOverride(raw) {
47754
+ if (!isLimitsInputObject(raw)) {
47755
+ return void 0;
47756
+ }
47757
+ const out = {};
47758
+ const maxCost = readNullableNonNegativeNumber(readObjectProperty(raw, ["MaxCostUsd", "maxCostUsd"]));
47759
+ if (maxCost !== void 0) {
47760
+ out.MaxCostUsd = maxCost;
47761
+ }
47762
+ const maxWall = readNullablePositiveInteger(readObjectProperty(raw, ["MaxWallClockMs", "maxWallClockMs"]));
47763
+ if (maxWall !== void 0) {
47764
+ out.MaxWallClockMs = maxWall;
47765
+ }
47766
+ return Object.keys(out).length > 0 ? out : void 0;
47767
+ }
47768
+ function normalizeRunScopeBudgetOverride(raw) {
47769
+ if (!isLimitsInputObject(raw)) {
47770
+ return void 0;
47771
+ }
47772
+ const base = normalizeScopeBudgetOverride(raw) ?? {};
47773
+ const out = { ...base };
47774
+ const maxTokens = readNullablePositiveInteger(readObjectProperty(raw, ["MaxTokens", "maxTokens"]));
47775
+ if (maxTokens !== void 0) {
47776
+ out.MaxTokens = maxTokens;
47777
+ }
47778
+ return Object.keys(out).length > 0 ? out : void 0;
47779
+ }
47780
+ function normalizeUserDailyScopeBudgetOverride(raw) {
47781
+ if (!isLimitsInputObject(raw)) {
47782
+ return void 0;
47783
+ }
47784
+ const base = normalizeScopeBudgetOverride(raw) ?? {};
47785
+ const out = { ...base };
47786
+ const tz = readNonEmptyString(readObjectProperty(raw, ["DayBoundaryTimezone", "dayBoundaryTimezone"]));
47787
+ if (tz !== void 0) {
47788
+ out.DayBoundaryTimezone = tz;
47789
+ }
47790
+ return Object.keys(out).length > 0 ? out : void 0;
47791
+ }
47792
+ function normalizeBudgetsOverride(raw) {
47793
+ if (!isLimitsInputObject(raw)) {
47794
+ return void 0;
47795
+ }
47796
+ const out = {};
47797
+ const perRun = normalizeRunScopeBudgetOverride(readObjectProperty(raw, ["PerRun", "perRun"]));
47798
+ if (perRun) {
47799
+ out.PerRun = perRun;
47800
+ }
47801
+ const perRoutine = normalizeScopeBudgetOverride(readObjectProperty(raw, ["PerRoutine", "perRoutine"]));
47802
+ if (perRoutine) {
47803
+ out.PerRoutine = perRoutine;
47804
+ }
47805
+ const perUserPerDay = normalizeUserDailyScopeBudgetOverride(readObjectProperty(raw, ["PerUserPerDay", "perUserPerDay"]));
47806
+ if (perUserPerDay) {
47807
+ out.PerUserPerDay = perUserPerDay;
47808
+ }
47809
+ const countPaused = readBoolean(readObjectProperty(raw, ["CountPausedTimeTowardsWallClock", "countPausedTimeTowardsWallClock"]));
47810
+ if (countPaused !== void 0) {
47811
+ out.CountPausedTimeTowardsWallClock = countPaused;
47812
+ }
47813
+ const overshootUsd = readFiniteNonNegativeNumber(readObjectProperty(raw, ["AllowedInFlightOvershootUsd", "allowedInFlightOvershootUsd"]));
47814
+ if (overshootUsd !== void 0) {
47815
+ out.AllowedInFlightOvershootUsd = overshootUsd;
47816
+ }
47817
+ const overshootMs = readFiniteNonNegativeNumber(readObjectProperty(raw, ["AllowedInFlightOvershootMs", "allowedInFlightOvershootMs"]));
47818
+ if (overshootMs !== void 0) {
47819
+ out.AllowedInFlightOvershootMs = overshootMs;
47820
+ }
47821
+ return Object.keys(out).length > 0 ? out : void 0;
47822
+ }
47823
+ function normalizeProgressDetectorOverride(raw) {
47824
+ if (!isLimitsInputObject(raw)) {
47825
+ return void 0;
47826
+ }
47827
+ const out = {};
47828
+ const enabled = readBoolean(readObjectProperty(raw, ["Enabled", "enabled"]));
47829
+ if (enabled !== void 0)
47830
+ out.Enabled = enabled;
47831
+ const windowSize = readPositiveInteger(readObjectProperty(raw, ["WindowSize", "windowSize"]));
47832
+ if (windowSize !== void 0)
47833
+ out.WindowSize = windowSize;
47834
+ const minIterations = readPositiveInteger(readObjectProperty(raw, ["MinIterationsBeforeCheck", "minIterationsBeforeCheck"]));
47835
+ if (minIterations !== void 0)
47836
+ out.MinIterationsBeforeCheck = minIterations;
47837
+ const dupRatio = readUnitIntervalNumber(readObjectProperty(raw, ["DuplicateStepRatioThreshold", "duplicateStepRatioThreshold"]));
47838
+ if (dupRatio !== void 0)
47839
+ out.DuplicateStepRatioThreshold = dupRatio;
47840
+ const noDelta = readPositiveInteger(readObjectProperty(raw, ["NoPayloadDeltaWindowCount", "noPayloadDeltaWindowCount"]));
47841
+ if (noDelta !== void 0)
47842
+ out.NoPayloadDeltaWindowCount = noDelta;
47843
+ const repErr = readPositiveInteger(readObjectProperty(raw, ["RepeatingErrorWindowCount", "repeatingErrorWindowCount"]));
47844
+ if (repErr !== void 0)
47845
+ out.RepeatingErrorWindowCount = repErr;
47846
+ const lowScore = readUnitIntervalNumber(readObjectProperty(raw, ["AmbiguityLowScoreThreshold", "ambiguityLowScoreThreshold"]));
47847
+ if (lowScore !== void 0)
47848
+ out.AmbiguityLowScoreThreshold = lowScore;
47849
+ const highScore = readUnitIntervalNumber(readObjectProperty(raw, ["AmbiguityHighScoreThreshold", "ambiguityHighScoreThreshold"]));
47850
+ if (highScore !== void 0)
47851
+ out.AmbiguityHighScoreThreshold = highScore;
47852
+ const fastJudgeEnabled = readBoolean(readObjectProperty(raw, ["FastJudgeEnabled", "fastJudgeEnabled"]));
47853
+ if (fastJudgeEnabled !== void 0)
47854
+ out.FastJudgeEnabled = fastJudgeEnabled;
47855
+ const fastJudgeTimeoutMs = readPositiveInteger(readObjectProperty(raw, ["FastJudgeTimeoutMs", "fastJudgeTimeoutMs"]));
47856
+ if (fastJudgeTimeoutMs !== void 0)
47857
+ out.FastJudgeTimeoutMs = fastJudgeTimeoutMs;
47858
+ const minInterval = readPositiveInteger(readObjectProperty(raw, ["FastJudgeMinIntervalIterations", "fastJudgeMinIntervalIterations"]));
47859
+ if (minInterval !== void 0)
47860
+ out.FastJudgeMinIntervalIterations = minInterval;
47861
+ const maxInputChars = readPositiveInteger(readObjectProperty(raw, ["FastJudgeMaxInputChars", "fastJudgeMaxInputChars"]));
47862
+ if (maxInputChars !== void 0)
47863
+ out.FastJudgeMaxInputChars = maxInputChars;
47864
+ const fallback = readFastJudgeFallback(readObjectProperty(raw, ["FastJudgeFailureFallback", "fastJudgeFailureFallback"]));
47865
+ if (fallback !== void 0)
47866
+ out.FastJudgeFailureFallback = fallback;
47867
+ return Object.keys(out).length > 0 ? out : void 0;
47868
+ }
47869
+ function normalizePositiveIntSection(raw, keys) {
47870
+ if (!isLimitsInputObject(raw)) {
47871
+ return void 0;
47872
+ }
47873
+ const out = {};
47874
+ for (const key of keys) {
47875
+ const camel = key.charAt(0).toLowerCase() + key.slice(1);
47876
+ const val = readPositiveInteger(readObjectProperty(raw, [key, camel]));
47877
+ if (val !== void 0) {
47878
+ out[key] = val;
47879
+ }
47880
+ }
47881
+ return Object.keys(out).length > 0 ? out : void 0;
47882
+ }
47883
+ function NormalizeLimitsInput(raw) {
47884
+ if (!isLimitsInputObject(raw)) {
47885
+ return {};
47886
+ }
47887
+ const out = {};
47888
+ const turns = readPositiveInteger(readObjectProperty(raw, ["AgentChannelConsecutiveTurns", "agentChannelConsecutiveTurns", "MaxConsecutiveAgentTurns", "maxConsecutiveAgentTurns"]));
47889
+ if (turns !== void 0)
47890
+ out.AgentChannelConsecutiveTurns = turns;
47891
+ const wakes = readPositiveInteger(readObjectProperty(raw, ["AgentChannelWakesPerHour", "agentChannelWakesPerHour", "MaxHourlyWakes", "maxHourlyWakes"]));
47892
+ if (wakes !== void 0)
47893
+ out.AgentChannelWakesPerHour = wakes;
47894
+ const iterations = readPositiveInteger(readObjectProperty(raw, ["AgentAbsoluteIterations", "agentAbsoluteIterations", "absoluteMaxIterations"]));
47895
+ if (iterations !== void 0)
47896
+ out.AgentAbsoluteIterations = iterations;
47897
+ const agentGraph = readPositiveInteger(readObjectProperty(raw, ["MaxTasksPerAgentGraph", "maxTasksPerAgentGraph", "MAX_TASKS_PER_AGENT_GRAPH"]));
47898
+ if (agentGraph !== void 0)
47899
+ out.MaxTasksPerAgentGraph = agentGraph;
47900
+ const whileMax = readPositiveInteger(readObjectProperty(raw, ["WhileLoopMaxIterations", "whileLoopMaxIterations"]));
47901
+ if (whileMax !== void 0)
47902
+ out.WhileLoopMaxIterations = whileMax;
47903
+ const forEachMax = readPositiveInteger(readObjectProperty(raw, ["ForEachMaxIterations", "forEachMaxIterations"]));
47904
+ if (forEachMax !== void 0)
47905
+ out.ForEachMaxIterations = forEachMax;
47906
+ const graphCeiling = readPositiveInteger(readObjectProperty(raw, ["MaxTasksPerGraph", "maxTasksPerGraph", "MAX_TASKS_PER_GRAPH"]));
47907
+ if (graphCeiling !== void 0)
47908
+ out.MaxTasksPerGraph = graphCeiling;
47909
+ const briefingTimeout = readPositiveInteger(readObjectProperty(raw, ["BriefingContributorTimeoutMs", "briefingContributorTimeoutMs", "ContributorTimeoutMs"]));
47910
+ if (briefingTimeout !== void 0)
47911
+ out.BriefingContributorTimeoutMs = briefingTimeout;
47912
+ const briefingChars = readPositiveInteger(readObjectProperty(raw, ["BriefingMaxContributorChars", "briefingMaxContributorChars", "MaxContributorChars"]));
47913
+ if (briefingChars !== void 0)
47914
+ out.BriefingMaxContributorChars = briefingChars;
47915
+ const budgets = normalizeBudgetsOverride(readObjectProperty(raw, ["Budgets", "budgets"]));
47916
+ if (budgets)
47917
+ out.Budgets = budgets;
47918
+ const progressDetector = normalizeProgressDetectorOverride(readObjectProperty(raw, ["ProgressDetector", "progressDetector"]));
47919
+ if (progressDetector)
47920
+ out.ProgressDetector = progressDetector;
47921
+ const resourceGuards = normalizePositiveIntSection(readObjectProperty(raw, ["ResourceGuards", "resourceGuards"]), RESOURCE_GUARD_KEYS);
47922
+ if (resourceGuards)
47923
+ out.ResourceGuards = resourceGuards;
47924
+ const tuning = normalizePositiveIntSection(readObjectProperty(raw, ["Tuning", "tuning"]), TUNING_KEYS);
47925
+ if (tuning)
47926
+ out.Tuning = tuning;
47927
+ const isolation = normalizeIsolationOverride(readObjectProperty(raw, ["Isolation", "isolation"]));
47928
+ if (isolation)
47929
+ out.Isolation = isolation;
47930
+ const taskGraphQueue = normalizeTaskGraphQueueOverride(readObjectProperty(raw, ["TaskGraphQueue", "taskGraphQueue"]));
47931
+ if (taskGraphQueue)
47932
+ out.TaskGraphQueue = taskGraphQueue;
47933
+ return out;
47934
+ }
47935
+ function cloneDefaultLimits() {
47936
+ return {
47937
+ ...CODE_FALLBACK_LIMITS,
47938
+ Budgets: {
47939
+ PerRun: { ...CODE_FALLBACK_LIMITS.Budgets.PerRun },
47940
+ PerRoutine: { ...CODE_FALLBACK_LIMITS.Budgets.PerRoutine },
47941
+ PerUserPerDay: { ...CODE_FALLBACK_LIMITS.Budgets.PerUserPerDay },
47942
+ CountPausedTimeTowardsWallClock: CODE_FALLBACK_LIMITS.Budgets.CountPausedTimeTowardsWallClock,
47943
+ AllowedInFlightOvershootUsd: CODE_FALLBACK_LIMITS.Budgets.AllowedInFlightOvershootUsd,
47944
+ AllowedInFlightOvershootMs: CODE_FALLBACK_LIMITS.Budgets.AllowedInFlightOvershootMs
47945
+ },
47946
+ ProgressDetector: { ...CODE_FALLBACK_LIMITS.ProgressDetector },
47947
+ ResourceGuards: { ...CODE_FALLBACK_LIMITS.ResourceGuards },
47948
+ Tuning: { ...CODE_FALLBACK_LIMITS.Tuning },
47949
+ Isolation: { ...CODE_FALLBACK_LIMITS.Isolation },
47950
+ TaskGraphQueue: { ...CODE_FALLBACK_LIMITS.TaskGraphQueue }
47951
+ };
47952
+ }
47953
+ function extractTierValue(layer, key) {
47954
+ if (key.startsWith("ResourceGuards.")) {
47955
+ const subKey = key.slice("ResourceGuards.".length);
47956
+ return layer.ResourceGuards?.[subKey];
47957
+ }
47958
+ if (key.startsWith("Tuning.")) {
47959
+ const subKey = key.slice("Tuning.".length);
47960
+ return layer.Tuning?.[subKey];
47961
+ }
47962
+ if (key.startsWith("Isolation.")) {
47963
+ const subKey = key.slice("Isolation.".length);
47964
+ return layer.Isolation?.[subKey];
47965
+ }
47966
+ if (key.startsWith("TaskGraphQueue.")) {
47967
+ const subKey = key.slice("TaskGraphQueue.".length);
47968
+ return layer.TaskGraphQueue?.[subKey];
47969
+ }
47970
+ switch (key) {
47971
+ case "AgentChannelConsecutiveTurns":
47972
+ return layer.AgentChannelConsecutiveTurns;
47973
+ case "AgentChannelWakesPerHour":
47974
+ return layer.AgentChannelWakesPerHour;
47975
+ case "AgentAbsoluteIterations":
47976
+ return layer.AgentAbsoluteIterations;
47977
+ case "MaxTasksPerAgentGraph":
47978
+ return layer.MaxTasksPerAgentGraph;
47979
+ case "WhileLoopMaxIterations":
47980
+ return layer.WhileLoopMaxIterations;
47981
+ case "ForEachMaxIterations":
47982
+ return layer.ForEachMaxIterations;
47983
+ case "MaxTasksPerGraph":
47984
+ return layer.MaxTasksPerGraph;
47985
+ case "BriefingContributorTimeoutMs":
47986
+ return layer.BriefingContributorTimeoutMs;
47987
+ case "BriefingMaxContributorChars":
47988
+ return layer.BriefingMaxContributorChars;
47989
+ case "Budgets.PerRun.MaxCostUsd":
47990
+ return layer.Budgets?.PerRun?.MaxCostUsd;
47991
+ case "Budgets.PerRun.MaxWallClockMs":
47992
+ return layer.Budgets?.PerRun?.MaxWallClockMs;
47993
+ case "Budgets.PerRun.MaxTokens":
47994
+ return layer.Budgets?.PerRun?.MaxTokens;
47995
+ case "Budgets.PerRoutine.MaxCostUsd":
47996
+ return layer.Budgets?.PerRoutine?.MaxCostUsd;
47997
+ case "Budgets.PerRoutine.MaxWallClockMs":
47998
+ return layer.Budgets?.PerRoutine?.MaxWallClockMs;
47999
+ case "Budgets.PerUserPerDay.MaxCostUsd":
48000
+ return layer.Budgets?.PerUserPerDay?.MaxCostUsd;
48001
+ case "Budgets.PerUserPerDay.MaxWallClockMs":
48002
+ return layer.Budgets?.PerUserPerDay?.MaxWallClockMs;
48003
+ case "Budgets.PerUserPerDay.DayBoundaryTimezone":
48004
+ return layer.Budgets?.PerUserPerDay?.DayBoundaryTimezone;
48005
+ case "Budgets.CountPausedTimeTowardsWallClock":
48006
+ return layer.Budgets?.CountPausedTimeTowardsWallClock;
48007
+ case "Budgets.AllowedInFlightOvershootUsd":
48008
+ return layer.Budgets?.AllowedInFlightOvershootUsd;
48009
+ case "Budgets.AllowedInFlightOvershootMs":
48010
+ return layer.Budgets?.AllowedInFlightOvershootMs;
48011
+ case "ProgressDetector.Enabled":
48012
+ return layer.ProgressDetector?.Enabled;
48013
+ case "ProgressDetector.WindowSize":
48014
+ return layer.ProgressDetector?.WindowSize;
48015
+ case "ProgressDetector.MinIterationsBeforeCheck":
48016
+ return layer.ProgressDetector?.MinIterationsBeforeCheck;
48017
+ case "ProgressDetector.DuplicateStepRatioThreshold":
48018
+ return layer.ProgressDetector?.DuplicateStepRatioThreshold;
48019
+ case "ProgressDetector.NoPayloadDeltaWindowCount":
48020
+ return layer.ProgressDetector?.NoPayloadDeltaWindowCount;
48021
+ case "ProgressDetector.RepeatingErrorWindowCount":
48022
+ return layer.ProgressDetector?.RepeatingErrorWindowCount;
48023
+ case "ProgressDetector.AmbiguityLowScoreThreshold":
48024
+ return layer.ProgressDetector?.AmbiguityLowScoreThreshold;
48025
+ case "ProgressDetector.AmbiguityHighScoreThreshold":
48026
+ return layer.ProgressDetector?.AmbiguityHighScoreThreshold;
48027
+ case "ProgressDetector.FastJudgeEnabled":
48028
+ return layer.ProgressDetector?.FastJudgeEnabled;
48029
+ case "ProgressDetector.FastJudgeTimeoutMs":
48030
+ return layer.ProgressDetector?.FastJudgeTimeoutMs;
48031
+ case "ProgressDetector.FastJudgeMinIntervalIterations":
48032
+ return layer.ProgressDetector?.FastJudgeMinIntervalIterations;
48033
+ case "ProgressDetector.FastJudgeMaxInputChars":
48034
+ return layer.ProgressDetector?.FastJudgeMaxInputChars;
48035
+ case "ProgressDetector.FastJudgeFailureFallback":
48036
+ return layer.ProgressDetector?.FastJudgeFailureFallback;
48037
+ }
48038
+ }
48039
+ function assignResolvedValue(target, key, value) {
48040
+ if (key.startsWith("ResourceGuards.")) {
48041
+ const subKey = key.slice("ResourceGuards.".length);
48042
+ target.ResourceGuards[subKey] = value;
48043
+ return;
48044
+ }
48045
+ if (key.startsWith("Tuning.")) {
48046
+ const subKey = key.slice("Tuning.".length);
48047
+ target.Tuning[subKey] = value;
48048
+ return;
48049
+ }
48050
+ if (key.startsWith("Isolation.")) {
48051
+ const subKey = key.slice("Isolation.".length);
48052
+ if (subKey === "ContainerImage" || subKey === "ContainerRuntime") {
48053
+ target.Isolation[subKey] = value;
48054
+ } else if (subKey === "DefaultIsolation" || subKey === "DraftDefaultIsolation") {
48055
+ target.Isolation[subKey] = value;
48056
+ } else {
48057
+ target.Isolation[subKey] = value;
48058
+ }
48059
+ return;
48060
+ }
48061
+ if (key.startsWith("TaskGraphQueue.")) {
48062
+ const subKey = key.slice("TaskGraphQueue.".length);
48063
+ if (subKey === "GraphDispatchTopicName" || subKey === "DefaultEnqueueTopicName") {
48064
+ target.TaskGraphQueue[subKey] = value;
48065
+ } else {
48066
+ target.TaskGraphQueue[subKey] = value;
48067
+ }
48068
+ return;
48069
+ }
48070
+ switch (key) {
48071
+ case "AgentChannelConsecutiveTurns":
48072
+ target.AgentChannelConsecutiveTurns = value;
48073
+ break;
48074
+ case "AgentChannelWakesPerHour":
48075
+ target.AgentChannelWakesPerHour = value;
48076
+ break;
48077
+ case "AgentAbsoluteIterations":
48078
+ target.AgentAbsoluteIterations = value;
48079
+ break;
48080
+ case "MaxTasksPerAgentGraph":
48081
+ target.MaxTasksPerAgentGraph = value;
48082
+ break;
48083
+ case "WhileLoopMaxIterations":
48084
+ target.WhileLoopMaxIterations = value;
48085
+ break;
48086
+ case "ForEachMaxIterations":
48087
+ target.ForEachMaxIterations = value;
48088
+ break;
48089
+ case "MaxTasksPerGraph":
48090
+ target.MaxTasksPerGraph = value;
48091
+ break;
48092
+ case "BriefingContributorTimeoutMs":
48093
+ target.BriefingContributorTimeoutMs = value;
48094
+ break;
48095
+ case "BriefingMaxContributorChars":
48096
+ target.BriefingMaxContributorChars = value;
48097
+ break;
48098
+ case "Budgets.PerRun.MaxCostUsd":
48099
+ target.Budgets.PerRun.MaxCostUsd = value;
48100
+ break;
48101
+ case "Budgets.PerRun.MaxWallClockMs":
48102
+ target.Budgets.PerRun.MaxWallClockMs = value;
48103
+ break;
48104
+ case "Budgets.PerRun.MaxTokens":
48105
+ target.Budgets.PerRun.MaxTokens = value;
48106
+ break;
48107
+ case "Budgets.PerRoutine.MaxCostUsd":
48108
+ target.Budgets.PerRoutine.MaxCostUsd = value;
48109
+ break;
48110
+ case "Budgets.PerRoutine.MaxWallClockMs":
48111
+ target.Budgets.PerRoutine.MaxWallClockMs = value;
48112
+ break;
48113
+ case "Budgets.PerUserPerDay.MaxCostUsd":
48114
+ target.Budgets.PerUserPerDay.MaxCostUsd = value;
48115
+ break;
48116
+ case "Budgets.PerUserPerDay.MaxWallClockMs":
48117
+ target.Budgets.PerUserPerDay.MaxWallClockMs = value;
48118
+ break;
48119
+ case "Budgets.PerUserPerDay.DayBoundaryTimezone":
48120
+ target.Budgets.PerUserPerDay.DayBoundaryTimezone = value;
48121
+ break;
48122
+ case "Budgets.CountPausedTimeTowardsWallClock":
48123
+ target.Budgets.CountPausedTimeTowardsWallClock = value;
48124
+ break;
48125
+ case "Budgets.AllowedInFlightOvershootUsd":
48126
+ target.Budgets.AllowedInFlightOvershootUsd = value;
48127
+ break;
48128
+ case "Budgets.AllowedInFlightOvershootMs":
48129
+ target.Budgets.AllowedInFlightOvershootMs = value;
48130
+ break;
48131
+ case "ProgressDetector.Enabled":
48132
+ target.ProgressDetector.Enabled = value;
48133
+ break;
48134
+ case "ProgressDetector.WindowSize":
48135
+ target.ProgressDetector.WindowSize = value;
48136
+ break;
48137
+ case "ProgressDetector.MinIterationsBeforeCheck":
48138
+ target.ProgressDetector.MinIterationsBeforeCheck = value;
48139
+ break;
48140
+ case "ProgressDetector.DuplicateStepRatioThreshold":
48141
+ target.ProgressDetector.DuplicateStepRatioThreshold = value;
48142
+ break;
48143
+ case "ProgressDetector.NoPayloadDeltaWindowCount":
48144
+ target.ProgressDetector.NoPayloadDeltaWindowCount = value;
48145
+ break;
48146
+ case "ProgressDetector.RepeatingErrorWindowCount":
48147
+ target.ProgressDetector.RepeatingErrorWindowCount = value;
48148
+ break;
48149
+ case "ProgressDetector.AmbiguityLowScoreThreshold":
48150
+ target.ProgressDetector.AmbiguityLowScoreThreshold = value;
48151
+ break;
48152
+ case "ProgressDetector.AmbiguityHighScoreThreshold":
48153
+ target.ProgressDetector.AmbiguityHighScoreThreshold = value;
48154
+ break;
48155
+ case "ProgressDetector.FastJudgeEnabled":
48156
+ target.ProgressDetector.FastJudgeEnabled = value;
48157
+ break;
48158
+ case "ProgressDetector.FastJudgeTimeoutMs":
48159
+ target.ProgressDetector.FastJudgeTimeoutMs = value;
48160
+ break;
48161
+ case "ProgressDetector.FastJudgeMinIntervalIterations":
48162
+ target.ProgressDetector.FastJudgeMinIntervalIterations = value;
48163
+ break;
48164
+ case "ProgressDetector.FastJudgeMaxInputChars":
48165
+ target.ProgressDetector.FastJudgeMaxInputChars = value;
48166
+ break;
48167
+ case "ProgressDetector.FastJudgeFailureFallback":
48168
+ target.ProgressDetector.FastJudgeFailureFallback = value;
48169
+ break;
48170
+ }
48171
+ }
48172
+ function shouldClampToPolicyCeiling(key, runVal, policyVal) {
48173
+ if (!NUMERIC_CEILING_KEYS.has(key) || typeof policyVal !== "number" || !Number.isFinite(policyVal)) {
48174
+ return false;
48175
+ }
48176
+ if (runVal === null) {
48177
+ return true;
48178
+ }
48179
+ return typeof runVal === "number" && Number.isFinite(runVal) && runVal > policyVal;
48180
+ }
48181
+ function resolveSingleKey(key, defaults, tiers, enforceUserPolicyCeiling, enforceConfiguredCeilings, callerCanRaiseCeilings) {
48182
+ const codeFallbackBase = extractTierValue(defaults, key) ?? null;
48183
+ const tierValues = {
48184
+ CodeFallback: codeFallbackBase
48185
+ };
48186
+ let preRunValue = codeFallbackBase;
48187
+ let preRunTier = "CodeFallback";
48188
+ let wasClamped = false;
48189
+ for (const tier of LIMITS_TIER_PRECEDENCE) {
48190
+ if (tier === "RunOverride") {
48191
+ continue;
48192
+ }
48193
+ const layer = tiers[tier];
48194
+ if (!layer) {
48195
+ continue;
48196
+ }
48197
+ const candidate = extractTierValue(layer, key);
48198
+ if (candidate !== void 0) {
48199
+ tierValues[tier] = candidate;
48200
+ if (tier === "UserAgentPolicy" && !callerCanRaiseCeilings) {
48201
+ const mjConfigVal = tierValues.MjConfig;
48202
+ const clampAgainstPreRun = enforceConfiguredCeilings && shouldClampToPolicyCeiling(key, candidate, preRunValue);
48203
+ const clampAgainstMjConfig = (enforceConfiguredCeilings || enforceUserPolicyCeiling) && shouldClampToPolicyCeiling(key, candidate, mjConfigVal);
48204
+ if (clampAgainstPreRun || clampAgainstMjConfig) {
48205
+ if (clampAgainstMjConfig && (!clampAgainstPreRun || typeof mjConfigVal === "number" && typeof preRunValue === "number" && mjConfigVal <= preRunValue)) {
48206
+ preRunValue = mjConfigVal;
48207
+ preRunTier = "MjConfig";
48208
+ }
48209
+ wasClamped = true;
48210
+ continue;
48211
+ }
48212
+ }
48213
+ preRunValue = candidate;
48214
+ preRunTier = tier;
48215
+ }
48216
+ }
48217
+ let winningValue = preRunValue;
48218
+ let sourceTier = preRunTier;
48219
+ const runLayer = tiers.RunOverride;
48220
+ const runCandidate = runLayer ? extractTierValue(runLayer, key) : void 0;
48221
+ if (runCandidate !== void 0) {
48222
+ tierValues.RunOverride = runCandidate;
48223
+ winningValue = runCandidate;
48224
+ sourceTier = "RunOverride";
48225
+ if (!callerCanRaiseCeilings) {
48226
+ if (enforceConfiguredCeilings && shouldClampToPolicyCeiling(key, winningValue, preRunValue)) {
48227
+ winningValue = preRunValue;
48228
+ sourceTier = preRunTier;
48229
+ wasClamped = true;
48230
+ } else if (enforceUserPolicyCeiling && tierValues.UserAgentPolicy !== void 0) {
48231
+ const effectivePolicyCeiling = preRunTier === "MjConfig" || preRunTier === "UserAgentPolicy" ? preRunValue : tierValues.UserAgentPolicy;
48232
+ if (shouldClampToPolicyCeiling(key, winningValue, effectivePolicyCeiling)) {
48233
+ winningValue = effectivePolicyCeiling;
48234
+ sourceTier = preRunTier === "MjConfig" ? "MjConfig" : "UserAgentPolicy";
48235
+ wasClamped = true;
48236
+ }
48237
+ }
48238
+ }
48239
+ }
48240
+ return {
48241
+ Key: key,
48242
+ KeyRole: GetLimitsKeyRole(key),
48243
+ Value: winningValue,
48244
+ SourceTier: sourceTier,
48245
+ IsOverridden: sourceTier !== "CodeFallback",
48246
+ TierValues: tierValues,
48247
+ WasClampedByPolicyCeiling: wasClamped
48248
+ };
48249
+ }
48250
+ function ValidateLimitsConfig(config) {
48251
+ const issues = [];
48252
+ const positiveIntChecks = [
48253
+ ["AgentChannelConsecutiveTurns", config.AgentChannelConsecutiveTurns],
48254
+ ["AgentChannelWakesPerHour", config.AgentChannelWakesPerHour],
48255
+ ["AgentAbsoluteIterations", config.AgentAbsoluteIterations],
48256
+ ["MaxTasksPerAgentGraph", config.MaxTasksPerAgentGraph],
48257
+ ["WhileLoopMaxIterations", config.WhileLoopMaxIterations],
48258
+ ["ForEachMaxIterations", config.ForEachMaxIterations],
48259
+ ["MaxTasksPerGraph", config.MaxTasksPerGraph],
48260
+ ["BriefingContributorTimeoutMs", config.BriefingContributorTimeoutMs],
48261
+ ["BriefingMaxContributorChars", config.BriefingMaxContributorChars],
48262
+ ["ProgressDetector.WindowSize", config.ProgressDetector.WindowSize],
48263
+ ["ProgressDetector.MinIterationsBeforeCheck", config.ProgressDetector.MinIterationsBeforeCheck],
48264
+ ["ProgressDetector.NoPayloadDeltaWindowCount", config.ProgressDetector.NoPayloadDeltaWindowCount],
48265
+ ["ProgressDetector.RepeatingErrorWindowCount", config.ProgressDetector.RepeatingErrorWindowCount],
48266
+ ["ProgressDetector.FastJudgeTimeoutMs", config.ProgressDetector.FastJudgeTimeoutMs],
48267
+ ["ProgressDetector.FastJudgeMinIntervalIterations", config.ProgressDetector.FastJudgeMinIntervalIterations],
48268
+ ["ProgressDetector.FastJudgeMaxInputChars", config.ProgressDetector.FastJudgeMaxInputChars],
48269
+ ...RESOURCE_GUARD_KEYS.map((k) => [`ResourceGuards.${k}`, config.ResourceGuards[k]]),
48270
+ ...TUNING_KEYS.map((k) => [`Tuning.${k}`, config.Tuning[k]]),
48271
+ ...ISOLATION_NUMERIC_KEYS.map((k) => [`Isolation.${k}`, config.Isolation[k]]),
48272
+ ...TASK_GRAPH_QUEUE_NUMERIC_KEYS.map((k) => [`TaskGraphQueue.${k}`, config.TaskGraphQueue[k]])
48273
+ ];
48274
+ for (const [key, val] of positiveIntChecks) {
48275
+ if (!Number.isFinite(val) || val < 1) {
48276
+ issues.push({ Key: key, Message: `${key} must be a positive number >= 1.` });
48277
+ }
48278
+ }
48279
+ if (!IsTaskGraphIsolationLevel(config.Isolation.DefaultIsolation)) {
48280
+ issues.push({
48281
+ Key: "Isolation.DefaultIsolation",
48282
+ Message: "Isolation.DefaultIsolation must be one of InProcess, Worker, Process, or Container."
48283
+ });
48284
+ }
48285
+ if (!IsTaskGraphIsolationLevel(config.Isolation.DraftDefaultIsolation)) {
48286
+ issues.push({
48287
+ Key: "Isolation.DraftDefaultIsolation",
48288
+ Message: "Isolation.DraftDefaultIsolation must be one of InProcess, Worker, Process, or Container."
48289
+ });
48290
+ }
48291
+ if (!config.Isolation.ContainerImage || !config.Isolation.ContainerImage.trim()) {
48292
+ issues.push({
48293
+ Key: "Isolation.ContainerImage",
48294
+ Message: "Isolation.ContainerImage must be a non-empty string."
48295
+ });
48296
+ }
48297
+ if (!config.Isolation.ContainerRuntime || !config.Isolation.ContainerRuntime.trim()) {
48298
+ issues.push({
48299
+ Key: "Isolation.ContainerRuntime",
48300
+ Message: "Isolation.ContainerRuntime must be a non-empty string."
48301
+ });
48302
+ }
48303
+ if (!config.TaskGraphQueue.GraphDispatchTopicName || !config.TaskGraphQueue.GraphDispatchTopicName.trim()) {
48304
+ issues.push({
48305
+ Key: "TaskGraphQueue.GraphDispatchTopicName",
48306
+ Message: "TaskGraphQueue.GraphDispatchTopicName must be a non-empty string."
48307
+ });
48308
+ }
48309
+ if (!config.TaskGraphQueue.DefaultEnqueueTopicName || !config.TaskGraphQueue.DefaultEnqueueTopicName.trim()) {
48310
+ issues.push({
48311
+ Key: "TaskGraphQueue.DefaultEnqueueTopicName",
48312
+ Message: "TaskGraphQueue.DefaultEnqueueTopicName must be a non-empty string."
48313
+ });
48314
+ }
48315
+ if (config.MaxTasksPerAgentGraph > config.MaxTasksPerGraph) {
48316
+ issues.push({
48317
+ Key: "MaxTasksPerAgentGraph",
48318
+ Message: "MaxTasksPerAgentGraph cannot exceed MaxTasksPerGraph."
48319
+ });
48320
+ }
48321
+ if (config.ProgressDetector.AmbiguityLowScoreThreshold > config.ProgressDetector.AmbiguityHighScoreThreshold) {
48322
+ issues.push({
48323
+ Key: "ProgressDetector.AmbiguityLowScoreThreshold",
48324
+ Message: "AmbiguityLowScoreThreshold cannot exceed AmbiguityHighScoreThreshold."
48325
+ });
48326
+ }
48327
+ return { Valid: issues.length === 0, Issues: issues };
48328
+ }
48329
+ var LimitsConfigResolver = class _LimitsConfigResolver extends BaseSingleton {
48330
+ constructor() {
48331
+ super();
48332
+ this.registeredMjConfigLimits = null;
48333
+ }
48334
+ /** Returns the process-wide singleton {@link LimitsConfigResolver}. */
48335
+ static get Instance() {
48336
+ return _LimitsConfigResolver.getInstance();
48337
+ }
48338
+ /**
48339
+ * Convenience static entry point delegating to {@link LimitsConfigResolver.Instance.Resolve}.
48340
+ */
48341
+ static Resolve(input, options) {
48342
+ return _LimitsConfigResolver.Instance.Resolve(input, options);
48343
+ }
48344
+ /**
48345
+ * Registers Tier 2 (`MjConfig`) limits loaded from `mj.config.cjs` by a host bootstrapper.
48346
+ * Pass `null` to clear any registered config.
48347
+ */
48348
+ RegisterMjConfigLimits(limits) {
48349
+ if (limits === null) {
48350
+ this.registeredMjConfigLimits = null;
48351
+ return;
48352
+ }
48353
+ this.registeredMjConfigLimits = NormalizeLimitsInput(limits);
48354
+ }
48355
+ /** Returns the currently registered Tier 2 (`MjConfig`) override, or `null` when unset. */
48356
+ GetMjConfigLimits() {
48357
+ return this.registeredMjConfigLimits;
48358
+ }
48359
+ /** Clears any registered Tier 2 (`MjConfig`) override (primarily for unit test isolation). */
48360
+ ClearMjConfigLimits() {
48361
+ this.registeredMjConfigLimits = null;
48362
+ }
48363
+ /**
48364
+ * Resolves all limit keys across the 5 precedence tiers (`CodeFallback` -> `MjConfig` ->
48365
+ * `AgentOrWorkflowMetadata` -> `UserAgentPolicy` -> `RunOverride`), tracking full provenance.
48366
+ */
48367
+ Resolve(input = {}, options = {}) {
48368
+ const defaults = cloneDefaultLimits();
48369
+ const mjConfigTier = input.MjConfig !== void 0 ? input.MjConfig : this.registeredMjConfigLimits;
48370
+ const tiers = {
48371
+ CodeFallback: input.CodeFallback ?? null,
48372
+ MjConfig: mjConfigTier ?? null,
48373
+ AgentOrWorkflowMetadata: input.AgentOrWorkflowMetadata ?? null,
48374
+ UserAgentPolicy: input.UserAgentPolicy ?? null,
48375
+ RunOverride: input.RunOverride ?? null
48376
+ };
48377
+ const resolvedLimits = cloneDefaultLimits();
48378
+ const provenanceEntries = [];
48379
+ const overriddenKeys = [];
48380
+ const clampedKeys = [];
48381
+ const enforceUserPolicyCeiling = options.EnforceUserPolicyAsCeiling === true;
48382
+ const enforceConfiguredCeilings = options.EnforceConfiguredCeilings === true;
48383
+ const callerCanRaiseCeilings = options.AllowAuthorizedCeilingOverride === true && CanUserRaiseEnforcedLimitsCeilings(options.ContextUser, options.Provider);
48384
+ for (const key of LIMITS_KEY_PATHS) {
48385
+ const keyProvenance = resolveSingleKey(key, defaults, tiers, enforceUserPolicyCeiling, enforceConfiguredCeilings, callerCanRaiseCeilings);
48386
+ assignResolvedValue(resolvedLimits, key, keyProvenance.Value);
48387
+ provenanceEntries.push([key, keyProvenance]);
48388
+ if (keyProvenance.IsOverridden) {
48389
+ overriddenKeys.push(key);
48390
+ }
48391
+ if (keyProvenance.WasClampedByPolicyCeiling) {
48392
+ clampedKeys.push(key);
48393
+ }
48394
+ }
48395
+ return {
48396
+ Limits: resolvedLimits,
48397
+ Provenance: Object.fromEntries(provenanceEntries),
48398
+ ResolvedAtISO: options.ResolvedAtISO ?? (/* @__PURE__ */ new Date()).toISOString(),
48399
+ OverriddenKeys: overriddenKeys,
48400
+ ClampedKeys: clampedKeys
48401
+ };
48402
+ }
48403
+ /**
48404
+ * Reads a single resolved limit value from a resolution result by canonical key path.
48405
+ */
48406
+ GetLimitValue(result, key) {
48407
+ return result.Provenance[key].Value;
48408
+ }
48409
+ };
48410
+
46925
48411
  // ../../MJCore/dist/generic/graphqlTypeNames.js
46926
48412
  var MJ_CORE_SCHEMA = "__mj";
46927
48413
  function SanitizeGraphQLName(input) {
@@ -47713,6 +49199,13 @@ export {
47713
49199
  EntityRecordNameCache,
47714
49200
  ResolveMJAPIURL,
47715
49201
  AuthorizationEvaluator,
49202
+ LIMITS_TIER_PRECEDENCE,
49203
+ CODE_FALLBACK_LIMITS,
49204
+ LIMITS_KEY_PATHS,
49205
+ GetLimitsKeyRole,
49206
+ NormalizeLimitsInput,
49207
+ ValidateLimitsConfig,
49208
+ LimitsConfigResolver,
47716
49209
  getGraphQLTypeNameBase,
47717
49210
  RegisterForStartup,
47718
49211
  StartupManager,