@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.
Files changed (106) hide show
  1. package/README.md +1 -2
  2. package/dist/channels.d.mts +23 -12
  3. package/dist/channels.d.ts +23 -12
  4. package/dist/channels.mjs +1 -1
  5. package/dist/component.d.mts +54 -2
  6. package/dist/component.d.ts +54 -2
  7. package/dist/component.mjs +2 -2
  8. package/dist/core.d.mts +204 -0
  9. package/dist/core.d.ts +204 -0
  10. package/dist/core.mjs +1 -0
  11. package/dist/inbound.d.mts +12 -10
  12. package/dist/inbound.d.ts +12 -10
  13. package/dist/inbound.mjs +1 -1
  14. package/dist/index.d.mts +172 -143
  15. package/dist/index.d.ts +172 -143
  16. package/dist/index.mjs +1 -1
  17. package/dist/naming.d.mts +15 -7
  18. package/dist/naming.d.ts +15 -7
  19. package/dist/naming.mjs +1 -1
  20. package/dist/packem_chunks/createAgentGenerate.mjs +3 -0
  21. package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
  22. package/dist/packem_chunks/resolve-run.mjs +1 -0
  23. package/dist/packem_chunks/runAgentLoop.mjs +3 -0
  24. package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
  25. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs +1 -0
  26. package/dist/packem_shared/SecretUnavailableError-BsJMGfML.mjs +1 -0
  27. package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
  28. package/dist/packem_shared/adaptMcpResult-CA-3ovJd.mjs +2 -0
  29. package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
  30. package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
  31. package/dist/packem_shared/app-call-options-BE0CQ6Qg.mjs +1 -0
  32. package/dist/packem_shared/braintrustTelemetry-Ck09dC4G.mjs +1 -0
  33. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  34. package/dist/packem_shared/buildModelMessages-DVQdQ7_1.mjs +5 -0
  35. package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +1 -0
  36. package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs +1 -0
  37. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  38. package/dist/packem_shared/common-DBc9y7Np.mjs +1 -0
  39. package/dist/packem_shared/compileAgentWorkflow-yZB8fbYc.mjs +1 -0
  40. package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
  41. package/dist/packem_shared/consoleTelemetry-Cl-WQEsZ.mjs +1 -0
  42. package/dist/packem_shared/createAgentContext-TMvmjncE.mjs +1 -0
  43. package/dist/packem_shared/defineAgent-6Ih7L9E9.mjs +3 -0
  44. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  45. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  46. package/dist/packem_shared/functionTool-Cf433Hdo.mjs +1 -0
  47. package/dist/packem_shared/in-flight-calls-C9QGq8uH.mjs +1 -0
  48. package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
  49. package/dist/packem_shared/jsCodeTool-BJB3Fpm2.mjs +18 -0
  50. package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
  51. package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
  52. package/dist/packem_shared/normalizeEntityName-BiUH5B5W.mjs +2 -0
  53. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  54. package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
  55. package/dist/packem_shared/runVoiceTurn-DPa5UZ45.mjs +1 -0
  56. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  57. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  58. package/dist/packem_shared/sentryTelemetry-B1BuLxxj.mjs +1 -0
  59. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  60. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-Bzy_Qah6.d.mts} +435 -34
  61. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-Bzy_Qah6.d.ts} +435 -34
  62. package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
  63. package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
  64. package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs +1 -0
  65. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  66. package/dist/packem_shared/wrapUntrusted-CEngnRHW.mjs +2 -0
  67. package/dist/reply.d.mts +58 -0
  68. package/dist/reply.d.ts +58 -0
  69. package/dist/reply.mjs +1 -0
  70. package/dist/sandbox.d.mts +159 -18
  71. package/dist/sandbox.d.ts +159 -18
  72. package/dist/sandbox.mjs +1 -1
  73. package/dist/skill-markdown.d.mts +36 -0
  74. package/dist/skill-markdown.d.ts +36 -0
  75. package/dist/skill-markdown.mjs +1 -0
  76. package/dist/telemetry/index.d.mts +165 -38
  77. package/dist/telemetry/index.d.ts +165 -38
  78. package/dist/telemetry/index.mjs +1 -1
  79. package/package.json +24 -9
  80. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  81. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  82. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  83. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  84. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  85. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  86. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  87. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  88. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  89. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  90. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  91. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  92. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  93. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  94. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  95. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  96. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  97. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  98. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  99. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  100. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  101. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  102. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  103. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  104. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  105. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  106. package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,13 +1,15 @@
1
- import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-boAM2Yi1.mjs";
2
- export type { y as AgentEmailMapper, z as AgentEmailRun, B as AgentGenerateOptions, C as AgentGenerateResult, D as AgentInstructionsContext, E as AgentLiveEvent, F as AgentMemoryOptions, G as AgentMemorySource, H as AgentMessageStatus, J as AgentOnStepFinish, K as AgentPrepareStep, L as AgentPrepareStepInput, M as AgentPrepareStepResult, N as AgentProgressEvent, O as AgentRunHandle, P as AgentStepFinishInfo, Q as AgentStepInfo, R as AgentThreadStatus, T as AgentTokenDelta, U as AgentToolCall, a as AgentToolContext, V as AgentUsage, W as AgentVoiceConfig, X as AgentWorkflowBindingLike, Y as AgentWorkflowInstanceLike } from "./packem_shared/types.d-boAM2Yi1.mjs";
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.mjs";
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.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
- import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
6
- export { type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.mjs";
7
- import { createAi } from '@lunora/ai';
8
- import { WorkflowDefinition } from '@lunora/workflow';
4
+ export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.mjs";
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.mjs";
7
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
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": "&lt;stepId>", "$path": "a.b" }` refs. */
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-code
233
- * execution (the Cloudflare Worker Loader path) is a separate future mode.
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
- * Declare a reusable skill: a bundle of expertise — an instruction fragment,
561
- * tools, and retrieval `knowledge` — an agent composes in via
562
- * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
563
- * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
564
- * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
565
- * retrieval verbatim.
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 { defineSkill, functionTool } from "@lunora/agent";
525
+ * import { defineAgent, requestSecretTool } from "@lunora/agent";
569
526
  *
570
- * export const billing = defineSkill({
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
- * lookupInvoice: functionTool(api.billing.invoiceById, {
576
- * description: "Look up an invoice by id.",
577
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
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 merge into the agent's flat namespace (tool-name collisions, instruction
584
- * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
585
- * only validates its own `name`; tool-name validation is deferred to the merge,
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 defineSkill: (config: SkillConfig) => SkillDefinition;
590
- /**
591
- * Runtime brand check for a {@link SkillDefinition}.
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 isSkillDefinition: (value: unknown) => value is SkillDefinition;
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; `error` reports a non-fatal turn failure.
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
- * Compile a `defineAgent` definition into the workflow the generated
811
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
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 LunoraWorkflow from "@lunora/workflow/do";
815
- * import { compileAgentWorkflow } from "@lunora/agent";
816
- * import { support } from "../agents.js";
851
+ * import { defineAgent, webSearchTool } from "@lunora/agent";
817
852
  *
818
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
819
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
820
- * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
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 compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
830
- paths?: AgentFunctionPaths;
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 };