@blazingagents/sdk 0.20.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/dist/approvals.d.ts +4 -0
- package/dist/approvals.js +4 -0
- package/dist/chat-transport.d.ts +18 -1
- package/dist/chat-transport.js +16 -0
- package/dist/client.d.ts +24 -1
- package/dist/client.js +33 -1
- package/dist/contracts/api.d.ts +34 -0
- package/dist/contracts/api.js +28 -0
- 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 +3 -0
- package/dist/contracts/entities/chat.js +6 -0
- 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.js +3 -1
- package/dist/contracts/entities/sessions.d.ts +11 -0
- package/dist/contracts/entities/sessions.js +11 -1
- 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 +4 -3
- package/dist/contracts/index.js +2 -2
- package/dist/contracts/utils.d.ts +10 -0
- package/dist/contracts/utils.js +10 -0
- package/dist/direct-chat-transport.d.ts +27 -1
- package/dist/direct-chat-transport.js +26 -0
- 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 +32 -0
- package/dist/generation.js +83 -0
- package/dist/http.d.ts +26 -0
- package/dist/http.js +43 -0
- package/dist/index.d.ts +2 -2
- package/dist/relay.d.ts +23 -0
- package/dist/relay.js +16 -0
- 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 +40 -0
- 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 +679 -10
- package/package.json +1 -1
package/dist/functions.d.ts
CHANGED
|
@@ -9,12 +9,28 @@ export interface ChatFunctionContext {
|
|
|
9
9
|
}
|
|
10
10
|
export interface ChatFunction<Schema extends z.ZodType = z.ZodType, Output = unknown> {
|
|
11
11
|
description: string;
|
|
12
|
+
/**
|
|
13
|
+
* Runs a caller-local function with validated input and deadline cancellation.
|
|
14
|
+
* @param input - Input parsed by inputSchema.
|
|
15
|
+
* @param context - Function-call idempotency key and cancellation signal.
|
|
16
|
+
* @returns The function output, synchronously or as a promise.
|
|
17
|
+
*/
|
|
12
18
|
execute(input: z.output<Schema>, context: ChatFunctionContext): Output | Promise<Output>;
|
|
13
19
|
inputSchema: Schema;
|
|
14
20
|
}
|
|
15
21
|
export type ChatFunctions = Record<string, ChatFunction>;
|
|
16
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Declares a caller-local function whose handler input is inferred from its Zod schema.
|
|
24
|
+
* @param definition - Description, input schema, and local handler.
|
|
25
|
+
* @returns The unchanged definition with inferred handler types.
|
|
26
|
+
*/
|
|
17
27
|
export declare function defineFunction<Schema extends z.ZodType, Output>(definition: ChatFunction<Schema, Output>): ChatFunction<Schema, Output>;
|
|
28
|
+
/**
|
|
29
|
+
* Converts caller-local Zod input schemas to validated JSON Schema definitions.
|
|
30
|
+
* @param functions - Caller-local function handlers keyed by name.
|
|
31
|
+
* @returns Validated function descriptions and JSON input schemas.
|
|
32
|
+
* @throws BlazingAgentsError - If a definition cannot be represented as a valid JSON Schema.
|
|
33
|
+
*/
|
|
18
34
|
export declare function toChatFunctionDefinitions(functions: ChatFunctions): ChatFunctionDefinitions;
|
|
19
35
|
export interface FunctionDispatchTarget {
|
|
20
36
|
abortSignal?: AbortSignal;
|
|
@@ -23,16 +39,33 @@ export interface FunctionDispatchTarget {
|
|
|
23
39
|
sessionId: string;
|
|
24
40
|
}
|
|
25
41
|
interface FunctionEventHandlers {
|
|
42
|
+
/**
|
|
43
|
+
* Dispatches a function call without blocking the stream reader.
|
|
44
|
+
* @param call - Private function-call event payload.
|
|
45
|
+
* @param fail - Reports a dispatch failure to the stream reader.
|
|
46
|
+
*/
|
|
26
47
|
onCall?(call: ChatFunctionCallEvent["data"], fail: (error: unknown) => void): void;
|
|
48
|
+
/**
|
|
49
|
+
* Handles consumer cancellation.
|
|
50
|
+
*/
|
|
27
51
|
onCancel?(): void;
|
|
52
|
+
/**
|
|
53
|
+
* Stops function handlers when the upstream stream ends.
|
|
54
|
+
*/
|
|
28
55
|
onEnd?(): void;
|
|
29
56
|
}
|
|
30
57
|
/**
|
|
31
58
|
* Reads native SSE eagerly and returns it without private function events,
|
|
32
59
|
* so slow consumers never delay a call. A recognized but malformed event
|
|
33
60
|
* fails the stream.
|
|
61
|
+
* @param body - Upstream SSE byte stream.
|
|
34
62
|
*/
|
|
35
63
|
export declare function stripFunctionEvents(body: ReadableStream<Uint8Array>, { onCall, onCancel, onEnd }?: FunctionEventHandlers): ReadableStream<Uint8Array>;
|
|
36
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* Strips private function events and executes claimed calls without blocking the read loop.
|
|
66
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
67
|
+
* @param target - Agent, Session, local handlers, and caller cancellation signal.
|
|
68
|
+
* @param body - Upstream SSE byte stream.
|
|
69
|
+
*/
|
|
37
70
|
export declare function dispatchChatFunctions(config: HttpConfig, target: FunctionDispatchTarget, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
|
|
38
71
|
export {};
|
package/dist/functions.js
CHANGED
|
@@ -2,10 +2,20 @@ import { z } from "zod";
|
|
|
2
2
|
import { chatFunctionCallEventSchema, chatFunctionDefinitionsSchema, chatFunctionOutcomeSchema, claimChatFunctionResponseSchema, resolveChatFunctionResponseSchema, } from "./contracts/entities/chat.js";
|
|
3
3
|
import { BlazingAgentsError } from "./errors.js";
|
|
4
4
|
import { requestJson } from "./http.js";
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Declares a caller-local function whose handler input is inferred from its Zod schema.
|
|
7
|
+
* @param definition - Description, input schema, and local handler.
|
|
8
|
+
* @returns The unchanged definition with inferred handler types.
|
|
9
|
+
*/
|
|
6
10
|
export function defineFunction(definition) {
|
|
7
11
|
return definition;
|
|
8
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* Converts caller-local Zod input schemas to validated JSON Schema definitions.
|
|
15
|
+
* @param functions - Caller-local function handlers keyed by name.
|
|
16
|
+
* @returns Validated function descriptions and JSON input schemas.
|
|
17
|
+
* @throws BlazingAgentsError - If a definition cannot be represented as a valid JSON Schema.
|
|
18
|
+
*/
|
|
9
19
|
export function toChatFunctionDefinitions(functions) {
|
|
10
20
|
try {
|
|
11
21
|
return chatFunctionDefinitionsSchema.parse(Object.fromEntries(Object.entries(functions).map(([name, fn]) => {
|
|
@@ -54,6 +64,9 @@ function functionCallFrom(block) {
|
|
|
54
64
|
}
|
|
55
65
|
return chatFunctionCallEventSchema.safeParse(parsed).data ?? null;
|
|
56
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Reads Retry-After as seconds or an HTTP date and clamps past dates to zero.
|
|
69
|
+
*/
|
|
57
70
|
function retryAfterMs(headers) {
|
|
58
71
|
const value = headers?.get("retry-after");
|
|
59
72
|
if (!value) {
|
|
@@ -64,6 +77,9 @@ function retryAfterMs(headers) {
|
|
|
64
77
|
: Date.parse(value) - Date.now();
|
|
65
78
|
return Number.isNaN(ms) ? undefined : Math.max(0, ms);
|
|
66
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Returns the retry delay for transient transport or HTTP failures.
|
|
82
|
+
*/
|
|
67
83
|
function retryDelayMs({ code, headers, status }, attempt) {
|
|
68
84
|
const retryable = status === undefined
|
|
69
85
|
? code === "network_error"
|
|
@@ -74,6 +90,9 @@ function retryDelayMs({ code, headers, status }, attempt) {
|
|
|
74
90
|
return (retryAfterMs(headers) ??
|
|
75
91
|
Math.min(RETRY_BASE_MS * 2 ** (attempt - 1), RETRY_MAX_MS));
|
|
76
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* Waits for the delay or resolves early when the signal aborts.
|
|
95
|
+
*/
|
|
77
96
|
function sleep(ms, signal) {
|
|
78
97
|
return new Promise((resolve) => {
|
|
79
98
|
const timer = setTimeout(resolve, ms);
|
|
@@ -111,7 +130,9 @@ async function postWithRetry(config, path, json, schema, until, signal) {
|
|
|
111
130
|
}
|
|
112
131
|
}
|
|
113
132
|
}
|
|
114
|
-
/**
|
|
133
|
+
/**
|
|
134
|
+
* Classifies a failed attempt as a lost race, an exhausted budget, or the delay before retrying; permanent failures rethrow.
|
|
135
|
+
*/
|
|
115
136
|
function afterFailure(caught, attempt, until, signal) {
|
|
116
137
|
const error = BlazingAgentsError.isInstance(caught) ? caught : undefined;
|
|
117
138
|
if (error?.status === 409) {
|
|
@@ -130,7 +151,9 @@ const invalidResult = {
|
|
|
130
151
|
kind: "error",
|
|
131
152
|
message: "Function returned an invalid result.",
|
|
132
153
|
};
|
|
133
|
-
/**
|
|
154
|
+
/**
|
|
155
|
+
* Resolves `undefined` when the call became late or aborted before customer code could start.
|
|
156
|
+
*/
|
|
134
157
|
async function execute(functions, { id, name, input }, deadline, signal) {
|
|
135
158
|
const fn = Object.hasOwn(functions, name) ? functions[name] : undefined;
|
|
136
159
|
if (fn === undefined) {
|
|
@@ -175,6 +198,7 @@ async function execute(functions, { id, name, input }, deadline, signal) {
|
|
|
175
198
|
* Reads native SSE eagerly and returns it without private function events,
|
|
176
199
|
* so slow consumers never delay a call. A recognized but malformed event
|
|
177
200
|
* fails the stream.
|
|
201
|
+
* @param body - Upstream SSE byte stream.
|
|
178
202
|
*/
|
|
179
203
|
export function stripFunctionEvents(body, { onCall, onCancel, onEnd } = {}) {
|
|
180
204
|
const reader = body.getReader();
|
|
@@ -182,6 +206,9 @@ export function stripFunctionEvents(body, { onCall, onCancel, onEnd } = {}) {
|
|
|
182
206
|
const encoder = new TextEncoder();
|
|
183
207
|
let output;
|
|
184
208
|
let finished = false;
|
|
209
|
+
/**
|
|
210
|
+
* Fails the output stream once and cancels its upstream reader.
|
|
211
|
+
*/
|
|
185
212
|
const fail = (error) => {
|
|
186
213
|
if (finished) {
|
|
187
214
|
return;
|
|
@@ -190,6 +217,9 @@ export function stripFunctionEvents(body, { onCall, onCancel, onEnd } = {}) {
|
|
|
190
217
|
output.error(error);
|
|
191
218
|
reader.cancel(error).catch(() => undefined);
|
|
192
219
|
};
|
|
220
|
+
/**
|
|
221
|
+
* Forwards public SSE blocks and dispatches or rejects private function events.
|
|
222
|
+
*/
|
|
193
223
|
const handleBlock = (block, raw) => {
|
|
194
224
|
const call = functionCallFrom(block);
|
|
195
225
|
if (call === undefined) {
|
|
@@ -207,6 +237,9 @@ export function stripFunctionEvents(body, { onCall, onCancel, onEnd } = {}) {
|
|
|
207
237
|
onCall?.(call.data, fail);
|
|
208
238
|
}
|
|
209
239
|
};
|
|
240
|
+
/**
|
|
241
|
+
* Reads SSE bytes eagerly and splits complete event blocks for dispatch.
|
|
242
|
+
*/
|
|
210
243
|
const pump = async () => {
|
|
211
244
|
let buffer = "";
|
|
212
245
|
try {
|
|
@@ -236,10 +269,16 @@ export function stripFunctionEvents(body, { onCall, onCancel, onEnd } = {}) {
|
|
|
236
269
|
}
|
|
237
270
|
};
|
|
238
271
|
return new ReadableStream({
|
|
272
|
+
/**
|
|
273
|
+
* Initializes the stream controller.
|
|
274
|
+
*/
|
|
239
275
|
start(controller) {
|
|
240
276
|
output = controller;
|
|
241
277
|
pump();
|
|
242
278
|
},
|
|
279
|
+
/**
|
|
280
|
+
* Cancels the upstream reader with the consumer reason.
|
|
281
|
+
*/
|
|
243
282
|
async cancel(reason) {
|
|
244
283
|
finished = true;
|
|
245
284
|
onCancel?.();
|
|
@@ -247,12 +286,20 @@ export function stripFunctionEvents(body, { onCall, onCancel, onEnd } = {}) {
|
|
|
247
286
|
},
|
|
248
287
|
});
|
|
249
288
|
}
|
|
250
|
-
/**
|
|
289
|
+
/**
|
|
290
|
+
* Strips private function events and executes claimed calls without blocking the read loop.
|
|
291
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
292
|
+
* @param target - Agent, Session, local handlers, and caller cancellation signal.
|
|
293
|
+
* @param body - Upstream SSE byte stream.
|
|
294
|
+
*/
|
|
251
295
|
export function dispatchChatFunctions(config, target, body) {
|
|
252
296
|
/** Caller abort or consumer cancellation: stops every retry. */
|
|
253
297
|
const stop = new AbortController();
|
|
254
298
|
/** Also aborted when the stream ends: stops claims and handlers. */
|
|
255
299
|
const handlers = new AbortController();
|
|
300
|
+
/**
|
|
301
|
+
* Aborts pending function claims and retries.
|
|
302
|
+
*/
|
|
256
303
|
const abort = () => stop.abort();
|
|
257
304
|
stop.signal.addEventListener("abort", () => handlers.abort(), {
|
|
258
305
|
once: true,
|
|
@@ -262,6 +309,9 @@ export function dispatchChatFunctions(config, target, body) {
|
|
|
262
309
|
abort();
|
|
263
310
|
}
|
|
264
311
|
const dispatched = new Set();
|
|
312
|
+
/**
|
|
313
|
+
* Claims a function call, runs its handler, and posts the result within its retry budget.
|
|
314
|
+
*/
|
|
265
315
|
const runCall = async (call) => {
|
|
266
316
|
const path = `/v1/agents/${target.agentId}/sessions/${target.sessionId}/function-calls/${call.id}`;
|
|
267
317
|
const claimRequestId = crypto.randomUUID();
|
|
@@ -284,6 +334,9 @@ export function dispatchChatFunctions(config, target, body) {
|
|
|
284
334
|
await postWithRetry(config, `${path}/result`, { claimRequestId, outcome }, resolveChatFunctionResponseSchema, deadline + RESULT_RETRY_GRACE_MS, stop.signal);
|
|
285
335
|
};
|
|
286
336
|
return stripFunctionEvents(body, {
|
|
337
|
+
/**
|
|
338
|
+
* Dispatches a function call without blocking the stream reader.
|
|
339
|
+
*/
|
|
287
340
|
onCall(call, fail) {
|
|
288
341
|
if (!dispatched.has(call.id)) {
|
|
289
342
|
dispatched.add(call.id);
|
|
@@ -291,6 +344,9 @@ export function dispatchChatFunctions(config, target, body) {
|
|
|
291
344
|
}
|
|
292
345
|
},
|
|
293
346
|
onCancel: abort,
|
|
347
|
+
/**
|
|
348
|
+
* Stops function handlers when the upstream stream ends.
|
|
349
|
+
*/
|
|
294
350
|
onEnd() {
|
|
295
351
|
handlers.abort();
|
|
296
352
|
target.abortSignal?.removeEventListener("abort", abort);
|
package/dist/generation.d.ts
CHANGED
|
@@ -1,11 +1,43 @@
|
|
|
1
1
|
import type { ChatInput, ChatResult, CompletionInput, CompletionResult, ContinueChatInput, HttpConfig, ObjectInput, ObjectResult, TerminalStreamResult } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Creates or resumes a Session and returns its SSE stream and Session ID.
|
|
4
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
5
|
+
* @param input - Agent, message or stored Prompt, and optional existing Session.
|
|
6
|
+
* @returns The Session ID promise and single-owner SSE accessors.
|
|
7
|
+
*/
|
|
2
8
|
export declare function chat(config: HttpConfig, input: ChatInput): Promise<ChatResult>;
|
|
9
|
+
/**
|
|
10
|
+
* Submits a complete Tool approval round and streams its continuation.
|
|
11
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
12
|
+
* @param input - Agent, Session, and decisions for the complete approval round.
|
|
13
|
+
* @returns The Session ID promise and continuation SSE accessors.
|
|
14
|
+
*/
|
|
3
15
|
export declare function continueChat(config: HttpConfig, input: ContinueChatInput): Promise<ChatResult>;
|
|
4
16
|
/**
|
|
5
17
|
* Keeps status and headers while filtering the SSE body. Missing or locked
|
|
6
18
|
* bodies pass through so the stream result reports them as `stream_error`.
|
|
19
|
+
* @param response - Upstream HTTP response.
|
|
20
|
+
* @param filter - Transforms upstream SSE bytes before exposing them to the caller.
|
|
7
21
|
*/
|
|
8
22
|
export declare function withFilteredBody(response: Response, filter: (body: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>): Response;
|
|
23
|
+
/**
|
|
24
|
+
* Creates single-owner SSE response and byte-stream accessors.
|
|
25
|
+
* @param response - Upstream HTTP response.
|
|
26
|
+
* @param resourceName - Resource label used in stream errors.
|
|
27
|
+
* @param filter - Transforms upstream SSE bytes before exposing them to the caller.
|
|
28
|
+
*/
|
|
9
29
|
export declare function buildTerminalStreamResult(response: Response, resourceName: string, filter?: (body: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>): TerminalStreamResult;
|
|
30
|
+
/**
|
|
31
|
+
* Starts stateless text generation with independent final, incremental, and response outputs.
|
|
32
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
33
|
+
* @param input - Agent and literal prompt or stored Prompt reference.
|
|
34
|
+
* @returns Independent text stream, final text promise, and response relay.
|
|
35
|
+
*/
|
|
10
36
|
export declare function completion(config: HttpConfig, input: CompletionInput): Promise<CompletionResult>;
|
|
37
|
+
/**
|
|
38
|
+
* Starts stateless JSON generation with partial objects and a final parsed value.
|
|
39
|
+
* @param config - Authentication, base URL, and transport configuration.
|
|
40
|
+
* @param input - Agent, prompt source, and JSON output schema.
|
|
41
|
+
* @returns Partial JSON objects, a final JSON promise, and a text response relay.
|
|
42
|
+
*/
|
|
11
43
|
export declare function objectGeneration(config: HttpConfig, input: ObjectInput): Promise<ObjectResult>;
|
package/dist/generation.js
CHANGED
|
@@ -3,6 +3,12 @@ import { sessionIdSchema } from "./contracts/ids.js";
|
|
|
3
3
|
import { BlazingAgentsError } from "./errors.js";
|
|
4
4
|
import { dispatchChatFunctions, toChatFunctionDefinitions, } from "./functions.js";
|
|
5
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
|
+
*/
|
|
6
12
|
export async function chat(config, input) {
|
|
7
13
|
const body = buildChatBody(input);
|
|
8
14
|
if (input.functions && Object.keys(input.functions).length > 0) {
|
|
@@ -29,6 +35,12 @@ export async function chat(config, input) {
|
|
|
29
35
|
abortSignal: input.abortSignal,
|
|
30
36
|
});
|
|
31
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
|
+
*/
|
|
32
44
|
export async function continueChat(config, input) {
|
|
33
45
|
const response = await requestStream(config, `/v1/agents/${input.agentId}/sessions/${input.sessionId}/tool-approvals/continue`, {
|
|
34
46
|
json: {
|
|
@@ -50,6 +62,8 @@ export async function continueChat(config, input) {
|
|
|
50
62
|
/**
|
|
51
63
|
* Keeps status and headers while filtering the SSE body. Missing or locked
|
|
52
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.
|
|
53
67
|
*/
|
|
54
68
|
export function withFilteredBody(response, filter) {
|
|
55
69
|
if (!response.body || response.body.locked) {
|
|
@@ -61,6 +75,9 @@ export function withFilteredBody(response, filter) {
|
|
|
61
75
|
statusText: response.statusText,
|
|
62
76
|
});
|
|
63
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Builds a chat request body from messages or a stored Prompt.
|
|
80
|
+
*/
|
|
64
81
|
function buildChatBody(input) {
|
|
65
82
|
const base = {};
|
|
66
83
|
// Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined trigger.
|
|
@@ -122,6 +139,9 @@ function sessionIdFromLocation(response, requestId) {
|
|
|
122
139
|
}
|
|
123
140
|
return parsed.data;
|
|
124
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* Combines the Session ID promise with a single-owner SSE result.
|
|
144
|
+
*/
|
|
125
145
|
function buildChatResult(config, response, resumeSessionId, dispatch) {
|
|
126
146
|
/**
|
|
127
147
|
* `sessionId` resolves from the `Location` header on create, or to the
|
|
@@ -154,10 +174,20 @@ function buildChatResult(config, response, resumeSessionId, dispatch) {
|
|
|
154
174
|
...buildTerminalStreamResult(streamResponse, "chat"),
|
|
155
175
|
};
|
|
156
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
|
+
*/
|
|
157
183
|
export function buildTerminalStreamResult(response, resourceName, filter) {
|
|
158
184
|
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
159
185
|
const location = response.headers.get("location");
|
|
160
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
|
+
*/
|
|
161
191
|
const claimBody = () => {
|
|
162
192
|
if (bodyClaimed) {
|
|
163
193
|
const message = `The ${resourceName} response body has already been claimed.`;
|
|
@@ -175,6 +205,7 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
|
|
|
175
205
|
return {
|
|
176
206
|
requestId,
|
|
177
207
|
toStream: claimBody,
|
|
208
|
+
/** Claims the response relay once. */
|
|
178
209
|
toResponse: () => {
|
|
179
210
|
const headers = replacementResponseHeaders(requestId, location);
|
|
180
211
|
headers.set("content-type", "text/event-stream");
|
|
@@ -195,6 +226,9 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
|
|
|
195
226
|
},
|
|
196
227
|
};
|
|
197
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* Preserves a matching stream error or wraps a failure with request correlation.
|
|
231
|
+
*/
|
|
198
232
|
function toStreamError(cause, requestId, fallbackMessage) {
|
|
199
233
|
if (BlazingAgentsError.isInstance(cause) &&
|
|
200
234
|
cause.code === "stream_error" &&
|
|
@@ -217,6 +251,9 @@ function toStreamError(cause, requestId, fallbackMessage) {
|
|
|
217
251
|
requestId,
|
|
218
252
|
}, { cause });
|
|
219
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Wraps reads and cancellation failures as correlated SDK stream errors.
|
|
256
|
+
*/
|
|
220
257
|
function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
221
258
|
let reader;
|
|
222
259
|
try {
|
|
@@ -226,6 +263,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
|
226
263
|
throw toStreamError(cause, requestId, fallbackMessage);
|
|
227
264
|
}
|
|
228
265
|
return new ReadableStream({
|
|
266
|
+
/**
|
|
267
|
+
* Reads one upstream chunk and normalizes stream failures.
|
|
268
|
+
*/
|
|
229
269
|
async pull(controller) {
|
|
230
270
|
try {
|
|
231
271
|
const { done, value } = await reader.read();
|
|
@@ -239,6 +279,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
|
239
279
|
controller.error(toStreamError(cause, requestId, fallbackMessage));
|
|
240
280
|
}
|
|
241
281
|
},
|
|
282
|
+
/**
|
|
283
|
+
* Cancels the upstream reader with the consumer reason.
|
|
284
|
+
*/
|
|
242
285
|
async cancel(reason) {
|
|
243
286
|
try {
|
|
244
287
|
await reader.cancel(reason);
|
|
@@ -249,6 +292,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
|
|
|
249
292
|
},
|
|
250
293
|
});
|
|
251
294
|
}
|
|
295
|
+
/**
|
|
296
|
+
* Returns the response body or a stream that fails when the body is missing.
|
|
297
|
+
*/
|
|
252
298
|
function responseBodyStream(response, requestId, resourceName) {
|
|
253
299
|
if (response.body) {
|
|
254
300
|
return response.body;
|
|
@@ -261,11 +307,17 @@ function responseBodyStream(response, requestId, resourceName) {
|
|
|
261
307
|
requestId,
|
|
262
308
|
}, { cause });
|
|
263
309
|
return new ReadableStream({
|
|
310
|
+
/**
|
|
311
|
+
* Initializes the stream controller.
|
|
312
|
+
*/
|
|
264
313
|
start(controller) {
|
|
265
314
|
controller.error(error);
|
|
266
315
|
},
|
|
267
316
|
});
|
|
268
317
|
}
|
|
318
|
+
/**
|
|
319
|
+
* Copies request correlation and Session location into relay response headers.
|
|
320
|
+
*/
|
|
269
321
|
function replacementResponseHeaders(requestId, location) {
|
|
270
322
|
const headers = new Headers();
|
|
271
323
|
if (requestId !== undefined) {
|
|
@@ -276,6 +328,9 @@ function replacementResponseHeaders(requestId, location) {
|
|
|
276
328
|
}
|
|
277
329
|
return headers;
|
|
278
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* Builds a stateless prompt request with the selected output format.
|
|
333
|
+
*/
|
|
279
334
|
function buildStatelessGenerationBody(input, output) {
|
|
280
335
|
const body = { output };
|
|
281
336
|
if ("prompt" in input) {
|
|
@@ -298,6 +353,12 @@ function buildStatelessGenerationBody(input, output) {
|
|
|
298
353
|
}
|
|
299
354
|
return body;
|
|
300
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
|
+
*/
|
|
301
362
|
export async function completion(config, input) {
|
|
302
363
|
const body = buildStatelessGenerationBody(input, { type: "text" });
|
|
303
364
|
const path = `/v1/agents/${input.agentId}/generation`;
|
|
@@ -309,6 +370,9 @@ export async function completion(config, input) {
|
|
|
309
370
|
});
|
|
310
371
|
return buildCompletionResult(response);
|
|
311
372
|
}
|
|
373
|
+
/**
|
|
374
|
+
* Splits text output into a final promise, incremental stream, and response relay.
|
|
375
|
+
*/
|
|
312
376
|
function buildCompletionResult(response) {
|
|
313
377
|
const { finalStream, outputStream, requestId, toResponse } = buildStatelessGenerationStreams(response, "completion");
|
|
314
378
|
const textPromise = (async () => {
|
|
@@ -328,6 +392,12 @@ function buildCompletionResult(response) {
|
|
|
328
392
|
toResponse,
|
|
329
393
|
};
|
|
330
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
|
+
*/
|
|
331
401
|
export async function objectGeneration(config, input) {
|
|
332
402
|
const body = buildStatelessGenerationBody(input, {
|
|
333
403
|
type: "object",
|
|
@@ -342,10 +412,16 @@ export async function objectGeneration(config, input) {
|
|
|
342
412
|
});
|
|
343
413
|
return buildObjectResult(response);
|
|
344
414
|
}
|
|
415
|
+
/**
|
|
416
|
+
* Parses partial and final JSON from independent text-stream branches.
|
|
417
|
+
*/
|
|
345
418
|
function buildObjectResult(response) {
|
|
346
419
|
const { finalStream, outputStream, requestId, toResponse } = buildStatelessGenerationStreams(response, "object");
|
|
347
420
|
let accumulatedText = "";
|
|
348
421
|
const partialObjectStream = outputStream.pipeThrough(new TransformStream({
|
|
422
|
+
/**
|
|
423
|
+
* Accumulates generated text and emits each available partial JSON value.
|
|
424
|
+
*/
|
|
349
425
|
async transform(chunk, controller) {
|
|
350
426
|
accumulatedText += chunk;
|
|
351
427
|
const { value } = await parsePartialJson(accumulatedText);
|
|
@@ -353,6 +429,9 @@ function buildObjectResult(response) {
|
|
|
353
429
|
controller.enqueue(value);
|
|
354
430
|
}
|
|
355
431
|
},
|
|
432
|
+
/**
|
|
433
|
+
* Rejects malformed final JSON when the text stream ends.
|
|
434
|
+
*/
|
|
356
435
|
flush() {
|
|
357
436
|
try {
|
|
358
437
|
JSON.parse(accumulatedText);
|
|
@@ -392,6 +471,9 @@ function buildObjectResult(response) {
|
|
|
392
471
|
toResponse,
|
|
393
472
|
};
|
|
394
473
|
}
|
|
474
|
+
/**
|
|
475
|
+
* Splits decoded text into final, public, and response-relay branches.
|
|
476
|
+
*/
|
|
395
477
|
function buildStatelessGenerationStreams(response, resourceName) {
|
|
396
478
|
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
397
479
|
const location = response.headers.get("location");
|
|
@@ -408,6 +490,7 @@ function buildStatelessGenerationStreams(response, resourceName) {
|
|
|
408
490
|
finalStream,
|
|
409
491
|
outputStream,
|
|
410
492
|
requestId,
|
|
493
|
+
/** Claims the response relay once. */
|
|
411
494
|
toResponse: () => {
|
|
412
495
|
if (responseBodyClaimed) {
|
|
413
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;
|