@ai-matrx/agents 0.10.7 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/content-transfer/index.cjs +1422 -0
  3. package/dist/content-transfer/index.cjs.map +1 -0
  4. package/dist/content-transfer/index.d.cts +84 -0
  5. package/dist/content-transfer/index.d.ts +84 -0
  6. package/dist/content-transfer/index.js +1404 -0
  7. package/dist/content-transfer/index.js.map +1 -0
  8. package/dist/content-transfer/react/index.cjs +1564 -0
  9. package/dist/content-transfer/react/index.cjs.map +1 -0
  10. package/dist/content-transfer/react/index.d.cts +63 -0
  11. package/dist/content-transfer/react/index.d.ts +63 -0
  12. package/dist/content-transfer/react/index.js +1539 -0
  13. package/dist/content-transfer/react/index.js.map +1 -0
  14. package/dist/index.cjs +23 -0
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +2 -1
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.js +23 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/mandates/index.cjs +7 -2
  21. package/dist/mandates/index.cjs.map +1 -1
  22. package/dist/mandates/index.d.cts +10 -5
  23. package/dist/mandates/index.d.ts +10 -5
  24. package/dist/mandates/index.js +7 -2
  25. package/dist/mandates/index.js.map +1 -1
  26. package/dist/matrx/index.cjs +23 -0
  27. package/dist/matrx/index.cjs.map +1 -1
  28. package/dist/matrx/index.d.cts +13 -646
  29. package/dist/matrx/index.d.ts +13 -646
  30. package/dist/matrx/index.js +23 -0
  31. package/dist/matrx/index.js.map +1 -1
  32. package/dist/operations--f5ko9Su.d.cts +659 -0
  33. package/dist/operations-BT5kKMHl.d.cts +203 -0
  34. package/dist/operations-BT5kKMHl.d.ts +203 -0
  35. package/dist/operations-Dp4ut-ac.d.ts +659 -0
  36. package/dist/react/index.cjs.map +1 -1
  37. package/dist/react/index.d.cts +44 -244
  38. package/dist/react/index.d.ts +44 -244
  39. package/dist/react/index.js.map +1 -1
  40. package/mandates/snapshots/keys.0.11.0.json +475 -0
  41. package/package.json +24 -3
@@ -1,100 +1,9 @@
1
+ import { B as MatrxTransport, m as MatrxJsonValue, l as MatrxJsonObject } from '../operations-Dp4ut-ac.js';
2
+ 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, 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, 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';
1
3
  import { CredentialsPort } from '@ai-matrx/data';
2
4
  import { ResilientFetchOptions } from '@ai-matrx/data/net';
3
- import { MatrxStreamEnvelope, MatrxNdjsonIssue, MatrxStreamEnvelopeObservation } from '../stream/ndjson.js';
4
- import { MatrxSseFrame } from '../stream/sse.js';
5
-
6
- /**
7
- * `@ai-matrx/agents/matrx` — the Matrx transport port.
8
- *
9
- * The ONE seam between this package's wire semantics and a host's connection
10
- * policy. This package owns WHAT is said to the AI Matrx server — paths,
11
- * methods, JSON bodies, streaming Accept headers, the `Last-Event-ID` cursor
12
- * header — and the host owns HOW the connection is made:
13
- *
14
- * - base-URL / backend-channel resolution (global, sandbox override, local
15
- * engine, EC2-dedicated — whatever ladder the host runs);
16
- * - credentials (Supabase JWT `Authorization: Bearer`, guest
17
- * `X-Fingerprint-ID`, or the API-key lane) — NEVER implemented here;
18
- * - the `X-Organization-Id` context header;
19
- * - retry policy, network-level timeouts, and diagnostics capture.
20
- *
21
- * A host implements the port in a few lines:
22
- *
23
- * ```ts
24
- * const transport: MatrxTransport = {
25
- * fetch: (path, init) =>
26
- * fetch(`${baseUrl}${path}`, {
27
- * ...init,
28
- * headers: { ...init.headers, ...authHeaders() },
29
- * }),
30
- * };
31
- * ```
32
- *
33
- * The port is deliberately structural and `fetch`-shaped so `@ai-matrx/data`'s
34
- * `/api` transport can implement it without importing this package.
35
- */
36
- /**
37
- * The request this package hands the port. A strict subset of `RequestInit`,
38
- * so a host can spread it straight into `fetch`.
39
- */
40
- interface MatrxTransportRequest {
41
- method: "GET" | "POST";
42
- /**
43
- * Wire-semantic headers the CALL requires (`Content-Type`, `Accept`,
44
- * `Last-Event-ID`). The host merges its policy headers (auth, org) on top;
45
- * it must not drop these.
46
- */
47
- headers: Record<string, string>;
48
- /** Pre-serialized JSON body, present on POST calls that carry one. */
49
- body?: string;
50
- /** Caller cancellation. The host must wire it to the underlying fetch. */
51
- signal?: AbortSignal;
52
- }
53
- /**
54
- * The transport port. `path` is server-relative and always starts with `/`
55
- * (`/ai/...`, `/runtime/...`); the host prepends its resolved base URL.
56
- */
57
- interface MatrxTransport {
58
- fetch(path: string, init: MatrxTransportRequest): Promise<Response>;
59
- }
60
- /**
61
- * A non-2xx response from the Matrx API, with the server's structured error
62
- * body preserved and its richest human-readable message extracted.
63
- */
64
- declare class MatrxApiError extends Error {
65
- readonly name = "MatrxApiError";
66
- /** HTTP status of the failed response. */
67
- readonly status: number;
68
- /** Machine code from the server body (`code`, or `detail.code`), when present. */
69
- readonly code: string | null;
70
- /** The parsed server error body, verbatim (undefined when unparsable). */
71
- readonly serverDetail: unknown;
72
- /** The request path the failure came from (server-relative). */
73
- readonly path: string;
74
- constructor(args: {
75
- status: number;
76
- path: string;
77
- serverDetail?: unknown;
78
- message?: string;
79
- });
80
- }
81
- /**
82
- * Extract the richest human-readable message from a Matrx/FastAPI error body.
83
- *
84
- * aidream 4xx validation errors look like
85
- * `{ error, user_message, details: [{ field, message, help }] }`; hand-raised
86
- * HTTPExceptions carry `{ detail: { code, message } }`; FastAPI's defaults are
87
- * `{ detail: string | [{ msg }] }`. Preference order: `user_message` →
88
- * `message` → joined `details[].message` → `detail.message` →
89
- * `detail` string → joined `detail[].msg`. Returns undefined for
90
- * unrecognized bodies so callers fall back to the bare status line.
91
- */
92
- declare function extractMatrxErrorMessage(serverDetail: unknown): string | undefined;
93
- /**
94
- * Extract the machine error code from a Matrx error body: top-level `code`,
95
- * else `detail.code` (the hand-raised HTTPException shape). Null when absent.
96
- */
97
- declare function extractMatrxErrorCode(serverDetail: unknown): string | null;
5
+ import '../stream/ndjson.js';
6
+ import '../stream/sse.js';
98
7
 
99
8
  /**
100
9
  * The AI API protocol-version policy — which version of the AI runtime a
@@ -370,6 +279,14 @@ declare class OrganizationContextError extends Error {
370
279
  readonly code: OrganizationContextErrorCode;
371
280
  constructor(code: OrganizationContextErrorCode, message: string);
372
281
  }
282
+ declare const organizationOperationBrand: unique symbol;
283
+ /** A validated organization operation; construct only through the factory. */
284
+ type OrganizationOperation = Readonly<{
285
+ organization_id: string;
286
+ readonly [organizationOperationBrand]: true;
287
+ }>;
288
+ declare function createOrganizationOperation(organizationId: string): OrganizationOperation;
289
+ declare function assertOrganizationMatchesOperation(operation: OrganizationOperation, organizationId: string): void;
373
290
  /**
374
291
  * Normalize and validate the effective organization id for a request. The
375
292
  * override (an explicit per-call value) beats the selected context value.
@@ -390,556 +307,6 @@ declare function applyOrganizationContextHeader(headers: Record<string, string>,
390
307
  */
391
308
  declare function assertQueryOrganizationMatchesContext(queryParams: Record<string, string | number | boolean> | undefined, organizationId: string): void;
392
309
 
393
- /**
394
- * The conversation-start contract — client-minted `conversation_id`, `is_new`,
395
- * `store` — typed exactly per the cross-repo System of Record
396
- * (`common-docs/systems/agents/conversation-start-contract/FEATURE.md`;
397
- * server truth `aidream/services/conversation_context/scope.py::
398
- * ConversationStartRequest`).
399
- *
400
- * Every request that STARTS a conversation sends all three fields, no
401
- * defaults:
402
- *
403
- * | `is_new` | `store` | Result |
404
- * |----------|---------|----------------------------------------------------------|
405
- * | true | true | Create the row with the caller's id — 409 if it exists |
406
- * | true | false | No row. The id is correlation only (ephemeral run) |
407
- * | false | true | Continue it — 404 if the caller doesn't own it |
408
- * | false | false | Ephemeral run on a known id; nothing read, nothing written |
409
- *
410
- * `store` is the ONLY ephemeral signal; `is_new` is the caller's assertion
411
- * about the id, never a persistence switch. `prior_messages` (the client-owned
412
- * transcript of an ephemeral multi-turn run) is only valid with
413
- * `store: false` — the union below makes the invalid combination
414
- * unrepresentable, mirroring the server's 422.
415
- *
416
- * Continue routes (`POST /ai/conversations/{id}`) take the id from the path
417
- * and do not carry this triple.
418
- */
419
- /** Recursive JSON value — the package's honest type for free-form wire bags. */
420
- type MatrxJsonValue = string | number | boolean | null | MatrxJsonValue[] | {
421
- [key: string]: MatrxJsonValue;
422
- };
423
- /** A JSON object on the wire. */
424
- type MatrxJsonObject = {
425
- [key: string]: MatrxJsonValue;
426
- };
427
- /**
428
- * One LLM message on the request wire — `prior_messages` entries for
429
- * stateless multi-turn runs. Mirrors aidream's `ChatMessageInput`
430
- * (`aidream/schemas/messages.py`, `extra="allow"` — additional provider
431
- * fields round-trip untouched).
432
- */
433
- interface MatrxChatMessage {
434
- role: string;
435
- content?: string | MatrxJsonValue[] | null;
436
- name?: string | null;
437
- tool_call_id?: string | null;
438
- tool_calls?: MatrxJsonObject[] | null;
439
- [extra: string]: MatrxJsonValue | undefined;
440
- }
441
- /** `is_new: true, store: true` — create the row with the caller's id. */
442
- interface MatrxStoredConversationCreate {
443
- conversation_id: string;
444
- is_new: true;
445
- store: true;
446
- }
447
- /** `is_new: false, store: true` — continue an owned stored conversation via a start route. */
448
- interface MatrxStoredConversationContinue {
449
- conversation_id: string;
450
- is_new: false;
451
- store: true;
452
- }
453
- /**
454
- * `store: false` — ephemeral: nothing read, nothing written; the id is the
455
- * caller's correlation handle. This is the ONLY member that may carry
456
- * `prior_messages` (the server 422s a client transcript on a stored run).
457
- */
458
- interface MatrxEphemeralConversation {
459
- conversation_id: string;
460
- is_new: boolean;
461
- store: false;
462
- prior_messages?: MatrxChatMessage[];
463
- }
464
- /** The full conversation-start triple, one member per contract cell. */
465
- type MatrxConversationStart = MatrxStoredConversationCreate | MatrxStoredConversationContinue | MatrxEphemeralConversation;
466
- /** Mint a fresh client-side conversation id (the contract requires the CLIENT to mint it). */
467
- declare function mintMatrxConversationId(): string;
468
- /** Start a NEW stored conversation (`is_new: true, store: true`). */
469
- declare function newStoredConversationStart(conversationId?: string): MatrxStoredConversationCreate;
470
- /**
471
- * Continue an EXISTING stored conversation through a start route
472
- * (`is_new: false, store: true` — 404 when the caller doesn't own the id).
473
- * Prefer `continueAgentConversation` (the dedicated continue route) for
474
- * ordinary follow-up turns.
475
- */
476
- declare function continueStoredConversationStart(conversationId: string): MatrxStoredConversationContinue;
477
- /**
478
- * Start a NEW ephemeral run (`is_new: true, store: false`) — a freshly minted
479
- * correlation id, nothing persisted.
480
- */
481
- declare function newEphemeralConversationStart(conversationId?: string): MatrxEphemeralConversation;
482
- /**
483
- * Continue an ephemeral multi-turn run (`is_new: false, store: false`): the
484
- * CLIENT owns the transcript and replays it as `prior_messages` (ordered
485
- * oldest-first) because the server wrote no rows to rebuild from. The server
486
- * still owns the agent definition, model, tools, and system prompt.
487
- */
488
- declare function continueEphemeralConversationStart(conversationId: string, priorMessages: MatrxChatMessage[]): MatrxEphemeralConversation;
489
-
490
- /**
491
- * Internal request plumbing for `@ai-matrx/agents/matrx`. Not part of the
492
- * public surface — `matrx/index.ts` deliberately does not re-export this
493
- * module. Everything here is pure: no globals, no work at import time.
494
- */
495
-
496
- /**
497
- * Options for every streaming call, riding the NDJSON kernel's contract.
498
- * Public via `./run`'s re-export.
499
- */
500
- interface MatrxStreamCallOptions {
501
- /** Abort the fetch and end the events iterator. */
502
- signal?: AbortSignal;
503
- /** Bounded background read-ahead (see `stream/ndjson`). */
504
- maxReadAhead?: number;
505
- /** Malformed NDJSON is non-fatal but must never disappear silently. */
506
- onMalformedLine?: (issue: MatrxNdjsonIssue) => void;
507
- /** Valid JSON with no recognized Matrx envelope. */
508
- onUnknownEnvelope?: (value: unknown) => void;
509
- /** Observe every valid envelope in its exact wire form. */
510
- onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;
511
- }
512
- /**
513
- * A live agent run: the server-assigned ids (from response headers, available
514
- * BEFORE any event) and the normalized event stream. Public via `./run`.
515
- */
516
- interface MatrxRunHandle {
517
- /** `X-Request-ID` — the ONLY id `POST /ai/cancel/{request_id}` accepts. */
518
- requestId: string | null;
519
- /** `X-Conversation-ID` — the server's conversation identity. */
520
- conversationId: string | null;
521
- /** Normalized `{event, data}` envelopes through the ONE wire kernel. */
522
- events: AsyncGenerator<MatrxStreamEnvelope, void, undefined>;
523
- /** The raw response, for hosts that need headers/status beyond the ids. */
524
- response: Response;
525
- }
526
-
527
- /**
528
- * Agent run lifecycle against the AI Matrx API — start, continue, resume,
529
- * cancel — over the `MatrxTransport` port, with every streaming response
530
- * parsed through the package's ONE NDJSON wire kernel (`stream/ndjson`).
531
- *
532
- * Server truth (verified against aidream source):
533
- * - `POST /ai/agents/{agent_id}` — start (`aidream/api/routers/agents.py`)
534
- * - `POST /ai/conversations/{conversation_id}` — continue (`aidream/api/routers/conversations.py`)
535
- * - `POST /ai/conversations/{conversation_id}/resume` — resume after
536
- * client-delegated tool suspension (same router)
537
- * - `POST /ai/cancel/{request_id}?mode=interrupt` — cancel (`aidream/api/routers/cancel.py`)
538
- *
539
- * Response headers arrive before the body: `X-Conversation-ID` and
540
- * `X-Request-ID` are surfaced on the run handle immediately. `X-Request-ID`
541
- * is the ONLY id the server accepts for cancel — a client-local id means
542
- * nothing to it.
543
- *
544
- * Host policy stays out: no retry, no store, no timeouts, no persistence
545
- * (C10: no-persistence). Cancellation is the caller's `AbortSignal`; a client
546
- * disconnect never stops server work (`detach_on_disconnect`).
547
- */
548
-
549
- /**
550
- * Stable identity of the durable entity whose saved context owns a run —
551
- * the server reloads the row and uses ITS scope (`ContextAnchor`,
552
- * `aidream/services/conversation_context/scope.py`).
553
- */
554
- interface MatrxContextAnchor {
555
- resource_type: string;
556
- resource_id: string;
557
- }
558
- /**
559
- * Scope and source fields shared by every scoped request
560
- * (`ScopedRequest` / `AcceptsInjectedScope` server-side). All optional here;
561
- * the start request narrows `organization_id` to required.
562
- */
563
- interface MatrxRequestScope {
564
- organization_id?: string;
565
- project_id?: string | null;
566
- task_id?: string | null;
567
- /** Active context-scope ids from the client's global picker (membership-validated server-side). */
568
- scope_ids?: string[] | null;
569
- /** Active scope-TYPE ids — a type-level selection with no specific scope chosen. */
570
- active_scope_type_ids?: string[] | null;
571
- context_anchor?: MatrxContextAnchor | null;
572
- /** Stable application slug that initiated the request. */
573
- source_app?: string | null;
574
- /** Stable feature slug within the source application. */
575
- source_feature?: string | null;
576
- /** "user" = a person directly triggered this; "auto" = client automation; omit for API callers. */
577
- initiation?: "user" | "auto" | null;
578
- /** Specific connected desktop instance allowed to claim delegated local tools. */
579
- target_instance_id?: string | null;
580
- }
581
- /**
582
- * Fields shared by start/continue turn requests (tool injection, client
583
- * capability envelope, context object). The complex bags (`tools`, `client`,
584
- * `user`, `config_overrides`) are typed as JSON objects — their authoritative
585
- * schemas are the server's Pydantic models and the generated API types;
586
- * this package stays payload-agnostic about them by design.
587
- */
588
- interface MatrxTurnFields {
589
- /** What the human typed (string), or structured input parts. Never smuggle machine content here. */
590
- user_input?: string | MatrxJsonValue[] | null;
591
- /** Per-run model/config overrides (LLMParams shape). */
592
- config_overrides?: MatrxJsonObject | null;
593
- debug?: boolean;
594
- /** Additive tool specs merged into the agent's resolved tool set. */
595
- tools?: MatrxJsonObject[];
596
- /** When set, becomes the agent's ENTIRE tool set for the turn. */
597
- tools_replace?: MatrxJsonObject[] | null;
598
- /** Client capability envelope (`ClientContext`). */
599
- client?: MatrxJsonObject | null;
600
- /** Per-request user-level tool inclusion/exclusion overrides. */
601
- user?: MatrxJsonObject | null;
602
- /** Per-route context object, free-form by design. */
603
- context?: MatrxJsonObject;
604
- writable_variables?: string[];
605
- allow_context_create?: boolean;
606
- /** Request-snapshot capture override (tri-state; omit for the platform default). */
607
- snapshot?: boolean | null;
608
- }
609
- /**
610
- * `POST /ai/agents/{agent_id}` body (`AgentStartRequest` server-side).
611
- * The conversation-start triple is required by construction; `organization_id`
612
- * is required (the server 422s a blank one — it never manufactures an org).
613
- * `stream` is not accepted here: this client is the streaming path and always
614
- * sends `stream: true`.
615
- */
616
- type MatrxAgentStartRequest = MatrxConversationStart & Omit<MatrxRequestScope, "organization_id"> & MatrxTurnFields & {
617
- organization_id: string;
618
- /** Variable name → value map filling the agent's declared variables. */
619
- variables?: MatrxJsonObject | null;
620
- /** Run the versions table row instead of the live agent row. */
621
- is_version?: boolean;
622
- max_iterations?: number;
623
- max_retries_per_iteration?: number;
624
- };
625
- /** `POST /ai/conversations/{id}` body (`ConversationContinueRequest` server-side). */
626
- type MatrxConversationContinueRequest = MatrxRequestScope & MatrxTurnFields & {
627
- /** Re-run the conversation's current persisted state (recovery after a failed turn); omit `user_input`. */
628
- retry?: boolean;
629
- };
630
- /**
631
- * `POST /ai/conversations/{id}/resume` body (`ResumeRequest` server-side) —
632
- * the shipped durable continuation after client-delegated tool calls were
633
- * answered via `POST /tool_results` while the original stream was gone.
634
- * `user_request_id` is optional: when omitted the server resolves the turn
635
- * from the conversation's newest answered client-delegated tool call.
636
- * Re-send fresh `context` here — a resumed loop is otherwise context-blind.
637
- */
638
- type MatrxConversationResumeRequest = MatrxRequestScope & {
639
- user_request_id?: string | null;
640
- config_overrides?: MatrxJsonObject | null;
641
- debug?: boolean;
642
- tools?: MatrxJsonObject[];
643
- tools_replace?: MatrxJsonObject[] | null;
644
- client?: MatrxJsonObject | null;
645
- user?: MatrxJsonObject | null;
646
- context?: MatrxJsonObject;
647
- writable_variables?: string[];
648
- allow_context_create?: boolean;
649
- };
650
- /** `POST /ai/cancel/{request_id}` response (`CancelResponse` server-side). */
651
- interface MatrxCancelResponse {
652
- status: string;
653
- request_id: string;
654
- spine_executions_signalled: string[];
655
- }
656
- /** Start an agent run: `POST /ai/agents/{agent_id}` (NDJSON stream). */
657
- declare function startAgentRun(transport: MatrxTransport, agentId: string, request: MatrxAgentStartRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
658
- /** Continue a stored conversation: `POST /ai/conversations/{id}` (NDJSON stream). */
659
- declare function continueAgentConversation(transport: MatrxTransport, conversationId: string, request: MatrxConversationContinueRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
660
- /**
661
- * Resume a suspended loop after delegated tool answers landed:
662
- * `POST /ai/conversations/{id}/resume` (NDJSON stream). A 409
663
- * (`resume_conflict`) means another resume holds the run claim — retrying is
664
- * host policy.
665
- */
666
- declare function resumeAgentConversation(transport: MatrxTransport, conversationId: string, request?: MatrxConversationResumeRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
667
- /**
668
- * Stop a running request at its next iteration boundary:
669
- * `POST /ai/cancel/{request_id}`. Cooperative and best-effort — the in-flight
670
- * provider call finishes by design, and everything already streamed persists.
671
- * `mode: "interrupt"` = stop-and-fork: the tail after the last clean boundary
672
- * persists hidden so the user's follow-up replies to what they actually saw.
673
- * The id must be the server's `X-Request-ID`.
674
- */
675
- declare function cancelAgentRun(transport: MatrxTransport, requestId: string, options?: {
676
- mode?: "cancel" | "interrupt";
677
- signal?: AbortSignal;
678
- }): Promise<MatrxCancelResponse>;
679
- /**
680
- * A run that terminated unsuccessfully: the server emitted a fatal `error`
681
- * event, or the `user_request` completion settled `failed`/`cancelled`.
682
- */
683
- declare class MatrxRunError extends Error {
684
- readonly name = "MatrxRunError";
685
- /** The verbatim `error` event payload, when one fired. */
686
- readonly errorPayload: Record<string, unknown> | null;
687
- /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
688
- readonly completionStatus: string | null;
689
- /** Text streamed before the failure — partial content never vanishes. */
690
- readonly partialText: string;
691
- constructor(args: {
692
- message: string;
693
- errorPayload?: Record<string, unknown> | null;
694
- completionStatus?: string | null;
695
- partialText?: string;
696
- });
697
- }
698
- interface MatrxCompletedRun {
699
- /** Accumulated `chunk` text (falls back to the completion's `result.output`). */
700
- text: string;
701
- requestId: string | null;
702
- conversationId: string | null;
703
- /** The `user_request` completion payload, verbatim, when one arrived. */
704
- completion: Record<string, unknown> | null;
705
- }
706
- interface RunAgentToCompletionOptions extends MatrxStreamCallOptions {
707
- /** Live progress: the full accumulated text after each chunk. */
708
- onChunk?: (fullText: string) => void;
709
- /** Every normalized envelope, before this helper interprets it. */
710
- onEvent?: (envelope: MatrxStreamEnvelope) => void;
711
- }
712
- /**
713
- * Run an agent end-to-end and resolve with its full text output — the
714
- * package-level equivalent of the simplest existing host path
715
- * (`useRunAgent`): accumulate `chunk` text, treat a fatal `error` event or a
716
- * `failed`/`cancelled` `user_request` completion as a thrown `MatrxRunError`,
717
- * and fall back to the completion's `result.output` when no text streamed.
718
- *
719
- * The caller still owns the conversation-start triple on `request` — a
720
- * one-shot run typically uses `newEphemeralConversationStart()`.
721
- */
722
- declare function runAgentToCompletion(transport: MatrxTransport, agentId: string, request: MatrxAgentStartRequest, options?: RunAgentToCompletionOptions): Promise<MatrxCompletedRun>;
723
-
724
- /**
725
- * Runtime operations — the canonical reconnect & resume read surface of the
726
- * execution spine, over the `MatrxTransport` port.
727
- *
728
- * Server truth (verified against aidream source,
729
- * `aidream/api/routers/runtime_operations.py` + `aidream/services/runtime/
730
- * reconnect.py`; mounted at bare `/runtime`):
731
- * - `GET /runtime/operations/{request_id}` — identify by `X-Request-ID`
732
- * - `GET /runtime/operations/by-link/{kind}/{id}` — identify by feature record
733
- * - `GET /runtime/executions/{id}/events` — durable seq-cursored page
734
- * - `GET /runtime/executions/{id}/events/stream` — SSE replay-then-follow,
735
- * `id:` = per-tree seq, reconnect with `Last-Event-ID`
736
- * - `POST /runtime/operations/{request_id}/rejoin` — replay + follow the
737
- * ORIGINAL NDJSON response while its detached task is alive (409 when live
738
- * delivery is unavailable — fall back to the durable lifecycle stream)
739
- *
740
- * The contract: identify → recover durable progress → follow live → re-query
741
- * the final result from the feature's own record. Token text is deliberately
742
- * never replayed on the lifecycle stream — that is what `/rejoin` is for.
743
- *
744
- * The SSE wire rides the package's own `stream/sse` kernel. This module owns
745
- * ONE connection's semantics (frames → typed events, cursor advancement,
746
- * terminal `end`); stall timers, retry budgets, and reconnect loops stay host
747
- * policy — every yielded item carries the cursor the next attempt resumes from.
748
- */
749
-
750
- /** `matrx_runtime.models.ExecutionStatus` — the only progress column. */
751
- type MatrxRuntimeExecutionStatus = "pending" | "running" | "paused" | "waiting_input" | "completed" | "failed" | "cancelled";
752
- declare const TERMINAL_MATRX_RUNTIME_STATUSES: ReadonlySet<MatrxRuntimeExecutionStatus>;
753
- /** One durable spine event on the wire (`OperationEvent`) — `seq` is the reconnect cursor. */
754
- interface MatrxRuntimeOperationEvent {
755
- seq: number | null;
756
- /** Lifecycle vocabulary: created | started | paused | resumed | waiting_input | completed | failed | cancelled | checkpoint_saved | note. */
757
- kind: string;
758
- execution_id: string;
759
- root_execution_id: string | null;
760
- detail: MatrxJsonObject | null;
761
- created_at: string | null;
762
- }
763
- /** One root execution as a reconnecting client sees it (`OperationView`). */
764
- interface MatrxRuntimeOperationView {
765
- execution_id: string;
766
- /** Durable request identity — feeds `/rejoin` and no-prompt resume recovery. */
767
- request_id: string | null;
768
- type: string;
769
- status: MatrxRuntimeExecutionStatus;
770
- is_terminal: boolean;
771
- waiting_input: boolean;
772
- /** Decimal on the wire — may arrive as number or string; display-only. */
773
- cost: number | string;
774
- meters: Record<string, number | string>;
775
- link_kind: string | null;
776
- link_id: string | null;
777
- error: MatrxJsonObject | null;
778
- created_at: string | null;
779
- started_at: string | null;
780
- ended_at: string | null;
781
- last_event_seq: number;
782
- events_path: string;
783
- stream_path: string;
784
- }
785
- interface MatrxOperationStatusResponse {
786
- request_id: string;
787
- operation_count: number;
788
- operations: MatrxRuntimeOperationView[];
789
- }
790
- interface MatrxOperationsByLinkResponse {
791
- link_kind: string;
792
- link_id: string;
793
- operation_count: number;
794
- operations: MatrxRuntimeOperationView[];
795
- }
796
- interface MatrxOperationEventsPage {
797
- execution_id: string;
798
- root_execution_id: string;
799
- events: MatrxRuntimeOperationEvent[];
800
- /** Feeds the next page or the SSE `Last-Event-ID` — polling and push share ONE cursor. */
801
- next_after_seq: number;
802
- has_more: boolean;
803
- root_status: MatrxRuntimeExecutionStatus;
804
- root_is_terminal: boolean;
805
- }
806
- /**
807
- * Where is my operation? Resolves an `X-Request-ID` to its root execution(s).
808
- * Returns null on 404 — missing and unowned share one shape by design
809
- * (existence is never leaked).
810
- */
811
- declare function getRuntimeOperationStatus(transport: MatrxTransport, requestId: string, options?: {
812
- signal?: AbortSignal;
813
- }): Promise<MatrxOperationStatusResponse | null>;
814
- /**
815
- * Operations for a feature record — e.g. `("conversation", conversationId)`,
816
- * `("workflow", runId)`, `("agent_run", runId)`. Newest first; unowned trees
817
- * omitted. Returns null on 404 (surface absent, or the caller owns nothing —
818
- * one shape by design).
819
- */
820
- declare function getRuntimeOperationsByLink(transport: MatrxTransport, linkKind: string, linkId: string, options?: {
821
- limit?: number;
822
- signal?: AbortSignal;
823
- }): Promise<MatrxOperationsByLinkResponse | null>;
824
- /**
825
- * Durable progress page for the whole operation TREE:
826
- * `GET /runtime/executions/{id}/events?after_seq=…`. Pass any node id — it
827
- * resolves to the root.
828
- */
829
- declare function listRuntimeOperationEvents(transport: MatrxTransport, executionId: string, options?: {
830
- afterSeq?: number;
831
- limit?: number;
832
- /** Repeatable event-kind filter. */
833
- kinds?: readonly string[];
834
- signal?: AbortSignal;
835
- }): Promise<MatrxOperationEventsPage>;
836
- /**
837
- * One item from the follow stream. Every item carries `cursor` — the highest
838
- * event seq seen so far, which is exactly the `Last-Event-ID` a reconnect
839
- * resumes from (host retry policy owns the reconnect loop).
840
- */
841
- type MatrxOperationFollowEvent = {
842
- /** A parsed durable spine event. */
843
- type: "event";
844
- event: MatrxRuntimeOperationEvent;
845
- /** The frame's SSE `id:` as an integer, when it carried one. */
846
- seq: number | null;
847
- cursor: number;
848
- } | {
849
- /**
850
- * A frame that carried no deliverable event — a comment heartbeat, an
851
- * unknown event name, or a malformed payload (also surfaced through
852
- * `onMalformedFrame`). ANY parsed frame proves the wire is alive: hosts
853
- * reset stall timers and retry budgets on it.
854
- */
855
- type: "liveness";
856
- cursor: number;
857
- } | {
858
- /** The server's terminal frame — the root settled; the stream is over. */
859
- type: "end";
860
- status: MatrxRuntimeExecutionStatus | null;
861
- cursor: number;
862
- };
863
- interface FollowRuntimeOperationOptions {
864
- /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */
865
- lastEventSeq?: number;
866
- /** Abort the follow — the generator simply ends. */
867
- signal?: AbortSignal;
868
- /** A frame whose payload failed to parse — never silently dropped. */
869
- onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;
870
- /** Unterminated trailing SSE text at stream end (diagnostic, never an event). */
871
- onIncomplete?: (text: string) => void;
872
- }
873
- /**
874
- * Follow ONE SSE connection of an operation's lifecycle stream:
875
- * `GET /runtime/executions/{id}/events/stream` with `Last-Event-ID` when
876
- * resuming past 0. Replays from the cursor, then follows live; a
877
- * WAITING_INPUT park keeps it open (a resume re-attaches to the same
878
- * execution and its events continue here). Ends after yielding
879
- * `{type: "end"}` when the root settles; a server close WITHOUT an end frame
880
- * simply ends the generator — reconnect from the last yielded `cursor` (host
881
- * retry policy).
882
- */
883
- declare function followRuntimeOperationEvents(transport: MatrxTransport, executionId: string, options?: FollowRuntimeOperationOptions): AsyncGenerator<MatrxOperationFollowEvent, void, undefined>;
884
- interface FollowRuntimeOperationToEndOptions {
885
- /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */
886
- lastEventSeq?: number;
887
- /** Caller teardown — aborting resolves with `ended: false`. */
888
- signal?: AbortSignal;
889
- /**
890
- * The server pings every ~15s, so a wire that is open but silent past this
891
- * is dead (buffering proxy, idle-killed connection) — abort the attempt and
892
- * retry rather than hanging forever. Default 45_000.
893
- */
894
- stallTimeoutMs?: number;
895
- /**
896
- * Consecutive failed attempts before giving up. A single-server deployment
897
- * deliberately drains for 60s, then starts a new container — the default
898
- * budget (60 × 2s) keeps following for ~three minutes so the runtime ledger
899
- * can bridge that handoff. ANY parsed frame resets the budget. Default 60.
900
- */
901
- reconnectLimit?: number;
902
- /** Delay between attempts. Default 2_000. */
903
- reconnectDelayMs?: number;
904
- /** Fired per durable spine event (lifecycle transitions + notes). */
905
- onEvent: (event: MatrxRuntimeOperationEvent, seq: number | null) => void;
906
- /** A failed attempt (never silently swallowed when provided). */
907
- onAttemptError?: (error: unknown) => void;
908
- /** A frame whose payload failed to parse (the ledger heals gaps on reconnect). */
909
- onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;
910
- }
911
- interface FollowRuntimeOperationToEndResult {
912
- /** True when the server sent the terminal `end` frame. */
913
- ended: boolean;
914
- /** The root status carried on the `end` frame (when `ended`). */
915
- status: MatrxRuntimeExecutionStatus | null;
916
- }
917
- /**
918
- * Follow an operation's lifecycle stream TO ITS END — the full production
919
- * reconnect policy over `followRuntimeOperationEvents`: replay-then-follow
920
- * with bounded reconnects, a stall watchdog, and durable `Last-Event-ID`
921
- * cursor advancement across attempts.
922
- *
923
- * Resolves `{ended: true, status}` on the server's `end` frame (the operation
924
- * settled); `{ended: false}` when the caller aborted or every reconnect
925
- * attempt failed. A WAITING_INPUT park keeps the stream open by design — a
926
- * resume re-attaches to the same execution and its events continue arriving
927
- * on the same cursor. Any parsed frame — comment heartbeats included —
928
- * proves the wire is alive and resets both the stall timer and the retry
929
- * budget.
930
- */
931
- declare function followRuntimeOperationToEnd(transport: MatrxTransport, executionId: string, options: FollowRuntimeOperationToEndOptions): Promise<FollowRuntimeOperationToEndResult>;
932
- /**
933
- * Rejoin the ORIGINAL NDJSON response while its detached task is still alive:
934
- * `POST /runtime/operations/{request_id}/rejoin`. Replays the response from
935
- * frame one, then continues live — every frame is sequence-stamped
936
- * (`stream_seq`), so a same-page reconnect can drop frames it already
937
- * rendered. Throws `MatrxApiError` with status 409 when live delivery is
938
- * unavailable — fall back to `followRuntimeOperationEvents` + a final record
939
- * re-query. The `requestId` must be the server's `X-Request-ID`.
940
- */
941
- declare function rejoinRuntimeOperation(transport: MatrxTransport, requestId: string, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
942
-
943
310
  /**
944
311
  * Delegated client tools — submit results and discover pending calls.
945
312
  *
@@ -1032,4 +399,4 @@ declare function listUserPendingToolCalls(transport: MatrxTransport, options?: {
1032
399
  signal?: AbortSignal;
1033
400
  }): Promise<MatrxPendingCallSummary[]>;
1034
401
 
1035
- export { type CreateMatrxTransportOptions, type FollowRuntimeOperationOptions, type FollowRuntimeOperationToEndOptions, type FollowRuntimeOperationToEndResult, MATRX_AI_API_VERSION_DEFAULT, type MatrxAgentStartRequest, type MatrxAiApiVersion, MatrxApiError, type MatrxCallError, type MatrxCancelResponse, type MatrxChatMessage, type MatrxClientToolResult, type MatrxCompletedRun, type MatrxContextAnchor, type MatrxConversationContinueRequest, type MatrxConversationResumeRequest, type MatrxConversationStart, type MatrxEphemeralConversation, type MatrxJsonObject, type MatrxJsonValue, type MatrxOperationEventsPage, type MatrxOperationFollowEvent, type MatrxOperationStatusResponse, type MatrxOperationsByLinkResponse, type MatrxPendingCallSummary, type MatrxProtocolDowngrade, type MatrxProtocolFallbackOptions, type MatrxRequestInfo, type MatrxRequestScope, MatrxRunError, type MatrxRunHandle, type MatrxRuntimeExecutionStatus, type MatrxRuntimeOperationEvent, type MatrxRuntimeOperationView, type MatrxStoredConversationContinue, type MatrxStoredConversationCreate, type MatrxStreamCallOptions, type MatrxToolResultsResponse, type MatrxTransport, type MatrxTransportDiagnostics, type MatrxTransportRequest, type MatrxTransportTarget, type MatrxTurnFields, OrganizationContextError, type OrganizationContextErrorCode, type RunAgentToCompletionOptions, TERMINAL_MATRX_RUNTIME_STATUSES, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertQueryOrganizationMatchesContext, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, extractMatrxErrorCode, extractMatrxErrorMessage, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, getRuntimeOperationStatus, getRuntimeOperationsByLink, isCoveredAiPath, isV2Path, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, rejoinRuntimeOperation, requireOrganizationContext, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults, toV1FallbackUrl, toV2Path };
402
+ export { type CreateMatrxTransportOptions, MATRX_AI_API_VERSION_DEFAULT, type MatrxAiApiVersion, type MatrxCallError, type MatrxClientToolResult, MatrxJsonObject, MatrxJsonValue, type MatrxPendingCallSummary, type MatrxProtocolDowngrade, type MatrxProtocolFallbackOptions, type MatrxRequestInfo, type MatrxToolResultsResponse, MatrxTransport, type MatrxTransportDiagnostics, type MatrxTransportTarget, OrganizationContextError, type OrganizationContextErrorCode, type OrganizationOperation, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createMatrxTransport, createOrganizationOperation, fetchWithMatrxProtocolFallback, isCoveredAiPath, isV2Path, listConversationPendingToolCalls, listUserPendingToolCalls, normalizeMatrxError, requireOrganizationContext, submitAgentToolResults, toV1FallbackUrl, toV2Path };