@zackbart/connecta 0.7.9 → 0.8.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.
Files changed (180) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +67 -144
  3. package/dist/auth/bearer.d.ts +1 -1
  4. package/dist/auth/bearer.js +4 -4
  5. package/dist/auth/bearer.js.map +1 -1
  6. package/dist/auth/clerk.d.ts +1 -1
  7. package/dist/auth/clerk.js +1 -1
  8. package/dist/call-admission.d.ts.map +1 -1
  9. package/dist/call-admission.js +9 -3
  10. package/dist/call-admission.js.map +1 -1
  11. package/dist/catalog-fingerprint.d.ts +20 -0
  12. package/dist/catalog-fingerprint.d.ts.map +1 -0
  13. package/dist/catalog-fingerprint.js +34 -0
  14. package/dist/catalog-fingerprint.js.map +1 -0
  15. package/dist/catalog-limits.d.ts +10 -0
  16. package/dist/catalog-limits.d.ts.map +1 -0
  17. package/dist/catalog-limits.js +10 -0
  18. package/dist/catalog-limits.js.map +1 -0
  19. package/dist/catalog-service.d.ts +138 -0
  20. package/dist/catalog-service.d.ts.map +1 -0
  21. package/dist/catalog-service.js +407 -0
  22. package/dist/catalog-service.js.map +1 -0
  23. package/dist/catalog.js +2 -2
  24. package/dist/catalog.js.map +1 -1
  25. package/dist/concurrency.d.ts +4 -0
  26. package/dist/concurrency.d.ts.map +1 -0
  27. package/dist/concurrency.js +31 -0
  28. package/dist/concurrency.js.map +1 -0
  29. package/dist/connectors/api.d.ts.map +1 -1
  30. package/dist/connectors/api.js +22 -12
  31. package/dist/connectors/api.js.map +1 -1
  32. package/dist/connectors/remote-mcp.d.ts.map +1 -1
  33. package/dist/connectors/remote-mcp.js +44 -19
  34. package/dist/connectors/remote-mcp.js.map +1 -1
  35. package/dist/credential-health.d.ts +0 -22
  36. package/dist/credential-health.d.ts.map +1 -1
  37. package/dist/credential-health.js +14 -10
  38. package/dist/credential-health.js.map +1 -1
  39. package/dist/credentials.d.ts +3 -2
  40. package/dist/credentials.d.ts.map +1 -1
  41. package/dist/errors.d.ts +1 -1
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js.map +1 -1
  44. package/dist/execute.d.ts +9 -8
  45. package/dist/execute.d.ts.map +1 -1
  46. package/dist/execute.js +144 -321
  47. package/dist/execute.js.map +1 -1
  48. package/dist/executor-result.d.ts +0 -3
  49. package/dist/executor-result.d.ts.map +1 -1
  50. package/dist/executor-result.js +2 -2
  51. package/dist/executor-result.js.map +1 -1
  52. package/dist/executors/quickjs-child.js +3 -3
  53. package/dist/executors/quickjs-child.js.map +1 -1
  54. package/dist/executors/quickjs-protocol.d.ts +4 -1
  55. package/dist/executors/quickjs-protocol.d.ts.map +1 -1
  56. package/dist/executors/quickjs-runtime.d.ts.map +1 -1
  57. package/dist/executors/quickjs-runtime.js +7 -2
  58. package/dist/executors/quickjs-runtime.js.map +1 -1
  59. package/dist/executors/quickjs.d.ts.map +1 -1
  60. package/dist/executors/quickjs.js +4 -1
  61. package/dist/executors/quickjs.js.map +1 -1
  62. package/dist/favicon.js +2 -2
  63. package/dist/favicon.js.map +1 -1
  64. package/dist/index.d.ts +5 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +44 -17
  67. package/dist/index.js.map +1 -1
  68. package/dist/invocation.d.ts +96 -0
  69. package/dist/invocation.d.ts.map +1 -0
  70. package/dist/invocation.js +369 -0
  71. package/dist/invocation.js.map +1 -0
  72. package/dist/meta-tools.d.ts +8 -86
  73. package/dist/meta-tools.d.ts.map +1 -1
  74. package/dist/meta-tools.js +145 -583
  75. package/dist/meta-tools.js.map +1 -1
  76. package/dist/operator-ui/generated.d.ts +3 -0
  77. package/dist/operator-ui/generated.d.ts.map +1 -0
  78. package/dist/operator-ui/generated.js +5 -0
  79. package/dist/operator-ui/generated.js.map +1 -0
  80. package/dist/operator-ui/model.d.ts +94 -0
  81. package/dist/operator-ui/model.d.ts.map +1 -0
  82. package/dist/operator-ui/model.js +28 -0
  83. package/dist/operator-ui/model.js.map +1 -0
  84. package/dist/registry.d.ts +22 -6
  85. package/dist/registry.d.ts.map +1 -1
  86. package/dist/registry.js +328 -35
  87. package/dist/registry.js.map +1 -1
  88. package/dist/routes/activity.d.ts +3 -0
  89. package/dist/routes/activity.d.ts.map +1 -0
  90. package/dist/routes/activity.js +173 -0
  91. package/dist/routes/activity.js.map +1 -0
  92. package/dist/routes/credentials.d.ts +3 -0
  93. package/dist/routes/credentials.d.ts.map +1 -0
  94. package/dist/routes/credentials.js +181 -0
  95. package/dist/routes/credentials.js.map +1 -0
  96. package/dist/routes/mcp.d.ts +8 -0
  97. package/dist/routes/mcp.d.ts.map +1 -0
  98. package/dist/routes/mcp.js +383 -0
  99. package/dist/routes/mcp.js.map +1 -0
  100. package/dist/routes/oauth.d.ts +4 -0
  101. package/dist/routes/oauth.d.ts.map +1 -0
  102. package/dist/routes/oauth.js +268 -0
  103. package/dist/routes/oauth.js.map +1 -0
  104. package/dist/routes/shared.d.ts +97 -0
  105. package/dist/routes/shared.d.ts.map +1 -0
  106. package/dist/routes/shared.js +199 -0
  107. package/dist/routes/shared.js.map +1 -0
  108. package/dist/routes/ui.d.ts +3 -0
  109. package/dist/routes/ui.d.ts.map +1 -0
  110. package/dist/routes/ui.js +122 -0
  111. package/dist/routes/ui.js.map +1 -0
  112. package/dist/server.d.ts +9 -40
  113. package/dist/server.d.ts.map +1 -1
  114. package/dist/server.js +63 -1293
  115. package/dist/server.js.map +1 -1
  116. package/dist/skills.d.ts +0 -15
  117. package/dist/skills.d.ts.map +1 -1
  118. package/dist/skills.js +6 -5
  119. package/dist/skills.js.map +1 -1
  120. package/dist/storage/file.d.ts.map +1 -1
  121. package/dist/storage/file.js +3 -1
  122. package/dist/storage/file.js.map +1 -1
  123. package/dist/storage/memory.d.ts.map +1 -1
  124. package/dist/storage/memory.js +3 -1
  125. package/dist/storage/memory.js.map +1 -1
  126. package/dist/toolkits.d.ts +0 -22
  127. package/dist/toolkits.d.ts.map +1 -1
  128. package/dist/toolkits.js +2 -2
  129. package/dist/toolkits.js.map +1 -1
  130. package/dist/types.d.ts +9 -2
  131. package/dist/types.d.ts.map +1 -1
  132. package/dist/ui.d.ts +3 -93
  133. package/dist/ui.d.ts.map +1 -1
  134. package/dist/ui.js +26 -1393
  135. package/dist/ui.js.map +1 -1
  136. package/dist/version.d.ts +1 -1
  137. package/dist/version.js +1 -1
  138. package/package.json +15 -8
  139. package/src/auth/bearer.ts +4 -4
  140. package/src/auth/clerk.ts +1 -1
  141. package/src/call-admission.ts +8 -5
  142. package/src/catalog-fingerprint.ts +52 -0
  143. package/src/catalog-limits.ts +11 -0
  144. package/src/catalog-service.ts +601 -0
  145. package/src/catalog.ts +2 -2
  146. package/src/concurrency.ts +39 -0
  147. package/src/connectors/api.ts +22 -12
  148. package/src/connectors/remote-mcp.ts +52 -22
  149. package/src/credential-health.ts +13 -10
  150. package/src/credentials.ts +2 -2
  151. package/src/errors.ts +1 -1
  152. package/src/execute.ts +194 -409
  153. package/src/executor-result.ts +2 -2
  154. package/src/executors/quickjs-child.ts +8 -4
  155. package/src/executors/quickjs-protocol.ts +1 -1
  156. package/src/executors/quickjs-runtime.ts +5 -1
  157. package/src/executors/quickjs.ts +11 -8
  158. package/src/favicon.ts +2 -2
  159. package/src/index.ts +49 -17
  160. package/src/invocation.ts +527 -0
  161. package/src/meta-tools.ts +366 -906
  162. package/src/operator-ui/browser.css +413 -0
  163. package/src/operator-ui/browser.ts +1121 -0
  164. package/src/operator-ui/generated.ts +4 -0
  165. package/src/operator-ui/model.ts +127 -0
  166. package/src/registry.ts +434 -44
  167. package/src/routes/activity.ts +220 -0
  168. package/src/routes/credentials.ts +266 -0
  169. package/src/routes/mcp.ts +485 -0
  170. package/src/routes/oauth.ts +328 -0
  171. package/src/routes/shared.ts +330 -0
  172. package/src/routes/ui.ts +153 -0
  173. package/src/server.ts +66 -1703
  174. package/src/skills.ts +6 -5
  175. package/src/storage/file.ts +3 -1
  176. package/src/storage/memory.ts +3 -1
  177. package/src/toolkits.ts +2 -2
  178. package/src/types.ts +9 -2
  179. package/src/ui.ts +52 -1493
  180. package/src/version.ts +1 -1
