@lowdefy/ai-utils 6.1.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.
@@ -199,9 +199,38 @@
199
199
  oneOf: 'AISDKAgent agent property "timeout" should be a number or an object with totalMs, stepMs, and/or chunkMs.'
200
200
  }
201
201
  },
202
+ fileDownload: {
203
+ type: 'object',
204
+ description: 'Limits for a file link the server downloads because the model does not take it as a link.',
205
+ properties: {
206
+ maxBytes: {
207
+ type: 'integer',
208
+ minimum: 1,
209
+ description: 'Largest file the server downloads, in bytes. Default: 20971520 (20 MB).',
210
+ errorMessage: {
211
+ type: 'AISDKAgent agent property "fileDownload.maxBytes" should be an integer.',
212
+ minimum: 'AISDKAgent agent property "fileDownload.maxBytes" should be at least 1.'
213
+ }
214
+ },
215
+ timeout: {
216
+ type: 'integer',
217
+ minimum: 1,
218
+ description: 'Milliseconds a file download may take. Default: 30000.',
219
+ errorMessage: {
220
+ type: 'AISDKAgent agent property "fileDownload.timeout" should be an integer.',
221
+ minimum: 'AISDKAgent agent property "fileDownload.timeout" should be at least 1.'
222
+ }
223
+ }
224
+ },
225
+ additionalProperties: false,
226
+ errorMessage: {
227
+ type: 'AISDKAgent agent property "fileDownload" should be an object.',
228
+ additionalProperties: 'AISDKAgent agent property "fileDownload" should only have maxBytes and timeout.'
229
+ }
230
+ },
202
231
  pageContext: {
203
232
  type: 'boolean',
204
- description: 'When true, prepend page context (pageId, userId, conversationId, urlQuery) to instructions.',
233
+ description: 'When true, prepend page context (pageId, userId, conversationId, urlQuery, pathParams) to instructions.',
205
234
  errorMessage: {
206
235
  type: 'AISDKAgent agent property "pageContext" should be a boolean.'
207
236
  }
@@ -0,0 +1,222 @@
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 { RESERVED_QUESTION_IDS } from './decideQuestions.js';
16
+ const text = {
17
+ type: 'string',
18
+ minLength: 1
19
+ };
20
+ const choiceQuestion = {
21
+ type: 'object',
22
+ required: [
23
+ 'choice',
24
+ 'options'
25
+ ],
26
+ additionalProperties: false,
27
+ properties: {
28
+ choice: {
29
+ ...text,
30
+ description: 'What to decide — picks exactly one of "options".'
31
+ },
32
+ options: {
33
+ type: 'object',
34
+ minProperties: 2,
35
+ maxProperties: 255,
36
+ additionalProperties: {
37
+ anyOf: [
38
+ {
39
+ type: [
40
+ 'string',
41
+ 'null'
42
+ ]
43
+ },
44
+ {
45
+ type: 'object',
46
+ properties: {
47
+ description: {
48
+ type: [
49
+ 'string',
50
+ 'null'
51
+ ]
52
+ }
53
+ }
54
+ }
55
+ ]
56
+ },
57
+ description: 'Option names mapped to what each one means (null for no description), or to an object with a "description" — its other keys are ignored, so one file can describe the options for Decide and for a block such as IntentInput.'
58
+ }
59
+ }
60
+ };
61
+ const yesnoQuestion = {
62
+ type: 'object',
63
+ required: [
64
+ 'yesno'
65
+ ],
66
+ additionalProperties: false,
67
+ properties: {
68
+ yesno: {
69
+ ...text,
70
+ description: 'A statement to judge true or false.'
71
+ },
72
+ criteria: {
73
+ type: 'object',
74
+ additionalProperties: false,
75
+ properties: {
76
+ yes: {
77
+ type: 'string'
78
+ },
79
+ no: {
80
+ type: 'string'
81
+ }
82
+ },
83
+ description: 'Optional: what counts as yes and as no.'
84
+ }
85
+ }
86
+ };
87
+ const scoreQuestion = {
88
+ type: 'object',
89
+ required: [
90
+ 'score',
91
+ 'levels'
92
+ ],
93
+ additionalProperties: false,
94
+ properties: {
95
+ score: {
96
+ ...text,
97
+ description: 'What to rate — places the state on "levels".'
98
+ },
99
+ levels: {
100
+ type: 'array',
101
+ minItems: 2,
102
+ maxItems: 10,
103
+ items: {
104
+ type: 'string'
105
+ },
106
+ description: 'Ordered levels, lowest first.'
107
+ }
108
+ }
109
+ };
110
+ const BACKEND_DESCRIPTIONS = {
111
+ evaluation: 'evaluation — an evaluation model (e.g. "typesafe-ai/jev" on the AI Gateway): typed answers with calibrated probabilities, input tokens only.',
112
+ 'structured-output': "structured-output — any language model, asked for the answers as structured output; its confidence is the model's own estimate."
113
+ };
114
+ // One schema per connection type: the backends it offers set the enum, and
115
+ // the first is the default.
116
+ function decideSchema({ backends }) {
117
+ return {
118
+ $schema: 'http://json-schema.org/draft-07/schema#',
119
+ title: 'Lowdefy Request Schema - Decide',
120
+ type: 'object',
121
+ required: [
122
+ 'model',
123
+ 'state',
124
+ 'questions'
125
+ ],
126
+ properties: {
127
+ model: {
128
+ type: 'string',
129
+ description: 'Model id to decide with.',
130
+ errorMessage: {
131
+ type: 'Decide request property "model" should be a string.'
132
+ }
133
+ },
134
+ backend: {
135
+ type: 'string',
136
+ enum: backends,
137
+ description: `How the model is asked (default "${backends[0]}"): ${backends.map((backend)=>BACKEND_DESCRIPTIONS[backend]).join(' ')}`,
138
+ errorMessage: {
139
+ type: 'Decide request property "backend" should be a string.',
140
+ enum: `Decide request property "backend" should be one of: ${backends.join(', ')}.`
141
+ }
142
+ },
143
+ state: {
144
+ type: [
145
+ 'string',
146
+ 'object',
147
+ 'array'
148
+ ],
149
+ description: 'What the questions are about — text, an object or an array. Send only what the questions need.',
150
+ errorMessage: {
151
+ type: 'Decide request property "state" should be a string, object or array.'
152
+ }
153
+ },
154
+ questions: {
155
+ type: 'object',
156
+ minProperties: 1,
157
+ propertyNames: {
158
+ not: {
159
+ enum: RESERVED_QUESTION_IDS
160
+ }
161
+ },
162
+ additionalProperties: {
163
+ oneOf: [
164
+ choiceQuestion,
165
+ yesnoQuestion,
166
+ scoreQuestion
167
+ ],
168
+ errorMessage: 'Decide questions should be one of { choice, options }, { yesno, criteria? } or { score, levels }.'
169
+ },
170
+ description: 'Named questions, answered together against the state. Each id becomes a key of the response.',
171
+ errorMessage: {
172
+ type: 'Decide request property "questions" should be an object.',
173
+ minProperties: 'Decide request property "questions" should have at least one question.',
174
+ propertyNames: `Decide question ids may not be ${RESERVED_QUESTION_IDS.map((id)=>`"${id}"`).join(', ')} — the response uses them.`
175
+ }
176
+ },
177
+ maxRetries: {
178
+ type: 'integer',
179
+ minimum: 0,
180
+ description: 'Maximum number of retries. Defaults to 2.',
181
+ errorMessage: {
182
+ type: 'Decide request property "maxRetries" should be an integer.',
183
+ minimum: 'Decide request property "maxRetries" should be at least 0.'
184
+ }
185
+ },
186
+ maxOutputTokens: {
187
+ type: 'integer',
188
+ minimum: 1,
189
+ description: "Maximum number of tokens to generate, on the structured-output backend (an evaluation model generates no text). Defaults to the connection's maxOutputTokens.",
190
+ errorMessage: {
191
+ type: 'Decide request property "maxOutputTokens" should be an integer.',
192
+ minimum: 'Decide request property "maxOutputTokens" should be at least 1.'
193
+ }
194
+ },
195
+ timeout: {
196
+ type: 'integer',
197
+ minimum: 1,
198
+ description: "Milliseconds the model call may take, retries included, before it is cancelled. Defaults to the connection's timeout.",
199
+ errorMessage: {
200
+ type: 'Decide request property "timeout" should be an integer.',
201
+ minimum: 'Decide request property "timeout" should be at least 1.'
202
+ }
203
+ },
204
+ providerOptions: {
205
+ type: 'object',
206
+ description: 'Provider-specific options, keyed by provider (e.g. { gateway: { zeroDataRetention: true } }).',
207
+ errorMessage: {
208
+ type: 'Decide request property "providerOptions" should be an object.'
209
+ }
210
+ }
211
+ },
212
+ errorMessage: {
213
+ type: 'Decide request properties should be an object.',
214
+ required: {
215
+ model: 'Decide request should have required property "model".',
216
+ state: 'Decide request should have required property "state".',
217
+ questions: 'Decide request should have required property "questions".'
218
+ }
219
+ }
220
+ };
221
+ }
222
+ export default decideSchema;
@@ -73,10 +73,18 @@
73
73
  type: 'GenerateObject request property "system" should be a string.'
74
74
  }
