@graph-compose/client 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,313 @@
1
+ import { Node, ToolNode, WorkflowConfig, WorkflowGraph } from "@graph-compose/core";
2
+ import { ApiResponse, ValidationResult as ClientValidationResult, ExecuteOptions, GetWorkflowResponse, TerminateWorkflowResponse, WorkflowResponse } from "../types";
3
+ import { NodeBuilder } from "./node-builder";
4
+ import { ToolBuilder } from "./tool-builder";
5
+ interface ApiValidationError {
6
+ name: string;
7
+ message: string;
8
+ }
9
+ interface ApiValidationResult {
10
+ isValid: boolean;
11
+ errors: ApiValidationError[];
12
+ }
13
+ export interface GraphComposeOptions {
14
+ /** API token for authentication. Can also be set via GRAPH_COMPOSE_TOKEN environment variable */
15
+ token?: string;
16
+ }
17
+ /**
18
+ * GraphCompose is the main builder class for creating workflow graphs.
19
+ * It provides a fluent API for building and executing workflows composed of HTTP nodes, agents, and error boundaries.
20
+ * You configure each node or tool using chained methods and **must** call `.end()` to finalize its definition.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const graph = new GraphCompose({ token: "your-token" });
25
+ *
26
+ * // Create and finalize a simple HTTP node
27
+ * graph.node("fetch_data")
28
+ * .get("https://api.example.com/data")
29
+ * .withHeaders({ "Authorization": "Bearer token" })
30
+ * .end(); // Required!
31
+ *
32
+ * // Define and end a tool (example)
33
+ * graph.tool("analyze")
34
+ * .post("https://api.example.com/analyze")
35
+ * .end();
36
+ *
37
+ * // Create and finalize an agent node that uses the tool
38
+ * graph.agent("process_data")
39
+ * .withMaxIterations(5)
40
+ * .withTools(["analyze"])
41
+ * .post("https://api.example.com/agent")
42
+ * .withDependencies(["fetch_data"])
43
+ * .end(); // Required!
44
+ *
45
+ * // Validate the complete workflow (requires all nodes/tools ended)
46
+ * const validationResult = graph.validate();
47
+ * if (!validationResult.isValid) { console.error("Validation failed:", validationResult.errors); }
48
+ *
49
+ * // Execute the workflow (requires all nodes/tools ended)
50
+ * try {
51
+ * const result = await graph.execute({});
52
+ * console.log("Execution started:", result);
53
+ * } catch (error) { console.error("Execution failed:", error); }
54
+ *
55
+ * // Get the raw workflow definition (requires all nodes/tools ended)
56
+ * const definition = graph.toJSON();
57
+ * console.log("Workflow JSON:", JSON.stringify(definition, null, 2));
58
+ *
59
+ * // Interact with existing workflows via API
60
+ * // const statusResult = await graph.getWorkflowStatus('some-workflow-id');
61
+ * // const terminateResult = await graph.terminateWorkflow('some-workflow-id');
62
+ * ```
63
+ */
64
+ export declare class GraphCompose {
65
+ private nodes;
66
+ private _tools;
67
+ private currentNodeBuilder?;
68
+ private currentToolBuilder?;
69
+ private webhookUrl?;
70
+ private context?;
71
+ private workflowConfig?;
72
+ private token;
73
+ private baseUrl;
74
+ /**
75
+ * Creates a new GraphCompose instance.
76
+ *
77
+ * @param options Configuration options for the graph builder
78
+ * @throws {Error} If no API token is provided via options or environment variable
79
+ */
80
+ constructor(options?: GraphComposeOptions);
81
+ /** Internal method for ToolBuilder to add its definition */
82
+ _addToolDefinition(tool: ToolNode): void;
83
+ /** Internal method for NodeBuilder to add its definition */
84
+ _addNodeDefinition(node: Node): void;
85
+ /**
86
+ * Checks if there's an unfinalized builder and throws an error.
87
+ * Call this before operations that require a complete workflow definition.
88
+ */
89
+ private ensureBuildersFinalized;
90
+ /**
91
+ * Start building a new HTTP node.
92
+ * HTTP nodes are the basic building blocks of workflows, used to make HTTP requests.
93
+ * **Note:** You must call `.end()` on the returned `NodeBuilder` before starting another node or finishing the graph.
94
+ *
95
+ * @param id Unique identifier for the node (must be alphanumeric with underscores)
96
+ * @returns NodeBuilder instance for method chaining
97
+ * @throws {Error} If another node or tool is currently being built.
98
+ * @example
99
+ * ```typescript
100
+ * graph.node("fetch_data")
101
+ * .get("https://api.example.com/data")
102
+ * .withHeaders({ "Authorization": "Bearer token" })
103
+ * .end(); // Required!
104
+ * ```
105
+ */
106
+ node(id: string): NodeBuilder;
107
+ /**
108
+ * Start building a new error boundary node.
109
+ * Error boundaries catch and handle errors from their protected nodes.
110
+ * **Note:** You must call `.end()` on the returned `NodeBuilder` before starting another node or finishing the graph.
111
+ *
112
+ * @param id Unique identifier for the node (must be alphanumeric with underscores)
113
+ * @param protectedNodes Array of node IDs that this error boundary protects
114
+ * @returns NodeBuilder instance for method chaining
115
+ * @throws {Error} If another node or tool is currently being built.
116
+ * @example
117
+ * ```typescript
118
+ * graph.errorBoundary("data_error_handler", ["fetch_data"])
119
+ * .post("https://api.example.com/error-handler")
120
+ * .withBody(({ context, results }) => ({
121
+ * error: results.error,
122
+ * nodeId: results.nodeId
123
+ * }))
124
+ * .end(); // Required!
125
+ * ```
126
+ */
127
+ errorBoundary(id: string, protectedNodes: string[]): NodeBuilder;
128
+ /**
129
+ * Start building a new agent node.
130
+ * Agent nodes are special nodes that can execute multiple iterations and use tools.
131
+ * **Note:** You must call `.end()` on the returned `NodeBuilder` before starting another node or finishing the graph.
132
+ *
133
+ * @param id Unique identifier for the node (must be alphanumeric with underscores)
134
+ * @returns NodeBuilder instance for method chaining
135
+ * @throws {Error} If another node or tool is currently being built.
136
+ * @example
137
+ * ```typescript
138
+ * graph.agent("research_agent")
139
+ * .withMaxIterations(10)
140
+ * .withTools(["search", "analyze"])
141
+ * .post("https://api.example.com/agent")
142
+ * .end(); // Required!
143
+ * ```
144
+ */
145
+ agent(id: string): NodeBuilder;
146
+ /**
147
+ * Start building a new tool definition.
148
+ * Tools are reusable components (HTTP calls or sub-graphs) usable by agent nodes.
149
+ * **Note:** You must call `.end()` on the returned `ToolBuilder` before starting another tool/node or finishing the graph.
150
+ *
151
+ * @param id Unique identifier for the tool (must be alphanumeric with underscores)
152
+ * @returns ToolBuilder instance for method chaining
153
+ * @throws {Error} If another node or tool is currently being built.
154
+ * @example
155
+ * ```typescript
156
+ * graph.tool("search")
157
+ * .get("https://api.search.com")
158
+ * .withHeaders({ "Authorization": "Bearer token" })
159
+ * .end(); // Required!
160
+ * ```
161
+ */
162
+ tool(id: string): ToolBuilder;
163
+ /**
164
+ * Add a pre-configured node to the workflow.
165
+ * Ensures no other builder is active before adding.
166
+ *
167
+ * @param node The node configuration to add
168
+ * @returns this GraphCompose instance for method chaining
169
+ * @throws {Error} If another node or tool is currently being built.
170
+ */
171
+ addNode(node: Node): GraphCompose;
172
+ /**
173
+ * Add a pre-configured tool definition to the workflow.
174
+ * Ensures no other builder is active before adding.
175
+ *
176
+ * @param tool The tool configuration to add
177
+ * @returns this GraphCompose instance for method chaining
178
+ * @throws {Error} If another node or tool is currently being built.
179
+ */
180
+ addTool(tool: ToolNode): GraphCompose;
181
+ /**
182
+ * Get the complete workflow definition object.
183
+ * This includes all nodes, tools, webhook URL, context, and workflow configuration.
184
+ * **Note:** Requires all active builders to be finalized using `.end()`.
185
+ *
186
+ * @returns The complete workflow graph definition object.
187
+ * @throws {Error} If a node or tool is currently being built (missing `.end()`).
188
+ */
189
+ getWorkflow(): WorkflowGraph;
190
+ /**
191
+ * Returns the complete workflow definition as a plain JavaScript object.
192
+ * This is the raw representation suitable for serialization (e.g., to JSON).
193
+ * **Note:** Requires all active builders to be finalized using `.end()`.
194
+ *
195
+ * @returns The complete workflow graph definition object.
196
+ * @throws {Error} If a node or tool is currently being built (missing `.end()`).
197
+ * @alias getWorkflow
198
+ */
199
+ toJSON(): WorkflowGraph;
200
+ /**
201
+ * Validate the current workflow locally.
202
+ * Checks for:
203
+ * - Valid node IDs
204
+ * - Valid URLs
205
+ * - Valid dependencies
206
+ * - Valid tool configurations
207
+ * - No circular dependencies
208
+ * - Agent-specific requirements (e.g., `max_iterations` presence and value)
209
+ *
210
+ * Note: This performs client-side validation only. Use `validateApi()` for server-side checks including tier limits.
211
+ *
212
+ * @returns Validation result indicating if the workflow is valid and any errors.
213
+ * @throws {Error} If a node or tool is currently being built (missing `.end()`).
214
+ */
215
+ validate(): ClientValidationResult;
216
+ /**
217
+ * Validates the current workflow definition against the API endpoint.
218
+ * Performs server-side checks including tier limits.
219
+ * **Note:** Requires all active builders to be finalized using `.end()`.
220
+ *
221
+ * @returns {Promise<ApiResponse<ApiValidationResult | null>>} The validation result from the API, wrapped in an ApiResponse.
222
+ * @throws {Error} If the API call fails or returns an unexpected format.
223
+ */
224
+ validateApi(): Promise<ApiResponse<ApiValidationResult | null>>;
225
+ /**
226
+ * Retrieves the details and status of a specific workflow instance by its ID.
227
+ *
228
+ * @param workflowId The unique identifier of the workflow instance.
229
+ * @returns Promise resolving to the full API response containing the workflow details.
230
+ * @throws {Error} If the API request fails (e.g., 404 Not Found).
231
+ */
232
+ getWorkflowStatus(workflowId: string): Promise<ApiResponse<GetWorkflowResponse | null>>;
233
+ /**
234
+ * Requests the termination of a running workflow instance.
235
+ *
236
+ * @param workflowId The unique identifier of the workflow instance to terminate.
237
+ * @param options Optional parameters including the specific run ID and a reason for termination.
238
+ * @returns Promise resolving to the full API response confirming the termination request.
239
+ * @throws {Error} If the API request fails.
240
+ */
241
+ terminateWorkflow(workflowId: string, options?: {
242
+ runId?: string;
243
+ reason?: string;
244
+ }): Promise<ApiResponse<TerminateWorkflowResponse | null>>;
245
+ /**
246
+ * Set the execution context for the workflow.
247
+ * The context is available to all nodes via JSONata expressions.
248
+ * **Note:** Requires all active builders to be finalized using `.end()`.
249
+ *
250
+ * @param context Key-value pairs that will be available to nodes
251
+ * @returns this GraphCompose instance for method chaining
252
+ * @throws {Error} If a node or tool is currently being built.
253
+ * @example
254
+ * ```typescript
255
+ * graph.withContext({
256
+ * api_key: process.env.API_KEY,
257
+ * user_id: "123",
258
+ * });
259
+ * ```
260
+ */
261
+ withContext(context: Record<string, any>): GraphCompose;
262
+ /**
263
+ * Execute the workflow asynchronously without waiting for completion.
264
+ * **Note:** Requires all active builders to be finalized using `.end()`.
265
+ *
266
+ * @param options Execution options including webhook URL and context
267
+ * @returns Promise resolving to the full API response containing the initial workflow details (like workflow ID and run ID). The status will likely be RUNNING.
268
+ * @throws {Error} If a node or tool is currently being built.
269
+ * @throws {Error} If validation fails or if the execution fails
270
+ * @example
271
+ * ```typescript
272
+ * const apiResponse = await graph.execute({ ... });
273
+ * if (apiResponse.success && apiResponse.data) {
274
+ * console.log("Workflow started:", apiResponse.data.workflowId);
275
+ * // apiResponse.data will contain workflowId, runId, etc.
276
+ * }
277
+ * ```
278
+ */
279
+ execute(options?: Omit<ExecuteOptions, "token" | "baseUrl">): Promise<ApiResponse<WorkflowResponse | null>>;
280
+ /**
281
+ * Execute the workflow synchronously and wait for completion.
282
+ * **Note:** Requires all active builders to be finalized using `.end()`.
283
+ *
284
+ * @param options Execution options including webhook URL and context
285
+ * @returns Promise resolving to the full API response containing the final workflow details (status, results, error) upon completion or failure.
286
+ * @throws {Error} If a node or tool is currently being built (missing `.end()`).
287
+ */
288
+ executeSync(options?: Omit<ExecuteOptions, "token" | "baseUrl">): Promise<ApiResponse<WorkflowResponse | null>>;
289
+ /**
290
+ * Set the webhook URL for workflow notifications.
291
+ * **Note:** Requires all active builders to be finalized using `.end()`.
292
+ *
293
+ * @param url The URL that will receive webhook notifications
294
+ * @returns this GraphCompose instance for method chaining
295
+ * @throws {Error} If a node or tool is currently being built.
296
+ */
297
+ withWebhookUrl(url: string): GraphCompose;
298
+ /**
299
+ * Sets the workflow-level configuration.
300
+ * **Note:** Requires all active builders to be finalized using `.end()`.
301
+ *
302
+ * @param config The workflow configuration object
303
+ * @returns this GraphCompose instance for method chaining
304
+ * @throws {Error} If a node or tool is currently being built.
305
+ * @example
306
+ * ```typescript
307
+ * graph.withWorkflowConfig({ workflowExecutionTimeout: '5 minutes' });
308
+ * ```
309
+ */
310
+ withWorkflowConfig(config: WorkflowConfig): GraphCompose;
311
+ }
312
+ export {};
313
+ //# sourceMappingURL=builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../../src/core/builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC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