@lunora/agent 1.0.0-alpha.14 → 1.0.0-alpha.141

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 (88) hide show
  1. package/dist/channels.d.mts +3 -11
  2. package/dist/channels.d.ts +3 -11
  3. package/dist/channels.mjs +1 -1
  4. package/dist/component.d.mts +2 -0
  5. package/dist/component.d.ts +2 -0
  6. package/dist/component.mjs +2 -2
  7. package/dist/inbound.d.mts +7 -5
  8. package/dist/inbound.d.ts +7 -5
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +50 -9
  11. package/dist/index.d.ts +50 -9
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.mjs +1 -1
  14. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  15. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs +1 -0
  16. package/dist/packem_shared/VoiceSessionDO-BkPBpwRR.mjs +1 -0
  17. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  18. package/dist/packem_shared/agent-loop-CR27O7MC.mjs +3 -0
  19. package/dist/packem_shared/agentAsTool-CgZb6ycK.mjs +1 -0
  20. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  21. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  22. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  23. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  24. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  25. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  26. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  27. package/dist/packem_shared/compileAgentWorkflow-D3BN5OWk.mjs +1 -0
  28. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  29. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  30. package/dist/packem_shared/createAgentContext-BVy7RzqD.mjs +1 -0
  31. package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
  32. package/dist/packem_shared/defineAgent-uEeT0WuM.mjs +3 -0
  33. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  34. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  35. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  36. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  37. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  38. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  39. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  40. package/dist/packem_shared/runAgentLoop-Dg1GXqsX.mjs +1 -0
  41. package/dist/packem_shared/runVoiceTurn-Bs47Kfx2.mjs +1 -0
  42. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  43. package/dist/packem_shared/sandboxComponent-CKX-iNXC.mjs +7 -0
  44. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  45. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  46. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-B_VV-x4x.d.mts} +282 -23
  47. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-B_VV-x4x.d.ts} +282 -23
  48. package/dist/packem_shared/voice-turn-7a1NoDHS.mjs +1 -0
  49. package/dist/reply.d.mts +40 -0
  50. package/dist/reply.d.ts +40 -0
  51. package/dist/reply.mjs +1 -0
  52. package/dist/sandbox.d.mts +62 -16
  53. package/dist/sandbox.d.ts +62 -16
  54. package/dist/sandbox.mjs +1 -1
  55. package/dist/skill-markdown.d.mts +36 -0
  56. package/dist/skill-markdown.d.ts +36 -0
  57. package/dist/skill-markdown.mjs +1 -0
  58. package/dist/telemetry/index.d.mts +152 -33
  59. package/dist/telemetry/index.d.ts +152 -33
  60. package/dist/telemetry/index.mjs +1 -1
  61. package/package.json +18 -9
  62. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  63. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  64. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  65. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  66. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  67. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  68. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  69. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  70. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  71. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  72. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  73. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  74. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  75. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  76. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  77. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  78. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  79. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  80. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  81. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  82. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  83. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  84. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  85. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  86. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  87. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  88. package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