75
75
  },
76
+ allowSystemInMessages: {
77
+ type: 'boolean',
78
+ default: false,
79
+ description: 'Allow "system" role messages in "messages". Off by default, since a system message instructs the model as the app: only enable it when the messages come from the app, never from a user.',
80
+ errorMessage: {
81
+ type: 'GenerateObject request property "allowSystemInMessages" should be a boolean.'
82
+ }
83
+ },
76
84
  maxOutputTokens: {
77
85
  type: 'integer',
78
86
  minimum: 1,
79
- description: 'Maximum number of tokens to generate.',
87
+ description: "Maximum number of tokens to generate. Defaults to the connection's maxOutputTokens.",
80
88
  errorMessage: {
81
89
  type: 'GenerateObject request property "maxOutputTokens" should be an integer.',
82
90
  minimum: 'GenerateObject request property "maxOutputTokens" should be at least 1.'
@@ -137,6 +145,44 @@
137
145
  minimum: 'GenerateObject request property "maxRetries" should be at least 0.'
138
146
  }
139
147
  },
148
+ timeout: {
149
+ type: 'integer',
150
+ minimum: 1,
151
+ description: "Milliseconds the model call may take, retries included, before it is cancelled. Defaults to the connection's timeout.",
152
+ errorMessage: {
153
+ type: 'GenerateObject request property "timeout" should be an integer.',
154
+ minimum: 'GenerateObject request property "timeout" should be at least 1.'
155
+ }
156
+ },
157
+ fileDownload: {
158
+ type: 'object',
159
+ description: 'Limits for a file link in "messages" the server downloads because the model does not take it as a link.',
160
+ properties: {
161
+ maxBytes: {
162
+ type: 'integer',
163
+ minimum: 1,
164
+ description: 'Largest file the server downloads, in bytes. Default: 20971520 (20 MB).',
165
+ errorMessage: {
166
+ type: 'GenerateObject request property "fileDownload.maxBytes" should be an integer.',
167
+ minimum: 'GenerateObject request property "fileDownload.maxBytes" should be at least 1.'
168
+ }
169
+ },
170
+ timeout: {
171
+ type: 'integer',
172
+ minimum: 1,
173
+ description: 'Milliseconds a file download may take. Default: 30000.',
174
+ errorMessage: {
175
+ type: 'GenerateObject request property "fileDownload.timeout" should be an integer.',
176
+ minimum: 'GenerateObject request property "fileDownload.timeout" should be at least 1.'
177
+ }
178
+ }
179
+ },
180
+ additionalProperties: false,
181
+ errorMessage: {
182
+ type: 'GenerateObject request property "fileDownload" should be an object.',
183
+ additionalProperties: 'GenerateObject request property "fileDownload" should only have maxBytes and timeout.'
184
+ }
185
+ },
140
186
  providerOptions: {
141
187
  type: 'object',
142
188
  description: 'Provider-specific options, keyed by provider.',
@@ -51,10 +51,18 @@
51
51
  type: 'GenerateText request property "system" should be a string.'
52
52
  }
