@lunora/agent 1.0.0-alpha.16 → 1.0.0-alpha.160
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels.d.mts +23 -12
- package/dist/channels.d.ts +23 -12
- package/dist/channels.mjs +1 -1
- package/dist/component.d.mts +2 -0
- package/dist/component.d.ts +2 -0
- package/dist/component.mjs +2 -2
- package/dist/inbound.d.mts +9 -7
- package/dist/inbound.d.ts +9 -7
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +62 -15
- package/dist/index.d.ts +62 -15
- package/dist/index.mjs +1 -1
- package/dist/naming.d.mts +3 -7
- package/dist/naming.d.ts +3 -7
- package/dist/naming.mjs +1 -1
- package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-Dc09ClZz.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
- package/dist/packem_shared/agent-loop-CQUKMFWA.mjs +3 -0
- package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
- package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
- package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
- package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-Dijgn4Cz.mjs +1 -0
- package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
- package/dist/packem_shared/createAgentContext-D3mf7LEU.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
- package/dist/packem_shared/defineAgent-CK3CpiOr.mjs +3 -0
- package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-BLOvjXGF.mjs +18 -0
- package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-DFDJPAyk.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-xFvfDZ2Q.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-CKX-iNXC.mjs +7 -0
- package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
- package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-CbYtFBw9.d.mts} +289 -27
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-CbYtFBw9.d.ts} +289 -27
- package/dist/packem_shared/voice-turn-BiDZeZwp.mjs +1 -0
- package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
- package/dist/reply.d.mts +40 -0
- package/dist/reply.d.ts +40 -0
- package/dist/reply.mjs +1 -0
- package/dist/sandbox.d.mts +114 -16
- package/dist/sandbox.d.ts +114 -16
- package/dist/sandbox.mjs +1 -1
- package/dist/skill-markdown.d.mts +36 -0
- package/dist/skill-markdown.d.ts +36 -0
- package/dist/skill-markdown.mjs +1 -0
- package/dist/telemetry/index.d.mts +152 -33
- package/dist/telemetry/index.d.ts +152 -33
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +18 -9
- package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
- package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
- package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
- package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
- package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
- package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
- package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
- package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
- package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
- package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
- package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
- package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
- package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
- package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
- package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
- package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
- package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
- package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
- package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
- package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
- package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
- package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
- package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
- package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
- package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { A as AgentDefinition,
|
|
2
|
-
export type {
|
|
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, z as SkillConfig } from "./packem_shared/types.d-CbYtFBw9.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, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
|
-
export {
|
|
6
|
-
export {
|
|
5
|
+
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
|
|
6
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
|
|
7
7
|
import { createAi } from '@lunora/ai';
|
|
8
8
|
import { WorkflowDefinition } from '@lunora/workflow';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
|
|
|
23
23
|
env: Record<string, unknown>;
|
|
24
24
|
/** The agent's `lunora/agents.ts` export name (thread attribution). */
|
|
25
25
|
exportName: string;
|
|
26
|
+
/** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
|
|
27
|
+
exports?: unknown;
|
|
26
28
|
/**
|
|
27
29
|
* The run-end episode-summary seam — production wires AI SDK `generateText`.
|
|
28
30
|
* Absent (the default) disables episode recording, so an agent with no
|
|
@@ -183,7 +185,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
|
|
|
183
185
|
interface ToolScriptStep {
|
|
184
186
|
/** A stable name later steps reference the output by. */
|
|
185
187
|
id: string;
|
|
186
|
-
/** The tool's input; values may embed `{ "$from": "
|
|
188
|
+
/** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
|
|
187
189
|
input?: Record<string, unknown>;
|
|
188
190
|
/** The tool to call — one of the tools handed to {@link codeTool}. */
|
|
189
191
|
tool: string;
|
|
@@ -229,8 +231,8 @@ interface CodeToolOptions {
|
|
|
229
231
|
* SCRIPT that composes several of the tools you hand `codeTool` — chaining a
|
|
230
232
|
* later call's input to an earlier call's output — and the whole thing runs in a
|
|
231
233
|
* single turn. This is a SAFE interpreted data-flow between whitelisted tools
|
|
232
|
-
* (no `eval`, no isolate), so it runs natively in workerd; arbitrary
|
|
233
|
-
*
|
|
234
|
+
* (no `eval`, no isolate), so it runs natively in workerd; for arbitrary code
|
|
235
|
+
* in a Worker Loader isolate, see `jsCodeTool`.
|
|
234
236
|
*
|
|
235
237
|
* Each composed tool dispatches through the same durable context a normal call
|
|
236
238
|
* gets (inheriting RLS), with a per-step idempotency key. A code-mode script runs
|
|
@@ -239,6 +241,16 @@ interface CodeToolOptions {
|
|
|
239
241
|
* keep approval-gated tools as normal top-level tools. Gate the whole script via
|
|
240
242
|
* `opts.needsApproval` instead.
|
|
241
243
|
*
|
|
244
|
+
* STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
|
|
245
|
+
* step runs inside its own durable `step.do`, so the workflow host serializes
|
|
246
|
+
* the returned value before the next step (or the tool result) ever sees it. A
|
|
247
|
+
* `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
|
|
248
|
+
* `null` or a dropped key, and a `bigint` throws outright. That applies to the
|
|
249
|
+
* value a later step reads through `{ "$from": … }` just as much as to the
|
|
250
|
+
* returned `results` — the hand-off is durable state, not an in-memory one. A
|
|
251
|
+
* composed tool that wants to pass a rich value should return its JSON form
|
|
252
|
+
* (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
|
|
253
|
+
*
|
|
242
254
|
* ```ts
|
|
243
255
|
* import { codeTool, defineAgent, functionTool } from "@lunora/agent";
|
|
244
256
|
*
|
|
@@ -259,8 +271,9 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
|
|
|
259
271
|
/**
|
|
260
272
|
* Build the `ctx.agents` producer surface from the codegen-emitted spec list
|
|
261
273
|
* (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
|
|
262
|
-
* declared agent resolves its
|
|
263
|
-
*
|
|
274
|
+
* declared agent resolves by its export key (the generated class name) off the
|
|
275
|
+
* invoking context's `exports` — or `env`, on a host without workflow exports —
|
|
276
|
+
* lazily, so a missing agent only errors when it is actually started.
|
|
264
277
|
*
|
|
265
278
|
* `cancel` also needs to write the thread's status, so it dispatches the agent
|
|
266
279
|
* runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
|
|
@@ -269,7 +282,10 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
|
|
|
269
282
|
* inject a `dispatch` double.
|
|
270
283
|
* @experimental
|
|
271
284
|
*/
|
|
272
|
-
declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>,
|
|
285
|
+
declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
|
|
286
|
+
dispatch?: AgentRunFunction;
|
|
287
|
+
exports?: unknown;
|
|
288
|
+
}) => Record<string, AgentHandle>;
|
|
273
289
|
/**
|
|
274
290
|
* Declare a durable agent. The definition compiles onto a Cloudflare Workflow
|
|
275
291
|
* (each LLM turn and each tool call a named durable step; thread messages
|
|
@@ -344,8 +360,14 @@ interface FunctionToolOptions<Input> {
|
|
|
344
360
|
* ```
|
|
345
361
|
*
|
|
346
362
|
* The function reference may be a typed `api.*` reference or a `"module:name"`
|
|
347
|
-
* path. The model-provided input is passed
|
|
348
|
-
* `inputSchema` should mirror the referenced function's argument validator
|
|
363
|
+
* path. The model-provided input is passed as the function's args, so
|
|
364
|
+
* `inputSchema` should mirror the referenced function's argument validator —
|
|
365
|
+
* PLUS the call's `idempotencyKey`, pinned onto the args after the model
|
|
366
|
+
* input (so out-of-schema model input can never override it). A function
|
|
367
|
+
* that wants to dedupe a side-effecting call across an at-least-once step
|
|
368
|
+
* retry declares `idempotencyKey: v.optional(v.string())` in its own args
|
|
369
|
+
* and checks it; a function that ignores it is unaffected — an args field
|
|
370
|
+
* the function's own validator doesn't declare is dropped, not rejected.
|
|
349
371
|
* @experimental
|
|
350
372
|
*/
|
|
351
373
|
declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
|
|
@@ -471,6 +493,17 @@ interface McpToolsOptions {
|
|
|
471
493
|
command?: string;
|
|
472
494
|
/** Identify this client to the server on connect. Default `"lunora-agent"`. */
|
|
473
495
|
name?: string;
|
|
496
|
+
/**
|
|
497
|
+
* Gate an adapted tool's call behind a human approval. Defaults to
|
|
498
|
+
* **unattended** (no gate) — matching today's behavior. An MCP tool's
|
|
499
|
+
* result feeds back into the model's context (`adaptMcpResult`), so a
|
|
500
|
+
* hostile downstream server can pair indirect prompt injection with an
|
|
501
|
+
* unattended mutating tool call; pass a boolean to gate every adapted
|
|
502
|
+
* tool the same way, or a predicate `(toolName, input) => boolean` to
|
|
503
|
+
* gate per tool (evaluated from replay-stable input, so keep it
|
|
504
|
+
* deterministic).
|
|
505
|
+
*/
|
|
506
|
+
needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
|
|
474
507
|
/** Only adapt these tool names (default: every tool the server lists). */
|
|
475
508
|
only?: ReadonlyArray<string>;
|
|
476
509
|
/** Prefix added to each adapted tool's key (disambiguate multiple servers). */
|
|
@@ -510,6 +543,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
|
|
|
510
543
|
* every call. In the Workers runtime only the HTTP/SSE transports run (stdio
|
|
511
544
|
* does not) — pass `url`, or inject an already-connected `client` for a custom
|
|
512
545
|
* transport (also the test seam).
|
|
546
|
+
*
|
|
547
|
+
* Every adapted tool runs UNATTENDED by default (no approval gate) — pass
|
|
548
|
+
* `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
|
|
513
549
|
* @experimental
|
|
514
550
|
*/
|
|
515
551
|
declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
|
|
@@ -674,6 +710,13 @@ interface VoiceTurnResult {
|
|
|
674
710
|
interface RunVoiceTurnOptions {
|
|
675
711
|
/** The agent whose thread + models back this session. */
|
|
676
712
|
agent: AgentDefinition;
|
|
713
|
+
/**
|
|
714
|
+
* History-compaction seam — the SAME one the durable loop uses. Voice and
|
|
715
|
+
* text turns share one thread, so an agent that declares `compaction` must
|
|
716
|
+
* get it here too; absent (or with no `compaction` config) the turn takes
|
|
717
|
+
* the byte-identical uncompacted path.
|
|
718
|
+
*/
|
|
719
|
+
compact?: AgentCompact;
|
|
677
720
|
/** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
|
|
678
721
|
connectionId: string;
|
|
679
722
|
/** The Worker env (resolves a dynamic `instructions` thunk). */
|
|
@@ -755,6 +798,8 @@ declare class VoiceSessionDO {
|
|
|
755
798
|
protected readonly streamGenerate: AgentStreamGenerate;
|
|
756
799
|
protected readonly sttModel: string;
|
|
757
800
|
protected readonly ttsModel: string;
|
|
801
|
+
/** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
|
|
802
|
+
private readonly maxSessionTurns;
|
|
758
803
|
private readonly audioBuffers;
|
|
759
804
|
private readonly bufferedBytes;
|
|
760
805
|
private readonly controllers;
|
|
@@ -793,6 +838,8 @@ declare class VoiceSessionDO {
|
|
|
793
838
|
private synthesizeWithSignal;
|
|
794
839
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
840
|
private cleanupSocket;
|
|
841
|
+
/** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
|
|
842
|
+
private closeSocket;
|
|
796
843
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
797
844
|
private send;
|
|
798
845
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
|
@@ -808,15 +855,15 @@ declare class VoiceSessionDO {
|
|
|
808
855
|
}
|
|
809
856
|
/**
|
|
810
857
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
858
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
859
|
*
|
|
813
860
|
* ```ts
|
|
814
861
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
862
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
863
|
* import { support } from "../agents.js";
|
|
817
864
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
865
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
866
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
867
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
868
|
* }
|
|
822
869
|
* }
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as t,s as r}from"./packem_shared/agent-loop-CQUKMFWA.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-1Gwq45M3.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-D3mf7LEU.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CK3CpiOr.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";import{adaptMcpResult as k,mcpTools as v}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as R}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as b,agentDefaultName as h,voiceBindingName as w,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 y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as q,containerTool as z,fsTool as J}from"./sandbox.mjs";import{defineSkill as Y,isSkillDefinition as Z}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ee}from"./packem_shared/VoiceSessionDO-Dc09ClZz.mjs";import{r as te}from"./packem_shared/voice-turn-BiDZeZwp.mjs";import{default as ne}from"./packem_shared/compileAgentWorkflow-Dijgn4Cz.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,ee as VoiceSessionDO,k as adaptMcpResult,s as agentAsTool,b as agentClassName,c as agentComponent,h as agentDefaultName,x as agentExtension,q as browserTool,R as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,ne as compileAgentWorkflow,z as containerTool,T as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Y as defineSkill,J as fsTool,D as functionTool,N as isAgentDefinition,Z as isSkillDefinition,L as jsCodeTool,v as mcpTools,G as resolveAgentModel,t as runAgentLoop,te as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,w as voiceBindingName,H as voiceClassName};
|
package/dist/naming.d.mts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name
|
|
2
|
+
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
|
|
3
|
+
* and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
|
|
3
4
|
* @experimental
|
|
4
5
|
*/
|
|
5
6
|
declare const agentClassName: (exportName: string) => string;
|
|
6
|
-
/**
|
|
7
|
-
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
-
* @experimental
|
|
9
|
-
*/
|
|
10
|
-
declare const agentBindingName: (exportName: string) => string;
|
|
11
7
|
/**
|
|
12
8
|
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
9
|
* @experimental
|
|
@@ -27,4 +23,4 @@ declare const voiceClassName: (exportName: string) => string;
|
|
|
27
23
|
* @experimental
|
|
28
24
|
*/
|
|
29
25
|
declare const voiceBindingName: (exportName: string) => string;
|
|
30
|
-
export {
|
|
26
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
package/dist/naming.d.ts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name
|
|
2
|
+
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
|
|
3
|
+
* and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
|
|
3
4
|
* @experimental
|
|
4
5
|
*/
|
|
5
6
|
declare const agentClassName: (exportName: string) => string;
|
|
6
|
-
/**
|
|
7
|
-
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
-
* @experimental
|
|
9
|
-
*/
|
|
10
|
-
declare const agentBindingName: (exportName: string) => string;
|
|
11
7
|
/**
|
|
12
8
|
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
9
|
* @experimental
|
|
@@ -27,4 +23,4 @@ declare const voiceClassName: (exportName: string) => string;
|
|
|
27
23
|
* @experimental
|
|
28
24
|
*/
|
|
29
25
|
declare const voiceBindingName: (exportName: string) => string;
|
|
30
|
-
export {
|
|
26
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
package/dist/naming.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`
|
|
1
|
+
const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,c=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,o=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{s as agentClassName,t as agentDefaultName,o as voiceBindingName,c 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{LunoraError as b,isLunoraError as D}from"@lunora/errors";const k="DISPATCH_IN_PROGRESS",B="x-lunora-dispatch-declined",M=(r,e,o)=>{if(e===void 0)return{dispose:()=>{},signal:r};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},e);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},A=r=>{let e="";for(let o=0;o<r.length;o+=32768)e+=String.fromCharCode(...r.subarray(o,o+32768));return btoa(e)},C=r=>{const e=atob(r),o=new Uint8Array(e.length);for(let a=0;a<e.length;a+=1)o[a]=e.codePointAt(a)??0;return o},p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",j=r=>{let e="",o=0;const a=r.length-2;for(;o<a;o+=3){const t=r[o]<<16|r[o+1]<<8|r[o+2];e+=p.charAt(t>>18&63)+p.charAt(t>>12&63)+p.charAt(t>>6&63)+p.charAt(t&63)}const n=r.length-o;if(n===1){const t=r[o]<<16;e+=p.charAt(t>>18&63)+p.charAt(t>>12&63)}else if(n===2){const t=r[o]<<16|r[o+1]<<8;e+=p.charAt(t>>18&63)+p.charAt(t>>12&63)+p.charAt(t>>6&63)}return e};new TextDecoder;const _=new TextEncoder,S="=",J=r=>{for(let e=0;e<r.length;e+=1)if(r.charCodeAt(e)>255)return!1;return!0},K=r=>j(_.encode(JSON.stringify(r))),F=r=>!r.startsWith(S)&&J(r)?r:`${S}${j(_.encode(r))}`,u="$lunora.wire$",E=64,$=1024,v="__proto__",I={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},R={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},H=r=>{if(r===null||typeof r!="object")return!1;const e=Object.getPrototypeOf(r);return e===null||e===Object.prototype},h=(r,e=0)=>{if(e>E)throw new RangeError(`wire-codec: value nesting exceeds the ${E}-level limit`);if(r===void 0)return[u,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint")return[u,"bigint",r.toString()];if(o==="number"){const t=r;return Number.isNaN(t)?[u,"nan"]:t===1/0?[u,"inf"]:t===-1/0?[u,"-inf"]:t}if(o!=="object")return r;if(r instanceof Date)return[u,"date",h(r.getTime(),e+1)];if(r instanceof Error){const t=r,s={};for(const c of Object.keys(t)){if(t[c]===void 0)continue;const f=h(t[c],e+1);c===v?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:f,writable:!0}):s[c]=f}const i=[u,"error",String(t.name),String(t.message),s];return t.cause!==void 0&&i.push(h(t.cause,e+1)),i}if(r instanceof URL)return[u,"url",r.href];if(r instanceof Map)return[u,"map",[...r.entries()].map(([t,s])=>[h(t,e+1),h(s,e+1)])];if(r instanceof Set)return[u,"set",[...r].map(t=>h(t,e+1))];if(r instanceof ArrayBuffer)return[u,"bytes",A(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const t=r,s=t.constructor.name,i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return s==="Uint8Array"?[u,"bytes",A(i)]:[u,"bytes",A(i),s]}if(Array.isArray(r)){const t=r.map(s=>h(s,e+1));return t.length>0&&t[0]===u?[u,"arr",t]:t}if(!H(r)){const t=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,n={};for(const t of Object.keys(a)){const s=a[t];if(s===void 0)continue;const i=h(s,e+1);t===v?Object.defineProperty(n,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[t]=i}return n},l=(r,e=0)=>{if(e>E)throw new RangeError(`wire-codec: value nesting exceeds the ${E}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===u)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(n=>l(n,e+1));case"bigint":{const n=r[2];if(typeof n!="string"||n.length>$||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${$} digits)`);return BigInt(n)}case"date":{const n=l(r[2],e+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=r[2];return new Map(n.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[l(t[0],e+1),l(t[1],e+1)]}))}case"set":return new Set(r[2].map(n=>l(n,e+1)));case"url":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=r[2],t=r[3];if(typeof n!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(R,n)?R[n]:void 0)??Error,i=new s(t);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=l(r[4],e+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const f of Object.keys(c))f===v?Object.defineProperty(i,f,{configurable:!0,enumerable:!0,value:c[f],writable:!0}):i[f]=c[f];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:l(r[5],e+1),writable:!0}),i}case"bytes":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=C(n);if(A(t)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=r[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(I,s)?I[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(n=>l(n,e+1))}return r.map(n=>l(n,e+1))}const o=r,a={};for(const n of Object.keys(o)){const t=l(o[n],e+1);n===v?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:t,writable:!0}):a[n]=t}return a},W=(r,e,o)=>{try{return h(o)}catch(a){throw new TypeError(`${r}: cannot encode args for '${e}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},G="/_lunora/scheduler/dispatch",z=3e4,V=r=>{let e=r.length;for(;e>0&&r[e-1]==="/";)e-=1;return r.slice(0,e)},U=Symbol("lunoraDispatchFailure"),Q=Symbol("lunoraDispatchDecline"),X=Symbol("lunoraDispatchMessageId"),L=(r,e)=>(e!==void 0&&Object.defineProperty(r,X,{value:e}),r),Y=(r,e)=>(Object.defineProperty(r,U,{value:!0}),L(r,e)),Z=(r,e,o,a)=>{const{status:n}=e;try{const t=JSON.parse(o)?.error;if(typeof t=="object"&&t!==null&&typeof t.code=="string"){const{code:s,data:i,message:c}=t,f=Y(new b(s,typeof c=="string"?c:void 0,{data:i,status:n}),a);return e.headers.get(B)==="1"&&Object.defineProperty(f,Q,{value:!0}),f}}catch{}return L(new b("INTERNAL",`${r}: function dispatch failed (${String(n)}): ${o}`,{status:n}),a)},q=new Set([400,403,404,422]),rr=new Set([k,"DISPATCH_UNAUTHENTICATED"]),tr=r=>D(r)&&r[U]===!0,or=r=>tr(r)&&q.has(r.status)&&!rr.has(r.code),er=(r,e,o)=>new b("INTERNAL",`${r}: function dispatch to "${e}" timed out after ${String(o)}ms`,{status:503}),ar=r=>{const{label:e}=r,o=globalThis.fetch,a=r.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,t,s={})=>{if(typeof a!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>r.argsAlreadyEncoded===!0?t??{}:W(e,n.__lunoraRef,t??{}),c=r.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new b("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=r.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new b("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const P=`${V(c)}${G}`,w={authorization:`Bearer ${f}`,"content-type":"application/json"};r.traceparent!==void 0&&r.traceparent.length>0&&(w.traceparent=r.traceparent),r.identity?.userId!==void 0&&(w["x-lunora-userid"]=F(r.identity.userId)),r.identity?.claims!==void 0&&(w["x-lunora-identity"]=K(r.identity.claims));const O=s.timeoutMs??z,T=M(void 0,O,()=>new DOMException(`dispatch timed out after ${String(O)}ms`,"TimeoutError")),N=y=>{throw y instanceof Error&&y.name==="TimeoutError"?er(e,n.__lunoraRef,O):y};let d;try{try{d=await a(P,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:w,method:"POST",signal:T.signal})}catch(m){return N(m)}if(!d.ok){let m;try{m=await d.text()}catch(x){return N(x)}throw Z(e,d,m,s.messageId)}let y;try{y=await d.text()}catch(m){return N(m)}if(y.length===0)return;let g;try{g=JSON.parse(y)}catch{throw new b("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(d.status)}): ${y}`,{status:d.status})}if(g===null||typeof g!="object"||Array.isArray(g)||!("result"in g))throw new b("INTERNAL",`${e}: function dispatch returned a JSON body that is not a { result } envelope (${String(d.status)}): ${y}`,{status:d.status});return l(g.result)}finally{T.dispose()}}};export{or as f,ar as l};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.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 I}from"./voice-turn-BiDZeZwp.mjs";import{createStreamGenerate as C,createCompact as R}from"./createAgentGenerate-BOILDUZj.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as L,toFunctionReference as m}from"./AGENT_MODULE-M4D1EejI.mjs";const N="@cf/openai/whisper-large-v3-turbo",O="@cf/deepgram/aura-1",U=8*1024*1024,B=100,f=4e3,g=f*4+1024,F=4002,D=4003,z=4004,W=256*1024,S=15,G=5e3,X=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,s,r){this.state=t,this.env=e,this.agent=s,this.exportName=r,this.paths=L,this.ai=A({binding:e.AI,env:e}),this.streamGenerate=C(s,e),this.sttModel=s.voice?.stt??N,this.ttsModel=s.voice?.tts??O,this.maxSessionTurns=s.voice?.maxTurns??B}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=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:s,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,s,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(p(s.expiresAt)){y(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=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return M(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){if(s.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,z,"control_frame_limit");return}let r;try{r=JSON.parse(s)}catch{return}if(!X(r)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=r;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,F,"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,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"}),this.closeSocket(s,D,"utterance_too_large");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 w({agent:this.agent,compact:R(),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{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...r===void 0?{}:{owner:r}}))?.outcome!=="created")return;for await(const u of I(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: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))}closeSocket(t,e,s){try{t.close?.(e,s)}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 s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>W&&s<G;)await new Promise(r=>{setTimeout(r,S)}),s+=S}}export{J 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,3 @@
|
|
|
1
|
+
import{f as ot}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{r as W}from"./workflow-binding-Dm9hBzx_.mjs";import{c as b,d as nt}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as at}from"./createAgentGenerate-BOILDUZj.mjs";import{buildModelMessages as H}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as z}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as st}from"./positive-integer-ztHqqpBk.mjs";import{combineTelemetry as rt}from"./combineTelemetry-DgE9W9G8.mjs";import{c as G}from"./tool-output-Cmk3JWMG.mjs";const it=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",F=e=>e.memorySources?e.memorySources:e.memory&&it(e.memory)?[{key:"default",...e.memory}]:[],ct=e=>F(e).find(t=>t.kind==="graph"),dt=e=>F(e).find(t=>t.kind==="episodic"),S=(e,t)=>t==="default"?e:`${e}:${t}`,ut=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:rt(...n)},lt=async(e,t,n)=>{const o=ut(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},c=Date.now();await o.onToolExecutionStart?.(s);let d;const u=()=>(d??=n(),d);try{if(o.executeTool===void 0)await u();else try{await o.executeTool({...s,execute:u,toolCallId:t.id})}catch{}const i=await u();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,input:t.input,output:i,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),i}catch(i){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,error:i,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),i}},pt=8,mt=e=>st(e)?e:0,V=e=>e===void 0?"null":JSON.stringify(e),yt=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},vt=e=>e===void 0?[]:[e].flat(),ft=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),ht=(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},gt=async(e,t,n,o,a)=>{const{needsApproval:s}=e;return s===void 0||s===!1?!1:s===!0?!0:n.do(o,async()=>s(t,a))},wt="WorkflowTimeoutError",Tt=e=>e instanceof Error&&e.name===wt,L=4320*60*1e3,xt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Ct=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,St=e=>{if(e===void 0)return L;if(typeof e=="number")return Math.min(e,b);const t=Ct.exec(e);return t===null?L:Math.min(Number(t[1])*xt[t[2]],b)},kt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:c,step:d}=e;await c({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 s({status:"awaiting_input"});const u=await d.waitForEvent(`approval:${t.id}`,{timeout:St(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(i=>({decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}})).catch(i=>{if(!Tt(i))throw i;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},A="lunoraToolOutcome",Et=e=>typeof e=="object"&&e!==null&&A in e?e[A]:{ok:e},Mt=async(e,t)=>{const{agent:n,depth:o,env:a,exports:s,getState:c,instanceId:d,onTokenDelta:u,owner:i,persist:m,run:r,setState:l,step:p,threadKey:f,tools:E}=e,h=`tool:${t.name}:${t.id}`,v=E[t.name],T=`${d}:tool:${t.id}`;if(!v){await m({content:`Error: unknown tool "${t.name}"`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await m({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}const O={depth:o,env:a,exports:s,getState:c,idempotencyKey:h,owner:i,reportProgress:w=>{u?.({data:w,kind:"progress",threadKey:f,toolCallId:t.id})},run:r,setState:l,step:p,threadKey:f,toolCallId:t.id},_={depth:o,env:a,getState:c,idempotencyKey:h,run:r,threadKey:f,toolCallId:t.id},U=`tool:approval-gate:${t.id}`;let x;if(await gt(v,t.input,p,U,_)){const{decision:w,note:k}=await kt(e,t);if(w==="reject"){const D=k===void 0?"":` Reason: ${k}`;await m({content:`Tool "${t.name}" was rejected by the user and not run.${D}`,messageKey:T,role:"tool",status:"rejected",stepName:h,toolCallId:t.id,toolName:t.name});return}x="approved"}const M=Et(await p.do(h,async()=>{try{const w=()=>Promise.resolve(v.execute(t.input,O)),k=await lt(n.telemetry,{id:t.id,input:t.input,name:t.name},w);return{[A]:{ok:k}}}catch(w){if(ot(w))return{[A]:{failed:w.message}};throw w}}));if("failed"in M){await m({content:G(`Error: tool "${t.name}" failed and will not be retried. ${M.failed}`),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name});return}const $=M.ok;await m({content:G(typeof $=="string"?$:V($)),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},$t=(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:at(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},Rt=(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)}},It=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=Rt(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:H({history:s.older}),model:n.compaction?.model??n.model});return c.length>0?{history:s.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Kt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:c,listMessages:d,memoryContext:u,onTokenDelta:i,run:m,step:r,streamGenerate:l,threadKey:p}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const f=await m(d,{key:p}),{history:E,summary:h}=await It(e,f);let v={activeTools:o.activeTools,messages:H({history:E,instructions:c,memoryContext:u,summary:h}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=$t(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:n}),a));const T={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 l&&i?l(T,R=>{i({text:R,threadKey:p,turn:t})}):s(T)})},B=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))},Nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),j=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},At=e=>nt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Ot=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,c=S("memory:retrieve",e.key),d=await n.do(c,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return j(d)},_t=async(e,t,n,o,a,s)=>{if(n===void 0)return;const c=S("memory:traverse",e.key),d=await a.do(c,async()=>s(o,{owner:n,query:t,...At(e.graph)}));return j(d)},Ut=async(e,t,n,o,a)=>{if(t===void 0)return;const s=S("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},d=await o.do(s,async()=>a(n,c));return j(d)},Dt=async(e,t)=>e.kind==="episodic"?Ut(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?_t(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Ot(e,t.input,t.step,t.run),Pt=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Ft=async(e,t,n,o,a,s)=>{const c=Pt(F(e));if(c.length===0)return;const d=g(o.graphTraverse),u=g(o.episodeRecall),i=[];for(const m of c){const r=await Dt(m,{episodeRecall:u,graphTraverse:d,input:t,owner:n,run:s,step:a});r!==void 0&&i.push(r)}return i.length>0?i.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},jt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const r=ct(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},p=await m.do(S("memory:extract",r.key),async()=>o(l));await i(g(u.graphUpsert),{...p,messageKey:`${c}:${S("extract",r.key)}`,owner:d})}catch{}},qt=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m,threadKey:r}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const l=dt(t);if(l!==void 0)try{const p={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:f}=await m.do(S("memory:episode",l.key),async()=>o(p));await i(g(u.episodeUpsert),{messageKey:`${c}:${S("episode",l.key)}`,owner:d,summary:f,threadKey:r})}catch{}},bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},Gt="12 hours",Lt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Gt,type:`agent-dequeue:${t}:${n}`})},Bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},Wt=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{}},Ht=async(e,t,n,o,a)=>{const{instanceId:s,persist:c}=e,d=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const u=n.output!==void 0&&n.text.length===0?V(n.output):n.text;return await c({content:u,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await B(e,{text:n.text,toolCalls:[],turn:t,...d}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await c({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const u of n.toolCalls)await Mt(e,u);if(await B(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...d}),o.push(Nt(n)),a.length>0&&await ft(a,o))return"stopCondition"},zt=async(e,t,n,o)=>{const a=[];let s,c=!1,d=0;for(let u=0;u<t;u+=1){const i=await Kt(e,u,a);o.value=ht(o.value,i.usage),d=u+1;const m=await Ht(e,u,i,a,n);if(m==="stopCondition"){c=!0;break}if(m!==void 0){s=m.final;break}}return{final:s,stoppedByCondition:c,turnsRun:d}},ae=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:c,extractGraph:d,generate:u,instanceId:i,onTokenDelta:m,params:r,paths:l,run:p,step:f,streamGenerate:E}=e,h=t.maxTurns??pt,v=vt(t.stopWhen),T=g(l.appendMessage),R=g(l.completeRun),O=g(l.ensureThread),_=g(l.listMessages),U=g(l.deleteMessage),x=g(l.patchThread),M=g(l.setState),$=g(l.state),w=async y=>{await p(T,{threadKey:r.threadKey,...y})},k=async y=>{await p(x,{key:r.threadKey,...y})},D=async y=>{await p(U,{messageKey:y,threadKey:r.threadKey})},X=async()=>{await w({content:r.input,messageKey:`${i}:user`,role:"user"})},q={dispatched:!1},I=async y=>{q.dispatched=!0;const N=await p(R,{instanceId:i,key:r.threadKey,...y});N?.dequeued!==void 0&&await Bt({env:o,exportName:a,exports:s,step:f},r.threadKey,N.dequeued)},J=async()=>await p($,{key:r.threadKey}),Q=async y=>{await p(M,{key:r.threadKey,state:y})},P=await p(O,{agent:a,instanceId:i,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 bt({env:o,exports:s},a,P.priorInstanceId);const Y=await Ft(t,r.input,r.owner,l,f,p),Z=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,tt={agent:t,compact:n,depth:mt(r.depth),env:o,exports:s,generate:u,getState:J,instanceId:i,instructions:Z,listMessages:_,memoryContext:Y,onTokenDelta:m,owner:r.owner,deleteMessage:D,patchThread:k,persist:w,run:p,setState:Q,step:f,streamGenerate:E,threadKey:r.threadKey,tools:t.tools??{}},K={value:void 0};try{P?.outcome==="queued"&&await Lt(f,r.threadKey,i),await X();const{final:y,stoppedByCondition:N,turnsRun:et}=await zt(tt,h,v,K),C=K.value===void 0?{}:{usage:K.value};return await jt({agent:t,env:o,extractGraph:d,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f}),await qt({agent:t,env:o,extractEpisode:c,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f,threadKey:r.threadKey}),y?(await Wt(t,{env:o,params:r,step:f},{...y,...C}),await I({status:"idle",...C}),{...y,...C}):N?(await I({status:"idle",...C}),{stopped:"stopCondition",turns:et,...C}):(await I({error:`agent stopped: maxTurns (${String(h)}) reached`,status:"error",...C}),{stopped:"maxTurns",turns:h,...C})}catch(y){throw q.dispatched||await yt(I,y,K.value),y}};export{St as a,It as c,it as i,ae as r,Rt as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as I}from"@lunora/workflow";import{jsonSchema as L}from"ai";import{f as S}from"./fnv1a-BNN96GYb.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${S(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!I(d))throw d;l=await i.get(g)}const{output:v,status:u}=await D(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(U(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return j(E)};return{description:t.description,execute:T,inputSchema:L({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as o,d as E,t as C,s as T,c as b}from"./common-CJSjtsfv.mjs";import{c as v}from"./in-flight-calls-GH1A_1P3.mjs";const k=(i,g)=>typeof i=="string"&&i.length>0?i:g,P=i=>{const{functionId:g,logger:m,recordInputs:p=!1,recordOutputs:y=!1}=i,n=v((e,t,s,r)=>{const l={},c=T(o(r,"usage")??o(e.result,"usage"));if(c&&(l.metrics={completion_tokens:c.outputTokens,prompt_tokens:c.inputTokens,tokens:c.totalTokens}),t||(l.error=s??"the model call failed"),y){const d=b(o(r,"content")??o(e.result,"content"));d!==void 0&&(l.output=d)}Object.keys(l).length>0&&e.span.log(l),e.finish()},e=>{e.finish()}),h=(e,t,s)=>{const r=o(e,"callId");if(typeof r!="string")return;let l=s;t instanceof Error?l=t.message:typeof t=="string"&&t.length>0&&(l=t),n.close(r,!1,l,void 0)};return{executeLanguageModelCall:e=>{const{callId:t,execute:s}=e;let r,l;const c=new Promise((a,f)=>{r=a,l=f});let d;const x=new Promise(a=>{d=a});return Promise.resolve(m.traced(async a=>{n.open(t,()=>({finish:d,result:void 0,span:a})),p&&a.log({input:o(e,"messages"),model:o(e,"modelId")});let f;try{f=await s()}catch(u){n.close(t,!1,u instanceof Error?u.message:String(u),void 0),l(u);return}const I=n.get(t);I!==void 0&&(I.result=f),r(f),await x},{name:k(g,"language_model_call"),type:"llm"})).catch(()=>{}),c},executeTool:e=>{const t=o(o(e,"toolCall"),"toolName");return m.traced(async s=>{p&&s.log({input:C(e),tool:t});const r=await e.execute();return y&&s.log({output:r}),r},{name:k(t,"execute_tool"),type:"tool"})},onAbort:e=>{h(e,o(e,"reason"),"aborted")},onEnd:e=>{n.fromLifecycle(e)},onError:e=>{m.traced(t=>{t.log({error:E(o(e,"error")??e)})},{name:"error",type:"error"}),h(e,o(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{const t=o(e,"callId");typeof t=="string"&&n.close(t,!0,void 0,e)},onStepEnd:e=>{n.fromLifecycle(e)}}};export{P as braintrustTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),r=`may not contain the reserved workflow branch-marker key ("${e}")`;export{r as B,o as h};
|
|
@@ -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 h,asSchema as v}from"ai";import{i as A}from"./positive-integer-ztHqqpBk.mjs";import{M as g,c as w}from"./tool-output-Cmk3JWMG.mjs";const $=16,T=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=g?e:w(o)},S=(e,o)=>{let t=e;for(const n of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=t[n]}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"?S(o[r],t.$path):o[r]}const n={};for(const[r,i]of Object.entries(t))r!=="__proto__"&&(n[r]=l(i,o));return n},b=async(e,o,t)=>{const{validate:n}=v(o.inputSchema);if(n===void 0)return t;const r=await n(t);if(r.success)return r.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${r.error.message}`)},O=async(e,o,t,n)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>n)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(n)}. Split it across several code calls.`);const i={},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 b(s,c,l(s.input??{},i)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},y=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,y);i[s.id]=f,p.push({id:s.id,output:T(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("; ")}.`,_=h({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),P=(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\`.`);if(o.maxSteps!==void 0&&!A(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??$;return{description:o.description??E(e),execute:(r,i)=>O(r,e,i,n),inputSchema:_,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{P as codeTool,l as resolveReferences,O 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 i}from"@lunora/workflow";import{r as m}from"./agent-loop-CQUKMFWA.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-BOILDUZj.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{l as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-ByqrB-72.mjs";const E=(r,t,a)=>T({env:t,label:"@lunora/agent",...a===void 0?{}:{fetchImpl:a},...r===void 0?{}:{identity:{userId:r}}}),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,o=[r.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...o,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>i({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exports:e.exports,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.params.owner,e.env,e.fetchImpl),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{l as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{LunoraError as o}from"@lunora/errors";import{h as g,B as w}from"./branch-marker-boZ00zmk.mjs";import{r as h}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as E,DEFAULT_AGENT_FUNCTION_PATHS as N}from"./AGENT_MODULE-M4D1EejI.mjs";const _=(r,c,i={})=>{const{dispatch:l,exports:u}=i,s={},d=E(N.patchThread),p=()=>l??f({env:r,label:"@lunora/agent"});for(const n of c){const a=()=>{const t=h(r,u,n.className,["create","get"]);if(t===void 0)throw new o("INTERNAL",`@lunora/agent: no "${n.className}" on ctx.exports or env for agent "${n.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};s[n.exportName]={cancel:async t=>{await(await a().get(t)).terminate();try{await p()(d,{instanceId:t,status:"cancelled"})}catch{}},publicRun:n.publicRun===!0,run:async(t,e)=>{if(g(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${w}`);return{id:(await a().create({...e?.id===void 0?{}:{id:e.id},params:t})).id}},sendEvent:async(t,e)=>{await(await a().get(t)).sendEvent(e)},status:async t=>(await a().get(t)).status()}}return s};export{_ 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 g=t=>{if(!t)return;const e={};for(const o of["inputTokens","outputTokens","totalTokens"]){const r=t[o];r!==void 0&&(e[o]=r)}return Object.keys(e).length>0?e:void 0},y=t=>t.map(e=>{const o={id:e.toolCallId,input:e.input,name:e.toolName};return e.invalid!==!0?o:{...o,invalid:e.error instanceof Error?e.error.message:String(e.error)}}),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),r={};for(const[a,i]of Object.entries(t.tools??{}))r[a]=A({description:i.description,inputSchema:i.inputSchema});const n=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:n,staticSettings:s,tools:r}},v=(t,{activeTools:e,messages:o,model:r,signal:n,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:r??a,...h,...Object.keys(l).length>0?{tools:l}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...n===void 0?{}:{abortSignal:n}}},I=(t,e)=>{const o=b(t,e);return async r=>{const n=await d(v(o,r)),s=g(n.usage);return{text:n.text,toolCalls:y(n.toolCalls),...s===void 0?{}:{usage:s},...o.output===void 0?{}:{output:n.output}}}},q=(t,e)=>{const o=b(t,e);return async(r,n)=>{const s=C(v(o,r));let a="";try{for await(const u of s.textStream)a+=u,n(u)}catch(u){if(r.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=g(c);return{text:i,toolCalls:y(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:r})=>{const{output:n}=await d({model:m(o,e),output:f.object({schema:k}),prompt:j(r,t)});return n},E=(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:r})=>{const{text:n}=await d({model:m(o,e),prompt:E(r,t)});return{summary:n.trim()}},O="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:r}=await d({messages:e,model:m(o,t),system:O});return r.trim()};export{I as createAgentGenerate,R as createCompact,_ as createEpisodeExtract,M as createGraphExtract,q as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-CQUKMFWA.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as p}from"./agentAsTool-1Gwq45M3.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,N=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]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]=a}return o},A=(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},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.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)}},v=(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)`)},E=(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\``)},L=e=>{if(e===void 0)return;const n=f(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},$=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&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");L(e.approvalTimeout);const o=e.skills??[];y(o),E(e,o);const t=N(e,o),s=g(e,o);for(const[i,h]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]=h}const a=Object.keys(s).length>0;v(e.activeTools,s);for(const i of Object.keys(t))if(!T.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=k(e,o),d=A(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},j=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,M=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{$ as defineAgent,M as defineAgentTool,j 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
|
+
const o=c=>c.toString(16).padStart(4,"0"),g=c=>{let t=8997,n=33826,e=40164,s=52210;for(let h=0;h<c.length;h+=1){t^=c.charCodeAt(h);const r=t*435,p=n*435,x=e*435+t*256,d=s*435+n*256,l=p+(r>>>16),a=x+(l>>>16),f=d+(a>>>16);t=r&65535,n=l&65535,e=a&65535,s=f&65535}return o(s)+o(e)+o(n)+o(t)};export{g as f};
|
|
@@ -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
|
+
import{r as s}from"./common-CJSjtsfv.mjs";const f=600*1e3,h=(i,a)=>{const t=new Map,c=(e,o,n,r)=>{const l=t.get(e);l!==void 0&&(t.delete(e),i(l.call,o,n,r))};return{close:c,fromLifecycle:e=>{const o=s(e,"callId");if(typeof o!="string"||!t.has(o))return;const n=s(e,"finishReason"),r=n==="error"||s(n,"unified")==="error";c(o,!r,r?"the model call ended with an error":void 0,e)},get:e=>t.get(e)?.call,open:(e,o)=>{const n=Date.now()-f;for(const[r,l]of t)l.openedAt<n&&(t.delete(r),a?.(l.call));t.has(e)||t.set(e,{call:o(),openedAt:Date.now()})}}};export{h as c};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{jsonSchema as y}from"ai";const u="LOADER",b="2026-04-07",S=1e3,f=100,v=2e3,g=256*1024,p=3e4,T="Run JavaScript in an isolated sandbox and get its result. Provide `code`: the body of an async function — `return` the answer. Use it for calculation, parsing and data transformation. The sandbox has no network, no bindings and no tools; `console.log` output is returned as `logs`.",h=y({additionalProperties:!1,properties:{code:{description:"The body of an async function. `return` the result; it must be JSON-serializable.",type:"string"}},required:["code"],type:"object"}),w=e=>`const logs = [];
|
|
2
|
+
const format = (value) => { if (typeof value === "string") return value; try { return JSON.stringify(value); } catch { return String(value); } };
|
|
3
|
+
const record = (...values) => { if (logs.length < ${String(f)}) logs.push(values.map(format).join(" ")); };
|
|
4
|
+
const sandboxConsole = { debug: record, error: record, info: record, log: record, warn: record };
|
|
5
|
+
const run = async (console) => {
|
|
6
|
+
${e}
|
|
7
|
+
};
|
|
8
|
+
export default {
|
|
9
|
+
async fetch() {
|
|
10
|
+
try {
|
|
11
|
+
const value = await run(sandboxConsole);
|
|
12
|
+
return new Response(JSON.stringify({ logs, value: value === undefined ? null : value }));
|
|
13
|
+
} catch (error) {
|
|
14
|
+
return new Response(JSON.stringify({ error: error instanceof Error ? (error.stack ?? error.message) : String(error), logs }));
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
`,E=e=>e instanceof Error?e.message:String(e),_=async(e,r)=>{const o=e.body?.getReader();if(o===void 0)return"";const t=new TextDecoder;let n="",a=0;for(;;){const{done:s,value:i}=await o.read();if(s)break;if(a+=i.byteLength,a>r){await o.cancel();return}n+=t.decode(i,{stream:!0})}return n+t.decode()},L=e=>(Array.isArray(e)?e:[]).slice(0,f).map(r=>String(r).slice(0,v)),A=async(e,r,o)=>{let t;const n=new Promise(s=>{t=setTimeout(()=>{s({error:`the script did not finish within ${String(p)} ms`,logs:[]})},p)}),a=async()=>{const i=await e.load({compatibilityDate:b,env:{},globalOutbound:null,limits:{cpuMs:o,subRequests:0},mainModule:"main.js",modules:{"main.js":w(r)}}).getEntrypoint().fetch("https://sandbox/"),l=await _(i,g);if(l===void 0)return{error:`the script's result is over ${String(g)} bytes — return less`,logs:[]};const c=JSON.parse(l),d=L(c.logs);return typeof c.error=="string"?{error:c.error,logs:d}:{logs:d,value:c.value}};try{return await Promise.race([a(),n])}catch(s){return{error:E(s),logs:[]}}finally{clearTimeout(t)}},M=(e={})=>{const r=e.cpuMs??S;if(!Number.isInteger(r)||r<=0)throw new m("INTERNAL","@lunora/agent: jsCodeTool `cpuMs` must be a positive integer");return{description:e.description??T,execute:async(o,t)=>{const n=t.env[u];return typeof n?.load!="function"?{error:`jsCodeTool: no Worker Loader binding "${u}" on env — declare \`"worker_loaders": [{ "binding": "${u}" }]\` in wrangler.jsonc`,logs:[]}:A(n,o.code,r)},inputSchema:h,isLunoraAgentTool:!0}};export{M as jsCodeTool};
|
|
@@ -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-G8ngerkU.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{estimateModelCost as z}from"@lunora/ai";import{a as D,r as d,s as F,e as V,c as P,t as J}from"./common-CJSjtsfv.mjs";import{c as Y}from"./in-flight-calls-GH1A_1P3.mjs";const k=e=>`${String(Math.round(e))}000000`,q=Array.from({length:256},(e,o)=>o.toString(16).padStart(2,"0")),v=512,M=new Uint8Array(v);let w=v;const j=(e,o,n)=>{let c="";for(let s=0;s<n;s+=1)c+=q[e[o+s]];return c},R=e=>{if(e>v){const n=new Uint8Array(e);return crypto.getRandomValues(n),j(n,0,e)}w+e>v&&(crypto.getRandomValues(M),w=0);const o=j(M,w,e);return w+=e,o},A=(e,o)=>typeof o=="boolean"?{key:e,value:{boolValue:o}}:typeof o=="number"?Number.isFinite(o)?Number.isSafeInteger(o)?{key:e,value:{intValue:String(o)}}:{key:e,value:{doubleValue:o}}:{key:e,value:{stringValue:String(o)}}:{key:e,value:{stringValue:o}},G=(e,o,n)=>{const c={},s=new Map,_=(g,m)=>{const x=g.toLowerCase(),T=s.get(x);T===void 0?(s.set(x,g),c[g]=m):c[T]=m};for(const[g,m]of Object.entries(e))_(g,m);for(const[g,m]of Object.entries(o??{}))_(g,m);return n!==void 0&&n.length>0&&_("authorization",`Bearer ${n}`),c},W=e=>Array.isArray(e)?e:[e],X=(e,o)=>{const n={"service.name":e};for(const[c,s]of Object.entries({}))n[c]=s;return Object.entries(n).map(([c,s])=>A(c,s))},K=(e,o,n,c)=>({resourceSpans:[{resource:{attributes:X(n)},scopeSpans:[{scope:{name:o},spans:W(e)}]}]}),i=(e,o,n)=>{if(n!=null){if(typeof n=="boolean"||typeof n=="number"||typeof n=="string"){e.push(A(o,n));return}e.push(A(o,JSON.stringify(n)))}},Q=(e,o)=>{(async()=>{let c;try{c=await e}catch(s){o(!1,s instanceof Error?s.message:String(s),void 0);return}o(!0,void 0,c)})().catch(()=>{})},oe=e=>{const{conversationId:o,endpoint:n,headers:c,recordInputs:s=!1,recordOutputs:_=!1,token:g,traceId:m,waitUntil:x}=e,T=e.serviceName??"lunora";let S=n;for(;S.endsWith("/");)S=S.slice(0,-1);const $=`${S}/v1/traces`,B=G({"content-type":"application/json"},c,g),N=(t,r,a,l,y)=>{const f={attributes:y,endTimeUnixNano:k(Date.now()),kind:1,name:t,spanId:R(8),startTimeUnixNano:k(r),status:a?{code:1}:{code:2,message:l??""},traceId:m??R(16)};try{const b=fetch($,{body:JSON.stringify(K(f,"@lunora/agent",T)),headers:B,method:"POST"}).catch(()=>{});x?.(b)}catch{}},h=Y((t,r,a,l)=>{const{messages:y,modelId:f,provider:b,result:p,startTs:H}=t,u=[];i(u,"gen_ai.operation.name","chat"),i(u,"gen_ai.request.model",f),i(u,"gen_ai.system",b),i(u,"gen_ai.conversation.id",o);const I=F(d(l,"usage")??d(p,"usage"));I&&(i(u,"gen_ai.usage.input_tokens",I.inputTokens),i(u,"gen_ai.usage.output_tokens",I.outputTokens),i(u,"gen_ai.usage.total_tokens",I.totalTokens));const O=V(l)??V(p);O&&(i(u,"gen_ai.response.cached",O.cached),i(u,"cf.aig.log_id",O.logId));const U=O?.cost,L=U??(typeof f=="string"?z(f,{inputTokens:I?.inputTokens,outputTokens:I?.outputTokens}):void 0);L!==void 0&&(i(u,"gen_ai.usage.cost",L),i(u,"lunora.usage.cost.source",U===void 0?"estimated":"provider")),s&&i(u,"gen_ai.prompt",y),_&&i(u,"gen_ai.completion",P(d(l,"content")??d(p,"content"))),N(typeof f=="string"?`chat ${f}`:"language_model_call",H,r,a,u)}),C=(t,r,a)=>{const l=d(t,"callId");if(typeof l!="string")return;let y=a;r instanceof Error?y=r.message:typeof r=="string"&&r.length>0&&(y=r),h.close(l,!1,y,void 0)},E=t=>({messages:d(t,"messages"),modelId:d(t,"modelId"),provider:d(t,"provider"),result:void 0,startTs:Date.now()});return{executeLanguageModelCall:async t=>{const{callId:r}=t;h.open(r,()=>E(t));try{const a=await t.execute(),l=h.get(r);return l!==void 0&&(l.result=a),a}catch(a){throw h.close(r,!1,a instanceof Error?a.message:String(a),void 0),a}},onAbort:t=>{C(t,d(t,"reason"),"aborted")},onEnd:t=>{h.fromLifecycle(t)},onError:t=>{C(t,d(t,"error"),"the model call failed")},onLanguageModelCallEnd:t=>{const r=d(t,"callId");typeof r=="string"&&h.close(r,!0,void 0,t)},onLanguageModelCallStart:t=>{const r=d(t,"callId");typeof r=="string"&&h.open(r,()=>E(t))},onStepEnd:t=>{h.fromLifecycle(t)},executeTool:t=>{const r=Date.now(),a=D(t),l=t.execute();return Q(l,(f,b)=>{const p=[];i(p,"gen_ai.operation.name","execute_tool"),i(p,"gen_ai.tool.name",a),i(p,"gen_ai.tool.call.id",d(t,"toolCallId")),s&&i(p,"gen_ai.tool.input",J(t)),N(typeof a=="string"?`execute_tool ${a}`:"execute_tool",r,f,b,p)}),l}}};export{oe as otlpTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const i=e=>Number.isInteger(e)&&e>0;export{i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-BOILDUZj.mjs";import{a as l,c as u,r as f,s as g}from"./agent-loop-CQUKMFWA.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{l as approvalTimeoutMs,u as compactHistory,f as runAgentLoop,g as splitForCompaction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-BiDZeZwp.mjs";import"./agent-loop-CQUKMFWA.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 @@
|
|
|
1
|
+
const _=12e4,S=15e4,T=12e4,O=12e4,E=15e4;export{S,E as a,_ as b,T as c,O as d};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{initLunora as x}from"@lunora/server";import{v as a}from"@lunora/values";import{b as T,c as S,d as _}from"./sandbox-budgets-DDvj4Orr.mjs";const v=async(e,t,n)=>{if(e===null)return{overflowed:!1,text:""};const r=e.getReader(),o=new TextDecoder,s=()=>{r.cancel().catch(()=>{})};n?.addEventListener("abort",s);let c="",d=0,l=!1;try{for(;n?.aborted!==!0;){const{done:h,value:p}=await r.read();if(h)break;if(d+p.byteLength>t){l=!0,c+=o.decode(p.subarray(0,t-d),{stream:!0});break}d+=p.byteLength,c+=o.decode(p,{stream:!0})}c+=o.decode()}finally{n?.removeEventListener("abort",s),r.cancel().catch(()=>{})}if(n?.aborted===!0)throw n.reason;return{overflowed:l,text:c}},{internalAction:A}=x.dataModel().create(),N=()=>globalThis.document?.documentElement?.outerHTML??"",u=1e6,g=1e6,$=20,R=new TextEncoder,L=e=>{const t=[`exit code: ${String(e.code)}`];return e.stdout.length>0&&t.push(`stdout:
|
|
2
|
+
${e.stdout}`),e.stderr.length>0&&t.push(`stderr:
|
|
3
|
+
${e.stderr}`),t.join(`
|
|
4
|
+
|
|
5
|
+
`)},B=async(e,t)=>{const n=AbortSignal.timeout(_);try{const r=await e.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET",signal:n}),o=await v(r.body,g,n);return o.overflowed?`${o.text}
|
|
6
|
+
|
|
7
|
+
[truncated at ${String(g)} bytes]`:o.text}catch(r){return`fetch failed: ${r instanceof Error?r.message:String(r)}`}},O=async(e,t)=>{if(t.instance===void 0||t.instance.length===0)throw new i("BAD_REQUEST","@lunora/agent: sandbox container op arrived with no `instance` — the tool pins the thread's own container");const n=e.get(t.instance);if(t.op==="exec")try{return L(await n.exec(t.command??"",{args:t.args??[],timeoutMs:S}))}catch(r){return`exec failed: ${r instanceof Error?r.message:String(r)}`}if(t.op==="fetch")return await B(n,t);throw new i("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},m=(e,t)=>new i("INTERNAL",`@lunora/agent: sandbox ${e} op found no R2 bucket "${t}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`),f=(e,t)=>{const n=e.env?.[t.bucket??""];return n&&typeof n.get=="function"?n:void 0},w=(e,t)=>{if(!e)throw m("browser",t.bucket??"");return e},E=e=>{let t=0,n=e.length;for(;t<n&&e[t]==="/";)t+=1;for(;n>t&&e[n-1]==="/";)n-=1;return e.slice(t,n)},y=(e,t)=>{const n=E(e),r=[];for(const s of t.split("/"))if(!(s===""||s===".")){if(s===".."){if(r.length===0)throw new i("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(s)}const o=r.join("/");return n&&o?`${n}/${o}`:n||o},k=async(e,t,n)=>{const r=t.length>0?`${t}/`:"",o=n.length>0?n.length+1:0,s=[];let c;for(let d=0;d<$;d+=1){const l=await e.list({prefix:r,...c===void 0?{}:{cursor:c}});for(const h of l.objects)s.push(h.key.slice(o));if(!l.truncated||l.cursor===void 0)return{entries:s,truncated:!1};c=l.cursor}return{entries:s,truncated:!0}},b=async(e,t,n,r,o)=>{const s=y(t,n);return await e.put(s,r),{bytes:r.byteLength,key:s,mediaType:o}},M=async(e,t,n)=>{const r=t.url??"",o={timeoutMs:T};switch(t.op){case"content":return e.content(r,o);case"pdf":return b(w(n,t),t.root??"",t.path??"",await e.pdf(r,o),"application/pdf");case"scrape":return e.scrape(r,N,o);case"screenshot":{const s=w(n,t),c=await e.screenshot(r,{...o,...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return b(s,t.root??"",t.path??"",c,t.type==="jpeg"?"image/jpeg":"image/png")}default:throw new i("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},I=async(e,t,n)=>{const r=E(t),o=y(t,n.path??"");switch(n.op){case"ls":{const{entries:s,truncated:c}=await k(e,o,r);return c?{entries:s,truncated:!0}:{entries:s}}case"read":{const s=await e.head(o);if(s&&s.size>u)throw new i("BAD_REQUEST",`@lunora/agent: fs read: "${n.path??""}" is ${String(s.size)} bytes (max ${String(u)})`);const c=await e.get(o);if(!c)throw new i("NOT_FOUND",`@lunora/agent: fs read: no file at "${n.path??""}"`);return c.text()}case"rm":return await e.delete(o),{path:n.path??"",removed:!0};case"stat":{const s=await e.head(o);return s?{exists:!0,size:s.size}:{exists:!1}}case"write":{const s=n.content??"",c=R.encode(s).length;if(c>u)throw new i("BAD_REQUEST",`@lunora/agent: fs write: ${String(c)} bytes exceeds the max (${String(u)})`);return await e.put(o,s),{bytes:c,path:n.path??"",wrote:!0}}default:throw new i("INTERNAL",`@lunora/agent: sandbox fs op "${n.op}" is not supported`)}},U=()=>({invoke:A.input({args:a.optional(a.array(a.string())),body:a.optional(a.string()),bucket:a.optional(a.string()),command:a.optional(a.string()),content:a.optional(a.string()),fullPage:a.optional(a.boolean()),instance:a.optional(a.string()),kind:a.union(a.literal("browser"),a.literal("container"),a.literal("fs")),method:a.optional(a.string()),name:a.optional(a.string()),op:a.string(),path:a.optional(a.string()),root:a.optional(a.string()),selector:a.optional(a.string()),type:a.optional(a.string()),url:a.optional(a.string())}).action(async({args:t,ctx:n})=>{const r=n,o=t;if(o.kind==="browser"){if(!r.browser)throw new i("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return M(r.browser,o,f(r,o))}if(o.kind==="fs"){const d=f(r,o);if(!d)throw m("fs",o.bucket??"");return I(d,o.root??"",o)}const s=o.name??"",c=r.containers?.[s];if(!c)throw new i("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${s}"] — declare the container in lunora/containers.ts and run codegen`);return O(c,o)})});export{y as resolveFsKey,I as runFsOp,U as sandboxComponent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as n,t as _,s as y,c as I}from"./common-CJSjtsfv.mjs";import{c as x}from"./in-flight-calls-GH1A_1P3.mjs";const g=(c,i)=>typeof c=="string"&&c.length>0?c:i,k=c=>{const{functionId:i,recordInputs:d=!1,recordOutputs:p=!1,Sentry:u}=c,s=x((e,o,a,r)=>{const t={},l=y(n(r,"usage")??n(e.result,"usage"));if(l&&(t["gen_ai.usage.input_tokens"]=l.inputTokens,t["gen_ai.usage.output_tokens"]=l.outputTokens,t["gen_ai.usage.total_tokens"]=l.totalTokens),p){const m=I(n(r,"content")??n(e.result,"content"));m!==void 0&&(t["gen_ai.completion"]=m)}Object.keys(t).length>0&&e.span.setAttributes?.(t),e.span.setStatus?.(o?{code:1}:{code:2,message:a??""}),e.span.end()},e=>{e.span.end()}),f=(e,o,a)=>{const r=n(e,"callId");if(typeof r!="string")return;let t=a;o instanceof Error?t=o.message:typeof o=="string"&&o.length>0&&(t=o),s.close(r,!1,t,void 0)};return{executeLanguageModelCall:e=>{const{callId:o}=e,a={"gen_ai.operation.name":g(i,"language_model_call"),"gen_ai.request.model":n(e,"modelId"),"gen_ai.system":n(e,"provider")};return d&&(a["gen_ai.prompt"]=n(e,"messages")),u.startSpanManual({attributes:a,name:g(i,"language_model_call"),op:"gen_ai.generate"},async r=>{s.open(o,()=>({result:void 0,span:r}));try{const t=await e.execute(),l=s.get(o);return l!==void 0&&(l.result=t),t}catch(t){throw s.close(o,!1,t instanceof Error?t.message:String(t),void 0),t}})},executeTool:e=>{const o=n(n(e,"toolCall"),"toolName"),a={"gen_ai.operation.name":"execute_tool","gen_ai.tool.call.id":n(e,"toolCallId"),"gen_ai.tool.name":o};return d&&(a["gen_ai.tool.input"]=_(e)),u.startSpan({attributes:a,name:`execute_tool ${g(o,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onAbort:e=>{f(e,n(e,"reason"),"aborted")},onEnd:e=>{s.fromLifecycle(e)},onError:e=>{u.captureException(n(e,"error")??e),f(e,n(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{const o=n(e,"callId");typeof o=="string"&&s.close(o,!0,void 0,e)},onStepEnd:e=>{s.fromLifecycle(e)}}};export{k as sentryTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const _=4e3,O="… [truncated]",t=T=>T.length<=4e3?T:`${T.slice(0,4e3-O.length)}${O}`;export{_ as M,t as c};
|