@blazingagents/sdk 0.51.0 → 0.53.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.
@@ -1,22 +1,50 @@
1
- import { type ChatTransport, type HttpChatTransportInitOptions, type UIMessage } from "ai";
1
+ import { type ChatTransport, type HttpChatTransportInitOptions, type UIMessage, type UIMessageChunk } from "ai";
2
2
  export type BlazingAgentsChatTransportOptions<UI_MESSAGE extends UIMessage = UIMessage> = Omit<HttpChatTransportInitOptions<UI_MESSAGE>, "prepareReconnectToStreamRequest" | "prepareSendMessagesRequest"> & {
3
3
  /**
4
4
  * Receives the Session ID minted by the first successful response.
5
5
  * @param sessionId - Session to look up or record.
6
6
  */
7
7
  onSessionId?: (sessionId: string) => Promise<void> | void;
8
+ /**
9
+ * Called when the running Turn reads a steered message, from the transient
10
+ * `data-ba-steer-consumed` chunk. The chunk still reaches `Chat` as a
11
+ * transient data part.
12
+ * @param requestId - The steer's request ID.
13
+ */
14
+ onSteerConsumed?: (requestId: string) => void;
15
+ /**
16
+ * Called when the running Turn's stream carries its `finish` chunk. A
17
+ * stream that ends without one, by Stop, a server `abort`, an error, or a
18
+ * dropped connection, did not complete, though the Turn may have stored its
19
+ * messages before it ended.
20
+ */
21
+ onTurnFinish?: () => void;
8
22
  /**
9
23
  * Receives the running Turn ID from each response that names one, before
10
24
  * its stream is consumed. Pass it to Stop.
11
25
  * @param turnId - Turn the response runs.
12
26
  */
13
27
  onTurnId?: (turnId: string) => Promise<void> | void;
28
+ /**
29
+ * Called when the relay answers a chat request with a stream, before any
30
+ * chunk is read. From then on the Turn accepts steers.
31
+ */
32
+ onTurnStart?: () => void;
14
33
  /** An authorized Session ID used to resume after a remount or reload. */
15
34
  sessionId?: string;
16
35
  };
17
36
  /**
18
- * Adapts AI SDK chat requests to the Blazing Agents backend-relay shape and
19
- * resumes with the server-minted Session ID returned in `Location`.
37
+ * What a steer did, folded into what the caller does next:
38
+ * - `accepted`: the running Turn holds it and may still read it.
39
+ * - `committed`: it is stored with that Turn's history.
40
+ * - `resend`: it will never reach this Turn (its receipt is `not_placed`, or
41
+ * the relay answered 409 `steer_not_available`); send it as ordinary chat.
42
+ */
43
+ export type SteerOutcome = "accepted" | "committed" | "resend";
44
+ /**
45
+ * Adapts AI SDK chat requests to the Blazing Agents relay, resumes with the
46
+ * server-minted Session ID returned in `Location`, and reads history and
47
+ * steers through the same relay endpoint.
20
48
  */
21
49
  export declare class BlazingAgentsChatTransport<UI_MESSAGE extends UIMessage = UIMessage> implements ChatTransport<UI_MESSAGE> {
22
50
  #private;
@@ -25,16 +53,46 @@ export declare class BlazingAgentsChatTransport<UI_MESSAGE extends UIMessage = U
25
53
  * @param options - Configuration for this operation.
26
54
  */
27
55
  constructor(options?: BlazingAgentsChatTransportOptions<UI_MESSAGE>);
56
+ /** The Session this transport talks to: the supplied one, or the one the first chat minted. */
57
+ get sessionId(): string | undefined;
28
58
  /**
29
59
  * Submits the latest user message or complete assistant approval round to the chat.
30
60
  * @param input - Operation input and optional cancellation signal.
31
61
  * @returns The decoded AI SDK message-chunk stream.
32
62
  */
33
- sendMessages(input: Parameters<ChatTransport<UI_MESSAGE>["sendMessages"]>[0]): Promise<ReadableStream<import("ai").UIMessageChunk>>;
63
+ sendMessages(input: Parameters<ChatTransport<UI_MESSAGE>["sendMessages"]>[0]): Promise<ReadableStream<UIMessageChunk>>;
34
64
  /**
35
65
  * Returns null because reconnecting to an existing stream is unsupported.
36
66
  * @param _input - Unused reconnect request.
37
67
  * @returns A promise resolving to null.
38
68
  */
39
69
  reconnectToStream(_input: Parameters<ChatTransport<UI_MESSAGE>["reconnectToStream"]>[0]): Promise<null>;
70
+ /**
71
+ * Reads the Session's stored transcript through the relay, oldest first.
72
+ * Pages are read newest first. With `known`, the read stops at the first
73
+ * page whose oldest message is in `known`, and the known messages before
74
+ * that one complete the transcript, so a transcript that changed only near
75
+ * its end costs one request.
76
+ * @param options - `known`: messages already known to be stored, oldest first. Optional cancellation signal.
77
+ * @returns The stored messages, validated as `UIMessage`s; empty without a Session.
78
+ * @throws BlazingAgentsError - The relay's error, such as 404 `not_found` when the Session is gone or belongs to another End-user; `invalid_response` when a page or message is malformed; `network_error` or `request_aborted` when the request fails.
79
+ */
80
+ loadHistory(options?: {
81
+ abortSignal?: AbortSignal;
82
+ known?: readonly UI_MESSAGE[];
83
+ }): Promise<UI_MESSAGE[]>;
84
+ /**
85
+ * Sends one user message into the Turn running now. Retrying with the same
86
+ * `requestId` and message replays the receipt.
87
+ * @param input - The user message, its steer request ID, and an optional cancellation signal.
88
+ * @returns What the steer did; see `SteerOutcome`.
89
+ * @throws BlazingAgentsError - `invalid_request` without a Session; the relay's error, such as 409 `input_idempotency_conflict`; `network_error` when the answer was lost.
90
+ */
91
+ steer(input: {
92
+ abortSignal?: AbortSignal;
93
+ message: UI_MESSAGE & {
94
+ role: "user";
95
+ };
96
+ requestId: string;
97
+ }): Promise<SteerOutcome>;
40
98
  }
@@ -1,12 +1,25 @@
1
- import { lastAssistantMessageIsCompleteWithApprovalResponses, } from "ai";
1
+ import { lastAssistantMessageIsCompleteWithApprovalResponses, safeValidateUIMessages, } from "ai";
2
+ import { relayHistoryPageSchema, relaySteerReceiptSchema, } from "./chat-relay-wire.js";
2
3
  import { ChatStreamTransport } from "./chat-stream-transport.js";
4
+ import { chatSteerConsumedEventSchema } from "./contracts/entities/session-inputs.js";
3
5
  import { sessionIdSchema, turnIdSchema } from "./contracts/ids.js";
4
- import { parseClientInput } from "./errors.js";
6
+ import { BlazingAgentsError, parseClientInput } from "./errors.js";
7
+ import { errorFromResponse, invalidResponseError, sendRequest, } from "./http.js";
8
+ /** At most this many history pages (of 200 messages) are read. */
9
+ const HISTORY_PAGE_LIMIT = 50;
5
10
  /**
6
- * Adapts AI SDK chat requests to the Blazing Agents backend-relay shape and
7
- * resumes with the server-minted Session ID returned in `Location`.
11
+ * Adapts AI SDK chat requests to the Blazing Agents relay, resumes with the
12
+ * server-minted Session ID returned in `Location`, and reads history and
13
+ * steers through the same relay endpoint.
8
14
  */
