@lowdefy/ai-utils 7.1.0 → 7.2.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.
@@ -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 } from '@lowdefy/errors';
16
+ // What an agent log may say about an error: the summary every Lowdefy log of an error uses (its
17
+ // name, code, status code and message cut to 500 characters, with an AI SDK error's message left
18
+ // out but for an APICallError's, and the same for three causes). Chat text can hold personal
19
+ // information, so no agent log carries messages, prompts, tool inputs or tool outputs.
20
+ const agentErrorForLog = errorSummaryForLog;
21
+ const CAUSE_DEPTH = 3;
22
+ // AISDKError.isInstance reads this marker; the error classes themselves are not imported so
23
+ // any copy of the AI SDK in the app is recognised.
24
+ const aiSdkErrorMarker = Symbol.for('vercel.ai.error');
25
+ function isAiSdkError(error) {
26
+ return error[aiSdkErrorMarker] === true;
27
+ }
28
+ // The stack's frames without its opening lines, which repeat the message. The lines are
29
+ // dropped by count, not by shape: a message can hold a line that looks like a frame.
30
+ function stackFramesForLog(error) {
31
+ if (!(error instanceof Error) || typeof error.stack !== 'string') return [];
32
+ const headerLineCount = String(error).split('\n').length;
33
+ return error.stack.split('\n').slice(headerLineCount).filter((line)=>/^\s+at /.test(line)).map((line)=>line.trim());
34
+ }
35
+ function carriesAiSdkError(error, depth = 0) {
36
+ if (!(error instanceof Error)) return false;
37
+ if (isAiSdkError(error)) return true;
38
+ const cause = error.lastError ?? error.cause;
39
+ return depth < CAUSE_DEPTH && carriesAiSdkError(cause, depth + 1);
40
+ }
41
+ // What an agent run may throw on to the routine, which logs a thrown error whole (its message,
42
+ // stack and causes). An error with an AI SDK error in its chain is replaced by one that says
43
+ // only what agentErrorForLog would: its name, code, statusCode and, for an APICallError, the
44
+ // message. Any other error is thrown as it is.
45
+ function agentErrorForThrow(error) {
46
+ if (!carriesAiSdkError(error)) return error;
47
+ const summary = agentErrorForLog(error);
48
+ const safe = new Error(summary.message ?? `${summary.name} (message withheld from logs).`);
49
+ safe.name = summary.name;
50
+ if (summary.code !== undefined) safe.code = summary.code;
51
+ if (summary.statusCode !== undefined) safe.statusCode = summary.statusCode;
52
+ return safe;
53
+ }
54
+ // What every agent log names its run by: ids, never the conversation's content.
55
+ function agentLogIds({ agent, context }) {
56
+ return {
57
+ agentId: agent.agentId,
58
+ conversationId: context.agentContext?.conversationId ?? null
59
+ };
60
+ }
61
+ export { agentErrorForThrow, agentLogIds, stackFramesForLog };
62
+ export default agentErrorForLog;
@@ -13,6 +13,7 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { ToolLoopAgent, isStepCount, hasToolCall } from 'ai';
16
+ import agentErrorForLog, { agentLogIds } from './agentErrorForLog.js';
16
17
  import buildAgentTools from './buildAgentTools.js';
17
18
  import buildPrepareStep from './buildPrepareStep.js';
18
19
  import buildUpdatePageStateTool from './buildUpdatePageStateTool.js';
@@ -43,7 +44,7 @@ const hookMapping = {
43
44
  onToolCallFinish: 'onToolExecutionEnd',
44
45
  onStepFinish: 'onStepEnd'
45
46
  };
