@lowdefy/ai-utils 6.1.0 → 6.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,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
+ */ // What an agent log may say about an error. Chat text can hold personal information, and
16
+ // logs have their own retention and access, so no log carries messages, prompts, tool inputs
17
+ // or tool outputs. An error carries them where a plain `{ err }` log would write them: a
18
+ // TypeValidationError's or JSONParseError's message embeds the value it rejected (the whole
19
+ // conversation, a tool's input), InvalidToolInputError, ToolCallRepairError and RetryError
20
+ // repeat their cause's message, and every stack opens with its message. So an AI SDK error is
21
+ // logged by name and code alone, except APICallError, whose message is the provider's reply;
22
+ // any other error keeps its message, cut to 500 characters. Causes are followed the same way.
23
+ const MESSAGE_LIMIT = 500;
24
+ const CAUSE_DEPTH = 3;
25
+ // AISDKError.isInstance reads this marker; the error classes themselves are not imported so
26
+ // any copy of the AI SDK in the app is recognised.
27
+ const aiSdkErrorMarker = Symbol.for('vercel.ai.error');
28
+ function isAiSdkError(error) {
29
+ return error[aiSdkErrorMarker] === true;
30
+ }
31
+ function truncate(text) {
32
+ if (text.length <= MESSAGE_LIMIT) return text;
33
+ return `${text.slice(0, MESSAGE_LIMIT - 1)}…`;
34
+ }
35
+ function agentErrorForLog(error, depth = 0) {
36
+ if (!(error instanceof Error)) {
37
+ return {
38
+ name: typeof error
39
+ };
40
+ }
41
+ const summary = {
42
+ name: error.name
43
+ };
44
+ if (!isAiSdkError(error) || error.name === 'AI_APICallError') {
45
+ summary.message = truncate(String(error.message));
46
+ }
47
+ if (error.code !== undefined) summary.code = error.code;
48
+ if (error.statusCode !== undefined) summary.statusCode = error.statusCode;
49
+ // A RetryError holds the attempt that failed last as lastError rather than as its cause.
50
+ const cause = error.lastError ?? error.cause;
51
+ if (cause !== undefined && depth < CAUSE_DEPTH) {
52
+ summary.cause = agentErrorForLog(cause, depth + 1);
53
+ }
54
+ return summary;
55
+ }
56
+ function carriesAiSdkError(error, depth = 0) {
57
+ if (!(error instanceof Error)) return false;
58
+ if (isAiSdkError(error)) return true;
59
+ const cause = error.lastError ?? error.cause;
60
+ return depth < CAUSE_DEPTH && carriesAiSdkError(cause, depth + 1);
61
+ }
62
+ // What an agent run may throw on to the routine, which logs a thrown error whole (its message,
63
+ // stack and causes). An error with an AI SDK error in its chain is replaced by one that says
64
+ // only what agentErrorForLog would: its name, code, statusCode and, for an APICallError, the
65
+ // message. Any other error is thrown as it is.
66
+ function agentErrorForThrow(error) {
67
+ if (!carriesAiSdkError(error)) return error;
68
+ const summary = agentErrorForLog(error);
69
+ const safe = new Error(summary.message ?? `${summary.name} (message withheld from logs).`);
70
+ safe.name = summary.name;
71
+ if (summary.code !== undefined) safe.code = summary.code;
72
+ if (summary.statusCode !== undefined) safe.statusCode = summary.statusCode;
73
+ return safe;
74
+ }
75
+ // What every agent log names its run by: ids, never the conversation's content.
76
+ function agentLogIds({ agent, context }) {
77
+ return {
78
+ agentId: agent.agentId,
79
+ conversationId: context.agentContext?.conversationId ?? null
80
+ };
81
+ }
82
+ // One log line: the event's ids and the error's summary as JSON, for console.warn and
83
+ // console.error, which this line logs through.
84
+ function agentLogLine(text, fields) {
85
+ return `${text} ${JSON.stringify(fields)}`;
86
+ }
87
+ export { agentErrorForThrow, agentLogIds, agentLogLine };
88
+ 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, stepCountIs, hasToolCall } from 'ai';
16
+ import agentErrorForLog, { agentLogIds, agentLogLine } from './agentErrorForLog.js';
16
17
  import buildAgentTools from './buildAgentTools.js';
17
18
  import buildPrepareStep from './buildPrepareStep.js';
18
19
  import buildUpdatePageStateTool from './buildUpdatePageStateTool.js';
