@lunora/agent 1.0.0-alpha.2 → 1.0.0-alpha.200

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 (95) hide show
  1. package/dist/channels.d.mts +52 -33
  2. package/dist/channels.d.ts +52 -33
  3. package/dist/channels.mjs +1 -181
  4. package/dist/component.d.mts +97 -70
  5. package/dist/component.d.ts +97 -70
  6. package/dist/component.mjs +2 -407
  7. package/dist/inbound.d.mts +24 -22
  8. package/dist/inbound.d.ts +24 -22
  9. package/dist/inbound.mjs +1 -32
  10. package/dist/index.d.mts +576 -497
  11. package/dist/index.d.ts +576 -497
  12. package/dist/index.mjs +1 -18
  13. package/dist/naming.d.mts +18 -22
  14. package/dist/naming.d.ts +18 -22
  15. package/dist/naming.mjs +1 -8
  16. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs +1 -0
  18. package/dist/packem_shared/VoiceSessionDO-CB_yuzWV.mjs +1 -0
  19. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  20. package/dist/packem_shared/agent-ai-CxEYOyOu.mjs +1 -0
  21. package/dist/packem_shared/agent-loop-DyJWnyiT.mjs +3 -0
  22. package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +1 -0
  23. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  24. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  25. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  26. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  27. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  28. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  29. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  30. package/dist/packem_shared/compileAgentWorkflow-C287O2ux.mjs +1 -0
  31. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  32. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  33. package/dist/packem_shared/createAgentContext-BxDMNWNG.mjs +1 -0
  34. package/dist/packem_shared/createAgentGenerate-EEFNvpS5.mjs +3 -0
  35. package/dist/packem_shared/defineAgent-CjxGfOg7.mjs +3 -0
  36. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  37. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  38. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  39. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  40. package/dist/packem_shared/jsCodeTool-BLOvjXGF.mjs +18 -0
  41. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  42. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  43. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  44. package/dist/packem_shared/runAgentLoop-BIjYgCLE.mjs +1 -0
  45. package/dist/packem_shared/runVoiceTurn-CtKjHnfU.mjs +1 -0
  46. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  47. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  48. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  49. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  50. package/dist/packem_shared/types.d-CbYtFBw9.d.mts +1376 -0
  51. package/dist/packem_shared/types.d-CbYtFBw9.d.ts +1376 -0
  52. package/dist/packem_shared/voice-turn-DZNbOsWB.mjs +1 -0
  53. package/dist/packem_shared/webSearchTool-BptEsfd9.mjs +1 -0
  54. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  55. package/dist/reply.d.mts +40 -0
  56. package/dist/reply.d.ts +40 -0
  57. package/dist/reply.mjs +1 -0
  58. package/dist/sandbox.d.mts +269 -124
  59. package/dist/sandbox.d.ts +269 -124
  60. package/dist/sandbox.mjs +1 -109
  61. package/dist/skill-markdown.d.mts +36 -0
  62. package/dist/skill-markdown.d.ts +36 -0
  63. package/dist/skill-markdown.mjs +1 -0
  64. package/dist/telemetry/index.d.mts +314 -114
  65. package/dist/telemetry/index.d.ts +314 -114
  66. package/dist/telemetry/index.mjs +1 -4
  67. package/package.json +18 -9
  68. package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
  69. package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +0 -297
  70. package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
  71. package/dist/packem_shared/agentAsTool-Dt8NlU6k.mjs +0 -94
  72. package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
  73. package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +0 -47
  74. package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
  75. package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
  76. package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
  77. package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
  78. package/dist/packem_shared/common-DAeFCot5.mjs +0 -61
  79. package/dist/packem_shared/compileAgentWorkflow-BxJjHgtD.mjs +0 -55
  80. package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +0 -93
  81. package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
  82. package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +0 -192
  83. package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
  84. package/dist/packem_shared/defineAgent-D6maSbVc.mjs +0 -148
  85. package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
  86. package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
  87. package/dist/packem_shared/graph-component-aoUwO-f0.mjs +0 -216
  88. package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
  89. package/dist/packem_shared/normalizeEntityName-CyEEWFkR.mjs +0 -3
  90. package/dist/packem_shared/runAgentLoop-Dhg4ZNvw.mjs +0 -493
  91. package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
  92. package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
  93. package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +0 -36
  94. package/dist/packem_shared/types.d-BhJFTvz_.d.mts +0 -1114
  95. package/dist/packem_shared/types.d-BhJFTvz_.d.ts +0 -1114
package/dist/index.d.mts CHANGED
@@ -1,103 +1,105 @@
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-BhJFTvz_.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-BhJFTvz_.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 AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
+ export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
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';
5
+ export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
6
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
7
+ import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
10
10
  import '@lunora/server';
11
11
  /**
12
- * `AgentLoopOptions` is part of the experimental `@lunora/agent` API and may change without a major version bump.
13
- * @experimental
14
- */
12
+ * `AgentLoopOptions` is part of the experimental `@lunora/agent` API and may change without a major version bump.
13
+ * @experimental
14
+ */
15
15
  interface AgentLoopOptions {
16
16
  agent: AgentDefinition;
17
17
  /**
18
- * The history-compaction seam — production wires AI SDK `generateText`.
19
- * Absent (the default) disables compaction, so an agent with no `compaction`
20
- * config, and every unit test that doesn't opt in, is byte-identical.
21
- */
18
+ * The history-compaction seam — production wires AI SDK `generateText`.
19
+ * Absent (the default) disables compaction, so an agent with no `compaction`
20
+ * config, and every unit test that doesn't opt in, is byte-identical.
21
+ */
22
22
  compact?: AgentCompact;
23
23
  env: Record<string, unknown>;
24
24
  /** The agent's `lunora/agents.ts` export name (thread attribution). */
25
25
  exportName: string;
26
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
27
+ exports?: unknown;
26
28
  /**
27
- * The run-end episode-summary seam — production wires AI SDK `generateText`.
28
- * Absent (the default) disables episode recording, so an agent with no
29
- * episodic memory, and every unit test that doesn't opt in, is byte-identical.
30
- */
29
+ * The run-end episode-summary seam — production wires AI SDK `generateText`.
30
+ * Absent (the default) disables episode recording, so an agent with no
31
+ * episodic memory, and every unit test that doesn't opt in, is byte-identical.
32
+ */
31
33
  extractEpisode?: AgentEpisodeExtract;
32
34
  /**
33
- * The run-end graph-extraction seam — production wires AI SDK `generateText`
34
- * with a structured `Output.object`. Absent (the default) disables
35
- * extraction, so an agent with no graph memory, and every unit test that
36
- * doesn't opt in, is byte-identical.
37
- */
35
+ * The run-end graph-extraction seam — production wires AI SDK `generateText`
36
+ * with a structured `Output.object`. Absent (the default) disables
37
+ * extraction, so an agent with no graph memory, and every unit test that
38
+ * doesn't opt in, is byte-identical.
39
+ */
38
40
  extractGraph?: AgentGraphExtract;
39
41
  /** The LLM-turn seam — production wires AI SDK `generateText`. */
40
42
  generate: AgentGenerate;
41
43
  /** The workflow instance id — the deterministic per-run message-key prefix. */
42
44
  instanceId: string;
43
45
  /**
44
- * Live-only sink for streamed token deltas. Supplied by the runtime (tees to
45
- * the existing stream transport); when present together with
46
- * {@link AgentLoopOptions.streamGenerate} each turn streams its deltas here
47
- * instead of a single non-streaming `generate` call. Absent (the default)
48
- * keeps the byte-identical non-streaming path. Never fired on a replay — the
49
- * memoized turn skips the step body that would emit deltas.
50
- */
46
+ * Live-only sink for streamed token deltas. Supplied by the runtime (tees to
47
+ * the existing stream transport); when present together with
48
+ * {@link AgentLoopOptions.streamGenerate} each turn streams its deltas here
49
+ * instead of a single non-streaming `generate` call. Absent (the default)
50
+ * keeps the byte-identical non-streaming path. Never fired on a replay — the
51
+ * memoized turn skips the step body that would emit deltas.
52
+ */
51
53
  onTokenDelta?: AgentTokenSink;
52
54
  params: AgentRunInput;
53
55
  paths: AgentFunctionPaths;
54
56
  run: AgentRunFunction;
55
57
  step: AgentStepLike;
56
58
  /**
57
- * The streaming LLM-turn seam — production wires AI SDK `streamText`. Used
58
- * only when {@link AgentLoopOptions.onTokenDelta} is also present; otherwise
59
- * the loop falls back to {@link AgentLoopOptions.generate} unchanged.
60
- */
59
+ * The streaming LLM-turn seam — production wires AI SDK `streamText`. Used
60
+ * only when {@link AgentLoopOptions.onTokenDelta} is also present; otherwise
61
+ * the loop falls back to {@link AgentLoopOptions.generate} unchanged.
62
+ */
61
63
  streamGenerate?: AgentStreamGenerate;
62
64
  }
