@lunora/agent 1.0.0-alpha.14 → 1.0.0-alpha.140
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 +3 -11
- package/dist/channels.d.ts +3 -11
- package/dist/channels.mjs +1 -1
- package/dist/component.d.mts +2 -0
- package/dist/component.d.ts +2 -0
- package/dist/component.mjs +2 -2
- package/dist/inbound.d.mts +7 -5
- package/dist/inbound.d.ts +7 -5
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +50 -9
- package/dist/index.d.ts +50 -9
- package/dist/index.mjs +1 -1
- package/dist/naming.mjs +1 -1
- package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-BkPBpwRR.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
- package/dist/packem_shared/agent-loop-CR27O7MC.mjs +3 -0
- package/dist/packem_shared/agentAsTool-CgZb6ycK.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-BQb-K3my.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.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-D3BN5OWk.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-BVy7RzqD.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
- package/dist/packem_shared/defineAgent-uEeT0WuM.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-D3CP4f8-.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
- package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-Dg1GXqsX.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-Bs47Kfx2.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-CKX-iNXC.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-B_VV-x4x.d.mts} +282 -23
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-B_VV-x4x.d.ts} +282 -23
- package/dist/packem_shared/voice-turn-7a1NoDHS.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 +62 -16
- package/dist/sandbox.d.ts +62 -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 +18 -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 };
|
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-ByqrB-72.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.140",
|
|
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,15 @@
|
|
|
76
84
|
"access": "public"
|
|
77
85
|
},
|
|
78
86
|
"dependencies": {
|
|
79
|
-
"@lunora/ai": "1.0.0-alpha.
|
|
80
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
81
|
-
"@lunora/mail": "1.0.0-alpha.
|
|
82
|
-
"@lunora/server": "1.0.0-alpha.
|
|
83
|
-
"@lunora/values": "1.0.0-alpha.
|
|
84
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
85
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
86
|
-
"ai": "7.0.
|
|
87
|
+
"@lunora/ai": "1.0.0-alpha.96",
|
|
88
|
+
"@lunora/errors": "1.0.0-alpha.41",
|
|
89
|
+
"@lunora/mail": "1.0.0-alpha.86",
|
|
90
|
+
"@lunora/server": "1.0.0-alpha.148",
|
|
91
|
+
"@lunora/values": "1.0.0-alpha.52",
|
|
92
|
+
"@lunora/workflow": "1.0.0-alpha.63",
|
|
93
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
94
|
+
"ai": "7.0.93",
|
|
95
|
+
"yaml": "^2.9.0"
|
|
87
96
|
},
|
|
88
97
|
"engines": {
|
|
89
98
|
"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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{g as d}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{LunoraError as f}from"@lunora/errors";import{toFunctionReference as g,DEFAULT_AGENT_FUNCTION_PATHS as l}from"./AGENT_MODULE-BXx-tSCe.mjs";const y=(r,i,c)=>{const o={},s=g(l.patchThread),u=()=>c??d({env:r,label:"@lunora/agent"});for(const n of i){const e=()=>{const t=r[n.binding];if(!t||typeof t.create!="function"||typeof t.get!="function")throw new f("INTERNAL",`@lunora/agent: no Workflow binding "${n.binding}" on env for agent "${n.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};o[n.exportName]={cancel:async t=>{await(await e().get(t)).terminate();try{await u()(s,{instanceId:t,status:"cancelled"})}catch{}},publicRun:n.publicRun===!0,run:async(t,a)=>({id:(await e().create({...a?.id===void 0?{}:{id:a.id},params:t})).id}),sendEvent:async(t,a)=>{await(await e().get(t)).sendEvent(a)},status:async t=>(await e().get(t)).status()}}return o};export{y as default};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{createAi as T}from"@lunora/ai";import{LunoraError as w}from"@lunora/errors";import{jsonSchema as x,generateText as d,streamText as k,Output as g,tool as j}from"ai";const y=t=>{if(!t)return;const e={};return t.inputTokens!==void 0&&(e.inputTokens=t.inputTokens),t.outputTokens!==void 0&&(e.outputTokens=t.outputTokens),t.totalTokens!==void 0&&(e.totalTokens=t.totalTokens),Object.keys(e).length>0?e:void 0},f=t=>t.map(e=>({id:e.toolCallId,input:e.input,name:e.toolName})),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new w("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return T({binding:o,env:e}).model(t)}return t},v=(t,e)=>{const o=m(t.model,e),n={};for(const[i,a]of Object.entries(t.tools??{}))n[i]=j({description:a.description,inputSchema:a.inputSchema});const s=t.output===void 0?void 0:g.object({schema:t.output}),r={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:s,staticSettings:r,tools:n}},b=(t,{activeTools:e,messages:o,model:n,signal:s,toolChoice:r})=>{const{defaultModel:i,output:a,staticSettings:h,tools:l}=t,c=e===void 0?l:Object.fromEntries(Object.entries(l).filter(([p])=>e.includes(p)));return{messages:o,model:n??i,...h,...Object.keys(c).length>0?{tools:c}:{},...r===void 0?{}:{toolChoice:r},...a===void 0?{}:{output:a},...s===void 0?{}:{abortSignal:s}}},N=(t,e)=>{const o=v(t,e);return async n=>{const s=await d(b(o,n)),r=y(s.usage);return{text:s.text,toolCalls:f(s.toolCalls),...r===void 0?{}:{usage:r},...o.output===void 0?{}:{output:s.output}}}},q=(t,e)=>{const o=v(t,e);return async(n,s)=>{const r=k(b(o,n));let i="";try{for await(const u of r.textStream)i+=u,s(u)}catch(u){if(n.signal?.aborted)return{text:i,toolCalls:[]};throw u}const[a,h,l,c]=await Promise.all([r.text,r.toolCalls,r.usage,o.output===void 0?Promise.resolve(void 0):r.output]),p=y(l);return{text:a,toolCalls:f(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:c}}}},C=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),O=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
2
|
-
`),$=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{output:s}=await d({model:m(o,e),output:g.object({schema:C}),prompt:O(n,t)});return s},A=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
3
|
-
`),G=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{text:s}=await d({model:m(o,e),prompt:A(n,t)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",M=()=>async({env:t,messages:e,model:o})=>{const{text:n}=await d({messages:e,model:m(o,t),system:S});return n.trim()};export{N as createAgentGenerate,M as createCompact,G as createEpisodeExtract,$ as createGraphExtract,q as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const p="/_lunora/scheduler/dispatch",y=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},N=(t,e,r)=>{try{const n=JSON.parse(r)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:s,data:c,message:i}=n;return new a(s,typeof i=="string"?i:void 0,{data:c,status:e})}}catch{}return new a("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${r}`,{status:e})},w=t=>{const{label:e}=t,r=globalThis.fetch,n=t.fetchImpl??(typeof r=="function"?r.bind(globalThis):void 0);return async(s,c,i={})=>{if(typeof n!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const u=t.env.LUNORA_ORIGIN_URL;if(typeof u!="string"||u.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const h=t.env.LUNORA_ADMIN_TOKEN;if(typeof h!="string"||h.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const d=`${y(u)}${p}`,l={authorization:`Bearer ${h}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(l["x-lunora-userid"]=t.identity.userId),t.identity?.claims!==void 0&&(l["x-lunora-identity"]=JSON.stringify(t.identity.claims));const o=await n(d,{body:JSON.stringify({args:c??{},functionPath:s.__lunoraRef,shardKey:i.shardKey}),headers:l,method:"POST"});if(!o.ok)throw N(e,o.status,await o.text());const f=await o.text();if(f.length!==0)try{return JSON.parse(f)}catch{throw new a("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(o.status)}): ${f}`,{status:o.status})}}};export{w as g};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as d}from"./agentAsTool-CJCTyAQG.mjs";import{r as m}from"./memory-DNRyyp1b.mjs";import{SKILL_NAME_PATTERN as h,RESERVED_SKILL_NAME as c}from"./defineSkill-DfJxCwfZ.mjs";const w=/^[a-zA-Z][\w-]*$/u,p=(e,r)=>{const o={...e.tools};for(const n of r)for(const[t,a]of Object.entries(n.tools??{})){if(Object.hasOwn(o,t))throw new s("INTERNAL",`@lunora/agent: skill "${n.name}" tool "${t}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[t]=a}return o},y=(e,r)=>{const o=[];for(const n of[e.instructions,...r.map(t=>t.instructions)])n&&o.push(n);return o.length<=1?o[0]:n=>o.map(t=>typeof t=="function"?t(n):t).filter(t=>t.length>0).join(`
|
|
2
|
-
|
|
3
|
-
`)},N=(e,r)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const n of r)n.knowledge&&m(n.knowledge)&&o.push({key:n.name,...n.knowledge});return o},T=e=>{const r=new Set;for(const o of e){if(typeof o.name!="string"||!h.test(o.name))throw new s("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new s("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(r.has(o.name))throw new s("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);r.add(o.name)}},A=(e,r)=>{if(e===void 0)return;const o=Object.keys(r).filter(n=>!e.includes(n));if(o.length>0)throw new s("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(n=>`"${n}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},k=(e,r)=>{const o=(n,t)=>{if(n&&n.kind!=="graph"&&n.kind!=="episodic"&&n.source===void 0)throw new s("INTERNAL",`@lunora/agent: ${t} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const n of r)o(n.knowledge,`skill "${n.name}" \`knowledge\``)},$=e=>{const r=e.model;if(r==null||typeof r=="string"&&r.length===0)throw new s("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&(!Number.isInteger(e.maxTurns)||e.maxTurns<1))throw new s("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");const o=e.skills??[];T(o),k(e,o);const n=p(e,o),t=f(e,o);for(const[i,g]of Object.entries(t)){if(Object.hasOwn(n,i))throw new s("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);n[i]=g}const a=Object.keys(t).length>0;A(e.activeTools,t);for(const i of Object.keys(n))if(!w.test(i))throw new s("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=N(e,o),u=y(e,o);return{...e,asTool:d,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:u}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:n}:{}}},b=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,j=e=>{if(typeof e.execute!="function")throw new s("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,j as defineAgentTool,b as isAgentDefinition};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as t}from"@lunora/errors";const r=/^[a-zA-Z][\w-]*$/u,i="default",a=e=>{if(typeof e.name!="string"||!r.test(e.name))throw new t("INTERNAL",`@lunora/agent: defineSkill requires a \`name\` that is a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(e.name)}`);if(e.name===i)throw new t("INTERNAL",`@lunora/agent: skill name "${i}" is reserved (it keys the agent's own \`memory\` source / the historic \`memory:retrieve\` step) — choose another name`);return{...e,isLunoraSkill:!0}},o=e=>typeof e=="object"&&e!==null&&e.isLunoraSkill===!0;export{i as RESERVED_SKILL_NAME,r as SKILL_NAME_PATTERN,a as defineSkill,o as isSkillDefinition};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as e}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-BXx-tSCe.mjs";const s=(n,o)=>{if(typeof o.description!="string"||o.description.length===0)throw new e("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(o.inputSchema===void 0)throw new e("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(n);return{description:o.description,execute:(r,i)=>i.run(t,r),inputSchema:o.inputSchema,isLunoraAgentTool:!0}};export{s as functionTool};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{defineTable as f,initLunora as v}from"@lunora/server";import{v as e}from"@lunora/values";const A="agent",x=t=>({...t,visibility:"internal"}),S=t=>{const n={};for(const[a,r]of Object.entries(t))r!==void 0&&(n[a]=r);return n},O="entities",K="edges",N=`${A}_${O}`,g=`${A}_${K}`,E={[O]:f({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[K]:f({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},q=64,C=2,$=4,I=8,j=32,L=500,M=/\s+/gu,T=/[^\p{L}\p{N}]+/u,b=t=>t.trim().replaceAll(M," ").toLowerCase(),_=t=>t.toLowerCase().split(T).filter(n=>n.length>=2),D=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,n)=>n.weight-t.weight||t.label.localeCompare(n.label)||t.srcName.localeCompare(n.srcName)||t.dstName.localeCompare(n.dstName),k=(t,n)=>n.some(a=>t.includes(a)||a.includes(t)),G=t=>t.map(n=>`- ${n.srcName} —[${n.label}]→ ${n.dstName}`).toSorted((n,a)=>n.localeCompare(a)).join(`
|
|
2
|
-
`),P=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,z=(t,n,a,r)=>{const s=P(t);r.collectedKeys.has(s)||(r.collectedKeys.add(s),r.collected.push(t));const l=t.srcName===n?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<a.maxNodes&&(r.seen.add(l),r.next.push(l))},B=async(t,n,a)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(n)};let s=n.slice(0,a.maxNodes);for(let l=0;l<a.depth&&s.length>0;l+=1){r.next=[];for(const u of s){const o=(await t(u)).toSorted(U).slice(0,a.fanOut);for(const m of o)z(m,u,a,r)}s=r.next}return r.collected},{mutation:F,query:H}=v.dataModel().create(),J=()=>{const t=F.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:a,ctx:r})=>{const s=Date.now(),l=async(c,i)=>{const d=b(c);if(d.length===0)return;const w=await r.db.query(N).withIndex("byOwnerName",p=>p.eq("owner",a.owner).eq("name",d)).first();return w?(i!==void 0&&w.type===void 0&&await r.db.patch(w._id,{type:i,updatedAt:s}),d):(await r.db.insert(N,{createdAt:s,name:d,owner:a.owner,updatedAt:s,weight:1,...S({firstMessageKey:a.messageKey,type:i})}),d)},u=async c=>{const i=b(c.src),d=b(c.dst),w=b(c.label);if(i.length===0||d.length===0||w.length===0||i===d)return!1;await l(i),await l(d);const p=c.confidence??1,y=await r.db.query(g).withIndex("byTriple",h=>h.eq("owner",a.owner).eq("srcName",i).eq("label",w).eq("dstName",d)).first();if(y){const h=y.weight??1;await r.db.patch(y._id,{updatedAt:s,weight:Math.max(h,p)})}else await r.db.insert(g,{createdAt:s,dstName:d,label:w,messageKey:a.messageKey,owner:a.owner,srcName:i,updatedAt:s,weight:p});return!0};let o=0;for(const c of a.entities.slice(0,q))await l(c.name,c.type)!==void 0&&(o+=1);let m=0;for(const c of a.relations.slice(0,q))await u(c)&&(m+=1);return{entities:o,relations:m}}),n=H.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:a,ctx:r})=>{const s=_(a.query);if(s.length===0)return{context:""};const l=(await r.db.query(N).withIndex("byOwnerUpdatedAt",o=>o.eq("owner",a.owner)).order("desc").take(L)).filter(o=>k(o.name,s)).toSorted((o,m)=>(m.weight??1)-(o.weight??1)||o.name.localeCompare(m.name)).slice(0,a.maxSeeds??$).map(o=>o.name);if(l.length===0)return{context:""};const u=await B(async o=>{const[m,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",i=>i.eq("owner",a.owner).eq("srcName",o)).collect(),r.db.query(g).withIndex("byOwnerDst",i=>i.eq("owner",a.owner).eq("dstName",o)).collect()]);return[...m,...c].map(i=>D(i))},l,{depth:a.depth??C,fanOut:a.fanOut??I,maxNodes:a.maxNodes??j});return{context:G(u)}});return{agentGraphTraverse:x(n),agentGraphUpsert:x(t)}};export{x as i,J as j,A as o,b as p,E as q,S as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const o=i=>i.kind==="graph"||i.kind==="episodic"||i.mode!=="agentic",m=i=>i.memorySources?i.memorySources:i.memory&&o(i.memory)?[{key:"default",...i.memory}]:[],r=i=>m(i).find(d=>d.kind==="graph"),n=i=>m(i).find(d=>d.kind==="episodic"),e=(i,d)=>d==="default"?i:`${i}:${d}`;export{e as c,r as i,m as n,o as r,n as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/server";import"@lunora/values";import{j as m,q as t,p as e}from"./graph-component-B2YmC2eL.mjs";export{m as graphComponent,t as graphTables,e as normalizeEntityName};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as U,r as d,e as V,c as j,t as A,b as z}from"./common-Dck97z3Y.mjs";const I=e=>`${String(Math.round(e))}000000`,w=e=>{const t=new Uint8Array(e);crypto.getRandomValues(t);let o="";for(const n of t)o+=n.toString(16).padStart(2,"0");return o},x=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},C=(e,t,o)=>{const n={},c=new Map,m=(u,g)=>{const h=u.toLowerCase(),b=c.get(h);b===void 0?(c.set(h,u),n[u]=g):n[b]=g};for(const[u,g]of Object.entries(e))m(u,g);for(const[u,g]of Object.entries(t??{}))m(u,g);return o!==void 0&&o.length>0&&m("authorization",`Bearer ${o}`),n},D=e=>Array.isArray(e)?e:[e],M=(e,t)=>{const o={"service.name":e};for(const[n,c]of Object.entries({}))o[n]=c;return Object.entries(o).map(([n,c])=>x(n,c))},F=(e,t,o,n)=>({resourceSpans:[{resource:{attributes:M(o)},scopeSpans:[{scope:{name:t},spans:D(e)}]}]}),a=(e,t,o)=>{if(o!=null){if(typeof o=="boolean"||typeof o=="number"||typeof o=="string"){e.push(x(t,o));return}e.push(x(t,JSON.stringify(o)))}},T=(e,t)=>{(async()=>{let o;try{o=await e}catch(n){t(!1,n instanceof Error?n.message:String(n),void 0);return}t(!0,void 0,o)})().catch(()=>{})},L=e=>{const{conversationId:t,endpoint:o,headers:n,recordInputs:c=!1,recordOutputs:m=!1,token:u,traceId:g,waitUntil:h}=e,b=e.serviceName??"lunora";let v=o;for(;v.endsWith("/");)v=v.slice(0,-1);const N=`${v}/v1/traces`,$=C({"content-type":"application/json"},n,u),O=(r,f,l,p,y)=>{const _={attributes:y,endTimeUnixNano:I(Date.now()),kind:1,name:r,spanId:w(8),startTimeUnixNano:I(f),status:l?{code:1}:{code:2,message:p??""},traceId:g??w(16)};try{const i=fetch(N,{body:JSON.stringify(F(_,"@lunora/agent",b)),headers:$,method:"POST"}).catch(()=>{});h?.(i)}catch{}};return{executeLanguageModelCall:r=>{const f=Date.now(),l=d(r,"modelId"),p=r.execute();return T(p,(y,_,i)=>{const s=[];a(s,"gen_ai.operation.name","chat"),a(s,"gen_ai.request.model",l),a(s,"gen_ai.system",d(r,"provider")),a(s,"gen_ai.conversation.id",t);const k=U(d(i,"usage"));k&&(a(s,"gen_ai.usage.input_tokens",k.inputTokens),a(s,"gen_ai.usage.output_tokens",k.outputTokens),a(s,"gen_ai.usage.total_tokens",k.totalTokens));const S=V(i);S&&(a(s,"gen_ai.usage.cost",S.cost),a(s,"gen_ai.response.cached",S.cached),a(s,"cf.aig.log_id",S.logId)),c&&a(s,"gen_ai.prompt",d(r,"messages")),m&&a(s,"gen_ai.completion",j(d(i,"content"))),O(typeof l=="string"?`chat ${l}`:"language_model_call",f,y,_,s)}),p},executeTool:r=>{const f=Date.now(),l=z(r),p=r.execute();return T(p,(y,_)=>{const i=[];a(i,"gen_ai.operation.name","execute_tool"),a(i,"gen_ai.tool.name",l),a(i,"gen_ai.tool.call.id",d(r,"toolCallId")),c&&a(i,"gen_ai.tool.input",A(r)),O(typeof l=="string"?`execute_tool ${l}`:"execute_tool",f,y,_,i)}),p}}};export{L as otlpTelemetry};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{resolveAgentModel as q}from"./createAgentGenerate-BUVImo85.mjs";import{i as L,c as T,t as J,n as Q}from"./memory-DNRyyp1b.mjs";import{buildModelMessages as R}from"./buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as V}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-BXx-tSCe.mjs";const W=8,E=e=>e===void 0?"null":JSON.stringify(e),X=e=>e===void 0?[]:Array.isArray(e)?e:[e],Y=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),I=(e,t)=>e===void 0&&t===void 0?void 0:(e??0)+(t??0),Z=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const a={},o=I(e.inputTokens,t.inputTokens),n=I(e.outputTokens,t.outputTokens),i=I(e.totalTokens,t.totalTokens);return o!==void 0&&(a.inputTokens=o),n!==void 0&&(a.outputTokens=n),i!==void 0&&(a.totalTokens=i),a},z=async(e,t,a)=>{const{needsApproval:o}=e;return o===void 0||o===!1?!1:o===!0?!0:o(t,a)},H=async(e,t)=>{const{instanceId:a,patchThread:o,persist:n,step:i}=e;await n({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await o({status:"awaiting_input"});const r=await i.waitForEvent(`approval:${t.id}`,{type:`agent-approval:${t.id}`});return await o({status:"running"}),{decision:r.payload.decision,...r.payload.note===void 0?{}:{note:r.payload.note}}},tt=async(e,t)=>{const{env:a,getState:o,instanceId:n,onTokenDelta:i,persist:r,run:l,setState:c,step:p,threadKey:s,tools:u}=e,d=`tool:${t.name}:${t.id}`,y=u[t.name],h=`${n}:tool:${t.id}`;if(!y){await r({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const w={env:a,getState:o,idempotencyKey:d,reportProgress:f=>{i?.({data:f,kind:"progress",threadKey:s,toolCallId:t.id})},run:l,setState:c,threadKey:s,toolCallId:t.id};let x;if(await z(y,t.input,w)){const{decision:f,note:C}=await H(e,t);if(f==="reject"){const k=C===void 0?"":` Reason: ${C}`;await r({content:`Tool "${t.name}" was rejected by the user and not run.${k}`,messageKey:h,role:"tool",status:"rejected",stepName:d,toolCallId:t.id,toolName:t.name});return}x="approved"}const m=await p.do(d,()=>Promise.resolve(y.execute(t.input,w)));await r({content:typeof m=="string"?m:E(m),messageKey:h,role:"tool",stepName:d,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},et=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:q(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},ot=async(e,t)=>{const{agent:a,compact:o,env:n}=e,i=at(t,a.compaction);if(i===void 0||o===void 0)return{history:t,summary:void 0};try{const r=await o({env:n,messages:R({history:i.older}),model:a.compaction?.model??a.model});return r.length>0?{history:i.recent,summary:r}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},st=async(e,t,a)=>{const{agent:o,env:n,generate:i,instructions:r,listMessages:l,memoryContext:c,onTokenDelta:p,run:s,step:u,streamGenerate:d,threadKey:y}=e;return u.do(`llm:turn:${String(t)}`,async()=>{const h=await s(l,{key:y}),{history:w,summary:x}=await ot(e,h);let m={activeTools:o.activeTools,messages:R({history:w,instructions:r,memoryContext:c,summary:x}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(m=et(m,await o.prepareStep({messages:m.messages,stepNumber:t,steps:a}),n));const f={messages:m.messages,...m.activeTools===void 0?{}:{activeTools:m.activeTools},...m.model===void 0?{}:{model:m.model},...m.toolChoice===void 0?{}:{toolChoice:m.toolChoice}};return d&&p?d(f,C=>{p({text:C,threadKey:y,turn:t})}):i(f)})},A=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),N=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},it=e=>{const t={};return e?.depth!==void 0&&(t.depth=e.depth),e?.fanOut!==void 0&&(t.fanOut=e.fanOut),e?.maxNodes!==void 0&&(t.maxNodes=e.maxNodes),e?.maxSeeds!==void 0&&(t.maxSeeds=e.maxSeeds),t},rt=async(e,t,a,o)=>{if(e.source===void 0)return;const n=g(e.source),{topK:i}=e,r=T("memory:retrieve",e.key),l=await a.do(r,async()=>o(n,{query:t,...i===void 0?{}:{topK:i}}));return N(l)},dt=async(e,t,a,o,n,i)=>{if(a===void 0)return;const r=T("memory:traverse",e.key),l=await n.do(r,async()=>i(o,{owner:a,query:t,...it(e.graph)}));return N(l)},lt=async(e,t,a,o,n)=>{if(t===void 0)return;const i=T("memory:recall",e.key),r={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},l=await o.do(i,async()=>n(a,r));return N(l)},ct=async(e,t)=>e.kind==="episodic"?lt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?dt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):rt(e,t.input,t.step,t.run),ut=e=>{let t=!1;return e.filter(a=>a.kind!=="episodic"?!0:t?!1:(t=!0,!0))},pt=async(e,t,a,o,n,i)=>{const r=ut(Q(e));if(r.length===0)return;const l=g(o.graphTraverse),c=g(o.episodeRecall),p=[];for(const s of r){const u=await ct(s,{episodeRecall:c,graphTraverse:l,input:t,owner:a,run:i,step:n});u!==void 0&&p.push(u)}return p.length>0?p.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0},mt=async e=>{const{agent:t,env:a,extractGraph:o,finalText:n,input:i,instanceId:r,owner:l,paths:c,run:p,step:s}=e;if(o===void 0||l===void 0||n===void 0||n.length===0)return;const u=L(t);if(u!==void 0)try{const d={assistantText:n,env:a,model:u.graph?.extractionModel??t.model,userInput:i},y=await s.do(T("memory:extract",u.key),async()=>o(d));await p(g(c.graphUpsert),{...y,messageKey:`${r}:${T("extract",u.key)}`,owner:l})}catch{}},yt=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:n,input:i,instanceId:r,owner:l,paths:c,run:p,step:s,threadKey:u}=e;if(o===void 0||l===void 0||n===void 0||n.length===0)return;const d=J(t);if(d!==void 0)try{const y={assistantText:n,env:a,model:d.episodic?.extractionModel??t.model,userInput:i},{summary:h}=await s.do(T("memory:episode",d.key),async()=>o(y));await p(g(c.episodeUpsert),{messageKey:`${r}:${T("episode",d.key)}`,owner:l,summary:h,threadKey:u})}catch{}},vt=async(e,t,a)=>{const o=e[V(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(a)).terminate()}catch{}},gt=async(e,t,a,o,n)=>{const{instanceId:i,persist:r}=e,l=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const c=a.output!==void 0&&a.text.length===0?E(a.output):a.text;return await r({content:c,messageKey:`${i}:assistant:${String(t)}`,role:"assistant"}),await A(e,{text:a.text,toolCalls:[],turn:t,...l}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await r({content:a.text,messageKey:`${i}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});for(const c of a.toolCalls)await tt(e,c);if(await A(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...l}),o.push(nt(a)),n.length>0&&await Y(n,o))return"stopCondition"},ht=async(e,t,a,o)=>{const n=[];let i,r=!1,l=0;for(let c=0;c<t;c+=1){const p=await st(e,c,n);o.value=Z(o.value,p.usage),l=c+1;const s=await gt(e,c,p,n,a);if(s==="stopCondition"){r=!0;break}if(s!==void 0){i=s.final;break}}return{final:i,stoppedByCondition:r,turnsRun:l}},Ct=async e=>{const{agent:t,compact:a,env:o,exportName:n,extractEpisode:i,extractGraph:r,generate:l,instanceId:c,onTokenDelta:p,params:s,paths:u,run:d,step:y,streamGenerate:h}=e,w=t.maxTurns??W,x=X(t.stopWhen),m=g(u.appendMessage),f=g(u.ensureThread),C=g(u.listMessages),k=g(u.patchThread),b=g(u.setState),F=g(u.state),M=async v=>{await d(m,{threadKey:s.threadKey,...v})},G=async v=>{await d(k,{key:s.threadKey,...v})},j=async()=>await d(F,{key:s.threadKey}),B=async v=>{await d(b,{key:s.threadKey,state:v})},S=await d(f,{agent:n,instanceId:c,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});S?.replaced&&S.priorInstanceId!==void 0&&await vt(o,n,S.priorInstanceId),await M({content:s.input,messageKey:`${c}:user`,role:"user"});const D=await pt(t,s.input,s.owner,u,y,d),O=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,P={agent:t,compact:a,env:o,generate:l,getState:j,instanceId:c,instructions:O,listMessages:C,memoryContext:D,onTokenDelta:p,patchThread:G,persist:M,run:d,setState:B,step:y,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},$={value:void 0};try{const{final:v,stoppedByCondition:U,turnsRun:_}=await ht(P,w,x,$),K=$.value===void 0?{}:{usage:$.value};return await mt({agent:t,env:o,extractGraph:r,finalText:v?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:y}),await yt({agent:t,env:o,extractEpisode:i,finalText:v?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:y,threadKey:s.threadKey}),v?(await d(k,{key:s.threadKey,status:"idle",...K}),{...v,...K}):U?(await d(k,{key:s.threadKey,status:"idle",...K}),{stopped:"stopCondition",turns:_,...K}):(await d(k,{error:`agent stopped: maxTurns (${String(w)}) reached`,key:s.threadKey,status:"error",...K}),{stopped:"maxTurns",turns:w,...K})}catch(v){throw await d(k,{error:v instanceof Error?v.message:String(v),key:s.threadKey,status:"error",...$.value===void 0?{}:{usage:$.value}}),v}};export{Ct as runAgentLoop,at as splitForCompaction};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as W}from"./base64-jU-Ci6Tu.mjs";import{buildModelMessages as z}from"./buildModelMessages-Dm2wVNQy.mjs";import{toFunctionReference as x}from"./AGENT_MODULE-BXx-tSCe.mjs";const G=16e3,J=1,q=16,K=/[^.!?]*[.!?]+\s+/u,C=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:s}=await e.read();if(n)break;yield s}}finally{e.releaseLock()}return}yield*t},Y=(t,e=G,n=J,s=q)=>{const u=n*s/8,y=e*u,f=new ArrayBuffer(44+t.byteLength),r=new DataView(f),a=(U,l)=>{for(let g=0;g<l.length;g+=1)r.setUint8(U+g,l.codePointAt(g)??0)};a(0,"RIFF"),r.setUint32(4,36+t.byteLength,!0),a(8,"WAVE"),a(12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,e,!0),r.setUint32(28,y,!0),r.setUint16(32,u,!0),r.setUint16(34,s,!0),a(36,"data"),r.setUint32(40,t.byteLength,!0);const d=new Uint8Array(f);return d.set(t,44),d},H=t=>{const e=[];let n=t,s=K.exec(n);for(;s&&s[0].length>0;){const u=s[0],y=u.trim();y.length>0&&e.push(y),n=n.slice(u.length),s=K.exec(n)}return{rest:n,sentences:e}},Z=async t=>{const{agent:e,connectionId:n,env:s,exportName:u,owner:y,paths:f,pcm:r,run:a,send:d,sendAudio:U,signal:l,streamGenerate:g,synthesize:F,text:I,threadKey:c,transcribe:L,turn:T,waitForDrain:M}=t,p=()=>l.aborted,v=x(f.appendMessage),j=x(f.ensureThread),V=x(f.listMessages),A=x(f.patchThread),w=(I??(r?await L(r):"")).trim();if(w.length===0)return{assistantText:"",interrupted:!1,userText:""};d({text:w,type:"user_transcript"}),await a(j,{agent:u,key:c,...e.initialState===void 0?{}:{initialState:e.initialState},...y===void 0?{}:{owner:y}}),await a(v,{content:w,messageKey:`voice:${n}:${String(T)}:user`,role:"user",threadKey:c}),await a(A,{key:c,status:"running"});const k=typeof e.instructions=="function"?e.instructions({env:s,input:w,threadKey:c}):e.instructions,_=await a(V,{key:c}),B=z({history:_,...k===void 0?{}:{instructions:k}});let h="",b="",S=Promise.resolve();const D=async i=>{if(p()||i.length===0)return;let m=!1;try{for await(const o of C(await F(i,l))){if(p()||(await M?.(),p()))break;U(o),m=!0}}catch(o){d({message:o instanceof Error?o.message:String(o),type:"error"})}m&&(b=b.length>0?`${b} ${i}`:i)},R=i=>{S=S.then(async()=>D(i))};try{const i=await g({messages:B,signal:l},$=>{if(p())return;d({text:$,type:"assistant_delta"}),h+=$;const{rest:E,sentences:N}=H(h);h=E;for(const P of N)R(P)});!p()&&h.trim().length>0&&R(h.trim()),h="",await S;const m=p(),o=m?b:i.text;return await a(v,{content:o,messageKey:`voice:${n}:${String(T)}:assistant`,role:"assistant",threadKey:c}),await a(A,{key:c,status:"idle"}),d(m?{type:"interrupted"}:{text:o,type:"assistant_done"}),{assistantText:o,interrupted:m,userText:w}}catch(i){throw await a(A,{key:c,status:"idle"}),i}},tt=t=>{if(t)try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}},et=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},nt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return W(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{tt as parseIdentity,Y as pcmToWav,nt as readSynthesisAudio,et as readTranscriptionText,Z as runVoiceTurn,C as toByteIterable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as n}from"@lunora/values";import{o as d}from"./base64-jU-Ci6Tu.mjs";const{internalAction:w}=h.dataModel().create(),b=()=>globalThis.document?.documentElement?.outerHTML??"",u=1e6,m=20,y=new TextEncoder,x=async(o,t)=>{const e=t.url??"";switch(t.op){case"content":return o.content(e);case"pdf":return{data:d(await o.pdf(e)),encoding:"base64",mediaType:"application/pdf"};case"scrape":return o.scrape(e,b);case"screenshot":{const r=await o.screenshot(e,{...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return{data:d(r),encoding:"base64",mediaType:t.type==="jpeg"?"image/jpeg":"image/png"}}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},T=async(o,t)=>{const e=o.any();if(t.op==="exec")return(await e.fetch("/exec",{body:JSON.stringify({args:t.args??[],command:t.command??""}),headers:{"content-type":"application/json"},method:"POST"})).text();if(t.op==="fetch")return(await e.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET"})).text();throw new c("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},g=o=>{let t=0,e=o.length;for(;t<e&&o[t]==="/";)t+=1;for(;e>t&&o[e-1]==="/";)e-=1;return o.slice(t,e)},E=(o,t)=>{const e=g(o),r=[];for(const a of t.split("/"))if(!(a===""||a===".")){if(a===".."){if(r.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(a)}const i=r.join("/");return e&&i?`${e}/${i}`:e||i},N=async(o,t,e)=>{const r=t.length>0?`${t}/`:"",i=e.length>0?e.length+1:0,a=[];let s;for(let l=0;l<m;l+=1){const p=await o.list({prefix:r,...s===void 0?{}:{cursor:s}});for(const f of p.objects)a.push(f.key.slice(i));if(!p.truncated||p.cursor===void 0)return{entries:a,truncated:!1};s=p.cursor}return{entries:a,truncated:!0}},$=async(o,t,e)=>{const r=g(t),i=E(t,e.path??"");switch(e.op){case"ls":{const{entries:a,truncated:s}=await N(o,i,r);return s?{entries:a,truncated:!0}:{entries:a}}case"read":{const a=await o.head(i);if(a&&a.size>u)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${e.path??""}" is ${String(a.size)} bytes (max ${String(u)})`);const s=await o.get(i);if(!s)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${e.path??""}"`);return s.text()}case"rm":return await o.delete(i),{path:e.path??"",removed:!0};case"stat":{const a=await o.head(i);return a?{exists:!0,size:a.size}:{exists:!1}}case"write":{const a=e.content??"",s=y.encode(a).length;if(s>u)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(s)} bytes exceeds the max (${String(u)})`);return await o.put(i,a),{bytes:s,path:e.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${e.op}" is not supported`)}},S=()=>({invoke:w.input({args:n.optional(n.array(n.string())),body:n.optional(n.string()),bucket:n.optional(n.string()),command:n.optional(n.string()),content:n.optional(n.string()),fullPage:n.optional(n.boolean()),kind:n.union(n.literal("browser"),n.literal("container"),n.literal("fs")),method:n.optional(n.string()),name:n.optional(n.string()),op:n.string(),path:n.optional(n.string()),root:n.optional(n.string()),selector:n.optional(n.string()),type:n.optional(n.string()),url:n.optional(n.string())}).action(async({args:o,ctx:t})=>{const e=t,r=o;if(r.kind==="browser"){if(!e.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return x(e.browser,r)}if(r.kind==="fs"){const s=e.env?.[r.bucket??""];if(!s||typeof s.get!="function")throw new c("INTERNAL",`@lunora/agent: sandbox fs op found no R2 bucket "${r.bucket??""}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`);return $(s,r.root??"",r)}const i=r.name??"",a=e.containers?.[i];if(!a)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${i}"] — declare the container in lunora/containers.ts and run codegen`);return T(a,r)})});export{E as resolveFsKey,$ as runFsOp,S as sandboxComponent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as u,r as t}from"./common-Dck97z3Y.mjs";const r=(o,n)=>typeof o=="string"&&o.length>0?o:n,c=o=>{const{functionId:n,recordInputs:i=!1,Sentry:l}=o;return{executeLanguageModelCall:e=>{const a={"gen_ai.operation.name":r(n,"language_model_call"),"gen_ai.request.model":t(e,"modelId"),"gen_ai.system":t(e,"provider")};return i&&(a["gen_ai.prompt"]=t(e,"messages")),l.startSpan({attributes:a,name:r(n,"language_model_call"),op:"gen_ai.generate"},()=>e.execute())},executeTool:e=>{const a=t(t(e,"toolCall"),"toolName"),s={"gen_ai.operation.name":"execute_tool","gen_ai.tool.call.id":t(e,"toolCallId"),"gen_ai.tool.name":a};return i&&(s["gen_ai.tool.input"]=u(e)),l.startSpan({attributes:s,name:`execute_tool ${r(a,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onError:e=>{l.captureException(e)}}};export{c as sentryTelemetry};
|