@lunora/agent 1.0.0-alpha.27 → 1.0.0-alpha.270

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 (96) 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 +54 -2
  5. package/dist/component.d.ts +54 -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 +207 -18
  11. package/dist/index.d.ts +207 -18
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.d.mts +15 -7
  14. package/dist/naming.d.ts +15 -7
  15. package/dist/naming.mjs +1 -1
  16. package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs +1 -0
  18. package/dist/packem_shared/SecretUnavailableError-BCp40Leh.mjs +1 -0
  19. package/dist/packem_shared/VoiceSessionDO-BIfcyunp.mjs +1 -0
  20. package/dist/packem_shared/adaptMcpResult-DFF_g58r.mjs +2 -0
  21. package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
  22. package/dist/packem_shared/agent-loop-ByDqRJo7.mjs +3 -0
  23. package/dist/packem_shared/agentAsTool-CA7Sha2i.mjs +1 -0
  24. package/dist/packem_shared/braintrustTelemetry-Ck09dC4G.mjs +1 -0
  25. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  26. package/dist/packem_shared/buildModelMessages-DVQdQ7_1.mjs +5 -0
  27. package/dist/packem_shared/codeTool-Hm_Af6t4.mjs +1 -0
  28. package/dist/packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs +1 -0
  29. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  30. package/dist/packem_shared/common-DBc9y7Np.mjs +1 -0
  31. package/dist/packem_shared/compileAgentWorkflow-BkVDrDvM.mjs +1 -0
  32. package/dist/packem_shared/component-shared-DdXFbng-.mjs +1 -0
  33. package/dist/packem_shared/consoleTelemetry-Cl-WQEsZ.mjs +1 -0
  34. package/dist/packem_shared/createAgentContext-CjdW-jip.mjs +1 -0
  35. package/dist/packem_shared/createAgentGenerate-DSLXAeY2.mjs +3 -0
  36. package/dist/packem_shared/defineAgent-D4eUl6YE.mjs +3 -0
  37. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  38. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  39. package/dist/packem_shared/functionTool-C95ns65V.mjs +1 -0
  40. package/dist/packem_shared/in-flight-calls-C9QGq8uH.mjs +1 -0
  41. package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
  42. package/dist/packem_shared/normalizeEntityName-Rr5OQxhc.mjs +2 -0
  43. package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +1 -0
  44. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  45. package/dist/packem_shared/runAgentLoop-Cv661XGm.mjs +1 -0
  46. package/dist/packem_shared/runVoiceTurn-DAtWSeXj.mjs +1 -0
  47. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  48. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  49. package/dist/packem_shared/sentryTelemetry-B1BuLxxj.mjs +1 -0
  50. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  51. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-vAmttAsE.d.mts} +355 -33
  52. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-vAmttAsE.d.ts} +355 -33
  53. package/dist/packem_shared/voice-turn-DBWkPcQH.mjs +1 -0
  54. package/dist/packem_shared/webSearchTool-BobmV4cD.mjs +1 -0
  55. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  56. package/dist/packem_shared/wrapUntrusted-BuHBC6sV.mjs +2 -0
  57. package/dist/reply.d.mts +58 -0
  58. package/dist/reply.d.ts +58 -0
  59. package/dist/reply.mjs +1 -0
  60. package/dist/sandbox.d.mts +157 -16
  61. package/dist/sandbox.d.ts +157 -16
  62. package/dist/sandbox.mjs +1 -1
  63. package/dist/skill-markdown.d.mts +36 -0
  64. package/dist/skill-markdown.d.ts +36 -0
  65. package/dist/skill-markdown.mjs +1 -0
  66. package/dist/telemetry/index.d.mts +165 -38
  67. package/dist/telemetry/index.d.ts +165 -38
  68. package/dist/telemetry/index.mjs +1 -1
  69. package/package.json +20 -9
  70. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  71. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  72. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  73. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  74. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  75. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  76. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  77. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  78. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  79. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  80. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  81. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  82. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  83. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  84. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  85. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  86. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  87. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  88. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  89. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  90. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  91. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  92. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  93. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  94. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  95. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  96. package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-boAM2Yi1.js";
2
- export type { y as AgentEmailMapper, z as AgentEmailRun, B as AgentGenerateOptions, C as AgentGenerateResult, D as AgentInstructionsContext, E as AgentLiveEvent, F as AgentMemoryOptions, G as AgentMemorySource, H as AgentMessageStatus, J as AgentOnStepFinish, K as AgentPrepareStep, L as AgentPrepareStepInput, M as AgentPrepareStepResult, N as AgentProgressEvent, O as AgentRunHandle, P as AgentStepFinishInfo, Q as AgentStepInfo, R as AgentThreadStatus, T as AgentTokenDelta, U as AgentToolCall, a as AgentToolContext, V as AgentUsage, W as AgentVoiceConfig, X as AgentWorkflowBindingLike, Y as AgentWorkflowInstanceLike } from "./packem_shared/types.d-boAM2Yi1.js";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, d as AgentToolContext, z as SkillConfig } from "./packem_shared/types.d-vAmttAsE.js";
2
+ export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-vAmttAsE.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
6
- export { type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.js";
7
- import { createAi } from '@lunora/ai';
5
+ export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
6
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
7
+ import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai/create';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
10
10
  import '@lunora/server';
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
23
23
  env: Record<string, unknown>;
24
24
  /** The agent's `lunora/agents.ts` export name (thread attribution). */
25
25
  exportName: string;
26
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
27
+ exports?: unknown;
26
28
  /**
27
29
  * The run-end episode-summary seam — production wires AI SDK `generateText`.
28
30
  * Absent (the default) disables episode recording, so an agent with no
@@ -183,7 +185,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
183
185
  interface ToolScriptStep {
184
186
  /** A stable name later steps reference the output by. */
185
187
  id: string;
186
- /** The tool's input; values may embed `{ "$from": "&lt;stepId>", "$path": "a.b" }` refs. */
188
+ /** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
187
189
  input?: Record<string, unknown>;
188
190
  /** The tool to call — one of the tools handed to {@link codeTool}. */
189
191
  tool: string;
@@ -229,8 +231,8 @@ interface CodeToolOptions {
229
231
  * SCRIPT that composes several of the tools you hand `codeTool` — chaining a
230
232
  * later call's input to an earlier call's output — and the whole thing runs in a
231
233
  * single turn. This is a SAFE interpreted data-flow between whitelisted tools
232
- * (no `eval`, no isolate), so it runs natively in workerd; arbitrary-code
233
- * execution (the Cloudflare Worker Loader path) is a separate future mode.
234
+ * (no `eval`, no isolate), so it runs natively in workerd; for arbitrary code
235
+ * in a Worker Loader isolate, see `jsCodeTool`.
234
236
  *
235
237
  * Each composed tool dispatches through the same durable context a normal call
236
238
  * gets (inheriting RLS), with a per-step idempotency key. A code-mode script runs
@@ -239,6 +241,16 @@ interface CodeToolOptions {
239
241
  * keep approval-gated tools as normal top-level tools. Gate the whole script via
240
242
  * `opts.needsApproval` instead.
241
243
  *
244
+ * STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
245
+ * step runs inside its own durable `step.do`, so the workflow host serializes
246
+ * the returned value before the next step (or the tool result) ever sees it. A
247
+ * `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
248
+ * `null` or a dropped key, and a `bigint` throws outright. That applies to the
249
+ * value a later step reads through `{ "$from": … }` just as much as to the
250
+ * returned `results` — the hand-off is durable state, not an in-memory one. A
251
+ * composed tool that wants to pass a rich value should return its JSON form
252
+ * (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
253
+ *
242
254
  * ```ts
243
255
  * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
244
256
  *
@@ -259,8 +271,9 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
259
271
  /**
260
272
  * Build the `ctx.agents` producer surface from the codegen-emitted spec list
261
273
  * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
262
- * declared agent resolves its `AGENT_*` Workflow binding off `env` lazily, so
263
- * a missing binding only errors when that agent is actually started.
274
+ * declared agent resolves by its export key (the generated class name) off the
275
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
276
+ * lazily, so a missing agent only errors when it is actually started.
264
277
  *
265
278
  * `cancel` also needs to write the thread's status, so it dispatches the agent
266
279
  * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
@@ -269,7 +282,10 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
269
282
  * inject a `dispatch` double.
270
283
  * @experimental
271
284
  */
272
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, dispatch?: AgentRunFunction) => Record<string, AgentHandle>;
285
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
+ dispatch?: AgentRunFunction;
287
+ exports?: unknown;
288
+ }) => Record<string, AgentHandle>;
273
289
  /**
274
290
  * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
275
291
  * (each LLM turn and each tool call a named durable step; thread messages
@@ -344,8 +360,14 @@ interface FunctionToolOptions<Input> {
344
360
  * ```
345
361
  *
346
362
  * The function reference may be a typed `api.*` reference or a `"module:name"`
347
- * path. The model-provided input is passed verbatim as the function's args, so
348
- * `inputSchema` should mirror the referenced function's argument validator.
363
+ * path. The model-provided input is passed as the function's args, so
364
+ * `inputSchema` should mirror the referenced function's argument validator —
365
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
366
+ * input (so out-of-schema model input can never override it). A function
367
+ * that wants to dedupe a side-effecting call across an at-least-once step
368
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
369
+ * and checks it; a function that ignores it is unaffected — an args field
370
+ * the function's own validator doesn't declare is dropped, not rejected.
349
371
  * @experimental
350
372
  */
