@lunora/agent 1.0.0-alpha.22 → 1.0.0-alpha.221

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.
Files changed (94) hide show
  1. package/dist/channels.d.mts +23 -12
  2. package/dist/channels.d.ts +23 -12
  3. package/dist/channels.mjs +1 -1
  4. package/dist/component.d.mts +41 -2
  5. package/dist/component.d.ts +41 -2
  6. package/dist/component.mjs +2 -2
  7. package/dist/inbound.d.mts +9 -7
  8. package/dist/inbound.d.ts +9 -7
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +112 -17
  11. package/dist/index.d.ts +112 -17
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.d.mts +3 -7
  14. package/dist/naming.d.ts +3 -7
  15. package/dist/naming.mjs +1 -1
  16. package/dist/packem_shared/AGENT_MODULE-B6FqQC80.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs +1 -0
  18. package/dist/packem_shared/VoiceSessionDO-D7O6Fclt.mjs +1 -0
  19. package/dist/packem_shared/adaptMcpResult-DFF_g58r.mjs +2 -0
  20. package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
  21. package/dist/packem_shared/agent-loop-DzzRTrgP.mjs +3 -0
  22. package/dist/packem_shared/agentAsTool-BJi-uU4s.mjs +1 -0
  23. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  24. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  25. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  26. package/dist/packem_shared/codeTool-dpJANTDc.mjs +1 -0
  27. package/dist/packem_shared/collectAgenticMemoryTools-D07XhGKr.mjs +1 -0
  28. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  29. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  30. package/dist/packem_shared/compileAgentWorkflow-KtkWJyHR.mjs +1 -0
  31. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  32. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  33. package/dist/packem_shared/createAgentContext-Wlc1ZgWa.mjs +1 -0
  34. package/dist/packem_shared/createAgentGenerate-D9DbEj9I.mjs +3 -0
  35. package/dist/packem_shared/defineAgent-DrI8Hw7B.mjs +3 -0
  36. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  37. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  38. package/dist/packem_shared/functionTool-Baqdn0OK.mjs +1 -0
  39. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  40. package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
  41. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  42. package/dist/packem_shared/otlpTelemetry-DC5n77sQ.mjs +1 -0
  43. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  44. package/dist/packem_shared/runAgentLoop-COwgPdOl.mjs +1 -0
  45. package/dist/packem_shared/runVoiceTurn-DdQVm4Kv.mjs +1 -0
  46. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  47. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  48. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  49. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  50. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-DqYbp4ye.d.mts} +300 -27
  51. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-DqYbp4ye.d.ts} +300 -27
  52. package/dist/packem_shared/voice-turn-CzFz5tWG.mjs +1 -0
  53. package/dist/packem_shared/webSearchTool-BobmV4cD.mjs +1 -0
  54. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  55. package/dist/reply.d.mts +40 -0
  56. package/dist/reply.d.ts +40 -0
  57. package/dist/reply.mjs +1 -0
  58. package/dist/sandbox.d.mts +157 -16
  59. package/dist/sandbox.d.ts +157 -16
  60. package/dist/sandbox.mjs +1 -1
  61. package/dist/skill-markdown.d.mts +36 -0
  62. package/dist/skill-markdown.d.ts +36 -0
  63. package/dist/skill-markdown.mjs +1 -0
  64. package/dist/telemetry/index.d.mts +165 -38
  65. package/dist/telemetry/index.d.ts +165 -38
  66. package/dist/telemetry/index.mjs +1 -1
  67. package/package.json +19 -9
  68. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  69. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  70. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  71. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  72. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  73. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  74. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  75. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  76. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  77. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  78. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  79. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  80. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  81. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  82. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  83. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  84. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  85. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  86. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  87. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  88. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  89. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  90. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  91. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  92. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  93. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  94. 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. Prompts / tool arguments