@@ -9,11 +9,33 @@ import { FlexibleSchema, LanguageModel, ModelMessage, ToolSet, ToolChoice, ToolC
9
9
  interface AgentFunctionReference {
10
10
  __lunoraRef: string;
11
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
+ }
12
34
  /**
13
35
  * `ctx.run`-shaped dispatcher the loop uses to call Lunora functions.
14
36
  * @experimental
15
37
  */
16
- type AgentRunFunction = (reference: AgentFunctionReference, args?: Record<string, unknown>) => Promise<unknown>;
38
+ type AgentRunFunction = (reference: AgentFunctionReference, args?: Record<string, unknown>, options?: AgentRunOptions) => Promise<unknown>;
17
39
  /**
18
40
  * Structural subset of the Cloudflare Workflows durable-step API the loop needs.
19
41
  * @experimental
@@ -23,7 +45,7 @@ interface AgentStepLike {
23
45
  /**
24
46
  * Durably hibernate until an external event of `type` arrives, then return
25
47
  * its payload. Used for human-in-the-loop approvals: a run pauses on
26
- * `approval:&lt;toolCallId>` until a client resolves it. Like `do`, a resolved
48
+ * `approval:<toolCallId>` until a client resolves it. Like `do`, a resolved
27
49
  * wait is memoized — a replay returns the recorded decision without pausing
28
50
  * again. Signature mirrors `@lunora/workflow`'s `WorkflowStepLike`.
29
51
  */
@@ -42,13 +64,26 @@ interface AgentStepLike {
42
64
  * `idempotencyKey`.
43
65
  *
44
66
  * The `idempotencyKey` is the deterministic durable-step name
45
- * (`tool:&lt;name>:&lt;toolCallId>`). A COMPLETED tool step is never re-run on a
46
- * workflow replay (native step memoization) — but a step that FAILS mid-body
47
- * is retried at-least-once, so a side-effecting tool (charge a card, send a
48
- * mail) must dedupe on this key itself.
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).
49
77
  * @experimental
50
78
  */
51
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;
52
87
  /** The Worker environment bindings. */
53
88
  env: Record<string, unknown>;
54
89
  /**
@@ -67,6 +102,14 @@ interface AgentToolContext {
67
102
  getState: () => Promise<Record<string, unknown> | undefined>;
68
103
  /** Deterministic idempotency key — the tool's durable-step name. */
69
104
  idempotencyKey: string;
105
+ /**
106
+ * Verified owner of the thread this run belongs to (the loop copies it off
107
+ * {@link AgentRunInput.owner}); `undefined` on an anonymous/single-tenant
108
+ * thread. `agent.asTool` forwards it to the CHILD run, so a sub-agent thread
109
+ * under an owned parent inherits the same RLS scope instead of being created
110
+ * ownerless — which left it readable by anyone who knew its key.
111
+ */
112
+ owner?: string;
70
113
  /**
71
114
  * Emit an EPHEMERAL progress event for this tool call on the agent's live
72
115
  * channel — the same live-only sink the streamed token deltas ride. NOT
@@ -102,11 +145,45 @@ interface AgentToolContext {
102
145
  * skip the write when it is already present.
103
146
  */
104
147
  setState: (state: Record<string, unknown>) => Promise<void>;
148
+ /**
149
+ * The durable-step handle (`step.do`/`waitForEvent`). ALWAYS present:
150
+ * `agent-loop.ts` threads it into every tool's context unconditionally, and
151
+ * it is required rather than optional so a missing handle is a compile
152
+ * error instead of a silent durability downgrade. `codeTool` uses it to give
153
+ * each script step its OWN nested durable boundary — see `code-tool.ts` — so
154
+ * a failure at script step 3 retries only step 3, not steps 1–2's
155
+ * already-committed side effects. Cloudflare Workflows supports a `step.do`
156
+ * nested inside another `step.do`'s callback (the codeTool call's own
157
+ * enclosing step). Most tools never touch this directly; a test driving
158
+ * `execute`/`runToolScript` by hand passes a pass-through double.
159
+ */
160
+ step: AgentStepLike;
105
161
  /** The thread this tool call belongs to. */
106
162
  threadKey: string;
107
163
  /** The provider-issued tool-call id. */
108
164
  toolCallId: string;
109
165
  }
