@ai-matrx/agents 0.22.0 → 0.23.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/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@ export { projectAgentResultForDisplay } from './presentation/result.cjs';
4
4
  export { AgentProjectionEvent, AgentProjectionOperation, AgentProjectionRenderBlock, AgentProjectionStatus, AgentProjectionTool, AgentRequestProjection, createAgentRequestProjection, projectAgentEvent, projectAgentEvents } from './projection/request.cjs';
5
5
  export { DEFAULT_WORKFLOW_PROJECTION_LIMITS, WorkflowNodeProjection, WorkflowNodeStreamEvent, WorkflowProjectionLimits, WorkflowRenderBlockIssue, WorkflowRenderBlockIssueCode, WorkflowRenderFrameSet, createWorkflowNodeProjection, projectWorkflowNodeEvent } from './projection/workflow.cjs';
6
6
  export { F as FollowRuntimeOperationOptions, a as FollowRuntimeOperationToEndOptions, b as FollowRuntimeOperationToEndResult, M as MatrxAgentStartRequest, c as MatrxApiError, d as MatrxCancelResponse, e as MatrxChatMessage, f as MatrxCompletedRun, g as MatrxContextAnchor, h as MatrxConversationContinueRequest, i as MatrxConversationResumeRequest, j as MatrxConversationStart, k as MatrxEphemeralConversation, l as MatrxJsonObject, m as MatrxJsonValue, n as MatrxMandateStartRequest, o as MatrxOperationEventsPage, p as MatrxOperationFollowEvent, q as MatrxOperationStatusResponse, r as MatrxOperationsByLinkResponse, s as MatrxRequestScope, t as MatrxRunError, u as MatrxRunHandle, v as MatrxRuntimeExecutionStatus, w as MatrxRuntimeOperationEvent, x as MatrxRuntimeOperationView, y as MatrxStoredConversationContinue, z as MatrxStoredConversationCreate, A as MatrxStreamCallOptions, B as MatrxTransport, C as MatrxTransportRequest, D as MatrxTurnFields, R as RunAgentToCompletionOptions, T as TERMINAL_MATRX_RUNTIME_STATUSES, E as cancelAgentRun, G as continueAgentConversation, H as continueEphemeralConversationStart, I as continueStoredConversationStart, J as extractMatrxErrorCode, K as extractMatrxErrorMessage, L as followRuntimeOperationEvents, N as followRuntimeOperationToEnd, O as getRuntimeOperationStatus, P as getRuntimeOperationsByLink, Q as listRuntimeOperationEvents, S as mintMatrxConversationId, U as newEphemeralConversationStart, V as newStoredConversationStart, W as rejoinRuntimeOperation, X as resumeAgentConversation, Y as runAgentToCompletion, Z as startAgentRun, _ as startMandateRun } from './operations--f5ko9Su.cjs';
7
- export { CreateMatrxTransportOptions, MATRX_AI_API_VERSION_DEFAULT, MatrxAiApiVersion, MatrxCallError, MatrxClientToolResult, MatrxPendingCallSummary, MatrxProtocolDowngrade, MatrxProtocolFallbackOptions, MatrxRequestInfo, MatrxToolResultsResponse, MatrxTransportDiagnostics, MatrxTransportTarget, OrganizationContextError, OrganizationContextErrorCode, OrganizationOperation, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createMatrxTransport, createOrganizationOperation, fetchWithMatrxProtocolFallback, isCoveredAiPath, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, requireOrganizationContext, submitAgentToolResults, toV1FallbackUrl, toV2Path } from './matrx/index.cjs';
7
+ export { CreateMatrxTransportOptions, MATRX_AI_API_VERSION_DEFAULT, MATRX_LIVE_STREAM_UNAVAILABLE, MATRX_RESUME_CONFLICT, MATRX_RUN_IN_PROGRESS, MatrxAiApiVersion, MatrxCallError, MatrxClientSessionProvider, MatrxClientToolResult, MatrxHttpErrorLike, MatrxPendingCallSummary, MatrxProtocolDowngrade, MatrxProtocolFallbackOptions, MatrxRequestInfo, MatrxToolResultsResponse, MatrxTransportDiagnostics, MatrxTransportTarget, OrganizationContextError, OrganizationContextErrorCode, OrganizationOperation, ProviderSessionFailure, ProviderSessionFailureVerdict, ResumeOrRejoinOptions, ResumeOrRejoinOutcome, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createMatrxTransport, createOrganizationOperation, fetchWithMatrxProtocolFallback, isCoveredAiPath, isLiveStreamUnavailable, isResumeConflict, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, openMatrxStream, providerSessionFailureBody, readLiveRunRequestId, readMatrxErrorCode, reportProviderSessionFailure, requireOrganizationContext, resumeOrRejoin, runtimeOperationRejoinPath, streamErrorText, submitAgentToolResults, toV1FallbackUrl, toV2Path, withRunOrganization } from './matrx/index.cjs';
8
8
  import '@ai-matrx/data';
