@lunora/agent 1.0.0-alpha.7 → 1.0.0-alpha.71

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 (84) hide show
  1. package/dist/channels.d.mts +2 -2
  2. package/dist/channels.d.ts +2 -2
  3. package/dist/channels.mjs +1 -181
  4. package/dist/component.d.mts +2 -0
  5. package/dist/component.d.ts +2 -0
  6. package/dist/component.mjs +2 -418
  7. package/dist/inbound.d.mts +1 -1
  8. package/dist/inbound.d.ts +1 -1
  9. package/dist/inbound.mjs +1 -32
  10. package/dist/index.d.mts +38 -8
  11. package/dist/index.d.ts +38 -8
  12. package/dist/index.mjs +1 -18
  13. package/dist/naming.mjs +1 -8
  14. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  15. package/dist/packem_shared/VoiceSessionDO-Dxj0V8Ej.mjs +1 -0
  16. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  17. package/dist/packem_shared/agentAsTool-DrFnh9UQ.mjs +1 -0
  18. package/dist/packem_shared/base64-5eyBfWO3.mjs +1 -0
  19. package/dist/packem_shared/braintrustTelemetry-CoYK-pq7.mjs +1 -0
  20. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  21. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  22. package/dist/packem_shared/codeTool-qdwj8j8S.mjs +1 -0
  23. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  24. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  25. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  26. package/dist/packem_shared/compileAgentWorkflow-GDJ_HWln.mjs +1 -0
  27. package/dist/packem_shared/component-shared-IZozysYq.mjs +1 -0
  28. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  29. package/dist/packem_shared/createAgentContext-iS35-Xrs.mjs +1 -0
  30. package/dist/packem_shared/createAgentGenerate-9bZ2YhpN.mjs +3 -0
  31. package/dist/packem_shared/createDispatchRunner-pLyQ70FK-2_j6ocGT.mjs +1 -0
  32. package/dist/packem_shared/defineAgent-CZdh7y3W.mjs +3 -0
  33. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  34. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  35. package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
  36. package/dist/packem_shared/normalizeEntityName-Ce0X6Afj.mjs +2 -0
  37. package/dist/packem_shared/otlpTelemetry-CoyeTO8S.mjs +1 -0
  38. package/dist/packem_shared/runAgentLoop-KUUoFT3r.mjs +3 -0
  39. package/dist/packem_shared/runVoiceTurn-CRPeNXsS.mjs +1 -0
  40. package/dist/packem_shared/sandboxComponent-BtOkUYpY.mjs +5 -0
  41. package/dist/packem_shared/sentryTelemetry-CPqEbFPA.mjs +1 -0
  42. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-eCuvcLzf.d.mts} +211 -21
  43. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-eCuvcLzf.d.ts} +211 -21
  44. package/dist/packem_shared/voice-turn-DbVR0H6T.mjs +1 -0
  45. package/dist/reply.d.mts +40 -0
  46. package/dist/reply.d.ts +40 -0
  47. package/dist/reply.mjs +1 -0
  48. package/dist/sandbox.d.mts +14 -13
  49. package/dist/sandbox.d.ts +14 -13
  50. package/dist/sandbox.mjs +1 -113
  51. package/dist/skill-markdown.d.mts +36 -0
  52. package/dist/skill-markdown.d.ts +36 -0
  53. package/dist/skill-markdown.mjs +1 -0
  54. package/dist/telemetry/index.d.mts +72 -9
  55. package/dist/telemetry/index.d.ts +72 -9
  56. package/dist/telemetry/index.mjs +1 -5
  57. package/package.json +18 -9
  58. package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
  59. package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +0 -297
  60. package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
  61. package/dist/packem_shared/agentAsTool-CUHlWsmt.mjs +0 -98
  62. package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
  63. package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +0 -47
  64. package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
  65. package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
  66. package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
  67. package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
  68. package/dist/packem_shared/common-DAeFCot5.mjs +0 -61
  69. package/dist/packem_shared/compileAgentWorkflow-DX90058f.mjs +0 -55
  70. package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +0 -93
  71. package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
  72. package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +0 -192
  73. package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
  74. package/dist/packem_shared/defineAgent-DAwAZC9P.mjs +0 -148
  75. package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
  76. package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
  77. package/dist/packem_shared/graph-component-Bbaxxymp.mjs +0 -217
  78. package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
  79. package/dist/packem_shared/normalizeEntityName-BouctxLC.mjs +0 -3
  80. package/dist/packem_shared/otlpTelemetry-DL6iZ9e2.mjs +0 -164
  81. package/dist/packem_shared/runAgentLoop-B3Q2o-Uz.mjs +0 -493
  82. package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
  83. package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
  84. package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +0 -36
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-boAM2Yi1.js";
2
- export type { y as AgentEmailMapper, z as AgentEmailRun, B as AgentGenerateOptions, C as AgentGenerateResult, D as AgentInstructionsContext, E as AgentLiveEvent, F as AgentMemoryOptions, G as AgentMemorySource, H as AgentMessageStatus, J as AgentOnStepFinish, K as AgentPrepareStep, L as AgentPrepareStepInput, M as AgentPrepareStepResult, N as AgentProgressEvent, O as AgentRunHandle, P as AgentStepFinishInfo, Q as AgentStepInfo, R as AgentThreadStatus, T as AgentTokenDelta, U as AgentToolCall, a as AgentToolContext, V as AgentUsage, W as AgentVoiceConfig, X as AgentWorkflowBindingLike, Y as AgentWorkflowInstanceLike } from "./packem_shared/types.d-boAM2Yi1.js";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, d 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, z as SkillConfig } from "./packem_shared/types.d-eCuvcLzf.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 AgentStepFinishInfo, W as AgentStepInfo, X as AgentThreadStatus, Y as AgentTokenDelta, Z as AgentToolCall, b as AgentToolContext, _ as AgentUsage, $ as AgentVoiceConfig, a0 as AgentWorkflowBindingLike, a1 as AgentWorkflowInstanceLike, a2 as EnsureThreadOutcome } from "./packem_shared/types.d-eCuvcLzf.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
5
  export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
