@lunora/agent 1.0.0-alpha.17 → 1.0.0-alpha.171

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 +2 -0
  5. package/dist/component.d.ts +2 -0
  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-DRXZ0uJJ-CzPOpA2g.mjs +1 -0
  18. package/dist/packem_shared/VoiceSessionDO-c8KpjkPk.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-B8Ra_VJg.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-C1-gaq8q.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-D3mf7LEU.mjs +1 -0
  34. package/dist/packem_shared/createAgentGenerate-EEFNvpS5.mjs +3 -0
  35. package/dist/packem_shared/defineAgent-vb1xAmyx.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-B9Wc9zPg.mjs +1 -0
  45. package/dist/packem_shared/runVoiceTurn-TLyTQ_UA.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-obvJnpv6.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
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-boAM2Yi1.mjs";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-boAM2Yi1.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -18,6 +18,12 @@ declare const verifySlack: (options: {
18
18
  }) => Promise<boolean>;
19
19
  /**
20
20
  * Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
21
+ *
22
+ * There is no replay window: GitHub signs the body alone, with no timestamp, so
23
+ * a captured delivery verifies indefinitely. `dispatchAgentChannel` bounds that
24
+ * by keying the run on the SHA-256 of the signed body (see `deliveryId`), so a
25
+ * replay dedupes to the original run — for as long as the Workflow keeps that
26
+ * instance id.
21
27
  * @experimental
22
28
  */