63
65
  /**
64
- * Decide the compaction split for a turn: when `compaction` is configured and the
65
- * history exceeds `maxMessages`, return the `older` messages to summarize and the
66
- * `recent` tail to keep verbatim (the most recent `keepRecent`, default
67
- * `ceil(maxMessages / 2)`). Returns `undefined` when compaction is unset, the
68
- * history is short enough, or the tail would be the whole history — a PURE
69
- * decision (no I/O), unit-testable in isolation.
70
- * @experimental
71
- */
66
+ * Decide the compaction split for a turn: when `compaction` is configured and the
67
+ * history exceeds `maxMessages`, return the `older` messages to summarize and the
68
+ * `recent` tail to keep verbatim (the most recent `keepRecent`, default
69
+ * `ceil(maxMessages / 2)`). Returns `undefined` when compaction is unset, the
70
+ * history is short enough, or the tail would be the whole history — a PURE
71
+ * decision (no I/O), unit-testable in isolation.
72
+ * @experimental
73
+ */
72
74
  declare const splitForCompaction: (history: ReadonlyArray<AgentMessageRow>, compaction: AgentConfig["compaction"]) => {
73
75
  older: AgentMessageRow[];
74
76
  recent: AgentMessageRow[];
75
77
  } | undefined;
76
78
  /**
77
- * The durable tool-loop. Correctness rests on two invariants:
78
- *
79
- * 1. **Deterministic step names.** Each LLM turn is `llm:turn:N` (`N` = the
80
- * loop index, replay-stable) and each tool call is `tool:NAME:CALL_ID`
81
- * (`CALL_ID` = the provider's stable id, itself replayed from the memoized LLM
82
- * step). Native `step.do` memoization then guarantees a COMPLETED step is
83
- * never re-run on replay — a resumed run cannot double-charge a card. A step
84
- * that FAILS mid-body is retried at-least-once; the tool receives its step
85
- * name as `idempotencyKey` to dedupe on.
86
- *
87
- * 2. **Idempotent persistence.** Every message write is keyed
88
- * `INSTANCE:ROLE:POSITION` and the append mutation dedupes on it, so a
89
- * replayed persist is a no-op — the thread never duplicates.
90
- *
91
- * Loop control derives ONLY from persisted step outputs (never fresh
92
- * `Date.now()`/`Math.random()` at the top level), so replays walk the same
93
- * step-name sequence.
94
- * @experimental
95
- */
79
+ * The durable tool-loop. Correctness rests on two invariants:
80
+ *
81
+ * 1. **Deterministic step names.** Each LLM turn is `llm:turn:N` (`N` = the
82
+ * loop index, replay-stable) and each tool call is `tool:NAME:CALL_ID`
83
+ * (`CALL_ID` = the provider's stable id, itself replayed from the memoized LLM
84
+ * step). Native `step.do` memoization then guarantees a COMPLETED step is
85
+ * never re-run on replay — a resumed run cannot double-charge a card. A step
86
+ * that FAILS mid-body is retried at-least-once; the tool receives its step
87
+ * name as `idempotencyKey` to dedupe on.
88
+ *
89
+ * 2. **Idempotent persistence.** Every message write is keyed
90
+ * `INSTANCE:ROLE:POSITION` and the append mutation dedupes on it, so a
91
+ * replayed persist is a no-op — the thread never duplicates.
92
+ *
93
+ * Loop control derives ONLY from persisted step outputs (never fresh
94
+ * `Date.now()`/`Math.random()` at the top level), so replays walk the same
95
+ * step-name sequence.
96
+ * @experimental
97
+ */
96
98
  declare const runAgentLoop: (options: AgentLoopOptions) => Promise<AgentRunResult>;
