@lunora/agent 1.0.0-alpha.19 → 1.0.0-alpha.190

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 (94) hide show
  1. package/dist/channels.d.mts +23 -12
  2. package/dist/channels.d.ts +23 -12
  3. package/dist/channels.mjs +1 -1
  4. package/dist/component.d.mts +40 -2
  5. package/dist/component.d.ts +40 -2
  6. package/dist/component.mjs +2 -2
  7. package/dist/inbound.d.mts +9 -7
  8. package/dist/inbound.d.ts +9 -7
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +112 -17
  11. package/dist/index.d.ts +112 -17
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.d.mts +3 -7
  14. package/dist/naming.d.ts +3 -7
  15. package/dist/naming.mjs +1 -1
  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-boAM2Yi1.d.mts → types.d-CbYtFBw9.d.mts} +289 -27
  51. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-CbYtFBw9.d.ts} +289 -27
  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 +157 -16
  59. package/dist/sandbox.d.ts +157 -16
  60. package/dist/sandbox.mjs +1 -1
  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 +152 -33
  65. package/dist/telemetry/index.d.ts +152 -33
  66. package/dist/telemetry/index.mjs +1 -1
  67. package/package.json +18 -9
  68. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  69. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  70. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  71. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  72. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  73. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  74. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  75. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  76. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  77. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  78. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  79. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  80. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  81. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  82. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  83. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  84. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  85. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  86. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  87. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  88. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  89. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  90. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  91. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  92. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  93. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  94. 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,15 +64,30 @@ 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>;
89
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes the declared agents (see `agent.asTool`). */
90
+ exports?: unknown;
54
91
  /**
55
92
  * Read the thread's synced state — dispatches the public owner-gated
56
93
  * `agents:agentState` query through {@link AgentToolContext.run} (the same
@@ -67,6 +104,14 @@ interface AgentToolContext {
67
104
  getState: () => Promise<Record<string, unknown> | undefined>;
68
105
  /** Deterministic idempotency key — the tool's durable-step name. */
69
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;
70
115
  /**
71
116
  * Emit an EPHEMERAL progress event for this tool call on the agent's live
72
117
  * channel — the same live-only sink the streamed token deltas ride. NOT
@@ -102,11 +147,45 @@ interface AgentToolContext {
102
147
  * skip the write when it is already present.
103
148
  */
104
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;
105
163
  /** The thread this tool call belongs to. */
106
164
  threadKey: string;
107
165
  /** The provider-issued tool-call id. */
108
166
  toolCallId: string;
109
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">;
110
189
  /**
111
190
  * An agent tool. Unlike a raw AI SDK tool, `execute` is NOT handed to the
112
191
  * model call — the loop runs it itself inside a named durable step so a
@@ -127,17 +206,25 @@ interface AgentToolDefinition<Input = unknown, Output = unknown> {
127
206
  * Gate the tool behind a human approval (mirrors the AI SDK's
128
207
  * `needsApproval`). When it resolves truthy the durable run PAUSES — the
129
208
  * thread moves to `"awaiting_input"` and the workflow hibernates on
130
- * `approval:&lt;toolCallId>` — until a client calls `agents:agentResolveApproval`.
209
+ * `approval:<toolCallId>` — until a client calls `agents:agentResolveApproval`.
131
210
  * On approve the tool runs exactly as normal; on reject it is skipped and a
132
211
  * tool result explaining the rejection is persisted so the next turn recovers.
133
212
  * 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.
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}.
139
226
  */
140
- needsApproval?: ((input: Input, context: AgentToolContext) => boolean | Promise<boolean>) | boolean;
227
+ needsApproval?: ((input: Input, context: AgentApprovalContext) => boolean | Promise<boolean>) | boolean;
141
228
  }
142
229
  /**
143
230
  * Author-supplied tool config (see {@link AgentToolDefinition}).
@@ -252,7 +339,7 @@ interface AgentMemoryOptions {
252
339
  * (`key: "default"`) from {@link AgentConfig.memory}, then one per skill that
253
340
  * carries `knowledge` (keyed by the skill's name). The key names the durable
254
341
  * step — the default source keeps the historic `"memory:retrieve"`, a skill
255
- * source uses `"memory:retrieve:&lt;key>"` — so replay stays deterministic.
342
+ * source uses `"memory:retrieve:<key>"` — so replay stays deterministic.
256
343
  * @experimental
257
344
  */