64
- * are logged only when `recordInputs` is set; generated text / tool results
65
- * only when `recordOutputs` is set. `onError` opens a span and logs the error.
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
@@ -122,6 +137,10 @@ interface ConsoleTelemetryOptions extends CommonOptions {
122
137
  * @experimental
123
138
  */
124
139
  declare const consoleTelemetry: (options?: ConsoleTelemetryOptions) => Telemetry;
140
+ /** A {@link Telemetry} that buffers and exports on `flush()`; the agent loop calls it once per run. */
141
+ type FlushableTelemetry = Telemetry & {
142
+ flush: () => void;
143
+ };
125
144
  /**
126
145
  * Options for {@link otlpTelemetry}.
127
146
  * @experimental
@@ -173,36 +192,76 @@ interface OtlpTelemetryOptions extends CommonOptions {
173
192
  * An OTLP-over-HTTP telemetry integration for `@lunora/agent`.
174
193
  *
175
194
  * The OTLP counterpart to the `sentryTelemetry` / `braintrustTelemetry` bridges:
176
- * it wraps each language-model call and tool execution in an OTLP **span**
195
+ * it records each language-model call and each tool execution as an OTLP **span**
177
196
  * (`gen_ai.*` semantic-convention attributes — model, provider, token usage,
178
197
  * tool name) and ships it to a collector, so agent generations land in the same
179
198
  * trace store as the rest of an app's telemetry (the Lunora Cloud, or any OTel
180
199
  * collector). Plug it into `defineAgent({ telemetry: { isEnabled: true,
181
200
  * integrations: [otlpTelemetry({ endpoint, token })] } })`.
182
201
  *
183
- * Emitting inside the turn's execution wrapper means one span per **real** turn:
184
- * the agent loop memoizes each `step.do('llm:turn:N')`, so a Workflow replay
185
- * returns the cached result without re-invoking `execute`, and no duplicate span
186
- * is emitted. Privacy-safe by default — `recordInputs`/`recordOutputs` both
187
- * default `false`, so no prompt or generated text leaves the worker without an
188
- * explicit opt-in; only structural metadata + token counts are recorded.
189
- *
190
- * Each export is fire-and-forget (registered with `waitUntil` when supplied);
191
- * every rejection is swallowed so a flaky collector never surfaces to the run.
192
- *
193
- * Two deliberate differences from the SDK-backed bridges, which delegate to a
194
- * host tracer. First, no `onError`: a failed call already emits a span with
195
- * `status.code === 2`, so the failure is on the trace and there is no host client
196
- * to also notify. Second, flat not nested: every span gets `traceId` (shared when
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.
202
+ * **A model-call span closes when the CALL ends, not when `execute()` resolves.**
203
+ * On a streamed turn `execute()` resolves the instant `doStream` hands back the
204
+ * stream — before a single token, before any usage, and before any mid-stream
205
+ * failure. Closing the span there reported every voice and workflow-streamed turn
206
+ * as a ~1 ms, zero-token, always-OK call. So the span opens in
207
+ * `executeLanguageModelCall` (which also owns the failure path, since a rejected
208
+ * provider call produces no end event) and closes on `onLanguageModelCallEnd`,
209
+ * which the SDK fires once the response is normalized — after the stream's
210
+ * `finish` part, where the duration and the token usage actually live.
211
+ * `onError` / `onAbort` close whatever is still open, so a stream that dies or is
212
+ * barged in on reports a failure instead of a phantom success.
213
+ *
214
+ * **Tool spans come from the agent loop.** Lunora exposes tools to the model
215
+ * schema-only, so `ai` never runs one and never fires its tool telemetry; the
216
+ * loop calls `executeTool` itself from the durable step where the tool really
217
+ * runs (see `telemetry/tool-execution.ts`).
218
+ *
219
+ * One span per REAL execution: the agent loop memoizes each `step.do(...)`, so a
220
+ * Workflow replay returns the cached result without re-invoking the wrapped work
221
+ * and no duplicate span is emitted. Privacy-safe by default —
222
+ * `recordInputs`/`recordOutputs` both default `false`, so no prompt or generated
223
+ * text leaves the worker without an explicit opt-in; only structural metadata +
224
+ * token counts are recorded.
225
+ *
226
+ * Spans are buffered and exported as ONE POST per batch (50 spans or 256 KB), and
227
+ * the agent loop calls `flush()` at run end. A caller driving this integration
228
+ * outside the loop must call `flush()` itself or the tail of the buffer is never
229
+ * sent. Each export is fire-and-forget (registered with `waitUntil` when
230
+ * supplied); every rejection is swallowed so a flaky collector never surfaces to
231
+ * the run.
232
+ *
233
+ * One deliberate difference from the SDK-backed bridges, which delegate to a host
234
+ * tracer: flat, not nested. Every span gets `traceId` (shared when `traceId` is
235
+ * set) but no `parentSpanId`, so model-call and tool spans are siblings under the
236
+ * run rather than a tree — OTLP has no ambient span context to parent to here.
200
237
  * @param options `endpoint` (+ optional `token`/`headers`/`serviceName`),
201
238
  * `traceId` to group a run's spans, `waitUntil`, and the `recordInputs`/
202
239
  * `recordOutputs` privacy flags.
203
240
  * @experimental
204
241
  */
205
- declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
242
+ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => FlushableTelemetry;
243
+ /** The span context both `startSpan` and `startSpanManual` are called with. */
244
+ interface SentrySpanContext {
245
+ attributes?: Record<string, unknown>;
246
+ name: string;
247
+ op?: string;
248
+ }
249
+ /**
250
+ * The subset of a Sentry `Span` this bridge drives. Structural, like
251
+ * {@link SentryLike} itself — a real `@sentry/*` span satisfies it.
252
+ * @experimental
253
+ */
254
+ interface SentrySpan {
255
+ /** Finish the span. Called once, from whichever terminal event closes the call. */
256
+ end: () => void;
257
+ /** Attach attributes discovered after the span started (token usage). */
258
+ setAttributes?: (attributes: Record<string, unknown>) => unknown;
259
+ /** `1` = OK, `2` = ERROR (Sentry's `SPAN_STATUS_OK` / `SPAN_STATUS_ERROR`). */
260
+ setStatus?: (status: {
261
+ code: 0 | 1 | 2;
262
+ message?: string;
263
+ }) => unknown;
264
+ }
206
265
  /**
207
266
  * The minimal, **structural** slice of `@sentry/cloudflare` (equivalently
208
267
  * `@sentry/node`/`@sentry/browser`) this bridge needs. `@sentry/cloudflare` is
@@ -214,16 +273,16 @@ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
214
273
  interface SentryLike {
215
274
  /** Capture a thrown value / exception. */
216
275
  captureException: (exception: unknown) => unknown;
217
- /** Run `callback` inside a new span and return its result. */
218
- startSpan: <T>(context: {
219
- attributes?: Record<string, unknown>;
220
- name: string;
221
- op?: string;
222
- }, callback: (span: {
223
- setStatus?: (status: {
224
- code: number;
225
- } | string) => void;
226
- }) => T) => T;
276
+ /** Run `callback` inside a new span, finished when the callback settles. */
277
+ startSpan: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
278
+ /**
279
+ * Run `callback` inside a new span that is **not** finished automatically —
280
+ * the caller owns its lifetime through `span.end()`. Present on every Sentry
281
+ * SDK built on `@sentry/core` (verified against `@sentry/core@10.55.0`); it is
282
+ * what lets a streamed model call be measured to the end of the stream while
283
+ * still nesting the provider's own work under it.
284
+ */
285
+ startSpanManual: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
227
286
  }