9
9
  import '@ai-matrx/data/net';
10
10
 
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { projectAgentResultForDisplay } from './presentation/result.js';
4
4
  export { AgentProjectionEvent, AgentProjectionOperation, AgentProjectionRenderBlock, AgentProjectionStatus, AgentProjectionTool, AgentRequestProjection, createAgentRequestProjection, projectAgentEvent, projectAgentEvents } from './projection/request.js';
5
5
  export { DEFAULT_WORKFLOW_PROJECTION_LIMITS, WorkflowNodeProjection, WorkflowNodeStreamEvent, WorkflowProjectionLimits, WorkflowRenderBlockIssue, WorkflowRenderBlockIssueCode, WorkflowRenderFrameSet, createWorkflowNodeProjection, projectWorkflowNodeEvent } from './projection/workflow.js';
6
6
  export { F as FollowRuntimeOperationOptions, a as FollowRuntimeOperationToEndOptions, b as FollowRuntimeOperationToEndResult, M as MatrxAgentStartRequest, c as MatrxApiError, d as MatrxCancelResponse, e as MatrxChatMessage, f as MatrxCompletedRun, g as MatrxContextAnchor, h as MatrxConversationContinueRequest, i as MatrxConversationResumeRequest, j as MatrxConversationStart, k as MatrxEphemeralConversation, l as MatrxJsonObject, m as MatrxJsonValue, n as MatrxMandateStartRequest, o as MatrxOperationEventsPage, p as MatrxOperationFollowEvent, q as MatrxOperationStatusResponse, r as MatrxOperationsByLinkResponse, s as MatrxRequestScope, t as MatrxRunError, u as MatrxRunHandle, v as MatrxRuntimeExecutionStatus, w as MatrxRuntimeOperationEvent, x as MatrxRuntimeOperationView, y as MatrxStoredConversationContinue, z as MatrxStoredConversationCreate, A as MatrxStreamCallOptions, B as MatrxTransport, C as MatrxTransportRequest, D as MatrxTurnFields, R as RunAgentToCompletionOptions, T as TERMINAL_MATRX_RUNTIME_STATUSES, E as cancelAgentRun, G as continueAgentConversation, H as continueEphemeralConversationStart, I as continueStoredConversationStart, J as extractMatrxErrorCode, K as extractMatrxErrorMessage, L as followRuntimeOperationEvents, N as followRuntimeOperationToEnd, O as getRuntimeOperationStatus, P as getRuntimeOperationsByLink, Q as listRuntimeOperationEvents, S as mintMatrxConversationId, U as newEphemeralConversationStart, V as newStoredConversationStart, W as rejoinRuntimeOperation, X as resumeAgentConversation, Y as runAgentToCompletion, Z as startAgentRun, _ as startMandateRun } from './operations-Dp4ut-ac.js';