@@ -135,6 +136,17 @@ async function createToolLoopAgent({ connection, agent, context, autoApprove = f
135
136
  prepareStep: buildPrepareStep(agent.properties.prepareStep)
136
137
  } : {},
137
138
  ...hookCallbacks,
139
+ // streamText's default onError writes the whole error to the console, and an AI SDK error
140
+ // can carry the request body (instructions, page context, messages) or the provider's
141
+ // reply. A mid-stream error reaches the client as an error chunk without throwing, so this
142
+ // is the only log of it: its summary and ids.
143
+ onError: ({ error })=>console.error(agentLogLine('Agent stream error:', {
144
+ ...agentLogIds({
145
+ agent,
146
+ context
147
+ }),
148
+ error: agentErrorForLog(error)
149
+ })),
138
150
  ...agent.properties.repairToolCall ? {
139
151
  experimental_repairToolCall: async ({ toolCall })=>{
140
152
  return {
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { convertToModelMessages, createAgentUIStream, createUIMessageStream, createUIMessageStreamResponse, generateId, generateText, pruneMessages, validateUIMessages } from 'ai';
16
16
  import { serializer } from '@lowdefy/helpers';
17
+ import agentErrorForLog, { agentLogIds, agentLogLine } from './agentErrorForLog.js';
17
18
  import createToolLoopAgent from './createToolLoopAgent.js';
18
19
  import createUsageAccumulator from './createUsageAccumulator.js';
19
20
  import handleAgentGenerate from './handleAgentGenerate.js';
@@ -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({
@@ -140,7 +145,10 @@ async function handleAgentChat({ connection, properties, context }) {
140
145
  });
141
146
  }
142
147
  }).catch((error)=>{
143
- console.warn(`generateTitle failed: ${error.message}`);
148
+ console.warn(agentLogLine('generateTitle failed:', {
149
+ ...logIds,
150
+ error: agentErrorForLog(error)
151
+ }));
144
152
  });
145
153
  }
146
154
  }
@@ -212,8 +220,13 @@ async function handleAgentChat({ connection, properties, context }) {
212
220
  }
213
221
  } catch (error) {
214
222
  // The client only sees the (possibly redacted) error text, so the fault
215
- // is logged server-side before it is written to the stream.
216
- console.error(`Agent stream failed: ${error.message}`);
223
+ // is logged server-side before it is written to the stream - its summary,
224
+ // since the error itself can embed the whole conversation.
225
+ console.error(agentLogLine('Agent stream failed:', {
226
+ ...logIds,
227
+ stepCount: steps.length,
228
+ error: agentErrorForLog(error)
229
+ }));
217
230
  writer.write({
218
231
  type: 'error',
219
232
  errorText: writer.onError(error)
@@ -247,7 +260,11 @@ async function handleAgentChat({ connection, properties, context }) {
247
260
  }
248
261
  }
249
262
  } catch (error) {
250
- console.warn(`onFinish hook "${endpointId}" failed: ${error.message}`);
263
+ console.warn(agentLogLine(`onFinish hook "${endpointId}" failed:`, {
264
+ ...logIds,
265
+ endpointId,
266
+ error: agentErrorForLog(error)
267
+ }));
251
268
  }
252
269
  }
253
270
  }
@@ -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 createToolLoopAgent from './createToolLoopAgent.js';
15
+ */ import agentErrorForLog, { agentErrorForThrow, agentLogIds, agentLogLine } from './agentErrorForLog.js';
16
+ import createToolLoopAgent from './createToolLoopAgent.js';
16
17
  import createUsageAccumulator from './createUsageAccumulator.js';
17
18
  // Runs an agent headlessly to completion — no chat UI, no streaming. Used by
18
19
  // the CallAgent routine step. Confirm tools auto-execute (no client exists to
@@ -34,6 +35,10 @@ async function handleAgentGenerate({ connection, properties, context }) {
34
35
  ...timeoutConfig,
35
36
  onStepFinish: (stepResult)=>usageAccumulator.add(stepResult)
36
37
  });
38
+ } catch (error) {
39
+ // The routine logs what is thrown whole, and an AI SDK error can embed the prompt or
40
+ // the messages.
41
+ throw agentErrorForThrow(error);
37
42
  } finally{
38
43
  await Promise.all(mcpClients.map(({ client })=>client.close().catch(()=>{})));
39
44
  }
@@ -82,7 +87,14 @@ async function handleAgentGenerate({ connection, properties, context }) {
82
87
  payload: finishPayload
83
88
  });
84
89
  } catch (error) {
85
- console.warn(`onFinish hook "${endpointId}" failed: ${error.message}`);
90
+ console.warn(agentLogLine(`onFinish hook "${endpointId}" failed:`, {
91
+ ...agentLogIds({
92
+ agent,
93
+ context
94
+ }),
95
+ endpointId,
96
+ error: agentErrorForLog(error)
97
+ }));
86
98
  }
87
99
  }
88
100
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/ai-utils",
3
- "version": "6.1.0",
3
+ "version": "6.2.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,14 +17,14 @@
17
17
  ],
18
18
  "dependencies": {
19
19
  "@ai-sdk/mcp": "1.0.41",
20
- "@lowdefy/errors": "6.1.0",
21
- "@lowdefy/helpers": "6.1.0",
20
+ "@lowdefy/errors": "6.2.0",
21
+ "@lowdefy/helpers": "6.2.0",
22
22
  "ai": "6.0.176",
23
23
  "glob": "13.0.6"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@jest/globals": "28.1.3",
27
- "@lowdefy/ajv": "6.1.0",
27
+ "@lowdefy/ajv": "6.2.0",
28
28
  "@swc/cli": "0.8.1",
29
29
  "@swc/core": "1.15.32",
30
30
  "@swc/jest": "0.2.39",