@lunora/agent 1.0.0-alpha.28 → 1.0.0-alpha.281
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/README.md +1 -2
- 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/core.d.mts +204 -0
- package/dist/core.d.ts +204 -0
- package/dist/core.mjs +1 -0
- package/dist/inbound.d.mts +12 -10
- package/dist/inbound.d.ts +12 -10
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +172 -143
- package/dist/index.d.ts +172 -143
- 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_chunks/createAgentGenerate.mjs +3 -0
- package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
- package/dist/packem_chunks/resolve-run.mjs +1 -0
- package/dist/packem_chunks/runAgentLoop.mjs +3 -0
- package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs +1 -0
- package/dist/packem_shared/SecretUnavailableError-BsJMGfML.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-CA-3ovJd.mjs +2 -0
- package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
- package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
- package/dist/packem_shared/app-call-options-BE0CQ6Qg.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-Cn8TuNjk.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.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-yZB8fbYc.mjs +1 -0
- package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-Cl-WQEsZ.mjs +1 -0
- package/dist/packem_shared/createAgentContext-TMvmjncE.mjs +1 -0
- package/dist/packem_shared/defineAgent-6Ih7L9E9.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-Cf433Hdo.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-C9QGq8uH.mjs +1 -0
- package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-BJB3Fpm2.mjs +18 -0
- package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
- package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
- package/dist/packem_shared/normalizeEntityName-BiUH5B5W.mjs +2 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-DPa5UZ45.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-Bzy_Qah6.d.mts} +435 -34
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-Bzy_Qah6.d.ts} +435 -34
- package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
- package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs +1 -0
- package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
- package/dist/packem_shared/wrapUntrusted-CEngnRHW.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 +159 -18
- package/dist/sandbox.d.ts +159 -18
- 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 +24 -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,13 +1,15 @@
|
|
|
1
|
-
import { A as AgentDefinition,
|
|
2
|
-
export type { y as
|
|
1
|
+
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.js";
|
|
2
|
+
export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-Bzy_Qah6.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export { type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.js";
|
|
7
|
-
|
|
8
|
-
import {
|
|
4
|
+
export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.js";
|
|
5
|
+
import { LanguageModel, ModelMessage } from 'ai';
|
|
6
|
+
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
|
|
7
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
|
|
8
|
+
import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai/create';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
10
10
|
import '@lunora/server';
|
|
11
|
+
import '@ai-sdk/provider-utils';
|
|
12
|
+
import '@lunora/workflow';
|
|
11
13
|
/**
|
|
12
14
|
* `AgentLoopOptions` is part of the experimental `@lunora/agent` API and may change without a major version bump.
|
|
13
15
|
* @experimental
|
|
@@ -23,6 +25,8 @@ interface AgentLoopOptions {
|
|
|
23
25
|
env: Record<string, unknown>;
|
|
24
26
|
/** The agent's `lunora/agents.ts` export name (thread attribution). */
|
|
25
27
|
exportName: string;
|
|
28
|
+
/** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
|
|
29
|
+
exports?: unknown;
|
|
26
30
|
/**
|
|
27
31
|
* The run-end episode-summary seam — production wires AI SDK `generateText`.
|
|
28
32
|
* Absent (the default) disables episode recording, so an agent with no
|
|
@@ -183,7 +187,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
|
|
|
183
187
|
interface ToolScriptStep {
|
|
184
188
|
/** A stable name later steps reference the output by. */
|
|
185
189
|
id: string;
|
|
186
|
-
/** The tool's input; values may embed `{ "$from": "
|
|
190
|
+
/** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
|
|
187
191
|
input?: Record<string, unknown>;
|
|
188
192
|
/** The tool to call — one of the tools handed to {@link codeTool}. */
|
|
189
193
|
tool: string;
|
|
@@ -229,8 +233,8 @@ interface CodeToolOptions {
|
|
|
229
233
|
* SCRIPT that composes several of the tools you hand `codeTool` — chaining a
|
|
230
234
|
* later call's input to an earlier call's output — and the whole thing runs in a
|
|
231
235
|
* 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
|
-
*
|
|
236
|
+
* (no `eval`, no isolate), so it runs natively in workerd; for arbitrary code
|
|
237
|
+
* in a Worker Loader isolate, see `jsCodeTool`.
|
|
234
238
|
*
|
|
235
239
|
* Each composed tool dispatches through the same durable context a normal call
|
|
236
240
|
* gets (inheriting RLS), with a per-step idempotency key. A code-mode script runs
|
|
@@ -239,6 +243,16 @@ interface CodeToolOptions {
|
|
|
239
243
|
* keep approval-gated tools as normal top-level tools. Gate the whole script via
|
|
240
244
|
* `opts.needsApproval` instead.
|
|
241
245
|
*
|
|
246
|
+
* STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
|
|
247
|
+
* step runs inside its own durable `step.do`, so the workflow host serializes
|
|
248
|
+
* the returned value before the next step (or the tool result) ever sees it. A
|
|
249
|
+
* `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
|
|
250
|
+
* `null` or a dropped key, and a `bigint` throws outright. That applies to the
|
|
251
|
+
* value a later step reads through `{ "$from": … }` just as much as to the
|
|
252
|
+
* returned `results` — the hand-off is durable state, not an in-memory one. A
|
|
253
|
+
* composed tool that wants to pass a rich value should return its JSON form
|
|
254
|
+
* (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
|
|
255
|
+
*
|
|
242
256
|
* ```ts
|
|
243
257
|
* import { codeTool, defineAgent, functionTool } from "@lunora/agent";
|
|
244
258
|
*
|
|
@@ -256,99 +270,6 @@ interface CodeToolOptions {
|
|
|
256
270
|
* @experimental
|
|
257
271
|
*/
|
|
258
272
|
declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeToolOptions) => AgentToolDefinition<ToolScript, ToolScriptResult>;
|
|
259
|
-
/**
|
|
260
|
-
* Build the `ctx.agents` producer surface from the codegen-emitted spec list
|
|
261
|
-
* (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
|
|
262
|
-
* declared agent resolves its `AGENT_*` Workflow binding off `env` lazily, so
|
|
263
|
-
* a missing binding only errors when that agent is actually started.
|
|
264
|
-
*
|
|
265
|
-
* `cancel` also needs to write the thread's status, so it dispatches the agent
|
|
266
|
-
* runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
|
|
267
|
-
* and the env-backed `createDispatchRunner` (the same runner the workflow body
|
|
268
|
-
* uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
|
|
269
|
-
* inject a `dispatch` double.
|
|
270
|
-
* @experimental
|
|
271
|
-
*/
|
|
272
|
-
declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, dispatch?: AgentRunFunction) => Record<string, AgentHandle>;
|
|
273
|
-
/**
|
|
274
|
-
* Declare a durable agent. The definition compiles onto a Cloudflare Workflow
|
|
275
|
-
* (each LLM turn and each tool call a named durable step; thread messages
|
|
276
|
-
* persisted idempotently in DO SQLite), invoked from mutations/actions via
|
|
277
|
-
* `ctx.agents.NAME.run(...)` and observed live by subscribing to the
|
|
278
|
-
* `agents:agentMessages` query.
|
|
279
|
-
*
|
|
280
|
-
* ```ts
|
|
281
|
-
* // lunora/agents.ts
|
|
282
|
-
* import { defineAgent, defineAgentTool } from "@lunora/agent";
|
|
283
|
-
*
|
|
284
|
-
* export const support = defineAgent({
|
|
285
|
-
* instructions: "You are a helpful support agent.",
|
|
286
|
-
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
287
|
-
* tools: {
|
|
288
|
-
* getWeather: defineAgentTool({
|
|
289
|
-
* description: "Look up the current weather for a city.",
|
|
290
|
-
* execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
|
|
291
|
-
* inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
|
|
292
|
-
* }),
|
|
293
|
-
* },
|
|
294
|
-
* });
|
|
295
|
-
* ```
|
|
296
|
-
*
|
|
297
|
-
* Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
|
|
298
|
-
* functions (from `agentComponent()`) and the `ctx.agents` producer surface.
|
|
299
|
-
* @experimental
|
|
300
|
-
*/
|
|
301
|
-
declare const defineAgent: (config: AgentConfig) => AgentDefinition;
|
|
302
|
-
/**
|
|
303
|
-
* Runtime brand check for a {@link AgentDefinition}.
|
|
304
|
-
* @experimental
|
|
305
|
-
*/
|
|
306
|
-
declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
|
|
307
|
-
/**
|
|
308
|
-
* Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
|
|
309
|
-
* the loop's durable step (with an `AgentToolContext`) rather than inside the
|
|
310
|
-
* model call.
|
|
311
|
-
* @experimental
|
|
312
|
-
*/
|
|
313
|
-
declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
|
|
314
|
-
/**
|
|
315
|
-
* Author-supplied config for {@link functionTool}.
|
|
316
|
-
* @experimental
|
|
317
|
-
*/
|
|
318
|
-
interface FunctionToolOptions<Input> {
|
|
319
|
-
/** What the tool does — shown to the model (the model decides from it). */
|
|
320
|
-
description: string;
|
|
321
|
-
/** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
|
|
322
|
-
inputSchema: FlexibleSchema<Input>;
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* Expose any Lunora query/mutation/action as an agent tool. The returned
|
|
326
|
-
* definition's `execute` dispatches the referenced function through the loop's
|
|
327
|
-
* existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
|
|
328
|
-
* per tool, and the call runs inside the loop's named durable step exactly like
|
|
329
|
-
* any other tool.
|
|
330
|
-
*
|
|
331
|
-
* ```ts
|
|
332
|
-
* import { functionTool } from "@lunora/agent";
|
|
333
|
-
* import { api } from "./_generated/api";
|
|
334
|
-
*
|
|
335
|
-
* export const support = defineAgent({
|
|
336
|
-
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
337
|
-
* tools: {
|
|
338
|
-
* lookupOrder: functionTool(api.orders.byId, {
|
|
339
|
-
* description: "Look up an order by its id.",
|
|
340
|
-
* inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
|
|
341
|
-
* }),
|
|
342
|
-
* },
|
|
343
|
-
* });
|
|
344
|
-
* ```
|
|
345
|
-
*
|
|
346
|
-
* The function reference may be a typed `api.*` reference or a `"module:name"`
|
|
347
|
-
* path. The model-provided input is passed verbatim as the function's args, so
|
|
348
|
-
* `inputSchema` should mirror the referenced function's argument validator.
|
|
349
|
-
* @experimental
|
|
350
|
-
*/
|
|
351
|
-
declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
|
|
352
273
|
/**
|
|
353
274
|
* Resolve the configured model against the Worker env (see `AgentModelInput`).
|
|
354
275
|
* @experimental
|
|
@@ -471,6 +392,17 @@ interface McpToolsOptions {
|
|
|
471
392
|
command?: string;
|
|
472
393
|
/** Identify this client to the server on connect. Default `"lunora-agent"`. */
|
|
473
394
|
name?: string;
|
|
395
|
+
/**
|
|
396
|
+
* Gate an adapted tool's call behind a human approval. Defaults to
|
|
397
|
+
* **unattended** (no gate) — matching today's behavior. An MCP tool's
|
|
398
|
+
* result feeds back into the model's context (`adaptMcpResult`), so a
|
|
399
|
+
* hostile downstream server can pair indirect prompt injection with an
|
|
400
|
+
* unattended mutating tool call; pass a boolean to gate every adapted
|
|
401
|
+
* tool the same way, or a predicate `(toolName, input) => boolean` to
|
|
402
|
+
* gate per tool (evaluated from replay-stable input, so keep it
|
|
403
|
+
* deterministic).
|
|
404
|
+
*/
|
|
405
|
+
needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
|
|
474
406
|
/** Only adapt these tool names (default: every tool the server lists). */
|
|
475
407
|
only?: ReadonlyArray<string>;
|
|
476
408
|
/** Prefix added to each adapted tool's key (disambiguate multiple servers). */
|
|
@@ -510,6 +442,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
|
|
|
510
442
|
* every call. In the Workers runtime only the HTTP/SSE transports run (stdio
|
|
511
443
|
* does not) — pass `url`, or inject an already-connected `client` for a custom
|
|
512
444
|
* transport (also the test seam).
|
|
445
|
+
*
|
|
446
|
+
* Every adapted tool runs UNATTENDED by default (no approval gate) — pass
|
|
447
|
+
* `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
|
|
513
448
|
* @experimental
|
|
514
449
|
*/
|
|
515
450
|
declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
|
|
@@ -556,48 +491,104 @@ declare const DEFAULT_AGENT_FUNCTION_PATHS: AgentFunctionPaths;
|
|
|
556
491
|
* @experimental
|
|
557
492
|
*/
|
|
558
493
|
declare const toFunctionReference: (source: AgentFunctionReference | string) => AgentFunctionReference;
|
|
494
|
+
/** The model's input to {@link requestSecretTool}: what the secret is for, shown to the person asked. */
|
|
495
|
+
interface SecretRequestInput {
|
|
496
|
+
label: string;
|
|
497
|
+
}
|
|
559
498
|
/**
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
499
|
+
* Thrown by {@link withSecret} when the value is no longer takeable. The loop
|
|
500
|
+
* records it as a deterministic tool failure, so the model can recover rather
|
|
501
|
+
* than the durable step retrying a read that can never succeed.
|
|
502
|
+
*/
|
|
503
|
+
declare class SecretUnavailableError extends Error {
|
|
504
|
+
readonly code = "SECRET_UNAVAILABLE";
|
|
505
|
+
constructor();
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* An agent tool that asks the human for a secret value (an API key, a token) and
|
|
509
|
+
* hands the model only an opaque `{ secretRef }` in return. The loop pauses the
|
|
510
|
+
* run until the owner supplies the value through `agents:agentSupplySecret`, or
|
|
511
|
+
* declines through `agents:agentDeclineSecret`. `execute` is never called: the
|
|
512
|
+
* loop resolves this tool itself.
|
|
513
|
+
*
|
|
514
|
+
* `consumer` names the one tool allowed to read the value. The model can pass the
|
|
515
|
+
* `secretRef` to any tool, but only the declared consumer's {@link withSecret} call
|
|
516
|
+
* takes it, so a prompt-injected model cannot route the value elsewhere.
|
|
517
|
+
*
|
|
518
|
+
* Codegen wires the secret store when a source in `lunora/` value-imports this tool
|
|
519
|
+
* from `@lunora/agent`: by a named import, a namespace import that reads it, or a
|
|
520
|
+
* relative barrel that re-exports it. Without that wiring the supply mutation refuses,
|
|
521
|
+
* and the refusal names the missing import. Requires a host that rates `secretValues`
|
|
522
|
+
* as supported.
|
|
566
523
|
*
|
|
567
524
|
* ```ts
|
|
568
|
-
* import {
|
|
525
|
+
* import { defineAgent, requestSecretTool } from "@lunora/agent";
|
|
569
526
|
*
|
|
570
|
-
* export const billing =
|
|
571
|
-
* name: "billing",
|
|
572
|
-
* instructions: "When asked about invoices, cite the invoice id.",
|
|
573
|
-
* knowledge: { source: "rag:searchBillingDocs", topK: 4 },
|
|
527
|
+
* export const billing = defineAgent({
|
|
574
528
|
* tools: {
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
*
|
|
529
|
+
* requestApiKey: requestSecretTool({
|
|
530
|
+
* consumer: "chargeCard",
|
|
531
|
+
* description: "Ask the user for their payment-provider API key.",
|
|
578
532
|
* }),
|
|
533
|
+
* chargeCard: functionTool({ ... }), // reads the value with withSecret
|
|
579
534
|
* },
|
|
580
535
|
* });
|
|
581
536
|
* ```
|
|
582
537
|
*
|
|
583
|
-
* The
|
|
584
|
-
*
|
|
585
|
-
*
|
|
586
|
-
* which owns the flat model-facing namespace.
|
|
538
|
+
* The value transits the supply mutation's arguments, which are marked
|
|
539
|
+
* `v.sensitive`: the request log masks them. The run's history records only the
|
|
540
|
+
* request id.
|
|
587
541
|
* @experimental
|
|
588
542
|
*/
|
|
589
|
-
declare const
|
|
590
|
-
|
|
591
|
-
|
|
543
|
+
declare const requestSecretTool: (options: {
|
|
544
|
+
consumer: string;
|
|
545
|
+
description: string;
|
|
546
|
+
}) => AgentToolDefinition<SecretRequestInput, {
|
|
547
|
+
secretRef: string;
|
|
548
|
+
}>;
|
|
549
|
+
/**
|
|
550
|
+
* Read a human-supplied secret inside the tool that the request declared as its
|
|
551
|
+
* `consumer`, hand it to `use`, and return only what `use` returns. The value never
|
|
552
|
+
* leaves the callback: it is not a step output, not a tool result and not a message.
|
|
553
|
+
* The read is its own durable step named for this call, so a retry of the same step
|
|
554
|
+
* re-takes the value (the claimant is this step's name), while a different call
|
|
555
|
+
* cannot.
|
|
556
|
+
*
|
|
557
|
+
* Call it from inside a tool's `execute`. The discard runs as a separate durable step
|
|
558
|
+
* only after the take succeeded and `use` returned, so a call that is refused (the
|
|
559
|
+
* wrong tool, another thread, an expired request) cannot burn a value the declared
|
|
560
|
+
* consumer still needs. If `use` keeps failing, the value stays until its TTL expires,
|
|
561
|
+
* which is the backstop for a crash between the take and the discard. `use` must not
|
|
562
|
+
* return or log the value. A result that carries it is refused (the call fails with
|
|
563
|
+
* `LunoraError`) rather than journalled. An error that carries it is redacted before
|
|
564
|
+
* it propagates, so the step's retry, the failure the loop records and telemetry never
|
|
565
|
+
* see the value; `traceToolExecution` records the tool's input and output.
|
|
566
|
+
* @throws {SecretUnavailableError} when the request is unknown, not supplied, declared for another consumer, or from another thread
|
|
567
|
+
* @experimental
|
|
568
|
+
*/
|
|
569
|
+
declare const withSecret: <Result>(context: AgentToolContext, secretRef: string, use: (secret: string) => Promise<Result> | Result) => Promise<Result>;
|
|
570
|
+
/**
|
|
571
|
+
* Wrap untrusted text for inclusion in a prompt. The text sits between a tag
|
|
572
|
+
* whose id is random per call, so payload text cannot forge the closing tag (it
|
|
573
|
+
* cannot know the id), and any `<` or `>` in it is escaped so it cannot form a
|
|
574
|
+
* tag at all. A mention or cashtag (`@`, `$`) not glued to a word, and a slash
|
|
575
|
+
* command `/` at the start of a token, get a zero-width space after them. Given a header map, the headers are rendered
|
|
576
|
+
* above the body with credential-like values redacted. A one-line note after the
|
|
577
|
+
* block tells the model the enclosed data is not to be followed as instructions.
|
|
578
|
+
*
|
|
579
|
+
* Use it on the text a mapper hands the model, e.g. `input: wrapUntrusted(email.text ?? "")`.
|
|
592
580
|
* @experimental
|
|
593
581
|
*/
|
|
594
|
-
declare const
|
|
582
|
+
declare const wrapUntrusted: (value: string, headers?: Headers | Readonly<Record<string, string>>) => string;
|
|
595
583
|
/**
|
|
596
584
|
* A control frame the server sends the client as a JSON text message (audio
|
|
597
585
|
* rides separate binary frames). `ready` announces the negotiated codec on
|
|
598
586
|
* connect; `user_transcript` carries the STT result; `assistant_delta` streams
|
|
599
587
|
* the live LLM text; `assistant_done` is the final turn text; `interrupted`
|
|
600
|
-
* acks a barge-in; `
|
|
588
|
+
* acks a barge-in; `assistant_discarded` says the turn failed, so the deltas
|
|
589
|
+
* already streamed for it are not an answer; `error` reports a failure. An
|
|
590
|
+
* `error` alone does not end a turn: a speech-synthesis failure reports one and
|
|
591
|
+
* the turn still completes.
|
|
601
592
|
* @experimental
|
|
602
593
|
*/
|
|
603
594
|
type VoiceServerFrame = {
|
|
@@ -615,6 +606,8 @@ type VoiceServerFrame = {
|
|
|
615
606
|
} | {
|
|
616
607
|
text: string;
|
|
617
608
|
type: "user_transcript";
|
|
609
|
+
} | {
|
|
610
|
+
type: "assistant_discarded";
|
|
618
611
|
} | {
|
|
619
612
|
type: "interrupted";
|
|
620
613
|
};
|
|
@@ -674,6 +667,13 @@ interface VoiceTurnResult {
|
|
|
674
667
|
interface RunVoiceTurnOptions {
|
|
675
668
|
/** The agent whose thread + models back this session. */
|
|
676
669
|
agent: AgentDefinition;
|
|
670
|
+
/**
|
|
671
|
+
* History-compaction seam — the SAME one the durable loop uses. Voice and
|
|
672
|
+
* text turns share one thread, so an agent that declares `compaction` must
|
|
673
|
+
* get it here too; absent (or with no `compaction` config) the turn takes
|
|
674
|
+
* the byte-identical uncompacted path.
|
|
675
|
+
*/
|
|
676
|
+
compact?: AgentCompact;
|
|
677
677
|
/** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
|
|
678
678
|
connectionId: string;
|
|
679
679
|
/** The Worker env (resolves a dynamic `instructions` thunk). */
|
|
@@ -755,6 +755,8 @@ declare class VoiceSessionDO {
|
|
|
755
755
|
protected readonly streamGenerate: AgentStreamGenerate;
|
|
756
756
|
protected readonly sttModel: string;
|
|
757
757
|
protected readonly ttsModel: string;
|
|
758
|
+
/** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
|
|
759
|
+
private readonly maxSessionTurns;
|
|
758
760
|
private readonly audioBuffers;
|
|
759
761
|
private readonly bufferedBytes;
|
|
760
762
|
private readonly controllers;
|
|
@@ -793,6 +795,8 @@ declare class VoiceSessionDO {
|
|
|
793
795
|
private synthesizeWithSignal;
|
|
794
796
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
797
|
private cleanupSocket;
|
|
798
|
+
/** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
|
|
799
|
+
private closeSocket;
|
|
796
800
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
797
801
|
private send;
|
|
798
802
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
|
@@ -807,26 +811,51 @@ declare class VoiceSessionDO {
|
|
|
807
811
|
private waitForSocketDrain;
|
|
808
812
|
}
|
|
809
813
|
/**
|
|
810
|
-
*
|
|
811
|
-
*
|
|
814
|
+
* Config for {@link webSearchTool}.
|
|
815
|
+
* @experimental
|
|
816
|
+
*/
|
|
817
|
+
interface WebSearchToolOptions {
|
|
818
|
+
/** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
|
|
819
|
+
byokAlias?: string;
|
|
820
|
+
/** Overrides the description shown to the model. */
|
|
821
|
+
description?: string;
|
|
822
|
+
/**
|
|
823
|
+
* The AI Gateway that brokers and bills the search. Defaults to
|
|
824
|
+
* `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
|
|
825
|
+
*/
|
|
826
|
+
gatewayId?: string;
|
|
827
|
+
/** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
|
|
828
|
+
limit?: number;
|
|
829
|
+
/** Defaults to the Web Search API's own default (`"ceramic"`). */
|
|
830
|
+
provider?: AiWebSearchProvider;
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* What the model passes.
|
|
834
|
+
* @experimental
|
|
835
|
+
*/
|
|
836
|
+
interface WebSearchToolInput {
|
|
837
|
+
query: string;
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* A batteries-included agent tool over the Cloudflare Web Search API (beta,
|
|
841
|
+
* `ctx.ai.websearch`), so an agent can ground an answer in live results.
|
|
842
|
+
* A search bills a provider key stored on the gateway (`byokAlias`, else the
|
|
843
|
+
* `default` alias) when there is one, otherwise AI Gateway credits; every
|
|
844
|
+
* provider runs under Zero Data Retention.
|
|
845
|
+
*
|
|
846
|
+
* It calls the `AI` binding straight from the tool's durable step: a search
|
|
847
|
+
* is a read, so the at-least-once step retry repeats nothing but a query, and
|
|
848
|
+
* there is no dispatcher action to register.
|
|
812
849
|
*
|
|
813
850
|
* ```ts
|
|
814
|
-
* import
|
|
815
|
-
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
|
-
* import { support } from "../agents.js";
|
|
851
|
+
* import { defineAgent, webSearchTool } from "@lunora/agent";
|
|
817
852
|
*
|
|
818
|
-
* export
|
|
819
|
-
*
|
|
820
|
-
*
|
|
821
|
-
*
|
|
822
|
-
* }
|
|
853
|
+
* export const researcher = defineAgent({
|
|
854
|
+
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
855
|
+
* tools: { search: webSearchTool({ provider: "exa" }) },
|
|
856
|
+
* });
|
|
823
857
|
* ```
|
|
824
|
-
*
|
|
825
|
-
* The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
|
|
826
|
-
* (`run`); the loop supplies determinism (step naming + idempotent persists).
|
|
827
858
|
* @experimental
|
|
828
859
|
*/
|
|
829
|
-
declare const
|
|
830
|
-
|
|
831
|
-
}) => 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 };
|
|
860
|
+
declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
|
|
861
|
+
export { AGENT_MODULE, type AgentAsToolOptions, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolContext, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SecretRequestInput, SecretUnavailableError, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, mcpTools, requestSecretTool, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool, withSecret, wrapUntrusted };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runAgentLoop as
|
|
1
|
+
import{runAgentLoop as r,splitForCompaction as t}from"./packem_chunks/runAgentLoop.mjs";import{collectAgenticMemoryTools as n,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as m}from"./packem_shared/agentAsTool-BF-7Dnzy.mjs";import{codeTool as s}from"./packem_shared/codeTool-Cn8TuNjk.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-TMvmjncE.mjs";import{defineAgent as A,defineAgentTool as g,isAgentDefinition as S}from"./packem_shared/defineAgent-6Ih7L9E9.mjs";import{functionTool as N}from"./packem_shared/functionTool-Cf433Hdo.mjs";import{createAgentGenerate as h,createEpisodeExtract as C,createGraphExtract as M,createStreamGenerate as O,resolveAgentModel as _}from"./packem_chunks/createAgentGenerate.mjs";import{jsCodeTool as U}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";import{default as G}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{adaptMcpResult as v,mcpTools as L}from"./packem_shared/adaptMcpResult-CA-3ovJd.mjs";import{buildModelMessages as B}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V,agentDefaultName as j,voiceBindingName as H,voiceClassName as I}from"./naming.mjs";import{AGENT_MODULE as X,DEFAULT_AGENT_FUNCTION_PATHS as q,SANDBOX_INVOKE_PATH as y,SANDBOX_MODULE as K,toFunctionReference as W}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as J,containerFsTool as Q,containerTool as Y,fsTool as Z}from"./sandbox.mjs";import{default as ee}from"./packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs";import{SecretUnavailableError as re,requestSecretTool as te,withSecret as ae}from"./packem_shared/SecretUnavailableError-BsJMGfML.mjs";import{defineSkill as fe,isSkillDefinition as le}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as pe}from"./packem_shared/wrapUntrusted-CEngnRHW.mjs";import{default as ie}from"./packem_shared/VoiceSessionDO-CdvG2L-D.mjs";import{r as xe}from"./packem_shared/voice-turn-B9omvXoR.mjs";import{webSearchTool as Te}from"./packem_shared/webSearchTool-BzXW0R4r.mjs";import{default as Ae}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{X as AGENT_MODULE,q as DEFAULT_AGENT_FUNCTION_PATHS,y as SANDBOX_INVOKE_PATH,K as SANDBOX_MODULE,re as SecretUnavailableError,ie as VoiceSessionDO,v as adaptMcpResult,m as agentAsTool,V as agentClassName,c as agentComponent,j as agentDefaultName,x as agentExtension,J as browserTool,B as buildModelMessages,s as codeTool,n as collectAgenticMemoryTools,Ae as compileAgentWorkflow,Q as containerFsTool,Y as containerTool,T as createAgentContext,h as createAgentGenerate,C as createEpisodeExtract,M as createGraphExtract,O as createStreamGenerate,A as defineAgent,g as defineAgentTool,fe as defineSkill,Z as fsTool,N as functionTool,S as isAgentDefinition,le as isSkillDefinition,U as jsCodeTool,G as jsonSchema,L as mcpTools,te as requestSecretTool,_ as resolveAgentModel,r as runAgentLoop,xe as runVoiceTurn,t as splitForCompaction,W as toFunctionReference,f as toSearchResults,H as voiceBindingName,I as voiceClassName,Te as webSearchTool,ee as withAgentScheduleShard,ae as withSecret,pe as wrapUntrusted};
|
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,3 @@
|
|
|
1
|
+
import{usageStatus as O}from"@lunora/ai/create";import{LunoraError as j}from"@lunora/errors";import{r as P}from"../packem_shared/agent-ai-CP87uSoZ.mjs";import R from"../packem_shared/jsonSchema-fhoaBWpN.mjs";import{F as v,s as b}from"../packem_shared/common-DBc9y7Np.mjs";const m=e=>({...e,status:O(e)}),k=e=>m(b(e)),x=e=>e.map(t=>{const o={id:t.toolCallId,input:t.input,name:t.toolName};return t.invalid!==!0?o:{...o,invalid:t.error instanceof Error?t.error.message:String(t.error)}}),h=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=P(t);if(!o)throw new j("INTERNAL",`@lunora/agent: the agent model "${e}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return o.model(e)}return e};let T;const f=()=>(T??=import("ai").catch(e=>{throw T=void 0,e}),T),q=(e,t,o)=>{const r=h(t.model,o),n={};for(const[a,u]of Object.entries(t.tools??{}))n[a]=e.tool({description:u.description,inputSchema:e.asSchema(u.inputSchema)});const i=t.output===void 0?void 0:e.Output.object({schema:t.output}),s={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:r,output:i,staticSettings:s,tools:n}},E=(e,t)=>{let o;return()=>(o??=f().then(r=>({ai:r,base:q(r,e,t)})).catch(r=>{throw o=void 0,r}),o)},S=(e,{activeTools:t,messages:o,model:r,signal:n,toolChoice:i})=>{const{defaultModel:s,output:a,staticSettings:u,tools:l}=e,d=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([g])=>t.includes(g)));return{messages:o,model:r??s,...u,...Object.keys(d).length>0?{tools:d}:{},...i===void 0?{}:{toolChoice:i},...a===void 0?{}:{output:a},...n===void 0?{}:{abortSignal:n}}},M=e=>e instanceof Error?e:new Error(`model stream failed: ${String(e)}`,{cause:e}),N=e=>({inputTokens:{cacheRead:e?.inputTokens?.cacheRead,cacheWrite:e?.inputTokens?.cacheWrite,noCache:void 0,total:e?.inputTokens?.total},outputTokens:{reasoning:e?.outputTokens?.reasoning,text:void 0,total:e?.outputTokens?.total}}),_=e=>{if(e===void 0)return m(void 0);const t=e.inputTokens?.total,o=e.outputTokens?.total,r=t===void 0||o===void 0?void 0:t+o;return m(b({inputTokens:t,inputTokenDetails:{cacheReadTokens:e.inputTokens?.cacheRead,cacheWriteTokens:e.inputTokens?.cacheWrite},outputTokens:o,outputTokenDetails:{reasoningTokens:e.outputTokens?.reasoning},totalTokens:r}))},y=(e,t)=>{const o=new Error(e.raw===void 0?"model finished with an error reason":`model finished with an error reason (provider reason: ${e.raw})`,{cause:e});return o[v]=_(t),o},B=e=>{if(!(typeof e!="object"||e===null))return e[v]},I=(e,t)=>e.wrapLanguageModel({middleware:{wrapGenerate:async({doGenerate:o})=>{const r=await o();if(r.finishReason.unified==="error")throw y(r.finishReason,r.usage);return r},wrapStream:async({doStream:o})=>{const{stream:r,...n}=await o();let i=!1;return{...n,stream:r.pipeThrough(new TransformStream({flush:s=>{i||s.enqueue({error:new Error("model stream ended without a finish part"),type:"error"})},transform:(s,a)=>{if(s.type==="finish"&&(i=!0,s.finishReason.unified==="error")){a.enqueue({...s,usage:N(s.usage)}),a.enqueue({error:y(s.finishReason,s.usage),type:"error"});return}a.enqueue(s)}}))}}},model:t}),p=(e,t)=>typeof t=="string"?t:I(e,t),H=(e,t)=>{const o=E(e,t);return async r=>{const{ai:n,base:i}=await o(),s=S(i,r),a=await n.generateText({...s,model:p(n,s.model)});return{text:a.text,toolCalls:x(a.toolCalls),usage:k(a.usage),...i.output===void 0?{}:{output:a.output}}}},X=(e,t)=>{const o=E(e,t);return async(r,n)=>{const{ai:i,base:s}=await o(),a=S(s,r),u=i.streamText({...a,model:p(i,a.model)});let l="";try{for await(const c of u.stream){if(c.type==="error")throw M(c.error);c.type==="text-delta"&&(l+=c.text,n(c.text))}}catch(c){if(!r.signal?.aborted)throw c}if(r.signal?.aborted)return{text:l,toolCalls:[],usage:m(void 0)};const[d,g,A,C]=await Promise.all([u.text,u.toolCalls,u.usage,s.output===void 0?Promise.resolve(void 0):u.output]);return{text:d,toolCalls:x(g),usage:k(A),...s.output===void 0?{}:{output:C}}}},U=R({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),$=(e,t)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${e}`,"",`Assistant: ${t}`].join(`
|
|
2
|
+
`),J=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{output:i}=await n.generateText({model:p(n,h(o,t)),output:n.Output.object({schema:U}),prompt:$(r,e)});return i},G=(e,t)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${e}`,"",`Assistant: ${t}`].join(`
|
|
3
|
+
`),K=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{text:i}=await n.generateText({model:p(n,h(o,t)),prompt:G(r,e)});return{summary:i.trim()}},w="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",W=" An existing brief of the earlier conversation is included above. UPDATE that brief: keep every still-relevant fact from it and fold in the newly aged-out messages. Do not replace it with a summary of only the new messages.",Q=()=>async({env:e,messages:t,model:o,previousSummary:r})=>{const n=await f(),{text:i}=await n.generateText({messages:t,model:p(n,h(o,e)),system:r===void 0?w:`${w}${W}`});return i.trim()};export{H as createAgentGenerate,Q as createCompact,K as createEpisodeExtract,J as createGraphExtract,X as createStreamGenerate,h as resolveAgentModel,B as usageOfFailedTurn};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{usageStatus as X,USAGE_ATTRIBUTE as _,estimateModelCost as Y}from"@lunora/ai/create";import{a as G,r as d,f as H,s as q,e as j,c as K,t as Q}from"../packem_shared/common-DBc9y7Np.mjs";import{c as Z}from"../packem_shared/in-flight-calls-C9QGq8uH.mjs";const W=t=>`${String(Math.round(t))}000000`,ee=Array.from({length:256},(t,o)=>o.toString(16).padStart(2,"0")),O=512,$=new Uint8Array(O);let k=O;const D=(t,o,n)=>{let l="";for(let i=0;i<n;i+=1)l+=ee[t[o+i]];return l},F=t=>{if(t>O){const n=new Uint8Array(t);return crypto.getRandomValues(n),D(n,0,t)}k+t>O&&(crypto.getRandomValues($),k=0);const o=D($,k,t);return k+=t,o},w=(t,o)=>typeof o=="boolean"?{key:t,value:{boolValue:o}}:typeof o=="number"?Number.isFinite(o)?Number.isSafeInteger(o)?{key:t,value:{intValue:String(o)}}:{key:t,value:{doubleValue:o}}:{key:t,value:{stringValue:String(o)}}:{key:t,value:{stringValue:o}},te=(t,o,n)=>{const l={},i=new Map,S=(p,h)=>{const b=p.toLowerCase(),x=i.get(b);x===void 0?(i.set(b,p),l[p]=h):l[x]=h};for(const[p,h]of Object.entries(t))S(p,h);for(const[p,h]of Object.entries(o??{}))S(p,h);return n!==void 0&&n.length>0&&S("authorization",`Bearer ${n}`),l},oe=t=>Array.isArray(t)?t:[t],ne=(t,o)=>{const n={"service.name":t};for(const[l,i]of Object.entries({}))n[l]=i;return Object.entries(n).map(([l,i])=>w(l,i))},se=(t,o,n,l)=>({resourceSpans:[{resource:{attributes:ne(n)},scopeSpans:[{scope:{name:o},spans:oe(t)}]}]}),re=50,ae=256*1024,ce=new TextEncoder,r=(t,o,n)=>{if(n!=null){if(typeof n=="boolean"||typeof n=="number"||typeof n=="string"){t.push(w(o,n));return}t.push(w(o,JSON.stringify(n)))}},ie=(t,o)=>{(async()=>{let l;try{l=await t}catch(i){o(!1,i instanceof Error?i.message:String(i),void 0);return}o(!0,void 0,l)})().catch(()=>{})},ge=t=>{const{conversationId:o,endpoint:n,headers:l,recordInputs:i=!1,recordOutputs:S=!1,token:p,traceId:h,waitUntil:b}=t,x=t.serviceName??"lunora";let A=n;for(;A.endsWith("/");)A=A.slice(0,-1);const P=`${A}/v1/traces`,z=te({"content-type":"application/json"},l,p);let I=[],N=0;const R=()=>{if(I.length===0)return;const e=I;I=[],N=0;try{const s=fetch(P,{body:JSON.stringify(se(e,"@lunora/agent",x)),headers:z,method:"POST"}).catch(()=>{});b?.(s)}catch{}},U=(e,s,a,u,y)=>{const f={attributes:y,endTimeUnixNano:W(Date.now()),kind:1,name:e,spanId:F(8),startTimeUnixNano:W(s),status:a?{code:1}:{code:2,message:u??""},traceId:h??F(16)};I.push(f),N+=ce.encode(JSON.stringify(f)).byteLength,(I.length>=re||N>=ae)&&R()},T=Z((e,s,a,u)=>{const{messages:y,modelId:f,provider:C,result:m,startTs:J}=e,c=[];r(c,"gen_ai.operation.name","chat"),r(c,"gen_ai.request.model",f),r(c,"gen_ai.system",C),r(c,"gen_ai.conversation.id",o);const g=q(d(u,"usage")??d(m,"usage")),L=X(g);r(c,"lunora.usage.status",L),r(c,_.inputTokens,g?.inputTokens),r(c,_.outputTokens,g?.outputTokens),r(c,"gen_ai.usage.total_tokens",g?.totalTokens),r(c,_.cacheReadTokens,g?.cacheReadTokens),r(c,_.cacheWriteTokens,g?.cacheWriteTokens),r(c,_.reasoningTokens,g?.reasoningTokens);const E=j(u)??j(m);E&&(r(c,"gen_ai.response.cached",E.cached),r(c,"cf.aig.log_id",E.logId));const M=E?.cost,V=M??(typeof f=="string"&&L==="complete"?Y(f,{cacheReadTokens:g?.cacheReadTokens,cacheWriteTokens:g?.cacheWriteTokens,inputTokens:g?.inputTokens,outputTokens:g?.outputTokens}):void 0);V!==void 0&&(r(c,"gen_ai.usage.cost",V),r(c,"lunora.usage.cost.source",M===void 0?"estimated":"provider")),i&&r(c,"gen_ai.prompt",y),S&&r(c,"gen_ai.completion",K(d(u,"content")??d(m,"content"))),U(typeof f=="string"?`chat ${f}`:"language_model_call",J,s,a,c)}),v=(e,s,a)=>{const u=d(e,"callId");if(typeof u!="string")return;let y=a;s instanceof Error?y=s.message:typeof s=="string"&&s.length>0&&(y=s),T.close(u,!1,y,H(s))},B=e=>({messages:d(e,"messages"),modelId:d(e,"modelId"),provider:d(e,"provider"),result:void 0,startTs:Date.now()});return{flush:R,executeLanguageModelCall:async e=>{const{callId:s}=e;T.open(s,()=>B(e));try{const a=await e.execute(),u=T.get(s);return u!==void 0&&(u.result=a),a}catch(a){throw T.close(s,!1,a instanceof Error?a.message:String(a),H(a)),a}},onAbort:e=>{v(e,d(e,"reason"),"aborted")},onEnd:e=>{T.fromLifecycle(e)},onError:e=>{v(e,d(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof d(e,"callId")=="string"&&T.fromLifecycle(e)},onLanguageModelCallStart:e=>{const s=d(e,"callId");typeof s=="string"&&T.open(s,()=>B(e))},onStepEnd:e=>{T.fromLifecycle(e)},executeTool:e=>{const s=Date.now(),a=G(e),u=e.execute();return ie(u,(f,C)=>{const m=[];r(m,"gen_ai.operation.name","execute_tool"),r(m,"gen_ai.tool.name",a),r(m,"gen_ai.tool.call.id",d(e,"toolCallId")),i&&r(m,"gen_ai.tool.input",Q(e)),U(typeof a=="string"?`execute_tool ${a}`:"execute_tool",s,f,C,m)}),u}}};export{ge as otlpTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as o}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";const i=(a,e,t)=>o({env:e,label:"@lunora/agent",...t===void 0?{}:{fetchImpl:t},...a===void 0?{}:{identity:{userId:a}}});export{i as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{usageStatus as dt}from"@lunora/ai/create";import{e as ut}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as lt}from"@lunora/platform";import{r as Q}from"../packem_shared/workflow-binding-Dm9hBzx_.mjs";import{a as pt}from"../packem_shared/app-call-options-BE0CQ6Qg.mjs";import{d as mt,a as V,S as z}from"../packem_shared/component-shared--SPcu0Iw.mjs";import{usageOfFailedTurn as yt,resolveAgentModel as ft}from"./createAgentGenerate.mjs";import{r as ht,f as gt,m as I,a as wt}from"../packem_shared/memory-JI0lUu84.mjs";import{buildModelMessages as B}from"../packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as Z}from"../naming.mjs";import{toFunctionReference as v}from"../packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"../packem_shared/positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as Tt,secretLabelOf as St}from"../packem_shared/SecretUnavailableError-BsJMGfML.mjs";import{combineTelemetry as $t}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{c as J}from"../packem_shared/tool-output-Cmk3JWMG.mjs";const Et=200,Ct=e=>{const t=e.findIndex(o=>o.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=Et;for(;;){const o=await e(t),a=Ct(o);if(a.length>0||o.length<t)return a;t*=2}},xt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const o=Array.isArray(t)?t:[t];return o.length===0?void 0:$t(...o)},It=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,o)=>{const a=xt(e);if(a===void 0)return o();const n={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},r={callId:t.id,messages:[],toolCall:n,toolContext:void 0},i=Date.now();await a.onToolExecutionStart?.(r);let c;const d=()=>(c??=o(),c);try{if(a.executeTool===void 0)await d();else try{await a.executeTool({...r,execute:d,toolCallId:t.id})}catch{}const u=await d();return await a.onToolExecutionEnd?.({...r,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 a.onToolExecutionEnd?.({...r,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},kt=8,Mt=e=>vt(e)?e:0,tt=e=>e===void 0?"null":JSON.stringify(e),Nt=async(e,t,o)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...o===void 0?{}:{usage:o}})}catch(a){t instanceof Error&&t.cause===void 0&&(t.cause=a)}},Ot=e=>e===void 0?[]:[e].flat(),At=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),_t=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??dt(e),qt=(e,t)=>e===t?e:"partial",et=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const o={status:qt(j(e),j(t))};for(const a of _t)(e[a]!==void 0||t[a]!==void 0)&&(o[a]=(e[a]??0)+(t[a]??0));return o},Ut=async(e,t,o,a,n,r)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:o.do(a,async()=>await r()?!1:i===!0||i(t,n))},bt="WorkflowTimeoutError",ot=e=>e instanceof Error&&e.name===bt,Dt=async(e,t)=>{const{agent:o,deleteMessage:a,instanceId:n,patchThread:r,persist:i,step:c}=e,d=V(o.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${n}:approval:${t.id}`,role:"tool",approvalAgent:e.agentName,status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await r({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(!ot(p))throw p;return{decision:"reject",note:"approval timed out"}});return await a(`${n}:approval:${t.id}`),await r({status:"running"}),u},Ft={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Gt=(e,t)=>`${String(e)}:${t}`,Lt=async(e,t,o,a,n)=>{const{agent:r,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:s,settleSecretRef:l,step:m,threadKey:f}=e,T=`${c}:secret:${n}`,y=Math.min(V(r.approvalTimeout),lt-z);await m.do(`secret:request:${n}`,async()=>{await s(d,{consumerTool:o,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:a,threadKey:f,toolCallId:n,toolName:t.name})}),await m.do(`secret:await:${n}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${a}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${n}`,{timeout:y+z,type:`agent-secret:${n}`}).catch(w=>{if(!ot(w))throw w});const{status:h}=await m.do(`secret:settle:${n}`,async()=>await s(l,{instanceId:c,threadKey:f,toolCallId:n}));return await i(T),await u({ifInstanceId:c,status:"running"}),h},U="lunoraToolOutcome",Pt=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Wt=async(e,t,o,a)=>{const{instanceId:n,persist:r}=e,i=Gt(a,t.id),c=`${n}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=St(t.input);if(u===void 0){await r({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 r({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 Lt(e,t,o,u,i);await r({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${Ft[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},jt=async(e,t,o)=>{const{agent:a,agentName:n,approvalGrantedRef:r,depth:i,env:c,exports:d,getState:u,instanceId:p,onTokenDelta:s,owner:l,persist:m,run:f,setState:T,shardKey:y,step:h,threadKey:w,tools:b}=e,$=`tool:${t.name}:${t.id}`,E=b[t.name],C=`${p}:tool:${t.id}`;if(!E){await m({content:`Error: unknown tool "${t.name}"`,messageKey:C,role:"tool",stepName:$,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await m({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:C,role:"tool",stepName:$,toolCallId:t.id,toolName:t.name});return}if(E.secretRequest!==void 0){await Wt(e,t,E.secretRequest.consumer,o);return}const D={depth:i,env:c,exports:d,getState:u,idempotencyKey:$,instanceId:p,owner:l,reportProgress:S=>{s?.({data:S,kind:"progress",threadKey:w,toolCallId:t.id})},run:f,setState:T,shardKey:y,step:h,threadKey:w,toolCallId:t.id},F={depth:i,env:c,getState:u,idempotencyKey:$,instanceId:p,run:f,shardKey:y,threadKey:w,toolCallId:t.id},G=`tool:approval-gate:${t.id}`;let M,N;const L=async()=>await f(r,{agent:n,key:w,toolName:t.name})===!0;if(await Ut(E,t.input,h,G,F,L)){const{decision:S,note:R,scope:K}=await Dt(e,t);if(S==="reject"){const P=R===void 0?"":` Reason: ${R}`;await m({content:`Tool "${t.name}" was rejected by the user and not run.${P}`,messageKey:C,role:"tool",status:"rejected",stepName:$,toolCallId:t.id,toolName:t.name});return}M="approved",N=K}const O={...M===void 0?{}:{status:M},...N===void 0?{}:{approvalScope:N}},A=Pt(await h.do($,async()=>{try{const S=()=>Promise.resolve(E.execute(t.input,D)),R=await Kt(a.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:R}}}catch(S){if(ut(S)||S instanceof Tt)return{[U]:{failed:S.message}};throw S}}));if("failed"in A){await m({content:J(`Error: tool "${t.name}" failed and will not be retried. ${A.failed}`),messageKey:C,role:"tool",stepName:$,...O,toolCallId:t.id,toolName:t.name});return}const _=A.ok;await m({content:J(typeof _=="string"?_:tt(_)),messageKey:C,role:"tool",stepName:$,...O,toolCallId:t.id,toolName:t.name})},Bt=(e,t,o)=>{if(!t)return e;let{messages:a}=e;return t.messages!==void 0&&(a=t.messages),t.system!==void 0&&(a=[{content:t.system,role:"system"},...a]),{activeTools:t.activeTools??e.activeTools,messages:a,model:t.model===void 0?e.model:ft(t.model,o),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const o=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=o)return;let a=e.length-o;for(;a>0&&e[a]?.role==="tool";)a-=1;if(!(a<=0))return{older:e.slice(0,a),recent:e.slice(a)}},Ht=async(e,t)=>{const{agent:o,compact:a,env:n}=e,r=at(t,o.compaction);if(r===void 0||a===void 0)return{history:t,summary:void 0};try{const i=await a({env:n,messages:B({history:r.older}),model:o.compaction?.model??o.model});return i.length>0?{history:r.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Yt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},zt=async e=>{const{agent:t,compact:o,env:a,historyRef:n,instanceId:r,patchThread:i,run:c,threadKey:d}=e,u=Yt(t.compaction),p=await c(n,{configKey:u,key:d}),{messages:s,summary:l}=p,m=at(s,t.compaction);if(m===void 0||o===void 0)return{history:s,summary:l};const f=async()=>{const{fallback:h}=p;return h===void 0?{history:s,summary:l}:(await i({ifInstanceId:r,summaryRebuiltSeq:h.throughSeq}).catch(w=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,w)}),{history:s.filter(w=>w.seq>h.throughSeq),summary:h.summary})};let T;try{T=await o({env:a,messages:B({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(h){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,h),f()}if(T.length===0)return f();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:r,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(h=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,h)}),{history:m.recent,summary:T}},Jt=async(e,t,o)=>{const{agent:a,env:n,generate:r,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:s,streamGenerate:l,threadKey:m}=e;return s.do(`llm:turn:${String(t)}`,async()=>{const{history:f,summary:T}=a.compaction!==void 0&&e.compact!==void 0?await zt(e):await Ht(e,await Rt(async w=>await p(c,{key:m,limit:w})));let y={activeTools:a.activeTools,messages:B({history:f,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:a.toolChoice};a.prepareStep&&(y=Bt(y,await a.prepareStep({messages:y.messages,stepNumber:t,steps:o}),n));const h={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(h,w=>{u({text:w,threadKey:m,turn:t})}):r(h)})},X=async(e,t)=>{const{agent:o,step:a}=e;o.onStepFinish&&await a.do(`agent:step-finish:${String(t.turn)}`,async()=>(await o.onStepFinish?.(t),!0))},Xt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Qt=e=>mt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Vt=async(e,t,o,a,n)=>{if(e.source===void 0)return;const r=v(e.source),{topK:i}=e,c=I("memory:retrieve",e.key),d={query:t,...i===void 0?{}:{topK:i}},u=await a.do(c,async()=>n(r,d,pt(o)));return H(u)},Zt=async(e,t,o,a,n,r)=>{if(o===void 0)return;const i=I("memory:traverse",e.key),c=await n.do(i,async()=>r(a,{owner:o,query:t,...Qt(e.graph)}));return H(c)},te=async(e,t,o,a,n)=>{if(t===void 0)return;const r=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await a.do(r,async()=>n(o,i));return H(c)},ee=async(e,t)=>e.kind==="episodic"?te(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Zt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Vt(e,t.input,t.shardKey,t.step,t.run),oe=e=>{const t=e.findIndex(o=>o.kind==="episodic");return e.filter((o,a)=>o.kind!=="episodic"||a===t)},ae=async(e,t,o,a,n,r,i)=>{const c=oe(ht(e));if(c.length===0)return;const d=v(n.graphTraverse),u=v(n.episodeRecall),p=[];for(const s of c){const l=await ee(s,{episodeRecall:u,graphTraverse:d,input:t,owner:o,run:i,shardKey:a,step:r});l!==void 0&&p.push(l)}return p.length>0?p.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},ne=async e=>{const{agent:t,env:o,extractGraph:a,finalText:n,input:r,instanceId:i,owner:c,paths:d,run:u,step:p}=e;if(a===void 0||c===void 0||n===void 0||n.length===0)return;const s=gt(t);if(s!==void 0)try{const l={assistantText:n,env:o,model:s.graph?.extractionModel??t.model,userInput:r},m=await p.do(I("memory:extract",s.key),async()=>a(l));await u(v(d.graphUpsert),{...m,messageKey:`${i}:${I("extract",s.key)}`,owner:c})}catch{}},se=async e=>{const{agent:t,env:o,extractEpisode:a,finalText:n,input:r,instanceId:i,owner:c,paths:d,run:u,step:p,threadKey:s}=e;if(a===void 0||c===void 0||n===void 0||n.length===0)return;const l=wt(t);if(l!==void 0)try{const m={assistantText:n,env:o,model:l.episodic?.extractionModel??t.model,userInput:r},{summary:f}=await p.do(I("memory:episode",l.key),async()=>a(m));await u(v(d.episodeUpsert),{messageKey:`${i}:${I("episode",l.key)}`,owner:c,summary:f,threadKey:s})}catch{}},re=async(e,t,o)=>{const a=Q(e.env,e.exports,Z(t),["get"]);if(a!==void 0)try{await(await a.get(o)).terminate()}catch{}},ie="12 hours",ce=async(e,t,o)=>{await e.waitForEvent(`dequeue:${o}`,{timeout:ie,type:`agent-dequeue:${t}:${o}`})},de=async(e,t,o)=>{const a=Q(e.env,e.exports,Z(e.exportName),["get"]);if(a===void 0)return;const n=a.get.bind(a);try{await e.step.do(`dequeue-wake:${o}`,async()=>(await(await n(o)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${o}`}),o))}catch{}},ue=async(e,t,o)=>{const{onReply:a}=e,{replyRef:n}=t.params;if(!(a===void 0||n===void 0))try{await t.step.do("agent:reply",async()=>(await a({env:t.env,replyRef:n,result:o,threadKey:t.params.threadKey}),n.channel))}catch{}},le=async(e,t,o,a,n)=>{const{instanceId:r,persist:i}=e,c=o.usage===void 0?{}:{usage:o.usage};if(o.toolCalls.length===0){const d=o.output!==void 0&&o.text.length===0?tt(o.output):o.text;return await i({content:d,messageKey:`${r}:assistant:${String(t)}`,role:"assistant"}),await X(e,{text:o.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:o.text,turns:t+1,...o.output===void 0?{}:{output:o.output}}}}await i({content:o.text,messageKey:`${r}:assistant:${String(t)}`,role:"assistant",toolCalls:o.toolCalls});for(const d of o.toolCalls)await jt(e,d,t);if(await X(e,{text:o.text,toolCalls:o.toolCalls,turn:t,...c}),a.push(Xt(o)),n.length>0&&await At(n,a))return"stopCondition"},pe=async(e,t,o,a)=>{const n=[];let r,i=!1,c=0;for(let d=0;d<t;d+=1){const u=await Jt(e,d,n);a.value=et(a.value,u.usage),c=d+1;const p=await le(e,d,u,n,o);if(p==="stopCondition"){i=!0;break}if(p!==void 0){r=p.final;break}}return{final:r,stoppedByCondition:i,turnsRun:c}},Ke=async e=>{const{agent:t,compact:o,env:a,exportName:n,exports:r,extractEpisode:i,extractGraph:c,generate:d,instanceId:u,onTokenDelta:p,params:s,paths:l,run:m,step:f,streamGenerate:T}=e,y=t.maxTurns??kt,h=Ot(t.stopWhen),w=v(l.appendMessage),b=v(l.approvalGranted),$=v(l.openSecretRequest),E=v(l.settleSecretRequest),C=v(l.completeRun),Y=v(l.ensureThread),D=v(l.listMessages),F=v(l.history),G=v(l.deleteMessage),M=v(l.patchThread),N=v(l.setState),L=v(l.state),O=async g=>{await m(w,{threadKey:s.threadKey,...g})},A=async g=>{await m(M,{key:s.threadKey,...g})},_=async g=>{await m(G,{messageKey:g,threadKey:s.threadKey})},S=async()=>{await O({content:s.input,messageKey:`${u}:user`,role:"user"})},R={dispatched:!1},K=async g=>{R.dispatched=!0;const q=await m(C,{instanceId:u,key:s.threadKey,...g});q?.dequeued!==void 0&&await de({env:a,exportName:n,exports:r,step:f},s.threadKey,q.dequeued)},P=async()=>await m(L,{key:s.threadKey}),nt=async g=>{await m(N,{key:s.threadKey,state:g})},W=await m(Y,{agent:n,instanceId:u,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});W?.outcome==="replaced"&&await re({env:a,exports:r},n,W.priorInstanceId);const st=await ae(t,s.input,s.owner,s.shardKey,l,f,m),rt=typeof t.instructions=="function"?t.instructions({env:a,input:s.input,threadKey:s.threadKey}):t.instructions,it={agent:t,agentName:n,approvalGrantedRef:b,openSecretRef:$,settleSecretRef:E,compact:o,depth:Mt(s.depth),env:a,exports:r,generate:d,getState:P,historyRef:F,instanceId:u,instructions:rt,listMessages:D,memoryContext:st,onTokenDelta:p,owner:s.owner,deleteMessage:_,patchThread:A,persist:O,run:m,setState:nt,shardKey:s.shardKey,step:f,streamGenerate:T,threadKey:s.threadKey,tools:t.tools??{}},k={value:void 0};try{W?.outcome==="queued"&&await ce(f,s.threadKey,u),await S();const{final:g,stoppedByCondition:q,turnsRun:ct}=await pe(it,y,h,k),x=k.value===void 0?{}:{usage:k.value};return await ne({agent:t,env:a,extractGraph:c,finalText:g?.text,input:s.input,instanceId:u,owner:s.owner,paths:l,run:m,step:f}),await se({agent:t,env:a,extractEpisode:i,finalText:g?.text,input:s.input,instanceId:u,owner:s.owner,paths:l,run:m,step:f,threadKey:s.threadKey}),g?(await ue(t,{env:a,params:s,step:f},{...g,...x}),await K({status:"idle",...x}),{...g,...x}):q?(await K({status:"idle",...x}),{stopped:"stopCondition",turns:ct,...x}):(await K({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...x}),{stopped:"maxTurns",turns:y,...x})}catch(g){throw R.dispatched||(k.value=et(k.value,yt(g)),await Nt(K,g,k.value)),g}finally{await It(t.telemetry)}};export{et as addUsage,Ht as compactHistory,Ke as runAgentLoop,at as splitForCompaction};
|