a13n-stream-protocol 0.0.3__py3-none-any.whl

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.
@@ -0,0 +1,18 @@
1
+ """Shared stream-protocol boundary for Agent Foundation surfaces."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from a13n_stream_protocol.observer import (
6
+ AguiEventProcessor,
7
+ AguiObservationError,
8
+ HarnessAguiObserver,
9
+ )
10
+
11
+ __version__ = version("a13n-stream-protocol")
12
+
13
+ __all__ = [
14
+ "AguiEventProcessor",
15
+ "AguiObservationError",
16
+ "HarnessAguiObserver",
17
+ "__version__",
18
+ ]
@@ -0,0 +1,612 @@
1
+ """Stateful observation of public Harness streams as AG-UI events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import AsyncIterable, Callable, Sequence
7
+ from copy import deepcopy
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Literal, cast
10
+
11
+ from a13n_harness import (
12
+ HarnessEvent,
13
+ HarnessExtensionEvent,
14
+ HarnessRunResultEvent,
15
+ HarnessStreamEvent,
16
+ )
17
+ from ag_ui.core import Event
18
+ from ag_ui.core.events import (
19
+ BaseEvent,
20
+ CustomEvent,
21
+ ReasoningEncryptedValueEvent,
22
+ ReasoningMessageContentEvent,
23
+ ReasoningMessageEndEvent,
24
+ ReasoningMessageStartEvent,
25
+ RunErrorEvent,
26
+ RunFinishedEvent,
27
+ RunFinishedSuccessOutcome,
28
+ TextMessageContentEvent,
29
+ TextMessageEndEvent,
30
+ TextMessageStartEvent,
31
+ TokenUsage,
32
+ ToolCallArgsEvent,
33
+ ToolCallEndEvent,
34
+ ToolCallResultEvent,
35
+ ToolCallStartEvent,
36
+ )
37
+ from pydantic import JsonValue, TypeAdapter
38
+ from pydantic_ai.messages import (
39
+ AgentStreamEvent,
40
+ FunctionToolResultEvent,
41
+ OutputToolResultEvent,
42
+ PartDeltaEvent,
43
+ PartEndEvent,
44
+ PartStartEvent,
45
+ TextPart,
46
+ TextPartDelta,
47
+ ThinkingPart,
48
+ ThinkingPartDelta,
49
+ ToolCallPart,
50
+ ToolCallPartDelta,
51
+ ToolReturnPart,
52
+ )
53
+ from pydantic_ai.tools import DeferredToolRequests
54
+
55
+ _AGENT_EVENT_ADAPTER = TypeAdapter(AgentStreamEvent)
56
+ _AGUI_EVENT_ADAPTER = TypeAdapter(Event)
57
+ _ANY_ADAPTER = TypeAdapter(Any)
58
+ _JSON_VALUE_ADAPTER = TypeAdapter(JsonValue)
59
+ _DEFERRED_REQUESTS_ADAPTER = TypeAdapter(DeferredToolRequests)
60
+ _SOURCE_CORRELATION_FIELDS = ("thread_id", "run_id", "sequence", "occurred_at")
61
+ _MUTABLE_FIELDS_BY_EVENT_TYPE: dict[object, frozenset[str]] = {
62
+ TextMessageContentEvent.model_fields["type"].default: frozenset({"delta"}),
63
+ ReasoningMessageContentEvent.model_fields["type"].default: frozenset({"delta"}),
64
+ ReasoningEncryptedValueEvent.model_fields["type"].default: frozenset({"encrypted_value"}),
65
+ ToolCallArgsEvent.model_fields["type"].default: frozenset({"delta"}),
66
+ ToolCallResultEvent.model_fields["type"].default: frozenset({"content"}),
67
+ RunFinishedEvent.model_fields["type"].default: frozenset({"result"}),
68
+ RunErrorEvent.model_fields["type"].default: frozenset({"message"}),
69
+ CustomEvent.model_fields["type"].default: frozenset(),
70
+ }
71
+
72
+ type AguiEventProcessor = Callable[[HarnessStreamEvent[Any], Event], Event | None]
73
+
74
+
75
+ class AguiObservationError(ValueError):
76
+ """A public Harness item could not be observed without changing its meaning."""
77
+
78
+
79
+ @dataclass(slots=True)
80
+ class _PartCursor:
81
+ kind: Literal["text", "reasoning", "tool_call"]
82
+ part_id: str
83
+ tool_name: str | None = None
84
+ emitted_content: bool = False
85
+ emitted_signature: bool = False
86
+
87
+
88
+ @dataclass(slots=True)
89
+ class _ObserverState:
90
+ request_index: int = 0
91
+ parts: dict[int, _PartCursor] = field(default_factory=dict)
92
+
93
+
94
+ class HarnessAguiObserver:
95
+ """Convert and accumulate one public Harness run as typed AG-UI events."""
96
+
97
+ def __init__(self, *, processor: AguiEventProcessor | None = None) -> None:
98
+ self._processor = processor
99
+ self._thread_id: str | None = None
100
+ self._run_id: str | None = None
101
+ self._state = _ObserverState()
102
+ self._events: list[Event] = []
103
+ self._resuming = False
104
+ self._resume_completed = False
105
+
106
+ @property
107
+ def thread_id(self) -> str | None:
108
+ """Return the bound Harness Thread identity, if observation has begun."""
109
+ return self._thread_id
110
+
111
+ @property
112
+ def run_id(self) -> str | None:
113
+ """Return the bound Harness Run identity, if observation has begun."""
114
+ return self._run_id
115
+
116
+ async def resume(self, history: AsyncIterable[HarnessStreamEvent[Any]]) -> None:
117
+ """Atomically rebuild this fresh observer from finite source history.
118
+
119
+ Historical events are accumulated but not returned. Observation and
120
+ another resumption are rejected until the history iterable finishes.
121
+ """
122
+ if not isinstance(history, AsyncIterable):
123
+ raise TypeError("history must be an async iterable of Harness stream events")
124
+ if self._resuming:
125
+ raise AguiObservationError("Observer resumption is already in progress")
126
+ if self._resume_completed or self._thread_id is not None or self._run_id is not None:
127
+ raise AguiObservationError("Observer resumption requires a fresh observer")
128
+
129
+ staged = HarnessAguiObserver(processor=self._processor)
130
+ self._resuming = True
131
+ try:
132
+ async for item in history:
133
+ staged.observe(item)
134
+ self._thread_id = staged._thread_id
135
+ self._run_id = staged._run_id
136
+ self._state = staged._state
137
+ self._events = staged._events
138
+ self._resume_completed = True
139
+ finally:
140
+ self._resuming = False
141
+
142
+ def observe(self, item: HarnessStreamEvent[Any]) -> tuple[Event, ...]:
143
+ """Convert and atomically accumulate one source item."""
144
+ if self._resuming:
145
+ raise AguiObservationError("Cannot observe while observer resumption is in progress")
146
+ if not isinstance(item, HarnessEvent | HarnessRunResultEvent):
147
+ raise TypeError("item must be a HarnessEvent or HarnessRunResultEvent")
148
+ self._validate_correlation(item)
149
+
150
+ staged_state = deepcopy(self._state)
151
+ converted = self._convert(item, staged_state)
152
+ if not converted:
153
+ raise AguiObservationError("A public Harness item produced no AG-UI observation")
154
+
155
+ processed: list[Event] = []
156
+ for event in converted:
157
+ candidate = event if self._processor is None else self._processor(item, event.model_copy(deep=True))
158
+ if candidate is None:
159
+ continue
160
+ validated = self._validate_processor_result(event, candidate)
161
+ processed.append(validated)
162
+
163
+ self._thread_id = item.thread_id
164
+ self._run_id = item.run_id
165
+ self._state = staged_state
166
+ stored = _copy_events(processed)
167
+ self._events.extend(stored)
168
+ return _copy_events(stored)
169
+
170
+ def snapshot(self) -> tuple[Event, ...]:
171
+ """Return a detached immutable view of all accumulated events."""
172
+ return _copy_events(self._events)
173
+
174
+ def _validate_correlation(self, item: HarnessStreamEvent[Any]) -> None:
175
+ if self._thread_id is not None and item.thread_id != self._thread_id:
176
+ raise AguiObservationError("Harness Thread correlation changed within one observer")
177
+ if self._run_id is not None and item.run_id != self._run_id:
178
+ raise AguiObservationError("Harness Run correlation changed within one observer")
179
+
180
+ def _convert(self, item: HarnessStreamEvent[Any], state: _ObserverState) -> list[Event]:
181
+ if isinstance(item, HarnessRunResultEvent):
182
+ return [self._convert_terminal(item)]
183
+
184
+ source = item.event
185
+ if isinstance(source, HarnessExtensionEvent):
186
+ _observe_request_lifecycle(source, state)
187
+ return [_custom_harness_event(item, source)]
188
+ if isinstance(source, PartStartEvent):
189
+ events = _convert_part_start(item, source, state)
190
+ elif isinstance(source, PartDeltaEvent):
191
+ events = _convert_part_delta(item, source, state)
192
+ elif isinstance(source, PartEndEvent):
193
+ events = _convert_part_end(item, source, state)
194
+ elif isinstance(source, FunctionToolResultEvent | OutputToolResultEvent):
195
+ events = _convert_tool_result(item, source)
196
+ else:
197
+ events = []
198
+ return events or [_custom_pydantic_event(item, source)]
199
+
200
+ def _convert_terminal(self, item: HarnessRunResultEvent[Any]) -> Event:
201
+ result = item.result
202
+ timestamp = _timestamp_ms(item)
203
+ usage = _agui_usage(result.usage)
204
+ raw_event: dict[str, Any] = {
205
+ "thread_id": item.thread_id,
206
+ "run_id": item.run_id,
207
+ "sequence": item.sequence,
208
+ "occurred_at": item.occurred_at.isoformat(),
209
+ "status": result.status,
210
+ }
211
+ if result.status == "completed":
212
+ output, omitted = _json_safe_output(result.output)
213
+ if omitted:
214
+ raw_event["result_omitted"] = True
215
+ return RunFinishedEvent(
216
+ timestamp=timestamp,
217
+ raw_event=raw_event,
218
+ thread_id=item.thread_id,
219
+ run_id=item.run_id,
220
+ result=output,
221
+ outcome=RunFinishedSuccessOutcome(),
222
+ usage=usage,
223
+ )
224
+ if result.status == "suspended":
225
+ deferred = result.deferred
226
+ assert deferred is not None
227
+ return CustomEvent(
228
+ timestamp=timestamp,
229
+ name="a13n.harness.run_result",
230
+ value=_source_value(
231
+ item,
232
+ {
233
+ "status": "suspended",
234
+ "suspend_reason": result.suspend_reason,
235
+ "deferred": _DEFERRED_REQUESTS_ADAPTER.dump_python(
236
+ deferred,
237
+ mode="json",
238
+ by_alias=True,
239
+ ),
240
+ },
241
+ ),
242
+ )
243
+ if result.status == "failed":
244
+ failure = result.failure
245
+ assert failure is not None
246
+ raw_event["failure"] = failure.model_dump(mode="json", by_alias=True)
247
+ return RunErrorEvent(
248
+ timestamp=timestamp,
249
+ raw_event=raw_event,
250
+ message=failure.message,
251
+ code=failure.code,
252
+ usage=usage,
253
+ )
254
+ return RunErrorEvent(
255
+ timestamp=timestamp,
256
+ raw_event=raw_event,
257
+ message="The run was cancelled.",
258
+ code="run_cancelled",
259
+ usage=usage,
260
+ )
261
+
262
+ def _validate_processor_result(self, original: Event, candidate: object) -> Event:
263
+ if not isinstance(candidate, BaseEvent):
264
+ raise AguiObservationError("The event processor returned a non-AG-UI value")
265
+ try:
266
+ replacement = _AGUI_EVENT_ADAPTER.validate_python(candidate, strict=True)
267
+ except ValueError as exc:
268
+ raise AguiObservationError("The event processor returned an invalid AG-UI event") from exc
269
+ if replacement.type != original.type:
270
+ raise AguiObservationError("The event processor changed the AG-UI event type")
271
+
272
+ original_data = original.model_dump(mode="python")
273
+ replacement_data = replacement.model_dump(mode="python")
274
+ mutable_fields = _MUTABLE_FIELDS_BY_EVENT_TYPE.get(original.type, frozenset())
275
+ for field_name, original_value in original_data.items():
276
+ if field_name not in mutable_fields and replacement_data.get(field_name) != original_value:
277
+ raise AguiObservationError(f"The event processor changed structural field {field_name}")
278
+ _validate_nested_source_correlation(original, replacement)
279
+ return replacement.model_copy(deep=True)
280
+
281
+
282
+ def _convert_part_start(item: HarnessEvent, event: PartStartEvent, state: _ObserverState) -> list[Event]:
283
+ timestamp = _timestamp_ms(item)
284
+ part = event.part
285
+ if isinstance(part, TextPart):
286
+ message_id = part.id or _part_id(item.run_id, state.request_index, event.index, "text")
287
+ cursor = _PartCursor(kind="text", part_id=message_id, emitted_content=bool(part.content))
288
+ state.parts[event.index] = cursor
289
+ events: list[Event] = [TextMessageStartEvent(timestamp=timestamp, message_id=message_id, role="assistant")]
290
+ if part.content:
291
+ events.append(TextMessageContentEvent(timestamp=timestamp, message_id=message_id, delta=part.content))
292
+ return events
293
+ if isinstance(part, ThinkingPart):
294
+ message_id = part.id or _part_id(item.run_id, state.request_index, event.index, "reasoning")
295
+ cursor = _PartCursor(
296
+ kind="reasoning",
297
+ part_id=message_id,
298
+ emitted_content=bool(part.content),
299
+ emitted_signature=bool(part.signature),
300
+ )
301
+ state.parts[event.index] = cursor
302
+ events = [ReasoningMessageStartEvent(timestamp=timestamp, message_id=message_id, role="reasoning")]
303
+ if part.content:
304
+ events.append(ReasoningMessageContentEvent(timestamp=timestamp, message_id=message_id, delta=part.content))
305
+ if part.signature:
306
+ events.append(
307
+ ReasoningEncryptedValueEvent(
308
+ timestamp=timestamp,
309
+ subtype="message",
310
+ entity_id=message_id,
311
+ encrypted_value=part.signature,
312
+ )
313
+ )
314
+ return events
315
+ if isinstance(part, ToolCallPart):
316
+ state.parts[event.index] = _PartCursor(
317
+ kind="tool_call",
318
+ part_id=part.tool_call_id,
319
+ tool_name=part.tool_name,
320
+ )
321
+ return []
322
+ return []
323
+
324
+
325
+ def _convert_part_delta(item: HarnessEvent, event: PartDeltaEvent, state: _ObserverState) -> list[Event]:
326
+ timestamp = _timestamp_ms(item)
327
+ delta = event.delta
328
+ if isinstance(delta, TextPartDelta):
329
+ cursor, opened = _ensure_part_cursor(item, state, event.index, "text")
330
+ events: list[Event] = []
331
+ if opened:
332
+ events.append(TextMessageStartEvent(timestamp=timestamp, message_id=cursor.part_id, role="assistant"))
333
+ events.append(
334
+ TextMessageContentEvent(timestamp=timestamp, message_id=cursor.part_id, delta=delta.content_delta)
335
+ )
336
+ cursor.emitted_content = True
337
+ return events
338
+ if isinstance(delta, ThinkingPartDelta):
339
+ cursor, opened = _ensure_part_cursor(item, state, event.index, "reasoning")
340
+ events = []
341
+ if opened:
342
+ events.append(ReasoningMessageStartEvent(timestamp=timestamp, message_id=cursor.part_id, role="reasoning"))
343
+ if delta.content_delta:
344
+ events.append(
345
+ ReasoningMessageContentEvent(
346
+ timestamp=timestamp,
347
+ message_id=cursor.part_id,
348
+ delta=delta.content_delta,
349
+ )
350
+ )
351
+ cursor.emitted_content = True
352
+ if delta.signature_delta:
353
+ events.append(
354
+ ReasoningEncryptedValueEvent(
355
+ timestamp=timestamp,
356
+ subtype="message",
357
+ entity_id=cursor.part_id,
358
+ encrypted_value=delta.signature_delta,
359
+ )
360
+ )
361
+ cursor.emitted_signature = True
362
+ return events
363
+ if isinstance(delta, ToolCallPartDelta):
364
+ cursor, _ = _ensure_tool_cursor(item, state, event.index, delta)
365
+ if delta.tool_name_delta:
366
+ cursor.tool_name = f"{cursor.tool_name or ''}{delta.tool_name_delta}"
367
+ return []
368
+ return []
369
+
370
+
371
+ def _convert_part_end(item: HarnessEvent, event: PartEndEvent, state: _ObserverState) -> list[Event]:
372
+ timestamp = _timestamp_ms(item)
373
+ part = event.part
374
+ existing = state.parts.pop(event.index, None)
375
+ if isinstance(part, TextPart):
376
+ message_id = part.id or (existing.part_id if existing is not None else None)
377
+ message_id = message_id or _part_id(item.run_id, state.request_index, event.index, "text")
378
+ cursor, opened = _ending_cursor(existing, "text", message_id)
379
+ events: list[Event] = []
380
+ if opened:
381
+ events.append(TextMessageStartEvent(timestamp=timestamp, message_id=message_id, role="assistant"))
382
+ if part.content and not cursor.emitted_content:
383
+ events.append(TextMessageContentEvent(timestamp=timestamp, message_id=message_id, delta=part.content))
384
+ events.append(TextMessageEndEvent(timestamp=timestamp, message_id=message_id))
385
+ return events
386
+ if isinstance(part, ThinkingPart):
387
+ message_id = part.id or (existing.part_id if existing is not None else None)
388
+ message_id = message_id or _part_id(item.run_id, state.request_index, event.index, "reasoning")
389
+ cursor, opened = _ending_cursor(existing, "reasoning", message_id)
390
+ events = []
391
+ if opened:
392
+ events.append(ReasoningMessageStartEvent(timestamp=timestamp, message_id=message_id, role="reasoning"))
393
+ if part.content and not cursor.emitted_content:
394
+ events.append(ReasoningMessageContentEvent(timestamp=timestamp, message_id=message_id, delta=part.content))
395
+ if part.signature and not cursor.emitted_signature:
396
+ events.append(
397
+ ReasoningEncryptedValueEvent(
398
+ timestamp=timestamp,
399
+ subtype="message",
400
+ entity_id=message_id,
401
+ encrypted_value=part.signature,
402
+ )
403
+ )
404
+ events.append(ReasoningMessageEndEvent(timestamp=timestamp, message_id=message_id))
405
+ return events
406
+ if isinstance(part, ToolCallPart):
407
+ tool_call_id = existing.part_id if existing is not None else part.tool_call_id
408
+ _ending_cursor(existing, "tool_call", tool_call_id)
409
+ events = [
410
+ ToolCallStartEvent(
411
+ timestamp=timestamp,
412
+ tool_call_id=tool_call_id,
413
+ tool_call_name=part.tool_name,
414
+ )
415
+ ]
416
+ if part.args is not None:
417
+ events.append(
418
+ ToolCallArgsEvent(
419
+ timestamp=timestamp,
420
+ tool_call_id=tool_call_id,
421
+ delta=_tool_args_text(part.args),
422
+ )
423
+ )
424
+ events.append(ToolCallEndEvent(timestamp=timestamp, tool_call_id=tool_call_id))
425
+ return events
426
+ return []
427
+
428
+
429
+ def _convert_tool_result(
430
+ item: HarnessEvent,
431
+ event: FunctionToolResultEvent | OutputToolResultEvent,
432
+ ) -> list[Event]:
433
+ part = event.part
434
+ if not isinstance(part, ToolReturnPart) or part.outcome != "success":
435
+ return []
436
+ content: object = part.content
437
+ if isinstance(event, FunctionToolResultEvent) and event.content is not None:
438
+ content = event.content
439
+ return [
440
+ ToolCallResultEvent(
441
+ timestamp=_timestamp_ms(item),
442
+ message_id=f"{part.tool_call_id}:result",
443
+ tool_call_id=part.tool_call_id,
444
+ content=_tool_result_text(content),
445
+ role="tool",
446
+ )
447
+ ]
448
+
449
+
450
+ def _observe_request_lifecycle(event: HarnessExtensionEvent, state: _ObserverState) -> None:
451
+ payload = event.payload
452
+ if event.kind != "lifecycle" or not isinstance(payload, dict):
453
+ return
454
+ if payload.get("type") != "model_request_started":
455
+ return
456
+ request_index = payload.get("request_index")
457
+ if isinstance(request_index, int) and request_index >= 0:
458
+ state.request_index = request_index
459
+ state.parts.clear()
460
+
461
+
462
+ def _custom_harness_event(item: HarnessEvent, event: HarnessExtensionEvent) -> CustomEvent:
463
+ return CustomEvent(
464
+ timestamp=_timestamp_ms(item),
465
+ name=f"a13n.harness.{event.kind}",
466
+ value=_source_value(item, event.model_dump(mode="json", by_alias=True)),
467
+ )
468
+
469
+
470
+ def _custom_pydantic_event(item: HarnessEvent, event: AgentStreamEvent) -> CustomEvent:
471
+ source = _AGENT_EVENT_ADAPTER.dump_python(event, mode="json", by_alias=True)
472
+ return CustomEvent(
473
+ timestamp=_timestamp_ms(item),
474
+ name=f"a13n.pydantic_ai.{event.event_kind}",
475
+ value=_source_value(item, source),
476
+ )
477
+
478
+
479
+ def _source_value(item: HarnessStreamEvent[Any], event: object) -> dict[str, object]:
480
+ return {
481
+ "thread_id": item.thread_id,
482
+ "run_id": item.run_id,
483
+ "sequence": item.sequence,
484
+ "occurred_at": item.occurred_at.isoformat(),
485
+ "event": event,
486
+ }
487
+
488
+
489
+ def _ensure_part_cursor(
490
+ item: HarnessEvent,
491
+ state: _ObserverState,
492
+ index: int,
493
+ kind: Literal["text", "reasoning"],
494
+ ) -> tuple[_PartCursor, bool]:
495
+ existing = state.parts.get(index)
496
+ if existing is not None:
497
+ if existing.kind != kind:
498
+ raise AguiObservationError("Pydantic part kind changed before its end event")
499
+ return existing, False
500
+ cursor = _PartCursor(
501
+ kind=kind,
502
+ part_id=_part_id(item.run_id, state.request_index, index, kind),
503
+ )
504
+ state.parts[index] = cursor
505
+ return cursor, True
506
+
507
+
508
+ def _ensure_tool_cursor(
509
+ item: HarnessEvent,
510
+ state: _ObserverState,
511
+ index: int,
512
+ delta: ToolCallPartDelta,
513
+ ) -> tuple[_PartCursor, bool]:
514
+ existing = state.parts.get(index)
515
+ if existing is not None:
516
+ if existing.kind != "tool_call":
517
+ raise AguiObservationError("Pydantic part kind changed before its end event")
518
+ if delta.tool_call_id and delta.tool_call_id != existing.part_id:
519
+ raise AguiObservationError("Pydantic tool-call identity changed before its end event")
520
+ return existing, False
521
+ cursor = _PartCursor(
522
+ kind="tool_call",
523
+ part_id=delta.tool_call_id or _part_id(item.run_id, state.request_index, index, "tool"),
524
+ tool_name=None,
525
+ )
526
+ state.parts[index] = cursor
527
+ return cursor, True
528
+
529
+
530
+ def _ending_cursor(
531
+ existing: _PartCursor | None,
532
+ expected_kind: Literal["text", "reasoning", "tool_call"],
533
+ part_id: str,
534
+ ) -> tuple[_PartCursor, bool]:
535
+ if existing is None:
536
+ return _PartCursor(kind=expected_kind, part_id=part_id), True
537
+ if existing.kind != expected_kind:
538
+ raise AguiObservationError("Pydantic part kind changed before its end event")
539
+ if existing.part_id != part_id:
540
+ raise AguiObservationError("Pydantic part identity changed before its end event")
541
+ return existing, False
542
+
543
+
544
+ def _part_id(run_id: str, request_index: int, part_index: int, kind: str) -> str:
545
+ return f"{run_id}:request-{request_index}:part-{part_index}:{kind}"
546
+
547
+
548
+ def _tool_args_text(value: object) -> str:
549
+ if value is None:
550
+ return ""
551
+ if isinstance(value, str):
552
+ return value
553
+ serialized = _ANY_ADAPTER.dump_python(value, mode="json")
554
+ return json.dumps(serialized, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
555
+
556
+
557
+ def _json_safe_output(value: object) -> tuple[JsonValue, bool]:
558
+ try:
559
+ serialized = _ANY_ADAPTER.dump_python(value, mode="json", warnings="error")
560
+ return _JSON_VALUE_ADAPTER.validate_python(serialized, strict=True), False
561
+ except (TypeError, ValueError):
562
+ return None, True
563
+
564
+
565
+ def _tool_result_text(value: object) -> str:
566
+ if isinstance(value, str):
567
+ return value
568
+ serialized = _ANY_ADAPTER.dump_python(value, mode="json")
569
+ return json.dumps(serialized, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
570
+
571
+
572
+ def _agui_usage(usage: Any) -> list[TokenUsage] | None:
573
+ total_tokens = usage.input_tokens + usage.output_tokens
574
+ if total_tokens == 0 and usage.cache_read_tokens == 0:
575
+ return None
576
+ reasoning_tokens = usage.details.get("reasoning_tokens")
577
+ return [
578
+ TokenUsage(
579
+ input_tokens=usage.input_tokens,
580
+ output_tokens=usage.output_tokens,
581
+ total_tokens=total_tokens,
582
+ reasoning_tokens=reasoning_tokens if isinstance(reasoning_tokens, int) else None,
583
+ cached_input_tokens=usage.cache_read_tokens,
584
+ )
585
+ ]
586
+
587
+
588
+ def _timestamp_ms(item: HarnessStreamEvent[Any]) -> int:
589
+ return int(item.occurred_at.timestamp() * 1000)
590
+
591
+
592
+ def _validate_nested_source_correlation(original: Event, replacement: Event) -> None:
593
+ original_payload: object | None = None
594
+ replacement_payload: object | None = None
595
+ if isinstance(original, CustomEvent) and isinstance(replacement, CustomEvent):
596
+ original_payload = original.value
597
+ replacement_payload = replacement.value
598
+ elif original.raw_event is not None:
599
+ original_payload = original.raw_event
600
+ replacement_payload = replacement.raw_event
601
+ if not isinstance(original_payload, dict) or not isinstance(replacement_payload, dict):
602
+ return
603
+ for field_name in _SOURCE_CORRELATION_FIELDS:
604
+ if field_name in original_payload and replacement_payload.get(field_name) != original_payload[field_name]:
605
+ raise AguiObservationError(f"The event processor changed {field_name} source correlation")
606
+
607
+
608
+ def _copy_events(events: Sequence[Event]) -> tuple[Event, ...]:
609
+ return tuple(cast(Event, event.model_copy(deep=True)) for event in events)
610
+
611
+
612
+ __all__ = ["AguiEventProcessor", "AguiObservationError", "HarnessAguiObserver"]
File without changes
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.5
2
+ Name: a13n-stream-protocol
3
+ Version: 0.0.3
4
+ Summary: Shared AG-UI projection protocol for Agent Foundation agents
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.13
8
+ Requires-Dist: a13n-harness==0.0.3
9
+ Requires-Dist: ag-ui-protocol<0.2,>=0.1.18
10
+ Requires-Dist: pydantic-ai-slim<2.32,>=2.31.1
11
+ Requires-Dist: pydantic<3,>=2.12
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Agent Stream Protocol
15
+
16
+ `a13n-stream-protocol` observes public `a13n-harness` streams as typed AG-UI events. It maps text, reasoning, tool, and terminal observations to standard AG-UI events, exposes every other public observation through a namespaced `CUSTOM` fallback, applies an optional Host processor, and accumulates the resulting events for process-local use.
17
+
18
+ The repository directory is `packages/agent-stream-protocol`, the Python distribution is `a13n-stream-protocol`, and the import package is `a13n_stream_protocol`.
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from a13n_stream_protocol import HarnessAguiObserver
24
+
25
+ observers: dict[tuple[str, str], HarnessAguiObserver] = {}
26
+
27
+ async with executable.stream(input, bindings=bindings) as stream:
28
+ async for item in stream:
29
+ correlation = (item.thread_id, item.run_id)
30
+ observer = observers.get(correlation)
31
+ if observer is None:
32
+ observer = HarnessAguiObserver()
33
+ observers[correlation] = observer
34
+
35
+ new_events = observer.observe(item)
36
+ await host.persist_and_publish(new_events)
37
+ ```
38
+
39
+ One observer binds to the Thread and Run correlation on its first successful source item. Use a separate observer for each root or child Run, including child events forwarded through a parent stream. An integration whose source contains exactly one Run can use one observer directly.
40
+
41
+ A Host that retains the exact public Harness source history can atomically rebuild a fresh observer before continuing with live items:
42
+
43
+ ```python
44
+ observer = HarnessAguiObserver()
45
+ await observer.resume(host.source_history(run_id=run_id, through=cursor))
46
+
47
+ async for item in host.live_source(run_id=run_id, after=cursor):
48
+ new_events = observer.observe(item)
49
+ await host.persist_and_publish(new_events)
50
+ ```
51
+
52
+ The history is a finite async iterable for one Run. `resume()` accumulates its post-processor AG-UI events without returning them for duplicate publication, leaves the observer fresh if reconstruction fails, and knows nothing about storage, cursors, gaps, or replay-to-live cutover. Those remain Host responsibilities.
53
+
54
+ A Host can filter or adjust converted values before accumulation:
55
+
56
+ ```python
57
+ from ag_ui.core import Event
58
+ from ag_ui.core.events import CustomEvent
59
+ from a13n_harness import HarnessStreamEvent
60
+ from a13n_stream_protocol import HarnessAguiObserver
61
+
62
+
63
+ def process_event(
64
+ source: HarnessStreamEvent[object],
65
+ event: Event,
66
+ ) -> Event | None:
67
+ del source
68
+ if isinstance(event, CustomEvent) and event.name == "a13n.harness.diagnostic":
69
+ return None
70
+ return event
71
+
72
+
73
+ observer = HarnessAguiObserver(processor=process_event)
74
+ ```
75
+
76
+ A replacement must retain the same AG-UI event type and source-derived correlation. The processor is synchronous, replay-stable, and does not retain mutable processing state or persist, publish, or acknowledge events. The Host acts on the complete batch returned by live `observe()` calls.
77
+
78
+ ## Ownership
79
+
80
+ The package owns only:
81
+
82
+ - standard Harness-to-AG-UI conversion;
83
+ - generic `CUSTOM` fallback for unmapped public events;
84
+ - multipart text, reasoning, and tool-call observation state;
85
+ - optional replay-stable Host processing;
86
+ - atomic process-local reconstruction from supplied source history;
87
+ - detached incremental results and accumulated snapshots.
88
+
89
+ The Host owns source-history retention and selection, cursors, gaps, replay-to-live cutover, persistence, event identities, fan-out, backpressure, cancellation, transport, and rendering policy. The Harness owns source lifecycle facts and continuation state.
90
+
91
+ ## Dependencies
92
+
93
+ The source manifest declares an unversioned dependency on `a13n-harness`, so uv resolves Harness from the workspace during repository development. Conversion uses the upstream `ag-ui-protocol` models, Pydantic serialization, and the lightweight `pydantic-ai-slim` event runtime. The package does not depend on Agent UI, a Host persistence model, or a transport framework.
94
+
95
+ Release automation replaces the workspace-oriented Harness dependency in publishable metadata with an exact same-version requirement. Both the sdist and wheel therefore install only the Harness version released with that Stream Protocol artifact.
96
+
97
+ ## Versioning
98
+
99
+ Agent Stream Protocol, `a13n-harness`, and `a13n-environment-provider` form the Harness release group. A `release/harness-v<version>` tag publishes all three distributions at exactly the same version, where `<version>` is stable `X.Y.Z` or RC `X.Y.Z-rc.N`. Python package metadata represents the RC as `X.Y.ZrcN`. Published Harness metadata pins the exact Provider version, and this package pins the exact Harness version. Agent UI is versioned and released independently.
100
+
101
+ The accepted architecture and compatibility contract are defined in the [Agent Stream Protocol specification](../../spec/agent-stream-protocol/README.md).
@@ -0,0 +1,7 @@
1
+ a13n_stream_protocol/__init__.py,sha256=FD0VmujLFWRXj33APtcj8DZP8AsJsi3C4rfzuf7-Lvk,393
2
+ a13n_stream_protocol/observer.py,sha256=Wo4tRa1S7FtSjWohACEG9tyME19oE3COGPlhZAcfmnk,24521
3
+ a13n_stream_protocol/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ a13n_stream_protocol-0.0.3.dist-info/METADATA,sha256=sjwafQTwnV4oCRtTAXk5cezGUPfSODk-ytuzaiYaPFk,5245
5
+ a13n_stream_protocol-0.0.3.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
6
+ a13n_stream_protocol-0.0.3.dist-info/licenses/LICENSE,sha256=XaXNtDzXDcdKN1pP3_gZLlvPOIt0tNTg8toqB4B_faE,11341
7
+ a13n_stream_protocol-0.0.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Converge AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.