agentracer 0.1.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.
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/anthropic.ts
21
+ var anthropic_exports = {};
22
+ __export(anthropic_exports, {
23
+ TrackedAnthropic: () => TrackedAnthropic,
24
+ _setClientForTesting: () => _setClientForTesting,
25
+ anthropic: () => anthropic
26
+ });
27
+ module.exports = __toCommonJS(anthropic_exports);
28
+
29
+ // src/index.ts
30
+ var import_async_hooks = require("async_hooks");
31
+ var config = {
32
+ trackerApiKey: "",
33
+ projectId: "",
34
+ environment: "production",
35
+ host: "https://api.agentracer.dev",
36
+ debug: false,
37
+ enabled: true
38
+ };
39
+ var featureTagStorage = new import_async_hooks.AsyncLocalStorage();
40
+ var runStorage = new import_async_hooks.AsyncLocalStorage();
41
+ async function sendTelemetry(payload) {
42
+ if (!config.enabled) return;
43
+ try {
44
+ if (config.debug) console.log("[agentracer]", payload);
45
+ const response = await fetch(`${config.host}/api/ingest`, {
46
+ method: "POST",
47
+ headers: {
48
+ "Content-Type": "application/json",
49
+ "x-api-key": config.trackerApiKey
50
+ },
51
+ body: JSON.stringify(payload),
52
+ signal: AbortSignal.timeout(2e3)
53
+ });
54
+ } catch {
55
+ }
56
+ }
57
+ async function track(options) {
58
+ const currentTag = featureTagStorage.getStore();
59
+ let runId = options.runId;
60
+ let stepIndex = options.stepIndex;
61
+ const activeRun = runStorage.getStore();
62
+ if (activeRun && runId == null) {
63
+ runId = activeRun.runId;
64
+ stepIndex = activeRun._nextStep();
65
+ sendRunApi("/api/runs/step", {
66
+ project_id: config.projectId,
67
+ run_id: activeRun.runId,
68
+ step_index: stepIndex,
69
+ step_type: "llm_call",
70
+ model: options.model,
71
+ provider: options.provider ?? "custom",
72
+ input_tokens: options.inputTokens,
73
+ output_tokens: options.outputTokens,
74
+ cached_tokens: options.cachedTokens ?? 0,
75
+ cost_usd: 0,
76
+ latency_ms: options.latencyMs,
77
+ success: options.success ?? true,
78
+ error_type: options.errorType ?? null
79
+ }).catch(() => {
80
+ });
81
+ }
82
+ const payload = {
83
+ project_id: config.projectId,
84
+ provider: options.provider ?? "custom",
85
+ model: options.model,
86
+ feature_tag: options.featureTag ?? currentTag ?? "unknown",
87
+ input_tokens: options.inputTokens,
88
+ output_tokens: options.outputTokens,
89
+ cached_tokens: options.cachedTokens ?? 0,
90
+ latency_ms: options.latencyMs,
91
+ success: options.success ?? true,
92
+ environment: options.environment ?? config.environment
93
+ };
94
+ if (options.errorType != null) payload.error_type = options.errorType;
95
+ if (options.endUserId != null) payload.end_user_id = options.endUserId;
96
+ if (runId != null) payload.run_id = runId;
97
+ if (stepIndex != null) payload.step_index = stepIndex;
98
+ await sendTelemetry(payload);
99
+ }
100
+ async function sendRunApi(path, payload) {
101
+ if (!config.enabled) return;
102
+ try {
103
+ await fetch(`${config.host}${path}`, {
104
+ method: "POST",
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ "x-api-key": config.trackerApiKey
108
+ },
109
+ body: JSON.stringify(payload),
110
+ signal: AbortSignal.timeout(2e3)
111
+ });
112
+ } catch {
113
+ }
114
+ }
115
+
116
+ // src/anthropic.ts
117
+ var _clientInstance = null;
118
+ function getClient(opts) {
119
+ if (opts) {
120
+ const Anthropic = require("@anthropic-ai/sdk").default || require("@anthropic-ai/sdk");
121
+ return new Anthropic(opts);
122
+ }
123
+ if (!_clientInstance) {
124
+ const Anthropic = require("@anthropic-ai/sdk").default || require("@anthropic-ai/sdk");
125
+ _clientInstance = new Anthropic();
126
+ }
127
+ return _clientInstance;
128
+ }
129
+ function _setClientForTesting(client) {
130
+ _clientInstance = client;
131
+ }
132
+ async function* wrapAnthropicStream(stream, model, featureTag, start) {
133
+ let inputTokens = 0;
134
+ let outputTokens = 0;
135
+ for await (const event of stream) {
136
+ if (event.type === "message_start" && event.message?.usage) {
137
+ inputTokens = event.message.usage.input_tokens ?? 0;
138
+ }
139
+ if (event.type === "message_delta" && event.usage) {
140
+ outputTokens = event.usage.output_tokens ?? 0;
141
+ }
142
+ yield event;
143
+ }
144
+ track({
145
+ model,
146
+ inputTokens,
147
+ outputTokens,
148
+ latencyMs: Date.now() - start,
149
+ featureTag,
150
+ provider: "anthropic"
151
+ }).catch(() => {
152
+ });
153
+ }
154
+ function createAnthropicProxy(clientGetter) {
155
+ return new Proxy({}, {
156
+ get(_, prop) {
157
+ if (prop === "messages") {
158
+ return {
159
+ create: async (params) => {
160
+ const featureTag = params.feature_tag ?? featureTagStorage.getStore() ?? "unknown";
161
+ const { feature_tag, ...cleanParams } = params;
162
+ const start = Date.now();
163
+ const client = clientGetter();
164
+ if (cleanParams.stream) {
165
+ const stream = await client.messages.create(cleanParams);
166
+ return wrapAnthropicStream(stream, params.model, featureTag, start);
167
+ }
168
+ let response;
169
+ try {
170
+ response = await client.messages.create(cleanParams);
171
+ } catch (err) {
172
+ track({
173
+ model: params.model,
174
+ inputTokens: 0,
175
+ outputTokens: 0,
176
+ latencyMs: Date.now() - start,
177
+ featureTag,
178
+ provider: "anthropic",
179
+ success: false,
180
+ errorType: err?.constructor?.name ?? "Error"
181
+ }).catch(() => {
182
+ });
183
+ throw err;
184
+ }
185
+ track({
186
+ model: params.model,
187
+ inputTokens: response.usage?.input_tokens ?? 0,
188
+ outputTokens: response.usage?.output_tokens ?? 0,
189
+ cachedTokens: response.usage?.cache_read_input_tokens ?? 0,
190
+ latencyMs: Date.now() - start,
191
+ featureTag,
192
+ provider: "anthropic"
193
+ }).catch(() => {
194
+ });
195
+ return response;
196
+ }
197
+ };
198
+ }
199
+ return clientGetter()[prop];
200
+ }
201
+ });
202
+ }
203
+ var TrackedAnthropic = class {
204
+ constructor(options) {
205
+ const Anthropic = require("@anthropic-ai/sdk").default || require("@anthropic-ai/sdk");
206
+ const client = new Anthropic(options);
207
+ this._proxy = createAnthropicProxy(() => client);
208
+ }
209
+ get messages() {
210
+ return this._proxy.messages;
211
+ }
212
+ };
213
+ var anthropic = createAnthropicProxy(() => getClient());
214
+ // Annotate the CommonJS export names for ESM import in node:
215
+ 0 && (module.exports = {
216
+ TrackedAnthropic,
217
+ _setClientForTesting,
218
+ anthropic
219
+ });
@@ -0,0 +1,109 @@
1
+ import {
2
+ __require,
3
+ featureTagStorage,
4
+ track
5
+ } from "./chunk-72GBZ4TW.mjs";
6
+
7
+ // src/anthropic.ts
8
+ var _clientInstance = null;
9
+ function getClient(opts) {
10
+ if (opts) {
11
+ const Anthropic = __require("@anthropic-ai/sdk").default || __require("@anthropic-ai/sdk");
12
+ return new Anthropic(opts);
13
+ }
14
+ if (!_clientInstance) {
15
+ const Anthropic = __require("@anthropic-ai/sdk").default || __require("@anthropic-ai/sdk");
16
+ _clientInstance = new Anthropic();
17
+ }
18
+ return _clientInstance;
19
+ }
20
+ function _setClientForTesting(client) {
21
+ _clientInstance = client;
22
+ }
23
+ async function* wrapAnthropicStream(stream, model, featureTag, start) {
24
+ let inputTokens = 0;
25
+ let outputTokens = 0;
26
+ for await (const event of stream) {
27
+ if (event.type === "message_start" && event.message?.usage) {
28
+ inputTokens = event.message.usage.input_tokens ?? 0;
29
+ }
30
+ if (event.type === "message_delta" && event.usage) {
31
+ outputTokens = event.usage.output_tokens ?? 0;
32
+ }
33
+ yield event;
34
+ }
35
+ track({
36
+ model,
37
+ inputTokens,
38
+ outputTokens,
39
+ latencyMs: Date.now() - start,
40
+ featureTag,
41
+ provider: "anthropic"
42
+ }).catch(() => {
43
+ });
44
+ }
45
+ function createAnthropicProxy(clientGetter) {
46
+ return new Proxy({}, {
47
+ get(_, prop) {
48
+ if (prop === "messages") {
49
+ return {
50
+ create: async (params) => {
51
+ const featureTag = params.feature_tag ?? featureTagStorage.getStore() ?? "unknown";
52
+ const { feature_tag, ...cleanParams } = params;
53
+ const start = Date.now();
54
+ const client = clientGetter();
55
+ if (cleanParams.stream) {
56
+ const stream = await client.messages.create(cleanParams);
57
+ return wrapAnthropicStream(stream, params.model, featureTag, start);
58
+ }
59
+ let response;
60
+ try {
61
+ response = await client.messages.create(cleanParams);
62
+ } catch (err) {
63
+ track({
64
+ model: params.model,
65
+ inputTokens: 0,
66
+ outputTokens: 0,
67
+ latencyMs: Date.now() - start,
68
+ featureTag,
69
+ provider: "anthropic",
70
+ success: false,
71
+ errorType: err?.constructor?.name ?? "Error"
72
+ }).catch(() => {
73
+ });
74
+ throw err;
75
+ }
76
+ track({
77
+ model: params.model,
78
+ inputTokens: response.usage?.input_tokens ?? 0,
79
+ outputTokens: response.usage?.output_tokens ?? 0,
80
+ cachedTokens: response.usage?.cache_read_input_tokens ?? 0,
81
+ latencyMs: Date.now() - start,
82
+ featureTag,
83
+ provider: "anthropic"
84
+ }).catch(() => {
85
+ });
86
+ return response;
87
+ }
88
+ };
89
+ }
90
+ return clientGetter()[prop];
91
+ }
92
+ });
93
+ }
94
+ var TrackedAnthropic = class {
95
+ constructor(options) {
96
+ const Anthropic = __require("@anthropic-ai/sdk").default || __require("@anthropic-ai/sdk");
97
+ const client = new Anthropic(options);
98
+ this._proxy = createAnthropicProxy(() => client);
99
+ }
100
+ get messages() {
101
+ return this._proxy.messages;
102
+ }
103
+ };
104
+ var anthropic = createAnthropicProxy(() => getClient());
105
+ export {
106
+ TrackedAnthropic,
107
+ _setClientForTesting,
108
+ anthropic
109
+ };
@@ -0,0 +1,160 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/index.ts
9
+ import { AsyncLocalStorage } from "async_hooks";
10
+ import { randomUUID } from "crypto";
11
+ var config = {
12
+ trackerApiKey: "",
13
+ projectId: "",
14
+ environment: "production",
15
+ host: "https://api.agentracer.dev",
16
+ debug: false,
17
+ enabled: true
18
+ };
19
+ var featureTagStorage = new AsyncLocalStorage();
20
+ var runStorage = new AsyncLocalStorage();
21
+ function init(options) {
22
+ config = { ...config, ...options };
23
+ }
24
+ function getConfig() {
25
+ return config;
26
+ }
27
+ async function sendTelemetry(payload) {
28
+ if (!config.enabled) return;
29
+ try {
30
+ if (config.debug) console.log("[agentracer]", payload);
31
+ const response = await fetch(`${config.host}/api/ingest`, {
32
+ method: "POST",
33
+ headers: {
34
+ "Content-Type": "application/json",
35
+ "x-api-key": config.trackerApiKey
36
+ },
37
+ body: JSON.stringify(payload),
38
+ signal: AbortSignal.timeout(2e3)
39
+ });
40
+ } catch {
41
+ }
42
+ }
43
+ function observe(fn, options) {
44
+ return ((...args) => featureTagStorage.run(options.featureTag, () => fn(...args)));
45
+ }
46
+ async function track(options) {
47
+ const currentTag = featureTagStorage.getStore();
48
+ let runId = options.runId;
49
+ let stepIndex = options.stepIndex;
50
+ const activeRun = runStorage.getStore();
51
+ if (activeRun && runId == null) {
52
+ runId = activeRun.runId;
53
+ stepIndex = activeRun._nextStep();
54
+ sendRunApi("/api/runs/step", {
55
+ project_id: config.projectId,
56
+ run_id: activeRun.runId,
57
+ step_index: stepIndex,
58
+ step_type: "llm_call",
59
+ model: options.model,
60
+ provider: options.provider ?? "custom",
61
+ input_tokens: options.inputTokens,
62
+ output_tokens: options.outputTokens,
63
+ cached_tokens: options.cachedTokens ?? 0,
64
+ cost_usd: 0,
65
+ latency_ms: options.latencyMs,
66
+ success: options.success ?? true,
67
+ error_type: options.errorType ?? null
68
+ }).catch(() => {
69
+ });
70
+ }
71
+ const payload = {
72
+ project_id: config.projectId,
73
+ provider: options.provider ?? "custom",
74
+ model: options.model,
75
+ feature_tag: options.featureTag ?? currentTag ?? "unknown",
76
+ input_tokens: options.inputTokens,
77
+ output_tokens: options.outputTokens,
78
+ cached_tokens: options.cachedTokens ?? 0,
79
+ latency_ms: options.latencyMs,
80
+ success: options.success ?? true,
81
+ environment: options.environment ?? config.environment
82
+ };
83
+ if (options.errorType != null) payload.error_type = options.errorType;
84
+ if (options.endUserId != null) payload.end_user_id = options.endUserId;
85
+ if (runId != null) payload.run_id = runId;
86
+ if (stepIndex != null) payload.step_index = stepIndex;
87
+ await sendTelemetry(payload);
88
+ }
89
+ async function sendRunApi(path, payload) {
90
+ if (!config.enabled) return;
91
+ try {
92
+ await fetch(`${config.host}${path}`, {
93
+ method: "POST",
94
+ headers: {
95
+ "Content-Type": "application/json",
96
+ "x-api-key": config.trackerApiKey
97
+ },
98
+ body: JSON.stringify(payload),
99
+ signal: AbortSignal.timeout(2e3)
100
+ });
101
+ } catch {
102
+ }
103
+ }
104
+ var AgentRun = class {
105
+ constructor(options = {}) {
106
+ this.stepCounter = 0;
107
+ this.runId = options.runId ?? randomUUID();
108
+ this.runName = options.runName;
109
+ this.featureTag = options.featureTag ?? "unknown";
110
+ this.endUserId = options.endUserId;
111
+ }
112
+ /** @internal */
113
+ _nextStep() {
114
+ return ++this.stepCounter;
115
+ }
116
+ async execute(fn) {
117
+ sendRunApi("/api/runs/start", {
118
+ project_id: config.projectId,
119
+ run_id: this.runId,
120
+ run_name: this.runName,
121
+ feature_tag: this.featureTag,
122
+ end_user_id: this.endUserId
123
+ }).catch(() => {
124
+ });
125
+ try {
126
+ const result = await runStorage.run(
127
+ this,
128
+ () => featureTagStorage.run(this.featureTag, fn)
129
+ );
130
+ sendRunApi("/api/runs/end", {
131
+ project_id: config.projectId,
132
+ run_id: this.runId,
133
+ status: "completed"
134
+ }).catch(() => {
135
+ });
136
+ return result;
137
+ } catch (err) {
138
+ sendRunApi("/api/runs/end", {
139
+ project_id: config.projectId,
140
+ run_id: this.runId,
141
+ status: "failed",
142
+ error_type: err?.constructor?.name ?? "Error"
143
+ }).catch(() => {
144
+ });
145
+ throw err;
146
+ }
147
+ }
148
+ };
149
+
150
+ export {
151
+ __require,
152
+ featureTagStorage,
153
+ runStorage,
154
+ init,
155
+ getConfig,
156
+ sendTelemetry,
157
+ observe,
158
+ track,
159
+ AgentRun
160
+ };
@@ -0,0 +1,66 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/index.ts
9
+ import { AsyncLocalStorage } from "async_hooks";
10
+ var config = {
11
+ trackerApiKey: "",
12
+ projectId: "",
13
+ environment: "production",
14
+ host: "https://api.agentracer.dev",
15
+ debug: false,
16
+ enabled: true
17
+ };
18
+ var featureTagStorage = new AsyncLocalStorage();
19
+ function init(options) {
20
+ config = { ...config, ...options };
21
+ }
22
+ function getConfig() {
23
+ return config;
24
+ }
25
+ async function sendTelemetry(payload) {
26
+ if (!config.enabled) return;
27
+ try {
28
+ if (config.debug) console.log("[agentracer]", payload);
29
+ const response = await fetch(`${config.host}/api/ingest`, {
30
+ method: "POST",
31
+ headers: {
32
+ "Content-Type": "application/json",
33
+ "x-api-key": config.trackerApiKey
34
+ },
35
+ body: JSON.stringify(payload),
36
+ signal: AbortSignal.timeout(2e3)
37
+ });
38
+ } catch {
39
+ }
40
+ }
41
+ function observe(fn, options) {
42
+ return ((...args) => featureTagStorage.run(options.featureTag, () => fn(...args)));
43
+ }
44
+ async function track(options) {
45
+ const currentTag = featureTagStorage.getStore();
46
+ await sendTelemetry({
47
+ project_id: config.projectId,
48
+ provider: options.provider ?? "custom",
49
+ model: options.model,
50
+ feature_tag: options.featureTag ?? currentTag ?? "unknown",
51
+ input_tokens: options.inputTokens,
52
+ output_tokens: options.outputTokens,
53
+ latency_ms: options.latencyMs,
54
+ environment: options.environment ?? config.environment
55
+ });
56
+ }
57
+
58
+ export {
59
+ __require,
60
+ featureTagStorage,
61
+ init,
62
+ getConfig,
63
+ sendTelemetry,
64
+ observe,
65
+ track
66
+ };
@@ -0,0 +1,5 @@
1
+ /** @internal Test-only: inject a mock client */
2
+ declare function _setClientForTesting(client: any): void;
3
+ declare const gemini: any;
4
+
5
+ export { _setClientForTesting, gemini };
@@ -0,0 +1,5 @@
1
+ /** @internal Test-only: inject a mock client */
2
+ declare function _setClientForTesting(client: any): void;
3
+ declare const gemini: any;
4
+
5
+ export { _setClientForTesting, gemini };