@memberjunction/core-actions 6.2.0-edge.4 → 6.2.0-edge.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/README.md +76 -0
  2. package/dist/custom/ai/base-find-actions.action.d.ts +8 -0
  3. package/dist/custom/ai/base-find-actions.action.d.ts.map +1 -1
  4. package/dist/custom/ai/base-find-actions.action.js +18 -2
  5. package/dist/custom/ai/base-find-actions.action.js.map +1 -1
  6. package/dist/custom/ai/communication-oauth-service.d.ts +228 -0
  7. package/dist/custom/ai/communication-oauth-service.d.ts.map +1 -0
  8. package/dist/custom/ai/communication-oauth-service.js +309 -0
  9. package/dist/custom/ai/communication-oauth-service.js.map +1 -0
  10. package/dist/custom/ai/configure-agent-user-policy.action.d.ts +26 -0
  11. package/dist/custom/ai/configure-agent-user-policy.action.d.ts.map +1 -0
  12. package/dist/custom/ai/configure-agent-user-policy.action.js +270 -0
  13. package/dist/custom/ai/configure-agent-user-policy.action.js.map +1 -0
  14. package/dist/custom/ai/execute-agent.action.d.ts +49 -0
  15. package/dist/custom/ai/execute-agent.action.d.ts.map +1 -1
  16. package/dist/custom/ai/execute-agent.action.js +125 -52
  17. package/dist/custom/ai/execute-agent.action.js.map +1 -1
  18. package/dist/custom/ai/prepare-outbound-call-brief.action.d.ts +37 -0
  19. package/dist/custom/ai/prepare-outbound-call-brief.action.d.ts.map +1 -0
  20. package/dist/custom/ai/prepare-outbound-call-brief.action.js +224 -0
  21. package/dist/custom/ai/prepare-outbound-call-brief.action.js.map +1 -0
  22. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts +26 -0
  23. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts.map +1 -0
  24. package/dist/custom/ai/schedule-next-agent-wake.action.js +278 -0
  25. package/dist/custom/ai/schedule-next-agent-wake.action.js.map +1 -0
  26. package/dist/custom/ai/send-inter-agent-request.action.d.ts +42 -0
  27. package/dist/custom/ai/send-inter-agent-request.action.d.ts.map +1 -0
  28. package/dist/custom/ai/send-inter-agent-request.action.js +213 -0
  29. package/dist/custom/ai/send-inter-agent-request.action.js.map +1 -0
  30. package/dist/custom/ai/user-scoped-communication.action.d.ts +109 -0
  31. package/dist/custom/ai/user-scoped-communication.action.d.ts.map +1 -0
  32. package/dist/custom/ai/user-scoped-communication.action.js +1258 -0
  33. package/dist/custom/ai/user-scoped-communication.action.js.map +1 -0
  34. package/dist/custom/crud/base-record-mutation.action.d.ts +66 -21
  35. package/dist/custom/crud/base-record-mutation.action.d.ts.map +1 -1
  36. package/dist/custom/crud/base-record-mutation.action.js +178 -66
  37. package/dist/custom/crud/base-record-mutation.action.js.map +1 -1
  38. package/dist/custom/crud/create-record.action.d.ts +2 -2
  39. package/dist/custom/crud/create-record.action.d.ts.map +1 -1
  40. package/dist/custom/crud/create-record.action.js +7 -3
  41. package/dist/custom/crud/create-record.action.js.map +1 -1
  42. package/dist/custom/crud/delete-record.action.d.ts +2 -1
  43. package/dist/custom/crud/delete-record.action.d.ts.map +1 -1
  44. package/dist/custom/crud/delete-record.action.js +8 -6
  45. package/dist/custom/crud/delete-record.action.js.map +1 -1
  46. package/dist/custom/crud/get-record.action.d.ts +2 -1
  47. package/dist/custom/crud/get-record.action.d.ts.map +1 -1
  48. package/dist/custom/crud/get-record.action.js +8 -6
  49. package/dist/custom/crud/get-record.action.js.map +1 -1
  50. package/dist/custom/crud/get-records.action.d.ts.map +1 -1
  51. package/dist/custom/crud/get-records.action.js +19 -2
  52. package/dist/custom/crud/get-records.action.js.map +1 -1
  53. package/dist/custom/crud/update-record.action.d.ts +4 -3
  54. package/dist/custom/crud/update-record.action.d.ts.map +1 -1
  55. package/dist/custom/crud/update-record.action.js +23 -23
  56. package/dist/custom/crud/update-record.action.js.map +1 -1
  57. package/dist/custom/data/explore-database-schema.action.d.ts.map +1 -1
  58. package/dist/custom/data/explore-database-schema.action.js +22 -1
  59. package/dist/custom/data/explore-database-schema.action.js.map +1 -1
  60. package/dist/custom/data/get-entity-details.action.d.ts.map +1 -1
  61. package/dist/custom/data/get-entity-details.action.js +33 -7
  62. package/dist/custom/data/get-entity-details.action.js.map +1 -1
  63. package/dist/custom/data/run-adhoc-query.action.d.ts +2 -0
  64. package/dist/custom/data/run-adhoc-query.action.d.ts.map +1 -1
  65. package/dist/custom/data/run-adhoc-query.action.js +64 -9
  66. package/dist/custom/data/run-adhoc-query.action.js.map +1 -1
  67. package/dist/custom/data/run-record-process.action.d.ts +2 -0
  68. package/dist/custom/data/run-record-process.action.d.ts.map +1 -1
  69. package/dist/custom/data/run-record-process.action.js +10 -4
  70. package/dist/custom/data/run-record-process.action.js.map +1 -1
  71. package/dist/custom/data/run-stored-query.action.d.ts +1 -0
  72. package/dist/custom/data/run-stored-query.action.d.ts.map +1 -1
  73. package/dist/custom/data/run-stored-query.action.js +21 -5
  74. package/dist/custom/data/run-stored-query.action.js.map +1 -1
  75. package/dist/custom/files/base-file-storage.action.d.ts +53 -5
  76. package/dist/custom/files/base-file-storage.action.d.ts.map +1 -1
  77. package/dist/custom/files/base-file-storage.action.js +72 -14
  78. package/dist/custom/files/base-file-storage.action.js.map +1 -1
  79. package/dist/custom/files/copy-object.action.d.ts +3 -0
  80. package/dist/custom/files/copy-object.action.d.ts.map +1 -1
  81. package/dist/custom/files/copy-object.action.js +9 -1
  82. package/dist/custom/files/copy-object.action.js.map +1 -1
  83. package/dist/custom/files/create-directory.action.d.ts +3 -0
  84. package/dist/custom/files/create-directory.action.d.ts.map +1 -1
  85. package/dist/custom/files/create-directory.action.js +4 -0
  86. package/dist/custom/files/create-directory.action.js.map +1 -1
  87. package/dist/custom/files/create-document.action.d.ts.map +1 -1
  88. package/dist/custom/files/create-document.action.js +12 -0
  89. package/dist/custom/files/create-document.action.js.map +1 -1
  90. package/dist/custom/files/delete-directory.action.d.ts +3 -0
  91. package/dist/custom/files/delete-directory.action.d.ts.map +1 -1
  92. package/dist/custom/files/delete-directory.action.js +4 -0
  93. package/dist/custom/files/delete-directory.action.js.map +1 -1
  94. package/dist/custom/files/delete-object.action.d.ts +3 -0
  95. package/dist/custom/files/delete-object.action.d.ts.map +1 -1
  96. package/dist/custom/files/delete-object.action.js +9 -1
  97. package/dist/custom/files/delete-object.action.js.map +1 -1
  98. package/dist/custom/files/get-download-url.action.d.ts.map +1 -1
  99. package/dist/custom/files/get-download-url.action.js +5 -1
  100. package/dist/custom/files/get-download-url.action.js.map +1 -1
  101. package/dist/custom/files/get-file-content.action.d.ts +0 -20
  102. package/dist/custom/files/get-file-content.action.d.ts.map +1 -1
  103. package/dist/custom/files/get-file-content.action.js +18 -66
  104. package/dist/custom/files/get-file-content.action.js.map +1 -1
  105. package/dist/custom/files/get-metadata.action.d.ts.map +1 -1
  106. package/dist/custom/files/get-metadata.action.js +5 -1
  107. package/dist/custom/files/get-metadata.action.js.map +1 -1
  108. package/dist/custom/files/get-object.action.d.ts.map +1 -1
  109. package/dist/custom/files/get-object.action.js +5 -1
  110. package/dist/custom/files/get-object.action.js.map +1 -1
  111. package/dist/custom/files/get-upload-url.action.d.ts +3 -0
  112. package/dist/custom/files/get-upload-url.action.d.ts.map +1 -1
  113. package/dist/custom/files/get-upload-url.action.js +9 -1
  114. package/dist/custom/files/get-upload-url.action.js.map +1 -1
  115. package/dist/custom/files/list-objects.action.d.ts.map +1 -1
  116. package/dist/custom/files/list-objects.action.js +7 -3
  117. package/dist/custom/files/list-objects.action.js.map +1 -1
  118. package/dist/custom/files/list-storage-providers.action.d.ts +5 -4
  119. package/dist/custom/files/list-storage-providers.action.d.ts.map +1 -1
  120. package/dist/custom/files/list-storage-providers.action.js +15 -11
  121. package/dist/custom/files/list-storage-providers.action.js.map +1 -1
  122. package/dist/custom/files/move-object.action.d.ts +3 -0
  123. package/dist/custom/files/move-object.action.d.ts.map +1 -1
  124. package/dist/custom/files/move-object.action.js +9 -1
  125. package/dist/custom/files/move-object.action.js.map +1 -1
  126. package/dist/custom/files/search-storage-files.action.d.ts.map +1 -1
  127. package/dist/custom/files/search-storage-files.action.js +10 -6
  128. package/dist/custom/files/search-storage-files.action.js.map +1 -1
  129. package/dist/custom/lists/get-list-records.action.d.ts.map +1 -1
  130. package/dist/custom/lists/get-list-records.action.js +1 -0
  131. package/dist/custom/lists/get-list-records.action.js.map +1 -1
  132. package/dist/custom/search/scoped-search.action.d.ts +112 -22
  133. package/dist/custom/search/scoped-search.action.d.ts.map +1 -1
  134. package/dist/custom/search/scoped-search.action.js +351 -95
  135. package/dist/custom/search/scoped-search.action.js.map +1 -1
  136. package/dist/custom/search/search.action.d.ts +30 -0
  137. package/dist/custom/search/search.action.d.ts.map +1 -1
  138. package/dist/custom/search/search.action.js +77 -32
  139. package/dist/custom/search/search.action.js.map +1 -1
  140. package/dist/custom/security/password-strength.action.d.ts.map +1 -1
  141. package/dist/custom/security/password-strength.action.js +3 -4
  142. package/dist/custom/security/password-strength.action.js.map +1 -1
  143. package/dist/custom/utilities/artifact-builder-service.d.ts +3 -3
  144. package/dist/custom/utilities/artifact-builder-service.d.ts.map +1 -1
  145. package/dist/custom/utilities/artifact-builder-service.js +9 -9
  146. package/dist/custom/utilities/artifact-builder-service.js.map +1 -1
  147. package/dist/custom/utilities/base-file-handler.d.ts +14 -6
  148. package/dist/custom/utilities/base-file-handler.d.ts.map +1 -1
  149. package/dist/custom/utilities/base-file-handler.js +36 -28
  150. package/dist/custom/utilities/base-file-handler.js.map +1 -1
  151. package/dist/custom/web/web-page-content.action.d.ts.map +1 -1
  152. package/dist/custom/web/web-page-content.action.js +11 -12
  153. package/dist/custom/web/web-page-content.action.js.map +1 -1
  154. package/dist/custom/workflow/conditional.action.d.ts.map +1 -1
  155. package/dist/custom/workflow/conditional.action.js +5 -0
  156. package/dist/custom/workflow/conditional.action.js.map +1 -1
  157. package/dist/custom/workflow/loop.action.d.ts.map +1 -1
  158. package/dist/custom/workflow/loop.action.js +5 -0
  159. package/dist/custom/workflow/loop.action.js.map +1 -1
  160. package/dist/custom/workflow/parallel-execute.action.d.ts.map +1 -1
  161. package/dist/custom/workflow/parallel-execute.action.js +8 -2
  162. package/dist/custom/workflow/parallel-execute.action.js.map +1 -1
  163. package/dist/custom/workflow/retry.action.d.ts.map +1 -1
  164. package/dist/custom/workflow/retry.action.js +5 -0
  165. package/dist/custom/workflow/retry.action.js.map +1 -1
  166. package/dist/custom/workflow/workflow-run-scope.d.ts +15 -0
  167. package/dist/custom/workflow/workflow-run-scope.d.ts.map +1 -0
  168. package/dist/custom/workflow/workflow-run-scope.js +24 -0
  169. package/dist/custom/workflow/workflow-run-scope.js.map +1 -0
  170. package/dist/index.d.ts +7 -0
  171. package/dist/index.d.ts.map +1 -1
  172. package/dist/index.js +7 -0
  173. package/dist/index.js.map +1 -1
  174. package/package.json +44 -44