258
345
  interface AgentMemorySource extends AgentMemoryOptions {
@@ -308,7 +395,7 @@ interface SkillConfig {
308
395
  knowledge?: AgentMemoryOptions;
309
396
  /**
310
397
  * The skill's identifier — namespaces this skill's `knowledge` memory source
311
- * (the durable step `memory:retrieve:&lt;name>`). Must be identifier-shaped.
398
+ * (the durable step `memory:retrieve:<name>`). Must be identifier-shaped.
312
399
  */
313
400
  name: string;
314
401
  /**
@@ -318,6 +405,12 @@ interface SkillConfig {
318
405
  */
319
406
  tools?: Record<string, AnyAgentTool>;
320
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">;
321
414
  /**
322
415
  * A `defineSkill` result — config plus the brand the agent merge checks.
323
416
  * @experimental
@@ -358,11 +451,43 @@ interface AgentStepFinishInfo {
358
451
  }
359
452
  /**
360
453
  * 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
454
+ * inside a named durable step (`agent:step-finish:<turn>`) so it fires exactly
362
455
  * once per turn even across a workflow replay.
363
456
  * @experimental
364
457
  */
365
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;
366
491
  /**
367
492
  * The input {@link AgentConfig.prepareStep} sees before a turn runs.
368
493
  * @experimental
@@ -404,6 +529,39 @@ type AgentPrepareStep = (input: AgentPrepareStepInput) => AgentPrepareStepResult
404
529
  * start a run from an inbound email.
405
530
  * @experimental
406
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
+ };
407
565
  interface AgentEmailRun {
408
566
  /** The user message that starts (or continues) the thread — the model's prompt. */
409
567
  input: string;
@@ -414,6 +572,13 @@ interface AgentEmailRun {
414
572
  * `email.from`.
415
573
  */
416
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;
417
582
  /** The thread key — reuse to continue a conversation (e.g. a ticket id parsed from the subject). */
418
583
  threadKey: string;
419
584
  /** Optional thread title, set on first creation. */
@@ -484,6 +649,22 @@ interface AgentInboundChannel {
484
649
  interface AgentConfig {
485
650
  /** Restrict the tools the model may call, by name. Default: all tools. */
486
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;
487
668
  /**
488
669
  * Automatic thread-history compaction. When the persisted history exceeds
489
670
  * `maxMessages`, the loop summarizes the older messages (all but the most
@@ -530,9 +711,9 @@ interface AgentConfig {
530
711
  model: AgentModelInput;
531
712
  /**
532
713
  * Optional override for the deployed workflow name (`wrangler.jsonc`
533
- * `workflows[].name`). Defaults to `agent-&lt;kebab-cased export name>`. Does
714
+ * `workflows[].name`). Defaults to `agent-<kebab-cased export name>`. Does
534
715
  * NOT change the binding name, which is always derived from the export
535
- * name (`support` → `AGENT_SUPPORT`).
716
+ * name (`support` → `SupportAgentWorkflow`).
536
717
  */
537
718
  name?: string;
538
719
  /**
@@ -543,7 +724,16 @@ interface AgentConfig {
543
724
  *
544
725
  * - `"reject"` (default) — fail the new run fast with a `CONFLICT` error.
545
726
  * - `"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.
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.
547
737
  *
548
738
  * A workflow REPLAY re-enters the bootstrap under the SAME instance id and
549
739
  * is never a concurrent run (the guard compares the stored instance id).
@@ -563,6 +753,12 @@ interface AgentConfig {
563
753
  * signature over the raw body before calling `map`.
564
754
  */
565
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;
566
762
  /** Called after each LLM turn — see {@link AgentOnStepFinish}. */
567
763
  onStepFinish?: AgentOnStepFinish;
568
764
  /**
@@ -577,7 +773,7 @@ interface AgentConfig {
577
773
  * Opt this agent into being STARTED over the public RPC boundary — i.e. via
578
774
  * the auto-registered `agents:agentRun` mutation an HTTP-only client (e.g.
579
775
  * 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
776
+ * only from server-side app code (`ctx.agents.<name>.run(...)`), so declaring
581
777
  * an agent does NOT expose it to arbitrary RPC callers. Fail-closed — the run
582
778
  * mutation refuses an agent that has not opted in, regardless of any MCP-side
583
779
  * `allowAgents` configuration. A started thread is still owner-scoped to
@@ -649,8 +845,20 @@ interface AgentVoiceConfig {
649
845
  /**
650
846
  * Spoken on connect before the first user turn — a fixed greeting synthesized
651
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.
652
852
  */
653
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;
654
862
  /**
655
863
  * TTS voice/speaker id forwarded to the TTS model (e.g. a Deepgram Aura voice
656
864
  * like `"aura-asteria-en"`). Model-specific; omitted when unset so the model
@@ -685,11 +893,11 @@ interface AgentSubToolInput {
685
893
  interface AgentAsToolOptions {
686
894
  /** What the sub-agent does — shown to the parent's model (it decides from it). */
687
895
  description: string;
688
- /** Cap on child-run status polls before giving up. Default 120. */
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). */
689
897
  maxPolls?: number;
690
898
  /**
691
- * The child agent's export name — selects its `AGENT_&lt;NAME>` Workflow
692
- * binding (e.g. `"researcher"` → `AGENT_RESEARCHER`). The model-facing tool
899
+ * The child agent's export name — selects its `AGENT_<NAME>` Workflow
900
+ * export key (e.g. `"researcher"` → `ResearcherAgentWorkflow`). The model-facing tool
693
901
  * name is the KEY assigned in the parent's `tools` map, not this.
694
902
  */
695
903
  name: string;
@@ -725,11 +933,43 @@ interface AgentDefinition extends AgentConfig {
725
933
  */
726
934
  memorySources?: ReadonlyArray<AgentMemorySource>;
727
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
+ };
728
960
  /**
729
961
  * Params of one agent run (the compiled workflow's payload).
730
962
  * @experimental
731
963
  */
732
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;
733
973
  /** The user message that starts (or continues) the thread. */
734
974
  input: string;
735
975
  /**
@@ -741,6 +981,8 @@ interface AgentRunInput {
741
981
  * the first run.
742
982
  */
743
983
  owner?: string;
984
+ /** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
985
+ replyRef?: AgentReplyRef;
744
986
  /** The thread key — reuse to continue a conversation. */
745
987
  threadKey: string;
746
988
  /** Optional thread title, set on first creation. */
@@ -773,6 +1015,17 @@ interface AgentRunResult {
773
1015
  */
774
1016
  interface AgentFunctionPaths {
775
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;
776
1029
  ensureThread: string;
777
1030
  /** The internal `agents:agentEpisodeRecall` query the loop dispatches for an episodic-kind read. */
778
1031
  episodeRecall: string;
@@ -824,6 +1077,14 @@ interface AgentMessageRow {
824
1077
  interface AgentToolCall {
825
1078
  id: string;
826
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;
827
1088
  name: string;
828
1089
  }
829
1090
  /**
@@ -1018,11 +1279,12 @@ type AgentTokenSink = (event: AgentLiveEvent) => void;
1018
1279
  */
1019
1280
  type AgentStreamGenerate = (options: AgentGenerateOptions, onDelta: (text: string) => void) => Promise<AgentGenerateResult>;
1020
1281
  /**
1021
- * Spec entry codegen emits per agent: `{ binding: "AGENT_SUPPORT", exportName: "support" }`.
1282
+ * Spec entry codegen emits per agent: `{ className: "SupportAgentWorkflow", exportName: "support" }`.
1022
1283
  * @experimental
1023
1284
  */
1024
1285
  interface AgentBindingSpec {
1025
- binding: string;
1286
+ /** The agent's export key — its generated class name, e.g. `SupportAgentWorkflow`. */
1287
+ className: string;
1026
1288
  exportName: string;
1027
1289
  /**
1028
1290
  * Whether the app author opted this agent into public run-starts (via
@@ -1078,7 +1340,7 @@ interface AgentRunHandle {
1078
1340
  id: string;
1079
1341
  }
1080
1342
  /**
1081
- * The `ctx.agents.&lt;name>` producer handle.
1343
+ * The `ctx.agents.<name>` producer handle.
1082
1344
  * @experimental
1083
1345
  */
1084
1346
  interface AgentHandle {
@@ -1111,4 +1373,4 @@ interface AgentHandle {
1111
1373
  /** Read a run's workflow status by instance id. */
1112
1374
  status: (id: string) => Promise<unknown>;
1113
1375
  }
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 };
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 };
@@ -0,0 +1 @@
1
+ import{c as z}from"./agent-loop-DyJWnyiT.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-M4D1EejI.mjs";const ot=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},P=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},C=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return P(n)},D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(C(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},ct=t=>{if(t){if(!t.startsWith(N))return t;try{return D.decode(C(t.slice(N.length)))}catch{return}}},dt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},ut=t=>typeof t=="number"&&Date.now()>=t,yt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},Y=16e3,Z=1,tt=16,M=/[.!?]\s/u,et=/\s/u,nt=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ft=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,l=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(p,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(p+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,l,!0),s.setUint16(32,i,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const a=new Uint8Array(m);return a.set(t,44),a},rt=t=>{const e=[];let n=t,r=M.exec(n);for(;r;){let i=r.index+1;for(;i<n.length&&et.test(n[i]??"");)i+=1;const l=n.slice(0,i).trim();l.length>0&&e.push(l),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},lt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:l,owner:m,paths:s,pcm:u,run:a,send:p,sendAudio:b,signal:d,streamGenerate:H,synthesize:L,text:B,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=A(s.appendMessage),$=A(s.ensureThread),K=A(s.listMessages),x=A(s.patchThread);await a($,{agent:l,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const y=(B??(u?await F(u):"")).trim();if(y.length===0)return await a(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};p({text:y,type:"user_transcript"}),await a(v,{content:y,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(x,{key:o,status:"running"});const _=typeof e.instructions=="function"?e.instructions({env:i,input:y,threadKey:o}):e.instructions,j=await a(K,{key:o}),{history:W,summary:I}=await z({agent:e,compact:n,env:i},j),V=G({history:W,..._===void 0?{}:{instructions:_},...I===void 0?{}:{summary:I}});let g="",E="",k=Promise.resolve();const X=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const f of nt(await L(c,d))){if(h()||(await O?.(),h()))break;b(f),w=!0}}catch(f){p({message:f instanceof Error?f.message:String(f),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},R=c=>{k=k.then(async()=>X(c))},J=await H({messages:V,signal:d},c=>{if(h())return;p({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:f}=rt(g);g=w;for(const q of f)R(q)});!h()&&g.trim().length>0&&R(g.trim()),g="",await k;const S=h(),T=S?E:J.text;return await a(v,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(x,{key:o,status:"idle"}),p(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:y}}catch(y){throw await a(x,{key:o,status:"idle"}),y}},pt=t=>Q(t),ht=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},gt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return P(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,yt as b,ft as c,ct as d,ht as e,gt as f,nt as g,ut as i,pt as p,lt as r,ot as t};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{jsonSchema as h}from"ai";import{r as u}from"./agent-ai-CxEYOyOu.mjs";const l=5,d="Search the web for current information. Returns up to a handful of results, each with a url, a title and (when the provider has one) a description. Use it for facts that may have changed after your training data, then cite the urls you relied on.",m=h({properties:{query:{description:"The search query, 1–1024 characters.",maxLength:1024,minLength:1,type:"string"}},required:["query"],type:"object"}),E=new Set(["BAD_REQUEST","INTERNAL","NOT_IMPLEMENTED"]),T=(t={})=>{const{description:a=d,limit:o=l,...n}=t;return{description:a,execute:async(s,i)=>{const r=u(i.env);if(!r)return"Web search is unavailable: this Worker has no `AI` binding. Answer from what you already know, and say that you could not search.";try{return(await r.websearch(s.query,{...n,limit:o})).items}catch(e){if(e instanceof c&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};
@@ -0,0 +1 @@
1
+ const l=(e,r,o)=>e?.[o]??r?.[o],f=(e,r,o,t)=>{const n=l(e,r,o);if(!(typeof n!="object"||n===null))return t.every(i=>typeof n[i]=="function")?n:void 0};export{f as r};
@@ -0,0 +1,40 @@
1
+ import { Mailer } from '@lunora/mail';
2
+ import { InboundEmail } from '@lunora/mail/inbound';
3
+ import { a as AgentReplyRef } from "./packem_shared/types.d-CbYtFBw9.mjs";
4
+ import 'ai';
5
+ /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
6
+ type EmailReplyRef = Extract<AgentReplyRef, {
7
+ channel: "email";
8
+ }>;
9
+ /**
10
+ * Capture a reply reference from an already-parsed inbound email — call it in
11
+ * an `onEmail` mapper and put the result on the run's `replyRef`.
12
+ *
13
+ * Returns `undefined` when the message carries no `Message-ID`: there is
14
+ * nothing to thread a reply against, and an unthreaded reply lands as a new
15
+ * conversation in the recipient's client, which is worse than not replying.
16
+ */
17
+ declare const captureEmailReplyRef: (email: InboundEmail) => EmailReplyRef | undefined;
18
+ /** RFC 5322 threading: append the replied-to id to any existing `References` chain. */
19
+ declare const buildReferences: (replyRef: EmailReplyRef) => string;
20
+ /** Subject + body of a reply. */
21
+ interface ReplyBody {
22
+ subject: string;
23
+ text: string;
24
+ }
25
+ /**
26
+ * Send a threaded reply through the app's own `@lunora/mail` mailer.
27
+ *
28
+ * The mailer is a parameter rather than something this module constructs: the
29
+ * app already configures one (API key or `send_email` binding), and passing it
30
+ * in keeps this module free of any runtime dependency on `@lunora/mail`.
31
+ *
32
+ * The reply goes to the original sender, from the mailer's configured default.
33
+ * An app running several aliases that wants the reply to come from whichever
34
+ * mailbox received the message passes `from: replyRef.to[0]` itself — a
35
+ * decision only the app can make.
36
+ */
37
+ declare const replyToEmail: (mailer: Mailer, replyRef: EmailReplyRef, body: ReplyBody) => Promise<{
38
+ id: string;
39
+ }>;
40
+ export { type EmailReplyRef, ReplyBody, buildReferences, captureEmailReplyRef, replyToEmail };
@@ -0,0 +1,40 @@
1
+ import { Mailer } from '@lunora/mail';
2
+ import { InboundEmail } from '@lunora/mail/inbound';
3
+ import { a as AgentReplyRef } from "./packem_shared/types.d-CbYtFBw9.js";
4
+ import 'ai';
5
+ /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
6
+ type EmailReplyRef = Extract<AgentReplyRef, {
7
+ channel: "email";
8
+ }>;
9
+ /**
10
+ * Capture a reply reference from an already-parsed inbound email — call it in
11
+ * an `onEmail` mapper and put the result on the run's `replyRef`.
12
+ *
13
+ * Returns `undefined` when the message carries no `Message-ID`: there is
14
+ * nothing to thread a reply against, and an unthreaded reply lands as a new
15
+ * conversation in the recipient's client, which is worse than not replying.
16
+ */
17
+ declare const captureEmailReplyRef: (email: InboundEmail) => EmailReplyRef | undefined;
18
+ /** RFC 5322 threading: append the replied-to id to any existing `References` chain. */
19
+ declare const buildReferences: (replyRef: EmailReplyRef) => string;
20
+ /** Subject + body of a reply. */
21
+ interface ReplyBody {
22
+ subject: string;
23
+ text: string;
24
+ }
25
+ /**
26
+ * Send a threaded reply through the app's own `@lunora/mail` mailer.
27
+ *
28
+ * The mailer is a parameter rather than something this module constructs: the
29
+ * app already configures one (API key or `send_email` binding), and passing it
30
+ * in keeps this module free of any runtime dependency on `@lunora/mail`.
31
+ *
32
+ * The reply goes to the original sender, from the mailer's configured default.
33
+ * An app running several aliases that wants the reply to come from whichever
34
+ * mailbox received the message passes `from: replyRef.to[0]` itself — a
35
+ * decision only the app can make.
36
+ */
37
+ declare const replyToEmail: (mailer: Mailer, replyRef: EmailReplyRef, body: ReplyBody) => Promise<{
38
+ id: string;
39
+ }>;
40
+ export { type EmailReplyRef, ReplyBody, buildReferences, captureEmailReplyRef, replyToEmail };
package/dist/reply.mjs ADDED
@@ -0,0 +1 @@
1
+ const t=e=>{if(e.messageId!==void 0)return{channel:"email",from:e.from,messageId:e.messageId,to:e.to,...e.references===void 0?{}:{references:e.references}}},n=e=>e.references===void 0?e.messageId:`${e.references} ${e.messageId}`,c=async(e,s,r)=>e.send({headers:{"In-Reply-To":s.messageId,References:n(s)},subject:r.subject,text:r.text,to:s.from});export{n as buildReferences,t as captureEmailReplyRef,c as replyToEmail};