9
15
  export class BlazingAgentsChatTransport {
16
+ #api;
17
+ #body;
18
+ #credentials;
19
+ #fetch;
20
+ #headers;
21
+ #onSteerConsumed;
22
+ #onTurnFinish;
10
23
  #transport;
11
24
  #sessionId;
12
25
  /**
@@ -14,19 +27,26 @@ export class BlazingAgentsChatTransport {
14
27
  * @param options - Configuration for this operation.
15
28
  */
16
29
  constructor(options = {}) {
17
- const { onSessionId, onTurnId, sessionId, ...transportOptions } = options;
30
+ const { onSessionId, onSteerConsumed, onTurnFinish, onTurnId, onTurnStart, sessionId, ...transportOptions } = options;
18
31
  const transportFetch = transportOptions.fetch ?? globalThis.fetch;
32
+ this.#api = transportOptions.api ?? "/api/chat";
33
+ this.#body = transportOptions.body;
34
+ this.#credentials = transportOptions.credentials;
35
+ this.#fetch = transportFetch;
36
+ this.#headers = transportOptions.headers;
37
+ this.#onSteerConsumed = onSteerConsumed;
38
+ this.#onTurnFinish = onTurnFinish;
19
39
  this.#sessionId =
20
40
  sessionId === undefined
21
41
  ? undefined
22
42
  : parseClientInput(sessionIdSchema, sessionId, "sessionId");
23
43
  this.#transport = new ChatStreamTransport({
24
44
  ...transportOptions,
25
- /** Reads the first Session ID and each Turn ID before returning the response. */
45
+ /** Throws a relay error as a `BlazingAgentsError`, and reads the first Session ID and each Turn ID before returning the response. */
26
46
  fetch: async (input, init) => {
27
47
  const response = await transportFetch(input, init);
28
48
  if (!response.ok) {
29
- return response;
49
+ throw await errorFromResponse(response, init?.signal ?? undefined);
30
50
  }
31
51
  try {
32
52
  if (this.#sessionId === undefined) {
@@ -44,6 +64,7 @@ export class BlazingAgentsChatTransport {
44
64
  await response.body?.cancel(error).catch(() => undefined);
45
65
  throw error;
46
66
  }
67
+ onTurnStart?.();
47
68
  return response;
48
69
  },
49
70
  /** Selects the user message or complete approval round for the relay request. */
@@ -59,25 +80,44 @@ export class BlazingAgentsChatTransport {
59
80
  if (!message) {
60
81
  throw new Error("Chat submission requires a user message.");
61
82
  }
62
- return {
63
- body: {
64
- ...body,
65
- message,
66
- messageId,
67
- sessionId: this.#sessionId,
68
- trigger,
69
- },
83
+ const request = {
84
+ op: "chat",
85
+ message,
86
+ messageId,
87
+ sessionId: this.#sessionId,
88
+ trigger,
70
89
  };
90
+ return { body: { ...body, ...request } };
71
91
  },
72
92
  });
73
93
  }
94
+ /** The Session this transport talks to: the supplied one, or the one the first chat minted. */
95
+ get sessionId() {
96
+ return this.#sessionId;
97
+ }
74
98
  /**
75
99
  * Submits the latest user message or complete assistant approval round to the chat.
76
100
  * @param input - Operation input and optional cancellation signal.
77
101
  * @returns The decoded AI SDK message-chunk stream.
78
102
  */
79
- sendMessages(input) {
80
- return this.#transport.sendMessages(input);
103
+ async sendMessages(input) {
104
+ const onSteerConsumed = this.#onSteerConsumed;
105
+ const onTurnFinish = this.#onTurnFinish;
106
+ const stream = await this.#transport.sendMessages(input);
107
+ return stream.pipeThrough(new TransformStream({
108
+ transform(chunk, controller) {
109
+ if (chunk.type === "finish") {
110
+ onTurnFinish?.();
111
+ }
112
+ if (chunk.type === "data-ba-steer-consumed") {
113
+ const steer = chatSteerConsumedEventSchema.safeParse(chunk);
114
+ if (steer.success) {
115
+ onSteerConsumed?.(steer.data.data.requestId);
116
+ }
117
+ }
118
+ controller.enqueue(chunk);
119
+ },
120
+ }));
81
121
  }
82
122
  /**
83
123
  * Returns null because reconnecting to an existing stream is unsupported.
@@ -87,4 +127,122 @@ export class BlazingAgentsChatTransport {
87
127
  reconnectToStream(_input) {
88
128
  return Promise.resolve(null);
89
129
  }
130
+ /**
131
+ * Reads the Session's stored transcript through the relay, oldest first.
132
+ * Pages are read newest first. With `known`, the read stops at the first
133
+ * page whose oldest message is in `known`, and the known messages before
134
+ * that one complete the transcript, so a transcript that changed only near
135
+ * its end costs one request.
136
+ * @param options - `known`: messages already known to be stored, oldest first. Optional cancellation signal.
137
+ * @returns The stored messages, validated as `UIMessage`s; empty without a Session.
138
+ * @throws BlazingAgentsError - The relay's error, such as 404 `not_found` when the Session is gone or belongs to another End-user; `invalid_response` when a page or message is malformed; `network_error` or `request_aborted` when the request fails.
139
+ */
140
+ async loadHistory(options = {}) {
141
+ const sessionId = this.#sessionId;
142
+ if (sessionId === undefined) {
143
+ return [];
144
+ }
145
+ const { abortSignal, known = [] } = options;
146
+ const pages = [];
147
+ const cursors = new Set();
148
+ let cursor;
149
+ let kept = [];
150
+ do {
151
+ const page = await this.#post({ op: "history", sessionId, cursor }, relayHistoryPageSchema, abortSignal);
152
+ const messages = await validateHistory(page.data);
153
+ pages.unshift(messages);
154
+ const oldest = known.findIndex((message) => message.id === messages[0]?.id);
155
+ if (oldest !== -1) {
156
+ kept = known.slice(0, oldest);
157
+ break;
158
+ }
159
+ if (page.nextCursor === null || cursors.has(page.nextCursor)) {
160
+ break;
161
+ }
162
+ cursor = page.nextCursor;
163
+ cursors.add(cursor);
164
+ } while (pages.length < HISTORY_PAGE_LIMIT);
165
+ const read = pages.flat();
166
+ const readIds = new Set(read.map((message) => message.id));
167
+ return [
168
+ ...kept.filter((message) => !readIds.has(message.id)),
169
+ // A Turn that commits while the pages are read can repeat a message on two pages.
170
+ ...new Map(read.map((message) => [message.id, message])).values(),
171
+ ];
172
+ }
173
+ /**
174
+ * Sends one user message into the Turn running now. Retrying with the same
175
+ * `requestId` and message replays the receipt.
176
+ * @param input - The user message, its steer request ID, and an optional cancellation signal.
177
+ * @returns What the steer did; see `SteerOutcome`.
178
+ * @throws BlazingAgentsError - `invalid_request` without a Session; the relay's error, such as 409 `input_idempotency_conflict`; `network_error` when the answer was lost.
179
+ */
180
+ async steer(input) {
181
+ const sessionId = this.#sessionId;
182
+ if (sessionId === undefined) {
183
+ throw new BlazingAgentsError({
184
+ code: "invalid_request",
185
+ message: "Steering requires an existing Session.",
186
+ });
187
+ }
188
+ try {
189
+ const receipt = await this.#post({
190
+ op: "steer",
191
+ sessionId,
192
+ requestId: input.requestId,
193
+ message: input.message,
194
+ }, relaySteerReceiptSchema, input.abortSignal);
195
+ return receipt.state === "not_placed" ? "resend" : receipt.state;
196
+ }
197
+ catch (error) {
198
+ if (BlazingAgentsError.isInstance(error) &&
199
+ error.code === "steer_not_available") {
200
+ return "resend";
201
+ }
202
+ throw error;
203
+ }
204
+ }
205
+ /** POSTs one JSON op to the relay with the transport's headers, credentials, and body extras. */
206
+ async #post(request, schema, abortSignal) {
207
+ const [extras, headers, credentials] = await Promise.all([
208
+ resolveOption(this.#body),
209
+ resolveOption(this.#headers),
210
+ resolveOption(this.#credentials),
211
+ ]);
212
+ const requestHeaders = new Headers(headers);
213
+ requestHeaders.set("content-type", "application/json");
214
+ const response = await sendRequest(this.#fetch, this.#api, {
215
+ body: JSON.stringify({ ...extras, ...request }),
216
+ credentials,
217
+ headers: requestHeaders,
218
+ method: "POST",
219
+ signal: abortSignal,
220
+ });
221
+ if (!response.ok) {
222
+ throw await errorFromResponse(response, abortSignal);
223
+ }
224
+ const text = await response.text();
225
+ try {
226
+ return schema.parse(JSON.parse(text));
227
+ }
228
+ catch (cause) {
229
+ throw invalidResponseError(response.headers, response.status, text, false, cause);
230
+ }
231
+ }
232
+ }
233
+ async function validateHistory(messages) {
234
+ if (messages.length === 0) {
235
+ return [];
236
+ }
237
+ const validated = await safeValidateUIMessages({ messages });
238
+ if (!validated.success) {
239
+ throw new BlazingAgentsError({
240
+ code: "invalid_response",
241
+ message: "The relay returned a malformed history message.",
242
+ }, { cause: validated.error });
243
+ }
244
+ return validated.data;
245
+ }
246
+ function resolveOption(value) {
247
+ return Promise.resolve(typeof value === "function" ? value() : value);
90
248
  }
@@ -9,12 +9,12 @@ export declare const sessionInputSchema: z.ZodObject<{
9
9
  requestId: z.ZodString;
10
10
  sequence: z.ZodNumber;
11
11
  message: z.ZodObject<{
12
- role: z.ZodLiteral<"user">;
13
12
  id: z.ZodString;
14
13
  parts: z.ZodArray<z.ZodObject<{
15
14
  type: z.ZodString;
16
15
  }, z.core.$loose>>;
17
16
  metadata: z.ZodOptional<z.ZodUnknown>;
17
+ role: z.ZodLiteral<"user">;
18
18
  }, z.core.$loose>;
19
19
  state: z.ZodEnum<{
20
20
  accepted: "accepted";
@@ -45,12 +45,12 @@ export declare const sessionInputResponseSchema: z.ZodObject<{
45
45
  requestId: z.ZodString;
46
46
  sequence: z.ZodNumber;
47
47
  message: z.ZodObject<{
48
- role: z.ZodLiteral<"user">;
49
48
  id: z.ZodString;
50
49
  parts: z.ZodArray<z.ZodObject<{
51
50
  type: z.ZodString;
52
51
  }, z.core.$loose>>;
53
52
  metadata: z.ZodOptional<z.ZodUnknown>;
53
+ role: z.ZodLiteral<"user">;
54
54
  }, z.core.$loose>;
55
55
  state: z.ZodEnum<{
56
56
  accepted: "accepted";
@@ -82,12 +82,12 @@ export declare const sessionInputsResponseSchema: z.ZodObject<{
82
82
  requestId: z.ZodString;
83
83
  sequence: z.ZodNumber;
84
84
  message: z.ZodObject<{
85
- role: z.ZodLiteral<"user">;
86
85
  id: z.ZodString;
87
86
  parts: z.ZodArray<z.ZodObject<{
88
87
  type: z.ZodString;
89
88
  }, z.core.$loose>>;
90
89
  metadata: z.ZodOptional<z.ZodUnknown>;
90
+ role: z.ZodLiteral<"user">;
91
91
  }, z.core.$loose>;
92
92
  state: z.ZodEnum<{
93
93
  accepted: "accepted";
@@ -156,12 +156,12 @@ export declare const chatSteerConsumedEventSchema: z.ZodObject<{
156
156
  requestId: z.ZodString;
157
157
  sequence: z.ZodNumber;
158
158
  message: z.ZodObject<{
159
- role: z.ZodLiteral<"user">;
160
159
  id: z.ZodString;
161
160
  parts: z.ZodArray<z.ZodObject<{
162
161
  type: z.ZodString;
163
162
  }, z.core.$loose>>;
164
163
  metadata: z.ZodOptional<z.ZodUnknown>;
164
+ role: z.ZodLiteral<"user">;
165
165
  }, z.core.$loose>;
166
166
  turnId: z.ZodString;
167
167
  }, z.core.$strip>;
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { turnIdSchema } from "../ids.js";
3
- import { sessionMessageSchema } from "./sessions.js";
3
+ import { sessionMessageSchema } from "./session-messages.js";
4
4
  export const sessionInputStateSchema = z.enum([
5
5
  "accepted",
6
6
  "committed",
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
4
+ * `UIMessage[]` verbatim, paginated backwards (newest page first) with an
5
+ * optional forward `?after={cursor}` for the poll loop.
6
+ */
7
+ export declare const sessionMessageSchema: z.ZodObject<{
8
+ id: z.ZodString;
9
+ role: z.ZodEnum<{
10
+ assistant: "assistant";
11
+ system: "system";
12
+ user: "user";
13
+ }>;
14
+ branchable: z.ZodBoolean;
15
+ parts: z.ZodArray<z.ZodObject<{
16
+ type: z.ZodString;
17
+ }, z.core.$loose>>;
18
+ metadata: z.ZodOptional<z.ZodUnknown>;
19
+ }, z.core.$loose>;
20
+ export type SessionMessage = z.infer<typeof sessionMessageSchema>;
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
4
+ * `UIMessage[]` verbatim, paginated backwards (newest page first) with an
5
+ * optional forward `?after={cursor}` for the poll loop.
6
+ */
7
+ export const sessionMessageSchema = z
8
+ .object({
9
+ id: z.string().min(1),
10
+ role: z.enum(["system", "user", "assistant"]),
11
+ branchable: z.boolean(),
12
+ parts: z
13
+ .array(z
14
+ .object({
15
+ type: z.string().min(1),
16
+ })
17
+ .passthrough())
18
+ .min(1),
19
+ metadata: z.unknown().optional(),
20
+ })
21
+ .passthrough();
@@ -193,24 +193,6 @@ export declare const latestSessionsListResponseSchema: z.ZodObject<{
193
193
  }, z.core.$strip>>;
194
194
  nextCursor: z.ZodNullable<z.ZodString>;
195
195
  }, z.core.$strip>;
196
- /**
197
- * `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
198
- * `UIMessage[]` verbatim, paginated backwards (newest page first) with an
199
- * optional forward `?after={cursor}` for the poll loop.
200
- */
201
- export declare const sessionMessageSchema: z.ZodObject<{
202
- id: z.ZodString;
203
- role: z.ZodEnum<{
204
- assistant: "assistant";
205
- system: "system";
206
- user: "user";
207
- }>;
208
- branchable: z.ZodBoolean;
209
- parts: z.ZodArray<z.ZodObject<{
210
- type: z.ZodString;
211
- }, z.core.$loose>>;
212
- metadata: z.ZodOptional<z.ZodUnknown>;
213
- }, z.core.$loose>;
214
196
  /**
215
197
  * The messages endpoint carries two cursors: `nextCursor` for continuing
216
198
  * pagination in the requested direction (backward `?cursor=` walks older
@@ -382,7 +364,6 @@ export type TurnStreamErrorEvent = z.infer<typeof turnStreamErrorEventSchema>;
382
364
  export type SessionForkedFrom = z.infer<typeof sessionForkedFromSchema>;
383
365
  export type SessionListItem = z.infer<typeof sessionListItemSchema>;
384
366
  export type LatestSessionListItem = z.infer<typeof latestSessionListItemSchema>;
385
- export type SessionMessage = z.infer<typeof sessionMessageSchema>;
386
367
  export type SessionResponse = z.infer<typeof sessionResponseSchema>;
387
368
  export type SessionsListResponse = z.infer<typeof sessionsListResponseSchema>;
388
369
  export type LatestSessionsListResponse = z.infer<typeof latestSessionsListResponseSchema>;
@@ -5,6 +5,7 @@ import { toolExecutionReferenceSchema } from "./agent-approval.js";
5
5
  import { agentConfigSchema, agentResponseSchema } from "./agents.js";
6
6
  import { metadataSchema, userIdSchema } from "./attribution.js";
7
7
  import { chatRequestBodySchema } from "./chat.js";
8
+ import { sessionMessageSchema } from "./session-messages.js";
8
9
  /**
9
10
  * `GET /v1/agents/{agentId}/sessions` list item. `agentId`/`tenantId` never
10
11
  * leak to the wire; `userId`/`metadata` come from the first successful Turn.
@@ -48,26 +49,6 @@ export const latestSessionListItemSchema = sessionListItemSchema
48
49
  })
49
50
  .strip();
50
51
  export const latestSessionsListResponseSchema = paginatedResponseSchema(latestSessionListItemSchema);
51
- /**
52
- * `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
53
- * `UIMessage[]` verbatim, paginated backwards (newest page first) with an
54
- * optional forward `?after={cursor}` for the poll loop.
55
- */
56
- export const sessionMessageSchema = z
57
- .object({
58
- id: z.string().min(1),
59
- role: z.enum(["system", "user", "assistant"]),
60
- branchable: z.boolean(),
61
- parts: z
62
- .array(z
63
- .object({
64
- type: z.string().min(1),
65
- })
66
- .passthrough())
67
- .min(1),
68
- metadata: z.unknown().optional(),
69
- })
70
- .passthrough();
71
52
  /**
72
53
  * The messages endpoint carries two cursors: `nextCursor` for continuing
73
54
  * pagination in the requested direction (backward `?cursor=` walks older
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  /**
3
- * Schedule kinds — discriminated union, Cohand's kinds with croner-forked
4
- * next-run math. `staggerMs` is an optional cron load-spreading offset.
3
+ * Schedule kinds — discriminated union. `staggerMs` is an optional cron
4
+ * load-spreading offset.
5
5
  */
6
6
  export declare const taskScheduleKindSchema: z.ZodEnum<{
7
7
  cron: "cron";
@@ -15,8 +15,10 @@ export declare const taskIntervalConfigSchema: z.ZodObject<{
15
15
  everyMs: z.ZodNumber;
16
16
  }, z.core.$strict>;
17
17
  /**
18
- * Croner validates the expression in the schedule's own timezone. The DBOS
19
- * schedule plan uses that validated expression and timezone unchanged.
18
+ * A cron schedule: five numeric fields in an IANA timezone. The schema checks
19
+ * only that shape. The API validates the expression's values in the
20
+ * schedule's own timezone, so an out-of-range field or an impossible date
21
+ * fails there.
20
22
  */
21
23
  export declare const taskCronConfigSchema: z.ZodObject<{
22
24
  expression: z.ZodString;
@@ -1,4 +1,3 @@
1
- import { Cron } from "croner";
2
1
  import { z } from "zod";
3
2
  import { paginatedResponseSchema, receivedApiErrorCodeSchema } from "../api.js";
4
3
  import { agentIdSchema, sessionIdSchema, taskIdSchema, taskRunIdSchema, tenantIdSchema, turnIdSchema, } from "../ids.js";
@@ -8,8 +7,8 @@ import { agentConfigSchema } from "./agents.js";
8
7
  import { metadataSchema, userIdSchema } from "./attribution.js";
9
8
  import { sessionMessagesResponseSchema } from "./sessions.js";
10
9
  /**
11
- * Schedule kinds — discriminated union, Cohand's kinds with croner-forked
12
- * next-run math. `staggerMs` is an optional cron load-spreading offset.
10
+ * Schedule kinds — discriminated union. `staggerMs` is an optional cron
11
+ * load-spreading offset.
13
12
  */
14
13
  export const taskScheduleKindSchema = z.enum(["once", "interval", "cron"]);
15
14
  export const taskOnceConfigSchema = z
@@ -24,7 +23,7 @@ export const taskIntervalConfigSchema = z
24
23
  .strict();
25
24
  const CRON_FIELDS_SEPARATOR = /\s+/;
26
25
  const NUMERIC_CRON_EXPRESSION = /^[\d*,/\-\s]+$/;
27
- /** Croner owns cron grammar; the product limits schedules to five numeric fields. */
26
+ /** The product limits schedules to five numeric fields. The API checks the values. */
28
27
  const cronExpressionSchema = z
29
28
  .string()
30
29
  .trim()
@@ -35,7 +34,7 @@ const cronExpressionSchema = z
35
34
  /**
36
35
  * Canonical IANA timezone: `UTC` or `Area/Location` (optionally
37
36
  * `Area/Location/Sublocation`). Rejects legacy abbreviations (`PST`, `GMT`)
38
- * that `Intl` quietly accepts but `croner` cannot resolve deterministically.
37
+ * that `Intl` quietly accepts but a scheduler cannot resolve deterministically.
39
38
  */
40
39
  const IANA_TIMEZONE_REGEX = /^(UTC|[A-Za-z_]+\/[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)?)$/;
41
40
  const ianaTimezoneSchema = z
@@ -54,8 +53,10 @@ const ianaTimezoneSchema = z
54
53
  }
55
54
  }, { message: "Unknown IANA timezone." });
56
55
  /**
57
- * Croner validates the expression in the schedule's own timezone. The DBOS
58
- * schedule plan uses that validated expression and timezone unchanged.
56
+ * A cron schedule: five numeric fields in an IANA timezone. The schema checks
57
+ * only that shape. The API validates the expression's values in the
58
+ * schedule's own timezone, so an out-of-range field or an impossible date
59
+ * fails there.
59
60
  */
60
61
  export const taskCronConfigSchema = z
61
62
  .object({
@@ -63,27 +64,7 @@ export const taskCronConfigSchema = z
63
64
  staggerMs: z.number().int().min(0).optional(),
64
65
  timezone: ianaTimezoneSchema.default("UTC"),
65
66
  })
66
- .strict()
67
- .superRefine((config, ctx) => {
68
- try {
69
- const cron = new Cron(config.expression, {
70
- paused: true,
71
- timezone: config.timezone,
72
- });
73
- // A five-field expression repeats, so a run after the epoch exists
74
- // exactly when one after now does; this keeps parsing off the clock.
75
- if (cron.nextRun(new Date(0)) === null) {
76
- throw new Error("no next run");
77
- }
78
- }
79
- catch {
80
- ctx.addIssue({
81
- code: "custom",
82
- message: "Invalid cron expression.",
83
- path: ["expression"],
84
- });
85
- }
86
- });
67
+ .strict();
87
68
  export const taskScheduleInputSchema = z.discriminatedUnion("kind", [
88
69
  z
89
70
  .object({
@@ -20,8 +20,9 @@ export { createPromptBodySchema, parsePromptVariables, promptResponseSchema, pro
20
20
  export { createProviderBodySchema, providerListItemSchema, providerModelsResponseSchema, providerResponseSchema, providersResponseSchema, providerTypeSchema, thinkingLevelsResponseSchema, updateProviderBodySchema, } from "./entities/providers.ts";
21
21
  export type { ChatSteerConsumedEvent, SessionActivity, SessionInput, SessionInputResponse, SessionInputState, SessionInputsQuery, SessionInputsResponse, StopSessionBody, StopSessionResponse, SubmitSessionInputBody, } from "./entities/session-inputs.ts";
22
22
  export { chatSteerConsumedEventSchema, sessionActivitySchema, sessionInputRequestIdSchema, sessionInputResponseSchema, sessionInputSchema, sessionInputStateSchema, sessionInputsQuerySchema, sessionInputsResponseSchema, stopSessionBodySchema, stopSessionResponseSchema, submitSessionInputBodySchema, } from "./entities/session-inputs.ts";
23
- export type { ContinueToolApprovalsBody, LatestSessionListItem, SessionForkedFrom, SessionListItem, SessionMessage, ToolApprovalContinuationState, ToolApprovalDecision, ToolApprovalsResponse, TurnStreamErrorEvent, } from "./entities/sessions.ts";
24
- export { continueToolApprovalsBodySchema, latestSessionListItemSchema, latestSessionsListResponseSchema, sessionForkedFromSchema, sessionListItemSchema, sessionMessageSchema, sessionMessagesResponseSchema, sessionResponseSchema, sessionsListResponseSchema, toolApprovalContinuationSchema, toolApprovalContinuationStateSchema, toolApprovalDecisionSchema, toolApprovalStateSchema, toolApprovalsResponseSchema, turnStreamErrorEventSchema, } from "./entities/sessions.ts";
23
+ export { type SessionMessage, sessionMessageSchema, } from "./entities/session-messages.ts";
24
+ export type { ContinueToolApprovalsBody, LatestSessionListItem, SessionForkedFrom, SessionListItem, ToolApprovalContinuationState, ToolApprovalDecision, ToolApprovalsResponse, TurnStreamErrorEvent, } from "./entities/sessions.ts";
25
+ export { continueToolApprovalsBodySchema, latestSessionListItemSchema, latestSessionsListResponseSchema, sessionForkedFromSchema, sessionListItemSchema, sessionMessagesResponseSchema, sessionResponseSchema, sessionsListResponseSchema, toolApprovalContinuationSchema, toolApprovalContinuationStateSchema, toolApprovalDecisionSchema, toolApprovalStateSchema, toolApprovalsResponseSchema, turnStreamErrorEventSchema, } from "./entities/sessions.ts";
25
26
  export { copySkillBodySchema, createSkillBodySchema, skillArchiveTypeSchema, skillCopyResultsSchema, skillDescriptionSchema, skillDetailSchema, skillFilePathSchema, skillMetadataSchema, skillNameSchema, skillSchema, skillsListResponseSchema, } from "./entities/skills.ts";
26
27
  export type { SpendingLimit, SpendingLimitResponse, SpendingLimitStopDetails, UpdateSpendingLimitBody, } from "./entities/spending-limits.ts";
27
28
  export { nextSpendingLimitReset, spendingLimitPeriodSchema, spendingLimitResetIntervalSchema, spendingLimitResponseSchema, spendingLimitSchema, spendingLimitStopDetailsSchema, updateSpendingLimitBodySchema, } from "./entities/spending-limits.ts";
@@ -14,7 +14,8 @@ export { createMerchantConnectionBodySchema, merchantBindingResponseSchema, merc
14
14
  export { createPromptBodySchema, parsePromptVariables, promptResponseSchema, promptsListQuerySchema, promptsResponseSchema, promptTemplateSchema, renderPromptTemplate, updatePromptBodySchema, } from "./entities/prompts.js";
15
15
  export { createProviderBodySchema, providerListItemSchema, providerModelsResponseSchema, providerResponseSchema, providersResponseSchema, providerTypeSchema, thinkingLevelsResponseSchema, updateProviderBodySchema, } from "./entities/providers.js";
16
16
  export { chatSteerConsumedEventSchema, sessionActivitySchema, sessionInputRequestIdSchema, sessionInputResponseSchema, sessionInputSchema, sessionInputStateSchema, sessionInputsQuerySchema, sessionInputsResponseSchema, stopSessionBodySchema, stopSessionResponseSchema, submitSessionInputBodySchema, } from "./entities/session-inputs.js";
17
- export { continueToolApprovalsBodySchema, latestSessionListItemSchema, latestSessionsListResponseSchema, sessionForkedFromSchema, sessionListItemSchema, sessionMessageSchema, sessionMessagesResponseSchema, sessionResponseSchema, sessionsListResponseSchema, toolApprovalContinuationSchema, toolApprovalContinuationStateSchema, toolApprovalDecisionSchema, toolApprovalStateSchema, toolApprovalsResponseSchema, turnStreamErrorEventSchema, } from "./entities/sessions.js";
17
+ export { sessionMessageSchema, } from "./entities/session-messages.js";
18
+ export { continueToolApprovalsBodySchema, latestSessionListItemSchema, latestSessionsListResponseSchema, sessionForkedFromSchema, sessionListItemSchema, sessionMessagesResponseSchema, sessionResponseSchema, sessionsListResponseSchema, toolApprovalContinuationSchema, toolApprovalContinuationStateSchema, toolApprovalDecisionSchema, toolApprovalStateSchema, toolApprovalsResponseSchema, turnStreamErrorEventSchema, } from "./entities/sessions.js";
18
19
  export { copySkillBodySchema, createSkillBodySchema, skillArchiveTypeSchema, skillCopyResultsSchema, skillDescriptionSchema, skillDetailSchema, skillFilePathSchema, skillMetadataSchema, skillNameSchema, skillSchema, skillsListResponseSchema, } from "./entities/skills.js";
19
20
  export { nextSpendingLimitReset, spendingLimitPeriodSchema, spendingLimitResetIntervalSchema, spendingLimitResponseSchema, spendingLimitSchema, spendingLimitStopDetailsSchema, updateSpendingLimitBodySchema, } from "./entities/spending-limits.js";
20
21
  export { createTaskBodySchema, createTaskResponseSchema, createTaskRunBodySchema, createTaskRunResponseSchema, taskCronConfigSchema, taskIntervalConfigSchema, taskLatestRunSchema, taskListItemSchema, taskOnceConfigSchema, taskResponseSchema, taskRunMessagesResponseSchema, taskRunResponseSchema, taskRunStatusSchema, taskRunsListResponseSchema, taskScheduleInputSchema, taskScheduleKindSchema, tasksListResponseSchema, updateTaskBodySchema, } from "./entities/tasks.js";