@ai-matrx/agents 0.5.1 → 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.
Files changed (41) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +41 -16
  3. package/dist/index.cjs +415 -40
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +3 -1
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.js +396 -3
  8. package/dist/index.js.map +1 -1
  9. package/dist/matrx/index.cjs +401 -26
  10. package/dist/matrx/index.cjs.map +1 -1
  11. package/dist/matrx/index.d.cts +345 -1
  12. package/dist/matrx/index.d.ts +345 -1
  13. package/dist/matrx/index.js +382 -3
  14. package/dist/matrx/index.js.map +1 -1
  15. package/dist/presentation/result.cjs +23 -4
  16. package/dist/presentation/result.cjs.map +1 -1
  17. package/dist/presentation/result.js +3 -3
  18. package/dist/presentation/result.js.map +1 -1
  19. package/dist/projection/request.cjs +25 -6
  20. package/dist/projection/request.cjs.map +1 -1
  21. package/dist/projection/request.js +5 -3
  22. package/dist/projection/request.js.map +1 -1
  23. package/dist/projection/workflow.cjs +25 -6
  24. package/dist/projection/workflow.cjs.map +1 -1
  25. package/dist/projection/workflow.js +5 -3
  26. package/dist/projection/workflow.js.map +1 -1
  27. package/dist/react/index.cjs +1038 -0
  28. package/dist/react/index.cjs.map +1 -0
  29. package/dist/react/index.d.cts +540 -0
  30. package/dist/react/index.d.ts +540 -0
  31. package/dist/react/index.js +1016 -0
  32. package/dist/react/index.js.map +1 -0
  33. package/dist/stream/ndjson.cjs +26 -7
  34. package/dist/stream/ndjson.cjs.map +1 -1
  35. package/dist/stream/ndjson.js +6 -3
  36. package/dist/stream/ndjson.js.map +1 -1
  37. package/dist/stream/sse.cjs +25 -6
  38. package/dist/stream/sse.cjs.map +1 -1
  39. package/dist/stream/sse.js +5 -3
  40. package/dist/stream/sse.js.map +1 -1
  41. package/package.json +28 -2
