@lunora/agent 1.0.0-alpha.276 → 1.0.0-alpha.278

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 (69) hide show
  1. package/README.md +1 -2
  2. package/dist/channels.d.mts +2 -2
  3. package/dist/channels.d.ts +2 -2
  4. package/dist/channels.mjs +1 -1
  5. package/dist/component.mjs +1 -1
  6. package/dist/core.d.mts +204 -0
  7. package/dist/core.d.ts +204 -0
  8. package/dist/core.mjs +1 -0
  9. package/dist/inbound.d.mts +4 -4
  10. package/dist/inbound.d.ts +4 -4
  11. package/dist/inbound.mjs +1 -1
  12. package/dist/index.d.mts +7 -167
  13. package/dist/index.d.ts +7 -167
  14. package/dist/index.mjs +1 -1
  15. package/dist/packem_chunks/createAgentGenerate.mjs +3 -0
  16. package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
  17. package/dist/packem_chunks/resolve-run.mjs +1 -0
  18. package/dist/packem_chunks/runAgentLoop.mjs +3 -0
  19. package/dist/packem_shared/SecretUnavailableError-DOy2M4Ak.mjs +1 -0
  20. package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
  21. package/dist/packem_shared/{adaptMcpResult-DOud9k_Q.mjs → adaptMcpResult-CA-3ovJd.mjs} +1 -1
  22. package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
  23. package/dist/packem_shared/app-call-options-BE0CQ6Qg.mjs +1 -0
  24. package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +1 -0
  25. package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs +1 -0
  26. package/dist/packem_shared/compileAgentWorkflow-yZB8fbYc.mjs +1 -0
  27. package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
  28. package/dist/packem_shared/createAgentContext-C8k1y2Ot.mjs +1 -0
  29. package/dist/packem_shared/defineAgent-6Ih7L9E9.mjs +3 -0
  30. package/dist/packem_shared/functionTool-Cf433Hdo.mjs +1 -0
  31. package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
  32. package/dist/packem_shared/{jsCodeTool-Bh4jaeoy.mjs → jsCodeTool-BJB3Fpm2.mjs} +1 -1
  33. package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
  34. package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
  35. package/dist/packem_shared/{normalizeEntityName-Rr5OQxhc.mjs → normalizeEntityName-BiUH5B5W.mjs} +1 -1
  36. package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
  37. package/dist/packem_shared/runVoiceTurn-DPa5UZ45.mjs +1 -0
  38. package/dist/packem_shared/{types.d-vAmttAsE.d.mts → types.d-Bzy_Qah6.d.mts} +81 -2
  39. package/dist/packem_shared/{types.d-vAmttAsE.d.ts → types.d-Bzy_Qah6.d.ts} +81 -2
  40. package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
  41. package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
  42. package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs +1 -0
  43. package/dist/reply.d.mts +1 -1
  44. package/dist/reply.d.ts +1 -1
  45. package/dist/sandbox.d.mts +1 -1
  46. package/dist/sandbox.d.ts +1 -1
  47. package/dist/sandbox.mjs +1 -1
  48. package/dist/skill-markdown.d.mts +1 -1
  49. package/dist/skill-markdown.d.ts +1 -1
  50. package/dist/telemetry/index.mjs +1 -1
  51. package/package.json +5 -1
  52. package/dist/packem_shared/SecretUnavailableError-D8u6pPM6.mjs +0 -1
  53. package/dist/packem_shared/VoiceSessionDO-D4dEV12P.mjs +0 -1
  54. package/dist/packem_shared/agent-loop-C11GY0Yw.mjs +0 -3
  55. package/dist/packem_shared/agentAsTool-ifwGRMR6.mjs +0 -1
  56. package/dist/packem_shared/codeTool-BZkKDqsZ.mjs +0 -1
  57. package/dist/packem_shared/collectAgenticMemoryTools-Dxs7mpo6.mjs +0 -1
  58. package/dist/packem_shared/compileAgentWorkflow-DDQ-_8S0.mjs +0 -1
  59. package/dist/packem_shared/component-shared-DdXFbng-.mjs +0 -1
  60. package/dist/packem_shared/createAgentContext-CjdW-jip.mjs +0 -1
  61. package/dist/packem_shared/createAgentGenerate-CTkL_e0Z.mjs +0 -3
  62. package/dist/packem_shared/defineAgent-BsDM3vh8.mjs +0 -3
  63. package/dist/packem_shared/functionTool-C95ns65V.mjs +0 -1
  64. package/dist/packem_shared/json-schema-CHVg-SsJ.mjs +0 -1
  65. package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +0 -1
  66. package/dist/packem_shared/runAgentLoop-8K0vPhGY.mjs +0 -1
  67. package/dist/packem_shared/runVoiceTurn-C4BAG61O.mjs +0 -1
  68. package/dist/packem_shared/voice-turn-BjkorohD.mjs +0 -1
  69. package/dist/packem_shared/webSearchTool-DUubGqov.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,13 +1,15 @@
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.mjs";
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.mjs";
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 AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.mjs";
2
+ export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-Bzy_Qah6.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
- import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
4
+ export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.mjs";
5
+ import { LanguageModel, ModelMessage } from 'ai';
5
6
  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.mjs";
6
7
  export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
7
8
  import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai/create';
8
- import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
10
10
  import '@lunora/server';
11
+ import '@ai-sdk/provider-utils';
12
+ import '@lunora/workflow';
11
13
  /**
12
14
  * `AgentLoopOptions` is part of the experimental `@lunora/agent` API and may change without a major version bump.
13
15
  * @experimental
@@ -268,109 +270,6 @@ interface CodeToolOptions {
268
270
  * @experimental
269
271
  */
270
272
  declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeToolOptions) => AgentToolDefinition<ToolScript, ToolScriptResult>;