53
53
  },
54
+ allowSystemInMessages: {
55
+ type: 'boolean',
56
+ default: false,
57
+ description: 'Allow "system" role messages in "messages". Off by default, since a system message instructs the model as the app: only enable it when the messages come from the app, never from a user.',
58
+ errorMessage: {
59
+ type: 'GenerateText request property "allowSystemInMessages" should be a boolean.'
60
+ }
61
+ },
54
62
  maxOutputTokens: {
55
63
  type: 'integer',
56
64
  minimum: 1,
57
- description: 'Maximum number of tokens to generate.',
65
+ description: "Maximum number of tokens to generate. Defaults to the connection's maxOutputTokens.",
58
66
  errorMessage: {
59
67
  type: 'GenerateText request property "maxOutputTokens" should be an integer.',
60
68
  minimum: 'GenerateText request property "maxOutputTokens" should be at least 1.'
@@ -125,6 +133,44 @@
125
133
  minimum: 'GenerateText request property "maxRetries" should be at least 0.'
126
134
  }
127
135
  },
136
+ timeout: {
137
+ type: 'integer',
138
+ minimum: 1,
139
+ description: "Milliseconds the model call may take, retries included, before it is cancelled. Defaults to the connection's timeout.",
140
+ errorMessage: {
141
+ type: 'GenerateText request property "timeout" should be an integer.',
142
+ minimum: 'GenerateText request property "timeout" should be at least 1.'
143
+ }
144
+ },
145
+ fileDownload: {
146
+ type: 'object',
147
+ description: 'Limits for a file link in "messages" the server downloads because the model does not take it as a link.',
148
+ properties: {
149
+ maxBytes: {
150
+ type: 'integer',
151
+ minimum: 1,
152
+ description: 'Largest file the server downloads, in bytes. Default: 20971520 (20 MB).',
153
+ errorMessage: {
154
+ type: 'GenerateText request property "fileDownload.maxBytes" should be an integer.',
155
+ minimum: 'GenerateText request property "fileDownload.maxBytes" should be at least 1.'
156
+ }
157
+ },
158
+ timeout: {
159
+ type: 'integer',
160
+ minimum: 1,
161
+ description: 'Milliseconds a file download may take. Default: 30000.',
162
+ errorMessage: {
163
+ type: 'GenerateText request property "fileDownload.timeout" should be an integer.',
164
+ minimum: 'GenerateText request property "fileDownload.timeout" should be at least 1.'
165
+ }
166
+ }
167
+ },
168
+ additionalProperties: false,
169
+ errorMessage: {
170
+ type: 'GenerateText request property "fileDownload" should be an object.',
171
+ additionalProperties: 'GenerateText request property "fileDownload" should only have maxBytes and timeout.'
172
+ }
173
+ },
128
174
  providerOptions: {
129
175
  type: 'object',
130
176
  description: 'Provider-specific options, keyed by provider.',
@@ -12,24 +12,17 @@
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 { ToolLoopAgent, tool, jsonSchema, stepCountIs } from 'ai';
15
+ */ import { ToolLoopAgent, tool, jsonSchema, isStepCount } from 'ai';
16
16
  import { createMCPClient } from '@ai-sdk/mcp';
17
17
  import { Experimental_StdioMCPTransport } from '@ai-sdk/mcp/mcp-stdio';
18
- import { ConfigError } from '@lowdefy/errors';
19
- import { getKey, isReserved, serializer, setKey, translate } from '@lowdefy/helpers';
18
+ import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
19
+ import { cleanBuildArtifact, getKey, isReserved, serializer, setKey, translate } from '@lowdefy/helpers';
20
20
  import listFiles from './fileSystem/listFiles.js';
21
21
  import readFile from './fileSystem/readFile.js';
22
22
  import searchFiles from './fileSystem/searchFiles.js';
23
23
  import statFile from './fileSystem/statFile.js';
24
+ import buildToolInputSchema from './buildToolInputSchema.js';
24
25
  import RESERVED_PLATFORM_TOOL_NAMES from './reservedToolNames.js';
25
- // Build artifacts carry serializer markers (~k, ~r, ~l) and wrap location-marked
26
- // arrays as { '~arr': [...], '~k': '...' }. serializer.deserialize un-wraps
27
- // ~arr back to a plain array and demotes markers to non-enumerable properties;
28
- // the subsequent JSON round-trip drops those non-enumerable markers, leaving a
29
- // clean structure for the AI SDK.
30
- function cleanBuildArtifact(obj) {
31
- return JSON.parse(JSON.stringify(serializer.deserialize(obj)));
32
- }
33
26
  function assertNotPlatformToolName(name, kind, i18n) {
34
27
  if (RESERVED_PLATFORM_TOOL_NAMES.includes(name)) {
35
28
  throw new ConfigError(translate({
@@ -43,12 +36,16 @@ function assertNotPlatformToolName(name, kind, i18n) {
43
36
  }));
44
37
  }
45
38
  }
46
- // autoApprove skips needsApproval on confirm tools — used by headless
47
- // run-to-completion agents, where no client exists to resolve an approval.
39
+ // Confirm tools need a person's approval before they run. Since ai v7 approval
40
+ // is a call-level setting rather than a tool property, so the builder returns
41
+ // it beside the tools: `toolApproval` maps each confirm tool's name to
42
+ // 'user-approval', for the ToolLoopAgent that owns the tools. autoApprove
43
+ // leaves it empty — used by headless run-to-completion agents, where no client
44
+ // exists to resolve an approval.
48
45
  async function buildAgentTools({ agent, context, depth = 0, autoApprove = false }) {
49
46
  const MAX_DEPTH = 5;
50
47
  if (depth > MAX_DEPTH) {
51
- throw new Error(translate({
48
+ throw new ConfigError(translate({
52
49
  key: 'agent.runtime.subAgentDepthExceeded',
53
50
  values: {
54
51
  max: MAX_DEPTH
@@ -57,7 +54,9 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
57
54
  }));
58
55
  }
59
56
  const tools = {};
57
+ const toolApproval = {};
60
58
  const mcpClients = [];
59
+ const requireApproval = (name)=>setKey(toolApproval, name, 'user-approval');
61
60
  // Build endpoint tools. The model-facing tool name is toolConfig.name
62
61
  // (assigned by buildAgents — endpoint id with '/' → '__' unless overridden);
63
62
  // execution still targets the endpointId.
@@ -67,37 +66,47 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
67
66
  assertNotPlatformToolName(toolName, 'Endpoint tool', context.i18n);
68
67
  // A second, disjoint list: RESERVED_PLATFORM_TOOL_NAMES are the tools Lowdefy itself registers,
69
68
  // isReserved are the prototype-pollution keys setKey refuses. A name can pass one gate and fail
70
- // the other, so both checks are needed. The build rejects reserved key names, so this only fires
71
- // for a stale or hand-edited build artifact. Skip the tool rather than fail the whole agent, as
72
- // the MCP name cases below do.
69
+ // the other, so both checks are needed. The build rejects reserved key names, so this can only
70
+ // fire for a stale or hand-edited build artifact - an invariant violation, not a config fault.
73
71
  if (isReserved(toolName)) {
74
- console.warn(`Endpoint tool "${toolName}" uses a reserved key name — skipped.`);
75
- continue;
72
+ throw new LowdefyInternalError(`Endpoint tool "${toolName}" uses a reserved key name.`);
76
73
  }
77
74
  const endpointConfig = await context.getEndpointConfig({
78
75
  endpointId
79
76
  });
77
+ const { inputSchema, description } = buildToolInputSchema({
78
+ schema: cleanBuildArtifact(endpointConfig.payloadSchema),
79
+ description: endpointConfig.description
80
+ });
80
81
  setKey(tools, toolName, tool({
81
- description: endpointConfig.description,
82
- inputSchema: jsonSchema(cleanBuildArtifact(endpointConfig.payloadSchema)),
83
- ...confirm && !autoApprove ? {
84
- needsApproval: true
85
- } : {},
82
+ description,
83
+ inputSchema: jsonSchema(inputSchema),
86
84
  execute: async (input, { abortSignal } = {})=>{
85
+ // The model built the input, so a payload the endpoint's schema refuses
86
+ // is the model's mistake to correct, not a config fault.
87
87
  const result = await context.callEndpoint(endpointId, {
88
88
  payload: input,
89
- abortSignal
89
+ abortSignal,
90
+ outsideCaller: true
90
91
  });
91
92
  if (!result.success) {
92
93
  const err = serializer.deserialize(result.error);
94
+ // A Lowdefy error already carries its class, cause and location -
95
+ // rewrapping it as a plain Error would lose all three.
96
+ if (err?.isLowdefyError) {
97
+ throw err;
98
+ }
93
99
  throw new Error(err?.message ?? translate({
94
100
  key: 'agent.runtime.toolExecutionFailed',
95
101
  i18n: context.i18n
96
- }));
102
+ }), {
103
+ cause: err
104
+ });
97
105
  }
98
106
  return cleanBuildArtifact(result.response);
99
107
  }
100
108
  }));
109
+ if (confirm && !autoApprove) requireApproval(toolName);
101
110
  }
102
111
  // Build MCP clients and merge their tools
103
112
  for (const mcpSource of agent.mcp ?? []){
@@ -131,7 +140,9 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
131
140
  });
132
141
  } catch (err) {
133
142
  const label = evaluatedSource.transport === 'stdio' ? evaluatedSource.command : evaluatedSource.url;
134
- console.warn(`MCP server "${label}" unreachable: ${err.message}`);
143
+ context.logger.warn({
144
+ err
145
+ }, `MCP server "${label}" unreachable.`);
135
146
  }
136
147
  }
