@ai-matrx/agents 0.3.0 → 0.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/CHANGELOG.md +43 -0
- package/README.md +38 -0
- package/dist/index.cjs +542 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +517 -1
- package/dist/index.js.map +1 -1
- package/dist/matrx/index.cjs +747 -0
- package/dist/matrx/index.cjs.map +1 -0
- package/dist/matrx/index.d.cts +691 -0
- package/dist/matrx/index.d.ts +691 -0
- package/dist/matrx/index.js +723 -0
- package/dist/matrx/index.js.map +1 -0
- package/dist/stream/sse.cjs +69 -0
- package/dist/stream/sse.cjs.map +1 -0
- package/dist/stream/sse.d.cts +76 -0
- package/dist/stream/sse.d.ts +76 -0
- package/dist/stream/sse.js +65 -0
- package/dist/stream/sse.js.map +1 -0
- package/package.json +22 -2
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
// matrx/transport.ts
|
|
2
|
+
var MatrxApiError = class extends Error {
|
|
3
|
+
name = "MatrxApiError";
|
|
4
|
+
/** HTTP status of the failed response. */
|
|
5
|
+
status;
|
|
6
|
+
/** Machine code from the server body (`code`, or `detail.code`), when present. */
|
|
7
|
+
code;
|
|
8
|
+
/** The parsed server error body, verbatim (undefined when unparsable). */
|
|
9
|
+
serverDetail;
|
|
10
|
+
/** The request path the failure came from (server-relative). */
|
|
11
|
+
path;
|
|
12
|
+
constructor(args) {
|
|
13
|
+
super(
|
|
14
|
+
args.message ?? extractMatrxErrorMessage(args.serverDetail) ?? `HTTP ${args.status}`
|
|
15
|
+
);
|
|
16
|
+
this.status = args.status;
|
|
17
|
+
this.path = args.path;
|
|
18
|
+
this.serverDetail = args.serverDetail;
|
|
19
|
+
this.code = extractMatrxErrorCode(args.serverDetail);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
function nonBlankString(value) {
|
|
26
|
+
return typeof value === "string" && value.trim() ? value : void 0;
|
|
27
|
+
}
|
|
28
|
+
function extractMatrxErrorMessage(serverDetail) {
|
|
29
|
+
if (!isRecord(serverDetail)) return void 0;
|
|
30
|
+
const userMessage = nonBlankString(serverDetail.user_message);
|
|
31
|
+
if (userMessage) return userMessage;
|
|
32
|
+
const message = nonBlankString(serverDetail.message);
|
|
33
|
+
if (message) return message;
|
|
34
|
+
if (Array.isArray(serverDetail.details)) {
|
|
35
|
+
const messages = serverDetail.details.map((entry) => {
|
|
36
|
+
if (!isRecord(entry)) return void 0;
|
|
37
|
+
const detailMessage = nonBlankString(entry.message);
|
|
38
|
+
if (!detailMessage) return void 0;
|
|
39
|
+
const field = nonBlankString(entry.field);
|
|
40
|
+
return field ? `${field}: ${detailMessage}` : detailMessage;
|
|
41
|
+
}).filter((m) => typeof m === "string");
|
|
42
|
+
if (messages.length > 0) return messages.join("; ");
|
|
43
|
+
}
|
|
44
|
+
const detail = serverDetail.detail;
|
|
45
|
+
if (isRecord(detail)) {
|
|
46
|
+
const detailMessage = nonBlankString(detail.message) ?? nonBlankString(detail.user_message);
|
|
47
|
+
if (detailMessage) return detailMessage;
|
|
48
|
+
}
|
|
49
|
+
if (typeof detail === "string" && detail.trim()) return detail;
|
|
50
|
+
if (Array.isArray(detail)) {
|
|
51
|
+
const messages = detail.map(
|
|
52
|
+
(entry) => isRecord(entry) ? nonBlankString(entry.msg) : void 0
|
|
53
|
+
).filter((m) => typeof m === "string");
|
|
54
|
+
if (messages.length > 0) return messages.join("; ");
|
|
55
|
+
}
|
|
56
|
+
return void 0;
|
|
57
|
+
}
|
|
58
|
+
function extractMatrxErrorCode(serverDetail) {
|
|
59
|
+
if (!isRecord(serverDetail)) return null;
|
|
60
|
+
const topLevel = nonBlankString(serverDetail.code);
|
|
61
|
+
if (topLevel) return topLevel;
|
|
62
|
+
const detail = serverDetail.detail;
|
|
63
|
+
if (isRecord(detail)) {
|
|
64
|
+
const nested = nonBlankString(detail.code);
|
|
65
|
+
if (nested) return nested;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// matrx/conversation.ts
|
|
71
|
+
function mintMatrxConversationId() {
|
|
72
|
+
return crypto.randomUUID();
|
|
73
|
+
}
|
|
74
|
+
function newStoredConversationStart(conversationId) {
|
|
75
|
+
return {
|
|
76
|
+
conversation_id: conversationId ?? mintMatrxConversationId(),
|
|
77
|
+
is_new: true,
|
|
78
|
+
store: true
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function continueStoredConversationStart(conversationId) {
|
|
82
|
+
return { conversation_id: conversationId, is_new: false, store: true };
|
|
83
|
+
}
|
|
84
|
+
function newEphemeralConversationStart(conversationId) {
|
|
85
|
+
return {
|
|
86
|
+
conversation_id: conversationId ?? mintMatrxConversationId(),
|
|
87
|
+
is_new: true,
|
|
88
|
+
store: false
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function continueEphemeralConversationStart(conversationId, priorMessages) {
|
|
92
|
+
return {
|
|
93
|
+
conversation_id: conversationId,
|
|
94
|
+
is_new: false,
|
|
95
|
+
store: false,
|
|
96
|
+
prior_messages: priorMessages
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// stream/ndjson.ts
|
|
101
|
+
var DEFAULT_MATRX_NDJSON_READ_AHEAD = 64;
|
|
102
|
+
function isRecord2(value) {
|
|
103
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
104
|
+
}
|
|
105
|
+
function normalizeMatrxStreamEnvelope(value) {
|
|
106
|
+
if (!isRecord2(value)) return null;
|
|
107
|
+
if (typeof value.event === "string") {
|
|
108
|
+
const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
|
|
109
|
+
return {
|
|
110
|
+
event: value.event,
|
|
111
|
+
data: value.data,
|
|
112
|
+
...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
if (value.e === "c" && typeof value.t === "string") {
|
|
116
|
+
return { event: "chunk", data: { text: value.t } };
|
|
117
|
+
}
|
|
118
|
+
if (value.e === "r" && typeof value.t === "string") {
|
|
119
|
+
return { event: "reasoning_chunk", data: { text: value.t } };
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
function createMatrxNdjsonFramer(options = {}) {
|
|
124
|
+
const decoder = new TextDecoder();
|
|
125
|
+
let buffer = "";
|
|
126
|
+
let lineNumber = 0;
|
|
127
|
+
let finished = false;
|
|
128
|
+
const assertOpen = () => {
|
|
129
|
+
if (finished) throw new Error("Matrx NDJSON framer is already finished");
|
|
130
|
+
};
|
|
131
|
+
const parseLine = (line, atCompletion) => {
|
|
132
|
+
const currentLineNumber = ++lineNumber;
|
|
133
|
+
const trimmed = line.trim();
|
|
134
|
+
if (!trimmed) return null;
|
|
135
|
+
let parsed;
|
|
136
|
+
try {
|
|
137
|
+
parsed = JSON.parse(trimmed);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
options.onMalformedLine?.({
|
|
140
|
+
line: trimmed,
|
|
141
|
+
error,
|
|
142
|
+
lineNumber: currentLineNumber,
|
|
143
|
+
atCompletion
|
|
144
|
+
});
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
const envelope = normalizeMatrxStreamEnvelope(parsed);
|
|
148
|
+
if (!envelope) {
|
|
149
|
+
options.onUnknownEnvelope?.(parsed);
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
options.onValidEnvelope?.({
|
|
153
|
+
raw: parsed,
|
|
154
|
+
envelope,
|
|
155
|
+
line: trimmed,
|
|
156
|
+
lineNumber: currentLineNumber,
|
|
157
|
+
atCompletion
|
|
158
|
+
});
|
|
159
|
+
return envelope;
|
|
160
|
+
};
|
|
161
|
+
const pushDecodedText = (fragment) => {
|
|
162
|
+
buffer += fragment;
|
|
163
|
+
const lines = buffer.split("\n");
|
|
164
|
+
buffer = lines.pop() ?? "";
|
|
165
|
+
const envelopes = [];
|
|
166
|
+
for (const line of lines) {
|
|
167
|
+
const envelope = parseLine(line, false);
|
|
168
|
+
if (envelope) envelopes.push(envelope);
|
|
169
|
+
}
|
|
170
|
+
return envelopes;
|
|
171
|
+
};
|
|
172
|
+
return {
|
|
173
|
+
pushText(fragment) {
|
|
174
|
+
assertOpen();
|
|
175
|
+
return pushDecodedText(decoder.decode() + fragment);
|
|
176
|
+
},
|
|
177
|
+
pushBytes(fragment) {
|
|
178
|
+
assertOpen();
|
|
179
|
+
return pushDecodedText(decoder.decode(fragment, { stream: true }));
|
|
180
|
+
},
|
|
181
|
+
finish() {
|
|
182
|
+
assertOpen();
|
|
183
|
+
finished = true;
|
|
184
|
+
const envelopes = pushDecodedText(decoder.decode());
|
|
185
|
+
if (buffer.length > 0) {
|
|
186
|
+
const envelope = parseLine(buffer, true);
|
|
187
|
+
buffer = "";
|
|
188
|
+
if (envelope) envelopes.push(envelope);
|
|
189
|
+
}
|
|
190
|
+
return envelopes;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
function readAheadLimit(value) {
|
|
195
|
+
const limit = value ?? DEFAULT_MATRX_NDJSON_READ_AHEAD;
|
|
196
|
+
if (!Number.isSafeInteger(limit) || limit < 1) {
|
|
197
|
+
throw new RangeError("maxReadAhead must be a positive safe integer");
|
|
198
|
+
}
|
|
199
|
+
return limit;
|
|
200
|
+
}
|
|
201
|
+
async function* readMatrxNdjsonStream(body, options = {}) {
|
|
202
|
+
const maxReadAhead = readAheadLimit(options.maxReadAhead);
|
|
203
|
+
const queue = [];
|
|
204
|
+
let queuedEventCount = 0;
|
|
205
|
+
let wakeConsumer = null;
|
|
206
|
+
let wakeProducer = null;
|
|
207
|
+
let readerFinished = false;
|
|
208
|
+
let consumerClosed = false;
|
|
209
|
+
const wakeWaitingConsumer = () => {
|
|
210
|
+
const wake = wakeConsumer;
|
|
211
|
+
wakeConsumer = null;
|
|
212
|
+
wake?.();
|
|
213
|
+
};
|
|
214
|
+
const wakeWaitingProducer = () => {
|
|
215
|
+
const wake = wakeProducer;
|
|
216
|
+
wakeProducer = null;
|
|
217
|
+
wake?.();
|
|
218
|
+
};
|
|
219
|
+
const enqueueTerminal = (item) => {
|
|
220
|
+
if (consumerClosed) return;
|
|
221
|
+
queue.push(item);
|
|
222
|
+
wakeWaitingConsumer();
|
|
223
|
+
};
|
|
224
|
+
const enqueueEvent = async (value) => {
|
|
225
|
+
while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
|
|
226
|
+
await new Promise((resolve) => {
|
|
227
|
+
wakeProducer = resolve;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
if (consumerClosed || options.signal?.aborted) return false;
|
|
231
|
+
queue.push({ kind: "event", value });
|
|
232
|
+
queuedEventCount += 1;
|
|
233
|
+
wakeWaitingConsumer();
|
|
234
|
+
return true;
|
|
235
|
+
};
|
|
236
|
+
const waitForReadCapacity = async () => {
|
|
237
|
+
while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
|
|
238
|
+
await new Promise((resolve) => {
|
|
239
|
+
wakeProducer = resolve;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return !consumerClosed && !options.signal?.aborted;
|
|
243
|
+
};
|
|
244
|
+
const reader = body.getReader();
|
|
245
|
+
const framer = createMatrxNdjsonFramer(options);
|
|
246
|
+
const onAbort = () => {
|
|
247
|
+
wakeWaitingProducer();
|
|
248
|
+
wakeWaitingConsumer();
|
|
249
|
+
void reader.cancel(options.signal?.reason).catch(() => void 0);
|
|
250
|
+
};
|
|
251
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
252
|
+
if (options.signal?.aborted) onAbort();
|
|
253
|
+
const readerPromise = (async () => {
|
|
254
|
+
try {
|
|
255
|
+
while (!options.signal?.aborted && !consumerClosed) {
|
|
256
|
+
if (!await waitForReadCapacity()) return;
|
|
257
|
+
const { value, done } = await reader.read();
|
|
258
|
+
if (done) break;
|
|
259
|
+
for (const envelope of framer.pushBytes(value)) {
|
|
260
|
+
if (!await enqueueEvent(envelope)) return;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (!options.signal?.aborted && !consumerClosed) {
|
|
264
|
+
for (const envelope of framer.finish()) {
|
|
265
|
+
if (!await enqueueEvent(envelope)) return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
} catch (error) {
|
|
269
|
+
const aborted = options.signal?.aborted || consumerClosed || error instanceof Error && error.name === "AbortError";
|
|
270
|
+
if (!aborted) enqueueTerminal({ kind: "error", error });
|
|
271
|
+
} finally {
|
|
272
|
+
readerFinished = true;
|
|
273
|
+
reader.releaseLock();
|
|
274
|
+
enqueueTerminal({ kind: "done" });
|
|
275
|
+
}
|
|
276
|
+
})();
|
|
277
|
+
try {
|
|
278
|
+
while (true) {
|
|
279
|
+
if (queue.length === 0) {
|
|
280
|
+
if (options.signal?.aborted || readerFinished) return;
|
|
281
|
+
await new Promise((resolve) => {
|
|
282
|
+
wakeConsumer = resolve;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
const item = queue.shift();
|
|
286
|
+
if (item?.kind === "event") queuedEventCount -= 1;
|
|
287
|
+
wakeWaitingProducer();
|
|
288
|
+
if (!item || item.kind === "done") return;
|
|
289
|
+
if (item.kind === "error") throw item.error;
|
|
290
|
+
yield item.value;
|
|
291
|
+
}
|
|
292
|
+
} finally {
|
|
293
|
+
consumerClosed = true;
|
|
294
|
+
wakeWaitingProducer();
|
|
295
|
+
wakeWaitingConsumer();
|
|
296
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
297
|
+
if (!readerFinished) {
|
|
298
|
+
await reader.cancel().catch(() => void 0);
|
|
299
|
+
}
|
|
300
|
+
await readerPromise;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// matrx/internal.ts
|
|
305
|
+
function encodePathSegment(value) {
|
|
306
|
+
return encodeURIComponent(value);
|
|
307
|
+
}
|
|
308
|
+
function buildQuery(params) {
|
|
309
|
+
const search = new URLSearchParams();
|
|
310
|
+
for (const [key, value] of Object.entries(params)) {
|
|
311
|
+
if (value === void 0) continue;
|
|
312
|
+
if (Array.isArray(value)) {
|
|
313
|
+
for (const entry of value) search.append(key, entry);
|
|
314
|
+
} else {
|
|
315
|
+
search.append(key, String(value));
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
const encoded = search.toString();
|
|
319
|
+
return encoded ? `?${encoded}` : "";
|
|
320
|
+
}
|
|
321
|
+
async function readServerDetail(response) {
|
|
322
|
+
try {
|
|
323
|
+
return await response.json();
|
|
324
|
+
} catch {
|
|
325
|
+
return void 0;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
async function throwApiError(path, response) {
|
|
329
|
+
throw new MatrxApiError({
|
|
330
|
+
status: response.status,
|
|
331
|
+
path,
|
|
332
|
+
serverDetail: await readServerDetail(response)
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
async function requestJson(transport, path, options) {
|
|
336
|
+
const hasBody = options.method !== "GET" && options.body !== void 0;
|
|
337
|
+
const response = await transport.fetch(path, {
|
|
338
|
+
method: options.method,
|
|
339
|
+
headers: hasBody ? { "Content-Type": "application/json" } : {},
|
|
340
|
+
...hasBody ? { body: JSON.stringify(options.body) } : {},
|
|
341
|
+
...options.signal ? { signal: options.signal } : {}
|
|
342
|
+
});
|
|
343
|
+
if (!response.ok) return throwApiError(path, response);
|
|
344
|
+
return await response.json();
|
|
345
|
+
}
|
|
346
|
+
function toRunHandle(response, options) {
|
|
347
|
+
return {
|
|
348
|
+
requestId: response.headers.get("X-Request-ID"),
|
|
349
|
+
conversationId: response.headers.get("X-Conversation-ID"),
|
|
350
|
+
events: readMatrxNdjsonStream(response.body, {
|
|
351
|
+
...options.signal ? { signal: options.signal } : {},
|
|
352
|
+
...options.maxReadAhead !== void 0 ? { maxReadAhead: options.maxReadAhead } : {},
|
|
353
|
+
...options.onMalformedLine ? { onMalformedLine: options.onMalformedLine } : {},
|
|
354
|
+
...options.onUnknownEnvelope ? { onUnknownEnvelope: options.onUnknownEnvelope } : {},
|
|
355
|
+
...options.onValidEnvelope ? { onValidEnvelope: options.onValidEnvelope } : {}
|
|
356
|
+
}),
|
|
357
|
+
response
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
async function requestStream(transport, path, options) {
|
|
361
|
+
const hasBody = options.method !== "GET" && options.body !== void 0;
|
|
362
|
+
const response = await transport.fetch(path, {
|
|
363
|
+
method: options.method,
|
|
364
|
+
headers: {
|
|
365
|
+
...hasBody ? { "Content-Type": "application/json" } : {},
|
|
366
|
+
...options.headers
|
|
367
|
+
},
|
|
368
|
+
...hasBody ? { body: JSON.stringify(options.body) } : {},
|
|
369
|
+
...options.signal ? { signal: options.signal } : {}
|
|
370
|
+
});
|
|
371
|
+
if (!response.ok) return throwApiError(path, response);
|
|
372
|
+
if (!response.body) {
|
|
373
|
+
throw new MatrxApiError({
|
|
374
|
+
status: response.status,
|
|
375
|
+
path,
|
|
376
|
+
serverDetail: { code: "missing_response_body" },
|
|
377
|
+
message: "The streaming response carried no body."
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
return response;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// matrx/run.ts
|
|
384
|
+
async function streamCall(transport, path, body, options) {
|
|
385
|
+
const response = await requestStream(transport, path, {
|
|
386
|
+
method: "POST",
|
|
387
|
+
// This client IS the streaming path — `stream: true` always, last so a
|
|
388
|
+
// caller-supplied value can never flip the response off NDJSON.
|
|
389
|
+
body: { ...body, stream: true },
|
|
390
|
+
...options.signal ? { signal: options.signal } : {}
|
|
391
|
+
});
|
|
392
|
+
return toRunHandle(response, options);
|
|
393
|
+
}
|
|
394
|
+
function startAgentRun(transport, agentId, request, options = {}) {
|
|
395
|
+
return streamCall(
|
|
396
|
+
transport,
|
|
397
|
+
`/ai/agents/${encodePathSegment(agentId)}`,
|
|
398
|
+
request,
|
|
399
|
+
options
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
function continueAgentConversation(transport, conversationId, request, options = {}) {
|
|
403
|
+
return streamCall(
|
|
404
|
+
transport,
|
|
405
|
+
`/ai/conversations/${encodePathSegment(conversationId)}`,
|
|
406
|
+
request,
|
|
407
|
+
options
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
|
|
411
|
+
return streamCall(
|
|
412
|
+
transport,
|
|
413
|
+
`/ai/conversations/${encodePathSegment(conversationId)}/resume`,
|
|
414
|
+
request,
|
|
415
|
+
options
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
function cancelAgentRun(transport, requestId, options = {}) {
|
|
419
|
+
const query = buildQuery(
|
|
420
|
+
options.mode === "interrupt" ? { mode: "interrupt" } : {}
|
|
421
|
+
);
|
|
422
|
+
return requestJson(
|
|
423
|
+
transport,
|
|
424
|
+
`/ai/cancel/${encodePathSegment(requestId)}${query}`,
|
|
425
|
+
{
|
|
426
|
+
method: "POST",
|
|
427
|
+
...options.signal ? { signal: options.signal } : {}
|
|
428
|
+
}
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
var MatrxRunError = class extends Error {
|
|
432
|
+
name = "MatrxRunError";
|
|
433
|
+
/** The verbatim `error` event payload, when one fired. */
|
|
434
|
+
errorPayload;
|
|
435
|
+
/** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
|
|
436
|
+
completionStatus;
|
|
437
|
+
/** Text streamed before the failure — partial content never vanishes. */
|
|
438
|
+
partialText;
|
|
439
|
+
constructor(args) {
|
|
440
|
+
super(args.message);
|
|
441
|
+
this.errorPayload = args.errorPayload ?? null;
|
|
442
|
+
this.completionStatus = args.completionStatus ?? null;
|
|
443
|
+
this.partialText = args.partialText ?? "";
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
function isRecord3(value) {
|
|
447
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
448
|
+
}
|
|
449
|
+
function stringField(value, key) {
|
|
450
|
+
if (!isRecord3(value)) return null;
|
|
451
|
+
const field = value[key];
|
|
452
|
+
return typeof field === "string" && field ? field : null;
|
|
453
|
+
}
|
|
454
|
+
async function runAgentToCompletion(transport, agentId, request, options = {}) {
|
|
455
|
+
const handle = await startAgentRun(transport, agentId, request, options);
|
|
456
|
+
let text = "";
|
|
457
|
+
let completion = null;
|
|
458
|
+
let failure = null;
|
|
459
|
+
for await (const envelope of handle.events) {
|
|
460
|
+
options.onEvent?.(envelope);
|
|
461
|
+
if (envelope.event === "chunk") {
|
|
462
|
+
const chunk = stringField(envelope.data, "text");
|
|
463
|
+
if (chunk !== null) {
|
|
464
|
+
text += chunk;
|
|
465
|
+
options.onChunk?.(text);
|
|
466
|
+
}
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
if (envelope.event === "error" && failure === null) {
|
|
470
|
+
const payload = isRecord3(envelope.data) ? envelope.data : null;
|
|
471
|
+
failure = new MatrxRunError({
|
|
472
|
+
message: stringField(payload, "user_message") ?? stringField(payload, "message") ?? "The agent run failed",
|
|
473
|
+
errorPayload: payload,
|
|
474
|
+
partialText: text
|
|
475
|
+
});
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (envelope.event !== "completion" || !isRecord3(envelope.data)) continue;
|
|
479
|
+
if (envelope.data.operation !== "user_request") continue;
|
|
480
|
+
completion = envelope.data;
|
|
481
|
+
const status = envelope.data.status;
|
|
482
|
+
if ((status === "failed" || status === "cancelled") && failure === null) {
|
|
483
|
+
const result = isRecord3(envelope.data.result) ? envelope.data.result : null;
|
|
484
|
+
failure = new MatrxRunError({
|
|
485
|
+
message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
|
|
486
|
+
completionStatus: status,
|
|
487
|
+
partialText: text
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (failure) throw failure;
|
|
492
|
+
if (!text && completion) {
|
|
493
|
+
const result = completion.result;
|
|
494
|
+
const output = stringField(result, "output");
|
|
495
|
+
if (output !== null) text = output;
|
|
496
|
+
}
|
|
497
|
+
return {
|
|
498
|
+
text,
|
|
499
|
+
requestId: handle.requestId,
|
|
500
|
+
conversationId: handle.conversationId,
|
|
501
|
+
completion
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// stream/sse.ts
|
|
506
|
+
var FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/;
|
|
507
|
+
var LINE_SEPARATOR = /\r\n|\n|\r/;
|
|
508
|
+
function parseMatrxSseFrame(frame) {
|
|
509
|
+
let event = "message";
|
|
510
|
+
let id = null;
|
|
511
|
+
const dataLines = [];
|
|
512
|
+
let sawData = false;
|
|
513
|
+
for (const line of frame.split(LINE_SEPARATOR)) {
|
|
514
|
+
if (line.startsWith(":")) continue;
|
|
515
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
516
|
+
else if (line.startsWith("data:")) {
|
|
517
|
+
sawData = true;
|
|
518
|
+
dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
519
|
+
} else if (line.startsWith("id:")) id = line.slice(3).trim();
|
|
520
|
+
}
|
|
521
|
+
const seqCandidate = id !== null && id !== "" ? Number(id) : NaN;
|
|
522
|
+
const seq = Number.isSafeInteger(seqCandidate) && seqCandidate >= 0 ? seqCandidate : null;
|
|
523
|
+
return { event, id, seq, data: sawData ? dataLines.join("\n") : null };
|
|
524
|
+
}
|
|
525
|
+
function createMatrxSseFramer() {
|
|
526
|
+
let buffer = "";
|
|
527
|
+
return {
|
|
528
|
+
push(chunk) {
|
|
529
|
+
buffer += chunk;
|
|
530
|
+
const frames = [];
|
|
531
|
+
for (; ; ) {
|
|
532
|
+
const sep = FRAME_SEPARATOR.exec(buffer);
|
|
533
|
+
if (sep === null) break;
|
|
534
|
+
const frame = buffer.slice(0, sep.index);
|
|
535
|
+
buffer = buffer.slice(sep.index + sep[0].length);
|
|
536
|
+
frames.push(parseMatrxSseFrame(frame));
|
|
537
|
+
}
|
|
538
|
+
return frames;
|
|
539
|
+
},
|
|
540
|
+
flush() {
|
|
541
|
+
const rest = buffer;
|
|
542
|
+
buffer = "";
|
|
543
|
+
return { incomplete: rest.length > 0 ? rest : null };
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
async function* readMatrxSseStream(stream, options = {}) {
|
|
548
|
+
const reader = stream.getReader();
|
|
549
|
+
const decoder = new TextDecoder();
|
|
550
|
+
const framer = createMatrxSseFramer();
|
|
551
|
+
try {
|
|
552
|
+
for (; ; ) {
|
|
553
|
+
const { value, done } = await reader.read();
|
|
554
|
+
if (done) break;
|
|
555
|
+
const frames = framer.push(decoder.decode(value, { stream: true }));
|
|
556
|
+
for (const frame of frames) yield frame;
|
|
557
|
+
}
|
|
558
|
+
const tail = framer.push(decoder.decode());
|
|
559
|
+
for (const frame of tail) yield frame;
|
|
560
|
+
const { incomplete } = framer.flush();
|
|
561
|
+
if (incomplete !== null) options.onIncomplete?.(incomplete);
|
|
562
|
+
} finally {
|
|
563
|
+
reader.releaseLock();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// matrx/operations.ts
|
|
568
|
+
var TERMINAL_MATRX_RUNTIME_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
|
|
569
|
+
var RUNTIME_STATUSES = /* @__PURE__ */ new Set([
|
|
570
|
+
"pending",
|
|
571
|
+
"running",
|
|
572
|
+
"paused",
|
|
573
|
+
"waiting_input",
|
|
574
|
+
"completed",
|
|
575
|
+
"failed",
|
|
576
|
+
"cancelled"
|
|
577
|
+
]);
|
|
578
|
+
async function getRuntimeOperationStatus(transport, requestId, options = {}) {
|
|
579
|
+
try {
|
|
580
|
+
return await requestJson(
|
|
581
|
+
transport,
|
|
582
|
+
`/runtime/operations/${encodePathSegment(requestId)}`,
|
|
583
|
+
{ method: "GET", ...options.signal ? { signal: options.signal } : {} }
|
|
584
|
+
);
|
|
585
|
+
} catch (error) {
|
|
586
|
+
if (error instanceof MatrxApiError && error.status === 404) return null;
|
|
587
|
+
throw error;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
async function getRuntimeOperationsByLink(transport, linkKind, linkId, options = {}) {
|
|
591
|
+
const query = buildQuery(
|
|
592
|
+
options.limit !== void 0 ? { limit: options.limit } : {}
|
|
593
|
+
);
|
|
594
|
+
try {
|
|
595
|
+
return await requestJson(
|
|
596
|
+
transport,
|
|
597
|
+
`/runtime/operations/by-link/${encodePathSegment(linkKind)}/${encodePathSegment(linkId)}${query}`,
|
|
598
|
+
{ method: "GET", ...options.signal ? { signal: options.signal } : {} }
|
|
599
|
+
);
|
|
600
|
+
} catch (error) {
|
|
601
|
+
if (error instanceof MatrxApiError && error.status === 404) return null;
|
|
602
|
+
throw error;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
function listRuntimeOperationEvents(transport, executionId, options = {}) {
|
|
606
|
+
const query = buildQuery({
|
|
607
|
+
...options.afterSeq !== void 0 ? { after_seq: options.afterSeq } : {},
|
|
608
|
+
...options.limit !== void 0 ? { limit: options.limit } : {},
|
|
609
|
+
...options.kinds !== void 0 ? { kind: options.kinds } : {}
|
|
610
|
+
});
|
|
611
|
+
return requestJson(
|
|
612
|
+
transport,
|
|
613
|
+
`/runtime/executions/${encodePathSegment(executionId)}/events${query}`,
|
|
614
|
+
{ method: "GET", ...options.signal ? { signal: options.signal } : {} }
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
function parseEndStatus(data) {
|
|
618
|
+
if (data === null) return null;
|
|
619
|
+
try {
|
|
620
|
+
const parsed = JSON.parse(data);
|
|
621
|
+
if (typeof parsed === "object" && parsed !== null && typeof parsed.status === "string") {
|
|
622
|
+
const status = parsed.status;
|
|
623
|
+
return RUNTIME_STATUSES.has(status) ? status : null;
|
|
624
|
+
}
|
|
625
|
+
} catch {
|
|
626
|
+
}
|
|
627
|
+
return null;
|
|
628
|
+
}
|
|
629
|
+
async function* followRuntimeOperationEvents(transport, executionId, options = {}) {
|
|
630
|
+
let cursor = options.lastEventSeq ?? 0;
|
|
631
|
+
const headers = { Accept: "text/event-stream" };
|
|
632
|
+
if (cursor > 0) headers["Last-Event-ID"] = String(cursor);
|
|
633
|
+
const response = await requestStream(
|
|
634
|
+
transport,
|
|
635
|
+
`/runtime/executions/${encodePathSegment(executionId)}/events/stream`,
|
|
636
|
+
{
|
|
637
|
+
method: "GET",
|
|
638
|
+
headers,
|
|
639
|
+
...options.signal ? { signal: options.signal } : {}
|
|
640
|
+
}
|
|
641
|
+
);
|
|
642
|
+
const frames = readMatrxSseStream(
|
|
643
|
+
response.body,
|
|
644
|
+
options.onIncomplete ? { onIncomplete: options.onIncomplete } : {}
|
|
645
|
+
);
|
|
646
|
+
for await (const frame of frames) {
|
|
647
|
+
if (frame.event === "end") {
|
|
648
|
+
yield { type: "end", status: parseEndStatus(frame.data), cursor };
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
if (frame.event === "execution_event" && frame.data !== null) {
|
|
652
|
+
let event;
|
|
653
|
+
try {
|
|
654
|
+
event = JSON.parse(frame.data);
|
|
655
|
+
} catch (error) {
|
|
656
|
+
options.onMalformedFrame?.(frame, error);
|
|
657
|
+
yield { type: "liveness", cursor };
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
if (frame.seq !== null && frame.seq > cursor) cursor = frame.seq;
|
|
661
|
+
yield { type: "event", event, seq: frame.seq, cursor };
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
yield { type: "liveness", cursor };
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
async function rejoinRuntimeOperation(transport, requestId, options = {}) {
|
|
668
|
+
const response = await requestStream(
|
|
669
|
+
transport,
|
|
670
|
+
`/runtime/operations/${encodePathSegment(requestId)}/rejoin`,
|
|
671
|
+
{
|
|
672
|
+
method: "POST",
|
|
673
|
+
// The route takes no body model; the reference client posts an empty
|
|
674
|
+
// JSON object. Match it so proxies see an ordinary JSON POST.
|
|
675
|
+
body: {},
|
|
676
|
+
...options.signal ? { signal: options.signal } : {}
|
|
677
|
+
}
|
|
678
|
+
);
|
|
679
|
+
return toRunHandle(response, options);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// matrx/tools.ts
|
|
683
|
+
function submitAgentToolResults(transport, conversationId, results, options = {}) {
|
|
684
|
+
return requestJson(
|
|
685
|
+
transport,
|
|
686
|
+
`/ai/conversations/${encodePathSegment(conversationId)}/tool_results`,
|
|
687
|
+
{
|
|
688
|
+
method: "POST",
|
|
689
|
+
body: {
|
|
690
|
+
results,
|
|
691
|
+
...options.instanceId !== void 0 ? { instance_id: options.instanceId } : {}
|
|
692
|
+
},
|
|
693
|
+
...options.signal ? { signal: options.signal } : {}
|
|
694
|
+
}
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
function listConversationPendingToolCalls(transport, conversationId, options = {}) {
|
|
698
|
+
return requestJson(
|
|
699
|
+
transport,
|
|
700
|
+
`/ai/conversations/${encodePathSegment(conversationId)}/pending_calls`,
|
|
701
|
+
{
|
|
702
|
+
method: "GET",
|
|
703
|
+
...options.signal ? { signal: options.signal } : {}
|
|
704
|
+
}
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
function listUserPendingToolCalls(transport, options = {}) {
|
|
708
|
+
const query = buildQuery(
|
|
709
|
+
options.instanceId !== void 0 ? { instance_id: options.instanceId } : {}
|
|
710
|
+
);
|
|
711
|
+
return requestJson(
|
|
712
|
+
transport,
|
|
713
|
+
`/ai/user/pending_calls${query}`,
|
|
714
|
+
{
|
|
715
|
+
method: "GET",
|
|
716
|
+
...options.signal ? { signal: options.signal } : {}
|
|
717
|
+
}
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
export { MatrxApiError, MatrxRunError, TERMINAL_MATRX_RUNTIME_STATUSES, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, extractMatrxErrorCode, extractMatrxErrorMessage, followRuntimeOperationEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, rejoinRuntimeOperation, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults };
|
|
722
|
+
//# sourceMappingURL=index.js.map
|
|
723
|
+
//# sourceMappingURL=index.js.map
|