agent2perfetto 0.2.0__tar.gz

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,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 agent2perfetto contributors
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.
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent2perfetto
3
+ Version: 0.2.0
4
+ Summary: Convert agent session logs (Claude Code JSONL) into Perfetto/Chrome trace JSON for ui.perfetto.dev
5
+ Author: agent2perfetto contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ictechgy/agent2perfetto
8
+ Keywords: perfetto,trace,claude-code,llm,agent,observability
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Debuggers
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # agent2perfetto
25
+
26
+ **Don't build a viewer — put agent traces in the best one.**
27
+
28
+ `agent2perfetto` converts an agent session log (Claude Code JSONL) into a
29
+ [Perfetto](https://perfetto.dev/) / Chrome Trace Event Format JSON that loads in
30
+ [ui.perfetto.dev](https://ui.perfetto.dev) — the free, browser-based trace viewer Google built
31
+ for Chrome and Android profiling. You get hierarchical slices, counter time series, flow
32
+ arrows, and PerfettoSQL over your agent session without anyone writing a line of viewer code.
33
+
34
+ ## The problem
35
+
36
+ Agent observability today is bipolar:
37
+
38
+ - **Vendor SaaS dashboards** (LangSmith, LangFuse): cloud accounts, proprietary UIs, your
39
+ traces leaving your machine.
40
+ - **Text dumps and aggregators** (ccusage): totals and averages, no time axis.
41
+
42
+ But an agent session *is* a hierarchical event stream on a timeline: session → turns → tool
43
+ calls → results. The one local UI that renders exactly that shape — millions of events,
44
+ layered slices, counter tracks, flows — already exists, is free, runs in your browser, and
45
+ officially accepts arbitrary trace-like data. Nobody was sending agent traces to it.
46
+ This project is exactly that adapter.
47
+
48
+ ## Quickstart
49
+
50
+ Requires Python 3.10+, stdlib only, zero runtime network calls.
51
+
52
+ ```bash
53
+ # from a checkout
54
+ pip install .
55
+
56
+ # convert the checked-in example
57
+ agent2perfetto examples/sample_session.jsonl
58
+ # -> examples/sample_session.perfetto.json
59
+
60
+ # convert one of your own sessions and open the viewer
61
+ agent2perfetto ~/.claude/projects/<project>/session.jsonl --open
62
+ ```
63
+
64
+ `--open` runs macOS `open https://ui.perfetto.dev` (falls back to your browser elsewhere),
65
+ then prints drag-and-drop instructions. Drag the generated `.perfetto.json` into the UI —
66
+ the trace is parsed **in your browser's memory and never uploaded**. (For a fully offline
67
+ setup, Perfetto's UI also ships as a WASM bundle you can serve from localhost.)
68
+
69
+ Self-check a trace file any time:
70
+
71
+ ```bash
72
+ python scripts/validate_trace.py examples/sample_session.perfetto.json
73
+ ```
74
+
75
+ ## What the trace looks like (track map)
76
+
77
+ | Agent concept | Perfetto element |
78
+ | ------------------ | ----------------------------------------------------------------------------- |
79
+ | Session | process (one process per `sessionId`, named `agent session <id>`) |
80
+ | Assistant turns | complete slices (`X`) on the **turns** thread |
81
+ | Tool calls | complete slices named by tool (`Bash`, `Read`, …) on the **tools** thread |
82
+ | Tool results | complete slices (`result <tool>`) on the **tools** thread |
83
+ | Call → result | flow arrows (`s`/`f` events paired by `tool_use_id`) |
84
+ | Context occupancy | counter tracks `ctx_total`, `ctx_input`, `ctx_cache_read`, `ctx_cache_create` — per-call occupancy |
85
+ | Session spend | counter tracks `spend_total`, `spend_input`, `spend_cache_read`, `spend_cache_create` — cumulative |
86
+ | User prompts | instant markers on the **turns** thread |
87
+
88
+ Timeline rules (deterministic — same log in, same trace out):
89
+
90
+ - `ts` = microseconds since the earliest timestamp in the file; the original epoch time and
91
+ ISO base timestamp are kept in `metadata`.
92
+ - A turn/tool slice runs from its message timestamp to the next event's timestamp (for a
93
+ tool call, to its result's arrival). The final slice of a stream has nothing to bound it,
94
+ so it gets a 1 s estimate flagged `"dur_estimated": true` in its args.
95
+ - Counters are emitted at every assistant message. `ctx_*` is **per-call occupancy**: the
96
+ `input_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens` that *that single
97
+ call* reported (plus their total) — the model's context on that turn. `spend_*` is the
98
+ **cumulative** sum of the same fields across the session — the billing trajectory.
99
+
100
+ ## Approximation honesty
101
+
102
+ The context lane is an **approximation**. `ctx_*` counters report the usage fields each API
103
+ call claimed; they do not reproduce the provider-side context window (cache lifetime,
104
+ truncation, and system-prompt composition are not observable from the log). `spend_*`
105
+ counters re-bill cached tokens every call, so they grow monotonically and are **not** context
106
+ size. Slice durations that had no bounding event are estimates. This note ships inside every
107
+ trace under `metadata.approximation_note`, and the caveats above live in `metadata`.
108
+
109
+ ## Privacy: local by construction
110
+
111
+ The converter is a file-to-file transform with **zero network calls**. `--open` merely opens
112
+ a URL in your browser; the trace itself travels by drag-and-drop and is processed in the
113
+ browser locally. Nothing is uploaded, no account exists, no telemetry exists.
114
+
115
+ ## How this differs from adjacent tools
116
+
117
+ | Adjacent tool | Difference |
118
+ | --------------------------------- | ----------------------------------------------------------------------------- |
119
+ | LangSmith / LangFuse | Web SaaS with their own UIs and cloud storage. Here: local file → a standard format; viewer cost = 0. |
120
+ | ccusage / tokscale | Aggregates (how much was spent). Here: a time-space map (what ate context, when). |
121
+ | Perfetto itself | Provides the viewer and format but has no agent-domain adapter — that gap is exactly this project. |
122
+ | Perfetto MCP servers | The reverse direction (LLMs analyzing Perfetto traces). Here a human looks. |
123
+ | One-off "LLM trace JSON" scripts | A maintained adapter with golden-fixture tests against schema drift, plus lane semantics. |
124
+
125
+ ## Limits & roadmap
126
+
127
+ - v0.1 supported Claude Code JSONL only. v0.2 introduces the vendor-neutral
128
+ **Agent Trace IR** ([docs/agent-trace-ir.md](docs/agent-trace-ir.md)): new agent
129
+ logs (Codex next, then OTel GenAI) enter as adapters into the same IR, so the
130
+ same viewer, lanes, and PerfettoSQL work across harnesses. Subagent/async
131
+ slices are also planned.
132
+ - Perfetto's JSON format is the legacy entry point; a proto-format exporter is on the roadmap.
133
+ - Multiple `sessionId`s in one file become multiple processes; per-subagent processes and
134
+ context-composition lanes (system prompt / files / MCP schemas) are future work.
135
+
136
+ ## Development
137
+
138
+ ```bash
139
+ python3 -m venv /tmp/a2p-venv && . /tmp/a2p-venv/bin/activate
140
+ pip install -e .
141
+ pip install pytest # test-only dependency; the package itself needs nothing
142
+ pytest
143
+ ```
144
+
145
+ Layout: `src/agent2perfetto/` — a three-stage pipeline (`parser` adapter →
146
+ `ir` Agent Trace IR → `trace` Perfetto emitter → `cli`), synthetic fixtures and
147
+ a frozen golden trace under `tests/fixtures/`, the example session and its
148
+ generated trace under `examples/`, and the IR schema at
149
+ [docs/agent-trace-ir.md](docs/agent-trace-ir.md).
150
+
151
+ ## License
152
+
153
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,130 @@
1
+ # agent2perfetto
2
+
3
+ **Don't build a viewer — put agent traces in the best one.**
4
+
5
+ `agent2perfetto` converts an agent session log (Claude Code JSONL) into a
6
+ [Perfetto](https://perfetto.dev/) / Chrome Trace Event Format JSON that loads in
7
+ [ui.perfetto.dev](https://ui.perfetto.dev) — the free, browser-based trace viewer Google built
8
+ for Chrome and Android profiling. You get hierarchical slices, counter time series, flow
9
+ arrows, and PerfettoSQL over your agent session without anyone writing a line of viewer code.
10
+
11
+ ## The problem
12
+
13
+ Agent observability today is bipolar:
14
+
15
+ - **Vendor SaaS dashboards** (LangSmith, LangFuse): cloud accounts, proprietary UIs, your
16
+ traces leaving your machine.
17
+ - **Text dumps and aggregators** (ccusage): totals and averages, no time axis.
18
+
19
+ But an agent session *is* a hierarchical event stream on a timeline: session → turns → tool
20
+ calls → results. The one local UI that renders exactly that shape — millions of events,
21
+ layered slices, counter tracks, flows — already exists, is free, runs in your browser, and
22
+ officially accepts arbitrary trace-like data. Nobody was sending agent traces to it.
23
+ This project is exactly that adapter.
24
+
25
+ ## Quickstart
26
+
27
+ Requires Python 3.10+, stdlib only, zero runtime network calls.
28
+
29
+ ```bash
30
+ # from a checkout
31
+ pip install .
32
+
33
+ # convert the checked-in example
34
+ agent2perfetto examples/sample_session.jsonl
35
+ # -> examples/sample_session.perfetto.json
36
+
37
+ # convert one of your own sessions and open the viewer
38
+ agent2perfetto ~/.claude/projects/<project>/session.jsonl --open
39
+ ```
40
+
41
+ `--open` runs macOS `open https://ui.perfetto.dev` (falls back to your browser elsewhere),
42
+ then prints drag-and-drop instructions. Drag the generated `.perfetto.json` into the UI —
43
+ the trace is parsed **in your browser's memory and never uploaded**. (For a fully offline
44
+ setup, Perfetto's UI also ships as a WASM bundle you can serve from localhost.)
45
+
46
+ Self-check a trace file any time:
47
+
48
+ ```bash
49
+ python scripts/validate_trace.py examples/sample_session.perfetto.json
50
+ ```
51
+
52
+ ## What the trace looks like (track map)
53
+
54
+ | Agent concept | Perfetto element |
55
+ | ------------------ | ----------------------------------------------------------------------------- |
56
+ | Session | process (one process per `sessionId`, named `agent session <id>`) |
57
+ | Assistant turns | complete slices (`X`) on the **turns** thread |
58
+ | Tool calls | complete slices named by tool (`Bash`, `Read`, …) on the **tools** thread |
59
+ | Tool results | complete slices (`result <tool>`) on the **tools** thread |
60
+ | Call → result | flow arrows (`s`/`f` events paired by `tool_use_id`) |
61
+ | Context occupancy | counter tracks `ctx_total`, `ctx_input`, `ctx_cache_read`, `ctx_cache_create` — per-call occupancy |
62
+ | Session spend | counter tracks `spend_total`, `spend_input`, `spend_cache_read`, `spend_cache_create` — cumulative |
63
+ | User prompts | instant markers on the **turns** thread |
64
+
65
+ Timeline rules (deterministic — same log in, same trace out):
66
+
67
+ - `ts` = microseconds since the earliest timestamp in the file; the original epoch time and
68
+ ISO base timestamp are kept in `metadata`.
69
+ - A turn/tool slice runs from its message timestamp to the next event's timestamp (for a
70
+ tool call, to its result's arrival). The final slice of a stream has nothing to bound it,
71
+ so it gets a 1 s estimate flagged `"dur_estimated": true` in its args.
72
+ - Counters are emitted at every assistant message. `ctx_*` is **per-call occupancy**: the
73
+ `input_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens` that *that single
74
+ call* reported (plus their total) — the model's context on that turn. `spend_*` is the
75
+ **cumulative** sum of the same fields across the session — the billing trajectory.
76
+
77
+ ## Approximation honesty
78
+
79
+ The context lane is an **approximation**. `ctx_*` counters report the usage fields each API
80
+ call claimed; they do not reproduce the provider-side context window (cache lifetime,
81
+ truncation, and system-prompt composition are not observable from the log). `spend_*`
82
+ counters re-bill cached tokens every call, so they grow monotonically and are **not** context
83
+ size. Slice durations that had no bounding event are estimates. This note ships inside every
84
+ trace under `metadata.approximation_note`, and the caveats above live in `metadata`.
85
+
86
+ ## Privacy: local by construction
87
+
88
+ The converter is a file-to-file transform with **zero network calls**. `--open` merely opens
89
+ a URL in your browser; the trace itself travels by drag-and-drop and is processed in the
90
+ browser locally. Nothing is uploaded, no account exists, no telemetry exists.
91
+
92
+ ## How this differs from adjacent tools
93
+
94
+ | Adjacent tool | Difference |
95
+ | --------------------------------- | ----------------------------------------------------------------------------- |
96
+ | LangSmith / LangFuse | Web SaaS with their own UIs and cloud storage. Here: local file → a standard format; viewer cost = 0. |
97
+ | ccusage / tokscale | Aggregates (how much was spent). Here: a time-space map (what ate context, when). |
98
+ | Perfetto itself | Provides the viewer and format but has no agent-domain adapter — that gap is exactly this project. |
99
+ | Perfetto MCP servers | The reverse direction (LLMs analyzing Perfetto traces). Here a human looks. |
100
+ | One-off "LLM trace JSON" scripts | A maintained adapter with golden-fixture tests against schema drift, plus lane semantics. |
101
+
102
+ ## Limits & roadmap
103
+
104
+ - v0.1 supported Claude Code JSONL only. v0.2 introduces the vendor-neutral
105
+ **Agent Trace IR** ([docs/agent-trace-ir.md](docs/agent-trace-ir.md)): new agent
106
+ logs (Codex next, then OTel GenAI) enter as adapters into the same IR, so the
107
+ same viewer, lanes, and PerfettoSQL work across harnesses. Subagent/async
108
+ slices are also planned.
109
+ - Perfetto's JSON format is the legacy entry point; a proto-format exporter is on the roadmap.
110
+ - Multiple `sessionId`s in one file become multiple processes; per-subagent processes and
111
+ context-composition lanes (system prompt / files / MCP schemas) are future work.
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ python3 -m venv /tmp/a2p-venv && . /tmp/a2p-venv/bin/activate
117
+ pip install -e .
118
+ pip install pytest # test-only dependency; the package itself needs nothing
119
+ pytest
120
+ ```
121
+
122
+ Layout: `src/agent2perfetto/` — a three-stage pipeline (`parser` adapter →
123
+ `ir` Agent Trace IR → `trace` Perfetto emitter → `cli`), synthetic fixtures and
124
+ a frozen golden trace under `tests/fixtures/`, the example session and its
125
+ generated trace under `examples/`, and the IR schema at
126
+ [docs/agent-trace-ir.md](docs/agent-trace-ir.md).
127
+
128
+ ## License
129
+
130
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "agent2perfetto"
7
+ dynamic = ["version"]
8
+ description = "Convert agent session logs (Claude Code JSONL) into Perfetto/Chrome trace JSON for ui.perfetto.dev"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "agent2perfetto contributors" }]
14
+ keywords = ["perfetto", "trace", "claude-code", "llm", "agent", "observability"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Debuggers",
26
+ ]
27
+ dependencies = []
28
+
29
+ [project.scripts]
30
+ agent2perfetto = "agent2perfetto.cli:main"
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/ictechgy/agent2perfetto"
34
+
35
+ [tool.setuptools.dynamic]
36
+ version = { attr = "agent2perfetto.__version__" }
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+ addopts = "-q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """agent2perfetto: convert agent session logs into Perfetto trace JSON."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,89 @@
1
+ """Command-line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import subprocess
8
+ import sys
9
+ import webbrowser
10
+ from pathlib import Path
11
+
12
+ from . import __version__
13
+ from .ir import from_claude_session
14
+ from .parser import StrictParseError, parse_file
15
+ from .trace import build_trace
16
+
17
+ PERFETTO_UI_URL = "https://ui.perfetto.dev"
18
+
19
+
20
+ def main(argv=None) -> int:
21
+ parser = argparse.ArgumentParser(
22
+ prog="agent2perfetto",
23
+ description=(
24
+ "Convert a Claude Code session JSONL into a Perfetto/Chrome trace "
25
+ "JSON that loads in ui.perfetto.dev."
26
+ ),
27
+ )
28
+ parser.add_argument("input", help="Claude Code session log (.jsonl)")
29
+ parser.add_argument(
30
+ "-o",
31
+ "--output",
32
+ help="output trace path (default: <input stem>.perfetto.json next to the input)",
33
+ )
34
+ parser.add_argument(
35
+ "--open",
36
+ action="store_true",
37
+ help=f"open {PERFETTO_UI_URL} so you can drag and drop the trace (browser-local; never uploaded)",
38
+ )
39
+ parser.add_argument(
40
+ "--strict",
41
+ action="store_true",
42
+ help="fail on malformed or unusable lines instead of skipping them",
43
+ )
44
+ parser.add_argument("--version", action="version", version=f"agent2perfetto {__version__}")
45
+ args = parser.parse_args(argv)
46
+
47
+ src = Path(args.input)
48
+ if not src.is_file():
49
+ print(f"agent2perfetto: input file not found: {src}", file=sys.stderr)
50
+ return 1
51
+ dst = Path(args.output) if args.output else src.with_name(src.stem + ".perfetto.json")
52
+
53
+ try:
54
+ session = parse_file(src, strict=args.strict)
55
+ except StrictParseError as exc:
56
+ print(f"agent2perfetto: strict mode: {exc}", file=sys.stderr)
57
+ return 1
58
+ except OSError as exc:
59
+ print(f"agent2perfetto: cannot read {src}: {exc}", file=sys.stderr)
60
+ return 1
61
+
62
+ # Three-stage pipeline: adapter (parser) → IR → Perfetto emitter.
63
+ trace = build_trace(from_claude_session(session))
64
+ dst.write_text(json.dumps(trace, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
65
+
66
+ stats = session.stats
67
+ print(
68
+ f"agent2perfetto: parsed {len(session.records)} record(s) from {src} "
69
+ f"({stats.malformed_lines} malformed, {stats.skipped_records} skipped)"
70
+ )
71
+ print(f"agent2perfetto: wrote {len(trace['traceEvents'])} trace event(s) -> {dst}")
72
+
73
+ if args.open:
74
+ _open_viewer(dst)
75
+ return 0
76
+
77
+
78
+ def _open_viewer(trace_path: Path) -> None:
79
+ print(f"agent2perfetto: opening {PERFETTO_UI_URL} ...")
80
+ if sys.platform == "darwin":
81
+ subprocess.run(["open", PERFETTO_UI_URL], check=False)
82
+ else:
83
+ webbrowser.open(PERFETTO_UI_URL)
84
+ print(f"agent2perfetto: drag and drop this file into the Perfetto UI: {trace_path}")
85
+ print("agent2perfetto: the UI processes traces locally in your browser; nothing is uploaded.")
86
+
87
+
88
+ if __name__ == "__main__":
89
+ sys.exit(main())