228
287
  /**
229
288
  * Options for {@link sentryTelemetry}.
@@ -241,14 +300,82 @@ interface SentryTelemetryOptions extends CommonOptions {
241
300
  /**
242
301
  * A dependency-injected Sentry bridge for the ai@7 telemetry surface.
243
302
  *
244
- * It wraps model calls and tool executions in Sentry spans (via
245
- * `Sentry.startSpan`) so nested provider/tool work is correctly parented, and
246
- * routes `onError` to `Sentry.captureException`. Span attributes carry only
247
- * structural metadata (model, provider, tool name) unless `recordInputs` is
248
- * set, in which case prompts / tool arguments are attached too.
303
+ * It wraps model calls and tool executions in Sentry spans so nested
304
+ * provider/tool work is correctly parented, and routes `onError` to
305
+ * `Sentry.captureException`. Span attributes carry only structural metadata
306
+ * (model, provider, tool name, token usage) unless `recordInputs` /
307
+ * `recordOutputs` are set, in which case prompts, tool arguments and generated
308
+ * text are attached too.
309
+ *
310
+ * The tool span is driven by the agent LOOP, not by `ai`: Lunora exposes tools
311
+ * schema-only so the SDK never executes one (see `telemetry/tool-execution.ts`).
312
+ *
313
+ * **A model-call span closes when the CALL ends, not when `execute()` resolves.**
314
+ * On a streamed turn `execute()` resolves the instant `doStream` hands back the
315
+ * stream — before a token, before any usage. The span still OPENS around
316
+ * `execute()`, because that is what makes it the active span nested provider work
317
+ * parents to, but it is opened with `startSpanManual` and so is not finished
318
+ * there: `onLanguageModelCallEnd` ends it, once the response is normalized and
319
+ * the real duration and token usage are both known. `onAbort` / `onError` end the
320
+ * call they name as a failure, so a stream that dies or is barged in on reports
321
+ * one instead of a phantom success.
249
322
  *
250
323
  * The app owns Sentry initialization; pass the namespace in as `Sentry`.
251
324
  * @experimental
252
325
  */
