@flytedesk/app-kit 11.4.0 → 11.5.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 CHANGED
@@ -618,6 +618,109 @@ The job's MCP tools module (`app-kit-chat-mcp --tools <path>`) need not register
618
618
  tool: a module that builds `kit.createChatMcpProtocol({ serverName, tools })` with only
619
619
  its own tools is served as it is.
620
620
 
621
+ ## Flytebot (`@flytedesk/app-kit/flytebot`)
622
+
623
+ Flytebot is the service that runs flytedesk's agents and structured LLM calls. An app
624
+ reaches it with a Google ID token of its Cloud Run service account (audience: Flytebot's
625
+ origin); no shared secret exists. Wire types come from `@flytedesk/flytebot-contracts`.
626
+
627
+ ```ts
628
+ import { createFlytebotClient, parseFlytebotEnv, verifyTerminalWebhook } from "@flytedesk/app-kit/flytebot";
629
+
630
+ const env = parseFlytebotEnv(process.env); // FLYTEBOT_URL, FLYTEBOT_SERVICE_ACCOUNT
631
+ const flytebot = createFlytebotClient({
632
+ baseUrl: env.flytebotUrl,
633
+ timeoutMs: 15_000,
634
+ retries: 3, // network failures, timeouts, 5xx and 429, with the SAME idempotency key
635
+ // idToken: (audience) => ..., // default: google-auth-library; inject one in tests
636
+ });
637
+
638
+ // one structured answer (an `llm` profile), validated against your zod schema
639
+ const { output, usage, costUsd } = await flytebot.llm.generate(
640
+ { profile: "goal-judgment", messages, actor },
641
+ outputZodSchema,
642
+ );
643
+
644
+ // an agent run; the key is your own row id, so a retried launch never starts a second run
645
+ const { run } = await flytebot.runs.create({
646
+ profile: "audience-chat",
647
+ conversation: { externalRef: conversationId },
648
+ task,
649
+ actor,
650
+ tools: { "sms-app-chat": { bearer } }, // the per-run bearer for your MCP server
651
+ webhook: { url },
652
+ idempotencyKey: dispatchId,
653
+ });
654
+ for await (const event of flytebot.runs.stream(run.id, { signal })) {
655
+ // in order, once each; reconnects with Last-Event-ID; ends after the terminal event
656
+ }
657
+ await flytebot.runs.get(run.id);
658
+ await flytebot.runs.usage(run.id);
659
+ await flytebot.runs.cancel(run.id, "user pressed stop"); // idempotent
660
+ await flytebot.profiles.get("planner-chat"); // model and effort pickers
661
+ ```
662
+
663
+ Every failure is a `FlytebotError` with `code` (the service's error code, or
664
+ `network_error`, `timeout`, `aborted`, `invalid_response`), `httpStatus` (null when no
665
+ response arrived), `retryable` and `requestId`. A `409 conversation_busy` carries
666
+ `details.activeRunId`.
667
+
668
+ The terminal webhook route verifies the call before it trusts the body:
669
+
670
+ ```ts
671
+ const run = await verifyTerminalWebhook(request, {
672
+ flytebotServiceAccount: env.flytebotServiceAccount,
673
+ audienceOrigin: "https://my-app.flytedesk.com", // the origin of the webhook URL you gave Flytebot
674
+ });
675
+ ```
676
+
677
+ It accepts only a Google-signed, unexpired ID token addressed to `audienceOrigin` whose
678
+ verified email is the Flytebot service account; anything else throws a
679
+ `FlytebotError` with code `unauthenticated` (answer 401). The route must be idempotent on
680
+ `(run.id, run.status)`: delivery is at-least-once.
681
+
682
+ ### Testing against the fake
683
+
684
+ `@flytedesk/app-kit/flytebot/testing` is an in-process Flytebot that speaks the contract:
685
+
686
+ ```ts
687
+ const fake = createFakeFlytebot();
688
+ await fake.start();
689
+ const flytebot = createFlytebotClient({ baseUrl: fake.url, idToken: async () => "t", timeoutMs: 1_000, retries: 2 });
690
+
691
+ fake.scriptRun({ events: [{ type: "text", messageId: "m1", delta: "hi" }], terminal: { status: "timeout" } });
692
+ fake.scriptRun({ hold: true }); // stays running: fake.emit(runId, ...) then fake.finish(runId)
693
+ fake.scriptRun({ events, dropStreamAfter: 3 }); // cuts the first stream to exercise reconnect
694
+ fake.failNext({ match: "POST /v1/runs", code: "unavailable" }); // a 503, then success
695
+ fake.setLlm("goal-judgment", { output: { achieved: true } });
696
+ fake.requests; // every request, with headers and parsed body
697
+ ```
698
+
699
+ Any terminal status and any error code can be scripted; it also enforces one active run per
700
+ conversation and replays an idempotency key.
701
+
702
+ ### Serving your tools to Flytebot (`@flytedesk/app-kit/chat/tools`)
703
+
704
+ `createRemoteMcpPlugin` serves your `AppRegisteredTool`s (and `createReplyTool`, unchanged)
705
+ over MCP streamable HTTP from your own API process. `authenticate` runs on every request and
706
+ returns your context for the bearer, or `null` (401); `tools(context)` builds that request's
707
+ tools, so a handler sees the context through its closure.
708
+
709
+ ```ts
710
+ await app.register(
711
+ createRemoteMcpPlugin({
712
+ serverName: "sms-app-chat",
713
+ authenticate: async (bearer) => findRunningTurnByToken(bearer),
714
+ tools: (turn) => [createReplyTool({ description, deliver: (reply) => recordReply(turn, reply) })],
715
+ }),
716
+ { prefix: "/mcp/chat" },
717
+ );
718
+ ```
719
+
720
+ A handler that throws is logged and reported to the agent as a tool error (`Tool "x"
721
+ failed.`); a validation error you return as `{ ok: false, retryable: false }` is read by the
722
+ model, and a retryable one is a JSON-RPC error.
723
+
621
724
  ## Tests
