@blazingagents/sdk 0.19.0 → 0.21.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 +17 -1
- package/dist/approvals.d.ts +4 -12
- package/dist/approvals.js +12 -13
- package/dist/chat-transport.d.ts +18 -1
- package/dist/chat-transport.js +16 -0
- package/dist/client.d.ts +28 -5
- package/dist/client.js +39 -7
- package/dist/contracts/api.d.ts +40 -6
- package/dist/contracts/api.js +30 -2
- package/dist/contracts/entities/agent-tools.d.ts +5 -2
- package/dist/contracts/entities/agent-tools.js +5 -2
- package/dist/contracts/entities/agents.d.ts +4 -0
- package/dist/contracts/entities/agents.js +9 -0
- package/dist/contracts/entities/chat.d.ts +11 -10
- package/dist/contracts/entities/chat.js +11 -7
- package/dist/contracts/entities/mcp-connections.d.ts +3 -1
- package/dist/contracts/entities/mcp-connections.js +3 -1
- package/dist/contracts/entities/prompts.d.ts +13 -0
- package/dist/contracts/entities/prompts.js +13 -0
- package/dist/contracts/entities/session-inputs.d.ts +29 -87
- package/dist/contracts/entities/session-inputs.js +21 -19
- package/dist/contracts/entities/sessions.d.ts +27 -17
- package/dist/contracts/entities/sessions.js +23 -8
- package/dist/contracts/entities/skills.d.ts +3 -0
- package/dist/contracts/entities/skills.js +3 -0
- package/dist/contracts/entities/tasks.d.ts +1 -0
- package/dist/contracts/entities/usage.d.ts +4 -1
- package/dist/contracts/entities/usage.js +7 -1
- package/dist/contracts/entities/workspaces.d.ts +17 -6
- package/dist/contracts/entities/workspaces.js +3 -7
- package/dist/contracts/ids.d.ts +31 -0
- package/dist/contracts/ids.js +34 -0
- package/dist/contracts/index.d.ts +7 -6
- package/dist/contracts/index.js +4 -4
- package/dist/contracts/utils.d.ts +10 -0
- package/dist/contracts/utils.js +10 -0
- package/dist/direct-chat-transport.d.ts +30 -3
- package/dist/direct-chat-transport.js +40 -35
- package/dist/errors.d.ts +9 -0
- package/dist/errors.js +9 -0
- package/dist/functions.d.ts +35 -2
- package/dist/functions.js +60 -4
- package/dist/generation.d.ts +34 -2
- package/dist/generation.js +97 -19
- package/dist/http.d.ts +26 -0
- package/dist/http.js +43 -0
- package/dist/index.d.ts +4 -4
- package/dist/relay.d.ts +26 -3
- package/dist/relay.js +25 -10
- package/dist/resources/agents.d.ts +5 -0
- package/dist/resources/agents.js +38 -0
- package/dist/resources/artifacts.d.ts +2 -0
- package/dist/resources/artifacts.js +14 -0
- package/dist/resources/chat-connections.d.ts +5 -0
- package/dist/resources/chat-connections.js +32 -0
- package/dist/resources/chat-deliveries.d.ts +2 -0
- package/dist/resources/chat-deliveries.js +5 -0
- package/dist/resources/mcp-connections.d.ts +5 -0
- package/dist/resources/mcp-connections.js +26 -0
- package/dist/resources/memories.d.ts +2 -0
- package/dist/resources/memories.js +17 -0
- package/dist/resources/merchant-bindings.d.ts +2 -0
- package/dist/resources/merchant-bindings.js +11 -0
- package/dist/resources/merchant-connection.d.ts +2 -0
- package/dist/resources/merchant-connection.js +14 -0
- package/dist/resources/merchant-usage-events.d.ts +2 -0
- package/dist/resources/merchant-usage-events.js +20 -0
- package/dist/resources/prompts.d.ts +5 -0
- package/dist/resources/prompts.js +20 -0
- package/dist/resources/providers.d.ts +2 -0
- package/dist/resources/providers.js +23 -0
- package/dist/resources/sessions.d.ts +2 -0
- package/dist/resources/sessions.js +42 -39
- package/dist/resources/skills.d.ts +5 -0
- package/dist/resources/skills.js +35 -0
- package/dist/resources/tasks.d.ts +2 -0
- package/dist/resources/tasks.js +32 -0
- package/dist/resources/tenant.d.ts +2 -0
- package/dist/resources/tenant.js +8 -0
- package/dist/resources/usage.d.ts +2 -0
- package/dist/resources/usage.js +14 -0
- package/dist/resources/workspaces.d.ts +5 -0
- package/dist/resources/workspaces.js +20 -0
- package/dist/types.d.ts +691 -48
- package/package.json +1 -1
package/dist/generation.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { createTextStreamResponse, parsePartialJson } from "ai";
|
|
2
|
-
import { toolApprovalsResponseSchema } from "./contracts/entities/sessions.js";
|
|
3
2
|
import { sessionIdSchema } from "./contracts/ids.js";
|
|
4
3
|
import { BlazingAgentsError } from "./errors.js";
|
|
5
4
|
import { dispatchChatFunctions, toChatFunctionDefinitions, } from "./functions.js";
|
|
6
|
-
import {
|
|
5
|
+
import { requestStream } from "./http.js";
|
|
6
|
+
/**
|
|
7
|
+
* Creates or resumes a Session and returns its SSE stream and Session ID.
|
|
8
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
9
|
+
* @param input - Agent, message or stored Prompt, and optional existing Session.
|
|
10
|
+
* @returns The Session ID promise and single-owner SSE accessors.
|
|
11
|
+
*/
|
|
7
12
|
export async function chat(config, input) {
|
|
8
13
|
const body = buildChatBody(input);
|
|
9
14
|
if (input.functions && Object.keys(input.functions).length > 0) {
|
|
@@ -30,14 +35,23 @@ export async function chat(config, input) {
|
|
|
30
35
|
abortSignal: input.abortSignal,
|
|
31
36
|
});
|
|
32
37
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Submits a complete Tool approval round and streams its continuation.
|
|
40
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
41
|
+
* @param input - Agent, Session, and decisions for the complete approval round.
|
|
42
|
+
* @returns The Session ID promise and continuation SSE accessors.
|
|
43
|
+
*/
|
|
44
|
+
export async function continueChat(config, input) {
|
|
45
|
+
const response = await requestStream(config, `/v1/agents/${input.agentId}/sessions/${input.sessionId}/tool-approvals/continue`, {
|
|
46
|
+
json: {
|
|
47
|
+
decisions: input.decisions,
|
|
48
|
+
...(input.functions === undefined
|
|
49
|
+
? {}
|
|
50
|
+
: { functions: toChatFunctionDefinitions(input.functions) }),
|
|
51
|
+
},
|
|
38
52
|
method: "POST",
|
|
39
53
|
clientRequestId: input.clientRequestId,
|
|
40
|
-
|
|
54
|
+
signal: input.abortSignal,
|
|
41
55
|
});
|
|
42
56
|
return buildChatResult(config, response, input.sessionId, {
|
|
43
57
|
agentId: input.agentId,
|
|
@@ -45,19 +59,11 @@ export async function resumeChat(config, input) {
|
|
|
45
59
|
abortSignal: input.abortSignal,
|
|
46
60
|
});
|
|
47
61
|
}
|
|
48
|
-
async function activeContinuationId(config, { agentId, sessionId, abortSignal }) {
|
|
49
|
-
const { continuation } = await requestJson(config, `/v1/agents/${agentId}/sessions/${sessionId}/tool-approvals`, { signal: abortSignal }, toolApprovalsResponseSchema);
|
|
50
|
-
if (continuation?.state !== "queued" && continuation?.state !== "running") {
|
|
51
|
-
throw new BlazingAgentsError({
|
|
52
|
-
code: "not_found",
|
|
53
|
-
message: "The Session has no tool approval continuation to resume.",
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
return continuation.id;
|
|
57
|
-
}
|
|
58
62
|
/**
|
|
59
63
|
* Keeps status and headers while filtering the SSE body. Missing or locked
|
|
60
64
|
* bodies pass through so the stream result reports them as `stream_error`.
|
|
65
|
+
* @param response - Upstream HTTP response.
|
|
66
|
+
* @param filter - Transforms upstream SSE bytes before exposing them to the caller.
|
|
61
67
|
*/
|
|
62
68
|
export function withFilteredBody(response, filter) {
|
|
63
69
|
if (!response.body || response.body.locked) {
|
|
@@ -69,6 +75,9 @@ export function withFilteredBody(response, filter) {
|
|
|
69
75
|
statusText: response.statusText,
|
|
70
76
|
});
|
|
71
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Builds a chat request body from messages or a stored Prompt.
|
|
80
|
+
*/
|
|
72
81
|
function buildChatBody(input) {
|
|
73
82
|
const base = {};
|
|
74
83
|
// Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined trigger.
|
|
@@ -80,7 +89,10 @@ function buildChatBody(input) {
|
|
|
80
89
|
base.messageId = input.messageId;
|
|
81
90
|
}
|
|
82
91
|
if ("message" in input) {
|
|
83
|
-
base.
|
|
92
|
+
base.messages = [input.message];
|
|
93
|
+
}
|
|
94
|
+
else if ("messages" in input) {
|
|
95
|
+
base.messages = input.messages;
|
|
84
96
|
}
|
|
85
97
|
else {
|
|
86
98
|
base.promptId = input.promptId;
|
|
@@ -127,6 +139,9 @@ function sessionIdFromLocation(response, requestId) {
|
|
|
127
139
|
}
|
|
128
140
|
return parsed.data;
|
|
129
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* Combines the Session ID promise with a single-owner SSE result.
|
|
144
|
+
*/
|
|
130
145
|
function buildChatResult(config, response, resumeSessionId, dispatch) {
|
|
131
146
|
/**
|
|
132
147
|
* `sessionId` resolves from the `Location` header on create, or to the
|
|
@@ -159,10 +174,20 @@ function buildChatResult(config, response, resumeSessionId, dispatch) {
|
|
|
159
174
|
...buildTerminalStreamResult(streamResponse, "chat"),
|
|
160
175
|
};
|
|
161
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* Creates single-owner SSE response and byte-stream accessors.
|
|
179
|
+
* @param response - Upstream HTTP response.
|
|
180
|
+
* @param resourceName - Resource label used in stream errors.
|
|
181
|
+
* @param filter - Transforms upstream SSE bytes before exposing them to the caller.
|
|
182
|
+
*/
|
|
162
183
|
export function buildTerminalStreamResult(response, resourceName, filter) {
|
|
163
184
|
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
164
185
|
const location = response.headers.get("location");
|
|
165
186
|
let bodyClaimed = false;
|
|
187
|
+
/**
|
|
188
|
+
* Claims the response body once and normalizes stream failures.
|
|
189
|
+
* @throws BlazingAgentsError - If the response body has already been claimed.
|
|
190
|
+
*/
|
|
166
191
|
const claimBody = () => {
|
|
167
192
|
if (bodyClaimed) {
|
|
168
193
|
const message = `The ${resourceName} response body has already been claimed.`;
|
|
@@ -180,6 +205,7 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
|
|
|
180
205
|
return {
|
|
181
206
|
requestId,
|
|
182
207
|
toStream: claimBody,
|
|
208
|
+
/** Claims the response relay once. */
|
|
183
209
|
toResponse: () => {
|
|
184
210
|
const headers = replacementResponseHeaders(requestId, location);
|
|
185
211
|
headers.set("content-type", "text/event-stream");
|
|
@@ -200,6 +226,9 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
|
|
|
200
226
|
},
|
|
201
227
|
};
|
|
202
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* Preserves a matching stream error or wraps a failure with request correlation.
|
|
231
|
+
*/
|
|
203
232
|
function toStreamError(cause, requestId, fallbackMessage) {
|
|
204
233
|
if (BlazingAgentsError.isInstance(cause) &&
|
|
205
234
|
cause.code === "stream_error" &&
|
|
@@ -222,6 +251,9 @@ function toStreamError(cause, requestId, fallbackMessage) {
|
|
|
222
251
|
requestId,
|
|
223
252
|
}, { cause });
|
|
224
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Wraps reads and cancellation failures as correlated SDK stream errors.
|
|
256
|
+
*/
|
|
225
257
|
function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
226
258
|
let reader;
|
|
227
259
|
try {
|
|
@@ -231,6 +263,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
|
231
263
|
throw toStreamError(cause, requestId, fallbackMessage);
|
|
232
264
|
}
|
|
233
265
|
return new ReadableStream({
|
|
266
|
+
/**
|
|
267
|
+
* Reads one upstream chunk and normalizes stream failures.
|
|
268
|
+
*/
|
|
234
269
|
async pull(controller) {
|
|
235
270
|
try {
|
|
236
271
|
const { done, value } = await reader.read();
|
|
@@ -244,6 +279,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
|
244
279
|
controller.error(toStreamError(cause, requestId, fallbackMessage));
|
|
245
280
|
}
|
|
246
281
|
},
|
|
282
|
+
/**
|
|
283
|
+
* Cancels the upstream reader with the consumer reason.
|
|
284
|
+
*/
|
|
247
285
|
async cancel(reason) {
|
|
248
286
|
try {
|
|
249
287
|
await reader.cancel(reason);
|
|
@@ -254,6 +292,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
|
254
292
|
},
|
|
255
293
|
});
|
|
256
294
|
}
|
|
295
|
+
/**
|
|
296
|
+
* Returns the response body or a stream that fails when the body is missing.
|
|
297
|
+
*/
|
|
257
298
|
function responseBodyStream(response, requestId, resourceName) {
|
|
258
299
|
if (response.body) {
|
|
259
300
|
return response.body;
|
|
@@ -266,11 +307,17 @@ function responseBodyStream(response, requestId, resourceName) {
|
|
|
266
307
|
requestId,
|
|
267
308
|
}, { cause });
|
|
268
309
|
return new ReadableStream({
|
|
310
|
+
/**
|
|
311
|
+
* Initializes the stream controller.
|
|
312
|
+
*/
|
|
269
313
|
start(controller) {
|
|
270
314
|
controller.error(error);
|
|
271
315
|
},
|
|
272
316
|
});
|
|
273
317
|
}
|
|
318
|
+
/**
|
|
319
|
+
* Copies request correlation and Session location into relay response headers.
|
|
320
|
+
*/
|
|
274
321
|
function replacementResponseHeaders(requestId, location) {
|
|
275
322
|
const headers = new Headers();
|
|
276
323
|
if (requestId !== undefined) {
|
|
@@ -281,6 +328,9 @@ function replacementResponseHeaders(requestId, location) {
|
|
|
281
328
|
}
|
|
282
329
|
return headers;
|
|
283
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* Builds a stateless prompt request with the selected output format.
|
|
333
|
+
*/
|
|
284
334
|
function buildStatelessGenerationBody(input, output) {
|
|
285
335
|
const body = { output };
|
|
286
336
|
if ("prompt" in input) {
|
|
@@ -303,6 +353,12 @@ function buildStatelessGenerationBody(input, output) {
|
|
|
303
353
|
}
|
|
304
354
|
return body;
|
|
305
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* Starts stateless text generation with independent final, incremental, and response outputs.
|
|
358
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
359
|
+
* @param input - Agent and literal prompt or stored Prompt reference.
|
|
360
|
+
* @returns Independent text stream, final text promise, and response relay.
|
|
361
|
+
*/
|
|
306
362
|
export async function completion(config, input) {
|
|
307
363
|
const body = buildStatelessGenerationBody(input, { type: "text" });
|
|
308
364
|
const path = `/v1/agents/${input.agentId}/generation`;
|
|
@@ -314,6 +370,9 @@ export async function completion(config, input) {
|
|
|
314
370
|
});
|
|
315
371
|
return buildCompletionResult(response);
|
|
316
372
|
}
|
|
373
|
+
/**
|
|
374
|
+
* Splits text output into a final promise, incremental stream, and response relay.
|
|
375
|
+
*/
|
|
317
376
|
function buildCompletionResult(response) {
|
|
318
377
|
const { finalStream, outputStream, requestId, toResponse } = buildStatelessGenerationStreams(response, "completion");
|
|
319
378
|
const textPromise = (async () => {
|
|
@@ -333,6 +392,12 @@ function buildCompletionResult(response) {
|
|
|
333
392
|
toResponse,
|
|
334
393
|
};
|
|
335
394
|
}
|
|
395
|
+
/**
|
|
396
|
+
* Starts stateless JSON generation with partial objects and a final parsed value.
|
|
397
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
398
|
+
* @param input - Agent, prompt source, and JSON output schema.
|
|
399
|
+
* @returns Partial JSON objects, a final JSON promise, and a text response relay.
|
|
400
|
+
*/
|
|
336
401
|
export async function objectGeneration(config, input) {
|
|
337
402
|
const body = buildStatelessGenerationBody(input, {
|
|
338
403
|
type: "object",
|
|
@@ -347,10 +412,16 @@ export async function objectGeneration(config, input) {
|
|
|
347
412
|
});
|
|
348
413
|
return buildObjectResult(response);
|
|
349
414
|
}
|
|
415
|
+
/**
|
|
416
|
+
* Parses partial and final JSON from independent text-stream branches.
|
|
417
|
+
*/
|
|
350
418
|
function buildObjectResult(response) {
|
|
351
419
|
const { finalStream, outputStream, requestId, toResponse } = buildStatelessGenerationStreams(response, "object");
|
|
352
420
|
let accumulatedText = "";
|
|
353
421
|
const partialObjectStream = outputStream.pipeThrough(new TransformStream({
|
|
422
|
+
/**
|
|
423
|
+
* Accumulates generated text and emits each available partial JSON value.
|
|
424
|
+
*/
|
|
354
425
|
async transform(chunk, controller) {
|
|
355
426
|
accumulatedText += chunk;
|
|
356
427
|
const { value } = await parsePartialJson(accumulatedText);
|
|
@@ -358,6 +429,9 @@ function buildObjectResult(response) {
|
|
|
358
429
|
controller.enqueue(value);
|
|
359
430
|
}
|
|
360
431
|
},
|
|
432
|
+
/**
|
|
433
|
+
* Rejects malformed final JSON when the text stream ends.
|
|
434
|
+
*/
|
|
361
435
|
flush() {
|
|
362
436
|
try {
|
|
363
437
|
JSON.parse(accumulatedText);
|
|
@@ -397,6 +471,9 @@ function buildObjectResult(response) {
|
|
|
397
471
|
toResponse,
|
|
398
472
|
};
|
|
399
473
|
}
|
|
474
|
+
/**
|
|
475
|
+
* Splits decoded text into final, public, and response-relay branches.
|
|
476
|
+
*/
|
|
400
477
|
function buildStatelessGenerationStreams(response, resourceName) {
|
|
401
478
|
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
402
479
|
const location = response.headers.get("location");
|
|
@@ -413,6 +490,7 @@ function buildStatelessGenerationStreams(response, resourceName) {
|
|
|
413
490
|
finalStream,
|
|
414
491
|
outputStream,
|
|
415
492
|
requestId,
|
|
493
|
+
/** Claims the response relay once. */
|
|
416
494
|
toResponse: () => {
|
|
417
495
|
if (responseBodyClaimed) {
|
|
418
496
|
const message = `The ${resourceName} response body has already been claimed.`;
|
package/dist/http.d.ts
CHANGED
|
@@ -4,20 +4,46 @@ import type { HttpConfig, RequestOptions } from "./types.ts";
|
|
|
4
4
|
* Performs a request and returns the parsed JSON body for success (status
|
|
5
5
|
* 2xx). API errors preserve the tolerant wire envelope; malformed responses
|
|
6
6
|
* become `invalid_response`.
|
|
7
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
8
|
+
* @param path - Endpoint path relative to the base URL.
|
|
9
|
+
* @param options - Configuration for this operation.
|
|
10
|
+
* @param schema - Schema used to validate the value.
|
|
7
11
|
*/
|
|
8
12
|
export declare function requestJson<T>(config: HttpConfig, path: string, options?: RequestOptions, schema?: {
|
|
13
|
+
/**
|
|
14
|
+
* Validates the decoded response value.
|
|
15
|
+
* @param value - Value to inspect.
|
|
16
|
+
*/
|
|
9
17
|
parse(value: unknown): T;
|
|
10
18
|
}): Promise<T>;
|
|
11
19
|
/**
|
|
12
20
|
* Performs a request and returns the raw `Response` for streaming paths.
|
|
13
21
|
* Non-2xx bodies are decoded before a caller can observe a streaming body.
|
|
22
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
23
|
+
* @param path - Endpoint path relative to the base URL.
|
|
24
|
+
* @param options - Configuration for this operation.
|
|
14
25
|
*/
|
|
15
26
|
export declare function requestStream(config: HttpConfig, path: string, options?: RequestOptions): Promise<Response>;
|
|
27
|
+
/**
|
|
28
|
+
* Checks whether the signal aborted or the cause names an AbortError.
|
|
29
|
+
* @param cause - Original failure to retain.
|
|
30
|
+
* @param signal - Signal that cancels the operation.
|
|
31
|
+
* @returns Whether the request signal or cause indicates cancellation.
|
|
32
|
+
*/
|
|
16
33
|
export declare function isRequestAborted(cause: unknown, signal?: AbortSignal): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Wraps an abort cause as a request_aborted SDK error.
|
|
36
|
+
* @param cause - Original failure to retain.
|
|
37
|
+
* @returns A request_aborted error retaining the cause.
|
|
38
|
+
*/
|
|
17
39
|
export declare function requestAbortedError(cause: unknown): BlazingAgentsError;
|
|
18
40
|
/**
|
|
19
41
|
* Decodes a response body with the tolerant consumer schema. Unknown future
|
|
20
42
|
* codes and fields remain valid; malformed responses never infer a domain
|
|
21
43
|
* code from HTTP status.
|
|
44
|
+
* @param bodyText - Response body as text.
|
|
45
|
+
* @param status - HTTP response status.
|
|
46
|
+
* @param headers - Response headers to preserve or inspect.
|
|
47
|
+
* @returns The server error, or invalid_response when the envelope is malformed.
|
|
22
48
|
*/
|
|
23
49
|
export declare function parseErrorEnvelope(bodyText: string, status: number, headers?: Headers): BlazingAgentsError;
|
package/dist/http.js
CHANGED
|
@@ -4,6 +4,9 @@ const DIAGNOSTIC_BODY_LIMIT_BYTES = 64 * 1024;
|
|
|
4
4
|
const INVALID_RESPONSE_MESSAGE = "The server returned an invalid response.";
|
|
5
5
|
const NETWORK_ERROR_MESSAGE = "Network request failed (fetch threw before any HTTP exchange).";
|
|
6
6
|
const REQUEST_ABORTED_MESSAGE = "The request was aborted before any HTTP response.";
|
|
7
|
+
/**
|
|
8
|
+
* Appends query values while omitting null and undefined entries.
|
|
9
|
+
*/
|
|
7
10
|
function buildUrl(baseUrl, path, query) {
|
|
8
11
|
const url = `${baseUrl}${path}`;
|
|
9
12
|
if (!query) {
|
|
@@ -23,6 +26,10 @@ function buildUrl(baseUrl, path, query) {
|
|
|
23
26
|
* Performs a request and returns the parsed JSON body for success (status
|
|
24
27
|
* 2xx). API errors preserve the tolerant wire envelope; malformed responses
|
|
25
28
|
* become `invalid_response`.
|
|
29
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
30
|
+
* @param path - Endpoint path relative to the base URL.
|
|
31
|
+
* @param options - Configuration for this operation.
|
|
32
|
+
* @param schema - Schema used to validate the value.
|
|
26
33
|
*/
|
|
27
34
|
export async function requestJson(config, path, options = {}, schema) {
|
|
28
35
|
const response = await rawRequest(config, path, options);
|
|
@@ -56,6 +63,9 @@ export async function requestJson(config, path, options = {}, schema) {
|
|
|
56
63
|
/**
|
|
57
64
|
* Performs a request and returns the raw `Response` for streaming paths.
|
|
58
65
|
* Non-2xx bodies are decoded before a caller can observe a streaming body.
|
|
66
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
67
|
+
* @param path - Endpoint path relative to the base URL.
|
|
68
|
+
* @param options - Configuration for this operation.
|
|
59
69
|
*/
|
|
60
70
|
export async function requestStream(config, path, options = {}) {
|
|
61
71
|
const response = await rawRequest(config, path, options);
|
|
@@ -64,6 +74,9 @@ export async function requestStream(config, path, options = {}) {
|
|
|
64
74
|
}
|
|
65
75
|
throw await errorFromResponse(response, options.signal);
|
|
66
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Sends an authenticated request and reports response metadata to the observer.
|
|
79
|
+
*/
|
|
67
80
|
async function rawRequest(config, path, options) {
|
|
68
81
|
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
69
82
|
const url = buildUrl(config.baseUrl, path, options.query);
|
|
@@ -122,6 +135,9 @@ async function rawRequest(config, path, options) {
|
|
|
122
135
|
}, { cause });
|
|
123
136
|
}
|
|
124
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Reads bounded diagnostics and decodes a failed HTTP response.
|
|
140
|
+
*/
|
|
125
141
|
async function errorFromResponse(response, signal) {
|
|
126
142
|
const read = await readResponseBody(response, true);
|
|
127
143
|
if (read.readFailed && isRequestAborted(read.cause, signal)) {
|
|
@@ -133,6 +149,12 @@ async function errorFromResponse(response, signal) {
|
|
|
133
149
|
}
|
|
134
150
|
return parseErrorEnvelope(read.diagnosticBody, response.status, headers);
|
|
135
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Checks whether the signal aborted or the cause names an AbortError.
|
|
154
|
+
* @param cause - Original failure to retain.
|
|
155
|
+
* @param signal - Signal that cancels the operation.
|
|
156
|
+
* @returns Whether the request signal or cause indicates cancellation.
|
|
157
|
+
*/
|
|
136
158
|
export function isRequestAborted(cause, signal) {
|
|
137
159
|
return (signal?.aborted === true ||
|
|
138
160
|
(cause !== null &&
|
|
@@ -140,6 +162,11 @@ export function isRequestAborted(cause, signal) {
|
|
|
140
162
|
"name" in cause &&
|
|
141
163
|
cause.name === "AbortError"));
|
|
142
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* Wraps an abort cause as a request_aborted SDK error.
|
|
167
|
+
* @param cause - Original failure to retain.
|
|
168
|
+
* @returns A request_aborted error retaining the cause.
|
|
169
|
+
*/
|
|
143
170
|
export function requestAbortedError(cause) {
|
|
144
171
|
return new BlazingAgentsError({
|
|
145
172
|
code: "request_aborted",
|
|
@@ -215,6 +242,9 @@ async function readResponseBody(response, stopAtDiagnosticLimit) {
|
|
|
215
242
|
byteLength += chunk.byteLength;
|
|
216
243
|
}
|
|
217
244
|
}
|
|
245
|
+
/**
|
|
246
|
+
* Cancels an oversized error body and retains its bounded diagnostic prefix.
|
|
247
|
+
*/
|
|
218
248
|
async function cancelTruncatedBody(reader, chunks, byteLength) {
|
|
219
249
|
const diagnosticBody = decodeDiagnosticChunks(chunks, byteLength, true).body;
|
|
220
250
|
try {
|
|
@@ -236,6 +266,9 @@ async function cancelTruncatedBody(reader, chunks, byteLength) {
|
|
|
236
266
|
};
|
|
237
267
|
}
|
|
238
268
|
}
|
|
269
|
+
/**
|
|
270
|
+
* Decodes diagnostics without exceeding the UTF-8 byte limit.
|
|
271
|
+
*/
|
|
239
272
|
function decodeDiagnosticChunks(chunks, byteLength, sourceTruncated) {
|
|
240
273
|
const body = decodeChunks(chunks, byteLength, sourceTruncated);
|
|
241
274
|
const encoded = new TextEncoder().encode(body);
|
|
@@ -247,6 +280,9 @@ function decodeDiagnosticChunks(chunks, byteLength, sourceTruncated) {
|
|
|
247
280
|
truncated: true,
|
|
248
281
|
};
|
|
249
282
|
}
|
|
283
|
+
/**
|
|
284
|
+
* Joins retained bytes and omits an incomplete trailing character when truncated.
|
|
285
|
+
*/
|
|
250
286
|
function decodeChunks(chunks, byteLength, truncated) {
|
|
251
287
|
const bytes = new Uint8Array(byteLength);
|
|
252
288
|
let offset = 0;
|
|
@@ -264,6 +300,10 @@ function decodeChunks(chunks, byteLength, truncated) {
|
|
|
264
300
|
* Decodes a response body with the tolerant consumer schema. Unknown future
|
|
265
301
|
* codes and fields remain valid; malformed responses never infer a domain
|
|
266
302
|
* code from HTTP status.
|
|
303
|
+
* @param bodyText - Response body as text.
|
|
304
|
+
* @param status - HTTP response status.
|
|
305
|
+
* @param headers - Response headers to preserve or inspect.
|
|
306
|
+
* @returns The server error, or invalid_response when the envelope is malformed.
|
|
267
307
|
*/
|
|
268
308
|
export function parseErrorEnvelope(bodyText, status, headers = new Headers()) {
|
|
269
309
|
let parsed;
|
|
@@ -292,6 +332,9 @@ export function parseErrorEnvelope(bodyText, status, headers = new Headers()) {
|
|
|
292
332
|
}
|
|
293
333
|
return invalidResponseError(headers, status, bodyText, false);
|
|
294
334
|
}
|
|
335
|
+
/**
|
|
336
|
+
* Builds an invalid_response error with bounded diagnostics and request correlation.
|
|
337
|
+
*/
|
|
295
338
|
function invalidResponseError(headers, status, responseBody, responseBodyTruncated, cause) {
|
|
296
339
|
return new BlazingAgentsError({
|
|
297
340
|
code: "invalid_response",
|
package/dist/index.d.ts
CHANGED
|
@@ -15,14 +15,14 @@ export type { CreateMcpConnectionBody, McpAttachmentResponse, McpAttachmentsResp
|
|
|
15
15
|
export type { CreateMerchantConnectionBody, MerchantBindingResponse, MerchantBindingsResponse, MerchantConnection, MerchantConnectionResponse, MerchantCustomerBinding, MerchantGuard, MerchantProviderKind, MerchantUsageEvent, MerchantUsageEventResponse, MerchantUsageEventStatus, MerchantUsageEventsResponse, MerchantUsageSummary, MerchantUsageSummaryResponse, UpdateMerchantConnectionBody, UpsertMerchantBindingBody, } from "./contracts/entities/merchant.ts";
|
|
16
16
|
export type { CreatePromptBody, PromptResponse, PromptsListQuery, PromptsResponse, UpdatePromptBody, } from "./contracts/entities/prompts.ts";
|
|
17
17
|
export type { CreateProviderBody, ProviderListItem, ProviderModel, ProviderModelsResponse, ProviderResponse, ProvidersResponse, ProviderType, ThinkingLevelsResponse, UpdateProviderBody, } from "./contracts/entities/providers.ts";
|
|
18
|
-
export type {
|
|
19
|
-
export type { SessionResponse,
|
|
18
|
+
export type { ChatSteerConsumedEvent, SessionActivity, SessionInput, SessionInputResponse, SessionInputState, SessionInputsQuery, SessionInputsResponse, StopSessionBody, StopSessionResponse, SubmitSessionInputBody, } from "./contracts/entities/session-inputs.ts";
|
|
19
|
+
export type { ContinueToolApprovalsBody, SessionForkedFrom, SessionResponse, ToolApprovalDecision, ToolApprovalState, ToolApprovalsResponse, } from "./contracts/entities/sessions.ts";
|
|
20
20
|
export { sessionResponseSchema } from "./contracts/entities/sessions.ts";
|
|
21
21
|
export type { CreateSkillBody, Skill, SkillArchiveType, SkillCopyResult, SkillCopyResults, SkillDetail, SkillFile, SkillsListResponse, } from "./contracts/entities/skills.ts";
|
|
22
22
|
export type { SessionUsageQuery, SessionUsageResponse, UsageBucket, UsageOverviewQuery, UsageOverviewResponse, UsageTotals, } from "./contracts/entities/usage.ts";
|
|
23
|
-
export type { CreateWorkspaceBody, UpdateWorkspaceBody, Workspace, WorkspaceNetworkPolicy, WorkspacesListResponse, } from "./contracts/entities/workspaces.ts";
|
|
23
|
+
export type { CreateWorkspaceBody, UpdateWorkspaceBody, Workspace, WorkspaceNetworkPolicy, WorkspacesListResponse, WorkspaceTier, } from "./contracts/entities/workspaces.ts";
|
|
24
24
|
export { BlazingAgentsDirectChatTransport, type BlazingAgentsDirectChatTransportOptions, } from "./direct-chat-transport.ts";
|
|
25
25
|
export { BlazingAgentsError } from "./errors.ts";
|
|
26
26
|
export { type ChatFunction, type ChatFunctionContext, type ChatFunctions, defineFunction, } from "./functions.ts";
|
|
27
27
|
export { createChatRelay, createCompletionRelay, type RelayContext, type SessionOwnershipStore, } from "./relay.ts";
|
|
28
|
-
export type { AgentClient, AgentSkillsResource, AgentsListOptions, AgentsResource, ArtifactsResource, AttributionInput, BlazingAgentsErrorCode, BlazingAgentsOptions, BlazingAgentsRequestOptions, BlazingAgentsUIMessage, BlazingAgentsUIMessageChunk, ChatConnectionsResource, ChatDeliveriesListOptions, ChatDeliveriesResource, ChatInput, ChatMessageInput, ChatPromptInput, ChatResult, ChatTrigger, CompletionInput, CompletionPromptIdInput, CompletionPromptInput, CompletionResult, KnownBlazingAgentsErrorCode, LatestSessionsListOptions, McpConnectionsResource, MemoriesListOptions, MemoriesResource, MerchantBindingsListOptions, MerchantBindingsResource, MerchantConnectionResource, MerchantUsageEventsListOptions, MerchantUsageEventsResource, ObjectInput, ObjectPromptIdInput, ObjectPromptInput, ObjectResult, PromptsResource, ProvidersResource, ResourceRequestOptions, ResponseObservation,
|
|
28
|
+
export type { AgentClient, AgentSkillsResource, AgentsListOptions, AgentsResource, ArtifactsResource, AttributionInput, BlazingAgentsErrorCode, BlazingAgentsOptions, BlazingAgentsRequestOptions, BlazingAgentsUIMessage, BlazingAgentsUIMessageChunk, ChatConnectionsResource, ChatDeliveriesListOptions, ChatDeliveriesResource, ChatInput, ChatMessageInput, ChatMessagesInput, ChatPromptInput, ChatResult, ChatTrigger, CompletionInput, CompletionPromptIdInput, CompletionPromptInput, CompletionResult, ContinueChatInput, KnownBlazingAgentsErrorCode, LatestSessionsListOptions, McpConnectionsResource, MemoriesListOptions, MemoriesResource, MerchantBindingsListOptions, MerchantBindingsResource, MerchantConnectionResource, MerchantUsageEventsListOptions, MerchantUsageEventsResource, ObjectInput, ObjectPromptIdInput, ObjectPromptInput, ObjectResult, PromptsResource, ProvidersResource, ResourceRequestOptions, ResponseObservation, SessionsResource, SkillsListOptions, TasksResource, TenantResource, TerminalStreamResult, UsageResource, UserClient, WorkspacesListOptions, WorkspacesResource, } from "./types.ts";
|
package/dist/relay.d.ts
CHANGED
|
@@ -2,25 +2,48 @@ import type { BlazingAgents } from "./client.ts";
|
|
|
2
2
|
import type { ChatFunctions } from "./functions.ts";
|
|
3
3
|
export interface RelayContext {
|
|
4
4
|
agentId: string;
|
|
5
|
-
/** Handlers for this authenticated request
|
|
5
|
+
/** Handlers for this authenticated request and its approved continuation. */
|
|
6
6
|
functions?: ChatFunctions;
|
|
7
7
|
metadata?: Record<string, unknown>;
|
|
8
8
|
userId: string;
|
|
9
9
|
}
|
|
10
10
|
export interface SessionOwnershipStore {
|
|
11
|
+
/**
|
|
12
|
+
* Looks up the end user who owns the Session.
|
|
13
|
+
* @param sessionId - Session to look up or record.
|
|
14
|
+
* @returns The owner ID, or undefined when no owner is recorded.
|
|
15
|
+
*/
|
|
11
16
|
ownerOf(sessionId: string): Promise<string | undefined>;
|
|
17
|
+
/**
|
|
18
|
+
* Records ownership of a newly created Session.
|
|
19
|
+
* @param sessionId - Session to look up or record.
|
|
20
|
+
* @param userId - End-user ID for request scope.
|
|
21
|
+
* @returns Resolves after ownership is stored.
|
|
22
|
+
*/
|
|
12
23
|
recordOwner(sessionId: string, userId: string): Promise<void>;
|
|
13
24
|
}
|
|
14
25
|
interface RelayOptions<Method extends keyof BlazingAgents> {
|
|
15
26
|
client: Pick<BlazingAgents, Method>;
|
|
27
|
+
/**
|
|
28
|
+
* Resolves authenticated Agent and end-user context, or null for an unauthenticated request.
|
|
29
|
+
* @param request - Incoming HTTP request.
|
|
30
|
+
* @returns Authenticated context, or null when authentication fails.
|
|
31
|
+
*/
|
|
16
32
|
resolveContext(request: Request): Promise<RelayContext | null>;
|
|
17
33
|
}
|
|
18
34
|
/**
|
|
19
35
|
* Relays useChat submissions. An assistant message carrying approval
|
|
20
|
-
* responses
|
|
36
|
+
* responses submits the complete round and streams the continuation.
|
|
37
|
+
* @param options - Configuration for this operation.
|
|
38
|
+
* @returns An HTTP handler that checks Session ownership before resuming.
|
|
21
39
|
*/
|
|
22
|
-
export declare function createChatRelay(options: RelayOptions<"chat" | "
|
|
40
|
+
export declare function createChatRelay(options: RelayOptions<"chat" | "continueChat"> & {
|
|
23
41
|
sessions: SessionOwnershipStore;
|
|
24
42
|
}): (request: Request) => Promise<Response>;
|
|
43
|
+
/**
|
|
44
|
+
* Creates an authenticated HTTP handler that validates prompts and relays text generation.
|
|
45
|
+
* @param options - Configuration for this operation.
|
|
46
|
+
* @returns An HTTP handler that validates prompts and relays text generation.
|
|
47
|
+
*/
|
|
25
48
|
export declare function createCompletionRelay(options: RelayOptions<"completion">): (request: Request) => Promise<Response>;
|
|
26
49
|
export {};
|
package/dist/relay.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { safeValidateUIMessages } from "ai";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import {
|
|
3
|
+
import { extractApprovalDecisions } from "./approvals.js";
|
|
4
4
|
import { sessionIdSchema } from "./contracts/ids.js";
|
|
5
5
|
import { BlazingAgentsError } from "./errors.js";
|
|
6
6
|
const chatBodySchema = z.object({
|
|
@@ -14,7 +14,9 @@ const chatBodySchema = z.object({
|
|
|
14
14
|
const completionBodySchema = z.object({ prompt: z.string().trim().min(1) });
|
|
15
15
|
/**
|
|
16
16
|
* Relays useChat submissions. An assistant message carrying approval
|
|
17
|
-
* responses
|
|
17
|
+
* responses submits the complete round and streams the continuation.
|
|
18
|
+
* @param options - Configuration for this operation.
|
|
19
|
+
* @returns An HTTP handler that checks Session ownership before resuming.
|
|
18
20
|
*/
|
|
19
21
|
export function createChatRelay(options) {
|
|
20
22
|
return async (request) => {
|
|
@@ -44,6 +46,9 @@ export function createChatRelay(options) {
|
|
|
44
46
|
sessionId: body.sessionId,
|
|
45
47
|
});
|
|
46
48
|
}
|
|
49
|
+
if (message.role !== "user") {
|
|
50
|
+
return errorResponse(400, "invalid_request", "Chat submission requires a user message.");
|
|
51
|
+
}
|
|
47
52
|
const chatInput = {
|
|
48
53
|
agentId: context.agentId,
|
|
49
54
|
functions: context.functions,
|
|
@@ -83,6 +88,9 @@ export function createChatRelay(options) {
|
|
|
83
88
|
}
|
|
84
89
|
};
|
|
85
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Validates the Session and forwards the last assistant approval round.
|
|
93
|
+
*/
|
|
86
94
|
async function relayApprovalResponses(client, { functions, message, request, ...input }) {
|
|
87
95
|
if (input.sessionId === undefined) {
|
|
88
96
|
return errorResponse(400, "invalid_request", "Tool approval requires an existing Session.");
|
|
@@ -92,21 +100,22 @@ async function relayApprovalResponses(client, { functions, message, request, ...
|
|
|
92
100
|
sessionId: input.sessionId,
|
|
93
101
|
abortSignal: request.signal,
|
|
94
102
|
};
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
message,
|
|
98
|
-
});
|
|
99
|
-
if (continuationId === undefined) {
|
|
103
|
+
const decisions = extractApprovalDecisions(message);
|
|
104
|
+
if (decisions.length === 0) {
|
|
100
105
|
return errorResponse(400, "invalid_request", "The message has no tool approval responses.");
|
|
101
106
|
}
|
|
102
|
-
|
|
103
|
-
const continuation = await client.resumeChat({
|
|
107
|
+
const continuation = await client.continueChat({
|
|
104
108
|
...target,
|
|
105
|
-
|
|
109
|
+
decisions,
|
|
106
110
|
functions: functions ?? {},
|
|
107
111
|
});
|
|
108
112
|
return continuation.toResponse();
|
|
109
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Creates an authenticated HTTP handler that validates prompts and relays text generation.
|
|
116
|
+
* @param options - Configuration for this operation.
|
|
117
|
+
* @returns An HTTP handler that validates prompts and relays text generation.
|
|
118
|
+
*/
|
|
110
119
|
export function createCompletionRelay(options) {
|
|
111
120
|
return async (request) => {
|
|
112
121
|
try {
|
|
@@ -129,6 +138,9 @@ export function createCompletionRelay(options) {
|
|
|
129
138
|
}
|
|
130
139
|
};
|
|
131
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* Maps validation and SDK failures to safe public error responses.
|
|
143
|
+
*/
|
|
132
144
|
function safeErrorResponse(error) {
|
|
133
145
|
if (error instanceof z.ZodError || error instanceof SyntaxError) {
|
|
134
146
|
return errorResponse(400, "invalid_request", "Invalid request body.");
|
|
@@ -144,6 +156,9 @@ function safeErrorResponse(error) {
|
|
|
144
156
|
}
|
|
145
157
|
return errorResponse(500, "internal_error", "Request failed.");
|
|
146
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Builds a JSON error envelope with the selected HTTP status.
|
|
161
|
+
*/
|
|
147
162
|
function errorResponse(status, code, message, headers) {
|
|
148
163
|
const responseHeaders = new Headers(headers);
|
|
149
164
|
responseHeaders.set("content-type", "application/json");
|
|
@@ -1,2 +1,7 @@
|
|
|
1
1
|
import type { AgentsResource, HttpConfig } from "../types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Builds the Agents operations using the shared HTTP configuration.
|
|
4
|
+
* @param config - Shared authentication and transport configuration.
|
|
5
|
+
* @returns The configured resource client.
|
|
6
|
+
*/
|
|
2
7
|
export declare function createAgentsResource(config: HttpConfig): AgentsResource;
|