@bevel-software/platform-mcp-core 0.23.0 → 0.24.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/chain-example.d.ts +58 -0
- package/dist/chain-example.d.ts.map +1 -0
- package/dist/chain-example.js +259 -0
- package/dist/chain-example.js.map +1 -0
- package/dist/chain-runtime.d.ts +122 -0
- package/dist/chain-runtime.d.ts.map +1 -0
- package/dist/chain-runtime.js +352 -0
- package/dist/chain-runtime.js.map +1 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/meta-tools.d.ts +100 -1
- package/dist/meta-tools.d.ts.map +1 -1
- package/dist/meta-tools.js +181 -53
- package/dist/meta-tools.js.map +1 -1
- package/dist/results.d.ts +20 -0
- package/dist/results.d.ts.map +1 -1
- package/dist/results.js +111 -1
- package/dist/results.js.map +1 -1
- package/dist/retired-tools.d.ts +0 -12
- package/dist/retired-tools.d.ts.map +1 -1
- package/dist/retired-tools.js +0 -22
- package/dist/retired-tools.js.map +1 -1
- package/package.json +1 -1
- package/src/chain-example.ts +315 -0
- package/src/chain-runtime.ts +382 -0
- package/src/index.ts +29 -2
- package/src/meta-tools.ts +212 -58
- package/src/results.ts +106 -1
- package/src/retired-tools.ts +0 -22
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import type { CodeModeUtcpClient } from '@utcp/code-mode';
|
|
2
|
+
import { utcpNameToTsInterfaceName } from './code-mode-names.js';
|
|
3
|
+
import { describeToolFailure } from './results.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What runs a `call_tool_chain` chain, for every surface that offers one: the
|
|
7
|
+
* hosted MCP proxy, the local `hexis-mcp` server and the in-process agent's
|
|
8
|
+
* Mastra tool.
|
|
9
|
+
*
|
|
10
|
+
* Three things live here because all three surfaces need them to be the same:
|
|
11
|
+
*
|
|
12
|
+
* - the BROWSER GLOBALS a chain is promised (`atob`, `btoa`, `TextEncoder`,
|
|
13
|
+
* `TextDecoder`). `@utcp/code-mode` runs the chain in a bare `isolated-vm`
|
|
14
|
+
* isolate — plain V8, so no Node globals (`Buffer`) and no web platform
|
|
15
|
+
* (`atob`), and a chain could not decode base64 or bytes at all. They are
|
|
16
|
+
* added as a PRELUDE to the chain's own source rather than injected into
|
|
17
|
+
* the isolate's context, because the isolate is created inside
|
|
18
|
+
* `callToolChain` and is reachable from nowhere else (see
|
|
19
|
+
* {@link CHAIN_RUNTIME_PRELUDE});
|
|
20
|
+
* - the ANSWER for a chain that failed. `callToolChain` does not throw when
|
|
21
|
+
* the chain dies: it resolves `{ result: null, logs: ['[ERROR] Code
|
|
22
|
+
* execution failed: …'] }`, so a surface that read only `result` reported
|
|
23
|
+
* `success: true` with a null result and the agent was told nothing. Every
|
|
24
|
+
* failure — a timeout, an undefined namespace, a tool that threw — becomes
|
|
25
|
+
* an error that says what happened;
|
|
26
|
+
* - the promise that a chain ALWAYS answers. A request that never settles is
|
|
27
|
+
* what reaches an agent as a dropped connection rather than as something it
|
|
28
|
+
* can act on, so the runner is raced against a watchdog (see
|
|
29
|
+
* {@link WATCHDOG_GRACE_MS}).
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The largest `timeout` a chain may ask for, in milliseconds. One constant: it
|
|
34
|
+
* is the schema's bound on every surface AND the figure the timeout error tells
|
|
35
|
+
* the agent it may raise `timeout` to, and those two drifting apart would send
|
|
36
|
+
* an agent to retry with a value the schema then clamps straight back down.
|
|
37
|
+
*/
|
|
38
|
+
export const CHAIN_TIMEOUT_MAX_MS = 120_000;
|
|
39
|
+
|
|
40
|
+
/** The smallest `timeout` a chain may ask for, in milliseconds. */
|
|
41
|
+
export const CHAIN_TIMEOUT_MIN_MS = 1_000;
|
|
42
|
+
|
|
43
|
+
/** The `timeout` a chain that does not ask for one gets, in milliseconds. */
|
|
44
|
+
export const CHAIN_TIMEOUT_DEFAULT_MS = 30_000;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* How long past its own `timeout` the runner is given to answer before the
|
|
48
|
+
* watchdog answers for it. `callToolChain` enforces the timeout itself and so
|
|
49
|
+
* normally settles well inside this; the watchdog covers the case where it does
|
|
50
|
+
* not, where the alternative is a request that hangs until the client gives up
|
|
51
|
+
* — the dropped connection an agent cannot tell from a crash.
|
|
52
|
+
*/
|
|
53
|
+
const WATCHDOG_GRACE_MS = 5_000;
|
|
54
|
+
|
|
55
|
+
/** The log line `@utcp/code-mode` records when a chain's code fails. */
|
|
56
|
+
const CHAIN_FAILURE_LOG = '[ERROR] Code execution failed: ';
|
|
57
|
+
|
|
58
|
+
/** The runner's own wording for a chain it stopped at the timeout. */
|
|
59
|
+
const RUNNER_TIMEOUT = /Script execution timeout after (\d+)\s*ms/;
|
|
60
|
+
|
|
61
|
+
/** `isolated-vm`'s wording when V8 itself terminated the script at the deadline. */
|
|
62
|
+
const ISOLATE_TERMINATED = /Script execution timed out|execution was terminated|script execution interrupted/i;
|
|
63
|
+
|
|
64
|
+
/** `isolated-vm`'s wording when the chain exhausted the isolate's heap. */
|
|
65
|
+
const ISOLATE_OUT_OF_MEMORY = /memory limit|out of memory|allocation failed/i;
|
|
66
|
+
|
|
67
|
+
/** The identifier a chain named that the isolate has no binding for. */
|
|
68
|
+
const UNDEFINED_IDENTIFIER = /ReferenceError: ([A-Za-z_$][\w$]*) is not defined/;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The browser globals, as ONE physical line of plain ES5 JavaScript.
|
|
72
|
+
*
|
|
73
|
+
* One line on purpose. The prelude is prepended to the agent's own chain
|
|
74
|
+
* source, and a failed chain is reported with its stack in it; a multi-line
|
|
75
|
+
* prelude would shift every line number in that stack and point the agent at
|
|
76
|
+
* the wrong line of its own code. Prepended WITHOUT a trailing newline for the
|
|
77
|
+
* same reason, so the chain's first line stays line one. (The one casualty is
|
|
78
|
+
* a `'use strict'` directive written as a chain's first statement, which is no
|
|
79
|
+
* longer in first position and so no longer applies. A chain is a handful of
|
|
80
|
+
* statements against a tool catalog, and strict mode is not something the
|
|
81
|
+
* chain protocol ever offered.)
|
|
82
|
+
*
|
|
83
|
+
* `atob`/`btoa` follow WHATWG forgiving-base64: ASCII whitespace is stripped,
|
|
84
|
+
* the padding is optional, and anything else throws rather than decoding to
|
|
85
|
+
* silent garbage. `TextEncoder`/`TextDecoder` are UTF-8 only — that is the
|
|
86
|
+
* encoding the Specification asks for, and a decoder that took a `label` it
|
|
87
|
+
* then ignored would quietly answer mojibake. `TextDecoder` drops a leading
|
|
88
|
+
* byte-order mark the way a browser's default does, and keeps it under
|
|
89
|
+
* `{ ignoreBOM: true }`: a chain decoding a UTF-8 file written on Windows would
|
|
90
|
+
* otherwise find a stray `\uFEFF` at the front of it, which breaks a
|
|
91
|
+
* `JSON.parse` and every exact-match comparison. It honours `{ stream: true }`:
|
|
92
|
+
* a chain that decodes bytes in pieces gets a character whose bytes straddle
|
|
93
|
+
* two pieces whole, where a decoder that started afresh on every call returned
|
|
94
|
+
* two replacement characters for it — and a call without the option ends the
|
|
95
|
+
* stream, answering a sequence left unfinished as one. Each is defined only when the
|
|
96
|
+
* runtime does not already have it, so a future `@utcp/code-mode` that ships
|
|
97
|
+
* them natively wins.
|
|
98
|
+
*/
|
|
99
|
+
export const CHAIN_RUNTIME_PRELUDE: string = [
|
|
100
|
+
'(function(g){',
|
|
101
|
+
"var A='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';",
|
|
102
|
+
'if(typeof g.btoa!=="function"){g.btoa=function(input){',
|
|
103
|
+
'var s=String(input),i,o="";',
|
|
104
|
+
'for(i=0;i<s.length;i++){if(s.charCodeAt(i)>255)throw new Error("InvalidCharacterError: btoa() takes a string whose every character is in the Latin-1 range (0-255). To base64 text, encode it to UTF-8 bytes with TextEncoder first.");}',
|
|
105
|
+
'for(i=0;i<s.length;i+=3){',
|
|
106
|
+
'var b0=s.charCodeAt(i),b1=s.charCodeAt(i+1),b2=s.charCodeAt(i+2),h1=!isNaN(b1),h2=!isNaN(b2);',
|
|
107
|
+
'o+=A.charAt(b0>>2)+A.charAt(((b0&3)<<4)|(h1?b1>>4:0));',
|
|
108
|
+
'o+=(h1?A.charAt(((b1&15)<<2)|(h2?b2>>6:0)):"=")+(h2?A.charAt(b2&63):"=");',
|
|
109
|
+
'}return o;};}',
|
|
110
|
+
'if(typeof g.atob!=="function"){g.atob=function(input){',
|
|
111
|
+
'var s=String(input).replace(/[\\t\\n\\f\\r ]/g,"");',
|
|
112
|
+
'if(s.length%4===0)s=s.replace(/==?$/,"");',
|
|
113
|
+
'if(s.length%4===1||/[^+\\/0-9A-Za-z]/.test(s))throw new Error("InvalidCharacterError: atob() was given a string that is not valid base64.");',
|
|
114
|
+
'var o="",buf=0,bits=0,i;',
|
|
115
|
+
'for(i=0;i<s.length;i++){buf=(buf<<6)|A.indexOf(s.charAt(i));bits+=6;',
|
|
116
|
+
'if(bits>=8){bits-=8;o+=String.fromCharCode((buf>>bits)&255);}}',
|
|
117
|
+
'return o;};}',
|
|
118
|
+
'if(typeof g.TextEncoder!=="function"){',
|
|
119
|
+
'var TE=function TextEncoder(){};',
|
|
120
|
+
'TE.prototype.encoding="utf-8";',
|
|
121
|
+
'TE.prototype.encode=function(input){',
|
|
122
|
+
'var s=String(input===undefined?"":input),out=[],i=0;',
|
|
123
|
+
'while(i<s.length){var c=s.codePointAt(i);i+=c>65535?2:1;',
|
|
124
|
+
'if(c<128)out.push(c);',
|
|
125
|
+
'else if(c<2048)out.push(192|(c>>6),128|(c&63));',
|
|
126
|
+
'else if(c>=55296&&c<=57343)out.push(239,191,189);',
|
|
127
|
+
'else if(c<65536)out.push(224|(c>>12),128|((c>>6)&63),128|(c&63));',
|
|
128
|
+
'else out.push(240|(c>>18),128|((c>>12)&63),128|((c>>6)&63),128|(c&63));}',
|
|
129
|
+
'return new Uint8Array(out);};',
|
|
130
|
+
'g.TextEncoder=TE;}',
|
|
131
|
+
'if(typeof g.TextDecoder!=="function"){',
|
|
132
|
+
'var TD=function TextDecoder(label,options){',
|
|
133
|
+
'var e=String(label===undefined?"utf-8":label).toLowerCase();',
|
|
134
|
+
'if(e!=="utf-8"&&e!=="utf8"&&e!=="unicode-1-1-utf-8")throw new RangeError("TextDecoder(): the tool-chain runtime decodes UTF-8 only, not \\""+label+"\\".");',
|
|
135
|
+
'this.ignoreBOM=!!(options&&options.ignoreBOM);};',
|
|
136
|
+
'TD.prototype.encoding="utf-8";',
|
|
137
|
+
'TD.prototype.ignoreBOM=false;',
|
|
138
|
+
// `p` is what one call leaves for the next under `{ stream: true }`: the
|
|
139
|
+
// sequence in progress (need, seen, c and the bounds on its next byte) and
|
|
140
|
+
// whether the stream has produced its first character yet, which is the
|
|
141
|
+
// only place a byte-order mark is one.
|
|
142
|
+
'TD.prototype.decode=function(input,options){',
|
|
143
|
+
'var st=!!(options&&options.stream),ig=this.ignoreBOM,p=this._p||[0,0,0,128,191,0];',
|
|
144
|
+
'var b=(input===undefined||input===null)?new Uint8Array(0):(input instanceof Uint8Array?input:(input instanceof ArrayBuffer?new Uint8Array(input):(input&&input.buffer instanceof ArrayBuffer?new Uint8Array(input.buffer,input.byteOffset,input.byteLength):new Uint8Array(input))));',
|
|
145
|
+
'var o="",n=b.length,need=p[0],seen=p[1],c=p[2],lo=p[3],hi=p[4],bom=p[5],i=0,x,t;',
|
|
146
|
+
'while(i<n){x=b[i];',
|
|
147
|
+
'if(need===0){i++;',
|
|
148
|
+
'if(x<128){bom=1;o+=String.fromCharCode(x);}',
|
|
149
|
+
'else if(x>=194&&x<=223){need=1;c=x&31;}',
|
|
150
|
+
'else if(x>=224&&x<=239){if(x===224)lo=160;if(x===237)hi=159;need=2;c=x&15;}',
|
|
151
|
+
'else if(x>=240&&x<=244){if(x===240)lo=144;if(x===244)hi=143;need=3;c=x&7;}',
|
|
152
|
+
'else{bom=1;o+="\\uFFFD";}',
|
|
153
|
+
'continue;}',
|
|
154
|
+
'if(x<lo||x>hi){need=0;seen=0;c=0;lo=128;hi=191;bom=1;o+="\\uFFFD";continue;}',
|
|
155
|
+
'lo=128;hi=191;i++;c=(c<<6)|(x&63);seen++;',
|
|
156
|
+
'if(seen===need){',
|
|
157
|
+
'if(c===65279&&!bom&&!ig){}',
|
|
158
|
+
'else if(c<=65535)o+=String.fromCharCode(c);',
|
|
159
|
+
'else{t=c-65536;o+=String.fromCharCode(55296+(t>>10),56320+(t&1023));}',
|
|
160
|
+
'bom=1;need=0;seen=0;c=0;}}',
|
|
161
|
+
'if(st){this._p=[need,seen,c,lo,hi,bom];return o;}',
|
|
162
|
+
'if(need!==0)o+="\\uFFFD";',
|
|
163
|
+
'this._p=null;',
|
|
164
|
+
'return o;};',
|
|
165
|
+
'g.TextDecoder=TD;}',
|
|
166
|
+
'})(globalThis);',
|
|
167
|
+
].join('');
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The agent's chain source with the runtime prelude in front of it, on the same
|
|
171
|
+
* physical line, so a stack from the chain still names the chain's own line
|
|
172
|
+
* numbers (see {@link CHAIN_RUNTIME_PRELUDE}).
|
|
173
|
+
*/
|
|
174
|
+
export function withChainRuntime(code: string): string {
|
|
175
|
+
return `${CHAIN_RUNTIME_PRELUDE}${code}`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The outcome of a chain: either its value, or the reason it has none. */
|
|
179
|
+
export type ToolChainOutcome =
|
|
180
|
+
| { ok: true; result: unknown; logs: string[] }
|
|
181
|
+
| { ok: false; error: string; logs: string[]; status?: number; data?: unknown };
|
|
182
|
+
|
|
183
|
+
/** The namespaces and bare functions a chain can call, as the runtime spells them. */
|
|
184
|
+
export interface ChainNamespaces {
|
|
185
|
+
namespaces: string[];
|
|
186
|
+
bare: string[];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* What a chain can actually call. `@utcp/code-mode` gives every tool whose UTCP
|
|
191
|
+
* name is `MANUAL.tool` a `global.MANUAL` object, so the namespaces are the
|
|
192
|
+
* sanitized manual names — and a tool registered under a bare name becomes a
|
|
193
|
+
* global function rather than a namespace, which is why those are listed apart.
|
|
194
|
+
*/
|
|
195
|
+
export async function chainNamespaces(client: CodeModeUtcpClient): Promise<ChainNamespaces> {
|
|
196
|
+
const namespaces = new Set<string>();
|
|
197
|
+
const bare = new Set<string>();
|
|
198
|
+
for (const tool of await client.config.tool_repository.getTools()) {
|
|
199
|
+
const tsName = utcpNameToTsInterfaceName(tool.name);
|
|
200
|
+
const dot = tsName.indexOf('.');
|
|
201
|
+
if (dot > 0) namespaces.add(tsName.slice(0, dot));
|
|
202
|
+
else bare.add(tsName);
|
|
203
|
+
}
|
|
204
|
+
return { namespaces: [...namespaces].sort(), bare: [...bare].sort() };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** What a chain is told when it timed out: the limit it hit, and how to raise it. */
|
|
208
|
+
export function chainTimeoutMessage(timeoutMs: number): string {
|
|
209
|
+
return (
|
|
210
|
+
`The tool chain timed out after ${timeoutMs} ms and was stopped, so it has no result. ` +
|
|
211
|
+
`Raise \`timeout\` (milliseconds, up to a maximum of ${CHAIN_TIMEOUT_MAX_MS}) and run it again, ` +
|
|
212
|
+
'or split the work across several shorter chains. The connection is unaffected — your next tool call works as usual.'
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** What a chain is told when it exhausted the isolate's heap. */
|
|
217
|
+
export function chainOutOfMemoryMessage(reason: string): string {
|
|
218
|
+
return (
|
|
219
|
+
`The tool chain ran out of memory and was stopped, so it has no result (${reason}). ` +
|
|
220
|
+
'Return less from the chain — filter, map or count inside it instead of accumulating every record — ' +
|
|
221
|
+
'or split the work across several chains. The connection is unaffected — your next tool call works as usual.'
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** What a chain is told when it named something the runtime has no binding for. */
|
|
226
|
+
export function unknownNamespaceMessage(identifier: string, found: ChainNamespaces): string {
|
|
227
|
+
const { namespaces, bare } = found;
|
|
228
|
+
const existing = namespaces.length
|
|
229
|
+
? `The tool namespaces this connection exposes are: ${namespaces.join(', ')}.`
|
|
230
|
+
: 'This connection exposes no tool namespaces at all.';
|
|
231
|
+
const example = namespaces[0] ? ` Call a tool as \`${namespaces[0]}.<tool>({ body: { … } })\`.` : '';
|
|
232
|
+
const bareNote = bare.length ? ` Callable without a namespace: ${bare.join(', ')}.` : '';
|
|
233
|
+
return (
|
|
234
|
+
`ReferenceError: ${identifier} is not defined — "${identifier}" is not one of them. ` +
|
|
235
|
+
`${existing}${example}${bareNote} Use \`list_tools\` for the exact callable names.`
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Why a RESOLVED `callToolChain` is a failure, or undefined when it is not one.
|
|
241
|
+
*
|
|
242
|
+
* `callToolChain` resolves rather than throws on a dead chain, reporting it as
|
|
243
|
+
* a `[ERROR] Code execution failed: …` log line with a null result. Both halves
|
|
244
|
+
* are required: a chain that returned a value succeeded however it logged.
|
|
245
|
+
*
|
|
246
|
+
* The LAST such line, not the last line: the runner appends its own entry in a
|
|
247
|
+
* `catch` and then, in the `finally`, a `[WARN] Tool call "…" abandoned` line
|
|
248
|
+
* per tool call still in flight — so a chain that timed out mid-call has the
|
|
249
|
+
* reason second-from-last or further back. A chain that prints that exact
|
|
250
|
+
* prefix itself through `console.error` AND returns null is read as a failure;
|
|
251
|
+
* that trade is deliberate, since the alternative — a dead chain reported as a
|
|
252
|
+
* success with a null result — is the bug this replaces.
|
|
253
|
+
*/
|
|
254
|
+
function failureReason(outcome: { result: unknown; logs: string[] }): string | undefined {
|
|
255
|
+
if (outcome.result !== null && outcome.result !== undefined) return undefined;
|
|
256
|
+
for (let i = outcome.logs.length - 1; i >= 0; i -= 1) {
|
|
257
|
+
const line = outcome.logs[i];
|
|
258
|
+
if (typeof line === 'string' && line.startsWith(CHAIN_FAILURE_LOG)) {
|
|
259
|
+
return line.slice(CHAIN_FAILURE_LOG.length);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Turn the runner's reason into the sentence the agent reads. A timeout, an
|
|
267
|
+
* exhausted heap and an undefined namespace each get their own; anything else
|
|
268
|
+
* passes through exactly as the runner reported it, so a real cause is never
|
|
269
|
+
* replaced by a guess.
|
|
270
|
+
*/
|
|
271
|
+
export async function describeChainFailure(
|
|
272
|
+
client: CodeModeUtcpClient,
|
|
273
|
+
reason: string,
|
|
274
|
+
timeoutMs: number,
|
|
275
|
+
): Promise<string> {
|
|
276
|
+
// Memory before termination: an isolate killed for its heap reports being
|
|
277
|
+
// disposed too, and calling that a timeout would send the agent to raise a
|
|
278
|
+
// limit that was never the problem.
|
|
279
|
+
if (ISOLATE_OUT_OF_MEMORY.test(reason)) return chainOutOfMemoryMessage(reason);
|
|
280
|
+
const runnerTimeout = RUNNER_TIMEOUT.exec(reason);
|
|
281
|
+
if (runnerTimeout) return chainTimeoutMessage(Number(runnerTimeout[1]));
|
|
282
|
+
if (ISOLATE_TERMINATED.test(reason)) return chainTimeoutMessage(timeoutMs);
|
|
283
|
+
const undefinedIdentifier = UNDEFINED_IDENTIFIER.exec(reason);
|
|
284
|
+
if (undefinedIdentifier) {
|
|
285
|
+
// The namespace list costs one catalog read, so it is fetched only on the
|
|
286
|
+
// failure that needs it. A catalog that cannot be read must not replace the
|
|
287
|
+
// chain's own reason with an unrelated one: the agent keeps the
|
|
288
|
+
// ReferenceError, just without the list.
|
|
289
|
+
try {
|
|
290
|
+
return unknownNamespaceMessage(undefinedIdentifier[1]!, await chainNamespaces(client));
|
|
291
|
+
} catch {
|
|
292
|
+
return reason;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return reason;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Run a chain and ALWAYS answer: with its value, or with the reason it has
|
|
300
|
+
* none. Never throws, and never leaves a caller waiting past the chain's own
|
|
301
|
+
* timeout plus {@link WATCHDOG_GRACE_MS}.
|
|
302
|
+
*
|
|
303
|
+
* What the caller does with an error is still the caller's (the hosted proxy
|
|
304
|
+
* maps a retired tool's name onto its own message first, for instance); this
|
|
305
|
+
* decides only whether there IS one and what it says about the runtime.
|
|
306
|
+
*/
|
|
307
|
+
export async function runToolChain(
|
|
308
|
+
client: CodeModeUtcpClient,
|
|
309
|
+
code: string,
|
|
310
|
+
timeoutMs: number,
|
|
311
|
+
): Promise<ToolChainOutcome> {
|
|
312
|
+
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
|
313
|
+
try {
|
|
314
|
+
const watchdogFired = new Promise<'watchdog'>((resolve) => {
|
|
315
|
+
watchdog = setTimeout(() => resolve('watchdog'), timeoutMs + WATCHDOG_GRACE_MS);
|
|
316
|
+
// A watchdog nobody is waiting on must not hold a CLI's exit open.
|
|
317
|
+
(watchdog as unknown as { unref?: () => void }).unref?.();
|
|
318
|
+
});
|
|
319
|
+
const settled = await Promise.race([
|
|
320
|
+
client.callToolChain(withChainRuntime(code), timeoutMs).then((outcome) => ({ outcome })),
|
|
321
|
+
watchdogFired,
|
|
322
|
+
]);
|
|
323
|
+
if (settled === 'watchdog') return { ok: false, error: chainTimeoutMessage(timeoutMs), logs: [] };
|
|
324
|
+
const logs = Array.isArray(settled.outcome.logs) ? settled.outcome.logs : [];
|
|
325
|
+
const reason = failureReason({ result: settled.outcome.result, logs });
|
|
326
|
+
if (reason !== undefined) {
|
|
327
|
+
return { ok: false, error: await describeChainFailure(client, reason, timeoutMs), logs };
|
|
328
|
+
}
|
|
329
|
+
return { ok: true, result: settled.outcome.result, logs };
|
|
330
|
+
} catch (err) {
|
|
331
|
+
// Everything the runner throws BEFORE the chain starts (a catalog read, a
|
|
332
|
+
// registry outage) and anything a tool bridge rethrows. The http transport
|
|
333
|
+
// carries a status and a body on a tool failure, and both are worth more to
|
|
334
|
+
// the agent than the message on its own.
|
|
335
|
+
//
|
|
336
|
+
// `describeToolFailure` is what reads the PROVIDER's own reason out of such
|
|
337
|
+
// a failure — `response.data.error`, with the machine-readable `kind` kept
|
|
338
|
+
// beside it on a typed refusal. The MCP dispatcher used to call it on the
|
|
339
|
+
// thrown error itself; now that the catch lives here, taking `err.message`
|
|
340
|
+
// instead would hand the agent a generic transport line and drop the half
|
|
341
|
+
// it can act on.
|
|
342
|
+
//
|
|
343
|
+
// Under a guard even so. `describeToolFailure` is total — it reads `err`
|
|
344
|
+
// through try/catch — but THIS function's contract is that it never throws,
|
|
345
|
+
// and that contract is what the "no chain failure reaches the agent as a
|
|
346
|
+
// dropped connection" criterion rests on. A guard here keeps it local
|
|
347
|
+
// rather than resting on another module staying total.
|
|
348
|
+
let error: string;
|
|
349
|
+
try {
|
|
350
|
+
error = describeToolFailure(err);
|
|
351
|
+
} catch {
|
|
352
|
+
// Describing it is the first thing that can fail, so the fallback is
|
|
353
|
+
// itself layered: the thrown value's own message if it can be read, and
|
|
354
|
+
// a fixed sentence if even that throws. An opaque answer is still an
|
|
355
|
+
// ANSWER — what must never happen is a rejection out of this catch.
|
|
356
|
+
try {
|
|
357
|
+
error = err instanceof Error ? err.message : String(err);
|
|
358
|
+
} catch {
|
|
359
|
+
error = '(indescribable tool failure)';
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
let status: unknown;
|
|
363
|
+
let data: unknown;
|
|
364
|
+
try {
|
|
365
|
+
const e = err as { status?: unknown; data?: unknown; response?: { status?: unknown; data?: unknown } };
|
|
366
|
+
status = e?.status ?? e?.response?.status;
|
|
367
|
+
data = e?.data ?? e?.response?.data;
|
|
368
|
+
} catch {
|
|
369
|
+
// A throwing getter or Proxy says nothing about the failure; the message
|
|
370
|
+
// above already stands on its own.
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
ok: false,
|
|
374
|
+
error,
|
|
375
|
+
logs: [],
|
|
376
|
+
...(typeof status === 'number' ? { status } : {}),
|
|
377
|
+
...(data !== undefined ? { data } : {}),
|
|
378
|
+
};
|
|
379
|
+
} finally {
|
|
380
|
+
if (watchdog) clearTimeout(watchdog);
|
|
381
|
+
}
|
|
382
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -36,6 +36,7 @@ export {
|
|
|
36
36
|
|
|
37
37
|
export {
|
|
38
38
|
describeToolFailure,
|
|
39
|
+
withTransportDetail,
|
|
39
40
|
toCallToolResult,
|
|
40
41
|
renderProgress,
|
|
41
42
|
toolError,
|
|
@@ -48,13 +49,40 @@ export {
|
|
|
48
49
|
} from './results.js';
|
|
49
50
|
|
|
50
51
|
export {
|
|
51
|
-
|
|
52
|
+
codeModeMetaTools,
|
|
53
|
+
chainNamespaceExample,
|
|
52
54
|
META_TOOL_NAMES,
|
|
53
55
|
CALL_TOOL_CHAIN_MAX_OUTPUT,
|
|
56
|
+
CALL_TOOL_CHAIN_NAME,
|
|
57
|
+
CHAIN_FAILURES_RULE,
|
|
58
|
+
CHAIN_LARGE_RESULTS_RULE,
|
|
59
|
+
type CodeModeMetaToolsOptions,
|
|
54
60
|
type SpillPort,
|
|
55
61
|
dispatchMetaTool,
|
|
56
62
|
} from './meta-tools.js';
|
|
57
63
|
|
|
64
|
+
export {
|
|
65
|
+
CHAIN_RUNTIME_PRELUDE,
|
|
66
|
+
CHAIN_TIMEOUT_DEFAULT_MS,
|
|
67
|
+
CHAIN_TIMEOUT_MAX_MS,
|
|
68
|
+
CHAIN_TIMEOUT_MIN_MS,
|
|
69
|
+
type ChainNamespaces,
|
|
70
|
+
type ToolChainOutcome,
|
|
71
|
+
chainNamespaces,
|
|
72
|
+
chainOutOfMemoryMessage,
|
|
73
|
+
chainTimeoutMessage,
|
|
74
|
+
describeChainFailure,
|
|
75
|
+
runToolChain,
|
|
76
|
+
unknownNamespaceMessage,
|
|
77
|
+
withChainRuntime,
|
|
78
|
+
} from './chain-runtime.js';
|
|
79
|
+
|
|
80
|
+
export {
|
|
81
|
+
type ChainExample,
|
|
82
|
+
type ChainExampleTool,
|
|
83
|
+
chainExample,
|
|
84
|
+
} from './chain-example.js';
|
|
85
|
+
|
|
58
86
|
export { registerManual, dispatchToolCall } from './dispatch.js';
|
|
59
87
|
|
|
60
88
|
export {
|
|
@@ -62,7 +90,6 @@ export {
|
|
|
62
90
|
RETIRED_TOOL_NAMES,
|
|
63
91
|
retiredToolMessage,
|
|
64
92
|
retiredToolInFailure,
|
|
65
|
-
retiredToolChainFailure,
|
|
66
93
|
} from './retired-tools.js';
|
|
67
94
|
|
|
68
95
|
export {
|