351
373
  declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
@@ -471,6 +493,17 @@ interface McpToolsOptions {
471
493
  command?: string;
472
494
  /** Identify this client to the server on connect. Default `"lunora-agent"`. */
473
495
  name?: string;
496
+ /**
497
+ * Gate an adapted tool's call behind a human approval. Defaults to
498
+ * **unattended** (no gate) — matching today's behavior. An MCP tool's
499
+ * result feeds back into the model's context (`adaptMcpResult`), so a
500
+ * hostile downstream server can pair indirect prompt injection with an
501
+ * unattended mutating tool call; pass a boolean to gate every adapted
502
+ * tool the same way, or a predicate `(toolName, input) => boolean` to
503
+ * gate per tool (evaluated from replay-stable input, so keep it
504
+ * deterministic).
505
+ */
506
+ needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
474
507
  /** Only adapt these tool names (default: every tool the server lists). */
475
508
  only?: ReadonlyArray<string>;
476
509
  /** Prefix added to each adapted tool's key (disambiguate multiple servers). */
@@ -510,6 +543,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
510
543
  * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
511
544
  * does not) — pass `url`, or inject an already-connected `client` for a custom
512
545
  * transport (also the test seam).
546
+ *
547
+ * Every adapted tool runs UNATTENDED by default (no approval gate) — pass
548
+ * `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
513
549
  * @experimental
514
550
  */
515
551
  declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
@@ -556,6 +592,82 @@ declare const DEFAULT_AGENT_FUNCTION_PATHS: AgentFunctionPaths;
556
592
  * @experimental
557
593
  */
558
594
  declare const toFunctionReference: (source: AgentFunctionReference | string) => AgentFunctionReference;
595
+ /** The model's input to {@link requestSecretTool}: what the secret is for, shown to the person asked. */
596
+ interface SecretRequestInput {
597
+ label: string;
598
+ }
599
+ /**
600
+ * Thrown by {@link withSecret} when the value is no longer takeable. The loop
601
+ * records it as a deterministic tool failure, so the model can recover rather
602
+ * than the durable step retrying a read that can never succeed.
603
+ */
604
+ declare class SecretUnavailableError extends Error {
605
+ readonly code = "SECRET_UNAVAILABLE";
606
+ constructor();
607
+ }
608
+ /**
609
+ * An agent tool that asks the human for a secret value (an API key, a token) and
610
+ * hands the model only an opaque `{ secretRef }` in return. The loop pauses the
611
+ * run until the owner supplies the value through `agents:agentSupplySecret`, or
612
+ * declines through `agents:agentDeclineSecret`. `execute` is never called: the
613
+ * loop resolves this tool itself.
614
+ *
615
+ * `consumer` names the one tool allowed to read the value. The model can pass the
616
+ * `secretRef` to any tool, but only the declared consumer's {@link withSecret} call
617
+ * takes it, so a prompt-injected model cannot route the value elsewhere.
618
+ *
619
+ * Codegen wires the secret store when a source in `lunora/` value-imports this tool
620
+ * from `@lunora/agent`: by a named import, a namespace import that reads it, or a
621
+ * relative barrel that re-exports it. Without that wiring the supply mutation refuses,
622
+ * and the refusal names the missing import. Requires a host that rates `secretValues`
623
+ * as supported.
624
+ *
625
+ * ```ts
626
+ * import { defineAgent, requestSecretTool } from "@lunora/agent";
627
+ *
628
+ * export const billing = defineAgent({
629
+ * tools: {
630
+ * requestApiKey: requestSecretTool({
631
+ * consumer: "chargeCard",
632
+ * description: "Ask the user for their payment-provider API key.",
633
+ * }),
634
+ * chargeCard: functionTool({ ... }), // reads the value with withSecret
635
+ * },
636
+ * });
637
+ * ```
638
+ *
639
+ * The value transits the supply mutation's arguments, which are marked
640
+ * `v.sensitive`: the request log masks them. The run's history records only the
641
+ * request id.
642
+ * @experimental
643
+ */
644
+ declare const requestSecretTool: (options: {
645
+ consumer: string;
646
+ description: string;
647
+ }) => AgentToolDefinition<SecretRequestInput, {
648
+ secretRef: string;
649
+ }>;
650
+ /**
651
+ * Read a human-supplied secret inside the tool that the request declared as its
652
+ * `consumer`, hand it to `use`, and return only what `use` returns. The value never
653
+ * leaves the callback: it is not a step output, not a tool result and not a message.
654
+ * The read is its own durable step named for this call, so a retry of the same step
655
+ * re-takes the value (the claimant is this step's name), while a different call
656
+ * cannot.
657
+ *
658
+ * Call it from inside a tool's `execute`. The discard runs as a separate durable step
659
+ * only after the take succeeded and `use` returned, so a call that is refused (the
660
+ * wrong tool, another thread, an expired request) cannot burn a value the declared
661
+ * consumer still needs. If `use` keeps failing, the value stays until its TTL expires,
662
+ * which is the backstop for a crash between the take and the discard. `use` must not
663
+ * return or log the value. A result that carries it is refused (the call fails with
664
+ * `LunoraError`) rather than journalled. An error that carries it is redacted before
665
+ * it propagates, so the step's retry, the failure the loop records and telemetry never
666
+ * see the value; `traceToolExecution` records the tool's input and output.
667
+ * @throws {SecretUnavailableError} when the request is unknown, not supplied, declared for another consumer, or from another thread
668
+ * @experimental
669
+ */
670
+ declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
559
671
  /**
560
672
  * Declare a reusable skill: a bundle of expertise — an instruction fragment,
561
673
  * tools, and retrieval `knowledge` — an agent composes in via
@@ -592,12 +704,28 @@ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
592
704
  * @experimental
593
705
  */
594
706
  declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
707
+ /**
708
+ * Wrap untrusted text for inclusion in a prompt. The text sits between a tag
709
+ * whose id is random per call, so payload text cannot forge the closing tag (it
710
+ * cannot know the id), and any `<` or `>` in it is escaped so it cannot form a
711
+ * tag at all. A mention or cashtag (`@`, `$`) not glued to a word, and a slash
712
+ * command `/` at the start of a token, get a zero-width space after them. Given a header map, the headers are rendered
713
+ * above the body with credential-like values redacted. A one-line note after the
714
+ * block tells the model the enclosed data is not to be followed as instructions.
715
+ *
716
+ * Use it on the text a mapper hands the model, e.g. `input: wrapUntrusted(email.text ?? "")`.
717
+ * @experimental
718
+ */
719
+ declare const wrapUntrusted: (value: string, headers?: Headers | Readonly<Record<string, string>>) => string;
595
720
  /**
596
721
  * A control frame the server sends the client as a JSON text message (audio
597
722
  * rides separate binary frames). `ready` announces the negotiated codec on
598
723
  * connect; `user_transcript` carries the STT result; `assistant_delta` streams
599
724
  * the live LLM text; `assistant_done` is the final turn text; `interrupted`
600
- * acks a barge-in; `error` reports a non-fatal turn failure.
725
+ * acks a barge-in; `assistant_discarded` says the turn failed, so the deltas
726
+ * already streamed for it are not an answer; `error` reports a failure. An
727
+ * `error` alone does not end a turn: a speech-synthesis failure reports one and
728
+ * the turn still completes.
601
729
  * @experimental
602
730
  */
603
731
  type VoiceServerFrame = {
@@ -615,6 +743,8 @@ type VoiceServerFrame = {
615
743
  } | {
616
744
  text: string;
617
745
  type: "user_transcript";
746
+ } | {
747
+ type: "assistant_discarded";
618
748
  } | {
619
749
  type: "interrupted";
620
750
  };
@@ -674,6 +804,13 @@ interface VoiceTurnResult {
674
804
  interface RunVoiceTurnOptions {
675
805
  /** The agent whose thread + models back this session. */
676
806
  agent: AgentDefinition;
807
+ /**
808
+ * History-compaction seam — the SAME one the durable loop uses. Voice and
809
+ * text turns share one thread, so an agent that declares `compaction` must
810
+ * get it here too; absent (or with no `compaction` config) the turn takes
811
+ * the byte-identical uncompacted path.
812
+ */
813
+ compact?: AgentCompact;
677
814
  /** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
678
815
  connectionId: string;
679
816
  /** The Worker env (resolves a dynamic `instructions` thunk). */
@@ -755,6 +892,8 @@ declare class VoiceSessionDO {
755
892
  protected readonly streamGenerate: AgentStreamGenerate;
756
893
  protected readonly sttModel: string;
757
894
  protected readonly ttsModel: string;
895
+ /** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
896
+ private readonly maxSessionTurns;
758
897
  private readonly audioBuffers;
759
898
  private readonly bufferedBytes;
760
899
  private readonly controllers;
@@ -793,6 +932,8 @@ declare class VoiceSessionDO {
793
932
  private synthesizeWithSignal;
794
933
  /** Abort an in-flight turn and free a socket's transient buffers. */
795
934
  private cleanupSocket;
935
+ /** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
936
+ private closeSocket;
796
937
  /** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
797
938
  private send;
798
939
  /** Send a binary audio frame, swallowing a closed-socket error. */
@@ -806,17 +947,65 @@ declare class VoiceSessionDO {
806
947
  */
807
948
  private waitForSocketDrain;
808
949
  }
950
+ /**
951
+ * Config for {@link webSearchTool}.
952
+ * @experimental
953
+ */
954
+ interface WebSearchToolOptions {
955
+ /** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
956
+ byokAlias?: string;
957
+ /** Overrides the description shown to the model. */
958
+ description?: string;
959
+ /**
960
+ * The AI Gateway that brokers and bills the search. Defaults to
961
+ * `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
962
+ */
963
+ gatewayId?: string;
964
+ /** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
965
+ limit?: number;
966
+ /** Defaults to the Web Search API's own default (`"ceramic"`). */
967
+ provider?: AiWebSearchProvider;
968
+ }
969
+ /**
970
+ * What the model passes.
971
+ * @experimental
972
+ */
973
+ interface WebSearchToolInput {
974
+ query: string;
975
+ }
976
+ /**
977
+ * A batteries-included agent tool over the Cloudflare Web Search API (beta,
978
+ * `ctx.ai.websearch`), so an agent can ground an answer in live results.
979
+ * A search bills a provider key stored on the gateway (`byokAlias`, else the
980
+ * `default` alias) when there is one, otherwise AI Gateway credits; every
981
+ * provider runs under Zero Data Retention.
982
+ *
983
+ * It calls the `AI` binding straight from the tool's durable step: a search
984
+ * is a read, so the at-least-once step retry repeats nothing but a query, and
985
+ * there is no dispatcher action to register.
986
+ *
987
+ * ```ts
988
+ * import { defineAgent, webSearchTool } from "@lunora/agent";
989
+ *
990
+ * export const researcher = defineAgent({
991
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
992
+ * tools: { search: webSearchTool({ provider: "exa" }) },
993
+ * });
994
+ * ```
995
+ * @experimental
996
+ */
997
+ declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
809
998
  /**
810
999
  * Compile a `defineAgent` definition into the workflow the generated
811
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
1000
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
812
1001
  *
813
1002
  * ```ts
814
1003
  * import LunoraWorkflow from "@lunora/workflow/do";
815
1004
  * import { compileAgentWorkflow } from "@lunora/agent";
816
1005
  * import { support } from "../agents.js";
817
1006
  *
818
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
819
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
1007
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1008
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
820
1009
  * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
821
1010
  * }
822
1011
  * }
@@ -829,4 +1018,4 @@ declare class VoiceSessionDO {
829
1018
  declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
830
1019
  paths?: AgentFunctionPaths;
831
1020
  }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
832
- export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
1021
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-DNAt-pGz.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-CJCTyAQG.mjs";import{codeTool as p}from"./packem_shared/codeTool-DYJVy-bH.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-B1IfI7ro.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CKhzzmys.mjs";import{functionTool as D}from"./packem_shared/functionTool-CWHhkYqd.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BUVImo85.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-18G7zpFo.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-BXx-tSCe.mjs";import{browserTool as j,containerTool as q,fsTool as z}from"./sandbox.mjs";import{defineSkill as Q,isSkillDefinition as Y}from"./packem_shared/defineSkill-DfJxCwfZ.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-CTaBSdXk.mjs";import{runVoiceTurn as oe}from"./packem_shared/runVoiceTurn-PkMsfG_v.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-C4xqSw82.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,j as browserTool,k as buildModelMessages,p as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,q as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,Q as defineSkill,z as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
1
+ import{r,s as t}from"./packem_shared/agent-loop-ByDqRJo7.mjs";import{collectAgenticMemoryTools as n,toSearchResults as l}from"./packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-CA7Sha2i.mjs";import{codeTool as p}from"./packem_shared/codeTool-Hm_Af6t4.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-CjdW-jip.mjs";import{defineAgent as g,defineAgentTool as u,isAgentDefinition as S}from"./packem_shared/defineAgent-D4eUl6YE.mjs";import{functionTool as N}from"./packem_shared/functionTool-C95ns65V.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as U}from"./packem_shared/createAgentGenerate-DSLXAeY2.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as L}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as q,toFunctionReference as y}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as W,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{SecretUnavailableError as Z,requestSecretTool as $,withSecret as ee}from"./packem_shared/SecretUnavailableError-BCp40Leh.mjs";import{defineSkill as re,isSkillDefinition as te}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ne}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as fe}from"./packem_shared/VoiceSessionDO-BIfcyunp.mjs";import{r as ie}from"./packem_shared/voice-turn-DBWkPcQH.mjs";import{webSearchTool as me}from"./packem_shared/webSearchTool-BobmV4cD.mjs";import{default as xe}from"./packem_shared/compileAgentWorkflow-BkVDrDvM.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,q as SANDBOX_MODULE,Z as SecretUnavailableError,fe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,W as browserTool,L as buildModelMessages,p as codeTool,n as collectAgenticMemoryTools,xe as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,g as defineAgent,u as defineAgentTool,re as defineSkill,Q as fsTool,N as functionTool,S as isAgentDefinition,te as isSkillDefinition,F as jsCodeTool,h as mcpTools,$ as requestSecretTool,U as resolveAgentModel,r as runAgentLoop,ie as runVoiceTurn,t as splitForCompaction,y as toFunctionReference,l as toSearchResults,V as voiceBindingName,H as voiceClassName,me as webSearchTool,ee as withSecret,ne as wrapUntrusted};
package/dist/naming.d.mts CHANGED
@@ -1,13 +1,9 @@
1
1
  /**
2
- * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
2
+ * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
3
+ * and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
3
4
  * @experimental
4
5
  */
