@lowdefy/ai-utils 6.0.0 → 7.0.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.
@@ -12,7 +12,7 @@
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, TypeValidationError, validateUIMessages } from 'ai';
15
+ */ import { convertToModelMessages, createAgentUIStream, createUIMessageStream, createUIMessageStreamResponse, generateId, generateText, pruneMessages, toUIMessageStream, validateUIMessages } from 'ai';
16
16
  import { serializer } from '@lowdefy/helpers';
17
17
  import createToolLoopAgent from './createToolLoopAgent.js';
18
18
  import createUsageAccumulator from './createUsageAccumulator.js';
@@ -51,15 +51,15 @@ function convertDataUrlsToBase64(messages) {
51
51
  function dropEmptyMessages(messages) {
52
52
  return messages.filter((msg)=>Array.isArray(msg.parts) && msg.parts.length > 0);
53
53
  }
54
- // What the client is told when a turn fails. TypeValidationError.message
55
- // embeds JSON.stringify(value) — for a UIMessage validation failure that is
56
- // the entire conversation, which the chat block then shows in a toast. The
57
- // full error is logged server-side before this is written to the stream.
58
- function clientErrorText(error) {
59
- if (TypeValidationError.isInstance(error)) {
60
- return 'The conversation could not be sent: a message failed validation.';
61
- }
62
- return error?.message ?? String(error);
54
+ // What the client is told when a turn fails or a tool throws. The text reaches the end
55
+ // user and AgentChat config (`_event: message`), so it takes the wire policy: the
56
+ // author's message for a UserError or an auth refusal, the generic message otherwise. A
57
+ // library's message can embed anything it saw - a TypeValidationError's embeds the whole
58
+ // conversation. The full error is logged server-side.
59
+ function createClientErrorText(context) {
60
+ return function clientErrorText(error) {
61
+ return context.wireErrorMessage(error);
62
+ };
63
63
  }
64
64
  // Concatenate the text parts of the first user message — used as the source
65
65
  // for generateTitle.
@@ -90,6 +90,9 @@ async function handleAgentChat({ connection, properties, context }) {
90
90
  const hasMcpClients = mcpClients.length > 0;
91
91
  const pruneConfig = agent.properties.prune;
92
92
  const titleEnabled = agent.properties.generateTitle === true;
93
+ const clientErrorText = createClientErrorText(context);
94
+ // Every stream gets clientErrorText: the AI SDK's default onError writes a tool error or
95
+ // an in-stream error to the client raw.
93
96
  const stream = createUIMessageStream({
94
97
  onError: clientErrorText,
95
98
  execute: async ({ writer })=>{
@@ -97,7 +100,7 @@ async function handleAgentChat({ connection, properties, context }) {
97
100
  const steps = [];
98
101
  let agentStream;
99
102
  // The AI SDK delivers the full updated UI message list (input + generated
100
- // assistant reply) to the stream-level onFinish. Capture it so onFinish
103
+ // assistant reply) to the stream-level onEnd. Capture it so onFinish
101
104
  // hooks persist the complete conversation, not just the request input.
102
105
  let capturedMessages;
103
106
  function collectStep(stepResult) {
@@ -137,7 +140,9 @@ async function handleAgentChat({ connection, properties, context }) {
137
140
  });
138
141
  }
139
142
  }).catch((error)=>{
140
- console.warn(`generateTitle failed: ${error.message}`);
143
+ context.logger.warn({
144
+ err: error
145
+ }, 'generateTitle failed.');
141
146
  });
142
147
  }
143
148
  }
@@ -163,14 +168,19 @@ async function handleAgentChat({ connection, properties, context }) {
163
168
  const result = await agentInstance.stream({
164
169
  prompt: prunedMessages,
165
170
  ...timeoutConfig,
166
- onStepFinish: collectStep
171
+ onStepEnd: collectStep
167
172
  });
168
- agentStream = result.toUIMessageStream({
173
+ // ai v7: the stream-result method is deprecated for the stateless
174
+ // helper over the result's part stream.
175
+ agentStream = toUIMessageStream({
176
+ stream: result.stream,
177
+ tools: agentInstance.tools,
169
178
  originalMessages: validatedMessages,
170
- // Without a generator the assistant message reaches onFinish with
179
+ // Without a generator the assistant message reaches onEnd with
171
180
  // id: '' — see the createAgentUIStream call below.
172
181
  generateMessageId: generateId,
173
- onFinish: captureMessages
182
+ onEnd: captureMessages,
183
+ onError: clientErrorText
174
184
  });
175
185
  } else {
176
186
  // createAgentUIStream validates UIMessages, converts to ModelMessages,
@@ -192,8 +202,9 @@ async function handleAgentChat({ connection, properties, context }) {
192
202
  // generates its own id while streaming, so the damage only shows up
193
203
  // after a reload.
194
204
  generateMessageId: generateId,
195
- onStepFinish: collectStep,
196
- onFinish: captureMessages
205
+ onStepEnd: collectStep,
206
+ onEnd: captureMessages,
207
+ onError: clientErrorText
197
208
  });
198
209
  }
199
210
  // Read the agent stream to completion before running onFinish hooks.
@@ -206,9 +217,11 @@ async function handleAgentChat({ connection, properties, context }) {
206
217
  writer.write(value);
207
218
  }
208
219
  } catch (error) {
209
- // 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
- console.error(`Agent stream failed: ${error.message}`);
220
+ // The client only ever sees the redacted error text, so the fault is
221
+ // logged server-side before it is written to the stream.
222
+ context.logger.error({
223
+ err: error
224
+ }, 'Agent stream failed.');
212
225
  writer.write({
213
226
  type: 'error',
214
227
  errorText: writer.onError(error)
@@ -242,7 +255,9 @@ async function handleAgentChat({ connection, properties, context }) {
242
255
  }
243
256
  }
244
257
  } catch (error) {
245
- console.warn(`onFinish hook "${endpointId}" failed: ${error.message}`);
258
+ context.logger.error({
259
+ err: error
260
+ }, `onFinish hook "${endpointId}" failed.`);
246
261
  }
247
262
  }
248
263
  }
@@ -12,14 +12,15 @@
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 buildGeneratePrompt from './buildGeneratePrompt.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
19
20
  // resolve an approval), update-page-state is excluded (callers pass no
20
21
  // sharedState), and no conversation title is generated.
21
22
  async function handleAgentGenerate({ connection, properties, context }) {
22
- const { agent, prompt } = properties;
23
+ const { agent, prompt, files } = properties;
23
24
  const { agentInstance, mcpClients, timeoutConfig, locale } = await createToolLoopAgent({
24
25
  connection,
25
26
  agent,
@@ -30,9 +31,13 @@ async function handleAgentGenerate({ connection, properties, context }) {
30
31
  let result;
31
32
  try {
32
33
  result = await agentInstance.generate({
33
- prompt,
34
+ prompt: buildGeneratePrompt({
35
+ prompt,
36
+ files
37
+ }),
38
+ abortSignal: context.signal,
34
39
  ...timeoutConfig,
35
- onStepFinish: (stepResult)=>usageAccumulator.add(stepResult)
40
+ onStepEnd: (stepResult)=>usageAccumulator.add(stepResult)
36
41
  });
37
42
  } finally{
38
43
  await Promise.all(mcpClients.map(({ client })=>client.close().catch(()=>{})));
@@ -82,7 +87,9 @@ 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
+ context.logger.error({
91
+ err: error
92
+ }, `onFinish hook "${endpointId}" failed.`);
86
93
  }
87
94
  }
88
95
  }
@@ -16,7 +16,7 @@
16
16
  import buildGenerateCallOptions from './buildGenerateCallOptions.js';
17
17
  // generateObject is deprecated in ai v6 — structured output is generateText
18
18
  // with an Output.object spec, which also keeps both handlers on one code path.
19
- async function handleGenerateObject({ model, request }) {
19
+ async function handleGenerateObject({ model, request, limits, signal }) {
20
20
  const result = await generateText({
21
21
  model,
22
22
  output: Output.object({
@@ -25,15 +25,17 @@ async function handleGenerateObject({ model, request }) {
25
25
  description: request.schemaDescription
26
26
  }),
27
27
  ...buildGenerateCallOptions({
28
- request
29
- })
28
+ request,
29
+ signal
30
+ }),
31
+ ...limits
30
32
  });
31
33
  return {
32
34
  object: result.output,
33
- reasoningText: result.reasoningText,
35
+ reasoningText: result.finalStep?.reasoningText,
34
36
  finishReason: result.finishReason,
35
37
  usage: result.usage,
36
- providerMetadata: result.providerMetadata,
38
+ providerMetadata: result.finalStep?.providerMetadata,
37
39
  warnings: result.warnings
38
40
  };
39
41
  }
@@ -14,19 +14,21 @@
14
14
  limitations under the License.
15
15
  */ import { generateText } from 'ai';
16
16
  import buildGenerateCallOptions from './buildGenerateCallOptions.js';
17
- async function handleGenerateText({ model, request }) {
17
+ async function handleGenerateText({ model, request, limits, signal }) {
18
18
  const result = await generateText({
19
19
  model,
20
20
  ...buildGenerateCallOptions({
21
- request
22
- })
21
+ request,
22
+ signal
23
+ }),
24
+ ...limits
23
25
  });
24
26
  return {
25
27
  text: result.text,
26
- reasoningText: result.reasoningText,
28
+ reasoningText: result.finalStep?.reasoningText,
27
29
  finishReason: result.finishReason,
28
30
  usage: result.usage,
29
- providerMetadata: result.providerMetadata,
31
+ providerMetadata: result.finalStep?.providerMetadata,
30
32
  warnings: result.warnings
31
33
  };
32
34
  }
package/dist/index.js CHANGED
@@ -12,7 +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
- */ export { default as createGenerateObject } from './createGenerateObject.js';
15
+ */ export { default as createDecide } from './createDecide.js';
16
+ export { default as decide } from './decide.js';
17
+ export { default as createGenerateObject } from './createGenerateObject.js';
18
+ export { ANSWER_FIELDS as DECIDE_ANSWER_FIELDS, answerValues as decideAnswerValues, questionKind as decideQuestionKind } from './decideQuestions.js';
16
19
  export { default as createGenerateText } from './createGenerateText.js';
17
20
  export { default as handleAgentChat } from './handleAgentChat.js';
18
21
  export { default as handleAgentGenerate } from './handleAgentGenerate.js';
@@ -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
+ */ function withoutLowdefyMetadata(part) {
16
+ if (part.providerOptions?.lowdefy === undefined) {
17
+ return part;
18
+ }
19
+ const { lowdefy: _lowdefy, ...providerOptions } = part.providerOptions;
20
+ const { providerOptions: _providerOptions, ...rest } = part;
21
+ if (Object.keys(providerOptions).length === 0) {
22
+ return rest;
23
+ }
24
+ return {
25
+ ...rest,
26
+ providerOptions
27
+ };
28
+ }
29
+ // Puts a text part naming each attached file just before it in the user messages sent to the
30
+ // model, so the model can pass a file's name to a tool (which looks it up in `_agent: files`).
31
+ // The model sees an image as content, not by name. AgentChat keeps an upload's storage key in
32
+ // providerMetadata.lowdefy, which reaches the model messages as providerOptions.lowdefy; it is
33
+ // removed here, so the key stays with Lowdefy. The UI messages that are saved are not changed.
34
+ function nameAttachedFiles(prompt) {
35
+ if (!Array.isArray(prompt)) {
36
+ return prompt;
37
+ }
38
+ return prompt.map((message)=>{
39
+ if (message.role !== 'user' || !Array.isArray(message.content)) {
40
+ return message;
41
+ }
42
+ const content = [];
43
+ for (const part of message.content){
44
+ if (part.type !== 'file') {
45
+ content.push(part);
46
+ continue;
47
+ }
48
+ if (typeof part.filename === 'string') {
49
+ content.push({
50
+ type: 'text',
51
+ text: `Attached file: ${part.filename}`
52
+ });
53
+ }
54
+ content.push(withoutLowdefyMetadata(part));
55
+ }
56
+ return {
57
+ ...message,
58
+ content
59
+ };
60
+ });
61
+ }
62
+ export default nameAttachedFiles;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/ai-utils",
3
- "version": "6.0.0",
3
+ "version": "7.0.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,15 +16,17 @@
16
16
  "dist/*"
17
17
  ],
18
18
  "dependencies": {
19
- "@ai-sdk/mcp": "1.0.41",
20
- "@lowdefy/errors": "6.0.0",
21
- "@lowdefy/helpers": "6.0.0",
22
- "ai": "6.0.176",
23
- "glob": "13.0.6"
19
+ "@ai-sdk/mcp": "2.0.60",
20
+ "@lowdefy/errors": "7.0.0",
21
+ "@lowdefy/helpers": "7.0.0",
22
+ "@lowdefy/node-utils": "7.0.0",
23
+ "ai": "7.0.116",
24
+ "glob": "13.0.6",
25
+ "undici": "7.30.0"
24
26
  },
25
27
  "devDependencies": {
26
28
  "@jest/globals": "28.1.3",
27
- "@lowdefy/ajv": "6.0.0",
29
+ "@lowdefy/ajv": "7.0.0",
28
30
  "@swc/cli": "0.8.1",
29
31
  "@swc/core": "1.15.32",
30
32
  "@swc/jest": "0.2.39",