@@ -4,11 +4,18 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
+ import { ActionRunScopeIsBounded } from "@memberjunction/actions-base";
7
8
  import { BaseAction } from "@memberjunction/actions";
8
- import { RegisterClass, UUIDsEqual } from "@memberjunction/global";
9
+ import { IsPlainObject, NormalizeUUID, RegisterClass, UUIDsEqual } from "@memberjunction/global";
9
10
  import { LogError, LogStatusEx, IsVerboseLoggingEnabled, Metadata } from "@memberjunction/core";
10
11
  import { SearchEngine, GetSearchScopePermissionResolver } from "@memberjunction/search-engine";
11
12
  import { SearchEngineBase } from "@memberjunction/core-entities";
13
+ /**
14
+ * What a well-formed `SecondaryScopes` is, said in every refusal of a malformed one so the model can correct the call.
15
+ * (The parameter descriptions in the action's metadata predate the refusal; this text is the authority until they are updated.)
16
+ */
17
+ const SECONDARY_SCOPES_SHAPE = 'SecondaryScopes must be a JSON object mapping each dimension name to a string, number, boolean or '
18
+ + 'array of strings — e.g. {"Department":"Finance","Tags":["q3"]} — or be omitted.';
12
19
  /** Strict UUID shape for the skill principal — it is caller-supplied and binds into a query. */
13
20
  const SCOPED_SEARCH_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
21
  /**
@@ -41,31 +48,47 @@ const SCOPED_SEARCH_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-
41
48
  * - If `ScopeID` supplied: used as-is.
42
49
  * - If omitted: uses the Global scope.
43
50
  *
44
- * Multi-tenant `SearchContext` (per-call):
45
- * Two optional inputs assemble a `SearchContext` that is threaded into
51
+ * Multi-tenant `SearchContext`:
52
+ * A tenant and secondary dimensions assemble a `SearchContext` that is threaded into
46
53
  * `SearchParams.SearchContext`. The engine renders the values into every
47
54
  * scope-level Nunjucks template (MetadataFilter, ExtraFilter, UserSearchString,
48
- * FolderPath) at search time — so one scope definition serves many tenants.
55
+ * FolderPath) at search time — so one scope definition serves many tenants. The
56
+ * same tenant goes into the permission decision (`ResolveEffectivePermission`),
57
+ * so tenant-scoped grants and denies apply to exactly the search that runs.
49
58
  *
50
59
  * - `PrimaryScopeRecordID` (string) — primary tenant key (e.g. OrganizationID).
51
60
  * Available in templates as `{{ context.PrimaryScopeRecordID }}`.
52
- * - `SecondaryScopes` (JSON string) — flat object of additional dimensions.
53
- * Each value must be `string | number | boolean | string[]`. Available in
54
- * templates as `{{ context.SecondaryScopes.<key> }}`. Incompatible value
55
- * types are dropped with a log; malformed JSON falls back to undefined
56
- * rather than failing the call.
61
+ * - `SecondaryScopes` (a JSON object string, or an object) — flat object of
62
+ * additional dimensions. Each value must be `string | number | boolean | string[]`.
63
+ * Available in templates as `{{ context.SecondaryScopes.<key> }}`. Input that is
64
+ * not valid JSON, not an object, or holds an unsupported value is REFUSED
65
+ * (`INVALID_PARAM`) — never dropped, which would search without the dimension.
66
+ *
67
+ * INSIDE AN AGENT RUN THE RUN'S SCOPE IS AUTHORITATIVE. BaseAgent stamps the run's
68
+ * validated scope on every dispatch (`RunActionParams.RunScope`); the two inputs are
69
+ * model-written there, so they are bound to the run as `AISkillID` is:
70
+ * - no `PrimaryScopeRecordID` → the run's tenant (none when the run is unscoped);
71
+ * - a `PrimaryScopeRecordID` that is not the run's (case-insensitive), or any value
72
+ * when the run has no tenant → refused with `INVALID_PARAM` and a `Forbidden`
73
+ * search-log row. The host sets a run's tenant (`ExecuteAgentParams.PrimaryScope*`);
74
+ * the model never does;
75
+ * - `SecondaryScopes` may restate a dimension the run sets only with an equal value
76
+ * (refused otherwise, as above); a dimension the run does not set is added, bounded
77
+ * by the scope's own dimension trust rules.
78
+ * Outside an agent run (no `RunScope`, e.g. a direct call) both inputs are used as given.
57
79
  *
58
- * `SearchContext` is included only when at least one of the two inputs is
59
- * provided — omitting both preserves the original "no per-call tenant
60
- * filter" behavior. See `guides/SEARCH_SCOPES_AND_RAG_GUIDE.md` §10 for the
61
- * full multi-tenant model and template-rendering details.
80
+ * `SearchContext` is included only when a tenant or a secondary dimension applies —
81
+ * none preserves the original "no per-call tenant filter" behavior. See
82
+ * `guides/SEARCH_SCOPES_AND_RAG_GUIDE.md` §10 for the full multi-tenant model and
83
+ * template-rendering details.
62
84
  *
63
85
  * @example Agent tool call
64
86
  * ```
65
87
  * { "tool": "Scoped Search", "params": { "Query": "refund policy", "AgentID": "<agent-uuid>" } }
66
88
  * ```
67
89
  *
68
- * @example Per-tenant scoped call
90
+ * @example Per-tenant scoped call (a direct call outside an agent run; inside a run scoped to `<org-uuid>`, omit
91
+ * `PrimaryScopeRecordID` — the run's tenant applies)
69
92
  * ```
70
93
  * {
71
94
  * "tool": "Scoped Search",
@@ -79,6 +102,14 @@ const SCOPED_SEARCH_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-
79
102
  * ```
80
103
  */
81
104
  let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
105
+ /**
106
+ * Honours an audience (`RunActionParams.Audience`): every reader must pass the same scope-permission gate
107
+ * the caller does, the search keeps only results every reader may read (`SearchParams.Audience`), and
108
+ * `SourceCounts` — counted before that filtering — are left out of the output.
109
+ */
110
+ get SupportsAudience() {
111
+ return true;
112
+ }
82
113
  async InternalRunAction(params) {
83
114
  // Track action-call wall-clock so any Forbidden log row reports
84
115
  // accurate latency for "denial took 12ms" telemetry.
@@ -114,6 +145,14 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
114
145
  if ('result' in vetted)
115
146
  return vetted.result;
116
147
  const skill = vetted.skill;
148
+ // 1c. The tenant and secondary scopes, for the permission decision AND the search. THE RUN IS THE
149
+ // AUTHORITY inside an agent run (RunActionParams.RunScope): a missing tenant defaults to the run's and one
150
+ // the run does not carry is refused — inside a Loop agent these parameters are model-written. Outside a
151
+ // run they are used as given. Malformed SecondaryScopes are refused either way, never dropped.
152
+ const tenantOutcome = await this.resolveAndVetTenant(params, agent, skill, query, requestedScopeID, startTime);
153
+ if ('result' in tenantOutcome)
154
+ return tenantOutcome.result;
155
+ const { tenant } = tenantOutcome;
117
156
  // 2. Resolve scope (agent-side SearchScopeAccess gate, with denial logging)
118
157
  await SearchEngineBase.Instance.Config(false, params.ContextUser);
119
158
  // skill?.ID, not the raw caller string. By here the skill is loaded and validated, and
@@ -124,38 +163,23 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
124
163
  if ('result' in scopeOutcome)
125
164
  return scopeOutcome.result;
126
165
  const { scope, scopeID } = scopeOutcome;
127
- // 3. User-side permission check (Phase 2A) + Read-level gate, with denial logging
128
- const permDenial = await this.enforceUserPermission(agent, skill, scopeID, query, params, startTime);
166
+ const unboundedDenial = await this.refuseUnboundedScopeInScopedRun(agent, skill, scope, query, params, startTime);
167
+ if (unboundedDenial)
168
+ return unboundedDenial;
169
+ // 3. User-side permission check (Phase 2A) + Read-level gate, with denial logging — then the same
170
+ // gate for every reader of the run's audience: a room may search a scope only if each of them may.
171
+ const permDenial = await this.enforceUserPermission(agent, skill, scopeID, query, params, startTime, tenant.primaryScopeRecordID);
129
172
  if (permDenial)
130
173
  return permDenial;
131
- // 4. Run the search (sync or streaming)
132
- const maxResults = this.getNumericParam(params, "maxresults", 25);
133
- const minScore = this.getNumericParam(params, "minscore", 0);
134
- const streamingMode = (this.getStringParam(params, "streamingmode") ?? 'finalOnly').toLowerCase();
135
- // Per-call multi-tenant context. PrimaryScopeRecordID is the
136
- // primary tenant key (e.g. OrganizationID). SecondaryScopes is
137
- // an opaque JSON object of additional dimensions; each key
138
- // becomes `{{ context.SecondaryScopes.<key> }}` available to
139
- // the scope's Nunjucks-rendered MetadataFilter / ExtraFilter /
140
- // UserSearchString / FolderPath. Dimensions are fully dynamic
141
- // here — validation against scope.SearchContextConfig.dimensions
142
- // (if desired) is the engine's responsibility, not the action's.
143
- const primaryScopeRecordID = this.getStringParam(params, "primaryscoperecordid");
144
- const secondaryScopes = this.parseSecondaryScopes(params);
145
- LogStatusEx({
146
- message: `ScopedSearchAction: Agent="${agent.Name}" scope="${scope?.Name ?? 'Global'}" query="${query}" streamingMode="${streamingMode}" primaryScopeRecordID="${primaryScopeRecordID ?? ''}" aiSkillID="${aiSkillID ?? ''}" secondaryScopeKeys=[${Object.keys(secondaryScopes ?? {}).join(',')}]`,
147
- verboseOnly: true,
148
- isVerboseEnabled: IsVerboseLoggingEnabled
149
- });
150
- const exec = await this.runSearch({
151
- query, maxResults, minScore, scopeID, agent,
152
- contextUser: params.ContextUser, streamingMode,
153
- primaryScopeRecordID, secondaryScopes, aiSkillID: skill?.ID ?? undefined,
154
- });
174
+ const audienceDenial = await this.enforceAudiencePermission(agent, skill, scopeID, query, params, startTime, tenant.primaryScopeRecordID);
175
+ if (audienceDenial)
176
+ return audienceDenial;
177
+ // 4. Run the search (sync or streaming) under the tenant resolved in 1c
178
+ const exec = await this.searchUnderTenant(params, { query, agent, scope, scopeID, skillID: skill?.ID ?? undefined, tenant });
155
179
  if ('result' in exec)
156
180
  return exec.result;
157
- // 5. Build the success response
158
- return this.buildSuccessResult(exec.sr, scope, scopeID, exec.progressEvents);
181
+ // 5. Build the success response (no SourceCounts for a room: they are counted before the audience pass)
182
+ return this.buildSuccessResult(exec.sr, scope, scopeID, exec.progressEvents, params.Audience !== undefined);
159
183
  }
160
184
  catch (error) {
161
185
  const msg = error instanceof Error ? error.message : String(error);
@@ -223,6 +247,29 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
223
247
  }
224
248
  return { ok: true, scope: scopeResolution.scope, scopeID: scopeResolution.scopeID };
225
249
  }
250
+ /**
251
+ * Step 2b — inside a tenant-scoped agent run (`ActionRunScopeIsBounded(params.RunScope)`), refuse a search with
252
+ * no scope or the Global scope: neither renders the run's tenant, so it would reach every tenant the user can
253
+ * read — the reason the Search action is refused in such a run. `null` when the search may proceed. A non-global
254
+ * scope whose templates ignore the tenant is still the scope author's to bound.
255
+ */
256
+ async refuseUnboundedScopeInScopedRun(agent, skill, scope, query, params, startTime) {
257
+ if (!ActionRunScopeIsBounded(params.RunScope) || (scope && !scope.IsGlobal))
258
+ return null;
259
+ const which = scope ? `the Global scope '${scope.Name}'` : 'no search scope';
260
+ await SearchEngine.Instance.LogForbiddenSearch({
261
+ Query: query,
262
+ ScopeIDs: scope ? [scope.ID] : undefined,
263
+ FailureReason: `Refused ${which} inside a tenant-scoped agent run: it would search across every tenant.`,
264
+ StartTime: startTime,
265
+ ContextUser: params.ContextUser,
266
+ AIAgentID: agent.ID,
267
+ AISkillID: skill?.ID ?? null,
268
+ PrimaryScopeRecordID: params.RunScope ? this.runTenantID(params.RunScope) ?? null : null,
269
+ });
270
+ return this.createErrorResult(`This agent run is scoped to a tenant, and ${which} would search across every tenant. `
271
+ + 'Pass a ScopeID for a scope that is bounded to the tenant.', 'INVALID_PARAM');
272
+ }
226
273
  /**
227
274
  * Step 3 helper — Phase 2A user-side permission check. Returns null when
228
275
  * the user is allowed to invoke; returns a denial response (with a
@@ -232,7 +279,7 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
232
279
  * - Resolver Allowed=false ⇒ ACCESS_DENIED (agent-side) or PERMISSION_DENIED (user-side)
233
280
  * - Resolver Allowed=true with Level='Read' ⇒ Read grants visibility, not invocation
234
281
  */
235
- async enforceUserPermission(agent, skill, scopeID, query, params, startTime) {
282
+ async enforceUserPermission(agent, skill, scopeID, query, params, startTime, primaryScopeRecordID) {
236
283
  if (!scopeID) {
237
284
  // No scope resolved, so there is nothing for the per-scope rules to judge. Unchanged for
238
285
  // every caller that passes no skill — which is every caller that existed before this
@@ -249,6 +296,7 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
249
296
  ContextUser: params.ContextUser,
250
297
  AIAgentID: agent.ID,
251
298
  AISkillID: skill.ID,
299
+ PrimaryScopeRecordID: primaryScopeRecordID ?? null,
252
300
  });
253
301
  return this.createErrorResult(`Forbidden: no search scope resolved, so the supplied skill principal cannot be judged.`, 'ACCESS_DENIED');
254
302
  }
@@ -261,8 +309,8 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
261
309
  // decision — which cuts both ways, and the second way is a fail-open: a tenant-scoped
262
310
  // PermissionLevel='None' (an explicit admin deny) was discarded too, so a user holding any
263
311
  // NULL-tenant role grant had that deny silently evaporate. `ExplainScope` passed the tenant
264
- // and denied correctly, so preview and search disagreed in both directions.
265
- const primaryScopeRecordID = this.getStringParam(params, "primaryscoperecordid");
312
+ // and denied correctly, so preview and search disagreed in both directions. The tenant is the one resolved
313
+ // for the search (resolveTenant) — inside an agent run, the run's — so the decision and the search agree.
266
314
  const verdict = await permResolver.ResolveEffectivePermission({
267
315
  User: params.ContextUser,
268
316
  SearchScopeID: scopeID,
@@ -306,6 +354,7 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
306
354
  // Attribute the denial to the skill too. A skill can BE the reason for it
307
355
  // (SkillNone / SkillAssignedNotListed), so a NULL here loses the cause.
308
356
  AISkillID: skill?.ID ?? null,
357
+ PrimaryScopeRecordID: primaryScopeRecordID ?? null,
309
358
  });
310
359
  // THE AUDIT ROW ABOVE KEEPS THE FULL REASON. THE CALLER GETS BACK ONLY WHAT IT SENT.
311
360
  //
@@ -342,11 +391,82 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
342
391
  // cause HERE is the Read level, not the skill — SkillNone/SkillAssignedNotListed
343
392
  // deny outright and can never reach this branch.
344
393
  AISkillID: skill?.ID ?? null,
394
+ PrimaryScopeRecordID: primaryScopeRecordID ?? null,
345
395
  });
346
396
  return this.createErrorResult(`Forbidden: ${reason}`, 'PERMISSION_DENIED');
347
397
  }
348
398
  return null;
349
399
  }
400
+ /**
401
+ * Step 3b — the run's audience (`RunActionParams.Audience`, already normalized by the engine to the distinct
402
+ * readers beyond the caller). Each reader must pass the gate the caller just passed — the same principals and
403
+ * tenant, the same bar above `Read` — because the search engine judges scope entitlement for the caller only.
404
+ * Every refused reader gets its own `Forbidden` search-log row naming them; the caller is told only that the
405
+ * scope is not open to everyone the results are for. A resolver failure propagates, as the caller's does.
406
+ */
407
+ async enforceAudiencePermission(agent, skill, scopeID, query, params, startTime, primaryScopeRecordID) {
408
+ const readers = Array.isArray(params.Audience?.Readers) ? params.Audience.Readers : [];
409
+ if (!scopeID || readers.length === 0)
410
+ return null;
411
+ const resolver = GetSearchScopePermissionResolver();
412
+ const verdicts = await Promise.all(readers.map(reader => resolver.ResolveEffectivePermission({
413
+ User: reader, SearchScopeID: scopeID, Agent: agent, Skill: skill,
414
+ PrimaryScopeRecordID: primaryScopeRecordID ?? null, ContextUser: params.ContextUser,
415
+ })));
416
+ const refused = readers
417
+ .map((reader, i) => ({ reader, verdict: verdicts[i] }))
418
+ .filter(r => !r.verdict.Allowed || r.verdict.Level === 'Read');
419
+ if (refused.length === 0)
420
+ return null;
421
+ for (const { reader, verdict } of refused) {
422
+ await SearchEngine.Instance.LogForbiddenSearch({
423
+ Query: query,
424
+ ScopeIDs: [scopeID],
425
+ FailureReason: this.audienceRefusalReason(reader, verdict),
426
+ StartTime: startTime,
427
+ ContextUser: params.ContextUser,
428
+ AIAgentID: agent.ID,
429
+ AISkillID: skill?.ID ?? null,
430
+ PrimaryScopeRecordID: primaryScopeRecordID ?? null,
431
+ });
432
+ }
433
+ return this.createErrorResult(`Forbidden: scope '${scopeID}' is not open to everyone these results are for (${refused[0].verdict.Source}).`, 'PERMISSION_DENIED');
434
+ }
435
+ /**
436
+ * The audit reason for one refused audience reader. The row is recorded under the CALLER, who can read their own
437
+ * search log, so it names the reader by ID with the verdict's fixed `Source` (or the `Read` level) only — never the
438
+ * reader's name, nor the resolver's `Reason`, which describes the reader's own grants and principals.
439
+ */
440
+ audienceRefusalReason(reader, verdict) {
441
+ const kind = verdict.Allowed && verdict.Level === 'Read' ? 'Read level: visibility, not search' : verdict.Source;
442
+ return `Audience reader ${reader.ID} may not search this scope (${kind}).`.substring(0, 500);
443
+ }
444
+ /**
445
+ * Step 4 — read the search options and run the search ({@link runSearch}) under the tenant resolved in step 1c.
446
+ * Each secondary key becomes `{{ context.SecondaryScopes.<key> }}` in the scope's Nunjucks templates; validating
447
+ * the keys against the scope's dimensions is the engine's job, not the action's.
448
+ */
449
+ async searchUnderTenant(params, resolved) {
450
+ const { query, agent, scope, scopeID, skillID, tenant } = resolved;
451
+ const streamingMode = (this.getStringParam(params, "streamingmode") ?? 'finalOnly').toLowerCase();
452
+ LogStatusEx({
453
+ message: `ScopedSearchAction: Agent="${agent.Name}" scope="${scope?.Name ?? 'Global'}" query="${query}" streamingMode="${streamingMode}" `
454
+ + `primaryScopeRecordID="${tenant.primaryScopeRecordID ?? ''}" aiSkillID="${skillID ?? ''}" `
455
+ + `secondaryScopeKeys=[${Object.keys(tenant.secondaryScopes ?? {}).join(',')}]`,
456
+ verboseOnly: true,
457
+ isVerboseEnabled: IsVerboseLoggingEnabled
458
+ });
459
+ return this.runSearch({
460
+ query, scopeID, agent, streamingMode,
461
+ maxResults: this.getNumericParam(params, "maxresults", 25),
462
+ minScore: this.getNumericParam(params, "minscore", 0),
463
+ contextUser: params.ContextUser,
464
+ primaryScopeRecordID: tenant.primaryScopeRecordID,
465
+ secondaryScopes: tenant.secondaryScopes,
466
+ aiSkillID: skillID,
467
+ audience: params.Audience,
468
+ });
469
+ }
350
470
  /**
351
471
  * Step 4 helper — execute the search via either the synchronous
352
472
  * `Search()` path or the streaming `streamSearch()` path. Returns the
@@ -388,6 +508,9 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
388
508
  // / FolderPath fields at search time so a single scope definition
389
509
  // can serve many tenants.
390
510
  SearchContext: searchContext,
511
+ // Everyone else who will see these results (RunActionParams.Audience, normalized by the engine):
512
+ // the engine keeps only what every reader may read.
513
+ Audience: input.audience,
391
514
  };
392
515
  if (input.streamingMode !== 'partials') {
393
516
  const sr = await SearchEngine.Instance.Search(baseParams, input.contextUser);
@@ -404,26 +527,15 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
404
527
  let finalEvent;
405
528
  let errorMsg;
406
529
  for await (const ev of SearchEngine.Instance.streamSearch(baseParams, input.contextUser)) {
407
- // Skip 'final' event's results from the progress trail to keep
408
- // the param size sane — the final results are returned via the
409
- // Results output param anyway.
410
530
  if (ev.phase === 'final') {
411
531
  finalEvent = { results: ev.results, sourceCounts: ev.sourceCounts, elapsedMs: ev.elapsedMs };
412
- progressEvents.push({ phase: 'final', count: ev.results.length, elapsedMs: ev.elapsedMs });
413
- }
414
- else if (ev.phase === 'provider') {
415
- progressEvents.push({ phase: 'provider', providerName: ev.providerName, count: ev.results.length, durationMs: ev.durationMs });
416
- }
417
- else if (ev.phase === 'fused') {
418
- progressEvents.push({ phase: 'fused', count: ev.results.length });
419
- }
420
- else if (ev.phase === 'reranked') {
421
- progressEvents.push({ phase: 'reranked', rerankerName: ev.rerankerName, count: ev.results.length });
422
532
  }
423
533
  else if (ev.phase === 'error') {
424
534
  errorMsg = ev.error;
425
- progressEvents.push({ phase: 'error', error: ev.error });
426
535
  }
536
+ const progress = this.progressEventFor(ev, input.audience !== undefined);
537
+ if (progress)
538
+ progressEvents.push(progress);
427
539
  }
428
540
  if (errorMsg || !finalEvent) {
429
541
  return { ok: false, result: this.createErrorResult(errorMsg ?? 'Stream completed without a final event', 'SEARCH_FAILED') };
@@ -438,17 +550,42 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
438
550
  };
439
551
  return { ok: true, sr, progressEvents };
440
552
  }
553
+ /**
554
+ * One streamed event as a `ProgressEvents` entry, or null when it is left out. A 'final' event carries only its
555
+ * count (the results are the Results output). A 'provider' event carries a count, never the rows — and that count
556
+ * precedes the permission and audience passes, so it is the caller's unfiltered reach: under an audience (`!== undefined`
557
+ * at the call, so a malformed one counts) provider events are left out entirely, as `SourceCounts` are.
558
+ */
559
+ progressEventFor(ev, underAudience) {
560
+ switch (ev.phase) {
561
+ case 'final':
562
+ return { phase: 'final', count: ev.results.length, elapsedMs: ev.elapsedMs };
563
+ case 'provider':
564
+ return underAudience ? null : { phase: 'provider', providerName: ev.providerName, count: ev.resultCount, durationMs: ev.durationMs };
565
+ case 'fused':
566
+ return { phase: 'fused', count: ev.results.length };
567
+ case 'reranked':
568
+ return { phase: 'reranked', rerankerName: ev.rerankerName, count: ev.results.length };
569
+ case 'error':
570
+ return { phase: 'error', error: ev.error };
571
+ default:
572
+ return null;
573
+ }
574
+ }
441
575
  /**
442
576
  * Step 5 helper — pack the SearchResult into the action's output
443
577
  * envelope (Results + counts + scope echo + optional ProgressEvents).
444
578
  */
445
- buildSuccessResult(sr, scope, scopeID, progressEvents) {
579
+ buildSuccessResult(sr, scope, scopeID, progressEvents, withholdSourceCounts) {
446
580
  const formatted = this.formatResults(sr.Results);
581
+ // SourceCounts are counted before the permission and audience passes, so they reveal the caller's
582
+ // unfiltered reach: never shown to a room.
583
+ const sourceCounts = withholdSourceCounts ? [] : [{ Name: "SourceCounts", Value: sr.SourceCounts, Type: "Output" }];
447
584
  const outputParams = [
448
585
  { Name: "Results", Value: formatted, Type: "Output" },
449
586
  { Name: "TotalCount", Value: sr.TotalCount, Type: "Output" },
450
587
  { Name: "ElapsedMs", Value: sr.ElapsedMs, Type: "Output" },
451
- { Name: "SourceCounts", Value: sr.SourceCounts, Type: "Output" },
588
+ ...sourceCounts,
452
589
  { Name: "ScopeID_Resolved", Value: scopeID ?? null, Type: "Output" },
453
590
  { Name: "ScopeName_Resolved", Value: scope?.Name ?? "Global", Type: "Output" }
454
591
  ];
@@ -555,11 +692,13 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
555
692
  * action call. A named skill the run never activated is REFUSED — inside a Loop agent this parameter
556
693
  * is written by the model, and a model must not be able to widen its own reach by naming a skill —
557
694
  * and, when exactly one skill is active and none is named, it becomes the principal without the
558
- * model having to say so. Several active and none named: no principal (logged as verbose). Outside
559
- * a run (no ActiveSkillIDs on the context) the explicit parameter is the only source, unchanged.
695
+ * model having to say so. Several active and none named: no principal (logged as verbose). A dispatch
696
+ * that carries the run's `RunScope` but not its context (a runtime action's bridge call) has no list
697
+ * of active skills to trust, so it counts as a run with none active: a named skill is refused. Outside
698
+ * a run (no RunScope, no ActiveSkillIDs) the explicit parameter is the only source, unchanged.
560
699
  */
561
700
  resolveSkillPrincipalID(params) {
562
- const activeInRun = this.readActiveSkillIDs(params);
701
+ const activeInRun = this.readActiveSkillIDs(params) ?? (params.RunScope ? [] : undefined);
563
702
  const named = this.getStringParam(params, "aiskillid");
564
703
  if (!activeInRun)
565
704
  return { skillID: named };
@@ -664,6 +803,112 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
664
803
  return null;
665
804
  }
666
805
  }
806
+ // ─── Tenant: PrimaryScopeRecordID + SecondaryScopes ────────────────
807
+ /**
808
+ * Step 1c — resolve the tenant and secondary scopes ({@link resolveTenant}) and turn a refusal into the caller's
809
+ * result. A malformed `SecondaryScopes` is `INVALID_PARAM`. A tenant or secondary value the run does not carry is
810
+ * `INVALID_PARAM` too, and also a `Forbidden` search-log row: it is an attempt to search outside the run's tenant.
811
+ */
812
+ async resolveAndVetTenant(params, agent, skill, query, requestedScopeID, startTime) {
813
+ const resolution = this.resolveTenant(params);
814
+ if ('tenant' in resolution)
815
+ return { tenant: resolution.tenant };
816
+ if ('malformed' in resolution)
817
+ return { result: this.createErrorResult(resolution.malformed, 'INVALID_PARAM') };
818
+ await SearchEngine.Instance.LogForbiddenSearch({
819
+ Query: query,
820
+ ScopeIDs: requestedScopeID ? [requestedScopeID] : undefined,
821
+ FailureReason: resolution.audit.substring(0, 500),
822
+ StartTime: startTime,
823
+ ContextUser: params.ContextUser,
824
+ AIAgentID: agent.ID,
825
+ AISkillID: skill?.ID ?? null,
826
+ // The row belongs to the run's tenant (a refusal happens only inside a run); the named one is in the reason.
827
+ PrimaryScopeRecordID: params.RunScope ? this.runTenantID(params.RunScope) ?? null : null,
828
+ });
829
+ return { result: this.createErrorResult(resolution.forbidden, 'INVALID_PARAM') };
830
+ }
831
+ /**
832
+ * The tenant (`PrimaryScopeRecordID`) and secondary scopes this search runs under — used for BOTH the permission
833
+ * decision and the search. THE RUN IS THE AUTHORITY inside an agent run (`params.RunScope`, stamped by BaseAgent
834
+ * on every dispatch), where these parameters are model-written, as `AISkillID` is bound to the run's skills:
835
+ * - a missing `PrimaryScopeRecordID` defaults to the run's; one that differs from the run's (case-insensitively),
836
+ * or any value at all when the run has no tenant, is refused;
837
+ * - `SecondaryScopes` may restate a key the run sets only with an equal value, and the run's value is used; a key
838
+ * the run does not set is added, as outside a run (the scope's dimension trust rules still bound it).
839
+ * Outside a run (no `RunScope`) both parameters are used as given. A malformed `SecondaryScopes` is refused either way.
840
+ */
841
+ resolveTenant(params) {
842
+ const parsed = this.parseSecondaryScopes(params);
843
+ if ('malformed' in parsed)
844
+ return parsed;
845
+ const named = this.getStringParam(params, "primaryscoperecordid");
846
+ const run = params.RunScope;
847
+ if (!run)
848
+ return { tenant: { primaryScopeRecordID: named, secondaryScopes: parsed.value } };
849
+ const runTenant = this.runTenantID(run);
850
+ if (named && !(runTenant && UUIDsEqual(named, runTenant)))
851
+ return this.tenantRefusal(named, runTenant);
852
+ const secondary = this.mergeRunSecondaryScopes(run.SecondaryScopes ?? undefined, parsed.value);
853
+ if ('forbidden' in secondary)
854
+ return secondary;
855
+ return { tenant: { primaryScopeRecordID: runTenant, secondaryScopes: secondary.value } };
856
+ }
857
+ /**
858
+ * The refusal of a model-named tenant the run does not carry. The caller is told exactly what to do — inside an
859
+ * agent run the tenant comes from the run, so omit `PrimaryScopeRecordID` — and never the run's own tenant; the
860
+ * audit row names both.
861
+ */
862
+ tenantRefusal(named, runTenant) {
863
+ const why = runTenant
864
+ ? `PrimaryScopeRecordID '${named}' is not this agent run's tenant.`
865
+ : `PrimaryScopeRecordID '${named}' was given, but this agent run is not scoped to a tenant.`;
866
+ return {
867
+ forbidden: `${why} Inside an agent run the tenant comes from the run — omit PrimaryScopeRecordID`
868
+ + `${runTenant ? " and the run's tenant applies" : ''}; never pass one.`,
869
+ audit: `Refused a PrimaryScopeRecordID the agent run does not carry: '${named}' (the run is scoped to `
870
+ + `${runTenant ? `'${runTenant}'` : 'no tenant'}).`,
871
+ };
872
+ }
873
+ /** The run's tenant as a non-blank string, or `undefined` when the run has none. */
874
+ runTenantID(run) {
875
+ const id = run.PrimaryScopeRecordID;
876
+ return typeof id === 'string' && id.trim().length > 0 ? id.trim() : undefined;
877
+ }
878
+ /**
879
+ * The run's secondary scopes plus the caller's: a key the run sets keeps the run's value and may be restated only
880
+ * with an equal one ({@link scopeValuesEqual}); a key it does not set is added.
881
+ */
882
+ mergeRunSecondaryScopes(run, named) {
883
+ const runEntries = Object.entries(run ?? {});
884
+ const added = [];
885
+ for (const [key, value] of Object.entries(named ?? {})) {
886
+ const runEntry = runEntries.find(([runKey]) => runKey === key);
887
+ if (!runEntry) {
888
+ added.push([key, value]);
889
+ }
890
+ else if (!this.scopeValuesEqual(runEntry[1], value)) {
891
+ return {
892
+ forbidden: `SecondaryScopes '${key}' differs from this agent run's value for it. Inside an agent run the run's `
893
+ + `dimensions come from the run — omit '${key}' from SecondaryScopes and the run's value applies.`,
894
+ audit: `Refused a SecondaryScopes value the agent run does not carry: '${key}' = ${JSON.stringify(value)} `
895
+ + `(the run has ${JSON.stringify(runEntry[1])}).`,
896
+ };
897
+ }
898
+ }
899
+ const merged = [...runEntries, ...added];
900
+ return { value: merged.length > 0 ? Object.fromEntries(merged) : undefined };
901
+ }
902
+ /** Whether a restated secondary value matches the run's: text compared case-insensitively, arrays as sets. */
903
+ scopeValuesEqual(runValue, named) {
904
+ if (!Array.isArray(runValue) || !Array.isArray(named)) {
905
+ return !Array.isArray(runValue) && !Array.isArray(named) && UUIDsEqual(String(runValue), String(named));
906
+ }
907
+ const normalized = (values) => values.map(v => NormalizeUUID(v)).sort();
908
+ const left = normalized(runValue);
909
+ const right = normalized(named);
910
+ return left.length === right.length && left.every((v, i) => v === right[i]);
911
+ }
667
912
  // ─── Result formatting ─────────────────────────────────────────────
668
913
  formatResults(items) {
669
914
  return items.map(item => ({
@@ -699,43 +944,54 @@ let ScopedSearchAction = class ScopedSearchAction extends BaseAction {
699
944
  return value.length > 0 ? value : undefined;
700
945
  }
701
946
  /**
702
- * Parse the optional SecondaryScopes input. Accepts a JSON string
703
- * containing a flat object of dimension keys to values. Values are
704
- * passed through verbatim; the SearchEngine's Nunjucks render handles
705
- * type coercion when interpolating into MetadataFilter / ExtraFilter
706
- * templates. Malformed input is logged and treated as undefined rather
707
- * than failing the whole search — a stray bad payload shouldn't kill
708
- * an otherwise-valid query.
947
+ * Parse the optional `SecondaryScopes` input: a JSON object string, or an object passed as is, of dimension keys
948
+ * to values (`string | number | boolean | string[]`). Absent or blank is no secondary scopes. Anything else is
949
+ * REFUSED, not dropped: dropping a dimension runs the search without it, wider than the caller asked for.
709
950
  */
710
951
  parseSecondaryScopes(params) {
711
- const raw = this.getStringParam(params, "secondaryscopes");
712
- if (!raw)
713
- return undefined;
714
- let parsed;
715
- try {
716
- parsed = JSON.parse(raw);
952
+ const raw = this.readSecondaryScopesInput(params);
953
+ if ('malformed' in raw)
954
+ return raw;
955
+ if (raw.value === undefined)
956
+ return { value: undefined };
957
+ if (!IsPlainObject(raw.value)) {
958
+ return { malformed: `SecondaryScopes is ${this.describeScopeValue(raw.value)}, not an object. ${SECONDARY_SCOPES_SHAPE}` };
717
959
  }
718
- catch (e) {
719
- LogError(`ScopedSearchAction: SecondaryScopes was not valid JSON; ignoring: ${e instanceof Error ? e.message : String(e)}`);
720
- return undefined;
960
+ const entries = Object.entries(raw.value);
961
+ const valid = entries.filter((entry) => this.isSecondaryScopeValue(entry[1]));
962
+ const bad = entries.find(([, value]) => !this.isSecondaryScopeValue(value));
963
+ if (bad) {
964
+ return { malformed: `SecondaryScopes key '${bad[0]}' has an unsupported value (${this.describeScopeValue(bad[1])}). `
965
+ + SECONDARY_SCOPES_SHAPE };
721
966
  }
722
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
723
- LogError(`ScopedSearchAction: SecondaryScopes must be a JSON object, got ${Array.isArray(parsed) ? 'array' : typeof parsed} — ignoring.`);
724
- return undefined;
967
+ // fromEntries defines own properties, so a '__proto__' key stays a plain key rather than a prototype.
968
+ return { value: valid.length > 0 ? Object.fromEntries(valid) : undefined };
969
+ }
970
+ /** The raw `SecondaryScopes` input: an object as passed, a JSON string parsed; `undefined` when absent or blank. */
971
+ readSecondaryScopesInput(params) {
972
+ const param = params.Params.find(p => p.Name.trim().toLowerCase() === 'secondaryscopes');
973
+ const value = param?.Value;
974
+ if (value === undefined || value === null)
975
+ return { value: undefined };
976
+ if (typeof value !== 'string')
977
+ return { value };
978
+ if (value.trim().length === 0)
979
+ return { value: undefined };
980
+ try {
981
+ const parsed = JSON.parse(value);
982
+ return { value: parsed };
725
983
  }
726
- // Validate each value against SecondaryScopeValue = string | number | boolean | string[].
727
- // Drop incompatible entries (with a log) rather than failing the whole call — partial
728
- // context is more useful than no context.
729
- const cleaned = {};
730
- for (const [key, value] of Object.entries(parsed)) {
731
- if (this.isSecondaryScopeValue(value)) {
732
- cleaned[key] = value;
733
- }
734
- else {
735
- LogError(`ScopedSearchAction: SecondaryScopes key '${key}' has unsupported value type (${Array.isArray(value) ? 'mixed-array' : typeof value}); skipping.`);
736
- }
984
+ catch (e) {
985
+ return { malformed: `SecondaryScopes is not valid JSON (${e instanceof Error ? e.message : String(e)}). ${SECONDARY_SCOPES_SHAPE}` };
737
986
  }
738
- return Object.keys(cleaned).length > 0 ? cleaned : undefined;
987
+ }
988
+ /** A short, value-free description of an input's shape for an error message. */
989
+ describeScopeValue(value) {
990
+ if (value === null)
991
+ return 'null';
992
+ if (Array.isArray(value))
993
+ return 'an array';
994
+ return typeof value === 'object' ? 'an object' : `a ${typeof value}`;
739
995
  }
740
996
  /** Type guard mirroring `SecondaryScopeValue` from @memberjunction/ai-core-plus. */
741
997
  isSecondaryScopeValue(value) {