@lowdefy/api 6.0.0 → 7.0.0

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 (208) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +10 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -12,13 +12,17 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { type } from '@lowdefy/helpers';
15
+ */ import { normalizeCaller, type } from '@lowdefy/helpers';
16
16
  // Tries the configured API auth strategies in config order; the first
17
17
  // verifier match wins. A strategy caller is a config-derived, org-less
18
18
  // principal: roles are the strategy's static grant unioned with any
19
19
  // claim-derived roles, and attributes are the static bag shallow-merged
20
20
  // with claim-mapped values (claim wins), so _user.attributes reads the same
21
21
  // for session and strategy callers.
22
+ //
23
+ // normalizeCaller gives it the same snake_case key shape as the session
24
+ // caller, over the verifier's user fields as well as the two stamped here -
25
+ // app config reads one caller shape whichever branch resolved it.
22
26
  async function resolveStrategyCaller({ headers, logger, strategies }) {
23
27
  for (const strategy of strategies ?? []){
24
28
  const match = await strategy.verify({
@@ -43,13 +47,13 @@ async function resolveStrategyCaller({ headers, logger, strategies }) {
43
47
  authMethod: strategy.type,
44
48
  strategyId: strategy.id
45
49
  }, `Request authenticated by auth strategy "${strategy.id}" (${strategy.type}).`);
46
- return {
50
+ return normalizeCaller({
47
51
  ...match.user,
48
52
  authMethod: strategy.type,
49
53
  strategyId: strategy.id,
50
54
  roles,
51
55
  attributes
52
- };
56
+ });
53
57
  }
54
58
  return null;
55
59
  }
@@ -0,0 +1,23 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ // Each script and style element in app.html.appendHead / appendBody gets the
16
+ // render's nonce, so author snippets keep running under the policy. Matching
17
+ // whole elements (up to the first closing tag, as the HTML parser does) leaves
18
+ // "<script" text inside a script body untouched.
19
+ const ELEMENT_PATTERN = /<(script|style)\b([^>]*)>([\s\S]*?)<\/\1(\s*)>/gi;
20
+ function addNonceToElements({ html, nonce }) {
21
+ return html.replace(ELEMENT_PATTERN, (_, tag, attributes, body, closingSpace)=>`<${tag} nonce="${nonce}"${attributes}>${body}</${tag}${closingSpace}>`);
22
+ }
23
+ export default addNonceToElements;
@@ -0,0 +1,45 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import crypto from 'node:crypto';
16
+ import getWebSocketSources from './getWebSocketSources.js';
17
+ // Builds the header for one page render from the policy the build resolved
18
+ // (build/security.json). Each call draws a new 128-bit nonce, which the page's
19
+ // inline scripts and styles carry.
20
+ function createContentSecurityPolicy({ policy, requestUrl, allowWebSocket }) {
21
+ const nonce = crypto.randomBytes(16).toString('base64');
22
+ const directives = Object.entries(policy.directives).map(([directive, sources])=>{
23
+ const directiveSources = [
24
+ ...sources
25
+ ];
26
+ if (policy.nonceDirectives.includes(directive)) {
27
+ directiveSources.push(`'nonce-${nonce}'`);
28
+ }
29
+ if (directive === 'connect-src' && allowWebSocket) {
30
+ directiveSources.push(...getWebSocketSources({
31
+ requestUrl
32
+ }));
33
+ }
34
+ return [
35
+ directive,
36
+ ...directiveSources
37
+ ].join(' ');
38
+ });
39
+ return {
40
+ name: policy.reportOnly ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy',
41
+ nonce,
42
+ value: directives.join('; ')
43
+ };
44
+ }
45
+ export default createContentSecurityPolicy;
@@ -0,0 +1,36 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ // The page's websocket (and in dev, Vite's hot reload socket) connects to the host the page
16
+ // was served from. Older browsers do not match 'self' against ws: and wss:, so the policy
17
+ // names that host. ws: is listed only when the request itself arrived over plain http.
18
+ // A host that is not a plain hostname, IPv4 or bracketed IPv6 address with an optional
19
+ // port is not written into the header.
20
+ const HOST_PATTERN = /^([a-z0-9.-]+|\[[0-9a-f:.]+\])(:\d+)?$/i;
21
+ function getWebSocketSources({ requestUrl }) {
22
+ const { host, protocol } = new URL(requestUrl);
23
+ if (!HOST_PATTERN.test(host)) {
24
+ return [];
25
+ }
26
+ if (protocol === 'http:') {
27
+ return [
28
+ `ws://${host}`,
29
+ `wss://${host}`
30
+ ];
31
+ }
32
+ return [
33
+ `wss://${host}`
34
+ ];
35
+ }
36
+ export default getWebSocketSources;
@@ -0,0 +1,99 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import { EmailOTPEmail, InvitationEmail, MagicLinkEmail, ResetPasswordEmail, VerifyEmail, interpolateProperties, renderEmail } from '@lowdefy/email-templates';
18
+ import getNotificationConfig from '../routes/notifications/getNotificationConfig.js';
19
+ import resolveThemeLogo from './resolveThemeLogo.js';
20
+ const stockTemplates = {
21
+ verifyEmail: VerifyEmail,
22
+ resetPassword: ResetPasswordEmail,
23
+ magicLink: MagicLinkEmail,
24
+ invitation: InvitationEmail,
25
+ emailOTP: EmailOTPEmail
26
+ };
27
+ // Single render path for the auth email flows. Resolves the flow's template
28
+ // (a stock component by default, or an app-configured override notification when
29
+ // auth.email.templates[flow] names one), applies the app.email brand, and returns
30
+ // { subject, html, text }. Pure render — it never sends.
31
+ async function renderAuthEmail({ flow, vars, authEmailConfig, baseURL, context }) {
32
+ const app = await context.readConfigFile('app.json') ?? {};
33
+ const basePath = context.config?.basePath ?? '';
34
+ // baseURL is the pinned origin the caller resolved; without a usable origin
35
+ // string relative logos cannot be fetched by an email client, so they drop.
36
+ const serverUrl = type.isString(baseURL) ? baseURL : undefined;
37
+ const notificationId = authEmailConfig?.templates?.[flow];
38
+ if (type.isString(notificationId)) {
39
+ const notificationConfig = await getNotificationConfig(context, {
40
+ notificationId
41
+ });
42
+ const Template = context.notifications?.[notificationConfig.type];
43
+ if (!Template) {
44
+ throw new ConfigError(`Notification template type "${notificationConfig.type}" can not be found.`, {
45
+ configKey: notificationConfig['~k']
46
+ });
47
+ }
48
+ // Resolve after the merge so a per-notification theme.logo override also
49
+ // resolves; precedence stays notification theme over app.email.
50
+ const theme = resolveThemeLogo({
51
+ theme: {
52
+ ...app.email ?? {},
53
+ ...notificationConfig.theme ?? {}
54
+ },
55
+ serverUrl,
56
+ basePath
57
+ });
58
+ const interpolated = interpolateProperties({
59
+ properties: notificationConfig.properties,
60
+ data: vars,
61
+ markdownProperties: Template.markdownProperties ?? []
62
+ });
63
+ const { html, text } = await renderEmail({
64
+ Template,
65
+ properties: interpolated,
66
+ data: vars,
67
+ theme,
68
+ links: {}
69
+ });
70
+ return {
71
+ subject: interpolated.subject,
72
+ html,
73
+ text
74
+ };
75
+ }
76
+ const Template = stockTemplates[flow];
77
+ if (!Template) {
78
+ throw new ConfigError(`Unknown auth email flow "${flow}".`);
79
+ }
80
+ const theme = resolveThemeLogo({
81
+ theme: app.email ?? {},
82
+ serverUrl,
83
+ basePath
84
+ });
85
+ const { html, text } = await renderEmail({
86
+ Template,
87
+ properties: vars,
88
+ data: vars,
89
+ theme,
90
+ links: {}
91
+ });
92
+ const subject = type.isFunction(Template.subject) ? Template.subject(vars) : Template.subject;
93
+ return {
94
+ subject,
95
+ html,
96
+ text
97
+ };
98
+ }
99
+ export default renderAuthEmail;
package/dist/index.js CHANGED
@@ -12,27 +12,44 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import buildEndpointResult from './response/buildEndpointResult.js';
15
+ */ import addNonceToElements from './csp/addNonceToElements.js';
16
+ import buildEndpointResult from './response/buildEndpointResult.js';
16
17
  import callAgent from './routes/agent/callAgent.js';
17
18
  import callEndpoint from './routes/endpoints/callEndpoint.js';
18
19
  import getEndpointConfig from './routes/endpoints/getEndpointConfig.js';
19
20
  import callRequest from './routes/request/callRequest.js';
20
21
  import createApiContext from './context/createApiContext.js';
22
+ import createAsMetadataHandler from './routes/auth/createAsMetadataHandler.js';
21
23
  import createChannelRegistry from './routes/websocket/createChannelRegistry.js';
24
+ import createContentSecurityPolicy from './csp/createContentSecurityPolicy.js';
22
25
  import createMcpServer from './routes/mcp/createMcpServer.js';
26
+ import createRequestSignal from './context/createRequestSignal.js';
27
+ import createSystemContext from './context/createSystemContext.js';
23
28
  import createWebSocketConnection from './routes/websocket/createWebSocketConnection.js';
24
- import createSessionCallback from './routes/auth/callbacks/createSessionCallback.js';
25
- import getAuthConfig from './routes/auth/getAuthConfig.js';
29
+ import createWireProjection from './response/createWireProjection.js';
26
30
  import getAuthStrategies from './routes/auth/strategies/getAuthStrategies.js';
31
+ import getBetterAuth from './routes/auth/getBetterAuth.js';
32
+ import { MCP_OAUTH_SCOPES } from './routes/auth/getBetterAuthConfig.js';
33
+ import handleAuthRequest from './routes/auth/handleAuthRequest.js';
34
+ import { getAsIssuer, getMcpResourceMetadataUri, getMcpResourceUri } from './routes/mcp/getMcpUri.js';
35
+ import getMcpResourceBinding, { registerMcpResourceBinding } from './routes/mcp/getMcpResourceBinding.js';
36
+ import { ensureMcpOauthResource } from './routes/mcp/oauthResourceLifecycle.js';
27
37
  import getHomeAndMenus from './routes/rootConfig/getHomeAndMenus.js';
28
- import resolveStrategyCaller from './context/resolveStrategyCaller.js';
29
38
  import getPageConfig from './routes/page/getPageConfig.js';
30
39
  import getRootConfig from './routes/rootConfig/getRootConfig.js';
40
+ import isSameOriginRequest from './context/isSameOriginRequest.js';
41
+ import isWebSocketOriginAllowed from './context/isWebSocketOriginAllowed.js';
31
42
  import logClientError from './routes/log/logClientError.js';
43
+ import normalizeInjectedCaller from './context/normalizeInjectedCaller.js';
44
+ import parseRequestBody from './context/parseRequestBody.js';
32
45
  import redactErrorResponse from './response/redactErrorResponse.js';
33
46
  import redactResponse from './response/redactResponse.js';
47
+ import resolveAuthentication from './context/resolveAuthentication.js';
48
+ import resolvePinnedOrganization from './routes/auth/organizations/resolvePinnedOrganization.js';
49
+ import resolveTenantPreflight, { getTenantIntegrityStatus } from './routes/connections/resolveTenantPreflight.js';
34
50
  import forwardScheduledEndpoint from './routes/endpoints/forwardScheduledEndpoint.js';
51
+ import acceptDetachedEndpoint from './routes/endpoints/acceptDetachedEndpoint.js';
35
52
  import runDetachedEndpoint from './routes/endpoints/runDetachedEndpoint.js';
36
53
  import runWebhookEndpoint from './routes/endpoints/runWebhookEndpoint.js';
37
54
  import runScheduledEndpoint from './routes/endpoints/runScheduledEndpoint.js';
38
- export { buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createChannelRegistry, createMcpServer, createSessionCallback, createWebSocketConnection, getAuthConfig, getAuthStrategies, getHomeAndMenus, getPageConfig, getRootConfig, logClientError, redactErrorResponse, redactResponse, resolveStrategyCaller, forwardScheduledEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
55
+ export { addNonceToElements, buildEndpointResult, callAgent, callEndpoint, getEndpointConfig, callRequest, createApiContext, createAsMetadataHandler, createChannelRegistry, createContentSecurityPolicy, createMcpServer, createRequestSignal, createSystemContext, createWebSocketConnection, createWireProjection, ensureMcpOauthResource, getAsIssuer, getAuthStrategies, getBetterAuth, MCP_OAUTH_SCOPES, getHomeAndMenus, handleAuthRequest, getMcpResourceBinding, getMcpResourceMetadataUri, getMcpResourceUri, registerMcpResourceBinding, getPageConfig, getRootConfig, isSameOriginRequest, isWebSocketOriginAllowed, logClientError, normalizeInjectedCaller, parseRequestBody, redactErrorResponse, redactResponse, resolveAuthentication, resolvePinnedOrganization, getTenantIntegrityStatus, resolveTenantPreflight, forwardScheduledEndpoint, acceptDetachedEndpoint, runDetachedEndpoint, runWebhookEndpoint, runScheduledEndpoint };
@@ -17,7 +17,9 @@ import redactResponse from './redactResponse.js';
17
17
  // The wire object every endpoint route returns after running its routine. One
18
18
  // function rather than a copy of the same return statement per route, so the
19
19
  // `response` field cannot end up policed differently from the `error` field beside
20
- // it - see redactResponse for why the response needs the policy at all.
20
+ // it - see redactResponse for why the response needs the policy at all. `error` is
21
+ // redactErrorResponse's error payload, so in dev it carries `devError`; `response`
22
+ // never does.
21
23
  function buildEndpointResult(context, { error, response, status }) {
22
24
  const success = ![
23
25
  'error',
@@ -0,0 +1,88 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { lowdefyErrorNames, readErrorCodes } from '@lowdefy/errors';
16
+ import { translate } from '@lowdefy/helpers';
17
+ // The framework writes these messages to reveal nothing, and clients branch on
18
+ // them, so they keep their text where every other non-author error does not.
19
+ const AUTH_REFUSAL_NAMES = new Set([
20
+ 'AuthenticationError',
21
+ 'AuthorizationError',
22
+ 'TwoFactorEnrolmentRequiredError'
23
+ ]);
24
+ // The client-bound error policy, as an allowlist. Passed to serializer.serialize
25
+ // as `projectError`, so it runs at every error node the walk emits - the cause
26
+ // chain, an Error-valued own property, an Error nested in a response value - and
27
+ // cannot become depth-limited.
28
+ //
29
+ // Only the author's message crosses. A library's message embeds whatever the
30
+ // library saw - URLs with credentials, SQL, hostnames - so every other error
31
+ // becomes one translated generic message plus the fields client config branches
32
+ // on. The full error stays in the server log, and in dev reaches the developer
33
+ // through `devError`, which config never reads.
34
+ //
35
+ // The context is optional: a websocket broadcast has no single request, so it
36
+ // passes no `rid`, and the server error handler can run before any request
37
+ // context exists.
38
+ function createWireProjection(context) {
39
+ const requestId = context?.rid;
40
+ const genericMessage = translate({
41
+ key: 'server.genericError',
42
+ i18n: context?.i18n
43
+ });
44
+ return function project(err) {
45
+ // A PluginError defaults configKey to null; the walk only drops undefined.
46
+ const configKey = err.configKey ?? undefined;
47
+ // Keyed on the name rather than instanceof: the error may come from another
48
+ // copy of @lowdefy/errors or from a serializer round trip, where the class
49
+ // identity is gone but the name survives. The cause is returned raw so the
50
+ // walk projects it too - an Error cause takes the generic shape, and a
51
+ // non-Error cause is author data cleaned as a value.
52
+ if (err.name === 'UserError') {
53
+ return {
54
+ name: err.name,
55
+ message: err.message,
56
+ cause: err.cause,
57
+ metaData: err.metaData,
58
+ blockId: err.blockId,
59
+ pageId: err.pageId,
60
+ isReject: err.isReject,
61
+ configKey,
62
+ // Not read from the node: a caught error rebuilt for `_error` keeps only
63
+ // its class, and without the flag the client wraps a rethrown UserError
64
+ // in an ActionError and reports it back to the server a second time.
65
+ isLowdefyError: true,
66
+ handled: err.handled,
67
+ requestId
68
+ };
69
+ }
70
+ const { code, statusCode } = readErrorCodes(err);
71
+ return {
72
+ // A foreign class name can itself say which library or driver failed.
73
+ name: lowdefyErrorNames.has(err.name) ? err.name : 'Error',
74
+ message: AUTH_REFUSAL_NAMES.has(err.name) ? err.message : genericMessage,
75
+ code,
76
+ statusCode,
77
+ configKey,
78
+ requestId,
79
+ // The client revives errors without running a constructor, so this flag
80
+ // exists there only if the wire carries it. Without it the action runner
81
+ // wraps the error in a new ActionError without `handled`, POSTs it back to
82
+ // /api/client-error, and the server logs and reports it a second time.
83
+ isLowdefyError: true,
84
+ handled: err.handled
85
+ };
86
+ };
87
+ }
88
+ export default createWireProjection;
@@ -0,0 +1,35 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import createWireProjection from './createWireProjection.js';
17
+ // The text an MCP tool caller reads when an endpoint fails. A dev MCP client is a
18
+ // coding agent, a dev tool: the message carries the resolved config location and
19
+ // any hint so it can go straight to the yaml. A prod MCP client is an end-user
20
+ // reader and gets the wire message - the author's message or the generic one -
21
+ // so no library text or server path reaches it.
22
+ function formatErrorForAgent(context, error) {
23
+ if (context.mode !== 'dev') {
24
+ return createWireProjection(context)(error).message;
25
+ }
26
+ let text = error.message;
27
+ if (!type.isNone(error.source)) {
28
+ text = `${text} (at ${error.source})`;
29
+ }
30
+ if (!type.isNone(error.hint)) {
31
+ text = `${text} Hint: ${error.hint}`;
32
+ }
33
+ return text;
34
+ }
35
+ export default formatErrorForAgent;
@@ -16,13 +16,12 @@
16
16
  import { type } from '@lowdefy/helpers';
17
17
  // extractErrorProps emits a nested error as a plain props object, not as a second
18
18
  // '~e' wrapper, so an error node is recognised by its shape. Keying on the shape
19
- // rather than on a map of where errors can appear is deliberate: re-deriving those
20
- // positions is the mistake the walk-level omit exists to avoid, and this predicate
21
- // still visits every position.
19
+ // rather than on a map of where errors can appear means every position is visited
20
+ // without re-deriving where the walk puts errors.
22
21
  //
23
- // The check matters because the payload also carries author-written data the policy
24
- // deliberately preserves - a UserError's non-Error cause, its metaData - and a
25
- // `source` key inside those belongs to the app, not to us.
22
+ // The check matters because the payload also carries author-written data - a
23
+ // UserError's non-Error cause, its metaData - and a `source` key inside those
24
+ // belongs to the app, not to us.
26
25
  function isErrorNode(value) {
27
26
  return type.isString(value.name) && type.isString(value.message);
28
27
  }
@@ -43,17 +42,15 @@ function stripConfigDirectory(value, prefix) {
43
42
  }
44
43
  Object.values(value).forEach((child)=>stripConfigDirectory(child, prefix));
45
44
  }
46
- // Guarantees `source` reaches a client config-relative, never as an absolute server
47
- // path. resolveConfigLocation makes it absolute whenever the context carries a
48
- // configDirectory - server-dev and server-e2e do, and production happens not to
49
- // today by omission rather than by invariant, which is the drift this closes.
45
+ // Makes `source` in the dev-only `devError` config-relative, never an absolute
46
+ // server path, so the dev tools show the path the developer knows. The wire error
47
+ // carries no `source` at all. resolveConfigLocation makes it absolute whenever the
48
+ // context carries a configDirectory, which server-dev does.
50
49
  //
51
50
  // A rewrite rather than an omission, and it needs the context, so it runs as a pass
52
51
  // over the serialized payload instead of inside the walk.
53
52
  function normalizeErrorSources(context, payload) {
54
- // errorHandler has an else branch for requests with no lowdefyContext, so a
55
- // missing context is a supported call - it only means no source to normalise.
56
- const configDirectory = context?.configDirectory;
53
+ const configDirectory = context.configDirectory;
57
54
  if (type.isNone(configDirectory)) return payload;
58
55
  // configDirectory is `LOWDEFY_DIRECTORY_CONFIG || process.cwd()` at every site
59
56
  // that sets it, so it may be relative or carry a trailing separator, while
@@ -13,18 +13,52 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { serializer, type } from '@lowdefy/helpers';
16
+ import createWireProjection from './createWireProjection.js';
16
17
  import normalizeErrorSources from './normalizeErrorSources.js';
17
- import omitErrorProps from './omitErrorProps.js';
18
- // Owns the serialization as well as the policy, so the policy cannot be forgotten:
19
- // no bare serializer.serialize(error) is left in response position to wrap. Every
20
- // route returning an error to a caller - any status, any transport - goes through
21
- // here or through buildEndpointResult.
18
+ // The one error payload every route and transport sends for a thrown error, at
19
+ // any status. Owning the serialization as well as the policy leaves no bare
20
+ // serializer.serialize(error) in response position for a caller to forget.
21
+ //
22
+ // `~e` is the wire error - identical in dev and prod, because it is what app
23
+ // config reads. In dev the payload also carries `devError`, the error as the dev
24
+ // terminal logs it, for the dev tools. It sits beside `~e` rather than inside it:
25
+ // the serializer's reviver replaces any object holding `~e` with its error, so a
26
+ // plain deserialize of the payload drops `devError` and config never sees it.
27
+ //
28
+ // `received` is left out of devError at every node: on the request path it is
29
+ // the evaluated request properties, resolved _secret values included, and the
30
+ // dev server can be reached over a LAN or tunnel. The terminal still logs it.
31
+ function projectDevError(err) {
32
+ const props = {
33
+ message: err.message,
34
+ name: err.name,
35
+ stack: err.stack,
36
+ cause: err.cause,
37
+ ...err
38
+ };
39
+ delete props.received;
40
+ return props;
41
+ }
22
42
  function redactErrorResponse(context, error) {
23
43
  // Endpoint routes serialize the error field on success too, where it is null.
24
44
  // Passing that through unchanged keeps them from emitting an empty {'~e'}.
25
45
  if (type.isNone(error)) return error;
26
- return normalizeErrorSources(context, serializer.serialize(error, {
27
- omitErrorProps
28
- }));
46
+ const payload = serializer.serialize(error, {
47
+ projectError: createWireProjection(context)
48
+ });
49
+ // The server error handler has no request context when it fails before the
50
+ // context middleware runs, so there is no mode to read and no devError.
51
+ if (context?.mode === 'dev') {
52
+ const full = serializer.serialize(error, {
53
+ projectError: projectDevError
54
+ });
55
+ payload.devError = normalizeErrorSources(context, {
56
+ '~e': {
57
+ ...full['~e'],
58
+ requestId: context.rid
59
+ }
60
+ });
61
+ }
62
+ return payload;
29
63
  }
30
64
  export default redactErrorResponse;
@@ -13,19 +13,26 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { serializer } from '@lowdefy/helpers';
16
- import normalizeErrorSources from './normalizeErrorSources.js';
17
- import omitErrorProps from './omitErrorProps.js';
16
+ import createWireProjection from './createWireProjection.js';
18
17
  // The response-value call shape, beside redactErrorResponse's error-only one.
19
18
  // A response is not an error, but makeReplacer wraps any Error it meets anywhere
20
- // in a value, so a response holding one is an error-serialization site too - the
21
- // grep that enumerated those sites could not see them, which is why this exists
22
- // as a function rather than as a rule to remember.
19
+ // in a value, so a response holding one is an error-serialization site too - a
20
+ // grep for serialize(error) cannot see those sites, which is why this exists as
21
+ // a function rather than as a rule to remember.
23
22
  //
24
- // Same policy as the error field, because it reaches the same audience: a browser
25
- // for a request or endpoint body, a third party for cron and detached.
23
+ // Same wire projection as the error field, because it reaches the same audience.
24
+ // No devError, in any mode: an Error in a response value is data the routine
25
+ // returned, not a failure of this request.
26
+ //
27
+ // A response built from config (a :return literal, a :set_state value read back)
28
+ // keeps the config's ~k, ~r and ~l markers as hidden properties. They are
29
+ // dropped here: the response is data, and a caller that is not the Lowdefy
30
+ // client (the third party calling a webhook endpoint, a dev tool, any HTTP
31
+ // client) reads the wire as it is.
26
32
  function redactResponse(context, response) {
27
- return normalizeErrorSources(context, serializer.serialize(response, {
28
- omitErrorProps
29
- }));
33
+ return serializer.serialize(response, {
34
+ projectError: createWireProjection(context),
35
+ skipMarkers: true
36
+ });
30
37
  }
31
38
  export default redactResponse;
@@ -12,17 +12,29 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { ConfigError } from '@lowdefy/errors';
16
- import { translate } from '@lowdefy/helpers';
17
- function authorizeAgent({ authorize, i18n, logger }, { agentConfig }) {
18
- if (!authorize(agentConfig)) {
15
+ */ import { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
+ import { translate, type } from '@lowdefy/helpers';
17
+ function authorizeAgent({ authorizeOutcome, i18n, logger, user }, { agentConfig }) {
18
+ const outcome = authorizeOutcome(agentConfig);
19
+ if (outcome !== 'allow') {
19
20
  logger.debug({
20
21
  event: 'debug_agent_authorize',
21
22
  authorized: false,
23
+ outcome,
22
24
  auth_config: agentConfig.auth
23
25
  });
26
+ if (outcome === 'enrol_required') {
27
+ // Reached only after the role check passed, so the caller is authorised and
28
+ // this reveals nothing about which agents exist.
29
+ throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for agent "${agentConfig.agentId}".`);
30
+ }
31
+ // Unauthenticated on a protected agent - 401 tells the caller to fix
32
+ // its credentials. Wrong roles stay opaque below.
33
+ if (type.isNone(user)) {
34
+ throw new AuthenticationError(`Authentication required for agent "${agentConfig.agentId}".`);
35
+ }
24
36
  // Same message as an unknown agentId so responses do not reveal which agents exist.
25
- throw new ConfigError(translate({
37
+ throw new AuthorizationError(translate({
26
38
  key: 'agent.runtime.agentNotFound',
27
39
  values: {
28
40
  agentId: agentConfig.agentId
@@ -12,12 +12,17 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
15
+ */ import collectChatFiles from './collectChatFiles.js';
16
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
16
17
  import prepareAgent from './prepareAgent.js';
17
- async function callAgent(context, { agentId, pageId, messages, conversationId, urlQuery, sharedState }) {
18
+ async function callAgent(context, { agentId, pageId, messages, conversationId, pathParams, urlQuery, sharedState, sharedStateReadOnly }) {
18
19
  const { logger } = context;
19
20
  context.pageId = pageId;
20
21
  context.evaluateOperators = createEvaluateOperators(context);
22
+ // A chat run is not cancelled when the client disconnects: it runs to its end so the
23
+ // onFinish hooks still persist the whole conversation, bounded by the agent's timeout
24
+ // and maxSteps. Its tool endpoints' requests are not cancelled either.
25
+ context.signal = undefined;
21
26
  logger.debug({
22
27
  event: 'debug_agent',
23
28
  agentId,
@@ -26,7 +31,9 @@ async function callAgent(context, { agentId, pageId, messages, conversationId, u
26
31
  const agentContext = {
27
32
  conversationId: conversationId ?? undefined,
28
33
  pageId,
34
+ pathParams: pathParams ?? {},
29
35
  sharedState: sharedState ?? {},
36
+ sharedStateReadOnly: sharedStateReadOnly ?? false,
30
37
  urlQuery: urlQuery ?? {},
31
38
  userId: context.user?.sub ?? context.user?.id ?? null
32
39
  };
@@ -34,6 +41,9 @@ async function callAgent(context, { agentId, pageId, messages, conversationId, u
34
41
  agentId,
35
42
  agentContext,
36
43
  endpointDepth: 0,
44
+ files: collectChatFiles({
45
+ messages
46
+ }),
37
47
  mode: 'chat'
38
48
  });
39
49
  // Call the agent resolver