@lunora/agent 1.0.0-alpha.21 → 1.0.0-alpha.211
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/channels.d.mts +23 -12
- package/dist/channels.d.ts +23 -12
- package/dist/channels.mjs +1 -1
- package/dist/component.d.mts +41 -2
- package/dist/component.d.ts +41 -2
- package/dist/component.mjs +2 -2
- package/dist/inbound.d.mts +9 -7
- package/dist/inbound.d.ts +9 -7
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +112 -17
- package/dist/index.d.ts +112 -17
- package/dist/index.mjs +1 -1
- package/dist/naming.d.mts +3 -7
- package/dist/naming.d.ts +3 -7
- package/dist/naming.mjs +1 -1
- package/dist/packem_shared/AGENT_MODULE-B6FqQC80.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-CzjMEuTV.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-DFF_g58r.mjs +2 -0
- package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
- package/dist/packem_shared/agent-loop-D0-0Vef5.mjs +3 -0
- package/dist/packem_shared/agentAsTool-BJi-uU4s.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
- package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
- package/dist/packem_shared/codeTool-dpJANTDc.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-D07XhGKr.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
- package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-CCr3VqgT.mjs +1 -0
- package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
- package/dist/packem_shared/createAgentContext-Wlc1ZgWa.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-D9DbEj9I.mjs +3 -0
- package/dist/packem_shared/defineAgent-Bp6acfN1.mjs +3 -0
- package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/functionTool-Baqdn0OK.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
- package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-DJm-xu2K.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-gv4m8h9b.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-BwBezb19.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
- package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
- package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-DqYbp4ye.d.mts} +300 -27
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-DqYbp4ye.d.ts} +300 -27
- package/dist/packem_shared/voice-turn-BNCI9kAI.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BobmV4cD.mjs +1 -0
- package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
- package/dist/reply.d.mts +40 -0
- package/dist/reply.d.ts +40 -0
- package/dist/reply.mjs +1 -0
- package/dist/sandbox.d.mts +157 -16
- package/dist/sandbox.d.ts +157 -16
- package/dist/sandbox.mjs +1 -1
- package/dist/skill-markdown.d.mts +36 -0
- package/dist/skill-markdown.d.ts +36 -0
- package/dist/skill-markdown.mjs +1 -0
- package/dist/telemetry/index.d.mts +152 -33
- package/dist/telemetry/index.d.ts +152 -33
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +19 -9
- package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
- package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
- package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
- package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
- package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
- package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
- package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
- package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
- package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
- package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
- package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
- package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
- package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
- package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
- package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
- package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
- package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
- package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
- package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
- package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
- package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
- package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
- package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
- package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
- package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
|
@@ -60,9 +60,24 @@ interface BraintrustTelemetryOptions extends CommonOptions {
|
|
|
60
60
|
* A dependency-injected Braintrust bridge for the ai@7 telemetry surface.
|
|
61
61
|
*
|
|
62
62
|
* It wraps model calls (`type: "llm"`) and tool executions (`type: "tool"`) in
|
|
63
|
-
* `logger.traced` spans and logs structural metadata
|
|
64
|
-
*
|
|
65
|
-
*
|
|
63
|
+
* `logger.traced` spans and logs structural metadata, including the call's token
|
|
64
|
+
* usage as Braintrust `metrics`. Prompts / tool arguments are logged only when
|
|
65
|
+
* `recordInputs` is set; generated text / tool results only when `recordOutputs`
|
|
66
|
+
* is set. `onError` opens a span and logs the error.
|
|
67
|
+
*
|
|
68
|
+
* The tool span is driven by the agent LOOP, not by `ai`: Lunora exposes tools
|
|
69
|
+
* schema-only so the SDK never executes one (see `telemetry/tool-execution.ts`).
|
|
70
|
+
*
|
|
71
|
+
* **A model-call span closes when the CALL ends, not when `execute()` resolves.**
|
|
72
|
+
* On a streamed turn `execute()` resolves the instant `doStream` hands back the
|
|
73
|
+
* stream — before a token, before any usage — so a span that simply awaited it
|
|
74
|
+
* measured time-to-first-byte and logged the stream handle instead of the
|
|
75
|
+
* generation. `execute()` still runs INSIDE the traced callback, which is what
|
|
76
|
+
* parents the provider's own work under the span; the callback then parks until
|
|
77
|
+
* the SDK's terminal event for that `callId` arrives, so `traced` finishes the
|
|
78
|
+
* span at the real end of the call, with the real usage. The caller gets
|
|
79
|
+
* `execute()`'s value the moment it resolves, exactly as before — the span's
|
|
80
|
+
* lifetime and the caller's are deliberately separate.
|
|
66
81
|
*
|
|
67
82
|
* The app owns Braintrust initialization; pass the logger in as `logger`.
|
|
68
83
|
* @experimental
|
|
@@ -173,36 +188,72 @@ interface OtlpTelemetryOptions extends CommonOptions {
|
|
|
173
188
|
* An OTLP-over-HTTP telemetry integration for `@lunora/agent`.
|
|
174
189
|
*
|
|
175
190
|
* The OTLP counterpart to the `sentryTelemetry` / `braintrustTelemetry` bridges:
|
|
176
|
-
* it
|
|
191
|
+
* it records each language-model call and each tool execution as an OTLP **span**
|
|
177
192
|
* (`gen_ai.*` semantic-convention attributes — model, provider, token usage,
|
|
178
193
|
* tool name) and ships it to a collector, so agent generations land in the same
|
|
179
194
|
* trace store as the rest of an app's telemetry (the Lunora Cloud, or any OTel
|
|
180
195
|
* collector). Plug it into `defineAgent({ telemetry: { isEnabled: true,
|
|
181
196
|
* integrations: [otlpTelemetry({ endpoint, token })] } })`.
|
|
182
197
|
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
198
|
+
* **A model-call span closes when the CALL ends, not when `execute()` resolves.**
|
|
199
|
+
* On a streamed turn `execute()` resolves the instant `doStream` hands back the
|
|
200
|
+
* stream — before a single token, before any usage, and before any mid-stream
|
|
201
|
+
* failure. Closing the span there reported every voice and workflow-streamed turn
|
|
202
|
+
* as a ~1 ms, zero-token, always-OK call. So the span opens in
|
|
203
|
+
* `executeLanguageModelCall` (which also owns the failure path, since a rejected
|
|
204
|
+
* provider call produces no end event) and closes on `onLanguageModelCallEnd`,
|
|
205
|
+
* which the SDK fires once the response is normalized — after the stream's
|
|
206
|
+
* `finish` part, where the duration and the token usage actually live.
|
|
207
|
+
* `onError` / `onAbort` close whatever is still open, so a stream that dies or is
|
|
208
|
+
* barged in on reports a failure instead of a phantom success.
|
|
209
|
+
*
|
|
210
|
+
* **Tool spans come from the agent loop.** Lunora exposes tools to the model
|
|
211
|
+
* schema-only, so `ai` never runs one and never fires its tool telemetry; the
|
|
212
|
+
* loop calls `executeTool` itself from the durable step where the tool really
|
|
213
|
+
* runs (see `telemetry/tool-execution.ts`).
|
|
214
|
+
*
|
|
215
|
+
* One span per REAL execution: the agent loop memoizes each `step.do(...)`, so a
|
|
216
|
+
* Workflow replay returns the cached result without re-invoking the wrapped work
|
|
217
|
+
* and no duplicate span is emitted. Privacy-safe by default —
|
|
218
|
+
* `recordInputs`/`recordOutputs` both default `false`, so no prompt or generated
|
|
219
|
+
* text leaves the worker without an explicit opt-in; only structural metadata +
|
|
220
|
+
* token counts are recorded.
|
|
189
221
|
*
|
|
190
222
|
* Each export is fire-and-forget (registered with `waitUntil` when supplied);
|
|
191
223
|
* every rejection is swallowed so a flaky collector never surfaces to the run.
|
|
192
224
|
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* `traceId` is set) but no `parentSpanId`, so model-call and tool spans are
|
|
198
|
-
* siblings under the run rather than a tree — OTLP has no ambient span context to
|
|
199
|
-
* parent to here.
|
|
225
|
+
* One deliberate difference from the SDK-backed bridges, which delegate to a host
|
|
226
|
+
* tracer: flat, not nested. Every span gets `traceId` (shared when `traceId` is
|
|
227
|
+
* set) but no `parentSpanId`, so model-call and tool spans are siblings under the
|
|
228
|
+
* run rather than a tree — OTLP has no ambient span context to parent to here.
|
|
200
229
|
* @param options `endpoint` (+ optional `token`/`headers`/`serviceName`),
|
|
201
230
|
* `traceId` to group a run's spans, `waitUntil`, and the `recordInputs`/
|
|
202
231
|
* `recordOutputs` privacy flags.
|
|
203
232
|
* @experimental
|
|
204
233
|
*/
|
|
205
234
|
declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
|
|
235
|
+
/** The span context both `startSpan` and `startSpanManual` are called with. */
|
|
236
|
+
interface SentrySpanContext {
|
|
237
|
+
attributes?: Record<string, unknown>;
|
|
238
|
+
name: string;
|
|
239
|
+
op?: string;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* The subset of a Sentry `Span` this bridge drives. Structural, like
|
|
243
|
+
* {@link SentryLike} itself — a real `@sentry/*` span satisfies it.
|
|
244
|
+
* @experimental
|
|
245
|
+
*/
|
|
246
|
+
interface SentrySpan {
|
|
247
|
+
/** Finish the span. Called once, from whichever terminal event closes the call. */
|
|
248
|
+
end: () => void;
|
|
249
|
+
/** Attach attributes discovered after the span started (token usage). */
|
|
250
|
+
setAttributes?: (attributes: Record<string, unknown>) => unknown;
|
|
251
|
+
/** `1` = OK, `2` = ERROR (Sentry's `SPAN_STATUS_OK` / `SPAN_STATUS_ERROR`). */
|
|
252
|
+
setStatus?: (status: {
|
|
253
|
+
code: 0 | 1 | 2;
|
|
254
|
+
message?: string;
|
|
255
|
+
}) => unknown;
|
|
256
|
+
}
|
|
206
257
|
/**
|
|
207
258
|
* The minimal, **structural** slice of `@sentry/cloudflare` (equivalently
|
|
208
259
|
* `@sentry/node`/`@sentry/browser`) this bridge needs. `@sentry/cloudflare` is
|
|
@@ -214,16 +265,16 @@ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
|
|
|
214
265
|
interface SentryLike {
|
|
215
266
|
/** Capture a thrown value / exception. */
|
|
216
267
|
captureException: (exception: unknown) => unknown;
|
|
217
|
-
/** Run `callback` inside a new span
|
|
218
|
-
startSpan: <T>(context:
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
268
|
+
/** Run `callback` inside a new span, finished when the callback settles. */
|
|
269
|
+
startSpan: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
|
|
270
|
+
/**
|
|
271
|
+
* Run `callback` inside a new span that is **not** finished automatically —
|
|
272
|
+
* the caller owns its lifetime through `span.end()`. Present on every Sentry
|
|
273
|
+
* SDK built on `@sentry/core` (verified against `@sentry/core@10.55.0`); it is
|
|
274
|
+
* what lets a streamed model call be measured to the end of the stream while
|
|
275
|
+
* still nesting the provider's own work under it.
|
|
276
|
+
*/
|
|
277
|
+
startSpanManual: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
|
|
227
278
|
}
|
|
228
279
|
/**
|
|
229
280
|
* Options for {@link sentryTelemetry}.
|
|
@@ -241,14 +292,82 @@ interface SentryTelemetryOptions extends CommonOptions {
|
|
|
241
292
|
/**
|
|
242
293
|
* A dependency-injected Sentry bridge for the ai@7 telemetry surface.
|
|
243
294
|
*
|
|
244
|
-
* It wraps model calls and tool executions in Sentry spans
|
|
245
|
-
*
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
* set, in which case prompts
|
|
295
|
+
* It wraps model calls and tool executions in Sentry spans so nested
|
|
296
|
+
* provider/tool work is correctly parented, and routes `onError` to
|
|
297
|
+
* `Sentry.captureException`. Span attributes carry only structural metadata
|
|
298
|
+
* (model, provider, tool name, token usage) unless `recordInputs` /
|
|
299
|
+
* `recordOutputs` are set, in which case prompts, tool arguments and generated
|
|
300
|
+
* text are attached too.
|
|
301
|
+
*
|
|
302
|
+
* The tool span is driven by the agent LOOP, not by `ai`: Lunora exposes tools
|
|
303
|
+
* schema-only so the SDK never executes one (see `telemetry/tool-execution.ts`).
|
|
304
|
+
*
|
|
305
|
+
* **A model-call span closes when the CALL ends, not when `execute()` resolves.**
|
|
306
|
+
* On a streamed turn `execute()` resolves the instant `doStream` hands back the
|
|
307
|
+
* stream — before a token, before any usage. The span still OPENS around
|
|
308
|
+
* `execute()`, because that is what makes it the active span nested provider work
|
|
309
|
+
* parents to, but it is opened with `startSpanManual` and so is not finished
|
|
310
|
+
* there: `onLanguageModelCallEnd` ends it, once the response is normalized and
|
|
311
|
+
* the real duration and token usage are both known. `onAbort` / `onError` end the
|
|
312
|
+
* call they name as a failure, so a stream that dies or is barged in on reports
|
|
313
|
+
* one instead of a phantom success.
|
|
249
314
|
*
|
|
250
315
|
* The app owns Sentry initialization; pass the namespace in as `Sentry`.
|
|
251
316
|
* @experimental
|
|
252
317
|
*/
|
|
253
318
|
declare const sentryTelemetry: (options: SentryTelemetryOptions) => Telemetry;
|
|
254
|
-
export {
|
|
319
|
+
export {
|
|
320
|
+
/**
|
|
321
|
+
* `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
|
|
322
|
+
*
|
|
323
|
+
* Every export here produces an ai@7 `Telemetry` object suitable for the
|
|
324
|
+
* `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
|
|
325
|
+
* isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
|
|
326
|
+
* zero-dependency structured console tracer; `combineTelemetry` fans the
|
|
327
|
+
* lifecycle out to several integrations and nests their execution wrappers;
|
|
328
|
+
* `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
|
|
329
|
+
* app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
|
|
330
|
+
* never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
|
|
331
|
+
* OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
|
|
332
|
+
* generations land in the same trace store as the rest of the app.
|
|
333
|
+
*
|
|
334
|
+
* All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
|
|
335
|
+
* both default `false`), so nothing sensitive is recorded without opt-in.
|
|
336
|
+
*/
|
|
337
|
+
type BraintrustLike,
|
|
338
|
+
/**
|
|
339
|
+
* `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
|
|
340
|
+
*
|
|
341
|
+
* Every export here produces an ai@7 `Telemetry` object suitable for the
|
|
342
|
+
* `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
|
|
343
|
+
* isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
|
|
344
|
+
* zero-dependency structured console tracer; `combineTelemetry` fans the
|
|
345
|
+
* lifecycle out to several integrations and nests their execution wrappers;
|
|
346
|
+
* `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
|
|
347
|
+
* app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
|
|
348
|
+
* never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
|
|
349
|
+
* OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
|
|
350
|
+
* generations land in the same trace store as the rest of the app.
|
|
351
|
+
*
|
|
352
|
+
* All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
|
|
353
|
+
* both default `false`), so nothing sensitive is recorded without opt-in.
|
|
354
|
+
*/
|
|
355
|
+
type BraintrustSpan,
|
|
356
|
+
/**
|
|
357
|
+
* `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
|
|
358
|
+
*
|
|
359
|
+
* Every export here produces an ai@7 `Telemetry` object suitable for the
|
|
360
|
+
* `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
|
|
361
|
+
* isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
|
|
362
|
+
* zero-dependency structured console tracer; `combineTelemetry` fans the
|
|
363
|
+
* lifecycle out to several integrations and nests their execution wrappers;
|
|
364
|
+
* `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
|
|
365
|
+
* app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
|
|
366
|
+
* never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
|
|
367
|
+
* OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
|
|
368
|
+
* generations land in the same trace store as the rest of the app.
|
|
369
|
+
*
|
|
370
|
+
* All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
|
|
371
|
+
* both default `false`), so nothing sensitive is recorded without opt-in.
|
|
372
|
+
*/
|
|
373
|
+
type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type OtlpTelemetryOptions, type SentryLike, type SentrySpan, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, otlpTelemetry, sentryTelemetry };
|
|
@@ -60,9 +60,24 @@ interface BraintrustTelemetryOptions extends CommonOptions {
|
|
|
60
60
|
* A dependency-injected Braintrust bridge for the ai@7 telemetry surface.
|
|
61
61
|
*
|
|
62
62
|
* It wraps model calls (`type: "llm"`) and tool executions (`type: "tool"`) in
|
|
63
|
-
* `logger.traced` spans and logs structural metadata
|
|
64
|
-
*
|
|
65
|
-
*
|
|
63
|
+
* `logger.traced` spans and logs structural metadata, including the call's token
|
|
64
|
+
* usage as Braintrust `metrics`. Prompts / tool arguments are logged only when
|
|
65
|
+
* `recordInputs` is set; generated text / tool results only when `recordOutputs`
|
|
66
|
+
* is set. `onError` opens a span and logs the error.
|
|
67
|
+
*
|
|
68
|
+
* The tool span is driven by the agent LOOP, not by `ai`: Lunora exposes tools
|
|
69
|
+
* schema-only so the SDK never executes one (see `telemetry/tool-execution.ts`).
|
|
70
|
+
*
|
|
71
|
+
* **A model-call span closes when the CALL ends, not when `execute()` resolves.**
|
|
72
|
+
* On a streamed turn `execute()` resolves the instant `doStream` hands back the
|
|
73
|
+
* stream — before a token, before any usage — so a span that simply awaited it
|
|
74
|
+
* measured time-to-first-byte and logged the stream handle instead of the
|
|
75
|
+
* generation. `execute()` still runs INSIDE the traced callback, which is what
|
|
76
|
+
* parents the provider's own work under the span; the callback then parks until
|
|
77
|
+
* the SDK's terminal event for that `callId` arrives, so `traced` finishes the
|
|
78
|
+
* span at the real end of the call, with the real usage. The caller gets
|
|
79
|
+
* `execute()`'s value the moment it resolves, exactly as before — the span's
|
|
80
|
+
* lifetime and the caller's are deliberately separate.
|
|
66
81
|
*
|
|
67
82
|
* The app owns Braintrust initialization; pass the logger in as `logger`.
|
|
68
83
|
* @experimental
|
|
@@ -173,36 +188,72 @@ interface OtlpTelemetryOptions extends CommonOptions {
|
|
|
173
188
|
* An OTLP-over-HTTP telemetry integration for `@lunora/agent`.
|
|
174
189
|
*
|
|
175
190
|
* The OTLP counterpart to the `sentryTelemetry` / `braintrustTelemetry` bridges:
|
|
176
|
-
* it
|
|
191
|
+
* it records each language-model call and each tool execution as an OTLP **span**
|
|
177
192
|
* (`gen_ai.*` semantic-convention attributes — model, provider, token usage,
|
|
178
193
|
* tool name) and ships it to a collector, so agent generations land in the same
|
|
179
194
|
* trace store as the rest of an app's telemetry (the Lunora Cloud, or any OTel
|
|
180
195
|
* collector). Plug it into `defineAgent({ telemetry: { isEnabled: true,
|
|
181
196
|
* integrations: [otlpTelemetry({ endpoint, token })] } })`.
|
|
182
197
|
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
198
|
+
* **A model-call span closes when the CALL ends, not when `execute()` resolves.**
|
|
199
|
+
* On a streamed turn `execute()` resolves the instant `doStream` hands back the
|
|
200
|
+
* stream — before a single token, before any usage, and before any mid-stream
|
|
201
|
+
* failure. Closing the span there reported every voice and workflow-streamed turn
|
|
202
|
+
* as a ~1 ms, zero-token, always-OK call. So the span opens in
|
|
203
|
+
* `executeLanguageModelCall` (which also owns the failure path, since a rejected
|
|
204
|
+
* provider call produces no end event) and closes on `onLanguageModelCallEnd`,
|
|
205
|
+
* which the SDK fires once the response is normalized — after the stream's
|
|
206
|
+
* `finish` part, where the duration and the token usage actually live.
|
|
207
|
+
* `onError` / `onAbort` close whatever is still open, so a stream that dies or is
|
|
208
|
+
* barged in on reports a failure instead of a phantom success.
|
|
209
|
+
*
|
|
210
|
+
* **Tool spans come from the agent loop.** Lunora exposes tools to the model
|
|
211
|
+
* schema-only, so `ai` never runs one and never fires its tool telemetry; the
|
|
212
|
+
* loop calls `executeTool` itself from the durable step where the tool really
|
|
213
|
+
* runs (see `telemetry/tool-execution.ts`).
|
|
214
|
+
*
|
|
215
|
+
* One span per REAL execution: the agent loop memoizes each `step.do(...)`, so a
|
|
216
|
+
* Workflow replay returns the cached result without re-invoking the wrapped work
|
|
217
|
+
* and no duplicate span is emitted. Privacy-safe by default —
|
|
218
|
+
* `recordInputs`/`recordOutputs` both default `false`, so no prompt or generated
|
|
219
|
+
* text leaves the worker without an explicit opt-in; only structural metadata +
|
|
220
|
+
* token counts are recorded.
|
|
189
221
|
*
|
|
190
222
|
* Each export is fire-and-forget (registered with `waitUntil` when supplied);
|
|
191
223
|
* every rejection is swallowed so a flaky collector never surfaces to the run.
|
|
192
224
|
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* `traceId` is set) but no `parentSpanId`, so model-call and tool spans are
|
|
198
|
-
* siblings under the run rather than a tree — OTLP has no ambient span context to
|
|
199
|
-
* parent to here.
|
|
225
|
+
* One deliberate difference from the SDK-backed bridges, which delegate to a host
|
|
226
|
+
* tracer: flat, not nested. Every span gets `traceId` (shared when `traceId` is
|
|
227
|
+
* set) but no `parentSpanId`, so model-call and tool spans are siblings under the
|
|
228
|
+
* run rather than a tree — OTLP has no ambient span context to parent to here.
|
|
200
229
|
* @param options `endpoint` (+ optional `token`/`headers`/`serviceName`),
|
|
201
230
|
* `traceId` to group a run's spans, `waitUntil`, and the `recordInputs`/
|
|
202
231
|
* `recordOutputs` privacy flags.
|
|
203
232
|
* @experimental
|
|
204
233
|
*/
|
|
205
234
|
declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
|
|
235
|
+
/** The span context both `startSpan` and `startSpanManual` are called with. */
|
|
236
|
+
interface SentrySpanContext {
|
|
237
|
+
attributes?: Record<string, unknown>;
|
|
238
|
+
name: string;
|
|
239
|
+
op?: string;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* The subset of a Sentry `Span` this bridge drives. Structural, like
|
|
243
|
+
* {@link SentryLike} itself — a real `@sentry/*` span satisfies it.
|
|
244
|
+
* @experimental
|
|
245
|
+
*/
|
|
246
|
+
interface SentrySpan {
|
|
247
|
+
/** Finish the span. Called once, from whichever terminal event closes the call. */
|
|
248
|
+
end: () => void;
|
|
249
|
+
/** Attach attributes discovered after the span started (token usage). */
|
|
250
|
+
setAttributes?: (attributes: Record<string, unknown>) => unknown;
|
|
251
|
+
/** `1` = OK, `2` = ERROR (Sentry's `SPAN_STATUS_OK` / `SPAN_STATUS_ERROR`). */
|
|
252
|
+
setStatus?: (status: {
|
|
253
|
+
code: 0 | 1 | 2;
|
|
254
|
+
message?: string;
|
|
255
|
+
}) => unknown;
|
|
256
|
+
}
|
|
206
257
|
/**
|
|
207
258
|
* The minimal, **structural** slice of `@sentry/cloudflare` (equivalently
|
|
208
259
|
* `@sentry/node`/`@sentry/browser`) this bridge needs. `@sentry/cloudflare` is
|
|
@@ -214,16 +265,16 @@ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
|
|
|
214
265
|
interface SentryLike {
|
|
215
266
|
/** Capture a thrown value / exception. */
|
|
216
267
|
captureException: (exception: unknown) => unknown;
|
|
217
|
-
/** Run `callback` inside a new span
|
|
218
|
-
startSpan: <T>(context:
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
268
|
+
/** Run `callback` inside a new span, finished when the callback settles. */
|
|
269
|
+
startSpan: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
|
|
270
|
+
/**
|
|
271
|
+
* Run `callback` inside a new span that is **not** finished automatically —
|
|
272
|
+
* the caller owns its lifetime through `span.end()`. Present on every Sentry
|
|
273
|
+
* SDK built on `@sentry/core` (verified against `@sentry/core@10.55.0`); it is
|
|
274
|
+
* what lets a streamed model call be measured to the end of the stream while
|
|
275
|
+
* still nesting the provider's own work under it.
|
|
276
|
+
*/
|
|
277
|
+
startSpanManual: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
|
|
227
278
|
}
|
|
228
279
|
/**
|
|
229
280
|
* Options for {@link sentryTelemetry}.
|
|
@@ -241,14 +292,82 @@ interface SentryTelemetryOptions extends CommonOptions {
|
|
|
241
292
|
/**
|
|
242
293
|
* A dependency-injected Sentry bridge for the ai@7 telemetry surface.
|
|
243
294
|
*
|
|
244
|
-
* It wraps model calls and tool executions in Sentry spans
|
|
245
|
-
*
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
* set, in which case prompts
|
|
295
|
+
* It wraps model calls and tool executions in Sentry spans so nested
|
|
296
|
+
* provider/tool work is correctly parented, and routes `onError` to
|
|
297
|
+
* `Sentry.captureException`. Span attributes carry only structural metadata
|
|
298
|
+
* (model, provider, tool name, token usage) unless `recordInputs` /
|
|
299
|
+
* `recordOutputs` are set, in which case prompts, tool arguments and generated
|
|
300
|
+
* text are attached too.
|
|
301
|
+
*
|
|
302
|
+
* The tool span is driven by the agent LOOP, not by `ai`: Lunora exposes tools
|
|
303
|
+
* schema-only so the SDK never executes one (see `telemetry/tool-execution.ts`).
|
|
304
|
+
*
|
|
305
|
+
* **A model-call span closes when the CALL ends, not when `execute()` resolves.**
|
|
306
|
+
* On a streamed turn `execute()` resolves the instant `doStream` hands back the
|
|
307
|
+
* stream — before a token, before any usage. The span still OPENS around
|
|
308
|
+
* `execute()`, because that is what makes it the active span nested provider work
|
|
309
|
+
* parents to, but it is opened with `startSpanManual` and so is not finished
|
|
310
|
+
* there: `onLanguageModelCallEnd` ends it, once the response is normalized and
|
|
311
|
+
* the real duration and token usage are both known. `onAbort` / `onError` end the
|
|
312
|
+
* call they name as a failure, so a stream that dies or is barged in on reports
|
|
313
|
+
* one instead of a phantom success.
|
|
249
314
|
*
|
|
250
315
|
* The app owns Sentry initialization; pass the namespace in as `Sentry`.
|
|
251
316
|
* @experimental
|
|
252
317
|
*/
|
|
253
318
|
declare const sentryTelemetry: (options: SentryTelemetryOptions) => Telemetry;
|
|
254
|
-
export {
|
|
319
|
+
export {
|
|
320
|
+
/**
|
|
321
|
+
* `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
|
|
322
|
+
*
|
|
323
|
+
* Every export here produces an ai@7 `Telemetry` object suitable for the
|
|
324
|
+
* `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
|
|
325
|
+
* isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
|
|
326
|
+
* zero-dependency structured console tracer; `combineTelemetry` fans the
|
|
327
|
+
* lifecycle out to several integrations and nests their execution wrappers;
|
|
328
|
+
* `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
|
|
329
|
+
* app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
|
|
330
|
+
* never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
|
|
331
|
+
* OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
|
|
332
|
+
* generations land in the same trace store as the rest of the app.
|
|
333
|
+
*
|
|
334
|
+
* All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
|
|
335
|
+
* both default `false`), so nothing sensitive is recorded without opt-in.
|
|
336
|
+
*/
|
|
337
|
+
type BraintrustLike,
|
|
338
|
+
/**
|
|
339
|
+
* `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
|
|
340
|
+
*
|
|
341
|
+
* Every export here produces an ai@7 `Telemetry` object suitable for the
|
|
342
|
+
* `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
|
|
343
|
+
* isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
|
|
344
|
+
* zero-dependency structured console tracer; `combineTelemetry` fans the
|
|
345
|
+
* lifecycle out to several integrations and nests their execution wrappers;
|
|
346
|
+
* `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
|
|
347
|
+
* app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
|
|
348
|
+
* never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
|
|
349
|
+
* OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
|
|
350
|
+
* generations land in the same trace store as the rest of the app.
|
|
351
|
+
*
|
|
352
|
+
* All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
|
|
353
|
+
* both default `false`), so nothing sensitive is recorded without opt-in.
|
|
354
|
+
*/
|
|
355
|
+
type BraintrustSpan,
|
|
356
|
+
/**
|
|
357
|
+
* `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
|
|
358
|
+
*
|
|
359
|
+
* Every export here produces an ai@7 `Telemetry` object suitable for the
|
|
360
|
+
* `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
|
|
361
|
+
* isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
|
|
362
|
+
* zero-dependency structured console tracer; `combineTelemetry` fans the
|
|
363
|
+
* lifecycle out to several integrations and nests their execution wrappers;
|
|
364
|
+
* `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
|
|
365
|
+
* app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
|
|
366
|
+
* never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
|
|
367
|
+
* OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
|
|
368
|
+
* generations land in the same trace store as the rest of the app.
|
|
369
|
+
*
|
|
370
|
+
* All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
|
|
371
|
+
* both default `false`), so nothing sensitive is recorded without opt-in.
|
|
372
|
+
*/
|
|
373
|
+
type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type OtlpTelemetryOptions, type SentryLike, type SentrySpan, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, otlpTelemetry, sentryTelemetry };
|
package/dist/telemetry/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-
|
|
1
|
+
import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-Byne8uPK.mjs";import{combineTelemetry as m}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{consoleTelemetry as p}from"../packem_shared/consoleTelemetry-BZY3Y-Ly.mjs";import{otlpTelemetry as f}from"../packem_shared/otlpTelemetry-DJm-xu2K.mjs";import{sentryTelemetry as T}from"../packem_shared/sentryTelemetry-BHeydiAB.mjs";export{o as braintrustTelemetry,m as combineTelemetry,p as consoleTelemetry,f as otlpTelemetry,T as sentryTelemetry};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/agent",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.211",
|
|
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",
|
|
@@ -62,6 +62,14 @@
|
|
|
62
62
|
"types": "./dist/naming.d.ts",
|
|
63
63
|
"import": "./dist/naming.mjs"
|
|
64
64
|
},
|
|
65
|
+
"./skill-markdown": {
|
|
66
|
+
"types": "./dist/skill-markdown.d.ts",
|
|
67
|
+
"import": "./dist/skill-markdown.mjs"
|
|
68
|
+
},
|
|
69
|
+
"./reply": {
|
|
70
|
+
"types": "./dist/reply.d.ts",
|
|
71
|
+
"import": "./dist/reply.mjs"
|
|
72
|
+
},
|
|
65
73
|
"./sandbox": {
|
|
66
74
|
"types": "./dist/sandbox.d.ts",
|
|
67
75
|
"import": "./dist/sandbox.mjs"
|
|
@@ -76,14 +84,16 @@
|
|
|
76
84
|
"access": "public"
|
|
77
85
|
},
|
|
78
86
|
"dependencies": {
|
|
79
|
-
"@
|
|
80
|
-
"@lunora/
|
|
81
|
-
"@lunora/
|
|
82
|
-
"@lunora/
|
|
83
|
-
"@lunora/
|
|
84
|
-
"@lunora/
|
|
85
|
-
"@
|
|
86
|
-
"
|
|
87
|
+
"@ai-sdk/provider-utils": "5.0.53",
|
|
88
|
+
"@lunora/ai": "1.0.0-alpha.128",
|
|
89
|
+
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
90
|
+
"@lunora/mail": "1.0.0-alpha.108",
|
|
91
|
+
"@lunora/server": "1.0.0-alpha.204",
|
|
92
|
+
"@lunora/values": "1.0.0-alpha.66",
|
|
93
|
+
"@lunora/workflow": "1.0.0-alpha.78",
|
|
94
|
+
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
95
|
+
"ai": "7.0.127",
|
|
96
|
+
"yaml": "^2.9.1"
|
|
87
97
|
},
|
|
88
98
|
"engines": {
|
|
89
99
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e="agents",t="sandbox",s=`${t}:invoke`,n={appendMessage:`${e}:agentAppendMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=a=>typeof a=="string"?{__lunoraRef:a}:a;export{e as AGENT_MODULE,n as DEFAULT_AGENT_FUNCTION_PATHS,s as SANDBOX_INVOKE_PATH,t as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAi as l}from"@lunora/ai";import{g as f}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{o as y}from"./base64-jU-Ci6Tu.mjs";import{createStreamGenerate as p}from"./createAgentGenerate-BUVImo85.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as g,toFunctionReference as h}from"./AGENT_MODULE-BXx-tSCe.mjs";import{parseIdentity as m,pcmToWav as b,readTranscriptionText as w,readSynthesisAudio as v,runVoiceTurn as S,toByteIterable as A}from"./runVoiceTurn-PkMsfG_v.mjs";const I="@cf/openai/whisper-large-v3-turbo",k="@cf/deepgram/aura-1",x=8*1024*1024,B=256*1024,u=15,T=5e3;class W{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,n){this.state=t,this.env=e,this.agent=s,this.exportName=n,this.paths=g,this.ai=l({binding:e.AI,env:e}),this.streamGenerate=p(s,e),this.sttModel=s.voice?.stt??I,this.ttsModel=s.voice?.tts??k}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const e=new URL(t.url).searchParams.get("threadKey");if(!e)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,n=new s,i=n[0],r=n[1];this.state.acceptWebSocket(r);const c=crypto.randomUUID(),o=m(t.headers.get("x-lunora-identity")),d=t.headers.get("x-lunora-userid")??void 0;r.serializeAttachment?.({connectionId:c,threadKey:e,turn:0,...o===void 0?{}:{identity:o},...d===void 0?{}:{userId:d}}),this.send(r,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const a=this.agent.voice?.greeting;return a&&a.length>0&&this.state.waitUntil?.(this.speakGreeting(r,c,e,d,o,a)),new Response(null,{status:101,webSocket:i})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s)try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(n){this.send(t,{message:n instanceof Error?n.message:String(n),type:"error"})}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return f({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=b(t);return w(await this.ai.run(this.sttModel,{audio:y(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return v(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let n;try{n=JSON.parse(s)}catch{return}if(n.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(n.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:n.text})}bufferAudio(t,e,s){const n=(this.bufferedBytes.get(t)??0)+e.byteLength;if(n>x){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,n)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((r,c)=>r+c.byteLength,0),n=new Uint8Array(s);let i=0;for(const r of e)n.set(r,i),i+=r.byteLength;return n}async runTurn(t,e,s){const n=new AbortController;this.controllers.set(e.connectionId,n);try{await S({agent:this.agent,connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:n.signal,streamGenerate:this.streamGenerate,synthesize:async(i,r)=>this.synthesizeWithSignal(i,r),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===n&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,n,i,r){const c=this.resolveRun(n,i),o=new AbortController,d=()=>o.signal.aborted;this.controllers.set(e,o);try{await c(h(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...n===void 0?{}:{owner:n}});for await(const a of A(await this.synthesizeWithSignal(r,o.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,a)}d()||(await c(h(this.paths.appendMessage),{content:r,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:r,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===o&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>B&&s<T;)await new Promise(n=>{setTimeout(n,u)}),s+=u}}export{W as default};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{jsonSchema as s}from"ai";const c=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const e=(t.content??[]).filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>o.text).join(`
|
|
2
|
-
`);return t.isError===!0?`MCP tool error: ${e.length>0?e:"unknown error"}`:e.length>0?e:t.content},l=(t,e)=>({description:e.description??`MCP tool "${e.name}".`,execute:async o=>c(await t.callTool({arguments:o,name:e.name})),inputSchema:s(e.inputSchema),isLunoraAgentTool:!0}),u=async t=>{if(t.command!==void 0)throw new i("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new i("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const e=new URL(t.url),{Client:o}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(e)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(e)}const n=new o({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await n.connect(r),n},w=async t=>{const e=t.client??await u(t),{tools:o}=await e.listTools(),r={};for(const n of o)t.only!==void 0&&!t.only.includes(n.name)||(r[`${t.prefix??""}${n.name}`]=l(e,n));return r};export{c as adaptMcpResult,w as mcpTools};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{jsonSchema as T}from"ai";import{isDuplicateInstanceError as $}from"../channels.mjs";import{agentBindingName as N}from"../naming.mjs";import{toFunctionReference as b,DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-BXx-tSCe.mjs";const E=new Set(["complete","errored","terminated"]),I=120,S=500,k=e=>e!==null&&typeof e=="object"&&typeof e.status=="string"?e.status:"unknown",L=async e=>{await new Promise(t=>{setTimeout(t,e)})},C=async(e,t,n,u)=>{for(let a=0;a<t;a+=1){const i=k(await e.status());if(E.has(i))return i;await u(n)}return"timeout"},R=e=>{for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},j=e=>{if(typeof e.name!="string"||e.name.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof e.description!="string"||e.description.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");const{name:t}=e,n=N(t),u=e.maxPolls??I,a=e.pollIntervalMs??S,i=e.wait??L,m=b(A.listMessages),f=async(w,r)=>{const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new p("INTERNAL",`@lunora/agent: agent.asTool("${t}") found no Workflow binding "${n}" on env — declare the "${t}" agent so codegen wires its binding`);const d=`${r.threadKey}::sub::${t}::${r.toolCallId}`,g=`sub-${t}-${r.toolCallId}`,h={input:w.prompt,threadKey:d};let c;try{const l=await o.create({id:g,params:h});c=await o.get(l.id)}catch(l){if(!$(l))throw l;c=await o.get(g)}const s=await C(c,u,a,i);if(s==="errored"||s==="terminated")return`Sub-agent "${t}" ${s} before producing an answer.`;if(s==="timeout")return`Sub-agent "${t}" did not finish within the allotted time.`;const y=await r.run(m,{key:d});return R(y)};return{description:e.description,execute:f,inputSchema:T({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{j as agentAsTool};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const o=n=>{let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)},a=n=>{const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.codePointAt(r)??0;return t};export{a,o};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as g,t as p,r as l}from"./common-Dck97z3Y.mjs";const d=(o,a)=>typeof o=="string"&&o.length>0?o:a,i=o=>{const{functionId:a,logger:n,recordInputs:u=!1,recordOutputs:c=!1}=o;return{executeLanguageModelCall:e=>n.traced(async t=>{u&&t.log({input:l(e,"messages"),model:l(e,"modelId")});const r=await e.execute();return c&&t.log({output:r}),r},{name:d(a,"language_model_call"),type:"llm"}),executeTool:e=>{const t=l(l(e,"toolCall"),"toolName");return n.traced(async r=>{u&&r.log({input:p(e),tool:t});const s=await e.execute();return c&&r.log({output:s}),s},{name:d(t,"execute_tool"),type:"tool"})},onError:e=>{n.traced(t=>{t.log({error:g(e)})},{name:"error",type:"error"})}}};export{i as braintrustTelemetry};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
const n=t=>t.toolCalls===void 0||t.toolCalls.length===0?{content:t.content,role:"assistant"}:{content:[...t.content.length>0?[{text:t.content,type:"text"}]:[],...t.toolCalls.map(o=>({input:o.input,toolCallId:o.id,toolName:o.name,type:"tool-call"}))],role:"assistant"},s=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),l=t=>{const o=[];t.instructions!==void 0&&t.instructions.length>0&&o.push({content:t.instructions,role:"system"}),t.memoryContext!==void 0&&t.memoryContext.length>0&&o.push({content:`Relevant context retrieved for this conversation:
|
|
2
|
-
|
|
3
|
-
${t.memoryContext}`,role:"system"}),t.summary!==void 0&&t.summary.length>0&&o.push({content:`Summary of the earlier conversation:
|
|
4
|
-
|
|
5
|
-
${t.summary}`,role:"system"});for(const e of t.history)if(e.status!=="awaiting_approval")switch(e.role){case"assistant":{o.push(n(e));break}case"system":{o.push({content:e.content,role:"system"});break}case"tool":{o.push(s(e));break}case"user":{o.push({content:e.content,role:"user"});break}}return o};export{l as buildModelMessages};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";import{jsonSchema as h}from"ai";const $=16,f=4e3,A=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=f?e:`${o.slice(0,f)}… [truncated]`},b=(e,o)=>{let t=e;for(const s of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,s))return;t=t[s]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!(r in o))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?b(o[r],t.$path):o[r]}const s={};for(const[r,i]of Object.entries(t))s[r]=l(i,o);return s},v=async(e,o,t,s)=>{const r=Array.isArray(e.steps)?e.steps.slice(0,s):[],i={},p=[],c=new Set;for(const n of r){if(c.has(n.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${n.id}" — each step id must be unique (later steps reference an output by id via $from)`);c.add(n.id)}for(const n of r){const d=o[n.tool];if(!d)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${n.tool}" (available: ${Object.keys(o).join(", ")})`);const y=l(n.input??{},i),m={...t,idempotencyKey:`${t.idempotencyKey}:${n.id}`,toolCallId:`${t.toolCallId}:${n.id}`},u=await d.execute(y,m);i[n.id]=u,p.push({id:n.id,output:A(u)})}return{final:p.at(-1)?.output,results:p}},w=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,g=h({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),E=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);const s=o.maxSteps??$;return{description:o.description??w(e),execute:(r,i)=>v(r,e,i,s),inputSchema:g,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{E as codeTool,l as resolveReferences,v as runToolScript};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jsonSchema as u}from"ai";import{toFunctionReference as d}from"./AGENT_MODULE-BXx-tSCe.mjs";const y=240,h=50,m=(t,i)=>t.length<=i?t:`${t.slice(0,i)}…`,l=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(h,Math.max(1,Math.trunc(t)))},f=(t,i)=>{const r=t??{},s=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:s.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:m(typeof o.text=="string"?o.text:"",i),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},g=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),k=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),x=(t,i,r)=>{const s=d(i),e=Math.max(1,t.snippetChars??y),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,a)=>{const c=l(n.topK)??o,p=await a.run(s,{query:n.query,...c===void 0?{}:{topK:c}});return f(p,e)},inputSchema:g,isLunoraAgentTool:!0}},q=t=>{const i=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,s)=>s.run(i,{id:r.id}),inputSchema:k,isLunoraAgentTool:!0}},A=(t,i)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of i)e.knowledge&&r.push({key:e.name,...e.knowledge});const s={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,n=e.key==="default"?"readMemory":`read_${e.key}`,a=e.read!==void 0;s[o]=x(e,e.source,a?n:void 0),a&&(s[n]=q(e.read))}return s};export{A as collectAgenticMemoryTools,f as toSearchResults};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const t=e=>async n=>{await Promise.allSettled(e.map(async a=>a?.(n)))},r=e=>{const n=e.filter(a=>typeof a=="function");return a=>{let o=a.execute;for(const p of n.toReversed()){const l=o;o=()=>p({...a,execute:l})}return o()}},d=(...e)=>({executeLanguageModelCall:r(e.map(n=>n.executeLanguageModelCall)),executeTool:r(e.map(n=>n.executeTool)),onAbort:t(e.map(n=>n.onAbort)),onEmbedEnd:t(e.map(n=>n.onEmbedEnd)),onEmbedStart:t(e.map(n=>n.onEmbedStart)),onEnd:t(e.map(n=>n.onEnd)),onError:t(e.map(n=>n.onError)),onLanguageModelCallEnd:t(e.map(n=>n.onLanguageModelCallEnd)),onLanguageModelCallStart:t(e.map(n=>n.onLanguageModelCallStart)),onObjectStepEnd:t(e.map(n=>n.onObjectStepEnd)),onObjectStepStart:t(e.map(n=>n.onObjectStepStart)),onRerankEnd:t(e.map(n=>n.onRerankEnd)),onRerankStart:t(e.map(n=>n.onRerankStart)),onStart:t(e.map(n=>n.onStart)),onStepEnd:t(e.map(n=>n.onStepEnd)),onStepFinish:t(e.map(n=>n.onStepFinish)),onStepStart:t(e.map(n=>n.onStepStart)),onToolExecutionEnd:t(e.map(n=>n.onToolExecutionEnd)),onToolExecutionStart:t(e.map(n=>n.onToolExecutionStart))});export{d as combineTelemetry};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const t=(o,e)=>{if(!(o===null||typeof o!="object"))return o[e]},y=o=>{const e={};for(const r of["inputTokens","outputTokens","totalTokens"]){const s=t(o,r);typeof s=="number"&&(e[r]=s)}return Object.keys(e).length>0?e:void 0},m=o=>{const e=t(t(o,"providerMetadata"),"gateway"),r=t(t(o,"response"),"headers"),s=d=>{const g=t(r,"get"),f=typeof g=="function"?g.call(r,d):t(r,d);return typeof f=="string"&&f.length>0?f:void 0},n={},c=t(e,"cost");typeof c=="number"&&Number.isFinite(c)&&(n.cost=c);const i=t(e,"cached"),a=t(e,"cacheStatus"),l=typeof a=="string"?a:s("cf-aig-cache-status");typeof i=="boolean"?n.cached=i:typeof l=="string"&&(n.cached=l.toUpperCase()==="HIT");const u=t(e,"logId")??t(e,"log_id"),p=typeof u=="string"&&u.length>0?u:s("cf-aig-log-id");return typeof p=="string"&&p.length>0&&(n.logId=p),Object.keys(n).length>0?n:void 0},b=o=>{const e=t(o,"toolCall"),r=t(e,"toolName"),s=typeof r=="string"?r:void 0,n=t(o,"toolOutput"),c=t(n,"type"),i=t(o,"success"),a=typeof i=="boolean"?i:c!=="tool-error",l=t(o,"toolExecutionMs");return{error:a?void 0:t(n,"error")??t(o,"error"),name:s,output:a?t(n,"output"):void 0,success:a,toolExecutionMs:typeof l=="number"?l:void 0}},h=o=>{const e=t(t(o,"toolCall"),"toolName");return typeof e=="string"?e:void 0},v=o=>t(t(o,"toolCall"),"input"),T=o=>{if(!Array.isArray(o))return;let e="";for(const r of o)if(t(r,"type")==="text"){const s=t(r,"text");typeof s=="string"&&(e+=s)}return e.length>0?e:void 0},x=o=>o instanceof Error?{message:o.message,name:o.name}:o;export{b as a,h as b,T as c,x as d,m as e,t as r,y as s,v as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{defineWorkflow as m}from"@lunora/workflow";import{runAgentLoop as i}from"./runAgentLoop-DNAt-pGz.mjs";import{createStreamGenerate as p,createAgentGenerate as c,createEpisodeExtract as l,createGraphExtract as d,createCompact as f}from"./createAgentGenerate-BUVImo85.mjs";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as v}from"./AGENT_MODULE-BXx-tSCe.mjs";import{g as E}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{otlpTelemetry as N}from"./otlpTelemetry-DcW9mOLV.mjs";const T=(t,r,a)=>r===void 0?t:E({env:a,identity:{userId:r},label:"@lunora/agent"}),g=(t,r,a)=>{const e=r.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||t.telemetry?.isEnabled===!1)return t;const n=typeof r.LUNORA_OTLP_TOKEN=="string"?r.LUNORA_OTLP_TOKEN:void 0,o=[t.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...t,telemetry:{...t.telemetry,integrations:[...o,N({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},G=(t,r,a)=>m({handler:async e=>{const n=g(t,e.env,e.params.threadKey);return i({agent:n,compact:f(),env:e.env,exportName:r,extractGraph:d(),extractEpisode:l(),generate:c(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??v,run:T(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:t.name??u(r)});export{G as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as f,d as u,s as l,c as g,a as I,r as o,b as m}from"./common-Dck97z3Y.mjs";const b=(i,r,s)=>{const a=globalThis.console;i==="error"?a.error(r,s):i==="warn"?a.warn(r,s):a.info(r,s)},x=(i={})=>{const{functionId:r,logger:s=b,recordInputs:a=!1,recordOutputs:c=!1}=i,p=r===void 0?"":`[${r}] `,t=(e,n,d)=>{s(e,`${p}${n}`,d)};return{onAbort:e=>{t("warn","agent operation aborted",{callId:o(e,"callId"),reason:o(e,"reason")})},onEnd:e=>{t("info","agent operation completed",{callId:o(e,"callId"),finishReason:o(e,"finishReason"),operationId:o(e,"operationId"),usage:l(o(e,"usage"))})},onError:e=>{t("error","agent operation errored",{error:u(e)})},onLanguageModelCallEnd:e=>{const n={callId:o(e,"callId"),finishReason:o(e,"finishReason"),modelId:o(e,"modelId"),provider:o(e,"provider"),usage:l(o(e,"usage"))};c&&(n.text=g(o(e,"content"))),t("info","language model call ended",n)},onStart:e=>{t("info","agent operation started",{callId:o(e,"callId"),modelId:o(e,"modelId"),operationId:o(e,"operationId"),provider:o(e,"provider")})},onStepEnd:e=>{t("info","agent step ended",{finishReason:o(e,"finishReason"),stepNumber:o(e,"stepNumber"),usage:l(o(e,"usage"))})},onStepStart:e=>{t("info","agent step started",{stepNumber:o(e,"stepNumber")})},onToolExecutionEnd:e=>{const n=I(e),d={success:n.success,tool:n.name,toolExecutionMs:n.toolExecutionMs};n.success||(d.error=u(n.error)),c&&n.success&&(d.output=n.output),t(n.success?"info":"warn","tool execution ended",d)},onToolExecutionStart:e=>{const n={tool:m(e)};a&&(n.input=f(e)),t("info","tool execution started",n)}}};export{x as consoleTelemetry};
|