23
29
  declare const verifyGithub: (options: {
@@ -28,13 +34,18 @@ declare const verifyGithub: (options: {
28
34
  /**
29
35
  * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
30
36
  * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
37
+ * The signed `x-signature-timestamp` must be within `tolerance` seconds of
38
+ * `now` in either direction, or a captured interaction would verify forever.
39
+ * `now` is injectable for deterministic tests (defaults to the wall clock).
31
40
  * @experimental
32
41
  */
33
42
  declare const verifyDiscord: (options: {
34
43
  body: string;
44
+ now?: number;
35
45
  publicKey: string;
36
46
  signature: string | undefined;
37
47
  timestamp: string | undefined;
48
+ tolerance?: number;
38
49
  }) => Promise<boolean>;
39
50
  /**
40
51
  * One agent wired into the inbound channel HTTP handler.
@@ -43,22 +54,22 @@ declare const verifyDiscord: (options: {
43
54
  interface AgentChannelTarget {
44
55
  /** The agent definition — only its `onInbound` config is read. */
45
56
  agent: Pick<AgentDefinition, "onInbound">;
46
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
47
- binding: string;
57
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
58
+ className: string;
48
59
  }
49
60
  /**
50
61
  * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
51
62
  * @experimental
52
63
  */
53
- type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
54
64
  /**
55
- * Whether a `workflow.create()` rejection is a duplicate-instance-id error — the
56
- * idempotency signal — as opposed to a transient/config failure (Workflows
57
- * service error, instance-creation quota, bad params). Only the former may be
58
- * acked; every other failure MUST surface so the handler returns non-2xx and the
59
- * provider redelivers, rather than silently dropping the event.
65
+ * A Worker `fetch`-shaped handler. The Worker `ctx` is required: on Cloudflare
66
+ * the agent is reached as `ctx.exports.<Class>`, so a handler mounted without it
67
+ * could never start a run (from an `httpRouter` route: `handler(c.req.raw,
68
+ * c.env, c.executionCtx)`).
60
69
  */
61
- declare const isDuplicateInstanceError: (error: unknown) => boolean;
70
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>, context: {
71
+ exports?: unknown;
72
+ }) => Promise<Response>;
62
73
  /**
63
74
  * Build an HTTP handler that starts a durable agent run from a verified inbound
64
75
  * webhook. The channel is detected from the signature headers; EACH eligible
@@ -71,4 +82,4 @@ declare const isDuplicateInstanceError: (error: unknown) => boolean;
71
82
  * @experimental
72
83
  */
73
84
  declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
74
- export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, isDuplicateInstanceError, verifyDiscord, verifyGithub, verifySlack };
85
+ export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-boAM2Yi1.js";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-boAM2Yi1.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-CbYtFBw9.js";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -18,6 +18,12 @@ declare const verifySlack: (options: {
18
18
  }) => Promise<boolean>;
19
19
  /**
20
20
  * Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
21
+ *
22
+ * There is no replay window: GitHub signs the body alone, with no timestamp, so
23
+ * a captured delivery verifies indefinitely. `dispatchAgentChannel` bounds that
24
+ * by keying the run on the SHA-256 of the signed body (see `deliveryId`), so a
25
+ * replay dedupes to the original run — for as long as the Workflow keeps that
26
+ * instance id.
21
27
  * @experimental
22
28
  */
23
29
  declare const verifyGithub: (options: {
@@ -28,13 +34,18 @@ declare const verifyGithub: (options: {
28
34
  /**
29
35
  * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
30
36
  * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
37
+ * The signed `x-signature-timestamp` must be within `tolerance` seconds of
38
+ * `now` in either direction, or a captured interaction would verify forever.
39
+ * `now` is injectable for deterministic tests (defaults to the wall clock).
31
40
  * @experimental
32
41
  */
33
42
  declare const verifyDiscord: (options: {
34
43
  body: string;
44
+ now?: number;
35
45
  publicKey: string;
36
46
  signature: string | undefined;
37
47
  timestamp: string | undefined;
48
+ tolerance?: number;
38
49
  }) => Promise<boolean>;
39
50
  /**
40
51
  * One agent wired into the inbound channel HTTP handler.
@@ -43,22 +54,22 @@ declare const verifyDiscord: (options: {
43
54
  interface AgentChannelTarget {
44
55
  /** The agent definition — only its `onInbound` config is read. */
45
56
  agent: Pick<AgentDefinition, "onInbound">;
46
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
47
- binding: string;
57
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
58
+ className: string;
48
59
  }
49
60
  /**
50
61
  * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
51
62
  * @experimental
52
63
  */
53
- type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
54
64
  /**
55
- * Whether a `workflow.create()` rejection is a duplicate-instance-id error — the
56
- * idempotency signal — as opposed to a transient/config failure (Workflows
57
- * service error, instance-creation quota, bad params). Only the former may be
58
- * acked; every other failure MUST surface so the handler returns non-2xx and the
59
- * provider redelivers, rather than silently dropping the event.
65
+ * A Worker `fetch`-shaped handler. The Worker `ctx` is required: on Cloudflare
66
+ * the agent is reached as `ctx.exports.<Class>`, so a handler mounted without it
67
+ * could never start a run (from an `httpRouter` route: `handler(c.req.raw,
68
+ * c.env, c.executionCtx)`).
60
69
  */
61
- declare const isDuplicateInstanceError: (error: unknown) => boolean;
70
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>, context: {
71
+ exports?: unknown;
72
+ }) => Promise<Response>;
62
73
  /**
63
74
  * Build an HTTP handler that starts a durable agent run from a verified inbound
64
75
  * webhook. The channel is detected from the signature headers; EACH eligible
@@ -71,4 +82,4 @@ declare const isDuplicateInstanceError: (error: unknown) => boolean;
71
82
  * @experimental
72
83
  */
73
84
  declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
74
- export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, isDuplicateInstanceError, verifyDiscord, verifyGithub, verifySlack };
85
+ export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
package/dist/channels.mjs CHANGED
@@ -1 +1 @@
1
- import{LunoraError as w}from"@lunora/errors";const m=300,v=/[^0-9a-f]/iu,x=new TextEncoder,d=e=>new Uint8Array(x.encode(e)),g=e=>{if(e.length%2!==0||v.test(e))throw new w("BAD_REQUEST","@lunora/agent: malformed hex signature");const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t},b=async(e,t,r)=>{try{const s=await crypto.subtle.importKey("raw",d(e),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",s,g(r),d(t))}catch{return!1}},k=(e,t,r)=>Number.isFinite(e)&&Math.abs(t-e)<=r,A=async e=>{const{body:t,now:r=Date.now()/1e3,signature:s,signingSecret:n,timestamp:a,tolerance:o=m}=e;return!s||!a||!s.startsWith("v0=")||!k(Number(a),r,o)?!1:b(n,`v0:${a}:${t}`,s.slice(3))},E=async e=>{const{body:t,secret:r,signature:s}=e;return s?.startsWith("sha256=")?b(r,t,s.slice(7)):!1},S=async e=>{const{body:t,publicKey:r,signature:s,timestamp:n}=e;if(!s||!n)return!1;try{const a=await crypto.subtle.importKey("raw",g(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},a,g(s),d(n+t))}catch{return!1}},N=e=>{if(e.has("x-slack-signature"))return"slack";if(e.has("x-hub-signature-256"))return"github";if(e.has("x-signature-ed25519"))return"discord"},R=(e,t)=>{if(typeof e=="function")return e(t);const r=t[e];return typeof r=="string"?r:void 0},I=async(e,t,r,s)=>{switch(e){case"discord":return S({body:s,publicKey:t,signature:r.get("x-signature-ed25519")??void 0,timestamp:r.get("x-signature-timestamp")??void 0});case"github":return E({body:s,secret:t,signature:r.get("x-hub-signature-256")??void 0});case"slack":return A({body:s,signature:r.get("x-slack-signature")??void 0,signingSecret:t,timestamp:r.get("x-slack-request-timestamp")??void 0});default:return!1}},D=(e,t)=>{if(e==="discord")try{if(JSON.parse(t).type===1)return Response.json({type:1})}catch{}},K=/[^\w-]/gu,U=/already[\s-]?exists/iu,u=()=>new Response(void 0,{status:200}),$=e=>U.test(e instanceof Error?e.message:String(e)),C=(e,t,r)=>{if(e==="github")return t.get("x-github-delivery")??void 0;try{const s=JSON.parse(r),n=e==="slack"?s.event_id:s.id;return typeof n=="string"?n:void 0}catch{return}},H=async(e,t,r,s)=>{const n=s===void 0?"":s.replaceAll(K,"");if(n==="")return await e.create({params:t}),u();try{await e.create({id:`${r}-${n}`.slice(0,60),params:t})}catch(a){if($(a))return u();throw a}return u()},j=e=>async(t,r)=>{const s=await t.text(),n=N(t.headers);if(n===void 0)return new Response("Unrecognized webhook",{status:400});const a=e.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===n),o={channel:n,headers:t.headers,json:()=>JSON.parse(s),rawBody:s};let f=!1;for(const{config:i,target:l}of a){const y=R(i.secret,r);if(y===void 0||!await I(n,y,t.headers,s))continue;f=!0;const h=D(n,s);if(h)return h;const p=await i.map(o);if(!p)continue;const c=r[l.binding];if(!c||typeof c.create!="function")throw new w("INTERNAL",`@lunora/agent: no Workflow binding "${l.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await H(c,p,n,C(n,t.headers,s))}return f?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{j as dispatchAgentChannel,$ as isDuplicateInstanceError,S as verifyDiscord,E as verifyGithub,A as verifySlack};
1
+ import{LunoraError as l}from"@lunora/errors";import{isDuplicateInstanceError as A}from"@lunora/workflow";import{h as x,B as N}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as R}from"./packem_shared/fnv1a-BNN96GYb.mjs";import{r as k}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";const v=300,S=/[^0-9a-f]/iu,T=new TextEncoder,c=t=>new Uint8Array(T.encode(t)),f=t=>{if(t.length%2!==0||S.test(t))throw new l("BAD_REQUEST","@lunora/agent: malformed hex signature");const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n+=1)e[n]=Number.parseInt(t.slice(n*2,n*2+2),16);return e},b=async(t,e,n)=>{try{const r=await crypto.subtle.importKey("raw",c(t),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",r,f(n),c(e))}catch{return!1}},E=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,H=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:a,timestamp:s,tolerance:i=v}=t;return!r||!s||!r.startsWith("v0=")||!E(Number(s),n,i)?!1:b(a,`v0:${s}:${e}`,r.slice(3))},C=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?b(n,e,r.slice(7)):!1},I=async t=>{const{body:e,now:n=Date.now()/1e3,publicKey:r,signature:a,timestamp:s,tolerance:i=v}=t;if(!a||!s||!E(Number(s),n,i))return!1;try{const u=await crypto.subtle.importKey("raw",f(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},u,f(a),c(s+e))}catch{return!1}},_=t=>{if(t.has("x-slack-signature"))return"slack";if(t.has("x-hub-signature-256"))return"github";if(t.has("x-signature-ed25519"))return"discord"},B=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},D=async(t,e,n,r)=>{switch(t){case"discord":return I({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return C({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return H({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},M=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},w=()=>new Response(void 0,{status:200}),U=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",c(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),O=async(t,e)=>{if(t!=="github")try{const n=JSON.parse(e),r=t==="slack"?n.event_id:n.id;if(typeof r=="string"&&r!=="")return r}catch{}return U(e)},$=async(t,e,n,r)=>{if(x(e))throw new l("BAD_REQUEST",`@lunora/agent: inbound channel run params ${N}`);try{await t.create({id:`${n}-${R(r)}`,params:e})}catch(a){if(A(a))return w();throw a}return w()},W=t=>async(e,n,r)=>{const a=await e.text(),s=_(e.headers);if(s===void 0)return new Response("Unrecognized webhook",{status:400});const i=t.map(o=>({config:o.agent.onInbound,target:o})).filter(o=>o.config?.channel===s),u={channel:s,headers:e.headers,json:()=>JSON.parse(a),rawBody:a};let d=!1;for(const{config:o,target:g}of i){const p=B(o.secret,n);if(p===void 0||!await D(s,p,e.headers,a))continue;d=!0;const y=M(s,a);if(y)return y;const h=await o.map(u);if(!h)continue;const m=k(n,r.exports,g.className,["create"]);if(m===void 0)throw new l("INTERNAL",`@lunora/agent: no "${g.className}" on ctx.exports or env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await $(m,h,s,await O(s,a))}return d?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{W as dispatchAgentChannel,I as verifyDiscord,C as verifyGithub,H as verifySlack};
@@ -72,6 +72,8 @@ interface AgentComponent {
72
72
  extension: SchemaExtension;
73
73
  functions: {
74
74
  agentAppendMessage: AgentRegisteredFunction;
75
+ agentCompleteRun: AgentRegisteredFunction;
76
+ agentDeleteMessage: AgentRegisteredFunction;
75
77
  agentEnsureThread: AgentRegisteredFunction;
76
78
  agentEpisodeRecall: AgentRegisteredFunction;
77
79
  agentEpisodeUpsert: AgentRegisteredFunction;
@@ -72,6 +72,8 @@ interface AgentComponent {
72
72
  extension: SchemaExtension;
73
73
  functions: {
74
74
  agentAppendMessage: AgentRegisteredFunction;
75
+ agentCompleteRun: AgentRegisteredFunction;
76
+ agentDeleteMessage: AgentRegisteredFunction;
75
77
  agentEnsureThread: AgentRegisteredFunction;
76
78
  agentEpisodeRecall: AgentRegisteredFunction;
77
79
  agentEpisodeUpsert: AgentRegisteredFunction;
@@ -1,2 +1,2 @@
1
- import{LunoraError as w}from"@lunora/errors";import{defineTable as x,initLunora as $,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{i as b,o as k,q as O,s as S,j as F}from"./packem_shared/graph-component-B2YmC2eL.mjs";import{p as ne}from"./packem_shared/graph-component-B2YmC2eL.mjs";import{sandboxComponent as ie}from"./packem_shared/sandboxComponent-BhaGHsQZ.mjs";const I="agent_episodes",L=5,U=20,B=500,N=200,G=/\s+/gu,z=c=>c===void 0||!Number.isFinite(c)?L:Math.min(U,Math.max(1,Math.trunc(c))),P={episodes:x({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:H,query:J}=$.dataModel().create(),Q=()=>{const c=H.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:s,ctx:u})=>{const l=s.summary.replaceAll(G," ").trim().slice(0,B);if(l.length===0)return{recorded:!1};if(await u.db.query(I).withIndex("byOwnerMessageKey",p=>p.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await u.db.insert(I,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:l,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const g=await u.db.query(I).withIndex("byOwnerCreatedAt",p=>p.eq("owner",s.owner)).order("asc").take(N+1);for(const p of g.slice(0,Math.max(0,g.length-N)))await u.db.delete(p._id);return{recorded:!0}}),v=J.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:u})=>{const l=await u.db.query(I).withIndex("byOwnerCreatedAt",g=>g.eq("owner",s.owner)).order("desc").take(z(s.limit));return l.length===0?{context:""}:{context:l.toReversed().map(g=>`- ${g.summary}`).join(`
2
- `)}});return{agentEpisodeRecall:b(v),agentEpisodeUpsert:b(c)}},T="threads",R="messages",d=`${k}_${T}`,K=`${k}_${R}`,V=j(k,{tables:{[R]:x({content:e.string(),createdAt:e.number(),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[T]:x({agent:e.string(),createdAt:e.number(),error:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),...O,...P}}),{mutation:m,query:q}=$.dataModel().create(),ee=()=>{const c=m.input({agent:e.string(),initialState:e.optional(e.any()),instanceId:e.optional(e.string()),key:e.string(),onConcurrentRun:e.optional(e.union(e.literal("reject"),e.literal("queue"),e.literal("replace"))),owner:e.optional(e.string()),title:e.optional(e.string())}).mutation(async({args:t,ctx:a})=>{const r=Date.now(),n=await a.db.query(d).withIndex("byKey",i=>i.eq("key",t.key)).first();if(n){if(n.owner!==t.owner&&t.owner!==void 0)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);const i=n.instanceId;if((n.status==="running"||n.status==="awaiting_input")&&i!==void 0&&(t.instanceId===void 0||t.instanceId!==i)){const o=t.onConcurrentRun??"reject";if(o!=="replace")throw new w("CONFLICT",`@lunora/agent: thread "${t.key}" already has a run in flight (instance "${i}") — onConcurrentRun="${o}"`);return await a.db.patch(n._id,{error:void 0,status:"running",updatedAt:r,...t.instanceId===void 0?{}:{instanceId:t.instanceId}}),{created:!1,priorInstanceId:i,replaced:!0}}return await a.db.patch(n._id,{error:void 0,status:"running",updatedAt:r,...t.instanceId===void 0?{}:{instanceId:t.instanceId}}),{created:!1}}return await a.db.insert(d,{agent:t.agent,createdAt:r,key:t.key,messageCount:0,status:"running",updatedAt:r,...S({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{created:!0}}),v=m.input({content:e.string(),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).mutation(async({args:t,ctx:a})=>{const r=await a.db.query(K).withIndex("byMessageKey",y=>y.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(r)return{seq:r.seq};const n=await a.db.query(d).withIndex("byKey",y=>y.eq("key",t.threadKey)).first();if(!n)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const i=n.messageCount,o=Date.now();return await a.db.insert(K,{content:t.content,createdAt:o,messageKey:t.messageKey,role:t.role,seq:i,threadKey:t.threadKey,...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await a.db.patch(n._id,{messageCount:i+1,updatedAt:o}),{seq:i}}),s=m.input({error:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),title:e.optional(e.string()),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:a})=>{const{instanceId:r,key:n}=t;let i;n!==void 0?i=await a.db.query(d).withIndex("byKey",o=>o.eq("key",n)).first():r!==void 0&&(i=await a.db.query(d).withIndex("byInstance",o=>o.eq("instanceId",r)).first()),i&&await a.db.patch(i._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),u=m.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();r&&await a.db.patch(r._id,{state:t.state,updatedAt:Date.now()})}),l=(t,a)=>{if(!t)return;const{owner:r}=t;if(!(r!==void 0&&r!==(a.userId??void 0)))return t},g=q.input({key:e.string()}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)}),p=q.input({key:e.string()}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)?.state}),_=q.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)===void 0?[]:t.limit!==void 0?(await a.db.query(K).withIndex("byThread",n=>n.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():a.db.query(K).withIndex("byThread",n=>n.eq("threadKey",t.key)).collect()}),D=m.input({decision:e.union(e.literal("approve"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",h=>h.eq("key",t.threadKey)).first(),n=l(r,a.auth);if(n===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(n.instanceId!==t.instanceId)throw new w("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const i=n.agent,{agents:o}=a,y=o?.[i];if(typeof y?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${i}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return await y.sendEvent(t.instanceId,{payload:{decision:t.decision,toolCallId:t.toolCallId,...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),M=m.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:a})=>{const{agents:r}=a,n=r?.[t.agent];if(typeof n?.run!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(n.publicRun!==!0)throw new w("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const i=a.auth.userId??void 0,o=await a.db.query(d).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(o){const h=o.status,E=o.instanceId,f=o.owner;if((h==="running"||h==="awaiting_input")&&E!==void 0&&(f===void 0||f===i))return{id:E,threadKey:t.threadKey};if(f!==i&&i!==void 0)throw new w("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:y}=await n.run({input:t.input,threadKey:t.threadKey,...i===void 0?{}:{owner:i},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),C=F(),A=Q();return{extension:V,functions:{agentAppendMessage:b(v),agentEnsureThread:b(c),agentEpisodeRecall:A.agentEpisodeRecall,agentEpisodeUpsert:A.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:_,agentPatchThread:b(s),agentResolveApproval:D,agentRun:M,agentSetState:b(u),agentState:p,agentThread:g}}};export{ee as agentComponent,V as agentExtension,ne as normalizeEntityName,ie as sandboxComponent};
1
+ import{LunoraError as g}from"@lunora/errors";import{defineTable as k,initLunora as D,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{a as q,A as _,d as P,b as F}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as G,graphComponent as H}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as he}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as we}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const v="agent_episodes",X=5,Q=20,W=500,N=200,Y=/\s+/gu,z=d=>d===void 0||!Number.isFinite(d)?X:Math.min(Q,Math.max(1,Math.trunc(d))),V={episodes:k({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:J,query:Z}=D.dataModel().create(),ee=()=>{const d=J.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:s,ctx:u})=>{const c=s.summary.replaceAll(Y," ").trim().slice(0,W);if(c.length===0)return{recorded:!1};if(await u.db.query(v).withIndex("byOwnerMessageKey",I=>I.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await u.db.insert(v,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:c,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const w=await u.db.query(v).withIndex("byOwnerCreatedAt",I=>I.eq("owner",s.owner)).order("asc").take(N+1);for(const I of w.slice(0,Math.max(0,w.length-N)))await u.db.delete(I._id);return{recorded:!0}}),o=Z.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:u})=>{const c=await u.db.query(v).withIndex("byOwnerCreatedAt",h=>h.eq("owner",s.owner)).order("desc").take(z(s.limit));return c.length===0?{context:""}:{context:c.toReversed().map(h=>`- ${h.summary}`).join(`
2
+ `)}});return{agentEpisodeRecall:q(o),agentEpisodeUpsert:q(d)}},S="threads",$="messages",M="run_queue",p=`${_}_${S}`,E=`${_}_${$}`,A=`${_}_${M}`,x=5,te=780*60*1e3,ne=j(_,{tables:{[$]:k({content:e.string(),createdAt:e.number(),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[S]:k({agent:e.string(),createdAt:e.number(),error:e.optional(e.string().nullable()),completedInstanceId:e.optional(e.string().nullable()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),[M]:k({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),...G,...V}}),{mutation:f,query:T}=D.dataModel().create(),ie=async(d,o,s)=>{if(o.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=o,c=await d.query(A).withIndex("byThreadInstance",I=>I.eq("threadKey",o.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const h=await d.query(A).withIndex("byThread",I=>I.eq("threadKey",o.key)).collect();if(h.length>=x)throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(x)}) — rejecting instance "${u}"`);const w=(h.at(-1)?.position??-1)+1;return await d.insert(A,{agent:o.agent,enqueuedAt:s,instanceId:u,position:w,threadKey:o.key}),{outcome:"queued",position:w}},ae=async(d,o,s)=>{if(o.policy==="queue")return ie(d,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},s);if(o.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await d.patch(o.existingId,{error:null,status:"running",updatedAt:s,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},oe=(d,o,s)=>{const u=d.instanceId;if(u===void 0||o===u||d.status!=="running"&&d.status!=="awaiting_input")return;const c=typeof d.updatedAt=="number"?d.updatedAt:0,h=d.status==="awaiting_input"?F:te;return s-c>h?void 0:u},ce=()=>{const d=f.input({agent:e.string(),initialState:e.optional(e.any()),instanceId:e.optional(e.string()),key:e.string(),onConcurrentRun:e.optional(e.union(e.literal("reject"),e.literal("queue"),e.literal("replace"))),owner:e.optional(e.string()),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();if(i){if(i.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&i.completedInstanceId===t.instanceId)return{outcome:"completed"};const r=oe(i,t.instanceId,a);return r!==void 0?ae(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:r},a):(await n.db.patch(i._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(p,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...P({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=f.input({content:e.string(),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(E).withIndex("byMessageKey",y=>y.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(p).withIndex("byKey",y=>y.eq("key",t.threadKey)).first();if(!i)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const r=i.messageCount,l=Date.now();return await n.db.insert(E,{content:t.content,createdAt:l,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await n.db.patch(i._id,{messageCount:r+1,updatedAt:l}),{seq:r}}),s=f.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(E).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),u=f.input({error:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),title:e.optional(e.string()),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(p).withIndex("byKey",l=>l.eq("key",i)).first():a!==void 0&&(r=await n.db.query(p).withIndex("byInstance",l=>l.eq("instanceId",a)).first()),r&&await n.db.patch(r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=f.input({error:e.optional(e.string()),instanceId:e.string(),key:e.string(),status:e.union(e.literal("idle"),e.literal("error"),e.literal("cancelled")),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",b=>b.eq("key",t.key)).first();if(i?.instanceId!==t.instanceId){if(i?.completedInstanceId===t.instanceId&&i.status==="running"&&typeof i.instanceId=="string")return{dequeued:i.instanceId};const b=await n.db.query(A).withIndex("byThreadInstance",K=>K.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return b&&await n.db.delete(b._id),{}}const y=(i.completedInstanceId===t.instanceId?[]:await n.db.query(A).withIndex("byThread",b=>b.eq("threadKey",t.key)).collect())[0];if(!y)return await n.db.patch(i._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const m=y.instanceId;return await n.db.delete(y._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:m,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:m}}),h=f.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();a&&await n.db.patch(a._id,{state:t.state,updatedAt:Date.now()})}),w=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},I=T.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return w(a,n.auth)}),O=T.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return w(a,n.auth)?.state}),L=T.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return w(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(E).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(E).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),U=f.input({decision:e.union(e.literal("approve"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",m=>m.eq("key",t.threadKey)).first(),i=w(a,n.auth);if(i===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new g("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:l}=n,y=l?.[r];if(typeof y?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return await y.sendEvent(t.instanceId,{payload:{decision:t.decision,toolCallId:t.toolCallId,...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),B=f.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const{agents:a}=n,i=a?.[t.agent];if(typeof i?.run!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(i.publicRun!==!0)throw new g("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const r=n.auth.userId??void 0,l=await n.db.query(p).withIndex("byKey",m=>m.eq("key",t.threadKey)).first();if(l){const m=l.status,b=l.instanceId,K=l.owner;if((m==="running"||m==="awaiting_input")&&b!==void 0&&(K===void 0||K===r))return{id:b,threadKey:t.threadKey};if(K!==r)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:y}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),C=H(),R=ee();return{extension:ne,functions:{agentAppendMessage:q(o),agentCompleteRun:q(c),agentEnsureThread:q(d),agentEpisodeRecall:R.agentEpisodeRecall,agentEpisodeUpsert:R.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:L,agentDeleteMessage:q(s),agentPatchThread:q(u),agentResolveApproval:U,agentRun:B,agentSetState:q(h),agentState:O,agentThread:I}}};export{ce as agentComponent,ne as agentExtension,he as normalizeEntityName,we as sandboxComponent};
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-boAM2Yi1.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -11,8 +11,8 @@ interface AgentEmailTarget {
11
11
  * this agent claims the message and, if so, the run to start.
12
12
  */
13
13
  agent: Pick<AgentDefinition, "onEmail">;
14
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
15
- binding: string;
14
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
15
+ className: string;
16
16
  }
17
17
  /**
18
18
  * The worker `email(message, env, ctx)` callback. Typed with `unknown`
@@ -24,10 +24,12 @@ type InboundAgentEmailHandler = (message: unknown, env: unknown, context: unknow
24
24
  /**
25
25
  * Build the inbound `email()` handler for one or more `onEmail` agents. The
26
26
  * returned callback parses the message, then walks `targets` in order and starts
27
- * a durable run for the first agent whose `onEmail` mapper returns a run. If the
28
- * matched agent's Workflow binding is missing from `env` (run codegen/dev so
29
- * `wrangler.jsonc` declares it) the dispatch throws, and the inbound handler's
30
- * `onError` rejects (bounces) the message.
27
+ * a durable run for the first agent whose `onEmail` mapper returns a run.
28
+ *
29
+ * Two dispatch failures bounce the message permanently rather than retrying: a
30
+ * missing Workflow binding (run codegen/dev so `wrangler.jsonc` declares it) and
31
+ * a run carrying the reserved workflow branch-marker key. See
32
+ * {@link rejectPermanently}.
31
33
  * @experimental
32
34
  */
33
35
  declare const dispatchAgentEmail: (targets: ReadonlyArray<AgentEmailTarget>) => InboundAgentEmailHandler;
package/dist/inbound.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-boAM2Yi1.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -11,8 +11,8 @@ interface AgentEmailTarget {
11
11
  * this agent claims the message and, if so, the run to start.
12
12
  */
13
13
  agent: Pick<AgentDefinition, "onEmail">;
14
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
15
- binding: string;
14
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
15
+ className: string;
16
16
  }
17
17
  /**
18
18
  * The worker `email(message, env, ctx)` callback. Typed with `unknown`
@@ -24,10 +24,12 @@ type InboundAgentEmailHandler = (message: unknown, env: unknown, context: unknow
24
24
  /**
25
25
  * Build the inbound `email()` handler for one or more `onEmail` agents. The
26
26
  * returned callback parses the message, then walks `targets` in order and starts
27
- * a durable run for the first agent whose `onEmail` mapper returns a run. If the
28
- * matched agent's Workflow binding is missing from `env` (run codegen/dev so
29
- * `wrangler.jsonc` declares it) the dispatch throws, and the inbound handler's
30
- * `onError` rejects (bounces) the message.
27
+ * a durable run for the first agent whose `onEmail` mapper returns a run.
28
+ *
29
+ * Two dispatch failures bounce the message permanently rather than retrying: a
30
+ * missing Workflow binding (run codegen/dev so `wrangler.jsonc` declares it) and
31
+ * a run carrying the reserved workflow branch-marker key. See
32
+ * {@link rejectPermanently}.
31
33
  * @experimental
32
34
  */
33
35
  declare const dispatchAgentEmail: (targets: ReadonlyArray<AgentEmailTarget>) => InboundAgentEmailHandler;
package/dist/inbound.mjs CHANGED
@@ -1 +1 @@
1
- import{LunoraError as s}from"@lunora/errors";import{createInboundEmailHandler as d,parseInboundEmail as u}from"@lunora/mail/inbound";const m=i=>{const c=d({dispatch:async(o,a)=>{for(const n of i){const t=n.agent.onEmail;if(!t)continue;const e=await t(o);if(e==null)continue;const r=a.env[n.binding];if(!r||typeof r.create!="function")throw new s("INTERNAL",`@lunora/agent: no Workflow binding "${n.binding}" on env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);await r.create({params:e});return}},parse:u});return async(o,a,n)=>c(o,a,n)};export{m as dispatchAgentEmail};
1
+ import{createInboundEmailHandler as l,authenticatesFrom as u,parseInboundEmail as m}from"@lunora/mail/inbound";import{h as d,B as p}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{r as g}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";const f="message could not be processed",i=(a,o)=>{console.error("@lunora/agent/inbound: bouncing message —",o),a.message.setReject(f)},h=a=>{const o=l({dispatch:async(s,n)=>{for(const e of a){const t=e.agent.onEmail;if(!t)continue;const r=await t(s);if(r==null)continue;const c=g(n.env,n.ctx?.exports,e.className,["create"]);if(c===void 0){i(n,`@lunora/agent: no "${e.className}" on ctx.exports or env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);return}if(d(r)){i(n,`@lunora/agent: inbound run params ${p}`);return}await c.create({params:r});return}},parse:m,verify:u});return async(s,n,e)=>o(s,n,e)};export{h as dispatchAgentEmail};
package/dist/index.d.mts CHANGED
@@ -1,10 +1,10 @@
1
- import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-boAM2Yi1.mjs";
2
- export type { y as AgentEmailMapper, z as AgentEmailRun, B as AgentGenerateOptions, C as AgentGenerateResult, D as AgentInstructionsContext, E as AgentLiveEvent, F as AgentMemoryOptions, G as AgentMemorySource, H as AgentMessageStatus, J as AgentOnStepFinish, K as AgentPrepareStep, L as AgentPrepareStepInput, M as AgentPrepareStepResult, N as AgentProgressEvent, O as AgentRunHandle, P as AgentStepFinishInfo, Q as AgentStepInfo, R as AgentThreadStatus, T as AgentTokenDelta, U as AgentToolCall, a as AgentToolContext, V as AgentUsage, W as AgentVoiceConfig, X as AgentWorkflowBindingLike, Y as AgentWorkflowInstanceLike } from "./packem_shared/types.d-boAM2Yi1.mjs";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
+ export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
6
- export { type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.mjs";
7
- import { createAi } from '@lunora/ai';
5
+ export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
6
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
7
+ import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
10
10
  import '@lunora/server';
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
23
23
  env: Record<string, unknown>;
24
24
  /** The agent's `lunora/agents.ts` export name (thread attribution). */
25
25
  exportName: string;
26
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
27
+ exports?: unknown;
26
28
  /**
27
29
  * The run-end episode-summary seam — production wires AI SDK `generateText`.
28
30
  * Absent (the default) disables episode recording, so an agent with no
@@ -183,7 +185,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
183
185
  interface ToolScriptStep {
184
186
  /** A stable name later steps reference the output by. */
185
187
  id: string;
186
- /** The tool's input; values may embed `{ "$from": "&lt;stepId>", "$path": "a.b" }` refs. */
188
+ /** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
187
189
  input?: Record<string, unknown>;
188
190
  /** The tool to call — one of the tools handed to {@link codeTool}. */
189
191
  tool: string;
@@ -229,8 +231,8 @@ interface CodeToolOptions {
229
231
  * SCRIPT that composes several of the tools you hand `codeTool` — chaining a
230
232
  * later call's input to an earlier call's output — and the whole thing runs in a
231
233
  * single turn. This is a SAFE interpreted data-flow between whitelisted tools
232
- * (no `eval`, no isolate), so it runs natively in workerd; arbitrary-code
233
- * execution (the Cloudflare Worker Loader path) is a separate future mode.
234
+ * (no `eval`, no isolate), so it runs natively in workerd; for arbitrary code
235
+ * in a Worker Loader isolate, see `jsCodeTool`.
234
236
  *
235
237
  * Each composed tool dispatches through the same durable context a normal call
236
238
  * gets (inheriting RLS), with a per-step idempotency key. A code-mode script runs
@@ -239,6 +241,16 @@ interface CodeToolOptions {
239
241
  * keep approval-gated tools as normal top-level tools. Gate the whole script via
240
242
  * `opts.needsApproval` instead.
241
243
  *
244
+ * STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
245
+ * step runs inside its own durable `step.do`, so the workflow host serializes
246
+ * the returned value before the next step (or the tool result) ever sees it. A
247
+ * `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
248
+ * `null` or a dropped key, and a `bigint` throws outright. That applies to the
249
+ * value a later step reads through `{ "$from": … }` just as much as to the
250
+ * returned `results` — the hand-off is durable state, not an in-memory one. A
251
+ * composed tool that wants to pass a rich value should return its JSON form
252
+ * (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
253
+ *
242
254
  * ```ts
243
255
  * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
244
256
  *
@@ -259,8 +271,9 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
259
271
  /**
260
272
  * Build the `ctx.agents` producer surface from the codegen-emitted spec list
261
273
  * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
262
- * declared agent resolves its `AGENT_*` Workflow binding off `env` lazily, so
263
- * a missing binding only errors when that agent is actually started.
274
+ * declared agent resolves by its export key (the generated class name) off the
275
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
276
+ * lazily, so a missing agent only errors when it is actually started.
264
277
  *
265
278
  * `cancel` also needs to write the thread's status, so it dispatches the agent
266
279
  * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
@@ -269,7 +282,10 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
269
282
  * inject a `dispatch` double.
270
283
  * @experimental
271
284
  */
272
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, dispatch?: AgentRunFunction) => Record<string, AgentHandle>;
285
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
+ dispatch?: AgentRunFunction;
287
+ exports?: unknown;
288
+ }) => Record<string, AgentHandle>;
273
289
  /**
274
290
  * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
275
291
  * (each LLM turn and each tool call a named durable step; thread messages
@@ -344,8 +360,14 @@ interface FunctionToolOptions<Input> {
344
360
  * ```
345
361
  *
346
362
  * The function reference may be a typed `api.*` reference or a `"module:name"`
347
- * path. The model-provided input is passed verbatim as the function's args, so
348
- * `inputSchema` should mirror the referenced function's argument validator.
363
+ * path. The model-provided input is passed as the function's args, so
364
+ * `inputSchema` should mirror the referenced function's argument validator —
365
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
366
+ * input (so out-of-schema model input can never override it). A function
367
+ * that wants to dedupe a side-effecting call across an at-least-once step
368
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
369
+ * and checks it; a function that ignores it is unaffected — an args field
370
+ * the function's own validator doesn't declare is dropped, not rejected.
349
371
  * @experimental
350
372
  */
351
373
  declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
@@ -471,6 +493,17 @@ interface McpToolsOptions {
471
493
  command?: string;
472
494
  /** Identify this client to the server on connect. Default `"lunora-agent"`. */
473
495
  name?: string;
496
+ /**
497
+ * Gate an adapted tool's call behind a human approval. Defaults to
498
+ * **unattended** (no gate) — matching today's behavior. An MCP tool's
499
+ * result feeds back into the model's context (`adaptMcpResult`), so a
500
+ * hostile downstream server can pair indirect prompt injection with an
501
+ * unattended mutating tool call; pass a boolean to gate every adapted
502
+ * tool the same way, or a predicate `(toolName, input) => boolean` to
503
+ * gate per tool (evaluated from replay-stable input, so keep it
504
+ * deterministic).
505
+ */
506
+ needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
474
507
  /** Only adapt these tool names (default: every tool the server lists). */
475
508
  only?: ReadonlyArray<string>;
476
509
  /** Prefix added to each adapted tool's key (disambiguate multiple servers). */
@@ -510,6 +543,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
510
543
  * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
511
544
  * does not) — pass `url`, or inject an already-connected `client` for a custom
512
545
  * transport (also the test seam).
546
+ *
547
+ * Every adapted tool runs UNATTENDED by default (no approval gate) — pass
548
+ * `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
513
549
  * @experimental
514
550
  */
515
551
  declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
@@ -674,6 +710,13 @@ interface VoiceTurnResult {
674
710
  interface RunVoiceTurnOptions {
675
711
  /** The agent whose thread + models back this session. */
676
712
  agent: AgentDefinition;
713
+ /**
714
+ * History-compaction seam — the SAME one the durable loop uses. Voice and
715
+ * text turns share one thread, so an agent that declares `compaction` must
716
+ * get it here too; absent (or with no `compaction` config) the turn takes
717
+ * the byte-identical uncompacted path.
718
+ */
719
+ compact?: AgentCompact;
677
720
  /** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
678
721
  connectionId: string;
679
722
  /** The Worker env (resolves a dynamic `instructions` thunk). */
@@ -755,6 +798,8 @@ declare class VoiceSessionDO {
755
798
  protected readonly streamGenerate: AgentStreamGenerate;
756
799
  protected readonly sttModel: string;
757
800
  protected readonly ttsModel: string;
801
+ /** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
802
+ private readonly maxSessionTurns;
758
803
  private readonly audioBuffers;
759
804
  private readonly bufferedBytes;
760
805
  private readonly controllers;
@@ -793,6 +838,8 @@ declare class VoiceSessionDO {
793
838
  private synthesizeWithSignal;
794
839
  /** Abort an in-flight turn and free a socket's transient buffers. */
795
840
  private cleanupSocket;
841
+ /** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
842
+ private closeSocket;
796
843
  /** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
797
844
  private send;
798
845
  /** Send a binary audio frame, swallowing a closed-socket error. */
@@ -806,17 +853,65 @@ declare class VoiceSessionDO {
806
853
  */
807
854
  private waitForSocketDrain;
808
855
  }
856
+ /**
857
+ * Config for {@link webSearchTool}.
858
+ * @experimental
859
+ */
860
+ interface WebSearchToolOptions {
861
+ /** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
862
+ byokAlias?: string;
863
+ /** Overrides the description shown to the model. */
864
+ description?: string;
865
+ /**
866
+ * The AI Gateway that brokers and bills the search. Defaults to
867
+ * `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
868
+ */
869
+ gatewayId?: string;
870
+ /** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
871
+ limit?: number;
872
+ /** Defaults to the Web Search API's own default (`"ceramic"`). */
873
+ provider?: AiWebSearchProvider;
874
+ }
875
+ /**
876
+ * What the model passes.
877
+ * @experimental
878
+ */
879
+ interface WebSearchToolInput {
880
+ query: string;
881
+ }
882
+ /**
883
+ * A batteries-included agent tool over the Cloudflare Web Search API (beta,
884
+ * `ctx.ai.websearch`), so an agent can ground an answer in live results.
885
+ * A search bills a provider key stored on the gateway (`byokAlias`, else the
886
+ * `default` alias) when there is one, otherwise AI Gateway credits; every
887
+ * provider runs under Zero Data Retention.
888
+ *
889
+ * It calls the `AI` binding straight from the tool's durable step: a search
890
+ * is a read, so the at-least-once step retry repeats nothing but a query, and
891
+ * there is no dispatcher action to register.
892
+ *
893
+ * ```ts
894
+ * import { defineAgent, webSearchTool } from "@lunora/agent";
895
+ *
896
+ * export const researcher = defineAgent({
897
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
898
+ * tools: { search: webSearchTool({ provider: "exa" }) },
899
+ * });
900
+ * ```
901
+ * @experimental
902
+ */
903
+ declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
809
904
  /**
810
905
  * Compile a `defineAgent` definition into the workflow the generated
811
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
906
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
812
907
  *
813
908
  * ```ts
814
909
  * import LunoraWorkflow from "@lunora/workflow/do";
815
910
  * import { compileAgentWorkflow } from "@lunora/agent";
816
911
  * import { support } from "../agents.js";
817
912
  *
818
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
819
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
913
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
914
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
820
915
  * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
821
916
  * }
822
917
  * }
@@ -829,4 +924,4 @@ declare class VoiceSessionDO {
829
924
  declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
830
925
  paths?: AgentFunctionPaths;
831
926
  }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
832
- export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
927
+ export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };