pi-cloudflare-agent-tracing 0.2.0 → 0.3.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Pi Cloudflare Agent Tracing
2
2
 
3
- A dependency-free Pi package for read-only investigation of Pi Durable and other agent applications running on Cloudflare.
3
+ A Pi package and required Worker runtime adapter for content-safe tracing of Pi Durable applications running on Cloudflare.
4
4
 
5
5
  It adds:
6
6
 
@@ -23,13 +23,14 @@ The package registers Cloudflare's official MCP server, applies an evidence-firs
23
23
  - Queries deployments, versions, bindings, logs, traces, and bounded metrics.
24
24
  - Evaluates deterministic fulfillment from normalized, content-free evidence.
25
25
  - Summarizes Pi Durable-shaped context exports without transcript or tool content.
26
- - Includes an optional Cloudflare custom-span adapter for future runtime integration.
26
+ - Emits `pi.durable.*` and `pi.ai.*` spans through Cloudflare Workers custom spans.
27
+ - Requires the runtime adapter on every production `Harness.open()` before investigations run.
27
28
 
28
29
  It does **not** deploy, repair state, mutate Cloudflare resources, or create diagnostic endpoints.
29
30
 
30
31
  ## Install
31
32
 
32
- ### Install from npm
33
+ ### 1. Install the Pi investigation package
33
34
 
34
35
  ```bash
35
36
  pi install npm:pi-cloudflare-agent-tracing
@@ -37,6 +38,44 @@ pi install npm:pi-cloudflare-agent-tracing
37
38
 
38
39
  The `pi-package` keyword makes the published package eligible for discovery in the [Pi package gallery](https://pi.dev/packages).
39
40
 
41
+ ### 2. Install the required Worker runtime dependency
42
+
43
+ From every Pi Durable Worker project that will be investigated:
44
+
45
+ ```bash
46
+ pnpm add pi-cloudflare-agent-tracing
47
+ # or: npm install pi-cloudflare-agent-tracing
48
+ ```
49
+
50
+ Enable Workers observability and tracing:
51
+
52
+ ```jsonc
53
+ {
54
+ "observability": {
55
+ "enabled": true,
56
+ "traces": { "enabled": true },
57
+ },
58
+ }
59
+ ```
60
+
61
+ Wire the package into every production `Harness.open()`:
62
+
63
+ ```ts
64
+ import { tracing } from "cloudflare:workers";
65
+ import { createCloudflareTelemetryContext } from "pi-cloudflare-agent-tracing/cloudflare";
66
+
67
+ const harness = await Harness.open(
68
+ storage,
69
+ {
70
+ ...harnessOptions,
71
+ telemetry: createCloudflareTelemetryContext(tracing),
72
+ },
73
+ context,
74
+ );
75
+ ```
76
+
77
+ The profiler requires all three conditions—the dependency, Workers tracing, and `Harness.open()` wiring. Investigation commands stop with setup guidance when any condition is missing because platform traces alone do not provide Pi execution telemetry.
78
+
40
79
  ### Try from a local checkout
41
80
 
42
81
  ```bash
@@ -62,7 +101,7 @@ pi install /absolute/path/to/pi-cloudflare-agent-tracing
62
101
  The same package can be installed from Git:
63
102
 
64
103
  ```bash
65
- pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.2.0
104
+ pi install git:github.com/oskarcode/pi-cloudflare-agent-tracing@v0.3.0
66
105
  ```
67
106
 
68
107
  Use a pinned release tag or commit for reproducible investigations.
@@ -109,7 +148,7 @@ Each saved report produces matching `.md`, content-free `.json`, and standalone
109
148
  ```text
110
149
  slash command
111
150
  → extension dispatches /skill:cloudflare-agent-tracing
112
- → skill profiles the selected local Worker
151
+ → skill verifies required Pi runtime instrumentation
113
152
  → Cloudflare MCP performs bounded GET queries
114
153
  → optional authorized diagnostics provide durable evidence
115
154
  → evaluator produces a content-free verdict
@@ -120,7 +159,7 @@ The extension and skill have different responsibilities:
120
159
  - `extensions/cloudflare-agent-tracing.ts` owns executable Pi wiring, command registration, MCP registration, queue behavior, and the read-only gate.
121
160
  - `skills/cloudflare-agent-tracing/SKILL.md` owns investigation policy, evidence order, privacy rules, and report structure.
122
161
  - `skills/cloudflare-agent-tracing/scripts/` contains dependency-free local evidence utilities.
123
- - `runtime/` contains an optional application telemetry adapter; it is never wired automatically.
162
+ - `runtime/` contains the required Worker adapter that forwards Pi telemetry to Cloudflare custom spans.
124
163
 
125
164
  ## Project discovery
126
165
 
@@ -138,9 +177,9 @@ node skills/cloudflare-agent-tracing/scripts/project-profile.mjs \
138
177
  --config apps/agent/wrangler.jsonc
139
178
  ```
140
179
 
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.
180
+ Source discovery is bounded and excludes build output, dependencies, and hidden directories. It searches common TypeScript and JavaScript files for every production `Harness.open()` and reports whether each call passes `telemetry:`. `instrumentation.ready` is true only when the package dependency and Wrangler tracing settings are also present.
142
181
 
143
- The profiler is heuristic evidence, not runtime proof.
182
+ The profiler is heuristic setup evidence. A sampled production span remains the runtime proof.
144
183
 
145
184
  ## Fulfillment evaluation
146
185
 
@@ -195,19 +234,15 @@ node skills/cloudflare-agent-tracing/scripts/summarize-session-context.mjs \
195
234
 
196
235
  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
236
 
198
- ## Optional Pi telemetry adapter
237
+ ## Required Pi telemetry adapter
199
238
 
200
- `runtime/cloudflare-telemetry-context.ts` structurally implements Pi's telemetry context over Cloudflare Workers custom spans without importing project packages.
239
+ `pi-cloudflare-agent-tracing/cloudflare` structurally implements Pi's telemetry context over Cloudflare Workers custom spans without importing project packages. It must be passed to every production `Harness.open()`.
201
240
 
202
- It is reference application code, not an automatically loaded Pi extension. Before integrating it into a long-lived Durable Object:
241
+ Pi Durable emits content-free admission, phase, task, tool, recovery, and commit evidence. Pi AI emits model, timing, usage, and cost evidence when the provider supplies it. The adapter redacts error messages by default. Workers custom spans do not expose native event and link APIs, so bounded events and links are encoded as attributes.
203
242
 
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.
243
+ The package never persists a telemetry context in Durable Object state. Cloudflare's `tracing.enterSpan()` uses the active JavaScript async context for request-time nesting; resumed Durable Object work can begin a new trace when no caller span exists.
209
244
 
210
- Workers custom spans currently lack native event and link APIs, so bounded events and links are encoded as attributes.
245
+ After integration, verify the adapter under workerd and then prove expected `pi.durable.*` and `pi.ai.*` spans with one bounded, authorized production smoke before relying on the reports.
211
246
 
212
247
  ## Security model
213
248
 
@@ -237,7 +272,8 @@ skills/cloudflare-agent-tracing/scripts/
237
272
  render-report.mjs
238
273
  skills/cloudflare-agent-tracing/references/
239
274
  report.example.json
240
- runtime/cloudflare-telemetry-context.ts
275
+ runtime/cloudflare-telemetry-context.js
276
+ runtime/cloudflare-telemetry-context.d.ts
241
277
  test/extension.test.mjs
242
278
  ```
243
279
 
package/package.json CHANGED
@@ -1,50 +1,68 @@
1
1
  {
2
2
  "name": "pi-cloudflare-agent-tracing",
3
- "version": "0.2.0",
4
- "description": "Read-only Cloudflare observability, health, cost, incident, and fulfillment workflows for Pi Durable projects.",
5
- "type": "module",
3
+ "version": "0.3.0",
4
+ "description": "Required Cloudflare custom-span runtime and read-only tracing reports for Pi Durable applications.",
5
+ "keywords": [
6
+ "agents",
7
+ "cloudflare",
8
+ "observability",
9
+ "pi-durable",
10
+ "pi-extension",
11
+ "pi-package"
12
+ ],
13
+ "homepage": "https://github.com/oskarcode/pi-cloudflare-agent-tracing#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/oskarcode/pi-cloudflare-agent-tracing/issues"
16
+ },
6
17
  "license": "MIT",
7
18
  "author": "Oskar Ablimit",
8
19
  "repository": {
9
20
  "type": "git",
10
21
  "url": "git+https://github.com/oskarcode/pi-cloudflare-agent-tracing.git"
11
22
  },
12
- "homepage": "https://github.com/oskarcode/pi-cloudflare-agent-tracing#readme",
13
- "bugs": {
14
- "url": "https://github.com/oskarcode/pi-cloudflare-agent-tracing/issues"
23
+ "files": [
24
+ "extensions",
25
+ "skills",
26
+ "runtime",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "type": "module",
31
+ "exports": {
32
+ "./cloudflare": {
33
+ "types": "./runtime/cloudflare-telemetry-context.d.ts",
34
+ "import": "./runtime/cloudflare-telemetry-context.js",
35
+ "default": "./runtime/cloudflare-telemetry-context.js"
36
+ },
37
+ "./runtime/cloudflare-telemetry-context.js": {
38
+ "types": "./runtime/cloudflare-telemetry-context.d.ts",
39
+ "import": "./runtime/cloudflare-telemetry-context.js",
40
+ "default": "./runtime/cloudflare-telemetry-context.js"
41
+ },
42
+ "./runtime/cloudflare-telemetry-context.ts": {
43
+ "types": "./runtime/cloudflare-telemetry-context.d.ts",
44
+ "import": "./runtime/cloudflare-telemetry-context.js",
45
+ "default": "./runtime/cloudflare-telemetry-context.js"
46
+ },
47
+ "./package.json": "./package.json"
15
48
  },
16
49
  "publishConfig": {
17
50
  "access": "public"
18
51
  },
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
52
  "scripts": {
36
53
  "test": "node --test test/*.test.mjs runtime/*.test.mjs skills/cloudflare-agent-tracing/scripts/*.test.mjs",
37
54
  "profile": "node skills/cloudflare-agent-tracing/scripts/project-profile.mjs",
38
55
  "render-report": "node skills/cloudflare-agent-tracing/scripts/render-report.mjs"
39
56
  },
40
- "files": [
41
- "extensions",
42
- "skills",
43
- "runtime",
44
- "README.md",
45
- "LICENSE"
46
- ],
47
57
  "engines": {
48
58
  "node": ">=22"
59
+ },
60
+ "pi": {
61
+ "extensions": [
62
+ "./extensions/cloudflare-agent-tracing.ts"
63
+ ],
64
+ "skills": [
65
+ "./skills"
66
+ ]
49
67
  }
50
68
  }
package/runtime/README.md CHANGED
@@ -1,29 +1,36 @@
1
- # Optional runtime telemetry
1
+ # Required Worker telemetry
2
2
 
3
- `cloudflare-telemetry-context.ts` is optional application code. The Pi coding-agent package does not inject it into target Workers.
3
+ The `pi-cloudflare-agent-tracing/cloudflare` export adapts Pi's vendor-neutral telemetry contract to Cloudflare Workers custom spans. Install this package in the Worker application as well as in Pi:
4
4
 
5
- Conceptual integration:
5
+ ```bash
6
+ pnpm add pi-cloudflare-agent-tracing
7
+ pi install npm:pi-cloudflare-agent-tracing
8
+ ```
9
+
10
+ Enable `observability.enabled` and `observability.traces.enabled` in Wrangler, then wire every production Harness:
6
11
 
7
12
  ```ts