7
- export { CreateMatrxTransportOptions, MATRX_AI_API_VERSION_DEFAULT, MatrxAiApiVersion, MatrxCallError, MatrxClientToolResult, MatrxPendingCallSummary, MatrxProtocolDowngrade, MatrxProtocolFallbackOptions, MatrxRequestInfo, MatrxToolResultsResponse, MatrxTransportDiagnostics, MatrxTransportTarget, OrganizationContextError, OrganizationContextErrorCode, OrganizationOperation, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createMatrxTransport, createOrganizationOperation, fetchWithMatrxProtocolFallback, isCoveredAiPath, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, requireOrganizationContext, submitAgentToolResults, toV1FallbackUrl, toV2Path } from './matrx/index.js';
7
+ export { CreateMatrxTransportOptions, MATRX_AI_API_VERSION_DEFAULT, MATRX_LIVE_STREAM_UNAVAILABLE, MATRX_RESUME_CONFLICT, MATRX_RUN_IN_PROGRESS, MatrxAiApiVersion, MatrxCallError, MatrxClientSessionProvider, MatrxClientToolResult, MatrxHttpErrorLike, MatrxPendingCallSummary, MatrxProtocolDowngrade, MatrxProtocolFallbackOptions, MatrxRequestInfo, MatrxToolResultsResponse, MatrxTransportDiagnostics, MatrxTransportTarget, OrganizationContextError, OrganizationContextErrorCode, OrganizationOperation, ProviderSessionFailure, ProviderSessionFailureVerdict, ResumeOrRejoinOptions, ResumeOrRejoinOutcome, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createMatrxTransport, createOrganizationOperation, fetchWithMatrxProtocolFallback, isCoveredAiPath, isLiveStreamUnavailable, isResumeConflict, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, openMatrxStream, providerSessionFailureBody, readLiveRunRequestId, readMatrxErrorCode, reportProviderSessionFailure, requireOrganizationContext, resumeOrRejoin, runtimeOperationRejoinPath, streamErrorText, submitAgentToolResults, toV1FallbackUrl, toV2Path, withRunOrganization } from './matrx/index.js';
8
8
  import '@ai-matrx/data';
9
9
  import '@ai-matrx/data/net';
10
10
 
package/dist/index.js CHANGED
@@ -1270,136 +1270,6 @@ async function requestStream(transport, path, options) {
1270
1270
  return response;
1271
1271
  }
1272
1272
 
