@lushly-dev/afd-client 1.0.0 → 2.1.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/README.md +217 -34
- package/dist/backoff.d.ts +20 -0
- package/dist/backoff.d.ts.map +1 -0
- package/dist/backoff.js +42 -0
- package/dist/backoff.js.map +1 -0
- package/dist/client-errors.d.ts +39 -0
- package/dist/client-errors.d.ts.map +1 -0
- package/dist/client-errors.js +163 -0
- package/dist/client-errors.js.map +1 -0
- package/dist/client-events.d.ts +23 -0
- package/dist/client-events.d.ts.map +1 -0
- package/dist/client-events.js +47 -0
- package/dist/client-events.js.map +1 -0
- package/dist/client.d.ts +89 -31
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +364 -452
- package/dist/client.js.map +1 -1
- package/dist/direct-timeout.d.ts +22 -0
- package/dist/direct-timeout.d.ts.map +1 -0
- package/dist/direct-timeout.js +54 -0
- package/dist/direct-timeout.js.map +1 -0
- package/dist/direct-transport.d.ts +72 -0
- package/dist/direct-transport.d.ts.map +1 -0
- package/dist/direct-transport.js +231 -0
- package/dist/direct-transport.js.map +1 -0
- package/dist/direct-types.d.ts +108 -0
- package/dist/direct-types.d.ts.map +1 -0
- package/dist/direct-types.js +5 -0
- package/dist/direct-types.js.map +1 -0
- package/dist/direct-validation.d.ts +1 -1
- package/dist/direct-validation.d.ts.map +1 -1
- package/dist/direct-validation.js +4 -1
- package/dist/direct-validation.js.map +1 -1
- package/dist/direct.d.ts +62 -192
- package/dist/direct.d.ts.map +1 -1
- package/dist/direct.js +116 -450
- package/dist/direct.js.map +1 -1
- package/dist/handlers.d.ts.map +1 -1
- package/dist/handlers.js +24 -21
- package/dist/handlers.js.map +1 -1
- package/dist/handoff.d.ts +19 -6
- package/dist/handoff.d.ts.map +1 -1
- package/dist/handoff.js +112 -88
- package/dist/handoff.js.map +1 -1
- package/dist/index.d.ts +12 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -5
- package/dist/index.js.map +1 -1
- package/dist/mcp-session.d.ts +37 -0
- package/dist/mcp-session.d.ts.map +1 -0
- package/dist/mcp-session.js +159 -0
- package/dist/mcp-session.js.map +1 -0
- package/dist/mcp-stream.d.ts +59 -0
- package/dist/mcp-stream.d.ts.map +1 -0
- package/dist/mcp-stream.js +215 -0
- package/dist/mcp-stream.js.map +1 -0
- package/dist/request-abort.d.ts +3 -0
- package/dist/request-abort.d.ts.map +1 -0
- package/dist/request-abort.js +18 -0
- package/dist/request-abort.js.map +1 -0
- package/dist/result-parsing.d.ts +27 -0
- package/dist/result-parsing.d.ts.map +1 -0
- package/dist/result-parsing.js +107 -0
- package/dist/result-parsing.js.map +1 -0
- package/dist/sse-parser.d.ts +70 -0
- package/dist/sse-parser.d.ts.map +1 -0
- package/dist/sse-parser.js +159 -0
- package/dist/sse-parser.js.map +1 -0
- package/dist/transport.d.ts +53 -6
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +193 -40
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +40 -10
- package/dist/types.d.ts.map +1 -1
- package/dist/unknown-tool.d.ts +28 -8
- package/dist/unknown-tool.d.ts.map +1 -1
- package/dist/unknown-tool.js +51 -52
- package/dist/unknown-tool.js.map +1 -1
- package/package.json +7 -7
package/dist/direct.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// afd-override: max-lines=950 — DirectTransport + DirectClient + pipe() are tightly coupled via shared registry/context
|
|
2
1
|
/**
|
|
3
2
|
* @fileoverview Direct Transport for zero-overhead in-process command execution
|
|
4
3
|
*
|
|
@@ -8,225 +7,22 @@
|
|
|
8
7
|
* @example
|
|
9
8
|
* ```typescript
|
|
10
9
|
* import { createDirectClient } from '@lushly-dev/afd-client';
|
|
11
|
-
* import {
|
|
10
|
+
* import { createDirectRegistry } from '@lushly-dev/afd-server';
|
|
11
|
+
* import { commands } from '@my-app/commands';
|
|
12
12
|
*
|
|
13
|
-
*
|
|
14
|
-
* const
|
|
15
|
-
*
|
|
16
|
-
* ```
|
|
17
|
-
*
|
|
18
|
-
* @example Context propagation
|
|
19
|
-
* ```typescript
|
|
20
|
-
* const client = createDirectClient(registry, {
|
|
21
|
-
* source: 'my-agent',
|
|
22
|
-
* debug: true,
|
|
23
|
-
* });
|
|
24
|
-
*
|
|
25
|
-
* // traceId is auto-generated or can be passed per-call
|
|
26
|
-
* const result = await client.call('command', args, { traceId: 'trace-123' });
|
|
13
|
+
* // Zod validation, middleware and expose.agent checks, in process
|
|
14
|
+
* const client = createDirectClient(createDirectRegistry(commands));
|
|
15
|
+
* const result = await client.call('todo-create', { title: 'Fast!' }, { timeout: 5000 });
|
|
27
16
|
* ```
|
|
28
17
|
*/
|
|
29
|
-
import {
|
|
18
|
+
import { executePipeline, executionFailure, failure, truncateName, validationError, } from '@lushly-dev/afd-core';
|
|
19
|
+
import { runWithTimeout } from './direct-timeout.js';
|
|
30
20
|
import { validateInput } from './direct-validation.js';
|
|
31
21
|
import { connectHandoff, createReconnectingHandoff } from './handoff.js';
|
|
32
|
-
import {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
* This transport calls the command registry directly, bypassing
|
|
37
|
-
* all MCP protocol overhead. It provides:
|
|
38
|
-
*
|
|
39
|
-
* - **Zero latency**: ~0.01-0.1ms per call (vs 10-100ms for MCP)
|
|
40
|
-
* - **No serialization**: Objects passed directly (no JSON encode/decode)
|
|
41
|
-
* - **Same API**: Compatible with Transport interface for drop-in use
|
|
42
|
-
*
|
|
43
|
-
* Trade-offs:
|
|
44
|
-
* - Requires same runtime (Node.js, Bun, etc.)
|
|
45
|
-
* - No process isolation (exceptions propagate)
|
|
46
|
-
* - Registry must be importable
|
|
47
|
-
*/
|
|
48
|
-
export class DirectTransport {
|
|
49
|
-
registry;
|
|
50
|
-
connected = false;
|
|
51
|
-
messageHandler = null;
|
|
52
|
-
errorHandler = null;
|
|
53
|
-
closeHandler = null;
|
|
54
|
-
requestIdCounter = 0;
|
|
55
|
-
constructor(registry) {
|
|
56
|
-
this.registry = registry;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Connect (no-op for direct transport, always succeeds immediately).
|
|
60
|
-
*/
|
|
61
|
-
async connect() {
|
|
62
|
-
this.connected = true;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Disconnect (marks as disconnected).
|
|
66
|
-
*/
|
|
67
|
-
disconnect() {
|
|
68
|
-
this.connected = false;
|
|
69
|
-
if (this.closeHandler) {
|
|
70
|
-
this.closeHandler();
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Send a request by executing the command directly.
|
|
75
|
-
*
|
|
76
|
-
* This bypasses MCP protocol and calls the registry directly.
|
|
77
|
-
*/
|
|
78
|
-
async send(request) {
|
|
79
|
-
const requestId = request.id ?? ++this.requestIdCounter;
|
|
80
|
-
try {
|
|
81
|
-
// Handle MCP protocol methods
|
|
82
|
-
if (request.method === 'initialize') {
|
|
83
|
-
return this.handleInitialize(requestId);
|
|
84
|
-
}
|
|
85
|
-
if (request.method === 'tools/list') {
|
|
86
|
-
return this.handleToolsList(requestId);
|
|
87
|
-
}
|
|
88
|
-
if (request.method === 'tools/call') {
|
|
89
|
-
// SAFETY: When method is 'tools/call', params conforms to ToolCallParams per the MCP protocol spec.
|
|
90
|
-
const params = request.params;
|
|
91
|
-
return await this.handleToolCall(requestId, params);
|
|
92
|
-
}
|
|
93
|
-
// Unknown method
|
|
94
|
-
return {
|
|
95
|
-
jsonrpc: '2.0',
|
|
96
|
-
id: requestId,
|
|
97
|
-
error: {
|
|
98
|
-
code: -32601,
|
|
99
|
-
message: `Method not found: ${request.method}`,
|
|
100
|
-
},
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
catch (error) {
|
|
104
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
105
|
-
if (this.errorHandler) {
|
|
106
|
-
this.errorHandler(err);
|
|
107
|
-
}
|
|
108
|
-
return {
|
|
109
|
-
jsonrpc: '2.0',
|
|
110
|
-
id: requestId,
|
|
111
|
-
error: {
|
|
112
|
-
code: -32603,
|
|
113
|
-
message: err.message,
|
|
114
|
-
},
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Check if connected.
|
|
120
|
-
*/
|
|
121
|
-
isConnected() {
|
|
122
|
-
return this.connected;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Set message handler (called after each response).
|
|
126
|
-
*/
|
|
127
|
-
onMessage(handler) {
|
|
128
|
-
this.messageHandler = handler;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Set error handler.
|
|
132
|
-
*/
|
|
133
|
-
onError(handler) {
|
|
134
|
-
this.errorHandler = handler;
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Set close handler.
|
|
138
|
-
*/
|
|
139
|
-
onClose(handler) {
|
|
140
|
-
this.closeHandler = handler;
|
|
141
|
-
}
|
|
142
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
143
|
-
// MCP PROTOCOL HANDLERS
|
|
144
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
145
|
-
handleInitialize(requestId) {
|
|
146
|
-
return {
|
|
147
|
-
jsonrpc: '2.0',
|
|
148
|
-
id: requestId,
|
|
149
|
-
result: {
|
|
150
|
-
protocolVersion: '2024-11-05',
|
|
151
|
-
capabilities: {
|
|
152
|
-
tools: { listChanged: false },
|
|
153
|
-
},
|
|
154
|
-
serverInfo: {
|
|
155
|
-
name: 'direct-transport',
|
|
156
|
-
version: '1.0.0',
|
|
157
|
-
},
|
|
158
|
-
},
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
handleToolsList(requestId) {
|
|
162
|
-
const commands = this.registry.listCommands();
|
|
163
|
-
const tools = commands.map((cmd) => ({
|
|
164
|
-
name: cmd.name,
|
|
165
|
-
description: cmd.description,
|
|
166
|
-
inputSchema: {
|
|
167
|
-
type: 'object',
|
|
168
|
-
properties: {},
|
|
169
|
-
},
|
|
170
|
-
}));
|
|
171
|
-
return {
|
|
172
|
-
jsonrpc: '2.0',
|
|
173
|
-
id: requestId,
|
|
174
|
-
result: {
|
|
175
|
-
tools,
|
|
176
|
-
},
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
async handleToolCall(requestId, params) {
|
|
180
|
-
const { name, arguments: args } = params;
|
|
181
|
-
// Check if the command exists - return structured error if not
|
|
182
|
-
if (!this.registry.hasCommand(name)) {
|
|
183
|
-
const availableTools = this.registry.listCommandNames();
|
|
184
|
-
const unknownToolError = createUnknownToolError(name, availableTools);
|
|
185
|
-
// Return as a successful MCP response with error content
|
|
186
|
-
// This allows the agent to receive and process the error
|
|
187
|
-
const content = [
|
|
188
|
-
{
|
|
189
|
-
type: 'text',
|
|
190
|
-
text: JSON.stringify(unknownToolError),
|
|
191
|
-
},
|
|
192
|
-
];
|
|
193
|
-
const response = {
|
|
194
|
-
jsonrpc: '2.0',
|
|
195
|
-
id: requestId,
|
|
196
|
-
result: {
|
|
197
|
-
content,
|
|
198
|
-
isError: true,
|
|
199
|
-
},
|
|
200
|
-
};
|
|
201
|
-
if (this.messageHandler) {
|
|
202
|
-
this.messageHandler(response);
|
|
203
|
-
}
|
|
204
|
-
return response;
|
|
205
|
-
}
|
|
206
|
-
// Execute the command directly
|
|
207
|
-
const result = await this.registry.execute(name, args ?? {});
|
|
208
|
-
// Convert CommandResult to MCP response format
|
|
209
|
-
const content = [
|
|
210
|
-
{
|
|
211
|
-
type: 'text',
|
|
212
|
-
text: JSON.stringify(result),
|
|
213
|
-
},
|
|
214
|
-
];
|
|
215
|
-
const response = {
|
|
216
|
-
jsonrpc: '2.0',
|
|
217
|
-
id: requestId,
|
|
218
|
-
result: {
|
|
219
|
-
content,
|
|
220
|
-
isError: !result.success,
|
|
221
|
-
},
|
|
222
|
-
};
|
|
223
|
-
// Dispatch through message handler if set
|
|
224
|
-
if (this.messageHandler) {
|
|
225
|
-
this.messageHandler(response);
|
|
226
|
-
}
|
|
227
|
-
return response;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
22
|
+
import { unknownToolFailure } from './unknown-tool.js';
|
|
23
|
+
// Re-export extracted modules for backward compatibility
|
|
24
|
+
export { DirectTransport } from './direct-transport.js';
|
|
25
|
+
export { isUnknownToolError } from './unknown-tool.js';
|
|
230
26
|
/**
|
|
231
27
|
* Generate a unique trace ID.
|
|
232
28
|
*/
|
|
@@ -242,16 +38,20 @@ function generateTraceId() {
|
|
|
242
38
|
*
|
|
243
39
|
* @example
|
|
244
40
|
* ```typescript
|
|
245
|
-
* import {
|
|
246
|
-
* import {
|
|
41
|
+
* import { isSuccess } from '@lushly-dev/afd-core';
|
|
42
|
+
* import { createDirectClient, isUnknownToolError } from '@lushly-dev/afd-client';
|
|
43
|
+
* import { createDirectRegistry } from '@lushly-dev/afd-server';
|
|
44
|
+
* import { commands } from '@my-app/commands';
|
|
247
45
|
*
|
|
248
|
-
* const client = createDirectClient(
|
|
46
|
+
* const client = createDirectClient(createDirectRegistry(commands));
|
|
249
47
|
*
|
|
250
48
|
* // Type-safe command execution
|
|
251
49
|
* const result = await client.call<Todo>('todo-create', { title: 'Test' });
|
|
252
50
|
*
|
|
253
|
-
* if (result
|
|
254
|
-
* console.log(result.data
|
|
51
|
+
* if (isUnknownToolError(result)) {
|
|
52
|
+
* console.log(result.data?.hint); // e.g. "Did you mean 'todo-create'?"
|
|
53
|
+
* } else if (isSuccess(result)) {
|
|
54
|
+
* console.log(result.data.id); // result is CommandResult<Todo>
|
|
255
55
|
* }
|
|
256
56
|
* ```
|
|
257
57
|
*
|
|
@@ -276,8 +76,20 @@ export class DirectClient {
|
|
|
276
76
|
debug: options.debug ?? false,
|
|
277
77
|
validateInputs: options.validateInputs ?? true,
|
|
278
78
|
middleware: options.middleware ?? [],
|
|
79
|
+
allow: options.allow,
|
|
279
80
|
};
|
|
280
81
|
}
|
|
82
|
+
/** Whether the `allow` option lets this client call a command. A throwing predicate denies. */
|
|
83
|
+
isAllowed(name) {
|
|
84
|
+
if (!this.options.allow)
|
|
85
|
+
return true;
|
|
86
|
+
try {
|
|
87
|
+
return this.options.allow(name) === true;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
281
93
|
/**
|
|
282
94
|
* Call a command and return a CommandResult.
|
|
283
95
|
*
|
|
@@ -293,21 +105,20 @@ export class DirectClient {
|
|
|
293
105
|
const startTime = this.options.debug ? performance.now() : 0;
|
|
294
106
|
const traceId = context?.traceId ?? generateTraceId();
|
|
295
107
|
this.debug(`[${traceId}] Calling ${name}`, args);
|
|
108
|
+
if (!this.isAllowed(name)) {
|
|
109
|
+
this.debug(`[${traceId}] Not allowed: ${name}`);
|
|
110
|
+
return failure({
|
|
111
|
+
code: 'COMMAND_NOT_ALLOWED',
|
|
112
|
+
message: `Command '${truncateName(name)}' is not allowed for this client`,
|
|
113
|
+
suggestion: 'Call one of the commands returned by listCommandNames()',
|
|
114
|
+
retryable: false,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
296
117
|
// Check if the command exists - return structured error if not
|
|
297
118
|
if (!this.registry.hasCommand(name)) {
|
|
298
|
-
const availableTools = this.registry.listCommandNames();
|
|
299
|
-
const unknownToolError = createUnknownToolError(name, availableTools);
|
|
300
119
|
this.debug(`[${traceId}] Unknown command: ${name}`);
|
|
301
|
-
//
|
|
302
|
-
|
|
303
|
-
return {
|
|
304
|
-
success: false,
|
|
305
|
-
data: unknownToolError,
|
|
306
|
-
error: {
|
|
307
|
-
code: 'UNKNOWN_TOOL',
|
|
308
|
-
message: unknownToolError.message,
|
|
309
|
-
},
|
|
310
|
-
};
|
|
120
|
+
// The UnknownToolError is the data, so agents get structured recovery information.
|
|
121
|
+
return unknownToolFailure(name, this.listCommandNames());
|
|
311
122
|
}
|
|
312
123
|
// Input validation (if registry supports getCommand)
|
|
313
124
|
if (this.options.validateInputs && this.registry.getCommand) {
|
|
@@ -329,24 +140,12 @@ export class DirectClient {
|
|
|
329
140
|
if (this.options.source) {
|
|
330
141
|
commandContext.source = this.options.source;
|
|
331
142
|
}
|
|
332
|
-
// Execute the command (with middleware if configured)
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
const mw = this.options.middleware[i];
|
|
339
|
-
if (!mw)
|
|
340
|
-
continue;
|
|
341
|
-
const currentNext = next;
|
|
342
|
-
next = () => mw(name, args ?? {}, commandContext, currentNext);
|
|
343
|
-
}
|
|
344
|
-
result = (await next());
|
|
345
|
-
}
|
|
346
|
-
else {
|
|
347
|
-
// Zero-overhead path: no middleware
|
|
348
|
-
result = await this.registry.execute(name, args, commandContext);
|
|
349
|
-
}
|
|
143
|
+
// Execute the command (with middleware if configured), enforcing context.timeout
|
|
144
|
+
const result = await runWithTimeout(name, context?.timeout, context?.signal, (signal) => {
|
|
145
|
+
if (signal)
|
|
146
|
+
commandContext.signal = signal;
|
|
147
|
+
return this.execute(name, args, commandContext);
|
|
148
|
+
});
|
|
350
149
|
if (this.options.debug) {
|
|
351
150
|
const duration = performance.now() - startTime;
|
|
352
151
|
this.debug(`[${traceId}] Completed in ${duration.toFixed(3)}ms`, {
|
|
@@ -356,22 +155,44 @@ export class DirectClient {
|
|
|
356
155
|
return result;
|
|
357
156
|
}
|
|
358
157
|
/**
|
|
359
|
-
*
|
|
158
|
+
* Run the registry through the client middleware (none: the zero-overhead path). A registry,
|
|
159
|
+
* handler or middleware that throws gives a `COMMAND_EXECUTION_ERROR` failure (without the
|
|
160
|
+
* exception text), as `createDirectRegistry()` and the MCP server do, instead of a rejection.
|
|
161
|
+
*/
|
|
162
|
+
async execute(name, args, commandContext) {
|
|
163
|
+
let next = () => this.registry.execute(name, args, commandContext);
|
|
164
|
+
for (let i = this.options.middleware.length - 1; i >= 0; i--) {
|
|
165
|
+
const mw = this.options.middleware[i];
|
|
166
|
+
if (!mw)
|
|
167
|
+
continue;
|
|
168
|
+
const currentNext = next;
|
|
169
|
+
next = () => mw(name, args ?? {}, commandContext, currentNext);
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
return (await next());
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
this.debug(`Command '${truncateName(name)}' threw:`, error);
|
|
176
|
+
return executionFailure(error);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* List available commands (those the `allow` option permits).
|
|
360
181
|
*/
|
|
361
182
|
listCommands() {
|
|
362
|
-
return this.registry.listCommands();
|
|
183
|
+
return this.registry.listCommands().filter((command) => this.isAllowed(command.name));
|
|
363
184
|
}
|
|
364
185
|
/**
|
|
365
|
-
* List command names.
|
|
186
|
+
* List command names (those the `allow` option permits).
|
|
366
187
|
*/
|
|
367
188
|
listCommandNames() {
|
|
368
|
-
return this.registry.listCommandNames();
|
|
189
|
+
return this.registry.listCommandNames().filter((name) => this.isAllowed(name));
|
|
369
190
|
}
|
|
370
191
|
/**
|
|
371
|
-
* Check if a command exists.
|
|
192
|
+
* Check if a command exists and the `allow` option permits it.
|
|
372
193
|
*/
|
|
373
194
|
hasCommand(name) {
|
|
374
|
-
return this.registry.hasCommand(name);
|
|
195
|
+
return this.isAllowed(name) && this.registry.hasCommand(name);
|
|
375
196
|
}
|
|
376
197
|
/**
|
|
377
198
|
* Get the source identifier for this client.
|
|
@@ -405,11 +226,22 @@ export class DirectClient {
|
|
|
405
226
|
*
|
|
406
227
|
* Pipelines allow declarative composition of commands where the output
|
|
407
228
|
* of one step flows into the next. Supports variable resolution
|
|
408
|
-
* ($prev, $first, $steps[n], $steps.alias), conditional execution,
|
|
409
|
-
* and aggregated metadata (confidence, reasoning, warnings).
|
|
229
|
+
* ($prev, $first, $steps[n], $steps.alias, $input), conditional execution,
|
|
230
|
+
* and aggregated metadata (confidence, reasoning, warnings). Resolution follows
|
|
231
|
+
* `spec/pipeline-variables.md`: other `$` strings are literals, `$$` escapes a
|
|
232
|
+
* literal `$`, and unresolved references are omitted (or `null` in arrays).
|
|
233
|
+
*
|
|
234
|
+
* **Behavior change:** `$input` resolves to the request's own `input` field.
|
|
235
|
+
* It used to resolve to `context`, so a step could copy trace IDs, auth or any
|
|
236
|
+
* custom call-context value into a command input. `context` still reaches every
|
|
237
|
+
* command's context, but no reference can read it. Pass pipeline data as
|
|
238
|
+
* `pipe({ input, steps })` instead.
|
|
239
|
+
*
|
|
240
|
+
* Each step's data is copied as it is recorded and as it is resolved, so a
|
|
241
|
+
* handler that mutates its input cannot change another step's data.
|
|
410
242
|
*
|
|
411
|
-
* @param request - Pipeline request or array of steps
|
|
412
|
-
* @param context - Optional call context
|
|
243
|
+
* @param request - Pipeline request (with optional `input`) or array of steps
|
|
244
|
+
* @param context - Optional call context passed to each command; not visible to `$input`
|
|
413
245
|
* @returns Pipeline result with final data and aggregated metadata
|
|
414
246
|
*
|
|
415
247
|
* @example Basic pipeline
|
|
@@ -430,191 +262,30 @@ export class DirectClient {
|
|
|
430
262
|
* { command: 'user-get', input: { id: 123 }, as: 'user' },
|
|
431
263
|
* {
|
|
432
264
|
* command: 'premium-features',
|
|
433
|
-
* input: { userId: '$user.id' },
|
|
434
|
-
* when: { $eq: ['$user.tier', 'premium'] }
|
|
265
|
+
* input: { userId: '$steps.user.id' },
|
|
266
|
+
* when: { $eq: ['$steps.user.tier', 'premium'] }
|
|
435
267
|
* }
|
|
436
268
|
* ]);
|
|
437
269
|
* ```
|
|
270
|
+
*
|
|
271
|
+
* @example Pipeline input
|
|
272
|
+
* ```typescript
|
|
273
|
+
* const result = await client.pipe({
|
|
274
|
+
* input: { userId: 123 },
|
|
275
|
+
* steps: [{ command: 'order-list', input: { userId: '$input.userId' } }],
|
|
276
|
+
* });
|
|
277
|
+
* ```
|
|
438
278
|
*/
|
|
439
279
|
async pipe(request, context) {
|
|
440
|
-
const startTime = performance.now();
|
|
441
280
|
const traceId = context?.traceId ?? generateTraceId();
|
|
442
|
-
// Normalize request
|
|
443
281
|
const pipelineRequest = Array.isArray(request) ? { steps: request } : request;
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
previousResult: undefined,
|
|
452
|
-
};
|
|
453
|
-
const stepResults = [];
|
|
454
|
-
let finalData;
|
|
455
|
-
let pipelineFailed = false;
|
|
456
|
-
// Execute each step
|
|
457
|
-
for (let i = 0; i < stepDefs.length; i++) {
|
|
458
|
-
const stepDef = stepDefs[i];
|
|
459
|
-
if (!stepDef)
|
|
460
|
-
continue;
|
|
461
|
-
const stepStartTime = performance.now();
|
|
462
|
-
// Check timeout
|
|
463
|
-
if (timeoutMs && performance.now() - startTime > timeoutMs) {
|
|
464
|
-
const stepResult = {
|
|
465
|
-
index: i,
|
|
466
|
-
alias: stepDef.as,
|
|
467
|
-
command: stepDef.command,
|
|
468
|
-
status: 'skipped',
|
|
469
|
-
executionTimeMs: 0,
|
|
470
|
-
error: {
|
|
471
|
-
code: 'TIMEOUT',
|
|
472
|
-
message: `Pipeline timeout (${timeoutMs}ms) exceeded`,
|
|
473
|
-
},
|
|
474
|
-
};
|
|
475
|
-
stepResults.push(stepResult);
|
|
476
|
-
pipelineFailed = true;
|
|
477
|
-
break;
|
|
478
|
-
}
|
|
479
|
-
// Evaluate condition if present
|
|
480
|
-
if (stepDef.when) {
|
|
481
|
-
const conditionMet = evaluateCondition(stepDef.when, pipelineContext);
|
|
482
|
-
if (!conditionMet) {
|
|
483
|
-
this.debug(`[${traceId}] Step ${i} (${stepDef.command}) skipped: condition not met`);
|
|
484
|
-
const stepResult = {
|
|
485
|
-
index: i,
|
|
486
|
-
alias: stepDef.as,
|
|
487
|
-
command: stepDef.command,
|
|
488
|
-
status: 'skipped',
|
|
489
|
-
executionTimeMs: 0,
|
|
490
|
-
};
|
|
491
|
-
stepResults.push(stepResult);
|
|
492
|
-
// Add to context with undefined data so alias is still resolvable
|
|
493
|
-
pipelineContext.steps.push({
|
|
494
|
-
index: i,
|
|
495
|
-
alias: stepDef.as,
|
|
496
|
-
command: stepDef.command,
|
|
497
|
-
status: 'skipped',
|
|
498
|
-
data: undefined,
|
|
499
|
-
executionTimeMs: 0,
|
|
500
|
-
});
|
|
501
|
-
continue;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
// If pipeline already failed and we're not continuing on failure, skip
|
|
505
|
-
if (pipelineFailed && !continueOnFailure) {
|
|
506
|
-
const stepResult = {
|
|
507
|
-
index: i,
|
|
508
|
-
alias: stepDef.as,
|
|
509
|
-
command: stepDef.command,
|
|
510
|
-
status: 'skipped',
|
|
511
|
-
executionTimeMs: 0,
|
|
512
|
-
};
|
|
513
|
-
stepResults.push(stepResult);
|
|
514
|
-
continue;
|
|
515
|
-
}
|
|
516
|
-
// Resolve variables in input
|
|
517
|
-
const resolvedInput = stepDef.input
|
|
518
|
-
? resolveVariables(stepDef.input, pipelineContext)
|
|
519
|
-
: undefined;
|
|
520
|
-
this.debug(`[${traceId}] Step ${i}: ${stepDef.command}`, resolvedInput);
|
|
521
|
-
// Execute the command
|
|
522
|
-
const result = await this.call(stepDef.command, resolvedInput, {
|
|
523
|
-
...context,
|
|
524
|
-
traceId: `${traceId}-step-${i}`,
|
|
525
|
-
});
|
|
526
|
-
const stepExecutionTime = performance.now() - stepStartTime;
|
|
527
|
-
if (result.success) {
|
|
528
|
-
const stepResult = {
|
|
529
|
-
index: i,
|
|
530
|
-
alias: stepDef.as,
|
|
531
|
-
command: stepDef.command,
|
|
532
|
-
status: 'success',
|
|
533
|
-
data: result.data,
|
|
534
|
-
executionTimeMs: stepExecutionTime,
|
|
535
|
-
metadata: this.extractResultMetadata(result),
|
|
536
|
-
};
|
|
537
|
-
stepResults.push(stepResult);
|
|
538
|
-
// Update context
|
|
539
|
-
pipelineContext.steps.push(stepResult);
|
|
540
|
-
pipelineContext.previousResult = stepResult;
|
|
541
|
-
finalData = result.data;
|
|
542
|
-
}
|
|
543
|
-
else {
|
|
544
|
-
const stepResult = {
|
|
545
|
-
index: i,
|
|
546
|
-
alias: stepDef.as,
|
|
547
|
-
command: stepDef.command,
|
|
548
|
-
status: 'failure',
|
|
549
|
-
error: result.error,
|
|
550
|
-
executionTimeMs: stepExecutionTime,
|
|
551
|
-
};
|
|
552
|
-
stepResults.push(stepResult);
|
|
553
|
-
pipelineContext.steps.push(stepResult);
|
|
554
|
-
pipelineFailed = true;
|
|
555
|
-
if (!continueOnFailure) {
|
|
556
|
-
this.debug(`[${traceId}] Pipeline failed at step ${i}: ${result.error?.message}`);
|
|
557
|
-
// Mark remaining steps as skipped
|
|
558
|
-
for (let j = i + 1; j < stepDefs.length; j++) {
|
|
559
|
-
const skippedDef = stepDefs[j];
|
|
560
|
-
if (!skippedDef)
|
|
561
|
-
continue;
|
|
562
|
-
stepResults.push({
|
|
563
|
-
index: j,
|
|
564
|
-
alias: skippedDef.as,
|
|
565
|
-
command: skippedDef.command,
|
|
566
|
-
status: 'skipped',
|
|
567
|
-
executionTimeMs: 0,
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
break;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
const totalExecutionTime = performance.now() - startTime;
|
|
575
|
-
// Build aggregated metadata
|
|
576
|
-
const metadata = this.buildPipelineMetadata(stepResults, stepDefs, totalExecutionTime);
|
|
577
|
-
this.debug(`[${traceId}] Pipeline completed in ${totalExecutionTime.toFixed(3)}ms`, {
|
|
578
|
-
completedSteps: metadata.completedSteps,
|
|
579
|
-
totalSteps: metadata.totalSteps,
|
|
580
|
-
success: !pipelineFailed,
|
|
581
|
-
});
|
|
582
|
-
return {
|
|
583
|
-
data: finalData,
|
|
584
|
-
metadata,
|
|
585
|
-
steps: stepResults,
|
|
586
|
-
};
|
|
587
|
-
}
|
|
588
|
-
/**
|
|
589
|
-
* Extract metadata from a command result.
|
|
590
|
-
*/
|
|
591
|
-
extractResultMetadata(result) {
|
|
592
|
-
return {
|
|
593
|
-
confidence: result.confidence,
|
|
594
|
-
reasoning: result.reasoning,
|
|
595
|
-
warnings: result.warnings,
|
|
596
|
-
sources: result.sources,
|
|
597
|
-
alternatives: result.alternatives,
|
|
598
|
-
executionTimeMs: result.metadata?.executionTimeMs,
|
|
599
|
-
};
|
|
600
|
-
}
|
|
601
|
-
/**
|
|
602
|
-
* Build aggregated pipeline metadata from step results.
|
|
603
|
-
*/
|
|
604
|
-
buildPipelineMetadata(steps, stepDefs, totalExecutionTime) {
|
|
605
|
-
const completedSteps = steps.filter((s) => s.status === 'success').length;
|
|
606
|
-
const totalSteps = steps.length;
|
|
607
|
-
return {
|
|
608
|
-
confidence: aggregatePipelineConfidence(steps),
|
|
609
|
-
confidenceBreakdown: buildConfidenceBreakdown(steps, stepDefs),
|
|
610
|
-
reasoning: aggregatePipelineReasoning(steps),
|
|
611
|
-
warnings: aggregatePipelineWarnings(steps),
|
|
612
|
-
sources: aggregatePipelineSources(steps),
|
|
613
|
-
alternatives: aggregatePipelineAlternatives(steps),
|
|
614
|
-
executionTimeMs: totalExecutionTime,
|
|
615
|
-
completedSteps,
|
|
616
|
-
totalSteps,
|
|
617
|
-
};
|
|
282
|
+
this.debug(`[${traceId}] Starting pipeline`);
|
|
283
|
+
let stepIndex = 0;
|
|
284
|
+
return executePipeline(pipelineRequest, (command, input, commandContext) => this.call(command, input, {
|
|
285
|
+
...context,
|
|
286
|
+
...commandContext,
|
|
287
|
+
traceId: `${traceId}-step-${stepIndex++}`,
|
|
288
|
+
}), { ...context, traceId });
|
|
618
289
|
}
|
|
619
290
|
/**
|
|
620
291
|
* Debug logging helper.
|
|
@@ -636,23 +307,18 @@ export class DirectClient {
|
|
|
636
307
|
* @param options - Optional configuration for validation, context, and debugging
|
|
637
308
|
* @returns A new DirectClient instance
|
|
638
309
|
*
|
|
639
|
-
* @example
|
|
310
|
+
* @example
|
|
640
311
|
* ```typescript
|
|
641
312
|
* import { createDirectClient } from '@lushly-dev/afd-client';
|
|
642
|
-
* import {
|
|
643
|
-
*
|
|
644
|
-
* const client = createDirectClient(registry);
|
|
645
|
-
* const result = await client.call('plant-get', { id: 'tomato-123' });
|
|
646
|
-
* // ~0.03-0.1ms latency vs ~2-10ms for MCP
|
|
647
|
-
* ```
|
|
313
|
+
* import { createDirectRegistry } from '@lushly-dev/afd-server';
|
|
314
|
+
* import { commands } from './commands';
|
|
648
315
|
*
|
|
649
|
-
*
|
|
650
|
-
* ```typescript
|
|
651
|
-
* const client = createDirectClient(registry, {
|
|
316
|
+
* const client = createDirectClient(createDirectRegistry(commands), {
|
|
652
317
|
* source: 'garden-api',
|
|
653
|
-
*
|
|
654
|
-
* validateInputs: true,
|
|
318
|
+
* allow: (name) => name.startsWith('plant-'),
|
|
655
319
|
* });
|
|
320
|
+
* const result = await client.call('plant-get', { id: 'tomato-123' });
|
|
321
|
+
* // ~0.03-0.1ms latency vs ~2-10ms for MCP
|
|
656
322
|
* ```
|
|
657
323
|
*/
|
|
658
324
|
export function createDirectClient(registry, options) {
|