@@ -183,7 +183,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
183
183
  interface ToolScriptStep {
184
184
  /** A stable name later steps reference the output by. */
185
185
  id: string;
186
- /** The tool's input; values may embed `{ "$from": "&lt;stepId>", "$path": "a.b" }` refs. */
186
+ /** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
187
187
  input?: Record<string, unknown>;
188
188
  /** The tool to call — one of the tools handed to {@link codeTool}. */
189
189
  tool: string;
@@ -239,6 +239,16 @@ interface CodeToolOptions {
239
239
  * keep approval-gated tools as normal top-level tools. Gate the whole script via
240
240
  * `opts.needsApproval` instead.
241
241
  *
242
+ * STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
243
+ * step runs inside its own durable `step.do`, so the workflow host serializes
244
+ * the returned value before the next step (or the tool result) ever sees it. A
245
+ * `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
246
+ * `null` or a dropped key, and a `bigint` throws outright. That applies to the
247
+ * value a later step reads through `{ "$from": … }` just as much as to the
248
+ * returned `results` — the hand-off is durable state, not an in-memory one. A
249
+ * composed tool that wants to pass a rich value should return its JSON form
250
+ * (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
251
+ *
242
252
  * ```ts
243
253
  * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
244
254
  *
@@ -344,8 +354,14 @@ interface FunctionToolOptions<Input> {
344
354
  * ```
345
355
  *
346
356
  * The function reference may be a typed `api.*` reference or a `"module:name"`
347
- * path. The model-provided input is passed verbatim as the function's args, so
348
- * `inputSchema` should mirror the referenced function's argument validator.
357
+ * path. The model-provided input is passed as the function's args, so
358
+ * `inputSchema` should mirror the referenced function's argument validator
359
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
360
+ * input (so out-of-schema model input can never override it). A function
361
+ * that wants to dedupe a side-effecting call across an at-least-once step
362
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
363
+ * and checks it; a function that ignores it is unaffected — an args field
364
+ * the function's own validator doesn't declare is dropped, not rejected.
349
365
  * @experimental
350
366
  */
351
367
  declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
@@ -471,6 +487,17 @@ interface McpToolsOptions {
471
487
  command?: string;
472
488
  /** Identify this client to the server on connect. Default `"lunora-agent"`. */
473
489
  name?: string;
490
+ /**
491
+ * Gate an adapted tool's call behind a human approval. Defaults to
492
+ * **unattended** (no gate) — matching today's behavior. An MCP tool's
493
+ * result feeds back into the model's context (`adaptMcpResult`), so a
494
+ * hostile downstream server can pair indirect prompt injection with an
495
+ * unattended mutating tool call; pass a boolean to gate every adapted
496
+ * tool the same way, or a predicate `(toolName, input) => boolean` to
497
+ * gate per tool (evaluated from replay-stable input, so keep it
498
+ * deterministic).
499
+ */
500
+ needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
474
501
  /** Only adapt these tool names (default: every tool the server lists). */
475
502
  only?: ReadonlyArray<string>;
476
503
  /** Prefix added to each adapted tool's key (disambiguate multiple servers). */
@@ -510,6 +537,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
510
537
  * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
511
538
  * does not) — pass `url`, or inject an already-connected `client` for a custom
512
539
  * transport (also the test seam).
540
+ *
541
+ * Every adapted tool runs UNATTENDED by default (no approval gate) — pass
542
+ * `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
513
543
  * @experimental
514
544
  */
515
545
  declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
@@ -808,15 +838,15 @@ declare class VoiceSessionDO {
808
838
  }
809
839
  /**
810
840
  * Compile a `defineAgent` definition into the workflow the generated
811
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
841
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
812
842
  *
813
843
  * ```ts
814
844
  * import LunoraWorkflow from "@lunora/workflow/do";
815
845
  * import { compileAgentWorkflow } from "@lunora/agent";
816
846
  * import { support } from "../agents.js";
817
847
  *
818
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
819
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
848
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
849
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
820
850
  * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
821
851
  * }
822
852
  * }
package/dist/index.mjs CHANGED
@@ -1,18 +1 @@
1
- export { runAgentLoop, splitForCompaction } from './packem_shared/runAgentLoop-B3Q2o-Uz.mjs';
2
- export { collectAgenticMemoryTools, toSearchResults } from './packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs';
3
- export { agentAsTool } from './packem_shared/agentAsTool-CUHlWsmt.mjs';
4
- export { codeTool } from './packem_shared/codeTool-CjgJOC9t.mjs';
5
- export { agentComponent, agentExtension } from './component.mjs';
6
- export { default as createAgentContext } from './packem_shared/createAgentContext-4xJGXNR4.mjs';
7
- export { defineAgent, defineAgentTool, isAgentDefinition } from './packem_shared/defineAgent-DAwAZC9P.mjs';
8
- export { functionTool } from './packem_shared/functionTool-D6lCa2jB.mjs';
9
- export { createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, resolveAgentModel } from './packem_shared/createAgentGenerate-BQv9YJ01.mjs';
10
- export { adaptMcpResult, mcpTools } from './packem_shared/adaptMcpResult-wtNMvLoP.mjs';
11
- export { buildModelMessages } from './packem_shared/buildModelMessages-BWFigaoo.mjs';
12
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from './naming.mjs';
13
- export { AGENT_MODULE, DEFAULT_AGENT_FUNCTION_PATHS, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, toFunctionReference } from './packem_shared/AGENT_MODULE-Dnt_-AAT.mjs';
14
- export { browserTool, containerTool, fsTool } from './sandbox.mjs';
15
- export { defineSkill, isSkillDefinition } from './packem_shared/defineSkill-Ctf_S-rz.mjs';
16
- export { default as VoiceSessionDO } from './packem_shared/VoiceSessionDO-DLoXsHGF.mjs';
17
- export { runVoiceTurn } from './packem_shared/runVoiceTurn-LnqLvCRR.mjs';
18
- export { default as compileAgentWorkflow } from './packem_shared/compileAgentWorkflow-DX90058f.mjs';
1
+ import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-KUUoFT3r.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-DrFnh9UQ.mjs";import{codeTool as p}from"./packem_shared/codeTool-qdwj8j8S.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-iS35-Xrs.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CZdh7y3W.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-9bZ2YhpN.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as j,containerTool as q,fsTool as z}from"./sandbox.mjs";import{defineSkill as Q,isSkillDefinition as Y}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-Dxj0V8Ej.mjs";import{r as oe}from"./packem_shared/voice-turn-DbVR0H6T.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-GDJ_HWln.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,j as browserTool,k as buildModelMessages,p as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,q as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,Q as defineSkill,z as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
package/dist/naming.mjs CHANGED
@@ -1,8 +1 @@
1
- const CAMEL_BOUNDARY = /([a-z0-9])([A-Z])/gu;
2
- const agentClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}AgentWorkflow`;
3
- const agentBindingName = (exportName) => `AGENT_${exportName.replaceAll(CAMEL_BOUNDARY, "$1_$2").toUpperCase()}`;
4
- const agentDefaultName = (exportName) => `agent-${exportName.replaceAll(CAMEL_BOUNDARY, "$1-$2").toLowerCase()}`;
5
- const voiceClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}VoiceDO`;
6
- const voiceBindingName = (exportName) => `VOICE_${exportName.replaceAll(CAMEL_BOUNDARY, "$1_$2").toUpperCase()}`;
7
-
8
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
1
+ const a=/([a-z0-9])([A-Z])/gu,t=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,s=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,c=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,l=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{s as agentBindingName,t as agentClassName,c as agentDefaultName,l as voiceBindingName,o as voiceClassName};
@@ -0,0 +1 @@
1
+ const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
@@ -0,0 +1 @@
1
+ import{createAi as g}from"@lunora/ai";import{F as b}from"./createDispatchRunner-pLyQ70FK-2_j6ocGT.mjs";import{t as m}from"./base64-5eyBfWO3.mjs";import{p as A,d as S,a as v,i as l,b as f,c as w,e as k,f as x,r as T,t as E}from"./voice-turn-DbVR0H6T.mjs";import{createStreamGenerate as M}from"./createAgentGenerate-9bZ2YhpN.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as B,toFunctionReference as p}from"./AGENT_MODULE-M4D1EejI.mjs";const _="@cf/openai/whisper-large-v3-turbo",I="@cf/deepgram/aura-1",U=8*1024*1024,F=256*1024,y=15,D=5e3;class O{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,r){this.state=t,this.env=e,this.agent=s,this.exportName=r,this.paths=B,this.ai=g({binding:e.AI,env:e}),this.streamGenerate=M(s,e),this.sttModel=s.voice?.stt??_,this.ttsModel=s.voice?.tts??I}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const s=new URL(t.url).searchParams.get("threadKey");if(!s)return new Response("Missing threadKey",{status:400});const r=globalThis.WebSocketPair,i=new r,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=A(t.headers.get("x-lunora-identity")),a=S(t.headers.get("x-lunora-userid")),h=v(t.headers.get("x-lunora-identity-exp"));if(l(h))return f(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:s,turn:0,...h===void 0?{}:{expiresAt:h},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const u=this.agent.voice?.greeting;return u&&u.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,s,a,d,u)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(l(s.expiresAt)){f(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(r){this.send(t,{message:r instanceof Error?r.message:String(r),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=w(t);return k(await this.ai.run(this.sttModel,{audio:m(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return x(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let r;try{r=JSON.parse(s)}catch{return}if(r.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(r.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:r.text})}bufferAudio(t,e,s){const r=(this.bufferedBytes.get(t)??0)+e.byteLength;if(r>U){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,r)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((n,o)=>n+o.byteLength,0),r=new Uint8Array(s);let i=0;for(const n of e)r.set(n,i),i+=n.byteLength;return r}async runTurn(t,e,s){const r=new AbortController;this.controllers.set(e.connectionId,r);try{await T({agent:this.agent,connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:r.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},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===r&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,r,i,n){const o=this.resolveRun(r,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{await o(p(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...r===void 0?{}:{owner:r}});for await(const a of E(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,a)}d()||(await o(p(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),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))}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>F&&s<D;)await new Promise(r=>{setTimeout(r,y)}),s+=y}}export{O as default};
@@ -0,0 +1,2 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{jsonSchema as i}from"ai";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
2
+ `);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";import{jsonSchema as y}from"ai";import{isDuplicateInstanceError as A}from"../channels.mjs";import{agentBindingName as L}from"../naming.mjs";import{toFunctionReference as N,DEFAULT_AGENT_FUNCTION_PATHS as b}from"./AGENT_MODULE-M4D1EejI.mjs";const E=new Set(["complete","errored","terminated"]),I=120,S=500,$=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",_=async t=>{await new Promise(e=>{setTimeout(e,t)})},M=async(t,e,n,c)=>{for(let a=0;a<e;a+=1){const i=$(await t.status());if(E.has(i))return i;await c(n)}return"timeout"},P=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""},k=t=>{if(typeof t.name!="string"||t.name.length===0)throw new d("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof t.description!="string"||t.description.length===0)throw new d("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");const{name:e}=t,n=L(e),c=t.maxPolls??I,a=t.pollIntervalMs??S,i=t.wait??_,p=N(b.listMessages),f=async(h,r)=>{const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new d("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no Workflow binding "${n}" on env — declare the "${e}" agent so codegen wires its binding`);const m=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${r.toolCallId}`,w={input:h.prompt,threadKey:m};let u;try{const l=await o.create({id:g,params:w});u=await o.get(l.id)}catch(l){if(!A(l))throw l;u=await o.get(g)}const s=await M(u,c,a,i);if(s==="errored"||s==="terminated")return`Sub-agent "${e}" ${s} before producing an answer.`;if(s==="timeout")return`Sub-agent "${e}" did not finish within the allotted time.`;const T=await r.run(p,{key:m});return P(T)};return{description:t.description,execute:f,inputSchema:y({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{k as agentAsTool};
@@ -0,0 +1 @@
1
+ const a=n=>{let t="";for(let e=0;e<n.length;e+=32768)t+=String.fromCharCode(...n.subarray(e,e+32768));return btoa(t)},o=n=>{const t=atob(n),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.codePointAt(e)??0;return r},s=n=>{const t=n.replaceAll("-","+").replaceAll("_","/"),r=t+"=".repeat((4-t.length%4)%4);return o(r)};export{o as a,s as f,a as t};
@@ -0,0 +1 @@
1
+ import{d as g,r as l,t as m}from"./common-CJSjtsfv.mjs";const d=(r,a)=>typeof r=="string"&&r.length>0?r:a,f=r=>{const{functionId:a,logger:n,recordInputs:c=!1,recordOutputs:u=!1}=r;return{executeLanguageModelCall:e=>n.traced(async t=>{c&&t.log({input:l(e,"messages"),model:l(e,"modelId")});const o=await e.execute();return u&&t.log({output:o}),o},{name:d(a,"language_model_call"),type:"llm"}),executeTool:e=>{const t=l(l(e,"toolCall"),"toolName");return n.traced(async o=>{c&&o.log({input:m(e),tool:t});const s=await e.execute();return u&&o.log({output:s}),s},{name:d(t,"execute_tool"),type:"tool"})},onError:e=>{n.traced(t=>{t.log({error:g(e)})},{name:"error",type:"error"})}}};export{f as braintrustTelemetry};
@@ -0,0 +1 @@
1
+ const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),r=`may not contain the reserved workflow branch-marker key ("${e}")`;export{r as B,o as h};
@@ -0,0 +1,5 @@
1
+ const o=t=>t.toolCalls===void 0||t.toolCalls.length===0?{content:t.content,role:"assistant"}:{content:[...t.content.length>0?[{text:t.content,type:"text"}]:[],...t.toolCalls.map(e=>({input:e.input,toolCallId:e.id,toolName:e.name,type:"tool-call"}))],role:"assistant"},n=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),l=t=>{const e=[];t.instructions!==void 0&&t.instructions.length>0&&e.push({content:t.instructions,role:"system"}),t.memoryContext!==void 0&&t.memoryContext.length>0&&e.push({content:`Relevant context retrieved for this conversation:
2
+
3
+ ${t.memoryContext}`,role:"system"}),t.summary!==void 0&&t.summary.length>0&&e.push({content:`Summary of the earlier conversation:
4
+
5
+ ${t.summary}`,role:"system"});for(const s of t.history)if(s.status!=="awaiting_approval")switch(s.role){case"assistant":{e.push(o(s));break}case"system":{e.push({content:s.content,role:"system"});break}case"tool":{e.push(n(s));break}case"user":{e.push({content:s.content,role:"user"});break}}return e};export{l as buildModelMessages};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{jsonSchema as A}from"ai";const $=16,y=4e3,b=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=y?e:`${o.slice(0,y)}… [truncated]`},T=(e,o)=>{let t=e;for(const s of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,s))return;t=t[s]}return t},c=(e,o)=>{if(Array.isArray(e))return e.map(r=>c(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!(r in o))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?T(o[r],t.$path):o[r]}const s={};for(const[r,i]of Object.entries(t))r!=="__proto__"&&(s[r]=c(i,o));return s},g=async(e,o,t,s)=>{const r=Array.isArray(e.steps)?e.steps.slice(0,s):[],i={},p=[],d=new Set;for(const n of r){if(d.has(n.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${n.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(n.id)}for(const n of r){const l=o[n.tool];if(!l)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${n.tool}" (available: ${Object.keys(o).join(", ")})`);const m=c(n.input??{},i),f={...t,idempotencyKey:`${t.idempotencyKey}:${n.id}`,toolCallId:`${t.toolCallId}:${n.id}`},h=()=>Promise.resolve(l.execute(m,f)),u=await t.step.do(f.idempotencyKey,h);i[n.id]=u,p.push({id:n.id,output:b(u)})}return{final:p.at(-1)?.output,results:p}},v=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("; ")}.`,w=A({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"}),S=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);const s=o.maxSteps??$;return{description:o.description??v(e),execute:(r,i)=>g(r,e,i,s),inputSchema:w,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{S as codeTool,c as resolveReferences,g as runToolScript};
@@ -0,0 +1 @@
1
+ import{jsonSchema as u}from"ai";import{toFunctionReference as d}from"./AGENT_MODULE-M4D1EejI.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
@@ -0,0 +1 @@
1
+ const n=o=>async e=>{await Promise.allSettled(o.map(async p=>p?.(e)))},d=o=>{const e=o.filter(a=>typeof a=="function");return a=>{let t=a.execute;for(const m of e.toReversed()){const l=t;t=()=>m({...a,execute:l})}return t()}},c=(...o)=>({executeLanguageModelCall:d(o.map(e=>e.executeLanguageModelCall)),executeTool:d(o.map(e=>e.executeTool)),onAbort:n(o.map(e=>e.onAbort)),onEmbedEnd:n(o.map(e=>e.onEmbedEnd)),onEmbedStart:n(o.map(e=>e.onEmbedStart)),onEnd:n(o.map(e=>e.onEnd)),onError:n(o.map(e=>e.onError)),onLanguageModelCallEnd:n(o.map(e=>e.onLanguageModelCallEnd)),onLanguageModelCallStart:n(o.map(e=>e.onLanguageModelCallStart)),onObjectStepEnd:n(o.map(e=>e.onObjectStepEnd)),onObjectStepStart:n(o.map(e=>e.onObjectStepStart)),onRerankEnd:n(o.map(e=>e.onRerankEnd)),onRerankStart:n(o.map(e=>e.onRerankStart)),onStart:n(o.map(e=>e.onStart)),onStepEnd:n(o.map(e=>e.onStepEnd)),onStepFinish:n(o.map(e=>e.onStepFinish)),onStepStart:n(o.map(e=>e.onStepStart)),onToolExecutionEnd:n(o.map(e=>e.onToolExecutionEnd)),onToolExecutionStart:n(o.map(e=>e.onToolExecutionStart))});export{c as combineTelemetry};
@@ -0,0 +1 @@
1
+ const t=(o,e)=>{if(!(o===null||typeof o!="object"))return o[e]},y=o=>{const e={};for(const s of["inputTokens","outputTokens","totalTokens"]){const n=t(o,s);typeof n=="number"&&(e[s]=n)}return Object.keys(e).length>0?e:void 0},m=o=>{const e=t(t(o,"providerMetadata"),"gateway"),s=t(t(o,"response"),"headers"),n=p=>{const g=t(s,"get"),f=typeof g=="function"?g.call(s,p):t(s,p);return typeof f=="string"&&f.length>0?f:void 0},a={},r=t(e,"cost");typeof r=="number"&&Number.isFinite(r)&&(a.cost=r);const i=t(e,"cached"),c=t(e,"cacheStatus"),l=typeof c=="string"?c:n("cf-aig-cache-status");typeof i=="boolean"?a.cached=i:typeof l=="string"&&(a.cached=l.toUpperCase()==="HIT");const u=t(e,"logId")??t(e,"log_id"),d=typeof u=="string"&&u.length>0?u:n("cf-aig-log-id");return typeof d=="string"&&d.length>0&&(a.logId=d),Object.keys(a).length>0?a:void 0},h=o=>{const e=t(o,"toolCall"),s=t(e,"toolName"),n=typeof s=="string"?s:void 0,a=t(o,"toolOutput"),r=t(a,"type"),i=t(o,"success"),c=typeof i=="boolean"?i:r!=="tool-error",l=t(o,"toolExecutionMs");return{error:c?void 0:t(a,"error")??t(o,"error"),name:n,output:c?t(a,"output"):void 0,success:c,toolExecutionMs:typeof l=="number"?l:void 0}},b=o=>{const e=t(t(o,"toolCall"),"toolName");return typeof e=="string"?e:void 0},v=o=>t(t(o,"toolCall"),"input"),x=o=>{if(!Array.isArray(o))return;let e="";for(const s of o)if(t(s,"type")==="text"){const n=t(s,"text");typeof n=="string"&&(e+=n)}return e.length>0?e:void 0},T=o=>o instanceof Error?{message:o.message,name:o.name}:o;export{b as a,h as b,x as c,T as d,m as e,t as r,y as s,v as t};
@@ -0,0 +1 @@
1
+ import{defineWorkflow as s}from"@lunora/workflow";import{runAgentLoop as m}from"./runAgentLoop-KUUoFT3r.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-9bZ2YhpN.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{F as T}from"./createDispatchRunner-pLyQ70FK-2_j6ocGT.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-CoyeTO8S.mjs";const E=(r,t,a)=>t===void 0?r:T({env:a,identity:{userId:t},label:"@lunora/agent"}),O=(r,t,a)=>{const e=t.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||r.telemetry?.isEnabled===!1)return r;const n=typeof t.LUNORA_OTLP_TOKEN=="string"?t.LUNORA_OTLP_TOKEN:void 0,i=[r.telemetry?.integrations].flat().filter(o=>o!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...i,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>s({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
@@ -0,0 +1 @@
1
+ const o="agent",A=6048e5,a=12096e5,r=n=>({...n,visibility:"internal"}),_=n=>{const s={};for(const[e,t]of Object.entries(n))t!==void 0&&(s[e]=t);return s};export{o as A,r as a,A as b,a as c,_ as d};
@@ -0,0 +1 @@
1
+ import{a as f,t as g,b as m,d as c,r as e,s as i,c as I}from"./common-CJSjtsfv.mjs";const b=(n,a,d)=>{globalThis.console[n](a,d)},E=(n={})=>{const{functionId:a,logger:d=b,recordInputs:u=!1,recordOutputs:l=!1}=n,p=a===void 0?"":`[${a}] `,r=(o,s,t)=>{d(o,`${p}${s}`,t)};return{onAbort:o=>{r("warn","agent operation aborted",{callId:e(o,"callId"),reason:e(o,"reason")})},onEnd:o=>{r("info","agent operation completed",{callId:e(o,"callId"),finishReason:e(o,"finishReason"),operationId:e(o,"operationId"),usage:i(e(o,"usage"))})},onError:o=>{r("error","agent operation errored",{error:c(o)})},onLanguageModelCallEnd:o=>{const s={callId:e(o,"callId"),finishReason:e(o,"finishReason"),modelId:e(o,"modelId"),provider:e(o,"provider"),usage:i(e(o,"usage"))};l&&(s.text=I(e(o,"content"))),r("info","language model call ended",s)},onStart:o=>{r("info","agent operation started",{callId:e(o,"callId"),modelId:e(o,"modelId"),operationId:e(o,"operationId"),provider:e(o,"provider")})},onStepEnd:o=>{r("info","agent step ended",{finishReason:e(o,"finishReason"),stepNumber:e(o,"stepNumber"),usage:i(e(o,"usage"))})},onStepStart:o=>{r("info","agent step started",{stepNumber:e(o,"stepNumber")})},onToolExecutionEnd:o=>{const s=m(o),t={success:s.success,tool:s.name,toolExecutionMs:s.toolExecutionMs};s.success||(t.error=c(s.error)),l&&s.success&&(t.output=s.output),r(s.success?"info":"warn","tool execution ended",t)},onToolExecutionStart:o=>{const s={tool:f(o)};u&&(s.input=g(o)),r("info","tool execution started",s)}}};export{E as consoleTelemetry};
@@ -0,0 +1 @@
1
+ import{F as g}from"./createDispatchRunner-pLyQ70FK-2_j6ocGT.mjs";import{LunoraError as o}from"@lunora/errors";import{h as l,B as p}from"./branch-marker-boZ00zmk.mjs";import{toFunctionReference as w,DEFAULT_AGENT_FUNCTION_PATHS as m}from"./AGENT_MODULE-M4D1EejI.mjs";const T=(r,s,i)=>{const c={},u=w(m.patchThread),d=()=>i??g({env:r,label:"@lunora/agent"});for(const e of s){const a=()=>{const n=r[e.binding];if(!n||typeof n.create!="function"||typeof n.get!="function")throw new o("INTERNAL",`@lunora/agent: no Workflow binding "${e.binding}" on env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return n};c[e.exportName]={cancel:async n=>{await(await a().get(n)).terminate();try{await d()(u,{instanceId:n,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(n,t)=>{if(l(n))throw new o("BAD_REQUEST",`@lunora/agent: run input ${p}`);return{id:(await a().create({...t?.id===void 0?{}:{id:t.id},params:n})).id}},sendEvent:async(n,t)=>{await(await a().get(n)).sendEvent(t)},status:async n=>(await a().get(n)).status()}}return c};export{T as default};
@@ -0,0 +1,3 @@
1
+ import{createAi as w}from"@lunora/ai";import{LunoraError as T}from"@lunora/errors";import{jsonSchema as x,generateText as d,Output as f,streamText as C,tool as A}from"ai";const y=t=>{if(!t)return;const e={};for(const o of["inputTokens","outputTokens","totalTokens"]){const n=t[o];n!==void 0&&(e[o]=n)}return Object.keys(e).length>0?e:void 0},g=t=>t.map(e=>({id:e.toolCallId,input:e.input,name:e.toolName})),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new T("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return w({binding:o,env:e}).model(t)}return t},b=(t,e)=>{const o=m(t.model,e),n={};for(const[a,i]of Object.entries(t.tools??{}))n[a]=A({description:i.description,inputSchema:i.inputSchema});const r=t.output===void 0?void 0:f.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:o,output:r,staticSettings:s,tools:n}},v=(t,{activeTools:e,messages:o,model:n,signal:r,toolChoice:s})=>{const{defaultModel:a,output:i,staticSettings:h,tools:c}=t,l=e===void 0?c:Object.fromEntries(Object.entries(c).filter(([p])=>e.includes(p)));return{messages:o,model:n??a,...h,...Object.keys(l).length>0?{tools:l}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...r===void 0?{}:{abortSignal:r}}},I=(t,e)=>{const o=b(t,e);return async n=>{const r=await d(v(o,n)),s=y(r.usage);return{text:r.text,toolCalls:g(r.toolCalls),...s===void 0?{}:{usage:s},...o.output===void 0?{}:{output:r.output}}}},q=(t,e)=>{const o=b(t,e);return async(n,r)=>{const s=C(v(o,n));let a="";try{for await(const u of s.textStream)a+=u,r(u)}catch(u){if(n.signal?.aborted)return{text:a,toolCalls:[]};throw u}const[i,h,c,l]=await Promise.all([s.text,s.toolCalls,s.usage,o.output===void 0?Promise.resolve(void 0):s.output]),p=y(c);return{text:i,toolCalls:g(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:l}}}},k=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),j=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
2
+ `),M=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{output:r}=await d({model:m(o,e),output:f.object({schema:k}),prompt:j(n,t)});return r},O=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
3
+ `),_=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{text:r}=await d({model:m(o,e),prompt:O(n,t)});return{summary:r.trim()}},E="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.",R=()=>async({env:t,messages:e,model:o})=>{const{text:n}=await d({messages:e,model:m(o,t),system:E});return n.trim()};export{I as createAgentGenerate,R as createCompact,_ as createEpisodeExtract,M as createGraphExtract,q as createStreamGenerate,m as resolveAgentModel};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";const T=(t,e,n)=>{if(e===void 0)return{dispose:()=>{},signal:t};const s=new AbortController,r=setTimeout(()=>{s.abort(n())},e);return{dispose:()=>{clearTimeout(r)},signal:s.signal}},a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",w=t=>{let e="",n=0;const s=t.length-2;for(;n<s;n+=3){const o=t[n]<<16|t[n+1]<<8|t[n+2];e+=a.charAt(o>>18&63)+a.charAt(o>>12&63)+a.charAt(o>>6&63)+a.charAt(o&63)}const r=t.length-n;if(r===1){const o=t[n]<<16;e+=a.charAt(o>>18&63)+a.charAt(o>>12&63)}else if(r===2){const o=t[n]<<16|t[n+1]<<8;e+=a.charAt(o>>18&63)+a.charAt(o>>12&63)+a.charAt(o>>6&63)}return e};new TextDecoder;const b=new TextEncoder,N="=",$=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},R=t=>w(b.encode(JSON.stringify(t))),v=t=>!t.startsWith(N)&&$(t)?t:`${N}${w(b.encode(t))}`,E="/_lunora/scheduler/dispatch",L=3e4,_=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},S=Symbol("lunoraDispatchFailure"),x=Symbol("lunoraDispatchMessageId"),A=(t,e)=>(Object.defineProperty(t,S,{value:!0}),e!==void 0&&Object.defineProperty(t,x,{value:e}),t),D=(t,e,n,s)=>{try{const r=JSON.parse(n)?.error;if(typeof r=="object"&&r!==null&&typeof r.code=="string"){const{code:o,data:u,message:l}=r;return A(new d(o,typeof l=="string"?l:void 0,{data:u,status:e}),s)}}catch{}return A(new d("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${n}`,{status:e}),s)},U=(t,e,n)=>new d("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(n)}ms`,{status:503}),M=t=>{const{label:e}=t,n=globalThis.fetch,s=t.fetchImpl??(typeof n=="function"?n.bind(globalThis):void 0);return async(r,o,u={})=>{if(typeof s!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const l=t.env.LUNORA_ORIGIN_URL;if(typeof l!="string"||l.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=t.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const I=`${_(l)}${E}`,p={authorization:`Bearer ${f}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(p["x-lunora-userid"]=v(t.identity.userId)),t.identity?.claims!==void 0&&(p["x-lunora-identity"]=R(t.identity.claims));const y=u.timeoutMs??L,m=T(void 0,y,()=>new DOMException(`dispatch timed out after ${String(y)}ms`,"TimeoutError")),g=i=>{throw i instanceof Error&&i.name==="TimeoutError"?U(e,r.__lunoraRef,y):i};let c;try{try{c=await s(I,{body:JSON.stringify({args:o??{},functionPath:r.__lunoraRef,id:u.dedupId,shardKey:u.shardKey}),headers:p,method:"POST",signal:m.signal})}catch(h){return g(h)}if(!c.ok){let h;try{h=await c.text()}catch(O){return g(O)}throw D(e,c.status,h,u.messageId)}let i;try{i=await c.text()}catch(h){return g(h)}if(i.length===0)return;try{return JSON.parse(i)}catch{throw new d("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(c.status)}): ${i}`,{status:c.status})}}finally{m.dispose()}}};export{M as F};
@@ -0,0 +1,3 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as h}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as f}from"./agentAsTool-DrFnh9UQ.mjs";import{i as m}from"./memory-JI0lUu84.mjs";import{SKILL_NAME_PATTERN as g,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const w=/^[a-zA-Z][\w-]*$/u,p=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,l]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=l}return o},T=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
2
+
3
+ `)},k=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},N=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!g.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},A=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},y=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},v=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&(!Number.isInteger(e.maxTurns)||e.maxTurns<1))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");const o=e.skills??[];N(o),y(e,o);const t=p(e,o),s=h(e,o);for(const[i,d]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=d}const l=Object.keys(s).length>0;A(e.activeTools,s);for(const i of Object.keys(t))if(!w.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const a=k(e,o),u=T(e,o);return{...e,asTool:f,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:u}:{},...a.length>0?{memorySources:a}:{},...o.length>0||l?{tools:t}:{}}},S=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,O=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{v as defineAgent,O as defineAgentTool,S as isAgentDefinition};
@@ -0,0 +1 @@
1
+ import{LunoraError as t}from"@lunora/errors";const i=/^[a-zA-Z][\w-]*$/u,r="default",o=e=>{if(typeof e.name!="string"||!i.test(e.name))throw new t("INTERNAL",`@lunora/agent: defineSkill requires a \`name\` that is a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(e.name)}`);if(e.name===r)throw new t("INTERNAL",`@lunora/agent: skill name "${r}" is reserved (it keys the agent's own \`memory\` source / the historic \`memory:retrieve\` step) — choose another name`);return{...e,isLunoraSkill:!0}},s=e=>typeof e=="object"&&e!==null&&e.isLunoraSkill===!0;export{r as RESERVED_SKILL_NAME,i as SKILL_NAME_PATTERN,o as defineSkill,s as isSkillDefinition};
@@ -0,0 +1 @@
1
+ import{LunoraError as o}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-M4D1EejI.mjs";const m=(r,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new o("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new o("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(r);return{description:e.description,execute:(i,n)=>n.run(t,{...i,idempotencyKey:n.idempotencyKey}),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{m as functionTool};
@@ -0,0 +1 @@
1
+ const s=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",o=e=>e.memorySources?e.memorySources:e.memory&&s(e.memory)?[{key:"default",...e.memory}]:[],i=e=>o(e).find(r=>r.kind==="graph"),c=e=>o(e).find(r=>r.kind==="episodic"),d=(e,r)=>r==="default"?e:`${e}:${r}`;export{c as a,i as f,s as i,d as m,o as r};
@@ -0,0 +1,2 @@
1
+ import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,a as f,d as S}from"./component-shared-IZozysYq.mjs";const T="entities",x="edges",b=`${_}_${T}`,g=`${_}_${x}`,X={[T]:A({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[x]:A({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},E=64,O=2,G=4,D=8,C=32,R=500,I=/\s+/gu,K=/[^\p{L}\p{N}]+/u,h=t=>t.trim().replaceAll(I," ").toLowerCase(),L=t=>t.toLowerCase().split(K).filter(o=>o.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,o)=>o.weight-t.weight||t.label.localeCompare(o.label)||t.srcName.localeCompare(o.srcName)||t.dstName.localeCompare(o.dstName),$=(t,o)=>o.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(o=>`- ${o.srcName} —[${o.label}]→ ${o.dstName}`).toSorted((o,n)=>o.localeCompare(n)).join(`
2
+ `),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,B=(t,o,n,r)=>{const a=H(t);r.collectedKeys.has(a)||(r.collectedKeys.add(a),r.collected.push(t));const l=t.srcName===o?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},F=async(t,o,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(o)};let a=o.slice(0,n.maxNodes);for(let l=0;l<n.depth&&a.length>0;l+=1){r.next=[];for(const m of a){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)B(s,m,n,r)}a=r.next}return r.collected},{mutation:M,query:W}=q.dataModel().create(),Y=()=>{const t=M.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:n,ctx:r})=>{const a=Date.now(),l=async(s,i)=>{const c=h(s);if(c.length===0)return;const d=await r.db.query(b).withIndex("byOwnerName",u=>u.eq("owner",n.owner).eq("name",c)).first();return d?(i!==void 0&&d.type===void 0&&await r.db.patch(d._id,{type:i,updatedAt:a}),c):(await r.db.insert(b,{createdAt:a,name:c,owner:n.owner,updatedAt:a,weight:1,...S({firstMessageKey:n.messageKey,type:i})}),c)},m=async s=>{const i=h(s.src),c=h(s.dst),d=h(s.label);if(i.length===0||c.length===0||d.length===0||i===c)return!1;await l(i),await l(c);const u=s.confidence??1,N=await r.db.query(g).withIndex("byTriple",y=>y.eq("owner",n.owner).eq("srcName",i).eq("label",d).eq("dstName",c)).first();if(N){const y=N.weight??1;await r.db.patch(N._id,{updatedAt:a,weight:Math.max(y,u)})}else await r.db.insert(g,{createdAt:a,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:a,weight:u});return!0};let w=0;for(const s of n.entities.slice(0,E))await l(s.name,s.type)!==void 0&&(w+=1);let p=0;for(const s of n.relations.slice(0,E))await m(s)&&(p+=1);return{entities:w,relations:p}}),o=W.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:n,ctx:r})=>{const a=L(n.query);if(a.length===0)return{context:""};const m=(await r.db.query(b).withIndex("byOwnerUpdatedAt",s=>s.eq("owner",n.owner)).order("desc").take(R)).filter(s=>$(s.name,a)).toSorted((s,i)=>(i.weight??1)-(s.weight??1)||s.name.localeCompare(i.name)).slice(0,n.maxSeeds??G).map(s=>s.name);if(m.length===0)return{context:""};const p=await F(async s=>{const[i,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",d=>d.eq("owner",n.owner).eq("srcName",s)).collect(),r.db.query(g).withIndex("byOwnerDst",d=>d.eq("owner",n.owner).eq("dstName",s)).collect()]);return[...i,...c].map(d=>P(d))},m,{depth:n.depth??O,fanOut:n.fanOut??D,maxNodes:n.maxNodes??C});return{context:v(p)}});return{agentGraphTraverse:f(o),agentGraphUpsert:f(t)}};export{Y as graphComponent,X as graphTables,h as normalizeEntityName};
@@ -0,0 +1 @@
1
+ import{a as H,r as m,t as z,s as B,e as C,c as D}from"./common-CJSjtsfv.mjs";const U=e=>`${String(Math.round(e))}000000`,L=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),O=512,V=new Uint8Array(O);let w=O;const v=(e,t,n)=>{let r="";for(let o=0;o<n;o+=1)r+=L[e[t+o]];return r},j=e=>{if(e>O){const n=new Uint8Array(e);return crypto.getRandomValues(n),v(n,0,e)}w+e>O&&(crypto.getRandomValues(V),w=0);const t=v(V,w,e);return w+=e,t},N=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},M=(e,t,n)=>{const r={},o=new Map,f=(c,d)=>{const x=c.toLowerCase(),b=o.get(x);b===void 0?(o.set(x,c),r[c]=d):r[b]=d};for(const[c,d]of Object.entries(e))f(c,d);for(const[c,d]of Object.entries(t??{}))f(c,d);return n!==void 0&&n.length>0&&f("authorization",`Bearer ${n}`),r},P=e=>Array.isArray(e)?e:[e],k=(e,t)=>{const n={"service.name":e};for(const[r,o]of Object.entries({}))n[r]=o;return Object.entries(n).map(([r,o])=>N(r,o))},F=(e,t,n,r)=>({resourceSpans:[{resource:{attributes:k(n)},scopeSpans:[{scope:{name:t},spans:P(e)}]}]}),s=(e,t,n)=>{if(n!=null){if(typeof n=="boolean"||typeof n=="number"||typeof n=="string"){e.push(N(t,n));return}e.push(N(t,JSON.stringify(n)))}},R=(e,t)=>{(async()=>{let r;try{r=await e}catch(o){t(!1,o instanceof Error?o.message:String(o),void 0);return}t(!0,void 0,r)})().catch(()=>{})},Y=e=>{const{conversationId:t,endpoint:n,headers:r,recordInputs:o=!1,recordOutputs:f=!1,token:c,traceId:d,waitUntil:x}=e,b=e.serviceName??"lunora";let y=n;for(;y.endsWith("/");)y=y.slice(0,-1);const $=`${y}/v1/traces`,E=M({"content-type":"application/json"},r,c),A=(i,p,u,g,I)=>{const h={attributes:I,endTimeUnixNano:U(Date.now()),kind:1,name:i,spanId:j(8),startTimeUnixNano:U(p),status:u?{code:1}:{code:2,message:g??""},traceId:d??j(16)};try{const _=fetch($,{body:JSON.stringify(F(h,"@lunora/agent",b)),headers:E,method:"POST"}).catch(()=>{});x?.(_)}catch{}};return{executeLanguageModelCall:i=>{const p=Date.now(),u=m(i,"modelId"),g=i.execute();return R(g,(h,_,l)=>{const a=[];s(a,"gen_ai.operation.name","chat"),s(a,"gen_ai.request.model",u),s(a,"gen_ai.system",m(i,"provider")),s(a,"gen_ai.conversation.id",t);const S=B(m(l,"usage"));S&&(s(a,"gen_ai.usage.input_tokens",S.inputTokens),s(a,"gen_ai.usage.output_tokens",S.outputTokens),s(a,"gen_ai.usage.total_tokens",S.totalTokens));const T=C(l);T&&(s(a,"gen_ai.usage.cost",T.cost),s(a,"gen_ai.response.cached",T.cached),s(a,"cf.aig.log_id",T.logId)),o&&s(a,"gen_ai.prompt",m(i,"messages")),f&&s(a,"gen_ai.completion",D(m(l,"content"))),A(typeof u=="string"?`chat ${u}`:"language_model_call",p,h,_,a)}),g},executeTool:i=>{const p=Date.now(),u=H(i),g=i.execute();return R(g,(h,_)=>{const l=[];s(l,"gen_ai.operation.name","execute_tool"),s(l,"gen_ai.tool.name",u),s(l,"gen_ai.tool.call.id",m(i,"toolCallId")),o&&s(l,"gen_ai.tool.input",z(i)),A(typeof u=="string"?`execute_tool ${u}`:"execute_tool",p,h,_,l)}),g}}};export{Y as otlpTelemetry};
@@ -0,0 +1,3 @@
1
+ import{d as J,b as _}from"./component-shared-IZozysYq.mjs";import{resolveAgentModel as Q}from"./createAgentGenerate-9bZ2YhpN.mjs";import{r as Y,f as Z,m as T,a as tt}from"./memory-JI0lUu84.mjs";import{buildModelMessages as D}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as F}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-M4D1EejI.mjs";const et=8,q=e=>e===void 0?"null":JSON.stringify(e),ot=e=>e===void 0?[]:[e].flat(),nt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),at=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const n={};for(const o of["inputTokens","outputTokens","totalTokens"])(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},st=async(e,t,n,o,a)=>{const{needsApproval:r}=e;return r===void 0||r===!1?!1:r===!0?!0:n.do(o,async()=>r(t,a))},rt="WorkflowTimeoutError",it=e=>e instanceof Error&&e.name===rt,O=4320*60*1e3,ct={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},ut=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,dt=e=>{if(e===void 0)return O;if(typeof e=="number")return Math.min(e,_);const t=ut.exec(e);return t===null?O:Math.min(Number(t[1])*ct[t[2]],_)},pt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:r,persist:i,step:u}=e;await i({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await r({status:"awaiting_input"});const c=await u.waitForEvent(`approval:${t.id}`,{timeout:dt(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note}})).catch(p=>{if(!it(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await r({status:"running"}),c},lt=async(e,t)=>{const{env:n,getState:o,instanceId:a,onTokenDelta:r,persist:i,run:u,setState:c,step:p,threadKey:s,tools:l}=e,d=`tool:${t.name}:${t.id}`,y=l[t.name],h=`${a}:tool:${t.id}`;if(!y){await i({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const C={env:n,getState:o,idempotencyKey:d,reportProgress:R=>{r?.({data:R,kind:"progress",threadKey:s,toolCallId:t.id})},run:u,setState:c,step:p,threadKey:s,toolCallId:t.id},v={env:n,getState:o,idempotencyKey:d,run:u,threadKey:s,toolCallId:t.id},S=`tool:approval-gate:${t.id}`;let f;if(await st(y,t.input,p,S,v)){const{decision:R,note:$}=await pt(e,t);if(R==="reject"){const N=$===void 0?"":` Reason: ${$}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${N}`,messageKey:h,role:"tool",status:"rejected",stepName:d,toolCallId:t.id,toolName:t.name});return}f="approved"}const M=await p.do(d,()=>Promise.resolve(y.execute(t.input,C)));await i({content:typeof M=="string"?M:q(M),messageKey:h,role:"tool",stepName:d,...f===void 0?{}:{status:f},toolCallId:t.id,toolName:t.name})},mt=(e,t,n)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:Q(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},yt=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},vt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,r=yt(t,n.compaction);if(r===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:a,messages:D({history:r.older}),model:n.compaction?.model??n.model});return i.length>0?{history:r.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},gt=async(e,t,n)=>{const{agent:o,env:a,generate:r,instructions:i,listMessages:u,memoryContext:c,onTokenDelta:p,run:s,step:l,streamGenerate:d,threadKey:y}=e;return l.do(`llm:turn:${String(t)}`,async()=>{const h=await s(u,{key:y}),{history:x,summary:C}=await vt(e,h);let v={activeTools:o.activeTools,messages:D({history:x,instructions:i,memoryContext:c,summary:C}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=mt(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:n}),a));const S={messages:v.messages,...v.activeTools===void 0?{}:{activeTools:v.activeTools},...v.model===void 0?{}:{model:v.model},...v.toolChoice===void 0?{}:{toolChoice:v.toolChoice}};return d&&p?d(S,f=>{p({text:f,threadKey:y,turn:t})}):r(S)})},P=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.onStepFinish?.(t),!0))},ht=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}}),A=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ft=e=>J({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),wt=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:r}=e,i=T("memory:retrieve",e.key),u=await n.do(i,async()=>o(a,{query:t,...r===void 0?{}:{topK:r}}));return A(u)},Tt=async(e,t,n,o,a,r)=>{if(n===void 0)return;const i=T("memory:traverse",e.key),u=await a.do(i,async()=>r(o,{owner:n,query:t,...ft(e.graph)}));return A(u)},xt=async(e,t,n,o,a)=>{if(t===void 0)return;const r=T("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},u=await o.do(r,async()=>a(n,i));return A(u)},St=async(e,t)=>e.kind==="episodic"?xt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Tt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):wt(e,t.input,t.step,t.run),Ct=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Mt=async(e,t,n,o,a,r)=>{const i=Ct(Y(e));if(i.length===0)return;const u=g(o.graphTraverse),c=g(o.episodeRecall),p=[];for(const s of i){const l=await St(s,{episodeRecall:c,graphTraverse:u,input:t,owner:n,run:r,step:a});l!==void 0&&p.push(l)}return p.length>0?p.join(`
2
+
3
+ `):void 0},Rt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:r,instanceId:i,owner:u,paths:c,run:p,step:s}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const l=Z(t);if(l!==void 0)try{const d={assistantText:a,env:n,model:l.graph?.extractionModel??t.model,userInput:r},y=await s.do(T("memory:extract",l.key),async()=>o(d));await p(g(c.graphUpsert),{...y,messageKey:`${i}:${T("extract",l.key)}`,owner:u})}catch{}},kt=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:r,instanceId:i,owner:u,paths:c,run:p,step:s,threadKey:l}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const d=tt(t);if(d!==void 0)try{const y={assistantText:a,env:n,model:d.episodic?.extractionModel??t.model,userInput:r},{summary:h}=await s.do(T("memory:episode",d.key),async()=>o(y));await p(g(c.episodeUpsert),{messageKey:`${i}:${T("episode",d.key)}`,owner:u,summary:h,threadKey:l})}catch{}},$t=async(e,t,n)=>{const o=e[F(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(n)).terminate()}catch{}},Kt="12 hours",Et=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Kt,type:`agent-dequeue:${t}:${n}`})},Nt=async(e,t,n)=>{const o=e.env[F(e.exportName)];if(!o||typeof o.get!="function")return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},It=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},At=async(e,t,n,o,a)=>{const{instanceId:r,persist:i}=e,u=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const c=n.output!==void 0&&n.text.length===0?q(n.output):n.text;return await i({content:c,messageKey:`${r}:assistant:${String(t)}`,role:"assistant"}),await P(e,{text:n.text,toolCalls:[],turn:t,...u}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await i({content:n.text,messageKey:`${r}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const c of n.toolCalls)await lt(e,c);if(await P(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...u}),o.push(ht(n)),a.length>0&&await nt(a,o))return"stopCondition"},Ut=async(e,t,n,o)=>{const a=[];let r,i=!1,u=0;for(let c=0;c<t;c+=1){const p=await gt(e,c,a);o.value=at(o.value,p.usage),u=c+1;const s=await At(e,c,p,a,n);if(s==="stopCondition"){i=!0;break}if(s!==void 0){r=s.final;break}}return{final:r,stoppedByCondition:i,turnsRun:u}},jt=async e=>{const{agent:t,compact:n,env:o,exportName:a,extractEpisode:r,extractGraph:i,generate:u,instanceId:c,onTokenDelta:p,params:s,paths:l,run:d,step:y,streamGenerate:h}=e,x=t.maxTurns??et,C=ot(t.stopWhen),v=g(l.appendMessage),S=g(l.completeRun),f=g(l.ensureThread),M=g(l.listMessages),R=g(l.deleteMessage),$=g(l.patchThread),N=g(l.setState),j=g(l.state),U=async m=>{await d(v,{threadKey:s.threadKey,...m})},B=async m=>{await d($,{key:s.threadKey,...m})},G=async m=>{await d(R,{messageKey:m,threadKey:s.threadKey})},L=async()=>{await U({content:s.input,messageKey:`${c}:user`,role:"user"})},K=async m=>{const E=await d(S,{instanceId:c,key:s.threadKey,...m});E?.dequeued!==void 0&&await Nt({env:o,exportName:a,step:y},s.threadKey,E.dequeued)},b=async()=>await d(j,{key:s.threadKey}),W=async m=>{await d(N,{key:s.threadKey,state:m})},I=await d(f,{agent:a,instanceId:c,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});I?.outcome==="replaced"&&await $t(o,a,I.priorInstanceId);const H=await Mt(t,s.input,s.owner,l,y,d),V=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,X={agent:t,compact:n,env:o,generate:u,getState:b,instanceId:c,instructions:V,listMessages:M,memoryContext:H,onTokenDelta:p,deleteMessage:G,patchThread:B,persist:U,run:d,setState:W,step:y,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},k={value:void 0};try{I?.outcome==="queued"&&await Et(y,s.threadKey,c),await L();const{final:m,stoppedByCondition:E,turnsRun:z}=await Ut(X,x,C,k),w=k.value===void 0?{}:{usage:k.value};return await Rt({agent:t,env:o,extractGraph:i,finalText:m?.text,input:s.input,instanceId:c,owner:s.owner,paths:l,run:d,step:y}),await kt({agent:t,env:o,extractEpisode:r,finalText:m?.text,input:s.input,instanceId:c,owner:s.owner,paths:l,run:d,step:y,threadKey:s.threadKey}),m?(await It(t,{env:o,params:s,step:y},{...m,...w}),await K({status:"idle",...w}),{...m,...w}):E?(await K({status:"idle",...w}),{stopped:"stopCondition",turns:z,...w}):(await K({error:`agent stopped: maxTurns (${String(x)}) reached`,status:"error",...w}),{stopped:"maxTurns",turns:x,...w})}catch(m){throw await K({error:m instanceof Error?m.message:String(m),status:"error",...k.value===void 0?{}:{usage:k.value}}),m}};export{jt as runAgentLoop,yt as splitForCompaction};
@@ -0,0 +1 @@
1
+ import"./base64-5eyBfWO3.mjs";import{p as s,c as i,f as p,e as n,r as m,t as c}from"./voice-turn-DbVR0H6T.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as t}from"@lunora/values";import{t as g}from"./base64-5eyBfWO3.mjs";const{internalAction:w}=h.dataModel().create(),m=()=>globalThis.document?.documentElement?.outerHTML??"",l=1e6,b=20,x=new TextEncoder,y=async(e,n)=>{const o=n.url??"";switch(n.op){case"content":return e.content(o);case"pdf":return{data:g(await e.pdf(o)),encoding:"base64",mediaType:"application/pdf"};case"scrape":return e.scrape(o,m);case"screenshot":{const s=await e.screenshot(o,{...n.fullPage===void 0?{}:{fullPage:n.fullPage},...n.type===void 0?{}:{type:n.type}});return{data:g(s),encoding:"base64",mediaType:n.type==="jpeg"?"image/jpeg":"image/png"}}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${n.op}" is not supported`)}},E=e=>{const n=[`exit code: ${String(e.code)}`];return e.stdout.length>0&&n.push(`stdout:
2
+ ${e.stdout}`),e.stderr.length>0&&n.push(`stderr:
3
+ ${e.stderr}`),n.join(`
4
+
5
+ `)},$=async(e,n)=>{const o=e.any();if(n.op==="exec")try{return E(await o.exec(n.command??"",{args:n.args??[]}))}catch(s){return`exec failed: ${s instanceof Error?s.message:String(s)}`}if(n.op==="fetch")return(await o.fetch(n.path??"/",{...n.body===void 0?{}:{body:n.body},method:n.method??"GET"})).text();throw new c("INTERNAL",`@lunora/agent: sandbox container op "${n.op}" is not supported`)},u=e=>{let n=0,o=e.length;for(;n<o&&e[n]==="/";)n+=1;for(;o>n&&e[o-1]==="/";)o-=1;return e.slice(n,o)},T=(e,n)=>{const o=u(e),s=[];for(const r of n.split("/"))if(!(r===""||r===".")){if(r===".."){if(s.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");s.pop();continue}s.push(r)}const a=s.join("/");return o&&a?`${o}/${a}`:o||a},S=async(e,n,o)=>{const s=n.length>0?`${n}/`:"",a=o.length>0?o.length+1:0,r=[];let i;for(let d=0;d<b;d+=1){const p=await e.list({prefix:s,...i===void 0?{}:{cursor:i}});for(const f of p.objects)r.push(f.key.slice(a));if(!p.truncated||p.cursor===void 0)return{entries:r,truncated:!1};i=p.cursor}return{entries:r,truncated:!0}},N=async(e,n,o)=>{const s=u(n),a=T(n,o.path??"");switch(o.op){case"ls":{const{entries:r,truncated:i}=await S(e,a,s);return i?{entries:r,truncated:!0}:{entries:r}}case"read":{const r=await e.head(a);if(r&&r.size>l)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${o.path??""}" is ${String(r.size)} bytes (max ${String(l)})`);const i=await e.get(a);if(!i)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${o.path??""}"`);return i.text()}case"rm":return await e.delete(a),{path:o.path??"",removed:!0};case"stat":{const r=await e.head(a);return r?{exists:!0,size:r.size}:{exists:!1}}case"write":{const r=o.content??"",i=x.encode(r).length;if(i>l)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(i)} bytes exceeds the max (${String(l)})`);return await e.put(a,r),{bytes:i,path:o.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${o.op}" is not supported`)}},_=()=>({invoke:w.input({args:t.optional(t.array(t.string())),body:t.optional(t.string()),bucket:t.optional(t.string()),command:t.optional(t.string()),content:t.optional(t.string()),fullPage:t.optional(t.boolean()),kind:t.union(t.literal("browser"),t.literal("container"),t.literal("fs")),method:t.optional(t.string()),name:t.optional(t.string()),op:t.string(),path:t.optional(t.string()),root:t.optional(t.string()),selector:t.optional(t.string()),type:t.optional(t.string()),url:t.optional(t.string())}).action(async({args:n,ctx:o})=>{const s=o,a=n;if(a.kind==="browser"){if(!s.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return y(s.browser,a)}if(a.kind==="fs"){const d=s.env?.[a.bucket??""];if(!d||typeof d.get!="function")throw new c("INTERNAL",`@lunora/agent: sandbox fs op found no R2 bucket "${a.bucket??""}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`);return N(d,a.root??"",a)}const r=a.name??"",i=s.containers?.[r];if(!i)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${r}"] — declare the container in lunora/containers.ts and run codegen`);return $(i,a)})});export{T as resolveFsKey,N as runFsOp,_ as sandboxComponent};
@@ -0,0 +1 @@
1
+ import{r as t,t as i}from"./common-CJSjtsfv.mjs";const l=(a,n)=>typeof a=="string"&&a.length>0?a:n,s=a=>{const{functionId:n,recordInputs:g=!1,Sentry:r}=a;return{executeLanguageModelCall:e=>{const o={"gen_ai.operation.name":l(n,"language_model_call"),"gen_ai.request.model":t(e,"modelId"),"gen_ai.system":t(e,"provider")};return g&&(o["gen_ai.prompt"]=t(e,"messages")),r.startSpan({attributes:o,name:l(n,"language_model_call"),op:"gen_ai.generate"},()=>e.execute())},executeTool:e=>{const o=t(t(e,"toolCall"),"toolName"),c={"gen_ai.operation.name":"execute_tool","gen_ai.tool.call.id":t(e,"toolCallId"),"gen_ai.tool.name":o};return g&&(c["gen_ai.tool.input"]=i(e)),r.startSpan({attributes:c,name:`execute_tool ${l(o,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onError:e=>{r.captureException(e)}}};export{s as sentryTelemetry};