271
- /**
272
- * Build the `ctx.agents` producer surface from the codegen-emitted spec list
273
- * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
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.
277
- *
278
- * `cancel` also needs to write the thread's status, so it dispatches the agent
279
- * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
280
- * and the env-backed `createDispatchRunner` (the same runner the workflow body
281
- * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
282
- * inject a `dispatch` double.
283
- * @experimental
284
- */
285
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
- dispatch?: AgentRunFunction;
287
- exports?: unknown;
288
- }) => Record<string, AgentHandle>;
289
- /**
290
- * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
291
- * (each LLM turn and each tool call a named durable step; thread messages
292
- * persisted idempotently in DO SQLite), invoked from mutations/actions via
293
- * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
294
- * `agents:agentMessages` query.
295
- *
296
- * ```ts
297
- * // lunora/agents.ts
298
- * import { defineAgent, defineAgentTool } from "@lunora/agent";
299
- *
300
- * export const support = defineAgent({
301
- * instructions: "You are a helpful support agent.",
302
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
303
- * tools: {
304
- * getWeather: defineAgentTool({
305
- * description: "Look up the current weather for a city.",
306
- * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
307
- * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
308
- * }),
309
- * },
310
- * });
311
- * ```
312
- *
313
- * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
314
- * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
315
- * @experimental
316
- */
317
- declare const defineAgent: (config: AgentConfig) => AgentDefinition;
318
- /**
319
- * Runtime brand check for a {@link AgentDefinition}.
320
- * @experimental
321
- */
322
- declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
323
- /**
324
- * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
325
- * the loop's durable step (with an `AgentToolContext`) rather than inside the
326
- * model call.
327
- * @experimental
328
- */
329
- declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
330
- /**
331
- * Author-supplied config for {@link functionTool}.
332
- * @experimental
333
- */
334
- interface FunctionToolOptions<Input> {
335
- /** What the tool does — shown to the model (the model decides from it). */
336
- description: string;
337
- /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
338
- inputSchema: FlexibleSchema<Input>;
339
- }
340
- /**
341
- * Expose any Lunora query/mutation/action as an agent tool. The returned
342
- * definition's `execute` dispatches the referenced function through the loop's
343
- * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
344
- * per tool, and the call runs inside the loop's named durable step exactly like
345
- * any other tool.
346
- *
347
- * ```ts
348
- * import { functionTool } from "@lunora/agent";
349
- * import { api } from "./_generated/api";
350
- *
351
- * export const support = defineAgent({
352
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
353
- * tools: {
354
- * lookupOrder: functionTool(api.orders.byId, {
355
- * description: "Look up an order by its id.",
356
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
357
- * }),
358
- * },
359
- * });
360
- * ```
361
- *
362
- * The function reference may be a typed `api.*` reference or a `"module:name"`
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.
371
- * @experimental
372
- */
373
- declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
374
273
  /**
375
274
  * Resolve the configured model against the Worker env (see `AgentModelInput`).
376
275
  * @experimental
@@ -668,42 +567,6 @@ declare const requestSecretTool: (options: {
668
567
  * @experimental
669
568
  */
670
569
  declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
671
- /**
672
- * Declare a reusable skill: a bundle of expertise — an instruction fragment,
673
- * tools, and retrieval `knowledge` — an agent composes in via
674
- * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
675
- * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
676
- * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
677
- * retrieval verbatim.
678
- *
679
- * ```ts
680
- * import { defineSkill, functionTool } from "@lunora/agent";
681
- *
682
- * export const billing = defineSkill({
683
- * name: "billing",
684
- * instructions: "When asked about invoices, cite the invoice id.",
685
- * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
686
- * tools: {
687
- * lookupInvoice: functionTool(api.billing.invoiceById, {
688
- * description: "Look up an invoice by id.",
689
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
690
- * }),
691
- * },
692
- * });
693
- * ```
694
- *
695
- * The merge into the agent's flat namespace (tool-name collisions, instruction
696
- * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
697
- * only validates its own `name`; tool-name validation is deferred to the merge,
698
- * which owns the flat model-facing namespace.
699
- * @experimental
700
- */
701
- declare const defineSkill: (config: SkillConfig) => SkillDefinition;
702
- /**
703
- * Runtime brand check for a {@link SkillDefinition}.
704
- * @experimental
705
- */
706
- declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
707
570
  /**
708
571
  * Wrap untrusted text for inclusion in a prompt. The text sits between a tag
709
572
  * whose id is random per call, so payload text cannot forge the closing tag (it
@@ -995,27 +858,4 @@ interface WebSearchToolInput {
995
858
  * @experimental
996
859
  */
997
860
  declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
998
- /**
999
- * Compile a `defineAgent` definition into the workflow the generated
1000
- * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
1001
- *
1002
- * ```ts
1003
- * import LunoraWorkflow from "@lunora/workflow/do";
1004
- * import { compileAgentWorkflow } from "@lunora/agent";
1005
- * import { support } from "../agents.js";
1006
- *
1007
- * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1008
- * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1009
- * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
1010
- * }
1011
- * }
1012
- * ```
1013
- *
1014
- * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
1015
- * (`run`); the loop supplies determinism (step naming + idempotent persists).
1016
- * @experimental
1017
- */
1018
- declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
1019
- paths?: AgentFunctionPaths;
1020
- }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
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 };
861
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, 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 AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, 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, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,15 @@
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";
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 AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.js";
2
+ export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-Bzy_Qah6.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
- import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
4
+ export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.js";
5
+ import { LanguageModel, ModelMessage } from 'ai';
5
6
  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
7
  export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
7
8
  import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai/create';
8
- import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
10
10
  import '@lunora/server';
11
+ import '@ai-sdk/provider-utils';
12
+ import '@lunora/workflow';
11
13
  /**
12
14
  * `AgentLoopOptions` is part of the experimental `@lunora/agent` API and may change without a major version bump.
13
15
  * @experimental
@@ -268,109 +270,6 @@ interface CodeToolOptions {
268
270
  * @experimental
269
271
  */
270
272
  declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeToolOptions) => AgentToolDefinition<ToolScript, ToolScriptResult>;
271
- /**
272
- * Build the `ctx.agents` producer surface from the codegen-emitted spec list
273
- * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
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.
277
- *
278
- * `cancel` also needs to write the thread's status, so it dispatches the agent
279
- * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
280
- * and the env-backed `createDispatchRunner` (the same runner the workflow body
281
- * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
282
- * inject a `dispatch` double.
283
- * @experimental
284
- */
285
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
- dispatch?: AgentRunFunction;
287
- exports?: unknown;
288
- }) => Record<string, AgentHandle>;
289
- /**
290
- * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
291
- * (each LLM turn and each tool call a named durable step; thread messages
292
- * persisted idempotently in DO SQLite), invoked from mutations/actions via
293
- * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
294
- * `agents:agentMessages` query.
295
- *
296
- * ```ts
297
- * // lunora/agents.ts
298
- * import { defineAgent, defineAgentTool } from "@lunora/agent";
299
- *
300
- * export const support = defineAgent({
301
- * instructions: "You are a helpful support agent.",
302
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
303
- * tools: {
304
- * getWeather: defineAgentTool({
305
- * description: "Look up the current weather for a city.",
306
- * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
307
- * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
308
- * }),
309
- * },
310
- * });
311
- * ```
312
- *
313
- * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
314
- * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
315
- * @experimental
316
- */
317
- declare const defineAgent: (config: AgentConfig) => AgentDefinition;
318
- /**
319
- * Runtime brand check for a {@link AgentDefinition}.
320
- * @experimental
321
- */
322
- declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
323
- /**
324
- * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
325
- * the loop's durable step (with an `AgentToolContext`) rather than inside the
326
- * model call.
327
- * @experimental
328
- */
329
- declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
330
- /**
331
- * Author-supplied config for {@link functionTool}.
332
- * @experimental
333
- */
334
- interface FunctionToolOptions<Input> {
335
- /** What the tool does — shown to the model (the model decides from it). */
336
- description: string;
337
- /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
338
- inputSchema: FlexibleSchema<Input>;
339
- }
340
- /**
341
- * Expose any Lunora query/mutation/action as an agent tool. The returned
342
- * definition's `execute` dispatches the referenced function through the loop's
343
- * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
344
- * per tool, and the call runs inside the loop's named durable step exactly like
345
- * any other tool.
346
- *
347
- * ```ts
348
- * import { functionTool } from "@lunora/agent";
349
- * import { api } from "./_generated/api";
350
- *
351
- * export const support = defineAgent({
352
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
353
- * tools: {
354
- * lookupOrder: functionTool(api.orders.byId, {
355
- * description: "Look up an order by its id.",
356
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
357
- * }),
358
- * },
359
- * });
360
- * ```
361
- *
362
- * The function reference may be a typed `api.*` reference or a `"module:name"`
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.
371
- * @experimental
372
- */
373
- declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
374
273
  /**
375
274
  * Resolve the configured model against the Worker env (see `AgentModelInput`).
376
275
  * @experimental
@@ -668,42 +567,6 @@ declare const requestSecretTool: (options: {
668
567
  * @experimental
669
568
  */
670
569
  declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
671
- /**
672
- * Declare a reusable skill: a bundle of expertise — an instruction fragment,
673
- * tools, and retrieval `knowledge` — an agent composes in via
674
- * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
675
- * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
676
- * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
677
- * retrieval verbatim.
678
- *
679
- * ```ts
680
- * import { defineSkill, functionTool } from "@lunora/agent";
681
- *
682
- * export const billing = defineSkill({
683
- * name: "billing",
684
- * instructions: "When asked about invoices, cite the invoice id.",
685
- * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
686
- * tools: {
687
- * lookupInvoice: functionTool(api.billing.invoiceById, {
688
- * description: "Look up an invoice by id.",
689
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
690
- * }),
691
- * },
692
- * });
693
- * ```
694
- *
695
- * The merge into the agent's flat namespace (tool-name collisions, instruction
696
- * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
697
- * only validates its own `name`; tool-name validation is deferred to the merge,
698
- * which owns the flat model-facing namespace.
699
- * @experimental
700
- */
701
- declare const defineSkill: (config: SkillConfig) => SkillDefinition;
702
- /**
703
- * Runtime brand check for a {@link SkillDefinition}.
704
- * @experimental
705
- */
706
- declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
707
570
  /**
708
571
  * Wrap untrusted text for inclusion in a prompt. The text sits between a tag
709
572
  * whose id is random per call, so payload text cannot forge the closing tag (it
@@ -995,27 +858,4 @@ interface WebSearchToolInput {
995
858
  * @experimental
996
859
  */
997
860
  declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