166
+ /**
167
+ * The view of {@link AgentToolContext} handed to a `needsApproval` gate
168
+ * function — every field except `setState`, `step`, and `reportProgress`.
169
+ *
170
+ * `setState` is dropped because a gate that mutates thread state is a side
171
+ * effect inside a decision predicate, and `reportProgress` because emitting a
172
+ * live event is the same thing in observable form — the decision is what the
173
+ * loop reports, not the deciding. `step` goes because the loop already runs the
174
+ * gate inside a durable step of its own, so a gate has no business opening
175
+ * another.
176
+ *
177
+ * `getState` and `run` stay: reads are legitimate gate inputs (gate on the
178
+ * caller's plan tier, on a spend total), and the gate resolves inside its own
179
+ * durable step, so they are replay-safe there. Note this makes the type a
180
+ * NARROWING, not a proof of purity — `run` takes any
181
+ * {@link AgentFunctionReference}, so a gate can still dispatch a mutation
182
+ * before approval. Nothing in the type system distinguishes a query reference
183
+ * from a mutation one; keeping the gate side-effect-free is the author's.
184
+ * @experimental
185
+ */
186
+ type AgentApprovalContext = Omit<AgentToolContext, "reportProgress" | "setState" | "step">;
110
187
  /**
111
188
  * An agent tool. Unlike a raw AI SDK tool, `execute` is NOT handed to the
112
189
  * model call — the loop runs it itself inside a named durable step so a
@@ -127,17 +204,25 @@ interface AgentToolDefinition<Input = unknown, Output = unknown> {
127
204
  * Gate the tool behind a human approval (mirrors the AI SDK's
128
205
  * `needsApproval`). When it resolves truthy the durable run PAUSES — the
129
206
  * thread moves to `"awaiting_input"` and the workflow hibernates on
130
- * `approval:&lt;toolCallId>` — until a client calls `agents:agentResolveApproval`.
207
+ * `approval:<toolCallId>` — until a client calls `agents:agentResolveApproval`.
131
208
  * On approve the tool runs exactly as normal; on reject it is skipped and a
132
209
  * tool result explaining the rejection is persisted so the next turn recovers.
133
210
  * A boolean gates statically; a function gates per input. Default: `false`
134
- * (unchanged behavior). Evaluated from replay-stable input OUTSIDE the
135
- * durable step (it re-runs on every replay), so it must be a PURE predicate:
136
- * deterministic (no `Date.now()`/`Math.random()`) and free of side effects —
137
- * never call {@link AgentToolContext.setState}/`getState` or a mutating `run`
138
- * here; state writes belong only in `execute`, inside the memoized step.
211
+ * (unchanged behavior).
212
+ *
213
+ * The boolean/`undefined` forms are compile-time constants re-derived
214
+ * identically on every replay — no durable step. The FUNCTION form runs
215
+ * inside its OWN durable step (`tool:approval-gate:<toolCallId>`, distinct
216
+ * from the tool's own step), so it now runs exactly once per call, not once
217
+ * per replay. It must still be otherwise pure: deterministic given its
218
+ * inputs (no `Date.now()`/`Math.random()`) and free of side effects — the
219
+ * context it receives is {@link AgentApprovalContext}, which has neither
220
+ * `setState` nor `reportProgress`; state writes and progress events belong
221
+ * only in `execute`, inside the tool's own memoized step. It still holds
222
+ * `run`, which the type cannot narrow to reads — see
223
+ * {@link AgentApprovalContext}.
139
224
  */
140
- needsApproval?: ((input: Input, context: AgentToolContext) => boolean | Promise<boolean>) | boolean;
225
+ needsApproval?: ((input: Input, context: AgentApprovalContext) => boolean | Promise<boolean>) | boolean;
141
226
  }
142
227
  /**
143
228
  * Author-supplied tool config (see {@link AgentToolDefinition}).
@@ -252,7 +337,7 @@ interface AgentMemoryOptions {
252
337
  * (`key: "default"`) from {@link AgentConfig.memory}, then one per skill that
253
338
  * carries `knowledge` (keyed by the skill's name). The key names the durable
254
339
  * step — the default source keeps the historic `"memory:retrieve"`, a skill
255
- * source uses `"memory:retrieve:&lt;key>"` — so replay stays deterministic.
340
+ * source uses `"memory:retrieve:<key>"` — so replay stays deterministic.
256
341
  * @experimental
257
342
  */