8
13
  import { tracing } from "cloudflare:workers";
9
- import { createCloudflareTelemetryContext } from "./cloudflare-telemetry-context";
10
-
11
- const telemetry = createCloudflareTelemetryContext(tracing);
14
+ import { createCloudflareTelemetryContext } from "pi-cloudflare-agent-tracing/cloudflare";
12
15
 
13
16
  const harness = await Harness.open(
14
17
  storage,
15
- { ...harnessOptions, telemetry },
18
+ {
19
+ ...harnessOptions,
20
+ telemetry: createCloudflareTelemetryContext(tracing),
21
+ },
16
22
  context,
17
23
  );
18
24
  ```
19
25
 
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
26
  The adapter defaults to content-safe behavior:
23
27
 
24
28
  - error names are recorded;
25
29
  - error messages are omitted;
26
30
  - events and links are bounded;
27
- - arrays are encoded as JSON attributes because Workers custom spans do not expose native event/link APIs.
31
+ - arrays are encoded as JSON attributes because Workers custom spans do not expose native event/link APIs;
32
+ - telemetry contexts are process objects and are never durable application state.
33
+
34
+ Cloudflare's `tracing.enterSpan()` automatically nests spans using the active JavaScript async context and ends them when the callback's promise settles. A Pi task resumed by an alarm or another invocation may correctly start a new root trace when no caller span is active.
28
35
 
29
- Do not claim `pi.durable.*` or `pi.ai.*` spans exist until a sampled runtime request proves them.
36
+ The package profiler treats the runtime dependency and `Harness.open()` wiring as required setup. Still validate the selected compatibility date under workerd and prove sampled `pi.durable.*` and `pi.ai.*` spans in the deployed Worker before making production conclusions.
@@ -0,0 +1,58 @@
1
+ export type AttributeValue =
2
+ | string
3
+ | number
4
+ | boolean
5
+ | readonly string[]
6
+ | readonly number[]
7
+ | readonly boolean[];
8
+
9
+ export interface SpanAttributes {
10
+ [name: string]: AttributeValue | undefined;
11
+ }
12
+
13
+ export type TelemetryStatus =
14
+ | { status: "ok" }
15
+ | { status: "error"; error?: { name: string; message: string } };
16
+
17
+ export interface TelemetryLink {
18
+ context: TelemetryContext;
19
+ attributes?: SpanAttributes;
20
+ }
21
+
22
+ export interface TelemetryContext {
23
+ startSpan<T>(
24
+ options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
25
+ callback: (span: TelemetrySpan) => T | Promise<T>,
26
+ ): Promise<T>;
27
+ }
28
+
29
+ export interface TelemetrySpan extends TelemetryContext {
30
+ addLink(link: TelemetryLink): void;
31
+ addEvent(name: string, attributes?: SpanAttributes): void;
32
+ setAttributes(attributes: SpanAttributes): void;
33
+ setStatus(status: TelemetryStatus): void;
34
+ }
35
+
36
+ export interface CloudflareSpan {
37
+ setAttribute(key: string, value: string | number | boolean): this;
38
+ setAttributes(attributes: Record<string, string | number | boolean | undefined>): this;
39
+ setStatus(status: { code: "unset" | "ok" | "error"; message?: string }): this;
40
+ spanContext(): { traceId: string; spanId: string; traceFlags: number };
41
+ }
42
+
43
+ export interface CloudflareTracing {
44
+ enterSpan<T>(name: string, callback: (span: CloudflareSpan) => T): T;
45
+ }
46
+
47
+ export interface CloudflareTelemetryOptions {
48
+ /** Error messages can contain user/provider content and are redacted by default. */
49
+ includeErrorMessages?: boolean;
50
+ /** Events are encoded as bounded attributes because Workers custom spans have no event API. */
51
+ maxEventsPerSpan?: number;
52
+ maxLinksPerSpan?: number;
53
+ }
54
+
55
+ export declare function createCloudflareTelemetryContext(
56
+ tracing: CloudflareTracing,
57
+ options?: CloudflareTelemetryOptions,
58
+ ): TelemetryContext;
@@ -0,0 +1,139 @@
1
+ const DEFAULT_MAX_EVENTS = 32;
2
+ const DEFAULT_MAX_LINKS = 16;
3
+ const MAX_ERROR_MESSAGE = 500;
4
+
5
+ export function createCloudflareTelemetryContext(tracing, options = {}) {
6
+ return new CloudflareTelemetryContext(tracing, {
7
+ includeErrorMessages: options.includeErrorMessages ?? false,
8
+ maxEventsPerSpan: options.maxEventsPerSpan ?? DEFAULT_MAX_EVENTS,
9
+ maxLinksPerSpan: options.maxLinksPerSpan ?? DEFAULT_MAX_LINKS,
10
+ });
11
+ }
12
+
13
+ class CloudflareTelemetryContext {
14
+ constructor(tracing, options) {
15
+ this.tracing = tracing;
16
+ this.options = options;
17
+ }
18
+
19
+ async startSpan(options, callback) {
20
+ return await this.tracing.enterSpan(options.name, (nativeSpan) => {
21
+ const span = new CloudflareTelemetrySpan(this.tracing, nativeSpan, this.options);
22
+ if (options.attributes) span.setAttributes(options.attributes);
23
+ for (const link of options.links ?? []) span.addLink(link);
24
+
25
+ let result;
26
+ try {
27
+ result = callback(span);
28
+ } catch (error) {
29
+ span.finishError(error);
30
+ return Promise.reject(error);
31
+ }
32
+
33
+ return Promise.resolve(result).then(
34
+ (value) => {
35
+ span.finishSuccess();
36
+ return value;
37
+ },
38
+ (error) => {
39
+ span.finishError(error);
40
+ throw error;
41
+ },
42
+ );
43
+ });
44
+ }
45
+ }
46
+
47
+ class CloudflareTelemetrySpan {
48
+ settled = false;
49
+ explicitStatus = false;
50
+ eventCount = 0;
51
+ linkCount = 0;
52
+
53
+ constructor(tracing, nativeSpan, options) {
54
+ this.tracing = tracing;
55
+ this.nativeSpan = nativeSpan;
56
+ this.options = options;
57
+ }
58
+
59
+ startSpan(options, callback) {
60
+ return new CloudflareTelemetryContext(this.tracing, this.options).startSpan(options, callback);
61
+ }
62
+
63
+ addLink(link) {
64
+ if (this.settled || this.linkCount >= this.options.maxLinksPerSpan) return;
65
+ if (!(link.context instanceof CloudflareTelemetrySpan)) return;
66
+
67
+ const index = this.linkCount++;
68
+ const context = link.context.nativeSpan.spanContext();
69
+ this.nativeSpan.setAttributes({
70
+ [`link.${index}.trace_id`]: context.traceId,
71
+ [`link.${index}.span_id`]: context.spanId,
72
+ ...prefixAttributes(`link.${index}.attribute.`, link.attributes),
73
+ });
74
+ }
75
+
76
+ addEvent(name, attributes) {
77
+ if (this.settled || this.eventCount >= this.options.maxEventsPerSpan) return;
78
+ const index = this.eventCount++;
79
+ this.nativeSpan.setAttributes({
80
+ [`event.${index}.name`]: name,
81
+ ...prefixAttributes(`event.${index}.attribute.`, attributes),
82
+ });
83
+ }
84
+
85
+ setAttributes(attributes) {
86
+ if (this.settled) return;
87
+ this.nativeSpan.setAttributes(normalizeAttributes(attributes));
88
+ }
89
+
90
+ setStatus(status) {
91
+ if (this.settled) return;
92
+ this.explicitStatus = true;
93
+ if (status.status === "ok") {
94
+ this.nativeSpan.setStatus({ code: "ok" });
95
+ return;
96
+ }
97
+
98
+ const message = this.options.includeErrorMessages
99
+ ? status.error?.message.slice(0, MAX_ERROR_MESSAGE)
100
+ : undefined;
101
+ this.nativeSpan.setAttributes({ "error.name": status.error?.name });
102
+ this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
103
+ }
104
+
105
+ finishSuccess() {
106
+ if (this.settled) return;
107
+ if (!this.explicitStatus) this.nativeSpan.setStatus({ code: "ok" });
108
+ this.settled = true;
109
+ }
110
+
111
+ finishError(error) {
112
+ if (this.settled) return;
113
+ const name = error instanceof Error ? error.name : "UnknownError";
114
+ const message =
115
+ this.options.includeErrorMessages && error instanceof Error
116
+ ? error.message.slice(0, MAX_ERROR_MESSAGE)
117
+ : undefined;
118
+ this.nativeSpan.setAttributes({ "error.name": name });
119
+ this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
120
+ this.settled = true;
121
+ }
122
+ }
123
+
124
+ function normalizeAttributes(attributes) {
125
+ const normalized = {};
126
+ for (const [name, value] of Object.entries(attributes ?? {})) {
127
+ normalized[name] =
128
+ value !== undefined && typeof value === "object" ? JSON.stringify(value) : value;
129
+ }
130
+ return normalized;
131
+ }
132
+
133
+ function prefixAttributes(prefix, attributes) {
134
+ const prefixed = {};
135
+ for (const [name, value] of Object.entries(normalizeAttributes(attributes))) {
136
+ prefixed[`${prefix}${name}`] = value;
137
+ }
138
+ return prefixed;
139
+ }
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { createCloudflareTelemetryContext } from "./cloudflare-telemetry-context.ts";
3
+ import { createCloudflareTelemetryContext } from "pi-cloudflare-agent-tracing/cloudflare";
4
4
 
5
5
  class NativeSpan {
6
6
  attributes = {};
@@ -79,7 +79,10 @@ test("encodes links using trace and span identifiers", async () => {
79
79
  await telemetry.startSpan({ name: "parent" }, async (span) => {
80
80
  parent = span;
81
81
  });
82
- await telemetry.startSpan({ name: "child", links: [{ context: parent, attributes: { reason: "queued" } }] }, async () => {});
82
+ await telemetry.startSpan(
83
+ { name: "child", links: [{ context: parent, attributes: { reason: "queued" } }] },
84
+ async () => {},
85
+ );
83
86
 
84
87
  assert.deepEqual(tracing.spans[1].attributes, {
85
88
  "link.0.trace_id": "trace-1",
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: cloudflare-agent-tracing
3
- description: Investigate Pi Durable and other agent applications on Cloudflare using read-only Workers observability, deployments, Durable Object evidence, model telemetry, and bounded fulfillment evaluation. Use for traces, health, incidents, latency, model cost, errors, recovery, or whether an agent fulfilled a request.
4
- compatibility: Requires Node.js 22+, a Cloudflare account available through the official Cloudflare MCP, and a local Cloudflare Worker project or an explicit Worker target.
3
+ description: Investigate instrumented Pi Durable applications on Cloudflare using Workers observability, Pi telemetry, Durable Object evidence, model usage, and bounded fulfillment evaluation. Use for traces, health, incidents, latency, model cost, errors, recovery, or whether an agent fulfilled a request.
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.2.0"
7
+ version: "0.3.0"
8
8
  ---
9
9
 
10
10
  # Cloudflare agent tracing
@@ -21,11 +21,12 @@ Interpret the first argument as one of `trace`, `health`, `cost`, `evaluate`, or
21
21
 
22
22
  1. Run `node <skill-directory>/scripts/project-profile.mjs --cwd <project-directory>`.
23
23
  2. If the profiler reports multiple Wrangler configurations, select the relevant one from the user's target or ask one focused question. Re-run with `--config <path>` when needed.
24
- 3. Read only the selected Wrangler configuration, relevant composition root, and installed Pi versions as needed.
25
- 4. Check whether custom Pi telemetry is actually passed to `Harness.open()`. Wrangler tracing alone does not prove Pi spans are emitted.
26
- 5. Use the Cloudflare MCP namespace. Read its namespace instructions before querying unfamiliar tools.
27
- 6. Search the Cloudflare OpenAPI schema before an unfamiliar API call.
28
- 7. Use only Cloudflare GET requests. The extension blocks `cloudflare_execute` unless all statically visible requests are explicit GETs.
24
+ 3. Require `instrumentation.ready: true`. This means the application depends on `pi-cloudflare-agent-tracing`, Workers observability and traces are enabled, and every discovered production `Harness.open()` passes `telemetry`.
25
+ 4. If instrumentation is not ready, stop before production analysis. Report the missing requirements and point to the package's required Worker setup. Platform-only traces are not a substitute for Pi telemetry.
26
+ 5. Read only the selected Wrangler configuration, relevant composition root, and installed Pi versions as needed.
27
+ 6. Use the Cloudflare MCP namespace. Read its namespace instructions before querying unfamiliar tools.
28
+ 7. Search the Cloudflare OpenAPI schema before an unfamiliar API call.
29
+ 8. Use only Cloudflare GET requests. The extension blocks `cloudflare_execute` unless all statically visible requests are explicit GETs.
29
30
 
30
31
  ## Evidence order
31
32
 
@@ -35,11 +35,16 @@ export async function profileProject(options = {}) {
35
35
  const packagePath = configPath
36
36
  ? await findUp(dirname(configPath), "package.json", cwd)
37
37
  : await findUp(cwd, "package.json", cwd);
38
- const packageJson = packagePath
39
- ? JSON.parse(await readFile(packagePath, "utf8"))
40
- : undefined;
38
+ const packageJson = packagePath ? JSON.parse(await readFile(packagePath, "utf8")) : undefined;
41
39
  const sourceRoot = configPath ? dirname(configPath) : cwd;
42
40
  const sourceEvidence = await inspectSource(sourceRoot);
41
+ const tracingPackage = dependencyVersion(packageJson, "pi-cloudflare-agent-tracing");
42
+ const instrumentationReady =
43
+ Boolean(tracingPackage) &&
44
+ configBoolean(configText, "observability", "enabled") &&
45
+ configBoolean(configText, "traces", "enabled") &&
46
+ sourceEvidence.calls.length > 0 &&
47
+ sourceEvidence.allHarnessCallsWired;
43
48
 
44
49
  return {
45
50
  projectRoot: relative(cwd, sourceRoot) || ".",
@@ -54,6 +59,7 @@ export async function profileProject(options = {}) {
54
59
  durable: dependencyVersion(packageJson, "@earendil-works/pi-durable"),
55
60
  ai: dependencyVersion(packageJson, "@earendil-works/pi-ai"),
56
61
  agents: dependencyVersion(packageJson, "agents"),
62
+ tracingPackage,
57
63
  },
58
64
  observability: {
59
65
  enabled: configBoolean(configText, "observability", "enabled"),
@@ -61,6 +67,15 @@ export async function profileProject(options = {}) {
61
67
  },
62
68
  bindings: extractBindings(configText),
63
69
  harness: sourceEvidence,
70
+ instrumentation: {
71
+ ready: instrumentationReady,
72
+ requirements: {
73
+ tracingPackageInstalled: Boolean(tracingPackage),
74
+ workersObservabilityEnabled: configBoolean(configText, "observability", "enabled"),
75
+ workersTracingEnabled: configBoolean(configText, "traces", "enabled"),
76
+ harnessTelemetryWired: sourceEvidence.allHarnessCallsWired,
77
+ },
78
+ },
64
79
  notes: [
65
80
  "Configuration and telemetry detection are source heuristics; confirm relevant source before concluding.",
66
81
  "Wrangler tracing does not by itself emit Pi Durable or Pi AI custom spans.",
@@ -89,8 +104,8 @@ async function inspectSource(root) {
89
104
  if (!text.includes("Harness.open")) continue;
90
105
  const positions = [...text.matchAll(/Harness\.open\s*\(/gu)].map((match) => match.index ?? 0);
91
106
  for (const position of positions) {
92
- const window = text.slice(position, position + 4_000);
93
- const hasTelemetry = /\btelemetry\s*:/u.test(window);
107
+ const call = extractCall(text, position, 4_000);
108
+ const hasTelemetry = /\btelemetry\s*(?::|[,}])/u.test(call);
94
109
  telemetryWired ||= hasTelemetry;
95
110
  harnessCalls.push({ path: relative(root, path), telemetryOptionDetected: hasTelemetry });
96
111
  }
@@ -99,10 +114,38 @@ async function inspectSource(root) {
99
114
  filesScanned: files.length,
100
115
  calls: harnessCalls.slice(0, 20),
101
116
  telemetryWired,
117
+ allHarnessCallsWired:
118
+ harnessCalls.length > 0 && harnessCalls.every((call) => call.telemetryOptionDetected),
102
119
  truncated: files.length >= MAX_SOURCE_FILES,
103
120
  };
104
121
  }
105
122
 
123
+ function extractCall(source, start, maxLength) {
124
+ const endLimit = Math.min(source.length, start + maxLength);
125
+ const open = source.indexOf("(", start);
126
+ if (open < 0 || open >= endLimit) return source.slice(start, endLimit);
127
+
128
+ let depth = 0;
129
+ let quote;
130
+ let escaped = false;
131
+ for (let index = open; index < endLimit; index += 1) {
132
+ const character = source[index];
133
+ if (quote) {
134
+ if (escaped) escaped = false;
135
+ else if (character === "\\") escaped = true;
136
+ else if (character === quote) quote = undefined;
137
+ continue;
138
+ }
139
+ if (character === '"' || character === "'" || character === "`") {
140
+ quote = character;
141
+ continue;
142
+ }
143
+ if (character === "(") depth += 1;
144
+ if (character === ")" && --depth === 0) return source.slice(start, index + 1);
145
+ }
146
+ return source.slice(start, endLimit);
147
+ }
148
+
106
149
  async function findSourceFiles(root) {
107
150
  const results = [];
108
151
  const queue = [root];
@@ -151,7 +194,12 @@ async function findUp(start, name, boundary) {
151
194
  const stop = resolve(boundary);
152
195
  while (directory.startsWith(stop)) {
153
196
  const candidate = join(directory, name);
154
- if (await stat(candidate).then((value) => value.isFile()).catch(() => false)) return candidate;
197
+ if (
198
+ await stat(candidate)
199
+ .then((value) => value.isFile())
200
+ .catch(() => false)
201
+ )
202
+ return candidate;
155
203
  if (directory === stop) break;
156
204
  directory = dirname(directory);
157
205
  }
@@ -179,7 +227,10 @@ function configBoolean(text, section, key) {
179
227
  const jsonSection = text.match(
180
228
  new RegExp(`["']${escapeRegExp(section)}["']\\s*:\\s*\\{([\\s\\S]*?)\\n\\s*\\}`, "u"),
181
229
  )?.[1];
182
- if (jsonSection && new RegExp(`["']${escapeRegExp(key)}["']\\s*:\\s*true`, "u").test(jsonSection)) {
230
+ if (
231
+ jsonSection &&
232
+ new RegExp(`["']${escapeRegExp(key)}["']\\s*:\\s*true`, "u").test(jsonSection)
233
+ ) {
183
234
  return true;
184
235
  }
185
236
  for (const block of tomlSections(text)) {
@@ -24,6 +24,7 @@ test("profiles a JSONC Pi Durable Worker without project-specific paths", async
24
24
  dependencies: {
25
25
  "@earendil-works/pi-durable": "1.5.2",
26
26
  "@earendil-works/pi-ai": "1.5.2",
27
+ "pi-cloudflare-agent-tracing": "0.3.0",
27
28
  },
28
29
  }),
29
30
  );
@@ -46,11 +47,36 @@ test("profiles a JSONC Pi Durable Worker without project-specific paths", async
46
47
  assert.equal(profile.worker, "portable-worker");
47
48
  assert.equal(profile.pi.durable, "1.5.2");
48
49
  assert.equal(profile.harness.telemetryWired, true);
50
+ assert.equal(profile.harness.allHarnessCallsWired, true);
51
+ assert.equal(profile.instrumentation.ready, true);
49
52
  assert.deepEqual(profile.bindings, ["SESSIONS"]);
50
53
  assert.equal(profile.ambiguousConfiguration, false);
51
54
  });
52
55
  });