998
- /**
999
- * Compile a `defineAgent` definition into the workflow the generated
1000
- * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
1001
- *
1002
- * ```ts
1003
- * import LunoraWorkflow from "@lunora/workflow/do";
1004
- * import { compileAgentWorkflow } from "@lunora/agent";
1005
- * import { support } from "../agents.js";
1006
- *
1007
- * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
1008
- * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
1009
- * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
1010
- * }
1011
- * }
1012
- * ```
1013
- *
1014
- * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
1015
- * (`run`); the loop supplies determinism (step naming + idempotent persists).
1016
- * @experimental
1017
- */
1018
- declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
1019
- paths?: AgentFunctionPaths;
1020
- }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
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 };
861
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, 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 AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, 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, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{r,s as t}from"./packem_shared/agent-loop-C11GY0Yw.mjs";import{collectAgenticMemoryTools as n,toSearchResults as l}from"./packem_shared/collectAgenticMemoryTools-Dxs7mpo6.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-ifwGRMR6.mjs";import{codeTool as p}from"./packem_shared/codeTool-BZkKDqsZ.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-BsDM3vh8.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-CTkL_e0Z.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-Bh4jaeoy.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DOud9k_Q.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-D8u6pPM6.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-D4dEV12P.mjs";import{r as ie}from"./packem_shared/voice-turn-BjkorohD.mjs";import{webSearchTool as me}from"./packem_shared/webSearchTool-DUubGqov.mjs";import{default as xe}from"./packem_shared/compileAgentWorkflow-DDQ-_8S0.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};
1
+ import{runAgentLoop as r,splitForCompaction as t}from"./packem_chunks/runAgentLoop.mjs";import{collectAgenticMemoryTools as n,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as m}from"./packem_shared/agentAsTool-BF-7Dnzy.mjs";import{codeTool as s}from"./packem_shared/codeTool-Cn8TuNjk.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-C8k1y2Ot.mjs";import{defineAgent as A,defineAgentTool as g,isAgentDefinition as S}from"./packem_shared/defineAgent-6Ih7L9E9.mjs";import{functionTool as N}from"./packem_shared/functionTool-Cf433Hdo.mjs";import{createAgentGenerate as h,createEpisodeExtract as C,createGraphExtract as M,createStreamGenerate as O,resolveAgentModel as _}from"./packem_chunks/createAgentGenerate.mjs";import{jsCodeTool as U}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";import{default as G}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{adaptMcpResult as v,mcpTools as L}from"./packem_shared/adaptMcpResult-CA-3ovJd.mjs";import{buildModelMessages as B}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V,agentDefaultName as j,voiceBindingName as H,voiceClassName as I}from"./naming.mjs";import{AGENT_MODULE as X,DEFAULT_AGENT_FUNCTION_PATHS as q,SANDBOX_INVOKE_PATH as y,SANDBOX_MODULE as K,toFunctionReference as W}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as J,containerFsTool as Q,containerTool as Y,fsTool as Z}from"./sandbox.mjs";import{default as ee}from"./packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs";import{SecretUnavailableError as re,requestSecretTool as te,withSecret as ae}from"./packem_shared/SecretUnavailableError-DOy2M4Ak.mjs";import{defineSkill as fe,isSkillDefinition as le}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as pe}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as ie}from"./packem_shared/VoiceSessionDO-CdvG2L-D.mjs";import{r as xe}from"./packem_shared/voice-turn-B9omvXoR.mjs";import{webSearchTool as Te}from"./packem_shared/webSearchTool-BzXW0R4r.mjs";import{default as Ae}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{X as AGENT_MODULE,q as DEFAULT_AGENT_FUNCTION_PATHS,y as SANDBOX_INVOKE_PATH,K as SANDBOX_MODULE,re as SecretUnavailableError,ie as VoiceSessionDO,v as adaptMcpResult,m as agentAsTool,V as agentClassName,c as agentComponent,j as agentDefaultName,x as agentExtension,J as browserTool,B as buildModelMessages,s as codeTool,n as collectAgenticMemoryTools,Ae as compileAgentWorkflow,Q as containerFsTool,Y as containerTool,T as createAgentContext,h as createAgentGenerate,C as createEpisodeExtract,M as createGraphExtract,O as createStreamGenerate,A as defineAgent,g as defineAgentTool,fe as defineSkill,Z as fsTool,N as functionTool,S as isAgentDefinition,le as isSkillDefinition,U as jsCodeTool,G as jsonSchema,L as mcpTools,te as requestSecretTool,_ as resolveAgentModel,r as runAgentLoop,xe as runVoiceTurn,t as splitForCompaction,W as toFunctionReference,f as toSearchResults,H as voiceBindingName,I as voiceClassName,Te as webSearchTool,ee as withAgentScheduleShard,ae as withSecret,pe as wrapUntrusted};
@@ -0,0 +1,3 @@
1
+ import{usageStatus as O}from"@lunora/ai/create";import{LunoraError as j}from"@lunora/errors";import{r as P}from"../packem_shared/agent-ai-CP87uSoZ.mjs";import R from"../packem_shared/jsonSchema-fhoaBWpN.mjs";import{F as v,s as b}from"../packem_shared/common-DBc9y7Np.mjs";const m=e=>({...e,status:O(e)}),k=e=>m(b(e)),x=e=>e.map(t=>{const o={id:t.toolCallId,input:t.input,name:t.toolName};return t.invalid!==!0?o:{...o,invalid:t.error instanceof Error?t.error.message:String(t.error)}}),h=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=P(t);if(!o)throw new j("INTERNAL",`@lunora/agent: the agent model "${e}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return o.model(e)}return e};let T;const f=()=>(T??=import("ai").catch(e=>{throw T=void 0,e}),T),q=(e,t,o)=>{const r=h(t.model,o),n={};for(const[a,u]of Object.entries(t.tools??{}))n[a]=e.tool({description:u.description,inputSchema:e.asSchema(u.inputSchema)});const i=t.output===void 0?void 0:e.Output.object({schema:t.output}),s={...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:r,output:i,staticSettings:s,tools:n}},E=(e,t)=>{let o;return()=>(o??=f().then(r=>({ai:r,base:q(r,e,t)})).catch(r=>{throw o=void 0,r}),o)},S=(e,{activeTools:t,messages:o,model:r,signal:n,toolChoice:i})=>{const{defaultModel:s,output:a,staticSettings:u,tools:l}=e,d=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([g])=>t.includes(g)));return{messages:o,model:r??s,...u,...Object.keys(d).length>0?{tools:d}:{},...i===void 0?{}:{toolChoice:i},...a===void 0?{}:{output:a},...n===void 0?{}:{abortSignal:n}}},M=e=>e instanceof Error?e:new Error(`model stream failed: ${String(e)}`,{cause:e}),N=e=>({inputTokens:{cacheRead:e?.inputTokens?.cacheRead,cacheWrite:e?.inputTokens?.cacheWrite,noCache:void 0,total:e?.inputTokens?.total},outputTokens:{reasoning:e?.outputTokens?.reasoning,text:void 0,total:e?.outputTokens?.total}}),_=e=>{if(e===void 0)return m(void 0);const t=e.inputTokens?.total,o=e.outputTokens?.total,r=t===void 0||o===void 0?void 0:t+o;return m(b({inputTokens:t,inputTokenDetails:{cacheReadTokens:e.inputTokens?.cacheRead,cacheWriteTokens:e.inputTokens?.cacheWrite},outputTokens:o,outputTokenDetails:{reasoningTokens:e.outputTokens?.reasoning},totalTokens:r}))},y=(e,t)=>{const o=new Error(e.raw===void 0?"model finished with an error reason":`model finished with an error reason (provider reason: ${e.raw})`,{cause:e});return o[v]=_(t),o},B=e=>{if(!(typeof e!="object"||e===null))return e[v]},I=(e,t)=>e.wrapLanguageModel({middleware:{wrapGenerate:async({doGenerate:o})=>{const r=await o();if(r.finishReason.unified==="error")throw y(r.finishReason,r.usage);return r},wrapStream:async({doStream:o})=>{const{stream:r,...n}=await o();let i=!1;return{...n,stream:r.pipeThrough(new TransformStream({flush:s=>{i||s.enqueue({error:new Error("model stream ended without a finish part"),type:"error"})},transform:(s,a)=>{if(s.type==="finish"&&(i=!0,s.finishReason.unified==="error")){a.enqueue({...s,usage:N(s.usage)}),a.enqueue({error:y(s.finishReason,s.usage),type:"error"});return}a.enqueue(s)}}))}}},model:t}),p=(e,t)=>typeof t=="string"?t:I(e,t),H=(e,t)=>{const o=E(e,t);return async r=>{const{ai:n,base:i}=await o(),s=S(i,r),a=await n.generateText({...s,model:p(n,s.model)});return{text:a.text,toolCalls:x(a.toolCalls),usage:k(a.usage),...i.output===void 0?{}:{output:a.output}}}},X=(e,t)=>{const o=E(e,t);return async(r,n)=>{const{ai:i,base:s}=await o(),a=S(s,r),u=i.streamText({...a,model:p(i,a.model)});let l="";try{for await(const c of u.stream){if(c.type==="error")throw M(c.error);c.type==="text-delta"&&(l+=c.text,n(c.text))}}catch(c){if(!r.signal?.aborted)throw c}if(r.signal?.aborted)return{text:l,toolCalls:[],usage:m(void 0)};const[d,g,A,C]=await Promise.all([u.text,u.toolCalls,u.usage,s.output===void 0?Promise.resolve(void 0):u.output]);return{text:d,toolCalls:x(g),usage:k(A),...s.output===void 0?{}:{output:C}}}},U=R({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"}),$=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
2
+ `),J=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{output:i}=await n.generateText({model:p(n,h(o,t)),output:n.Output.object({schema:U}),prompt:$(r,e)});return i},G=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
3
+ `),K=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{text:i}=await n.generateText({model:p(n,h(o,t)),prompt:G(r,e)});return{summary:i.trim()}},w="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.",W=" An existing brief of the earlier conversation is included above. UPDATE that brief: keep every still-relevant fact from it and fold in the newly aged-out messages. Do not replace it with a summary of only the new messages.",Q=()=>async({env:e,messages:t,model:o,previousSummary:r})=>{const n=await f(),{text:i}=await n.generateText({messages:t,model:p(n,h(o,e)),system:r===void 0?w:`${w}${W}`});return i.trim()};export{H as createAgentGenerate,Q as createCompact,K as createEpisodeExtract,J as createGraphExtract,X as createStreamGenerate,h as resolveAgentModel,B as usageOfFailedTurn};
@@ -0,0 +1 @@
1
+ import{usageStatus as X,USAGE_ATTRIBUTE as _,estimateModelCost as Y}from"@lunora/ai/create";import{a as G,r as d,f as H,s as q,e as j,c as K,t as Q}from"../packem_shared/common-DBc9y7Np.mjs";import{c as Z}from"../packem_shared/in-flight-calls-C9QGq8uH.mjs";const W=t=>`${String(Math.round(t))}000000`,ee=Array.from({length:256},(t,o)=>o.toString(16).padStart(2,"0")),O=512,$=new Uint8Array(O);let k=O;const D=(t,o,n)=>{let l="";for(let i=0;i<n;i+=1)l+=ee[t[o+i]];return l},F=t=>{if(t>O){const n=new Uint8Array(t);return crypto.getRandomValues(n),D(n,0,t)}k+t>O&&(crypto.getRandomValues($),k=0);const o=D($,k,t);return k+=t,o},w=(t,o)=>typeof o=="boolean"?{key:t,value:{boolValue:o}}:typeof o=="number"?Number.isFinite(o)?Number.isSafeInteger(o)?{key:t,value:{intValue:String(o)}}:{key:t,value:{doubleValue:o}}:{key:t,value:{stringValue:String(o)}}:{key:t,value:{stringValue:o}},te=(t,o,n)=>{const l={},i=new Map,S=(p,h)=>{const b=p.toLowerCase(),x=i.get(b);x===void 0?(i.set(b,p),l[p]=h):l[x]=h};for(const[p,h]of Object.entries(t))S(p,h);for(const[p,h]of Object.entries(o??{}))S(p,h);return n!==void 0&&n.length>0&&S("authorization",`Bearer ${n}`),l},oe=t=>Array.isArray(t)?t:[t],ne=(t,o)=>{const n={"service.name":t};for(const[l,i]of Object.entries({}))n[l]=i;return Object.entries(n).map(([l,i])=>w(l,i))},se=(t,o,n,l)=>({resourceSpans:[{resource:{attributes:ne(n)},scopeSpans:[{scope:{name:o},spans:oe(t)}]}]}),re=50,ae=256*1024,ce=new TextEncoder,r=(t,o,n)=>{if(n!=null){if(typeof n=="boolean"||typeof n=="number"||typeof n=="string"){t.push(w(o,n));return}t.push(w(o,JSON.stringify(n)))}},ie=(t,o)=>{(async()=>{let l;try{l=await t}catch(i){o(!1,i instanceof Error?i.message:String(i),void 0);return}o(!0,void 0,l)})().catch(()=>{})},ge=t=>{const{conversationId:o,endpoint:n,headers:l,recordInputs:i=!1,recordOutputs:S=!1,token:p,traceId:h,waitUntil:b}=t,x=t.serviceName??"lunora";let A=n;for(;A.endsWith("/");)A=A.slice(0,-1);const P=`${A}/v1/traces`,z=te({"content-type":"application/json"},l,p);let I=[],N=0;const R=()=>{if(I.length===0)return;const e=I;I=[],N=0;try{const s=fetch(P,{body:JSON.stringify(se(e,"@lunora/agent",x)),headers:z,method:"POST"}).catch(()=>{});b?.(s)}catch{}},U=(e,s,a,u,y)=>{const f={attributes:y,endTimeUnixNano:W(Date.now()),kind:1,name:e,spanId:F(8),startTimeUnixNano:W(s),status:a?{code:1}:{code:2,message:u??""},traceId:h??F(16)};I.push(f),N+=ce.encode(JSON.stringify(f)).byteLength,(I.length>=re||N>=ae)&&R()},T=Z((e,s,a,u)=>{const{messages:y,modelId:f,provider:C,result:m,startTs:J}=e,c=[];r(c,"gen_ai.operation.name","chat"),r(c,"gen_ai.request.model",f),r(c,"gen_ai.system",C),r(c,"gen_ai.conversation.id",o);const g=q(d(u,"usage")??d(m,"usage")),L=X(g);r(c,"lunora.usage.status",L),r(c,_.inputTokens,g?.inputTokens),r(c,_.outputTokens,g?.outputTokens),r(c,"gen_ai.usage.total_tokens",g?.totalTokens),r(c,_.cacheReadTokens,g?.cacheReadTokens),r(c,_.cacheWriteTokens,g?.cacheWriteTokens),r(c,_.reasoningTokens,g?.reasoningTokens);const E=j(u)??j(m);E&&(r(c,"gen_ai.response.cached",E.cached),r(c,"cf.aig.log_id",E.logId));const M=E?.cost,V=M??(typeof f=="string"&&L==="complete"?Y(f,{cacheReadTokens:g?.cacheReadTokens,cacheWriteTokens:g?.cacheWriteTokens,inputTokens:g?.inputTokens,outputTokens:g?.outputTokens}):void 0);V!==void 0&&(r(c,"gen_ai.usage.cost",V),r(c,"lunora.usage.cost.source",M===void 0?"estimated":"provider")),i&&r(c,"gen_ai.prompt",y),S&&r(c,"gen_ai.completion",K(d(u,"content")??d(m,"content"))),U(typeof f=="string"?`chat ${f}`:"language_model_call",J,s,a,c)}),v=(e,s,a)=>{const u=d(e,"callId");if(typeof u!="string")return;let y=a;s instanceof Error?y=s.message:typeof s=="string"&&s.length>0&&(y=s),T.close(u,!1,y,H(s))},B=e=>({messages:d(e,"messages"),modelId:d(e,"modelId"),provider:d(e,"provider"),result:void 0,startTs:Date.now()});return{flush:R,executeLanguageModelCall:async e=>{const{callId:s}=e;T.open(s,()=>B(e));try{const a=await e.execute(),u=T.get(s);return u!==void 0&&(u.result=a),a}catch(a){throw T.close(s,!1,a instanceof Error?a.message:String(a),H(a)),a}},onAbort:e=>{v(e,d(e,"reason"),"aborted")},onEnd:e=>{T.fromLifecycle(e)},onError:e=>{v(e,d(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof d(e,"callId")=="string"&&T.fromLifecycle(e)},onLanguageModelCallStart:e=>{const s=d(e,"callId");typeof s=="string"&&T.open(s,()=>B(e))},onStepEnd:e=>{T.fromLifecycle(e)},executeTool:e=>{const s=Date.now(),a=G(e),u=e.execute();return ie(u,(f,C)=>{const m=[];r(m,"gen_ai.operation.name","execute_tool"),r(m,"gen_ai.tool.name",a),r(m,"gen_ai.tool.call.id",d(e,"toolCallId")),i&&r(m,"gen_ai.tool.input",Q(e)),U(typeof a=="string"?`execute_tool ${a}`:"execute_tool",s,f,C,m)}),u}}};export{ge as otlpTelemetry};
@@ -0,0 +1 @@
1
+ import{a as o}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";const i=(a,e,t)=>o({env:e,label:"@lunora/agent",...t===void 0?{}:{fetchImpl:t},...a===void 0?{}:{identity:{userId:a}}});export{i as default};
@@ -0,0 +1,3 @@
1
+ import{usageStatus as ut}from"@lunora/ai/create";import{e as dt}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as lt}from"@lunora/platform";import{r as X}from"../packem_shared/workflow-binding-Dm9hBzx_.mjs";import{a as pt}from"../packem_shared/app-call-options-BE0CQ6Qg.mjs";import{d as mt,a as Q,S as Y}from"../packem_shared/component-shared--SPcu0Iw.mjs";import{usageOfFailedTurn as yt,resolveAgentModel as ft}from"./createAgentGenerate.mjs";import{r as ht,f as wt,m as R,a as gt}from"../packem_shared/memory-JI0lUu84.mjs";import{buildModelMessages as j}from"../packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V}from"../naming.mjs";import{toFunctionReference as g}from"../packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"../packem_shared/positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as Tt,secretLabelOf as St}from"../packem_shared/SecretUnavailableError-DOy2M4Ak.mjs";import{combineTelemetry as $t}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{c as z}from"../packem_shared/tool-output-Cmk3JWMG.mjs";const Ct=200,Et=e=>{const t=e.findIndex(o=>o.role!=="tool");return t===-1?[]:e.slice(t)},xt=async e=>{let t=Ct;for(;;){const o=await e(t),a=Et(o);if(a.length>0||o.length<t)return a;t*=2}},Rt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const o=Array.isArray(t)?t:[t];return o.length===0?void 0:$t(...o)},It=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,o)=>{const a=Rt(e);if(a===void 0)return o();const n={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:n,toolContext:void 0},i=Date.now();await a.onToolExecutionStart?.(s);let c;const u=()=>(c??=o(),c);try{if(a.executeTool===void 0)await u();else try{await a.executeTool({...s,execute:u,toolCallId:t.id})}catch{}const d=await u();return await a.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:d,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),d}catch(d){throw await a.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:d,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),d}},kt=8,Mt=e=>vt(e)?e:0,Z=e=>e===void 0?"null":JSON.stringify(e),Nt=async(e,t,o)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...o===void 0?{}:{usage:o}})}catch(a){t instanceof Error&&t.cause===void 0&&(t.cause=a)}},Ot=e=>e===void 0?[]:[e].flat(),At=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),_t=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],W=e=>e.status??ut(e),qt=(e,t)=>e===t?e:"partial",tt=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:W(t)};const o={status:qt(W(e),W(t))};for(const a of _t)(e[a]!==void 0||t[a]!==void 0)&&(o[a]=(e[a]??0)+(t[a]??0));return o},Ut=async(e,t,o,a,n,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:o.do(a,async()=>await s()?!1:i===!0||i(t,n))},bt="WorkflowTimeoutError",et=e=>e instanceof Error&&e.name===bt,Dt=async(e,t)=>{const{agent:o,deleteMessage:a,instanceId:n,patchThread:s,persist:i,step:c}=e,u=Q(o.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+u,messageKey:`${n}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const d=await c.waitForEvent(`approval:${t.id}`,{timeout:u,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(!et(p))throw p;return{decision:"reject",note:"approval timed out"}});return await a(`${n}:approval:${t.id}`),await s({status:"running"}),d},Ft={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Gt=(e,t)=>`${String(e)}:${t}`,Lt=async(e,t,o,a,n)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:u,patchThread:d,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,v=`${c}:secret:${n}`,y=Math.min(Q(s.approvalTimeout),lt-Y);await m.do(`secret:request:${n}`,async()=>{await r(u,{consumerTool:o,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:a,threadKey:h,toolCallId:n,toolName:t.name})}),await m.do(`secret:await:${n}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${a}`,messageKey:v,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await d({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${n}`,{timeout:y+Y,type:`agent-secret:${n}`}).catch(T=>{if(!et(T))throw T});const{status:f}=await m.do(`secret:settle:${n}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:n}));return await i(v),await d({ifInstanceId:c,status:"running"}),f},b="lunoraToolOutcome",Pt=e=>typeof e=="object"&&e!==null&&b in e?e[b]:{ok:e},Wt=async(e,t,o,a)=>{const{instanceId:n,persist:s}=e,i=Gt(a,t.id),c=`${n}:secret-result:${i}`,u=`tool:${t.name}:${i}`,d=St(t.input);if(d===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:u,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:u,toolCallId:t.id,toolName:t.name});return}const p=await Lt(e,t,o,d,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${Ft[p]}.`,messageKey:c,role:"tool",stepName:u,toolCallId:t.id,toolName:t.name})},jt=async(e,t,o)=>{const{agent:a,approvalGrantedRef:n,depth:s,env:i,exports:c,getState:u,instanceId:d,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,shardKey:v,step:y,threadKey:f,tools:T}=e,$=`tool:${t.name}:${t.id}`,C=T[t.name],E=`${d}:tool:${t.id}`;if(!C){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:$,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:$,toolCallId:t.id,toolName:t.name});return}if(C.secretRequest!==void 0){await Wt(e,t,C.secretRequest.consumer,o);return}const D={depth:s,env:i,exports:c,getState:u,idempotencyKey:$,instanceId:d,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:f,toolCallId:t.id})},run:m,setState:h,shardKey:v,step:y,threadKey:f,toolCallId:t.id},F={depth:s,env:i,getState:u,idempotencyKey:$,instanceId:d,run:m,shardKey:v,threadKey:f,toolCallId:t.id},G=`tool:approval-gate:${t.id}`;let N,O;const L=async()=>await m(n,{key:f,toolName:t.name})===!0;if(await Ut(C,t.input,y,G,F,L)){const{decision:S,note:K,scope:q}=await Dt(e,t);if(S==="reject"){const k=K===void 0?"":` Reason: ${K}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${k}`,messageKey:E,role:"tool",status:"rejected",stepName:$,toolCallId:t.id,toolName:t.name});return}N="approved",O=q}const _={...N===void 0?{}:{status:N},...O===void 0?{}:{approvalScope:O}},I=Pt(await y.do($,async()=>{try{const S=()=>Promise.resolve(C.execute(t.input,D)),K=await Kt(a.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[b]:{ok:K}}}catch(S){if(dt(S)||S instanceof Tt)return{[b]:{failed:S.message}};throw S}}));if("failed"in I){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${I.failed}`),messageKey:E,role:"tool",stepName:$,..._,toolCallId:t.id,toolName:t.name});return}const A=I.ok;await l({content:z(typeof A=="string"?A:Z(A)),messageKey:E,role:"tool",stepName:$,..._,toolCallId:t.id,toolName:t.name})},Bt=(e,t,o)=>{if(!t)return e;let{messages:a}=e;return t.messages!==void 0&&(a=t.messages),t.system!==void 0&&(a=[{content:t.system,role:"system"},...a]),{activeTools:t.activeTools??e.activeTools,messages:a,model:t.model===void 0?e.model:ft(t.model,o),toolChoice:t.toolChoice??e.toolChoice}},ot=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const o=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=o)return;let a=e.length-o;for(;a>0&&e[a]?.role==="tool";)a-=1;if(!(a<=0))return{older:e.slice(0,a),recent:e.slice(a)}},Ht=async(e,t)=>{const{agent:o,compact:a,env:n}=e,s=ot(t,o.compaction);if(s===void 0||a===void 0)return{history:t,summary:void 0};try{const i=await a({env:n,messages:j({history:s.older}),model:o.compaction?.model??o.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Yt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},zt=async e=>{const{agent:t,compact:o,env:a,historyRef:n,instanceId:s,patchThread:i,run:c,threadKey:u}=e,d=Yt(t.compaction),p=await c(n,{configKey:d,key:u}),{messages:r,summary:l}=p,m=ot(r,t.compaction);if(m===void 0||o===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:f}=p;return f===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:f.throughSeq}).catch(T=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${u}"`,T)}),{history:r.filter(T=>T.seq>f.throughSeq),summary:f.summary})};let v;try{v=await o({env:a,messages:j({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(f){return console.warn(`@lunora/agent: summarising thread "${u}" failed`,f),h()}if(v.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:v,summaryConfig:d,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(f=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${u}"`,f)}),{history:m.recent,summary:v}},Jt=async(e,t,o)=>{const{agent:a,env:n,generate:s,instructions:i,listMessages:c,memoryContext:u,onTokenDelta:d,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:v}=a.compaction!==void 0&&e.compact!==void 0?await zt(e):await Ht(e,await xt(async T=>await p(c,{key:m,limit:T})));let y={activeTools:a.activeTools,messages:j({history:h,instructions:i,memoryContext:u,summary:v}),model:void 0,toolChoice:a.toolChoice};a.prepareStep&&(y=Bt(y,await a.prepareStep({messages:y.messages,stepNumber:t,steps:o}),n));const f={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&&d?l(f,T=>{d({text:T,threadKey:m,turn:t})}):s(f)})},J=async(e,t)=>{const{agent:o,step:a}=e;o.onStepFinish&&await a.do(`agent:step-finish:${String(t.turn)}`,async()=>(await o.onStepFinish?.(t),!0))},Xt=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}}),B=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Qt=e=>mt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Vt=async(e,t,o,a,n)=>{if(e.source===void 0)return;const s=g(e.source),{topK:i}=e,c=R("memory:retrieve",e.key),u={query:t,...i===void 0?{}:{topK:i}},d=await a.do(c,async()=>n(s,u,pt(o)));return B(d)},Zt=async(e,t,o,a,n,s)=>{if(o===void 0)return;const i=R("memory:traverse",e.key),c=await n.do(i,async()=>s(a,{owner:o,query:t,...Qt(e.graph)}));return B(c)},te=async(e,t,o,a,n)=>{if(t===void 0)return;const s=R("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await a.do(s,async()=>n(o,i));return B(c)},ee=async(e,t)=>e.kind==="episodic"?te(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Zt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Vt(e,t.input,t.shardKey,t.step,t.run),oe=e=>{const t=e.findIndex(o=>o.kind==="episodic");return e.filter((o,a)=>o.kind!=="episodic"||a===t)},ae=async(e,t,o,a,n,s,i)=>{const c=oe(ht(e));if(c.length===0)return;const u=g(n.graphTraverse),d=g(n.episodeRecall),p=[];for(const r of c){const l=await ee(r,{episodeRecall:d,graphTraverse:u,input:t,owner:o,run:i,shardKey:a,step:s});l!==void 0&&p.push(l)}return p.length>0?p.join(`
2
+
3
+ `):void 0},ne=async e=>{const{agent:t,env:o,extractGraph:a,finalText:n,input:s,instanceId:i,owner:c,paths:u,run:d,step:p}=e;if(a===void 0||c===void 0||n===void 0||n.length===0)return;const r=wt(t);if(r!==void 0)try{const l={assistantText:n,env:o,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(R("memory:extract",r.key),async()=>a(l));await d(g(u.graphUpsert),{...m,messageKey:`${i}:${R("extract",r.key)}`,owner:c})}catch{}},se=async e=>{const{agent:t,env:o,extractEpisode:a,finalText:n,input:s,instanceId:i,owner:c,paths:u,run:d,step:p,threadKey:r}=e;if(a===void 0||c===void 0||n===void 0||n.length===0)return;const l=gt(t);if(l!==void 0)try{const m={assistantText:n,env:o,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(R("memory:episode",l.key),async()=>a(m));await d(g(u.episodeUpsert),{messageKey:`${i}:${R("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},re=async(e,t,o)=>{const a=X(e.env,e.exports,V(t),["get"]);if(a!==void 0)try{await(await a.get(o)).terminate()}catch{}},ie="12 hours",ce=async(e,t,o)=>{await e.waitForEvent(`dequeue:${o}`,{timeout:ie,type:`agent-dequeue:${t}:${o}`})},ue=async(e,t,o)=>{const a=X(e.env,e.exports,V(e.exportName),["get"]);if(a===void 0)return;const n=a.get.bind(a);try{await e.step.do(`dequeue-wake:${o}`,async()=>(await(await n(o)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${o}`}),o))}catch{}},de=async(e,t,o)=>{const{onReply:a}=e,{replyRef:n}=t.params;if(!(a===void 0||n===void 0))try{await t.step.do("agent:reply",async()=>(await a({env:t.env,replyRef:n,result:o,threadKey:t.params.threadKey}),n.channel))}catch{}},le=async(e,t,o,a,n)=>{const{instanceId:s,persist:i}=e,c=o.usage===void 0?{}:{usage:o.usage};if(o.toolCalls.length===0){const u=o.output!==void 0&&o.text.length===0?Z(o.output):o.text;return await i({content:u,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await J(e,{text:o.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:o.text,turns:t+1,...o.output===void 0?{}:{output:o.output}}}}await i({content:o.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:o.toolCalls});for(const u of o.toolCalls)await jt(e,u,t);if(await J(e,{text:o.text,toolCalls:o.toolCalls,turn:t,...c}),a.push(Xt(o)),n.length>0&&await At(n,a))return"stopCondition"},pe=async(e,t,o,a)=>{const n=[];let s,i=!1,c=0;for(let u=0;u<t;u+=1){const d=await Jt(e,u,n);a.value=tt(a.value,d.usage),c=u+1;const p=await le(e,u,d,n,o);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:o,env:a,exportName:n,exports:s,extractEpisode:i,extractGraph:c,generate:u,instanceId:d,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:v}=e,y=t.maxTurns??kt,f=Ot(t.stopWhen),T=g(l.appendMessage),$=g(l.approvalGranted),C=g(l.openSecretRequest),E=g(l.settleSecretRequest),H=g(l.completeRun),D=g(l.ensureThread),F=g(l.listMessages),G=g(l.history),N=g(l.deleteMessage),O=g(l.patchThread),L=g(l.setState),_=g(l.state),I=async w=>{await m(T,{threadKey:r.threadKey,...w})},A=async w=>{await m(O,{key:r.threadKey,...w})},S=async w=>{await m(N,{messageKey:w,threadKey:r.threadKey})},K=async()=>{await I({content:r.input,messageKey:`${d}:user`,role:"user"})},q={dispatched:!1},k=async w=>{q.dispatched=!0;const U=await m(H,{instanceId:d,key:r.threadKey,...w});U?.dequeued!==void 0&&await ue({env:a,exportName:n,exports:s,step:h},r.threadKey,U.dequeued)},at=async()=>await m(_,{key:r.threadKey}),nt=async w=>{await m(L,{key:r.threadKey,state:w})},P=await m(D,{agent:n,instanceId:d,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}});P?.outcome==="replaced"&&await re({env:a,exports:s},n,P.priorInstanceId);const st=await ae(t,r.input,r.owner,r.shardKey,l,h,m),rt=typeof t.instructions=="function"?t.instructions({env:a,input:r.input,threadKey:r.threadKey}):t.instructions,it={agent:t,approvalGrantedRef:$,openSecretRef:C,settleSecretRef:E,compact:o,depth:Mt(r.depth),env:a,exports:s,generate:u,getState:at,historyRef:G,instanceId:d,instructions:rt,listMessages:F,memoryContext:st,onTokenDelta:p,owner:r.owner,deleteMessage:S,patchThread:A,persist:I,run:m,setState:nt,shardKey:r.shardKey,step:h,streamGenerate:v,threadKey:r.threadKey,tools:t.tools??{}},M={value:void 0};try{P?.outcome==="queued"&&await ce(h,r.threadKey,d),await K();const{final:w,stoppedByCondition:U,turnsRun:ct}=await pe(it,y,f,M),x=M.value===void 0?{}:{usage:M.value};return await ne({agent:t,env:a,extractGraph:c,finalText:w?.text,input:r.input,instanceId:d,owner:r.owner,paths:l,run:m,step:h}),await se({agent:t,env:a,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:d,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await de(t,{env:a,params:r,step:h},{...w,...x}),await k({status:"idle",...x}),{...w,...x}):U?(await k({status:"idle",...x}),{stopped:"stopCondition",turns:ct,...x}):(await k({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...x}),{stopped:"maxTurns",turns:y,...x})}catch(w){throw q.dispatched||(M.value=tt(M.value,yt(w)),await Nt(k,w,M.value)),w}finally{await It(t.telemetry)}};export{tt as addUsage,Ht as compactHistory,Ke as runAgentLoop,ot as splitForCompaction};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import y from"./jsonSchema-fhoaBWpN.mjs";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-B9omvXoR.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"../packem_chunks/createAgentGenerate.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};
@@ -1,2 +1,2 @@
1
- import{LunoraError as c}from"@lunora/errors";import{j as i}from"./json-schema-CHVg-SsJ.mjs";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(`
1
+ import{LunoraError as c}from"@lunora/errors";import i from"./jsonSchema-fhoaBWpN.mjs";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
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{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as S}from"@lunora/workflow";import{f as $}from"./fnv1a-BNN96GYb.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as L}from"./workflow-binding-Dm9hBzx_.mjs";import b from"./jsonSchema-fhoaBWpN.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as P,DEFAULT_AGENT_FUNCTION_PATHS as _}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as g}from"./positive-integer-ztHqqpBk.mjs";const M=new Set(["complete","errored","terminated"]),R=600,w=3,k=500,x=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",C=t=>t!==null&&typeof t=="object"?t.output:void 0,D=async t=>{await new Promise(e=>{setTimeout(e,t)})},U=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=x(a);if(M.has(s))return{output:C(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},j=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},F=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""},B=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&&!g(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??R,o=t.pollIntervalMs??k,a=t.wait??D,s=P(_.listMessages),T=async(y,r)=>{const p=(g(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=L(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}`,h=`sub-${e}-${$(`${r.instanceId}:${e}:${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:h,params:E(A,r.shardKey)});l=await i.get(d.id)}catch(d){if(!S(d))throw d;l=await i.get(h)}const{output:v,status:u}=await U(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(j(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 I=await r.run(s,{key:f});return F(I)};return{description:t.description,execute:T,inputSchema:b({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{B as agentAsTool};
@@ -0,0 +1 @@
1
+ const p=o=>o===void 0?void 0:{shardKey:o};export{p as a};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import y from"./jsonSchema-fhoaBWpN.mjs";import{i as w}from"./positive-integer-ztHqqpBk.mjs";import{M as v,c as A}from"./tool-output-Cmk3JWMG.mjs";const T=16,g=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=v?e:A(o)},$=(e,o)=>{let t=e;for(const i of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))return;t=t[i]}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(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?$(o[r],t.$path):o[r]}const i={};for(const[r,n]of Object.entries(t))r!=="__proto__"&&(i[r]=l(n,o));return i},S=async(e,o,t)=>{const{asSchema:i}=await import("@ai-sdk/provider-utils"),{validate:r}=i(o.inputSchema);if(r===void 0)return t;const n=await r(t);if(n.success)return n.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${n.error.message}`)},b=async(e,o,t,i)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>i)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(i)}. Split it across several code calls.`);const n={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await S(s,c,l(s.input??{},n)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},h=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,h);n[s.id]=f,p.push({id:s.id,output:g(f)})}return{final:p.at(-1)?.output,results:p}},E=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("; ")}.`,O=y({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"}),L=(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,n]of Object.entries(t)){if(n.needsApproval!==void 0&&n.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\`.`);if(n.secretRequest!==void 0)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it is a requestSecretTool, which a code-mode script can't pause for the owner to supply. Expose it as a normal top-level tool.`)}if(o.maxSteps!==void 0&&!w(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const i=o.maxSteps??T;return{description:o.description??E(e),execute:(r,n)=>b(r,e,n,i),inputSchema:O,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{L as codeTool,l as resolveReferences,b as runToolScript};
@@ -0,0 +1 @@
1
+ import{a as u}from"./app-call-options-BE0CQ6Qg.mjs";import p from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as l}from"./AGENT_MODULE-CYBmT9SD.mjs";const m=240,y=50,f=(r,s)=>r.length<=s?r:`${r.slice(0,s)}…`,g=r=>{if(!(r===void 0||!Number.isFinite(r)))return Math.min(y,Math.max(1,Math.trunc(r)))},S=(r,s)=>{const t=r??{},i=Array.isArray(t.chunks)?t.chunks:[],e=Array.isArray(t.sources)?t.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:f(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},A=p({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"}),b=p({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),T=(r,s,t)=>{const i=l(s),e=Math.max(1,r.snippetChars??m),o=r.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.${t===void 0?"":` Use \`${t}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,c)=>{const d=g(n.topK)??o,h=await c.run(i,{query:n.query,...d===void 0?{}:{topK:d}},u(c.shardKey));return S(h,e)},inputSchema:A,isLunoraAgentTool:!0}},q=r=>{const s=l(r);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(t,i)=>i.run(s,{id:t.id},u(i.shardKey)),inputSchema:b,isLunoraAgentTool:!0}},v=(r,s)=>{const t=[];r.memory&&t.push({key:"default",...r.memory});for(const e of s)e.knowledge&&t.push({key:e.name,...e.knowledge});const i={};for(const e of t){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,a=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=T(e,e.source,n?a:void 0),n&&(i[a]=q(e.read))}return i};export{v as collectAgenticMemoryTools,S as toSearchResults};
@@ -0,0 +1 @@
1
+ import{defineWorkflow as c}from"@lunora/workflow";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-CYBmT9SD.mjs";const T=(t,r,n,e)=>{const a=r.LUNORA_OTLP_ENDPOINT;if(typeof a!="string"||a===""||t.telemetry?.isEnabled===!1)return t;const s=typeof r.LUNORA_OTLP_TOKEN=="string"?r.LUNORA_OTLP_TOKEN:void 0,i=[t.telemetry?.integrations].flat().filter(o=>o!==void 0);return{...t,telemetry:{...t.telemetry,integrations:[...i,n({conversationId:e,endpoint:a,token:s})],isEnabled:!0}}},N=(t,r,n)=>c({handler:async e=>{const[{runAgentLoop:a},{createAgentGenerate:s,createCompact:i,createEpisodeExtract:o,createGraphExtract:m,createStreamGenerate:l},{default:f},{otlpTelemetry:d}]=await Promise.all([import("../packem_chunks/runAgentLoop.mjs"),import("../packem_chunks/createAgentGenerate.mjs"),import("../packem_chunks/resolve-run.mjs"),import("../packem_chunks/otlpTelemetry.mjs")]),p=T(t,e.env,d,e.params.threadKey);return a({agent:p,compact:i(),env:e.env,exports:e.exports,exportName:r,extractGraph:m(),extractEpisode:o(),generate:s(p,e.env),instanceId:e.event.instanceId,params:e.params,paths:n?.paths??A,run:f(e.params.owner,e.env,e.fetchImpl),step:e.step,streamGenerate:l(p,e.env)})},name:t.name??u(r)});export{N as default};
@@ -0,0 +1 @@
1
+ const s="agent";const o=12096e5,M=e=>({...e,visibility:"internal"}),a=e=>{const t={};for(const[_,n]of Object.entries(e))n!==void 0&&(t[_]=n);return t},r=9e5,E=6e4;const A={day:864e5,hour:36e5,minute:6e4,month:2592e6,second:1e3,week:6048e5,year:31536e6},T=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,O=e=>{if(e===void 0)return 2592e5;if(typeof e=="number")return Math.min(e,6048e5);const t=T.exec(e);return t===null?2592e5:Math.min(Number(t[1])*A[t[2]],6048e5)};export{s as A,E as S,O as a,M as b,o as c,a as d,r as e};