137
148
  // Merge MCP tools with endpoint tools.
@@ -143,28 +154,27 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
143
154
  const mcpTools = await client.tools();
144
155
  for (const [name, mcpTool] of Object.entries(mcpTools)){
145
156
  if (RESERVED_PLATFORM_TOOL_NAMES.includes(name)) {
146
- console.warn(`MCP tool "${name}" from ${source.url ?? source.command} ` + `uses a reserved platform tool name — skipped.`);
157
+ context.logger.warn(`MCP tool "${name}" from ${source.url ?? source.command} ` + `uses a reserved platform tool name — skipped.`);
147
158
  continue;
148
159
  }
149
160
  // Same policy as the reserved-platform-name and collision cases above:
150
161
  // MCP tool names are not under app control, so warn and skip.
151
162
  if (isReserved(name)) {
152
- console.warn(`MCP tool "${name}" from ${source.url ?? source.command} ` + `uses a reserved key name — skipped.`);
163
+ context.logger.warn(`MCP tool "${name}" from ${source.url ?? source.command} ` + `uses a reserved key name — skipped.`);
153
164
  continue;
154
165
  }
155
166
  if (getKey(tools, name)) {
156
- console.warn(`MCP tool "${name}" from ${source.url ?? source.command} ` + `conflicts with endpoint tool — skipped.`);
167
+ context.logger.warn(`MCP tool "${name}" from ${source.url ?? source.command} ` + `conflicts with endpoint tool — skipped.`);
157
168
  continue;
158
169
  }
159
- const needsApproval = source.confirm && !autoApprove;
160
- setKey(tools, name, needsApproval ? {
161
- ...mcpTool,
162
- needsApproval: true
163
- } : mcpTool);
170
+ setKey(tools, name, mcpTool);
171
+ if (source.confirm && !autoApprove) requireApproval(name);
164
172
  }
