pi-cloudflare-agent-tracing 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oskar Ablimit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,251 @@
1
- # Temporary Holding Version
1
+ # Pi Cloudflare Agent Tracing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A dependency-free Pi package for read-only investigation of Pi Durable and other agent applications running on Cloudflare.
4
+
5
+ It adds:
6
+
7
+ ```text
8
+ /agent-trace
9
+ /agent-health
10
+ /agent-cost
11
+ /agent-eval
12
+ /agent-incident
13
+ ```
14
+
15
+ 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
+
17
+ ## What it does
18
+
19
+ - Profiles `wrangler.jsonc`, `wrangler.json`, and `wrangler.toml` projects.
20
+ - Supports a single Worker or a monorepo with multiple Wrangler configurations.
21
+ - Discovers `Harness.open()` without assuming a source path.
22
+ - Distinguishes Workers platform tracing from custom Pi telemetry.
23
+ - Queries deployments, versions, bindings, logs, traces, and bounded metrics.
24
+ - Evaluates deterministic fulfillment from normalized, content-free evidence.
25
+ - Summarizes Pi Durable-shaped context exports without transcript or tool content.
26
+ - Includes an optional Cloudflare custom-span adapter for future runtime integration.
27
+
28
+ It does **not** deploy, repair state, mutate Cloudflare resources, or create diagnostic endpoints.
29
+
30
+ ## Install
31
+
32
+ ### Install from npm
33
+
34
+ ```bash
35
+ pi install npm:pi-cloudflare-agent-tracing
36
+ ```
37
+
38
+ The `pi-package` keyword makes the published package eligible for discovery in the [Pi package gallery](https://pi.dev/packages).
39
+
40
+ ### Try from a local checkout
41
+
42
+ ```bash
43
+ pi -e /absolute/path/to/pi-cloudflare-agent-tracing
44
+ ```
45
+
46
+ ### Install for one project
47
+
48
+ From the target project:
49
+
50
+ ```bash
51
+ pi install --local /absolute/path/to/pi-cloudflare-agent-tracing
52
+ ```
53
+
54
+ This writes the package declaration to the target project's `.pi/settings.json`.
55
+
56
+ ### Install for your user
57
+
58
+ ```bash
59
+ pi install /absolute/path/to/pi-cloudflare-agent-tracing
60
+ ```
61
+
62
+ The same package can be installed from Git:
63
+
64
+ ```bash
65
+ pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.2.0
66
+ ```
67
+
68
+ Use a pinned release tag or commit for reproducible investigations.
69
+
70
+ ## Start
71
+
72
+ Inside Pi:
73
+
74
+ ```text
75
+ /reload
76
+ /mcp
77
+ ```
78
+
79
+ If Cloudflare authentication is required:
80
+
81
+ ```text
82
+ /mcp login cloudflare
83
+ ```
84
+
85
+ Then run, for example:
86
+
87
+ ```text
88
+ /agent-health
89
+ /agent-trace my-worker last 30m
90
+ /agent-cost my-worker last 24h
91
+ /agent-eval submission 42
92
+ /agent-incident my-worker last 15m
93
+ ```
94
+
95
+ Add `--html` to save a detailed human-review bundle:
96
+
97
+ ```text
98
+ /agent-health my-worker last 6h --html
99
+ /agent-trace ray-id --html
100
+ /agent-cost my-worker last 24h --html
101
+ /agent-eval submission 42 --html
102
+ /agent-incident my-worker last 30m --html
103
+ ```
104
+
105
+ 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.
106
+
107
+ ## How it works
108
+
109
+ ```text
110
+ slash command
111
+ → extension dispatches /skill:cloudflare-agent-tracing
112
+ → skill profiles the selected local Worker
113
+ → Cloudflare MCP performs bounded GET queries
114
+ → optional authorized diagnostics provide durable evidence
115
+ → evaluator produces a content-free verdict
116
+ ```
117
+
118
+ The extension and skill have different responsibilities:
119
+
120
+ - `extensions/cloudflare-agent-tracing.ts` owns executable Pi wiring, command registration, MCP registration, queue behavior, and the read-only gate.
121
+ - `skills/cloudflare-agent-tracing/SKILL.md` owns investigation policy, evidence order, privacy rules, and report structure.
122
+ - `skills/cloudflare-agent-tracing/scripts/` contains dependency-free local evidence utilities.
123
+ - `runtime/` contains an optional application telemetry adapter; it is never wired automatically.
124
+
125
+ ## Project discovery
126
+
127
+ The profiler searches up to four directory levels for:
128
+
129
+ - `wrangler.jsonc`
130
+ - `wrangler.json`
131
+ - `wrangler.toml`
132
+
133
+ If exactly one configuration exists, it selects it. A root-level configuration wins when present. If a monorepo has multiple candidates, select one explicitly:
134
+
135
+ ```bash
136
+ node skills/cloudflare-agent-tracing/scripts/project-profile.mjs \
137
+ --cwd /path/to/project \
138
+ --config apps/agent/wrangler.jsonc
139
+ ```
140
+
141
+ Source discovery is bounded and excludes build output, dependencies, and hidden directories. It searches common TypeScript and JavaScript files for `Harness.open()` and reports whether a nearby `telemetry:` option was detected.
142
+
143
+ The profiler is heuristic evidence, not runtime proof.
144
+
145
+ ## Fulfillment evaluation
146
+
147
+ Create normalized evidence using:
148
+
149
+ ```text
150
+ skills/cloudflare-agent-tracing/references/evaluation-input.example.json
151
+ ```
152
+
153
+ Then run:
154
+
155
+ ```bash
156
+ node skills/cloudflare-agent-tracing/scripts/evaluate.mjs /tmp/evidence.json
157
+ ```
158
+
159
+ Deterministic evidence checks submission settlement, final answer presence, required tools, required durable effects, constraints, and terminal failures. Semantic evidence is optional; without authorized semantic evidence, a deterministic pass can remain `indeterminate`.
160
+
161
+ ## Human-review HTML reports
162
+
163
+ All five investigation modes use one normalized report schema. See:
164
+
165
+ ```text
166
+ skills/cloudflare-agent-tracing/references/report.example.json
167
+ ```
168
+
169
+ Render a normalized report directly:
170
+
171
+ ```bash
172
+ node skills/cloudflare-agent-tracing/scripts/render-report.mjs \
173
+ path/to/report.json \
174
+ --out path/to/report.html
175
+ ```
176
+
177
+ If `--out` is omitted, the renderer writes beside the JSON input with an `.html` extension. The renderer validates the schema version and mode, 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.
178
+
179
+ Saved reports should remain content-free and should normally be ignored by Git:
180
+
181
+ ```gitignore
182
+ .pi/agent-tracing-reports/
183
+ ```
184
+
185
+ ## Optional application diagnostics
186
+
187
+ The package intentionally has no project-specific transcript reader. A target application may expose an existing narrow, authorized diagnostic export. Keep raw output in `/tmp`, summarize it locally, and remove it.
188
+
189
+ For Pi Durable-shaped context JSON:
190
+
191
+ ```bash
192
+ node skills/cloudflare-agent-tracing/scripts/summarize-session-context.mjs \
193
+ /tmp/session-context.json
194
+ ```
195
+
196
+ The summary retains IDs, roles, tool names/statuses, stop reasons, token counts, and reported cost. It removes text, thinking, tool arguments, and tool results.
197
+
198
+ ## Optional Pi telemetry adapter
199
+
200
+ `runtime/cloudflare-telemetry-context.ts` structurally implements Pi's telemetry context over Cloudflare Workers custom spans without importing project packages.
201
+
202
+ It is reference application code, not an automatically loaded Pi extension. Before integrating it into a long-lived Durable Object:
203
+
204
+ 1. Verify invocation-scoped tracing behavior under workerd.
205
+ 2. Cover HTTP, RPC, WebSocket, alarms, retries, and resumed tasks.
206
+ 3. Keep error-message recording disabled unless content safety is established.
207
+ 4. Pass the adapter as `telemetry` to `Harness.open()`.
208
+ 5. Verify expected `pi.durable.*` and `pi.ai.*` spans in a bounded production smoke.
209
+
210
+ Workers custom spans currently lack native event and link APIs, so bounded events and links are encoded as attributes.
211
+
212
+ ## Security model
213
+
214
+ - Cloudflare API work is GET-only.
215
+ - Time ranges and pagination must be bounded.
216
+ - Broad event output that could expose headers or payloads is prohibited by skill policy.
217
+ - Reports must not include credentials, prompts, answers, thinking, tool arguments/results, or attachments.
218
+ - The extension's static method gate is defense in depth, not a security sandbox.
219
+ - Pi extensions execute with the local Pi process's operating-system permissions. Review source before installation.
220
+
221
+ ## Testing
222
+
223
+ No package installation is required:
224
+
225
+ ```bash
226
+ npm test
227
+ ```
228
+
229
+ The suite uses Node's built-in test runner and covers extension registration, read-only enforcement, JSONC/TOML project discovery, evaluation, content summarization, and telemetry adaptation.
230
+
231
+ ## Package layout
232
+
233
+ ```text
234
+ extensions/cloudflare-agent-tracing.ts
235
+ skills/cloudflare-agent-tracing/SKILL.md
236
+ skills/cloudflare-agent-tracing/scripts/
237
+ render-report.mjs
238
+ skills/cloudflare-agent-tracing/references/
239
+ report.example.json
240
+ runtime/cloudflare-telemetry-context.ts
241
+ test/extension.test.mjs
242
+ ```
243
+
244
+ ## Compatibility
245
+
246
+ - Node.js 22 or newer
247
+ - Pi package loading and extension APIs described by `@earendil-works/pi-coding-agent`
248
+ - Cloudflare's official MCP server
249
+ - Cloudflare Workers observability for production evidence
250
+
251
+ Pi Durable provides the richest task and usage evidence, but Worker-level trace, health, and incident modes can also investigate other Cloudflare agent frameworks.
@@ -0,0 +1,107 @@
1
+ interface CommandContext {
2
+ isIdle(): boolean;
3
+ ui: { notify(message: string, level: "info" | "warning" | "error"): void };
4
+ }
5
+
6
+ interface ToolCallEvent {
7
+ toolName: string;
8
+ input: Record<string, unknown>;
9
+ }
10
+
11
+ interface PiExtensionApi {
12
+ registerMcpServer(name: string, config: Record<string, unknown>): void;
13
+ registerCommand(
14
+ name: string,
15
+ options: {
16
+ description: string;
17
+ handler(args: string, context: CommandContext): Promise<void> | void;
18
+ },
19
+ ): void;
20
+ sendUserMessage(
21
+ content: string,
22
+ options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
23
+ ): void;
24
+ on(
25
+ event: "tool_call",
26
+ handler: (event: ToolCallEvent) => { block: true; reason: string } | undefined,
27
+ ): () => void;
28
+ }
29
+
30
+ const SKILL = "cloudflare-agent-tracing";
31
+ const CLOUDFLARE_EXECUTE_SUFFIX = "cloudflare_execute";
32
+ const METHOD_LITERAL = /\bmethod\s*:\s*["'`](GET|POST|PUT|PATCH|DELETE)["'`]/giu;
33
+
34
+ export const commands = [
35
+ {
36
+ name: "agent-trace",
37
+ description: "Trace one Cloudflare agent request or bounded time window",
38
+ mode: "trace",
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;
66
+
67
+ export const cloudflareExecuteIsReadOnly = (code: unknown): boolean => {
68
+ if (typeof code !== "string" || !code.includes("cloudflare.request")) return false;
69
+ const methods = [...code.matchAll(METHOD_LITERAL)].map((match) => match[1]?.toUpperCase());
70
+ return methods.length > 0 && methods.every((method) => method === "GET");
71
+ };
72
+
73
+ export default function cloudflareAgentTracing(pi: PiExtensionApi): void {
74
+ pi.registerMcpServer("cloudflare", {
75
+ url: "https://mcp.cloudflare.com/mcp",
76
+ exposure: "codemode",
77
+ timeout: 90,
78
+ description:
79
+ "Read Cloudflare configuration, Workers observability, deployments, traces, and documentation.",
80
+ });
81
+
82
+ // The package is an investigator, not a deployment or repair tool. Fail closed for
83
+ // cloudflare_execute unless every statically visible API request is an explicit GET.
84
+ pi.on("tool_call", (event) => {
85
+ if (!event.toolName.endsWith(CLOUDFLARE_EXECUTE_SUFFIX)) return undefined;
86
+ if (cloudflareExecuteIsReadOnly(event.input.code)) return undefined;
87
+ return {
88
+ block: true,
89
+ reason:
90
+ "Cloudflare Agent Tracing is read-only. cloudflare_execute requires explicit GET requests only.",
91
+ };
92
+ });
93
+
94
+ for (const command of commands) {
95
+ pi.registerCommand(command.name, {
96
+ description: command.description,
97
+ handler: (args, context) => {
98
+ const target = args.trim() || command.fallback;
99
+ pi.sendUserMessage(`/skill:${SKILL} ${command.mode} ${target}`, {
100
+ ...(context.isIdle() ? {} : { deliverAs: "followUp" as const }),
101
+ expandPromptTemplates: true,
102
+ });
103
+ if (!context.isIdle()) context.ui.notify(`${command.name} queued`, "info");
104
+ },
105
+ });
106
+ }
107
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "pi-cloudflare-agent-tracing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Read-only Cloudflare observability, health, cost, incident, and fulfillment workflows for Pi Durable projects.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Oskar Ablimit",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/oskarcode/pi-cloudflare-agent-tracing.git"
11
+ },
12
+ "homepage": "https://github.com/oskarcode/pi-cloudflare-agent-tracing#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/oskarcode/pi-cloudflare-agent-tracing/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "keywords": [
20
+ "pi-package",
21
+ "pi-extension",
22
+ "cloudflare",
23
+ "observability",
24
+ "pi-durable",
25
+ "agents"
26
+ ],
27
+ "pi": {
28
+ "extensions": [
29
+ "./extensions/cloudflare-agent-tracing.ts"
30
+ ],
31
+ "skills": [
32
+ "./skills"
33
+ ]
34
+ },
35
+ "scripts": {
36
+ "test": "node --test test/*.test.mjs runtime/*.test.mjs skills/cloudflare-agent-tracing/scripts/*.test.mjs",
37
+ "profile": "node skills/cloudflare-agent-tracing/scripts/project-profile.mjs",
38
+ "render-report": "node skills/cloudflare-agent-tracing/scripts/render-report.mjs"
39
+ },
40
+ "files": [
41
+ "extensions",
42
+ "skills",
43
+ "runtime",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "engines": {
48
+ "node": ">=22"
49
+ }
50
+ }
@@ -0,0 +1,29 @@
1
+ # Optional runtime telemetry
2
+
3
+ `cloudflare-telemetry-context.ts` is optional application code. The Pi coding-agent package does not inject it into target Workers.
4
+
5
+ Conceptual integration:
6
+
7
+ ```ts
8
+ import { tracing } from "cloudflare:workers";
9
+ import { createCloudflareTelemetryContext } from "./cloudflare-telemetry-context";
10
+
11
+ const telemetry = createCloudflareTelemetryContext(tracing);
12
+
13
+ const harness = await Harness.open(
14
+ storage,
15
+ { ...harnessOptions, telemetry },
16
+ context,
17
+ );
18
+ ```
19
+
20
+ Before deployment, prove under workerd that the selected Cloudflare tracing object remains valid for every invocation type that can use the Harness: HTTP, RPC, WebSockets, alarms, retries, and resumed tasks. A long-lived Durable Object must not accidentally retain an invocation-owned context beyond its valid lifetime.
21
+
22
+ The adapter defaults to content-safe behavior:
23
+
24
+ - error names are recorded;
25
+ - error messages are omitted;
26
+ - events and links are bounded;
27
+ - arrays are encoded as JSON attributes because Workers custom spans do not expose native event/link APIs.
28
+
29
+ Do not claim `pi.durable.*` or `pi.ai.*` spans exist until a sampled runtime request proves them.
@@ -0,0 +1,89 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createCloudflareTelemetryContext } from "./cloudflare-telemetry-context.ts";
4
+
5
+ class NativeSpan {
6
+ attributes = {};
7
+ statuses = [];
8
+ constructor(name, id) {
9
+ this.name = name;
10
+ this.id = id;
11
+ }
12
+ setAttribute(key, value) {
13
+ this.attributes[key] = value;
14
+ return this;
15
+ }
16
+ setAttributes(attributes) {
17
+ for (const [key, value] of Object.entries(attributes)) {
18
+ if (value !== undefined) this.attributes[key] = value;
19
+ }
20
+ return this;
21
+ }
22
+ setStatus(status) {
23
+ this.statuses.push(status);
24
+ return this;
25
+ }
26
+ spanContext() {
27
+ return { traceId: "trace-1", spanId: `span-${this.id}`, traceFlags: 1 };
28
+ }
29
+ }
30
+
31
+ class Tracing {
32
+ spans = [];
33
+ enterSpan(name, callback) {
34
+ const span = new NativeSpan(name, this.spans.length + 1);
35
+ this.spans.push(span);
36
+ return callback(span);
37
+ }
38
+ }
39
+
40
+ test("records Pi attributes and bounded events without content", async () => {
41
+ const tracing = new Tracing();
42
+ const telemetry = createCloudflareTelemetryContext(tracing, { maxEventsPerSpan: 1 });
43
+ await telemetry.startSpan(
44
+ { name: "pi.ai.request", attributes: { provider: "openai", tags: ["agent", "local"] } },
45
+ async (span) => {
46
+ span.addEvent("pi.ai.first_chunk");
47
+ span.addEvent("ignored");
48
+ span.setAttributes({ "usage.output": 12, absent: undefined });
49
+ },
50
+ );
51
+
52
+ assert.deepEqual(tracing.spans[0].attributes, {
53
+ provider: "openai",
54
+ tags: '["agent","local"]',
55
+ "event.0.name": "pi.ai.first_chunk",
56
+ "usage.output": 12,
57
+ });
58
+ assert.deepEqual(tracing.spans[0].statuses.at(-1), { code: "ok" });
59
+ });
60
+
61
+ test("redacts error messages by default", async () => {
62
+ const tracing = new Tracing();
63
+ const telemetry = createCloudflareTelemetryContext(tracing);
64
+ await assert.rejects(
65
+ telemetry.startSpan({ name: "pi.durable.phase" }, () => {
66
+ throw new TypeError("private provider payload");
67
+ }),
68
+ /private provider payload/,
69
+ );
70
+
71
+ assert.equal(tracing.spans[0].attributes["error.name"], "TypeError");
72
+ assert.deepEqual(tracing.spans[0].statuses.at(-1), { code: "error" });
73
+ });
74
+
75
+ test("encodes links using trace and span identifiers", async () => {
76
+ const tracing = new Tracing();
77
+ const telemetry = createCloudflareTelemetryContext(tracing);
78
+ let parent;
79
+ await telemetry.startSpan({ name: "parent" }, async (span) => {
80
+ parent = span;
81
+ });
82
+ await telemetry.startSpan({ name: "child", links: [{ context: parent, attributes: { reason: "queued" } }] }, async () => {});
83
+
84
+ assert.deepEqual(tracing.spans[1].attributes, {
85
+ "link.0.trace_id": "trace-1",
86
+ "link.0.span_id": "span-1",
87
+ "link.0.attribute.reason": "queued",
88
+ });
89
+ });