@lowdefy/ai-utils 6.0.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.
- package/dist/agentErrorForLog.js +88 -0
- package/dist/createToolLoopAgent.js +12 -0
- package/dist/handleAgentChat.js +38 -16
- package/dist/handleAgentGenerate.js +14 -2
- package/package.json +4 -4
|
@@ -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 {
|
package/dist/handleAgentChat.js
CHANGED
|
@@ -12,8 +12,9 @@
|
|
|
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 { convertToModelMessages, createAgentUIStream, createUIMessageStream, createUIMessageStreamResponse, generateId, generateText, pruneMessages,
|
|
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';
|
|
@@ -51,15 +52,15 @@ function convertDataUrlsToBase64(messages) {
|
|
|
51
52
|
function dropEmptyMessages(messages) {
|
|
52
53
|
return messages.filter((msg)=>Array.isArray(msg.parts) && msg.parts.length > 0);
|
|
53
54
|
}
|
|
54
|
-
// What the client is told when a turn fails.
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
55
|
+
// What the client is told when a turn fails or a tool throws. The text reaches the end
|
|
56
|
+
// user and AgentChat config (`_event: message`), so it takes the wire policy: the
|
|
57
|
+
// author's message for a UserError or an auth refusal, the generic message otherwise. A
|
|
58
|
+
// library's message can embed anything it saw - a TypeValidationError's embeds the whole
|
|
59
|
+
// conversation. The full error is logged server-side.
|
|
60
|
+
function createClientErrorText(context) {
|
|
61
|
+
return function clientErrorText(error) {
|
|
62
|
+
return context.wireErrorMessage(error);
|
|
63
|
+
};
|
|
63
64
|
}
|
|
64
65
|
// Concatenate the text parts of the first user message — used as the source
|
|
65
66
|
// for generateTitle.
|
|
@@ -90,6 +91,13 @@ async function handleAgentChat({ connection, properties, context }) {
|
|
|
90
91
|
const hasMcpClients = mcpClients.length > 0;
|
|
91
92
|
const pruneConfig = agent.properties.prune;
|
|
92
93
|
const titleEnabled = agent.properties.generateTitle === true;
|
|
94
|
+
const clientErrorText = createClientErrorText(context);
|
|
95
|
+
const logIds = agentLogIds({
|
|
96
|
+
agent,
|
|
97
|
+
context
|
|
98
|
+
});
|
|
99
|
+
// Every stream gets clientErrorText: the AI SDK's default onError writes a tool error or
|
|
100
|
+
// an in-stream error to the client raw.
|
|
93
101
|
const stream = createUIMessageStream({
|
|
94
102
|
onError: clientErrorText,
|
|
95
103
|
execute: async ({ writer })=>{
|
|
@@ -137,7 +145,10 @@ async function handleAgentChat({ connection, properties, context }) {
|
|
|
137
145
|
});
|
|
138
146
|
}
|
|
139
147
|
}).catch((error)=>{
|
|
140
|
-
console.warn(
|
|
148
|
+
console.warn(agentLogLine('generateTitle failed:', {
|
|
149
|
+
...logIds,
|
|
150
|
+
error: agentErrorForLog(error)
|
|
151
|
+
}));
|
|
141
152
|
});
|
|
142
153
|
}
|
|
143
154
|
}
|
|
@@ -170,7 +181,8 @@ async function handleAgentChat({ connection, properties, context }) {
|
|
|
170
181
|
// Without a generator the assistant message reaches onFinish with
|
|
171
182
|
// id: '' — see the createAgentUIStream call below.
|
|
172
183
|
generateMessageId: generateId,
|
|
173
|
-
onFinish: captureMessages
|
|
184
|
+
onFinish: captureMessages,
|
|
185
|
+
onError: clientErrorText
|
|
174
186
|
});
|
|
175
187
|
} else {
|
|
176
188
|
// createAgentUIStream validates UIMessages, converts to ModelMessages,
|
|
@@ -193,7 +205,8 @@ async function handleAgentChat({ connection, properties, context }) {
|
|
|
193
205
|
// after a reload.
|
|
194
206
|
generateMessageId: generateId,
|
|
195
207
|
onStepFinish: collectStep,
|
|
196
|
-
onFinish: captureMessages
|
|
208
|
+
onFinish: captureMessages,
|
|
209
|
+
onError: clientErrorText
|
|
197
210
|
});
|
|
198
211
|
}
|
|
199
212
|
// Read the agent stream to completion before running onFinish hooks.
|
|
@@ -207,8 +220,13 @@ async function handleAgentChat({ connection, properties, context }) {
|
|
|
207
220
|
}
|
|
208
221
|
} catch (error) {
|
|
209
222
|
// The client only sees the (possibly redacted) error text, so the fault
|
|
210
|
-
// is logged server-side before it is written to the stream
|
|
211
|
-
|
|
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
|
+
}));
|
|
212
230
|
writer.write({
|
|
213
231
|
type: 'error',
|
|
214
232
|
errorText: writer.onError(error)
|
|
@@ -242,7 +260,11 @@ async function handleAgentChat({ connection, properties, context }) {
|
|
|
242
260
|
}
|
|
243
261
|
}
|
|
244
262
|
} catch (error) {
|
|
245
|
-
console.warn(`onFinish hook "${endpointId}" failed
|
|
263
|
+
console.warn(agentLogLine(`onFinish hook "${endpointId}" failed:`, {
|
|
264
|
+
...logIds,
|
|
265
|
+
endpointId,
|
|
266
|
+
error: agentErrorForLog(error)
|
|
267
|
+
}));
|
|
246
268
|
}
|
|
247
269
|
}
|
|
248
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
|
|
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
|
|
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.
|
|
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.
|
|
21
|
-
"@lowdefy/helpers": "6.
|
|
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.
|
|
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",
|