@lunora/agent 1.0.0-alpha.22 → 1.0.0-alpha.220
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 +41 -2
- package/dist/component.d.ts +41 -2
- 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 +112 -17
- package/dist/index.d.ts +112 -17
- 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-B6FqQC80.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-D7O6Fclt.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-DFF_g58r.mjs +2 -0
- package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
- package/dist/packem_shared/agent-loop-DzzRTrgP.mjs +3 -0
- package/dist/packem_shared/agentAsTool-BJi-uU4s.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-dpJANTDc.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-D07XhGKr.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-KtkWJyHR.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-Wlc1ZgWa.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-D9DbEj9I.mjs +3 -0
- package/dist/packem_shared/defineAgent-DrI8Hw7B.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-Baqdn0OK.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
- package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-DC5n77sQ.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-COwgPdOl.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-DdQVm4Kv.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-Du0yENEO.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-DqYbp4ye.d.mts} +300 -27
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-DqYbp4ye.d.ts} +300 -27
- package/dist/packem_shared/voice-turn-CzFz5tWG.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BobmV4cD.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 +157 -16
- package/dist/sandbox.d.ts +157 -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 +165 -38
- package/dist/telemetry/index.d.ts +165 -38
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +19 -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.mts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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-DqYbp4ye.mjs";
|
|
2
|
+
export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-DqYbp4ye.mjs";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
|
-
export {
|
|
6
|
-
export {
|
|
7
|
-
import { createAi } from '@lunora/ai';
|
|
5
|
+
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
|
|
6
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
|
|
7
|
+
import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai/create';
|
|
8
8
|
import { WorkflowDefinition } from '@lunora/workflow';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
10
10
|
import '@lunora/server';
|
|
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
|
|
|
23
23
|
env: Record<string, unknown>;
|
|
24
24
|
/** The agent's `lunora/agents.ts` export name (thread attribution). */
|
|
25
25
|
exportName: string;
|
|
26
|
+
/** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
|
|
27
|
+
exports?: unknown;
|
|
26
28
|
/**
|
|
27
29
|
* The run-end episode-summary seam — production wires AI SDK `generateText`.
|
|
28
30
|
* Absent (the default) disables episode recording, so an agent with no
|
|
@@ -183,7 +185,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
|
|
|
183
185
|
interface ToolScriptStep {
|
|
184
186
|
/** A stable name later steps reference the output by. */
|
|
185
187
|
id: string;
|
|
186
|
-
/** The tool's input; values may embed `{ "$from": "
|
|
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. */
|
|
@@ -806,17 +853,65 @@ declare class VoiceSessionDO {
|
|
|
806
853
|
*/
|
|
807
854
|
private waitForSocketDrain;
|
|
808
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Config for {@link webSearchTool}.
|
|
858
|
+
* @experimental
|
|
859
|
+
*/
|
|
860
|
+
interface WebSearchToolOptions {
|
|
861
|
+
/** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
|
|
862
|
+
byokAlias?: string;
|
|
863
|
+
/** Overrides the description shown to the model. */
|
|
864
|
+
description?: string;
|
|
865
|
+
/**
|
|
866
|
+
* The AI Gateway that brokers and bills the search. Defaults to
|
|
867
|
+
* `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
|
|
868
|
+
*/
|
|
869
|
+
gatewayId?: string;
|
|
870
|
+
/** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
|
|
871
|
+
limit?: number;
|
|
872
|
+
/** Defaults to the Web Search API's own default (`"ceramic"`). */
|
|
873
|
+
provider?: AiWebSearchProvider;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* What the model passes.
|
|
877
|
+
* @experimental
|
|
878
|
+
*/
|
|
879
|
+
interface WebSearchToolInput {
|
|
880
|
+
query: string;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* A batteries-included agent tool over the Cloudflare Web Search API (beta,
|
|
884
|
+
* `ctx.ai.websearch`), so an agent can ground an answer in live results.
|
|
885
|
+
* A search bills a provider key stored on the gateway (`byokAlias`, else the
|
|
886
|
+
* `default` alias) when there is one, otherwise AI Gateway credits; every
|
|
887
|
+
* provider runs under Zero Data Retention.
|
|
888
|
+
*
|
|
889
|
+
* It calls the `AI` binding straight from the tool's durable step: a search
|
|
890
|
+
* is a read, so the at-least-once step retry repeats nothing but a query, and
|
|
891
|
+
* there is no dispatcher action to register.
|
|
892
|
+
*
|
|
893
|
+
* ```ts
|
|
894
|
+
* import { defineAgent, webSearchTool } from "@lunora/agent";
|
|
895
|
+
*
|
|
896
|
+
* export const researcher = defineAgent({
|
|
897
|
+
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
898
|
+
* tools: { search: webSearchTool({ provider: "exa" }) },
|
|
899
|
+
* });
|
|
900
|
+
* ```
|
|
901
|
+
* @experimental
|
|
902
|
+
*/
|
|
903
|
+
declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
|
|
809
904
|
/**
|
|
810
905
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
906
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
907
|
*
|
|
813
908
|
* ```ts
|
|
814
909
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
910
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
911
|
* import { support } from "../agents.js";
|
|
817
912
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
913
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
914
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
915
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
916
|
* }
|
|
822
917
|
* }
|
|
@@ -829,4 +924,4 @@ declare class VoiceSessionDO {
|
|
|
829
924
|
declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
|
|
830
925
|
paths?: AgentFunctionPaths;
|
|
831
926
|
}) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
|
|
832
|
-
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
|
|
927
|
+
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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-DqYbp4ye.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-DqYbp4ye.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
|
-
export {
|
|
6
|
-
export {
|
|
7
|
-
import { createAi } from '@lunora/ai';
|
|
5
|
+
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
|
|
6
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
|
|
7
|
+
import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai/create';
|
|
8
8
|
import { WorkflowDefinition } from '@lunora/workflow';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
10
10
|
import '@lunora/server';
|
|
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
|
|
|
23
23
|
env: Record<string, unknown>;
|
|
24
24
|
/** The agent's `lunora/agents.ts` export name (thread attribution). */
|
|
25
25
|
exportName: string;
|
|
26
|
+
/** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
|
|
27
|
+
exports?: unknown;
|
|
26
28
|
/**
|
|
27
29
|
* The run-end episode-summary seam — production wires AI SDK `generateText`.
|
|
28
30
|
* Absent (the default) disables episode recording, so an agent with no
|
|
@@ -183,7 +185,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
|
|
|
183
185
|
interface ToolScriptStep {
|
|
184
186
|
/** A stable name later steps reference the output by. */
|
|
185
187
|
id: string;
|
|
186
|
-
/** The tool's input; values may embed `{ "$from": "
|
|
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. */
|
|
@@ -806,17 +853,65 @@ declare class VoiceSessionDO {
|
|
|
806
853
|
*/
|
|
807
854
|
private waitForSocketDrain;
|
|
808
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Config for {@link webSearchTool}.
|
|
858
|
+
* @experimental
|
|
859
|
+
*/
|
|
860
|
+
interface WebSearchToolOptions {
|
|
861
|
+
/** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
|
|
862
|
+
byokAlias?: string;
|
|
863
|
+
/** Overrides the description shown to the model. */
|
|
864
|
+
description?: string;
|
|
865
|
+
/**
|
|
866
|
+
* The AI Gateway that brokers and bills the search. Defaults to
|
|
867
|
+
* `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
|
|
868
|
+
*/
|
|
869
|
+
gatewayId?: string;
|
|
870
|
+
/** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
|
|
871
|
+
limit?: number;
|
|
872
|
+
/** Defaults to the Web Search API's own default (`"ceramic"`). */
|
|
873
|
+
provider?: AiWebSearchProvider;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* What the model passes.
|
|
877
|
+
* @experimental
|
|
878
|
+
*/
|
|
879
|
+
interface WebSearchToolInput {
|
|
880
|
+
query: string;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* A batteries-included agent tool over the Cloudflare Web Search API (beta,
|
|
884
|
+
* `ctx.ai.websearch`), so an agent can ground an answer in live results.
|
|
885
|
+
* A search bills a provider key stored on the gateway (`byokAlias`, else the
|
|
886
|
+
* `default` alias) when there is one, otherwise AI Gateway credits; every
|
|
887
|
+
* provider runs under Zero Data Retention.
|
|
888
|
+
*
|
|
889
|
+
* It calls the `AI` binding straight from the tool's durable step: a search
|
|
890
|
+
* is a read, so the at-least-once step retry repeats nothing but a query, and
|
|
891
|
+
* there is no dispatcher action to register.
|
|
892
|
+
*
|
|
893
|
+
* ```ts
|
|
894
|
+
* import { defineAgent, webSearchTool } from "@lunora/agent";
|
|
895
|
+
*
|
|
896
|
+
* export const researcher = defineAgent({
|
|
897
|
+
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
898
|
+
* tools: { search: webSearchTool({ provider: "exa" }) },
|
|
899
|
+
* });
|
|
900
|
+
* ```
|
|
901
|
+
* @experimental
|
|
902
|
+
*/
|
|
903
|
+
declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
|
|
809
904
|
/**
|
|
810
905
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
906
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
907
|
*
|
|
813
908
|
* ```ts
|
|
814
909
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
910
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
911
|
* import { support } from "../agents.js";
|
|
817
912
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
913
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
914
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
915
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
916
|
* }
|
|
822
917
|
* }
|
|
@@ -829,4 +924,4 @@ declare class VoiceSessionDO {
|
|
|
829
924
|
declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
|
|
830
925
|
paths?: AgentFunctionPaths;
|
|
831
926
|
}) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
|
|
832
|
-
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
|
|
927
|
+
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as t,s as r}from"./packem_shared/agent-loop-DzzRTrgP.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-D07XhGKr.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-BJi-uU4s.mjs";import{codeTool as m}from"./packem_shared/codeTool-dpJANTDc.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-Wlc1ZgWa.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-DrI8Hw7B.mjs";import{functionTool as D}from"./packem_shared/functionTool-Baqdn0OK.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as F}from"./packem_shared/createAgentGenerate-D9DbEj9I.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as v}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-B6FqQC80.mjs";import{browserTool as q,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{defineSkill as Z,isSkillDefinition as $}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as oe}from"./packem_shared/VoiceSessionDO-D7O6Fclt.mjs";import{r as re}from"./packem_shared/voice-turn-CzFz5tWG.mjs";import{webSearchTool as ae}from"./packem_shared/webSearchTool-BobmV4cD.mjs";import{default as le}from"./packem_shared/compileAgentWorkflow-KtkWJyHR.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,oe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,q as browserTool,v as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,le as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Z as defineSkill,Q as fsTool,D as functionTool,N as isAgentDefinition,$ as isSkillDefinition,L as jsCodeTool,h as mcpTools,F as resolveAgentModel,t as runAgentLoop,re as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,V as voiceBindingName,H as voiceClassName,ae as webSearchTool};
|
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`,history:`${e}:agentHistory`,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 d,isLunoraError as P}from"@lunora/errors";const B=t=>{if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},w=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},k=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},s="$lunora.wire$",m=64,A=1024,C="__proto__",M=/^-?\d+$/,O={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},S={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},v=(t,e,r)=>{e===C?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r},J=t=>{const e=t.toString();if(e.length>A)throw new RangeError(`wire-codec: over-long bigint (max ${String(A)} digits)`);return[s,"bigint",e]},G=t=>Number.isNaN(t)?[s,"nan"]:t===1/0?[s,"inf"]:t===-1/0?[s,"-inf"]:t,K=(t,e)=>{const r=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),n=t,o=[s,"error",String(n.name),String(n.message),r];return t.cause!==void 0&&o.push(e(t.cause)),o},F=t=>{const e=t.constructor.name,r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[s,"bytes",w(r)]:[s,"bytes",w(r),e]},W=(t,e)=>t instanceof Date?[s,"date",e(t.getTime())]:t instanceof Error?K(t,e):t instanceof URL?[s,"url",t.href]:t instanceof Map?[s,"map",[...t.entries()].map(([r,n])=>[e(r),e(n)])]:t instanceof Set?[s,"set",[...t].map(r=>e(r))]:t instanceof ArrayBuffer?[s,"bytes",w(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?F(t):void 0,H=(t,e)=>{const r=t.map(n=>e(n));return r.length>0&&r[0]===s?[s,"arr",r]:r},q=(t,e)=>{const r={};for(const n of Object.keys(t)){const o=t[n];o!==void 0&&v(r,n,e(o))}return r},I=(t,e=0)=>{if(e>m)throw new RangeError(`wire-codec: value nesting exceeds the ${String(m)}-level limit`);if(t===void 0)return[s,"undefined"];if(t===null)return t;if(typeof t=="bigint")return J(t);if(typeof t=="number")return G(t);if(typeof t!="object")return t;const r=o=>I(o,e+1),n=W(t,r);if(n!==void 0)return n;if(Array.isArray(t))return H(t,r);if(!B(t)){const o=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${o} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}return q(t,r)},z=t=>{const e=t[2];if(typeof e!="string"||e.length>A||!M.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(A)} digits)`);return BigInt(e)},V=(t,e)=>{const r=e(t[2]);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)},X=(t,e)=>{const r=t[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[e(n[0]),e(n[1])]}))},Q=t=>{const e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(e)},Y=(t,e)=>{const r=t[2],n=t[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const o=(Object.hasOwn(S,r)?S[r]:void 0)??Error,a=new o(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const c=e(t[4]);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const[g,l]of Object.entries(c))v(a,g,l);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},Z=t=>{const e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const r=k(e);if(w(r)!==e)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const n=t[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:new Uint8Array(r).buffer;const o=Object.hasOwn(O,n)?O[n]:void 0;return o?new o(new Uint8Array(r).buffer):r},tt=(t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(r=>e(r));case"bigint":return z(t);case"bytes":return Z(t);case"date":return V(t,e);case"error":return Y(t,e);case"inf":return 1/0;case"map":return X(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(r=>e(r)));case"undefined":return;case"url":return Q(t);default:return t.map(r=>e(r))}},et=(t,e)=>{const r={};for(const n of Object.keys(t))v(r,n,e(t[n]));return r},R=(t,e=0)=>{if(e>m)throw new RangeError(`wire-codec: value nesting exceeds the ${String(m)}-level limit`);if(t===null||typeof t!="object")return t;const r=n=>R(n,e+1);if(Array.isArray(t)){const n=t;return n[0]===s?tt(n,r):n.map(o=>r(o))}return et(t,r)},rt=(t,e,r)=>{try{return I(r)}catch(n){throw new TypeError(`${t}: cannot encode args for '${e}' — ${n instanceof Error?n.message:String(n)}`,n instanceof Error?{cause:n}:void 0)}},nt="DISPATCH_IN_PROGRESS",ot="x-lunora-dispatch-declined",at=(t,e,r)=>{if(e===void 0)return{dispose:()=>{},signal:t};const n=new AbortController,o=setTimeout(()=>{n.abort(r())},e);return{dispose:()=>{clearTimeout(o)},signal:n.signal}},f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",j=t=>{let e="",r=0;const n=t.length-2;for(;r<n;r+=3){const a=t[r]<<16|t[r+1]<<8|t[r+2];e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)+f.charAt(a>>6&63)+f.charAt(a&63)}const o=t.length-r;if(o===1){const a=t[r]<<16;e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)}else if(o===2){const a=t[r]<<16|t[r+1]<<8;e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)+f.charAt(a>>6&63)}return e};new TextDecoder;const U=new TextEncoder,T="=",st=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},ct=t=>j(U.encode(JSON.stringify(t))),it=t=>!t.startsWith(T)&&st(t)?t:`${T}${j(U.encode(t))}`,ut="/_lunora/scheduler/dispatch",ft=3e4,lt=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},L=Symbol("lunoraDispatchFailure"),dt=Symbol("lunoraDispatchDecline"),yt=Symbol("lunoraDispatchMessageId"),_=(t,e)=>(e!==void 0&&Object.defineProperty(t,yt,{value:e}),t),pt=(t,e)=>(Object.defineProperty(t,L,{value:!0}),_(t,e)),ht=(t,e,r,n)=>{const{status:o}=e;try{const a=JSON.parse(r)?.error;if(typeof a=="object"&&a!==null&&typeof a.code=="string"){const{code:c,data:g,message:l}=a,y=pt(new d(c,typeof l=="string"?l:void 0,{data:g,status:o}),n);return e.headers.get(ot)==="1"&&Object.defineProperty(y,dt,{value:!0}),y}}catch{}return _(new d("INTERNAL",`${t}: function dispatch failed (${String(o)}): ${r}`,{status:o}),n)},gt=new Set([400,403,404,422]),bt=new Set([nt,"DISPATCH_UNAUTHENTICATED"]),wt=t=>P(t)&&t[L]===!0,Et=t=>wt(t)&>.has(t.status)&&!bt.has(t.code),mt=(t,e,r)=>new d("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(r)}ms`,{status:503}),$t=t=>{const{label:e}=t,r=globalThis.fetch,n=t.fetchImpl??(typeof r=="function"?r.bind(globalThis):void 0);return async(o,a,c={})=>{if(typeof n!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const g=()=>t.argsAlreadyEncoded===!0?a??{}:rt(e,o.__lunoraRef,a??{}),l=t.env.LUNORA_ORIGIN_URL;if(typeof l!="string"||l.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const y=t.env.LUNORA_ADMIN_TOKEN;if(typeof y!="string"||y.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const x=`${lt(l)}${ut}`,b={authorization:`Bearer ${y}`,"content-type":"application/json"};t.traceparent!==void 0&&t.traceparent.length>0&&(b.traceparent=t.traceparent),t.identity?.userId!==void 0&&(b["x-lunora-userid"]=it(t.identity.userId)),t.identity?.claims!==void 0&&(b["x-lunora-identity"]=ct(t.identity.claims));const E=c.timeoutMs??ft,N=at(void 0,E,()=>new DOMException(`dispatch timed out after ${String(E)}ms`,"TimeoutError")),$=u=>{throw u instanceof Error&&u.name==="TimeoutError"?mt(e,o.__lunoraRef,E):u};let i;try{try{i=await n(x,{body:JSON.stringify({args:g(),functionPath:o.__lunoraRef,id:c.dedupId,shardKey:c.shardKey}),headers:b,method:"POST",signal:N.signal})}catch(h){return $(h)}if(!i.ok){let h;try{h=await i.text()}catch(D){return $(D)}throw ht(e,i,h,c.messageId)}let u;try{u=await i.text()}catch(h){return $(h)}if(u.length===0)return;let p;try{p=JSON.parse(u)}catch{throw new d("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(i.status)}): ${u}`,{status:i.status})}if(p===null||typeof p!="object"||Array.isArray(p)||!("result"in p))throw new d("INTERNAL",`${e}: function dispatch returned a JSON body that is not a { result } envelope (${String(i.status)}): ${u}`,{status:i.status});return R(p.result)}finally{N.dispose()}}};export{$t as n,Et as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as A}from"@lunora/ai/create";import{n as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-CzFz5tWG.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-D9DbEj9I.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-B6FqQC80.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{jsonSchema as i}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
2
|
+
`);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as t}from"@lunora/ai/create";const i=r=>{const o=r.AI;return o?t({binding:o,env:r}):void 0};export{i as r};
|