@@ -0,0 +1,1038 @@
1
+ "use client";
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // react/index.ts
22
+ var react_exports = {};
23
+ __export(react_exports, {
24
+ useAgentRun: () => useAgentRun,
25
+ useFollowRuntimeOperation: () => useFollowRuntimeOperation
26
+ });
27
+ module.exports = __toCommonJS(react_exports);
28
+
29
+ // react/use-agent-run.ts
30
+ var import_react = require("react");
31
+
32
+ // projection/request.ts
33
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
34
+ var asString = (value) => typeof value === "string" ? value : null;
35
+ var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
36
+ function createAgentRequestProjection(input) {
37
+ return {
38
+ requestId: input.requestId,
39
+ conversationId: input.conversationId ?? null,
40
+ status: "pending",
41
+ answer: "",
42
+ reasoning: "",
43
+ reasoningActive: false,
44
+ phase: null,
45
+ phaseHistory: [],
46
+ operations: {},
47
+ tools: {},
48
+ renderBlocks: {},
49
+ renderBlockOrder: [],
50
+ completion: null,
51
+ error: null,
52
+ lastTransportSeq: 0,
53
+ eventCount: 0
54
+ };
55
+ }
56
+ function toolStatus(event) {
57
+ switch (event) {
58
+ case "tool_started":
59
+ return "started";
60
+ case "tool_step":
61
+ return "step";
62
+ case "tool_result_preview":
63
+ return "preview";
64
+ case "tool_completed":
65
+ return "completed";
66
+ case "tool_error":
67
+ return "error";
68
+ case "tool_delegated":
69
+ return "delegated";
70
+ default:
71
+ return "progress";
72
+ }
73
+ }
74
+ function projectAgentEvent(current, event) {
75
+ const streamSeq = asNumber(event.stream_seq);
76
+ if (streamSeq !== null && streamSeq <= current.lastTransportSeq) return current;
77
+ const data = asRecord(event.data);
78
+ const next = {
79
+ ...current,
80
+ status: current.status === "pending" ? "streaming" : current.status,
81
+ lastTransportSeq: streamSeq ?? current.lastTransportSeq,
82
+ eventCount: current.eventCount + 1
83
+ };
84
+ switch (event.event) {
85
+ case "chunk": {
86
+ const text = asString(data.text);
87
+ return text === null ? next : { ...next, answer: current.answer + text };
88
+ }
89
+ case "reasoning_chunk": {
90
+ const text = asString(data.text);
91
+ return text === null ? next : {
92
+ ...next,
93
+ reasoning: current.reasoning + text,
94
+ reasoningActive: true
95
+ };
96
+ }
97
+ case "reasoning":
98
+ return {
99
+ ...next,
100
+ reasoningActive: data.state === "started"
101
+ };
102
+ case "phase": {
103
+ const phase = asString(data.phase);
104
+ if (phase === null) return next;
105
+ return {
106
+ ...next,
107
+ phase,
108
+ phaseHistory: [...current.phaseHistory, phase]
109
+ };
110
+ }
111
+ case "init": {
112
+ const operationId = asString(data.operation_id);
113
+ const operation = asString(data.operation);
114
+ if (operationId === null || operation === null) return next;
115
+ return {
116
+ ...next,
117
+ operations: {
118
+ ...current.operations,
119
+ [operationId]: {
120
+ operationId,
121
+ operation,
122
+ parentOperationId: asString(data.parent_operation_id),
123
+ status: "active",
124
+ metadata: Object.keys(asRecord(data.metadata)).length ? asRecord(data.metadata) : null,
125
+ result: null
126
+ }
127
+ }
128
+ };
129
+ }
130
+ case "completion": {
131
+ const operationId = asString(data.operation_id);
132
+ const operation = asString(data.operation);
133
+ const rawStatus = asString(data.status);
134
+ const status = rawStatus === "failed" || rawStatus === "cancelled" ? rawStatus : "success";
135
+ const result = asRecord(data.result);
136
+ const operations = operationId ? {
137
+ ...current.operations,
138
+ [operationId]: {
139
+ ...current.operations[operationId] ?? {
140
+ operationId,
141
+ operation: operation ?? "unknown",
142
+ parentOperationId: null,
143
+ metadata: null
144
+ },
145
+ status,
146
+ result
147
+ }
148
+ } : current.operations;
149
+ if (operation === "user_request") {
150
+ return {
151
+ ...next,
152
+ operations,
153
+ completion: data,
154
+ status: status === "success" ? "complete" : status === "cancelled" ? "cancelled" : "error"
155
+ };
156
+ }
157
+ return { ...next, operations };
158
+ }
159
+ case "tool_event": {
160
+ const callId = asString(data.call_id);
161
+ const toolName = asString(data.tool_name);
162
+ const lifecycle = asString(data.event);
163
+ if (callId === null || toolName === null || lifecycle === null) return next;
164
+ const status = toolStatus(lifecycle);
165
+ return {
166
+ ...next,
167
+ status: status === "delegated" ? "awaiting-tools" : status === "completed" || status === "error" ? "streaming" : next.status,
168
+ tools: {
169
+ ...current.tools,
170
+ [callId]: {
171
+ callId,
172
+ toolName,
173
+ status,
174
+ message: asString(data.message),
175
+ data: Object.keys(asRecord(data.data)).length ? asRecord(data.data) : null
176
+ }
177
+ }
178
+ };
179
+ }
180
+ case "render_block": {
181
+ const blockId = asString(data.blockId);
182
+ const blockIndex = asNumber(data.blockIndex);
183
+ const type = asString(data.type);
184
+ if (blockId === null || blockIndex === null || type === null) return next;
185
+ const alreadyKnown = Object.hasOwn(current.renderBlocks, blockId);
186
+ return {
187
+ ...next,
188
+ renderBlocks: {
189
+ ...current.renderBlocks,
190
+ [blockId]: {
191
+ blockId,
192
+ blockIndex,
193
+ type,
194
+ status: data.status === "complete" || data.status === "error" ? data.status : "streaming",
195
+ content: asString(data.content),
196
+ data: Object.keys(asRecord(data.data)).length ? asRecord(data.data) : null,
197
+ metadata: Object.keys(asRecord(data.metadata)).length ? asRecord(data.metadata) : null
198
+ }
199
+ },
200
+ renderBlockOrder: alreadyKnown ? current.renderBlockOrder : [...current.renderBlockOrder, blockId]
201
+ };
202
+ }
203
+ case "error":
204
+ return { ...next, status: "error", error: data };
205
+ case "end":
206
+ return {
207
+ ...next,
208
+ status: current.status === "error" || current.status === "cancelled" ? current.status : "complete",
209
+ reasoningActive: false
210
+ };
211
+ case "data": {
212
+ const conversationId = data.type === "conversation_id" ? asString(data.conversation_id) : null;
213
+ return conversationId === null ? next : { ...next, conversationId };
214
+ }
215
+ default:
216
+ return next;
217
+ }
218
+ }
219
+
220
+ // matrx/transport.ts
221
+ var MatrxApiError = class extends Error {
222
+ name = "MatrxApiError";
223
+ /** HTTP status of the failed response. */
224
+ status;
225
+ /** Machine code from the server body (`code`, or `detail.code`), when present. */
226
+ code;
227
+ /** The parsed server error body, verbatim (undefined when unparsable). */
228
+ serverDetail;
229
+ /** The request path the failure came from (server-relative). */
230
+ path;
231
+ constructor(args) {
232
+ super(
233
+ args.message ?? extractMatrxErrorMessage(args.serverDetail) ?? `HTTP ${args.status}`
234
+ );
235
+ this.status = args.status;
236
+ this.path = args.path;
237
+ this.serverDetail = args.serverDetail;
238
+ this.code = extractMatrxErrorCode(args.serverDetail);
239
+ }
240
+ };
241
+ function isRecord(value) {
242
+ return typeof value === "object" && value !== null && !Array.isArray(value);
243
+ }
244
+ function nonBlankString(value) {
245
+ return typeof value === "string" && value.trim() ? value : void 0;
246
+ }
247
+ function extractMatrxErrorMessage(serverDetail) {
248
+ if (!isRecord(serverDetail)) return void 0;
249
+ const userMessage = nonBlankString(serverDetail.user_message);
250
+ if (userMessage) return userMessage;
251
+ const message = nonBlankString(serverDetail.message);
252
+ if (message) return message;
253
+ if (Array.isArray(serverDetail.details)) {
254
+ const messages = serverDetail.details.map((entry) => {
255
+ if (!isRecord(entry)) return void 0;
256
+ const detailMessage = nonBlankString(entry.message);
257
+ if (!detailMessage) return void 0;
258
+ const field = nonBlankString(entry.field);
259
+ return field ? `${field}: ${detailMessage}` : detailMessage;
260
+ }).filter((m) => typeof m === "string");
261
+ if (messages.length > 0) return messages.join("; ");
262
+ }
263
+ const detail = serverDetail.detail;
264
+ if (isRecord(detail)) {
265
+ const detailMessage = nonBlankString(detail.message) ?? nonBlankString(detail.user_message);
266
+ if (detailMessage) return detailMessage;
267
+ }
268
+ if (typeof detail === "string" && detail.trim()) return detail;
269
+ if (Array.isArray(detail)) {
270
+ const messages = detail.map(
271
+ (entry) => isRecord(entry) ? nonBlankString(entry.msg) : void 0
272
+ ).filter((m) => typeof m === "string");
273
+ if (messages.length > 0) return messages.join("; ");
274
+ }
275
+ return void 0;
276
+ }
277
+ function extractMatrxErrorCode(serverDetail) {
278
+ if (!isRecord(serverDetail)) return null;
279
+ const topLevel = nonBlankString(serverDetail.code);
280
+ if (topLevel) return topLevel;
281
+ const detail = serverDetail.detail;
282
+ if (isRecord(detail)) {
283
+ const nested = nonBlankString(detail.code);
284
+ if (nested) return nested;
285
+ }
286
+ return null;
287
+ }
288
+
289
+ // matrx/client.ts
290
+ var import_data = require("@ai-matrx/data");
291
+ var import_data2 = require("@ai-matrx/data");
292
+
293
+ // matrx/org-context.ts
294
+ var OrganizationContextError = class extends Error {
295
+ code;
296
+ constructor(code, message) {
297
+ super(message);
298
+ this.name = "OrganizationContextError";
299
+ this.code = code;
300
+ }
301
+ };
302
+
303
+ // matrx/client.ts
304
+ function classifyStatus(status) {
305
+ return status >= 400 && status < 500 ? "validation_error" : "http_error";
306
+ }
307
+ function normalizeMatrxError(err) {
308
+ if (err instanceof MatrxApiError) {
309
+ return {
310
+ type: classifyStatus(err.status),
311
+ message: err.message,
312
+ status: err.status,
313
+ serverDetail: err.serverDetail,
314
+ ...err.code ? { code: err.code } : {},
315
+ name: err.name
316
+ };
317
+ }
318
+ if (err instanceof OrganizationContextError) {
319
+ return {
320
+ type: "validation_error",
321
+ message: err.message,
322
+ code: err.code,
323
+ name: err.name,
324
+ ...err.stack !== void 0 ? { stack: err.stack } : {}
325
+ };
326
+ }
327
+ if (err instanceof DOMException && err.name === "AbortError") {
328
+ return { type: "abort_error", message: "Request was cancelled." };
329
+ }
330
+ if ((0, import_data.isNetError)(err)) {
331
+ if (err.code === "aborted") {
332
+ return { type: "abort_error", message: err.message };
333
+ }
334
+ if (err.code === "http") {
335
+ const status = err.status ?? 0;
336
+ return { type: classifyStatus(status), message: err.message, status };
337
+ }
338
+ return { type: "network_error", message: err.message };
339
+ }
340
+ if (err instanceof Error) {
341
+ const httpMatch = err.message.match(/HTTP (\d+):\s*(.*)/);
342
+ if (httpMatch) {
343
+ const status = parseInt(httpMatch[1], 10);
344
+ return {
345
+ type: classifyStatus(status),
346
+ message: httpMatch[2] ?? err.message,
347
+ status
348
+ };
349
+ }
350
+ return { type: "network_error", message: err.message };
351
+ }
352
+ return { type: "unknown", message: String(err ?? "Unknown error") };
353
+ }
354
+
355
+ // stream/ndjson.ts
356
+ var DEFAULT_MATRX_NDJSON_READ_AHEAD = 64;
357
+ function isRecord2(value) {
358
+ return typeof value === "object" && value !== null && !Array.isArray(value);
359
+ }
360
+ function normalizeMatrxStreamEnvelope(value) {
361
+ if (!isRecord2(value)) return null;
362
+ if (typeof value.event === "string") {
363
+ const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
364
+ return {
365
+ event: value.event,
366
+ data: value.data,
367
+ ...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
368
+ };
369
+ }
370
+ if (value.e === "c" && typeof value.t === "string") {
371
+ return { event: "chunk", data: { text: value.t } };
372
+ }
373
+ if (value.e === "r" && typeof value.t === "string") {
374
+ return { event: "reasoning_chunk", data: { text: value.t } };
375
+ }
376
+ return null;
377
+ }
378
+ function createMatrxNdjsonFramer(options = {}) {
379
+ const decoder = new TextDecoder();
380
+ let buffer = "";
381
+ let lineNumber = 0;
382
+ let finished = false;
383
+ const assertOpen = () => {
384
+ if (finished) throw new Error("Matrx NDJSON framer is already finished");
385
+ };
386
+ const parseLine = (line, atCompletion) => {
387
+ const currentLineNumber = ++lineNumber;
388
+ const trimmed = line.trim();
389
+ if (!trimmed) return null;
390
+ let parsed;
391
+ try {
392
+ parsed = JSON.parse(trimmed);
393
+ } catch (error) {
394
+ options.onMalformedLine?.({
395
+ line: trimmed,
396
+ error,
397
+ lineNumber: currentLineNumber,
398
+ atCompletion
399
+ });
400
+ return null;
401
+ }
402
+ const envelope = normalizeMatrxStreamEnvelope(parsed);
403
+ if (!envelope) {
404
+ options.onUnknownEnvelope?.(parsed);
405
+ return null;
406
+ }
407
+ options.onValidEnvelope?.({
408
+ raw: parsed,
409
+ envelope,
410
+ line: trimmed,
411
+ lineNumber: currentLineNumber,
412
+ atCompletion
413
+ });
414
+ return envelope;
415
+ };
416
+ const pushDecodedText = (fragment) => {
417
+ buffer += fragment;
418
+ const lines = buffer.split("\n");
419
+ buffer = lines.pop() ?? "";
420
+ const envelopes = [];
421
+ for (const line of lines) {
422
+ const envelope = parseLine(line, false);
423
+ if (envelope) envelopes.push(envelope);
424
+ }
425
+ return envelopes;
426
+ };
427
+ return {
428
+ pushText(fragment) {
429
+ assertOpen();
430
+ return pushDecodedText(decoder.decode() + fragment);
431
+ },
432
+ pushBytes(fragment) {
433
+ assertOpen();
434
+ return pushDecodedText(decoder.decode(fragment, { stream: true }));
435
+ },
436
+ finish() {
437
+ assertOpen();
438
+ finished = true;
439
+ const envelopes = pushDecodedText(decoder.decode());
440
+ if (buffer.length > 0) {
441
+ const envelope = parseLine(buffer, true);
442
+ buffer = "";
443
+ if (envelope) envelopes.push(envelope);
444
+ }
445
+ return envelopes;
446
+ }
447
+ };
448
+ }
449
+ function readAheadLimit(value) {
450
+ const limit = value ?? DEFAULT_MATRX_NDJSON_READ_AHEAD;
451
+ if (!Number.isSafeInteger(limit) || limit < 1) {
452
+ throw new RangeError("maxReadAhead must be a positive safe integer");
453
+ }
454
+ return limit;
455
+ }
456
+ async function* readMatrxNdjsonStream(body, options = {}) {
457
+ const maxReadAhead = readAheadLimit(options.maxReadAhead);
458
+ const queue = [];
459
+ let queuedEventCount = 0;
460
+ let wakeConsumer = null;
461
+ let wakeProducer = null;
462
+ let readerFinished = false;
463
+ let consumerClosed = false;
464
+ const wakeWaitingConsumer = () => {
465
+ const wake = wakeConsumer;
466
+ wakeConsumer = null;
467
+ wake?.();
468
+ };
469
+ const wakeWaitingProducer = () => {
470
+ const wake = wakeProducer;
471
+ wakeProducer = null;
472
+ wake?.();
473
+ };
474
+ const enqueueTerminal = (item) => {
475
+ if (consumerClosed) return;
476
+ queue.push(item);
477
+ wakeWaitingConsumer();
478
+ };
479
+ const enqueueEvent = async (value) => {
480
+ while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
481
+ await new Promise((resolve) => {
482
+ wakeProducer = resolve;
483
+ });
484
+ }
485
+ if (consumerClosed || options.signal?.aborted) return false;
486
+ queue.push({ kind: "event", value });
487
+ queuedEventCount += 1;
488
+ wakeWaitingConsumer();
489
+ return true;
490
+ };
491
+ const waitForReadCapacity = async () => {
492
+ while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
493
+ await new Promise((resolve) => {
494
+ wakeProducer = resolve;
495
+ });
496
+ }
497
+ return !consumerClosed && !options.signal?.aborted;
498
+ };
499
+ const reader = body.getReader();
500
+ const framer = createMatrxNdjsonFramer(options);
501
+ const onAbort = () => {
502
+ wakeWaitingProducer();
503
+ wakeWaitingConsumer();
504
+ void reader.cancel(options.signal?.reason).catch(() => void 0);
505
+ };
506
+ options.signal?.addEventListener("abort", onAbort, { once: true });
507
+ if (options.signal?.aborted) onAbort();
508
+ const readerPromise = (async () => {
509
+ try {
510
+ while (!options.signal?.aborted && !consumerClosed) {
511
+ if (!await waitForReadCapacity()) return;
512
+ const { value, done } = await reader.read();
513
+ if (done) break;
514
+ for (const envelope of framer.pushBytes(value)) {
515
+ if (!await enqueueEvent(envelope)) return;
516
+ }
517
+ }
518
+ if (!options.signal?.aborted && !consumerClosed) {
519
+ for (const envelope of framer.finish()) {
520
+ if (!await enqueueEvent(envelope)) return;
521
+ }
522
+ }
523
+ } catch (error) {
524
+ const aborted = options.signal?.aborted || consumerClosed || error instanceof Error && error.name === "AbortError";
525
+ if (!aborted) enqueueTerminal({ kind: "error", error });
526
+ } finally {
527
+ readerFinished = true;
528
+ reader.releaseLock();
529
+ enqueueTerminal({ kind: "done" });
530
+ }
531
+ })();
532
+ try {
533
+ while (true) {
534
+ if (queue.length === 0) {
535
+ if (options.signal?.aborted || readerFinished) return;
536
+ await new Promise((resolve) => {
537
+ wakeConsumer = resolve;
538
+ });
539
+ }
540
+ const item = queue.shift();
541
+ if (item?.kind === "event") queuedEventCount -= 1;
542
+ wakeWaitingProducer();
543
+ if (!item || item.kind === "done") return;
544
+ if (item.kind === "error") throw item.error;
545
+ yield item.value;
546
+ }
547
+ } finally {
548
+ consumerClosed = true;
549
+ wakeWaitingProducer();
550
+ wakeWaitingConsumer();
551
+ options.signal?.removeEventListener("abort", onAbort);
552
+ if (!readerFinished) {
553
+ await reader.cancel().catch(() => void 0);
554
+ }
555
+ await readerPromise;
556
+ }
557
+ }
558
+
559
+ // matrx/internal.ts
560
+ function encodePathSegment(value) {
561
+ return encodeURIComponent(value);
562
+ }
563
+ function buildQuery(params) {
564
+ const search = new URLSearchParams();
565
+ for (const [key, value] of Object.entries(params)) {
566
+ if (value === void 0) continue;
567
+ if (Array.isArray(value)) {
568
+ for (const entry of value) search.append(key, entry);
569
+ } else {
570
+ search.append(key, String(value));
571
+ }
572
+ }
573
+ const encoded = search.toString();
574
+ return encoded ? `?${encoded}` : "";
575
+ }
576
+ async function readServerDetail(response) {
577
+ try {
578
+ return await response.json();
579
+ } catch {
580
+ return void 0;
581
+ }
582
+ }
583
+ async function throwApiError(path, response) {
584
+ throw new MatrxApiError({
585
+ status: response.status,
586
+ path,
587
+ serverDetail: await readServerDetail(response)
588
+ });
589
+ }
590
+ async function requestJson(transport, path, options) {
591
+ const hasBody = options.method !== "GET" && options.body !== void 0;
592
+ const response = await transport.fetch(path, {
593
+ method: options.method,
594
+ headers: hasBody ? { "Content-Type": "application/json" } : {},
595
+ ...hasBody ? { body: JSON.stringify(options.body) } : {},
596
+ ...options.signal ? { signal: options.signal } : {}
597
+ });
598
+ if (!response.ok) return throwApiError(path, response);
599
+ return await response.json();
600
+ }
601
+ function toRunHandle(response, options) {
602
+ return {
603
+ requestId: response.headers.get("X-Request-ID"),
604
+ conversationId: response.headers.get("X-Conversation-ID"),
605
+ events: readMatrxNdjsonStream(response.body, {
606
+ ...options.signal ? { signal: options.signal } : {},
607
+ ...options.maxReadAhead !== void 0 ? { maxReadAhead: options.maxReadAhead } : {},
608
+ ...options.onMalformedLine ? { onMalformedLine: options.onMalformedLine } : {},
609
+ ...options.onUnknownEnvelope ? { onUnknownEnvelope: options.onUnknownEnvelope } : {},
610
+ ...options.onValidEnvelope ? { onValidEnvelope: options.onValidEnvelope } : {}
611
+ }),
612
+ response
613
+ };
614
+ }
615
+ async function requestStream(transport, path, options) {
616
+ const hasBody = options.method !== "GET" && options.body !== void 0;
617
+ const response = await transport.fetch(path, {
618
+ method: options.method,
619
+ headers: {
620
+ ...hasBody ? { "Content-Type": "application/json" } : {},
621
+ ...options.headers
622
+ },
623
+ ...hasBody ? { body: JSON.stringify(options.body) } : {},
624
+ ...options.signal ? { signal: options.signal } : {}
625
+ });
626
+ if (!response.ok) return throwApiError(path, response);
627
+ if (!response.body) {
628
+ throw new MatrxApiError({
629
+ status: response.status,
630
+ path,
631
+ serverDetail: { code: "missing_response_body" },
632
+ message: "The streaming response carried no body."
633
+ });
634
+ }
635
+ return response;
636
+ }
637
+
638
+ // matrx/run.ts
639
+ async function streamCall(transport, path, body, options) {
640
+ const response = await requestStream(transport, path, {
641
+ method: "POST",
642
+ // This client IS the streaming path — `stream: true` always, last so a
643
+ // caller-supplied value can never flip the response off NDJSON.
644
+ body: { ...body, stream: true },
645
+ ...options.signal ? { signal: options.signal } : {}
646
+ });
647
+ return toRunHandle(response, options);
648
+ }
649
+ function startAgentRun(transport, agentId, request, options = {}) {
650
+ return streamCall(
651
+ transport,
652
+ `/ai/agents/${encodePathSegment(agentId)}`,
653
+ request,
654
+ options
655
+ );
656
+ }
657
+ function continueAgentConversation(transport, conversationId, request, options = {}) {
658
+ return streamCall(
659
+ transport,
660
+ `/ai/conversations/${encodePathSegment(conversationId)}`,
661
+ request,
662
+ options
663
+ );
664
+ }
665
+ function cancelAgentRun(transport, requestId, options = {}) {
666
+ const query = buildQuery(
667
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
668
+ );
669
+ return requestJson(
670
+ transport,
671
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
672
+ {
673
+ method: "POST",
674
+ ...options.signal ? { signal: options.signal } : {}
675
+ }
676
+ );
677
+ }
678
+
679
+ // stream/sse.ts
680
+ var FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/;
681
+ var LINE_SEPARATOR = /\r\n|\n|\r/;
682
+ function parseMatrxSseFrame(frame) {
683
+ let event = "message";
684
+ let id = null;
685
+ const dataLines = [];
686
+ let sawData = false;
687
+ for (const line of frame.split(LINE_SEPARATOR)) {
688
+ if (line.startsWith(":")) continue;
689
+ if (line.startsWith("event:")) event = line.slice(6).trim();
690
+ else if (line.startsWith("data:")) {
691
+ sawData = true;
692
+ dataLines.push(line.slice(5).replace(/^ /, ""));
693
+ } else if (line.startsWith("id:")) id = line.slice(3).trim();
694
+ }
695
+ const seqCandidate = id !== null && id !== "" ? Number(id) : NaN;
696
+ const seq = Number.isSafeInteger(seqCandidate) && seqCandidate >= 0 ? seqCandidate : null;
697
+ return { event, id, seq, data: sawData ? dataLines.join("\n") : null };
698
+ }
699
+ function createMatrxSseFramer() {
700
+ let buffer = "";
701
+ return {
702
+ push(chunk) {
703
+ buffer += chunk;
704
+ const frames = [];
705
+ for (; ; ) {
706
+ const sep = FRAME_SEPARATOR.exec(buffer);
707
+ if (sep === null) break;
708
+ const frame = buffer.slice(0, sep.index);
709
+ buffer = buffer.slice(sep.index + sep[0].length);
710
+ frames.push(parseMatrxSseFrame(frame));
711
+ }
712
+ return frames;
713
+ },
714
+ flush() {
715
+ const rest = buffer;
716
+ buffer = "";
717
+ return { incomplete: rest.length > 0 ? rest : null };
718
+ }
719
+ };
720
+ }
721
+ async function* readMatrxSseStream(stream, options = {}) {
722
+ const reader = stream.getReader();
723
+ const decoder = new TextDecoder();
724
+ const framer = createMatrxSseFramer();
725
+ try {
726
+ for (; ; ) {
727
+ const { value, done } = await reader.read();
728
+ if (done) break;
729
+ const frames = framer.push(decoder.decode(value, { stream: true }));
730
+ for (const frame of frames) yield frame;
731
+ }
732
+ const tail = framer.push(decoder.decode());
733
+ for (const frame of tail) yield frame;
734
+ const { incomplete } = framer.flush();
735
+ if (incomplete !== null) options.onIncomplete?.(incomplete);
736
+ } finally {
737
+ reader.releaseLock();
738
+ }
739
+ }
740
+
741
+ // matrx/operations.ts
742
+ var RUNTIME_STATUSES = /* @__PURE__ */ new Set([
743
+ "pending",
744
+ "running",
745
+ "paused",
746
+ "waiting_input",
747
+ "completed",
748
+ "failed",
749
+ "cancelled"
750
+ ]);
751
+ function parseEndStatus(data) {
752
+ if (data === null) return null;
753
+ try {
754
+ const parsed = JSON.parse(data);
755
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.status === "string") {
756
+ const status = parsed.status;
757
+ return RUNTIME_STATUSES.has(status) ? status : null;
758
+ }
759
+ } catch {
760
+ }
761
+ return null;
762
+ }
763
+ async function* followRuntimeOperationEvents(transport, executionId, options = {}) {
764
+ let cursor = options.lastEventSeq ?? 0;
765
+ const headers = { Accept: "text/event-stream" };
766
+ if (cursor > 0) headers["Last-Event-ID"] = String(cursor);
767
+ const response = await requestStream(
768
+ transport,
769
+ `/runtime/executions/${encodePathSegment(executionId)}/events/stream`,
770
+ {
771
+ method: "GET",
772
+ headers,
773
+ ...options.signal ? { signal: options.signal } : {}
774
+ }
775
+ );
776
+ const frames = readMatrxSseStream(
777
+ response.body,
778
+ options.onIncomplete ? { onIncomplete: options.onIncomplete } : {}
779
+ );
780
+ for await (const frame of frames) {
781
+ if (frame.event === "end") {
782
+ yield { type: "end", status: parseEndStatus(frame.data), cursor };
783
+ return;
784
+ }
785
+ if (frame.event === "execution_event" && frame.data !== null) {
786
+ let event;
787
+ try {
788
+ event = JSON.parse(frame.data);
789
+ } catch (error) {
790
+ options.onMalformedFrame?.(frame, error);
791
+ yield { type: "liveness", cursor };
792
+ continue;
793
+ }
794
+ if (frame.seq !== null && frame.seq > cursor) cursor = frame.seq;
795
+ yield { type: "event", event, seq: frame.seq, cursor };
796
+ continue;
797
+ }
798
+ yield { type: "liveness", cursor };
799
+ }
800
+ }
801
+ async function followRuntimeOperationToEnd(transport, executionId, options) {
802
+ const stallTimeoutMs = options.stallTimeoutMs ?? 45e3;
803
+ const reconnectLimit = options.reconnectLimit ?? 60;
804
+ const reconnectDelayMs = options.reconnectDelayMs ?? 2e3;
805
+ const outer = options.signal;
806
+ let cursor = options.lastEventSeq ?? 0;
807
+ let failures = 0;
808
+ while (!outer?.aborted && failures < reconnectLimit) {
809
+ const attempt = new AbortController();
810
+ const onOuterAbort = () => attempt.abort();
811
+ outer?.addEventListener("abort", onOuterAbort, { once: true });
812
+ let stallTimer = null;
813
+ const armStall = () => {
814
+ if (stallTimer !== null) clearTimeout(stallTimer);
815
+ stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);
816
+ };
817
+ try {
818
+ const items = followRuntimeOperationEvents(transport, executionId, {
819
+ lastEventSeq: cursor,
820
+ signal: attempt.signal,
821
+ ...options.onMalformedFrame ? { onMalformedFrame: options.onMalformedFrame } : {}
822
+ });
823
+ armStall();
824
+ for await (const item of items) {
825
+ armStall();
826
+ failures = 0;
827
+ cursor = item.cursor;
828
+ if (item.type === "end") {
829
+ return { ended: true, status: item.status };
830
+ }
831
+ if (item.type === "event") {
832
+ options.onEvent(item.event, item.seq);
833
+ }
834
+ }
835
+ failures += 1;
836
+ } catch (error) {
837
+ if (outer?.aborted) break;
838
+ failures += 1;
839
+ options.onAttemptError?.(error);
840
+ } finally {
841
+ if (stallTimer !== null) clearTimeout(stallTimer);
842
+ outer?.removeEventListener("abort", onOuterAbort);
843
+ }
844
+ if (!outer?.aborted && failures < reconnectLimit) {
845
+ await new Promise((r) => setTimeout(r, reconnectDelayMs));
846
+ }
847
+ }
848
+ return { ended: false, status: null };
849
+ }
850
+
851
+ // react/use-agent-run.ts
852
+ function useAgentRun(options) {
853
+ const [phase, setPhase] = (0, import_react.useState)("idle");
854
+ const [projection, setProjection] = (0, import_react.useState)(
855
+ null
856
+ );
857
+ const [error, setError] = (0, import_react.useState)(null);
858
+ const optionsRef = (0, import_react.useRef)(options);
859
+ optionsRef.current = options;
860
+ const runSeqRef = (0, import_react.useRef)(0);
861
+ const controllerRef = (0, import_react.useRef)(null);
862
+ const requestIdRef = (0, import_react.useRef)(null);
863
+ const transportRef = (0, import_react.useRef)(null);
864
+ const abort = (0, import_react.useCallback)(() => {
865
+ controllerRef.current?.abort();
866
+ }, []);
867
+ (0, import_react.useEffect)(() => () => controllerRef.current?.abort(), []);
868
+ const runStream = (0, import_react.useCallback)(
869
+ async (open, seedConversationId) => {
870
+ const seq = ++runSeqRef.current;
871
+ const isCurrent = () => runSeqRef.current === seq;
872
+ controllerRef.current?.abort();
873
+ const controller = new AbortController();
874
+ controllerRef.current = controller;
875
+ requestIdRef.current = null;
876
+ const opts = optionsRef.current;
877
+ const transport = typeof opts.transport === "function" ? opts.transport() : opts.transport;
878
+ transportRef.current = transport;
879
+ setPhase("starting");
880
+ setError(null);
881
+ setProjection(null);
882
+ try {
883
+ const handle = await open(transport, {
884
+ ...opts.streamOptions,
885
+ signal: controller.signal
886
+ });
887
+ requestIdRef.current = handle.requestId;
888
+ let current = createAgentRequestProjection({
889
+ requestId: handle.requestId ?? crypto.randomUUID(),
890
+ conversationId: handle.conversationId ?? seedConversationId
891
+ });
892
+ if (isCurrent()) {
893
+ setPhase("streaming");
894
+ setProjection(current);
895
+ }
896
+ for await (const envelope of handle.events) {
897
+ current = projectAgentEvent(current, envelope);
898
+ if (isCurrent()) {
899
+ setProjection(current);
900
+ optionsRef.current.onProjection?.(current);
901
+ }
902
+ }
903
+ if (isCurrent()) {
904
+ setPhase(
905
+ current.status === "error" ? "error" : current.status === "cancelled" ? "cancelled" : "complete"
906
+ );
907
+ if (current.status === "error") {
908
+ const failure = {
909
+ type: "unknown",
910
+ message: typeof current.error?.user_message === "string" && current.error.user_message || typeof current.error?.message === "string" && current.error.message || "The agent run failed",
911
+ serverDetail: current.error
912
+ };
913
+ setError(failure);
914
+ optionsRef.current.onError?.(failure);
915
+ }
916
+ }
917
+ return current;
918
+ } catch (err) {
919
+ const failure = normalizeMatrxError(err);
920
+ if (isCurrent()) {
921
+ setPhase(failure.type === "abort_error" ? "cancelled" : "error");
922
+ if (failure.type !== "abort_error") {
923
+ setError(failure);
924
+ optionsRef.current.onError?.(failure);
925
+ }
926
+ }
927
+ throw err;
928
+ }
929
+ },
930
+ []
931
+ );
932
+ const start = (0, import_react.useCallback)(
933
+ (agentId, request) => runStream(
934
+ (transport, callOptions) => startAgentRun(transport, agentId, request, callOptions),
935
+ request.conversation_id
936
+ ),
937
+ [runStream]
938
+ );
939
+ const continueConversation = (0, import_react.useCallback)(
940
+ (conversationId, request) => runStream(
941
+ (transport, callOptions) => continueAgentConversation(
942
+ transport,
943
+ conversationId,
944
+ request,
945
+ callOptions
946
+ ),
947
+ conversationId
948
+ ),
949
+ [runStream]
950
+ );
951
+ const cancel = (0, import_react.useCallback)(
952
+ async (mode = "cancel") => {
953
+ const requestId = requestIdRef.current;
954
+ const transport = transportRef.current;
955
+ if (!requestId || !transport) return null;
956
+ return cancelAgentRun(transport, requestId, { mode });
957
+ },
958
+ []
959
+ );
960
+ const reset = (0, import_react.useCallback)(() => {
961
+ runSeqRef.current += 1;
962
+ controllerRef.current?.abort();
963
+ controllerRef.current = null;
964
+ requestIdRef.current = null;
965
+ setPhase("idle");
966
+ setProjection(null);
967
+ setError(null);
968
+ }, []);
969
+ return {
970
+ phase,
971
+ projection,
972
+ requestId: projection?.requestId ?? null,
973
+ conversationId: projection?.conversationId ?? null,
974
+ error,
975
+ start,
976
+ continueConversation,
977
+ cancel,
978
+ abort,
979
+ reset
980
+ };
981
+ }
982
+
983
+ // react/use-follow-runtime-operation.ts
984
+ var import_react2 = require("react");
985
+ function useFollowRuntimeOperation(options) {
986
+ const [following, setFollowing] = (0, import_react2.useState)(false);
987
+ const [ended, setEnded] = (0, import_react2.useState)(false);
988
+ const [status, setStatus] = (0, import_react2.useState)(
989
+ null
990
+ );
991
+ const optionsRef = (0, import_react2.useRef)(options);
992
+ optionsRef.current = options;
993
+ const { executionId, enabled = true } = options;
994
+ const active = enabled && !!executionId;
995
+ const follow = (0, import_react2.useCallback)(
996
+ (id, signal, isCurrent) => {
997
+ const opts = optionsRef.current;
998
+ const transport = typeof opts.transport === "function" ? opts.transport() : opts.transport;
999
+ return followRuntimeOperationToEnd(transport, id, {
1000
+ signal,
1001
+ ...opts.lastEventSeq !== void 0 ? { lastEventSeq: opts.lastEventSeq } : {},
1002
+ ...opts.stallTimeoutMs !== void 0 ? { stallTimeoutMs: opts.stallTimeoutMs } : {},
1003
+ ...opts.reconnectLimit !== void 0 ? { reconnectLimit: opts.reconnectLimit } : {},
1004
+ ...opts.reconnectDelayMs !== void 0 ? { reconnectDelayMs: opts.reconnectDelayMs } : {},
1005
+ onEvent: (event, seq) => {
1006
+ if (isCurrent()) optionsRef.current.onEvent?.(event, seq);
1007
+ }
1008
+ });
1009
+ },
1010
+ []
1011
+ );
1012
+ (0, import_react2.useEffect)(() => {
1013
+ if (!active || !executionId) return;
1014
+ let current = true;
1015
+ const controller = new AbortController();
1016
+ setFollowing(true);
1017
+ setEnded(false);
1018
+ setStatus(null);
1019
+ void follow(executionId, controller.signal, () => current).then((result) => {
1020
+ if (!current) return;
1021
+ setFollowing(false);
1022
+ setEnded(result.ended);
1023
+ setStatus(result.status);
1024
+ optionsRef.current.onSettled?.(result);
1025
+ }).catch(() => {
1026
+ if (!current) return;
1027
+ setFollowing(false);
1028
+ optionsRef.current.onSettled?.({ ended: false, status: null });
1029
+ });
1030
+ return () => {
1031
+ current = false;
1032
+ controller.abort();
1033
+ setFollowing(false);
1034
+ };
1035
+ }, [active, executionId, follow]);
1036
+ return { following, ended, status };
1037
+ }
1038
+ //# sourceMappingURL=index.cjs.map