253
326
  declare const sentryTelemetry: (options: SentryTelemetryOptions) => Telemetry;
254
- 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 };
327
+ export {
328
+ /**
329
+ * `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
330
+ *
331
+ * Every export here produces an ai@7 `Telemetry` object suitable for the
332
+ * `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
333
+ * isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
334
+ * zero-dependency structured console tracer; `combineTelemetry` fans the
335
+ * lifecycle out to several integrations and nests their execution wrappers;
336
+ * `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
337
+ * app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
338
+ * never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
339
+ * OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
340
+ * generations land in the same trace store as the rest of the app.
341
+ *
342
+ * All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
343
+ * both default `false`), so nothing sensitive is recorded without opt-in.
344
+ */
345
+ type BraintrustLike,
346
+ /**
347
+ * `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
348
+ *
349
+ * Every export here produces an ai@7 `Telemetry` object suitable for the
350
+ * `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
351
+ * isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
352
+ * zero-dependency structured console tracer; `combineTelemetry` fans the
353
+ * lifecycle out to several integrations and nests their execution wrappers;
354
+ * `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
355
+ * app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
356
+ * never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
357
+ * OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
358
+ * generations land in the same trace store as the rest of the app.
359
+ *
360
+ * All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
361
+ * both default `false`), so nothing sensitive is recorded without opt-in.
362
+ */
363
+ type BraintrustSpan,
364
+ /**
365
+ * `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
366
+ *
367
+ * Every export here produces an ai@7 `Telemetry` object suitable for the
368
+ * `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
369
+ * isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
370
+ * zero-dependency structured console tracer; `combineTelemetry` fans the
371
+ * lifecycle out to several integrations and nests their execution wrappers;
372
+ * `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
373
+ * app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
374
+ * never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
375
+ * OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
376
+ * generations land in the same trace store as the rest of the app.
377
+ *
378
+ * All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
379
+ * both default `false`), so nothing sensitive is recorded without opt-in.
380
+ */
381
+ 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. Prompts / tool arguments
64
- * are logged only when `recordInputs` is set; generated text / tool results
65
- * only when `recordOutputs` is set. `onError` opens a span and logs the error.
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
@@ -122,6 +137,10 @@ interface ConsoleTelemetryOptions extends CommonOptions {
122
137
  * @experimental
123
138
  */
124
139
  declare const consoleTelemetry: (options?: ConsoleTelemetryOptions) => Telemetry;
140
+ /** A {@link Telemetry} that buffers and exports on `flush()`; the agent loop calls it once per run. */
141
+ type FlushableTelemetry = Telemetry & {
142
+ flush: () => void;
143
+ };
125
144
  /**
126
145
  * Options for {@link otlpTelemetry}.
127
146
  * @experimental
@@ -173,36 +192,76 @@ interface OtlpTelemetryOptions extends CommonOptions {
173
192
  * An OTLP-over-HTTP telemetry integration for `@lunora/agent`.
174
193
  *
175
194
  * The OTLP counterpart to the `sentryTelemetry` / `braintrustTelemetry` bridges:
176
- * it wraps each language-model call and tool execution in an OTLP **span**
195
+ * it records each language-model call and each tool execution as an OTLP **span**
177
196
  * (`gen_ai.*` semantic-convention attributes — model, provider, token usage,
178
197
  * tool name) and ships it to a collector, so agent generations land in the same
179
198
  * trace store as the rest of an app's telemetry (the Lunora Cloud, or any OTel
180
199
  * collector). Plug it into `defineAgent({ telemetry: { isEnabled: true,
181
200
  * integrations: [otlpTelemetry({ endpoint, token })] } })`.
182
201
  *
183
- * Emitting inside the turn's execution wrapper means one span per **real** turn:
184
- * the agent loop memoizes each `step.do('llm:turn:N')`, so a Workflow replay
185
- * returns the cached result without re-invoking `execute`, and no duplicate span
186
- * is emitted. Privacy-safe by default — `recordInputs`/`recordOutputs` both
187
- * default `false`, so no prompt or generated text leaves the worker without an
188
- * explicit opt-in; only structural metadata + token counts are recorded.
189
- *
190
- * Each export is fire-and-forget (registered with `waitUntil` when supplied);
191
- * every rejection is swallowed so a flaky collector never surfaces to the run.
192
- *
193
- * Two deliberate differences from the SDK-backed bridges, which delegate to a
194
- * host tracer. First, no `onError`: a failed call already emits a span with
195
- * `status.code === 2`, so the failure is on the trace and there is no host client
196
- * to also notify. Second, flat not nested: every span gets `traceId` (shared when
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.
202
+ * **A model-call span closes when the CALL ends, not when `execute()` resolves.**
203
+ * On a streamed turn `execute()` resolves the instant `doStream` hands back the
204
+ * stream — before a single token, before any usage, and before any mid-stream
205
+ * failure. Closing the span there reported every voice and workflow-streamed turn
206
+ * as a ~1 ms, zero-token, always-OK call. So the span opens in
207
+ * `executeLanguageModelCall` (which also owns the failure path, since a rejected
208
+ * provider call produces no end event) and closes on `onLanguageModelCallEnd`,
209
+ * which the SDK fires once the response is normalized — after the stream's
210
+ * `finish` part, where the duration and the token usage actually live.
211
+ * `onError` / `onAbort` close whatever is still open, so a stream that dies or is
212
+ * barged in on reports a failure instead of a phantom success.
213
+ *
214
+ * **Tool spans come from the agent loop.** Lunora exposes tools to the model
215
+ * schema-only, so `ai` never runs one and never fires its tool telemetry; the
216
+ * loop calls `executeTool` itself from the durable step where the tool really
217
+ * runs (see `telemetry/tool-execution.ts`).
218
+ *
219
+ * One span per REAL execution: the agent loop memoizes each `step.do(...)`, so a
220
+ * Workflow replay returns the cached result without re-invoking the wrapped work
221
+ * and no duplicate span is emitted. Privacy-safe by default —
222
+ * `recordInputs`/`recordOutputs` both default `false`, so no prompt or generated
223
+ * text leaves the worker without an explicit opt-in; only structural metadata +
224
+ * token counts are recorded.
225
+ *
226
+ * Spans are buffered and exported as ONE POST per batch (50 spans or 256 KB), and
227
+ * the agent loop calls `flush()` at run end. A caller driving this integration
228
+ * outside the loop must call `flush()` itself or the tail of the buffer is never
229
+ * sent. Each export is fire-and-forget (registered with `waitUntil` when
230
+ * supplied); every rejection is swallowed so a flaky collector never surfaces to
231
+ * the run.
232
+ *
233
+ * One deliberate difference from the SDK-backed bridges, which delegate to a host
234
+ * tracer: flat, not nested. Every span gets `traceId` (shared when `traceId` is
235
+ * set) but no `parentSpanId`, so model-call and tool spans are siblings under the
236
+ * run rather than a tree — OTLP has no ambient span context to parent to here.
200
237
  * @param options `endpoint` (+ optional `token`/`headers`/`serviceName`),
201
238
  * `traceId` to group a run's spans, `waitUntil`, and the `recordInputs`/
202
239
  * `recordOutputs` privacy flags.
203
240
  * @experimental
204
241
  */
205
- declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
242
+ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => FlushableTelemetry;
243
+ /** The span context both `startSpan` and `startSpanManual` are called with. */
244
+ interface SentrySpanContext {
245
+ attributes?: Record<string, unknown>;
246
+ name: string;
247
+ op?: string;
248
+ }
249
+ /**
250
+ * The subset of a Sentry `Span` this bridge drives. Structural, like
251
+ * {@link SentryLike} itself — a real `@sentry/*` span satisfies it.
252
+ * @experimental
253
+ */
254
+ interface SentrySpan {
255
+ /** Finish the span. Called once, from whichever terminal event closes the call. */
256
+ end: () => void;
257
+ /** Attach attributes discovered after the span started (token usage). */
258
+ setAttributes?: (attributes: Record<string, unknown>) => unknown;
259
+ /** `1` = OK, `2` = ERROR (Sentry's `SPAN_STATUS_OK` / `SPAN_STATUS_ERROR`). */
260
+ setStatus?: (status: {
261
+ code: 0 | 1 | 2;
262
+ message?: string;
263
+ }) => unknown;
264
+ }
206
265
  /**
207
266
  * The minimal, **structural** slice of `@sentry/cloudflare` (equivalently
208
267
  * `@sentry/node`/`@sentry/browser`) this bridge needs. `@sentry/cloudflare` is
@@ -214,16 +273,16 @@ declare const otlpTelemetry: (options: OtlpTelemetryOptions) => Telemetry;
214
273
  interface SentryLike {
215
274
  /** Capture a thrown value / exception. */
216
275
  captureException: (exception: unknown) => unknown;
217
- /** Run `callback` inside a new span and return its result. */
218
- startSpan: <T>(context: {
219
- attributes?: Record<string, unknown>;
220
- name: string;
221
- op?: string;
222
- }, callback: (span: {
223
- setStatus?: (status: {
224
- code: number;
225
- } | string) => void;
226
- }) => T) => T;
276
+ /** Run `callback` inside a new span, finished when the callback settles. */
277
+ startSpan: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
278
+ /**
279
+ * Run `callback` inside a new span that is **not** finished automatically —
280
+ * the caller owns its lifetime through `span.end()`. Present on every Sentry
281
+ * SDK built on `@sentry/core` (verified against `@sentry/core@10.55.0`); it is
282
+ * what lets a streamed model call be measured to the end of the stream while
283
+ * still nesting the provider's own work under it.
284
+ */
285
+ startSpanManual: <T>(context: SentrySpanContext, callback: (span: SentrySpan) => T) => T;
227
286
  }
228
287
  /**
229
288
  * Options for {@link sentryTelemetry}.
@@ -241,14 +300,82 @@ interface SentryTelemetryOptions extends CommonOptions {
241
300
  /**
242
301
  * A dependency-injected Sentry bridge for the ai@7 telemetry surface.
243
302
  *
244
- * It wraps model calls and tool executions in Sentry spans (via
245
- * `Sentry.startSpan`) so nested provider/tool work is correctly parented, and
246
- * routes `onError` to `Sentry.captureException`. Span attributes carry only
247
- * structural metadata (model, provider, tool name) unless `recordInputs` is
248
- * set, in which case prompts / tool arguments are attached too.
303
+ * It wraps model calls and tool executions in Sentry spans so nested
304
+ * provider/tool work is correctly parented, and routes `onError` to
305
+ * `Sentry.captureException`. Span attributes carry only structural metadata
306
+ * (model, provider, tool name, token usage) unless `recordInputs` /
307
+ * `recordOutputs` are set, in which case prompts, tool arguments and generated
308
+ * text are attached too.
309
+ *
310
+ * The tool span is driven by the agent LOOP, not by `ai`: Lunora exposes tools
311
+ * schema-only so the SDK never executes one (see `telemetry/tool-execution.ts`).
312
+ *
313
+ * **A model-call span closes when the CALL ends, not when `execute()` resolves.**
314
+ * On a streamed turn `execute()` resolves the instant `doStream` hands back the
315
+ * stream — before a token, before any usage. The span still OPENS around
316
+ * `execute()`, because that is what makes it the active span nested provider work
317
+ * parents to, but it is opened with `startSpanManual` and so is not finished
318
+ * there: `onLanguageModelCallEnd` ends it, once the response is normalized and
319
+ * the real duration and token usage are both known. `onAbort` / `onError` end the
320
+ * call they name as a failure, so a stream that dies or is barged in on reports
321
+ * one instead of a phantom success.
249
322
  *
250
323
  * The app owns Sentry initialization; pass the namespace in as `Sentry`.
251
324
  * @experimental
252
325
  */
253
326
  declare const sentryTelemetry: (options: SentryTelemetryOptions) => Telemetry;
254
- 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 };
327
+ export {
328
+ /**
329
+ * `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
330
+ *
331
+ * Every export here produces an ai@7 `Telemetry` object suitable for the
332
+ * `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
333
+ * isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
334
+ * zero-dependency structured console tracer; `combineTelemetry` fans the
335
+ * lifecycle out to several integrations and nests their execution wrappers;
336
+ * `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
337
+ * app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
338
+ * never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
339
+ * OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
340
+ * generations land in the same trace store as the rest of the app.
341
+ *
342
+ * All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
343
+ * both default `false`), so nothing sensitive is recorded without opt-in.
344
+ */
345
+ type BraintrustLike,
346
+ /**
347
+ * `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
348
+ *
349
+ * Every export here produces an ai@7 `Telemetry` object suitable for the
350
+ * `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
351
+ * isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
352
+ * zero-dependency structured console tracer; `combineTelemetry` fans the
353
+ * lifecycle out to several integrations and nests their execution wrappers;
354
+ * `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
355
+ * app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
356
+ * never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
357
+ * OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
358
+ * generations land in the same trace store as the rest of the app.
359
+ *
360
+ * All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
361
+ * both default `false`), so nothing sensitive is recorded without opt-in.
362
+ */
363
+ type BraintrustSpan,
364
+ /**
365
+ * `@lunora/agent/telemetry` — observability integrations for `@lunora/agent`.
366
+ *
367
+ * Every export here produces an ai@7 `Telemetry` object suitable for the
368
+ * `integrations` array of `TelemetryOptions` (`defineAgent({ telemetry: {
369
+ * isEnabled: true, integrations: [...] } })`). `consoleTelemetry` is a
370
+ * zero-dependency structured console tracer; `combineTelemetry` fans the
371
+ * lifecycle out to several integrations and nests their execution wrappers;
372
+ * `sentryTelemetry` / `braintrustTelemetry` are dependency-injected bridges (the
373
+ * app passes its own Sentry namespace / Braintrust logger, so the heavy SDKs are
374
+ * never imported here); and `otlpTelemetry` ships `gen_ai.*` spans over
375
+ * OTLP-over-HTTP to any collector (the Lunora Cloud, or your own), so agent
376
+ * generations land in the same trace store as the rest of the app.
377
+ *
378
+ * All integrations are privacy-safe by default (`recordInputs` / `recordOutputs`
379
+ * both default `false`), so nothing sensitive is recorded without opt-in.
380
+ */
381
+ type BraintrustTelemetryOptions, type CommonOptions, type ConsoleLogLevel, type ConsoleLogger, type ConsoleTelemetryOptions, type OtlpTelemetryOptions, type SentryLike, type SentrySpan, type SentryTelemetryOptions, braintrustTelemetry, combineTelemetry, consoleTelemetry, otlpTelemetry, sentryTelemetry };
@@ -1 +1 @@
1
- import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-CnOI5WAw.mjs";import{combineTelemetry as m}from"../packem_shared/combineTelemetry-oLCV_EPV.mjs";import{consoleTelemetry as p}from"../packem_shared/consoleTelemetry-CaoI-NGg.mjs";import{otlpTelemetry as f}from"../packem_shared/otlpTelemetry-DcW9mOLV.mjs";import{sentryTelemetry as T}from"../packem_shared/sentryTelemetry-Dr2aPuvl.mjs";export{o as braintrustTelemetry,m as combineTelemetry,p as consoleTelemetry,f as otlpTelemetry,T as sentryTelemetry};
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-DC5n77sQ.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.22",
3
+ "version": "1.0.0-alpha.221",
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
- "@lunora/ai": "1.0.0-alpha.35",
80
- "@lunora/errors": "1.0.0-alpha.8",
81
- "@lunora/mail": "1.0.0-alpha.28",
82
- "@lunora/server": "1.0.0-alpha.43",
83
- "@lunora/values": "1.0.0-alpha.11",
84
- "@lunora/workflow": "1.0.0-alpha.13",
85
- "@modelcontextprotocol/sdk": "^1.29.0",
86
- "ai": "7.0.37"
87
+ "@ai-sdk/provider-utils": "5.0.53",
88
+ "@lunora/ai": "1.0.0-alpha.133",
89
+ "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
90
+ "@lunora/mail": "1.0.0-alpha.111",
91
+ "@lunora/server": "1.0.0-alpha.213",
92
+ "@lunora/values": "1.0.0-alpha.69",
93
+ "@lunora/workflow": "1.0.0-alpha.81",
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};