5
6
  declare const agentClassName: (exportName: string) => string;
6
- /**
7
- * `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
8
- * @experimental
9
- */
10
- declare const agentBindingName: (exportName: string) => string;
11
7
  /**
12
8
  * `supportBot` → `agent-support-bot` — the default deployed workflow name.
13
9
  * @experimental
@@ -27,4 +23,16 @@ declare const voiceClassName: (exportName: string) => string;
27
23
  * @experimental
28
24
  */
29
25
  declare const voiceBindingName: (exportName: string) => string;
30
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
26
+ /**
27
+ * Every runtime function `agentComponent()` registers, with its visibility —
28
+ * `"internal"` for the ones the durable loop dispatches by path, `"public"` for
29
+ * the client-facing queries and mutations.
30
+ *
31
+ * A static table so codegen can auto-register the functions without importing
32
+ * `@lunora/agent/component`, whose module graph (`@lunora/server`, the shard
33
+ * engine, drizzle, hono) every codegen process would otherwise load, agents or
34
+ * not. `__tests__/component.test.ts` fails when it drifts from the component.
35
+ * @experimental
36
+ */
37
+ declare const AGENT_RUNTIME_FUNCTIONS: Readonly<Record<string, "internal" | "public">>;
38
+ export { AGENT_RUNTIME_FUNCTIONS, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
package/dist/naming.d.ts CHANGED
@@ -1,13 +1,9 @@
1
1
  /**
2
- * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
2
+ * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
3
+ * and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
3
4
  * @experimental
4
5
  */
5
6
  declare const agentClassName: (exportName: string) => string;
6
- /**
7
- * `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
8
- * @experimental
9
- */
10
- declare const agentBindingName: (exportName: string) => string;
11
7
  /**
12
8
  * `supportBot` → `agent-support-bot` — the default deployed workflow name.
13
9
  * @experimental
@@ -27,4 +23,16 @@ declare const voiceClassName: (exportName: string) => string;
27
23
  * @experimental
28
24
  */
29
25
  declare const voiceBindingName: (exportName: string) => string;
30
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
26
+ /**
27
+ * Every runtime function `agentComponent()` registers, with its visibility —
28
+ * `"internal"` for the ones the durable loop dispatches by path, `"public"` for
29
+ * the client-facing queries and mutations.
30
+ *
31
+ * A static table so codegen can auto-register the functions without importing
32
+ * `@lunora/agent/component`, whose module graph (`@lunora/server`, the shard
33
+ * engine, drizzle, hono) every codegen process would otherwise load, agents or
34
+ * not. `__tests__/component.test.ts` fails when it drifts from the component.
35
+ * @experimental
36
+ */
37
+ declare const AGENT_RUNTIME_FUNCTIONS: Readonly<Record<string, "internal" | "public">>;
38
+ export { AGENT_RUNTIME_FUNCTIONS, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
package/dist/naming.mjs CHANGED
@@ -1 +1 @@
1
- const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,l=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,r=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{t as agentBindingName,s as agentClassName,l as agentDefaultName,r as voiceBindingName,o as voiceClassName};
1
+ const t=/([a-z0-9])([A-Z])/gu,a=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,n=e=>`agent-${e.replaceAll(t,"$1-$2").toLowerCase()}`,l=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,r=e=>`VOICE_${e.replaceAll(t,"$1_$2").toUpperCase()}`,i={agentAppendMessage:"internal",agentApprovalGranted:"internal",agentApprovalGrants:"public",agentCompleteRun:"internal",agentDeclineSecret:"public",agentDeleteMessage:"internal",agentDiscardSecret:"internal",agentEnsureThread:"internal",agentEpisodeRecall:"internal",agentEpisodeUpsert:"internal",agentGraphTraverse:"internal",agentGraphUpsert:"internal",agentHistory:"internal",agentMessages:"public",agentOpenSecretRequest:"internal",agentPatchThread:"internal",agentPendingApprovals:"public",agentResolveApproval:"public",agentRevokeApprovalGrant:"public",agentRun:"public",agentSecretRequests:"public",agentSetState:"internal",agentSettleSecretRequest:"internal",agentState:"public",agentSupplySecret:"public",agentTakeSecret:"internal",agentThread:"public"};export{i as AGENT_RUNTIME_FUNCTIONS,a as agentClassName,n as agentDefaultName,r as voiceBindingName,l as voiceClassName};
@@ -0,0 +1 @@
1
+ const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,approvalGranted:`${e}:agentApprovalGranted`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,history:`${e}:agentHistory`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`,takeSecret:`${e}:agentTakeSecret`,discardSecret:`${e}:agentDiscardSecret`,openSecretRequest:`${e}:agentOpenSecretRequest`,settleSecretRequest:`${e}:agentSettleSecretRequest`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
@@ -0,0 +1 @@
1
+ import{LunoraError as y,isLunoraError as H}from"@lunora/errors";const g=t=>{try{return t(),!0}catch{return!1}},V=new Set([Object.prototype,Function.prototype]),A=(t,e,r)=>{let n;for(let o=t;o!==null&&!V.has(o);o=Object.getPrototypeOf(o)){const a=Object.getOwnPropertyDescriptor(o,e)?.[r];typeof a=="function"&&(n=a)}return n},i=(t,e)=>A(t,e,"get"),k=A(Date.prototype,"getTime","value"),z=i(Map.prototype,"size"),q=i(Set.prototype,"size"),Y=i(ArrayBuffer.prototype,"byteLength"),m=typeof URL=="function"?i(URL.prototype,"href"):void 0,L=typeof URL=="function"?URL.prototype:void 0,Q=m!==void 0&&Function.prototype.toString.call(m).includes("[native code]"),D=A(Error,"isError","value"),P=Error.prototype,X=(t,e)=>typeof D=="function"?D(t):e!==null&&(e===P||P.isPrototypeOf(e)),Z=A(Map.prototype,"forEach","value"),tt=A(Set.prototype,"forEach","value"),I=Object.getPrototypeOf(Uint8Array.prototype),j={data:{buffer:i(DataView.prototype,"buffer"),byteLength:i(DataView.prototype,"byteLength"),byteOffset:i(DataView.prototype,"byteOffset")},typed:{buffer:i(I,"buffer"),byteLength:i(I,"byteLength"),byteOffset:i(I,"byteOffset")}},et=t=>Reflect.apply(k,t,[]),rt=t=>Reflect.apply(m,t,[]),nt=t=>{const e=[];return Reflect.apply(Z,t,[(r,n)=>e.push([n,r])]),e},ot=t=>{const e=[];return Reflect.apply(tt,t,[r=>e.push(r)]),e},at=t=>{const e=g(()=>Reflect.apply(j.typed.buffer,t,[]))?j.typed:j.data;return new Uint8Array(Reflect.apply(e.buffer,t,[]),Reflect.apply(e.byteOffset,t,[]),Reflect.apply(e.byteLength,t,[]))},st=t=>{if(Array.isArray(t))return"array";const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype?"plain":g(()=>Reflect.apply(k,t,[]))?"builtin-date":g(()=>Reflect.apply(z,t,[]))?"builtin-map":g(()=>Reflect.apply(q,t,[]))?"builtin-set":g(()=>Reflect.apply(Y,t,[]))?"builtin-array-buffer":ArrayBuffer.isView(t)?"builtin-view":X(t,e)?"builtin-error":m!==void 0&&(Q||L!==void 0&&e!==null&&(e===L||L.isPrototypeOf(e)))&&g(()=>Reflect.apply(m,t,[]))?"builtin-url":"other"},E=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},ct=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},s="$lunora.wire$",v=64,O=1024,it="__proto__",ut=/^-?\d+$/,x={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},B={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},U=(t,e,r)=>{e===it?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r},lt=t=>{const e=t.toString();if(e.length>O)throw new RangeError(`wire-codec: over-long bigint (max ${String(O)} digits)`);return[s,"bigint",e]},ft=t=>Number.isNaN(t)?[s,"nan"]:t===1/0?[s,"inf"]:t===-1/0?[s,"-inf"]:t,pt=(t,e)=>{const r=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),n=t,o=[s,"error",String(n.name),String(n.message),r];return t.cause!==void 0&&o.push(e(t.cause)),o},yt=t=>{const e=t.constructor.name,r=at(t);return e==="Uint8Array"?[s,"bytes",E(r)]:[s,"bytes",E(r),e]},dt=(t,e,r)=>{switch(e){case"builtin-array-buffer":return[s,"bytes",E(new Uint8Array(t)),"ArrayBuffer"];case"builtin-date":return[s,"date",r(et(t))];case"builtin-error":return pt(t,r);case"builtin-map":return[s,"map",nt(t).map(([n,o])=>[r(n),r(o)])];case"builtin-set":return[s,"set",ot(t).map(n=>r(n))];case"builtin-url":return[s,"url",rt(t)];case"builtin-view":return yt(t);default:return}},bt=(t,e)=>{const r=t.map(n=>S(n,e));return r.length>0&&r[0]===s?[s,"arr",r]:r},ht=(t,e)=>{const r={};for(const n of Object.keys(t)){const o=t[n];o!==void 0&&U(r,n,S(o,e))}return r},S=(t,e=0)=>{if(e>v)throw new RangeError(`wire-codec: value nesting exceeds the ${String(v)}-level limit`);if(t===void 0)return[s,"undefined"];if(t===null)return t;if(typeof t=="bigint")return lt(t);if(typeof t=="number")return ft(t);if(typeof t!="object")return t;const r=st(t);if(r==="array")return bt(t,e+1);if(r==="plain")return ht(t,e+1);const n=dt(t,r,a=>S(a,e+1));if(n!==void 0)return n;const o=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${o} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)},gt=t=>{const e=t[2];if(typeof e!="string"||e.length>O||!ut.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(O)} digits)`);return BigInt(e)},wt=(t,e)=>{const r=e(t[2]);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)},mt=(t,e)=>{const r=t[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[e(n[0]),e(n[1])]}))},At=t=>{const e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(e)},$t=(t,e)=>{const r=t[2],n=t[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const o=(Object.hasOwn(B,r)?B[r]:void 0)??Error,a=new o(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const c=e(t[4]);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const[w,p]of Object.entries(c))U(a,w,p);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},Et=t=>{const e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const r=ct(e);if(E(r)!==e)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const n=t[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:new Uint8Array(r).buffer;const o=Object.hasOwn(x,n)?x[n]:void 0;return o?new o(new Uint8Array(r).buffer):r},vt=(t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(r=>e(r));case"bigint":return gt(t);case"bytes":return Et(t);case"date":return wt(t,e);case"error":return $t(t,e);case"inf":return 1/0;case"map":return mt(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(r=>e(r)));case"undefined":return;case"url":return At(t);default:return t.map(r=>e(r))}},Ot=(t,e)=>{const r={};for(const n of Object.keys(t))U(r,n,R(t[n],e));return r},R=(t,e=0)=>{if(e>v)throw new RangeError(`wire-codec: value nesting exceeds the ${String(v)}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const r=t;return r[0]===s?vt(r,n=>R(n,e+1)):r.map(n=>R(n,e+1))}return Ot(t,e+1)},Rt=(t,e,r)=>{try{return S(r)}catch(n){throw new TypeError(`${t}: cannot encode args for '${e}' — ${n instanceof Error?n.message:String(n)}`,n instanceof Error?{cause:n}:void 0)}},St="DISPATCH_IN_PROGRESS",Nt="x-lunora-dispatch-declined",Tt=(t,e,r)=>{if(e===void 0)return{dispose:()=>{},signal:t};const n=new AbortController,o=setTimeout(()=>{n.abort(r())},e);return{dispose:()=>{clearTimeout(o)},signal:n.signal}},f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",C=t=>{let e="",r=0;const n=t.length-2;for(;r<n;r+=3){const a=t[r]<<16|t[r+1]<<8|t[r+2];e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)+f.charAt(a>>6&63)+f.charAt(a&63)}const o=t.length-r;if(o===1){const a=t[r]<<16;e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)}else if(o===2){const a=t[r]<<16|t[r+1]<<8;e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)+f.charAt(a>>6&63)}return e};new TextDecoder;const F=new TextEncoder,M="=",Lt=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},It=t=>C(F.encode(t)),jt=t=>It(JSON.stringify(t)),Ut=t=>!t.startsWith(M)&&Lt(t)?t:`${M}${C(F.encode(t))}`,_t="/_lunora/scheduler/dispatch",Dt=3e4,Pt=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},J=Symbol("lunoraDispatchFailure"),xt=Symbol("lunoraDispatchDecline"),Bt=Symbol("lunoraDispatchMessageId"),G=(t,e)=>(e!==void 0&&Object.defineProperty(t,Bt,{value:e}),t),Mt=(t,e)=>(Object.defineProperty(t,J,{value:!0}),G(t,e)),kt=(t,e,r,n)=>{const{status:o}=e;try{const a=JSON.parse(r)?.error;if(typeof a=="object"&&a!==null&&typeof a.code=="string"){const{code:c,data:w,message:p}=a,d=Mt(new y(c,typeof p=="string"?p:void 0,{data:w,status:o}),n);return e.headers.get(Nt)==="1"&&Object.defineProperty(d,xt,{value:!0}),d}}catch{}return G(new y("INTERNAL",`${t}: function dispatch failed (${String(o)}): ${r}`,{status:o}),n)},Ct=new Set([400,403,404,422]),Ft=new Set([St,"DISPATCH_UNAUTHENTICATED"]),Jt=t=>H(t)&&t[J]===!0,Wt=t=>Jt(t)&&Ct.has(t.status)&&!Ft.has(t.code),Gt=(t,e,r)=>new y("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(r)}ms`,{status:503}),Ht=t=>{const{label:e}=t,r=globalThis.fetch,n=t.fetchImpl??(typeof r=="function"?r.bind(globalThis):void 0);return async(o,a,c={})=>{if(typeof n!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const w=()=>t.argsAlreadyEncoded===!0?a??{}:Rt(e,o.__lunoraRef,a??{}),p=t.env.LUNORA_ORIGIN_URL;if(typeof p!="string"||p.length===0)throw new y("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const d=t.env.LUNORA_ADMIN_TOKEN;if(typeof d!="string"||d.length===0)throw new y("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const K=`${Pt(p)}${_t}`,$={authorization:`Bearer ${d}`,"content-type":"application/json"};t.traceparent!==void 0&&t.traceparent.length>0&&($.traceparent=t.traceparent),t.identity?.userId!==void 0&&($["x-lunora-userid"]=Ut(t.identity.userId)),t.identity?.claims!==void 0&&($["x-lunora-identity"]=jt(t.identity.claims));const N=c.timeoutMs??Dt,_=Tt(void 0,N,()=>new DOMException(`dispatch timed out after ${String(N)}ms`,"TimeoutError")),T=l=>{throw l instanceof Error&&l.name==="TimeoutError"?Gt(e,o.__lunoraRef,N):l};let u;try{try{u=await n(K,{body:JSON.stringify({args:w(),functionPath:o.__lunoraRef,id:c.dedupId,shardKey:c.shardKey}),headers:$,method:"POST",signal:_.signal})}catch(h){return T(h)}if(!u.ok){let h;try{h=await u.text()}catch(W){return T(W)}throw kt(e,u,h,c.messageId)}let l;try{l=await u.text()}catch(h){return T(h)}if(l.length===0)return;let b;try{b=JSON.parse(l)}catch{throw new y("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(u.status)}): ${l}`,{status:u.status})}if(b===null||typeof b!="object"||Array.isArray(b)||!("result"in b))throw new y("INTERNAL",`${e}: function dispatch returned a JSON body that is not a { result } envelope (${String(u.status)}): ${l}`,{status:u.status});return R(b.result)}finally{_.dispose()}}};export{Ht as a,Wt as e};
@@ -0,0 +1 @@
1
+ import{jsonSchema as y}from"@ai-sdk/provider-utils";import{LunoraError as s}from"@lunora/errors";import{toFunctionReference as l,DEFAULT_AGENT_FUNCTION_PATHS as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const p=200,N=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,p).join("")};class g extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const T=e=>{if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new s("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:y({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},w=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,f=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},h=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,w)}catch{return!1}return f(t).some(a=>n.includes(a))},E="[redacted]",u="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of f(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(E);return n},m=(e,t,n=new Set)=>{if(!(e instanceof Error))return new s("INTERNAL",u);if(n.has(e))return e;n.add(e);try{e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const a=e;for(const o of Object.getOwnPropertyNames(e)){if(o==="message"||o==="stack")continue;const r=a[o];if(r instanceof Error){const i=m(r,t,n);i!==r&&(a[o]=i)}else h(r,t)&&(a[o]=JSON.parse(c(JSON.stringify(r),t)))}}catch{return new s("INTERNAL",u)}return e},I=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(l(d.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(i){throw m(i,o)}return h(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new g;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(l(d.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new s("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{g as SecretUnavailableError,T as requestSecretTool,N as secretLabelOf,I as withSecret};
@@ -0,0 +1 @@
1
+ import{createAi as A}from"@lunora/ai/create";import{a as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-DBWkPcQH.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-DSLXAeY2.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),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:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&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))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}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 r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
@@ -0,0 +1,2 @@
1
+ import{jsonSchema as i}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
2
+ `);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("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 c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=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(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
@@ -0,0 +1 @@
1
+ import{createAi as t}from"@lunora/ai/create";const i=r=>{const o=r.AI;return o?t({binding:o,env:r}):void 0};export{i as r};
@@ -0,0 +1,3 @@
1
+ import{usageStatus as pt}from"@lunora/ai/create";import{e as mt}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as yt}from"@lunora/platform";import{r as Z}from"./workflow-binding-Dm9hBzx_.mjs";import{e as X,d as ft,S as Y}from"./component-shared-DdXFbng-.mjs";import{usageOfFailedTurn as ht,resolveAgentModel as wt}from"./createAgentGenerate-DSLXAeY2.mjs";import{buildModelMessages as W}from"./buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as tt}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"./positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as gt,secretLabelOf as Tt}from"./SecretUnavailableError-BCp40Leh.mjs";import{combineTelemetry as St}from"./combineTelemetry-DgE9W9G8.mjs";import{c as z}from"./tool-output-Cmk3JWMG.mjs";const $t=200,Et=e=>{const t=e.findIndex(n=>n.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=$t;for(;;){const n=await e(t),o=Et(n);if(o.length>0||n.length<t)return o;t*=2}},It=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",B=e=>e.memorySources?e.memorySources:e.memory&&It(e.memory)?[{key:"default",...e.memory}]:[],xt=e=>B(e).find(t=>t.kind==="graph"),Ct=e=>B(e).find(t=>t.kind==="episodic"),I=(e,t)=>t==="default"?e:`${e}:${t}`,kt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:St(...n)},Mt=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,n)=>{const o=kt(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},i=Date.now();await o.onToolExecutionStart?.(s);let c;const d=()=>(c??=n(),c);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const u=await d();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:u,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),u}catch(u){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},Nt=8,At=e=>vt(e)?e:0,et=e=>e===void 0?"null":JSON.stringify(e),Ot=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},_t=e=>e===void 0?[]:[e].flat(),qt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),Ut=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??pt(e),bt=(e,t)=>e===t?e:"partial",ot=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const n={status:bt(j(e),j(t))};for(const o of Ut)(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},Dt=async(e,t,n,o,a,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:n.do(o,async()=>await s()?!1:i===!0||i(t,a))},Ft="WorkflowTimeoutError",nt=e=>e instanceof Error&&e.name===Ft,J=4320*60*1e3,Pt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Gt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,at=e=>{if(e===void 0)return J;if(typeof e=="number")return Math.min(e,X);const t=Gt.exec(e);return t===null?J:Math.min(Number(t[1])*Pt[t[2]],X)},Lt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:i,step:c}=e,d=at(n.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const u=await c.waitForEvent(`approval:${t.id}`,{timeout:d,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!nt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},jt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Wt=(e,t)=>`${String(e)}:${t}`,Bt=async(e,t,n,o,a)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,T=`${c}:secret:${a}`,y=Math.min(at(s.approvalTimeout),yt-Y);await m.do(`secret:request:${a}`,async()=>{await r(d,{consumerTool:n,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:o,threadKey:h,toolCallId:a,toolName:t.name})}),await m.do(`secret:await:${a}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${o}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${a}`,{timeout:y+Y,type:`agent-secret:${a}`}).catch(f=>{if(!nt(f))throw f});const{status:v}=await m.do(`secret:settle:${a}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:a}));return await i(T),await u({ifInstanceId:c,status:"running"}),v},U="lunoraToolOutcome",Ht=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Vt=async(e,t,n,o)=>{const{instanceId:a,persist:s}=e,i=Wt(o,t.id),c=`${a}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=Tt(t.input);if(u===void 0){await s({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await s({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Bt(e,t,n,u,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${jt[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Xt=async(e,t,n)=>{const{agent:o,approvalGrantedRef:a,depth:s,env:i,exports:c,getState:d,instanceId:u,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,step:T,threadKey:y,tools:v}=e,f=`tool:${t.name}:${t.id}`,$=v[t.name],E=`${u}:tool:${t.id}`;if(!$){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if($.secretRequest!==void 0){await Vt(e,t,$.secretRequest.consumer,n);return}const b={depth:s,env:i,exports:c,getState:d,idempotencyKey:f,instanceId:u,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:y,toolCallId:t.id})},run:m,setState:h,step:T,threadKey:y,toolCallId:t.id},D={depth:s,env:i,getState:d,idempotencyKey:f,instanceId:u,run:m,threadKey:y,toolCallId:t.id},F=`tool:approval-gate:${t.id}`;let M,K;const P=async()=>await m(a,{key:y,toolName:t.name})===!0;if(await Dt($,t.input,T,F,D,P)){const{decision:S,note:C,scope:G}=await Lt(e,t);if(S==="reject"){const O=C===void 0?"":` Reason: ${C}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${O}`,messageKey:E,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}M="approved",K=G}const A={...M===void 0?{}:{status:M},...K===void 0?{}:{approvalScope:K}},N=Ht(await T.do(f,async()=>{try{const S=()=>Promise.resolve($.execute(t.input,b)),C=await Kt(o.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:C}}}catch(S){if(mt(S)||S instanceof gt)return{[U]:{failed:S.message}};throw S}}));if("failed"in N){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${N.failed}`),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name});return}const x=N.ok;await l({content:z(typeof x=="string"?x:et(x)),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name})},Yt=(e,t,n)=>{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:wt(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},st=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},zt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=st(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:a,messages:W({history:s.older}),model:n.compaction?.model??n.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Jt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Qt=async e=>{const{agent:t,compact:n,env:o,historyRef:a,instanceId:s,patchThread:i,run:c,threadKey:d}=e,u=Jt(t.compaction),p=await c(a,{configKey:u,key:d}),{messages:r,summary:l}=p,m=st(r,t.compaction);if(m===void 0||n===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:v}=p;return v===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:v.throughSeq}).catch(f=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,f)}),{history:r.filter(f=>f.seq>v.throughSeq),summary:v.summary})};let T;try{T=await n({env:o,messages:W({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(v){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,v),h()}if(T.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(v=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,v)}),{history:m.recent,summary:T}},Zt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Qt(e):await zt(e,await Rt(async f=>await p(c,{key:m,limit:f})));let y={activeTools:o.activeTools,messages:W({history:h,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=Yt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:n}),a));const v={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&u?l(v,f=>{u({text:f,threadKey:m,turn:t})}):s(v)})},Q=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.onStepFinish?.(t),!0))},te=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}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ee=e=>ft({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),oe=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,i=I("memory:retrieve",e.key),c=await n.do(i,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return H(c)},ne=async(e,t,n,o,a,s)=>{if(n===void 0)return;const i=I("memory:traverse",e.key),c=await a.do(i,async()=>s(o,{owner:n,query:t,...ee(e.graph)}));return H(c)},ae=async(e,t,n,o,a)=>{if(t===void 0)return;const s=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await o.do(s,async()=>a(n,i));return H(c)},se=async(e,t)=>e.kind==="episodic"?ae(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?ne(e,t.input,t.owner,t.graphTraverse,t.step,t.run):oe(e,t.input,t.step,t.run),re=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},ie=async(e,t,n,o,a,s)=>{const i=re(B(e));if(i.length===0)return;const c=g(o.graphTraverse),d=g(o.episodeRecall),u=[];for(const p of i){const r=await se(p,{episodeRecall:d,graphTraverse:c,input:t,owner:n,run:s,step:a});r!==void 0&&u.push(r)}return u.length>0?u.join(`
2
+
3
+ `):void 0},ce=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const r=xt(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(I("memory:extract",r.key),async()=>o(l));await u(g(d.graphUpsert),{...m,messageKey:`${i}:${I("extract",r.key)}`,owner:c})}catch{}},ue=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p,threadKey:r}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const l=Ct(t);if(l!==void 0)try{const m={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(I("memory:episode",l.key),async()=>o(m));await u(g(d.episodeUpsert),{messageKey:`${i}:${I("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},de=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},le="12 hours",pe=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:le,type:`agent-dequeue:${t}:${n}`})},me=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},ye=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},fe=async(e,t,n,o,a)=>{const{instanceId:s,persist:i}=e,c=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const d=n.output!==void 0&&n.text.length===0?et(n.output):n.text;return await i({content:d,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await Q(e,{text:n.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await i({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const d of n.toolCalls)await Xt(e,d,t);if(await Q(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...c}),o.push(te(n)),a.length>0&&await qt(a,o))return"stopCondition"},he=async(e,t,n,o)=>{const a=[];let s,i=!1,c=0;for(let d=0;d<t;d+=1){const u=await Zt(e,d,a);o.value=ot(o.value,u.usage),c=d+1;const p=await fe(e,d,u,a,n);if(p==="stopCondition"){i=!0;break}if(p!==void 0){s=p.final;break}}return{final:s,stoppedByCondition:i,turnsRun:c}},Ke=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:i,extractGraph:c,generate:d,instanceId:u,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:T}=e,y=t.maxTurns??Nt,v=_t(t.stopWhen),f=g(l.appendMessage),$=g(l.approvalGranted),E=g(l.openSecretRequest),V=g(l.settleSecretRequest),b=g(l.completeRun),D=g(l.ensureThread),F=g(l.listMessages),M=g(l.history),K=g(l.deleteMessage),P=g(l.patchThread),A=g(l.setState),N=g(l.state),x=async w=>{await m(f,{threadKey:r.threadKey,...w})},S=async w=>{await m(P,{key:r.threadKey,...w})},C=async w=>{await m(K,{messageKey:w,threadKey:r.threadKey})},G=async()=>{await x({content:r.input,messageKey:`${u}:user`,role:"user"})},O={dispatched:!1},_=async w=>{O.dispatched=!0;const q=await m(b,{instanceId:u,key:r.threadKey,...w});q?.dequeued!==void 0&&await me({env:o,exportName:a,exports:s,step:h},r.threadKey,q.dequeued)},rt=async()=>await m(N,{key:r.threadKey}),it=async w=>{await m(A,{key:r.threadKey,state:w})},L=await m(D,{agent:a,instanceId:u,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});L?.outcome==="replaced"&&await de({env:o,exports:s},a,L.priorInstanceId);const ct=await ie(t,r.input,r.owner,l,h,m),ut=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,dt={agent:t,approvalGrantedRef:$,openSecretRef:E,settleSecretRef:V,compact:n,depth:At(r.depth),env:o,exports:s,generate:d,getState:rt,historyRef:M,instanceId:u,instructions:ut,listMessages:F,memoryContext:ct,onTokenDelta:p,owner:r.owner,deleteMessage:C,patchThread:S,persist:x,run:m,setState:it,step:h,streamGenerate:T,threadKey:r.threadKey,tools:t.tools??{}},k={value:void 0};try{L?.outcome==="queued"&&await pe(h,r.threadKey,u),await G();const{final:w,stoppedByCondition:q,turnsRun:lt}=await he(dt,y,v,k),R=k.value===void 0?{}:{usage:k.value};return await ce({agent:t,env:o,extractGraph:c,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h}),await ue({agent:t,env:o,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await ye(t,{env:o,params:r,step:h},{...w,...R}),await _({status:"idle",...R}),{...w,...R}):q?(await _({status:"idle",...R}),{stopped:"stopCondition",turns:lt,...R}):(await _({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...R}),{stopped:"maxTurns",turns:y,...R})}catch(w){throw O.dispatched||(k.value=ot(k.value,ht(w)),await Ot(_,w,k.value)),w}finally{await Mt(t.telemetry)}};export{at as a,ot as b,zt as c,It as i,Ke as r,st as s};
@@ -0,0 +1 @@
1
+ import{jsonSchema as I}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as L}from"@lunora/workflow";import{f as S}from"./fnv1a-BNN96GYb.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${S(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!L(d))throw d;l=await i.get(g)}const{output:v,status:u}=await D(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(U(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return j(E)};return{description:t.description,execute:T,inputSchema:I({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
@@ -0,0 +1 @@
1
+ import{usageStatus as _}from"@lunora/ai/create";import{r as s,d as b,t as x,f as T,s as C,c as v}from"./common-DBc9y7Np.mjs";import{c as L}from"./in-flight-calls-C9QGq8uH.mjs";const E=(l,c)=>typeof l=="string"&&l.length>0?l:c,O={cacheReadTokens:"prompt_cached_tokens",cacheWriteTokens:"prompt_cache_creation_tokens",inputTokens:"prompt_tokens",outputTokens:"completion_tokens",reasoningTokens:"completion_reasoning_tokens",totalTokens:"tokens"},M=l=>{const c={};for(const[u,p]of Object.entries(O)){const f=l[u];f!==void 0&&(c[p]=f)}return c},P=l=>{const{functionId:c,logger:u,recordInputs:p=!1,recordOutputs:f=!1}=l,a=L((e,t,r,n)=>{const o={},d=C(s(n,"usage")??s(e.result,"usage")),y=_(d);if(o.metadata={"lunora.usage.status":y},d!==void 0&&(o.metrics=M(d)),t||(o.error=r??"the model call failed"),f){const h=v(s(n,"content")??s(e.result,"content"));h!==void 0&&(o.output=h)}Object.keys(o).length>0&&e.span.log(o),e.finish()},e=>{e.finish()}),k=(e,t,r)=>{const n=s(e,"callId");if(typeof n!="string")return;let o=r;t instanceof Error?o=t.message:typeof t=="string"&&t.length>0&&(o=t),a.close(n,!1,o,T(t))};return{executeLanguageModelCall:e=>{const{callId:t,execute:r}=e;let n,o;const d=new Promise((i,m)=>{n=i,o=m});let y;const h=new Promise(i=>{y=i});return Promise.resolve(u.traced(async i=>{a.open(t,()=>({finish:y,result:void 0,span:i})),p&&i.log({input:s(e,"messages"),model:s(e,"modelId")});let m;try{m=await r()}catch(g){a.close(t,!1,g instanceof Error?g.message:String(g),T(g)),o(g);return}const I=a.get(t);I!==void 0&&(I.result=m),n(m),await h},{name:E(c,"language_model_call"),type:"llm"})).catch(()=>{}),d},executeTool:e=>{const t=s(s(e,"toolCall"),"toolName");return u.traced(async r=>{p&&r.log({input:x(e),tool:t});const n=await e.execute();return f&&r.log({output:n}),n},{name:E(t,"execute_tool"),type:"tool"})},onAbort:e=>{k(e,s(e,"reason"),"aborted")},onEnd:e=>{a.fromLifecycle(e)},onError:e=>{u.traced(t=>{t.log({error:b(s(e,"error")??e)})},{name:"error",type:"error"}),k(e,s(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof s(e,"callId")=="string"&&a.fromLifecycle(e)},onStepEnd:e=>{a.fromLifecycle(e)}}};export{P as braintrustTelemetry};
@@ -0,0 +1 @@
1
+ const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),r=`may not contain the reserved workflow branch-marker key ("${e}")`;export{r as B,o as h};