@lunora/agent 1.0.0-alpha.5 → 1.0.0-alpha.7

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,164 @@
1
+ import { s as summarizeUsage, c as contentText, r as readField, t as toolInputOf, a as toolNameOf } from './common-DAeFCot5.mjs';
2
+
3
+ const otlpUnixNano = (ms) => `${String(Math.round(ms))}000000`;
4
+ const otlpRandomHex = (bytes) => {
5
+ const buffer = new Uint8Array(bytes);
6
+ crypto.getRandomValues(buffer);
7
+ let hex = "";
8
+ for (const byte of buffer) {
9
+ hex += byte.toString(16).padStart(2, "0");
10
+ }
11
+ return hex;
12
+ };
13
+ const encodeAttribute = (key, value) => {
14
+ if (typeof value === "boolean") {
15
+ return { key, value: { boolValue: value } };
16
+ }
17
+ if (typeof value === "number") {
18
+ if (!Number.isFinite(value)) {
19
+ return { key, value: { stringValue: String(value) } };
20
+ }
21
+ return Number.isSafeInteger(value) ? { key, value: { intValue: String(value) } } : { key, value: { doubleValue: value } };
22
+ }
23
+ return { key, value: { stringValue: value } };
24
+ };
25
+ const mergeHeaders = (defaults, overrides, token) => {
26
+ const merged = {};
27
+ const seen = /* @__PURE__ */ new Map();
28
+ const put = (name, value) => {
29
+ const lower = name.toLowerCase();
30
+ const existing = seen.get(lower);
31
+ if (existing === void 0) {
32
+ seen.set(lower, name);
33
+ merged[name] = value;
34
+ } else {
35
+ merged[existing] = value;
36
+ }
37
+ };
38
+ for (const [name, value] of Object.entries(defaults)) {
39
+ put(name, value);
40
+ }
41
+ for (const [name, value] of Object.entries(overrides ?? {})) {
42
+ put(name, value);
43
+ }
44
+ if (token !== void 0 && token.length > 0) {
45
+ put("authorization", `Bearer ${token}`);
46
+ }
47
+ return merged;
48
+ };
49
+ const wrapResourceSpans = (span, scopeName, serviceName) => {
50
+ return {
51
+ resourceSpans: [
52
+ {
53
+ resource: { attributes: [encodeAttribute("service.name", serviceName)] },
54
+ scopeSpans: [{ scope: { name: scopeName }, spans: [span] }]
55
+ }
56
+ ]
57
+ };
58
+ };
59
+
60
+ const pushAttribute = (attributes, key, value) => {
61
+ if (value === void 0 || value === null) {
62
+ return;
63
+ }
64
+ if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
65
+ attributes.push(encodeAttribute(key, value));
66
+ return;
67
+ }
68
+ attributes.push(encodeAttribute(key, JSON.stringify(value)));
69
+ };
70
+ const otlpTelemetry = (options) => {
71
+ const { endpoint, headers, recordInputs = false, recordOutputs = false, token, traceId: fixedTraceId, waitUntil } = options;
72
+ const serviceName = options.serviceName ?? "lunora";
73
+ let base = endpoint;
74
+ while (base.endsWith("/")) {
75
+ base = base.slice(0, -1);
76
+ }
77
+ const tracesUrl = `${base}/v1/traces`;
78
+ const mergedHeaders = mergeHeaders({ "content-type": "application/json" }, headers, token);
79
+ const emitSpan = (name, startTs, ok, message, attributes) => {
80
+ const span = {
81
+ attributes,
82
+ endTimeUnixNano: otlpUnixNano(Date.now()),
83
+ // SPAN_KIND_INTERNAL — matches the runtime's `ctx.trace` spans.
84
+ kind: 1,
85
+ name,
86
+ spanId: otlpRandomHex(8),
87
+ startTimeUnixNano: otlpUnixNano(startTs),
88
+ // STATUS_CODE_OK (1) / STATUS_CODE_ERROR (2).
89
+ status: ok ? { code: 1 } : { code: 2, message: message ?? "" },
90
+ traceId: fixedTraceId ?? otlpRandomHex(16)
91
+ };
92
+ try {
93
+ const sent = fetch(tracesUrl, {
94
+ body: JSON.stringify(wrapResourceSpans(span, "@lunora/agent", serviceName)),
95
+ headers: mergedHeaders,
96
+ method: "POST"
97
+ }).catch(() => {
98
+ });
99
+ waitUntil?.(sent);
100
+ } catch {
101
+ }
102
+ };
103
+ return {
104
+ executeLanguageModelCall: (options_) => {
105
+ const startTs = Date.now();
106
+ const modelId = readField(options_, "modelId");
107
+ const promise = options_.execute();
108
+ const emit = (ok, message, result) => {
109
+ const attributes = [];
110
+ pushAttribute(attributes, "gen_ai.operation.name", "chat");
111
+ pushAttribute(attributes, "gen_ai.request.model", modelId);
112
+ pushAttribute(attributes, "gen_ai.system", readField(options_, "provider"));
113
+ const usage = summarizeUsage(readField(result, "usage"));
114
+ if (usage) {
115
+ pushAttribute(attributes, "gen_ai.usage.input_tokens", usage.inputTokens);
116
+ pushAttribute(attributes, "gen_ai.usage.output_tokens", usage.outputTokens);
117
+ pushAttribute(attributes, "gen_ai.usage.total_tokens", usage.totalTokens);
118
+ }
119
+ if (recordInputs) {
120
+ pushAttribute(attributes, "gen_ai.prompt", readField(options_, "messages"));
121
+ }
122
+ if (recordOutputs) {
123
+ pushAttribute(attributes, "gen_ai.completion", contentText(readField(result, "content")));
124
+ }
125
+ emitSpan(typeof modelId === "string" ? `chat ${modelId}` : "language_model_call", startTs, ok, message, attributes);
126
+ };
127
+ promise.then(
128
+ (result) => {
129
+ emit(true, void 0, result);
130
+ },
131
+ (error) => {
132
+ emit(false, error instanceof Error ? error.message : String(error), void 0);
133
+ }
134
+ );
135
+ return promise;
136
+ },
137
+ executeTool: (options_) => {
138
+ const startTs = Date.now();
139
+ const toolName = toolNameOf(options_);
140
+ const promise = options_.execute();
141
+ const emit = (ok, message) => {
142
+ const attributes = [];
143
+ pushAttribute(attributes, "gen_ai.operation.name", "execute_tool");
144
+ pushAttribute(attributes, "gen_ai.tool.name", toolName);
145
+ pushAttribute(attributes, "gen_ai.tool.call.id", readField(options_, "toolCallId"));
146
+ if (recordInputs) {
147
+ pushAttribute(attributes, "gen_ai.tool.input", toolInputOf(options_));
148
+ }
149
+ emitSpan(typeof toolName === "string" ? `execute_tool ${toolName}` : "execute_tool", startTs, ok, message, attributes);
150
+ };
151
+ promise.then(
152
+ () => {
153
+ emit(true, void 0);
154
+ },
155
+ (error) => {
156
+ emit(false, error instanceof Error ? error.message : String(error));
157
+ }
158
+ );
159
+ return promise;
160
+ }
161
+ };
162
+ };
163
+
164
+ export { otlpTelemetry };
@@ -122,6 +122,78 @@ interface ConsoleTelemetryOptions extends CommonOptions {
122
122
  * @experimental
123
123
  */
124
124
  declare const consoleTelemetry: (options?: ConsoleTelemetryOptions) => Telemetry;
125
+ /**
126
+ * Options for {@link otlpTelemetry}.
127
+ * @experimental
128
+ */
129
+ interface OtlpTelemetryOptions extends CommonOptions {
130
+ /**
131
+ * The OTLP-over-HTTP collector base endpoint (e.g. the Lunora Cloud's `/v1`
132
+ * base). Spans are POSTed to `${endpoint}/v1/traces`; a trailing slash is
133
+ * tolerated. On the platform this is the injected `LUNORA_OTLP_ENDPOINT`.
134
+ */
135
+ endpoint: string;
136
+ /**
137
+ * Extra headers merged onto every POST — typically the correlation headers
138
+ * the platform injects. `Content-Type: application/json` is set by default.
139
+ */
140
+ headers?: Record<string, string>;
141
+ /** `service.name` resource attribute on every span. Defaults to `lunora`. */
142
+ serviceName?: string;
143
+ /**
144
+ * Bearer token added as `Authorization: Bearer` (wins over any authorization
145
+ * in `headers`) — the injected `LUNORA_OTLP_TOKEN`. Omit for an
146
+ * unauthenticated collector.
147
+ */
148
+ token?: string;
149
+ /**
150
+ * Trace id (32-hex) to hang every span of this run under, so one agent run
151
+ * reads as one trace. Pass a stable id derived from the run (e.g. the
152
+ * workflow run id). Omitted → each span mints its own trace id (still valid,
153
+ * just ungrouped).
154
+ */
155
+ traceId?: string;
156
+ /**
157
+ * The Worker request's `waitUntil`, so a fire-and-forget export survives
158
+ * isolate teardown after the turn returns. Omit and the send degrades to
159
+ * best-effort.
160
+ */
161
+ waitUntil?: (promise: Promise<unknown>) => void;
162
+ }
163
+ /**
164
+ * An OTLP-over-HTTP telemetry integration for `@lunora/agent`.
165
+ *
166
+ * The OTLP counterpart to {@link sentryTelemetry} / {@link braintrustTelemetry}:
167
+ * it wraps each language-model call and tool execution in an OTLP **span**
168
+ * (`gen_ai.*` semantic-convention attributes — model, provider, token usage,
169
+ * tool name) and ships it to a collector, so agent generations land in the same
170
+ * trace store as the rest of an app's telemetry (the Lunora Cloud, or any OTel
171
+ * collector). Plug it into `defineAgent({ telemetry: { isEnabled: true,
172
+ * integrations: [otlpTelemetry({ endpoint, token })] } })`.
173
+ *
174
+ * Emitting inside the turn's execution wrapper means one span per **real** turn:
175
+ * the agent loop memoizes each `step.do('llm:turn:N')`, so a Workflow replay
176
+ * returns the cached result without re-invoking `execute`, and no duplicate span
177
+ * is emitted. Privacy-safe by default — `recordInputs`/`recordOutputs` both
178
+ * default `false`, so no prompt or generated text leaves the worker without an
179
+ * explicit opt-in; only structural metadata + token counts are recorded.
180
+ *
181
+ * Each export is fire-and-forget (registered with `waitUntil` when supplied);
182
+ * every rejection is swallowed so a flaky collector never surfaces to the run.
183
+ *
184
+ * Two deliberate differences from the SDK-backed integrations (`sentryTelemetry`
185
+ * / `braintrustTelemetry`), which delegate to a host tracer:
186
+ * - **No `onError`.** A failed call already emits a span with `status.code === 2`,
187
+ * so the failure is on the trace; there is no host client to also notify.
188
+ * - **Flat, not nested.** Every span gets `traceId` (shared when `traceId` is set)
189
+ * but no `parentSpanId`, so model-call and tool spans are siblings under the run
190
+ * rather than a tree — OTLP has no ambient span context to parent to here.
191
+ * @param options `endpoint` (+ optional `token`/`headers`/`serviceName`),
192
+ * `traceId` to group a run's spans, `waitUntil`, and the `recordInputs`/
193
+ * `recordOutputs` privacy flags.
194
+ * @experimental
195
+ */
196
+ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
125
197
  /**
126
198
  * The minimal, **structural** slice of `@sentry/cloudflare` (equivalently
127
199
  * `@sentry/node`/`@sentry/browser`) this bridge needs. `@sentry/cloudflare` is
@@ -170,4 +242,4 @@ interface SentryTelemetryOptions extends CommonOptions {
170
242
  * @experimental
171
243
  */
172
244
  declare const sentryTelemetry: (options: SentryTelemetryOptions) => Telemetry;
173
- export { type BraintrustLike, type BraintrustSpan, type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type SentryLike, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, sentryTelemetry };
245
+ export { type BraintrustLike, type BraintrustSpan, type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type OtlpTelemetryOptions, type SentryLike, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, otlpTelemetry, sentryTelemetry };
@@ -122,6 +122,78 @@ interface ConsoleTelemetryOptions extends CommonOptions {
122
122
  * @experimental
123
123
  */
124
124
  declare const consoleTelemetry: (options?: ConsoleTelemetryOptions) => Telemetry;
125
+ /**
126
+ * Options for {@link otlpTelemetry}.
127
+ * @experimental
128
+ */
129
+ interface OtlpTelemetryOptions extends CommonOptions {
130
+ /**
131
+ * The OTLP-over-HTTP collector base endpoint (e.g. the Lunora Cloud's `/v1`
132
+ * base). Spans are POSTed to `${endpoint}/v1/traces`; a trailing slash is
133
+ * tolerated. On the platform this is the injected `LUNORA_OTLP_ENDPOINT`.
134
+ */
135
+ endpoint: string;
136
+ /**
137
+ * Extra headers merged onto every POST — typically the correlation headers
138
+ * the platform injects. `Content-Type: application/json` is set by default.
139
+ */
140
+ headers?: Record<string, string>;
141
+ /** `service.name` resource attribute on every span. Defaults to `lunora`. */
142
+ serviceName?: string;
143
+ /**
144
+ * Bearer token added as `Authorization: Bearer` (wins over any authorization
145
+ * in `headers`) — the injected `LUNORA_OTLP_TOKEN`. Omit for an
146
+ * unauthenticated collector.
147
+ */
148
+ token?: string;
149
+ /**
150
+ * Trace id (32-hex) to hang every span of this run under, so one agent run
151
+ * reads as one trace. Pass a stable id derived from the run (e.g. the
152
+ * workflow run id). Omitted → each span mints its own trace id (still valid,
153
+ * just ungrouped).
154
+ */
155
+ traceId?: string;
156
+ /**
157
+ * The Worker request's `waitUntil`, so a fire-and-forget export survives
158
+ * isolate teardown after the turn returns. Omit and the send degrades to
159
+ * best-effort.
160
+ */
161
+ waitUntil?: (promise: Promise<unknown>) => void;
162
+ }
163
+ /**
164
+ * An OTLP-over-HTTP telemetry integration for `@lunora/agent`.
165
+ *
166
+ * The OTLP counterpart to {@link sentryTelemetry} / {@link braintrustTelemetry}:
167
+ * it wraps each language-model call and tool execution in an OTLP **span**
168
+ * (`gen_ai.*` semantic-convention attributes — model, provider, token usage,
169
+ * tool name) and ships it to a collector, so agent generations land in the same
170
+ * trace store as the rest of an app's telemetry (the Lunora Cloud, or any OTel
171
+ * collector). Plug it into `defineAgent({ telemetry: { isEnabled: true,
172
+ * integrations: [otlpTelemetry({ endpoint, token })] } })`.
173
+ *
174
+ * Emitting inside the turn's execution wrapper means one span per **real** turn:
175
+ * the agent loop memoizes each `step.do('llm:turn:N')`, so a Workflow replay
176
+ * returns the cached result without re-invoking `execute`, and no duplicate span
177
+ * is emitted. Privacy-safe by default — `recordInputs`/`recordOutputs` both
178
+ * default `false`, so no prompt or generated text leaves the worker without an
179
+ * explicit opt-in; only structural metadata + token counts are recorded.
180
+ *
181
+ * Each export is fire-and-forget (registered with `waitUntil` when supplied);
182
+ * every rejection is swallowed so a flaky collector never surfaces to the run.
183
+ *
184
+ * Two deliberate differences from the SDK-backed integrations (`sentryTelemetry`
185
+ * / `braintrustTelemetry`), which delegate to a host tracer:
186
+ * - **No `onError`.** A failed call already emits a span with `status.code === 2`,
187
+ * so the failure is on the trace; there is no host client to also notify.
188
+ * - **Flat, not nested.** Every span gets `traceId` (shared when `traceId` is set)
189
+ * but no `parentSpanId`, so model-call and tool spans are siblings under the run
190
+ * rather than a tree — OTLP has no ambient span context to parent to here.
191
+ * @param options `endpoint` (+ optional `token`/`headers`/`serviceName`),
192
+ * `traceId` to group a run's spans, `waitUntil`, and the `recordInputs`/
193
+ * `recordOutputs` privacy flags.
194
+ * @experimental
195
+ */
196
+ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
125
197
  /**
126
198
  * The minimal, **structural** slice of `@sentry/cloudflare` (equivalently
127
199
  * `@sentry/node`/`@sentry/browser`) this bridge needs. `@sentry/cloudflare` is
@@ -170,4 +242,4 @@ interface SentryTelemetryOptions extends CommonOptions {
170
242
  * @experimental
171
243
  */
172
244
  declare const sentryTelemetry: (options: SentryTelemetryOptions) => Telemetry;
173
- export { type BraintrustLike, type BraintrustSpan, type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type SentryLike, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, sentryTelemetry };
245
+ export { type BraintrustLike, type BraintrustSpan, type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type OtlpTelemetryOptions, type SentryLike, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, otlpTelemetry, sentryTelemetry };
@@ -1,4 +1,5 @@
1
1
  export { braintrustTelemetry } from '../packem_shared/braintrustTelemetry-wuGDErob.mjs';
2
2
  export { combineTelemetry } from '../packem_shared/combineTelemetry-DCyaaWAI.mjs';
3
3
  export { consoleTelemetry } from '../packem_shared/consoleTelemetry-z2MiP1jt.mjs';
4
+ export { otlpTelemetry } from '../packem_shared/otlpTelemetry-DL6iZ9e2.mjs';
4
5
  export { sentryTelemetry } from '../packem_shared/sentryTelemetry-CgqFJyLO.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/agent",
3
- "version": "1.0.0-alpha.5",
3
+ "version": "1.0.0-alpha.7",
4
4
  "description": "Durable AI agents for Lunora: defineAgent compiles a replay-safe tool-loop onto Cloudflare Workflows, with DO SQLite threads and live message subscriptions",
5
5
  "keywords": [
6
6
  "agent",
@@ -76,10 +76,10 @@
76
76
  "access": "public"
77
77
  },
78
78
  "dependencies": {
79
- "@lunora/ai": "1.0.0-alpha.17",
79
+ "@lunora/ai": "1.0.0-alpha.18",
80
80
  "@lunora/errors": "1.0.0-alpha.6",
81
81
  "@lunora/mail": "1.0.0-alpha.16",
82
- "@lunora/server": "1.0.0-alpha.28",
82
+ "@lunora/server": "1.0.0-alpha.29",
83
83
  "@lunora/values": "1.0.0-alpha.9",
84
84
  "@lunora/workflow": "1.0.0-alpha.11",
85
85
  "@modelcontextprotocol/sdk": "^1.29.0",