@lunora/agent 1.0.0-alpha.26 → 1.0.0-alpha.261
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 +54 -2
- package/dist/component.d.ts +54 -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 +207 -18
- package/dist/index.d.ts +207 -18
- package/dist/index.mjs +1 -1
- package/dist/naming.d.mts +15 -7
- package/dist/naming.d.ts +15 -7
- package/dist/naming.mjs +1 -1
- package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-CE08SIwv.mjs +1 -0
- package/dist/packem_shared/SecretUnavailableError-BCp40Leh.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-REut3oqY.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-BgOHoyg_.mjs +3 -0
- package/dist/packem_shared/agentAsTool-CA7Sha2i.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-Ck09dC4G.mjs +1 -0
- package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-DVQdQ7_1.mjs +5 -0
- package/dist/packem_shared/codeTool-Hm_Af6t4.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
- package/dist/packem_shared/common-DBc9y7Np.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-yYM18j57.mjs +1 -0
- package/dist/packem_shared/component-shared-DdXFbng-.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-Cl-WQEsZ.mjs +1 -0
- package/dist/packem_shared/createAgentContext-CqF7NfUY.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-DSLXAeY2.mjs +3 -0
- package/dist/packem_shared/defineAgent-D7wY7Jl3.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-C95ns65V.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-C9QGq8uH.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
- package/dist/packem_shared/normalizeEntityName-Rr5OQxhc.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-CoQUnwKs.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-BpC_9Mm3.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-B1BuLxxj.mjs +1 -0
- package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-vAmttAsE.d.mts} +355 -33
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-vAmttAsE.d.ts} +355 -33
- package/dist/packem_shared/voice-turn-hIZ7r1ST.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BobmV4cD.mjs +1 -0
- package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
- package/dist/packem_shared/wrapUntrusted-BuHBC6sV.mjs +2 -0
- package/dist/reply.d.mts +58 -0
- package/dist/reply.d.ts +58 -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 +20 -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,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, d as AgentToolContext, z as SkillConfig } from "./packem_shared/types.d-vAmttAsE.js";
|
|
2
|
+
export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-vAmttAsE.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
|
-
export {
|
|
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>>>>;
|
|
@@ -556,6 +592,82 @@ declare const DEFAULT_AGENT_FUNCTION_PATHS: AgentFunctionPaths;
|
|
|
556
592
|
* @experimental
|
|
557
593
|
*/
|
|
558
594
|
declare const toFunctionReference: (source: AgentFunctionReference | string) => AgentFunctionReference;
|
|
595
|
+
/** The model's input to {@link requestSecretTool}: what the secret is for, shown to the person asked. */
|
|
596
|
+
interface SecretRequestInput {
|
|
597
|
+
label: string;
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Thrown by {@link withSecret} when the value is no longer takeable. The loop
|
|
601
|
+
* records it as a deterministic tool failure, so the model can recover rather
|
|
602
|
+
* than the durable step retrying a read that can never succeed.
|
|
603
|
+
*/
|
|
604
|
+
declare class SecretUnavailableError extends Error {
|
|
605
|
+
readonly code = "SECRET_UNAVAILABLE";
|
|
606
|
+
constructor();
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* An agent tool that asks the human for a secret value (an API key, a token) and
|
|
610
|
+
* hands the model only an opaque `{ secretRef }` in return. The loop pauses the
|
|
611
|
+
* run until the owner supplies the value through `agents:agentSupplySecret`, or
|
|
612
|
+
* declines through `agents:agentDeclineSecret`. `execute` is never called: the
|
|
613
|
+
* loop resolves this tool itself.
|
|
614
|
+
*
|
|
615
|
+
* `consumer` names the one tool allowed to read the value. The model can pass the
|
|
616
|
+
* `secretRef` to any tool, but only the declared consumer's {@link withSecret} call
|
|
617
|
+
* takes it, so a prompt-injected model cannot route the value elsewhere.
|
|
618
|
+
*
|
|
619
|
+
* Codegen wires the secret store when a source in `lunora/` value-imports this tool
|
|
620
|
+
* from `@lunora/agent`: by a named import, a namespace import that reads it, or a
|
|
621
|
+
* relative barrel that re-exports it. Without that wiring the supply mutation refuses,
|
|
622
|
+
* and the refusal names the missing import. Requires a host that rates `secretValues`
|
|
623
|
+
* as supported.
|
|
624
|
+
*
|
|
625
|
+
* ```ts
|
|
626
|
+
* import { defineAgent, requestSecretTool } from "@lunora/agent";
|
|
627
|
+
*
|
|
628
|
+
* export const billing = defineAgent({
|
|
629
|
+
* tools: {
|
|
630
|
+
* requestApiKey: requestSecretTool({
|
|
631
|
+
* consumer: "chargeCard",
|
|
632
|
+
* description: "Ask the user for their payment-provider API key.",
|
|
633
|
+
* }),
|
|
634
|
+
* chargeCard: functionTool({ ... }), // reads the value with withSecret
|
|
635
|
+
* },
|
|
636
|
+
* });
|
|
637
|
+
* ```
|
|
638
|
+
*
|
|
639
|
+
* The value transits the supply mutation's arguments, which are marked
|
|
640
|
+
* `v.sensitive`: the request log masks them. The run's history records only the
|
|
641
|
+
* request id.
|
|
642
|
+
* @experimental
|
|
643
|
+
*/
|
|
644
|
+
declare const requestSecretTool: (options: {
|
|
645
|
+
consumer: string;
|
|
646
|
+
description: string;
|
|
647
|
+
}) => AgentToolDefinition<SecretRequestInput, {
|
|
648
|
+
secretRef: string;
|
|
649
|
+
}>;
|
|
650
|
+
/**
|
|
651
|
+
* Read a human-supplied secret inside the tool that the request declared as its
|
|
652
|
+
* `consumer`, hand it to `use`, and return only what `use` returns. The value never
|
|
653
|
+
* leaves the callback: it is not a step output, not a tool result and not a message.
|
|
654
|
+
* The read is its own durable step named for this call, so a retry of the same step
|
|
655
|
+
* re-takes the value (the claimant is this step's name), while a different call
|
|
656
|
+
* cannot.
|
|
657
|
+
*
|
|
658
|
+
* Call it from inside a tool's `execute`. The discard runs as a separate durable step
|
|
659
|
+
* only after the take succeeded and `use` returned, so a call that is refused (the
|
|
660
|
+
* wrong tool, another thread, an expired request) cannot burn a value the declared
|
|
661
|
+
* consumer still needs. If `use` keeps failing, the value stays until its TTL expires,
|
|
662
|
+
* which is the backstop for a crash between the take and the discard. `use` must not
|
|
663
|
+
* return or log the value. A result that carries it is refused (the call fails with
|
|
664
|
+
* `LunoraError`) rather than journalled. An error that carries it is redacted before
|
|
665
|
+
* it propagates, so the step's retry, the failure the loop records and telemetry never
|
|
666
|
+
* see the value; `traceToolExecution` records the tool's input and output.
|
|
667
|
+
* @throws {SecretUnavailableError} when the request is unknown, not supplied, declared for another consumer, or from another thread
|
|
668
|
+
* @experimental
|
|
669
|
+
*/
|
|
670
|
+
declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
|
|
559
671
|
/**
|
|
560
672
|
* Declare a reusable skill: a bundle of expertise — an instruction fragment,
|
|
561
673
|
* tools, and retrieval `knowledge` — an agent composes in via
|
|
@@ -592,12 +704,28 @@ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
|
|
|
592
704
|
* @experimental
|
|
593
705
|
*/
|
|
594
706
|
declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
|
|
707
|
+
/**
|
|
708
|
+
* Wrap untrusted text for inclusion in a prompt. The text sits between a tag
|
|
709
|
+
* whose id is random per call, so payload text cannot forge the closing tag (it
|
|
710
|
+
* cannot know the id), and any `<` or `>` in it is escaped so it cannot form a
|
|
711
|
+
* tag at all. A mention or cashtag (`@`, `$`) not glued to a word, and a slash
|
|
712
|
+
* command `/` at the start of a token, get a zero-width space after them. Given a header map, the headers are rendered
|
|
713
|
+
* above the body with credential-like values redacted. A one-line note after the
|
|
714
|
+
* block tells the model the enclosed data is not to be followed as instructions.
|
|
715
|
+
*
|
|
716
|
+
* Use it on the text a mapper hands the model, e.g. `input: wrapUntrusted(email.text ?? "")`.
|
|
717
|
+
* @experimental
|
|
718
|
+
*/
|
|
719
|
+
declare const wrapUntrusted: (value: string, headers?: Headers | Readonly<Record<string, string>>) => string;
|
|
595
720
|
/**
|
|
596
721
|
* A control frame the server sends the client as a JSON text message (audio
|
|
597
722
|
* rides separate binary frames). `ready` announces the negotiated codec on
|
|
598
723
|
* connect; `user_transcript` carries the STT result; `assistant_delta` streams
|
|
599
724
|
* the live LLM text; `assistant_done` is the final turn text; `interrupted`
|
|
600
|
-
* acks a barge-in; `
|
|
725
|
+
* acks a barge-in; `assistant_discarded` says the turn failed, so the deltas
|
|
726
|
+
* already streamed for it are not an answer; `error` reports a failure. An
|
|
727
|
+
* `error` alone does not end a turn: a speech-synthesis failure reports one and
|
|
728
|
+
* the turn still completes.
|
|
601
729
|
* @experimental
|
|
602
730
|
*/
|
|
603
731
|
type VoiceServerFrame = {
|
|
@@ -615,6 +743,8 @@ type VoiceServerFrame = {
|
|
|
615
743
|
} | {
|
|
616
744
|
text: string;
|
|
617
745
|
type: "user_transcript";
|
|
746
|
+
} | {
|
|
747
|
+
type: "assistant_discarded";
|
|
618
748
|
} | {
|
|
619
749
|
type: "interrupted";
|
|
620
750
|
};
|
|
@@ -674,6 +804,13 @@ interface VoiceTurnResult {
|
|
|
674
804
|
interface RunVoiceTurnOptions {
|
|
675
805
|
/** The agent whose thread + models back this session. */
|
|
676
806
|
agent: AgentDefinition;
|
|
807
|
+
/**
|
|
808
|
+
* History-compaction seam — the SAME one the durable loop uses. Voice and
|
|
809
|
+
* text turns share one thread, so an agent that declares `compaction` must
|
|
810
|
+
* get it here too; absent (or with no `compaction` config) the turn takes
|
|
811
|
+
* the byte-identical uncompacted path.
|
|
812
|
+
*/
|
|
813
|
+
compact?: AgentCompact;
|
|
677
814
|
/** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
|
|
678
815
|
connectionId: string;
|
|
679
816
|
/** The Worker env (resolves a dynamic `instructions` thunk). */
|
|
@@ -755,6 +892,8 @@ declare class VoiceSessionDO {
|
|
|
755
892
|
protected readonly streamGenerate: AgentStreamGenerate;
|
|
756
893
|
protected readonly sttModel: string;
|
|
757
894
|
protected readonly ttsModel: string;
|
|
895
|
+
/** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
|
|
896
|
+
private readonly maxSessionTurns;
|
|
758
897
|
private readonly audioBuffers;
|
|
759
898
|
private readonly bufferedBytes;
|
|
760
899
|
private readonly controllers;
|
|
@@ -793,6 +932,8 @@ declare class VoiceSessionDO {
|
|
|
793
932
|
private synthesizeWithSignal;
|
|
794
933
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
934
|
private cleanupSocket;
|
|
935
|
+
/** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
|
|
936
|
+
private closeSocket;
|
|
796
937
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
797
938
|
private send;
|
|
798
939
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
|
@@ -806,17 +947,65 @@ declare class VoiceSessionDO {
|
|
|
806
947
|
*/
|
|
807
948
|
private waitForSocketDrain;
|
|
808
949
|
}
|
|
950
|
+
/**
|
|
951
|
+
* Config for {@link webSearchTool}.
|
|
952
|
+
* @experimental
|
|
953
|
+
*/
|
|
954
|
+
interface WebSearchToolOptions {
|
|
955
|
+
/** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
|
|
956
|
+
byokAlias?: string;
|
|
957
|
+
/** Overrides the description shown to the model. */
|
|
958
|
+
description?: string;
|
|
959
|
+
/**
|
|
960
|
+
* The AI Gateway that brokers and bills the search. Defaults to
|
|
961
|
+
* `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
|
|
962
|
+
*/
|
|
963
|
+
gatewayId?: string;
|
|
964
|
+
/** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
|
|
965
|
+
limit?: number;
|
|
966
|
+
/** Defaults to the Web Search API's own default (`"ceramic"`). */
|
|
967
|
+
provider?: AiWebSearchProvider;
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* What the model passes.
|
|
971
|
+
* @experimental
|
|
972
|
+
*/
|
|
973
|
+
interface WebSearchToolInput {
|
|
974
|
+
query: string;
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* A batteries-included agent tool over the Cloudflare Web Search API (beta,
|
|
978
|
+
* `ctx.ai.websearch`), so an agent can ground an answer in live results.
|
|
979
|
+
* A search bills a provider key stored on the gateway (`byokAlias`, else the
|
|
980
|
+
* `default` alias) when there is one, otherwise AI Gateway credits; every
|
|
981
|
+
* provider runs under Zero Data Retention.
|
|
982
|
+
*
|
|
983
|
+
* It calls the `AI` binding straight from the tool's durable step: a search
|
|
984
|
+
* is a read, so the at-least-once step retry repeats nothing but a query, and
|
|
985
|
+
* there is no dispatcher action to register.
|
|
986
|
+
*
|
|
987
|
+
* ```ts
|
|
988
|
+
* import { defineAgent, webSearchTool } from "@lunora/agent";
|
|
989
|
+
*
|
|
990
|
+
* export const researcher = defineAgent({
|
|
991
|
+
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
992
|
+
* tools: { search: webSearchTool({ provider: "exa" }) },
|
|
993
|
+
* });
|
|
994
|
+
* ```
|
|
995
|
+
* @experimental
|
|
996
|
+
*/
|
|
997
|
+
declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
|
|
809
998
|
/**
|
|
810
999
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
1000
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
1001
|
*
|
|
813
1002
|
* ```ts
|
|
814
1003
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
1004
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
1005
|
* import { support } from "../agents.js";
|
|
817
1006
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
1007
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1008
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
1009
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
1010
|
* }
|
|
822
1011
|
* }
|
|
@@ -829,4 +1018,4 @@ declare class VoiceSessionDO {
|
|
|
829
1018
|
declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
|
|
830
1019
|
paths?: AgentFunctionPaths;
|
|
831
1020
|
}) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
|
|
832
|
-
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
|
|
1021
|
+
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r,s as t}from"./packem_shared/agent-loop-BgOHoyg_.mjs";import{collectAgenticMemoryTools as n,toSearchResults as l}from"./packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-CA7Sha2i.mjs";import{codeTool as p}from"./packem_shared/codeTool-Hm_Af6t4.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-CqF7NfUY.mjs";import{defineAgent as g,defineAgentTool as u,isAgentDefinition as S}from"./packem_shared/defineAgent-D7wY7Jl3.mjs";import{functionTool as N}from"./packem_shared/functionTool-C95ns65V.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as U}from"./packem_shared/createAgentGenerate-DSLXAeY2.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as L}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as q,toFunctionReference as y}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as W,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{SecretUnavailableError as Z,requestSecretTool as $,withSecret as ee}from"./packem_shared/SecretUnavailableError-BCp40Leh.mjs";import{defineSkill as re,isSkillDefinition as te}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ne}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as fe}from"./packem_shared/VoiceSessionDO-REut3oqY.mjs";import{r as ie}from"./packem_shared/voice-turn-hIZ7r1ST.mjs";import{webSearchTool as me}from"./packem_shared/webSearchTool-BobmV4cD.mjs";import{default as xe}from"./packem_shared/compileAgentWorkflow-yYM18j57.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,q as SANDBOX_MODULE,Z as SecretUnavailableError,fe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,W as browserTool,L as buildModelMessages,p as codeTool,n as collectAgenticMemoryTools,xe as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,g as defineAgent,u as defineAgentTool,re as defineSkill,Q as fsTool,N as functionTool,S as isAgentDefinition,te as isSkillDefinition,F as jsCodeTool,h as mcpTools,$ as requestSecretTool,U as resolveAgentModel,r as runAgentLoop,ie as runVoiceTurn,t as splitForCompaction,y as toFunctionReference,l as toSearchResults,V as voiceBindingName,H as voiceClassName,me as webSearchTool,ee as withSecret,ne as wrapUntrusted};
|
package/dist/naming.d.mts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name
|
|
2
|
+
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
|
|
3
|
+
* and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
|
|
3
4
|
* @experimental
|
|
4
5
|
*/
|
|
5
6
|
declare const agentClassName: (exportName: string) => string;
|
|
6
|
-
/**
|
|
7
|
-
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
-
* @experimental
|
|
9
|
-
*/
|
|
10
|
-
declare const agentBindingName: (exportName: string) => string;
|
|
11
7
|
/**
|
|
12
8
|
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
9
|
* @experimental
|
|
@@ -27,4 +23,16 @@ declare const voiceClassName: (exportName: string) => string;
|
|
|
27
23
|
* @experimental
|
|
28
24
|
*/
|
|
29
25
|
declare const voiceBindingName: (exportName: string) => string;
|
|
30
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Every runtime function `agentComponent()` registers, with its visibility —
|
|
28
|
+
* `"internal"` for the ones the durable loop dispatches by path, `"public"` for
|
|
29
|
+
* the client-facing queries and mutations.
|
|
30
|
+
*
|
|
31
|
+
* A static table so codegen can auto-register the functions without importing
|
|
32
|
+
* `@lunora/agent/component`, whose module graph (`@lunora/server`, the shard
|
|
33
|
+
* engine, drizzle, hono) every codegen process would otherwise load, agents or
|
|
34
|
+
* not. `__tests__/component.test.ts` fails when it drifts from the component.
|
|
35
|
+
* @experimental
|
|
36
|
+
*/
|
|
37
|
+
declare const AGENT_RUNTIME_FUNCTIONS: Readonly<Record<string, "internal" | "public">>;
|
|
38
|
+
export { AGENT_RUNTIME_FUNCTIONS, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
package/dist/naming.d.ts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name
|
|
2
|
+
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
|
|
3
|
+
* and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
|
|
3
4
|
* @experimental
|
|
4
5
|
*/
|
|
5
6
|
declare const agentClassName: (exportName: string) => string;
|
|
6
|
-
/**
|
|
7
|
-
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
-
* @experimental
|
|
9
|
-
*/
|
|
10
|
-
declare const agentBindingName: (exportName: string) => string;
|
|
11
7
|
/**
|
|
12
8
|
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
9
|
* @experimental
|
|
@@ -27,4 +23,16 @@ declare const voiceClassName: (exportName: string) => string;
|
|
|
27
23
|
* @experimental
|
|
28
24
|
*/
|
|
29
25
|
declare const voiceBindingName: (exportName: string) => string;
|
|
30
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Every runtime function `agentComponent()` registers, with its visibility —
|
|
28
|
+
* `"internal"` for the ones the durable loop dispatches by path, `"public"` for
|
|
29
|
+
* the client-facing queries and mutations.
|
|
30
|
+
*
|
|
31
|
+
* A static table so codegen can auto-register the functions without importing
|
|
32
|
+
* `@lunora/agent/component`, whose module graph (`@lunora/server`, the shard
|
|
33
|
+
* engine, drizzle, hono) every codegen process would otherwise load, agents or
|
|
34
|
+
* not. `__tests__/component.test.ts` fails when it drifts from the component.
|
|
35
|
+
* @experimental
|
|
36
|
+
*/
|
|
37
|
+
declare const AGENT_RUNTIME_FUNCTIONS: Readonly<Record<string, "internal" | "public">>;
|
|
38
|
+
export { AGENT_RUNTIME_FUNCTIONS, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
package/dist/naming.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const t=/([a-z0-9])([A-Z])/gu,a=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,n=e=>`agent-${e.replaceAll(t,"$1-$2").toLowerCase()}`,l=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,r=e=>`VOICE_${e.replaceAll(t,"$1_$2").toUpperCase()}`,i={agentAppendMessage:"internal",agentApprovalGranted:"internal",agentApprovalGrants:"public",agentCompleteRun:"internal",agentDeclineSecret:"public",agentDeleteMessage:"internal",agentDiscardSecret:"internal",agentEnsureThread:"internal",agentEpisodeRecall:"internal",agentEpisodeUpsert:"internal",agentGraphTraverse:"internal",agentGraphUpsert:"internal",agentHistory:"internal",agentMessages:"public",agentOpenSecretRequest:"internal",agentPatchThread:"internal",agentPendingApprovals:"public",agentResolveApproval:"public",agentRevokeApprovalGrant:"public",agentRun:"public",agentSecretRequests:"public",agentSetState:"internal",agentSettleSecretRequest:"internal",agentState:"public",agentSupplySecret:"public",agentTakeSecret:"internal",agentThread:"public"};export{i as AGENT_RUNTIME_FUNCTIONS,a as agentClassName,n as agentDefaultName,r as voiceBindingName,l as voiceClassName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,approvalGranted:`${e}:agentApprovalGranted`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,history:`${e}:agentHistory`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`,takeSecret:`${e}:agentTakeSecret`,discardSecret:`${e}:agentDiscardSecret`,openSecretRequest:`${e}:agentOpenSecretRequest`,settleSecretRequest:`${e}:agentSettleSecretRequest`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as 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]},K=t=>Number.isNaN(t)?[s,"nan"]:t===1/0?[s,"inf"]:t===-1/0?[s,"-inf"]:t,W=(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]},G=(t,e)=>t instanceof Date?[s,"date",e(t.getTime())]:t instanceof Error?W(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 K(t);if(typeof t!="object")return t;const r=o=>I(o,e+1),n=G(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)},Q=(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)},V=(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])]}))},Y=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)},X=(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 Q(t,e);case"error":return X(t,e);case"inf":return 1/0;case"map":return V(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(r=>e(r)));case"undefined":return;case"url":return Y(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(t)),it=t=>ct(JSON.stringify(t)),ut=t=>!t.startsWith(T)&&st(t)?t:`${T}${j(U.encode(t))}`,ft="/_lunora/scheduler/dispatch",lt=3e4,dt=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},L=Symbol("lunoraDispatchFailure"),yt=Symbol("lunoraDispatchDecline"),pt=Symbol("lunoraDispatchMessageId"),_=(t,e)=>(e!==void 0&&Object.defineProperty(t,pt,{value:e}),t),ht=(t,e)=>(Object.defineProperty(t,L,{value:!0}),_(t,e)),gt=(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=ht(new d(c,typeof l=="string"?l:void 0,{data:g,status:o}),n);return e.headers.get(ot)==="1"&&Object.defineProperty(y,yt,{value:!0}),y}}catch{}return _(new d("INTERNAL",`${t}: function dispatch failed (${String(o)}): ${r}`,{status:o}),n)},bt=new Set([400,403,404,422]),wt=new Set([nt,"DISPATCH_UNAUTHENTICATED"]),mt=t=>P(t)&&t[L]===!0,$t=t=>mt(t)&&bt.has(t.status)&&!wt.has(t.code),At=(t,e,r)=>new d("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(r)}ms`,{status:503}),vt=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=`${dt(l)}${ft}`,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"]=ut(t.identity.userId)),t.identity?.claims!==void 0&&(b["x-lunora-identity"]=it(t.identity.claims));const E=c.timeoutMs??lt,N=at(void 0,E,()=>new DOMException(`dispatch timed out after ${String(E)}ms`,"TimeoutError")),$=u=>{throw u instanceof Error&&u.name==="TimeoutError"?At(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 gt(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{vt as a,$t as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as y}from"@ai-sdk/provider-utils";import{LunoraError as s}from"@lunora/errors";import{toFunctionReference as l,DEFAULT_AGENT_FUNCTION_PATHS as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const p=200,N=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,p).join("")};class g extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const T=e=>{if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new s("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:y({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},w=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,f=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},h=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,w)}catch{return!1}return f(t).some(a=>n.includes(a))},E="[redacted]",u="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of f(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(E);return n},m=(e,t,n=new Set)=>{if(!(e instanceof Error))return new s("INTERNAL",u);if(n.has(e))return e;n.add(e);try{e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const a=e;for(const o of Object.getOwnPropertyNames(e)){if(o==="message"||o==="stack")continue;const r=a[o];if(r instanceof Error){const i=m(r,t,n);i!==r&&(a[o]=i)}else h(r,t)&&(a[o]=JSON.parse(c(JSON.stringify(r),t)))}}catch{return new s("INTERNAL",u)}return e},I=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(l(d.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(i){throw m(i,o)}return h(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new g;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(l(d.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new s("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{g as SecretUnavailableError,T as requestSecretTool,N as secretLabelOf,I as withSecret};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as A}from"@lunora/ai/create";import{a as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-CE08SIwv.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-hIZ7r1ST.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-DSLXAeY2.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{jsonSchema as i}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
2
|
+
`);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as t}from"@lunora/ai/create";const i=r=>{const o=r.AI;return o?t({binding:o,env:r}):void 0};export{i as r};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{usageStatus as pt}from"@lunora/ai/create";import{e as mt}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-CE08SIwv.mjs";import{SECRET_VALUE_MAX_TTL_MS as yt}from"@lunora/platform";import{r as Z}from"./workflow-binding-Dm9hBzx_.mjs";import{e as X,d as ft,S as Y}from"./component-shared-DdXFbng-.mjs";import{usageOfFailedTurn as ht,resolveAgentModel as wt}from"./createAgentGenerate-DSLXAeY2.mjs";import{buildModelMessages as W}from"./buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as tt}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"./positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as gt,secretLabelOf as Tt}from"./SecretUnavailableError-BCp40Leh.mjs";import{combineTelemetry as St}from"./combineTelemetry-DgE9W9G8.mjs";import{c as z}from"./tool-output-Cmk3JWMG.mjs";const $t=200,Et=e=>{const t=e.findIndex(n=>n.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=$t;for(;;){const n=await e(t),o=Et(n);if(o.length>0||n.length<t)return o;t*=2}},It=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",B=e=>e.memorySources?e.memorySources:e.memory&&It(e.memory)?[{key:"default",...e.memory}]:[],xt=e=>B(e).find(t=>t.kind==="graph"),Ct=e=>B(e).find(t=>t.kind==="episodic"),I=(e,t)=>t==="default"?e:`${e}:${t}`,kt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:St(...n)},Mt=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,n)=>{const o=kt(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},i=Date.now();await o.onToolExecutionStart?.(s);let c;const d=()=>(c??=n(),c);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const u=await d();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:u,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),u}catch(u){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},Nt=8,At=e=>vt(e)?e:0,et=e=>e===void 0?"null":JSON.stringify(e),Ot=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},_t=e=>e===void 0?[]:[e].flat(),qt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),Ut=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??pt(e),bt=(e,t)=>e===t?e:"partial",ot=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const n={status:bt(j(e),j(t))};for(const o of Ut)(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},Dt=async(e,t,n,o,a,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:n.do(o,async()=>await s()?!1:i===!0||i(t,a))},Ft="WorkflowTimeoutError",nt=e=>e instanceof Error&&e.name===Ft,J=4320*60*1e3,Pt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Gt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,at=e=>{if(e===void 0)return J;if(typeof e=="number")return Math.min(e,X);const t=Gt.exec(e);return t===null?J:Math.min(Number(t[1])*Pt[t[2]],X)},Lt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:i,step:c}=e,d=at(n.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const u=await c.waitForEvent(`approval:${t.id}`,{timeout:d,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!nt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},jt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Wt=(e,t)=>`${String(e)}:${t}`,Bt=async(e,t,n,o,a)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,T=`${c}:secret:${a}`,y=Math.min(at(s.approvalTimeout),yt-Y);await m.do(`secret:request:${a}`,async()=>{await r(d,{consumerTool:n,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:o,threadKey:h,toolCallId:a,toolName:t.name})}),await m.do(`secret:await:${a}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${o}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${a}`,{timeout:y+Y,type:`agent-secret:${a}`}).catch(f=>{if(!nt(f))throw f});const{status:v}=await m.do(`secret:settle:${a}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:a}));return await i(T),await u({ifInstanceId:c,status:"running"}),v},U="lunoraToolOutcome",Ht=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Vt=async(e,t,n,o)=>{const{instanceId:a,persist:s}=e,i=Wt(o,t.id),c=`${a}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=Tt(t.input);if(u===void 0){await s({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await s({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Bt(e,t,n,u,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${jt[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Xt=async(e,t,n)=>{const{agent:o,approvalGrantedRef:a,depth:s,env:i,exports:c,getState:d,instanceId:u,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,step:T,threadKey:y,tools:v}=e,f=`tool:${t.name}:${t.id}`,$=v[t.name],E=`${u}:tool:${t.id}`;if(!$){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if($.secretRequest!==void 0){await Vt(e,t,$.secretRequest.consumer,n);return}const b={depth:s,env:i,exports:c,getState:d,idempotencyKey:f,instanceId:u,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:y,toolCallId:t.id})},run:m,setState:h,step:T,threadKey:y,toolCallId:t.id},D={depth:s,env:i,getState:d,idempotencyKey:f,instanceId:u,run:m,threadKey:y,toolCallId:t.id},F=`tool:approval-gate:${t.id}`;let M,K;const P=async()=>await m(a,{key:y,toolName:t.name})===!0;if(await Dt($,t.input,T,F,D,P)){const{decision:S,note:C,scope:G}=await Lt(e,t);if(S==="reject"){const O=C===void 0?"":` Reason: ${C}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${O}`,messageKey:E,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}M="approved",K=G}const A={...M===void 0?{}:{status:M},...K===void 0?{}:{approvalScope:K}},N=Ht(await T.do(f,async()=>{try{const S=()=>Promise.resolve($.execute(t.input,b)),C=await Kt(o.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:C}}}catch(S){if(mt(S)||S instanceof gt)return{[U]:{failed:S.message}};throw S}}));if("failed"in N){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${N.failed}`),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name});return}const x=N.ok;await l({content:z(typeof x=="string"?x:et(x)),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name})},Yt=(e,t,n)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:wt(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},st=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},zt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=st(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:a,messages:W({history:s.older}),model:n.compaction?.model??n.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Jt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Qt=async e=>{const{agent:t,compact:n,env:o,historyRef:a,instanceId:s,patchThread:i,run:c,threadKey:d}=e,u=Jt(t.compaction),p=await c(a,{configKey:u,key:d}),{messages:r,summary:l}=p,m=st(r,t.compaction);if(m===void 0||n===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:v}=p;return v===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:v.throughSeq}).catch(f=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,f)}),{history:r.filter(f=>f.seq>v.throughSeq),summary:v.summary})};let T;try{T=await n({env:o,messages:W({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(v){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,v),h()}if(T.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(v=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,v)}),{history:m.recent,summary:T}},Zt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Qt(e):await zt(e,await Rt(async f=>await p(c,{key:m,limit:f})));let y={activeTools:o.activeTools,messages:W({history:h,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=Yt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:n}),a));const v={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&u?l(v,f=>{u({text:f,threadKey:m,turn:t})}):s(v)})},Q=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.onStepFinish?.(t),!0))},te=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ee=e=>ft({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),oe=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,i=I("memory:retrieve",e.key),c=await n.do(i,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return H(c)},ne=async(e,t,n,o,a,s)=>{if(n===void 0)return;const i=I("memory:traverse",e.key),c=await a.do(i,async()=>s(o,{owner:n,query:t,...ee(e.graph)}));return H(c)},ae=async(e,t,n,o,a)=>{if(t===void 0)return;const s=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await o.do(s,async()=>a(n,i));return H(c)},se=async(e,t)=>e.kind==="episodic"?ae(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?ne(e,t.input,t.owner,t.graphTraverse,t.step,t.run):oe(e,t.input,t.step,t.run),re=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},ie=async(e,t,n,o,a,s)=>{const i=re(B(e));if(i.length===0)return;const c=g(o.graphTraverse),d=g(o.episodeRecall),u=[];for(const p of i){const r=await se(p,{episodeRecall:d,graphTraverse:c,input:t,owner:n,run:s,step:a});r!==void 0&&u.push(r)}return u.length>0?u.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},ce=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const r=xt(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(I("memory:extract",r.key),async()=>o(l));await u(g(d.graphUpsert),{...m,messageKey:`${i}:${I("extract",r.key)}`,owner:c})}catch{}},ue=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p,threadKey:r}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const l=Ct(t);if(l!==void 0)try{const m={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(I("memory:episode",l.key),async()=>o(m));await u(g(d.episodeUpsert),{messageKey:`${i}:${I("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},de=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},le="12 hours",pe=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:le,type:`agent-dequeue:${t}:${n}`})},me=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},ye=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},fe=async(e,t,n,o,a)=>{const{instanceId:s,persist:i}=e,c=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const d=n.output!==void 0&&n.text.length===0?et(n.output):n.text;return await i({content:d,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await Q(e,{text:n.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await i({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const d of n.toolCalls)await Xt(e,d,t);if(await Q(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...c}),o.push(te(n)),a.length>0&&await qt(a,o))return"stopCondition"},he=async(e,t,n,o)=>{const a=[];let s,i=!1,c=0;for(let d=0;d<t;d+=1){const u=await Zt(e,d,a);o.value=ot(o.value,u.usage),c=d+1;const p=await fe(e,d,u,a,n);if(p==="stopCondition"){i=!0;break}if(p!==void 0){s=p.final;break}}return{final:s,stoppedByCondition:i,turnsRun:c}},Ke=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:i,extractGraph:c,generate:d,instanceId:u,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:T}=e,y=t.maxTurns??Nt,v=_t(t.stopWhen),f=g(l.appendMessage),$=g(l.approvalGranted),E=g(l.openSecretRequest),V=g(l.settleSecretRequest),b=g(l.completeRun),D=g(l.ensureThread),F=g(l.listMessages),M=g(l.history),K=g(l.deleteMessage),P=g(l.patchThread),A=g(l.setState),N=g(l.state),x=async w=>{await m(f,{threadKey:r.threadKey,...w})},S=async w=>{await m(P,{key:r.threadKey,...w})},C=async w=>{await m(K,{messageKey:w,threadKey:r.threadKey})},G=async()=>{await x({content:r.input,messageKey:`${u}:user`,role:"user"})},O={dispatched:!1},_=async w=>{O.dispatched=!0;const q=await m(b,{instanceId:u,key:r.threadKey,...w});q?.dequeued!==void 0&&await me({env:o,exportName:a,exports:s,step:h},r.threadKey,q.dequeued)},rt=async()=>await m(N,{key:r.threadKey}),it=async w=>{await m(A,{key:r.threadKey,state:w})},L=await m(D,{agent:a,instanceId:u,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});L?.outcome==="replaced"&&await de({env:o,exports:s},a,L.priorInstanceId);const ct=await ie(t,r.input,r.owner,l,h,m),ut=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,dt={agent:t,approvalGrantedRef:$,openSecretRef:E,settleSecretRef:V,compact:n,depth:At(r.depth),env:o,exports:s,generate:d,getState:rt,historyRef:M,instanceId:u,instructions:ut,listMessages:F,memoryContext:ct,onTokenDelta:p,owner:r.owner,deleteMessage:C,patchThread:S,persist:x,run:m,setState:it,step:h,streamGenerate:T,threadKey:r.threadKey,tools:t.tools??{}},k={value:void 0};try{L?.outcome==="queued"&&await pe(h,r.threadKey,u),await G();const{final:w,stoppedByCondition:q,turnsRun:lt}=await he(dt,y,v,k),R=k.value===void 0?{}:{usage:k.value};return await ce({agent:t,env:o,extractGraph:c,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h}),await ue({agent:t,env:o,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await ye(t,{env:o,params:r,step:h},{...w,...R}),await _({status:"idle",...R}),{...w,...R}):q?(await _({status:"idle",...R}),{stopped:"stopCondition",turns:lt,...R}):(await _({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...R}),{stopped:"maxTurns",turns:y,...R})}catch(w){throw O.dispatched||(k.value=ot(k.value,ht(w)),await Ot(_,w,k.value)),w}finally{await Mt(t.telemetry)}};export{at as a,ot as b,zt as c,It as i,Ke as r,st as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as I}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as L}from"@lunora/workflow";import{f as S}from"./fnv1a-BNN96GYb.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${S(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!L(d))throw d;l=await i.get(g)}const{output:v,status:u}=await D(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(U(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return j(E)};return{description:t.description,execute:T,inputSchema:I({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{usageStatus as _}from"@lunora/ai/create";import{r as s,d as b,t as x,f as T,s as C,c as v}from"./common-DBc9y7Np.mjs";import{c as L}from"./in-flight-calls-C9QGq8uH.mjs";const E=(l,c)=>typeof l=="string"&&l.length>0?l:c,O={cacheReadTokens:"prompt_cached_tokens",cacheWriteTokens:"prompt_cache_creation_tokens",inputTokens:"prompt_tokens",outputTokens:"completion_tokens",reasoningTokens:"completion_reasoning_tokens",totalTokens:"tokens"},M=l=>{const c={};for(const[u,p]of Object.entries(O)){const f=l[u];f!==void 0&&(c[p]=f)}return c},P=l=>{const{functionId:c,logger:u,recordInputs:p=!1,recordOutputs:f=!1}=l,a=L((e,t,r,n)=>{const o={},d=C(s(n,"usage")??s(e.result,"usage")),y=_(d);if(o.metadata={"lunora.usage.status":y},d!==void 0&&(o.metrics=M(d)),t||(o.error=r??"the model call failed"),f){const h=v(s(n,"content")??s(e.result,"content"));h!==void 0&&(o.output=h)}Object.keys(o).length>0&&e.span.log(o),e.finish()},e=>{e.finish()}),k=(e,t,r)=>{const n=s(e,"callId");if(typeof n!="string")return;let o=r;t instanceof Error?o=t.message:typeof t=="string"&&t.length>0&&(o=t),a.close(n,!1,o,T(t))};return{executeLanguageModelCall:e=>{const{callId:t,execute:r}=e;let n,o;const d=new Promise((i,m)=>{n=i,o=m});let y;const h=new Promise(i=>{y=i});return Promise.resolve(u.traced(async i=>{a.open(t,()=>({finish:y,result:void 0,span:i})),p&&i.log({input:s(e,"messages"),model:s(e,"modelId")});let m;try{m=await r()}catch(g){a.close(t,!1,g instanceof Error?g.message:String(g),T(g)),o(g);return}const I=a.get(t);I!==void 0&&(I.result=m),n(m),await h},{name:E(c,"language_model_call"),type:"llm"})).catch(()=>{}),d},executeTool:e=>{const t=s(s(e,"toolCall"),"toolName");return u.traced(async r=>{p&&r.log({input:x(e),tool:t});const n=await e.execute();return f&&r.log({output:n}),n},{name:E(t,"execute_tool"),type:"tool"})},onAbort:e=>{k(e,s(e,"reason"),"aborted")},onEnd:e=>{a.fromLifecycle(e)},onError:e=>{u.traced(t=>{t.log({error:b(s(e,"error")??e)})},{name:"error",type:"error"}),k(e,s(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof s(e,"callId")=="string"&&a.fromLifecycle(e)},onStepEnd:e=>{a.fromLifecycle(e)}}};export{P as braintrustTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),r=`may not contain the reserved workflow branch-marker key ("${e}")`;export{r as B,o as h};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const u=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"},i=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),c=(t,e)=>({content:[{output:{type:"text",value:e?"Tool call is awaiting approval and has not run.":"Tool call outcome unknown: the run was interrupted before its result was recorded."},toolCallId:t.id,toolName:t.name,type:"tool-result"}],role:"tool"}),d=t=>{const e=new Map;let n;for(const o of t)o.role==="assistant"?(n={answered:new Set,awaitingApproval:new Set},e.set(o,n)):o.role==="tool"&&o.toolCallId!==void 0&&n!==void 0&&(o.status==="awaiting_approval"?n.awaitingApproval.add(o.toolCallId):o.status!=="awaiting_secret"&&n.answered.add(o.toolCallId));return e},m=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"});const n=d(t.history);let o=[];const l=()=>{e.push(...o),o=[]};for(const s of t.history)if(!(s.status==="awaiting_approval"||s.status==="awaiting_secret"))switch(s.role!=="tool"&&l(),s.role){case"assistant":{e.push(u(s));const r=n.get(s);o=(s.toolCalls??[]).filter(a=>r?.answered.has(a.id)!==!0).map(a=>c(a,r?.awaitingApproval.has(a.id)===!0));break}case"system":{e.push({content:s.content,role:"system"});break}case"tool":{e.push(i(s));break}case"user":{e.push({content:s.content,role:"user"});break}}return l(),e};export{m as buildModelMessages};
|