46
- function createHookCallbacks({ callEndpoint, hooks, locale, logger }) {
47
+ function createHookCallbacks({ callEndpoint, hooks, locale, logger, logIds }) {
47
48
  if (!hooks) return {};
48
49
  const callbacks = {};
49
50
  for (const [yamlKey, sdkKey] of Object.entries(hookMapping)){
@@ -58,8 +59,9 @@ function createHookCallbacks({ callEndpoint, hooks, locale, logger }) {
58
59
  callEndpoint(endpointId, {
59
60
  payload
60
61
  }).catch((error)=>logger.warn({
61
- err: error,
62
- endpointId
62
+ ...logIds,
63
+ endpointId,
64
+ error: agentErrorForLog(error)
63
65
  }, 'Agent hook endpoint failed.'));
64
66
  }
65
67
  };
@@ -90,7 +92,11 @@ async function createToolLoopAgent({ connection, agent, context, autoApprove = f
90
92
  callEndpoint: context.callEndpoint,
91
93
  hooks: agent.hooks,
92
94
  locale,
93
- logger: context.logger
95
+ logger: context.logger,
96
+ logIds: agentLogIds({
97
+ agent,
98
+ context
99
+ })
94
100
  });
95
101
  // Prepend page context to instructions when pageContext is enabled
96
102
  let instructions = agent.properties.instructions;
@@ -157,6 +163,17 @@ async function createToolLoopAgent({ connection, agent, context, autoApprove = f
157
163
  signal: context.signal
158
164
  }),
159
165
  ...hookCallbacks,
166
+ // streamText's default onError writes the whole error to the console, and an AI SDK error
167
+ // can carry the request body (instructions, page context, messages) or the provider's
168
+ // reply. A mid-stream error reaches the client as an error chunk without throwing, so this
169
+ // is the only log of it: its summary and ids.
170
+ onError: ({ error })=>context.logger.error({
171
+ ...agentLogIds({
172
+ agent,
173
+ context
174
+ }),
175
+ error: agentErrorForLog(error)
176
+ }, 'Agent stream error.'),
160
177
  ...agent.properties.repairToolCall ? {
161
178
  repairToolCall: async ({ toolCall })=>{
162
179
  return {
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { convertToModelMessages, createAgentUIStream, createUIMessageStream, createUIMessageStreamResponse, generateId, generateText, pruneMessages, toUIMessageStream, validateUIMessages } from 'ai';
16
16
  import { serializer } from '@lowdefy/helpers';
17
+ import agentErrorForLog, { agentLogIds, stackFramesForLog } from './agentErrorForLog.js';
17
18
  import createToolLoopAgent from './createToolLoopAgent.js';
18
19
  import createUsageAccumulator from './createUsageAccumulator.js';
19
20
  import handleAgentGenerate from './handleAgentGenerate.js';
@@ -55,7 +56,7 @@ function dropEmptyMessages(messages) {
55
56
  // user and AgentChat config (`_event: message`), so it takes the wire policy: the
56
57
  // author's message for a UserError or an auth refusal, the generic message otherwise. A
57
58
  // library's message can embed anything it saw - a TypeValidationError's embeds the whole
58
- // conversation. The full error is logged server-side.
59
+ // conversation. The server log takes agentErrorForLog's summary instead, for the same reason.
59
60
  function createClientErrorText(context) {
60
61
  return function clientErrorText(error) {
61
62
  return context.wireErrorMessage(error);
@@ -91,6 +92,10 @@ async function handleAgentChat({ connection, properties, context }) {
91
92
  const pruneConfig = agent.properties.prune;
92
93
  const titleEnabled = agent.properties.generateTitle === true;
93
94
  const clientErrorText = createClientErrorText(context);
95
+ const logIds = agentLogIds({
96
+ agent,
97
+ context
98
+ });
94
99
  // Every stream gets clientErrorText: the AI SDK's default onError writes a tool error or
95
100
  // an in-stream error to the client raw.
96
101
  const stream = createUIMessageStream({
@@ -141,7 +146,8 @@ async function handleAgentChat({ connection, properties, context }) {
141
146
  }
142
147
  }).catch((error)=>{
143
148
  context.logger.warn({
144
- err: error
149
+ ...logIds,
150
+ error: agentErrorForLog(error)
145
151
  }, 'generateTitle failed.');
146
152
  });
147
153
  }
@@ -218,10 +224,17 @@ async function handleAgentChat({ connection, properties, context }) {
218
224
  }
219
225
  } catch (error) {
220
226
  // The client only ever sees the redacted error text, so the fault is
221
- // logged server-side before it is written to the stream.
227
+ // logged server-side before it is written to the stream - its summary,
228
+ // since the error itself can embed the whole conversation.
222
229
  context.logger.error({
223
- err: error
230
+ ...logIds,
231
+ stepCount: steps.length,
232
+ error: agentErrorForLog(error)
224
233
  }, 'Agent stream failed.');
234
+ context.logger.debug({
235
+ ...logIds,
236
+ stack: stackFramesForLog(error)
237
+ }, 'Agent stream failed: stack.');
225
238
  writer.write({
226
239
  type: 'error',
227
240
  errorText: writer.onError(error)
@@ -256,7 +269,9 @@ async function handleAgentChat({ connection, properties, context }) {
256
269
  }
257
270
  } catch (error) {
258
271
  context.logger.error({
259
- err: error
272
+ ...logIds,
273
+ endpointId,
274
+ error: agentErrorForLog(error)
260
275
  }, `onFinish hook "${endpointId}" failed.`);
261
276
  }
262
277
  }
@@ -12,7 +12,8 @@
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 buildGeneratePrompt from './buildGeneratePrompt.js';
15
+ */ import agentErrorForLog, { agentErrorForThrow, agentLogIds } from './agentErrorForLog.js';
16
+ import buildGeneratePrompt from './buildGeneratePrompt.js';
16
17
  import createToolLoopAgent from './createToolLoopAgent.js';
17
18
  import createUsageAccumulator from './createUsageAccumulator.js';
18
19
  // Runs an agent headlessly to completion — no chat UI, no streaming. Used by
@@ -39,6 +40,10 @@ async function handleAgentGenerate({ connection, properties, context }) {
39
40
  ...timeoutConfig,
40
41
  onStepEnd: (stepResult)=>usageAccumulator.add(stepResult)
41
42
  });
43
+ } catch (error) {
44
+ // The routine logs what is thrown whole, and an AI SDK error can embed the prompt or
45
+ // the messages.
46
+ throw agentErrorForThrow(error);
42
47
  } finally{
43
48
  await Promise.all(mcpClients.map(({ client })=>client.close().catch(()=>{})));
44
49
  }
@@ -88,7 +93,12 @@ async function handleAgentGenerate({ connection, properties, context }) {
88
93
  });
89
94
  } catch (error) {
90
95
  context.logger.error({
91
- err: error
96
+ ...agentLogIds({
97
+ agent,
98
+ context
99
+ }),
100
+ endpointId,
101
+ error: agentErrorForLog(error)
92
102
  }, `onFinish hook "${endpointId}" failed.`);
93
103
  }
94
104
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/ai-utils",
3
- "version": "7.1.0",
3
+ "version": "7.2.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,20 +17,18 @@
17
17
  ],
18
18
  "dependencies": {
19
19
  "@ai-sdk/mcp": "2.0.60",
20
- "@lowdefy/errors": "7.1.0",
21
- "@lowdefy/helpers": "7.1.0",
22
- "@lowdefy/node-utils": "7.1.0",
20
+ "@lowdefy/errors": "7.2.0",
21
+ "@lowdefy/helpers": "7.2.0",
22
+ "@lowdefy/node-utils": "7.2.0",
23
23
  "ai": "7.0.116",
24
24
  "glob": "13.0.6",
25
- "undici": "7.30.0"
25
+ "undici": "7.30.1"
26
26
  },
27
27
  "devDependencies": {
28
- "@jest/globals": "28.1.3",
29
- "@lowdefy/ajv": "7.1.0",
28
+ "@lowdefy/ajv": "7.2.0",
30
29
  "@swc/cli": "0.8.1",
31
30
  "@swc/core": "1.15.32",
32
- "@swc/jest": "0.2.39",
33
- "jest": "28.1.3"
31
+ "vitest": "4.1.12"
34
32
  },
35
33
  "publishConfig": {
36
34
  "access": "public"
@@ -38,6 +36,6 @@
38
36
  "scripts": {
39
37
  "build": "swc src --out-dir dist --config-file ../../../.swcrc --cli-config-file ../../../.swc-cli.json",
40
38
  "clean": "rm -rf dist",
41
- "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
39
+ "test": "vitest run"
42
40
  }
43
41
  }