@analytix402/openclaw-skill 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.
package/dist/index.mjs ADDED
@@ -0,0 +1,447 @@
1
+ // ../sdk/src/client.ts
2
+ var SDK_NAME = "@analytix402/sdk";
3
+ var SDK_VERSION = "0.1.1";
4
+ var DEFAULT_CONFIG = {
5
+ baseUrl: "https://analytix402.com",
6
+ debug: false,
7
+ batchSize: 100,
8
+ flushInterval: 5e3,
9
+ maxRetries: 3,
10
+ maxQueueSize: 1e3,
11
+ timeout: 1e4,
12
+ excludePaths: ["/health", "/healthz", "/ready", "/metrics", "/favicon.ico"]
13
+ };
14
+ function createClient(config) {
15
+ if (!config.apiKey) {
16
+ throw new Error("Analytix402: apiKey is required");
17
+ }
18
+ if (!config.apiKey.startsWith("ax_live_") && !config.apiKey.startsWith("ax_test_")) {
19
+ console.warn("Analytix402: API key should start with ax_live_ or ax_test_");
20
+ }
21
+ const cfg = {
22
+ ...DEFAULT_CONFIG,
23
+ ...config
24
+ };
25
+ const agentId = cfg.agentId;
26
+ const queue = [];
27
+ let flushTimer = null;
28
+ let isFlushing = false;
29
+ let isShutdown = false;
30
+ const log = (...args) => {
31
+ if (cfg.debug) {
32
+ console.log("[Analytix402]", ...args);
33
+ }
34
+ };
35
+ const warn = (...args) => {
36
+ console.warn("[Analytix402]", ...args);
37
+ };
38
+ function enqueue(event) {
39
+ if (isShutdown) {
40
+ warn("Client is shutdown, event dropped");
41
+ return;
42
+ }
43
+ if (queue.length >= cfg.maxQueueSize) {
44
+ warn(`Queue full (${cfg.maxQueueSize}), dropping oldest event`);
45
+ queue.shift();
46
+ }
47
+ queue.push({
48
+ event,
49
+ attempts: 0,
50
+ addedAt: Date.now()
51
+ });
52
+ log(`Event queued (${queue.length} in queue)`);
53
+ if (queue.length >= cfg.batchSize) {
54
+ log("Batch size reached, flushing");
55
+ flush();
56
+ } else if (!flushTimer) {
57
+ flushTimer = setTimeout(() => {
58
+ flushTimer = null;
59
+ flush();
60
+ }, cfg.flushInterval);
61
+ }
62
+ }
63
+ function track(event) {
64
+ if (agentId && !event.agentId) {
65
+ event.agentId = agentId;
66
+ }
67
+ enqueue(event);
68
+ }
69
+ function heartbeat(status = "healthy", metadata) {
70
+ if (!agentId) {
71
+ warn("heartbeat() requires agentId in config");
72
+ return;
73
+ }
74
+ const event = {
75
+ type: "heartbeat",
76
+ agentId,
77
+ status,
78
+ metadata,
79
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
80
+ };
81
+ enqueue(event);
82
+ }
83
+ function reportOutcome(taskId, success, options) {
84
+ const event = {
85
+ type: "task_outcome",
86
+ agentId,
87
+ taskId,
88
+ success,
89
+ durationMs: options == null ? void 0 : options.durationMs,
90
+ cost: options == null ? void 0 : options.cost,
91
+ metadata: options == null ? void 0 : options.metadata,
92
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
93
+ };
94
+ enqueue(event);
95
+ }
96
+ function startTask(taskId) {
97
+ const id = taskId || `task_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
98
+ const startTime = Date.now();
99
+ return {
100
+ taskId: id,
101
+ end(success, metadata) {
102
+ const durationMs = Date.now() - startTime;
103
+ reportOutcome(id, success, { durationMs, metadata });
104
+ }
105
+ };
106
+ }
107
+ function trackLLM(usage) {
108
+ const event = {
109
+ type: "llm_usage",
110
+ agentId,
111
+ taskId: usage.taskId,
112
+ model: usage.model,
113
+ provider: usage.provider,
114
+ inputTokens: usage.inputTokens,
115
+ outputTokens: usage.outputTokens,
116
+ totalTokens: usage.inputTokens + usage.outputTokens,
117
+ costUsd: usage.costUsd,
118
+ durationMs: usage.durationMs,
119
+ metadata: usage.metadata,
120
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
121
+ };
122
+ enqueue(event);
123
+ }
124
+ async function sendBatch(events) {
125
+ if (events.length === 0) return true;
126
+ const payload = {
127
+ events,
128
+ sdk: {
129
+ name: SDK_NAME,
130
+ version: SDK_VERSION
131
+ },
132
+ sentAt: (/* @__PURE__ */ new Date()).toISOString()
133
+ };
134
+ try {
135
+ const controller = new AbortController();
136
+ const timeoutId = setTimeout(() => controller.abort(), cfg.timeout);
137
+ const response = await fetch(`${cfg.baseUrl}/api/ingest/batch`, {
138
+ method: "POST",
139
+ headers: {
140
+ "Content-Type": "application/json",
141
+ "X-API-Key": cfg.apiKey,
142
+ "User-Agent": `${SDK_NAME}/${SDK_VERSION}`
143
+ },
144
+ body: JSON.stringify(payload),
145
+ signal: controller.signal
146
+ });
147
+ clearTimeout(timeoutId);
148
+ if (!response.ok) {
149
+ const text = await response.text().catch(() => "Unknown error");
150
+ throw new Error(`HTTP ${response.status}: ${text}`);
151
+ }
152
+ log(`Sent ${events.length} events successfully`);
153
+ return true;
154
+ } catch (error) {
155
+ if (error instanceof Error && error.name === "AbortError") {
156
+ warn("Request timed out");
157
+ } else {
158
+ warn("Failed to send events:", error);
159
+ }
160
+ return false;
161
+ }
162
+ }
163
+ async function flush() {
164
+ if (isFlushing || queue.length === 0) {
165
+ return;
166
+ }
167
+ isFlushing = true;
168
+ if (flushTimer) {
169
+ clearTimeout(flushTimer);
170
+ flushTimer = null;
171
+ }
172
+ const batch = queue.splice(0, cfg.batchSize);
173
+ const events = batch.map((q) => q.event);
174
+ log(`Flushing ${events.length} events`);
175
+ const success = await sendBatch(events);
176
+ if (!success) {
177
+ const retriable = batch.filter((q) => q.attempts < cfg.maxRetries);
178
+ if (retriable.length > 0) {
179
+ log(`Re-queuing ${retriable.length} events for retry`);
180
+ for (const item of retriable.reverse()) {
181
+ item.attempts++;
182
+ queue.unshift(item);
183
+ }
184
+ const backoff = Math.min(1e3 * Math.pow(2, retriable[0].attempts), 3e4);
185
+ log(`Retry scheduled in ${backoff}ms`);
186
+ flushTimer = setTimeout(() => {
187
+ flushTimer = null;
188
+ flush();
189
+ }, backoff);
190
+ } else {
191
+ warn(`Dropped ${batch.length} events after ${cfg.maxRetries} retries`);
192
+ }
193
+ }
194
+ isFlushing = false;
195
+ if (queue.length > 0 && !flushTimer) {
196
+ flushTimer = setTimeout(() => {
197
+ flushTimer = null;
198
+ flush();
199
+ }, cfg.flushInterval);
200
+ }
201
+ }
202
+ async function shutdown2() {
203
+ log("Shutting down...");
204
+ isShutdown = true;
205
+ if (flushTimer) {
206
+ clearTimeout(flushTimer);
207
+ flushTimer = null;
208
+ }
209
+ if (queue.length > 0) {
210
+ log(`Flushing ${queue.length} remaining events`);
211
+ isFlushing = false;
212
+ await flush();
213
+ }
214
+ log("Shutdown complete");
215
+ }
216
+ if (typeof process !== "undefined") {
217
+ const handleExit = () => {
218
+ shutdown2().catch(console.error);
219
+ };
220
+ process.on("beforeExit", handleExit);
221
+ process.on("SIGINT", handleExit);
222
+ process.on("SIGTERM", handleExit);
223
+ }
224
+ return {
225
+ track,
226
+ flush,
227
+ shutdown: shutdown2,
228
+ heartbeat,
229
+ reportOutcome,
230
+ startTask,
231
+ trackLLM
232
+ };
233
+ }
234
+
235
+ // src/index.ts
236
+ var API_KEY = process.env.ANALYTIX402_API_KEY || "";
237
+ var BASE_URL = (process.env.ANALYTIX402_BASE_URL || "https://analytix402.com").replace(/\/$/, "");
238
+ var AGENT_ID = process.env.ANALYTIX402_AGENT_ID || `openclaw-${Date.now()}`;
239
+ var AGENT_NAME = process.env.ANALYTIX402_AGENT_NAME || "OpenClaw Agent";
240
+ var DAILY_BUDGET = parseFloat(process.env.ANALYTIX402_DAILY_BUDGET || "0") || 0;
241
+ var PER_CALL_LIMIT = parseFloat(process.env.ANALYTIX402_PER_CALL_LIMIT || "0") || 0;
242
+ var TRACK_LLM = process.env.ANALYTIX402_TRACK_LLM !== "false";
243
+ var client = null;
244
+ var sessionSpend = 0;
245
+ var sessionCalls = 0;
246
+ var dailySpend = 0;
247
+ var dailySpendDate = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
248
+ function getClient() {
249
+ if (!client) {
250
+ if (!API_KEY) {
251
+ throw new Error(
252
+ "ANALYTIX402_API_KEY is not set. Add it to your OpenClaw skill config."
253
+ );
254
+ }
255
+ client = createClient({
256
+ apiKey: API_KEY,
257
+ baseUrl: BASE_URL,
258
+ agentId: AGENT_ID,
259
+ agentName: AGENT_NAME
260
+ });
261
+ }
262
+ return client;
263
+ }
264
+ async function apiRequest(method, path, body) {
265
+ const url = `${BASE_URL}/api${path}`;
266
+ const headers = {
267
+ "Content-Type": "application/json",
268
+ "Authorization": `Bearer ${API_KEY}`,
269
+ "X-API-Key": API_KEY
270
+ };
271
+ const opts = { method, headers };
272
+ if (body && method !== "GET") {
273
+ opts.body = JSON.stringify(body);
274
+ }
275
+ const res = await fetch(url, opts);
276
+ const text = await res.text();
277
+ let data;
278
+ try {
279
+ data = JSON.parse(text);
280
+ } catch {
281
+ data = { raw: text };
282
+ }
283
+ if (!res.ok) {
284
+ throw new Error(`Analytix402 API ${res.status}: ${data.error || text}`);
285
+ }
286
+ return data;
287
+ }
288
+ async function analytix402_spend_report() {
289
+ const c = getClient();
290
+ c.heartbeat("healthy", { sessionCalls, sessionSpend });
291
+ try {
292
+ const overview = await apiRequest("GET", "/agents/overview");
293
+ const insights = await apiRequest("GET", "/agents/insights");
294
+ return JSON.stringify({
295
+ session: {
296
+ totalCalls: sessionCalls,
297
+ totalSpend: `$${sessionSpend.toFixed(4)}`,
298
+ dailySpend: `$${dailySpend.toFixed(4)}`,
299
+ dailyBudget: DAILY_BUDGET > 0 ? `$${DAILY_BUDGET.toFixed(2)}` : "unlimited",
300
+ budgetRemaining: DAILY_BUDGET > 0 ? `$${(DAILY_BUDGET - dailySpend).toFixed(4)}` : "unlimited"
301
+ },
302
+ platform: overview,
303
+ insights
304
+ }, null, 2);
305
+ } catch (error) {
306
+ return JSON.stringify({
307
+ session: {
308
+ totalCalls: sessionCalls,
309
+ totalSpend: `$${sessionSpend.toFixed(4)}`,
310
+ dailySpend: `$${dailySpend.toFixed(4)}`,
311
+ dailyBudget: DAILY_BUDGET > 0 ? `$${DAILY_BUDGET.toFixed(2)}` : "unlimited"
312
+ },
313
+ error: error instanceof Error ? error.message : String(error)
314
+ }, null, 2);
315
+ }
316
+ }
317
+ function analytix402_set_budget(params) {
318
+ const updates = [];
319
+ if (params.daily_limit !== void 0 && params.daily_limit >= 0) {
320
+ Object.defineProperty(globalThis, "__ax402_daily_budget", {
321
+ value: params.daily_limit,
322
+ writable: true,
323
+ configurable: true
324
+ });
325
+ updates.push(`Daily budget set to $${params.daily_limit.toFixed(2)}`);
326
+ }
327
+ if (params.per_call_limit !== void 0 && params.per_call_limit >= 0) {
328
+ Object.defineProperty(globalThis, "__ax402_per_call_limit", {
329
+ value: params.per_call_limit,
330
+ writable: true,
331
+ configurable: true
332
+ });
333
+ updates.push(`Per-call limit set to $${params.per_call_limit.toFixed(2)}`);
334
+ }
335
+ if (updates.length === 0) {
336
+ return "No budget parameters provided. Use daily_limit and/or per_call_limit.";
337
+ }
338
+ return updates.join(". ") + ".";
339
+ }
340
+ function analytix402_check_budget(params) {
341
+ const budget = DAILY_BUDGET || globalThis.__ax402_daily_budget || 0;
342
+ const callLimit = PER_CALL_LIMIT || globalThis.__ax402_per_call_limit || 0;
343
+ const estimated = params.estimated_cost || 0;
344
+ const remaining = budget > 0 ? budget - dailySpend : Infinity;
345
+ const allowed = (budget === 0 || remaining >= estimated) && (callLimit === 0 || estimated <= callLimit);
346
+ return JSON.stringify({
347
+ allowed,
348
+ dailyBudget: budget > 0 ? `$${budget.toFixed(2)}` : "unlimited",
349
+ dailySpent: `$${dailySpend.toFixed(4)}`,
350
+ remaining: budget > 0 ? `$${remaining.toFixed(4)}` : "unlimited",
351
+ estimatedCost: `$${estimated.toFixed(4)}`,
352
+ perCallLimit: callLimit > 0 ? `$${callLimit.toFixed(2)}` : "unlimited",
353
+ withinPerCallLimit: callLimit === 0 || estimated <= callLimit,
354
+ withinDailyBudget: budget === 0 || remaining >= estimated
355
+ }, null, 2);
356
+ }
357
+ function analytix402_flag_purchase(params) {
358
+ const c = getClient();
359
+ c.track({
360
+ type: "request",
361
+ method: "FLAG",
362
+ path: params.url,
363
+ endpoint: params.url,
364
+ statusCode: 0,
365
+ responseTimeMs: 0,
366
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
367
+ agentId: AGENT_ID,
368
+ metadata: {
369
+ flagged: true,
370
+ reason: params.reason || "Potential duplicate or unnecessary purchase",
371
+ estimatedCost: params.estimated_cost
372
+ }
373
+ });
374
+ return `Flagged: ${params.url} \u2014 ${params.reason || "potential duplicate purchase"}. This will appear in your Analytix402 dashboard for review.`;
375
+ }
376
+ function trackLLMCall(params) {
377
+ if (!TRACK_LLM) return;
378
+ const c = getClient();
379
+ const cost = params.costUsd || 0;
380
+ c.trackLLM({
381
+ model: params.model,
382
+ provider: params.provider,
383
+ inputTokens: params.inputTokens,
384
+ outputTokens: params.outputTokens,
385
+ costUsd: params.costUsd,
386
+ durationMs: params.durationMs,
387
+ taskId: params.taskId
388
+ });
389
+ sessionSpend += cost;
390
+ sessionCalls += 1;
391
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
392
+ if (today !== dailySpendDate) {
393
+ dailySpend = 0;
394
+ }
395
+ dailySpend += cost;
396
+ }
397
+ function trackAPICall(params) {
398
+ const c = getClient();
399
+ const payment = params.paymentAmount ? {
400
+ amount: String(params.paymentAmount),
401
+ currency: params.paymentCurrency || "USDC",
402
+ wallet: "",
403
+ status: "success",
404
+ txHash: params.txHash
405
+ } : void 0;
406
+ c.track({
407
+ type: "request",
408
+ method: params.method,
409
+ path: params.url,
410
+ endpoint: params.url,
411
+ statusCode: params.statusCode,
412
+ responseTimeMs: params.responseTimeMs,
413
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
414
+ agentId: AGENT_ID,
415
+ payment
416
+ });
417
+ if (params.paymentAmount) {
418
+ sessionSpend += params.paymentAmount;
419
+ dailySpend += params.paymentAmount;
420
+ }
421
+ sessionCalls += 1;
422
+ }
423
+ function sendHeartbeat(status = "healthy") {
424
+ const c = getClient();
425
+ c.heartbeat(status, {
426
+ sessionCalls,
427
+ sessionSpend,
428
+ dailySpend,
429
+ uptime: process.uptime()
430
+ });
431
+ }
432
+ async function shutdown() {
433
+ if (client) {
434
+ await client.shutdown();
435
+ client = null;
436
+ }
437
+ }
438
+ export {
439
+ analytix402_check_budget,
440
+ analytix402_flag_purchase,
441
+ analytix402_set_budget,
442
+ analytix402_spend_report,
443
+ sendHeartbeat,
444
+ shutdown,
445
+ trackAPICall,
446
+ trackLLMCall
447
+ };
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@analytix402/openclaw-skill",
3
+ "version": "0.1.0",
4
+ "description": "Analytix402 skill for OpenClaw — monitor, control, and optimize your AI agent's spend",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsup src/index.ts --format cjs,esm --dts",
9
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
10
+ "typecheck": "tsc --noEmit"
11
+ },
12
+ "keywords": [
13
+ "openclaw",
14
+ "analytix402",
15
+ "x402",
16
+ "ai-agent",
17
+ "monitoring",
18
+ "budget",
19
+ "spend-tracking",
20
+ "observability"
21
+ ],
22
+ "author": "Analytix402",
23
+ "license": "MIT",
24
+ "dependencies": {
25
+ "@analytix402/sdk": "^0.1.1"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^20.10.0",
29
+ "tsup": "^8.0.1",
30
+ "typescript": "^5.3.0"
31
+ },
32
+ "engines": {
33
+ "node": ">=22.0.0"
34
+ }
35
+ }