1273
- // matrx/run.ts
1274
- async function streamCall(transport, path, body, options) {
1275
- const response = await requestStream(transport, path, {
1276
- method: "POST",
1277
- // This client IS the streaming path — `stream: true` always, last so a
1278
- // caller-supplied value can never flip the response off NDJSON.
1279
- body: { ...body, stream: true },
1280
- ...options.signal ? { signal: options.signal } : {}
1281
- });
1282
- return toRunHandle(response, options);
1283
- }
1284
- function startAgentRun(transport, agentId, request, options = {}) {
1285
- return streamCall(
1286
- transport,
1287
- `/ai/agents/${encodePathSegment(agentId)}`,
1288
- request,
1289
- options
1290
- );
1291
- }
1292
- function startMandateRun(transport, mandateKey, request, options = {}) {
1293
- return streamCall(
1294
- transport,
1295
- `/ai/mandates/${encodePathSegment(mandateKey)}`,
1296
- request,
1297
- options
1298
- );
1299
- }
1300
- function continueAgentConversation(transport, conversationId, request, options = {}) {
1301
- return streamCall(
1302
- transport,
1303
- `/ai/conversations/${encodePathSegment(conversationId)}`,
1304
- request,
1305
- options
1306
- );
1307
- }
1308
- function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
1309
- return streamCall(
1310
- transport,
1311
- `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
1312
- request,
1313
- options
1314
- );
1315
- }
1316
- function cancelAgentRun(transport, requestId, options = {}) {
1317
- const query = buildQuery(
1318
- options.mode === "interrupt" ? { mode: "interrupt" } : {}
1319
- );
1320
- return requestJson(
1321
- transport,
1322
- `/ai/cancel/${encodePathSegment(requestId)}${query}`,
1323
- {
1324
- method: "POST",
1325
- ...options.signal ? { signal: options.signal } : {}
1326
- }
1327
- );
1328
- }
1329
- var MatrxRunError = class extends Error {
1330
- name = "MatrxRunError";
1331
- /** The verbatim `error` event payload, when one fired. */
1332
- errorPayload;
1333
- /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
1334
- completionStatus;
1335
- /** Text streamed before the failure — partial content never vanishes. */
1336
- partialText;
1337
- constructor(args) {
1338
- super(args.message);
1339
- this.errorPayload = args.errorPayload ?? null;
1340
- this.completionStatus = args.completionStatus ?? null;
1341
- this.partialText = args.partialText ?? "";
1342
- }
1343
- };
1344
- function isRecord4(value) {
1345
- return typeof value === "object" && value !== null && !Array.isArray(value);
1346
- }
1347
- function stringField(value, key) {
1348
- if (!isRecord4(value)) return null;
1349
- const field = value[key];
1350
- return typeof field === "string" && field ? field : null;
1351
- }
1352
- async function runAgentToCompletion(transport, agentId, request, options = {}) {
1353
- const handle = await startAgentRun(transport, agentId, request, options);
1354
- let text = "";
1355
- let completion = null;
1356
- let failure = null;
1357
- for await (const envelope of handle.events) {
1358
- options.onEvent?.(envelope);
1359
- if (envelope.event === "chunk") {
1360
- const chunk = stringField(envelope.data, "text");
1361
- if (chunk !== null) {
1362
- text += chunk;
1363
- options.onChunk?.(text);
1364
- }
1365
- continue;
1366
- }
1367
- if (envelope.event === "error" && failure === null) {
1368
- const payload = isRecord4(envelope.data) ? envelope.data : null;
1369
- failure = new MatrxRunError({
1370
- message: stringField(payload, "user_message") ?? stringField(payload, "message") ?? "The agent run failed",
1371
- errorPayload: payload,
1372
- partialText: text
1373
- });
1374
- continue;
1375
- }
1376
- if (envelope.event !== "completion" || !isRecord4(envelope.data)) continue;
1377
- if (envelope.data.operation !== "user_request") continue;
1378
- completion = envelope.data;
1379
- const status = envelope.data.status;
1380
- if ((status === "failed" || status === "cancelled") && failure === null) {
1381
- const result = isRecord4(envelope.data.result) ? envelope.data.result : null;
1382
- failure = new MatrxRunError({
1383
- message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
1384
- completionStatus: status,
1385
- partialText: text
1386
- });
1387
- }
1388
- }
1389
- if (failure) throw failure;
1390
- if (!text && completion) {
1391
- const result = completion.result;
1392
- const output = stringField(result, "output");
1393
- if (output !== null) text = output;
1394
- }
1395
- return {
1396
- text,
1397
- requestId: handle.requestId,
1398
- conversationId: handle.conversationId,
1399
- completion
1400
- };
1401
- }
1402
-
1403
1273
  // matrx/operations.ts
1404
1274
  var TERMINAL_MATRX_RUNTIME_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
1405
1275
  var RUNTIME_STATUSES = /* @__PURE__ */ new Set([
@@ -1564,6 +1434,317 @@ async function rejoinRuntimeOperation(transport, requestId, options = {}) {
1564
1434
  return toRunHandle(response, options);
1565
1435
  }
1566
1436
 
1437
+ // matrx/rejoin.ts
1438
+ var MATRX_RUN_IN_PROGRESS = "run_in_progress";
1439
+ var MATRX_RESUME_CONFLICT = "resume_conflict";
1440
+ var MATRX_LIVE_STREAM_UNAVAILABLE = "live_stream_unavailable";
1441
+ function isRecord4(value) {
1442
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1443
+ }
1444
+ function nonBlank(value) {
1445
+ return typeof value === "string" && value.trim() ? value : null;
1446
+ }
1447
+ function detailCandidates(body) {
1448
+ if (!isRecord4(body)) return [];
1449
+ const out = [];
1450
+ if (isRecord4(body.detail)) out.push(body.detail);
1451
+ if (isRecord4(body.details)) out.push(body.details);
1452
+ out.push(body);
1453
+ return out;
1454
+ }
1455
+ function statusOf(error) {
1456
+ if (!isRecord4(error) && !(error instanceof Error)) return null;
1457
+ const status = error.status;
1458
+ return typeof status === "number" ? status : null;
1459
+ }
1460
+ function bodyOf(error) {
1461
+ if (!isRecord4(error) && !(error instanceof Error)) return void 0;
1462
+ return error.serverDetail;
1463
+ }
1464
+ function readMatrxErrorCode(error) {
1465
+ for (const candidate of detailCandidates(bodyOf(error))) {
1466
+ const code = nonBlank(candidate.code);
1467
+ if (code) return code;
1468
+ }
1469
+ for (const candidate of detailCandidates(bodyOf(error))) {
1470
+ const code = nonBlank(candidate.error);
1471
+ if (code) return code;
1472
+ }
1473
+ return null;
1474
+ }
1475
+ function readLiveRunRequestId(error) {
1476
+ if (statusOf(error) !== 409) return null;
1477
+ for (const candidate of detailCandidates(bodyOf(error))) {
1478
+ if (candidate.code !== MATRX_RUN_IN_PROGRESS) continue;
1479
+ const live = nonBlank(candidate.live_request_id);
1480
+ if (live) return live.trim();
1481
+ }
1482
+ return null;
1483
+ }
1484
+ function isResumeConflict(error) {
1485
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_RESUME_CONFLICT;
1486
+ }
1487
+ function isLiveStreamUnavailable(error) {
1488
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_LIVE_STREAM_UNAVAILABLE;
1489
+ }
1490
+ function runtimeOperationRejoinPath(requestId) {
1491
+ return `/runtime/operations/${encodePathSegment(requestId)}/rejoin`;
1492
+ }
1493
+ function streamErrorText(eventOrPayload) {
1494
+ if (!isRecord4(eventOrPayload)) return null;
1495
+ const payload = typeof eventOrPayload.event === "string" && isRecord4(eventOrPayload.data) ? eventOrPayload.data : eventOrPayload;
1496
+ return nonBlank(payload.user_message) ?? nonBlank(payload.message);
1497
+ }
1498
+ async function openMatrxStream(transport, path, options = {}) {
1499
+ const response = await requestStream(transport, path, {
1500
+ method: "POST",
1501
+ ...options.body !== void 0 ? { body: options.body } : {},
1502
+ ...options.signal ? { signal: options.signal } : {}
1503
+ });
1504
+ return toRunHandle(response, options);
1505
+ }
1506
+ function withRunOrganization(transport, organizationId) {
1507
+ const orgId = requireOrganizationContext(organizationId);
1508
+ return {
1509
+ fetch: (path, init) => transport.fetch(path, {
1510
+ ...init,
1511
+ headers: { ...init.headers, "X-Organization-Id": orgId }
1512
+ })
1513
+ };
1514
+ }
1515
+ async function drain(handle, onEnvelope) {
1516
+ for await (const envelope of handle.events) onEnvelope(envelope);
1517
+ }
1518
+ async function resumeOrRejoin(transport, resumeCall, options) {
1519
+ const { onEnvelope, organizationId, onRejoin, onOperationEvent, follow, ...rest } = options;
1520
+ const bound = organizationId ? withRunOrganization(transport, organizationId) : transport;
1521
+ const streamOptions = {
1522
+ ...rest,
1523
+ ...options.signal ? { signal: options.signal } : {}
1524
+ };
1525
+ let liveRequestId;
1526
+ try {
1527
+ const handle = await resumeCall(bound, streamOptions);
1528
+ await drain(handle, onEnvelope);
1529
+ return { kind: "resumed", requestId: handle.requestId };
1530
+ } catch (error) {
1531
+ if (error instanceof MatrxApiError && isResumeConflict(error)) {
1532
+ return { kind: "resume_conflict", error };
1533
+ }
1534
+ const live = readLiveRunRequestId(error);
1535
+ if (!live) throw error;
1536
+ liveRequestId = live;
1537
+ }
1538
+ onRejoin?.(liveRequestId);
1539
+ try {
1540
+ const handle = await rejoinRuntimeOperation(bound, liveRequestId, streamOptions);
1541
+ await drain(handle, onEnvelope);
1542
+ return { kind: "rejoined", liveRequestId };
1543
+ } catch (error) {
1544
+ if (!isLiveStreamUnavailable(error)) throw error;
1545
+ }
1546
+ const statusView = await getRuntimeOperationStatus(bound, liveRequestId, {
1547
+ ...options.signal ? { signal: options.signal } : {}
1548
+ });
1549
+ const operation = statusView?.operations.find((op) => !op.is_terminal) ?? statusView?.operations[0] ?? null;
1550
+ if (!operation) {
1551
+ return {
1552
+ kind: "followed",
1553
+ liveRequestId,
1554
+ executionId: null,
1555
+ ended: false,
1556
+ status: null
1557
+ };
1558
+ }
1559
+ if (operation.is_terminal) {
1560
+ return {
1561
+ kind: "followed",
1562
+ liveRequestId,
1563
+ executionId: operation.execution_id,
1564
+ ended: true,
1565
+ status: operation.status
1566
+ };
1567
+ }
1568
+ const result = await followRuntimeOperationToEnd(bound, operation.execution_id, {
1569
+ ...follow,
1570
+ lastEventSeq: operation.last_event_seq,
1571
+ ...options.signal ? { signal: options.signal } : {},
1572
+ onEvent: (event) => onOperationEvent?.(event)
1573
+ });
1574
+ return {
1575
+ kind: "followed",
1576
+ liveRequestId,
1577
+ executionId: operation.execution_id,
1578
+ ended: result.ended,
1579
+ status: result.status
1580
+ };
1581
+ }
1582
+
1583
+ // matrx/run.ts
1584
+ async function streamCall(transport, path, body, options) {
1585
+ const response = await requestStream(transport, path, {
1586
+ method: "POST",
1587
+ // This client IS the streaming path — `stream: true` always, last so a
1588
+ // caller-supplied value can never flip the response off NDJSON.
1589
+ body: { ...body, stream: true },
1590
+ ...options.signal ? { signal: options.signal } : {}
1591
+ });
1592
+ return toRunHandle(response, options);
1593
+ }
1594
+ function startAgentRun(transport, agentId, request, options = {}) {
1595
+ return streamCall(
1596
+ transport,
1597
+ `/ai/agents/${encodePathSegment(agentId)}`,
1598
+ request,
1599
+ options
1600
+ );
1601
+ }
1602
+ function startMandateRun(transport, mandateKey, request, options = {}) {
1603
+ return streamCall(
1604
+ transport,
1605
+ `/ai/mandates/${encodePathSegment(mandateKey)}`,
1606
+ request,
1607
+ options
1608
+ );
1609
+ }
1610
+ function continueAgentConversation(transport, conversationId, request, options = {}) {
1611
+ return streamCall(
1612
+ transport,
1613
+ `/ai/conversations/${encodePathSegment(conversationId)}`,
1614
+ request,
1615
+ options
1616
+ );
1617
+ }
1618
+ function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
1619
+ return streamCall(
1620
+ transport,
1621
+ `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
1622
+ request,
1623
+ options
1624
+ );
1625
+ }
1626
+ function cancelAgentRun(transport, requestId, options = {}) {
1627
+ const query = buildQuery(
1628
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
1629
+ );
1630
+ return requestJson(
1631
+ transport,
1632
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
1633
+ {
1634
+ method: "POST",
1635
+ ...options.signal ? { signal: options.signal } : {}
1636
+ }
1637
+ );
1638
+ }
1639
+ var MatrxRunError = class extends Error {
1640
+ name = "MatrxRunError";
1641
+ /** The verbatim `error` event payload, when one fired. */
1642
+ errorPayload;
1643
+ /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
1644
+ completionStatus;
1645
+ /** Text streamed before the failure — partial content never vanishes. */
1646
+ partialText;
1647
+ constructor(args) {
1648
+ super(args.message);
1649
+ this.errorPayload = args.errorPayload ?? null;
1650
+ this.completionStatus = args.completionStatus ?? null;
1651
+ this.partialText = args.partialText ?? "";
1652
+ }
1653
+ };
1654
+ function isRecord5(value) {
1655
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1656
+ }
1657
+ function stringField(value, key) {
1658
+ if (!isRecord5(value)) return null;
1659
+ const field = value[key];
1660
+ return typeof field === "string" && field ? field : null;
1661
+ }
1662
+ async function runAgentToCompletion(transport, agentId, request, options = {}) {
1663
+ const handle = await startAgentRun(transport, agentId, request, options);
1664
+ let text = "";
1665
+ let completion = null;
1666
+ let failure = null;
1667
+ for await (const envelope of handle.events) {
1668
+ options.onEvent?.(envelope);
1669
+ if (envelope.event === "chunk") {
1670
+ const chunk = stringField(envelope.data, "text");
1671
+ if (chunk !== null) {
1672
+ text += chunk;
1673
+ options.onChunk?.(text);
1674
+ }
1675
+ continue;
1676
+ }
1677
+ if (envelope.event === "error" && failure === null) {
1678
+ const payload = isRecord5(envelope.data) ? envelope.data : null;
1679
+ failure = new MatrxRunError({
1680
+ message: streamErrorText(payload) ?? "The agent run failed",
1681
+ errorPayload: payload,
1682
+ partialText: text
1683
+ });
1684
+ continue;
1685
+ }
1686
+ if (envelope.event !== "completion" || !isRecord5(envelope.data)) continue;
1687
+ if (envelope.data.operation !== "user_request") continue;
1688
+ completion = envelope.data;
1689
+ const status = envelope.data.status;
1690
+ if ((status === "failed" || status === "cancelled") && failure === null) {
1691
+ const result = isRecord5(envelope.data.result) ? envelope.data.result : null;
1692
+ failure = new MatrxRunError({
1693
+ message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
1694
+ completionStatus: status,
1695
+ partialText: text
1696
+ });
1697
+ }
1698
+ }
1699
+ if (failure) throw failure;
1700
+ if (!text && completion) {
1701
+ const result = completion.result;
1702
+ const output = stringField(result, "output");
1703
+ if (output !== null) text = output;
1704
+ }
1705
+ return {
1706
+ text,
1707
+ requestId: handle.requestId,
1708
+ conversationId: handle.conversationId,
1709
+ completion
1710
+ };
1711
+ }
1712
+
1713
+ // matrx/provider-failures.ts
1714
+ var clip = (value, max) => value.length > max ? value.slice(0, max) : value;
1715
+ function providerSessionFailureBody(failure) {
1716
+ const message = failure.message?.trim() || failure.error_type?.trim() || (failure.status_code ? `HTTP ${failure.status_code}` : "provider session failed");
1717
+ const body = {
1718
+ provider: failure.provider,
1719
+ message: clip(message, 4e3)
1720
+ };
1721
+ if (failure.model?.trim()) body.model = clip(failure.model.trim(), 200);
1722
+ if (failure.error_type?.trim()) body.error_type = clip(failure.error_type.trim(), 200);
1723
+ if (typeof failure.status_code === "number" && Number.isInteger(failure.status_code) && failure.status_code >= 100 && failure.status_code <= 599) {
1724
+ body.status_code = failure.status_code;
1725
+ }
1726
+ return body;
1727
+ }
1728
+ async function reportProviderSessionFailure(transport, failure, options = {}) {
1729
+ try {
1730
+ return await requestJson(
1731
+ transport,
1732
+ "/broker/provider-failures",
1733
+ {
1734
+ method: "POST",
1735
+ body: providerSessionFailureBody(failure),
1736
+ ...options.signal ? { signal: options.signal } : {}
1737
+ }
1738
+ );
1739
+ } catch (error) {
1740
+ console.warn(
1741
+ `[provider-failures] could not report a ${failure.provider} session failure`,
1742
+ error
1743
+ );
1744
+ return null;
1745
+ }
1746
+ }
1747
+
1567
1748
  // matrx/tools.ts
