@lowdefy/api 6.1.0 → 6.2.1

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.
@@ -25,15 +25,19 @@ import normalizeErrorSources from './normalizeErrorSources.js';
25
25
  // the serializer's reviver replaces any object holding `~e` with its error, so a
26
26
  // plain deserialize of the payload drops `devError` and config never sees it.
27
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.
28
+ // `received` is left out of devError at every node: it holds evaluated values,
29
+ // resolved _secret values included, and the dev server can be reached over a LAN
30
+ // or tunnel.
31
+ //
32
+ // A failed request's error carries the connection's error only as a summary, so no log writes
33
+ // the inputs a driver's error can hold; the dev tools get the connection's error itself, from
34
+ // the error's non-enumerable `devCause`.
31
35
  function projectDevError(err) {
32
36
  const props = {
33
37
  message: err.message,
34
38
  name: err.name,
35
39
  stack: err.stack,
36
- cause: err.cause,
40
+ cause: err.devCause ?? err.cause,
37
41
  ...err
38
42
  };
39
43
  delete props.received;
@@ -12,8 +12,10 @@
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 { type } from '@lowdefy/helpers';
16
+ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
16
17
  import prepareAgent from './prepareAgent.js';
18
+ import redactMessages from './redactMessages.js';
17
19
  async function callAgent(context, { agentId, pageId, messages, conversationId, urlQuery, sharedState }) {
18
20
  const { logger } = context;
19
21
  context.pageId = pageId;
@@ -36,12 +38,28 @@ async function callAgent(context, { agentId, pageId, messages, conversationId, u
36
38
  endpointDepth: 0,
37
39
  mode: 'chat'
38
40
  });
41
+ // Mask the user's text before the resolver hands it to the model, title generation, tools
42
+ // and hooks.
43
+ let agentMessages = messages;
44
+ if (!type.isNone(agentConfig.redact)) {
45
+ const redacted = redactMessages({
46
+ messages,
47
+ redact: resolverContext.evaluateOperators(agentConfig.redact),
48
+ configKey: agentConfig['~k']
49
+ });
50
+ agentMessages = redacted.messages;
51
+ logger.debug({
52
+ event: 'debug_agent_redact',
53
+ agentId,
54
+ replacements: redacted.counts
55
+ });
56
+ }
39
57
  // Call the agent resolver
40
58
  const { response } = await agentType.resolver({
41
59
  connection: connectionInstance,
42
60
  properties: {
43
61
  agent: agentConfig,
44
- messages
62
+ messages: agentMessages
45
63
  },
46
64
  context: resolverContext
47
65
  });
@@ -0,0 +1,136 @@
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
+ const DEFAULT_REPLACEMENT = '[removed]';
18
+ // The build checks a literal redact config; this checks it again after operators are
19
+ // evaluated, since a pattern an operator returns is only known now. Returns the patterns as
20
+ // { name, regex }, each regex global so a replace masks every match.
21
+ function buildPatterns({ redact, configKey }) {
22
+ if (!type.isObject(redact)) {
23
+ throw new ConfigError('Agent "redact" should be an object.', {
24
+ received: redact,
25
+ configKey
26
+ });
27
+ }
28
+ if (!type.isArray(redact.patterns) || redact.patterns.length === 0) {
29
+ throw new ConfigError('Agent "redact.patterns" should be a non-empty array.', {
30
+ received: redact.patterns,
31
+ configKey
32
+ });
33
+ }
34
+ return redact.patterns.map((entry, index)=>{
35
+ const { name, pattern, flags } = type.isString(entry) ? {
36
+ pattern: entry
37
+ } : entry ?? {};
38
+ const location = `redact.patterns[${index}]`;
39
+ if (!type.isString(pattern)) {
40
+ throw new ConfigError(`Agent "${location}.pattern" should be a string.`, {
41
+ received: pattern,
42
+ configKey
43
+ });
44
+ }
45
+ if (!type.isNone(name) && !type.isString(name)) {
46
+ throw new ConfigError(`Agent "${location}.name" should be a string.`, {
47
+ received: name,
48
+ configKey
49
+ });
50
+ }
51
+ if (!type.isNone(flags) && !type.isString(flags)) {
52
+ throw new ConfigError(`Agent "${location}.flags" should be a string.`, {
53
+ received: flags,
54
+ configKey
55
+ });
56
+ }
57
+ // With the sticky flag a global replace stops at the first gap between matches.
58
+ if (type.isString(flags) && flags.includes('y')) {
59
+ throw new ConfigError(`Agent "${location}.flags" should not include "y".`, {
60
+ received: flags,
61
+ configKey
62
+ });
63
+ }
64
+ const allFlags = (flags ?? '').includes('g') ? flags : `${flags ?? ''}g`;
65
+ let regex;
66
+ try {
67
+ regex = new RegExp(pattern, allFlags);
68
+ } catch (error) {
69
+ throw new ConfigError(`Agent "${location}" is not a valid regular expression: ${error.message}`, {
70
+ cause: error,
71
+ received: pattern,
72
+ configKey
73
+ });
74
+ }
75
+ // A pattern that matches empty text would put the replacement between every character.
76
+ if (regex.test('')) {
77
+ throw new ConfigError(`Agent "${location}" matches empty text.`, {
78
+ received: pattern,
79
+ configKey
80
+ });
81
+ }
82
+ regex.lastIndex = 0;
83
+ return {
84
+ name: name ?? location,
85
+ regex
86
+ };
87
+ });
88
+ }
89
+ // Masks every match of the agent's redact patterns in the text parts of the user's messages,
90
+ // before the model, title generation, tools and hooks see them. Every user message is masked,
91
+ // not only the last: the browser sends the whole conversation each turn. Assistant and tool
92
+ // messages, and file parts, are left as they are. The messages are the client's, not yet
93
+ // validated, so a malformed message or part is passed over here and refused by the agent's
94
+ // message validation. counts holds the replacements made per pattern name, never the text.
95
+ function redactMessages({ messages, redact, configKey }) {
96
+ const patterns = buildPatterns({
97
+ redact,
98
+ configKey
99
+ });
100
+ const replacement = redact.replacement ?? DEFAULT_REPLACEMENT;
101
+ if (!type.isString(replacement)) {
102
+ throw new ConfigError('Agent "redact.replacement" should be a string.', {
103
+ received: replacement,
104
+ configKey
105
+ });
106
+ }
107
+ const counts = {};
108
+ function maskText(text) {
109
+ let masked = text;
110
+ for (const { name, regex } of patterns){
111
+ masked = masked.replace(regex, ()=>{
112
+ counts[name] = (counts[name] ?? 0) + 1;
113
+ return replacement;
114
+ });
115
+ }
116
+ return masked;
117
+ }
118
+ const redacted = messages.map((message)=>{
119
+ if (message?.role !== 'user' || !type.isArray(message.parts)) return message;
120
+ return {
121
+ ...message,
122
+ parts: message.parts.map((part)=>{
123
+ if (part?.type !== 'text' || !type.isString(part.text)) return part;
124
+ return {
125
+ ...part,
126
+ text: maskText(part.text)
127
+ };
128
+ })
129
+ };
130
+ });
131
+ return {
132
+ messages: redacted,
133
+ counts
134
+ };
135
+ }
136
+ export default redactMessages;
@@ -27,12 +27,13 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
27
27
  context.endpointId = endpointId;
28
28
  context.pageId = pageId;
29
29
  context.evaluateOperators = createEvaluateOperators(context);
30
+ // Ids only: a payload can carry chat text or other personal information (an agent
31
+ // chat's save-thread call sends the whole thread), which no log level may hold.
30
32
  logger.debug({
31
33
  event: 'debug_endpoint',
32
34
  blockId,
33
35
  endpointId,
34
- pageId,
35
- payload
36
+ pageId
36
37
  });
37
38
  const endpointConfig = await getEndpointConfig(context, {
38
39
  endpointId
@@ -28,7 +28,7 @@ async function controlFor(context, routineContext, { control }) {
28
28
  });
29
29
  logger.debug({
30
30
  event: 'debug_control_for',
31
- array,
31
+ itemCount: Array.isArray(array) ? array.length : null,
32
32
  itemName
33
33
  });
34
34
  if (!Array.isArray(array)) {
@@ -47,9 +47,8 @@ async function controlFor(context, routineContext, { control }) {
47
47
  };
48
48
  logger.debug({
49
49
  event: 'debug_control_for_iteration',
50
- itemName: itemName,
51
- value: item,
52
- items: updatedItems
50
+ itemName,
51
+ index
53
52
  });
54
53
  const res = await runRoutine(context, {
55
54
  ...routineContext,
@@ -20,11 +20,13 @@ async function controlIf(context, routineContext, { control }) {
20
20
  input: control[':if'],
21
21
  location: control['~k'] ?? ':if'
22
22
  });
23
+ // No evaluated values: they can carry chat text or other personal information,
24
+ // which no log level may hold.
23
25
  logger.debug({
24
26
  event: 'debug_control_if',
25
27
  condition: {
26
28
  input: control[':if'],
27
- evaluated: evaluatedIf
29
+ result: Boolean(evaluatedIf)
28
30
  }
29
31
  });
30
32
  if (evaluatedIf) {
@@ -28,7 +28,7 @@ async function controlParallelFor(context, routineContext, { control }) {
28
28
  });
29
29
  logger.debug({
30
30
  event: 'debug_control_parallel',
31
- array,
31
+ itemCount: Array.isArray(array) ? array.length : null,
32
32
  itemName
33
33
  });
34
34
  if (!Array.isArray(array)) {
@@ -47,9 +47,8 @@ async function controlParallelFor(context, routineContext, { control }) {
47
47
  };
48
48
  logger.debug({
49
49
  event: 'debug_control_parallel_iteration',
50
- itemName: itemName,
51
- value: item,
52
- items: updatedItems
50
+ itemName,
51
+ index
53
52
  });
54
53
  return runRoutine(context, {
55
54
  ...routineContext,
@@ -18,9 +18,10 @@ async function controlReturn(context, routineContext, { control }) {
18
18
  input: control[':return'],
19
19
  location: control['~k'] ?? ':return'
20
20
  });
21
+ // No evaluated values: they can carry chat text or other personal information,
22
+ // which no log level may hold.
21
23
  context.logger.debug({
22
- event: 'debug_control_return',
23
- response
24
+ event: 'debug_control_return'
24
25
  });
25
26
  return {
26
27
  status: 'return',
@@ -24,7 +24,7 @@ function controlSetState(context, routineContext, { control }) {
24
24
  logger.debug({
25
25
  event: 'debug_control_set_state',
26
26
  input: control[':set_state'],
27
- evaluated: evaluatedSetState
27
+ keys: Object.keys(evaluatedSetState ?? {})
28
28
  });
29
29
  Object.entries(evaluatedSetState).forEach(([key, value])=>{
30
30
  try {
@@ -29,7 +29,7 @@ async function controlSwitch(context, routineContext, { control }) {
29
29
  event: 'debug_control_switch_case',
30
30
  case: {
31
31
  input: caseObj[':case'],
32
- evaluated: evaluatedCase
32
+ result: Boolean(evaluatedCase)
33
33
  }
34
34
  });
35
35
  if (evaluatedCase) {
@@ -35,7 +35,7 @@ async function handleAgentCall(context, routineContext, { step }) {
35
35
  });
36
36
  }
37
37
  if (!type.isString(prompt)) {
38
- throw new ConfigError(`CallAgent step "${step.stepId}" properties.prompt must evaluate to a string. Received ${JSON.stringify(prompt)}.`, {
38
+ throw new ConfigError(`CallAgent step "${step.stepId}" properties.prompt must evaluate to a string. Received a value of type "${prompt === null ? 'null' : typeof prompt}".`, {
39
39
  configKey: step['~k']
40
40
  });
41
41
  }
@@ -92,8 +92,7 @@ async function handleEndpointCall(context, routineContext, { step }) {
92
92
  logger.debug({
93
93
  event: 'debug_end_endpoint_call',
94
94
  stepId: step.stepId,
95
- targetEndpointId: evaluatedProperties.endpointId,
96
- response
95
+ targetEndpointId: evaluatedProperties.endpointId
97
96
  });
98
97
  return {
99
98
  status: 'continue'
@@ -74,10 +74,11 @@ async function handleRequest(context, routineContext, { request }) {
74
74
  result,
75
75
  stepId: request.stepId
76
76
  });
77
+ // No evaluated values: they can carry chat text or other personal information,
78
+ // which no log level may hold.
77
79
  context.logger.debug({
78
80
  event: 'debug_end_request',
79
- id: requestConfig.id,
80
- result
81
+ id: requestConfig.id
81
82
  });
82
83
  return {
83
84
  status: 'continue'
@@ -47,9 +47,23 @@ const mockTestRequestError = jest.fn((request)=>{
47
47
  throw new Error(request.request.message);
48
48
  });
49
49
  const mockTestRequestWait = jest.fn((request)=>wait(request.request.ms));
50
+ // Fails as a MongoDB write fails schema validation: the driver's error carries the document it
51
+ // rejected.
52
+ const mockTestRequestRejectDocument = jest.fn((request)=>{
53
+ const error = new Error('Document failed validation');
54
+ error.name = 'MongoServerError';
55
+ error.code = 121;
56
+ error.errInfo = {
57
+ details: {
58
+ document: request.request.document
59
+ }
60
+ };
61
+ throw error;
62
+ });
50
63
  mockTestRequest.schema = {};
51
64
  mockTestRequestError.schema = {};
52
65
  mockTestRequestWait.schema = {};
66
+ mockTestRequestRejectDocument.schema = {};
53
67
  mockTestRequest.meta = {
54
68
  checkRead: false,
55
69
  checkWrite: false
@@ -62,13 +76,18 @@ mockTestRequestWait.meta = {
62
76
  checkRead: false,
63
77
  checkWrite: false
64
78
  };
79
+ mockTestRequestRejectDocument.meta = {
80
+ checkRead: false,
81
+ checkWrite: false
82
+ };
65
83
  const connections = {
66
84
  TestConnection: {
67
85
  schema: {},
68
86
  requests: {
69
87
  TestRequest: mockTestRequest,
70
88
  TestRequestError: mockTestRequestError,
71
- TestRequestWait: mockTestRequestWait
89
+ TestRequestWait: mockTestRequestWait,
90
+ TestRequestRejectDocument: mockTestRequestRejectDocument
72
91
  }
73
92
  }
74
93
  };
@@ -15,6 +15,7 @@
15
15
  */ import { RequestError, ServiceError } from '@lowdefy/errors';
16
16
  import getCurrentEnvironment from '../../context/getCurrentEnvironment.js';
17
17
  import invokeEndpoint from '../endpoints/invokeEndpoint.js';
18
+ import summarisedError from './summarisedError.js';
18
19
  async function callRequestResolver(context, { connectionProperties, endpointDepth, requestConfig, requestProperties, requestResolver }) {
19
20
  const { blockId, endpointId, logger, pageId, payload } = context;
20
21
  // stepId for endpoint steps (after build), requestId for page requests
@@ -62,13 +63,14 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
62
63
  });
63
64
  return response;
64
65
  } catch (error) {
65
- // Add configKey to any error for location tracing
66
- if (!error.configKey) {
66
+ // Add configKey to any error for location tracing. A thrown string or null takes no
67
+ // property, and the TypeError assigning one raises would quote the string.
68
+ if (error instanceof Object && !error.configKey) {
67
69
  error.configKey = requestConfig['~k'];
68
70
  }
69
71
  // Lowdefy errors pass through unchanged — re-wrapping every boundary would
70
72
  // nest causes and truncate the deepest (most informative) frame.
71
- if (error.isLowdefyError) {
73
+ if (error?.isLowdefyError) {
72
74
  logger.debug({
73
75
  params: {
74
76
  id: stepOrRequestId,
@@ -78,13 +80,33 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
78
80
  }, error.message);
79
81
  throw error;
80
82
  }
83
+ // The error that leaves here is logged whole at error level by the server's error handler
84
+ // and sent to Sentry, so it carries ids and the resolver's error summarised - never the request's
85
+ // evaluated properties (an agent chat's save-thread step holds the whole thread there) or
86
+ // the connection's error itself, which can embed the document it rejected. The dev tools
87
+ // still show that error: it is kept as devCause, which is not enumerable, so no log or error
88
+ // report walks it, and only the dev error payload reads it. stepId, not requestId: on an
89
+ // error requestId is the HTTP request's id (context.rid) everywhere else.
90
+ const cause = summarisedError(error);
91
+ const addFields = (wrapped)=>{
92
+ Object.assign(wrapped, {
93
+ endpointId: requestConfig.endpointId ?? endpointId,
94
+ stepId: stepOrRequestId,
95
+ connectionId: requestConfig.connectionId
96
+ });
97
+ Object.defineProperty(wrapped, 'devCause', {
98
+ value: error,
99
+ configurable: true
100
+ });
101
+ };
81
102
  // Check if this is a service error (network, timeout, 5xx)
82
103
  if (ServiceError.isServiceError(error)) {
83
104
  const serviceError = new ServiceError(undefined, {
84
- cause: error,
105
+ cause,
85
106
  service: requestConfig.connectionId,
86
107
  configKey: requestConfig['~k']
87
108
  });
109
+ addFields(serviceError);
88
110
  logger.debug({
89
111
  params: {
90
112
  id: stepOrRequestId,
@@ -95,13 +117,13 @@ async function callRequestResolver(context, { connectionProperties, endpointDept
95
117
  throw serviceError;
96
118
  }
97
119
  // Wrap other errors in RequestError (request/connection logic error)
98
- const requestError = new RequestError(error.message, {
99
- cause: error,
120
+ const requestError = new RequestError(cause.message, {
121
+ cause,
100
122
  typeName: requestConfig.type,
101
- received: requestProperties,
102
123
  location: `${requestConfig.connectionId}/${stepOrRequestId}`,
103
124
  configKey: requestConfig['~k']
104
125
  });
126
+ addFields(requestError);
105
127
  logger.debug({
106
128
  params: {
107
129
  id: stepOrRequestId,
@@ -0,0 +1,62 @@
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 { errorSummaryForLog, readErrorCodes } from '@lowdefy/errors';
16
+ // Stack frames name code, never data, so they are kept. The stack's opening lines repeat the
17
+ // message, so they are rebuilt from the summary's; they are dropped by count, not by shape,
18
+ // since a message can hold a line that looks like a frame.
19
+ function stackFrames(error) {
20
+ if (typeof error.stack !== 'string') return [];
21
+ const headerLineCount = String(error).split('\n').length;
22
+ return error.stack.split('\n').slice(headerLineCount).filter((line)=>/^\s+at /.test(line));
23
+ }
24
+ // An error from another realm, such as a DOMException in a VM context, fails instanceof Error.
25
+ function isError(value) {
26
+ if (value instanceof Error) return true;
27
+ return typeof value === 'object' && value !== null && typeof value.stack === 'string' && typeof value.message === 'string';
28
+ }
29
+ function fromSummary(summary, original) {
30
+ const message = summary.message ?? `${summary.name} (message withheld from logs).`;
31
+ const error = new Error(message);
32
+ error.name = summary.name;
33
+ error.stack = [
34
+ `${summary.name}: ${message}`,
35
+ ...stackFrames(original)
36
+ ].join('\n');
37
+ if (summary.code !== undefined) error.code = summary.code;
38
+ if (summary.statusCode !== undefined) error.statusCode = summary.statusCode;
39
+ const cause = original.lastError ?? original.cause;
40
+ if (summary.cause !== undefined && isError(cause)) {
41
+ error.cause = fromSummary(summary.cause, cause);
42
+ }
43
+ return error;
44
+ }
45
+ // A request resolver's error rebuilt from its log summary: the name, code, status code and
46
+ // message cut to 500 characters, with the stack frames, for the error and three causes. A
47
+ // connection's error can carry the request's inputs in its other fields - a MongoDB write
48
+ // error the document it rejected, an HTTP client's error the request body - and every log
49
+ // and error report writes the error it is given, so none of them is kept.
50
+ function summarisedError(error) {
51
+ if (!isError(error)) {
52
+ const { code, statusCode } = readErrorCodes(error);
53
+ return fromSummary({
54
+ name: 'Error',
55
+ message: `Request resolver threw a value of type ${typeof error}, not an error.`,
56
+ code,
57
+ statusCode
58
+ }, {});
59
+ }
60
+ return fromSummary(errorSummaryForLog(error), error);
61
+ }
62
+ export default summarisedError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "6.1.0",
3
+ "version": "6.2.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -34,14 +34,14 @@
34
34
  "dist/*"
35
35
  ],
36
36
  "dependencies": {
37
- "@lowdefy/ajv": "6.1.0",
38
- "@lowdefy/build": "6.1.0",
39
- "@lowdefy/errors": "6.1.0",
40
- "@lowdefy/helpers": "6.1.0",
41
- "@lowdefy/node-utils": "6.1.0",
42
- "@lowdefy/nunjucks": "6.1.0",
43
- "@lowdefy/operators": "6.1.0",
44
- "@lowdefy/operators-js": "6.1.0",
37
+ "@lowdefy/ajv": "6.2.1",
38
+ "@lowdefy/build": "6.2.1",
39
+ "@lowdefy/errors": "6.2.1",
40
+ "@lowdefy/helpers": "6.2.1",
41
+ "@lowdefy/node-utils": "6.2.1",
42
+ "@lowdefy/nunjucks": "6.2.1",
43
+ "@lowdefy/operators": "6.2.1",
44
+ "@lowdefy/operators-js": "6.2.1",
45
45
  "@modelcontextprotocol/sdk": "1.29.0"
46
46
  },
47
47
  "devDependencies": {