622
725
 
623
726
  `npm run check` is the full gate: lint, typecheck, build, unit tests, integration tests
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `@flytedesk/app-kit/chat/tools`: serve an app's agent tools to Flytebot over MCP
3
+ * streamable HTTP (PLAN-10 architecture section 6), from the app's own API process.
4
+ *
5
+ * Flytebot's runner calls this endpoint with the per-run bearer the app sent in
6
+ * `runs.create({ tools })`. The plugin authenticates that bearer on every request, builds
7
+ * the tool list for the context it resolves to, and hands the JSON-RPC message to the same
8
+ * `createChatMcpProtocol` the stdio server uses: `AppRegisteredTool` and `createReplyTool`
9
+ * are reused unchanged, only the transport is new.
10
+ *
11
+ * await app.register(
12
+ * createRemoteMcpPlugin({
13
+ * serverName: "sms-app-chat",
14
+ * authenticate: async (bearer) => findRunningTurnByToken(bearer), // context or null
15
+ * tools: (turn) => [createReplyTool({ description, deliver: (reply) => recordReply(turn, reply) })],
16
+ * }),
17
+ * { prefix: "/mcp/chat" },
18
+ * );
19
+ *
20
+ * The context reaches a tool through the closure `tools(context)` builds, so a handler
21
+ * never reads a bearer or a global.
22
+ */
23
+ import type { FastifyPluginAsync } from "fastify";
24
+ import type { AppRegisteredTool } from "../types.js";
25
+ export interface RemoteMcpPluginOptions<Context> {
26
+ /** Advertised in `initialize`'s `serverInfo.name`; also the key the app gives `runs.create({ tools })`. */
27
+ serverName: string;
28
+ serverVersion?: string;
29
+ /**
30
+ * Resolve a bearer to the app's context for that run, or null when the bearer is not a
31
+ * live run's (the request is then refused 401 before any tool runs). Called on every
32
+ * request. A throw is a server error, never an allow.
33
+ */
34
+ authenticate: (bearer: string) => Context | null | Promise<Context | null>;
35
+ /** The tools this request's context may call. */
36
+ tools: (context: Context) => AppRegisteredTool[];
37
+ }
38
+ export declare function createRemoteMcpPlugin<Context>(options: RemoteMcpPluginOptions<Context>): FastifyPluginAsync;
@@ -0,0 +1,60 @@
1
+ import { createChatMcpProtocol } from "../mcp-protocol.js";
2
+ const INVALID_REQUEST = -32600;
3
+ export function createRemoteMcpPlugin(options) {
4
+ return async (fastify) => {
5
+ fastify.post("/", async (request, reply) => {
6
+ const match = /^Bearer (\S+)$/i.exec(request.headers.authorization ?? "");
7
+ const context = match === null ? null : await options.authenticate(match[1]);
8
+ if (context === null) {
9
+ return reply
10
+ .code(401)
11
+ .header("www-authenticate", "Bearer")
12
+ .send({ error: "unauthorized" });
13
+ }
14
+ const message = request.body;
15
+ if (message === null || typeof message !== "object" || Array.isArray(message)) {
16
+ return reply.code(400).send({
17
+ jsonrpc: "2.0",
18
+ id: null,
19
+ error: { code: INVALID_REQUEST, message: "The body must be one JSON-RPC message object." },
20
+ });
21
+ }
22
+ // A tool that throws is reported to the model as a tool error and logged here, so
23
+ // an internal message never reaches the agent and one bad tool never drops the endpoint.
24
+ const tools = options.tools(context).map((tool) => ({
25
+ ...tool,
26
+ async handler(args) {
27
+ try {
28
+ return await tool.handler(args);
29
+ }
30
+ catch (error) {
31
+ request.log.error({ err: error, tool: tool.name }, "MCP tool handler threw");
32
+ return {
33
+ ok: false,
34
+ retryable: false,
35
+ message: `Tool "${tool.name}" failed.`,
36
+ };
37
+ }
38
+ },
39
+ }));
40
+ const response = await createChatMcpProtocol({
41
+ serverName: options.serverName,
42
+ serverVersion: options.serverVersion,
43
+ tools,
44
+ }).handleMessage(message);
45
+ if (response === null)
46
+ return reply.code(202).send();
47
+ return reply.send(response);
48
+ });
49
+ // Streamable HTTP lets a server decline the optional GET (server-initiated stream)
50
+ // and DELETE (session end); this server is stateless, so it does.
51
+ for (const method of ["GET", "DELETE"]) {
52
+ fastify.route({
53
+ method,
54
+ url: "/",
55
+ handler: async (_request, reply) => reply.code(405).header("allow", "POST").send({ error: "method_not_allowed" }),
56
+ });
57
+ }
58
+ };
59
+ }
60
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/chat/tools/index.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,66 @@
1
+ import { createRunRequest, llmRequest, type CreateRunResponse, type LlmResponse, type ProfileSummary, type Run, type RunEvent, type RunUsageResponse } from "@flytedesk/flytebot-contracts";
2
+ import type { z } from "zod";
3
+ export interface FlytebotClientOptions {
4
+ /** Flytebot's base URL, e.g. "https://flytebot.flytedesk.com". Its origin is the ID-token audience. */
5
+ baseUrl: string;
6
+ /**
7
+ * Returns a Google ID token for `audience`. Default: `google-auth-library` for the
8
+ * Cloud Run service account the process runs as. Inject a function in tests.
9
+ */
10
+ idToken?: (audience: string) => Promise<string>;
11
+ /** Per-request budget, including the response body; for a stream, the wait for the response headers. */
12
+ timeoutMs: number;
13
+ /** Retries after the first attempt, for network failures, timeouts, 5xx and 429. */
14
+ retries: number;
15
+ /** First retry delay; doubles each retry, jittered. A `Retry-After` header wins. Default 250. */
16
+ retryBaseDelayMs?: number;
17
+ /** A stream with no bytes (not even a ping) for this long is dropped and reconnected. Default 45000. */
18
+ streamIdleTimeoutMs?: number;
19
+ /** Default: global `fetch`. */
20
+ fetch?: typeof fetch;
21
+ }
22
+ type CreateRunInput = z.input<typeof createRunRequest> & {
23
+ /** Required: the app's own row id. A retry reuses it, so a launch is never duplicated. */
24
+ idempotencyKey: string;
25
+ };
26
+ export type CreateRunResult = CreateRunResponse & {
27
+ /** True when Flytebot answered with the original response to an earlier request with this key. */
28
+ replayed: boolean;
29
+ };
30
+ export type GenerateResult<T> = Omit<LlmResponse, "output"> & {
31
+ output: T;
32
+ };
33
+ export interface CallOptions {
34
+ signal?: AbortSignal;
35
+ }
36
+ export interface FlytebotClient {
37
+ llm: {
38
+ /** One structured answer from an `llm` profile, validated against `outputSchema`. */
39
+ generate<S extends z.ZodType>(request: z.input<typeof llmRequest>, outputSchema: S, options?: CallOptions & {
40
+ idempotencyKey?: string;
41
+ }): Promise<GenerateResult<z.output<S>>>;
42
+ /** The raw response, for an `llm` profile that answers in free text. */
43
+ generateText(request: z.input<typeof llmRequest>, options?: CallOptions & {
44
+ idempotencyKey?: string;
45
+ }): Promise<LlmResponse>;
46
+ };
47
+ runs: {
48
+ create(input: CreateRunInput, options?: CallOptions): Promise<CreateRunResult>;
49
+ get(id: string, options?: CallOptions): Promise<Run>;
50
+ usage(id: string, options?: CallOptions): Promise<RunUsageResponse>;
51
+ /**
52
+ * Every event of a run from `after` (exclusive), in order, once each. Reconnects with
53
+ * `Last-Event-ID` when the connection drops and ends after the terminal event.
54
+ */
55
+ stream(id: string, options?: CallOptions & {
56
+ after?: number;
57
+ }): AsyncGenerator<RunEvent>;
58
+ /** Always resolves with the run: cancelling a terminal run returns it unchanged. */
59
+ cancel(id: string, reason: string, options?: CallOptions): Promise<Run>;
60
+ };
61
+ profiles: {
62
+ get(name: string, options?: CallOptions): Promise<ProfileSummary>;
63
+ };
64
+ }
65
+ export declare function createFlytebotClient(options: FlytebotClientOptions): FlytebotClient;
66
+ export {};
@@ -0,0 +1,377 @@
1
+ import { IDEMPOTENCY_KEY_HEADER, IDEMPOTENT_REPLAYED_HEADER, cancelRunRequest, createRunRequest, createRunResponse, idempotencyKey, llmRequest, llmResponse, profileSummary, run, runEvent, runUsageResponse, } from "@flytedesk/flytebot-contracts";
2
+ import { GoogleAuth } from "google-auth-library";
3
+ import { FlytebotError, errorFromResponse } from "./error.js";
4
+ import { parseSse } from "./sse.js";
5
+ const MAX_RETRY_WAIT_MS = 30_000;
6
+ function aborted(cause) {
7
+ return new FlytebotError({
8
+ code: "aborted",
9
+ message: "The Flytebot request was aborted",
10
+ httpStatus: null,
11
+ retryable: false,
12
+ requestId: null,
13
+ cause,
14
+ });
15
+ }
16
+ function sleep(ms, signal) {
17
+ return new Promise((resolve, reject) => {
18
+ if (signal?.aborted)
19
+ return reject(aborted());
20
+ const timer = setTimeout(() => {
21
+ signal?.removeEventListener("abort", onAbort);
22
+ resolve();
23
+ }, ms);
24
+ const onAbort = () => {
25
+ clearTimeout(timer);
26
+ reject(aborted());
27
+ };
28
+ signal?.addEventListener("abort", onAbort, { once: true });
29
+ });
30
+ }
31
+ function defaultIdToken() {
32
+ const auth = new GoogleAuth();
33
+ return async (audience) => {
34
+ const client = await auth.getIdTokenClient(audience);
35
+ return client.idTokenProvider.fetchIdToken(audience);
36
+ };
37
+ }
38
+ function invalidResponse(what, error, status, headers) {
39
+ return new FlytebotError({
40
+ code: "invalid_response",
41
+ message: `Flytebot ${what} response does not match the contract: ${error.message}`,
42
+ httpStatus: status,
43
+ retryable: false,
44
+ requestId: headers.get("x-request-id"),
45
+ cause: error,
46
+ });
47
+ }
48
+ function invalidRequest(what, error) {
49
+ return new FlytebotError({
50
+ code: "invalid_request",
51
+ message: `Invalid Flytebot ${what} request: ${error.message}`,
52
+ httpStatus: null,
53
+ retryable: false,
54
+ requestId: null,
55
+ cause: error,
56
+ });
57
+ }
58
+ export function createFlytebotClient(options) {
59
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
60
+ const audience = new URL(baseUrl).origin;
61
+ const getToken = options.idToken ?? defaultIdToken();
62
+ const fetchImpl = options.fetch ?? fetch;
63
+ const retryBaseDelayMs = options.retryBaseDelayMs ?? 250;
64
+ const streamIdleTimeoutMs = options.streamIdleTimeoutMs ?? 45_000;
65
+ /** One HTTP attempt. Throws a FlytebotError for anything but a 2xx. */
66
+ async function attempt(spec, controller, readBody) {
67
+ const { signal } = spec;
68
+ if (signal?.aborted)
69
+ throw aborted();
70
+ const onAbort = () => controller.abort();
71
+ signal?.addEventListener("abort", onAbort, { once: true });
72
+ let timedOut = false;
73
+ const timer = setTimeout(() => {
74
+ timedOut = true;
75
+ controller.abort();
76
+ }, options.timeoutMs);
77
+ const classify = (cause) => {
78
+ if (signal?.aborted)
79
+ return aborted(cause);
80
+ return new FlytebotError({
81
+ code: timedOut ? "timeout" : "network_error",
82
+ message: timedOut
83
+ ? `Flytebot did not answer within ${options.timeoutMs} ms`
84
+ : `Flytebot request failed: ${cause instanceof Error ? cause.message : String(cause)}`,
85
+ httpStatus: null,
86
+ retryable: true,
87
+ requestId: null,
88
+ cause,
89
+ });
90
+ };
91
+ try {
92
+ let token;
93
+ try {
94
+ token = await getToken(audience);
95
+ }
96
+ catch (cause) {
97
+ if (signal?.aborted || timedOut)
98
+ throw classify(cause);
99
+ throw new FlytebotError({
100
+ code: "unauthenticated",
101
+ message: `Could not get a Google ID token for ${audience}: ${cause instanceof Error ? cause.message : String(cause)}`,
102
+ httpStatus: null,
103
+ retryable: false,
104
+ requestId: null,
105
+ cause,
106
+ });
107
+ }
108
+ let res;
109
+ try {
110
+ res = await fetchImpl(`${baseUrl}${spec.path}`, {
111
+ method: spec.method,
112
+ headers: {
113
+ authorization: `Bearer ${token}`,
114
+ accept: spec.body === undefined ? "*/*" : "application/json",
115
+ ...(spec.body === undefined
116
+ ? {}
117
+ : { "content-type": "application/json" }),
118
+ ...spec.headers,
119
+ },
120
+ body: spec.body === undefined ? undefined : JSON.stringify(spec.body),
121
+ signal: controller.signal,
122
+ });
123
+ }
124
+ catch (cause) {
125
+ throw classify(cause);
126
+ }
127
+ let payload;
128
+ if (!res.ok || readBody) {
129
+ let text;
130
+ try {
131
+ text = await res.text();
132
+ }
133
+ catch (cause) {
134
+ throw classify(cause);
135
+ }
136
+ if (text !== "") {
137
+ try {
138
+ payload = JSON.parse(text);
139
+ }
140
+ catch {
141
+ payload = undefined;
142
+ }
143
+ }
144
+ }
145
+ if (!res.ok)
146
+ throw errorFromResponse(res.status, res.headers, payload);
147
+ return { res, payload };
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ signal?.removeEventListener("abort", onAbort);
152
+ }
153
+ }
154
+ async function withRetries(signal, fn) {
155
+ for (let tries = 0;; tries++) {
156
+ try {
157
+ return await fn();
158
+ }
159
+ catch (error) {
160
+ if (!(error instanceof FlytebotError) ||
161
+ !error.retryable ||
162
+ tries >= options.retries) {
163
+ throw error;
164
+ }
165
+ const backoff = retryBaseDelayMs * 2 ** tries * (0.5 + Math.random() / 2);
166
+ await sleep(Math.min(error.retryAfterMs ?? backoff, MAX_RETRY_WAIT_MS), signal);
167
+ }
168
+ }
169
+ }
170
+ async function json(what, spec, schema) {
171
+ return withRetries(spec.signal, async () => {
172
+ const { res, payload } = await attempt(spec, new AbortController(), true);
173
+ const parsed = schema.safeParse(payload);
174
+ if (!parsed.success) {
175
+ throw invalidResponse(what, parsed.error, res.status, res.headers);
176
+ }
177
+ return {
178
+ data: parsed.data,
179
+ replayed: res.headers.get(IDEMPOTENT_REPLAYED_HEADER) === "true",
180
+ };
181
+ });
182
+ }
183
+ function checkedKey(key) {
184
+ const parsed = idempotencyKey.safeParse(key);
185
+ if (!parsed.success)
186
+ throw invalidRequest("idempotency key", parsed.error);
187
+ return parsed.data;
188
+ }
189
+ async function llmCall(request, callOptions) {
190
+ const body = llmRequest.safeParse(request);
191
+ if (!body.success)
192
+ throw invalidRequest("llm", body.error);
193
+ const key = callOptions?.idempotencyKey;
194
+ const { data } = await json("llm", {
195
+ method: "POST",
196
+ path: "/v1/llm",
197
+ body: body.data,
198
+ headers: key === undefined ? {} : { [IDEMPOTENCY_KEY_HEADER]: checkedKey(key) },
199
+ signal: callOptions?.signal,
200
+ }, llmResponse);
201
+ return data;
202
+ }
203
+ async function* stream(id, streamOptions) {
204
+ const signal = streamOptions?.signal;
205
+ let lastSeq = streamOptions?.after ?? 0;
206
+ let failures = 0;
207
+ for (;;) {
208
+ const controller = new AbortController();
209
+ const onAbort = () => controller.abort();
210
+ signal?.addEventListener("abort", onAbort, { once: true });
211
+ let idle;
212
+ const armIdle = () => {
213
+ clearTimeout(idle);
214
+ idle = setTimeout(() => controller.abort(), streamIdleTimeoutMs);
215
+ };
216
+ let progressed = false;
217
+ try {
218
+ let res;
219
+ try {
220
+ ({ res } = await attempt({
221
+ method: "GET",
222
+ path: `/v1/runs/${encodeURIComponent(id)}/events`,
223
+ headers: {
224
+ accept: "text/event-stream",
225
+ ...(lastSeq > 0 ? { "last-event-id": String(lastSeq) } : {}),
226
+ },
227
+ signal,
228
+ }, controller, false));
229
+ }
230
+ catch (error) {
231
+ if (!(error instanceof FlytebotError) || !error.retryable || failures >= options.retries) {
232
+ throw error;
233
+ }
234
+ failures++;
235
+ await sleep(Math.min(error.retryAfterMs ?? retryBaseDelayMs * 2 ** (failures - 1), MAX_RETRY_WAIT_MS), signal);
236
+ continue;
237
+ }
238
+ if (res.body === null) {
239
+ throw new FlytebotError({
240
+ code: "invalid_response",
241
+ message: "Flytebot event stream has no body",
242
+ httpStatus: res.status,
243
+ retryable: false,
244
+ requestId: res.headers.get("x-request-id"),
245
+ });
246
+ }
247
+ armIdle();
248
+ try {
249
+ for await (const frame of parseSse(res.body)) {
250
+ armIdle();
251
+ let raw;
252
+ try {
253
+ raw = JSON.parse(frame.data);
254
+ }
255
+ catch (cause) {
256
+ throw new FlytebotError({
257
+ code: "invalid_response",
258
+ message: "Flytebot event is not JSON",
259
+ httpStatus: res.status,
260
+ retryable: false,
261
+ requestId: res.headers.get("x-request-id"),
262
+ cause,
263
+ });
264
+ }
265
+ const parsed = runEvent.safeParse(raw);
266
+ if (!parsed.success) {
267
+ throw invalidResponse("event", parsed.error, res.status, res.headers);
268
+ }
269
+ const event = parsed.data;
270
+ if (event.seq <= lastSeq)
271
+ continue;
272
+ if (event.seq !== lastSeq + 1)
273
+ break; // a gap: reconnect from lastSeq
274
+ lastSeq = event.seq;
275
+ progressed = true;
276
+ yield event;
277
+ if (event.type === "terminal")
278
+ return;
279
+ }
280
+ }
281
+ catch (error) {
282
+ if (error instanceof FlytebotError)
283
+ throw error;
284
+ if (signal?.aborted)
285
+ throw aborted(error);
286
+ // the connection dropped or went idle: fall through to reconnect
287
+ }
288
+ if (signal?.aborted)
289
+ throw aborted();
290
+ failures = progressed ? 0 : failures + 1;
291
+ if (failures > options.retries) {
292
+ throw new FlytebotError({
293
+ code: "network_error",
294
+ message: `Flytebot event stream for ${id} ended without a terminal event after ${failures} reconnects without progress`,
295
+ httpStatus: null,
296
+ retryable: true,
297
+ requestId: null,
298
+ });
299
+ }
300
+ if (!progressed) {
301
+ await sleep(retryBaseDelayMs * 2 ** (failures - 1), signal);
302
+ }
303
+ }
304
+ finally {
305
+ clearTimeout(idle);
306
+ signal?.removeEventListener("abort", onAbort);
307
+ controller.abort();
308
+ }
309
+ }
310
+ }
311
+ return {
312
+ llm: {
313
+ async generate(request, outputSchema, callOptions) {
314
+ const data = await llmCall(request, callOptions);
315
+ const output = outputSchema.safeParse(data.output);
316
+ if (!output.success) {
317
+ throw new FlytebotError({
318
+ code: "output_invalid",
319
+ message: `Flytebot llm output does not match the caller's schema: ${output.error.message}`,
320
+ httpStatus: null,
321
+ retryable: false,
322
+ requestId: null,
323
+ cause: output.error,
324
+ });
325
+ }
326
+ return { ...data, output: output.data };
327
+ },
328
+ async generateText(request, callOptions) {
329
+ return llmCall(request, callOptions);
330
+ },
331
+ },
332
+ runs: {
333
+ async create(input, callOptions) {
334
+ const { idempotencyKey: key, ...rest } = input;
335
+ const body = createRunRequest.safeParse(rest);
336
+ if (!body.success)
337
+ throw invalidRequest("run", body.error);
338
+ const { data, replayed } = await json("run", {
339
+ method: "POST",
340
+ path: "/v1/runs",
341
+ body: body.data,
342
+ headers: { [IDEMPOTENCY_KEY_HEADER]: checkedKey(key) },
343
+ signal: callOptions?.signal,
344
+ }, createRunResponse);
345
+ return { ...data, replayed };
346
+ },
347
+ async get(id, callOptions) {
348
+ const { data } = await json("run", { method: "GET", path: `/v1/runs/${encodeURIComponent(id)}`, signal: callOptions?.signal }, run);
349
+ return data;
350
+ },
351
+ async usage(id, callOptions) {
352
+ const { data } = await json("run usage", { method: "GET", path: `/v1/runs/${encodeURIComponent(id)}/usage`, signal: callOptions?.signal }, runUsageResponse);
353
+ return data;
354
+ },
355
+ stream,
356
+ async cancel(id, reason, callOptions) {
357
+ const body = cancelRunRequest.safeParse({ reason });
358
+ if (!body.success)
359
+ throw invalidRequest("cancel", body.error);
360
+ const { data } = await json("run", {
361
+ method: "POST",
362
+ path: `/v1/runs/${encodeURIComponent(id)}/cancel`,
363
+ body: body.data,
364
+ signal: callOptions?.signal,
365
+ }, run);
366
+ return data;
367
+ },
368
+ },
369
+ profiles: {
370
+ async get(name, callOptions) {
371
+ const { data } = await json("profile", { method: "GET", path: `/v1/profiles/${encodeURIComponent(name)}`, signal: callOptions?.signal }, profileSummary);
372
+ return data;
373
+ },
374
+ },
375
+ };
376
+ }
377
+ //# sourceMappingURL=client.js.map