@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
@@ -0,0 +1,1376 @@
1
+ import { InboundEmail } from '@lunora/mail/inbound';
2
+ import { FlexibleSchema, LanguageModel, ModelMessage, ToolSet, ToolChoice, ToolCallRepairFunction, StopCondition, TelemetryOptions } from 'ai';
3
+ /**
4
+ * Structural mirror of the Lunora function reference (`{ __lunoraRef }`).
5
+ * Declared locally so the loop can mint references to the agent runtime
6
+ * functions by path without importing `@lunora/dispatch`.
7
+ * @experimental
8
+ */
9
+ interface AgentFunctionReference {
10
+ __lunoraRef: string;
11
+ }
12
+ /**
13
+ * Per-call options an {@link AgentRunFunction} forwards to the dispatcher —
14
+ * a structural subset of `@lunora/dispatch`'s `RunFunctionOptions`, declared
15
+ * locally so this module stays free of that import.
16
+ * @experimental
17
+ */
18
+ interface AgentRunOptions {
19
+ /**
20
+ * Abort the dispatch after this many ms, overriding the runner's 30s
21
+ * default (`DEFAULT_DISPATCH_TIMEOUT_MS`).
22
+ *
23
+ * Load-bearing for any tool whose target legitimately runs longer than
24
+ * that. A dispatch timeout answers 503, which is NOT a deterministic
25
+ * dispatch failure, so the tool's `step.do` rethrows and the host retries
26
+ * the step — dispatching the same call again while the FIRST one is still
27
+ * running. For a side-effecting target (a container command, a billed page
28
+ * render) that is a second execution, not a second attempt. Set this at
29
+ * least as wide as the target's own budget, and give the target an inner
30
+ * deadline strictly under it so the target aborts itself first.
31
+ */
32
+ timeoutMs?: number;
33
+ }
34
+ /**
35
+ * `ctx.run`-shaped dispatcher the loop uses to call Lunora functions.
36
+ * @experimental
37
+ */
38
+ type AgentRunFunction = (reference: AgentFunctionReference, args?: Record<string, unknown>, options?: AgentRunOptions) => Promise<unknown>;
39
+ /**
40
+ * Structural subset of the Cloudflare Workflows durable-step API the loop needs.
41
+ * @experimental
42
+ */
43
+ interface AgentStepLike {
44
+ do: <T>(name: string, callback: () => Promise<T>) => Promise<T>;
45
+ /**
46
+ * Durably hibernate until an external event of `type` arrives, then return
47
+ * its payload. Used for human-in-the-loop approvals: a run pauses on
48
+ * `approval:<toolCallId>` until a client resolves it. Like `do`, a resolved
49
+ * wait is memoized — a replay returns the recorded decision without pausing
50
+ * again. Signature mirrors `@lunora/workflow`'s `WorkflowStepLike`.
51
+ */
52
+ waitForEvent: <T = unknown>(name: string, options: {
53
+ timeout?: number | string;
54
+ type: string;
55
+ }) => Promise<{
56
+ payload: Readonly<T>;
57
+ type: string;
58
+ }>;
59
+ }
60
+ /**
61
+ * The context handed to an agent tool's `execute`. Beyond the model-provided
62
+ * input, a tool sees who it runs for (`threadKey`), how to call back into the
63
+ * app (`run` — dispatches Lunora queries/mutations/actions), and its
64
+ * `idempotencyKey`.
65
+ *
66
+ * The `idempotencyKey` is the deterministic durable-step name
67
+ * (`tool:<name>:<toolCallId>`, further suffixed per script step for a
68
+ * `codeTool`). A COMPLETED tool step is never re-run on a workflow replay
69
+ * (native step memoization) — but a step that FAILS mid-body is retried
70
+ * at-least-once, so a side-effecting tool (charge a card, send a mail) must
71
+ * dedupe on this key itself. `functionTool` forwards it to the dispatched
72
+ * function as `args.idempotencyKey` (pinned after the model input, so it
73
+ * can't be overridden) — a function that wants to dedupe declares
74
+ * `idempotencyKey: v.optional(v.string())` in its own args and checks it; a
75
+ * function that ignores it is unaffected (an undeclared arg field is dropped,
76
+ * not rejected).
77
+ * @experimental
78
+ */
79
+ interface AgentToolContext {
80
+ /**
81
+ * How many sub-agent delegations deep this run already is — 0 for a run a
82
+ * user started, one more per `agent.asTool` hop. The loop copies it off
83
+ * {@link AgentRunInput.depth}; `agent.asTool` reads it to refuse spawning a
84
+ * child past the delegation-depth bound (see `as-tool.ts`). Absent is 0.
85
+ */
86
+ depth?: number;
87
+ /** The Worker environment bindings. */
88
+ env: Record<string, unknown>;
89
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes the declared agents (see `agent.asTool`). */
90
+ exports?: unknown;
91
+ /**
92
+ * Read the thread's synced state — dispatches the public owner-gated
93
+ * `agents:agentState` query through {@link AgentToolContext.run} (the same
94
+ * admin-dispatch path the loop reads history with), so it inherits the
95
+ * thread's identity/owner gate. Returns `undefined` before any state was
96
+ * seeded (`defineAgent({ initialState })`) or written.
97
+ *
98
+ * NOT replay-stable: on an at-least-once step retry this reflects whatever a
99
+ * prior attempt already wrote via {@link AgentToolContext.setState} (a real
100
+ * committed write, not rolled back), so a value *derived* from it is not
101
+ * safe to pass straight back to `setState` — see its doc for the
102
+ * read-modify-write hazard and the `idempotencyKey` dedupe fix.
103
+ */
104
+ getState: () => Promise<Record<string, unknown> | undefined>;
105
+ /** Deterministic idempotency key — the tool's durable-step name. */
106
+ idempotencyKey: string;
107
+ /**
108
+ * Verified owner of the thread this run belongs to (the loop copies it off
109
+ * {@link AgentRunInput.owner}); `undefined` on an anonymous/single-tenant
110
+ * thread. `agent.asTool` forwards it to the CHILD run, so a sub-agent thread
111
+ * under an owned parent inherits the same RLS scope instead of being created
112
+ * ownerless — which left it readable by anyone who knew its key.
113
+ */
114
+ owner?: string;
115
+ /**
116
+ * Emit an EPHEMERAL progress event for this tool call on the agent's live
117
+ * channel — the same live-only sink the streamed token deltas ride. NOT
118
+ * persisted and NEVER replayed: it fires only while `execute` runs inside the
119
+ * tool's memoized durable step, so a COMPLETED step is served from the memo on
120
+ * replay without re-emitting. A safe no-op when the runtime wired no live sink
121
+ * (the durable path's default), exactly as `streamingText` stays empty then.
122
+ * Surfaced on the client by `useAgentToolEvents`, correlated to this call by
123
+ * {@link AgentToolContext.toolCallId}. `data` must be JSON-serializable.
124
+ */
125
+ reportProgress: (data: unknown) => void;
126
+ /** Dispatch a Lunora function (the workflow `ctx.run`). */
127
+ run: AgentRunFunction;
128
+ /**
129
+ * Replace the thread's synced state — dispatches the internal
130
+ * `agents:agentSetState` mutation (absolute REPLACE of the whole object) and
131
+ * broadcasts to every `useAgentState` subscriber over the existing reactive
132
+ * channel. Runs inside the tool's memoized durable step, so a COMPLETED step
133
+ * is served from the memo on replay without re-dispatching.
134
+ *
135
+ * REPLAY-SAFETY CONTRACT — the *value* you pass must be REPLAY-STABLE: a
136
+ * constant or derived purely from the replay-stable tool `input` (never
137
+ * `Date.now()`/`Math.random()`). A step that FAILS mid-body is retried
138
+ * at-least-once, and the retry re-runs the whole `execute` against state a
139
+ * prior attempt may already have written (the dispatch is a real committed
140
+ * mutation, not rolled back). Re-applying a replay-stable value is a no-op,
141
+ * so the absolute set converges. A value derived from
142
+ * {@link AgentToolContext.getState} is NOT replay-stable — a naive
143
+ * read-modify-write (`setState({ count: (await getState()).count + 1 })`)
144
+ * DOUBLE-ADVANCES on a retry because the retry re-reads the already-written
145
+ * value. For a read-modify-write, make the tool idempotent on
146
+ * {@link AgentToolContext.idempotencyKey}: record the key in the state and
147
+ * skip the write when it is already present.
148
+ */
149
+ setState: (state: Record<string, unknown>) => Promise<void>;
150
+ /**
151
+ * The durable-step handle (`step.do`/`waitForEvent`). ALWAYS present:
152
+ * `agent-loop.ts` threads it into every tool's context unconditionally, and
153
+ * it is required rather than optional so a missing handle is a compile
154
+ * error instead of a silent durability downgrade. `codeTool` uses it to give
155
+ * each script step its OWN nested durable boundary — see `code-tool.ts` — so
156
+ * a failure at script step 3 retries only step 3, not steps 1–2's
157
+ * already-committed side effects. Cloudflare Workflows supports a `step.do`
158
+ * nested inside another `step.do`'s callback (the codeTool call's own
159
+ * enclosing step). Most tools never touch this directly; a test driving
160
+ * `execute`/`runToolScript` by hand passes a pass-through double.
161
+ */
162
+ step: AgentStepLike;
163
+ /** The thread this tool call belongs to. */
164
+ threadKey: string;
165
+ /** The provider-issued tool-call id. */
166
+ toolCallId: string;
167
+ }
168
+ /**
169
+ * The view of {@link AgentToolContext} handed to a `needsApproval` gate
170
+ * function — every field except `setState`, `step`, and `reportProgress`.
171
+ *
172
+ * `setState` is dropped because a gate that mutates thread state is a side
173
+ * effect inside a decision predicate, and `reportProgress` because emitting a
174
+ * live event is the same thing in observable form — the decision is what the
175
+ * loop reports, not the deciding. `step` goes because the loop already runs the
176
+ * gate inside a durable step of its own, so a gate has no business opening
177
+ * another.
178
+ *
179
+ * `getState` and `run` stay: reads are legitimate gate inputs (gate on the
180
+ * caller's plan tier, on a spend total), and the gate resolves inside its own
181
+ * durable step, so they are replay-safe there. Note this makes the type a
182
+ * NARROWING, not a proof of purity — `run` takes any
183
+ * {@link AgentFunctionReference}, so a gate can still dispatch a mutation
184
+ * before approval. Nothing in the type system distinguishes a query reference
185
+ * from a mutation one; keeping the gate side-effect-free is the author's.
186
+ * @experimental
187
+ */
188
+ type AgentApprovalContext = Omit<AgentToolContext, "reportProgress" | "setState" | "step">;
189
+ /**
190
+ * An agent tool. Unlike a raw AI SDK tool, `execute` is NOT handed to the
191
+ * model call — the loop runs it itself inside a named durable step so a
192
+ * completed call never re-runs on replay, and passes the
193
+ * {@link AgentToolContext} alongside the input.
194
+ * @experimental
195
+ */
196
+ interface AgentToolDefinition<Input = unknown, Output = unknown> {
197
+ /** What the tool does — shown to the model. */
198
+ description: string;
199
+ /** Run the tool. The returned value is persisted as the tool message content. */
200
+ execute: (input: Input, context: AgentToolContext) => Promise<Output> | Output;
201
+ /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
202
+ inputSchema: FlexibleSchema<Input>;
203
+ /** Runtime brand. */
204
+ isLunoraAgentTool: true;
205
+ /**
206
+ * Gate the tool behind a human approval (mirrors the AI SDK's
207
+ * `needsApproval`). When it resolves truthy the durable run PAUSES — the
208
+ * thread moves to `"awaiting_input"` and the workflow hibernates on
209
+ * `approval:<toolCallId>` — until a client calls `agents:agentResolveApproval`.
210
+ * On approve the tool runs exactly as normal; on reject it is skipped and a
211
+ * tool result explaining the rejection is persisted so the next turn recovers.
212
+ * A boolean gates statically; a function gates per input. Default: `false`
213
+ * (unchanged behavior).
214
+ *
215
+ * The boolean/`undefined` forms are compile-time constants re-derived
216
+ * identically on every replay — no durable step. The FUNCTION form runs
217
+ * inside its OWN durable step (`tool:approval-gate:<toolCallId>`, distinct
218
+ * from the tool's own step), so it now runs exactly once per call, not once
219
+ * per replay. It must still be otherwise pure: deterministic given its
220
+ * inputs (no `Date.now()`/`Math.random()`) and free of side effects — the
221
+ * context it receives is {@link AgentApprovalContext}, which has neither
222
+ * `setState` nor `reportProgress`; state writes and progress events belong
223
+ * only in `execute`, inside the tool's own memoized step. It still holds
224
+ * `run`, which the type cannot narrow to reads — see
225
+ * {@link AgentApprovalContext}.
226
+ */
227
+ needsApproval?: ((input: Input, context: AgentApprovalContext) => boolean | Promise<boolean>) | boolean;
228
+ }
229
+ /**
230
+ * Author-supplied tool config (see {@link AgentToolDefinition}).
231
+ * @experimental
232
+ */
233
+ type AgentToolConfig<Input = unknown, Output = unknown> = Omit<AgentToolDefinition<Input, Output>, "isLunoraAgentTool">;
234
+ /**
235
+ * Generic-erased tool for tool maps. `Input` sits in both a covariant
236
+ * (`inputSchema`) and a contravariant (`execute`) position, so no single
237
+ * non-`any` instantiation admits every concrete tool — the same reason the AI
238
+ * SDK's `ToolSet` erases its generics.
239
+ * @experimental
240
+ */
241
+ type AnyAgentTool = AgentToolDefinition<any, any>;
242
+ /**
243
+ * The model an agent runs on: a Workers AI model id (resolved via `env.AI`),
244
+ * a prebuilt AI SDK {@link LanguageModel}, or a thunk building one from the
245
+ * Worker env (for providers that need API keys off `env`).
246
+ * @experimental
247
+ */
248
+ type AgentModelInput = LanguageModel | ((env: Record<string, unknown>) => LanguageModel);
249
+ /**
250
+ * Memory wiring: the path (or reference) of an app **action** taking
251
+ * `{ query: string }` and returning `@lunora/ai/rag`'s `RetrieveResult`
252
+ * (`{ context, chunks, sources }`) — typically three lines over
253
+ * `defineRag(...)(ctx).retrieve`. Dispatching to a real action (instead of
254
+ * embedding vector plumbing here) keeps retrieval inside a fully wired ctx:
255
+ * codegen-resolved vector bindings, RLS, observability.
256
+ *
257
+ * Two retrieval MODES. `"inject"` (default) runs the action as a durable step at
258
+ * turn start and injects `.context` as one system message (one-shot top-k).
259
+ * `"agentic"` skips auto-injection; the source instead mints a `searchMemory`
260
+ * tool the MODEL calls mid-reasoning (Recursive-LM / "read what you need") — each
261
+ * call a memoized durable step, so multi-hop retrieval is crash-safe for free.
262
+ * @experimental
263
+ */
264
+ interface AgentMemoryOptions {
265
+ /**
266
+ * Episodic-tier options — read only when {@link AgentMemoryOptions.kind} is
267
+ * `"episodic"`. `recall` bounds how many recent episodes are injected per run
268
+ * (default 5, capped at 20); `extractionModel` overrides the (optionally
269
+ * cheaper) model that summarizes each run into an episode (defaults to the
270
+ * agent's own model).
271
+ */
272
+ episodic?: {
273
+ /** Model for the run-end episode-summary step (defaults to the agent's model). */
274
+ extractionModel?: AgentModelInput;
275
+ /** Max recent episodes recalled per run (default 5, max 20). */
276
+ recall?: number;
277
+ };
278
+ /**
279
+ * Graph-tier bounds and extraction model — read only when
280
+ * {@link AgentMemoryOptions.kind} is `"graph"`. `depth`/`maxSeeds`/`fanOut`/
281
+ * `maxNodes` bound the run-time BFS traversal; `extractionModel` overrides the
282
+ * (optionally cheaper) model used for the run-end entity/relation extraction
283
+ * step (defaults to the agent's own model).
284
+ */
285
+ graph?: {
286
+ /** Max BFS hops from a seed entity (default 2). */
287
+ depth?: number;
288
+ /** Model for the run-end extraction step (defaults to the agent's model). */
289
+ extractionModel?: AgentModelInput;
290
+ /** Max edges expanded per visited node (default 8). */
291
+ fanOut?: number;
292
+ /** Max entities visited across the whole traversal (default 32). */
293
+ maxNodes?: number;
294
+ /** Max seed entities matched from the query (default 4). */
295
+ maxSeeds?: number;
296
+ };
297
+ /**
298
+ * `"semantic"` (default) is vector RAG over {@link AgentMemoryOptions.source}.
299
+ * `"graph"` traverses the owner-scoped entity/relation graph (auto-extracted
300
+ * on write, keyed by the thread's `owner`) via the built-in traverse function
301
+ * and ignores `source`. `"episodic"` recalls a recency-ordered timeline of the
302
+ * owner's past runs (each summarized at run end); it also ignores `source`.
303
+ * See {@link AgentMemoryOptions}.
304
+ */
305
+ kind?: "episodic" | "graph" | "semantic";
306
+ /**
307
+ * `"inject"` (default) auto-injects one top-k context system message per
308
+ * run; `"agentic"` skips injection and mints a `searchMemory` tool the model
309
+ * drives itself. Applies to `"semantic"` kind only. See
310
+ * {@link AgentMemoryOptions}.
311
+ */
312
+ mode?: "agentic" | "inject";
313
+ /**
314
+ * Agentic-only. An optional fetch-by-id **action** `{ id: string } -> string`
315
+ * that mints a companion `readMemory` tool so the model can pull a full
316
+ * document after `searchMemory` surfaces its id (typically a ~3-line action
317
+ * mapping `${sourceId}#${n}` → text). Ignored in `"inject"` mode.
318
+ */
319
+ read?: AgentFunctionReference | string;
320
+ /**
321
+ * Agentic-only. Per-result snippet truncation (chars) applied to each
322
+ * `searchMemory` hit for token economy. Default 240. Ignored in `"inject"`
323
+ * mode.
324
+ */
325
+ snippetChars?: number;
326
+ /**
327
+ * The memory action: a function path (`"rag:searchDocs"`) or reference.
328
+ * Required for `"semantic"` kind (enforced at `defineAgent`); ignored — and
329
+ * therefore optional — for `"graph"` kind, which dispatches the built-in
330
+ * traverse function instead.
331
+ */
332
+ source?: AgentFunctionReference | string;
333
+ /** Retrieval depth forwarded to the action as `topK`. */
334
+ topK?: number;
335
+ }
336
+ /**
337
+ * One keyed memory-retrieval source the loop dispatches per run. `defineAgent`
338
+ * folds them onto {@link AgentDefinition.memorySources}: the default source
339
+ * (`key: "default"`) from {@link AgentConfig.memory}, then one per skill that
340
+ * carries `knowledge` (keyed by the skill's name). The key names the durable
341
+ * step — the default source keeps the historic `"memory:retrieve"`, a skill
342
+ * source uses `"memory:retrieve:<key>"` — so replay stays deterministic.
343
+ * @experimental
344
+ */
345
+ interface AgentMemorySource extends AgentMemoryOptions {
346
+ /** Stable source key: `"default"` for `memory`, else the contributing skill's name. */
347
+ key: string;
348
+ }
349
+ /**
350
+ * Cumulative or per-turn token usage — AI SDK `LanguageModelUsage` field names.
351
+ * @experimental
352
+ */
353
+ interface AgentUsage {
354
+ /** Prompt (input) tokens. */
355
+ inputTokens?: number;
356
+ /** Completion (output) tokens. */
357
+ outputTokens?: number;
358
+ /** Input + output tokens. */
359
+ totalTokens?: number;
360
+ }
361
+ /**
362
+ * Context handed to a dynamic {@link AgentConfig.instructions} function.
363
+ * @experimental
364
+ */
365
+ interface AgentInstructionsContext {
366
+ /** The Worker environment bindings. */
367
+ env: Record<string, unknown>;
368
+ /** The user message that started this run. */
369
+ input: string;
370
+ /** The thread this run belongs to. */
371
+ threadKey: string;
372
+ }
373
+ /**
374
+ * Author-supplied config for {@link SkillDefinition} — a reusable bundle of
375
+ * expertise (an instruction fragment, tools, and retrieval knowledge) an agent
376
+ * composes in via `defineAgent({ skills: [...] })`. Reuse-first: `tools` carry
377
+ * the SAME {@link AnyAgentTool} shape agents already use
378
+ * (`functionTool`/`mcpTools`/`agentAsTool`), and `knowledge` reuses the
379
+ * {@link AgentMemoryOptions} retrieval verbatim.
380
+ * @experimental
381
+ */
382
+ interface SkillConfig {
383
+ /**
384
+ * An instruction fragment merged into the agent's system prompt — a static
385
+ * string or a thunk over the run context (same shape as
386
+ * {@link AgentConfig.instructions}). Fragments compose in order: the agent's
387
+ * own instructions first, then each skill's in `skills` array order.
388
+ */
389
+ instructions?: string | ((context: AgentInstructionsContext) => string);
390
+ /**
391
+ * Retrieval-augmented knowledge for this skill — see
392
+ * {@link AgentMemoryOptions}. Retrieved as its own durable step at run start
393
+ * (keyed by the skill `name`) and injected alongside the agent's `memory`.
394
+ */
395
+ knowledge?: AgentMemoryOptions;
396
+ /**
397
+ * The skill's identifier — namespaces this skill's `knowledge` memory source
398
+ * (the durable step `memory:retrieve:<name>`). Must be identifier-shaped.
399
+ */
400
+ name: string;
401
+ /**
402
+ * Tools this skill contributes, merged into the agent's FLAT tool namespace.
403
+ * A name collision with the agent's own tools (or another skill's) is an
404
+ * error at `defineAgent` — the agent owns the model-facing namespace.
405
+ */
406
+ tools?: Record<string, AnyAgentTool>;
407
+ }
408
+ /**
409
+ * The code-side parts of a markdown-authored skill — everything `SKILL.md`
410
+ * cannot carry. `name` and `instructions` come from the file itself.
411
+ * @experimental
412
+ */
413
+ type SkillMarkdownExtras = Omit<SkillConfig, "instructions" | "name">;
414
+ /**
415
+ * A `defineSkill` result — config plus the brand the agent merge checks.
416
+ * @experimental
417
+ */
418
+ interface SkillDefinition extends SkillConfig {
419
+ /** Runtime brand check (see `isSkillDefinition`). */
420
+ readonly isLunoraSkill: true;
421
+ }
422
+ /**
423
+ * One prior turn, as {@link AgentConfig.prepareStep} and `stopWhen` observe it.
424
+ * @experimental
425
+ */
426
+ interface AgentStepInfo {
427
+ /** The assistant text of the turn. */
428
+ text: string;
429
+ /** The tool calls the turn issued (AI SDK `StepResult.toolCalls` shape). */
430
+ toolCalls: ReadonlyArray<{
431
+ input: unknown;
432
+ toolCallId: string;
433
+ toolName: string;
434
+ }>;
435
+ /** The turn's token usage, when the model reported it. */
436
+ usage?: AgentUsage;
437
+ }
438
+ /**
439
+ * The turn summary handed to {@link AgentConfig.onStepFinish}.
440
+ * @experimental
441
+ */
442
+ interface AgentStepFinishInfo {
443
+ /** The assistant text produced this turn. */
444
+ text: string;
445
+ /** The tool calls issued this turn (empty on the final answer). */
446
+ toolCalls: ReadonlyArray<AgentToolCall>;
447
+ /** The zero-based turn index. */
448
+ turn: number;
449
+ /** The turn's token usage, when the model reported it. */
450
+ usage?: AgentUsage;
451
+ }
452
+ /**
453
+ * Called after each LLM turn with that turn's text, tool calls, and usage. Runs
454
+ * inside a named durable step (`agent:step-finish:<turn>`) so it fires exactly
455
+ * once per turn even across a workflow replay.
456
+ * @experimental
457
+ */
458
+ type AgentOnStepFinish = (info: AgentStepFinishInfo) => Promise<void> | void;
459
+ /**
460
+ * What {@link AgentConfig.onReply} is called with when a triggered run reaches
461
+ * its final answer.
462
+ * @experimental
463
+ */
464
+ interface AgentReplyInfo {
465
+ /** The worker `env` — where an outbound credential (a bot token, a mailer binding) lives. */
466
+ env: Record<string, unknown>;
467
+ /** Where to reply, captured by the mapper that started this run. */
468
+ replyRef: AgentReplyRef;
469
+ /** The run's final answer. */
470
+ result: AgentRunResult;
471
+ /** The thread this run belongs to. */
472
+ threadKey: string;
473
+ }
474
+ /**
475
+ * Send a triggered run's answer back where it came from — the outbound half of
476
+ * an `onEmail` / `onInbound` trigger.
477
+ *
478
+ * Called once, automatically, when a run started with a `replyRef` produces a
479
+ * final answer; a run without one (an ordinary in-app `ctx.agents.<name>.run`)
480
+ * never calls it. It runs inside a named durable step, so a transient failure
481
+ * is retried and a workflow replay does not send the answer twice.
482
+ *
483
+ * Delivery is the app's call, because only the app has the credential: email
484
+ * has a home already (`replyToEmail(mailer, ref, body)` from
485
+ * `@lunora/agent/reply`), while Slack/GitHub/Discord bot tokens have no
486
+ * framework-owned store yet — read them from `info.env` and make the provider
487
+ * call.
488
+ * @experimental
489
+ */
490
+ type AgentOnReply = (info: AgentReplyInfo) => Promise<void> | void;
491
+ /**
492
+ * The input {@link AgentConfig.prepareStep} sees before a turn runs.
493
+ * @experimental
494
+ */
495
+ interface AgentPrepareStepInput {
496
+ /** The messages assembled for this turn (instructions + memory + history). */
497
+ messages: ReadonlyArray<ModelMessage>;
498
+ /** The zero-based index of the turn about to run. */
499
+ stepNumber: number;
500
+ /** The turns already completed this run. */
501
+ steps: ReadonlyArray<AgentStepInfo>;
502
+ }
503
+ /**
504
+ * Per-turn overrides {@link AgentConfig.prepareStep} may return. A returned
505
+ * `messages` array **replaces** the assembled history for that turn — the seam
506
+ * where history compaction lives.
507
+ * @experimental
508
+ */
509
+ interface AgentPrepareStepResult {
510
+ /** Restrict the tools exposed to the model this turn (by name). */
511
+ activeTools?: ReadonlyArray<string>;
512
+ /** Replace the assembled messages for this turn (history compaction). */
513
+ messages?: ReadonlyArray<ModelMessage>;
514
+ /** Swap the model for this turn. */
515
+ model?: AgentModelInput;
516
+ /** Prepend a system message for this turn. */
517
+ system?: string;
518
+ /** Override the tool-choice strategy for this turn. */
519
+ toolChoice?: ToolChoice<ToolSet>;
520
+ }
521
+ /**
522
+ * Adjust the next turn before it runs — mirrors AI SDK's `prepareStep`. Invoked
523
+ * inside the turn's durable step so its effect is memoized on replay.
524
+ * @experimental
525
+ */
526
+ type AgentPrepareStep = (input: AgentPrepareStepInput) => AgentPrepareStepResult | Promise<AgentPrepareStepResult | undefined> | undefined;
527
+ /**
528
+ * The subset of {@link AgentRunInput} an {@link AgentEmailMapper} returns to
529
+ * start a run from an inbound email.
530
+ * @experimental
531
+ */
532
+ /**
533
+ * Where a triggered run should send its answer back to — captured by the
534
+ * mapper, from fields the verified inbound payload already carries, and carried
535
+ * through the run so {@link AgentConfig.onReply} can answer in the same place
536
+ * the question was asked.
537
+ *
538
+ * A discriminated union rather than an opaque blob because each channel threads
539
+ * differently: email by RFC 5322 `In-Reply-To`/`References`, Slack by
540
+ * `thread_ts`, GitHub by issue number, Discord by channel (plus the triggering
541
+ * message for a true reply).
542
+ * @experimental
543
+ */
544
+ type AgentReplyRef = {
545
+ channel: "discord";
546
+ channelId: string;
547
+ messageId?: string;
548
+ } | {
549
+ channel: "email";
550
+ from: string;
551
+ messageId: string;
552
+ references?: string;
553
+ to: string[];
554
+ } | {
555
+ channel: "github";
556
+ commentId?: number;
557
+ issueNumber: number;
558
+ owner: string;
559
+ repo: string;
560
+ } | {
561
+ channel: "slack";
562
+ channelId: string;
563
+ threadTs: string;
564
+ };
565
+ interface AgentEmailRun {
566
+ /** The user message that starts (or continues) the thread — the model's prompt. */
567
+ input: string;
568
+ /**
569
+ * Verified owner of the thread (its RLS scope). SECURITY: inbound `from` is
570
+ * spoofable and the run dispatches RLS-bypassed — derive this from a verified
571
+ * signal (a DKIM-checked address, a mapped account), never blindly from
572
+ * `email.from`.
573
+ */
574
+ owner?: string;
575
+ /**
576
+ * Where to send the answer — see {@link AgentReplyRef}. Populate it from the
577
+ * event the mapper already has (`captureEmailReplyRef(email)` does it for
578
+ * email) and the run calls {@link AgentConfig.onReply} with it once the
579
+ * final answer is ready. Omit it and the run simply never replies.
580
+ */
581
+ replyRef?: AgentReplyRef;
582
+ /** The thread key — reuse to continue a conversation (e.g. a ticket id parsed from the subject). */
583
+ threadKey: string;
584
+ /** Optional thread title, set on first creation. */
585
+ title?: string;
586
+ }
587
+ /**
588
+ * Map an inbound email into an agent run, or `null`/`undefined` to DROP it (a
589
+ * failed DKIM/SPF/DMARC check, or a message not addressed to this agent). Wired
590
+ * by codegen onto the worker's top-level `email()` handler when set — see
591
+ * `@lunora/agent/inbound`.
592
+ *
593
+ * SECURITY: the parsed `from`/`subject`/body are attacker-controlled and the run
594
+ * is dispatched with RLS bypassed. Gate on `email.authentication` (DKIM/SPF/DMARC
595
+ * verdicts) here before returning a run, and treat every returned field as
596
+ * untrusted input.
597
+ * @experimental
598
+ */
599
+ type AgentEmailMapper = (email: InboundEmail) => AgentEmailRun | null | Promise<AgentEmailRun | null | undefined> | undefined;
600
+ /** The inbound webhook channels an agent can be triggered from — see `@lunora/agent/channels`. */
601
+ type AgentInboundChannelKind = "discord" | "github" | "slack";
602
+ /** The run-input an inbound-channel mapper returns — the same shape as {@link AgentEmailRun}. */
603
+ type AgentChannelRun = AgentEmailRun;
604
+ /**
605
+ * The verified, parsed webhook event handed to an {@link AgentInboundChannel.map} mapper.
606
+ * @experimental
607
+ */
608
+ interface InboundChannelEvent {
609
+ /** Which channel delivered it. */
610
+ channel: AgentInboundChannelKind;
611
+ /** The raw request headers. */
612
+ headers: Headers;
613
+ /** Parse the body as JSON (throws on malformed JSON). */
614
+ json: () => unknown;
615
+ /** The raw (verified) request body. */
616
+ rawBody: string;
617
+ }
618
+ /**
619
+ * Map a VERIFIED inbound channel event into an agent run, or `null`/`undefined`
620
+ * to DECLINE it. Runs only AFTER the channel signature check passes.
621
+ *
622
+ * SECURITY: the payload is attacker-controlled and the run dispatches RLS
623
+ * bypassed. Derive the run `owner` from the verified channel identity (the
624
+ * workspace/installation the signing secret belongs to), never from an arbitrary
625
+ * payload field, and treat every returned field as untrusted input.
626
+ */
627
+ type AgentChannelMapper = (event: InboundChannelEvent) => AgentChannelRun | null | Promise<AgentChannelRun | null | undefined> | undefined;
628
+ /**
629
+ * Trigger an agent from a verified inbound webhook. Codegen wires the developer's
630
+ * chosen HTTP route to `dispatchAgentChannel(...)` (from `@lunora/agent/channels`),
631
+ * which verifies the channel signature over the raw body before calling `map`.
632
+ */
633
+ interface AgentInboundChannel {
634
+ /** Which channel this agent listens on (selects the signature scheme). */
635
+ channel: AgentInboundChannelKind;
636
+ /** Map a verified event to a run (or `null` to decline). */
637
+ map: AgentChannelMapper;
638
+ /**
639
+ * The verification credential, from `env`: an env-var NAME (string) or an
640
+ * `(env) => value` resolver. Slack → signing secret; GitHub → webhook secret;
641
+ * Discord → the application's Ed25519 public key (hex).
642
+ */
643
+ secret: string | ((env: Record<string, unknown>) => string | undefined);
644
+ }
645
+ /**
646
+ * `AgentConfig` is part of the experimental `@lunora/agent` API and may change without a major version bump.
647
+ * @experimental
648
+ */
649
+ interface AgentConfig {
650
+ /** Restrict the tools the model may call, by name. Default: all tools. */
651
+ activeTools?: ReadonlyArray<string>;
652
+ /**
653
+ * How long a human-in-the-loop tool approval may stay pending before the
654
+ * run stops waiting — a Cloudflare Workflows duration: milliseconds, or a
655
+ * `"<n> <unit>"` string like `"3 days"` (the unit set is the host's, so a
656
+ * typo is a compile error). Default `"3 days"`.
657
+ *
658
+ * On timeout the call is treated as REJECTED (the run records why and
659
+ * continues down the normal rejection path), so a run whose approver never
660
+ * answers ends instead of hibernating forever.
661
+ *
662
+ * CLAMPED to one week. A longer wait would outlive the thread's
663
+ * abandoned-run horizon, letting a new run reclaim the thread while the
664
+ * approval is still pending — which is the exact failure this timeout
665
+ * exists to prevent, so it cannot be configured back into existence.
666
+ */
667
+ approvalTimeout?: `${number} ${"day" | "hour" | "minute" | "month" | "second" | "week" | "year"}${"s" | ""}` | number;
668
+ /**
669
+ * Automatic thread-history compaction. When the persisted history exceeds
670
+ * `maxMessages`, the loop summarizes the older messages (all but the most
671
+ * recent `keepRecent`, default `ceil(maxMessages / 2)`) into one system-message
672
+ * brief and prompts the model with that brief plus the recent tail — keeping
673
+ * the context bounded as a conversation grows. The summary is produced inside
674
+ * the turn's memoized durable step (replay-safe) by `model` (a cheaper model
675
+ * may be set, else the agent's). Absent (the default) disables compaction —
676
+ * the full history is sent every turn, exactly as before. A manual
677
+ * {@link AgentConfig.prepareStep} still runs after and can override further.
678
+ */
679
+ compaction?: {
680
+ /** How many most-recent messages to keep verbatim (default `ceil(maxMessages / 2)`). */
681
+ keepRecent?: number;
682
+ /** Compact once history exceeds this many messages. */
683
+ maxMessages: number;
684
+ /** Model for the summarization step (defaults to the agent's model). */
685
+ model?: AgentModelInput;
686
+ };
687
+ /**
688
+ * Seed the thread's synced state — a static, JSON-serializable object set on
689
+ * the thread row at creation only (first writer wins, like `owner`/`title`),
690
+ * so a `useAgentState` client sees it immediately. Keep it DETERMINISTIC (no
691
+ * `Date.now()`/`Math.random()`); it is written once by the durable bootstrap.
692
+ * Runtime-only config — invisible to codegen (agent-free and agent-ful
693
+ * `_generated/*` output is unchanged by its presence).
694
+ */
695
+ initialState?: Record<string, unknown>;
696
+ /**
697
+ * System prompt prepended to every model call — a static string or a thunk
698
+ * derived from the run context (dynamic instructions).
699
+ */
700
+ instructions?: string | ((context: AgentInstructionsContext) => string);
701
+ /** Cap the tokens generated per turn (AI SDK `maxOutputTokens`). */
702
+ maxOutputTokens?: number;
703
+ /**
704
+ * Cost/step cap: maximum LLM turns per run. Default 8. Composes with
705
+ * {@link AgentConfig.stopWhen} — the loop ends when EITHER triggers.
706
+ */
707
+ maxTurns?: number;
708
+ /** Retrieval-augmented memory — see {@link AgentMemoryOptions}. */
709
+ memory?: AgentMemoryOptions;
710
+ /** The model — see {@link AgentModelInput}. */
711
+ model: AgentModelInput;
712
+ /**
713
+ * Optional override for the deployed workflow name (`wrangler.jsonc`
714
+ * `workflows[].name`). Defaults to `agent-<kebab-cased export name>`. Does
715
+ * NOT change the binding name, which is always derived from the export
716
+ * name (`support` → `SupportAgentWorkflow`).
717
+ */
718
+ name?: string;
719
+ /**
720
+ * Policy when a run starts on a thread that already has a DIFFERENT run in
721
+ * flight (the thread's `status` is `"running"` under another workflow
722
+ * instance) — the guard that stops two runs from interleaving messages on
723
+ * the shared per-thread seq counter:
724
+ *
725
+ * - `"reject"` (default) — fail the new run fast with a `CONFLICT` error.
726
+ * - `"replace"` — terminate the in-flight instance and take the thread over.
727
+ * - `"queue"` — park the new run behind the one in flight (FIFO, up to five deep) and hibernate it until the thread is handed over.
728
+ *
729
+ * Each parked run is a live workflow instance waiting on an event, so the
730
+ * queue's depth cap is a real resource bound: past it, a start is rejected
731
+ * exactly as `"reject"` would. A `"replace"` arriving later supersedes the
732
+ * run in FLIGHT, not the queue — parked runs still take their turn after it.
733
+ *
734
+ * A dispatch with no instance id (the inbound-email / inbound-channel
735
+ * paths) cannot be parked, because nothing later can tell it apart from
736
+ * another such dispatch to wake it; `"queue"` rejects those.
737
+ *
738
+ * A workflow REPLAY re-enters the bootstrap under the SAME instance id and
739
+ * is never a concurrent run (the guard compares the stored instance id).
740
+ */
741
+ onConcurrentRun?: "queue" | "reject" | "replace";
742
+ /**
743
+ * Map an inbound email into an agent run — see {@link AgentEmailMapper}.
744
+ * When set, codegen wires this agent onto the worker's top-level `email()`
745
+ * handler (via `@lunora/agent/inbound`) so a received message starts a
746
+ * durable run. Return `null`/`undefined` to drop the message.
747
+ */
748
+ onEmail?: AgentEmailMapper;
749
+ /**
750
+ * Trigger this agent from a verified inbound webhook (Slack / GitHub /
751
+ * Discord) — see {@link AgentInboundChannel}. Mount `dispatchAgentChannel(...)`
752
+ * (from `@lunora/agent/channels`) on an HTTP route; it verifies the channel
753
+ * signature over the raw body before calling `map`.
754
+ */
755
+ onInbound?: AgentInboundChannel;
756
+ /**
757
+ * Called with the final answer when the run was triggered from a channel
758
+ * that gave it a `replyRef` — see {@link AgentOnReply}. This is how an
759
+ * inbound-triggered agent answers where it was asked.
760
+ */
761
+ onReply?: AgentOnReply;
762
+ /** Called after each LLM turn — see {@link AgentOnStepFinish}. */
763
+ onStepFinish?: AgentOnStepFinish;
764
+ /**
765
+ * Structured final answer: a zod schema or `jsonSchema(...)`. When set the
766
+ * loop runs the model with AI SDK `Output.object({ schema })` and returns
767
+ * the parsed object in {@link AgentRunResult.output}.
768
+ */
769
+ output?: FlexibleSchema<unknown>;
770
+ /** Adjust the next turn before it runs — see {@link AgentPrepareStep}. */
771
+ prepareStep?: AgentPrepareStep;
772
+ /**
773
+ * Opt this agent into being STARTED over the public RPC boundary — i.e. via
774
+ * the auto-registered `agents:agentRun` mutation an HTTP-only client (e.g.
775
+ * the `@lunora/mcp` server) calls. Default `false`: an agent is startable
776
+ * only from server-side app code (`ctx.agents.<name>.run(...)`), so declaring
777
+ * an agent does NOT expose it to arbitrary RPC callers. Fail-closed — the run
778
+ * mutation refuses an agent that has not opted in, regardless of any MCP-side
779
+ * `allowAgents` configuration. A started thread is still owner-scoped to
780
+ * `ctx.auth.userId`. Deploy configuration codegen reads STATICALLY (a boolean
781
+ * literal), so it must be inline in the `defineAgent({ ... })` object literal.
782
+ */
783
+ publicRun?: boolean;
784
+ /**
785
+ * Repair a malformed tool call the model emits (AI SDK
786
+ * `experimental_repairToolCall`): given the failing `{ toolCall, error, tools,
787
+ * inputSchema, messages, system }`, return a corrected tool call or `null` to
788
+ * give up. Runs inside the model turn, so keep it deterministic (it re-runs on
789
+ * a replay). Unset (the default) leaves the loop's existing
790
+ * unknown-tool-name recovery as the only repair path.
791
+ */
792
+ repairToolCall?: ToolCallRepairFunction<ToolSet>;
793
+ /**
794
+ * Reusable {@link SkillDefinition}s to compose in — each contributes an
795
+ * instruction fragment, tools (merged into the flat namespace; collisions
796
+ * throw), and retrieval `knowledge` (its own keyed memory source). Folded at
797
+ * declaration time; the tool namespace and memory sources on the returned
798
+ * {@link AgentDefinition} already reflect the merge.
799
+ */
800
+ skills?: ReadonlyArray<SkillDefinition>;
801
+ /**
802
+ * Extra loop-stop conditions (AI SDK `StopCondition`s). Composes with
803
+ * {@link AgentConfig.maxTurns} — the loop ends when EITHER triggers.
804
+ */
805
+ stopWhen?: ReadonlyArray<StopCondition<ToolSet>> | StopCondition<ToolSet>;
806
+ /** Passed to `generateText` as its stable `telemetry` option. */
807
+ telemetry?: TelemetryOptions;
808
+ /** Sampling temperature forwarded to the model. */
809
+ temperature?: number;
810
+ /** Tool-choice strategy (AI SDK `ToolChoice`). Default: `"auto"`. */
811
+ toolChoice?: ToolChoice<ToolSet>;
812
+ /** The tools the model may call, by name. */
813
+ tools?: Record<string, AnyAgentTool>;
814
+ /**
815
+ * Opt into a real-time voice session — see {@link AgentVoiceConfig}. Its mere
816
+ * presence tells codegen to emit the `VOICE_...` hibernatable-WebSocket DO
817
+ * (`VoiceSessionDO` subclass) and the `api.agents.{name}Voice` client
818
+ * reference; an agent without it is byte-identical to before. Runtime config
819
+ * for the in-DO pipeline (models/voice) rides the same object.
820
+ */
821
+ voice?: AgentVoiceConfig;
822
+ }
823
+ /**
824
+ * Opt an agent into a real-time VOICE session — a dedicated hibernatable-
825
+ * WebSocket Durable Object (`VoiceSessionDO`) that runs a per-turn
826
+ * STT→LLM→TTS pipeline IN-DO and SHARES the agent's existing thread tables
827
+ * (`agent_threads`/`agent_messages`) via the runtime dispatch seam. Presence of
828
+ * this block is what codegen keys on to emit the `VOICE_...` DO class + the
829
+ * `api.agents.{name}Voice` client reference; agents without it are byte-
830
+ * identical.
831
+ *
832
+ * v1 slice: conversational turns only. In-DO voice turns are NOT replay-durable
833
+ * and get NO Workflow tool-loop — tool calls are deferred. All fields are
834
+ * optional; the defaults target Workers AI (`@cf/openai/whisper-large-v3-turbo`
835
+ * for STT, `@cf/deepgram/aura-1` for TTS).
836
+ * @experimental
837
+ */
838
+ interface AgentVoiceConfig {
839
+ /**
840
+ * Server→client audio container. `"mp3"` (default) matches the TTS model's
841
+ * native stream; carried to the client so it decodes the returned frames
842
+ * with the right codec.
843
+ */
844
+ audioFormat?: "mp3" | "wav";
845
+ /**
846
+ * Spoken on connect before the first user turn — a fixed greeting synthesized
847
+ * through the TTS model. Omit for a silent-until-spoken-to session.
848
+ *
849
+ * Synthesized once per THREAD, not once per socket: the greeting's persisted
850
+ * row is keyed per thread, and a reconnect onto a thread that already exists
851
+ * gets the `ready` frame without paying for the same line again.
852
+ */
853
+ greeting?: string;
854
+ /**
855
+ * Cap on how many turns one voice socket may run before it is closed with
856
+ * code `4002`. Every turn is a full LLM generation plus sentence-by-sentence
857
+ * TTS — billed and persisted — on a hibernatable socket that can live for
858
+ * days, and the one-turn-in-flight guard throttles nothing. Defaults to 100;
859
+ * a client that hits the cap reconnects for a fresh budget.
860
+ */
861
+ maxTurns?: number;
862
+ /**
863
+ * TTS voice/speaker id forwarded to the TTS model (e.g. a Deepgram Aura voice
864
+ * like `"aura-asteria-en"`). Model-specific; omitted when unset so the model
865
+ * uses its own default voice.
866
+ */
867
+ speaker?: string;
868
+ /**
869
+ * Speech-to-text model id (a Workers AI id, resolved via `env.AI`). Defaults
870
+ * to `@cf/openai/whisper-large-v3-turbo` — batch per-utterance transcription
871
+ * (the client marks utterance boundaries; continuous STT is deferred).
872
+ */
873
+ stt?: string;
874
+ /**
875
+ * Text-to-speech model id (a Workers AI id, resolved via `env.AI`). Defaults
876
+ * to `@cf/deepgram/aura-1` — streamed MP3 synthesized sentence-by-sentence
877
+ * from the LLM's token stream.
878
+ */
879
+ tts?: string;
880
+ }
881
+ /**
882
+ * The input the parent model provides when delegating to a sub-agent tool.
883
+ * @experimental
884
+ */
885
+ interface AgentSubToolInput {
886
+ /** The task or question to hand to the sub-agent. */
887
+ prompt: string;
888
+ }
889
+ /**
890
+ * Options for {@link AgentDefinition.asTool} (`agent.asTool(...)`).
891
+ * @experimental
892
+ */
893
+ interface AgentAsToolOptions {
894
+ /** What the sub-agent does — shown to the parent's model (it decides from it). */
895
+ description: string;
896
+ /** Cap on child-run status polls before giving up — a positive integer. Default 600 (with the 500 ms default interval, a five-minute budget). */
897
+ maxPolls?: number;
898
+ /**
899
+ * The child agent's export name — selects its `AGENT_<NAME>` Workflow
900
+ * export key (e.g. `"researcher"` → `ResearcherAgentWorkflow`). The model-facing tool
901
+ * name is the KEY assigned in the parent's `tools` map, not this.
902
+ */
903
+ name: string;
904
+ /** Delay (ms) between child-run status polls. Default 500. */
905
+ pollIntervalMs?: number;
906
+ /**
907
+ * Test seam replacing the between-poll wait. Production uses a real timer;
908
+ * tests inject an immediate resolve so polling runs without wall-clock delay.
909
+ */
910
+ wait?: (ms: number) => Promise<void>;
911
+ }
912
+ /**
913
+ * A `defineAgent` result — config plus the brand codegen discovers.
914
+ * @experimental
915
+ */
916
+ interface AgentDefinition extends AgentConfig {
917
+ /**
918
+ * Adapt this agent into a tool a PARENT agent can call: the returned tool's
919
+ * `execute` starts a durable child run on the named agent's Workflow binding
920
+ * and returns its final answer. Mirrors `@lunora/ai/rag`'s `asTool()`. The
921
+ * child run is correlated by a replay-stable `threadKey` derived from the
922
+ * parent's `toolCallId`, so a retried step reuses the same sub-run.
923
+ */
924
+ asTool: (options: AgentAsToolOptions) => AgentToolDefinition<AgentSubToolInput, string>;
925
+ /** Runtime brand check (see `isAgentDefinition`). */
926
+ readonly isLunoraAgent: true;
927
+ /**
928
+ * The keyed memory sources the loop dispatches per run — the merge of
929
+ * {@link AgentConfig.memory} (as `key: "default"`) and each skill's
930
+ * `knowledge`. Populated by `defineAgent`; `memory` stays on the config for
931
+ * back-compat and direct authoring. When absent the loop falls back to
932
+ * `memory` alone (preserving the historic `"memory:retrieve"` step).
933
+ */
934
+ memorySources?: ReadonlyArray<AgentMemorySource>;
935
+ }
936
+ /**
937
+ * What `agentEnsureThread` reports back to the loop.
938
+ *
939
+ * A discriminated union rather than a bag of optional booleans: the outcomes are
940
+ * mutually exclusive, and the data each carries only exists for its own case.
941
+ * `queued` has a position, `replaced` has the instance it took the thread from,
942
+ * and the rest have nothing — encoding that as independent optional fields made
943
+ * every reader re-derive which combination was legal.
944
+ *
945
+ * `completed` is the odd one: the thread was NOT (re)opened. This run already
946
+ * reported its outcome and is replaying because only the reply was lost, so it
947
+ * takes no ownership and revives nothing — it runs its body out of the step
948
+ * journal to re-dispatch the effects that never landed.
949
+ * @experimental
950
+ */
951
+ type EnsureThreadOutcome = {
952
+ outcome: "completed" | "continued" | "created";
953
+ } | {
954
+ outcome: "queued";
955
+ position: number;
956
+ } | {
957
+ outcome: "replaced";
958
+ priorInstanceId: string;
959
+ };
960
+ /**
961
+ * Params of one agent run (the compiled workflow's payload).
962
+ * @experimental
963
+ */
964
+ interface AgentRunInput {
965
+ /**
966
+ * Sub-agent delegation depth. A run a user starts omits it (0); each
967
+ * `agent.asTool` hop stamps its child one deeper, and the tool refuses to
968
+ * delegate past the bound — `maxTurns` bounds one level's turns, this bounds
969
+ * the TREE (every hop mints a distinct child `threadKey`, so the per-thread
970
+ * run-queue cap never applies across them).
971
+ */
972
+ depth?: number;
973
+ /** The user message that starts (or continues) the thread. */
974
+ input: string;
975
+ /**
976
+ * Verified identity of the thread owner — pass `ctx.auth.userId` from the
977
+ * mutation/action starting the run. An owned thread's public queries
978
+ * (`agents:agentThread` / `agents:agentMessages`) only answer for this
979
+ * identity; omitting it leaves the thread readable by anyone who knows the
980
+ * key (only appropriate for single-tenant/anonymous apps). Immutable after
981
+ * the first run.
982
+ */
983
+ owner?: string;
984
+ /** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
985
+ replyRef?: AgentReplyRef;
986
+ /** The thread key — reuse to continue a conversation. */
987
+ threadKey: string;
988
+ /** Optional thread title, set on first creation. */
989
+ title?: string;
990
+ }
991
+ /**
992
+ * Output of one agent run (the compiled workflow's return value).
993
+ * @experimental
994
+ */
995
+ interface AgentRunResult {
996
+ /** The parsed structured answer, when {@link AgentConfig.output} is set. */
997
+ output?: unknown;
998
+ /**
999
+ * Why the run ended: a final answer, a `stopWhen` condition, or the
1000
+ * `maxTurns` cap.
1001
+ */
1002
+ stopped: "final" | "maxTurns" | "stopCondition";
1003
+ /** The final assistant text (absent when stopped by `maxTurns`). */
1004
+ text?: string;
1005
+ /** LLM turns consumed. */
1006
+ turns: number;
1007
+ /** Cumulative token usage across the run's turns, when the model reported it. */
1008
+ usage?: AgentUsage;
1009
+ }
1010
+ /**
1011
+ * Function paths of the agent runtime functions (the `agentComponent()`
1012
+ * functions the app re-exports from `lunora/agents.ts`, so codegen registers
1013
+ * them under the `agents:` namespace).
1014
+ * @experimental
1015
+ */
1016
+ interface AgentFunctionPaths {
1017
+ appendMessage: string;
1018
+ /**
1019
+ * The internal `agents:agentCompleteRun` mutation the loop dispatches at the
1020
+ * end of a run: it writes the terminal status AND hands the thread to the
1021
+ * next queued run in the same mutation.
1022
+ */
1023
+ completeRun: string;
1024
+ /**
1025
+ * The internal `agents:agentDeleteMessage` mutation the loop dispatches to
1026
+ * retire the HITL approval marker once the decision has landed.
1027
+ */
1028
+ deleteMessage: string;
1029
+ ensureThread: string;
1030
+ /** The internal `agents:agentEpisodeRecall` query the loop dispatches for an episodic-kind read. */
1031
+ episodeRecall: string;
1032
+ /** The internal `agents:agentEpisodeUpsert` mutation the loop dispatches on run-end episode extraction. */
1033
+ episodeUpsert: string;
1034
+ /** The internal `agents:agentGraphTraverse` query the loop dispatches for a graph-kind read. */
1035
+ graphTraverse: string;
1036
+ /** The internal `agents:agentGraphUpsert` mutation the loop dispatches on run-end graph extraction. */
1037
+ graphUpsert: string;
1038
+ listMessages: string;
1039
+ patchThread: string;
1040
+ /**
1041
+ * The public `agents:agentRun` mutation an HTTP-only client (e.g. the
1042
+ * `@lunora/mcp` server) calls to START a durable run — owner-scoped to
1043
+ * `ctx.auth.userId`, deterministic (the caller supplies `threadKey`).
1044
+ */
1045
+ run: string;
1046
+ /** The internal `agents:agentSetState` mutation the loop dispatches for `setState`. */
1047
+ setState: string;
1048
+ /** The public owner-gated `agents:agentState` query (`getState` + `useAgentState`). */
1049
+ state: string;
1050
+ }
1051
+ /**
1052
+ * Approval lifecycle marker on a message: `"awaiting_approval"` on the
1053
+ * placeholder written while a run pauses on a gated tool, then `"approved"` /
1054
+ * `"rejected"` on the tool result once a client resolves it. Absent on ordinary
1055
+ * messages. `"awaiting_approval"` rows are filtered out of the model prompt.
1056
+ * @experimental
1057
+ */
1058
+ type AgentMessageStatus = "approved" | "awaiting_approval" | "rejected";
1059
+ /**
1060
+ * One persisted thread message, as the loop reads it back.
1061
+ * @experimental
1062
+ */
1063
+ interface AgentMessageRow {
1064
+ content: string;
1065
+ role: "assistant" | "system" | "tool" | "user";
1066
+ seq: number;
1067
+ /** Approval lifecycle marker — see {@link AgentMessageStatus}. */
1068
+ status?: AgentMessageStatus;
1069
+ toolCallId?: string;
1070
+ toolCalls?: ReadonlyArray<AgentToolCall>;
1071
+ toolName?: string;
1072
+ }
1073
+ /**
1074
+ * One model-issued tool call.
1075
+ * @experimental
1076
+ */
1077
+ interface AgentToolCall {
1078
+ id: string;
1079
+ input: unknown;
1080
+ /**
1081
+ * Why this call was REJECTED before it could run: the model's arguments
1082
+ * failed the tool's input schema, or did not parse as JSON. Present only on
1083
+ * a rejected call — the loop records it as a recoverable tool result and
1084
+ * never executes the tool, because the `input` above is the raw value the
1085
+ * provider sent, not a validated one.
1086
+ */
1087
+ invalid?: string;
1088
+ name: string;
1089
+ }
1090
+ /**
1091
+ * Normalized result of one LLM turn (the `generate` seam's return value).
1092
+ * @experimental
1093
+ */
1094
+ interface AgentGenerateResult {
1095
+ /** The parsed structured answer, when {@link AgentConfig.output} is set. */
1096
+ output?: unknown;
1097
+ text: string;
1098
+ toolCalls: ReadonlyArray<AgentToolCall>;
1099
+ /** Token usage the model reported for this turn. */
1100
+ usage?: AgentUsage;
1101
+ }
1102
+ /**
1103
+ * Options passed to the {@link AgentGenerate} seam for one LLM turn.
1104
+ * @experimental
1105
+ */
1106
+ interface AgentGenerateOptions {
1107
+ /** Restrict the tools exposed to the model this turn (by name). */
1108
+ activeTools?: ReadonlyArray<string>;
1109
+ /** The assembled conversation for this turn. */
1110
+ messages: ReadonlyArray<unknown>;
1111
+ /** A per-turn model override (from {@link AgentConfig.prepareStep}). */
1112
+ model?: LanguageModel;
1113
+ /**
1114
+ * Abort the in-flight turn (the streaming seam forwards it to `streamText`'s
1115
+ * `abortSignal`). On abort the streaming seam returns the text streamed so
1116
+ * far rather than rejecting, so a barge-in can persist the spoken prefix.
1117
+ * The durable (non-streaming) loop never sets it.
1118
+ */
1119
+ signal?: AbortSignal;
1120
+ /** A per-turn tool-choice override. */
1121
+ toolChoice?: ToolChoice<ToolSet>;
1122
+ }
1123
+ /**
1124
+ * The LLM-turn seam: given the assembled conversation, return the model's
1125
+ * decision. Production wires AI SDK `generateText`; tests inject a script.
1126
+ * @experimental
1127
+ */
1128
+ type AgentGenerate = (options: AgentGenerateOptions) => Promise<AgentGenerateResult>;
1129
+ /**
1130
+ * The entities and relations extracted from one run's exchange, upserted into
1131
+ * the owner-scoped graph. Endpoint names in `relations` reference entities by
1132
+ * name (normalized on write); `confidence` (0..1) seeds an edge's weight.
1133
+ */
1134
+ interface AgentGraphExtraction {
1135
+ entities: ReadonlyArray<{
1136
+ name: string;
1137
+ type?: string;
1138
+ }>;
1139
+ relations: ReadonlyArray<{
1140
+ confidence?: number;
1141
+ dst: string;
1142
+ label: string;
1143
+ src: string;
1144
+ }>;
1145
+ }
1146
+ /**
1147
+ * The run-end graph-extraction seam: given the run's exchange (user input +
1148
+ * final answer) and the model to run it on, return the extracted entities and
1149
+ * relations. Production wires AI SDK `generateObject` over a fixed schema
1150
+ * (`createGraphExtract`); the durable loop calls it inside a memoized
1151
+ * `memory:extract` step so the model never re-runs on replay. Absent (the
1152
+ * default) disables extraction, so an agent with no graph memory — and every
1153
+ * unit test that doesn't opt in — is byte-identical.
1154
+ */
1155
+ type AgentGraphExtract = (input: {
1156
+ /** The run's final assistant answer. */
1157
+ assistantText: string;
1158
+ /** The Worker env, for resolving a Workers AI model id. */
1159
+ env: Record<string, unknown>;
1160
+ /** The extraction model (the source's `extractionModel`, else the agent's). */
1161
+ model: AgentModelInput;
1162
+ /** The user message that started the run. */
1163
+ userInput: string;
1164
+ }) => Promise<AgentGraphExtraction>;
1165
+ /**
1166
+ * The history-compaction seam: given the OLDER model messages to condense (and
1167
+ * the model to run it on), return a summary brief. Production wires AI SDK
1168
+ * `generateText` (`createCompact`); the loop calls it INSIDE the turn's memoized
1169
+ * `llm:turn:N` step so the summarization is replay-safe. Absent (the default)
1170
+ * disables compaction, so an agent with no `compaction` config — and every unit
1171
+ * test that doesn't opt in — is byte-identical.
1172
+ */
1173
+ type AgentCompact = (input: {
1174
+ /** The Worker env, for resolving a Workers AI model id. */
1175
+ env: Record<string, unknown>;
1176
+ /** The older conversation messages to summarize (already assembled). */
1177
+ messages: ModelMessage[];
1178
+ /** The compaction model (the config's `model`, else the agent's). */
1179
+ model: AgentModelInput;
1180
+ }) => Promise<string>;
1181
+ /** The one-line summary an episodic-memory run records for later recency recall. */
1182
+ interface AgentEpisodeExtraction {
1183
+ summary: string;
1184
+ }
1185
+ /**
1186
+ * The run-end episode-extraction seam: given the run's exchange and the model to
1187
+ * run it on, return a one/two-sentence summary. Production wires AI SDK
1188
+ * `generateText` (`createEpisodeExtract`); the durable loop calls it inside a
1189
+ * memoized `memory:episode` step so the model never re-runs on replay. Absent
1190
+ * (the default) disables extraction, so an agent with no episodic memory — and
1191
+ * every unit test that doesn't opt in — is byte-identical.
1192
+ */
1193
+ type AgentEpisodeExtract = (input: {
1194
+ /** The run's final assistant answer. */
1195
+ assistantText: string;
1196
+ /** The Worker env, for resolving a Workers AI model id. */
1197
+ env: Record<string, unknown>;
1198
+ /** The extraction model (the source's `extractionModel`, else the agent's). */
1199
+ model: AgentModelInput;
1200
+ /** The user message that started the run. */
1201
+ userInput: string;
1202
+ }) => Promise<AgentEpisodeExtraction>;
1203
+ /**
1204
+ * A live token delta produced while a turn streams. Ephemeral — deltas are
1205
+ * pushed to the sink as the model generates and are NEVER replayed (the
1206
+ * persisted assistant message is the single source of truth). Keyed by
1207
+ * `threadKey` + the zero-based `turn` so a client can correlate a delta to the
1208
+ * in-flight turn.
1209
+ * @experimental
1210
+ */
1211
+ interface AgentTokenDelta {
1212
+ /**
1213
+ * Discriminates the token arm of {@link AgentLiveEvent}. Optional and left
1214
+ * unset on the wire (a token is the default) so the existing emit site and
1215
+ * its structural test assertions stay byte-identical; narrow the union with
1216
+ * `event.kind === "progress"` to isolate the {@link AgentProgressEvent} arm.
1217
+ */
1218
+ kind?: "token";
1219
+ /** The incremental text chunk the model just produced. */
1220
+ text: string;
1221
+ /** The thread this delta belongs to. */
1222
+ threadKey: string;
1223
+ /** The zero-based index of the turn producing the delta. */
1224
+ turn: number;
1225
+ }
1226
+ /**
1227
+ * A live, ephemeral progress event a tool emits via
1228
+ * {@link AgentToolContext.reportProgress} while its durable step runs. Rides the
1229
+ * SAME live-only sink as {@link AgentTokenDelta} — NEVER persisted, NEVER
1230
+ * replayed. Correlated to the in-flight tool call (and its persisted tool row)
1231
+ * by `toolCallId` rather than a turn index, since a single turn can fan out many
1232
+ * tool calls.
1233
+ * @experimental
1234
+ */
1235
+ interface AgentProgressEvent {
1236
+ /** The arbitrary, JSON-serializable payload the tool reported. */
1237
+ data: unknown;
1238
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
1239
+ kind: "progress";
1240
+ /** The thread this event belongs to. */
1241
+ threadKey: string;
1242
+ /** The tool call this progress belongs to (correlates with the persisted tool row). */
1243
+ toolCallId: string;
1244
+ }
1245
+ /**
1246
+ * A single event on the agent's live-only channel: either a streamed token
1247
+ * {@link AgentTokenDelta} (turn-keyed) or a tool {@link AgentProgressEvent}
1248
+ * (`toolCallId`-keyed). Both are ephemeral and never replayed — the persisted
1249
+ * thread messages remain the single source of truth. Discriminate on `kind`
1250
+ * (`"progress"` for the progress arm; token deltas leave it unset).
1251
+ * @experimental
1252
+ */
1253
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
1254
+ /**
1255
+ * A live-only sink for the agent's ephemeral channel — streamed token deltas
1256
+ * ({@link AgentTokenDelta}) and tool progress events
1257
+ * ({@link AgentProgressEvent}). The runtime provides it (teeing to the existing
1258
+ * stream transport); tests capture it. Invoked ONLY on the first execution of a
1259
+ * turn's / tool's durable step — a workflow replay serves the memoized result
1260
+ * without re-running the body, so no event is re-emitted.
1261
+ *
1262
+ * At-least-once caveat: if a turn's step *fails mid-stream* (before it commits)
1263
+ * the workflow retries the not-yet-memoized step and re-tees that turn's deltas
1264
+ * from scratch. This is the standard durable-step retry contract, not a replay
1265
+ * of a completed turn. Consumers should therefore reset/dedupe accumulated text
1266
+ * per `threadKey`+`turn` boundary so a step retry cannot visually double-append;
1267
+ * the persisted assistant message remains the single source of truth.
1268
+ * @experimental
1269
+ */
1270
+ type AgentTokenSink = (event: AgentLiveEvent) => void;
1271
+ /**
1272
+ * The streaming LLM-turn seam: like {@link AgentGenerate} but tees each text
1273
+ * delta to `onDelta` as the model produces it, then resolves the SAME
1274
+ * {@link AgentGenerateResult} the non-streaming seam returns — so the value the
1275
+ * durable `llm:turn:N` step memoizes (and persists) is identical whether the
1276
+ * turn streamed or not. Production wires AI SDK `streamText`; tests inject a
1277
+ * script. Deltas are live-only — a workflow replay never re-invokes the seam.
1278
+ * @experimental
1279
+ */
1280
+ type AgentStreamGenerate = (options: AgentGenerateOptions, onDelta: (text: string) => void) => Promise<AgentGenerateResult>;
1281
+ /**
1282
+ * Spec entry codegen emits per agent: `{ className: "SupportAgentWorkflow", exportName: "support" }`.
1283
+ * @experimental
1284
+ */
1285
+ interface AgentBindingSpec {
1286
+ /** The agent's export key — its generated class name, e.g. `SupportAgentWorkflow`. */
1287
+ className: string;
1288
+ exportName: string;
1289
+ /**
1290
+ * Whether the app author opted this agent into public run-starts (via
1291
+ * `defineAgent({ publicRun: true })`) — codegen emits it only when `true`.
1292
+ * Carried onto the {@link AgentHandle} so the public `agents:agentRun`
1293
+ * mutation gates on it fail-closed: an agent without it can be started only
1294
+ * from server-side app code, never by an external RPC client.
1295
+ */
1296
+ publicRun?: boolean;
1297
+ }
1298
+ /**
1299
+ * The lifecycle status stored on an agent thread: `"running"` while a run is in
1300
+ * flight, `"idle"` after it finishes (or stops on a condition), `"error"` on a
1301
+ * terminal failure, `"cancelled"` when a run was terminated via
1302
+ * {@link AgentHandle.cancel}, and `"awaiting_input"` while the run is paused on
1303
+ * a human-in-the-loop tool approval. Mirrored by the `status` `v.union` in
1304
+ * `component.ts`.
1305
+ * @experimental
1306
+ */
1307
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
1308
+ /**
1309
+ * Structural subset of a Cloudflare Workflow instance the producer surface needs.
1310
+ * @experimental
1311
+ */
1312
+ interface AgentWorkflowInstanceLike {
1313
+ /** Deliver an external event to the running instance (resumes a `waitForEvent`). */
1314
+ sendEvent: (event: {
1315
+ payload: unknown;
1316
+ type: string;
1317
+ }) => Promise<void>;
1318
+ status: () => Promise<unknown>;
1319
+ terminate: () => Promise<void>;
1320
+ }
1321
+ /**
1322
+ * Structural subset of a Cloudflare Workflow binding the producer surface needs.
1323
+ * @experimental
1324
+ */
1325
+ interface AgentWorkflowBindingLike {
1326
+ create: (options?: {
1327
+ id?: string;
1328
+ params?: unknown;
1329
+ }) => Promise<{
1330
+ id: string;
1331
+ }>;
1332
+ get: (id: string) => Promise<AgentWorkflowInstanceLike>;
1333
+ }
1334
+ /**
1335
+ * A started agent run (a workflow instance).
1336
+ * @experimental
1337
+ */
1338
+ interface AgentRunHandle {
1339
+ /** The workflow instance id. */
1340
+ id: string;
1341
+ }
1342
+ /**
1343
+ * The `ctx.agents.<name>` producer handle.
1344
+ * @experimental
1345
+ */
1346
+ interface AgentHandle {
1347
+ /**
1348
+ * Cancel a run by its workflow instance id: terminate the instance and mark
1349
+ * its thread `"cancelled"`. Safe to call on an already-finished run.
1350
+ */
1351
+ cancel: (id: string) => Promise<void>;
1352
+ /**
1353
+ * Whether this agent may be started over the PUBLIC `agents:agentRun`
1354
+ * mutation (the `defineAgent({ publicRun: true })` opt-in, carried from the
1355
+ * codegen wiring spec). `false` by default — the run mutation refuses it
1356
+ * fail-closed, so declaring an agent never exposes it to arbitrary RPC
1357
+ * callers. Does not affect the server-side `run(...)` path below.
1358
+ */
1359
+ publicRun: boolean;
1360
+ /** Start a durable agent run for a thread. */
1361
+ run: (input: AgentRunInput, options?: {
1362
+ id?: string;
1363
+ }) => Promise<AgentRunHandle>;
1364
+ /**
1365
+ * Deliver an external event to a run by its workflow instance id — the path
1366
+ * `agents:agentResolveApproval` uses to resume a run paused on a
1367
+ * human-in-the-loop tool approval.
1368
+ */
1369
+ sendEvent: (id: string, event: {
1370
+ payload: unknown;
1371
+ type: string;
1372
+ }) => Promise<void>;
1373
+ /** Read a run's workflow status by instance id. */
1374
+ status: (id: string) => Promise<unknown>;
1375
+ }
1376
+ export { AgentUsage as $, AgentDefinition as A, AgentApprovalContext as B, AgentEmailMapper as C, AgentEmailRun as D, AgentGenerateOptions as E, AgentGenerateResult as F, AgentInstructionsContext as G, AgentLiveEvent as H, InboundChannelEvent as I, AgentMemoryOptions as J, AgentMemorySource as K, AgentMessageStatus as L, AgentOnReply as M, AgentOnStepFinish as N, AgentPrepareStep as O, AgentPrepareStepInput as P, AgentPrepareStepResult as Q, AgentProgressEvent as R, SkillMarkdownExtras as S, AgentReplyInfo as T, AgentRunHandle as U, AgentRunOptions as V, AgentStepFinishInfo as W, AgentStepInfo as X, AgentThreadStatus as Y, AgentTokenDelta as Z, AgentToolCall as _, AgentReplyRef as a, AgentVoiceConfig as a0, AgentWorkflowBindingLike as a1, AgentWorkflowInstanceLike as a2, EnsureThreadOutcome as a3, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentBindingSpec as u, AgentHandle as v, AgentToolConfig as w, AgentFunctionReference as x, AgentModelInput as y, SkillConfig as z };