@@ -0,0 +1,527 @@
1
+ import {
2
+ recordToolActivity,
3
+ type ActivityCallSource,
4
+ type ActivityRequestContext,
5
+ } from "./activity.js";
6
+ import { isCallAdmissionError } from "./call-admission.js";
7
+ import {
8
+ CatalogService,
9
+ type CatalogResolution,
10
+ type ResolvedCatalogTool,
11
+ } from "./catalog-service.js";
12
+ import {
13
+ classifyCallError,
14
+ ConnectorCallError,
15
+ messageLooksRetryable,
16
+ type CallErrorDetails,
17
+ } from "./errors.js";
18
+ import { unwrapMcpResult } from "./mcp-result.js";
19
+ import type { RegistryView } from "./registry.js";
20
+ import type { ToolDef } from "./types.js";
21
+
22
+ /**
23
+ * The longest the engine will park a synchronous inbound request in *waiting
24
+ * alone*. The engine already treats ~15 s as the outer bound of one reasonable
25
+ * connector call (EXECUTE_HOST_CALL_TIMEOUT_MS), so sleeping for minutes trades
26
+ * a fast, informative failure for a hung one. A connector-reported window this
27
+ * long isn't truncated — it's declined (see `retryBackoffMs`) and reported
28
+ * verbatim as `error.retryAfterMs`, so the agent, which can afford to wait,
29
+ * decides when to re-issue.
30
+ */
31
+ export const MAX_RETRY_BACKOFF_MS = 10_000;
32
+
33
+ /**
34
+ * How long to wait before the next attempt, or `undefined` for "don't retry".
35
+ *
36
+ * A connector that read a `Retry-After` header knows the window exactly, so it
37
+ * is honoured **exactly or not at all**: truncating an exponential *guess* is
38
+ * harmless, but truncating a *known* window means deliberately retrying inside
39
+ * a rate limit — the harm this channel exists to prevent. A window longer than
40
+ * `MAX_RETRY_BACKOFF_MS` therefore declines the retry rather than shortening
41
+ * it. (`retryAfterMs` is normalized non-negative, so `0` means "retry now".)
42
+ * Connectors that report no window keep the historical exponential guess.
43
+ *
44
+ * Waits are per attempt, matching the per-attempt `timeoutMs` race in
45
+ * `InvocationService.invoke`. Exported for direct testing.
46
+ */
47
+ export function retryBackoffMs(
48
+ attempt: number,
49
+ retryAfterMs: number | undefined,
50
+ ): number | undefined {
51
+ if (retryAfterMs === undefined) {
52
+ return Math.min(250 * 2 ** (attempt - 1), 1_000);
53
+ }
54
+ return retryAfterMs <= MAX_RETRY_BACKOFF_MS ? retryAfterMs : undefined;
55
+ }
56
+
57
+ /** The one fail-closed admission predicate for every invocation adapter. */
58
+ function isExplicitlyReadOnly(definition: ToolDef): boolean {
59
+ return (
60
+ definition.annotations?.readOnlyHint === true &&
61
+ definition.annotations?.destructiveHint !== true
62
+ );
63
+ }
64
+
65
+ function retrySafe(definition: ToolDef): boolean {
66
+ return (
67
+ definition.annotations?.readOnlyHint === true ||
68
+ definition.annotations?.idempotentHint === true
69
+ );
70
+ }
71
+
72
+ function framingError(code: string, message: string): CallErrorDetails {
73
+ return { code, message, retryable: messageLooksRetryable(message) };
74
+ }
75
+
76
+ function callerCancelledDetails(): CallErrorDetails {
77
+ return {
78
+ code: "cancelled",
79
+ message: "Tool call was cancelled by the caller.",
80
+ retryable: false,
81
+ };
82
+ }
83
+
84
+ function isCallerCancellation(
85
+ error: unknown,
86
+ signal: AbortSignal | undefined,
87
+ ): boolean {
88
+ return (
89
+ signal?.aborted === true ||
90
+ (isCallAdmissionError(error) && error.admissionKind === "cancelled")
91
+ );
92
+ }
93
+
94
+ function assertRawMcpSuccess(
95
+ kind: ResolvedCatalogTool["connector"]["kind"],
96
+ result: unknown,
97
+ ): void {
98
+ if (kind !== "mcp" || result == null || typeof result !== "object") return;
99
+ const mcpResult = result as {
100
+ content?: Array<{ type?: string; text?: string }>;
101
+ isError?: boolean;
102
+ };
103
+ if (!mcpResult.isError) return;
104
+ throw new Error(
105
+ mcpResult.content
106
+ ?.filter((block) => block.type === "text")
107
+ .map((block) => block.text ?? "")
108
+ .join("") || "Downstream tool call failed",
109
+ );
110
+ }
111
+
112
+ export interface InvocationTiming {
113
+ catalogMs: number;
114
+ admissionMs: number;
115
+ connectorMs: number;
116
+ backoffMs: number;
117
+ resultProcessingMs: number;
118
+ totalMs: number;
119
+ }
120
+
121
+ interface InvocationBase {
122
+ durationMs: number;
123
+ attempts: number;
124
+ timing: InvocationTiming;
125
+ resolved?: ResolvedCatalogTool;
126
+ }
127
+
128
+ export type InvocationOutcome<T> =
129
+ | (InvocationBase & { ok: true; value: T; resolved: ResolvedCatalogTool })
130
+ | (InvocationBase & { ok: false; error: CallErrorDetails });
131
+
132
+ export interface InvocationContext<T> {
133
+ source: ActivityCallSource;
134
+ allowDestructive?: boolean;
135
+ timeoutMs?: number;
136
+ maxRetries?: number;
137
+ requestSignal?: AbortSignal;
138
+ unwrapResult?: boolean;
139
+ /**
140
+ * Caller-owned result policy. MCP passes fields + paging here; code mode
141
+ * normally accepts the already-unwrapped value unchanged.
142
+ */
143
+ processResult?: (
144
+ value: unknown,
145
+ resolved: ResolvedCatalogTool,
146
+ ) => T | Promise<T>;
147
+ /**
148
+ * Called after address/catalog/safety admission and before the first provider
149
+ * attempt. Code mode uses it for its host-call budget.
150
+ */
151
+ beforeDispatch?: () => void;
152
+ }
153
+
154
+ export class InvocationFailure extends Error {
155
+ readonly code: string;
156
+ readonly retryable: boolean;
157
+ readonly retryAfterMs: number | undefined;
158
+
159
+ constructor(readonly details: CallErrorDetails) {
160
+ super(details.message);
161
+ this.name = "InvocationFailure";
162
+ this.code = details.code;
163
+ this.retryable = details.retryable;
164
+ this.retryAfterMs = details.retryAfterMs;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Shared downstream invocation engine. Address/catalog resolution is delegated
170
+ * to the request-local CatalogService; every remaining call semantic lives
171
+ * here so MCP and code mode cannot drift independently.
172
+ */
173
+ export class InvocationService {
174
+ constructor(
175
+ private readonly registry: RegistryView,
176
+ private readonly catalog: CatalogService,
177
+ private readonly activity?: ActivityRequestContext,
178
+ ) {}
179
+
180
+ async invoke<T = unknown>(
181
+ address: string,
182
+ args: unknown,
183
+ context: InvocationContext<T>,
184
+ ): Promise<InvocationOutcome<T>> {
185
+ return this.invokeWithResolution(address, args, context, () =>
186
+ this.catalog.resolveTool(
187
+ address,
188
+ context.requestSignal !== undefined
189
+ ? { signal: context.requestSignal }
190
+ : {},
191
+ ),
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Code-mode namespace dispatch preserves JavaScript-safe tool aliases while
197
+ * still feeding the resolved catalog entry through the one invocation path.
198
+ */
199
+ async invokeToolAlias<T = unknown>(
200
+ connectorId: string,
201
+ toolAlias: string,
202
+ aliasFor: (toolName: string) => string,
203
+ args: unknown,
204
+ context: InvocationContext<T>,
205
+ ): Promise<InvocationOutcome<T>> {
206
+ return this.invokeWithResolution(
207
+ `${connectorId}.${toolAlias}`,
208
+ args,
209
+ context,
210
+ () =>
211
+ this.catalog.resolveToolAlias(
212
+ connectorId,
213
+ toolAlias,
214
+ aliasFor,
215
+ context.requestSignal !== undefined
216
+ ? { signal: context.requestSignal }
217
+ : {},
218
+ ),
219
+ );
220
+ }
221
+
222
+ private async invokeWithResolution<T>(
223
+ address: string,
224
+ args: unknown,
225
+ context: InvocationContext<T>,
226
+ resolve: () => Promise<CatalogResolution>,
227
+ ): Promise<InvocationOutcome<T>> {
228
+ const started = Date.now();
229
+ let catalogMs = 0;
230
+ let admissionMs = 0;
231
+ let connectorMs = 0;
232
+ let backoffMs = 0;
233
+ let resultProcessingMs = 0;
234
+ let attempts = 0;
235
+ let resolved: ResolvedCatalogTool | undefined;
236
+ let activityTarget:
237
+ | Pick<ResolvedCatalogTool, "connector" | "toolName">
238
+ | undefined;
239
+ const timing = (): InvocationTiming => ({
240
+ catalogMs,
241
+ admissionMs,
242
+ connectorMs,
243
+ backoffMs,
244
+ resultProcessingMs,
245
+ totalMs: Date.now() - started,
246
+ });
247
+ const record = (
248
+ outcome: "success" | "error" | "timeout" | "cancelled",
249
+ errorCode?: string,
250
+ ) => {
251
+ if (!activityTarget) return;
252
+ recordToolActivity(this.activity, {
253
+ connectorId: activityTarget.connector.id,
254
+ toolName: activityTarget.toolName,
255
+ address: `${activityTarget.connector.id}.${activityTarget.toolName}`,
256
+ source: context.source,
257
+ outcome,
258
+ durationMs: Date.now() - started,
259
+ attempts,
260
+ ...(errorCode ? { errorCode } : {}),
261
+ });
262
+ };
263
+ const failed = (error: CallErrorDetails): InvocationOutcome<T> => {
264
+ const diagnostics = timing();
265
+ record(
266
+ error.code === "timeout"
267
+ ? "timeout"
268
+ : error.code === "cancelled"
269
+ ? "cancelled"
270
+ : "error",
271
+ error.code,
272
+ );
273
+ return {
274
+ ok: false,
275
+ durationMs: Date.now() - started,
276
+ attempts,
277
+ timing: diagnostics,
278
+ ...(resolved ? { resolved } : {}),
279
+ error,
280
+ };
281
+ };
282
+
283
+ const resolution = await resolve();
284
+ catalogMs += resolution.catalogMs;
285
+ if (!resolution.ok) {
286
+ if (resolution.connector && resolution.toolName) {
287
+ activityTarget = {
288
+ connector: resolution.connector,
289
+ toolName: resolution.toolName,
290
+ };
291
+ }
292
+ if (resolution.cause && resolution.connector) {
293
+ if (context.requestSignal?.aborted) {
294
+ return failed(callerCancelledDetails());
295
+ }
296
+ // A connector whose catalog cannot be fetched is as unusable as one
297
+ // whose execution fails, so it feeds health accounting the same way the
298
+ // attempt catch below does — otherwise a connector every call fails
299
+ // against (a revoked downstream grant, say) still reads clean from the
300
+ // cheap `list_connectors({ probe: false })` signal.
301
+ //
302
+ // Recorded HERE rather than inside the registry's catalog fetch on
303
+ // purpose: `registry` is this connection's VIEW, so a toolkit-scoped
304
+ // session records into its own log as well as the deployment-wide one,
305
+ // which `Registry.refreshTools` could not reach. A cache hit that
306
+ // avoids a live listTools call records nothing either way — it is not
307
+ // evidence of health, and success stays what it has always been: an
308
+ // actual downstream call that returned.
309
+ this.registry.recordFailure(
310
+ resolution.connector.id,
311
+ Date.now() - started,
312
+ resolution.cause,
313
+ );
314
+ }
315
+ return failed(resolution.error);
316
+ }
317
+ resolved = resolution.resolved;
318
+ activityTarget = resolved;
319
+
320
+ if (!isExplicitlyReadOnly(resolved.definition) && !context.allowDestructive) {
321
+ const canonicalAddress = `${resolved.connector.id}.${resolved.toolName}`;
322
+ return failed(
323
+ framingError(
324
+ "destructive_tool_requires_approval",
325
+ `Tool "${canonicalAddress}" is not explicitly read-only. Invoke it through call_destructive_tool so the MCP host can request explicit approval.`,
326
+ ),
327
+ );
328
+ }
329
+
330
+ try {
331
+ context.beforeDispatch?.();
332
+ } catch (error) {
333
+ return failed(classifyCallError(error));
334
+ }
335
+
336
+ const maxRetries = Math.min(
337
+ 2,
338
+ Math.max(0, Math.trunc(context.maxRetries ?? 0)),
339
+ );
340
+ let result: unknown;
341
+ while (true) {
342
+ attempts++;
343
+ let permit: Awaited<ReturnType<RegistryView["admitCall"]>> | undefined;
344
+ const controller =
345
+ context.timeoutMs || context.requestSignal
346
+ ? new AbortController()
347
+ : undefined;
348
+ const forwardAbort = () =>
349
+ controller?.abort(context.requestSignal?.reason);
350
+ if (context.requestSignal?.aborted) forwardAbort();
351
+ else {
352
+ context.requestSignal?.addEventListener("abort", forwardAbort, {
353
+ once: true,
354
+ });
355
+ }
356
+ let timer: ReturnType<typeof setTimeout> | undefined;
357
+ let onAbort: (() => void) | undefined;
358
+ let attemptError: unknown;
359
+ let attemptFailed = false;
360
+ try {
361
+ const admissionStarted = Date.now();
362
+ try {
363
+ permit = await this.registry.admitCall(resolved.connector.id, {
364
+ toolName: resolved.toolName,
365
+ args: args ?? {},
366
+ ...(context.requestSignal !== undefined
367
+ ? { signal: context.requestSignal }
368
+ : {}),
369
+ });
370
+ } finally {
371
+ admissionMs += Date.now() - admissionStarted;
372
+ }
373
+ const connectorContext = this.registry.contextFor(
374
+ resolved.connector.id,
375
+ this.catalog.baseUrl,
376
+ this.catalog.requestScope,
377
+ {
378
+ ...(controller?.signal !== undefined
379
+ ? { signal: controller.signal }
380
+ : {}),
381
+ ...(context.timeoutMs !== undefined
382
+ ? { timeoutMs: context.timeoutMs }
383
+ : {}),
384
+ },
385
+ );
386
+ let rejectCancelled!: (reason: unknown) => void;
387
+ const cancelled = controller
388
+ ? new Promise<never>((_, reject) => {
389
+ rejectCancelled = reject;
390
+ })
391
+ : undefined;
392
+ onAbort = () => {
393
+ rejectCancelled(
394
+ controller?.signal.reason ??
395
+ new ConnectorCallError("timeout", "Tool call was cancelled"),
396
+ );
397
+ };
398
+ controller?.signal.addEventListener("abort", onAbort, { once: true });
399
+ if (controller?.signal.aborted) onAbort();
400
+ if (controller?.signal.aborted) await cancelled;
401
+ if (context.timeoutMs) {
402
+ timer = setTimeout(() => {
403
+ controller?.abort(
404
+ new ConnectorCallError(
405
+ "timeout",
406
+ `Tool call timed out after ${context.timeoutMs}ms`,
407
+ ),
408
+ );
409
+ }, context.timeoutMs);
410
+ }
411
+ const connectorStarted = Date.now();
412
+ try {
413
+ const pending = resolved.connector.callTool(
414
+ resolved.toolName,
415
+ args ?? {},
416
+ connectorContext,
417
+ );
418
+ const raw = cancelled
419
+ ? await Promise.race([pending, cancelled])
420
+ : await pending;
421
+ // isError is checked here for BOTH result shapes so every adapter
422
+ // reports the same downstream-failure wording, and the throw lands
423
+ // inside the attempt where it stays retry-eligible and feeds health.
424
+ assertRawMcpSuccess(resolved.connector.kind, raw);
425
+ result = context.unwrapResult
426
+ ? unwrapMcpResult(resolved.connector.kind, raw)
427
+ : raw;
428
+ } finally {
429
+ connectorMs += Date.now() - connectorStarted;
430
+ }
431
+ } catch (error) {
432
+ attemptFailed = true;
433
+ attemptError = error;
434
+ } finally {
435
+ if (timer) clearTimeout(timer);
436
+ if (onAbort) {
437
+ controller?.signal.removeEventListener("abort", onAbort);
438
+ }
439
+ context.requestSignal?.removeEventListener("abort", forwardAbort);
440
+ permit?.release();
441
+ }
442
+
443
+ if (attemptFailed) {
444
+ const callerCancelled = isCallerCancellation(
445
+ attemptError,
446
+ context.requestSignal,
447
+ );
448
+ const details = callerCancelled
449
+ ? callerCancelledDetails()
450
+ : classifyCallError(attemptError);
451
+ if (
452
+ !callerCancelled &&
453
+ attempts <= maxRetries &&
454
+ retrySafe(resolved.definition) &&
455
+ details.retryable
456
+ ) {
457
+ const wait = retryBackoffMs(attempts, details.retryAfterMs);
458
+ if (wait !== undefined) {
459
+ const backoffStarted = Date.now();
460
+ if (wait > 0) {
461
+ const completed = await new Promise<boolean>((resolve) => {
462
+ let settled = false;
463
+ const finish = (value: boolean) => {
464
+ if (settled) return;
465
+ settled = true;
466
+ clearTimeout(timer);
467
+ context.requestSignal?.removeEventListener("abort", cancel);
468
+ resolve(value);
469
+ };
470
+ const timer = setTimeout(() => finish(true), wait);
471
+ const cancel = () => finish(false);
472
+ context.requestSignal?.addEventListener("abort", cancel, {
473
+ once: true,
474
+ });
475
+ if (context.requestSignal?.aborted) cancel();
476
+ });
477
+ backoffMs += Date.now() - backoffStarted;
478
+ if (!completed) return failed(callerCancelledDetails());
479
+ } else {
480
+ backoffMs += Date.now() - backoffStarted;
481
+ }
482
+ continue;
483
+ }
484
+ // The reported window is longer than the engine will park a
485
+ // synchronous request for. Fall through to failure with
486
+ // retryAfterMs reported verbatim so the agent can re-issue.
487
+ }
488
+ if (!callerCancelled && !isCallAdmissionError(attemptError)) {
489
+ this.registry.recordFailure(
490
+ resolved.connector.id,
491
+ Date.now() - started,
492
+ attemptError,
493
+ );
494
+ }
495
+ return failed(details);
496
+ }
497
+ break;
498
+ }
499
+
500
+ this.registry.recordSuccess(resolved.connector.id, Date.now() - started);
501
+ const processingStarted = Date.now();
502
+ try {
503
+ const value = context.processResult
504
+ ? await context.processResult(result, resolved)
505
+ : (result as T);
506
+ resultProcessingMs += Date.now() - processingStarted;
507
+ const diagnostics = timing();
508
+ record("success");
509
+ return {
510
+ ok: true,
511
+ value,
512
+ resolved,
513
+ durationMs: Date.now() - started,
514
+ attempts,
515
+ timing: diagnostics,
516
+ };
517
+ } catch (error) {
518
+ resultProcessingMs += Date.now() - processingStarted;
519
+ return failed(
520
+ framingError(
521
+ "result_processing_failed",
522
+ error instanceof Error ? error.message : String(error),
523
+ ),
524
+ );
525
+ }
526
+ }
527
+ }