@rungent/react 0.0.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1167 @@
1
+ import * as z from "zod";
2
+ import { EventType } from "@ag-ui/core";
3
+ // ../rungent/src/spec/catalog.ts
4
+ /**
5
+ * The rungent catalog: the `x-rungent` OpenAPI extension and the operations derived from it.
6
+ * See spec/catalog.md.
7
+ */
8
+ const OPERATION_NAME = /^[a-z][a-z0-9_]{0,63}$/;
9
+ const operationName$1 = z.string().regex(OPERATION_NAME);
10
+ const productPath = z.string().regex(/^\/(?!\/)/, "must start with a single /");
11
+ const Effect = z.enum([
12
+ "read",
13
+ "create",
14
+ "update",
15
+ "delete",
16
+ "external"
17
+ ]);
18
+ const Approval = z.enum(["never", "always"]);
19
+ const Surface = z.enum([
20
+ "agent",
21
+ "mcp",
22
+ "cli"
23
+ ]);
24
+ const Role = z.enum([
25
+ "identity",
26
+ "search",
27
+ "form"
28
+ ]);
29
+ const Confirmation = z.strictObject({
30
+ title: z.string().min(1).max(200),
31
+ target: z.string().min(1).max(200).optional(),
32
+ fields: z.array(z.strictObject({
33
+ key: z.string().min(1),
34
+ label: z.string().min(1),
35
+ values: z.record(z.string(), z.string()).optional()
36
+ })).optional(),
37
+ lookup: z.strictObject({
38
+ path: productPath,
39
+ labelPath: z.string().min(1)
40
+ }).optional(),
41
+ risk: z.enum([
42
+ "low",
43
+ "medium",
44
+ "high"
45
+ ]).optional(),
46
+ costHint: z.string().min(1).max(200).optional()
47
+ });
48
+ const Next = z.strictObject({
49
+ op: operationName$1,
50
+ arguments: z.record(z.string(), z.string().min(1)).optional(),
51
+ argumentsFrom: z.string().min(1).optional(),
52
+ when: z.record(z.string(), z.unknown()).optional()
53
+ });
54
+ z.strictObject({
55
+ name: operationName$1,
56
+ title: z.string().min(1).max(80).optional(),
57
+ description: z.string().min(1).max(500).optional(),
58
+ effect: Effect.optional(),
59
+ approval: Approval.optional(),
60
+ role: Role.optional(),
61
+ surfaces: z.array(Surface).optional(),
62
+ confirmation: Confirmation.optional(),
63
+ form: operationName$1.optional(),
64
+ resolve: z.record(z.string(), z.strictObject({
65
+ op: operationName$1,
66
+ key: z.string().min(1).optional()
67
+ })).optional(),
68
+ next: Next.optional(),
69
+ open: productPath.optional(),
70
+ redact: z.array(z.string().min(1)).optional(),
71
+ repeatable: z.boolean().optional(),
72
+ timeoutSeconds: z.number().positive().max(3600).optional(),
73
+ cli: z.strictObject({
74
+ command: z.string().regex(/^[a-z][a-z0-9-]*( [a-z][a-z0-9-]*)*$/),
75
+ args: z.array(z.string().min(1)).optional()
76
+ }).optional()
77
+ }).meta({
78
+ id: "x-rungent",
79
+ title: "x-rungent",
80
+ description: "rungent operation metadata on an OpenAPI 3.1 operation."
81
+ });
82
+ z.object({
83
+ subject: z.string().min(1),
84
+ tenant: z.string().min(1).optional(),
85
+ name: z.string().min(1).optional(),
86
+ locale: z.string().min(2).optional(),
87
+ scopes: z.array(z.string().min(1)).optional()
88
+ }).meta({
89
+ id: "identity",
90
+ title: "Identity",
91
+ description: "Answer of the role: identity operation."
92
+ });
93
+ // ../rungent/src/spec/search.ts
94
+ /**
95
+ * Search: the source contract and federation. See spec/search.md.
96
+ */
97
+ const SearchHit = z.strictObject({
98
+ type: z.string().regex(/^[a-z][a-z0-9_.-]{0,31}$/),
99
+ id: z.string().min(1),
100
+ title: z.string().min(1),
101
+ excerpt: z.string().max(300).optional(),
102
+ url: z.string().regex(/^(\/(?!\/)|https?:\/\/)/, "must be a product path or an http(s) URL"),
103
+ updatedAt: z.iso.datetime({ offset: true }).optional(),
104
+ content: z.string().max(4e3).optional()
105
+ }).meta({
106
+ id: "search-hit",
107
+ title: "SearchHit"
108
+ });
109
+ /** A hit as users see it: `content` is for the model only. */
110
+ const PublicHit = SearchHit.omit({ content: true });
111
+ z.strictObject({ hits: z.array(SearchHit).max(50) }).meta({
112
+ id: "search-response",
113
+ title: "Search source response"
114
+ });
115
+ /** A hit of federated search, as `GET /rungent/v0/search` answers it: no `content`. */
116
+ const FederatedHit = PublicHit.extend({ source: z.string().regex(OPERATION_NAME) });
117
+ const SearchFailure = z.strictObject({
118
+ source: z.string().regex(OPERATION_NAME),
119
+ code: z.string().regex(/^(timeout|invalid_response|http_\d{3})$/)
120
+ });
121
+ z.strictObject({
122
+ hits: z.array(FederatedHit),
123
+ failed: z.array(SearchFailure)
124
+ }).meta({
125
+ id: "federated-search-response",
126
+ title: "Federated search response"
127
+ });
128
+ // ../rungent/src/spec/protocol.ts
129
+ /**
130
+ * rungent's AG-UI 1.0 profile: interrupts, forms, tool metadata and custom events.
131
+ * See spec/protocol.md.
132
+ */
133
+ const API_PREFIX = "/rungent/v0";
134
+ /** Key under which rungent's data sits in AG-UI `metadata`. */
135
+ const METADATA_KEY = "rungent";
136
+ /** `metadata.rungent` on every event. `seq` increases per thread and is the SSE id. */
137
+ const EventMeta = z.strictObject({ seq: z.int().positive() });
138
+ const InterruptReason = {
139
+ approval: "rungent:approval",
140
+ input: "rungent:input",
141
+ form: "rungent:form",
142
+ task: "rungent:task"
143
+ };
144
+ z.enum([
145
+ "model_unavailable",
146
+ "max_steps",
147
+ "open_interrupts",
148
+ "history_conflict",
149
+ "invalid_interaction",
150
+ "internal"
151
+ ]);
152
+ const ToolErrorCode = z.string().regex(/^(invalid_arguments|unresolved_reference|repeated_call|already_attempted|not_executed|credential_expired|timeout|http_\d{3})$/);
153
+ const operationName = z.string().regex(OPERATION_NAME);
154
+ /**
155
+ * `TOOL_CALL_START.metadata.rungent`: the call's operation, beside the event's `seq` (which a
156
+ * reader may have taken out already). Built-in tools (`search`, `request_input`) use their own
157
+ * name as op.
158
+ */
159
+ const ToolCallMeta = EventMeta.partial().extend({
160
+ op: operationName,
161
+ title: z.string().min(1),
162
+ effect: Effect
163
+ });
164
+ /** `TOOL_CALL_RESULT.metadata.rungent`: the call's outcome, beside the event's `seq`. */
165
+ const ToolResultMeta = EventMeta.partial().extend({
166
+ status: z.enum(["succeeded", "failed"]),
167
+ error: z.strictObject({
168
+ code: ToolErrorCode,
169
+ message: z.string()
170
+ }).optional(),
171
+ deduplicated: z.boolean().optional()
172
+ });
173
+ const ApprovalImpact = z.strictObject({
174
+ title: z.string().min(1),
175
+ target: z.string().nullable(),
176
+ effect: Effect,
177
+ risk: z.enum([
178
+ "low",
179
+ "medium",
180
+ "high"
181
+ ]).nullable(),
182
+ costHint: z.string().nullable(),
183
+ changes: z.array(z.string())
184
+ });
185
+ /** `Interrupt.metadata.rungent` for `rungent:approval`. */
186
+ const ApprovalInterruptMeta = z.strictObject({
187
+ op: operationName,
188
+ arguments: z.record(z.string(), z.unknown()),
189
+ argsHash: z.string().min(43),
190
+ impact: ApprovalImpact
191
+ }).meta({
192
+ id: "approval-interrupt",
193
+ title: "Approval interrupt metadata"
194
+ });
195
+ z.strictObject({ approved: z.boolean() });
196
+ z.strictObject({ argsHash: z.string().min(43) });
197
+ const FormOption = z.strictObject({
198
+ id: z.string().min(1),
199
+ label: z.string().min(1),
200
+ description: z.string().optional(),
201
+ recommended: z.boolean().optional()
202
+ });
203
+ const FormQuestion = z.discriminatedUnion("kind", [z.strictObject({
204
+ id: z.string().min(1),
205
+ prompt: z.string().min(1),
206
+ kind: z.literal("text"),
207
+ required: z.boolean(),
208
+ placeholder: z.string().optional(),
209
+ default: z.string().optional()
210
+ }), z.strictObject({
211
+ id: z.string().min(1),
212
+ prompt: z.string().min(1),
213
+ kind: z.literal("choice"),
214
+ required: z.boolean(),
215
+ options: z.array(FormOption).min(1),
216
+ multiple: z.boolean().optional(),
217
+ allowCustom: z.boolean().optional(),
218
+ default: z.union([z.string(), z.array(z.string())]).optional()
219
+ })]);
220
+ const Form = z.strictObject({
221
+ prompt: z.string().min(1),
222
+ questions: z.array(FormQuestion).min(1).max(24)
223
+ }).refine((form) => new Set(form.questions.map((question) => question.id)).size === form.questions.length, "question ids must be unique").meta({
224
+ id: "form",
225
+ title: "Form"
226
+ });
227
+ const ChoiceAnswer = z.strictObject({
228
+ selected: z.array(z.string()),
229
+ custom: z.string().optional()
230
+ });
231
+ z.strictObject({ answers: z.record(z.string(), z.union([z.string(), ChoiceAnswer])) }).meta({
232
+ id: "form-answers",
233
+ title: "Form resume payload"
234
+ });
235
+ /** `Interrupt.metadata.rungent` for `rungent:input`: the questions of `request_input`. */
236
+ const InputInterruptMeta = z.strictObject({ form: Form });
237
+ /** A problem with one argument of a submitted host form, by its dotted path. */
238
+ const FormIssue = z.strictObject({
239
+ path: z.string(),
240
+ message: z.string().min(1)
241
+ });
242
+ /**
243
+ * `Interrupt.metadata.rungent` for `rungent:form`: the host form of an operation. `arguments` are the
244
+ * call's arguments so far, which the form starts from; `form` is the host's generic form, for a
245
+ * client that has no form of its own for `op`; `issues` explain why a submission was refused.
246
+ */
247
+ const FormInterruptMeta = z.strictObject({
248
+ op: operationName,
249
+ arguments: z.record(z.string(), z.unknown()),
250
+ form: Form,
251
+ issues: z.array(FormIssue).optional()
252
+ }).meta({
253
+ id: "form-interrupt",
254
+ title: "Host form interrupt metadata"
255
+ });
256
+ z.strictObject({ arguments: z.record(z.string(), z.unknown()) }).meta({
257
+ id: "form-submission",
258
+ title: "Host form resume payload"
259
+ });
260
+ function setPath(target, path, value) {
261
+ const segments = path.split(".");
262
+ let current = target;
263
+ for (const segment of segments.slice(0, -1)) {
264
+ const next = current[segment];
265
+ if (typeof next !== "object" || next === null || Array.isArray(next)) current[segment] = {};
266
+ current = current[segment];
267
+ }
268
+ current[segments[segments.length - 1]] = value;
269
+ }
270
+ /**
271
+ * The arguments a generic host form submits: the call's arguments with each answer set at its
272
+ * question's dotted path. Empty answers leave the argument as it was.
273
+ */
274
+ function answersToArguments(form, args, answers) {
275
+ const out = structuredClone(args);
276
+ for (const question of form.questions) {
277
+ const answer = answers[question.id];
278
+ if (answer === void 0) continue;
279
+ const multiple = question.kind === "choice" && question.multiple === true;
280
+ const values = typeof answer === "string" ? [answer] : [...answer.selected, ...answer.custom?.trim() ? [answer.custom.trim()] : []];
281
+ const value = multiple ? values : values[0];
282
+ if (value === void 0 || value === "") continue;
283
+ setPath(out, question.id, value);
284
+ }
285
+ return out;
286
+ }
287
+ /** `Interrupt.metadata.rungent` for `rungent:task`. */
288
+ const TaskInterruptMeta = z.strictObject({
289
+ taskId: z.string().min(1),
290
+ op: operationName
291
+ });
292
+ /** Validates a form answer. An empty list means it is acceptable. */
293
+ function checkAnswers(form, answers) {
294
+ const issues = [];
295
+ const questions = new Map(form.questions.map((question) => [question.id, question]));
296
+ for (const id of Object.keys(answers)) if (!questions.has(id)) issues.push({
297
+ question: id,
298
+ message: "unknown question"
299
+ });
300
+ for (const question of form.questions) {
301
+ const answer = answers[question.id];
302
+ if (question.kind === "text") {
303
+ if (answer !== void 0 && typeof answer !== "string") issues.push({
304
+ question: question.id,
305
+ message: "expected text"
306
+ });
307
+ else if (question.required && !answer?.trim()) issues.push({
308
+ question: question.id,
309
+ message: "required"
310
+ });
311
+ continue;
312
+ }
313
+ if (answer === void 0) {
314
+ if (question.required) issues.push({
315
+ question: question.id,
316
+ message: "required"
317
+ });
318
+ continue;
319
+ }
320
+ if (typeof answer === "string") {
321
+ issues.push({
322
+ question: question.id,
323
+ message: "expected a choice"
324
+ });
325
+ continue;
326
+ }
327
+ const known = new Set(question.options.map((option) => option.id));
328
+ const unknown = answer.selected.filter((id) => !known.has(id));
329
+ if (unknown.length > 0) issues.push({
330
+ question: question.id,
331
+ message: `unknown options: ${unknown.join(", ")}`
332
+ });
333
+ const custom = answer.custom?.trim();
334
+ if (custom && !question.allowCustom) issues.push({
335
+ question: question.id,
336
+ message: "custom answers are not allowed"
337
+ });
338
+ const count = answer.selected.length + (custom ? 1 : 0);
339
+ if (count === 0 && question.required) issues.push({
340
+ question: question.id,
341
+ message: "required"
342
+ });
343
+ else if (count > 1 && !question.multiple) issues.push({
344
+ question: question.id,
345
+ message: "only one answer is allowed"
346
+ });
347
+ }
348
+ return issues;
349
+ }
350
+ const CustomEvents = {
351
+ "rungent.ui.open": z.strictObject({ path: z.string().regex(/^\/(?!\/)/) }),
352
+ "rungent.citation": z.strictObject({
353
+ messageId: z.string().min(1),
354
+ /** Each hit the answer cites, under the number `n` it wrote as `[n]`, by `n`. */
355
+ citations: z.array(z.strictObject({
356
+ n: z.int().positive(),
357
+ hit: PublicHit
358
+ })).min(1)
359
+ }),
360
+ "rungent.context": z.strictObject({
361
+ usedTokens: z.int().nonnegative(),
362
+ budgetTokens: z.int().positive(),
363
+ source: z.enum(["estimated", "provider"])
364
+ }),
365
+ "rungent.model.retry": z.strictObject({
366
+ step: z.int().positive(),
367
+ /** The attempt on `endpoint` that failed, and how many that endpoint gets. */
368
+ attempt: z.int().positive(),
369
+ maxAttempts: z.int().positive(),
370
+ reason: z.string().min(1),
371
+ /** The id of the chain endpoint that failed. */
372
+ endpoint: z.string().min(1),
373
+ /** True when the next attempt goes to another endpoint: this one rests. */
374
+ fallback: z.boolean()
375
+ }),
376
+ "rungent.message.discard": z.strictObject({ messageId: z.string().min(1) }),
377
+ "rungent.task": z.strictObject({
378
+ taskId: z.string().min(1),
379
+ status: z.enum([
380
+ "running",
381
+ "succeeded",
382
+ "failed",
383
+ "cancelled"
384
+ ]),
385
+ message: z.string().optional()
386
+ })
387
+ };
388
+ const ProgressContent = z.strictObject({ message: z.string().min(1) });
389
+ const PartSource = z.discriminatedUnion("type", [z.strictObject({
390
+ type: z.literal("url"),
391
+ value: z.string().min(1),
392
+ mimeType: z.string().optional()
393
+ }), z.strictObject({
394
+ type: z.literal("data"),
395
+ value: z.string().min(1),
396
+ mimeType: z.string().min(1)
397
+ })]);
398
+ const partMetadata = z.looseObject({ rungent: z.strictObject({ name: z.string().max(255).optional() }).optional() }).optional();
399
+ /** One content part of a user message: AG-UI text, image or document. */
400
+ const UserContentPart = z.discriminatedUnion("type", [
401
+ z.strictObject({
402
+ type: z.literal("text"),
403
+ id: z.string().optional(),
404
+ text: z.string(),
405
+ metadata: partMetadata
406
+ }),
407
+ z.strictObject({
408
+ type: z.literal("image"),
409
+ id: z.string().optional(),
410
+ source: PartSource,
411
+ metadata: partMetadata
412
+ }),
413
+ z.strictObject({
414
+ type: z.literal("document"),
415
+ id: z.string().optional(),
416
+ source: PartSource,
417
+ metadata: partMetadata
418
+ })
419
+ ]);
420
+ z.union([z.string(), z.array(UserContentPart).min(1).refine((parts) => parts.filter((part) => part.type !== "text").length <= 10, `at most 10 images and documents`)]);
421
+ z.strictObject({
422
+ description: z.string().max(200),
423
+ value: z.string()
424
+ });
425
+ z.strictObject({
426
+ instructions: z.string().max(2e4).optional(),
427
+ input: z.string().min(1).max(2e5),
428
+ /** A JSON Schema the answer must satisfy; the answer is then `{object}`. */
429
+ schema: z.record(z.string(), z.unknown()).optional(),
430
+ maxOutputTokens: z.int().positive().max(64e3).optional()
431
+ }).meta({
432
+ id: "generate-request",
433
+ title: "Generate request"
434
+ });
435
+ z.union([z.strictObject({ text: z.string() }), z.strictObject({ object: z.unknown() })]).meta({
436
+ id: "generate-response",
437
+ title: "Generate response"
438
+ });
439
+ const FeedbackRating = z.enum(["up", "down"]);
440
+ z.strictObject({
441
+ rating: FeedbackRating,
442
+ comment: z.string().trim().max(2e3).optional()
443
+ }).meta({
444
+ id: "feedback-input",
445
+ title: "Feedback"
446
+ });
447
+ z.strictObject({
448
+ threadId: z.string().min(1),
449
+ messageId: z.string().min(1),
450
+ rating: FeedbackRating,
451
+ comment: z.string().optional(),
452
+ subject: z.string().min(1),
453
+ createdAt: z.iso.datetime({ offset: true })
454
+ }).meta({
455
+ id: "feedback-item",
456
+ title: "Feedback item"
457
+ });
458
+ // src/client/sse.ts
459
+ var RungentProtocolError = class extends Error {
460
+ name = "RungentProtocolError";
461
+ };
462
+ /** Splits a byte stream into server-sent-event frames (WHATWG event-stream format). */
463
+ async function* readSse(body) {
464
+ const reader = body.getReader();
465
+ const decoder = new TextDecoder();
466
+ let buffer = "";
467
+ let data = [];
468
+ let id;
469
+ let retry;
470
+ try {
471
+ while (true) {
472
+ const { value, done } = await reader.read();
473
+ if (done) return;
474
+ buffer += decoder.decode(value, { stream: true });
475
+ let newline = buffer.search(/\r\n|\r|\n/);
476
+ while (newline !== -1 && !(newline === buffer.length - 1 && buffer.endsWith("\r"))) {
477
+ const line = buffer.slice(0, newline);
478
+ buffer = buffer.slice(newline + (buffer.startsWith("\r\n", newline) ? 2 : 1));
479
+ if (line === "") {
480
+ if (data.length > 0 || retry !== void 0) yield {
481
+ data: data.join("\n"),
482
+ ...id === void 0 ? {} : { id },
483
+ ...retry === void 0 ? {} : { retry }
484
+ };
485
+ data = [];
486
+ id = void 0;
487
+ retry = void 0;
488
+ } else if (!line.startsWith(":")) {
489
+ const colon = line.indexOf(":");
490
+ const field = colon === -1 ? line : line.slice(0, colon);
491
+ let text = colon === -1 ? "" : line.slice(colon + 1);
492
+ if (text.startsWith(" ")) text = text.slice(1);
493
+ if (field === "data") data.push(text);
494
+ else if (field === "id") id = text;
495
+ else if (field === "retry" && /^\d+$/.test(text)) retry = Number(text);
496
+ }
497
+ newline = buffer.search(/\r\n|\r|\n/);
498
+ }
499
+ }
500
+ } finally {
501
+ await reader.cancel().catch(() => {});
502
+ }
503
+ }
504
+ /** Parses a frame's data as a rungent event, checking `metadata.rungent.seq` against the SSE id. */
505
+ function parseEvent(frame) {
506
+ let event;
507
+ try {
508
+ event = JSON.parse(frame.data);
509
+ } catch {
510
+ throw new RungentProtocolError("event data is not JSON");
511
+ }
512
+ if (typeof event !== "object" || event === null || typeof event.type !== "string") throw new RungentProtocolError("event has no type");
513
+ const seq = event.metadata?.rungent?.seq;
514
+ if (typeof seq !== "number" || !Number.isInteger(seq) || seq < 1) throw new RungentProtocolError(`${event.type} has no metadata.rungent.seq`);
515
+ if (frame.id !== void 0 && frame.id !== String(seq)) throw new RungentProtocolError(`SSE id ${frame.id} does not match seq ${seq}`);
516
+ return event;
517
+ }
518
+ function seqOf(event) {
519
+ return event.metadata.rungent.seq;
520
+ }
521
+ // src/client/client.ts
522
+ var RungentRequestError = class extends Error {
523
+ status;
524
+ body;
525
+ name = "RungentRequestError";
526
+ constructor(status, body) {
527
+ super(`rungent request failed (${status})`);
528
+ this.status = status;
529
+ this.body = body;
530
+ }
531
+ };
532
+ const DEFAULT_RETRY_MS = 1e3;
533
+ const MAX_RETRY_MS = 3e4;
534
+ function sleep(ms, signal) {
535
+ return new Promise((resolve, reject) => {
536
+ if (signal?.aborted) return reject(signal.reason);
537
+ const timer = setTimeout(() => {
538
+ signal?.removeEventListener("abort", abort);
539
+ resolve();
540
+ }, ms);
541
+ const abort = () => {
542
+ clearTimeout(timer);
543
+ reject(signal?.reason);
544
+ };
545
+ signal?.addEventListener("abort", abort, { once: true });
546
+ });
547
+ }
548
+ /** Whether a failed `follow` request is worth retrying. */
549
+ function transient(error) {
550
+ return !(error instanceof RungentRequestError) || error.status === 408 || error.status === 429 || error.status >= 500;
551
+ }
552
+ function createClient(options = {}) {
553
+ const baseUrl = (options.baseUrl ?? "").replace(/\/+$/, "");
554
+ const base = `${baseUrl}${API_PREFIX}`;
555
+ const fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
556
+ async function request(path, init = {}) {
557
+ const headers = new Headers(await options.headers?.());
558
+ if (init.body !== void 0) headers.set("Content-Type", "application/json");
559
+ new Headers(init.headers).forEach((value, key) => {
560
+ headers.set(key, value);
561
+ });
562
+ const response = await fetcher(`${base}${path}`, {
563
+ ...init,
564
+ headers
565
+ });
566
+ if (!response.ok) {
567
+ const text = await response.text().catch(() => "");
568
+ let body = text;
569
+ try {
570
+ body = JSON.parse(text);
571
+ } catch {}
572
+ throw new RungentRequestError(response.status, body);
573
+ }
574
+ return response;
575
+ }
576
+ async function json(path, init) {
577
+ return (await request(path, init)).json();
578
+ }
579
+ async function* events(response) {
580
+ if (!response.body) throw new RungentRequestError(response.status, "no response body");
581
+ for await (const frame of readSse(response.body)) if (frame.data !== "") yield parseEvent(frame);
582
+ }
583
+ const thread = (id) => `/threads/${encodeURIComponent(id)}`;
584
+ return {
585
+ /** `ClientOptions.baseUrl` without a trailing slash, e.g. to key what a UI remembers. */
586
+ baseUrl,
587
+ createThread() {
588
+ return json("/threads", {
589
+ method: "POST",
590
+ body: "{}"
591
+ });
592
+ },
593
+ listThreads(cursor) {
594
+ return json(cursor ? `/threads?cursor=${encodeURIComponent(cursor)}` : "/threads");
595
+ },
596
+ getThread(id) {
597
+ return json(thread(id));
598
+ },
599
+ async renameThread(id, title) {
600
+ await request(thread(id), {
601
+ method: "PATCH",
602
+ body: JSON.stringify({ title })
603
+ });
604
+ },
605
+ async deleteThread(id) {
606
+ await request(thread(id), { method: "DELETE" });
607
+ },
608
+ /** Starts a run. Leaving the iteration early detaches from it; the run goes on. */
609
+ run(threadId, input, init = {}) {
610
+ const runId = crypto.randomUUID();
611
+ const messageId = input.message === void 0 ? void 0 : crypto.randomUUID();
612
+ const body = {
613
+ threadId,
614
+ runId,
615
+ messages: messageId === void 0 || input.message === void 0 ? [] : [{
616
+ id: messageId,
617
+ role: "user",
618
+ content: input.message
619
+ }],
620
+ tools: [],
621
+ context: input.context ?? [],
622
+ ...input.resume ? { resume: input.resume } : {}
623
+ };
624
+ return {
625
+ runId,
626
+ ...messageId === void 0 ? {} : { messageId },
627
+ async *[Symbol.asyncIterator]() {
628
+ yield* events(await request(`${thread(threadId)}/runs`, {
629
+ method: "POST",
630
+ body: JSON.stringify(body),
631
+ headers: { Accept: "text/event-stream" },
632
+ ...init.signal ? { signal: init.signal } : {}
633
+ }));
634
+ }
635
+ };
636
+ },
637
+ /**
638
+ * Replays the thread's events after `after`, then follows them live. It reconnects with
639
+ * `Last-Event-ID` and exponential backoff until `signal` aborts, never yielding a seq twice.
640
+ */
641
+ async *follow(threadId, init) {
642
+ let last = init.after;
643
+ let retryMs = DEFAULT_RETRY_MS;
644
+ let failures = 0;
645
+ while (!init.signal?.aborted) {
646
+ try {
647
+ const response = await request(`${thread(threadId)}/events?after=${last}`, {
648
+ headers: {
649
+ Accept: "text/event-stream",
650
+ "Last-Event-ID": String(last)
651
+ },
652
+ ...init.signal ? { signal: init.signal } : {}
653
+ });
654
+ if (!response.body) throw new RungentRequestError(response.status, "no response body");
655
+ for await (const frame of readSse(response.body)) {
656
+ if (frame.retry !== void 0) retryMs = frame.retry;
657
+ if (frame.data === "") continue;
658
+ const event = parseEvent(frame);
659
+ failures = 0;
660
+ if (seqOf(event) <= last) continue;
661
+ last = seqOf(event);
662
+ yield event;
663
+ }
664
+ } catch (error) {
665
+ if (init.signal?.aborted) return;
666
+ if (error instanceof RungentProtocolError || !transient(error)) throw error;
667
+ }
668
+ if (init.signal?.aborted) return;
669
+ await sleep(Math.min(retryMs * 2 ** failures, MAX_RETRY_MS), init.signal).catch(() => {});
670
+ failures += 1;
671
+ }
672
+ },
673
+ async cancel(runId) {
674
+ await request(`/runs/${encodeURIComponent(runId)}/cancel`, { method: "POST" });
675
+ },
676
+ info() {
677
+ return json("/info");
678
+ },
679
+ async catalog() {
680
+ return (await json("/catalog")).operations;
681
+ },
682
+ search(query, init = {}) {
683
+ const params = new URLSearchParams({ q: query });
684
+ if (init.limit !== void 0) params.set("limit", String(init.limit));
685
+ if (init.types?.length) params.set("types", init.types.join(","));
686
+ return json(`/search?${params}`, init.signal ? { signal: init.signal } : {});
687
+ },
688
+ getSettings() {
689
+ return json("/settings");
690
+ },
691
+ putSettings(settings) {
692
+ return json("/settings", {
693
+ method: "PUT",
694
+ body: JSON.stringify(settings)
695
+ });
696
+ },
697
+ /** Forgets the saved settings; the configured defaults apply again. Needs `rungent:admin`. */
698
+ resetSettings() {
699
+ return json("/settings", { method: "DELETE" });
700
+ },
701
+ /** Rates an assistant message; a later rating of the same message replaces it. */
702
+ setFeedback(threadId, messageId, feedback) {
703
+ return json(`${thread(threadId)}/messages/${encodeURIComponent(messageId)}/feedback`, {
704
+ method: "PUT",
705
+ body: JSON.stringify(feedback)
706
+ });
707
+ },
708
+ /** Every user's feedback, oldest first; needs `rungent:admin`. */
709
+ listFeedback(query = {}) {
710
+ const params = new URLSearchParams();
711
+ if (query.since) params.set("since", query.since);
712
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
713
+ if (query.cursor) params.set("cursor", query.cursor);
714
+ const search = params.toString();
715
+ return json(search ? `/feedback?${search}` : "/feedback");
716
+ }
717
+ };
718
+ }
719
+ // src/client/reducer.ts
720
+ const initialThreadState = {
721
+ lastSeq: 0,
722
+ status: "idle",
723
+ runId: null,
724
+ items: [],
725
+ interrupts: [],
726
+ citations: {},
727
+ opens: [],
728
+ context: null,
729
+ retry: null,
730
+ error: null,
731
+ usage: []
732
+ };
733
+ function rungentMeta(metadata) {
734
+ return metadata?.[METADATA_KEY];
735
+ }
736
+ /** An event's `metadata.rungent` without the `seq` every event carries. */
737
+ function eventMeta(event) {
738
+ const { seq: _, ...meta } = event.metadata.rungent;
739
+ return meta;
740
+ }
741
+ function text(content) {
742
+ return typeof content === "string" ? content : content.map((part) => part.type === "text" ? part.text : "").join("");
743
+ }
744
+ /** The images and documents of a message's content, as attachments. */
745
+ function attachmentsOf(content) {
746
+ if (typeof content === "string") return [];
747
+ return content.flatMap((part) => {
748
+ if (part.type !== "image" && part.type !== "document") return [];
749
+ const source = part.source;
750
+ if (source.type === "file") return [];
751
+ const url = source.type === "data" ? `data:${source.mimeType};base64,${source.value}` : source.value;
752
+ const name = part.metadata?.rungent?.name;
753
+ return [{
754
+ kind: part.type === "image" ? "image" : "file",
755
+ url,
756
+ ...source.mimeType ? { mimeType: source.mimeType } : {},
757
+ ...typeof name === "string" ? { name } : {}
758
+ }];
759
+ });
760
+ }
761
+ /**
762
+ * The content part of an uploaded file: an image part for `image/*`, otherwise a document
763
+ * part. The file name travels in `metadata.rungent.name`.
764
+ */
765
+ function attachmentPart(file) {
766
+ const source = {
767
+ type: "url",
768
+ value: file.url,
769
+ mimeType: file.mimeType
770
+ };
771
+ const metadata = file.name ? { metadata: { rungent: { name: file.name } } } : {};
772
+ return file.mimeType.startsWith("image/") ? {
773
+ type: "image",
774
+ source,
775
+ ...metadata
776
+ } : {
777
+ type: "document",
778
+ source,
779
+ ...metadata
780
+ };
781
+ }
782
+ function upsert(items, id, kind, update) {
783
+ const index = items.findIndex((item) => item.id === id && item.kind === kind);
784
+ if (index === -1) return [...items, update(void 0)];
785
+ const next = [...items];
786
+ next[index] = update(items[index]);
787
+ return next;
788
+ }
789
+ function toolItem(id, name, at) {
790
+ return {
791
+ kind: "tool",
792
+ id,
793
+ name,
794
+ startedAt: at,
795
+ endedAt: null,
796
+ meta: null,
797
+ arguments: null,
798
+ status: "running",
799
+ error: null,
800
+ deduplicated: false,
801
+ result: null
802
+ };
803
+ }
804
+ function parseArguments(json) {
805
+ try {
806
+ const value = JSON.parse(json);
807
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
808
+ } catch {
809
+ return null;
810
+ }
811
+ }
812
+ /** Reads an AG-UI interrupt as one of rungent's kinds. */
813
+ function openInterrupt(interrupt) {
814
+ const base = {
815
+ id: interrupt.id,
816
+ interrupt
817
+ };
818
+ const meta = rungentMeta(interrupt.metadata);
819
+ if (interrupt.reason === InterruptReason.approval) {
820
+ const parsed = ApprovalInterruptMeta.safeParse(meta);
821
+ if (parsed.success) return {
822
+ ...base,
823
+ kind: "approval",
824
+ meta: parsed.data
825
+ };
826
+ } else if (interrupt.reason === InterruptReason.input) {
827
+ const parsed = InputInterruptMeta.safeParse(meta);
828
+ if (parsed.success) return {
829
+ ...base,
830
+ kind: "input",
831
+ form: parsed.data.form
832
+ };
833
+ } else if (interrupt.reason === InterruptReason.form) {
834
+ const parsed = FormInterruptMeta.safeParse(meta);
835
+ if (parsed.success) return {
836
+ ...base,
837
+ kind: "form",
838
+ meta: parsed.data
839
+ };
840
+ } else if (interrupt.reason === InterruptReason.task) {
841
+ const parsed = TaskInterruptMeta.safeParse(meta);
842
+ if (parsed.success) return {
843
+ ...base,
844
+ kind: "task",
845
+ ...parsed.data,
846
+ progress: null
847
+ };
848
+ }
849
+ return {
850
+ ...base,
851
+ kind: "other"
852
+ };
853
+ }
854
+ function addUserMessages(state, input) {
855
+ let items = state.items;
856
+ for (const message of input?.messages ?? []) if (message.role === "user" && !items.some((item) => item.id === message.id)) items = [...items, {
857
+ kind: "user",
858
+ id: message.id,
859
+ text: text(message.content),
860
+ attachments: attachmentsOf(message.content)
861
+ }];
862
+ const answered = new Set(input?.resume?.map((entry) => entry.interruptId));
863
+ return {
864
+ ...state,
865
+ items,
866
+ interrupts: state.interrupts.filter((open) => !answered.has(open.id))
867
+ };
868
+ }
869
+ const streams = (item) => (item.kind === "assistant" || item.kind === "reasoning") && item.streaming;
870
+ /** Ends the text and reasoning still streaming when the run ends. */
871
+ function endStreaming(items, at) {
872
+ return items.some(streams) ? items.map((item) => streams(item) ? {
873
+ ...item,
874
+ streaming: false,
875
+ endedAt: item.endedAt ?? at
876
+ } : item) : items;
877
+ }
878
+ /** Appends a reasoning delta, starting the item when it is new. */
879
+ function reason(items, id, delta, at) {
880
+ return upsert(items, id, "reasoning", (current) => ({
881
+ kind: "reasoning",
882
+ id,
883
+ text: (current?.text ?? "") + delta,
884
+ streaming: true,
885
+ startedAt: current?.startedAt ?? at,
886
+ endedAt: null
887
+ }));
888
+ }
889
+ /** Ends one reasoning message, or with no id (`REASONING_END`) every one still streaming. */
890
+ function endReasoning(items, id, at) {
891
+ return items.map((item) => (id === null || item.id === id) && item.kind === "reasoning" && item.streaming ? {
892
+ ...item,
893
+ streaming: false,
894
+ endedAt: at
895
+ } : item);
896
+ }
897
+ function applyCustom(state, name, value, seq) {
898
+ if (!(name in CustomEvents)) return state;
899
+ const parsed = CustomEvents[name].safeParse(value);
900
+ if (!parsed.success) return state;
901
+ const data = parsed.data;
902
+ switch (name) {
903
+ case "rungent.ui.open": return {
904
+ ...state,
905
+ opens: [...state.opens, {
906
+ seq,
907
+ path: data.path
908
+ }]
909
+ };
910
+ case "rungent.citation": {
911
+ const { messageId, citations } = data;
912
+ return {
913
+ ...state,
914
+ citations: {
915
+ ...state.citations,
916
+ [messageId]: citations
917
+ }
918
+ };
919
+ }
920
+ case "rungent.context": return {
921
+ ...state,
922
+ context: data
923
+ };
924
+ case "rungent.model.retry": return {
925
+ ...state,
926
+ retry: data
927
+ };
928
+ case "rungent.message.discard": {
929
+ const { messageId } = data;
930
+ return {
931
+ ...state,
932
+ items: state.items.filter((item) => item.id !== messageId)
933
+ };
934
+ }
935
+ case "rungent.task": {
936
+ const progress = data;
937
+ return {
938
+ ...state,
939
+ interrupts: state.interrupts.map((open) => open.kind === "task" && open.taskId === progress.taskId ? {
940
+ ...open,
941
+ progress
942
+ } : open)
943
+ };
944
+ }
945
+ default: return state;
946
+ }
947
+ }
948
+ function apply(state, event) {
949
+ const at = event.timestamp ?? null;
950
+ switch (event.type) {
951
+ case EventType.RUN_STARTED: return addUserMessages({
952
+ ...state,
953
+ status: "running",
954
+ runId: event.runId,
955
+ error: null,
956
+ retry: null
957
+ }, event.input);
958
+ case EventType.RUN_FINISHED: {
959
+ const outcome = event.outcome ?? { type: "success" };
960
+ return {
961
+ ...state,
962
+ status: outcome.type === "interrupt" ? "interrupted" : outcome.type === "cancelled" ? "cancelled" : "succeeded",
963
+ interrupts: outcome.type === "interrupt" ? outcome.interrupts.map(openInterrupt) : [],
964
+ items: endStreaming(state.items, at),
965
+ retry: null,
966
+ usage: event.usage ?? []
967
+ };
968
+ }
969
+ case EventType.RUN_ERROR: return {
970
+ ...state,
971
+ status: "failed",
972
+ error: {
973
+ code: event.code ?? null,
974
+ message: event.message
975
+ },
976
+ items: endStreaming(state.items, at),
977
+ retry: null,
978
+ usage: event.usage ?? []
979
+ };
980
+ case EventType.TEXT_MESSAGE_START:
981
+ if (event.role === "user") return {
982
+ ...state,
983
+ items: upsert(state.items, event.messageId, "user", (current) => ({
984
+ kind: "user",
985
+ id: event.messageId,
986
+ text: current?.text ?? "",
987
+ attachments: current?.attachments ?? []
988
+ }))
989
+ };
990
+ return {
991
+ ...state,
992
+ retry: null,
993
+ items: upsert(state.items, event.messageId, "assistant", (current) => ({
994
+ kind: "assistant",
995
+ id: event.messageId,
996
+ text: current?.text ?? "",
997
+ streaming: true,
998
+ startedAt: current?.startedAt ?? at,
999
+ endedAt: null
1000
+ }))
1001
+ };
1002
+ case EventType.TEXT_MESSAGE_CONTENT: {
1003
+ const user = state.items.find((item) => item.id === event.messageId)?.kind === "user";
1004
+ return {
1005
+ ...state,
1006
+ retry: null,
1007
+ items: user ? upsert(state.items, event.messageId, "user", (current) => ({
1008
+ kind: "user",
1009
+ id: event.messageId,
1010
+ text: (current?.text ?? "") + event.delta,
1011
+ attachments: current?.attachments ?? []
1012
+ })) : upsert(state.items, event.messageId, "assistant", (current) => ({
1013
+ kind: "assistant",
1014
+ id: event.messageId,
1015
+ text: (current?.text ?? "") + event.delta,
1016
+ streaming: true,
1017
+ startedAt: current?.startedAt ?? at,
1018
+ endedAt: null
1019
+ }))
1020
+ };
1021
+ }
1022
+ case EventType.TEXT_MESSAGE_END: return {
1023
+ ...state,
1024
+ items: state.items.map((item) => item.id === event.messageId && item.kind === "assistant" ? {
1025
+ ...item,
1026
+ streaming: false,
1027
+ endedAt: at
1028
+ } : item)
1029
+ };
1030
+ case EventType.REASONING_MESSAGE_START: return {
1031
+ ...state,
1032
+ items: reason(state.items, event.messageId, "", at)
1033
+ };
1034
+ case EventType.REASONING_MESSAGE_CONTENT: return {
1035
+ ...state,
1036
+ retry: null,
1037
+ items: reason(state.items, event.messageId, event.delta, at)
1038
+ };
1039
+ case EventType.REASONING_MESSAGE_CHUNK: {
1040
+ const id = event.messageId ?? state.items.findLast((item) => item.kind === "reasoning")?.id;
1041
+ if (!id) return state;
1042
+ return {
1043
+ ...state,
1044
+ retry: null,
1045
+ items: reason(state.items, id, event.delta ?? "", at)
1046
+ };
1047
+ }
1048
+ case EventType.REASONING_MESSAGE_END: return {
1049
+ ...state,
1050
+ items: endReasoning(state.items, event.messageId, at)
1051
+ };
1052
+ case EventType.REASONING_END: return {
1053
+ ...state,
1054
+ items: endReasoning(state.items, null, at)
1055
+ };
1056
+ case EventType.TOOL_CALL_START: {
1057
+ const meta = ToolCallMeta.safeParse(eventMeta(event));
1058
+ return {
1059
+ ...state,
1060
+ items: upsert(state.items, event.toolCallId, "tool", (current) => ({
1061
+ ...current ?? toolItem(event.toolCallId, event.toolCallName, at),
1062
+ name: event.toolCallName,
1063
+ meta: meta.success ? meta.data : null
1064
+ }))
1065
+ };
1066
+ }
1067
+ case EventType.TOOL_CALL_ARGS: return {
1068
+ ...state,
1069
+ items: upsert(state.items, event.toolCallId, "tool", (current) => ({
1070
+ ...current ?? toolItem(event.toolCallId, "", at),
1071
+ arguments: parseArguments(event.delta)
1072
+ }))
1073
+ };
1074
+ case EventType.TOOL_CALL_RESULT: {
1075
+ const meta = ToolResultMeta.safeParse(eventMeta(event));
1076
+ return {
1077
+ ...state,
1078
+ items: upsert(state.items, event.toolCallId, "tool", (current) => ({
1079
+ ...current ?? toolItem(event.toolCallId, "", at),
1080
+ endedAt: at,
1081
+ status: meta.success ? meta.data.status : "succeeded",
1082
+ error: meta.success ? meta.data.error ?? null : null,
1083
+ deduplicated: meta.success && meta.data.deduplicated === true,
1084
+ result: text(event.content)
1085
+ }))
1086
+ };
1087
+ }
1088
+ case EventType.ACTIVITY_SNAPSHOT: {
1089
+ const content = ProgressContent.safeParse(event.content);
1090
+ if (event.activityType !== "rungent.progress" || !content.success) return state;
1091
+ return {
1092
+ ...state,
1093
+ items: upsert(state.items, event.messageId, "progress", (current) => ({
1094
+ kind: "progress",
1095
+ id: event.messageId,
1096
+ message: content.data.message,
1097
+ startedAt: current?.startedAt ?? at
1098
+ }))
1099
+ };
1100
+ }
1101
+ case EventType.CUSTOM: return applyCustom(state, event.name, event.value, event.metadata.rungent.seq);
1102
+ default: return state;
1103
+ }
1104
+ }
1105
+ /** Applies one event. Pure; an event at or below `lastSeq` (a replay) changes nothing. */
1106
+ function reduceThread(state, event) {
1107
+ const seq = event.metadata.rungent.seq;
1108
+ if (seq <= state.lastSeq) return state;
1109
+ return {
1110
+ ...apply(state, event),
1111
+ lastSeq: seq
1112
+ };
1113
+ }
1114
+ /** Shows a message the user just sent before the run echoes it; the echo is then ignored. */
1115
+ function appendUserMessage(state, message) {
1116
+ return state.items.some((item) => item.id === message.id) ? state : {
1117
+ ...state,
1118
+ items: [...state.items, message]
1119
+ };
1120
+ }
1121
+ // src/client/resume.ts
1122
+ /** Answers an approval, echoing the `argsHash` the user saw so rungent runs exactly those arguments. */
1123
+ function answerApproval(interrupt, approved) {
1124
+ return {
1125
+ interruptId: interrupt.id,
1126
+ status: "resolved",
1127
+ payload: { approved },
1128
+ metadata: { [METADATA_KEY]: { argsHash: interrupt.meta.argsHash } }
1129
+ };
1130
+ }
1131
+ function checked(form, answers) {
1132
+ const issues = checkAnswers(form, answers);
1133
+ if (issues.length > 0) throw new Error(`invalid answers: ${issues.map((issue) => `${issue.question}: ${issue.message}`).join("; ")}`);
1134
+ }
1135
+ /** Answers `request_input`. Throws when the answers fail `checkAnswers`. */
1136
+ function answerInput(interrupt, answers) {
1137
+ checked(interrupt.form, answers);
1138
+ return {
1139
+ interruptId: interrupt.id,
1140
+ status: "resolved",
1141
+ payload: { answers }
1142
+ };
1143
+ }
1144
+ /** Submits a host form with the operation's complete arguments, as the host's own form made them. */
1145
+ function submitForm(interrupt, args) {
1146
+ return {
1147
+ interruptId: interrupt.id,
1148
+ status: "resolved",
1149
+ payload: { arguments: args }
1150
+ };
1151
+ }
1152
+ /**
1153
+ * Submits a host form from the answers to its generic questions, set over the arguments it
1154
+ * started from. Throws when the answers fail `checkAnswers`.
1155
+ */
1156
+ function submitFormAnswers(interrupt, answers) {
1157
+ checked(interrupt.meta.form, answers);
1158
+ return submitForm(interrupt, answersToArguments(interrupt.meta.form, interrupt.meta.arguments, answers));
1159
+ }
1160
+ /** Cancels every open interrupt, as a new user message must. */
1161
+ function cancelAll(interrupts) {
1162
+ return interrupts.map((open) => ({
1163
+ interruptId: open.id,
1164
+ status: "cancelled"
1165
+ }));
1166
+ }
1167
+ export { submitFormAnswers as a, attachmentsOf as c, reduceThread as d, RungentRequestError as f, checkAnswers as h, submitForm as i, initialThreadState as l, RungentProtocolError as m, answerInput as n, appendUserMessage as o, createClient as p, cancelAll as r, attachmentPart as s, answerApproval as t, openInterrupt as u };