1568
1749
  function submitAgentToolResults(transport, conversationId, results, options = {}) {
1569
1750
  return requestJson(
@@ -1827,6 +2008,9 @@ export {
1827
2008
  IMAGE_REFERENCE_ROLES,
1828
2009
  IMAGE_ROLE_META,
1829
2010
  MATRX_AI_API_VERSION_DEFAULT,
2011
+ MATRX_LIVE_STREAM_UNAVAILABLE,
2012
+ MATRX_RESUME_CONFLICT,
2013
+ MATRX_RUN_IN_PROGRESS,
1830
2014
  MatrxApiError,
1831
2015
  MatrxRunError,
1832
2016
  OrganizationContextError,
@@ -1860,7 +2044,9 @@ export {
1860
2044
  isControlVariable,
1861
2045
  isCoveredAiPath,
1862
2046
  isImageReferenceRole,
2047
+ isLiveStreamUnavailable,
1863
2048
  isReferenceRole,
2049
+ isResumeConflict,
1864
2050
  isV2Path,
1865
2051
  listConversationPendingToolCalls,
1866
2052
  listRuntimeOperationEvents,
@@ -1872,6 +2058,7 @@ export {
1872
2058
  normalizeMatrxError,
1873
2059
  normalizeMatrxStreamEnvelope,
1874
2060
  normalizeReferenceName,
2061
+ openMatrxStream,
1875
2062
  orderVariablesForForm,
1876
2063
  parseMatrxSseFrame,
1877
2064
  partitionControlVariables,
@@ -1879,24 +2066,32 @@ export {
1879
2066
  projectAgentEvents,
1880
2067
  projectAgentResultForDisplay,
1881
2068
  projectWorkflowNodeEvent,
2069
+ providerSessionFailureBody,
1882
2070
  readImageRoleLimits,
2071
+ readLiveRunRequestId,
2072
+ readMatrxErrorCode,
1883
2073
  readMatrxNdjsonStream,
1884
2074
  readMatrxSseStream,
1885
2075
  referenceRoleCaption,
1886
2076
  rejoinRuntimeOperation,
2077
+ reportProviderSessionFailure,
1887
2078
  requireOrganizationContext,
1888
2079
  resumeAgentConversation,
2080
+ resumeOrRejoin,
1889
2081
  roleTakesName,
1890
2082
  rolesFor,
1891
2083
  runAgentToCompletion,
2084
+ runtimeOperationRejoinPath,
1892
2085
  startAgentRun,
1893
2086
  startMandateRun,
2087
+ streamErrorText,
1894
2088
  submitAgentToolResults,
1895
2089
  toV1FallbackUrl,
1896
2090
  toV2Path,
1897
2091
  variableNameOfImageUrl,
1898
2092
  variableNameOfMediaUrl,
1899
2093
  variableRunHint,
1900
- variableRunLabel
2094
+ variableRunLabel,
2095
+ withRunOrganization
1901
2096
  };
1902
2097
  //# sourceMappingURL=index.js.map