258
343
  interface AgentMemorySource extends AgentMemoryOptions {
@@ -308,7 +393,7 @@ interface SkillConfig {
308
393
  knowledge?: AgentMemoryOptions;
309
394
  /**
310
395
  * The skill's identifier — namespaces this skill's `knowledge` memory source
311
- * (the durable step `memory:retrieve:&lt;name>`). Must be identifier-shaped.
396
+ * (the durable step `memory:retrieve:<name>`). Must be identifier-shaped.
312
397
  */
313
398
  name: string;
314
399
  /**
@@ -318,6 +403,12 @@ interface SkillConfig {
318
403
  */
319
404
  tools?: Record<string, AnyAgentTool>;
320
405
  }
406
+ /**
407
+ * The code-side parts of a markdown-authored skill — everything `SKILL.md`
408
+ * cannot carry. `name` and `instructions` come from the file itself.
409
+ * @experimental
410
+ */
411
+ type SkillMarkdownExtras = Omit<SkillConfig, "instructions" | "name">;
321
412
  /**
322
413
  * A `defineSkill` result — config plus the brand the agent merge checks.
323
414
  * @experimental
@@ -358,11 +449,43 @@ interface AgentStepFinishInfo {
358
449
  }
359
450
  /**
360
451
  * Called after each LLM turn with that turn's text, tool calls, and usage. Runs
361
- * inside a named durable step (`agent:step-finish:&lt;turn>`) so it fires exactly
452
+ * inside a named durable step (`agent:step-finish:<turn>`) so it fires exactly
362
453
  * once per turn even across a workflow replay.
363
454
  * @experimental
364
455
  */
365
456
  type AgentOnStepFinish = (info: AgentStepFinishInfo) => Promise<void> | void;
457
+ /**
458
+ * What {@link AgentConfig.onReply} is called with when a triggered run reaches
459
+ * its final answer.
460
+ * @experimental
461
+ */
462
+ interface AgentReplyInfo {
463
+ /** The worker `env` — where an outbound credential (a bot token, a mailer binding) lives. */
464
+ env: Record<string, unknown>;
465
+ /** Where to reply, captured by the mapper that started this run. */
466
+ replyRef: AgentReplyRef;
467
+ /** The run's final answer. */
468
+ result: AgentRunResult;
469
+ /** The thread this run belongs to. */
470
+ threadKey: string;
471
+ }
472
+ /**
473
+ * Send a triggered run's answer back where it came from — the outbound half of
474
+ * an `onEmail` / `onInbound` trigger.
475
+ *
476
+ * Called once, automatically, when a run started with a `replyRef` produces a
477
+ * final answer; a run without one (an ordinary in-app `ctx.agents.<name>.run`)
478
+ * never calls it. It runs inside a named durable step, so a transient failure
479
+ * is retried and a workflow replay does not send the answer twice.
480
+ *
481
+ * Delivery is the app's call, because only the app has the credential: email
482
+ * has a home already (`replyToEmail(mailer, ref, body)` from
483
+ * `@lunora/agent/reply`), while Slack/GitHub/Discord bot tokens have no
484
+ * framework-owned store yet — read them from `info.env` and make the provider
485
+ * call.
486
+ * @experimental
487
+ */
488
+ type AgentOnReply = (info: AgentReplyInfo) => Promise<void> | void;
366
489
  /**
367
490
  * The input {@link AgentConfig.prepareStep} sees before a turn runs.
368
491
  * @experimental
@@ -404,6 +527,39 @@ type AgentPrepareStep = (input: AgentPrepareStepInput) => AgentPrepareStepResult
404
527
  * start a run from an inbound email.
405
528
  * @experimental
406
529
  */
530
+ /**
531
+ * Where a triggered run should send its answer back to — captured by the
532
+ * mapper, from fields the verified inbound payload already carries, and carried
533
+ * through the run so {@link AgentConfig.onReply} can answer in the same place
534
+ * the question was asked.
535
+ *
536
+ * A discriminated union rather than an opaque blob because each channel threads
537
+ * differently: email by RFC 5322 `In-Reply-To`/`References`, Slack by
538
+ * `thread_ts`, GitHub by issue number, Discord by channel (plus the triggering
539
+ * message for a true reply).
540
+ * @experimental
541
+ */
542
+ type AgentReplyRef = {
543
+ channel: "discord";
544
+ channelId: string;
545
+ messageId?: string;
546
+ } | {
547
+ channel: "email";
548
+ from: string;
549
+ messageId: string;
550
+ references?: string;
551
+ to: string[];
552
+ } | {
553
+ channel: "github";
554
+ commentId?: number;
555
+ issueNumber: number;
556
+ owner: string;
557
+ repo: string;
558
+ } | {
559
+ channel: "slack";
560
+ channelId: string;
561
+ threadTs: string;
562
+ };
407
563
  interface AgentEmailRun {
408
564
  /** The user message that starts (or continues) the thread — the model's prompt. */
409
565
  input: string;
@@ -414,6 +570,13 @@ interface AgentEmailRun {
414
570
  * `email.from`.
415
571
  */
416
572
  owner?: string;
573
+ /**
574
+ * Where to send the answer — see {@link AgentReplyRef}. Populate it from the
575
+ * event the mapper already has (`captureEmailReplyRef(email)` does it for
576
+ * email) and the run calls {@link AgentConfig.onReply} with it once the
577
+ * final answer is ready. Omit it and the run simply never replies.
578
+ */
579
+ replyRef?: AgentReplyRef;
417
580
  /** The thread key — reuse to continue a conversation (e.g. a ticket id parsed from the subject). */
418
581
  threadKey: string;
419
582
  /** Optional thread title, set on first creation. */
@@ -484,6 +647,22 @@ interface AgentInboundChannel {
484
647
  interface AgentConfig {
485
648
  /** Restrict the tools the model may call, by name. Default: all tools. */
486
649
  activeTools?: ReadonlyArray<string>;
650
+ /**
651
+ * How long a human-in-the-loop tool approval may stay pending before the
652
+ * run stops waiting — a Cloudflare Workflows duration: milliseconds, or a
653
+ * `"<n> <unit>"` string like `"3 days"` (the unit set is the host's, so a
654
+ * typo is a compile error). Default `"3 days"`.
655
+ *
656
+ * On timeout the call is treated as REJECTED (the run records why and
657
+ * continues down the normal rejection path), so a run whose approver never
658
+ * answers ends instead of hibernating forever.
659
+ *
660
+ * CLAMPED to one week. A longer wait would outlive the thread's
661
+ * abandoned-run horizon, letting a new run reclaim the thread while the
662
+ * approval is still pending — which is the exact failure this timeout
663
+ * exists to prevent, so it cannot be configured back into existence.
664
+ */
665
+ approvalTimeout?: `${number} ${"day" | "hour" | "minute" | "month" | "second" | "week" | "year"}${"s" | ""}` | number;
487
666
  /**
488
667
  * Automatic thread-history compaction. When the persisted history exceeds
489
668
  * `maxMessages`, the loop summarizes the older messages (all but the most
@@ -530,7 +709,7 @@ interface AgentConfig {
530
709
  model: AgentModelInput;
531
710
  /**
532
711
  * Optional override for the deployed workflow name (`wrangler.jsonc`
533
- * `workflows[].name`). Defaults to `agent-&lt;kebab-cased export name>`. Does
712
+ * `workflows[].name`). Defaults to `agent-<kebab-cased export name>`. Does
534
713
  * NOT change the binding name, which is always derived from the export
535
714
  * name (`support` → `AGENT_SUPPORT`).
536
715
  */
@@ -543,7 +722,16 @@ interface AgentConfig {
543
722
  *
544
723
  * - `"reject"` (default) — fail the new run fast with a `CONFLICT` error.
545
724
  * - `"replace"` — terminate the in-flight instance and take the thread over.
546
- * - `"queue"` — reserved for a future durable queue; currently degrades to `"reject"` (no queue exists yet), tracked as a follow-up.
725
+ * - `"queue"` — park the new run behind the one in flight (FIFO, up to five deep) and hibernate it until the thread is handed over.
726
+ *
727
+ * Each parked run is a live workflow instance waiting on an event, so the
728
+ * queue's depth cap is a real resource bound: past it, a start is rejected
729
+ * exactly as `"reject"` would. A `"replace"` arriving later supersedes the
730
+ * run in FLIGHT, not the queue — parked runs still take their turn after it.
731
+ *
732
+ * A dispatch with no instance id (the inbound-email / inbound-channel
733
+ * paths) cannot be parked, because nothing later can tell it apart from
734
+ * another such dispatch to wake it; `"queue"` rejects those.
547
735
  *
548
736
  * A workflow REPLAY re-enters the bootstrap under the SAME instance id and
549
737
  * is never a concurrent run (the guard compares the stored instance id).
@@ -563,6 +751,12 @@ interface AgentConfig {
563
751
  * signature over the raw body before calling `map`.
564
752
  */
565
753
  onInbound?: AgentInboundChannel;
754
+ /**
755
+ * Called with the final answer when the run was triggered from a channel
756
+ * that gave it a `replyRef` — see {@link AgentOnReply}. This is how an
757
+ * inbound-triggered agent answers where it was asked.
758
+ */
759
+ onReply?: AgentOnReply;
566
760
  /** Called after each LLM turn — see {@link AgentOnStepFinish}. */
567
761
  onStepFinish?: AgentOnStepFinish;
568
762
  /**
@@ -577,7 +771,7 @@ interface AgentConfig {
577
771
  * Opt this agent into being STARTED over the public RPC boundary — i.e. via
578
772
  * the auto-registered `agents:agentRun` mutation an HTTP-only client (e.g.
579
773
  * the `@lunora/mcp` server) calls. Default `false`: an agent is startable
580
- * only from server-side app code (`ctx.agents.&lt;name>.run(...)`), so declaring
774
+ * only from server-side app code (`ctx.agents.<name>.run(...)`), so declaring
581
775
  * an agent does NOT expose it to arbitrary RPC callers. Fail-closed — the run
582
776
  * mutation refuses an agent that has not opted in, regardless of any MCP-side
583
777
  * `allowAgents` configuration. A started thread is still owner-scoped to
@@ -649,8 +843,20 @@ interface AgentVoiceConfig {
649
843
  /**
650
844
  * Spoken on connect before the first user turn — a fixed greeting synthesized
651
845
  * through the TTS model. Omit for a silent-until-spoken-to session.
846
+ *
847
+ * Synthesized once per THREAD, not once per socket: the greeting's persisted
848
+ * row is keyed per thread, and a reconnect onto a thread that already exists
849
+ * gets the `ready` frame without paying for the same line again.
652
850
  */
653
851
  greeting?: string;
852
+ /**
853
+ * Cap on how many turns one voice socket may run before it is closed with
854
+ * code `4002`. Every turn is a full LLM generation plus sentence-by-sentence
855
+ * TTS — billed and persisted — on a hibernatable socket that can live for
856
+ * days, and the one-turn-in-flight guard throttles nothing. Defaults to 100;
857
+ * a client that hits the cap reconnects for a fresh budget.
858
+ */
859
+ maxTurns?: number;
654
860
  /**
655
861
  * TTS voice/speaker id forwarded to the TTS model (e.g. a Deepgram Aura voice
656
862
  * like `"aura-asteria-en"`). Model-specific; omitted when unset so the model
@@ -685,10 +891,10 @@ interface AgentSubToolInput {
685
891
  interface AgentAsToolOptions {
686
892
  /** What the sub-agent does — shown to the parent's model (it decides from it). */
687
893
  description: string;
688
- /** Cap on child-run status polls before giving up. Default 120. */
894
+ /** Cap on child-run status polls before giving up — a positive integer. Default 600 (with the 500 ms default interval, a five-minute budget). */
689
895
  maxPolls?: number;
690
896
  /**
691
- * The child agent's export name — selects its `AGENT_&lt;NAME>` Workflow
897
+ * The child agent's export name — selects its `AGENT_<NAME>` Workflow
692
898
  * binding (e.g. `"researcher"` → `AGENT_RESEARCHER`). The model-facing tool
693
899
  * name is the KEY assigned in the parent's `tools` map, not this.
694
900
  */
@@ -725,11 +931,43 @@ interface AgentDefinition extends AgentConfig {
725
931
  */
726
932
  memorySources?: ReadonlyArray<AgentMemorySource>;
727
933
  }
934
+ /**
935
+ * What `agentEnsureThread` reports back to the loop.
936
+ *
937
+ * A discriminated union rather than a bag of optional booleans: the outcomes are
938
+ * mutually exclusive, and the data each carries only exists for its own case.
939
+ * `queued` has a position, `replaced` has the instance it took the thread from,
940
+ * and the rest have nothing — encoding that as independent optional fields made
941
+ * every reader re-derive which combination was legal.
942
+ *
943
+ * `completed` is the odd one: the thread was NOT (re)opened. This run already
944
+ * reported its outcome and is replaying because only the reply was lost, so it
945
+ * takes no ownership and revives nothing — it runs its body out of the step
946
+ * journal to re-dispatch the effects that never landed.
947
+ * @experimental
948
+ */
949
+ type EnsureThreadOutcome = {
950
+ outcome: "completed" | "continued" | "created";
951
+ } | {
952
+ outcome: "queued";
953
+ position: number;
954
+ } | {
955
+ outcome: "replaced";
956
+ priorInstanceId: string;
957
+ };
728
958
  /**
729
959
  * Params of one agent run (the compiled workflow's payload).
730
960
  * @experimental
731
961
  */
732
962
  interface AgentRunInput {
963
+ /**
964
+ * Sub-agent delegation depth. A run a user starts omits it (0); each
965
+ * `agent.asTool` hop stamps its child one deeper, and the tool refuses to
966
+ * delegate past the bound — `maxTurns` bounds one level's turns, this bounds
967
+ * the TREE (every hop mints a distinct child `threadKey`, so the per-thread
968
+ * run-queue cap never applies across them).
969
+ */
970
+ depth?: number;
733
971
  /** The user message that starts (or continues) the thread. */
734
972
  input: string;
735
973
  /**
@@ -741,6 +979,8 @@ interface AgentRunInput {
741
979
  * the first run.
742
980
  */
743
981
  owner?: string;
982
+ /** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
983
+ replyRef?: AgentReplyRef;
744
984
  /** The thread key — reuse to continue a conversation. */
745
985
  threadKey: string;
746
986
  /** Optional thread title, set on first creation. */
@@ -773,6 +1013,17 @@ interface AgentRunResult {
773
1013
  */
774
1014
  interface AgentFunctionPaths {
775
1015
  appendMessage: string;
1016
+ /**
1017
+ * The internal `agents:agentCompleteRun` mutation the loop dispatches at the
1018
+ * end of a run: it writes the terminal status AND hands the thread to the
1019
+ * next queued run in the same mutation.
1020
+ */
1021
+ completeRun: string;
1022
+ /**
1023
+ * The internal `agents:agentDeleteMessage` mutation the loop dispatches to
1024
+ * retire the HITL approval marker once the decision has landed.
1025
+ */
1026
+ deleteMessage: string;
776
1027
  ensureThread: string;
777
1028
  /** The internal `agents:agentEpisodeRecall` query the loop dispatches for an episodic-kind read. */
778
1029
  episodeRecall: string;
@@ -824,6 +1075,14 @@ interface AgentMessageRow {
824
1075
  interface AgentToolCall {
825
1076
  id: string;
826
1077
  input: unknown;
1078
+ /**
1079
+ * Why this call was REJECTED before it could run: the model's arguments
1080
+ * failed the tool's input schema, or did not parse as JSON. Present only on
1081
+ * a rejected call — the loop records it as a recoverable tool result and
1082
+ * never executes the tool, because the `input` above is the raw value the
1083
+ * provider sent, not a validated one.
1084
+ */
1085
+ invalid?: string;
827
1086
  name: string;
828
1087
  }
829
1088
  /**
@@ -1078,7 +1337,7 @@ interface AgentRunHandle {
1078
1337
  id: string;
1079
1338
  }
1080
1339
  /**
1081
- * The `ctx.agents.&lt;name>` producer handle.
1340
+ * The `ctx.agents.<name>` producer handle.
1082
1341
  * @experimental
1083
1342
  */
1084
1343
  interface AgentHandle {
@@ -1111,4 +1370,4 @@ interface AgentHandle {
1111
1370
  /** Read a run's workflow status by instance id. */
1112
1371
  status: (id: string) => Promise<unknown>;
1113
1372
  }
1114
- export { AgentDefinition as A, AgentGenerateOptions as B, AgentGenerateResult as C, AgentInstructionsContext as D, AgentLiveEvent as E, AgentMemoryOptions as F, AgentMemorySource as G, AgentMessageStatus as H, InboundChannelEvent as I, AgentOnStepFinish as J, AgentPrepareStep as K, AgentPrepareStepInput as L, AgentPrepareStepResult as M, AgentProgressEvent as N, AgentRunHandle as O, AgentStepFinishInfo as P, AgentStepInfo as Q, AgentThreadStatus as R, SkillDefinition as S, AgentTokenDelta as T, AgentToolCall as U, AgentUsage as V, AgentVoiceConfig as W, AgentWorkflowBindingLike as X, AgentWorkflowInstanceLike as Y, AgentToolContext as a, AgentToolDefinition as b, AgentCompact as c, AgentEpisodeExtract as d, AgentGraphExtract as e, AgentGenerate as f, AgentTokenSink as g, AgentRunInput as h, AgentFunctionPaths as i, AgentRunFunction as j, AgentStepLike as k, AgentStreamGenerate as l, AgentRunResult as m, AgentMessageRow as n, AgentConfig as o, AnyAgentTool as p, AgentAsToolOptions as q, AgentSubToolInput as r, AgentBindingSpec as s, AgentHandle as t, AgentToolConfig as u, AgentFunctionReference as v, AgentModelInput as w, SkillConfig as x, AgentEmailMapper as y, AgentEmailRun as z };
1373
+ 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, AgentToolContext as b, AgentToolDefinition as c, SkillDefinition 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 };