53
56
 
57
+ test("requires every production Harness.open call to wire the tracing package", async () => {
58
+ await fixture(async (root) => {
59
+ await mkdir(join(root, "src"), { recursive: true });
60
+ await writeFile(
61
+ join(root, "package.json"),
62
+ JSON.stringify({ dependencies: { "pi-cloudflare-agent-tracing": "0.3.0" } }),
63
+ );
64
+ await writeFile(
65
+ join(root, "wrangler.jsonc"),
66
+ '{ "name": "partial", "observability": { "enabled": true, "traces": { "enabled": true } } }',
67
+ );
68
+ await writeFile(
69
+ join(root, "src", "session.ts"),
70
+ `await Harness.open(storage, { telemetry }, context);\nawait Harness.open(other, options, context);`,
71
+ );
72
+
73
+ const profile = await profileProject({ cwd: root });
74
+ assert.equal(profile.harness.telemetryWired, true);
75
+ assert.equal(profile.harness.allHarnessCallsWired, false);
76
+ assert.equal(profile.instrumentation.ready, false);
77
+ });
78
+ });
79
+
54
80
  test("supports an explicit TOML configuration in a monorepo", async () => {
55
81
  await fixture(async (root) => {
56
82
  await mkdir(join(root, "apps", "first"), { recursive: true });
@@ -83,6 +109,7 @@ class_name = "Agent"
83
109
  assert.equal(selected.worker, "second");
84
110
  assert.equal(selected.main, "src/index.ts");
85
111
  assert.equal(selected.observability.enabled, true);
112
+ assert.equal(selected.instrumentation.ready, false);
86
113
  assert.deepEqual(selected.bindings, ["AGENT"]);
87
114
  });
88
115
  });
@@ -1,225 +0,0 @@
1
- export type AttributeValue =
2
- | string
3
- | number
4
- | boolean
5
- | readonly string[]
6
- | readonly number[]
7
- | readonly boolean[];
8
-
9
- export interface SpanAttributes {
10
- [name: string]: AttributeValue | undefined;
11
- }
12
-
13
- export type TelemetryStatus =
14
- | { status: "ok" }
15
- | { status: "error"; error?: { name: string; message: string } };
16
-
17
- export interface TelemetryLink {
18
- context: TelemetryContext;
19
- attributes?: SpanAttributes;
20
- }
21
-
22
- export interface TelemetryContext {
23
- startSpan<T>(
24
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
25
- callback: (span: TelemetrySpan) => T | Promise<T>,
26
- ): Promise<T>;
27
- }
28
-
29
- export interface TelemetrySpan extends TelemetryContext {
30
- addLink(link: TelemetryLink): void;
31
- addEvent(name: string, attributes?: SpanAttributes): void;
32
- setAttributes(attributes: SpanAttributes): void;
33
- setStatus(status: TelemetryStatus): void;
34
- }
35
-
36
- export interface CloudflareSpan {
37
- setAttribute(key: string, value: string | number | boolean): this;
38
- setAttributes(
39
- attributes: Record<string, string | number | boolean | undefined>,
40
- ): this;
41
- setStatus(status: { code: "unset" | "ok" | "error"; message?: string }): this;
42
- spanContext(): { traceId: string; spanId: string; traceFlags: number };
43
- }
44
-
45
- export interface CloudflareTracing {
46
- enterSpan<T>(name: string, callback: (span: CloudflareSpan) => T): T;
47
- }
48
-
49
- export interface CloudflareTelemetryOptions {
50
- /** Error messages can contain user/provider content and are redacted by default. */
51
- includeErrorMessages?: boolean;
52
- /** Events are encoded as bounded attributes because Workers custom spans have no event API. */
53
- maxEventsPerSpan?: number;
54
- maxLinksPerSpan?: number;
55
- }
56
-
57
- const DEFAULT_MAX_EVENTS = 32;
58
- const DEFAULT_MAX_LINKS = 16;
59
- const MAX_ERROR_MESSAGE = 500;
60
-
61
- export function createCloudflareTelemetryContext(
62
- tracing: CloudflareTracing,
63
- options: CloudflareTelemetryOptions = {},
64
- ): TelemetryContext {
65
- return new CloudflareTelemetryContext(tracing, {
66
- includeErrorMessages: options.includeErrorMessages ?? false,
67
- maxEventsPerSpan: options.maxEventsPerSpan ?? DEFAULT_MAX_EVENTS,
68
- maxLinksPerSpan: options.maxLinksPerSpan ?? DEFAULT_MAX_LINKS,
69
- });
70
- }
71
-
72
- interface ResolvedOptions {
73
- includeErrorMessages: boolean;
74
- maxEventsPerSpan: number;
75
- maxLinksPerSpan: number;
76
- }
77
-
78
- class CloudflareTelemetryContext implements TelemetryContext {
79
- private readonly tracing: CloudflareTracing;
80
- private readonly options: ResolvedOptions;
81
-
82
- constructor(tracing: CloudflareTracing, options: ResolvedOptions) {
83
- this.tracing = tracing;
84
- this.options = options;
85
- }
86
-
87
- async startSpan<T>(
88
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
89
- callback: (span: TelemetrySpan) => T | Promise<T>,
90
- ): Promise<T> {
91
- return await this.tracing.enterSpan(options.name, (nativeSpan) => {
92
- const span = new CloudflareTelemetrySpan(this.tracing, nativeSpan, this.options);
93
- if (options.attributes) span.setAttributes(options.attributes);
94
- for (const link of options.links ?? []) span.addLink(link);
95
-
96
- let result: T | Promise<T>;
97
- try {
98
- result = callback(span);
99
- } catch (error) {
100
- span.finishError(error);
101
- return Promise.reject(error);
102
- }
103
-
104
- return Promise.resolve(result).then(
105
- (value) => {
106
- span.finishSuccess();
107
- return value;
108
- },
109
- (error: unknown) => {
110
- span.finishError(error);
111
- throw error;
112
- },
113
- );
114
- });
115
- }
116
- }
117
-
118
- class CloudflareTelemetrySpan implements TelemetrySpan {
119
- private settled = false;
120
- private explicitStatus = false;
121
- private eventCount = 0;
122
- private linkCount = 0;
123
- private readonly tracing: CloudflareTracing;
124
- private readonly nativeSpan: CloudflareSpan;
125
- private readonly options: ResolvedOptions;
126
-
127
- constructor(
128
- tracing: CloudflareTracing,
129
- nativeSpan: CloudflareSpan,
130
- options: ResolvedOptions,
131
- ) {
132
- this.tracing = tracing;
133
- this.nativeSpan = nativeSpan;
134
- this.options = options;
135
- }
136
-
137
- startSpan<T>(
138
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
139
- callback: (span: TelemetrySpan) => T | Promise<T>,
140
- ): Promise<T> {
141
- return new CloudflareTelemetryContext(this.tracing, this.options).startSpan(options, callback);
142
- }
143
-
144
- addLink(link: TelemetryLink): void {
145
- if (this.settled || this.linkCount >= this.options.maxLinksPerSpan) return;
146
- if (!(link.context instanceof CloudflareTelemetrySpan)) return;
147
-
148
- const index = this.linkCount++;
149
- const context = link.context.nativeSpan.spanContext();
150
- this.nativeSpan.setAttributes({
151
- [`link.${index}.trace_id`]: context.traceId,
152
- [`link.${index}.span_id`]: context.spanId,
153
- ...prefixAttributes(`link.${index}.attribute.`, link.attributes),
154
- });
155
- }
156
-
157
- addEvent(name: string, attributes?: SpanAttributes): void {
158
- if (this.settled || this.eventCount >= this.options.maxEventsPerSpan) return;
159
- const index = this.eventCount++;
160
- this.nativeSpan.setAttributes({
161
- [`event.${index}.name`]: name,
162
- ...prefixAttributes(`event.${index}.attribute.`, attributes),
163
- });
164
- }
165
-
166
- setAttributes(attributes: SpanAttributes): void {
167
- if (this.settled) return;
168
- this.nativeSpan.setAttributes(normalizeAttributes(attributes));
169
- }
170
-
171
- setStatus(status: TelemetryStatus): void {
172
- if (this.settled) return;
173
- this.explicitStatus = true;
174
- if (status.status === "ok") {
175
- this.nativeSpan.setStatus({ code: "ok" });
176
- return;
177
- }
178
-
179
- const message = this.options.includeErrorMessages
180
- ? status.error?.message.slice(0, MAX_ERROR_MESSAGE)
181
- : undefined;
182
- this.nativeSpan.setAttributes({ "error.name": status.error?.name });
183
- this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
184
- }
185
-
186
- finishSuccess(): void {
187
- if (this.settled) return;
188
- if (!this.explicitStatus) this.nativeSpan.setStatus({ code: "ok" });
189
- this.settled = true;
190
- }
191
-
192
- finishError(error: unknown): void {
193
- if (this.settled) return;
194
- const name = error instanceof Error ? error.name : "UnknownError";
195
- const message =
196
- this.options.includeErrorMessages && error instanceof Error
197
- ? error.message.slice(0, MAX_ERROR_MESSAGE)
198
- : undefined;
199
- this.nativeSpan.setAttributes({ "error.name": name });
200
- this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
201
- this.settled = true;
202
- }
203
- }
204
-
205
- function normalizeAttributes(
206
- attributes: SpanAttributes | undefined,
207
- ): Record<string, string | number | boolean | undefined> {
208
- const normalized: Record<string, string | number | boolean | undefined> = {};
209
- for (const [name, value] of Object.entries(attributes ?? {})) {
210
- normalized[name] =
211
- value !== undefined && typeof value === "object" ? JSON.stringify(value) : value;
212
- }
213
- return normalized;
214
- }
215
-
216
- function prefixAttributes(
217
- prefix: string,
218
- attributes: SpanAttributes | undefined,
219
- ): Record<string, string | number | boolean | undefined> {
220
- const prefixed: Record<string, string | number | boolean | undefined> = {};
221
- for (const [name, value] of Object.entries(normalizeAttributes(attributes))) {
222
- prefixed[`${prefix}${name}`] = value;
223
- }
224
- return prefixed;
225
- }