@lowdefy/ai-utils 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.
@@ -0,0 +1,60 @@
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
+ function carriesAiSdkError(error, depth = 0) {
29
+ if (!(error instanceof Error)) return false;
30
+ if (isAiSdkError(error)) return true;
31
+ const cause = error.lastError ?? error.cause;
32
+ return depth < CAUSE_DEPTH && carriesAiSdkError(cause, depth + 1);
33
+ }
34
+ // What an agent run may throw on to the routine, which logs a thrown error whole (its message,
35
+ // stack and causes). An error with an AI SDK error in its chain is replaced by one that says
36
+ // only what agentErrorForLog would: its name, code, statusCode and, for an APICallError, the
37
+ // message. Any other error is thrown as it is.
38
+ function agentErrorForThrow(error) {
39
+ if (!carriesAiSdkError(error)) return error;
40
+ const summary = agentErrorForLog(error);
41
+ const safe = new Error(summary.message ?? `${summary.name} (message withheld from logs).`);
42
+ safe.name = summary.name;
43
+ if (summary.code !== undefined) safe.code = summary.code;
44
+ if (summary.statusCode !== undefined) safe.statusCode = summary.statusCode;
45
+ return safe;
46
+ }
47
+ // What every agent log names its run by: ids, never the conversation's content.
48
+ function agentLogIds({ agent, context }) {
49
+ return {
50
+ agentId: agent.agentId,
51
+ conversationId: context.agentContext?.conversationId ?? null
52
+ };
53
+ }
54
+ // One log line: the event's ids and the error's summary as JSON, for console.warn and
55
+ // console.error, which this line logs through.
56
+ function agentLogLine(text, fields) {
57
+ return `${text} ${JSON.stringify(fields)}`;
58
+ }
59
+ export { agentErrorForThrow, agentLogIds, agentLogLine };
60
+ 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.1",
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.1",
21
+ "@lowdefy/helpers": "6.2.1",
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.1",
28
28
  "@swc/cli": "0.8.1",
29
29
  "@swc/core": "1.15.32",
30
30
  "@swc/jest": "0.2.39",