@ai-matrx/agents 0.22.0 → 0.24.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 (36) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/content-transfer/index.cjs +33 -33
  3. package/dist/content-transfer/index.cjs.map +1 -1
  4. package/dist/content-transfer/index.d.cts +1 -1
  5. package/dist/content-transfer/index.d.ts +1 -1
  6. package/dist/content-transfer/index.js +33 -33
  7. package/dist/content-transfer/index.js.map +1 -1
  8. package/dist/content-transfer/react/index.cjs +33 -33
  9. package/dist/content-transfer/react/index.cjs.map +1 -1
  10. package/dist/content-transfer/react/index.js +33 -33
  11. package/dist/content-transfer/react/index.js.map +1 -1
  12. package/dist/index.cjs +404 -131
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +404 -131
  17. package/dist/index.js.map +1 -1
  18. package/dist/mandates/index.cjs +2 -2
  19. package/dist/mandates/index.cjs.map +1 -1
  20. package/dist/mandates/index.d.cts +4 -4
  21. package/dist/mandates/index.d.ts +4 -4
  22. package/dist/mandates/index.js +2 -2
  23. package/dist/mandates/index.js.map +1 -1
  24. package/dist/matrx/index.cjs +404 -131
  25. package/dist/matrx/index.cjs.map +1 -1
  26. package/dist/matrx/index.d.cts +242 -4
  27. package/dist/matrx/index.d.ts +242 -4
  28. package/dist/matrx/index.js +404 -131
  29. package/dist/matrx/index.js.map +1 -1
  30. package/dist/react/index.cjs +41 -41
  31. package/dist/react/index.cjs.map +1 -1
  32. package/dist/react/index.js +41 -41
  33. package/dist/react/index.js.map +1 -1
  34. package/mandates/snapshots/keys.0.23.0.json +652 -0
  35. package/mandates/snapshots/keys.0.24.0.json +652 -0
  36. package/package.json +4 -4
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, MatrxLiveRunRejoin, 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, followWorkflowRunEvents, isCoveredAiPath, isLiveStreamUnavailable, isResumeConflict, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, openMatrxStream, providerSessionFailureBody, readLiveRunRejoin, 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, MatrxLiveRunRejoin, 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, followWorkflowRunEvents, isCoveredAiPath, isLiveStreamUnavailable, isResumeConflict, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, openMatrxStream, providerSessionFailureBody, readLiveRunRejoin, 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,393 @@ 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 firstString(candidates, key) {
1476
+ for (const candidate of candidates) {
1477
+ const value = nonBlank(candidate[key]);
1478
+ if (value) return value.trim();
1479
+ }
1480
+ return null;
1481
+ }
1482
+ function readLiveRunRejoin(error) {
1483
+ if (statusOf(error) !== 409) return null;
1484
+ const candidates = detailCandidates(bodyOf(error));
1485
+ if (candidates.length === 0) return null;
1486
+ const code = readMatrxErrorCode(error);
1487
+ if (code !== MATRX_RUN_IN_PROGRESS && code !== MATRX_RESUME_CONFLICT) return null;
1488
+ const liveRequestId = firstString(candidates, "live_request_id");
1489
+ const pathFromBody = firstString(candidates, "rejoin_path");
1490
+ const rejoinPath = pathFromBody && pathFromBody.startsWith("/") ? pathFromBody : liveRequestId ? runtimeOperationRejoinPath(liveRequestId) : null;
1491
+ if (!rejoinPath) return null;
1492
+ const root = bodyOf(error);
1493
+ return {
1494
+ liveRequestId,
1495
+ rejoinPath,
1496
+ runId: firstString(candidates, "run_id"),
1497
+ code,
1498
+ body: isRecord4(root) ? root : {}
1499
+ };
1500
+ }
1501
+ function readLiveRunRequestId(error) {
1502
+ return readLiveRunRejoin(error)?.liveRequestId ?? null;
1503
+ }
1504
+ function isResumeConflict(error) {
1505
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_RESUME_CONFLICT && readLiveRunRejoin(error) === null;
1506
+ }
1507
+ function isLiveStreamUnavailable(error) {
1508
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_LIVE_STREAM_UNAVAILABLE;
1509
+ }
1510
+ function runtimeOperationRejoinPath(requestId) {
1511
+ return `/runtime/operations/${encodePathSegment(requestId)}/rejoin`;
1512
+ }
1513
+ function streamErrorText(eventOrPayload) {
1514
+ if (!isRecord4(eventOrPayload)) return null;
1515
+ const payload = typeof eventOrPayload.event === "string" && isRecord4(eventOrPayload.data) ? eventOrPayload.data : eventOrPayload;
1516
+ return nonBlank(payload.user_message) ?? nonBlank(payload.message);
1517
+ }
1518
+ async function openMatrxStream(transport, path, options = {}) {
1519
+ const response = await requestStream(transport, path, {
1520
+ method: "POST",
1521
+ ...options.body !== void 0 ? { body: options.body } : {},
1522
+ ...options.signal ? { signal: options.signal } : {}
1523
+ });
1524
+ return toRunHandle(response, options);
1525
+ }
1526
+ function withRunOrganization(transport, organizationId) {
1527
+ const orgId = requireOrganizationContext(organizationId);
1528
+ return {
1529
+ fetch: (path, init) => transport.fetch(path, {
1530
+ ...init,
1531
+ headers: { ...init.headers, "X-Organization-Id": orgId }
1532
+ })
1533
+ };
1534
+ }
1535
+ async function followWorkflowRunEvents(transport, runId, options) {
1536
+ const headers = { Accept: "text/event-stream" };
1537
+ if (options.lastEventId) headers["Last-Event-ID"] = String(options.lastEventId);
1538
+ let response;
1539
+ try {
1540
+ response = await requestStream(
1541
+ transport,
1542
+ `/runs/${encodePathSegment(runId)}/events/stream`,
1543
+ {
1544
+ method: "GET",
1545
+ headers,
1546
+ ...options.signal ? { signal: options.signal } : {}
1547
+ }
1548
+ );
1549
+ } catch (error) {
1550
+ if (options.signal?.aborted) return { ended: false };
1551
+ throw error;
1552
+ }
1553
+ try {
1554
+ for await (const frame of readMatrxSseStream(
1555
+ response.body
1556
+ )) {
1557
+ if (frame.event === "end") return { ended: true };
1558
+ if (frame.data === null) continue;
1559
+ let parsed;
1560
+ try {
1561
+ parsed = JSON.parse(frame.data);
1562
+ } catch {
1563
+ continue;
1564
+ }
1565
+ if (!isRecord4(parsed)) continue;
1566
+ options.onEvent(parsed, parsed.event === "node_stream" ? null : frame.seq);
1567
+ }
1568
+ } catch (error) {
1569
+ if (!options.signal?.aborted) throw error;
1570
+ }
1571
+ return { ended: false };
1572
+ }
1573
+ async function drain(handle, onEnvelope) {
1574
+ for await (const envelope of handle.events) onEnvelope(envelope);
1575
+ }
1576
+ async function resumeOrRejoin(transport, resumeCall, options) {
1577
+ const {
1578
+ onEnvelope,
1579
+ organizationId,
1580
+ onRejoin,
1581
+ onOperationEvent,
1582
+ onWorkflowEvent,
1583
+ follow,
1584
+ ...rest
1585
+ } = options;
1586
+ const bound = organizationId ? withRunOrganization(transport, organizationId) : transport;
1587
+ const streamOptions = {
1588
+ ...rest,
1589
+ ...options.signal ? { signal: options.signal } : {}
1590
+ };
1591
+ const signalOnly = options.signal ? { signal: options.signal } : {};
1592
+ let rejoin;
1593
+ try {
1594
+ const handle = await resumeCall(bound, streamOptions);
1595
+ await drain(handle, onEnvelope);
1596
+ return { kind: "resumed", requestId: handle.requestId };
1597
+ } catch (error) {
1598
+ const target = readLiveRunRejoin(error);
1599
+ if (!target) {
1600
+ if (error instanceof MatrxApiError && isResumeConflict(error)) {
1601
+ return { kind: "resume_conflict", error };
1602
+ }
1603
+ throw error;
1604
+ }
1605
+ rejoin = target;
1606
+ }
1607
+ onRejoin?.(rejoin);
1608
+ let unavailableBody;
1609
+ try {
1610
+ const handle = await openMatrxStream(bound, rejoin.rejoinPath, {
1611
+ ...streamOptions,
1612
+ // The rejoin routes take no body model; the reference client posts {}.
1613
+ body: {}
1614
+ });
1615
+ await drain(handle, onEnvelope);
1616
+ return { kind: "rejoined", rejoin };
1617
+ } catch (error) {
1618
+ if (!isLiveStreamUnavailable(error)) throw error;
1619
+ unavailableBody = bodyOf(error);
1620
+ }
1621
+ const runId = firstString(detailCandidates(unavailableBody), "run_id") ?? rejoin.runId;
1622
+ if (runId && rejoin.rejoinPath.startsWith("/runtime/operations/")) {
1623
+ const result2 = await followWorkflowRunEvents(bound, runId, {
1624
+ ...signalOnly,
1625
+ onEvent: (event, seq) => onWorkflowEvent?.(event, seq)
1626
+ });
1627
+ return { kind: "followed_workflow", rejoin, runId, ended: result2.ended };
1628
+ }
1629
+ const liveRequestId = rejoin.liveRequestId;
1630
+ const statusView = liveRequestId ? await getRuntimeOperationStatus(bound, liveRequestId, signalOnly) : null;
1631
+ const operation = statusView?.operations.find((op) => !op.is_terminal) ?? statusView?.operations[0] ?? null;
1632
+ if (!operation) {
1633
+ return { kind: "followed", rejoin, executionId: null, ended: false, status: null };
1634
+ }
1635
+ if (operation.is_terminal) {
1636
+ return {
1637
+ kind: "followed",
1638
+ rejoin,
1639
+ executionId: operation.execution_id,
1640
+ ended: true,
1641
+ status: operation.status
1642
+ };
1643
+ }
1644
+ const result = await followRuntimeOperationToEnd(bound, operation.execution_id, {
1645
+ ...follow,
1646
+ lastEventSeq: operation.last_event_seq,
1647
+ ...signalOnly,
1648
+ onEvent: (event) => onOperationEvent?.(event)
1649
+ });
1650
+ return {
1651
+ kind: "followed",
1652
+ rejoin,
1653
+ executionId: operation.execution_id,
1654
+ ended: result.ended,
1655
+ status: result.status
1656
+ };
1657
+ }
1658
+
1659
+ // matrx/run.ts
1660
+ async function streamCall(transport, path, body, options) {
1661
+ const response = await requestStream(transport, path, {
1662
+ method: "POST",
1663
+ // This client IS the streaming path — `stream: true` always, last so a
1664
+ // caller-supplied value can never flip the response off NDJSON.
1665
+ body: { ...body, stream: true },
1666
+ ...options.signal ? { signal: options.signal } : {}
1667
+ });
1668
+ return toRunHandle(response, options);
1669
+ }
1670
+ function startAgentRun(transport, agentId, request, options = {}) {
1671
+ return streamCall(
1672
+ transport,
1673
+ `/ai/agents/${encodePathSegment(agentId)}`,
1674
+ request,
1675
+ options
1676
+ );
1677
+ }
1678
+ function startMandateRun(transport, mandateKey, request, options = {}) {
1679
+ return streamCall(
1680
+ transport,
1681
+ `/ai/mandates/${encodePathSegment(mandateKey)}`,
1682
+ request,
1683
+ options
1684
+ );
1685
+ }
1686
+ function continueAgentConversation(transport, conversationId, request, options = {}) {
1687
+ return streamCall(
1688
+ transport,
1689
+ `/ai/conversations/${encodePathSegment(conversationId)}`,
1690
+ request,
1691
+ options
1692
+ );
1693
+ }
1694
+ function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
1695
+ return streamCall(
1696
+ transport,
1697
+ `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
1698
+ request,
1699
+ options
1700
+ );
1701
+ }
1702
+ function cancelAgentRun(transport, requestId, options = {}) {
1703
+ const query = buildQuery(
1704
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
1705
+ );
1706
+ return requestJson(
1707
+ transport,
1708
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
1709
+ {
1710
+ method: "POST",
1711
+ ...options.signal ? { signal: options.signal } : {}
1712
+ }
1713
+ );
1714
+ }
1715
+ var MatrxRunError = class extends Error {
1716
+ name = "MatrxRunError";
1717
+ /** The verbatim `error` event payload, when one fired. */
1718
+ errorPayload;
1719
+ /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
1720
+ completionStatus;
1721
+ /** Text streamed before the failure — partial content never vanishes. */
1722
+ partialText;
1723
+ constructor(args) {
1724
+ super(args.message);
1725
+ this.errorPayload = args.errorPayload ?? null;
1726
+ this.completionStatus = args.completionStatus ?? null;
1727
+ this.partialText = args.partialText ?? "";
1728
+ }
1729
+ };
1730
+ function isRecord5(value) {
1731
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1732
+ }
1733
+ function stringField(value, key) {
1734
+ if (!isRecord5(value)) return null;
1735
+ const field = value[key];
1736
+ return typeof field === "string" && field ? field : null;
1737
+ }
1738
+ async function runAgentToCompletion(transport, agentId, request, options = {}) {
1739
+ const handle = await startAgentRun(transport, agentId, request, options);
1740
+ let text = "";
1741
+ let completion = null;
1742
+ let failure = null;
1743
+ for await (const envelope of handle.events) {
1744
+ options.onEvent?.(envelope);
1745
+ if (envelope.event === "chunk") {
1746
+ const chunk = stringField(envelope.data, "text");
1747
+ if (chunk !== null) {
1748
+ text += chunk;
1749
+ options.onChunk?.(text);
1750
+ }
1751
+ continue;
1752
+ }
1753
+ if (envelope.event === "error" && failure === null) {
1754
+ const payload = isRecord5(envelope.data) ? envelope.data : null;
1755
+ failure = new MatrxRunError({
1756
+ message: streamErrorText(payload) ?? "The agent run failed",
1757
+ errorPayload: payload,
1758
+ partialText: text
1759
+ });
1760
+ continue;
1761
+ }
1762
+ if (envelope.event !== "completion" || !isRecord5(envelope.data)) continue;
1763
+ if (envelope.data.operation !== "user_request") continue;
1764
+ completion = envelope.data;
1765
+ const status = envelope.data.status;
1766
+ if ((status === "failed" || status === "cancelled") && failure === null) {
1767
+ const result = isRecord5(envelope.data.result) ? envelope.data.result : null;
1768
+ failure = new MatrxRunError({
1769
+ message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
1770
+ completionStatus: status,
1771
+ partialText: text
1772
+ });
1773
+ }
1774
+ }
1775
+ if (failure) throw failure;
1776
+ if (!text && completion) {
1777
+ const result = completion.result;
1778
+ const output = stringField(result, "output");
1779
+ if (output !== null) text = output;
1780
+ }
1781
+ return {
1782
+ text,
1783
+ requestId: handle.requestId,
1784
+ conversationId: handle.conversationId,
1785
+ completion
1786
+ };
1787
+ }
1788
+
1789
+ // matrx/provider-failures.ts
1790
+ var clip = (value, max) => value.length > max ? value.slice(0, max) : value;
1791
+ function providerSessionFailureBody(failure) {
1792
+ const message = failure.message?.trim() || failure.error_type?.trim() || (failure.status_code ? `HTTP ${failure.status_code}` : "provider session failed");
1793
+ const body = {
1794
+ provider: failure.provider,
1795
+ message: clip(message, 4e3)
1796
+ };
1797
+ if (failure.model?.trim()) body.model = clip(failure.model.trim(), 200);
1798
+ if (failure.error_type?.trim()) body.error_type = clip(failure.error_type.trim(), 200);
1799
+ if (typeof failure.status_code === "number" && Number.isInteger(failure.status_code) && failure.status_code >= 100 && failure.status_code <= 599) {
1800
+ body.status_code = failure.status_code;
1801
+ }
1802
+ return body;
1803
+ }
1804
+ async function reportProviderSessionFailure(transport, failure, options = {}) {
1805
+ try {
1806
+ return await requestJson(
1807
+ transport,
1808
+ "/broker/provider-failures",
1809
+ {
1810
+ method: "POST",
1811
+ body: providerSessionFailureBody(failure),
1812
+ ...options.signal ? { signal: options.signal } : {}
1813
+ }
1814
+ );
1815
+ } catch (error) {
1816
+ console.warn(
1817
+ `[provider-failures] could not report a ${failure.provider} session failure`,
1818
+ error
1819
+ );
1820
+ return null;
1821
+ }
1822
+ }
1823
+
1567
1824
  // matrx/tools.ts
1568
1825
  function submitAgentToolResults(transport, conversationId, results, options = {}) {
1569
1826
  return requestJson(
@@ -1827,6 +2084,9 @@ export {
1827
2084
  IMAGE_REFERENCE_ROLES,
1828
2085
  IMAGE_ROLE_META,
1829
2086
  MATRX_AI_API_VERSION_DEFAULT,
2087
+ MATRX_LIVE_STREAM_UNAVAILABLE,
2088
+ MATRX_RESUME_CONFLICT,
2089
+ MATRX_RUN_IN_PROGRESS,
1830
2090
  MatrxApiError,
1831
2091
  MatrxRunError,
1832
2092
  OrganizationContextError,
@@ -1854,13 +2114,16 @@ export {
1854
2114
  fetchWithMatrxProtocolFallback,
1855
2115
  followRuntimeOperationEvents,
1856
2116
  followRuntimeOperationToEnd,
2117
+ followWorkflowRunEvents,
1857
2118
  getRuntimeOperationStatus,
1858
2119
  getRuntimeOperationsByLink,
1859
2120
  imageRoleVerdict,
1860
2121
  isControlVariable,
1861
2122
  isCoveredAiPath,
1862
2123
  isImageReferenceRole,
2124
+ isLiveStreamUnavailable,
1863
2125
  isReferenceRole,
2126
+ isResumeConflict,
1864
2127
  isV2Path,
1865
2128
  listConversationPendingToolCalls,
1866
2129
  listRuntimeOperationEvents,
@@ -1872,6 +2135,7 @@ export {
1872
2135
  normalizeMatrxError,
1873
2136
  normalizeMatrxStreamEnvelope,
1874
2137
  normalizeReferenceName,
2138
+ openMatrxStream,
1875
2139
  orderVariablesForForm,
1876
2140
  parseMatrxSseFrame,
1877
2141
  partitionControlVariables,
@@ -1879,24 +2143,33 @@ export {
1879
2143
  projectAgentEvents,
1880
2144
  projectAgentResultForDisplay,
1881
2145
  projectWorkflowNodeEvent,
2146
+ providerSessionFailureBody,
1882
2147
  readImageRoleLimits,
2148
+ readLiveRunRejoin,
2149
+ readLiveRunRequestId,
2150
+ readMatrxErrorCode,
1883
2151
  readMatrxNdjsonStream,
1884
2152
  readMatrxSseStream,
1885
2153
  referenceRoleCaption,
1886
2154
  rejoinRuntimeOperation,
2155
+ reportProviderSessionFailure,
1887
2156
  requireOrganizationContext,
1888
2157
  resumeAgentConversation,
2158
+ resumeOrRejoin,
1889
2159
  roleTakesName,
1890
2160
  rolesFor,
1891
2161
  runAgentToCompletion,
2162
+ runtimeOperationRejoinPath,
1892
2163
  startAgentRun,
1893
2164
  startMandateRun,
2165
+ streamErrorText,
1894
2166
  submitAgentToolResults,
1895
2167
  toV1FallbackUrl,
1896
2168
  toV2Path,
1897
2169
  variableNameOfImageUrl,
1898
2170
  variableNameOfMediaUrl,
1899
2171
  variableRunHint,
1900
- variableRunLabel
2172
+ variableRunLabel,
2173
+ withRunOrganization
1901
2174
  };
1902
2175
  //# sourceMappingURL=index.js.map