@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
@@ -0,0 +1,659 @@
1
+ import { MatrxStreamEnvelope, MatrxNdjsonIssue, MatrxStreamEnvelopeObservation } from './stream/ndjson.js';
2
+ import { MatrxSseFrame } from './stream/sse.js';
3
+
4
+ /**
5
+ * `@ai-matrx/agents/matrx` — the Matrx transport port.
6
+ *
7
+ * The ONE seam between this package's wire semantics and a host's connection
8
+ * policy. This package owns WHAT is said to the AI Matrx server — paths,
9
+ * methods, JSON bodies, streaming Accept headers, the `Last-Event-ID` cursor
10
+ * header — and the host owns HOW the connection is made:
11
+ *
12
+ * - base-URL / backend-channel resolution (global, sandbox override, local
13
+ * engine, EC2-dedicated — whatever ladder the host runs);
14
+ * - credentials (Supabase JWT `Authorization: Bearer`, guest
15
+ * `X-Fingerprint-ID`, or the API-key lane) — NEVER implemented here;
16
+ * - the `X-Organization-Id` context header;
17
+ * - retry policy, network-level timeouts, and diagnostics capture.
18
+ *
19
+ * A host implements the port in a few lines:
20
+ *
21
+ * ```ts
22
+ * const transport: MatrxTransport = {
23
+ * fetch: (path, init) =>
24
+ * fetch(`${baseUrl}${path}`, {
25
+ * ...init,
26
+ * headers: { ...init.headers, ...authHeaders() },
27
+ * }),
28
+ * };
29
+ * ```
30
+ *
31
+ * The port is deliberately structural and `fetch`-shaped so `@ai-matrx/data`'s
32
+ * `/api` transport can implement it without importing this package.
33
+ */
34
+ /**
35
+ * The request this package hands the port. A strict subset of `RequestInit`,
36
+ * so a host can spread it straight into `fetch`.
37
+ */
38
+ interface MatrxTransportRequest {
39
+ method: "GET" | "POST";
40
+ /**
41
+ * Wire-semantic headers the CALL requires (`Content-Type`, `Accept`,
42
+ * `Last-Event-ID`). The host merges its policy headers (auth, org) on top;
43
+ * it must not drop these.
44
+ */
45
+ headers: Record<string, string>;
46
+ /** Pre-serialized JSON body, present on POST calls that carry one. */
47
+ body?: string;
48
+ /** Caller cancellation. The host must wire it to the underlying fetch. */
49
+ signal?: AbortSignal;
50
+ }
51
+ /**
52
+ * The transport port. `path` is server-relative and always starts with `/`
53
+ * (`/ai/...`, `/runtime/...`); the host prepends its resolved base URL.
54
+ */
55
+ interface MatrxTransport {
56
+ fetch(path: string, init: MatrxTransportRequest): Promise<Response>;
57
+ }
58
+ /**
59
+ * A non-2xx response from the Matrx API, with the server's structured error
60
+ * body preserved and its richest human-readable message extracted.
61
+ */
62
+ declare class MatrxApiError extends Error {
63
+ readonly name = "MatrxApiError";
64
+ /** HTTP status of the failed response. */
65
+ readonly status: number;
66
+ /** Machine code from the server body (`code`, or `detail.code`), when present. */
67
+ readonly code: string | null;
68
+ /** The parsed server error body, verbatim (undefined when unparsable). */
69
+ readonly serverDetail: unknown;
70
+ /** The request path the failure came from (server-relative). */
71
+ readonly path: string;
72
+ constructor(args: {
73
+ status: number;
74
+ path: string;
75
+ serverDetail?: unknown;
76
+ message?: string;
77
+ });
78
+ }
79
+ /**
80
+ * Extract the richest human-readable message from a Matrx/FastAPI error body.
81
+ *
82
+ * aidream 4xx validation errors look like
83
+ * `{ error, user_message, details: [{ field, message, help }] }`; hand-raised
84
+ * HTTPExceptions carry `{ detail: { code, message } }`; FastAPI's defaults are
85
+ * `{ detail: string | [{ msg }] }`. Preference order: `user_message` →
86
+ * `message` → joined `details[].message` → `detail.message` →
87
+ * `detail` string → joined `detail[].msg`. Returns undefined for
88
+ * unrecognized bodies so callers fall back to the bare status line.
89
+ */
90
+ declare function extractMatrxErrorMessage(serverDetail: unknown): string | undefined;
91
+ /**
92
+ * Extract the machine error code from a Matrx error body: top-level `code`,
93
+ * else `detail.code` (the hand-raised HTTPException shape). Null when absent.
94
+ */
95
+ declare function extractMatrxErrorCode(serverDetail: unknown): string | null;
96
+
97
+ /**
98
+ * The conversation-start contract — client-minted `conversation_id`, `is_new`,
99
+ * `store` — typed exactly per the cross-repo System of Record
100
+ * (`common-docs/systems/agents/conversation-start-contract/FEATURE.md`;
101
+ * server truth `aidream/services/conversation_context/scope.py::
102
+ * ConversationStartRequest`).
103
+ *
104
+ * Every request that STARTS a conversation sends all three fields, no
105
+ * defaults:
106
+ *
107
+ * | `is_new` | `store` | Result |
108
+ * |----------|---------|----------------------------------------------------------|
109
+ * | true | true | Create the row with the caller's id — 409 if it exists |
110
+ * | true | false | No row. The id is correlation only (ephemeral run) |
111
+ * | false | true | Continue it — 404 if the caller doesn't own it |
112
+ * | false | false | Ephemeral run on a known id; nothing read, nothing written |
113
+ *
114
+ * `store` is the ONLY ephemeral signal; `is_new` is the caller's assertion
115
+ * about the id, never a persistence switch. `prior_messages` (the client-owned
116
+ * transcript of an ephemeral multi-turn run) is only valid with
117
+ * `store: false` — the union below makes the invalid combination
118
+ * unrepresentable, mirroring the server's 422.
119
+ *
120
+ * Continue routes (`POST /ai/conversations/{id}`) take the id from the path
121
+ * and do not carry this triple.
122
+ */
123
+ /** Recursive JSON value — the package's honest type for free-form wire bags. */
124
+ type MatrxJsonValue = string | number | boolean | null | MatrxJsonValue[] | {
125
+ [key: string]: MatrxJsonValue;
126
+ };
127
+ /** A JSON object on the wire. */
128
+ type MatrxJsonObject = {
129
+ [key: string]: MatrxJsonValue;
130
+ };
131
+ /**
132
+ * One LLM message on the request wire — `prior_messages` entries for
133
+ * stateless multi-turn runs. Mirrors aidream's `ChatMessageInput`
134
+ * (`aidream/schemas/messages.py`, `extra="allow"` — additional provider
135
+ * fields round-trip untouched).
136
+ */
137
+ interface MatrxChatMessage {
138
+ role: string;
139
+ content?: string | MatrxJsonValue[] | null;
140
+ name?: string | null;
141
+ tool_call_id?: string | null;
142
+ tool_calls?: MatrxJsonObject[] | null;
143
+ [extra: string]: MatrxJsonValue | undefined;
144
+ }
145
+ /** `is_new: true, store: true` — create the row with the caller's id. */
146
+ interface MatrxStoredConversationCreate {
147
+ conversation_id: string;
148
+ is_new: true;
149
+ store: true;
150
+ }
151
+ /** `is_new: false, store: true` — continue an owned stored conversation via a start route. */
152
+ interface MatrxStoredConversationContinue {
153
+ conversation_id: string;
154
+ is_new: false;
155
+ store: true;
156
+ }
157
+ /**
158
+ * `store: false` — ephemeral: nothing read, nothing written; the id is the
159
+ * caller's correlation handle. This is the ONLY member that may carry
160
+ * `prior_messages` (the server 422s a client transcript on a stored run).
161
+ */
162
+ interface MatrxEphemeralConversation {
163
+ conversation_id: string;
164
+ is_new: boolean;
165
+ store: false;
166
+ prior_messages?: MatrxChatMessage[];
167
+ }
168
+ /** The full conversation-start triple, one member per contract cell. */
169
+ type MatrxConversationStart = MatrxStoredConversationCreate | MatrxStoredConversationContinue | MatrxEphemeralConversation;
170
+ /** Mint a fresh client-side conversation id (the contract requires the CLIENT to mint it). */
171
+ declare function mintMatrxConversationId(): string;
172
+ /** Start a NEW stored conversation (`is_new: true, store: true`). */
173
+ declare function newStoredConversationStart(conversationId?: string): MatrxStoredConversationCreate;
174
+ /**
175
+ * Continue an EXISTING stored conversation through a start route
176
+ * (`is_new: false, store: true` — 404 when the caller doesn't own the id).
177
+ * Prefer `continueAgentConversation` (the dedicated continue route) for
178
+ * ordinary follow-up turns.
179
+ */
180
+ declare function continueStoredConversationStart(conversationId: string): MatrxStoredConversationContinue;
181
+ /**
182
+ * Start a NEW ephemeral run (`is_new: true, store: false`) — a freshly minted
183
+ * correlation id, nothing persisted.
184
+ */
185
+ declare function newEphemeralConversationStart(conversationId?: string): MatrxEphemeralConversation;
186
+ /**
187
+ * Continue an ephemeral multi-turn run (`is_new: false, store: false`): the
188
+ * CLIENT owns the transcript and replays it as `prior_messages` (ordered
189
+ * oldest-first) because the server wrote no rows to rebuild from. The server
190
+ * still owns the agent definition, model, tools, and system prompt.
191
+ */
192
+ declare function continueEphemeralConversationStart(conversationId: string, priorMessages: MatrxChatMessage[]): MatrxEphemeralConversation;
193
+
194
+ /**
195
+ * Internal request plumbing for `@ai-matrx/agents/matrx`. Not part of the
196
+ * public surface — `matrx/index.ts` deliberately does not re-export this
197
+ * module. Everything here is pure: no globals, no work at import time.
198
+ */
199
+
200
+ /**
201
+ * Options for every streaming call, riding the NDJSON kernel's contract.
202
+ * Public via `./run`'s re-export.
203
+ */
204
+ interface MatrxStreamCallOptions {
205
+ /** Abort the fetch and end the events iterator. */
206
+ signal?: AbortSignal;
207
+ /** Bounded background read-ahead (see `stream/ndjson`). */
208
+ maxReadAhead?: number;
209
+ /** Malformed NDJSON is non-fatal but must never disappear silently. */
210
+ onMalformedLine?: (issue: MatrxNdjsonIssue) => void;
211
+ /** Valid JSON with no recognized Matrx envelope. */
212
+ onUnknownEnvelope?: (value: unknown) => void;
213
+ /** Observe every valid envelope in its exact wire form. */
214
+ onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;
215
+ }
216
+ /**
217
+ * A live agent run: the server-assigned ids (from response headers, available
218
+ * BEFORE any event) and the normalized event stream. Public via `./run`.
219
+ */
220
+ interface MatrxRunHandle {
221
+ /** `X-Request-ID` — the ONLY id `POST /ai/cancel/{request_id}` accepts. */
222
+ requestId: string | null;
223
+ /** `X-Conversation-ID` — the server's conversation identity. */
224
+ conversationId: string | null;
225
+ /** Normalized `{event, data}` envelopes through the ONE wire kernel. */
226
+ events: AsyncGenerator<MatrxStreamEnvelope, void, undefined>;
227
+ /** The raw response, for hosts that need headers/status beyond the ids. */
228
+ response: Response;
229
+ }
230
+
231
+ /**
232
+ * Agent run lifecycle against the AI Matrx API — start, continue, resume,
233
+ * cancel — over the `MatrxTransport` port, with every streaming response
234
+ * parsed through the package's ONE NDJSON wire kernel (`stream/ndjson`).
235
+ *
236
+ * Server truth (verified against aidream source):
237
+ * - `POST /ai/agents/{agent_id}` — start (`aidream/api/routers/agents.py`)
238
+ * - `POST /ai/conversations/{conversation_id}` — continue (`aidream/api/routers/conversations.py`)
239
+ * - `POST /ai/conversations/{conversation_id}/resume` — resume after
240
+ * client-delegated tool suspension (same router)
241
+ * - `POST /ai/cancel/{request_id}?mode=interrupt` — cancel (`aidream/api/routers/cancel.py`)
242
+ *
243
+ * Response headers arrive before the body: `X-Conversation-ID` and
244
+ * `X-Request-ID` are surfaced on the run handle immediately. `X-Request-ID`
245
+ * is the ONLY id the server accepts for cancel — a client-local id means
246
+ * nothing to it.
247
+ *
248
+ * Host policy stays out: no retry, no store, no timeouts, no persistence
249
+ * (C10: no-persistence). Cancellation is the caller's `AbortSignal`; a client
250
+ * disconnect never stops server work (`detach_on_disconnect`).
251
+ */
252
+
253
+ /**
254
+ * Stable identity of the durable entity whose saved context owns a run —
255
+ * the server reloads the row and uses ITS scope (`ContextAnchor`,
256
+ * `aidream/services/conversation_context/scope.py`).
257
+ */
258
+ interface MatrxContextAnchor {
259
+ resource_type: string;
260
+ resource_id: string;
261
+ }
262
+ /**
263
+ * Scope and source fields shared by every scoped request
264
+ * (`ScopedRequest` / `AcceptsInjectedScope` server-side). All optional here;
265
+ * the start request narrows `organization_id` to required.
266
+ */
267
+ interface MatrxRequestScope {
268
+ organization_id?: string;
269
+ project_id?: string | null;
270
+ task_id?: string | null;
271
+ /** Active context-scope ids from the client's global picker (membership-validated server-side). */
272
+ scope_ids?: string[] | null;
273
+ /** Active scope-TYPE ids — a type-level selection with no specific scope chosen. */
274
+ active_scope_type_ids?: string[] | null;
275
+ context_anchor?: MatrxContextAnchor | null;
276
+ /** Stable application slug that initiated the request. */
277
+ source_app?: string | null;
278
+ /** Stable feature slug within the source application. */
279
+ source_feature?: string | null;
280
+ /** "user" = a person directly triggered this; "auto" = client automation; omit for API callers. */
281
+ initiation?: "user" | "auto" | null;
282
+ /** Specific connected desktop instance allowed to claim delegated local tools. */
283
+ target_instance_id?: string | null;
284
+ }
285
+ /**
286
+ * Fields shared by start/continue turn requests (tool injection, client
287
+ * capability envelope, context object). The complex bags (`tools`, `client`,
288
+ * `user`, `config_overrides`) are typed as JSON objects — their authoritative
289
+ * schemas are the server's Pydantic models and the generated API types;
290
+ * this package stays payload-agnostic about them by design.
291
+ */
292
+ interface MatrxTurnFields {
293
+ /** What the human typed (string), or structured input parts. Never smuggle machine content here. */
294
+ user_input?: string | MatrxJsonValue[] | null;
295
+ /** Per-run model/config overrides (LLMParams shape). */
296
+ config_overrides?: MatrxJsonObject | null;
297
+ debug?: boolean;
298
+ /** Additive tool specs merged into the agent's resolved tool set. */
299
+ tools?: MatrxJsonObject[];
300
+ /** When set, becomes the agent's ENTIRE tool set for the turn. */
301
+ tools_replace?: MatrxJsonObject[] | null;
302
+ /** Client capability envelope (`ClientContext`). */
303
+ client?: MatrxJsonObject | null;
304
+ /** Per-request user-level tool inclusion/exclusion overrides. */
305
+ user?: MatrxJsonObject | null;
306
+ /** Per-route context object, free-form by design. */
307
+ context?: MatrxJsonObject;
308
+ writable_variables?: string[];
309
+ allow_context_create?: boolean;
310
+ /** Request-snapshot capture override (tri-state; omit for the platform default). */
311
+ snapshot?: boolean | null;
312
+ }
313
+ /**
314
+ * `POST /ai/agents/{agent_id}` body (`AgentStartRequest` server-side).
315
+ * The conversation-start triple is required by construction; `organization_id`
316
+ * is required (the server 422s a blank one — it never manufactures an org).
317
+ * `stream` is not accepted here: this client is the streaming path and always
318
+ * sends `stream: true`.
319
+ */
320
+ type MatrxAgentStartRequest = MatrxConversationStart & Omit<MatrxRequestScope, "organization_id"> & MatrxTurnFields & {
321
+ organization_id: string;
322
+ /** Variable name → value map filling the agent's declared variables. */
323
+ variables?: MatrxJsonObject | null;
324
+ /** Run the versions table row instead of the live agent row. */
325
+ is_version?: boolean;
326
+ max_iterations?: number;
327
+ max_retries_per_iteration?: number;
328
+ };
329
+ /**
330
+ * `POST /ai/mandates/{mandate_key}` uses the exact saved-agent start body.
331
+ * The server resolves the mandate's holder, binding, and configuration; a
332
+ * client must offer only the declared variables and human input here.
333
+ */
334
+ type MatrxMandateStartRequest = MatrxAgentStartRequest;
335
+ /** `POST /ai/conversations/{id}` body (`ConversationContinueRequest` server-side). */
336
+ type MatrxConversationContinueRequest = MatrxRequestScope & MatrxTurnFields & {
337
+ /** Re-run the conversation's current persisted state (recovery after a failed turn); omit `user_input`. */
338
+ retry?: boolean;
339
+ };
340
+ /**
341
+ * `POST /ai/conversations/{id}/resume` body (`ResumeRequest` server-side) —
342
+ * the shipped durable continuation after client-delegated tool calls were
343
+ * answered via `POST /tool_results` while the original stream was gone.
344
+ * `user_request_id` is optional: when omitted the server resolves the turn
345
+ * from the conversation's newest answered client-delegated tool call.
346
+ * Re-send fresh `context` here — a resumed loop is otherwise context-blind.
347
+ */
348
+ type MatrxConversationResumeRequest = MatrxRequestScope & {
349
+ user_request_id?: string | null;
350
+ config_overrides?: MatrxJsonObject | null;
351
+ debug?: boolean;
352
+ tools?: MatrxJsonObject[];
353
+ tools_replace?: MatrxJsonObject[] | null;
354
+ client?: MatrxJsonObject | null;
355
+ user?: MatrxJsonObject | null;
356
+ context?: MatrxJsonObject;
357
+ writable_variables?: string[];
358
+ allow_context_create?: boolean;
359
+ };
360
+ /** `POST /ai/cancel/{request_id}` response (`CancelResponse` server-side). */
361
+ interface MatrxCancelResponse {
362
+ status: string;
363
+ request_id: string;
364
+ spine_executions_signalled: string[];
365
+ }
366
+ /** Start an agent run: `POST /ai/agents/{agent_id}` (NDJSON stream). */
367
+ declare function startAgentRun(transport: MatrxTransport, agentId: string, request: MatrxAgentStartRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
368
+ /**
369
+ * Start a declared mandate: `POST /ai/mandates/{mandate_key}` (NDJSON
370
+ * stream). This is deliberately separate from `startAgentRun`: callers name
371
+ * the mandate and never resolve or echo its holder/configuration themselves.
372
+ */
373
+ declare function startMandateRun(transport: MatrxTransport, mandateKey: string, request: MatrxMandateStartRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
374
+ /** Continue a stored conversation: `POST /ai/conversations/{id}` (NDJSON stream). */
375
+ declare function continueAgentConversation(transport: MatrxTransport, conversationId: string, request: MatrxConversationContinueRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
376
+ /**
377
+ * Resume a suspended loop after delegated tool answers landed:
378
+ * `POST /ai/conversations/{id}/resume` (NDJSON stream). A 409
379
+ * (`resume_conflict`) means another resume holds the run claim — retrying is
380
+ * host policy.
381
+ */
382
+ declare function resumeAgentConversation(transport: MatrxTransport, conversationId: string, request?: MatrxConversationResumeRequest, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
383
+ /**
384
+ * Stop a running request at its next iteration boundary:
385
+ * `POST /ai/cancel/{request_id}`. Cooperative and best-effort — the in-flight
386
+ * provider call finishes by design, and everything already streamed persists.
387
+ * `mode: "interrupt"` = stop-and-fork: the tail after the last clean boundary
388
+ * persists hidden so the user's follow-up replies to what they actually saw.
389
+ * The id must be the server's `X-Request-ID`.
390
+ */
391
+ declare function cancelAgentRun(transport: MatrxTransport, requestId: string, options?: {
392
+ mode?: "cancel" | "interrupt";
393
+ signal?: AbortSignal;
394
+ }): Promise<MatrxCancelResponse>;
395
+ /**
396
+ * A run that terminated unsuccessfully: the server emitted a fatal `error`
397
+ * event, or the `user_request` completion settled `failed`/`cancelled`.
398
+ */
399
+ declare class MatrxRunError extends Error {
400
+ readonly name = "MatrxRunError";
401
+ /** The verbatim `error` event payload, when one fired. */
402
+ readonly errorPayload: Record<string, unknown> | null;
403
+ /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
404
+ readonly completionStatus: string | null;
405
+ /** Text streamed before the failure — partial content never vanishes. */
406
+ readonly partialText: string;
407
+ constructor(args: {
408
+ message: string;
409
+ errorPayload?: Record<string, unknown> | null;
410
+ completionStatus?: string | null;
411
+ partialText?: string;
412
+ });
413
+ }
414
+ interface MatrxCompletedRun {
415
+ /** Accumulated `chunk` text (falls back to the completion's `result.output`). */
416
+ text: string;
417
+ requestId: string | null;
418
+ conversationId: string | null;
419
+ /** The `user_request` completion payload, verbatim, when one arrived. */
420
+ completion: Record<string, unknown> | null;
421
+ }
422
+ interface RunAgentToCompletionOptions extends MatrxStreamCallOptions {
423
+ /** Live progress: the full accumulated text after each chunk. */
424
+ onChunk?: (fullText: string) => void;
425
+ /** Every normalized envelope, before this helper interprets it. */
426
+ onEvent?: (envelope: MatrxStreamEnvelope) => void;
427
+ }
428
+ /**
429
+ * Run an agent end-to-end and resolve with its full text output — the
430
+ * package-level equivalent of the simplest existing host path
431
+ * (`useRunAgent`): accumulate `chunk` text, treat a fatal `error` event or a
432
+ * `failed`/`cancelled` `user_request` completion as a thrown `MatrxRunError`,
433
+ * and fall back to the completion's `result.output` when no text streamed.
434
+ *
435
+ * The caller still owns the conversation-start triple on `request` — a
436
+ * one-shot run typically uses `newEphemeralConversationStart()`.
437
+ */
438
+ declare function runAgentToCompletion(transport: MatrxTransport, agentId: string, request: MatrxAgentStartRequest, options?: RunAgentToCompletionOptions): Promise<MatrxCompletedRun>;
439
+
440
+ /**
441
+ * Runtime operations — the canonical reconnect & resume read surface of the
442
+ * execution spine, over the `MatrxTransport` port.
443
+ *
444
+ * Server truth (verified against aidream source,
445
+ * `aidream/api/routers/runtime_operations.py` + `aidream/services/runtime/
446
+ * reconnect.py`; mounted at bare `/runtime`):
447
+ * - `GET /runtime/operations/{request_id}` — identify by `X-Request-ID`
448
+ * - `GET /runtime/operations/by-link/{kind}/{id}` — identify by feature record
449
+ * - `GET /runtime/executions/{id}/events` — durable seq-cursored page
450
+ * - `GET /runtime/executions/{id}/events/stream` — SSE replay-then-follow,
451
+ * `id:` = per-tree seq, reconnect with `Last-Event-ID`
452
+ * - `POST /runtime/operations/{request_id}/rejoin` — replay + follow the
453
+ * ORIGINAL NDJSON response while its detached task is alive (409 when live
454
+ * delivery is unavailable — fall back to the durable lifecycle stream)
455
+ *
456
+ * The contract: identify → recover durable progress → follow live → re-query
457
+ * the final result from the feature's own record. Token text is deliberately
458
+ * never replayed on the lifecycle stream — that is what `/rejoin` is for.
459
+ *
460
+ * The SSE wire rides the package's own `stream/sse` kernel. This module owns
461
+ * ONE connection's semantics (frames → typed events, cursor advancement,
462
+ * terminal `end`); stall timers, retry budgets, and reconnect loops stay host
463
+ * policy — every yielded item carries the cursor the next attempt resumes from.
464
+ */
465
+
466
+ /** `matrx_runtime.models.ExecutionStatus` — the only progress column. */
467
+ type MatrxRuntimeExecutionStatus = "pending" | "running" | "paused" | "waiting_input" | "completed" | "failed" | "cancelled";
468
+ declare const TERMINAL_MATRX_RUNTIME_STATUSES: ReadonlySet<MatrxRuntimeExecutionStatus>;
469
+ /** One durable spine event on the wire (`OperationEvent`) — `seq` is the reconnect cursor. */
470
+ interface MatrxRuntimeOperationEvent {
471
+ seq: number | null;
472
+ /** Lifecycle vocabulary: created | started | paused | resumed | waiting_input | completed | failed | cancelled | checkpoint_saved | note. */
473
+ kind: string;
474
+ execution_id: string;
475
+ root_execution_id: string | null;
476
+ detail: MatrxJsonObject | null;
477
+ created_at: string | null;
478
+ }
479
+ /** One root execution as a reconnecting client sees it (`OperationView`). */
480
+ interface MatrxRuntimeOperationView {
481
+ execution_id: string;
482
+ /** Durable request identity — feeds `/rejoin` and no-prompt resume recovery. */
483
+ request_id: string | null;
484
+ type: string;
485
+ status: MatrxRuntimeExecutionStatus;
486
+ is_terminal: boolean;
487
+ waiting_input: boolean;
488
+ /** Decimal on the wire — may arrive as number or string; display-only. */
489
+ cost: number | string;
490
+ meters: Record<string, number | string>;
491
+ link_kind: string | null;
492
+ link_id: string | null;
493
+ error: MatrxJsonObject | null;
494
+ created_at: string | null;
495
+ started_at: string | null;
496
+ ended_at: string | null;
497
+ last_event_seq: number;
498
+ events_path: string;
499
+ stream_path: string;
500
+ }
501
+ interface MatrxOperationStatusResponse {
502
+ request_id: string;
503
+ operation_count: number;
504
+ operations: MatrxRuntimeOperationView[];
505
+ }
506
+ interface MatrxOperationsByLinkResponse {
507
+ link_kind: string;
508
+ link_id: string;
509
+ operation_count: number;
510
+ operations: MatrxRuntimeOperationView[];
511
+ }
512
+ interface MatrxOperationEventsPage {
513
+ execution_id: string;
514
+ root_execution_id: string;
515
+ events: MatrxRuntimeOperationEvent[];
516
+ /** Feeds the next page or the SSE `Last-Event-ID` — polling and push share ONE cursor. */
517
+ next_after_seq: number;
518
+ has_more: boolean;
519
+ root_status: MatrxRuntimeExecutionStatus;
520
+ root_is_terminal: boolean;
521
+ }
522
+ /**
523
+ * Where is my operation? Resolves an `X-Request-ID` to its root execution(s).
524
+ * Returns null on 404 — missing and unowned share one shape by design
525
+ * (existence is never leaked).
526
+ */
527
+ declare function getRuntimeOperationStatus(transport: MatrxTransport, requestId: string, options?: {
528
+ signal?: AbortSignal;
529
+ }): Promise<MatrxOperationStatusResponse | null>;
530
+ /**
531
+ * Operations for a feature record — e.g. `("conversation", conversationId)`,
532
+ * `("workflow", runId)`, `("agent_run", runId)`. Newest first; unowned trees
533
+ * omitted. Returns null on 404 (surface absent, or the caller owns nothing —
534
+ * one shape by design).
535
+ */
536
+ declare function getRuntimeOperationsByLink(transport: MatrxTransport, linkKind: string, linkId: string, options?: {
537
+ limit?: number;
538
+ signal?: AbortSignal;
539
+ }): Promise<MatrxOperationsByLinkResponse | null>;
540
+ /**
541
+ * Durable progress page for the whole operation TREE:
542
+ * `GET /runtime/executions/{id}/events?after_seq=…`. Pass any node id — it
543
+ * resolves to the root.
544
+ */
545
+ declare function listRuntimeOperationEvents(transport: MatrxTransport, executionId: string, options?: {
546
+ afterSeq?: number;
547
+ limit?: number;
548
+ /** Repeatable event-kind filter. */
549
+ kinds?: readonly string[];
550
+ signal?: AbortSignal;
551
+ }): Promise<MatrxOperationEventsPage>;
552
+ /**
553
+ * One item from the follow stream. Every item carries `cursor` — the highest
554
+ * event seq seen so far, which is exactly the `Last-Event-ID` a reconnect
555
+ * resumes from (host retry policy owns the reconnect loop).
556
+ */
557
+ type MatrxOperationFollowEvent = {
558
+ /** A parsed durable spine event. */
559
+ type: "event";
560
+ event: MatrxRuntimeOperationEvent;
561
+ /** The frame's SSE `id:` as an integer, when it carried one. */
562
+ seq: number | null;
563
+ cursor: number;
564
+ } | {
565
+ /**
566
+ * A frame that carried no deliverable event — a comment heartbeat, an
567
+ * unknown event name, or a malformed payload (also surfaced through
568
+ * `onMalformedFrame`). ANY parsed frame proves the wire is alive: hosts
569
+ * reset stall timers and retry budgets on it.
570
+ */
571
+ type: "liveness";
572
+ cursor: number;
573
+ } | {
574
+ /** The server's terminal frame — the root settled; the stream is over. */
575
+ type: "end";
576
+ status: MatrxRuntimeExecutionStatus | null;
577
+ cursor: number;
578
+ };
579
+ interface FollowRuntimeOperationOptions {
580
+ /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */
581
+ lastEventSeq?: number;
582
+ /** Abort the follow — the generator simply ends. */
583
+ signal?: AbortSignal;
584
+ /** A frame whose payload failed to parse — never silently dropped. */
585
+ onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;
586
+ /** Unterminated trailing SSE text at stream end (diagnostic, never an event). */
587
+ onIncomplete?: (text: string) => void;
588
+ }
589
+ /**
590
+ * Follow ONE SSE connection of an operation's lifecycle stream:
591
+ * `GET /runtime/executions/{id}/events/stream` with `Last-Event-ID` when
592
+ * resuming past 0. Replays from the cursor, then follows live; a
593
+ * WAITING_INPUT park keeps it open (a resume re-attaches to the same
594
+ * execution and its events continue here). Ends after yielding
595
+ * `{type: "end"}` when the root settles; a server close WITHOUT an end frame
596
+ * simply ends the generator — reconnect from the last yielded `cursor` (host
597
+ * retry policy).
598
+ */
599
+ declare function followRuntimeOperationEvents(transport: MatrxTransport, executionId: string, options?: FollowRuntimeOperationOptions): AsyncGenerator<MatrxOperationFollowEvent, void, undefined>;
600
+ interface FollowRuntimeOperationToEndOptions {
601
+ /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */
602
+ lastEventSeq?: number;
603
+ /** Caller teardown — aborting resolves with `ended: false`. */
604
+ signal?: AbortSignal;
605
+ /**
606
+ * The server pings every ~15s, so a wire that is open but silent past this
607
+ * is dead (buffering proxy, idle-killed connection) — abort the attempt and
608
+ * retry rather than hanging forever. Default 45_000.
609
+ */
610
+ stallTimeoutMs?: number;
611
+ /**
612
+ * Consecutive failed attempts before giving up. A single-server deployment
613
+ * deliberately drains for 60s, then starts a new container — the default
614
+ * budget (60 × 2s) keeps following for ~three minutes so the runtime ledger
615
+ * can bridge that handoff. ANY parsed frame resets the budget. Default 60.
616
+ */
617
+ reconnectLimit?: number;
618
+ /** Delay between attempts. Default 2_000. */
619
+ reconnectDelayMs?: number;
620
+ /** Fired per durable spine event (lifecycle transitions + notes). */
621
+ onEvent: (event: MatrxRuntimeOperationEvent, seq: number | null) => void;
622
+ /** A failed attempt (never silently swallowed when provided). */
623
+ onAttemptError?: (error: unknown) => void;
624
+ /** A frame whose payload failed to parse (the ledger heals gaps on reconnect). */
625
+ onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;
626
+ }
627
+ interface FollowRuntimeOperationToEndResult {
628
+ /** True when the server sent the terminal `end` frame. */
629
+ ended: boolean;
630
+ /** The root status carried on the `end` frame (when `ended`). */
631
+ status: MatrxRuntimeExecutionStatus | null;
632
+ }
633
+ /**
634
+ * Follow an operation's lifecycle stream TO ITS END — the full production
635
+ * reconnect policy over `followRuntimeOperationEvents`: replay-then-follow
636
+ * with bounded reconnects, a stall watchdog, and durable `Last-Event-ID`
637
+ * cursor advancement across attempts.
638
+ *
639
+ * Resolves `{ended: true, status}` on the server's `end` frame (the operation
640
+ * settled); `{ended: false}` when the caller aborted or every reconnect
641
+ * attempt failed. A WAITING_INPUT park keeps the stream open by design — a
642
+ * resume re-attaches to the same execution and its events continue arriving
643
+ * on the same cursor. Any parsed frame — comment heartbeats included —
644
+ * proves the wire is alive and resets both the stall timer and the retry
645
+ * budget.
646
+ */
647
+ declare function followRuntimeOperationToEnd(transport: MatrxTransport, executionId: string, options: FollowRuntimeOperationToEndOptions): Promise<FollowRuntimeOperationToEndResult>;
648
+ /**
649
+ * Rejoin the ORIGINAL NDJSON response while its detached task is still alive:
650
+ * `POST /runtime/operations/{request_id}/rejoin`. Replays the response from
651
+ * frame one, then continues live — every frame is sequence-stamped
652
+ * (`stream_seq`), so a same-page reconnect can drop frames it already
653
+ * rendered. Throws `MatrxApiError` with status 409 when live delivery is
654
+ * unavailable — fall back to `followRuntimeOperationEvents` + a final record
655
+ * re-query. The `requestId` must be the server's `X-Request-ID`.
656
+ */
657
+ declare function rejoinRuntimeOperation(transport: MatrxTransport, requestId: string, options?: MatrxStreamCallOptions): Promise<MatrxRunHandle>;
658
+
659
+ export { type MatrxStreamCallOptions as A, type MatrxTransport as B, type MatrxTransportRequest as C, type MatrxTurnFields as D, cancelAgentRun as E, type FollowRuntimeOperationOptions as F, continueAgentConversation as G, continueEphemeralConversationStart as H, continueStoredConversationStart as I, extractMatrxErrorCode as J, extractMatrxErrorMessage as K, followRuntimeOperationEvents as L, type MatrxAgentStartRequest as M, followRuntimeOperationToEnd as N, getRuntimeOperationStatus as O, getRuntimeOperationsByLink as P, listRuntimeOperationEvents as Q, type RunAgentToCompletionOptions as R, mintMatrxConversationId as S, TERMINAL_MATRX_RUNTIME_STATUSES as T, newEphemeralConversationStart as U, newStoredConversationStart as V, rejoinRuntimeOperation as W, resumeAgentConversation as X, runAgentToCompletion as Y, startAgentRun as Z, startMandateRun as _, type FollowRuntimeOperationToEndOptions as a, type FollowRuntimeOperationToEndResult as b, MatrxApiError as c, type MatrxCancelResponse as d, type MatrxChatMessage as e, type MatrxCompletedRun as f, type MatrxContextAnchor as g, type MatrxConversationContinueRequest as h, type MatrxConversationResumeRequest as i, type MatrxConversationStart as j, type MatrxEphemeralConversation as k, type MatrxJsonObject as l, type MatrxJsonValue as m, type MatrxMandateStartRequest as n, type MatrxOperationEventsPage as o, type MatrxOperationFollowEvent as p, type MatrxOperationStatusResponse as q, type MatrxOperationsByLinkResponse as r, type MatrxRequestScope as s, MatrxRunError as t, type MatrxRunHandle as u, type MatrxRuntimeExecutionStatus as v, type MatrxRuntimeOperationEvent as w, type MatrxRuntimeOperationView as x, type MatrxStoredConversationContinue as y, type MatrxStoredConversationCreate as z };