dangoldbj commited on
Commit
d38477a
·
verified ·
1 Parent(s): 9d3a3e6

release v1

Browse files
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .ruff_cache/
5
+ .pytest_cache/
6
+ uv.lock
7
+ .envrc
8
+ # raw per-run captures + eval outputs are intermediates; the published artifact is data/*.parquet
9
+ results/
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.13
DATASHEET.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A2A-MetaTrace datasheet
2
+
3
+ A labeled, metadata-only corpus of agent-to-agent (A2A) workflow traces, captured
4
+ from official A2A sample agents composed into multi-agent workflows. Released as a
5
+ standalone artifact alongside the paper; this datasheet follows the Gebru et al.
6
+ "Datasheets for Datasets" structure.
7
+
8
+ ## Motivation
9
+ The corpus evaluates metadata leakage on workloads that are not the authors' own
10
+ generator: the protocol path (Agent Cards,
11
+ discovery, `message/send`, SSE) and the agents are *officially authored*; only the
12
+ workflow composition and the class labels are ours.
13
+
14
+ ## Composition
15
+ - **Instances.** One trace = one workflow execution. The corpus is **270
16
+ traces**: 30 runs each of **9 workflow classes** over **6 capabilities**, each class
17
+ realized by 3 compositional **variants** (see `corpus/classes.py`), runs split across a
18
+ class's variants.
19
+ - **Per message (obs(m)).** `(src, dst, t, length, direction)` plus ground truth:
20
+ `stage_idx`, `step_type`, `capability`, `task_class`, `n_stages`, and a `variant` tag
21
+ for the leave-variant-out split. **Payloads are discarded**: the corpus is metadata
22
+ only (the capture records lengths, not bodies), so it is exactly a passive TLS
23
+ observer's view and carries no message content.
24
+ - **Labels.** `task_class` is the workflow class (the ground-truth the adversary
25
+ recovers); `variant` is the specific composition (the generalization group). Labels
26
+ and composition are ours; the protocol path is the real `a2a-sdk`.
27
+
28
+ ## Collection process
29
+ Each capability is an official `a2a-samples` agent launched as a standalone A2A server in
30
+ its own env (`corpus/sample_agents.py`, `corpus/launcher.py`); an orchestrator composes
31
+ them per (class, variant) and a real stage runner (`corpus/runner_samples.py`) records
32
+ obs(m) via a real discovery round-trip + `message/send` + SSE streaming, the same A2A
33
+ wire the measured binding observes. The runner overrides each resolved Agent Card's
34
+ interface URL to the real launch port (some samples ship a stale hardcoded card URL).
35
+ Transport: HTTPS-direct (the protection ladder is applied analytically in the
36
+ accompanying analysis).
37
+
38
+ ## Honest disclosures / limitations
39
+ - **Provenance.** The corpus is captured from **official `a2a-samples` agents**,
40
+ each run unmodified as its own server: `travel_planner` (OpenAI), `adk_currency_agent`,
41
+ `content_planner`, `adk_skills_agent` (Gemini via Vertex), `adk_expense_reimbursement`
42
+ (LiteLLM→OpenAI), and `helloworld` (no-LLM echo). The protocol path (Agent Cards,
43
+ discovery, `message/send`, SSE streaming) and the agent logic are official; **only the
44
+ workflow composition and the class labels are ours.**
45
+ - **Model substitutions (disclosed; agent logic unchanged).** Three bindings differ from
46
+ the samples' shipped defaults, with no behavioral edits:
47
+ - `adk_currency_agent`, `adk_skills_agent`: `model=` changed `gemini-3-flash-preview`
48
+ → `gemini-2.5-flash`.
49
+ - `adk_expense_reimbursement`: `LITELLM_MODEL=openai/gpt-4o-mini` (env only).
50
+ - `a2a_telemetry` is **excluded**: the sample hardcodes an ADK `google_search` tool with
51
+ a LiteLLM model, which the current ADK rejects as-shipped. These edits are not committed
52
+ into the `a2a-samples` clone; they are recorded here for reproducibility.
53
+ - **Observation model.** Records are per A2A application event. Because a network observer
54
+ sees TLS-record bursts, not application deltas, the accompanying analysis also reports a
55
+ **wire-faithful** view that aggregates each stage's streamed response into one
56
+ observation; recovery is robust to this (see below).
57
+ - **Uniformity.** The sample agents are more uniform than a production deployment; a
58
+ generalization limit, reported as such (leave-variant-out below).
59
+
60
+ ## Recommended splits
61
+ Random k-fold; **leave-variant-out** (generalization: hold out whole compositions, by
62
+ grouping on `variant` so no composition spans the train/test boundary). Report both.
63
+
64
+ ## Known result: real, artifact-robust, composition-specific, mitigable
65
+ On this corpus (270 traces, 9 classes, chance 0.111, 8 seeds; reproduced by the
66
+ accompanying analysis):
67
+ - **Random k-fold = 0.668 ± 0.02 (6.0× chance)**; **leave-variant-out = 0.18 (~chance)**.
68
+ The label-blind adversary recognizes *specific, previously seen compositions*, not the
69
+ abstract task intent, so a held-out composition of a known class is not recovered.
70
+ - **Not a streaming artifact.** Recovery is unchanged under the wire-faithful aggregation
71
+ (per-delta 0.676 → aggregated 0.668; mean msgs/wf 376 → 11), so it rests on real workflow
72
+ *structure*, not on the chattiest agent's per-delta volume.
73
+ - **Mitigable.** Under a metadata-protecting transport (wire-faithful, adversary vocabulary
74
+ fixed from the undefended deployment): none 6.0× → metadata-min shim 4.2× → cover 0.26×
75
+ → cover+unlinkability **1.00× = exactly chance**.
76
+
77
+ The corpus thus confirms the leakage claim on real official-SDK agent traffic, scopes it
78
+ (recurring/profiled workflows, not zero-shot novel compositions), and shows the defense
79
+ closes it.
80
+
81
+ ## Distribution
82
+ Dataset (Parquet) + this datasheet + the capture/generation harness (`corpus/`). Load
83
+ with `datasets` / `pandas` (see `README.md`).
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution 4.0 International (CC BY 4.0)
2
+
3
+ Copyright (c) 2026 Bijaya Dangol
4
+
5
+ The A2A-MetaTrace corpus in this repository (the data files under `data/`, the
6
+ datasheet, and the accompanying capture/generation harness under `corpus/` and
7
+ `scripts/`) is licensed under the Creative Commons Attribution 4.0 International
8
+ License (CC BY 4.0).
9
+
10
+ You are free to share and adapt the material for any purpose, even commercially,
11
+ provided you give appropriate credit, link to the license, and indicate if changes
12
+ were made.
13
+
14
+ Full legal text: https://creativecommons.org/licenses/by/4.0/legalcode
15
+ Summary: https://creativecommons.org/licenses/by/4.0/
16
+
17
+ Provenance and scope: the corpus is captured from official `a2a-samples` agents.
18
+ Those agents' code and the A2A protocol path remain under their respective upstream
19
+ licenses; this license covers only the workflow compositions, class labels, and the
20
+ recorded metadata (obs(m)) produced in this repository. No message payloads or
21
+ content are included in the dataset.
README.md ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ pretty_name: A2A-MetaTrace
4
+ task_categories:
5
+ - tabular-classification
6
+ tags:
7
+ - traffic-analysis
8
+ - metadata-privacy
9
+ - agent
10
+ - a2a
11
+ - multi-agent
12
+ - workflow-fingerprinting
13
+ size_categories:
14
+ - 100K<n<1M
15
+ configs:
16
+ - config_name: default
17
+ data_files:
18
+ - split: train
19
+ path: data/default/train.parquet
20
+ dataset_info:
21
+ - config_name: default
22
+ features:
23
+ - name: trace_id
24
+ dtype: int64
25
+ - name: task_class
26
+ dtype: string
27
+ - name: variant
28
+ dtype: string
29
+ - name: client_id
30
+ dtype: string
31
+ - name: n_stages
32
+ dtype: int32
33
+ - name: stage_idx
34
+ dtype: int32
35
+ - name: step_type
36
+ dtype: string
37
+ - name: direction
38
+ dtype: string
39
+ - name: src
40
+ dtype: string
41
+ - name: dst
42
+ dtype: string
43
+ - name: t
44
+ dtype: float64
45
+ - name: length
46
+ dtype: int64
47
+ - name: capability
48
+ dtype: string
49
+ - name: label_visible
50
+ dtype: bool
51
+ - name: mode
52
+ dtype: string
53
+ - name: transport
54
+ dtype: string
55
+ splits:
56
+ - name: train
57
+ num_examples: 101516
58
+ ---
59
+
60
+ # A2A-MetaTrace
61
+
62
+ A labeled, **metadata-only** corpus of multi-agent **A2A** (Agent-to-Agent) workflow
63
+ traffic. Each row is one wire message reduced to what a passive network observer sees,
64
+ `obs(m) = (src, dst, t, length, direction)`, with workflow ground-truth labels; message
65
+ bodies are discarded. The corpus exists to study how much of a *pending agent workflow*
66
+ leaks from communication-graph metadata alone, and to evaluate metadata-protecting
67
+ transports against it.
68
+
69
+ **Links:** [GitHub](https://github.com/dangoldbj/a2a-metatrace) | [HuggingFace dataset](https://huggingface.co/datasets/dangoldbj/a2a-metatrace) | [Paper (arXiv)](https://arxiv.org/abs/2606.07150)
70
+
71
+ **Provenance (disclosed).** Workflows run over the real `a2a-sdk` protocol path
72
+ (Agent Cards, discovery, `message/send`, SSE) against real official `a2a-samples` agent
73
+ servers backed by real language-model calls. The workflow *compositions* and *labels*
74
+ are ours (see `DATASHEET.md`). This is the honest provenance claim: the protocol path and
75
+ agent behavior are real; the composition is designed.
76
+
77
+ ## Config
78
+
79
+ | config | agent backend | transport | workflows | classes | variants | rows (messages) |
80
+ |---|---|---|---|---|---|---|
81
+ | `default` | agents | https | 270 | 9 | 27 | 101516 |
82
+
83
+ The corpus is captured from official `a2a-samples` agents composed into multi-agent
84
+ workflows; transport is HTTPS-direct (the metadata-protecting transport is evaluated
85
+ analytically; see `DATASHEET.md`).
86
+
87
+ ## Usage
88
+
89
+ ```python
90
+ from datasets import load_dataset
91
+ import pandas as pd
92
+
93
+ ds = load_dataset("a2a-metatrace", split="train") # message-level rows
94
+ df = ds.to_pandas()
95
+
96
+ # reconstruct workflows and their labels by grouping on trace_id
97
+ by_wf = df.groupby("trace_id")
98
+ labels = by_wf["task_class"].first()
99
+ ```
100
+
101
+ A workflow is the unit an adversary classifies; featurize per `trace_id` (message counts,
102
+ length stats, timing, direction n-grams) and recover `task_class`. Use the `variant`
103
+ column for a **leave-variant-out** split (generalization to unseen compositions).
104
+
105
+ ## Regenerating the corpus
106
+
107
+ The published Parquet is produced by capturing real official `a2a-samples` agents. To
108
+ reproduce it end to end:
109
+
110
+ 1. **Get the agents.** Clone the official samples repo and point the harness at its
111
+ Python agents directory:
112
+ ```bash
113
+ git clone https://github.com/a2aproject/a2a-samples.git
114
+ export A2A_SAMPLES_DIR=$(pwd)/a2a-samples/samples/python/agents
115
+ ```
116
+ 2. **Provide model credentials.** The sample agents call real models:
117
+ - `export OPENAI_API_KEY=...` (the OpenAI- and LiteLLM-backed agents), and
118
+ - for the Google-ADK agents, a Vertex project via Application Default Credentials:
119
+ `export GOOGLE_CLOUD_PROJECT=...` and `gcloud auth application-default login`.
120
+
121
+ Keys may instead be placed in a local `.envrc` (`export KEY=VALUE` lines); see
122
+ `corpus/sample_agents.py` for all configuration variables.
123
+ 3. **Install and run** (Python 3.13):
124
+ ```bash
125
+ uv sync
126
+ uv run python -m corpus.run_corpus --runs-per-class 30 # writes results/corpus/a2a_metatrace.json
127
+ uv run python scripts/export_hf.py # writes data/ + this README
128
+ ```
129
+
130
+ See `DATASHEET.md` for the workflow classes, provenance, and disclosed model substitutions.
131
+
132
+ ## What it is for
133
+
134
+ - **Workflow-fingerprinting / traffic analysis** on agent interoperation traffic.
135
+ - **Evaluating metadata-protecting transports** for agent interoperation.
136
+ - A reproducible, provenance-disclosed alternative to purely synthetic agent-traffic models.
137
+
138
+ See `DATASHEET.md` for construction, intended use, and limitations. Regenerate this card
139
+ and the Parquet files with `uv run python scripts/export_hf.py`.
140
+
141
+ ## Citation
142
+
143
+ ```bibtex
144
+ @misc{a2ametatrace,
145
+ title = {A2A-MetaTrace: a metadata-only corpus of multi-agent A2A workflow traffic},
146
+ author = {Dangol, Bijaya},
147
+ year = {2026}
148
+ }
149
+ ```
corpus/__init__.py ADDED
File without changes
corpus/classes.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""A2A-MetaTrace workflow classes and their compositional variants.
2
+
3
+ A *class* is the ground-truth label the adversary recovers; a *variant* is one concrete
4
+ capability composition that realizes it. Every variant of a class shares a distinctive
5
+ ordered **motif** (a characteristic capability pair) and differs in the *filler*
6
+ capabilities around it. The motif is the class invariant a leave-variant-out adversary
7
+ can latch onto; the filler, drawn from a vocabulary shared across classes, is what makes
8
+ a held-out variant a genuinely novel composition. So leave-variant-out asks the honest
9
+ generalization question, "does leakage survive compositions the adversary never saw?",
10
+ rather than collapsing to "can it recover a class with no shared structure?".
11
+
12
+ The orchestrator executes a (class, variant) as a real multi-agent A2A workflow, one
13
+ stage per capability. Provenance discipline (disclosed in the datasheet): the protocol
14
+ path is the real ``a2a-sdk`` and the agents run real streaming workflows; the
15
+ composition and labels are ours.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class WorkflowClassTemplate:
25
+ """One variant: an ordered capability composition with a unique name."""
26
+
27
+ name: str
28
+ stages: tuple[str, ...]
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class TaskClass:
33
+ """A label realized by several variants that share a capability motif."""
34
+
35
+ name: str
36
+ variants: tuple[WorkflowClassTemplate, ...]
37
+
38
+
39
+ # Capabilities are served by REAL official a2a-samples agents (corpus.sample_agents):
40
+ # travel (OpenAI), currency/expense/content (Gemini-ADK via Vertex), echo (no-LLM filler).
41
+ # Each class is anchored by a distinct ordered motif (present in all its variants) and
42
+ # padded with shared filler so compositions overlap across classes without erasing the
43
+ # per-class invariant -- the structure the leave-variant-out split tests.
44
+ CLASSES: tuple[TaskClass, ...] = (
45
+ TaskClass("fx_quote", ( # motif: travel -> currency
46
+ WorkflowClassTemplate("fx_quote_bare", ("travel", "currency")),
47
+ WorkflowClassTemplate("fx_quote_doc", ("travel", "currency", "content")),
48
+ WorkflowClassTemplate("fx_quote_pre", ("echo", "travel", "currency")),
49
+ )),
50
+ TaskClass("trip_brief", ( # motif: travel -> content
51
+ WorkflowClassTemplate("trip_brief_bare", ("travel", "content")),
52
+ WorkflowClassTemplate("trip_brief_fx", ("travel", "content", "currency")),
53
+ WorkflowClassTemplate("trip_brief_pre", ("echo", "travel", "content")),
54
+ )),
55
+ TaskClass("content_trip", ( # motif: content -> travel
56
+ WorkflowClassTemplate("content_trip_bare", ("content", "travel")),
57
+ WorkflowClassTemplate("content_trip_fx", ("content", "travel", "currency")),
58
+ WorkflowClassTemplate("content_trip_pre", ("echo", "content", "travel")),
59
+ )),
60
+ TaskClass("fx_content", ( # motif: currency -> content
61
+ WorkflowClassTemplate("fx_content_bare", ("currency", "content")),
62
+ WorkflowClassTemplate("fx_content_trip", ("currency", "content", "travel")),
63
+ WorkflowClassTemplate("fx_content_pre", ("echo", "currency", "content")),
64
+ )),
65
+ TaskClass("doc_fx", ( # motif: content -> currency
66
+ WorkflowClassTemplate("doc_fx_bare", ("content", "currency")),
67
+ WorkflowClassTemplate("doc_fx_trip", ("content", "currency", "travel")),
68
+ WorkflowClassTemplate("doc_fx_pre", ("echo", "content", "currency")),
69
+ )),
70
+ TaskClass("reimburse", ( # motif: currency -> expense (finance)
71
+ WorkflowClassTemplate("reimburse_bare", ("currency", "expense")),
72
+ WorkflowClassTemplate("reimburse_doc", ("currency", "expense", "content")),
73
+ WorkflowClassTemplate("reimburse_pre", ("travel", "currency", "expense")),
74
+ )),
75
+ TaskClass("expense_brief", ( # motif: expense -> content (finance)
76
+ WorkflowClassTemplate("expense_brief_bare", ("expense", "content")),
77
+ WorkflowClassTemplate("expense_brief_fx", ("expense", "content", "currency")),
78
+ WorkflowClassTemplate("expense_brief_pre", ("travel", "expense", "content")),
79
+ )),
80
+ TaskClass("skill_brief", ( # motif: skills -> content
81
+ WorkflowClassTemplate("skill_brief_bare", ("skills", "content")),
82
+ WorkflowClassTemplate("skill_brief_fx", ("skills", "content", "currency")),
83
+ WorkflowClassTemplate("skill_brief_pre", ("echo", "skills", "content")),
84
+ )),
85
+ TaskClass("skill_fx", ( # motif: skills -> currency
86
+ WorkflowClassTemplate("skill_fx_bare", ("skills", "currency")),
87
+ WorkflowClassTemplate("skill_fx_doc", ("skills", "currency", "content")),
88
+ WorkflowClassTemplate("skill_fx_pre", ("echo", "skills", "currency")),
89
+ )),
90
+ )
91
+
92
+
93
+ def all_variants() -> list[tuple[str, WorkflowClassTemplate]]:
94
+ """Flatten to (class_label, variant) pairs."""
95
+ return [(c.name, v) for c in CLASSES for v in c.variants]
96
+
97
+
98
+ def capabilities() -> list[str]:
99
+ """The distinct capabilities any variant invokes (one agent server each)."""
100
+ caps: list[str] = []
101
+ for c in CLASSES:
102
+ for v in c.variants:
103
+ for cap in v.stages:
104
+ if cap not in caps:
105
+ caps.append(cap)
106
+ return caps
107
+
108
+
109
+ def class_of(variant_name: str) -> str:
110
+ for c in CLASSES:
111
+ for v in c.variants:
112
+ if v.name == variant_name:
113
+ return c.name
114
+ raise KeyError(variant_name)
corpus/launcher.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Launch the official sample agents as subprocesses and health-check them.
2
+
3
+ Each agent runs in its own directory/env (its own ``uv.lock``, Python 3.13). We start it
4
+ with ``subprocess.Popen``, wait until its Agent Card endpoint answers, and return the
5
+ capabilities that came up. Agents that fail to start within the timeout are skipped (and
6
+ reported), so one flaky sample does not block the whole corpus run.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ import time
13
+ from dataclasses import dataclass, field
14
+
15
+ import httpx
16
+
17
+ from corpus.sample_agents import AGENTS, AgentSpec
18
+
19
+
20
+ def _free_port(port: int) -> None:
21
+ """Kill any stale process holding ``port`` (orphaned agent from a killed run)."""
22
+ try:
23
+ out = subprocess.run(["lsof", "-ti", f"tcp:{port}"], capture_output=True, text=True)
24
+ for pid in out.stdout.split():
25
+ subprocess.run(["kill", "-9", pid], capture_output=True)
26
+ except Exception:
27
+ pass
28
+
29
+
30
+ @dataclass
31
+ class LiveAgents:
32
+ urls: dict[str, str] = field(default_factory=dict) # capability -> base url
33
+ tokens: dict[str, str] = field(default_factory=dict) # capability -> provider token
34
+ domains: dict[str, str] = field(default_factory=dict) # capability -> domain
35
+ _procs: list[subprocess.Popen] = field(default_factory=list)
36
+ _logs: list = field(default_factory=list)
37
+
38
+ def stop(self) -> None:
39
+ for p in self._procs:
40
+ p.terminate()
41
+ time.sleep(1.0)
42
+ for p in self._procs:
43
+ if p.poll() is None:
44
+ p.kill()
45
+ for f in self._logs:
46
+ try:
47
+ f.close()
48
+ except Exception:
49
+ pass
50
+
51
+
52
+ def _card_ok(url: str) -> bool:
53
+ try:
54
+ return httpx.get(f"{url}/.well-known/agent-card.json", timeout=1.5).status_code == 200
55
+ except httpx.HTTPError:
56
+ return False
57
+
58
+
59
+ def launch(specs: tuple[AgentSpec, ...] = AGENTS, *, startup_timeout: float = 240.0) -> LiveAgents:
60
+ """Start every spec; return the ones whose card endpoint comes up."""
61
+ live = LiveAgents()
62
+ pending: list[tuple[AgentSpec, subprocess.Popen]] = []
63
+ for spec in specs:
64
+ _free_port(spec.port) # clear any orphaned agent holding this port
65
+ log = open(f"/tmp/a2a_metatrace_{spec.capability}.log", "w")
66
+ live._logs.append(log)
67
+ proc = subprocess.Popen(
68
+ spec.argv(), cwd=str(spec.cwd), env=spec.env(),
69
+ stdout=log, stderr=subprocess.STDOUT,
70
+ )
71
+ live._procs.append(proc)
72
+ pending.append((spec, proc))
73
+ print(f"[launch] {spec.capability:9s} pid={proc.pid} :{spec.port} ({spec.auth}) {spec.subdir}")
74
+
75
+ deadline = time.time() + startup_timeout
76
+ up: set[str] = set()
77
+ while time.time() < deadline and len(up) < len(pending):
78
+ for spec, proc in pending:
79
+ if spec.capability in up:
80
+ continue
81
+ if proc.poll() is not None: # process died
82
+ continue
83
+ if _card_ok(spec.url):
84
+ up.add(spec.capability)
85
+ live.urls[spec.capability] = spec.url
86
+ live.tokens[spec.capability] = spec.provider_token
87
+ live.domains[spec.capability] = spec.domain
88
+ print(f"[ready] {spec.capability:9s} {spec.url}")
89
+ time.sleep(2.0)
90
+
91
+ for spec, proc in pending:
92
+ if spec.capability not in up:
93
+ dead = proc.poll() is not None
94
+ print(f"[SKIP] {spec.capability:9s} did not come up "
95
+ f"({'process exited' if dead else 'timeout'}; see /tmp/a2a_metatrace_{spec.capability}.log)")
96
+ print(f"[launch] {len(up)}/{len(pending)} agents live: {sorted(up)}")
97
+ return live
corpus/orchestrator.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A2A-MetaTrace orchestrator: compose sample agents into labeled workflows.
2
+
3
+ The orchestrator turns a :class:`~corpus.classes.WorkflowClassTemplate` into a real
4
+ multi-agent A2A workflow and records metadata-only message dicts in a fixed 13-field
5
+ schema, so the exported corpus loads unchanged. It is deliberately decoupled from how a
6
+ stage is executed: a ``stage_runner`` callable performs one stage and returns its
7
+ records. The real runner (``corpus.runner_samples``, driven by ``corpus.run_corpus``)
8
+ drives official sample-agent servers over the ``a2a-sdk`` via a real discovery round-trip
9
+ + ``message/send`` + SSE streaming; the offline test injects a scripted runner, so the
10
+ composition and record schema are covered without standing up servers.
11
+
12
+ The record schema:
13
+ trace_id, task_class, client_id, n_stages, stage_idx, step_type, capability,
14
+ label_visible, src, dst, t, length, direction
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Callable
20
+
21
+ from corpus.classes import CLASSES, TaskClass, WorkflowClassTemplate
22
+
23
+ # stage_runner(variant, instance, stage_idx, capability, client_id) -> list[record]
24
+ StageRunner = Callable[[WorkflowClassTemplate, int, int, str, str], list[dict]]
25
+
26
+ # The 13 fields a stage runner must supply per message; the orchestrator adds the
27
+ # workflow-level labels (trace_id, task_class, client_id, n_stages, stage_idx,
28
+ # capability) and a `variant` tag for the leave-variant-out split, which is extra
29
+ # (records_to_traces ignores unknown keys).
30
+ REQUIRED_FIELDS = frozenset(
31
+ {
32
+ "trace_id", "task_class", "client_id", "n_stages", "stage_idx", "step_type",
33
+ "capability", "label_visible", "src", "dst", "t", "length", "direction",
34
+ }
35
+ )
36
+
37
+
38
+ def run_workflow(
39
+ variant: WorkflowClassTemplate,
40
+ instance: int,
41
+ *,
42
+ task_class: str,
43
+ trace_id: int,
44
+ client_id: str,
45
+ stage_runner: StageRunner,
46
+ ) -> list[dict]:
47
+ """Execute one workflow instance of ``variant`` under label ``task_class``.
48
+
49
+ Each record carries the workflow-level ground truth (``trace_id``, the class
50
+ ``task_class``, the ``variant`` name for grouped evaluation, ``client_id``, stage
51
+ count) so the corpus is self-describing; individual runners emit only the
52
+ per-message obs(m) + stage/step labels.
53
+ """
54
+ n_stages = len(variant.stages)
55
+ records: list[dict] = []
56
+ for stage_idx, capability in enumerate(variant.stages):
57
+ for rec in stage_runner(variant, instance, stage_idx, capability, client_id):
58
+ rec = {
59
+ "trace_id": trace_id,
60
+ "task_class": task_class,
61
+ "variant": variant.name,
62
+ "client_id": client_id,
63
+ "n_stages": n_stages,
64
+ "stage_idx": stage_idx,
65
+ "capability": capability,
66
+ **rec,
67
+ }
68
+ missing = REQUIRED_FIELDS - rec.keys()
69
+ if missing:
70
+ raise ValueError(f"stage runner record missing fields: {sorted(missing)}")
71
+ records.append(rec)
72
+ return records
73
+
74
+
75
+ def run_corpus(
76
+ classes: tuple[TaskClass, ...] = CLASSES,
77
+ *,
78
+ runs_per_class: int,
79
+ stage_runner: StageRunner,
80
+ transport: str = "https-direct",
81
+ proxy: str | None = None,
82
+ client_ids: tuple[str, ...] = ("client-001", "client-002", "client-003"),
83
+ ) -> dict:
84
+ """Build the capture document: ~``runs_per_class`` instances per class, split
85
+ across that class's variants as evenly as possible.
86
+
87
+ The ``trace_id`` is a global counter; clients round-robin across the pool so the
88
+ corpus has the same persistent-client structure as the synthetic population (the
89
+ unlinkability target). Returns the ``{transport, proxy, messages:[...]}`` document
90
+ ``records_to_traces`` consumes; the ``variant`` tag rides along for grouped eval.
91
+ """
92
+ messages: list[dict] = []
93
+ trace_id = 0
94
+ for cls in classes:
95
+ nvar = len(cls.variants)
96
+ for vi, variant in enumerate(cls.variants):
97
+ # distribute runs_per_class across variants (front variants absorb the
98
+ # remainder), so class totals stay balanced regardless of variant count
99
+ runs = runs_per_class // nvar + (1 if vi < runs_per_class % nvar else 0)
100
+ for instance in range(runs):
101
+ client_id = client_ids[trace_id % len(client_ids)]
102
+ messages.extend(
103
+ run_workflow(variant, instance, task_class=cls.name,
104
+ trace_id=trace_id, client_id=client_id,
105
+ stage_runner=stage_runner)
106
+ )
107
+ trace_id += 1
108
+ return {"transport": transport, "proxy": proxy, "messages": messages}
corpus/probe_enrichment.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Smoke-test for live sample-agent routing (Agent Card URL override + streaming).
2
+
3
+ Launches a small set of capabilities and runs one stage each, so routing failures
4
+ surface before any full corpus run. Not part of the corpus pipeline itself."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from corpus.launcher import launch
9
+ from corpus.runner_samples import build_sample_stage_runner
10
+ from corpus.sample_agents import BY_CAPABILITY
11
+
12
+ CAPS = ("currency", "content", "skills")
13
+
14
+
15
+ def main() -> None:
16
+ specs = tuple(BY_CAPABILITY[c] for c in CAPS)
17
+ live = launch(specs)
18
+ runner, teardown = build_sample_stage_runner(live)
19
+ try:
20
+ for cap in CAPS:
21
+ if cap not in live.urls:
22
+ print(f" {cap:9s} -> NOT LIVE (skipped launch)")
23
+ continue
24
+ try:
25
+ recs = runner(f"{cap}_probe", 0, 0, cap, "client-0")
26
+ msgs = len(recs)
27
+ final = next((r for r in recs if r.get("step_type") == "response"), None)
28
+ size = final["length"] if final else 0
29
+ print(f" {cap:9s} -> OK ({msgs} records, final={size}B)")
30
+ except Exception as e: # noqa: BLE001
31
+ print(f" {cap:9s} -> FAIL {type(e).__name__}: {e}")
32
+ finally:
33
+ teardown()
34
+ live.stop()
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
corpus/run_corpus.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the A2A-MetaTrace corpus from real official a2a-samples agents.
2
+
3
+ Launches the official sample agents (each in its own env), drives every workflow class
4
+ through its variants over the real ``a2a-sdk`` wire, records obs(m), and writes the
5
+ ``{transport, messages}`` capture document ``scripts/export_hf.py`` consumes.
6
+
7
+ uv run python -m corpus.run_corpus --runs-per-class 12
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import time
15
+ from pathlib import Path
16
+
17
+ from corpus.classes import CLASSES
18
+ from corpus.launcher import launch
19
+ from corpus.orchestrator import run_workflow
20
+ from corpus.runner_samples import build_sample_stage_runner
21
+
22
+ CLIENT_IDS = ("client-001", "client-002", "client-003")
23
+
24
+ ROOT = Path(__file__).resolve().parents[1]
25
+
26
+
27
+ def _filter_classes(live_caps: set[str]):
28
+ """Keep only classes whose every variant uses only live capabilities."""
29
+ kept = []
30
+ for cls in CLASSES:
31
+ ok = all(all(c in live_caps for c in v.stages) for v in cls.variants)
32
+ if ok:
33
+ kept.append(cls)
34
+ else:
35
+ missing = {c for v in cls.variants for c in v.stages if c not in live_caps}
36
+ print(f"[skip class] {cls.name}: needs missing caps {sorted(missing)}")
37
+ return tuple(kept)
38
+
39
+
40
+ def main() -> None:
41
+ ap = argparse.ArgumentParser()
42
+ ap.add_argument("--runs-per-class", type=int, default=12)
43
+ ap.add_argument("--out", type=Path,
44
+ default=ROOT / "results" / "corpus" / "a2a_metatrace.json")
45
+ args = ap.parse_args()
46
+
47
+ live = launch()
48
+ if len(live.urls) < 2:
49
+ print("fewer than 2 agents live; aborting")
50
+ live.stop()
51
+ return
52
+ classes = _filter_classes(set(live.urls))
53
+ if not classes:
54
+ print("no class fully covered by live agents; aborting")
55
+ live.stop()
56
+ return
57
+
58
+ stage_runner, teardown = build_sample_stage_runner(live)
59
+ t0 = time.time()
60
+ messages: list[dict] = []
61
+ trace_id = skipped = 0
62
+ try:
63
+ total = args.runs_per_class * len(classes)
64
+ print(f"generating ~{total} workflows over {len(classes)} classes "
65
+ f"({[c.name for c in classes]}), {args.runs_per_class}/class ...")
66
+ for cls in classes:
67
+ nvar = len(cls.variants)
68
+ for vi, variant in enumerate(cls.variants):
69
+ runs = args.runs_per_class // nvar + (1 if vi < args.runs_per_class % nvar else 0)
70
+ for instance in range(runs):
71
+ client_id = CLIENT_IDS[trace_id % len(CLIENT_IDS)]
72
+ # a whole workflow is the retry unit: a failed stage drops only its
73
+ # workflow (partial records discarded), never the whole corpus.
74
+ try:
75
+ recs = run_workflow(variant, instance, task_class=cls.name,
76
+ trace_id=trace_id, client_id=client_id,
77
+ stage_runner=stage_runner)
78
+ messages.extend(recs)
79
+ except Exception as e: # noqa: BLE001
80
+ skipped += 1
81
+ print(f" ! skip wf {trace_id} ({variant.name}): {type(e).__name__}: {str(e)[:80]}")
82
+ trace_id += 1
83
+ if trace_id % 20 == 0:
84
+ print(f" ... {trace_id} workflows, {len(messages)} msgs, {skipped} skipped")
85
+ finally:
86
+ teardown()
87
+ live.stop()
88
+ wall = time.time() - t0
89
+
90
+ capture = {"transport": "https-direct", "proxy": None, "messages": messages}
91
+ args.out.parent.mkdir(parents=True, exist_ok=True)
92
+ args.out.write_text(json.dumps(capture))
93
+ n_wf = len({m["trace_id"] for m in capture["messages"]})
94
+ print(f"wrote {len(messages)} messages ({n_wf} workflows, {skipped} skipped) "
95
+ f"in {wall:.0f}s -> {args.out}")
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
corpus/runner_samples.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage runner that drives the live official sample agents and records obs(m).
2
+
3
+ Returns a ``stage_runner(variant, instance, stage_idx, capability, client_id)`` the
4
+ orchestrator calls once per workflow stage. Each call performs, against that capability's
5
+ real sample-agent server:
6
+
7
+ * a real **discovery** round-trip (Agent Card fetch); the capability is named here, the
8
+ semantic-label channel (``label_visible=True``), and
9
+ * a real **message/send** + streamed updates/final response, recorded as wire-only
10
+ obs(m): request byte size (httpx request hook), per-event serialized sizes, timestamps,
11
+ and an *opaque* provider token (not the capability name).
12
+
13
+ The orchestrator is synchronous and a2a-sdk is async, so we own a background event loop:
14
+ clients live in it and each synchronous stage call submits its coroutine and blocks for
15
+ the records. The 7 per-message fields here + the orchestrator's workflow labels make the
16
+ 13-field obs(m) record the dataset exports.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import threading
23
+ import time
24
+ import uuid
25
+ from collections.abc import Callable
26
+
27
+ import httpx
28
+ from a2a.client.card_resolver import A2ACardResolver
29
+ from a2a.client.client_factory import ClientConfig, ClientFactory
30
+ from a2a.types import Message, Part, Role, SendMessageConfiguration, SendMessageRequest
31
+
32
+ # Capability-appropriate user prompts so the real agents do real work (content-driven sizes).
33
+ PROMPTS: dict[str, str] = {
34
+ "travel": "Plan a 3-day trip to Lisbon with a rough daily schedule.",
35
+ "currency": "How much is 250 USD in EUR right now?",
36
+ "expense": "I need to file a reimbursement for a 320 USD client dinner in Berlin.",
37
+ "content": "Draft a short outline for a blog post about sustainable travel.",
38
+ "echo": "hello there",
39
+ "skills": "What skills and capabilities are relevant for organizing a business trip?",
40
+ }
41
+ _DEFAULT_PROMPT = "Please handle this request."
42
+
43
+ # Capabilities whose sample server runs an a2a-sdk too old to advertise the streaming
44
+ # method our client would pick from a streaming-capable card; force them onto the
45
+ # universally-supported message/send path.
46
+ _NON_STREAMING: set[str] = set()
47
+
48
+
49
+ def build_sample_stage_runner(live) -> tuple[Callable, Callable[[], None]]:
50
+ """Given launched agents (``LiveAgents``), return ``(stage_runner, teardown)``."""
51
+ urls = live.urls
52
+ tokens = live.tokens
53
+
54
+ loop = asyncio.new_event_loop()
55
+ threading.Thread(target=loop.run_forever, daemon=True).start()
56
+
57
+ def _submit(coro):
58
+ return asyncio.run_coroutine_threadsafe(coro, loop).result()
59
+
60
+ clients: dict[str, dict] = {}
61
+ state: dict = {"pending": None}
62
+
63
+ async def _on_request(request: httpx.Request) -> None:
64
+ # record the c2s message/send body size at send time
65
+ if request.method == "POST" and state["pending"] is not None:
66
+ state["pending"]["length"] = len(request.content or b"")
67
+ state["pending"]["t"] = time.perf_counter()
68
+
69
+ async def _setup() -> None:
70
+ for cap, url in urls.items():
71
+ http = httpx.AsyncClient(timeout=120, event_hooks={"request": [_on_request]})
72
+ card = await A2ACardResolver(http, url + "/").get_agent_card()
73
+ # Some sample agents ship a static/copied agent_card.json with a stale hardcoded
74
+ # interface URL (adk_skills_agent advertises localhost:10999, ignoring --port), so
75
+ # the factory would dial the wrong server. We launched each agent ourselves and
76
+ # know its real URL -- force every advertised interface onto it.
77
+ for iface in card.supported_interfaces:
78
+ iface.url = url
79
+ streaming = cap not in _NON_STREAMING
80
+ client = ClientFactory(ClientConfig(httpx_client=http, streaming=streaming)).create(card)
81
+ clients[cap] = {"client": client, "http": http, "card_http": httpx.AsyncClient(timeout=30)}
82
+
83
+ _submit(_setup())
84
+
85
+ async def _run_stage(capability, client_id) -> list[dict]:
86
+ url = urls[capability]
87
+ provider = tokens[capability]
88
+ buf: list[dict] = []
89
+
90
+ # --- discovery: real Agent Card fetch (names the capability => label channel) ---
91
+ t_q = time.perf_counter()
92
+ card_http = clients[capability]["card_http"]
93
+ req_path = "/.well-known/agent-card.json"
94
+ resp = await card_http.get(url + req_path)
95
+ buf.append({"step_type": "discovery_query", "direction": "c2s",
96
+ "src": client_id, "dst": "registry", "t": t_q,
97
+ "length": len(req_path.encode()) + 64, "label_visible": True})
98
+ buf.append({"step_type": "discovery_result", "direction": "s2c",
99
+ "src": "registry", "dst": client_id, "t": time.perf_counter(),
100
+ "length": len(resp.content), "label_visible": False})
101
+
102
+ # --- delegation: real message/send + streamed updates/response ---
103
+ text = PROMPTS.get(capability, _DEFAULT_PROMPT)
104
+ msg = Message(message_id=str(uuid.uuid4()), role=Role.ROLE_USER, parts=[Part(text=text)])
105
+ req = SendMessageRequest(
106
+ message=msg,
107
+ configuration=SendMessageConfiguration(accepted_output_modes=["text/plain"]),
108
+ )
109
+ state["pending"] = {"length": 0, "t": time.perf_counter()}
110
+ stream: list[dict] = []
111
+ async for ev in clients[capability]["client"].send_message(req):
112
+ stream.append({"direction": "s2c", "src": provider, "dst": client_id,
113
+ "t": time.perf_counter(),
114
+ "length": len(ev.SerializeToString()), "label_visible": False})
115
+ pend = state["pending"]
116
+ state["pending"] = None
117
+ buf.append({"step_type": "request", "direction": "c2s", "src": client_id,
118
+ "dst": provider, "t": pend["t"], "length": pend["length"],
119
+ "label_visible": False})
120
+ for k, rec in enumerate(stream):
121
+ rec["step_type"] = "response" if k == len(stream) - 1 else "update"
122
+ buf.extend(stream)
123
+ return buf
124
+
125
+ def stage_runner(variant, instance, stage_idx, capability, client_id) -> list[dict]:
126
+ # real agents drop streams transiently (and free-tier Gemini rate-limits), so retry
127
+ # a stage with rate-limit-aware backoff before the whole workflow is abandoned (the
128
+ # orchestrator turns a raised error into a skip).
129
+ last: Exception | None = None
130
+ for wait in (4, 15, 40):
131
+ try:
132
+ return _submit(_run_stage(capability, client_id))
133
+ except Exception as e: # noqa: BLE001 - any transport/agent/rate-limit hiccup
134
+ last = e
135
+ time.sleep(wait)
136
+ raise last # type: ignore[misc]
137
+
138
+ def teardown() -> None:
139
+ async def _close():
140
+ for c in clients.values():
141
+ await c["http"].aclose()
142
+ await c["card_http"].aclose()
143
+ try:
144
+ _submit(_close())
145
+ finally:
146
+ loop.call_soon_threadsafe(loop.stop)
147
+
148
+ return stage_runner, teardown
corpus/sample_agents.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Registry of the official ``a2a-samples`` agents the corpus drives.
2
+
3
+ Each capability is served by a *real* official sample agent run as its own process in
4
+ its own env (its `uv.lock`), pinned to Python 3.13 (newer alpha interpreters break some
5
+ native builds). The orchestrator connects as an a2a-sdk client and records obs(m); the
6
+ agents bring their own LLM calls (OpenAI or Gemini-via-Vertex). Provenance disclosed in
7
+ ``DATASHEET.md``: the protocol path and the agents are official; only the composition is ours.
8
+
9
+ Configuration (all via environment):
10
+ * ``A2A_SAMPLES_DIR``: path to the official ``a2a-samples`` checkout's
11
+ ``samples/python/agents`` directory. Defaults to a sibling ``a2a-samples`` checkout.
12
+ * ``openai`` agents read ``OPENAI_API_KEY`` (travel_planner reads it as ``API_KEY``).
13
+ * ``vertex`` (ADK) agents use ``GOOGLE_CLOUD_PROJECT`` / ``GOOGLE_CLOUD_LOCATION`` with
14
+ ``GOOGLE_GENAI_USE_VERTEXAI=true``; a placeholder ``GOOGLE_API_KEY`` satisfies the
15
+ samples' startup guard while the call routes through Vertex/ADC.
16
+
17
+ Keys may also be supplied via an ``.envrc`` file (``export KEY=VALUE`` lines); set its
18
+ path with ``A2A_METATRACE_ENVRC`` (defaults to ``.envrc`` in the working directory).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ HOST = "127.0.0.1"
28
+ SAMPLES_DIR = Path(
29
+ os.environ.get(
30
+ "A2A_SAMPLES_DIR",
31
+ Path(__file__).resolve().parent.parent.parent
32
+ / "a2a-samples"
33
+ / "samples"
34
+ / "python"
35
+ / "agents",
36
+ )
37
+ )
38
+ ENVRC = Path(os.environ.get("A2A_METATRACE_ENVRC", ".envrc"))
39
+
40
+ GCLOUD_PROJECT = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
41
+ GCLOUD_LOCATION = os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1")
42
+
43
+
44
+ def _env_or_envrc(var: str) -> str:
45
+ """Read ``var`` from the environment, falling back to the optional ``.envrc``."""
46
+ if os.environ.get(var):
47
+ return os.environ[var]
48
+ if ENVRC.exists():
49
+ for line in ENVRC.read_text().splitlines():
50
+ line = line.strip()
51
+ if line.startswith(f"export {var}="):
52
+ return line.split("=", 1)[1].strip().strip('"').strip("'")
53
+ raise RuntimeError(f"{var} not found in env or {ENVRC}")
54
+
55
+
56
+ def _openai_key() -> str:
57
+ """Read OPENAI_API_KEY from the environment or the optional .envrc."""
58
+ return _env_or_envrc("OPENAI_API_KEY")
59
+
60
+
61
+ def _vertex_env() -> dict[str, str]:
62
+ return {
63
+ "GOOGLE_GENAI_USE_VERTEXAI": "TRUE", # uppercase: some samples compare exactly
64
+ "GOOGLE_CLOUD_PROJECT": GCLOUD_PROJECT,
65
+ "GOOGLE_CLOUD_LOCATION": GCLOUD_LOCATION,
66
+ # ADC performs the real call; these placeholders only satisfy the samples'
67
+ # startup guards (some check GOOGLE_API_KEY, some GEMINI_API_KEY).
68
+ "GOOGLE_API_KEY": "vertex-adc-in-use-placeholder",
69
+ "GEMINI_API_KEY": "vertex-adc-in-use-placeholder",
70
+ }
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class AgentSpec:
75
+ capability: str # the corpus capability label
76
+ domain: str # finance | travel | content | generic
77
+ subdir: str # directory under SAMPLES_DIR
78
+ run_args: tuple[str, ...] # args after `uv run --python 3.13`
79
+ port: int
80
+ auth: str # openai | vertex | litellm_openai | none
81
+ provider_token: str # opaque endpoint token on the wire (NOT the capability name)
82
+
83
+ @property
84
+ def cwd(self) -> Path:
85
+ return SAMPLES_DIR / self.subdir
86
+
87
+ @property
88
+ def url(self) -> str:
89
+ return f"http://{HOST}:{self.port}"
90
+
91
+ def env(self) -> dict[str, str]:
92
+ e = dict(os.environ)
93
+ # don't leak our orchestrator's venv into the agent's own uv project resolution
94
+ for k in ("VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT", "UV_PYTHON", "PYTHONPATH"):
95
+ e.pop(k, None)
96
+ if self.auth == "openai":
97
+ e["API_KEY"] = _openai_key()
98
+ e["OPENAI_API_KEY"] = _openai_key()
99
+ elif self.auth == "vertex":
100
+ e.update(_vertex_env())
101
+ elif self.auth == "litellm_openai":
102
+ # litellm-based ADK agents read the model from LITELLM_MODEL (env only, no
103
+ # code edit); the placeholder keys only satisfy the startup guards.
104
+ e.pop("GOOGLE_GENAI_USE_VERTEXAI", None)
105
+ e["OPENAI_API_KEY"] = _openai_key()
106
+ e["LITELLM_MODEL"] = "openai/gpt-4o-mini"
107
+ e["GEMINI_API_KEY"] = "placeholder-litellm-uses-openai"
108
+ e["GOOGLE_API_KEY"] = "placeholder-litellm-uses-openai"
109
+ return e
110
+
111
+ def argv(self) -> list[str]:
112
+ return ["uv", "run", "--python", "3.13", *self.run_args]
113
+
114
+
115
+ # The chosen set: official sample agents, mixed providers, 3 domains. Ports are distinct
116
+ # (travel_planner + helloworld hardcode theirs; ADK agents take --port).
117
+ AGENTS: tuple[AgentSpec, ...] = (
118
+ AgentSpec("travel", "travel", "travel_planner_agent", (".",), 10001, "openai", "agent-0001"),
119
+ AgentSpec("currency", "finance", "adk_currency_agent", ("currency_agent",), 10999, "vertex", "agent-0002"),
120
+ # adk_expense_reimbursement is litellm-based; LITELLM_MODEL points it at OpenAI (env only).
121
+ AgentSpec("expense", "finance", "adk_expense_reimbursement", (".", "--port", "10002"), 10002, "litellm_openai", "agent-0003"),
122
+ # content_planner ships no uv.lock and uses the 0.3.x server API, so pin a2a-sdk <1.0
123
+ AgentSpec("content", "content", "content_planner", ("--with", "a2a-sdk[http-server]<1.0", ".", "--port", "10003"), 10003, "vertex", "agent-0004"),
124
+ AgentSpec("echo", "generic", "helloworld", ("python", "__main__.py"), 9999, "none", "agent-0005"),
125
+ AgentSpec("skills", "knowledge", "adk_skills_agent", ("skills_agent", "--port", "10004"), 10004, "vertex", "agent-0006"),
126
+ )
127
+
128
+ BY_CAPABILITY: dict[str, AgentSpec] = {a.capability: a for a in AGENTS}
data/default/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f4e3e87bd2ec4f5f4f3d2fb97f7a21e6c7f4e9862ab977f2aec9b7c4e9c51dd
3
+ size 973617
pyproject.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "a2a-metatrace"
3
+ version = "0.1.0"
4
+ description = "A2A-MetaTrace: a labeled, metadata-only corpus of multi-agent A2A workflow traffic, built from real a2a-sdk agents. Generation harness + HuggingFace-style dataset export."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Bijaya Dangol", email = "dangoldbj23@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.13"
10
+ dependencies = [
11
+ # generation: real A2A servers + clients, optional real-LLM agents
12
+ "a2a-sdk>=1.1.0",
13
+ "httpx>=0.28.1",
14
+ "sse-starlette>=3.4.4",
15
+ "starlette>=1.2.1",
16
+ "uvicorn>=0.48.0",
17
+ "openai>=1.40.0",
18
+ # dataset export (HuggingFace-style Parquet)
19
+ "pandas>=3.0.3",
20
+ "pyarrow>=18.0.0",
21
+ ]
22
+
23
+ [dependency-groups]
24
+ dev = [
25
+ "pytest>=9.0.3",
26
+ "ruff>=0.15.15",
27
+ "datasets>=3.0.0", # to verify the export loads as a HF dataset
28
+ ]
29
+
30
+ [tool.uv]
31
+ package = false # a workspace of scripts/packages, not a distributable wheel
32
+
33
+ [tool.ruff]
34
+ line-length = 100
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+ pythonpath = ["."] # make the top-level `corpus` package importable in tests
scripts/export_hf.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export the raw A2A-MetaTrace capture JSON into a HuggingFace-style dataset.
2
+
3
+ Each generation run (``corpus.run_corpus``) writes a capture document
4
+ ``results/corpus/a2a_metatrace.json`` whose ``messages`` list is a flat sequence of
5
+ metadata-only records ``obs(m)`` with workflow ground-truth labels.
6
+ This script turns that capture into the layout the HuggingFace Hub expects:
7
+
8
+ * one Parquet file per config under ``data/<config>/train.parquet`` (message-level rows,
9
+ the natural tabular form; reconstruct a workflow by grouping on ``trace_id``), and
10
+ * a dataset card ``README.md`` whose YAML front matter declares the ``configs`` and
11
+ ``dataset_info`` so ``datasets.load_dataset("<repo>", "<config>")`` just works.
12
+
13
+ Run:
14
+ uv run python scripts/export_hf.py
15
+ The published artifact is ``data/*.parquet`` + ``README.md``; the raw JSON is an
16
+ intermediate (gitignored). The prose datasheet lives in ``DATASHEET.md``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ from pathlib import Path
23
+
24
+ import pandas as pd
25
+
26
+ ROOT = Path(__file__).resolve().parents[1]
27
+ CORPUS = ROOT / "results" / "corpus"
28
+ DATA = ROOT / "data"
29
+
30
+ # capture file -> (config name, mode, transport). A config is one coherent slice a
31
+ # consumer would load on its own; mode/transport ride along as columns too.
32
+ CONFIGS: list[tuple[str, str, str, str]] = [
33
+ # traffic from real official a2a-samples agents
34
+ ("a2a_metatrace.json", "default", "agents", "https"),
35
+ ]
36
+
37
+ # The message-level row schema. Order is the dataset's column order; dtypes are the
38
+ # HuggingFace feature dtypes the card advertises.
39
+ SCHEMA: list[tuple[str, str]] = [
40
+ ("trace_id", "int64"), # workflow id; group on this to reconstruct a workflow
41
+ ("task_class", "string"), # the label an adversary recovers
42
+ ("variant", "string"), # the concrete composition (group for leave-variant-out)
43
+ ("client_id", "string"), # orchestrating client (opaque token)
44
+ ("n_stages", "int32"), # stages in this workflow
45
+ ("stage_idx", "int32"), # which stage this message belongs to
46
+ ("step_type", "string"), # discovery_query|discovery_result|request|update|response
47
+ ("direction", "string"), # c2s | s2c
48
+ ("src", "string"), # opaque source endpoint token
49
+ ("dst", "string"), # opaque destination endpoint token
50
+ ("t", "float64"), # relative timestamp (seconds)
51
+ ("length", "int64"), # wire byte length of the message (the obs(m) volume axis)
52
+ ("capability", "string"), # capability named at this stage
53
+ ("label_visible", "bool"), # whether the semantic label is visible at this message
54
+ ("mode", "string"), # agent backend
55
+ ("transport", "string"), # transport the capture ran over
56
+ ]
57
+
58
+
59
+ def _frame(capture: dict, mode: str, transport: str) -> pd.DataFrame:
60
+ rows = []
61
+ for m in capture["messages"]:
62
+ row = {name: m.get(name) for name, _ in SCHEMA if name not in ("mode", "transport")}
63
+ row["mode"], row["transport"] = mode, transport
64
+ rows.append(row)
65
+ df = pd.DataFrame(rows, columns=[n for n, _ in SCHEMA])
66
+ for name, dtype in SCHEMA:
67
+ df[name] = df[name].astype(dtype)
68
+ return df
69
+
70
+
71
+ def _features_yaml() -> list[str]:
72
+ return [f" - name: {n}\n dtype: {d}" for n, d in SCHEMA]
73
+
74
+
75
+ def _front_matter(stats: list[dict]) -> str:
76
+ configs = []
77
+ info = []
78
+ for s in stats:
79
+ configs.append(
80
+ f"- config_name: {s['config']}\n"
81
+ f" data_files:\n"
82
+ f" - split: train\n"
83
+ f" path: data/{s['config']}/train.parquet"
84
+ )
85
+ info.append(
86
+ f"- config_name: {s['config']}\n"
87
+ f" features:\n" + "\n".join(_features_yaml()) + "\n"
88
+ f" splits:\n"
89
+ f" - name: train\n"
90
+ f" num_examples: {s['rows']}"
91
+ )
92
+ total = sum(s["rows"] for s in stats)
93
+ size_bucket = ("1K<n<10K" if total < 10_000 else
94
+ "10K<n<100K" if total < 100_000 else "100K<n<1M")
95
+ return (
96
+ "---\n"
97
+ "pretty_name: A2A-MetaTrace\n"
98
+ "task_categories:\n- tabular-classification\n"
99
+ "tags:\n"
100
+ "- traffic-analysis\n- metadata-privacy\n- agent\n- a2a\n"
101
+ "- multi-agent\n- workflow-fingerprinting\n"
102
+ f"size_categories:\n- {size_bucket}\n"
103
+ "configs:\n" + "\n".join(configs) + "\n"
104
+ "dataset_info:\n" + "\n".join(info) + "\n"
105
+ "---\n"
106
+ )
107
+
108
+
109
+ def _body(stats: list[dict]) -> str:
110
+ rows = "\n".join(
111
+ f"| `{s['config']}` | {s['mode']} | {s['transport']} | {s['workflows']} | "
112
+ f"{s['classes']} | {s['variants']} | {s['rows']} |"
113
+ for s in stats
114
+ )
115
+ return f"""# A2A-MetaTrace
116
+
117
+ A labeled, **metadata-only** corpus of multi-agent **A2A** (Agent-to-Agent) workflow
118
+ traffic. Each row is one wire message reduced to what a passive network observer sees,
119
+ `obs(m) = (src, dst, t, length, direction)`, with workflow ground-truth labels; message
120
+ bodies are discarded. The corpus exists to study how much of a *pending agent workflow*
121
+ leaks from communication-graph metadata alone, and to evaluate metadata-protecting
122
+ transports against it.
123
+
124
+ **Provenance (disclosed).** Workflows run over the real `a2a-sdk` protocol path
125
+ (Agent Cards, discovery, `message/send`, SSE) against real official `a2a-samples` agent
126
+ servers backed by real language-model calls. The workflow *compositions* and *labels*
127
+ are ours (see `DATASHEET.md`). This is the honest provenance claim: the protocol path and
128
+ agent behavior are real; the composition is designed.
129
+
130
+ ## Config
131
+
132
+ | config | agent backend | transport | workflows | classes | variants | rows (messages) |
133
+ |---|---|---|---|---|---|---|
134
+ {rows}
135
+
136
+ The corpus is captured from official `a2a-samples` agents composed into multi-agent
137
+ workflows; transport is HTTPS-direct (the metadata-protecting transport is evaluated
138
+ analytically; see `DATASHEET.md`).
139
+
140
+ ## Usage
141
+
142
+ ```python
143
+ from datasets import load_dataset
144
+ import pandas as pd
145
+
146
+ ds = load_dataset("a2a-metatrace", split="train") # message-level rows
147
+ df = ds.to_pandas()
148
+
149
+ # reconstruct workflows and their labels by grouping on trace_id
150
+ by_wf = df.groupby("trace_id")
151
+ labels = by_wf["task_class"].first()
152
+ ```
153
+
154
+ A workflow is the unit an adversary classifies; featurize per `trace_id` (message counts,
155
+ length stats, timing, direction n-grams) and recover `task_class`. Use the `variant`
156
+ column for a **leave-variant-out** split (generalization to unseen compositions).
157
+
158
+ ## Regenerating the corpus
159
+
160
+ The published Parquet is produced by capturing real official `a2a-samples` agents. To
161
+ reproduce it end to end:
162
+
163
+ 1. **Get the agents.** Clone the official samples repo and point the harness at its
164
+ Python agents directory:
165
+ ```bash
166
+ git clone https://github.com/a2aproject/a2a-samples.git
167
+ export A2A_SAMPLES_DIR=$(pwd)/a2a-samples/samples/python/agents
168
+ ```
169
+ 2. **Provide model credentials.** The sample agents call real models:
170
+ - `export OPENAI_API_KEY=...` (the OpenAI- and LiteLLM-backed agents), and
171
+ - for the Google-ADK agents, a Vertex project via Application Default Credentials:
172
+ `export GOOGLE_CLOUD_PROJECT=...` and `gcloud auth application-default login`.
173
+
174
+ Keys may instead be placed in a local `.envrc` (`export KEY=VALUE` lines); see
175
+ `corpus/sample_agents.py` for all configuration variables.
176
+ 3. **Install and run** (Python 3.13):
177
+ ```bash
178
+ uv sync
179
+ uv run python -m corpus.run_corpus --runs-per-class 30 # writes results/corpus/a2a_metatrace.json
180
+ uv run python scripts/export_hf.py # writes data/ + this README
181
+ ```
182
+
183
+ See `DATASHEET.md` for the workflow classes, provenance, and disclosed model substitutions.
184
+
185
+ ## What it is for
186
+
187
+ - **Workflow-fingerprinting / traffic analysis** on agent interoperation traffic.
188
+ - **Evaluating metadata-protecting transports** for agent interoperation.
189
+ - A reproducible, provenance-disclosed alternative to purely synthetic agent-traffic models.
190
+
191
+ See `DATASHEET.md` for construction, intended use, and limitations. Regenerate this card
192
+ and the Parquet files with `uv run python scripts/export_hf.py`.
193
+
194
+ ## Citation
195
+
196
+ ```bibtex
197
+ @misc{{a2ametatrace,
198
+ title = {{A2A-MetaTrace: a metadata-only corpus of multi-agent A2A workflow traffic}},
199
+ author = {{Dangol, Bijaya}},
200
+ year = {{2026}}
201
+ }}
202
+ ```
203
+ """
204
+
205
+
206
+ def main() -> None:
207
+ stats: list[dict] = []
208
+ for fname, config, mode, transport in CONFIGS:
209
+ src = CORPUS / fname
210
+ if not src.exists():
211
+ print(f"skip {config}: no capture at {src.name}")
212
+ continue
213
+ cap = json.loads(src.read_text())
214
+ df = _frame(cap, mode, transport)
215
+ out = DATA / config
216
+ out.mkdir(parents=True, exist_ok=True)
217
+ df.to_parquet(out / "train.parquet", index=False)
218
+ stats.append({
219
+ "config": config, "mode": mode, "transport": transport,
220
+ "rows": len(df), "workflows": int(df["trace_id"].nunique()),
221
+ "classes": int(df["task_class"].nunique()),
222
+ "variants": int(df["variant"].nunique()),
223
+ })
224
+ print(f"wrote data/{config}/train.parquet "
225
+ f"({len(df)} rows, {df['trace_id'].nunique()} workflows)")
226
+
227
+ if not stats:
228
+ print("no captures found; run `python -m corpus.run_corpus` first")
229
+ return
230
+ (ROOT / "README.md").write_text(_front_matter(stats) + "\n" + _body(stats))
231
+ print(f"wrote README.md (dataset card) for {len(stats)} configs")
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()
tests/test_corpus.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The A2A-MetaTrace orchestrator and variant-based classes, offline.
2
+
3
+ A scripted stage runner stands in for real agent servers, so these cover the generation
4
+ contracts that must hold before any server exists: the orchestrator emits schema-valid
5
+ records; the class label (not the variant) becomes ``task_class``; classes stay balanced
6
+ across their variants; every message carries a variant tag that maps back to its class;
7
+ and every variant stage has a serving capability.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from corpus.classes import CLASSES, all_variants, capabilities, class_of
13
+ from corpus.orchestrator import REQUIRED_FIELDS, run_corpus, run_workflow
14
+
15
+
16
+ def _scripted_runner(variant, instance, stage_idx, capability, client_id):
17
+ """Discovery round-trip + request + class-dependent updates (stands in for a server)."""
18
+ provider = f"agent-{abs(hash(capability)) % 9000 + 1000}"
19
+ t = float(stage_idx)
20
+ recs = [
21
+ {"step_type": "discovery_query", "direction": "c2s", "src": client_id,
22
+ "dst": "registry", "t": t, "length": 40, "label_visible": True},
23
+ {"step_type": "discovery_result", "direction": "s2c", "src": "registry",
24
+ "dst": client_id, "t": t + 0.01, "length": 60, "label_visible": False},
25
+ {"step_type": "request", "direction": "c2s", "src": client_id,
26
+ "dst": provider, "t": t + 0.02, "length": 200, "label_visible": False},
27
+ ]
28
+ n_updates = 1 + (len(capability) + stage_idx) % 4
29
+ for u in range(n_updates):
30
+ recs.append({"step_type": "update", "direction": "s2c", "src": provider,
31
+ "dst": client_id, "t": t + 0.03 + 0.01 * u, "length": 1500,
32
+ "label_visible": False})
33
+ recs.append({"step_type": "response", "direction": "s2c", "src": provider,
34
+ "dst": client_id, "t": t + 0.1, "length": 800, "label_visible": False})
35
+ return recs
36
+
37
+
38
+ def test_records_schema_and_class_label() -> None:
39
+ cls = CLASSES[0]
40
+ variant = cls.variants[0]
41
+ recs = run_workflow(variant, 0, task_class=cls.name, trace_id=0,
42
+ client_id="client-001", stage_runner=_scripted_runner)
43
+ assert recs
44
+ for r in recs:
45
+ assert REQUIRED_FIELDS <= r.keys()
46
+ assert r["task_class"] == cls.name # the CLASS, not the variant
47
+ assert r["variant"] == variant.name # variant rides along for grouping
48
+
49
+
50
+ def test_corpus_balanced_across_classes() -> None:
51
+ cap = run_corpus(CLASSES, runs_per_class=12, stage_runner=_scripted_runner)
52
+ # one workflow per trace_id; its class is constant across the trace's messages
53
+ class_of_trace = {m["trace_id"]: m["task_class"] for m in cap["messages"]}
54
+ counts: dict[str, int] = {}
55
+ for cls_name in class_of_trace.values():
56
+ counts[cls_name] = counts.get(cls_name, 0) + 1
57
+ assert set(counts) == {c.name for c in CLASSES}
58
+ # each class gets exactly runs_per_class workflows (split across its variants)
59
+ assert all(v == 12 for v in counts.values())
60
+
61
+
62
+ def test_variant_tag_present_for_every_message() -> None:
63
+ cap = run_corpus(CLASSES, runs_per_class=6, stage_runner=_scripted_runner)
64
+ variant_names = {v.name for _, v in all_variants()}
65
+ assert all(m["variant"] in variant_names for m in cap["messages"])
66
+ # variant maps back to its class
67
+ for m in cap["messages"]:
68
+ assert class_of(m["variant"]) == m["task_class"]
69
+
70
+
71
+ def test_capabilities_cover_all_variant_stages() -> None:
72
+ caps = set(capabilities())
73
+ for _, v in all_variants():
74
+ assert set(v.stages) <= caps