165
173
  } catch (err) {
166
174
  const label = source.transport === 'stdio' ? source.command : source.url;
167
- console.warn(`MCP server "${label}" tool listing failed: ${err.message}`);
175
+ context.logger.warn({
176
+ err
177
+ }, `MCP server "${label}" tool listing failed.`);
168
178
  }
169
179
  }
170
180
  // Build sub-agent tools — keyed by name for the same provider-rule reason
@@ -172,11 +182,9 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
172
182
  for (const subAgentRef of agent.agents ?? []){
173
183
  const subAgentToolName = subAgentRef.name ?? subAgentRef.agentId;
174
184
  assertNotPlatformToolName(subAgentToolName, 'Sub-agent', context.i18n);
175
- // Same policy as the endpoint tool name above: unreachable from valid config, so skip rather
176
- // than fail the whole agent.
185
+ // Same as the endpoint tool name above: unreachable from a valid build artifact.
177
186
  if (isReserved(subAgentToolName)) {
178
- console.warn(`Sub-agent tool "${subAgentToolName}" uses a reserved key name — skipped.`);
179
- continue;
187
+ throw new LowdefyInternalError(`Sub-agent tool "${subAgentToolName}" uses a reserved key name.`);
180
188
  }
181
189
  const subAgentConfig = await context.getAgentConfig({
182
190
  agentId: subAgentRef.agentId
@@ -188,7 +196,7 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
188
196
  agentConfig: subAgentConfig
189
197
  });
190
198
  // Recursively build sub-agent's tools
191
- const { tools: subTools, mcpClients: subMcpClients } = await buildAgentTools({
199
+ const { tools: subTools, mcpClients: subMcpClients, toolApproval: subToolApproval } = await buildAgentTools({
192
200
  agent: subAgentConfig,
193
201
  context,
194
202
  depth: depth + 1,
@@ -199,7 +207,8 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
199
207
  model: subModel,
200
208
  instructions: subAgentConfig.properties.instructions,
201
209
  tools: subTools,
202
- stopWhen: stepCountIs(subAgentConfig.properties.maxSteps ?? 10),
210
+ toolApproval: subToolApproval,
211
+ stopWhen: isStepCount(subAgentConfig.properties.maxSteps ?? 10),
203
212
  maxOutputTokens: subAgentConfig.properties.maxOutputTokens,
204
213
  temperature: subAgentConfig.properties.temperature,
205
214
  toolChoice: subAgentConfig.properties.toolChoice ?? 'auto',
@@ -320,7 +329,8 @@ async function buildAgentTools({ agent, context, depth = 0, autoApprove = false
320
329
  }
321
330
  return {
322
331
  tools,
323
- mcpClients
332
+ mcpClients,
333
+ toolApproval
324
334
  };
325
335
  }
326
336
  export default buildAgentTools;
@@ -0,0 +1,35 @@
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 { type } from '@lowdefy/helpers';
16
+ // The limits an AI request's provider call runs under: the request's maxOutputTokens
17
+ // and timeout, else the defaults set on its connection, and the signal of the request
18
+ // that started it, so a closed request (the client gone, the server's request timeout)
19
+ // cancels the provider call instead of letting it run, and bill, to the end.
20
+ function buildCallLimits({ connection, request, signal }) {
21
+ const limits = {};
22
+ const maxOutputTokens = request.maxOutputTokens ?? connection.maxOutputTokens;
23
+ if (!type.isNone(maxOutputTokens)) {
24
+ limits.maxOutputTokens = maxOutputTokens;
25
+ }
26
+ const timeout = request.timeout ?? connection.timeout;
27
+ if (!type.isNone(timeout)) {
28
+ limits.timeout = timeout;
29
+ }
30
+ if (!type.isNone(signal)) {
31
+ limits.abortSignal = signal;
32
+ }
33
+ return limits;
34
+ }
35
+ export default buildCallLimits;