@bevel-software/platform-mcp-core 0.23.0 → 0.25.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/google-service-account/google-auth-http.protocol.d.ts +24 -0
- package/dist/google-service-account/google-auth-http.protocol.d.ts.map +1 -0
- package/dist/google-service-account/google-auth-http.protocol.js +47 -0
- package/dist/google-service-account/google-auth-http.protocol.js.map +1 -0
- package/dist/google-service-account/google-service-account.auth.d.ts +45 -0
- package/dist/google-service-account/google-service-account.auth.d.ts.map +1 -0
- package/dist/google-service-account/google-service-account.auth.js +153 -0
- package/dist/google-service-account/google-service-account.auth.js.map +1 -0
- package/dist/google-service-account/google-service-account.token-source.d.ts +28 -0
- package/dist/google-service-account/google-service-account.token-source.d.ts.map +1 -0
- package/dist/google-service-account/google-service-account.token-source.js +206 -0
- package/dist/google-service-account/google-service-account.token-source.js.map +1 -0
- package/dist/google-service-account/index.d.ts +5 -0
- package/dist/google-service-account/index.d.ts.map +1 -0
- package/dist/google-service-account/index.js +7 -0
- package/dist/google-service-account/index.js.map +1 -0
- package/dist/google-service-account/service-account-token.contract.d.ts +33 -0
- package/dist/google-service-account/service-account-token.contract.d.ts.map +1 -0
- package/dist/google-service-account/service-account-token.contract.js +14 -0
- package/dist/google-service-account/service-account-token.contract.js.map +1 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -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 +3 -2
- package/src/chain-example.ts +315 -0
- package/src/chain-runtime.ts +382 -0
- package/src/google-service-account/google-auth-http.protocol.ts +62 -0
- package/src/google-service-account/google-service-account.auth.ts +161 -0
- package/src/google-service-account/google-service-account.token-source.ts +239 -0
- package/src/google-service-account/index.ts +15 -0
- package/src/google-service-account/service-account-token.contract.ts +38 -0
- package/src/index.ts +47 -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
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { CommunicationProtocol, type CallTemplate, type IUtcpClient } from '@utcp/sdk';
|
|
2
|
+
import { HttpCommunicationProtocol, type HttpCallTemplate } from '@utcp/http';
|
|
3
|
+
import { isGoogleServiceAccountAuth } from './google-service-account.auth.js';
|
|
4
|
+
import { GoogleServiceAccountTokenSource } from './google-service-account.token-source.js';
|
|
5
|
+
import type { IServiceAccountTokenSource } from './service-account-token.contract.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The stock UTCP `http` protocol, taught one more auth type. A call whose
|
|
9
|
+
* template names `google_service_account` is handed to the stock protocol with
|
|
10
|
+
* that auth swapped for the bearer token it resolves to (as `oauth2_user`,
|
|
11
|
+
* which the stock protocol sends as `Authorization: Bearer <token>` and strips
|
|
12
|
+
* on a cross-origin redirect). Every other call passes through untouched.
|
|
13
|
+
*/
|
|
14
|
+
export class GoogleAuthHttpProtocol extends HttpCommunicationProtocol {
|
|
15
|
+
constructor(private readonly tokens: IServiceAccountTokenSource) {
|
|
16
|
+
super();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
override async callTool(
|
|
20
|
+
caller: IUtcpClient,
|
|
21
|
+
toolName: string,
|
|
22
|
+
toolArgs: Record<string, unknown>,
|
|
23
|
+
toolCallTemplate: CallTemplate,
|
|
24
|
+
): Promise<unknown> {
|
|
25
|
+
return super.callTool(caller, toolName, toolArgs, await this.withBearerToken(toolCallTemplate));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
override async *callToolStreaming(
|
|
29
|
+
caller: IUtcpClient,
|
|
30
|
+
toolName: string,
|
|
31
|
+
toolArgs: Record<string, unknown>,
|
|
32
|
+
toolCallTemplate: CallTemplate,
|
|
33
|
+
): AsyncGenerator<unknown, void, unknown> {
|
|
34
|
+
yield* super.callToolStreaming(caller, toolName, toolArgs, await this.withBearerToken(toolCallTemplate));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private async withBearerToken(template: CallTemplate): Promise<CallTemplate> {
|
|
38
|
+
const auth = (template as HttpCallTemplate).auth;
|
|
39
|
+
if (!isGoogleServiceAccountAuth(auth)) return template;
|
|
40
|
+
const accessToken = await this.tokens.accessToken(auth);
|
|
41
|
+
return { ...template, auth: { auth_type: 'oauth2_user', access_token: accessToken } } as CallTemplate;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Put the service-account-aware protocol in place of the stock `http` one,
|
|
47
|
+
* minting tokens from `tokens`. Exported so a suite can answer for Google;
|
|
48
|
+
* a process never needs to call it, since loading this module already has.
|
|
49
|
+
*/
|
|
50
|
+
export function installGoogleServiceAccountAuth(
|
|
51
|
+
tokens: IServiceAccountTokenSource = new GoogleServiceAccountTokenSource(),
|
|
52
|
+
): void {
|
|
53
|
+
CommunicationProtocol.communicationProtocols['http'] = new GoogleAuthHttpProtocol(tokens);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Installed on module load, the way `@utcp/http` installs the protocol this
|
|
57
|
+
// one replaces: once per process, before any client exists (a client copies
|
|
58
|
+
// the registry when it is built). The import of `@utcp/http` above has already
|
|
59
|
+
// run its own registration by the time this line does, whatever order the
|
|
60
|
+
// importing module lists the two in. One token cache then serves the process;
|
|
61
|
+
// its entries are keyed by the key itself, so knowledge bases never share one.
|
|
62
|
+
installGoogleServiceAccountAuth();
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { AuthSerializer, Serializer, type Auth } from '@utcp/sdk';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { GOOGLE_SERVICE_ACCOUNT_AUTH_TYPE, type GoogleServiceAccountAuth } from './service-account-token.contract.js';
|
|
4
|
+
|
|
5
|
+
const GoogleServiceAccountAuthSchema = z.object({
|
|
6
|
+
auth_type: z.literal(GOOGLE_SERVICE_ACCOUNT_AUTH_TYPE),
|
|
7
|
+
credentials: z
|
|
8
|
+
.string()
|
|
9
|
+
.min(1)
|
|
10
|
+
.describe('The service-account key JSON. Recommended to use a vault variable like "${GOOGLE_SA_KEY}".'),
|
|
11
|
+
// Trimmed before the length check, so a blank scope is refused here rather
|
|
12
|
+
// than reaching Google as an empty one.
|
|
13
|
+
scopes: z
|
|
14
|
+
.union([z.string().trim().min(1), z.array(z.string().trim().min(1)).min(1)])
|
|
15
|
+
.describe('OAuth scopes for the token, e.g. "https://www.googleapis.com/auth/adwords".'),
|
|
16
|
+
subject: z.string().trim().min(1).optional().describe('User to impersonate under domain-wide delegation.'),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
class GoogleServiceAccountAuthSerializer extends Serializer<Auth> {
|
|
20
|
+
toDict(obj: Auth): Record<string, unknown> {
|
|
21
|
+
return { ...obj };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
validateDict(obj: Record<string, unknown>): Auth {
|
|
25
|
+
return GoogleServiceAccountAuthSchema.parse(obj) as Auth;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Whether a call template's `auth` asks for a Google service-account token. */
|
|
30
|
+
export function isGoogleServiceAccountAuth(auth: unknown): auth is GoogleServiceAccountAuth {
|
|
31
|
+
return (
|
|
32
|
+
typeof auth === 'object' &&
|
|
33
|
+
auth !== null &&
|
|
34
|
+
(auth as { auth_type?: unknown }).auth_type === GOOGLE_SERVICE_ACCOUNT_AUTH_TYPE
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The one call template type whose protocol turns the key into a token. */
|
|
39
|
+
const SERVED_CALL_TEMPLATE_TYPE = 'http';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The other call template types an author is likely to have reached for, which
|
|
43
|
+
* the answer below may name. A type outside this list is the file's own text,
|
|
44
|
+
* and is described rather than quoted back.
|
|
45
|
+
*/
|
|
46
|
+
const NAMEABLE_CALL_TEMPLATE_TYPES = ['sse', 'streamable_http', 'mcp', 'cli'];
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Where in `doc` a `google_service_account` auth block sits that nothing will
|
|
50
|
+
* act on, as a phrase for a refusal, or null when every block is the `auth` of
|
|
51
|
+
* one of `toolCallTemplates` and that template is an `http` one.
|
|
52
|
+
*
|
|
53
|
+
* `toolCallTemplates` are the templates tools are really called through, which
|
|
54
|
+
* only the caller knows: the document's shape is its business. A block
|
|
55
|
+
* anywhere else is read by nothing, whatever the object around it looks like:
|
|
56
|
+
* a template the document never registers, an `auth_tools`, a block at the
|
|
57
|
+
* root of a file that discovers its tools from a url.
|
|
58
|
+
*
|
|
59
|
+
* UTCP validates an auth type on any call template that takes an `auth`, but
|
|
60
|
+
* only the `http` protocol mints the token. Every other protocol sends an auth
|
|
61
|
+
* type it does not know as no credentials at all, so such a tool would save
|
|
62
|
+
* cleanly and then call Google unauthenticated.
|
|
63
|
+
*
|
|
64
|
+
* Every block in the document is found, at any depth (see
|
|
65
|
+
* `googleServiceAccountBlocks`), and the first one in document order that
|
|
66
|
+
* nothing will act on is the one named.
|
|
67
|
+
*/
|
|
68
|
+
export function findUnservedGoogleServiceAccountAuth(doc: unknown, toolCallTemplates: readonly unknown[]): string | null {
|
|
69
|
+
const served = new Set<unknown>(toolCallTemplates);
|
|
70
|
+
for (const { parent, key } of googleServiceAccountBlocks(doc)) {
|
|
71
|
+
// Judged by where it sits, so once per place it appears: an aliased
|
|
72
|
+
// block can be served in one place and ignored in another.
|
|
73
|
+
const where = unservedPlacement(parent, key, served);
|
|
74
|
+
if (where) return where;
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `${NAME}` or `$NAME`, as UTCP spells a variable, and nothing else around it. */
|
|
80
|
+
const ONE_VARIABLE_REFERENCE = /^\s*(?:\$\{[a-zA-Z0-9_]+\}|\$[a-zA-Z0-9_]+)\s*$/;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Whether any `google_service_account` block in `doc` has its key WRITTEN IN
|
|
84
|
+
* THE DOCUMENT: a `credentials` that is anything but one variable reference.
|
|
85
|
+
*
|
|
86
|
+
* The document is a `.tool`, which is knowledge-base content: it is committed
|
|
87
|
+
* to the repository, and read by everyone and every agent that can read the
|
|
88
|
+
* knowledge base. A key written into it is a key all of them hold, for as
|
|
89
|
+
* long as the history keeps it. So the place for the key is the vault, and
|
|
90
|
+
* `credentials` only ever names the variable.
|
|
91
|
+
*
|
|
92
|
+
* Asked of the document as its author wrote it, wherever the block sits: a
|
|
93
|
+
* key in a block nothing will act on is just as readable. It cannot be asked
|
|
94
|
+
* where the auth type itself is validated, because that also runs on the
|
|
95
|
+
* template AFTER its variables were substituted, where `credentials` is the
|
|
96
|
+
* key and has to be.
|
|
97
|
+
*
|
|
98
|
+
* Says only that one was found. It never returns, quotes or measures the
|
|
99
|
+
* value: what it would be describing is the secret.
|
|
100
|
+
*/
|
|
101
|
+
export function holdsLiteralGoogleServiceAccountKey(doc: unknown): boolean {
|
|
102
|
+
for (const { block } of googleServiceAccountBlocks(doc)) {
|
|
103
|
+
const { credentials } = block as { credentials?: unknown };
|
|
104
|
+
// Not a string is not a key either; the auth type's own schema refuses it.
|
|
105
|
+
if (typeof credentials === 'string' && !ONE_VARIABLE_REFERENCE.test(credentials)) return true;
|
|
106
|
+
}
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Every `google_service_account` auth block in `doc`, at any depth, with the
|
|
112
|
+
* object it sits in and the key it sits under, in document order.
|
|
113
|
+
*
|
|
114
|
+
* The walk keeps its own stack, so a deeply nested document cannot overflow
|
|
115
|
+
* the call stack, and it does not re-enter an object it has seen: a YAML
|
|
116
|
+
* anchor aliased inside itself parses to a cyclic object. A block is yielded
|
|
117
|
+
* once per place it appears, since an aliased one sits in several.
|
|
118
|
+
*/
|
|
119
|
+
function* googleServiceAccountBlocks(
|
|
120
|
+
doc: unknown,
|
|
121
|
+
): Generator<{ block: GoogleServiceAccountAuth; parent?: Record<string, unknown>; key?: string }> {
|
|
122
|
+
const seen = new WeakSet<object>();
|
|
123
|
+
const pending: { node: unknown; parent?: Record<string, unknown>; key?: string }[] = [{ node: doc }];
|
|
124
|
+
for (let next = pending.pop(); next; next = pending.pop()) {
|
|
125
|
+
const { node, parent, key } = next;
|
|
126
|
+
if (!node || typeof node !== 'object') continue;
|
|
127
|
+
if (isGoogleServiceAccountAuth(node)) {
|
|
128
|
+
yield { block: node, parent, key };
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (seen.has(node)) continue;
|
|
132
|
+
seen.add(node);
|
|
133
|
+
// Pushed in reverse, so blocks come out in document order.
|
|
134
|
+
if (Array.isArray(node)) {
|
|
135
|
+
for (let i = node.length - 1; i >= 0; i--) pending.push({ node: node[i] });
|
|
136
|
+
} else {
|
|
137
|
+
const obj = node as Record<string, unknown>;
|
|
138
|
+
const keys = Object.keys(obj);
|
|
139
|
+
for (let i = keys.length - 1; i >= 0; i--) pending.push({ node: obj[keys[i]!], parent: obj, key: keys[i] });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Why a block under `parent[key]` is acted on by nothing, or null when it is. */
|
|
145
|
+
function unservedPlacement(parent: Record<string, unknown> | undefined, key: string | undefined, served: Set<unknown>): string | null {
|
|
146
|
+
if (!parent || key !== 'auth' || typeof parent.call_template_type !== 'string') {
|
|
147
|
+
return "somewhere that is not a call template's `auth`";
|
|
148
|
+
}
|
|
149
|
+
const type = parent.call_template_type.toLowerCase().trim();
|
|
150
|
+
if (type !== SERVED_CALL_TEMPLATE_TYPE) {
|
|
151
|
+
return NAMEABLE_CALL_TEMPLATE_TYPES.includes(type) ? `a \`${type}\` call template` : 'a call template that is not an `http` one';
|
|
152
|
+
}
|
|
153
|
+
return served.has(parent) ? null : 'an `http` call template that no tool is called through';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Register the auth type on module load, so a `.tool` naming it validates
|
|
157
|
+
// wherever UTCP parses a call template: the inline manual route, the preview,
|
|
158
|
+
// and the client re-validating a template after substituting its variables.
|
|
159
|
+
// UTCP's registry is process-wide and the type carries no state, so one
|
|
160
|
+
// registration serves every knowledge base. Idempotent (safe under hot-reload).
|
|
161
|
+
AuthSerializer.registerAuth(GOOGLE_SERVICE_ACCOUNT_AUTH_TYPE, new GoogleServiceAccountAuthSerializer(), true);
|