97
99
  /**
98
- * Input the model provides to a minted `searchMemory` tool.
99
- * @experimental
100
- */
100
+ * Input the model provides to a minted `searchMemory` tool.
101
+ * @experimental
102
+ */
101
103
  interface AgentMemorySearchInput {
102
104
  /** The natural-language query. */
103
105
  query: string;
@@ -105,17 +107,17 @@ interface AgentMemorySearchInput {
105
107
  topK?: number;
106
108
  }
107
109
  /**
108
- * Input the model provides to a minted `readMemory` tool.
109
- * @experimental
110
- */
110
+ * Input the model provides to a minted `readMemory` tool.
111
+ * @experimental
112
+ */
111
113
  interface AgentMemoryReadInput {
112
114
  /** The chunk/document id from a `searchMemory` hit. */
113
115
  id: string;
114
116
  }
115
117
  /**
116
- * One ranked hit in a {@link AgentMemorySearchResult}.
117
- * @experimental
118
- */
118
+ * One ranked hit in a {@link AgentMemorySearchResult}.
119
+ * @experimental
120
+ */
119
121
  interface AgentMemorySearchHit {
120
122
  id: string;
121
123
  score: number;
@@ -124,81 +126,81 @@ interface AgentMemorySearchHit {
124
126
  sourceId: string;
125
127
  }
126
128
  /**
127
- * The compact shape a minted `searchMemory` tool returns to the model: ranked
128
- * hits plus deduped source refs, with the giant joined `.context` string
129
- * DROPPED — the model reads snippets and decides what (if anything) to pull with
130
- * `readMemory`, which is the whole point of agentic (vs inject) retrieval.
131
- * @experimental
132
- */
129
+ * The compact shape a minted `searchMemory` tool returns to the model: ranked
130
+ * hits plus deduped source refs, with the giant joined `.context` string
131
+ * DROPPED — the model reads snippets and decides what (if anything) to pull with
132
+ * `readMemory`, which is the whole point of agentic (vs inject) retrieval.
133
+ * @experimental
134
+ */
133
135
  interface AgentMemorySearchResult {
134
136
  results: AgentMemorySearchHit[];
135
137
  sources: ReadonlyArray<unknown>;
136
138
  }
137
139
  /**
138
- * Project a `@lunora/ai/rag` `RetrieveResult` into the compact
139
- * {@link AgentMemorySearchResult} a minted `searchMemory` tool returns. Defensive
140
- * against a source action that returns a differently-shaped value (the dispatch
141
- * boundary is untyped): a missing `chunks`/`sources` degrades to empty.
142
- * @experimental
143
- */
140
+ * Project a `@lunora/ai/rag` `RetrieveResult` into the compact
141
+ * {@link AgentMemorySearchResult} a minted `searchMemory` tool returns. Defensive
142
+ * against a source action that returns a differently-shaped value (the dispatch
143
+ * boundary is untyped): a missing `chunks`/`sources` degrades to empty.
144
+ * @experimental
145
+ */
144
146
  declare const toSearchResults: (retrieved: unknown, snippetChars: number) => AgentMemorySearchResult;
145
147
  /**
146
- * Mint the model-facing tools for every `mode: "agentic"` memory source — the
147
- * agent's own `memory` (keyed `"default"` → `searchMemory`/`readMemory`) and
148
- * each skill's `knowledge` (keyed by the skill name → `search_KEY`/`read_KEY`).
149
- * An `"inject"`-mode source contributes NO tool (it stays on the auto-injection
150
- * path). The returned map is folded into the agent's flat tool namespace by
151
- * `defineAgent`, where a collision with a real tool throws.
152
- *
153
- * Walks the same two source origins as `collectMemorySources` so the two stay in
154
- * lockstep; the split is deliberate — inject sources feed retrieval, agentic
155
- * sources feed tools, and no source is ever on both paths.
156
- * @experimental
157
- */
148
+ * Mint the model-facing tools for every `mode: "agentic"` memory source — the
149
+ * agent's own `memory` (keyed `"default"` → `searchMemory`/`readMemory`) and
150
+ * each skill's `knowledge` (keyed by the skill name → `search_KEY`/`read_KEY`).
151
+ * An `"inject"`-mode source contributes NO tool (it stays on the auto-injection
152
+ * path). The returned map is folded into the agent's flat tool namespace by
153
+ * `defineAgent`, where a collision with a real tool throws.
154
+ *
155
+ * Walks the same two source origins as `collectMemorySources` so the two stay in
156
+ * lockstep; the split is deliberate — inject sources feed retrieval, agentic
157
+ * sources feed tools, and no source is ever on both paths.
158
+ * @experimental
159
+ */
158
160
  declare const collectAgenticMemoryTools: (config: AgentConfig, skills: ReadonlyArray<SkillDefinition>) => Record<string, AnyAgentTool>;
159
161
  /**
160
- * Adapt a declared agent into a tool the parent's model can call: `execute`
161
- * starts a CHILD run on the child agent's Workflow binding, waits for it to
162
- * finish, and returns its final answer — so a supervisor agent can delegate to
163
- * specialists.
164
- *
165
- * Replay-safety: the whole `execute` runs inside the loop's `tool:NAME:CALL_ID`
166
- * durable step, so a completed sub-run is memoized and never re-run. The child
167
- * `threadKey` and Workflow instance id both DERIVE from the parent's
168
- * (replay-stable) `threadKey` + `toolCallId`, so a retried step reuses the same
169
- * child run rather than forking a new one (idempotent create-or-get). No
170
- * `Date.now()`/`Math.random()`.
171
- *
172
- * The child's completion is observed by POLLING `instance.status()` (Cloudflare
173
- * Workflows has no in-step await-instance primitive), and the answer is read
174
- * back from the child's persisted thread — the single source of truth — via the
175
- * shared `agents:agentMessages` runtime function.
176
- * @experimental
177
- */
162
+ * Adapt a declared agent into a tool the parent's model can call: `execute`
163
+ * starts a CHILD run on the child agent's Workflow binding, waits for it to
164
+ * finish, and returns its final answer — so a supervisor agent can delegate to
165
+ * specialists.
166
+ *
167
+ * Replay-safety: the whole `execute` runs inside the loop's `tool:NAME:CALL_ID`
168
+ * durable step, so a completed sub-run is memoized and never re-run. The child
169
+ * `threadKey` and Workflow instance id both DERIVE from the parent's
170
+ * (replay-stable) `threadKey` + `toolCallId`, so a retried step reuses the same
171
+ * child run rather than forking a new one (idempotent create-or-get). No
172
+ * `Date.now()`/`Math.random()`.
173
+ *
174
+ * The child's completion is observed by POLLING `instance.status()` (Cloudflare
175
+ * Workflows has no in-step await-instance primitive), and the answer is read
176
+ * back from the child's persisted thread — the single source of truth — via the
177
+ * shared `agents:agentMessages` runtime function.
178
+ * @experimental
179
+ */
178
180
  declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<AgentSubToolInput, string>;
179
181
  /**
180
- * One step of a tool-composition script — call `tool` with `input`, bind the result to `id`.
181
- * @experimental
182
- */
182
+ * One step of a tool-composition script — call `tool` with `input`, bind the result to `id`.
183
+ * @experimental
184
+ */
183
185
  interface ToolScriptStep {
184
186
  /** A stable name later steps reference the output by. */
185
187
  id: string;
186
- /** The tool's input; values may embed `{ "$from": "&lt;stepId>", "$path": "a.b" }` refs. */
188
+ /** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
187
189
  input?: Record<string, unknown>;
188
190
  /** The tool to call — one of the tools handed to {@link codeTool}. */
189
191
  tool: string;
190
192
  }
191
193
  /**
192
- * The model-provided input to a {@link codeTool} call.
193
- * @experimental
194
- */
194
+ * The model-provided input to a {@link codeTool} call.
195
+ * @experimental
196
+ */
195
197
  interface ToolScript {
196
198
  steps: ToolScriptStep[];
197
199
  }
198
200
  /**
199
- * The result of running a {@link ToolScript}: each step's output plus the last one.
200
- * @experimental
201
- */
201
+ * The result of running a {@link ToolScript}: each step's output plus the last one.
202
+ * @experimental
203
+ */
202
204
  interface ToolScriptResult {
203
205
  final: unknown;
204
206
  results: ReadonlyArray<{
@@ -207,121 +209,128 @@ interface ToolScriptResult {
207
209
  }>;
208
210
  }
209
211
  /**
210
- * Author-supplied config for {@link codeTool}.
211
- * @experimental
212
- */
212
+ * Author-supplied config for {@link codeTool}.
213
+ * @experimental
214
+ */
213
215
  interface CodeToolOptions {
214
216
  /** Override the model-facing description (the default lists the available tools). */
215
217
  description?: string;
216
218
  /** Max steps per script (default 16). */
217
219
  maxSteps?: number;
218
220
  /**
219
- * Gate a whole script behind a human approval. Default: unattended. Note the
220
- * COMPOSED tools cannot carry their own approval gate — `codeTool` rejects any
221
- * tool with a `needsApproval`, because a code-mode script runs its steps in one
222
- * shot and can't pause mid-script to hibernate for HITL. Gate the whole script
223
- * here instead. Evaluated from replay-stable input, so keep it deterministic.
224
- */
221
+ * Gate a whole script behind a human approval. Default: unattended. Note the
222
+ * COMPOSED tools cannot carry their own approval gate — `codeTool` rejects any
223
+ * tool with a `needsApproval`, because a code-mode script runs its steps in one
224
+ * shot and can't pause mid-script to hibernate for HITL. Gate the whole script
225
+ * here instead. Evaluated from replay-stable input, so keep it deterministic.
226
+ */
225
227
  needsApproval?: ((input: ToolScript) => boolean) | boolean;
226
228
  }
227
229
  /**
228
- * Resolve `{ "$from": "&lt;stepId>", "$path"?: "a.b" }` references in a step's input
229
- * against earlier step results, recursing through nested objects and arrays. An
230
- * unknown `$from` throws — a forward/typo reference is a hard error, not a silent
231
- * `undefined`. Pure and deterministic (no I/O), so it's unit-testable alone.
232
- */
233
-
234
- /**
235
- * A "code mode" tool: instead of the model calling one tool per turn, it writes a
236
- * SCRIPT that composes several of the tools you hand `codeTool` — chaining a
237
- * later call's input to an earlier call's output — and the whole thing runs in a
238
- * single turn. This is a SAFE interpreted data-flow between whitelisted tools
239
- * (no `eval`, no isolate), so it runs natively in workerd; arbitrary-code
240
- * execution (the Cloudflare Worker Loader path) is a separate future mode.
241
- *
242
- * Each composed tool dispatches through the same durable context a normal call
243
- * gets (inheriting RLS), with a per-step idempotency key. A code-mode script runs
244
- * its steps in one shot and CANNOT pause mid-script for a human approval, so
245
- * `codeTool` REJECTS at construction any tool carrying a `needsApproval` gate —
246
- * keep approval-gated tools as normal top-level tools. Gate the whole script via
247
- * `opts.needsApproval` instead.
248
- *
249
- * ```ts
250
- * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
251
- *
252
- * export const analyst = defineAgent({
253
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
254
- * tools: {
255
- * run: codeTool({
256
- * findUser: functionTool("users:byEmail", { description: "Look up a user by email.", inputSchema }),
257
- * recentOrders: functionTool("orders:recent", { description: "List a user's recent orders.", inputSchema }),
258
- * }),
259
- * },
260
- * });
261
- * // The model can now, in one turn, `findUser` then feed `{ "$from": "u", "$path": "id" }` into `recentOrders`.
262
- * ```
263
- * @experimental
264
- */
230
+ * A "code mode" tool: instead of the model calling one tool per turn, it writes a
231
+ * SCRIPT that composes several of the tools you hand `codeTool` — chaining a
232
+ * later call's input to an earlier call's output — and the whole thing runs in a
233
+ * single turn. This is a SAFE interpreted data-flow between whitelisted tools
234
+ * (no `eval`, no isolate), so it runs natively in workerd; for arbitrary code
235
+ * in a Worker Loader isolate, see `jsCodeTool`.
236
+ *
237
+ * Each composed tool dispatches through the same durable context a normal call
238
+ * gets (inheriting RLS), with a per-step idempotency key. A code-mode script runs
239
+ * its steps in one shot and CANNOT pause mid-script for a human approval, so
240
+ * `codeTool` REJECTS at construction any tool carrying a `needsApproval` gate —
241
+ * keep approval-gated tools as normal top-level tools. Gate the whole script via
242
+ * `opts.needsApproval` instead.
243
+ *
244
+ * STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
245
+ * step runs inside its own durable `step.do`, so the workflow host serializes
246
+ * the returned value before the next step (or the tool result) ever sees it. A
247
+ * `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
248
+ * `null` or a dropped key, and a `bigint` throws outright. That applies to the
249
+ * value a later step reads through `{ "$from": … }` just as much as to the
250
+ * returned `results` — the hand-off is durable state, not an in-memory one. A
251
+ * composed tool that wants to pass a rich value should return its JSON form
252
+ * (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
253
+ *
254
+ * ```ts
255
+ * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
256
+ *
257
+ * export const analyst = defineAgent({
258
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
259
+ * tools: {
260
+ * run: codeTool({
261
+ * findUser: functionTool("users:byEmail", { description: "Look up a user by email.", inputSchema }),
262
+ * recentOrders: functionTool("orders:recent", { description: "List a user's recent orders.", inputSchema }),
263
+ * }),
264
+ * },
265
+ * });
266
+ * // The model can now, in one turn, `findUser` then feed `{ "$from": "u", "$path": "id" }` into `recentOrders`.
267
+ * ```
268
+ * @experimental
269
+ */
265
270
  declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeToolOptions) => AgentToolDefinition<ToolScript, ToolScriptResult>;
266
271
  /**
267
- * Build the `ctx.agents` producer surface from the codegen-emitted spec list
268
- * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
269
- * declared agent resolves its `AGENT_*` Workflow binding off `env` lazily, so
270
- * a missing binding only errors when that agent is actually started.
271
- *
272
- * `cancel` also needs to write the thread's status, so it dispatches the agent
273
- * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
274
- * and the env-backed `createDispatchRunner` (the same runner the workflow body
275
- * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
276
- * inject a `dispatch` double.
277
- * @experimental
278
- */
279
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, dispatch?: AgentRunFunction) => Record<string, AgentHandle>;
280
- /**
281
- * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
282
- * (each LLM turn and each tool call a named durable step; thread messages
283
- * persisted idempotently in DO SQLite), invoked from mutations/actions via
284
- * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
285
- * `agents:agentMessages` query.
286
- *
287
- * ```ts
288
- * // lunora/agents.ts
289
- * import { defineAgent, defineAgentTool } from "@lunora/agent";
290
- *
291
- * export const support = defineAgent({
292
- * instructions: "You are a helpful support agent.",
293
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
294
- * tools: {
295
- * getWeather: defineAgentTool({
296
- * description: "Look up the current weather for a city.",
297
- * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
298
- * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
299
- * }),
300
- * },
301
- * });
302
- * ```
303
- *
304
- * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
305
- * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
306
- * @experimental
307
- */
272
+ * Build the `ctx.agents` producer surface from the codegen-emitted spec list
273
+ * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
274
+ * declared agent resolves by its export key (the generated class name) off the
275
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
276
+ * lazily, so a missing agent only errors when it is actually started.
277
+ *
278
+ * `cancel` also needs to write the thread's status, so it dispatches the agent
279
+ * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
280
+ * and the env-backed `createDispatchRunner` (the same runner the workflow body
281
+ * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
282
+ * inject a `dispatch` double.
283
+ * @experimental
284
+ */
285
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
+ dispatch?: AgentRunFunction;
287
+ exports?: unknown;
288
+ }) => Record<string, AgentHandle>;
289
+ /**
290
+ * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
291
+ * (each LLM turn and each tool call a named durable step; thread messages
292
+ * persisted idempotently in DO SQLite), invoked from mutations/actions via
293
+ * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
294
+ * `agents:agentMessages` query.
295
+ *
296
+ * ```ts
297
+ * // lunora/agents.ts
298
+ * import { defineAgent, defineAgentTool } from "@lunora/agent";
299
+ *
300
+ * export const support = defineAgent({
301
+ * instructions: "You are a helpful support agent.",
302
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
303
+ * tools: {
304
+ * getWeather: defineAgentTool({
305
+ * description: "Look up the current weather for a city.",
306
+ * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
307
+ * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
308
+ * }),
309
+ * },
310
+ * });
311
+ * ```
312
+ *
313
+ * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
314
+ * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
315
+ * @experimental
316
+ */
308
317
  declare const defineAgent: (config: AgentConfig) => AgentDefinition;
309
318
  /**
310
- * Runtime brand check for a {@link AgentDefinition}.
311
- * @experimental
312
- */
319
+ * Runtime brand check for a {@link AgentDefinition}.
320
+ * @experimental
321
+ */
313
322
  declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
314
323
  /**
315
- * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
316
- * the loop's durable step (with an `AgentToolContext`) rather than inside the
317
- * model call.
318
- * @experimental
319
- */
324
+ * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
325
+ * the loop's durable step (with an `AgentToolContext`) rather than inside the
326
+ * model call.
327
+ * @experimental
328
+ */
320
329
  declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
321
330
  /**
322
- * Author-supplied config for {@link functionTool}.
323
- * @experimental
324
- */
331
+ * Author-supplied config for {@link functionTool}.
332
+ * @experimental
333
+ */
325
334
  interface FunctionToolOptions<Input> {
326
335
  /** What the tool does — shown to the model (the model decides from it). */
327
336
  description: string;
@@ -329,106 +338,106 @@ interface FunctionToolOptions<Input> {
329
338
  inputSchema: FlexibleSchema<Input>;
330
339
  }
331
340
  /**
332
- * Expose any Lunora query/mutation/action as an agent tool. The returned
333
- * definition's `execute` dispatches the referenced function through the loop's
334
- * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
335
- * per tool, and the call runs inside the loop's named durable step exactly like
336
- * any other tool.
337
- *
338
- * ```ts
339
- * import { functionTool } from "@lunora/agent";
340
- * import { api } from "./_generated/api";
341
- *
342
- * export const support = defineAgent({
343
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
344
- * tools: {
345
- * lookupOrder: functionTool(api.orders.byId, {
346
- * description: "Look up an order by its id.",
347
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
348
- * }),
349
- * },
350
- * });
351
- * ```
352
- *
353
- * The function reference may be a typed `api.*` reference or a `"module:name"`
354
- * path. The model-provided input is passed verbatim as the function's args, so
355
- * `inputSchema` should mirror the referenced function's argument validator.
356
- * @experimental
357
- */
341
+ * Expose any Lunora query/mutation/action as an agent tool. The returned
342
+ * definition's `execute` dispatches the referenced function through the loop's
343
+ * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
344
+ * per tool, and the call runs inside the loop's named durable step exactly like
345
+ * any other tool.
346
+ *
347
+ * ```ts
348
+ * import { functionTool } from "@lunora/agent";
349
+ * import { api } from "./_generated/api";
350
+ *
351
+ * export const support = defineAgent({
352
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
353
+ * tools: {
354
+ * lookupOrder: functionTool(api.orders.byId, {
355
+ * description: "Look up an order by its id.",
356
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
357
+ * }),
358
+ * },
359
+ * });
360
+ * ```
361
+ *
362
+ * The function reference may be a typed `api.*` reference or a `"module:name"`
363
+ * path. The model-provided input is passed as the function's args, so
364
+ * `inputSchema` should mirror the referenced function's argument validator —
365
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
366
+ * input (so out-of-schema model input can never override it). A function
367
+ * that wants to dedupe a side-effecting call across an at-least-once step
368
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
369
+ * and checks it; a function that ignores it is unaffected — an args field
370
+ * the function's own validator doesn't declare is dropped, not rejected.
371
+ * @experimental
372
+ */
358
373
  declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
359
374
  /**
360
- * Resolve the configured model against the Worker env (see `AgentModelInput`).
361
- * @experimental
362
- */
375
+ * Resolve the configured model against the Worker env (see `AgentModelInput`).
376
+ * @experimental
377
+ */
363
378
  declare const resolveAgentModel: (model: AgentModelInput, env: Record<string, unknown>) => LanguageModel;
364
379
  /**
365
- * Build the production LLM-turn seam over AI SDK `generateText`. The agent's
366
- * tools are exposed to the model schema-only (NO `execute`) — the model can
367
- * decide to call them, but execution happens back in the loop as named
368
- * durable steps, never inside the model call.
369
- *
370
- * The static generation settings (`temperature`, `maxOutputTokens`,
371
- * `toolChoice`, `output`, `telemetry`) come off the agent config; the per-turn
372
- * `activeTools` / `toolChoice` / `model` overrides (from `prepareStep`) arrive
373
- * on each call. When `output` is set the model runs with `Output.object` and
374
- * the parsed answer is returned alongside the text.
375
- * @experimental
376
- */
380
+ * Build the production LLM-turn seam over AI SDK `generateText`. The agent's
381
+ * tools are exposed to the model schema-only (NO `execute`) — the model can
382
+ * decide to call them, but execution happens back in the loop as named
383
+ * durable steps, never inside the model call.
384
+ *
385
+ * The static generation settings (`temperature`, `maxOutputTokens`,
386
+ * `toolChoice`, `output`, `telemetry`) come off the agent config; the per-turn
387
+ * `activeTools` / `toolChoice` / `model` overrides (from `prepareStep`) arrive
388
+ * on each call. When `output` is set the model runs with `Output.object` and
389
+ * the parsed answer is returned alongside the text.
390
+ * @experimental
391
+ */
377
392
  declare const createAgentGenerate: (agent: AgentDefinition, env: Record<string, unknown>) => AgentGenerate;
378
393
  /**
379
- * The streaming counterpart of {@link createAgentGenerate} over AI SDK
380
- * `streamText`. It tees each text delta to `onDelta` as the model produces it,
381
- * then resolves the SAME {@link AgentGenerate} result the non-streaming seam
382
- * returns — identical `{ text, toolCalls, usage, output }` — so the value the
383
- * durable `llm:turn:N` step memoizes (and persists) is byte-for-byte unchanged
384
- * whether the turn streamed or not.
385
- *
386
- * Deltas are live-only: the seam runs inside the turn's durable step, so a
387
- * workflow replay serves the memoized final value without re-invoking it — no
388
- * delta is ever re-emitted. The persisted assistant message stays the single
389
- * source of truth.
390
- * @experimental
391
- */
394
+ * The streaming counterpart of {@link createAgentGenerate} over AI SDK
395
+ * `streamText`. It tees each text delta to `onDelta` as the model produces it,
396
+ * then resolves the SAME {@link AgentGenerate} result the non-streaming seam
397
+ * returns — identical `{ text, toolCalls, usage, output }` — so the value the
398
+ * durable `llm:turn:N` step memoizes (and persists) is byte-for-byte unchanged
399
+ * whether the turn streamed or not.
400
+ *
401
+ * Deltas are live-only: the seam runs inside the turn's durable step, so a
402
+ * workflow replay serves the memoized final value without re-invoking it — no
403
+ * delta is ever re-emitted. The persisted assistant message stays the single
404
+ * source of truth.
405
+ * @experimental
406
+ */
392
407
  declare const createStreamGenerate: (agent: AgentDefinition, env: Record<string, unknown>) => AgentStreamGenerate;
393
408
  /**
394
- * Build the production run-end graph-extraction seam over AI SDK `generateText`
395
- * with an `Output.object` setting (the non-deprecated replacement for
396
- * `generateObject`, and the same structured-output path the turn seams use). It
397
- * resolves the (optionally cheaper) extraction model against the env, runs the
398
- * model over {@link GRAPH_EXTRACTION_SCHEMA}, and returns the parsed
399
- * `{ entities, relations }`. Wired by `compileAgentWorkflow` and called inside
400
- * the loop's memoized `memory:extract` step.
401
- * @experimental
402
- */
409
+ * Build the production run-end graph-extraction seam over AI SDK `generateText`
410
+ * with an `Output.object` setting (the non-deprecated replacement for
411
+ * `generateObject`, and the same structured-output path the turn seams use). It
412
+ * resolves the (optionally cheaper) extraction model against the env, runs the
413
+ * model over {@link GRAPH_EXTRACTION_SCHEMA}, and returns the parsed
414
+ * `{ entities, relations }`. Wired by `compileAgentWorkflow` and called inside
415
+ * the loop's memoized `memory:extract` step.
416
+ * @experimental
417
+ */
403
418
  declare const createGraphExtract: () => AgentGraphExtract;
404
419
  /**
405
- * Build the production run-end episode-extraction seam over AI SDK `generateText`.
406
- * Unlike the graph extractor this needs no structured schema — an episode is a
407
- * single natural-language summary — so it returns the trimmed model text. Wired
408
- * by `compileAgentWorkflow` and called inside the loop's memoized
409
- * `memory:episode` step.
410
- * @experimental
411
- */
420
+ * Build the production run-end episode-extraction seam over AI SDK `generateText`.
421
+ * Unlike the graph extractor this needs no structured schema — an episode is a
422
+ * single natural-language summary — so it returns the trimmed model text. Wired
423
+ * by `compileAgentWorkflow` and called inside the loop's memoized
424
+ * `memory:episode` step.
425
+ * @experimental
426
+ */
412
427
  declare const createEpisodeExtract: () => AgentEpisodeExtract;
413
428
  /**
414
- * Build the production history-compaction seam over AI SDK `generateText`: it
415
- * summarizes the older conversation messages under {@link COMPACTION_SYSTEM} and
416
- * returns the brief. Wired by `compileAgentWorkflow` and called inside the loop's
417
- * memoized `llm:turn:N` step so the summarization is replay-safe.
418
- */
419
- /**
420
- * One text/image/… content part of an MCP `CallToolResult`.
421
- * @experimental
422
- */
429
+ * One text/image/… content part of an MCP `CallToolResult`.
430
+ * @experimental
431
+ */
423
432
  interface McpContentPart {
424
433
  [key: string]: unknown;
425
434
  text?: string;
426
435
  type: string;
427
436
  }
428
437
  /**
429
- * The result of an MCP `tools/call` — the structural subset the adapter reads.
430
- * @experimental
431
- */
438
+ * The result of an MCP `tools/call` — the structural subset the adapter reads.
439
+ * @experimental
440
+ */
432
441
  interface McpCallResult {
433
442
  [key: string]: unknown;
434
443
  content?: ReadonlyArray<McpContentPart>;
@@ -436,9 +445,9 @@ interface McpCallResult {
436
445
  structuredContent?: unknown;
437
446
  }
438
447
  /**
439
- * One entry of an MCP `tools/list` — the structural subset the adapter reads.
440
- * @experimental
441
- */
448
+ * One entry of an MCP `tools/list` — the structural subset the adapter reads.
449
+ * @experimental
450
+ */
442
451
  interface McpToolInfo {
443
452
  description?: string;
444
453
  inputSchema: {
@@ -450,11 +459,11 @@ interface McpToolInfo {
450
459
  name: string;
451
460
  }
452
461
  /**
453
- * Structural subset of `@modelcontextprotocol/sdk`'s `Client` the adapter uses.
454
- * Declaring it locally lets tests inject a mock without the real SDK (and its
455
- * transport) and keeps the heavy dependency behind a lazy dynamic import.
456
- * @experimental
457
- */
462
+ * Structural subset of `@modelcontextprotocol/sdk`'s `Client` the adapter uses.
463
+ * Declaring it locally lets tests inject a mock without the real SDK (and its
464
+ * transport) and keeps the heavy dependency behind a lazy dynamic import.
465
+ * @experimental
466
+ */
458
467
  interface McpClientLike {
459
468
  callTool: (params: {
460
469
  arguments?: Record<string, unknown>;
@@ -467,23 +476,34 @@ interface McpClientLike {
467
476
  }>;
468
477
  }
469
478
  /**
470
- * Options for {@link mcpTools}.
471
- * @experimental
472
- */
479
+ * Options for {@link mcpTools}.
480
+ * @experimental
481
+ */
473
482
  interface McpToolsOptions {
474
483
  /**
475
- * A pre-built (already-connected) MCP client. Takes precedence over `url` —
476
- * the seam tests inject, and the escape hatch for a custom transport.
477
- */
484
+ * A pre-built (already-connected) MCP client. Takes precedence over `url` —
485
+ * the seam tests inject, and the escape hatch for a custom transport.
486
+ */
478
487
  client?: McpClientLike;
479
488
  /**
480
- * A stdio command. NOT supported in the Workers runtime (stdio transports
481
- * cannot run in workerd) — passing it throws unless a `client` is injected.
482
- * Present so the intent is explicit rather than silently unsupported.
483
- */
489
+ * A stdio command. NOT supported in the Workers runtime (stdio transports
490
+ * cannot run in workerd) — passing it throws unless a `client` is injected.
491
+ * Present so the intent is explicit rather than silently unsupported.
492
+ */
484
493
  command?: string;
485
494
  /** Identify this client to the server on connect. Default `"lunora-agent"`. */
486
495
  name?: string;
496
+ /**
497
+ * Gate an adapted tool's call behind a human approval. Defaults to
498
+ * **unattended** (no gate) — matching today's behavior. An MCP tool's
499
+ * result feeds back into the model's context (`adaptMcpResult`), so a
500
+ * hostile downstream server can pair indirect prompt injection with an
501
+ * unattended mutating tool call; pass a boolean to gate every adapted
502
+ * tool the same way, or a predicate `(toolName, input) => boolean` to
503
+ * gate per tool (evaluated from replay-stable input, so keep it
504
+ * deterministic).
505
+ */
506
+ needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
487
507
  /** Only adapt these tool names (default: every tool the server lists). */
488
508
  only?: ReadonlyArray<string>;
489
509
  /** Prefix added to each adapted tool's key (disambiguate multiple servers). */
@@ -496,43 +516,46 @@ interface McpToolsOptions {
496
516
  version?: string;
497
517
  }
498
518
  /**
499
- * Reduce an MCP tool result to the value persisted as the tool message. A
500
- * server's `structuredContent` is returned as-is; otherwise the text parts are
501
- * joined. An `isError` result is returned as an error STRING (not thrown) so
502
- * the next LLM turn can recover, consistent with the loop's unknown-tool path.
503
- * @experimental
504
- */
519
+ * Reduce an MCP tool result to the value persisted as the tool message. A
520
+ * server's `structuredContent` is returned as-is; otherwise the text parts are
521
+ * joined. An `isError` result is returned as an error STRING (not thrown) so
522
+ * the next LLM turn can recover, consistent with the loop's unknown-tool path.
523
+ * @experimental
524
+ */
505
525
  declare const adaptMcpResult: (result: McpCallResult) => unknown;
506
526
  /**
507
- * Connect to an external MCP server, list its tools, and adapt each into an
508
- * {@link AgentToolDefinition} — a record you spread into an agent's `tools`.
509
- * Each adapted tool's `execute` calls the MCP tool through the client, and runs
510
- * inside the loop's named durable step like any other tool (so a completed call
511
- * is never re-run on a workflow replay).
512
- *
513
- * ```ts
514
- * export const support = defineAgent({
515
- * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
516
- * tools: {
517
- * ...(await mcpTools({ url: "https://mcp.example.com/mcp" })),
518
- * },
519
- * });
520
- * ```
521
- *
522
- * The connection is made at build time (listing tools needs it), then reused by
523
- * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
524
- * does not) — pass `url`, or inject an already-connected `client` for a custom
525
- * transport (also the test seam).
526
- * @experimental
527
- */
527
+ * Connect to an external MCP server, list its tools, and adapt each into an
528
+ * {@link AgentToolDefinition} — a record you spread into an agent's `tools`.
529
+ * Each adapted tool's `execute` calls the MCP tool through the client, and runs
530
+ * inside the loop's named durable step like any other tool (so a completed call
531
+ * is never re-run on a workflow replay).
532
+ *
533
+ * ```ts
534
+ * export const support = defineAgent({
535
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
536
+ * tools: {
537
+ * ...(await mcpTools({ url: "https://mcp.example.com/mcp" })),
538
+ * },
539
+ * });
540
+ * ```
541
+ *
542
+ * The connection is made at build time (listing tools needs it), then reused by
543
+ * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
544
+ * does not) — pass `url`, or inject an already-connected `client` for a custom
545
+ * transport (also the test seam).
546
+ *
547
+ * Every adapted tool runs UNATTENDED by default (no approval gate) — pass
548
+ * `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
549
+ * @experimental
550
+ */
528
551
  declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
529
552
  /**
530
- * Assemble the AI SDK conversation for one LLM turn: instructions, then the
531
- * retrieved memory context (when any), then the persisted thread history with
532
- * tool calls/results correlated the way providers expect (assistant tool-call
533
- * parts answered by tool-result parts sharing the `toolCallId`).
534
- * @experimental
535
- */
553
+ * Assemble the AI SDK conversation for one LLM turn: instructions, then the
554
+ * retrieved memory context (when any), then the persisted thread history with
555
+ * tool calls/results correlated the way providers expect (assistant tool-call
556
+ * parts answered by tool-result parts sharing the `toolCallId`).
557
+ * @experimental
558
+ */
536
559
  declare const buildModelMessages: (options: {
537
560
  history: ReadonlyArray<AgentMessageRow>;
538
561
  instructions?: string;
@@ -540,79 +563,79 @@ declare const buildModelMessages: (options: {
540
563
  summary?: string;
541
564
  }) => ModelMessage[];
542
565
  /**
543
- * The namespace the agent runtime functions register under. Codegen
544
- * auto-registers `agentComponent().functions` here whenever `lunora/agents.ts`
545
- * declares an agent, so the loop's dispatch paths below hold by construction.
546
- * @experimental
547
- */
566
+ * The namespace the agent runtime functions register under. Codegen
567
+ * auto-registers `agentComponent().functions` here whenever `lunora/agents.ts`
568
+ * declares an agent, so the loop's dispatch paths below hold by construction.
569
+ * @experimental
570
+ */
548
571
  declare const AGENT_MODULE = "agents";
549
572
  /**
550
- * The namespace + name the batteries-included sandbox dispatcher registers
551
- * under. Codegen auto-registers `sandboxComponent().invoke` here whenever
552
- * `lunora/` imports a sandbox tool (`browserTool`/`containerTool`), so the
553
- * tools' `execute` can dispatch to it through the loop's `run` seam.
554
- * @experimental
555
- */
573
+ * The namespace + name the batteries-included sandbox dispatcher registers
574
+ * under. Codegen auto-registers `sandboxComponent().invoke` here whenever
575
+ * `lunora/` imports a sandbox tool (`browserTool`/`containerTool`), so the
576
+ * tools' `execute` can dispatch to it through the loop's `run` seam.
577
+ * @experimental
578
+ */
556
579
  declare const SANDBOX_MODULE = "sandbox";
557
580
  /**
558
- * The dispatch path of the sandbox runtime action (an internal action).
559
- * @experimental
560
- */
581
+ * The dispatch path of the sandbox runtime action (an internal action).
582
+ * @experimental
583
+ */
561
584
  declare const SANDBOX_INVOKE_PATH: "sandbox:invoke";
562
585
  /**
563
- * Default dispatch paths of the agent runtime functions.
564
- * @experimental
565
- */
586
+ * Default dispatch paths of the agent runtime functions.
587
+ * @experimental
588
+ */
566
589
  declare const DEFAULT_AGENT_FUNCTION_PATHS: AgentFunctionPaths;
567
590
  /**
568
- * Mint a dispatchable function reference from a path (or pass one through).
569
- * @experimental
570
- */
591
+ * Mint a dispatchable function reference from a path (or pass one through).
592
+ * @experimental
593
+ */
571
594
  declare const toFunctionReference: (source: AgentFunctionReference | string) => AgentFunctionReference;
572
595
  /**
573
- * Declare a reusable skill: a bundle of expertise — an instruction fragment,
574
- * tools, and retrieval `knowledge` — an agent composes in via
575
- * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
576
- * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
577
- * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
578
- * retrieval verbatim.
579
- *
580
- * ```ts
581
- * import { defineSkill, functionTool } from "@lunora/agent";
582
- *
583
- * export const billing = defineSkill({
584
- * name: "billing",
585
- * instructions: "When asked about invoices, cite the invoice id.",
586
- * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
587
- * tools: {
588
- * lookupInvoice: functionTool(api.billing.invoiceById, {
589
- * description: "Look up an invoice by id.",
590
- * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
591
- * }),
592
- * },
593
- * });
594
- * ```
595
- *
596
- * The merge into the agent's flat namespace (tool-name collisions, instruction
597
- * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
598
- * only validates its own `name`; tool-name validation is deferred to the merge,
599
- * which owns the flat model-facing namespace.
600
- * @experimental
601
- */
596
+ * Declare a reusable skill: a bundle of expertise — an instruction fragment,
597
+ * tools, and retrieval `knowledge` — an agent composes in via
598
+ * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
599
+ * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
600
+ * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
601
+ * retrieval verbatim.
602
+ *
603
+ * ```ts
604
+ * import { defineSkill, functionTool } from "@lunora/agent";
605
+ *
606
+ * export const billing = defineSkill({
607
+ * name: "billing",
608
+ * instructions: "When asked about invoices, cite the invoice id.",
609
+ * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
610
+ * tools: {
611
+ * lookupInvoice: functionTool(api.billing.invoiceById, {
612
+ * description: "Look up an invoice by id.",
613
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
614
+ * }),
615
+ * },
616
+ * });
617
+ * ```
618
+ *
619
+ * The merge into the agent's flat namespace (tool-name collisions, instruction
620
+ * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
621
+ * only validates its own `name`; tool-name validation is deferred to the merge,
622
+ * which owns the flat model-facing namespace.
623
+ * @experimental
624
+ */
602
625
  declare const defineSkill: (config: SkillConfig) => SkillDefinition;
603
626
  /**
604
- * Runtime brand check for a {@link SkillDefinition}.
605
- * @experimental
606
- */
627
+ * Runtime brand check for a {@link SkillDefinition}.
628
+ * @experimental
629
+ */
607
630
  declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
608
631
  /**
609
- * A control frame the server sends the client as a JSON text message (audio
610
- * rides separate binary frames). `ready` announces the negotiated codec on
611
- * connect; `user_transcript` carries the STT result; `assistant_delta` streams
612
- * the live LLM text; `assistant_done` is the final turn text; `interrupted`
613
- * acks a barge-in; `error` reports a non-fatal turn failure.
614
- * @experimental
615
- */
632
+ * A control frame the server sends the client as a JSON text message (audio
633
+ * rides separate binary frames). `ready` announces the negotiated codec on
634
+ * connect; `user_transcript` carries the STT result; `assistant_delta` streams
635
+ * the live LLM text; `assistant_done` is the final turn text; `interrupted`
636
+ * acks a barge-in; `error` reports a non-fatal turn failure.
637
+ * @experimental
638
+ */
616
639
  type VoiceServerFrame = {
617
640
  audioFormat: "mp3" | "wav";
618
641
  type: "ready";
@@ -632,9 +655,9 @@ type VoiceServerFrame = {
632
655
  type: "interrupted";
633
656
  };
634
657
  /**
635
- * A control frame the client sends the server (audio rides separate binary frames).
636
- * @experimental
637
- */
658
+ * A control frame the client sends the server (audio rides separate binary frames).
659
+ * @experimental
660
+ */
638
661
  type VoiceClientFrame = {
639
662
  text: string;
640
663
  type: "text";
@@ -644,34 +667,34 @@ type VoiceClientFrame = {
644
667
  type: "interrupt";
645
668
  };
646
669
  /**
647
- * A synthesized-audio source the TTS seam yields — normalized to bytes by {@link toByteIterable}.
648
- * @experimental
649
- */
670
+ * A synthesized-audio source the TTS seam yields — normalized to bytes by {@link toByteIterable}.
671
+ * @experimental
672
+ */
650
673
  type VoiceAudioSource = AsyncIterable<Uint8Array> | ReadableStream<Uint8Array> | Uint8Array;
651
674
  /**
652
- * Transcribe one buffered utterance (16kHz mono 16-bit PCM) to text.
653
- * @experimental
654
- */
675
+ * Transcribe one buffered utterance (16kHz mono 16-bit PCM) to text.
676
+ * @experimental
677
+ */
655
678
  type VoiceTranscribe = (pcm: Uint8Array) => Promise<string>;
656
679
  /**
657
- * Synthesize one sentence to an audio byte stream; honors `signal` for barge-in.
658
- * @experimental
659
- */
680
+ * Synthesize one sentence to an audio byte stream; honors `signal` for barge-in.
681
+ * @experimental
682
+ */
660
683
  type VoiceSynthesize = (text: string, signal: AbortSignal) => Promise<VoiceAudioSource>;
661
684
  /**
662
- * Send a JSON control frame to the client.
663
- * @experimental
664
- */
685
+ * Send a JSON control frame to the client.
686
+ * @experimental
687
+ */
665
688
  type VoiceSend = (frame: VoiceServerFrame) => void;
666
689
  /**
667
- * Send a binary audio frame to the client.
668
- * @experimental
669
- */
690
+ * Send a binary audio frame to the client.
691
+ * @experimental
692
+ */
670
693
  type VoiceSendAudio = (bytes: Uint8Array) => void;
671
694
  /**
672
- * The outcome of one voice turn.
673
- * @experimental
674
- */
695
+ * The outcome of one voice turn.
696
+ * @experimental
697
+ */
675
698
  interface VoiceTurnResult {
676
699
  /** The final assistant text (may be partial if `interrupted`). */
677
700
  assistantText: string;
@@ -681,12 +704,19 @@ interface VoiceTurnResult {
681
704
  userText: string;
682
705
  }
683
706
  /**
684
- * Options for one {@link runVoiceTurn}.
685
- * @experimental
686
- */
707
+ * Options for one {@link runVoiceTurn}.
708
+ * @experimental
709
+ */
687
710
  interface RunVoiceTurnOptions {
688
711
  /** The agent whose thread + models back this session. */
689
712
  agent: AgentDefinition;
713
+ /**
714
+ * History-compaction seam — the SAME one the durable loop uses. Voice and
715
+ * text turns share one thread, so an agent that declares `compaction` must
716
+ * get it here too; absent (or with no `compaction` config) the turn takes
717
+ * the byte-identical uncompacted path.
718
+ */
719
+ compact?: AgentCompact;
690
720
  /** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
691
721
  connectionId: string;
692
722
  /** The Worker env (resolves a dynamic `instructions` thunk). */
@@ -722,24 +752,21 @@ interface RunVoiceTurnOptions {
722
752
  /** Optional outbound-audio backpressure: awaited before each audio frame so a slow client can't balloon DO memory. Never throws. */
723
753
  waitForDrain?: () => Promise<void>;
724
754
  }
725
- /** Normalize a {@link VoiceAudioSource} to an async iterable of byte chunks. */
726
-
727
- /**
728
- * Run one conversational voice turn IN-DO: transcribe the utterance (or take the
729
- * typed text), persist the user turn onto the SHARED agent thread, stream the
730
- * assistant reply, and synthesize it sentence-by-sentence back to the client —
731
- * TTS overlapping generation, both cancellable by a barge-in `signal`.
732
- *
733
- * This is NOT the replay-durable Workflow tool-loop: a voice turn is
734
- * conversational only (no tools in v1) and not replay-safe. Persistence stays
735
- * idempotent by `voice:{connectionId}:{turn}:{role}` message keys so a resent
736
- * frame never duplicates a row; the thread tables are the same ones the durable
737
- * agent loop and `useAgentChat` read, so a voice session and a text session on
738
- * the same `threadKey` share one history.
739
- * @experimental
740
- */
755
+ /**
756
+ * Run one conversational voice turn IN-DO: transcribe the utterance (or take the
757
+ * typed text), persist the user turn onto the SHARED agent thread, stream the
758
+ * assistant reply, and synthesize it sentence-by-sentence back to the client —
759
+ * TTS overlapping generation, both cancellable by a barge-in `signal`.
760
+ *
761
+ * This is NOT the replay-durable Workflow tool-loop: a voice turn is
762
+ * conversational only (no tools in v1) and not replay-safe. Persistence stays
763
+ * idempotent by `voice:{connectionId}:{turn}:{role}` message keys so a resent
764
+ * frame never duplicates a row; the thread tables are the same ones the durable
765
+ * agent loop and `useAgentChat` read, so a voice session and a text session on
766
+ * the same `threadKey` share one history.
767
+ * @experimental
768
+ */
741
769
  declare const runVoiceTurn: (options: RunVoiceTurnOptions) => Promise<VoiceTurnResult>;
742
- /** Parse the JSON identity envelope forwarded on the `x-lunora-identity` upgrade header. */
743
770
  /** Structural subset of `DurableObjectState` the voice DO needs (typed locally for unit doubles). */
744
771
  interface VoiceSessionState {
745
772
  acceptWebSocket: (ws: WebSocket, tags?: string[]) => void;
@@ -747,21 +774,21 @@ interface VoiceSessionState {
747
774
  waitUntil?: (promise: Promise<unknown>) => void;
748
775
  }
749
776
  /**
750
- * A hibernatable-WebSocket Durable Object that runs an agent's real-time VOICE
751
- * session. One instance per `threadKey`: the client opens a WebSocket, streams
752
- * 16kHz mono PCM as binary frames, and marks utterance boundaries with a JSON
753
- * `{ type: "commit" }` control frame; the DO transcribes the utterance, streams
754
- * the agent's reply through the LLM, and synthesizes it back as MP3 binary
755
- * frames — all IN-DO. It SHARES the agent's `agent_threads`/`agent_messages`
756
- * tables through the same runtime dispatch seam the durable loop uses, so voice
757
- * and text turns interleave on one history.
758
- *
759
- * Codegen emits a thin subclass per voice-enabled agent (e.g.
760
- * `SupportVoiceDO extends VoiceSessionDO`, constructed with the agent
761
- * definition + its export name) bound under the agent's `VOICE_...` Durable
762
- * Object binding.
763
- * @experimental
764
- */
777
+ * A hibernatable-WebSocket Durable Object that runs an agent's real-time VOICE
778
+ * session. One instance per `threadKey`: the client opens a WebSocket, streams
779
+ * 16kHz mono PCM as binary frames, and marks utterance boundaries with a JSON
780
+ * `{ type: "commit" }` control frame; the DO transcribes the utterance, streams
781
+ * the agent's reply through the LLM, and synthesizes it back as MP3 binary
782
+ * frames — all IN-DO. It SHARES the agent's `agent_threads`/`agent_messages`
783
+ * tables through the same runtime dispatch seam the durable loop uses, so voice
784
+ * and text turns interleave on one history.
785
+ *
786
+ * Codegen emits a thin subclass per voice-enabled agent (e.g.
787
+ * `SupportVoiceDO extends VoiceSessionDO`, constructed with the agent
788
+ * definition + its export name) bound under the agent's `VOICE_...` Durable
789
+ * Object binding.
790
+ * @experimental
791
+ */
765
792
  declare class VoiceSessionDO {
766
793
  protected readonly agent: AgentDefinition;
767
794
  protected readonly ai: ReturnType<typeof createAi>;
@@ -771,6 +798,8 @@ declare class VoiceSessionDO {
771
798
  protected readonly streamGenerate: AgentStreamGenerate;
772
799
  protected readonly sttModel: string;
773
800
  protected readonly ttsModel: string;
801
+ /** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
802
+ private readonly maxSessionTurns;
774
803
  private readonly audioBuffers;
775
804
  private readonly bufferedBytes;
776
805
  private readonly controllers;
@@ -785,11 +814,11 @@ declare class VoiceSessionDO {
785
814
  /** Abort any in-flight turn + free the socket's buffers on error. Never throws. */
786
815
  webSocketError(ws: WebSocket): void;
787
816
  /**
788
- * The runtime dispatch seam reaching the shared agent thread functions. When
789
- * the socket carries a verified identity it is forwarded so the `agents:*`
790
- * thread writes are attributed to the caller (RLS / row ownership) rather
791
- * than the anonymous system dispatch.
792
- */
817
+ * The runtime dispatch seam reaching the shared agent thread functions. When
818
+ * the socket carries a verified identity it is forwarded so the `agents:*`
819
+ * thread writes are attributed to the caller (RLS / row ownership) rather
820
+ * than the anonymous system dispatch.
821
+ */
793
822
  protected resolveRun(userId?: string, claims?: Record<string, unknown>): AgentRunFunction;
794
823
  /** Production STT seam: WAV-wrap the utterance and run the batch transcription model. */
795
824
  protected transcribe(pcm: Uint8Array): Promise<string>;
@@ -809,40 +838,90 @@ declare class VoiceSessionDO {
809
838
  private synthesizeWithSignal;
810
839
  /** Abort an in-flight turn and free a socket's transient buffers. */
811
840
  private cleanupSocket;
841
+ /** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
842
+ private closeSocket;
812
843
  /** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
813
844
  private send;
814
845
  /** Send a binary audio frame, swallowing a closed-socket error. */
815
846
  private sendAudio;
816
847
  /**
817
- * Outbound backpressure: if the socket exposes `bufferedAmount`, yield in
818
- * short polls until the send buffer drains below the cap so a slow client
819
- * can't balloon DO memory. Bounded by {@link MAX_DRAIN_WAIT_MS} so a stuck
820
- * socket never blocks a turn forever, and never throws (a socket without
821
- * `bufferedAmount` resolves immediately).
822
- */
848
+ * Outbound backpressure: if the socket exposes `bufferedAmount`, yield in
849
+ * short polls until the send buffer drains below the cap so a slow client
850
+ * can't balloon DO memory. Bounded by {@link MAX_DRAIN_WAIT_MS} so a stuck
851
+ * socket never blocks a turn forever, and never throws (a socket without
852
+ * `bufferedAmount` resolves immediately).
853
+ */
823
854
  private waitForSocketDrain;
824
855
  }
825
856
  /**
826
- * Compile a `defineAgent` definition into the workflow the generated
827
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
828
- *
829
- * ```ts
830
- * import LunoraWorkflow from "@lunora/workflow/do";
831
- * import { compileAgentWorkflow } from "@lunora/agent";
832
- * import { support } from "../agents.js";
833
- *
834
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
835
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
836
- * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
837
- * }
838
- * }
839
- * ```
840
- *
841
- * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
842
- * (`run`); the loop supplies determinism (step naming + idempotent persists).
843
- * @experimental
844
- */
857
+ * Config for {@link webSearchTool}.
858
+ * @experimental
859
+ */
860
+ interface WebSearchToolOptions {
861
+ /** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
862
+ byokAlias?: string;
863
+ /** Overrides the description shown to the model. */
864
+ description?: string;
865
+ /**
866
+ * The AI Gateway that brokers and bills the search. Defaults to
867
+ * `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
868
+ */
869
+ gatewayId?: string;
870
+ /** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
871
+ limit?: number;
872
+ /** Defaults to the Web Search API's own default (`"ceramic"`). */
873
+ provider?: AiWebSearchProvider;
874
+ }
875
+ /**
876
+ * What the model passes.
877
+ * @experimental
878
+ */
879
+ interface WebSearchToolInput {
880
+ query: string;
881
+ }
882
+ /**
883
+ * A batteries-included agent tool over the Cloudflare Web Search API (beta,
884
+ * `ctx.ai.websearch`), so an agent can ground an answer in live results.
885
+ * A search bills a provider key stored on the gateway (`byokAlias`, else the
886
+ * `default` alias) when there is one, otherwise AI Gateway credits; every
887
+ * provider runs under Zero Data Retention.
888
+ *
889
+ * It calls the `AI` binding straight from the tool's durable step: a search
890
+ * is a read, so the at-least-once step retry repeats nothing but a query, and
891
+ * there is no dispatcher action to register.
892
+ *
893
+ * ```ts
894
+ * import { defineAgent, webSearchTool } from "@lunora/agent";
895
+ *
896
+ * export const researcher = defineAgent({
897
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
898
+ * tools: { search: webSearchTool({ provider: "exa" }) },
899
+ * });
900
+ * ```
901
+ * @experimental
902
+ */
903
+ declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
904
+ /**
905
+ * Compile a `defineAgent` definition into the workflow the generated
906
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
907
+ *
908
+ * ```ts
909
+ * import LunoraWorkflow from "@lunora/workflow/do";
910
+ * import { compileAgentWorkflow } from "@lunora/agent";
911
+ * import { support } from "../agents.js";
912
+ *
913
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
914
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
915
+ * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
916
+ * }
917
+ * }
918
+ * ```
919
+ *
920
+ * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
921
+ * (`run`); the loop supplies determinism (step naming + idempotent persists).
922
+ * @experimental
923
+ */
845
924
  declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
846
925
  paths?: AgentFunctionPaths;
847
926
  }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
848
- export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
927
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };