@introspection-sdk/introspection-pi 0.4.1

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,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 Introspection AI Inc.
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # introspection-pi
2
+
3
+ Introspection observability extension for the
4
+ [Pi Agent SDK](https://github.com/badlogic/pi-mono) — emits OpenTelemetry
5
+ [GenAI semantic-convention](https://opentelemetry.io/docs/specs/semconv/gen-ai/)
6
+ spans for chat completions and tool execution.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install @introspection-sdk/introspection-pi \
12
+ @opentelemetry/api \
13
+ @mariozechner/pi-ai \
14
+ @mariozechner/pi-agent-core
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import { trace } from "@opentelemetry/api";
21
+ import { Agent } from "@mariozechner/pi-agent-core";
22
+ import {
23
+ instrumentAgent,
24
+ instrumentStream,
25
+ type AgentMeta,
26
+ } from "@introspection-sdk/introspection-pi";
27
+
28
+ const tracer = trace.getTracer("my-app");
29
+ const meta: AgentMeta = {
30
+ conversationId: "conv_123",
31
+ agentId: "support-agent",
32
+ agentName: "Support",
33
+ };
34
+
35
+ const agent = new Agent({
36
+ /* … */
37
+ });
38
+
39
+ // One chat span per LLM call
40
+ agent.streamFn = instrumentStream(agent.streamFn, { tracer, meta });
41
+
42
+ // One execute_tool span per tool call
43
+ const tools = instrumentAgent(agent, { tracer, meta });
44
+
45
+ // Later, on shutdown:
46
+ tools.stop();
47
+ ```
48
+
49
+ ### Adding caller-specific attributes
50
+
51
+ Use the `extraAttributes` hook to layer non-semconv attributes on every
52
+ chat span (tenant labels, correlation IDs, feature flags):
53
+
54
+ ```ts
55
+ agent.streamFn = instrumentStream(agent.streamFn, {
56
+ tracer,
57
+ meta,
58
+ extraAttributes: (model, ctx) => ({
59
+ "introspection.byok": !process.env.PROXY_KEY,
60
+ "tenant.id": meta.conversationId,
61
+ }),
62
+ });
63
+ ```
64
+
65
+ ### Parenting spans under a turn span
66
+
67
+ If you wrap an entire user turn in your own span, pass
68
+ `getParentContext` so each chat / tool span lands under it:
69
+
70
+ ```ts
71
+ const turnSpan = tracer.startSpan(`turn ${meta.agentName}`);
72
+ const turnContext = trace.setSpan(context.active(), turnSpan);
73
+
74
+ agent.streamFn = instrumentStream(agent.streamFn, {
75
+ tracer,
76
+ meta,
77
+ getParentContext: () => turnContext,
78
+ });
79
+ ```
80
+
81
+ ## What gets emitted
82
+
83
+ For each LLM call (`chat ${provider}` span):
84
+
85
+ - `gen_ai.conversation.id`, `gen_ai.agent.id`, `gen_ai.agent.name`
86
+ - `gen_ai.operation.name = "chat"`
87
+ - `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`
88
+ - `gen_ai.system_instructions`, `gen_ai.tool.definitions`
89
+ - `gen_ai.input.messages`, `gen_ai.output.messages`
90
+ - `gen_ai.response.id`, `gen_ai.response.finish_reasons`
91
+ - `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`
92
+ - `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens` (when > 0)
93
+ - `gen_ai.cost.usd` (when reported)
94
+
95
+ For each tool call (`execute_tool ${tool_name}` span):
96
+
97
+ - `gen_ai.conversation.id`, `gen_ai.agent.id`, `gen_ai.agent.name`
98
+ - `gen_ai.operation.name = "execute_tool"`
99
+ - `gen_ai.tool.name`, `gen_ai.tool.type`, `gen_ai.tool.call.id`
100
+ - `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`
101
+ - Errors are recorded via `span.recordException` and `setStatus(ERROR)`
102
+
103
+ ## License
104
+
105
+ Apache-2.0
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Attribute-record builders for chat / execute_tool spans.
3
+ *
4
+ * Builds plain `Attributes` records rather than mutating spans so callers
5
+ * can inspect, log, and merge with their own attributes (`extraAttributes`
6
+ * hook, environment-derived tenant labels, etc.).
7
+ */
8
+ import type { Attributes } from "@opentelemetry/api";
9
+ import type { AssistantMessage, Context, Model } from "@mariozechner/pi-ai";
10
+ /** Metadata that the consumer attaches to every chat / tool span. */
11
+ export interface AgentMeta {
12
+ conversationId: string;
13
+ agentId: string;
14
+ agentName: string;
15
+ }
16
+ /** Attributes set on a chat span at request time, before the model has streamed. */
17
+ export declare function chatRequestAttributes(model: Model<string>, context: Context, meta: AgentMeta): Attributes;
18
+ /**
19
+ * Attributes set on a chat span when the assistant message has settled.
20
+ *
21
+ * Cache usage fields are only set when > 0, matching the OTel semconv
22
+ * convention that an absent attribute means "not reported by provider".
23
+ */
24
+ export declare function chatResponseAttributes(message: AssistantMessage): Attributes;
25
+ /** Common attributes for an execute_tool span (set at start). */
26
+ export declare function executeToolAttributes(toolName: string, toolCallId: string, args: unknown, meta: AgentMeta): Attributes;
27
+ /** Result attribute for an execute_tool span (set at end). */
28
+ export declare function executeToolResultAttribute(result: unknown): Attributes;
29
+ //# sourceMappingURL=attributes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attributes.d.ts","sourceRoot":"","sources":["../src/attributes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EACV,gBAAgB,EAChB,OAAO,EACP,KAAK,EAEN,MAAM,qBAAqB,CAAC;AAU7B,qEAAqE;AACrE,MAAM,WAAW,SAAS;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,oFAAoF;AACpF,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,EACpB,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,SAAS,GACd,UAAU,CA+BZ;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,gBAAgB,GAAG,UAAU,CA0B5E;AAED,iEAAiE;AACjE,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,SAAS,GACd,UAAU,CAcZ;AAED,8DAA8D;AAC9D,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,OAAO,GAAG,UAAU,CAGtE"}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Attribute-record builders for chat / execute_tool spans.
3
+ *
4
+ * Builds plain `Attributes` records rather than mutating spans so callers
5
+ * can inspect, log, and merge with their own attributes (`extraAttributes`
6
+ * hook, environment-derived tenant labels, etc.).
7
+ */
8
+ import { GenAi } from "@introspection-sdk/types";
9
+ import { assistantToOutputMessages, messagesToInputMessages, systemPromptToInstructions, } from "./convert.js";
10
+ const MAX_BYTES = 64_000;
11
+ /** Attributes set on a chat span at request time, before the model has streamed. */
12
+ export function chatRequestAttributes(model, context, meta) {
13
+ const attributes = {
14
+ [GenAi.CONVERSATION_ID]: meta.conversationId,
15
+ [GenAi.AGENT_ID]: meta.agentId,
16
+ [GenAi.AGENT_NAME]: meta.agentName,
17
+ [GenAi.OPERATION_NAME]: "chat",
18
+ [GenAi.PROVIDER_NAME]: model.provider,
19
+ [GenAi.REQUEST_MODEL]: model.id,
20
+ };
21
+ if (context.systemPrompt) {
22
+ const serialized = serializeWithCap(() => JSON.stringify(systemPromptToInstructions(context.systemPrompt)), () => undefined, GenAi.SYSTEM_INSTRUCTIONS);
23
+ if (serialized) {
24
+ attributes[GenAi.SYSTEM_INSTRUCTIONS] = serialized;
25
+ }
26
+ }
27
+ const toolDefinitions = serializeToolDefinitions(context.tools);
28
+ if (toolDefinitions) {
29
+ attributes[GenAi.TOOL_DEFINITIONS] = toolDefinitions;
30
+ }
31
+ attributes[GenAi.INPUT_MESSAGES] = JSON.stringify(messagesToInputMessages(context.messages));
32
+ return attributes;
33
+ }
34
+ /**
35
+ * Attributes set on a chat span when the assistant message has settled.
36
+ *
37
+ * Cache usage fields are only set when > 0, matching the OTel semconv
38
+ * convention that an absent attribute means "not reported by provider".
39
+ */
40
+ export function chatResponseAttributes(message) {
41
+ const attributes = {
42
+ [GenAi.OUTPUT_MESSAGES]: JSON.stringify(assistantToOutputMessages(message)),
43
+ [GenAi.RESPONSE_FINISH_REASONS]: JSON.stringify([message.stopReason]),
44
+ [GenAi.USAGE_INPUT_TOKENS]: message.usage.input,
45
+ [GenAi.USAGE_OUTPUT_TOKENS]: message.usage.output,
46
+ };
47
+ if (message.usage.cacheRead > 0) {
48
+ attributes[GenAi.USAGE_CACHE_READ_INPUT_TOKENS] = message.usage.cacheRead;
49
+ }
50
+ if (message.usage.cacheWrite > 0) {
51
+ attributes[GenAi.USAGE_CACHE_CREATION_INPUT_TOKENS] =
52
+ message.usage.cacheWrite;
53
+ }
54
+ if (message.usage.cost?.total) {
55
+ attributes[GenAi.COST_USD] = message.usage.cost.total;
56
+ }
57
+ if (message.responseId) {
58
+ attributes[GenAi.RESPONSE_ID] = message.responseId;
59
+ }
60
+ if (message.model) {
61
+ attributes[GenAi.RESPONSE_MODEL] = message.model;
62
+ }
63
+ return attributes;
64
+ }
65
+ /** Common attributes for an execute_tool span (set at start). */
66
+ export function executeToolAttributes(toolName, toolCallId, args, meta) {
67
+ const attributes = {
68
+ [GenAi.CONVERSATION_ID]: meta.conversationId,
69
+ [GenAi.AGENT_ID]: meta.agentId,
70
+ [GenAi.AGENT_NAME]: meta.agentName,
71
+ [GenAi.OPERATION_NAME]: "execute_tool",
72
+ [GenAi.TOOL_NAME]: toolName,
73
+ [GenAi.TOOL_TYPE]: "function",
74
+ [GenAi.TOOL_CALL_ID]: toolCallId,
75
+ };
76
+ if (args !== undefined) {
77
+ attributes[GenAi.TOOL_CALL_ARGUMENTS] = stringify(args);
78
+ }
79
+ return attributes;
80
+ }
81
+ /** Result attribute for an execute_tool span (set at end). */
82
+ export function executeToolResultAttribute(result) {
83
+ if (result === undefined)
84
+ return {};
85
+ return { [GenAi.TOOL_CALL_RESULT]: stringify(result) };
86
+ }
87
+ // ─────────────────────────────────────────────────────────────────────────────
88
+ // Internals
89
+ // ─────────────────────────────────────────────────────────────────────────────
90
+ function serializeToolDefinitions(tools) {
91
+ if (!tools || tools.length === 0)
92
+ return undefined;
93
+ const detailed = tools.map((tool) => ({
94
+ name: tool.name,
95
+ description: tool.description,
96
+ parameters: tool.parameters,
97
+ }));
98
+ return serializeWithCap(() => JSON.stringify(detailed.map((def) => ({ type: "function", ...def }))), () => JSON.stringify(detailed.map((def) => ({ type: "function", name: def.name }))), GenAi.TOOL_DEFINITIONS);
99
+ }
100
+ /**
101
+ * Try the detailed serializer; if it exceeds the cap, try a compact fallback;
102
+ * if that still exceeds, drop the attribute (returns undefined).
103
+ */
104
+ function serializeWithCap(detailed, compact, attributeName) {
105
+ const fullPayload = detailed();
106
+ if (byteLength(fullPayload) <= MAX_BYTES) {
107
+ return fullPayload;
108
+ }
109
+ const compactPayload = compact();
110
+ if (compactPayload && byteLength(compactPayload) <= MAX_BYTES) {
111
+ console.warn(`[introspection-pi] Compacting oversized ${attributeName} (${byteLength(fullPayload)} bytes)`);
112
+ return compactPayload;
113
+ }
114
+ console.warn(`[introspection-pi] Dropping oversized ${attributeName} (${byteLength(fullPayload)} bytes)`);
115
+ return undefined;
116
+ }
117
+ function byteLength(value) {
118
+ if (typeof Buffer !== "undefined") {
119
+ return Buffer.byteLength(value);
120
+ }
121
+ return new TextEncoder().encode(value).length;
122
+ }
123
+ function stringify(value) {
124
+ return typeof value === "string" ? value : JSON.stringify(value);
125
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Pure converters between strongly-typed pi-ai messages and the OTEL GenAI
3
+ * semantic-convention JSON shapes from `@introspection-sdk/types`.
4
+ *
5
+ * No OTel runtime dependency — these functions only return plain values, so
6
+ * they can be unit-tested without a tracer or span context.
7
+ */
8
+ import type { AssistantMessage, Message } from "@mariozechner/pi-ai";
9
+ import type { InputMessage, OutputMessage, SystemInstruction } from "@introspection-sdk/types";
10
+ /** Convert a `Message[]` (pi-ai source) to the `gen_ai.input.messages` shape. */
11
+ export declare function messagesToInputMessages(messages: readonly Message[]): InputMessage[];
12
+ /** Convert an `AssistantMessage` to the `gen_ai.output.messages` shape. */
13
+ export declare function assistantToOutputMessages(message: AssistantMessage): OutputMessage[];
14
+ /** Wrap a system prompt in the semconv shape used for `gen_ai.system_instructions`. */
15
+ export declare function systemPromptToInstructions(systemPrompt: string): SystemInstruction[];
16
+ /**
17
+ * Hydrate an array of semconv messages back into pi-ai `Message[]`.
18
+ *
19
+ * - Drops messages whose `parts` are empty.
20
+ * - Resolves a `tool_call_response` `name` from a preceding assistant
21
+ * `tool_call` part if absent.
22
+ * - Drops orphaned tool results — sending them back to a model would
23
+ * break the assistant→tool_result pairing the providers expect.
24
+ * - Strips trailing assistant `tool_call` blocks that never received a
25
+ * matching tool result (e.g. an aborted turn).
26
+ */
27
+ export declare function inputMessagesToMessages(messages: readonly InputMessage[]): Message[];
28
+ //# sourceMappingURL=convert.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convert.d.ts","sourceRoot":"","sources":["../src/convert.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EACV,gBAAgB,EAEhB,OAAO,EAMR,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EACV,YAAY,EAEZ,aAAa,EAEb,iBAAiB,EAIlB,MAAM,0BAA0B,CAAC;AAMlC,iFAAiF;AACjF,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,SAAS,OAAO,EAAE,GAC3B,YAAY,EAAE,CAOhB;AAED,2EAA2E;AAC3E,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,gBAAgB,GACxB,aAAa,EAAE,CAGjB;AAED,uFAAuF;AACvF,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,MAAM,GACnB,iBAAiB,EAAE,CAErB;AAqJD;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAChC,OAAO,EAAE,CA2DX"}
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Pure converters between strongly-typed pi-ai messages and the OTEL GenAI
3
+ * semantic-convention JSON shapes from `@introspection-sdk/types`.
4
+ *
5
+ * No OTel runtime dependency — these functions only return plain values, so
6
+ * they can be unit-tested without a tracer or span context.
7
+ */
8
+ // ─────────────────────────────────────────────────────────────────────────────
9
+ // pi-ai → semconv
10
+ // ─────────────────────────────────────────────────────────────────────────────
11
+ /** Convert a `Message[]` (pi-ai source) to the `gen_ai.input.messages` shape. */
12
+ export function messagesToInputMessages(messages) {
13
+ const result = [];
14
+ for (const message of messages) {
15
+ const converted = messageToSemconv(message);
16
+ if (converted)
17
+ result.push(converted);
18
+ }
19
+ return result;
20
+ }
21
+ /** Convert an `AssistantMessage` to the `gen_ai.output.messages` shape. */
22
+ export function assistantToOutputMessages(message) {
23
+ const semconv = assistantMessageToSemconv(message);
24
+ return [outputMessageFromSemconv(semconv, message)];
25
+ }
26
+ /** Wrap a system prompt in the semconv shape used for `gen_ai.system_instructions`. */
27
+ export function systemPromptToInstructions(systemPrompt) {
28
+ return [{ type: "text", content: systemPrompt }];
29
+ }
30
+ function messageToSemconv(message) {
31
+ switch (message.role) {
32
+ case "user":
33
+ return userMessageToSemconv(message);
34
+ case "assistant": {
35
+ const semconv = assistantMessageToSemconv(message);
36
+ // For input messages we include the assistant message as-is (no
37
+ // finish_reason / response_id metadata at the input layer).
38
+ return { role: "assistant", parts: semconv.parts };
39
+ }
40
+ case "toolResult":
41
+ return toolResultToSemconv(message);
42
+ }
43
+ }
44
+ function userMessageToSemconv(message) {
45
+ const text = typeof message.content === "string"
46
+ ? message.content
47
+ : extractTextFromUserContent(message.content);
48
+ return {
49
+ role: "user",
50
+ parts: [{ type: "text", content: text }],
51
+ };
52
+ }
53
+ function assistantMessageToSemconv(message) {
54
+ const parts = [];
55
+ for (const block of message.content) {
56
+ const part = assistantBlockToPart(block);
57
+ if (part)
58
+ parts.push(part);
59
+ }
60
+ const result = { parts };
61
+ if (message.stopReason)
62
+ result.finish_reason = message.stopReason;
63
+ if (message.api)
64
+ result.api = message.api;
65
+ if (message.provider)
66
+ result.provider = message.provider;
67
+ if (message.model)
68
+ result.model = message.model;
69
+ if (message.responseId)
70
+ result.response_id = message.responseId;
71
+ return result;
72
+ }
73
+ function outputMessageFromSemconv(semconv, source) {
74
+ const result = { role: "assistant", parts: semconv.parts };
75
+ if (semconv.finish_reason)
76
+ result.finish_reason = semconv.finish_reason;
77
+ if (semconv.api)
78
+ result.api = semconv.api;
79
+ if (semconv.provider ?? source.provider) {
80
+ result.provider = semconv.provider ?? source.provider;
81
+ }
82
+ if (semconv.model ?? source.model) {
83
+ result.model = semconv.model ?? source.model;
84
+ }
85
+ if (semconv.response_id ?? source.responseId) {
86
+ result.response_id = semconv.response_id ?? source.responseId;
87
+ }
88
+ return result;
89
+ }
90
+ function toolResultToSemconv(message) {
91
+ return {
92
+ role: "tool",
93
+ name: message.toolName,
94
+ parts: [
95
+ {
96
+ type: "tool_call_response",
97
+ id: message.toolCallId,
98
+ name: message.toolName,
99
+ response: extractToolResultText(message.content),
100
+ },
101
+ ],
102
+ };
103
+ }
104
+ function assistantBlockToPart(block) {
105
+ switch (block.type) {
106
+ case "text": {
107
+ if (!block.text)
108
+ return null;
109
+ const part = { type: "text", content: block.text };
110
+ if (block.textSignature) {
111
+ part.text_signature = block.textSignature;
112
+ }
113
+ return part;
114
+ }
115
+ case "thinking": {
116
+ if (!block.thinking && !block.thinkingSignature)
117
+ return null;
118
+ const part = {
119
+ type: "thinking",
120
+ content: block.thinking ?? "",
121
+ };
122
+ if (block.thinkingSignature) {
123
+ part.signature = block.thinkingSignature;
124
+ }
125
+ if (block.redacted) {
126
+ part.redacted = true;
127
+ }
128
+ return part;
129
+ }
130
+ case "toolCall": {
131
+ const part = {
132
+ type: "tool_call",
133
+ name: block.name,
134
+ id: block.id,
135
+ arguments: block.arguments,
136
+ };
137
+ return part;
138
+ }
139
+ }
140
+ }
141
+ function extractTextFromUserContent(blocks) {
142
+ return blocks
143
+ .map((block) => (block.type === "text" ? block.text : ""))
144
+ .filter(Boolean)
145
+ .join("");
146
+ }
147
+ function extractToolResultText(content) {
148
+ if (typeof content === "string")
149
+ return content;
150
+ if (!Array.isArray(content))
151
+ return "";
152
+ return content
153
+ .map((block) => (block.type === "text" ? block.text : ""))
154
+ .filter(Boolean)
155
+ .join("\n");
156
+ }
157
+ // ─────────────────────────────────────────────────────────────────────────────
158
+ // semconv → pi-ai
159
+ // ─────────────────────────────────────────────────────────────────────────────
160
+ /**
161
+ * Hydrate an array of semconv messages back into pi-ai `Message[]`.
162
+ *
163
+ * - Drops messages whose `parts` are empty.
164
+ * - Resolves a `tool_call_response` `name` from a preceding assistant
165
+ * `tool_call` part if absent.
166
+ * - Drops orphaned tool results — sending them back to a model would
167
+ * break the assistant→tool_result pairing the providers expect.
168
+ * - Strips trailing assistant `tool_call` blocks that never received a
169
+ * matching tool result (e.g. an aborted turn).
170
+ */
171
+ export function inputMessagesToMessages(messages) {
172
+ if (messages.length === 0)
173
+ return [];
174
+ const result = [];
175
+ const toolNameById = new Map();
176
+ for (const message of messages) {
177
+ const parts = message.parts ?? [];
178
+ if (message.role === "user") {
179
+ const text = parts
180
+ .filter(isTextPart)
181
+ .map((part) => part.content)
182
+ .join("");
183
+ if (!text)
184
+ continue;
185
+ result.push({ role: "user", content: text, timestamp: 0 });
186
+ continue;
187
+ }
188
+ if (message.role === "assistant") {
189
+ const content = [];
190
+ for (const part of parts) {
191
+ const block = partToAssistantBlock(part, toolNameById);
192
+ if (block)
193
+ content.push(block);
194
+ }
195
+ if (content.length === 0)
196
+ continue;
197
+ result.push({
198
+ role: "assistant",
199
+ content,
200
+ api: "anthropic-messages",
201
+ provider: "anthropic",
202
+ model: "",
203
+ usage: emptyUsage(),
204
+ stopReason: "stop",
205
+ timestamp: 0,
206
+ });
207
+ continue;
208
+ }
209
+ if (message.role === "tool") {
210
+ for (const part of parts) {
211
+ if (!isToolCallResponsePart(part))
212
+ continue;
213
+ const id = part.id ?? "";
214
+ const toolName = part.name ?? message.name ?? toolNameById.get(id) ?? "";
215
+ if (!id || !toolName)
216
+ continue;
217
+ result.push({
218
+ role: "toolResult",
219
+ toolCallId: id,
220
+ toolName,
221
+ content: [{ type: "text", text: stringifyToolResult(part.response) }],
222
+ isError: false,
223
+ timestamp: 0,
224
+ });
225
+ }
226
+ }
227
+ }
228
+ return sanitizeToolPairing(result);
229
+ }
230
+ function partToAssistantBlock(part, toolNameById) {
231
+ if (isTextPart(part)) {
232
+ if (!part.content)
233
+ return null;
234
+ const block = { type: "text", text: part.content };
235
+ if (part.text_signature)
236
+ block.textSignature = part.text_signature;
237
+ return block;
238
+ }
239
+ if (isReasoningPart(part)) {
240
+ if (!part.content && !part.signature)
241
+ return null;
242
+ const block = {
243
+ type: "thinking",
244
+ thinking: part.content ?? "",
245
+ };
246
+ if (part.signature)
247
+ block.thinkingSignature = part.signature;
248
+ if (part.redacted)
249
+ block.redacted = true;
250
+ return block;
251
+ }
252
+ if (isToolCallRequestPart(part)) {
253
+ if (part.id && part.name) {
254
+ toolNameById.set(part.id, part.name);
255
+ }
256
+ return {
257
+ type: "toolCall",
258
+ id: part.id ?? "",
259
+ name: part.name,
260
+ arguments: parseToolArguments(part.arguments),
261
+ };
262
+ }
263
+ return null;
264
+ }
265
+ function parseToolArguments(value) {
266
+ if (typeof value === "string") {
267
+ try {
268
+ const parsed = JSON.parse(value);
269
+ return typeof parsed === "object" && parsed !== null
270
+ ? parsed
271
+ : {};
272
+ }
273
+ catch {
274
+ return {};
275
+ }
276
+ }
277
+ if (typeof value === "object" && value !== null) {
278
+ return value;
279
+ }
280
+ return {};
281
+ }
282
+ function stringifyToolResult(value) {
283
+ if (typeof value === "string")
284
+ return value;
285
+ if (value == null)
286
+ return "";
287
+ return JSON.stringify(value);
288
+ }
289
+ function emptyUsage() {
290
+ return {
291
+ input: 0,
292
+ output: 0,
293
+ cacheRead: 0,
294
+ cacheWrite: 0,
295
+ totalTokens: 0,
296
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
297
+ };
298
+ }
299
+ function sanitizeToolPairing(messages) {
300
+ const result = [];
301
+ let activeToolCallIds = new Set();
302
+ for (const message of messages) {
303
+ if (message.role === "assistant") {
304
+ activeToolCallIds = new Set();
305
+ for (const block of message.content) {
306
+ if (block.type === "toolCall" && block.id) {
307
+ activeToolCallIds.add(block.id);
308
+ }
309
+ }
310
+ result.push(message);
311
+ continue;
312
+ }
313
+ if (message.role === "toolResult") {
314
+ if (activeToolCallIds.has(message.toolCallId)) {
315
+ activeToolCallIds.delete(message.toolCallId);
316
+ result.push(message);
317
+ }
318
+ continue;
319
+ }
320
+ activeToolCallIds = new Set();
321
+ result.push(message);
322
+ }
323
+ if (activeToolCallIds.size === 0 || result.length === 0) {
324
+ return result;
325
+ }
326
+ for (let i = result.length - 1; i >= 0; i -= 1) {
327
+ const message = result[i];
328
+ if (!message || message.role !== "assistant")
329
+ continue;
330
+ const cleanedContent = message.content.filter((block) => !(block.type === "toolCall" &&
331
+ block.id &&
332
+ activeToolCallIds.has(block.id)));
333
+ if (cleanedContent.length === 0) {
334
+ result.splice(i, 1);
335
+ }
336
+ else if (cleanedContent.length !== message.content.length) {
337
+ result[i] = { ...message, content: cleanedContent };
338
+ }
339
+ break;
340
+ }
341
+ return result;
342
+ }
343
+ function isTextPart(part) {
344
+ return part.type === "text";
345
+ }
346
+ function isReasoningPart(part) {
347
+ return part.type === "thinking";
348
+ }
349
+ function isToolCallRequestPart(part) {
350
+ return part.type === "tool_call";
351
+ }
352
+ function isToolCallResponsePart(part) {
353
+ return part.type === "tool_call_response";
354
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @introspection-sdk/introspection-pi
3
+ *
4
+ * Introspection observability extension for the Pi Agent SDK
5
+ * (`@mariozechner/pi-ai`, `@mariozechner/pi-agent-core`).
6
+ *
7
+ * Emits OTel GenAI semantic-convention spans for chat completions
8
+ * (`chat ${provider}`) and tool execution (`execute_tool ${tool_name}`).
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { instrumentAgent, instrumentStream } from "@introspection-sdk/introspection-pi";
13
+ *
14
+ * agent.streamFn = instrumentStream(agent.streamFn, { tracer, meta });
15
+ * const tools = instrumentAgent(agent, { tracer, meta });
16
+ *
17
+ * // later: tools.stop();
18
+ * ```
19
+ */
20
+ export { instrumentStream, type InstrumentStreamOptions, } from "./instrument-stream.js";
21
+ export { instrumentAgent, type AgentInstrumentation, type InstrumentAgentOptions, } from "./instrument-agent.js";
22
+ export { chatRequestAttributes, chatResponseAttributes, executeToolAttributes, executeToolResultAttribute, type AgentMeta, } from "./attributes.js";
23
+ export { assistantToOutputMessages, inputMessagesToMessages, messagesToInputMessages, systemPromptToInstructions, } from "./convert.js";
24
+ export type { GenAiAttributes, InputMessage, MessagePart, MessageRole, OutputMessage, ReasoningPart, SystemInstruction, TextPart, ToolCallRequestPart, ToolCallResponsePart, ToolDefinition, } from "@introspection-sdk/types";
25
+ export { GenAi, GenAiSpanName, toAttributes } from "@introspection-sdk/types";
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EACL,gBAAgB,EAChB,KAAK,uBAAuB,GAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,eAAe,EACf,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,GAC5B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,KAAK,SAAS,GACf,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAGtB,YAAY,EACV,eAAe,EACf,YAAY,EACZ,WAAW,EACX,WAAW,EACX,aAAa,EACb,aAAa,EACb,iBAAiB,EACjB,QAAQ,EACR,mBAAmB,EACnB,oBAAoB,EACpB,cAAc,GACf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @introspection-sdk/introspection-pi
3
+ *
4
+ * Introspection observability extension for the Pi Agent SDK
5
+ * (`@mariozechner/pi-ai`, `@mariozechner/pi-agent-core`).
6
+ *
7
+ * Emits OTel GenAI semantic-convention spans for chat completions
8
+ * (`chat ${provider}`) and tool execution (`execute_tool ${tool_name}`).
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { instrumentAgent, instrumentStream } from "@introspection-sdk/introspection-pi";
13
+ *
14
+ * agent.streamFn = instrumentStream(agent.streamFn, { tracer, meta });
15
+ * const tools = instrumentAgent(agent, { tracer, meta });
16
+ *
17
+ * // later: tools.stop();
18
+ * ```
19
+ */
20
+ // Instrumentation
21
+ export { instrumentStream, } from "./instrument-stream.js";
22
+ export { instrumentAgent, } from "./instrument-agent.js";
23
+ // Attribute builders — exposed for callers that want to compose their own spans
24
+ export { chatRequestAttributes, chatResponseAttributes, executeToolAttributes, executeToolResultAttribute, } from "./attributes.js";
25
+ // Converters — exposed for telemetry replay (rebuilding pi-ai message arrays
26
+ // from stored span attributes) and downstream consumers that want the raw
27
+ // semconv shapes.
28
+ export { assistantToOutputMessages, inputMessagesToMessages, messagesToInputMessages, systemPromptToInstructions, } from "./convert.js";
29
+ export { GenAi, GenAiSpanName, toAttributes } from "@introspection-sdk/types";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Subscribe to a pi-agent {@link Agent} to emit `execute_tool` spans for every
3
+ * tool call the loop runs.
4
+ */
5
+ import { type Context as OtelContext, type Tracer } from "@opentelemetry/api";
6
+ import type { Agent } from "@mariozechner/pi-agent-core";
7
+ import { type AgentMeta } from "./attributes.js";
8
+ export interface InstrumentAgentOptions {
9
+ /** Tracer to start the execute_tool spans on. */
10
+ tracer: Tracer;
11
+ /** Required metadata stamped onto every execute_tool span. */
12
+ meta: AgentMeta;
13
+ /**
14
+ * Returns the parent OTel context for the next tool span. If undefined or
15
+ * returns null, `context.active()` is used at the time the start event fires.
16
+ */
17
+ getParentContext?: () => OtelContext | null | undefined;
18
+ /** Override the default span name builder. */
19
+ spanName?: (toolName: string) => string;
20
+ }
21
+ export interface AgentInstrumentation {
22
+ /** Stop subscribing and finalize any tool spans still open. */
23
+ stop: () => void;
24
+ }
25
+ /**
26
+ * Subscribe to {@link Agent.subscribe} and emit one `execute_tool ${name}`
27
+ * span per tool call. Returns a handle whose `stop()` unsubscribes and
28
+ * finalizes any still-open spans.
29
+ *
30
+ * Tool call IDs are assumed unique per agent run; concurrent tool execution
31
+ * (`ToolExecutionMode = "parallel"`) is supported because each id keys its
32
+ * own span entry.
33
+ */
34
+ export declare function instrumentAgent(agent: Agent, opts: InstrumentAgentOptions): AgentInstrumentation;
35
+ //# sourceMappingURL=instrument-agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrument-agent.d.ts","sourceRoot":"","sources":["../src/instrument-agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAKL,KAAK,OAAO,IAAI,WAAW,EAE3B,KAAK,MAAM,EACZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,KAAK,EAAc,MAAM,6BAA6B,CAAC;AAErE,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,sBAAsB;IACrC,iDAAiD;IACjD,MAAM,EAAE,MAAM,CAAC;IACf,8DAA8D;IAC9D,IAAI,EAAE,SAAS,CAAC;IAChB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,WAAW,GAAG,IAAI,GAAG,SAAS,CAAC;IACxD,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,MAAM,CAAC;CACzC;AAED,MAAM,WAAW,oBAAoB;IACnC,+DAA+D;IAC/D,IAAI,EAAE,MAAM,IAAI,CAAC;CAClB;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,sBAAsB,GAC3B,oBAAoB,CAkBtB"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Subscribe to a pi-agent {@link Agent} to emit `execute_tool` spans for every
3
+ * tool call the loop runs.
4
+ */
5
+ import { context as otelContext, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
6
+ import { GenAiSpanName } from "@introspection-sdk/types";
7
+ import { executeToolAttributes, executeToolResultAttribute, } from "./attributes.js";
8
+ /**
9
+ * Subscribe to {@link Agent.subscribe} and emit one `execute_tool ${name}`
10
+ * span per tool call. Returns a handle whose `stop()` unsubscribes and
11
+ * finalizes any still-open spans.
12
+ *
13
+ * Tool call IDs are assumed unique per agent run; concurrent tool execution
14
+ * (`ToolExecutionMode = "parallel"`) is supported because each id keys its
15
+ * own span entry.
16
+ */
17
+ export function instrumentAgent(agent, opts) {
18
+ const buildSpanName = opts.spanName ?? GenAiSpanName.executeTool;
19
+ const activeSpans = new Map();
20
+ const unsubscribe = agent.subscribe((event) => {
21
+ handleEvent(event, opts, activeSpans, buildSpanName);
22
+ });
23
+ return {
24
+ stop: () => {
25
+ unsubscribe();
26
+ for (const span of activeSpans.values()) {
27
+ span.setStatus({ code: SpanStatusCode.OK });
28
+ span.end();
29
+ }
30
+ activeSpans.clear();
31
+ },
32
+ };
33
+ }
34
+ function handleEvent(event, opts, activeSpans, buildSpanName) {
35
+ switch (event.type) {
36
+ case "tool_execution_start": {
37
+ const parentContext = opts.getParentContext?.() ?? otelContext.active();
38
+ const span = opts.tracer.startSpan(buildSpanName(event.toolName), { kind: SpanKind.INTERNAL }, parentContext ?? undefined);
39
+ span.setAttributes(executeToolAttributes(event.toolName, event.toolCallId, event.args, opts.meta));
40
+ // Activate the tool span as the current OTel context for the duration
41
+ // of the tool execution. Pi runs tool execution in user code, so any
42
+ // child spans created inside the tool implementation should parent to
43
+ // this span automatically.
44
+ otelContext.with(trace.setSpan(parentContext ?? otelContext.active(), span), () => { });
45
+ activeSpans.set(event.toolCallId, span);
46
+ return;
47
+ }
48
+ case "tool_execution_end": {
49
+ const span = activeSpans.get(event.toolCallId);
50
+ if (!span)
51
+ return;
52
+ activeSpans.delete(event.toolCallId);
53
+ span.setAttributes(executeToolResultAttribute(event.result));
54
+ if (event.isError) {
55
+ span.setStatus({
56
+ code: SpanStatusCode.ERROR,
57
+ message: typeof event.result === "string"
58
+ ? event.result
59
+ : event.result !== undefined
60
+ ? safeStringify(event.result)
61
+ : undefined,
62
+ });
63
+ }
64
+ else {
65
+ span.setStatus({ code: SpanStatusCode.OK });
66
+ }
67
+ span.end();
68
+ return;
69
+ }
70
+ default:
71
+ return;
72
+ }
73
+ }
74
+ function safeStringify(value) {
75
+ try {
76
+ return JSON.stringify(value);
77
+ }
78
+ catch {
79
+ return String(value);
80
+ }
81
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Wrap a pi-agent `StreamFn` so each invocation emits a `chat` span that
3
+ * conforms to the OTEL GenAI semantic convention.
4
+ */
5
+ import { type Attributes, type Context as OtelContext, type Tracer } from "@opentelemetry/api";
6
+ import { type Context, type Model } from "@mariozechner/pi-ai";
7
+ import type { StreamFn } from "@mariozechner/pi-agent-core";
8
+ import { type AgentMeta } from "./attributes.js";
9
+ export interface InstrumentStreamOptions {
10
+ /** Tracer to start the chat span on. */
11
+ tracer: Tracer;
12
+ /** Required metadata stamped onto every chat span. */
13
+ meta: AgentMeta;
14
+ /**
15
+ * Returns the parent OTel context for the next chat span. If undefined or
16
+ * returns null, `context.active()` is used at call time.
17
+ */
18
+ getParentContext?: () => OtelContext | null | undefined;
19
+ /**
20
+ * Caller-specific attributes (e.g. tenant labels, correlation IDs) layered
21
+ * on top of the GenAI semconv attributes for each chat span.
22
+ */
23
+ extraAttributes?: (model: Model<string>, context: Context) => Attributes;
24
+ /** Override the default span name builder. */
25
+ spanName?: (model: Model<string>, context: Context) => string;
26
+ }
27
+ /**
28
+ * Wrap a {@link StreamFn} to emit `chat ${provider}` spans.
29
+ *
30
+ * Reassign `agent.streamFn` with the result:
31
+ *
32
+ * ```ts
33
+ * agent.streamFn = instrumentStream(agent.streamFn, { tracer, meta });
34
+ * ```
35
+ *
36
+ * The wrapper preserves the {@link StreamFn} contract: errors thrown by the
37
+ * underlying `streamFn` are surfaced through the returned event stream as
38
+ * `error` events, never thrown synchronously.
39
+ */
40
+ export declare function instrumentStream(streamFn: StreamFn, opts: InstrumentStreamOptions): StreamFn;
41
+ //# sourceMappingURL=instrument-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrument-stream.d.ts","sourceRoot":"","sources":["../src/instrument-stream.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAKL,KAAK,UAAU,EACf,KAAK,OAAO,IAAI,WAAW,EAE3B,KAAK,MAAM,EACZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAKL,KAAK,OAAO,EACZ,KAAK,KAAK,EACX,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAE5D,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,uBAAuB;IACtC,wCAAwC;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,IAAI,EAAE,SAAS,CAAC;IAChB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,WAAW,GAAG,IAAI,GAAG,SAAS,CAAC;IACxD;;;OAGG;IACH,eAAe,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,UAAU,CAAC;IACzE,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;CAC/D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,uBAAuB,GAC5B,QAAQ,CAqCV"}
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Wrap a pi-agent `StreamFn` so each invocation emits a `chat` span that
3
+ * conforms to the OTEL GenAI semantic convention.
4
+ */
5
+ import { context as otelContext, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
6
+ import { createAssistantMessageEventStream, } from "@mariozechner/pi-ai";
7
+ import { GenAiSpanName } from "@introspection-sdk/types";
8
+ import { chatRequestAttributes, chatResponseAttributes, } from "./attributes.js";
9
+ /**
10
+ * Wrap a {@link StreamFn} to emit `chat ${provider}` spans.
11
+ *
12
+ * Reassign `agent.streamFn` with the result:
13
+ *
14
+ * ```ts
15
+ * agent.streamFn = instrumentStream(agent.streamFn, { tracer, meta });
16
+ * ```
17
+ *
18
+ * The wrapper preserves the {@link StreamFn} contract: errors thrown by the
19
+ * underlying `streamFn` are surfaced through the returned event stream as
20
+ * `error` events, never thrown synchronously.
21
+ */
22
+ export function instrumentStream(streamFn, opts) {
23
+ const buildSpanName = opts.spanName ?? ((model) => GenAiSpanName.chat(model.provider));
24
+ return ((model, context, options) => {
25
+ const parentContext = opts.getParentContext?.() ?? otelContext.active();
26
+ const span = opts.tracer.startSpan(buildSpanName(model, context), { kind: SpanKind.INTERNAL }, parentContext ?? undefined);
27
+ span.setAttributes(chatRequestAttributes(model, context, opts.meta));
28
+ const extra = opts.extraAttributes?.(model, context);
29
+ if (extra) {
30
+ span.setAttributes(extra);
31
+ }
32
+ const proxy = createAssistantMessageEventStream();
33
+ const spanContext = trace.setSpan(parentContext ?? otelContext.active(), span);
34
+ void runUpstream({
35
+ streamFn,
36
+ model,
37
+ context,
38
+ options,
39
+ spanContext,
40
+ span,
41
+ proxy,
42
+ });
43
+ return proxy;
44
+ });
45
+ }
46
+ async function runUpstream({ streamFn, model, context, options, spanContext, span, proxy, }) {
47
+ let finished = false;
48
+ try {
49
+ const upstream = await otelContext.with(spanContext, () => streamFn(model, context, options));
50
+ for await (const event of upstream) {
51
+ proxy.push(event);
52
+ if (!finished && (event.type === "done" || event.type === "error")) {
53
+ finished = true;
54
+ finishSpan(span, event);
55
+ }
56
+ }
57
+ }
58
+ catch (err) {
59
+ const errorMessage = err instanceof Error ? err.message : String(err);
60
+ const errorEvent = {
61
+ type: "error",
62
+ reason: "error",
63
+ error: assistantErrorMessage(model, errorMessage),
64
+ };
65
+ span.recordException(err instanceof Error ? err : new Error(errorMessage));
66
+ proxy.push(errorEvent);
67
+ if (!finished) {
68
+ finished = true;
69
+ finishSpan(span, errorEvent);
70
+ }
71
+ }
72
+ finally {
73
+ if (!finished) {
74
+ // Upstream ended without a terminal event — close the span anyway so
75
+ // we don't leak.
76
+ span.setStatus({ code: SpanStatusCode.OK });
77
+ span.end();
78
+ }
79
+ }
80
+ }
81
+ function finishSpan(span, event) {
82
+ const message = event.type === "done" ? event.message : event.error;
83
+ span.setAttributes(chatResponseAttributes(message));
84
+ if (event.type === "error" || message.stopReason === "error") {
85
+ const errorMessage = message.errorMessage ?? "Unknown error";
86
+ span.recordException(new Error(errorMessage));
87
+ span.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage });
88
+ }
89
+ else {
90
+ span.setStatus({ code: SpanStatusCode.OK });
91
+ }
92
+ span.end();
93
+ }
94
+ function assistantErrorMessage(model, errorMessage) {
95
+ return {
96
+ role: "assistant",
97
+ content: [],
98
+ api: model.api,
99
+ provider: model.provider,
100
+ model: model.id,
101
+ usage: {
102
+ input: 0,
103
+ output: 0,
104
+ cacheRead: 0,
105
+ cacheWrite: 0,
106
+ totalTokens: 0,
107
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
108
+ },
109
+ stopReason: "error",
110
+ errorMessage,
111
+ timestamp: Date.now(),
112
+ };
113
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@introspection-sdk/introspection-pi",
3
+ "version": "0.4.1",
4
+ "license": "Apache-2.0",
5
+ "description": "Introspection observability extension for the Pi Agent SDK — OTEL GenAI semantic-convention spans for chat completions and tool execution",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist/"
17
+ ],
18
+ "dependencies": {
19
+ "@opentelemetry/api": "^1.9.0",
20
+ "@introspection-sdk/types": "0.4.1"
21
+ },
22
+ "peerDependencies": {
23
+ "@mariozechner/pi-ai": ">=0.70.0",
24
+ "@mariozechner/pi-agent-core": ">=0.70.0"
25
+ },
26
+ "peerDependenciesMeta": {
27
+ "@mariozechner/pi-ai": {
28
+ "optional": true
29
+ },
30
+ "@mariozechner/pi-agent-core": {
31
+ "optional": true
32
+ }
33
+ },
34
+ "devDependencies": {
35
+ "@mariozechner/pi-agent-core": "^0.70.6",
36
+ "@mariozechner/pi-ai": "^0.70.6",
37
+ "@types/node": "^22.15.3",
38
+ "eslint": "^9.39.1",
39
+ "typescript": "5.9.3",
40
+ "@repo/typescript-config": "0.0.0",
41
+ "@repo/eslint-config": "0.0.0"
42
+ },
43
+ "engines": {
44
+ "node": ">=18"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc",
48
+ "check-types": "tsc --noEmit",
49
+ "lint": "eslint . --max-warnings 0"
50
+ }
51
+ }