pi-cloudflare-agent-tracing 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -24
- package/extensions/cloudflare-agent-tracing.ts +16 -45
- package/package.json +1 -1
- package/skills/cloudflare-agent-tracing/SKILL.md +27 -26
- package/skills/cloudflare-agent-tracing/references/report.example.json +4 -5
- package/skills/cloudflare-agent-tracing/scripts/render-report.mjs +143 -48
- package/skills/cloudflare-agent-tracing/scripts/render-report.test.mjs +49 -35
package/README.md
CHANGED
|
@@ -2,16 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
A Pi package and required Worker runtime adapter for content-safe tracing of Pi Durable applications running on Cloudflare.
|
|
4
4
|
|
|
5
|
-
It adds:
|
|
5
|
+
It adds one command:
|
|
6
6
|
|
|
7
7
|
```text
|
|
8
|
-
/
|
|
9
|
-
/agent-health
|
|
10
|
-
/agent-cost
|
|
11
|
-
/agent-eval
|
|
12
|
-
/agent-incident
|
|
8
|
+
/pi-trace [target] [--scope turn|thread|service] [--html]
|
|
13
9
|
```
|
|
14
10
|
|
|
11
|
+
One report combines the execution path, reliability, latency, usage, cost, fulfillment, recovery, anomalies, and evidence-linked improvements.
|
|
12
|
+
|
|
15
13
|
The package registers Cloudflare's official MCP server, applies an evidence-first investigation skill, and blocks `cloudflare_execute` unless every statically visible API request is an explicit `GET`.
|
|
16
14
|
|
|
17
15
|
## What it does
|
|
@@ -101,7 +99,7 @@ pi install /absolute/path/to/pi-cloudflare-agent-tracing
|
|
|
101
99
|
The same package can be installed from Git:
|
|
102
100
|
|
|
103
101
|
```bash
|
|
104
|
-
pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.
|
|
102
|
+
pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.4.0
|
|
105
103
|
```
|
|
106
104
|
|
|
107
105
|
Use a pinned release tag or commit for reproducible investigations.
|
|
@@ -124,22 +122,15 @@ If Cloudflare authentication is required:
|
|
|
124
122
|
Then run, for example:
|
|
125
123
|
|
|
126
124
|
```text
|
|
127
|
-
/
|
|
128
|
-
/
|
|
129
|
-
/
|
|
130
|
-
/
|
|
131
|
-
/
|
|
125
|
+
/pi-trace
|
|
126
|
+
/pi-trace my-worker --since 30m
|
|
127
|
+
/pi-trace <ray-or-trace-id>
|
|
128
|
+
/pi-trace <submission-or-task-id>
|
|
129
|
+
/pi-trace <conversation-id>
|
|
130
|
+
/pi-trace my-worker --since 6h --html
|
|
132
131
|
```
|
|
133
132
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
```text
|
|
137
|
-
/agent-health my-worker last 6h --html
|
|
138
|
-
/agent-trace ray-id --html
|
|
139
|
-
/agent-cost my-worker last 24h --html
|
|
140
|
-
/agent-eval submission 42 --html
|
|
141
|
-
/agent-incident my-worker last 30m --html
|
|
142
|
-
```
|
|
133
|
+
The target automatically selects the narrowest useful scope: request, Ray, trace, submission, and task identifiers produce a `turn` report; a conversation produces a `thread`; a Worker or deployment plus time range produces a `service` report. Use `--scope` only to override that inference.
|
|
143
134
|
|
|
144
135
|
Each saved report produces matching `.md`, content-free `.json`, and standalone `.html` files under the target project's `.pi/agent-tracing-reports/`. The HTML is printable, responsive, self-contained, uses no remote assets, and renders the same bounded evidence as the Markdown and JSON versions.
|
|
145
136
|
|
|
@@ -199,7 +190,7 @@ Deterministic evidence checks submission settlement, final answer presence, requ
|
|
|
199
190
|
|
|
200
191
|
## Human-review HTML reports
|
|
201
192
|
|
|
202
|
-
|
|
193
|
+
Every investigation uses one normalized Pi trace schema. See:
|
|
203
194
|
|
|
204
195
|
```text
|
|
205
196
|
skills/cloudflare-agent-tracing/references/report.example.json
|
|
@@ -213,7 +204,7 @@ node skills/cloudflare-agent-tracing/scripts/render-report.mjs \
|
|
|
213
204
|
--out path/to/report.html
|
|
214
205
|
```
|
|
215
206
|
|
|
216
|
-
If `--out` is omitted, the renderer writes beside the JSON input with an `.html` extension. The renderer validates
|
|
207
|
+
If `--out` is omitted, the renderer writes beside the JSON input with an `.html` extension. The renderer validates schema version 2, `kind: "pi-agent-trace"`, and the resolved `turn`, `thread`, or `service` scope. It caps CLI input at 2 MB, escapes every displayed value, and emits a restrictive content security policy. Unknown JSON fields are not rendered, reducing the risk of accidentally exposing unrelated diagnostic data.
|
|
217
208
|
|
|
218
209
|
Saved reports should remain content-free and should normally be ignored by Git:
|
|
219
210
|
|
|
@@ -284,4 +275,4 @@ test/extension.test.mjs
|
|
|
284
275
|
- Cloudflare's official MCP server
|
|
285
276
|
- Cloudflare Workers observability for production evidence
|
|
286
277
|
|
|
287
|
-
Pi Durable provides the
|
|
278
|
+
Pi Durable provides the task, recovery, model, usage, and durable outcome evidence required by the unified trace report.
|
|
@@ -31,38 +31,11 @@ const SKILL = "cloudflare-agent-tracing";
|
|
|
31
31
|
const CLOUDFLARE_EXECUTE_SUFFIX = "cloudflare_execute";
|
|
32
32
|
const METHOD_LITERAL = /\bmethod\s*:\s*["'`](GET|POST|PUT|PATCH|DELETE)["'`]/giu;
|
|
33
33
|
|
|
34
|
-
export const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
fallback: "the current project during the last 30 minutes",
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
name: "agent-health",
|
|
43
|
-
description: "Report Cloudflare agent health, errors, recovery, and latency",
|
|
44
|
-
mode: "health",
|
|
45
|
-
fallback: "the current project during the last 60 minutes",
|
|
46
|
-
},
|
|
47
|
-
{
|
|
48
|
-
name: "agent-cost",
|
|
49
|
-
description: "Analyze provider- or Pi-reported model usage and cost evidence",
|
|
50
|
-
mode: "cost",
|
|
51
|
-
fallback: "the current project during the last 24 hours",
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
name: "agent-eval",
|
|
55
|
-
description: "Evaluate whether an agent fulfilled a request",
|
|
56
|
-
mode: "evaluate",
|
|
57
|
-
fallback: "the target described in the current conversation",
|
|
58
|
-
},
|
|
59
|
-
{
|
|
60
|
-
name: "agent-incident",
|
|
61
|
-
description: "Produce an evidence-linked Cloudflare agent incident report",
|
|
62
|
-
mode: "incident",
|
|
63
|
-
fallback: "the current project during the last 30 minutes",
|
|
64
|
-
},
|
|
65
|
-
] as const;
|
|
34
|
+
export const command = {
|
|
35
|
+
name: "pi-trace",
|
|
36
|
+
description: "Trace a Pi agent across execution, health, cost, fulfillment, and recovery",
|
|
37
|
+
fallback: "the current project during the last 30 minutes",
|
|
38
|
+
} as const;
|
|
66
39
|
|
|
67
40
|
export const cloudflareExecuteIsReadOnly = (code: unknown): boolean => {
|
|
68
41
|
if (typeof code !== "string" || !code.includes("cloudflare.request")) return false;
|
|
@@ -91,17 +64,15 @@ export default function cloudflareAgentTracing(pi: PiExtensionApi): void {
|
|
|
91
64
|
};
|
|
92
65
|
});
|
|
93
66
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
});
|
|
106
|
-
}
|
|
67
|
+
pi.registerCommand(command.name, {
|
|
68
|
+
description: command.description,
|
|
69
|
+
handler: (args, context) => {
|
|
70
|
+
const target = args.trim() || command.fallback;
|
|
71
|
+
pi.sendUserMessage(`/skill:${SKILL} ${target}`, {
|
|
72
|
+
...(context.isIdle() ? {} : { deliverAs: "followUp" as const }),
|
|
73
|
+
expandPromptTemplates: true,
|
|
74
|
+
});
|
|
75
|
+
if (!context.isIdle()) context.ui.notify(`${command.name} queued`, "info");
|
|
76
|
+
},
|
|
77
|
+
});
|
|
107
78
|
}
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@ description: Investigate instrumented Pi Durable applications on Cloudflare usin
|
|
|
4
4
|
compatibility: Requires Node.js 22+, the pi-cloudflare-agent-tracing runtime dependency wired into every production Harness.open(), Workers tracing enabled, and Cloudflare available through the official MCP.
|
|
5
5
|
metadata:
|
|
6
6
|
author: oskarcode
|
|
7
|
-
version: "0.
|
|
7
|
+
version: "0.4.0"
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
# Cloudflare agent tracing
|
|
@@ -15,7 +15,15 @@ Resolve relative paths in this skill against the directory containing this `SKIL
|
|
|
15
15
|
|
|
16
16
|
## Inputs
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Treat the arguments as one target plus optional controls. A target can be a Worker, request/Ray/trace/submission/task/conversation ID, deployment, or bounded time range. `--html` requests a saved human-review bundle. `--scope turn|thread|service` overrides automatic scope selection. If the target is ambiguous, profile the local project before asking one focused question.
|
|
19
|
+
|
|
20
|
+
Infer one report scope:
|
|
21
|
+
|
|
22
|
+
- **turn** — one request, trace, submission, or task and its nested Pi work;
|
|
23
|
+
- **thread** — related turns for one conversation;
|
|
24
|
+
- **service** — one Worker or deployment over a bounded time window.
|
|
25
|
+
|
|
26
|
+
Use the narrowest scope supported by exact identifiers. A Worker plus time range is `service`; a conversation is `thread`; request, Ray, trace, submission, and task IDs are `turn`. Never make the user choose separate health, cost, evaluation, or incident modes.
|
|
19
27
|
|
|
20
28
|
## Start locally
|
|
21
29
|
|
|
@@ -47,42 +55,35 @@ Prefer exact joins in this order: trace ID, Ray ID, deployment/version ID, reque
|
|
|
47
55
|
|
|
48
56
|
For Dynamic Workers, inspect dispatcher and dispatched Worker separately and verify propagation. For Durable Objects, inspect RPC/invocation evidence and bounded application diagnostics. Never invent or expose arbitrary remote SQL or transcript endpoints.
|
|
49
57
|
|
|
50
|
-
##
|
|
58
|
+
## Unified trace analysis
|
|
51
59
|
|
|
52
|
-
|
|
60
|
+
Produce one report from the same correlated evidence. Every report includes the sections below when evidence exists and marks unavailable sections explicitly.
|
|
53
61
|
|
|
54
|
-
|
|
62
|
+
### Execution path
|
|
55
63
|
|
|
56
|
-
|
|
64
|
+
Reconstruct edge request, Worker, Durable Object/RPC, Pi submission or task, model calls, tools/subrequests, storage/commit, recovery, and streaming. Preserve parent-child relationships; label timestamp-only joins as inferences.
|
|
57
65
|
|
|
58
|
-
|
|
66
|
+
### Reliability and performance
|
|
59
67
|
|
|
60
|
-
|
|
68
|
+
Measure outcomes, exceptions, cancellations, latency, CPU/wall time, deployment boundaries, authorization failures, task faults, retries, recovery, and alarm gaps. Distinguish successful Pi Durable recovery from terminal failure and identify the largest evidenced bottleneck.
|
|
61
69
|
|
|
62
|
-
|
|
70
|
+
### Usage and cost
|
|
63
71
|
|
|
64
|
-
|
|
72
|
+
Use provider- or Pi-reported tokens and `cost.total` when present. Label catalog estimates separately. Never present a precise total from sampled or incomplete telemetry.
|
|
65
73
|
|
|
66
|
-
|
|
74
|
+
### Outcome and fulfillment
|
|
75
|
+
|
|
76
|
+
Tracing cannot establish semantic fulfillment by itself. For an exact turn with normalized evidence, run:
|
|
67
77
|
|
|
68
78
|
```bash
|
|
69
79
|
node <skill-directory>/scripts/evaluate.mjs /tmp/agent-evaluation.json
|
|
70
80
|
```
|
|
71
81
|
|
|
72
|
-
Use `references/evaluation-input.example.json` as the content-free contract. Check
|
|
73
|
-
|
|
74
|
-
- submission settled `done`, not `unanswered`;
|
|
75
|
-
- final committed answer exists;
|
|
76
|
-
- required tools succeeded;
|
|
77
|
-
- required durable side effects exist;
|
|
78
|
-
- explicit constraints were met;
|
|
79
|
-
- no terminal failure invalidated the outcome.
|
|
80
|
-
|
|
81
|
-
Only use semantic evidence when the user authorized content inspection and an existing authorized application path provides it. If semantic evidence is unavailable, return `indeterminate` when appropriate.
|
|
82
|
+
Use `references/evaluation-input.example.json` as the content-free contract. Check settlement, final committed answer, required tools, required durable effects, explicit constraints, and terminal failures. Only use semantic evidence when the user authorized content inspection and an existing authorized application path provides it. Otherwise report `indeterminate` when appropriate.
|
|
82
83
|
|
|
83
|
-
###
|
|
84
|
+
### Anomalies and improvements
|
|
84
85
|
|
|
85
|
-
|
|
86
|
+
Explain errors, retries, recovery, user impact, and prioritized evidence-linked improvements. Do not perform repairs. An ordinary successful trace still includes a short anomaly section stating what was checked.
|
|
86
87
|
|
|
87
88
|
## Optional application evidence
|
|
88
89
|
|
|
@@ -128,9 +129,9 @@ Distinguish observations from hypotheses. Every conclusion must name its evidenc
|
|
|
128
129
|
Always return the concise report in the conversation. When the command includes `--html`, or the user asks to save the report:
|
|
129
130
|
|
|
130
131
|
1. Create `.pi/agent-tracing-reports/` under the target project.
|
|
131
|
-
2. Use one collision-resistant basename: `<UTC timestamp
|
|
132
|
+
2. Use one collision-resistant basename: `<UTC timestamp>-pi-trace-<safe target slug>`.
|
|
132
133
|
3. Write the concise Markdown report to `<basename>.md`.
|
|
133
|
-
4. Write normalized, content-free JSON to `<basename>.json` using `references/report.example.json` as the schema example. Use `schemaVersion:
|
|
134
|
+
4. Write normalized, content-free JSON to `<basename>.json` using `references/report.example.json` as the schema example. Use `schemaVersion: 2`, `kind: "pi-agent-trace"`, and the resolved `scope.level`. Omit unavailable sections rather than inventing values.
|
|
134
135
|
5. Render the standalone HTML report:
|
|
135
136
|
|
|
136
137
|
```bash
|
|
@@ -141,4 +142,4 @@ node <skill-directory>/scripts/render-report.mjs \
|
|
|
141
142
|
|
|
142
143
|
6. Return all three paths and state that the HTML contains the same bounded evidence, not additional private data.
|
|
143
144
|
|
|
144
|
-
The HTML renderer
|
|
145
|
+
The HTML renderer presents the unified trace, is printable, embeds no remote assets, applies a restrictive content security policy, and escapes all report values. Never put prompts, answers, thinking, tool arguments/results, credentials, headers, attachment contents, or raw transcript text in any report format. Recommend ignoring `.pi/agent-tracing-reports/` in Git.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
|
-
"schemaVersion":
|
|
3
|
-
"
|
|
2
|
+
"schemaVersion": 2,
|
|
3
|
+
"kind": "pi-agent-trace",
|
|
4
4
|
"title": "Checkout agent incident",
|
|
5
5
|
"generatedAt": "2026-12-02T17:30:00Z",
|
|
6
6
|
"verdict": {
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"summary": "Requests recovered after a bounded model-provider failure, but two submissions were cancelled."
|
|
10
10
|
},
|
|
11
11
|
"scope": {
|
|
12
|
+
"level": "service",
|
|
12
13
|
"worker": "checkout-agent",
|
|
13
14
|
"environment": "production",
|
|
14
15
|
"deployment": "version-id",
|
|
@@ -57,9 +58,7 @@
|
|
|
57
58
|
"score": 100,
|
|
58
59
|
"semanticEvidence": "unavailable",
|
|
59
60
|
"summary": "Deterministic checks passed; semantic request content was not inspected.",
|
|
60
|
-
"checks": [
|
|
61
|
-
{ "name": "submission settled", "passed": true, "evidence": "E3" }
|
|
62
|
-
]
|
|
61
|
+
"checks": [{ "name": "submission settled", "passed": true, "evidence": "E3" }]
|
|
63
62
|
},
|
|
64
63
|
"durableState": [
|
|
65
64
|
{
|
|
@@ -3,7 +3,8 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
3
3
|
import { dirname, extname, resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
|
|
6
|
-
const
|
|
6
|
+
const REPORT_KIND = "pi-agent-trace";
|
|
7
|
+
const SCOPE_LEVELS = new Set(["turn", "thread", "service"]);
|
|
7
8
|
const MAX_INPUT_BYTES = 2_000_000;
|
|
8
9
|
|
|
9
10
|
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
|
@@ -26,12 +27,13 @@ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
|
|
26
27
|
|
|
27
28
|
export function renderReportHtml(report) {
|
|
28
29
|
validateReport(report);
|
|
29
|
-
const
|
|
30
|
+
const scope = asObject(report.scope);
|
|
31
|
+
const level = text(scope.level, "service");
|
|
30
32
|
const verdict = asObject(report.verdict);
|
|
31
33
|
const verdictLabel = text(verdict.label, "Indeterminate");
|
|
32
34
|
const confidence = text(verdict.confidence, "not stated");
|
|
33
35
|
const generatedAt = text(report.generatedAt, new Date().toISOString());
|
|
34
|
-
const title = text(report.title,
|
|
36
|
+
const title = text(report.title, "Pi agent trace");
|
|
35
37
|
const sections = [
|
|
36
38
|
renderScope(report.scope),
|
|
37
39
|
renderMetrics(report.metrics),
|
|
@@ -64,7 +66,7 @@ export function renderReportHtml(report) {
|
|
|
64
66
|
<body>
|
|
65
67
|
<main>
|
|
66
68
|
<header class="hero">
|
|
67
|
-
<p class="eyebrow">${escapeHtml(
|
|
69
|
+
<p class="eyebrow">${escapeHtml(level)} · Pi agent trace</p>
|
|
68
70
|
<h1>${escapeHtml(title)}</h1>
|
|
69
71
|
<p class="subtitle">${escapeHtml(text(verdict.summary, "Evidence-backed report for human review."))}</p>
|
|
70
72
|
<div class="hero-grid">
|
|
@@ -82,53 +84,81 @@ ${sections.join("\n")}
|
|
|
82
84
|
}
|
|
83
85
|
|
|
84
86
|
export function validateReport(report) {
|
|
85
|
-
if (!report || typeof report !== "object" || Array.isArray(report))
|
|
86
|
-
|
|
87
|
-
if (report.
|
|
87
|
+
if (!report || typeof report !== "object" || Array.isArray(report))
|
|
88
|
+
throw new Error("Report must be a JSON object");
|
|
89
|
+
if (report.kind !== REPORT_KIND) throw new Error(`Report kind must be ${REPORT_KIND}`);
|
|
90
|
+
if (report.schemaVersion !== 2) throw new Error("Unsupported report schemaVersion");
|
|
91
|
+
const level = asObject(report.scope).level;
|
|
92
|
+
if (!SCOPE_LEVELS.has(level))
|
|
93
|
+
throw new Error(`Report scope.level must be one of: ${[...SCOPE_LEVELS].join(", ")}`);
|
|
88
94
|
}
|
|
89
95
|
|
|
90
96
|
function renderScope(scopeValue) {
|
|
91
97
|
const scope = asObject(scopeValue);
|
|
92
98
|
const entries = [
|
|
93
|
-
["
|
|
94
|
-
["
|
|
99
|
+
["Level", scope.level],
|
|
100
|
+
["Worker", scope.worker],
|
|
101
|
+
["Environment", scope.environment],
|
|
102
|
+
["Deployment", scope.deployment],
|
|
103
|
+
["Target", scope.target],
|
|
104
|
+
["Start UTC", scope.startUtc],
|
|
105
|
+
["End UTC", scope.endUtc],
|
|
95
106
|
].filter(([, value]) => present(value));
|
|
96
107
|
if (!entries.length) return "";
|
|
97
|
-
return section(
|
|
108
|
+
return section(
|
|
109
|
+
"Scope",
|
|
110
|
+
`<div class="scope-grid">${entries.map(([label, value]) => `<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value mono">${escapeHtml(text(value))}</span></div>`).join("")}</div>`,
|
|
111
|
+
);
|
|
98
112
|
}
|
|
99
113
|
|
|
100
114
|
function renderMetrics(metrics) {
|
|
101
115
|
if (!Array.isArray(metrics) || metrics.length === 0) return "";
|
|
102
|
-
const cards = metrics
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
116
|
+
const cards = metrics
|
|
117
|
+
.slice(0, 50)
|
|
118
|
+
.map((metric) => {
|
|
119
|
+
const item = asObject(metric);
|
|
120
|
+
const value = [text(item.value, "—"), text(item.unit)].filter(Boolean).join(" ");
|
|
121
|
+
return `<div class="stat"><span class="label">${escapeHtml(text(item.label, "Metric"))}</span><span class="value ${statusClass(item.status)}">${escapeHtml(value)}</span>${present(item.detail) ? `<span class="count">${escapeHtml(text(item.detail))}</span>` : ""}</div>`;
|
|
122
|
+
})
|
|
123
|
+
.join("");
|
|
107
124
|
return section("Key metrics", `<div class="metric-grid">${cards}</div>`, metrics.length);
|
|
108
125
|
}
|
|
109
126
|
|
|
110
127
|
function renderRequestPath(items) {
|
|
111
128
|
if (!Array.isArray(items) || items.length === 0) return "";
|
|
112
|
-
const timeline = items
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
129
|
+
const timeline = items
|
|
130
|
+
.slice(0, 100)
|
|
131
|
+
.map((entry) => {
|
|
132
|
+
const item = asObject(entry);
|
|
133
|
+
return `<div class="timeline-item"><span class="dot"></span><h3>${escapeHtml(text(item.stage, "Stage"))} <span class="${statusClass(item.status)}">${escapeHtml(text(item.status))}</span></h3>${present(item.detail) ? `<p>${escapeHtml(text(item.detail))}</p>` : ""}<div class="meta">${chips([item.timestampUtc, duration(item.durationMs), ...array(item.evidenceIds)])}</div></div>`;
|
|
134
|
+
})
|
|
135
|
+
.join("");
|
|
116
136
|
return section("Request path", `<div class="timeline">${timeline}</div>`, items.length);
|
|
117
137
|
}
|
|
118
138
|
|
|
119
139
|
function renderFailures(items) {
|
|
120
140
|
if (!Array.isArray(items) || items.length === 0) return "";
|
|
121
|
-
return section(
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
141
|
+
return section(
|
|
142
|
+
"Failures and recovery",
|
|
143
|
+
`<div class="cards">${items
|
|
144
|
+
.slice(0, 100)
|
|
145
|
+
.map((entry) => {
|
|
146
|
+
const item = asObject(entry);
|
|
147
|
+
return `<article class="card"><h3 class="${statusClass(item.severity)}">${escapeHtml(text(item.title, "Failure"))}</h3>${paragraph(item.detail)}${present(item.recovery) ? `<p><strong>Recovery:</strong> ${escapeHtml(text(item.recovery))}</p>` : ""}<div class="meta">${chips([item.severity, item.status, ...array(item.evidenceIds)])}</div></article>`;
|
|
148
|
+
})
|
|
149
|
+
.join("")}</div>`,
|
|
150
|
+
items.length,
|
|
151
|
+
);
|
|
125
152
|
}
|
|
126
153
|
|
|
127
154
|
function renderLatency(value) {
|
|
128
155
|
const latency = asObject(value);
|
|
129
156
|
const metrics = array(latency.metrics);
|
|
130
157
|
if (!present(latency.summary) && metrics.length === 0) return "";
|
|
131
|
-
return section(
|
|
158
|
+
return section(
|
|
159
|
+
"Latency",
|
|
160
|
+
`${paragraph(latency.summary)}${renderSimpleTable(metrics, ["label", "value", "unit", "source"])}`,
|
|
161
|
+
);
|
|
132
162
|
}
|
|
133
163
|
|
|
134
164
|
function renderCost(value) {
|
|
@@ -137,9 +167,19 @@ function renderCost(value) {
|
|
|
137
167
|
if (!present(cost.total) && !present(cost.summary) && items.length === 0) return "";
|
|
138
168
|
const overview = `<div class="scope-grid">${[
|
|
139
169
|
["Total", [text(cost.currency), text(cost.total)].filter(Boolean).join(" ")],
|
|
140
|
-
["Source", cost.source],
|
|
141
|
-
|
|
142
|
-
|
|
170
|
+
["Source", cost.source],
|
|
171
|
+
["Completeness", cost.completeness],
|
|
172
|
+
]
|
|
173
|
+
.filter(([, item]) => present(item))
|
|
174
|
+
.map(
|
|
175
|
+
([label, item]) =>
|
|
176
|
+
`<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value">${escapeHtml(text(item))}</span></div>`,
|
|
177
|
+
)
|
|
178
|
+
.join("")}</div>`;
|
|
179
|
+
return section(
|
|
180
|
+
"Cost",
|
|
181
|
+
`${paragraph(cost.summary)}${overview}${renderSimpleTable(items, ["label", "model", "tokens", "cost", "source"])}`,
|
|
182
|
+
);
|
|
143
183
|
}
|
|
144
184
|
|
|
145
185
|
function renderFulfillment(value) {
|
|
@@ -147,39 +187,86 @@ function renderFulfillment(value) {
|
|
|
147
187
|
const checks = array(fulfillment.checks);
|
|
148
188
|
if (!present(fulfillment.verdict) && checks.length === 0) return "";
|
|
149
189
|
const header = `<div class="scope-grid">${[
|
|
150
|
-
["Verdict", fulfillment.verdict],
|
|
151
|
-
|
|
152
|
-
|
|
190
|
+
["Verdict", fulfillment.verdict],
|
|
191
|
+
["Score", fulfillment.score],
|
|
192
|
+
["Semantic evidence", fulfillment.semanticEvidence],
|
|
193
|
+
]
|
|
194
|
+
.filter(([, item]) => present(item))
|
|
195
|
+
.map(
|
|
196
|
+
([label, item]) =>
|
|
197
|
+
`<div class="scope-item"><span class="label">${escapeHtml(label)}</span><span class="value ${statusClass(item)}">${escapeHtml(text(item))}</span></div>`,
|
|
198
|
+
)
|
|
199
|
+
.join("")}</div>`;
|
|
200
|
+
const rows = checks.length
|
|
201
|
+
? `<div class="table-wrap"><table><thead><tr><th>Check</th><th>Result</th><th>Evidence</th></tr></thead><tbody>${checks
|
|
202
|
+
.slice(0, 100)
|
|
203
|
+
.map((entry) => {
|
|
204
|
+
const item = asObject(entry);
|
|
205
|
+
const passed = item.passed === true;
|
|
206
|
+
return `<tr><td>${escapeHtml(text(item.name, "Check"))}</td><td><span class="check ${passed ? "pass" : "fail"}">${passed ? "Passed" : "Failed"}</span></td><td>${escapeHtml(text(item.evidence, "—"))}</td></tr>`;
|
|
207
|
+
})
|
|
208
|
+
.join("")}</tbody></table></div>`
|
|
209
|
+
: "";
|
|
153
210
|
return section("Fulfillment", `${paragraph(fulfillment.summary)}${header}${rows}`);
|
|
154
211
|
}
|
|
155
212
|
|
|
156
213
|
function renderDurableState(items) {
|
|
157
214
|
if (!Array.isArray(items) || items.length === 0) return "";
|
|
158
|
-
return section(
|
|
215
|
+
return section(
|
|
216
|
+
"Durable state evidence",
|
|
217
|
+
renderSimpleTable(items, ["owner", "record", "status", "summary", "evidenceId"]),
|
|
218
|
+
items.length,
|
|
219
|
+
);
|
|
159
220
|
}
|
|
160
221
|
|
|
161
222
|
function renderRecommendations(items) {
|
|
162
223
|
if (!Array.isArray(items) || items.length === 0) return "";
|
|
163
|
-
return section(
|
|
224
|
+
return section(
|
|
225
|
+
"Recommendations",
|
|
226
|
+
`<div class="cards">${items
|
|
227
|
+
.slice(0, 100)
|
|
228
|
+
.map((entry, index) => {
|
|
229
|
+
const item = asObject(entry);
|
|
230
|
+
return `<article class="card"><h3>${index + 1}. ${escapeHtml(text(item.title, "Recommendation"))}</h3>${paragraph(item.detail)}<div class="meta">${chips([item.priority, item.owner, item.evidenceId])}</div></article>`;
|
|
231
|
+
})
|
|
232
|
+
.join("")}</div>`,
|
|
233
|
+
items.length,
|
|
234
|
+
);
|
|
164
235
|
}
|
|
165
236
|
|
|
166
237
|
function renderEvidence(items) {
|
|
167
238
|
if (!Array.isArray(items) || items.length === 0) return "";
|
|
168
|
-
const details = items
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
239
|
+
const details = items
|
|
240
|
+
.slice(0, 200)
|
|
241
|
+
.map((entry) => {
|
|
242
|
+
const item = asObject(entry);
|
|
243
|
+
return `<details><summary><span class="mono">${escapeHtml(text(item.id, "evidence"))}</span> · ${escapeHtml(text(item.summary, item.type ?? "Evidence"))}</summary>${paragraph(item.detail)}<div class="meta">${chips([item.type, item.source, item.observedAt, item.correlation])}</div>${present(item.limitation) ? `<p><strong>Limitation:</strong> ${escapeHtml(text(item.limitation))}</p>` : ""}</details>`;
|
|
244
|
+
})
|
|
245
|
+
.join("");
|
|
172
246
|
return section("Evidence", details, items.length);
|
|
173
247
|
}
|
|
174
248
|
|
|
175
249
|
function renderLimitations(items) {
|
|
176
250
|
if (!Array.isArray(items) || items.length === 0) return "";
|
|
177
|
-
return section(
|
|
251
|
+
return section(
|
|
252
|
+
"Limitations",
|
|
253
|
+
`<div class="cards">${items
|
|
254
|
+
.slice(0, 100)
|
|
255
|
+
.map((item) => `<div class="card">${escapeHtml(text(item))}</div>`)
|
|
256
|
+
.join("")}</div>`,
|
|
257
|
+
items.length,
|
|
258
|
+
);
|
|
178
259
|
}
|
|
179
260
|
|
|
180
261
|
function renderSimpleTable(items, keys) {
|
|
181
262
|
if (!items.length) return "";
|
|
182
|
-
return `<div class="table-wrap"><table><thead><tr>${keys.map((key) => `<th>${escapeHtml(titleCase(key))}</th>`).join("")}</tr></thead><tbody>${items
|
|
263
|
+
return `<div class="table-wrap"><table><thead><tr>${keys.map((key) => `<th>${escapeHtml(titleCase(key))}</th>`).join("")}</tr></thead><tbody>${items
|
|
264
|
+
.slice(0, 100)
|
|
265
|
+
.map((entry) => {
|
|
266
|
+
const item = asObject(entry);
|
|
267
|
+
return `<tr>${keys.map((key) => `<td>${escapeHtml(text(item[key], "—"))}</td>`).join("")}</tr>`;
|
|
268
|
+
})
|
|
269
|
+
.join("")}</tbody></table></div>`;
|
|
183
270
|
}
|
|
184
271
|
|
|
185
272
|
function section(title, body, count) {
|
|
@@ -195,7 +282,10 @@ function paragraph(value) {
|
|
|
195
282
|
}
|
|
196
283
|
|
|
197
284
|
function chips(values) {
|
|
198
|
-
return values
|
|
285
|
+
return values
|
|
286
|
+
.filter(present)
|
|
287
|
+
.map((value) => `<span class="chip">${escapeHtml(text(value))}</span>`)
|
|
288
|
+
.join("");
|
|
199
289
|
}
|
|
200
290
|
|
|
201
291
|
function duration(value) {
|
|
@@ -204,20 +294,25 @@ function duration(value) {
|
|
|
204
294
|
|
|
205
295
|
function statusClass(value) {
|
|
206
296
|
const normalized = text(value).toLowerCase();
|
|
207
|
-
if (/fulfilled|healthy|success|succeeded|done|recovered|verified|low|complete/.test(normalized))
|
|
297
|
+
if (/fulfilled|healthy|success|succeeded|done|recovered|verified|low|complete/.test(normalized))
|
|
298
|
+
return "status-good";
|
|
208
299
|
if (/fail|error|critical|high|not_fulfilled|unhealthy/.test(normalized)) return "status-bad";
|
|
209
|
-
if (/partial|warning|warn|indeterminate|medium|incomplete|cancel/.test(normalized))
|
|
300
|
+
if (/partial|warning|warn|indeterminate|medium|incomplete|cancel/.test(normalized))
|
|
301
|
+
return "status-warn";
|
|
210
302
|
return "";
|
|
211
303
|
}
|
|
212
304
|
|
|
213
305
|
function formatTimestamp(value) {
|
|
214
306
|
const date = new Date(value);
|
|
215
|
-
return Number.isNaN(date.valueOf())
|
|
307
|
+
return Number.isNaN(date.valueOf())
|
|
308
|
+
? value
|
|
309
|
+
: date.toISOString().replace("T", " ").replace(".000Z", " UTC");
|
|
216
310
|
}
|
|
217
311
|
|
|
218
312
|
function parseArguments(args) {
|
|
219
313
|
const input = args[0];
|
|
220
|
-
if (!input || input === "--help")
|
|
314
|
+
if (!input || input === "--help")
|
|
315
|
+
throw new Error("Usage: node render-report.mjs <report.json> [--out <report.html>]");
|
|
221
316
|
const outIndex = args.indexOf("--out");
|
|
222
317
|
if (outIndex >= 0 && !args[outIndex + 1]) throw new Error("--out requires a path");
|
|
223
318
|
return { input: resolve(input), output: outIndex >= 0 ? args[outIndex + 1] : undefined };
|
|
@@ -248,11 +343,11 @@ function text(value, fallback = "") {
|
|
|
248
343
|
}
|
|
249
344
|
|
|
250
345
|
function escapeHtml(value) {
|
|
251
|
-
return text(value).replace(
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
346
|
+
return text(value).replace(
|
|
347
|
+
/[&<>"']/g,
|
|
348
|
+
(character) =>
|
|
349
|
+
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[character],
|
|
350
|
+
);
|
|
256
351
|
}
|
|
257
352
|
|
|
258
353
|
function titleCase(value) {
|
|
@@ -1,42 +1,52 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
2
3
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
4
|
import { tmpdir } from "node:os";
|
|
4
5
|
import { join } from "node:path";
|
|
5
|
-
import { spawnSync } from "node:child_process";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
7
6
|
import test from "node:test";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { renderReportHtml, validateReport } from "./render-report.mjs";
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
function report(overrides = {}) {
|
|
11
|
+
return {
|
|
12
|
+
schemaVersion: 2,
|
|
13
|
+
kind: "pi-agent-trace",
|
|
14
|
+
title: "Pi agent trace",
|
|
15
|
+
generatedAt: "2026-12-02T17:30:00Z",
|
|
16
|
+
verdict: { label: "indeterminate", confidence: "medium", summary: "Bounded evidence." },
|
|
17
|
+
scope: { level: "turn", worker: "portable-worker", startUtc: "2026-12-02T17:00:00Z" },
|
|
18
|
+
evidence: [{ id: "E1", type: "trace", summary: "Request observed" }],
|
|
19
|
+
limitations: ["Sampling enabled"],
|
|
20
|
+
...overrides,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
test("renders one unified Pi agent trace report", () => {
|
|
25
|
+
const html = renderReportHtml(report());
|
|
11
26
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
verdict: { label: "indeterminate", confidence: "medium", summary: "Bounded evidence." },
|
|
20
|
-
scope: { worker: "portable-worker", startUtc: "2026-12-02T17:00:00Z" },
|
|
21
|
-
evidence: [{ id: "E1", type: "trace", summary: "Request observed" }],
|
|
22
|
-
limitations: ["Sampling enabled"],
|
|
23
|
-
});
|
|
27
|
+
assert.match(html, /<!doctype html>/);
|
|
28
|
+
assert.match(html, /Content-Security-Policy/);
|
|
29
|
+
assert.match(html, /Pi agent trace/);
|
|
30
|
+
assert.match(html, /portable-worker/);
|
|
31
|
+
assert.match(html, /Request observed/);
|
|
32
|
+
assert.match(html, /turn · Pi agent trace/);
|
|
33
|
+
});
|
|
24
34
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
assert.match(html,
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
35
|
+
test("supports turn, thread, and service scopes", () => {
|
|
36
|
+
for (const level of ["turn", "thread", "service"]) {
|
|
37
|
+
const html = renderReportHtml(report({ scope: { level } }));
|
|
38
|
+
assert.match(html, new RegExp(`${level} · Pi agent trace`));
|
|
39
|
+
}
|
|
40
|
+
});
|
|
32
41
|
|
|
33
42
|
test("escapes report values instead of emitting executable markup", () => {
|
|
34
|
-
const html = renderReportHtml(
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
43
|
+
const html = renderReportHtml(
|
|
44
|
+
report({
|
|
45
|
+
title: "<script>alert(1)</script>",
|
|
46
|
+
verdict: { label: "partial", summary: "<img src=x onerror=alert(1)>" },
|
|
47
|
+
evidence: [{ id: "E1", summary: "<b>unsafe</b>" }],
|
|
48
|
+
}),
|
|
49
|
+
);
|
|
40
50
|
|
|
41
51
|
assert.doesNotMatch(html, /<script>alert/);
|
|
42
52
|
assert.doesNotMatch(html, /<img src=x/);
|
|
@@ -44,22 +54,26 @@ test("escapes report values instead of emitting executable markup", () => {
|
|
|
44
54
|
assert.match(html, /<b>unsafe<\/b>/);
|
|
45
55
|
});
|
|
46
56
|
|
|
47
|
-
test("rejects unknown
|
|
48
|
-
assert.throws(
|
|
49
|
-
|
|
57
|
+
test("rejects legacy modes, unknown scopes, and schema versions", () => {
|
|
58
|
+
assert.throws(
|
|
59
|
+
() => validateReport({ ...report(), kind: undefined, mode: "health" }),
|
|
60
|
+
/Report kind/,
|
|
61
|
+
);
|
|
62
|
+
assert.throws(() => validateReport(report({ scope: { level: "repair" } })), /scope.level/);
|
|
63
|
+
assert.throws(() => validateReport(report({ schemaVersion: 1 })), /schemaVersion/);
|
|
50
64
|
});
|
|
51
65
|
|
|
52
66
|
test("CLI writes the report beside JSON by default", async () => {
|
|
53
67
|
const directory = await mkdtemp(join(tmpdir(), "agent-report-"));
|
|
54
68
|
try {
|
|
55
|
-
const input = join(directory, "
|
|
56
|
-
await writeFile(input, JSON.stringify({
|
|
69
|
+
const input = join(directory, "trace.json");
|
|
70
|
+
await writeFile(input, JSON.stringify(report({ title: "Human trace review" })));
|
|
57
71
|
const script = fileURLToPath(new URL("./render-report.mjs", import.meta.url));
|
|
58
72
|
const result = spawnSync(process.execPath, [script, input], { encoding: "utf8" });
|
|
59
73
|
assert.equal(result.status, 0, result.stderr);
|
|
60
|
-
const output = join(directory, "
|
|
74
|
+
const output = join(directory, "trace.html");
|
|
61
75
|
assert.equal(result.stdout.trim(), output);
|
|
62
|
-
assert.match(await readFile(output, "utf8"), /
|
|
76
|
+
assert.match(await readFile(output, "utf8"), /Human trace review/);
|
|
63
77
|
} finally {
|
|
64
78
|
await rm(directory, { recursive: true, force: true });
|
|
65
79
|
}
|