@lunora/agent 1.0.0-alpha.15 → 1.0.0-alpha.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/channels.d.mts +14 -11
  2. package/dist/channels.d.ts +14 -11
  3. package/dist/channels.mjs +1 -1
  4. package/dist/component.d.mts +2 -0
  5. package/dist/component.d.ts +2 -0
  6. package/dist/component.mjs +2 -2
  7. package/dist/inbound.d.mts +7 -5
  8. package/dist/inbound.d.ts +7 -5
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +50 -9
  11. package/dist/index.d.ts +50 -9
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.mjs +1 -1
  14. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  15. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs +1 -0
  16. package/dist/packem_shared/VoiceSessionDO-BkPBpwRR.mjs +1 -0
  17. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  18. package/dist/packem_shared/agent-loop-CR27O7MC.mjs +3 -0
  19. package/dist/packem_shared/agentAsTool-CgZb6ycK.mjs +1 -0
  20. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  21. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  22. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  23. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  24. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  25. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  26. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  27. package/dist/packem_shared/compileAgentWorkflow-D3BN5OWk.mjs +1 -0
  28. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  29. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  30. package/dist/packem_shared/createAgentContext-BVy7RzqD.mjs +1 -0
  31. package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
  32. package/dist/packem_shared/defineAgent-uEeT0WuM.mjs +3 -0
  33. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  34. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  35. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  36. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  37. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  38. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  39. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  40. package/dist/packem_shared/runAgentLoop-Dg1GXqsX.mjs +1 -0
  41. package/dist/packem_shared/runVoiceTurn-Bs47Kfx2.mjs +1 -0
  42. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  43. package/dist/packem_shared/sandboxComponent-CKX-iNXC.mjs +7 -0
  44. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  45. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  46. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-B_VV-x4x.d.mts} +282 -23
  47. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-B_VV-x4x.d.ts} +282 -23
  48. package/dist/packem_shared/voice-turn-7a1NoDHS.mjs +1 -0
  49. package/dist/reply.d.mts +40 -0
  50. package/dist/reply.d.ts +40 -0
  51. package/dist/reply.mjs +1 -0
  52. package/dist/sandbox.d.mts +62 -16
  53. package/dist/sandbox.d.ts +62 -16
  54. package/dist/sandbox.mjs +1 -1
  55. package/dist/skill-markdown.d.mts +36 -0
  56. package/dist/skill-markdown.d.ts +36 -0
  57. package/dist/skill-markdown.mjs +1 -0
  58. package/dist/telemetry/index.d.mts +152 -33
  59. package/dist/telemetry/index.d.ts +152 -33
  60. package/dist/telemetry/index.mjs +1 -1
  61. package/package.json +18 -9
  62. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  63. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  64. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  65. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  66. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  67. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  68. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  69. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  70. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  71. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  72. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  73. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  74. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  75. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  76. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  77. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  78. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  79. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  80. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  81. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  82. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  83. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  84. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  85. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  86. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  87. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  88. package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
@@ -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-B_VV-x4x.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-B_VV-x4x.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.
@@ -51,14 +62,6 @@ interface AgentChannelTarget {
51
62
  * @experimental
52
63
  */
53
64
  type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
54
- /**
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.
60
- */
61
- declare const isDuplicateInstanceError: (error: unknown) => boolean;
62
65
  /**
63
66
  * Build an HTTP handler that starts a durable agent run from a verified inbound
64
67
  * webhook. The channel is detected from the signature headers; EACH eligible
@@ -71,4 +74,4 @@ declare const isDuplicateInstanceError: (error: unknown) => boolean;
71
74
  * @experimental
72
75
  */
73
76
  declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
74
- export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, isDuplicateInstanceError, verifyDiscord, verifyGithub, verifySlack };
77
+ 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-B_VV-x4x.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-B_VV-x4x.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.
@@ -51,14 +62,6 @@ interface AgentChannelTarget {
51
62
  * @experimental
52
63
  */
53
64
  type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
54
- /**
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.
60
- */
61
- declare const isDuplicateInstanceError: (error: unknown) => boolean;
62
65
  /**
63
66
  * Build an HTTP handler that starts a durable agent run from a verified inbound
64
67
  * webhook. The channel is detected from the signature headers; EACH eligible
@@ -71,4 +74,4 @@ declare const isDuplicateInstanceError: (error: unknown) => boolean;
71
74
  * @experimental
72
75
  */
73
76
  declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
74
- export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, isDuplicateInstanceError, verifyDiscord, verifyGithub, verifySlack };
77
+ 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 g}from"@lunora/errors";import{isDuplicateInstanceError as E}from"@lunora/workflow";import{h as A,B as R}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as k}from"./packem_shared/fnv1a-BNN96GYb.mjs";const m=300,N=/[^0-9a-f]/iu,S=new TextEncoder,u=t=>new Uint8Array(S.encode(t)),l=t=>{if(t.length%2!==0||N.test(t))throw new g("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},v=async(t,e,n)=>{try{const r=await crypto.subtle.importKey("raw",u(t),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",r,l(n),u(e))}catch{return!1}},b=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,x=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:a,timestamp:s,tolerance:o=m}=t;return!r||!s||!r.startsWith("v0=")||!b(Number(s),n,o)?!1:v(a,`v0:${s}:${e}`,r.slice(3))},T=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?v(n,e,r.slice(7)):!1},C=async t=>{const{body:e,now:n=Date.now()/1e3,publicKey:r,signature:a,timestamp:s,tolerance:o=m}=t;if(!a||!s||!b(Number(s),n,o))return!1;try{const c=await crypto.subtle.importKey("raw",l(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},c,l(a),u(s+e))}catch{return!1}},H=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"},I=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},_=async(t,e,n,r)=>{switch(t){case"discord":return C({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return T({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return x({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},B=(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}),D=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",u(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),M=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 D(e)},U=async(t,e,n,r)=>{if(A(e))throw new g("BAD_REQUEST",`@lunora/agent: inbound channel run params ${R}`);try{await t.create({id:`${n}-${k(r)}`,params:e})}catch(a){if(E(a))return w();throw a}return w()},J=t=>async(e,n)=>{const r=await e.text(),a=H(e.headers);if(a===void 0)return new Response("Unrecognized webhook",{status:400});const s=t.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===a),o={channel:a,headers:e.headers,json:()=>JSON.parse(r),rawBody:r};let c=!1;for(const{config:i,target:d}of s){const y=I(i.secret,n);if(y===void 0||!await _(a,y,e.headers,r))continue;c=!0;const p=B(a,r);if(p)return p;const h=await i.map(o);if(!h)continue;const f=n[d.binding];if(!f||typeof f.create!="function")throw new g("INTERNAL",`@lunora/agent: no Workflow binding "${d.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await U(f,h,a,await M(a,r))}return c?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{J as dispatchAgentChannel,C as verifyDiscord,T as verifyGithub,x 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-CKX-iNXC.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-B_VV-x4x.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -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-B_VV-x4x.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -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 u,authenticatesFrom as d,parseInboundEmail as g}from"@lunora/mail/inbound";import{h as l,B as m}from"./packem_shared/branch-marker-boZ00zmk.mjs";const f="message could not be processed",c=(r,o)=>{console.error("@lunora/agent/inbound: bouncing message —",o),r.message.setReject(f)},b=r=>{const o=u({dispatch:async(t,n)=>{for(const e of r){const s=e.agent.onEmail;if(!s)continue;const a=await s(t);if(a==null)continue;const i=n.env[e.binding];if(!i||typeof i.create!="function"){c(n,`@lunora/agent: no Workflow binding "${e.binding}" on env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);return}if(l(a)){c(n,`@lunora/agent: inbound run params ${m}`);return}await i.create({params:a});return}},parse:g,verify:d});return async(t,n,e)=>o(t,n,e)};export{b as dispatchAgentEmail};
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
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, d 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-B_VV-x4x.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, b as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-B_VV-x4x.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
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";
6
+ export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.mjs";
7
7
  import { createAi } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
@@ -183,7 +183,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
183
183
  interface ToolScriptStep {
184
184
  /** A stable name later steps reference the output by. */
185
185
  id: string;
186
- /** The tool's input; values may embed `{ "$from": "&lt;stepId>", "$path": "a.b" }` refs. */
186
+ /** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
187
187
  input?: Record<string, unknown>;
188
188
  /** The tool to call — one of the tools handed to {@link codeTool}. */
189
189
  tool: string;
@@ -239,6 +239,16 @@ interface CodeToolOptions {
239
239
  * keep approval-gated tools as normal top-level tools. Gate the whole script via
240
240
  * `opts.needsApproval` instead.
241
241
  *
242
+ * STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
243
+ * step runs inside its own durable `step.do`, so the workflow host serializes
244
+ * the returned value before the next step (or the tool result) ever sees it. A
245
+ * `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
246
+ * `null` or a dropped key, and a `bigint` throws outright. That applies to the
247
+ * value a later step reads through `{ "$from": … }` just as much as to the
248
+ * returned `results` — the hand-off is durable state, not an in-memory one. A
249
+ * composed tool that wants to pass a rich value should return its JSON form
250
+ * (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
251
+ *
242
252
  * ```ts
243
253
  * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
244
254
  *
@@ -344,8 +354,14 @@ interface FunctionToolOptions<Input> {
344
354
  * ```
345
355
  *
346
356
  * 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.
357
+ * path. The model-provided input is passed as the function's args, so
358
+ * `inputSchema` should mirror the referenced function's argument validator —
359
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
360
+ * input (so out-of-schema model input can never override it). A function
361
+ * that wants to dedupe a side-effecting call across an at-least-once step
362
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
363
+ * and checks it; a function that ignores it is unaffected — an args field
364
+ * the function's own validator doesn't declare is dropped, not rejected.
349
365
  * @experimental
350
366
  */
351
367
  declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
@@ -471,6 +487,17 @@ interface McpToolsOptions {
471
487
  command?: string;
472
488
  /** Identify this client to the server on connect. Default `"lunora-agent"`. */
473
489
  name?: string;
490
+ /**
491
+ * Gate an adapted tool's call behind a human approval. Defaults to
492
+ * **unattended** (no gate) — matching today's behavior. An MCP tool's
493
+ * result feeds back into the model's context (`adaptMcpResult`), so a
494
+ * hostile downstream server can pair indirect prompt injection with an
495
+ * unattended mutating tool call; pass a boolean to gate every adapted
496
+ * tool the same way, or a predicate `(toolName, input) => boolean` to
497
+ * gate per tool (evaluated from replay-stable input, so keep it
498
+ * deterministic).
499
+ */
500
+ needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
474
501
  /** Only adapt these tool names (default: every tool the server lists). */
475
502
  only?: ReadonlyArray<string>;
476
503
  /** Prefix added to each adapted tool's key (disambiguate multiple servers). */
@@ -510,6 +537,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
510
537
  * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
511
538
  * does not) — pass `url`, or inject an already-connected `client` for a custom
512
539
  * transport (also the test seam).
540
+ *
541
+ * Every adapted tool runs UNATTENDED by default (no approval gate) — pass
542
+ * `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
513
543
  * @experimental
514
544
  */
515
545
  declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
@@ -674,6 +704,13 @@ interface VoiceTurnResult {
674
704
  interface RunVoiceTurnOptions {
675
705
  /** The agent whose thread + models back this session. */
676
706
  agent: AgentDefinition;
707
+ /**
708
+ * History-compaction seam — the SAME one the durable loop uses. Voice and
709
+ * text turns share one thread, so an agent that declares `compaction` must
710
+ * get it here too; absent (or with no `compaction` config) the turn takes
711
+ * the byte-identical uncompacted path.
712
+ */
713
+ compact?: AgentCompact;
677
714
  /** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
678
715
  connectionId: string;
679
716
  /** The Worker env (resolves a dynamic `instructions` thunk). */
@@ -755,6 +792,8 @@ declare class VoiceSessionDO {
755
792
  protected readonly streamGenerate: AgentStreamGenerate;
756
793
  protected readonly sttModel: string;
757
794
  protected readonly ttsModel: string;
795
+ /** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
796
+ private readonly maxSessionTurns;
758
797
  private readonly audioBuffers;
759
798
  private readonly bufferedBytes;
760
799
  private readonly controllers;
@@ -793,6 +832,8 @@ declare class VoiceSessionDO {
793
832
  private synthesizeWithSignal;
794
833
  /** Abort an in-flight turn and free a socket's transient buffers. */
795
834
  private cleanupSocket;
835
+ /** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
836
+ private closeSocket;
796
837
  /** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
797
838
  private send;
798
839
  /** Send a binary audio frame, swallowing a closed-socket error. */
@@ -808,15 +849,15 @@ declare class VoiceSessionDO {
808
849
  }
809
850
  /**
810
851
  * Compile a `defineAgent` definition into the workflow the generated
811
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
852
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
812
853
  *
813
854
  * ```ts
814
855
  * import LunoraWorkflow from "@lunora/workflow/do";
815
856
  * import { compileAgentWorkflow } from "@lunora/agent";
816
857
  * import { support } from "../agents.js";
817
858
  *
818
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
819
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
859
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
860
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
820
861
  * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
821
862
  * }
822
863
  * }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
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.js";
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.js";
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, d 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-B_VV-x4x.js";
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, b as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-B_VV-x4x.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
5
  export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
6
- export { type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.js";
6
+ export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, browserTool, containerTool, fsTool } from "./sandbox.js";
7
7
  import { createAi } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
@@ -183,7 +183,7 @@ declare const agentAsTool: (options: AgentAsToolOptions) => AgentToolDefinition<
183
183
  interface ToolScriptStep {
184
184
  /** A stable name later steps reference the output by. */
185
185
  id: string;
186
- /** The tool's input; values may embed `{ "$from": "&lt;stepId>", "$path": "a.b" }` refs. */
186
+ /** The tool's input; values may embed `{ "$from": "<stepId>", "$path": "a.b" }` refs. */
187
187
  input?: Record<string, unknown>;
188
188
  /** The tool to call — one of the tools handed to {@link codeTool}. */
189
189
  tool: string;
@@ -239,6 +239,16 @@ interface CodeToolOptions {
239
239
  * keep approval-gated tools as normal top-level tools. Gate the whole script via
240
240
  * `opts.needsApproval` instead.
241
241
  *
242
+ * STEP-OUTPUT CONTRACT — **every step's output must be JSON-serializable.** Each
243
+ * step runs inside its own durable `step.do`, so the workflow host serializes
244
+ * the returned value before the next step (or the tool result) ever sees it. A
245
+ * `Date` comes back as an ISO string, a `Map`/`Set` as `{}`, `undefined` as
246
+ * `null` or a dropped key, and a `bigint` throws outright. That applies to the
247
+ * value a later step reads through `{ "$from": … }` just as much as to the
248
+ * returned `results` — the hand-off is durable state, not an in-memory one. A
249
+ * composed tool that wants to pass a rich value should return its JSON form
250
+ * (`date.toISOString()`, `[...map]`) and let the consuming step rebuild it.
251
+ *
242
252
  * ```ts
243
253
  * import { codeTool, defineAgent, functionTool } from "@lunora/agent";
244
254
  *
@@ -344,8 +354,14 @@ interface FunctionToolOptions<Input> {
344
354
  * ```
345
355
  *
346
356
  * 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.
357
+ * path. The model-provided input is passed as the function's args, so
358
+ * `inputSchema` should mirror the referenced function's argument validator —
359
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
360
+ * input (so out-of-schema model input can never override it). A function
361
+ * that wants to dedupe a side-effecting call across an at-least-once step
362
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
363
+ * and checks it; a function that ignores it is unaffected — an args field
364
+ * the function's own validator doesn't declare is dropped, not rejected.
349
365
  * @experimental
350
366
  */
351
367
  declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
@@ -471,6 +487,17 @@ interface McpToolsOptions {
471
487
  command?: string;
472
488
  /** Identify this client to the server on connect. Default `"lunora-agent"`. */
473
489
  name?: string;
490
+ /**
491
+ * Gate an adapted tool's call behind a human approval. Defaults to
492
+ * **unattended** (no gate) — matching today's behavior. An MCP tool's
493
+ * result feeds back into the model's context (`adaptMcpResult`), so a
494
+ * hostile downstream server can pair indirect prompt injection with an
495
+ * unattended mutating tool call; pass a boolean to gate every adapted
496
+ * tool the same way, or a predicate `(toolName, input) => boolean` to
497
+ * gate per tool (evaluated from replay-stable input, so keep it
498
+ * deterministic).
499
+ */
500
+ needsApproval?: ((toolName: string, input: Record<string, unknown>) => boolean) | boolean;
474
501
  /** Only adapt these tool names (default: every tool the server lists). */
475
502
  only?: ReadonlyArray<string>;
476
503
  /** Prefix added to each adapted tool's key (disambiguate multiple servers). */
@@ -510,6 +537,9 @@ declare const adaptMcpResult: (result: McpCallResult) => unknown;
510
537
  * every call. In the Workers runtime only the HTTP/SSE transports run (stdio
511
538
  * does not) — pass `url`, or inject an already-connected `client` for a custom
512
539
  * transport (also the test seam).
540
+ *
541
+ * Every adapted tool runs UNATTENDED by default (no approval gate) — pass
542
+ * `opts.needsApproval` to change that; see {@link McpToolsOptions.needsApproval}.
513
543
  * @experimental
514
544
  */
515
545
  declare const mcpTools: (options: McpToolsOptions) => Promise<Record<string, AgentToolDefinition<Record<string, unknown>>>>;
@@ -674,6 +704,13 @@ interface VoiceTurnResult {
674
704
  interface RunVoiceTurnOptions {
675
705
  /** The agent whose thread + models back this session. */
676
706
  agent: AgentDefinition;
707
+ /**
708
+ * History-compaction seam — the SAME one the durable loop uses. Voice and
709
+ * text turns share one thread, so an agent that declares `compaction` must
710
+ * get it here too; absent (or with no `compaction` config) the turn takes
711
+ * the byte-identical uncompacted path.
712
+ */
713
+ compact?: AgentCompact;
677
714
  /** Stable per-socket id — the message-key prefix that keeps persisted rows idempotent. */
678
715
  connectionId: string;
679
716
  /** The Worker env (resolves a dynamic `instructions` thunk). */
@@ -755,6 +792,8 @@ declare class VoiceSessionDO {
755
792
  protected readonly streamGenerate: AgentStreamGenerate;
756
793
  protected readonly sttModel: string;
757
794
  protected readonly ttsModel: string;
795
+ /** Turn budget for one socket — see {@link DEFAULT_MAX_SESSION_TURNS}. */
796
+ private readonly maxSessionTurns;
758
797
  private readonly audioBuffers;
759
798
  private readonly bufferedBytes;
760
799
  private readonly controllers;
@@ -793,6 +832,8 @@ declare class VoiceSessionDO {
793
832
  private synthesizeWithSignal;
794
833
  /** Abort an in-flight turn and free a socket's transient buffers. */
795
834
  private cleanupSocket;
835
+ /** Close a socket that broke a session bound, swallowing an already-closed error (never throw from a handler). */
836
+ private closeSocket;
796
837
  /** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
797
838
  private send;
798
839
  /** Send a binary audio frame, swallowing a closed-socket error. */
@@ -808,15 +849,15 @@ declare class VoiceSessionDO {
808
849
  }
809
850
  /**
810
851
  * Compile a `defineAgent` definition into the workflow the generated
811
- * `&lt;Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
852
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
812
853
  *
813
854
  * ```ts
814
855
  * import LunoraWorkflow from "@lunora/workflow/do";
815
856
  * import { compileAgentWorkflow } from "@lunora/agent";
816
857
  * import { support } from "../agents.js";
817
858
  *
818
- * export class SupportAgentWorkflow extends LunoraWorkflow&lt;AgentRunInput, AgentRunResult> {
819
- * public constructor(ctx: ConstructorParameters&lt;typeof LunoraWorkflow>[0], env: Record&lt;string, unknown>) {
859
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
860
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
820
861
  * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
821
862
  * }
822
863
  * }
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-DNAt-pGz.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-CJCTyAQG.mjs";import{codeTool as p}from"./packem_shared/codeTool-DYJVy-bH.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-B1IfI7ro.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CKhzzmys.mjs";import{functionTool as D}from"./packem_shared/functionTool-CWHhkYqd.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BUVImo85.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-18G7zpFo.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-BXx-tSCe.mjs";import{browserTool as j,containerTool as q,fsTool as z}from"./sandbox.mjs";import{defineSkill as Q,isSkillDefinition as Y}from"./packem_shared/defineSkill-DfJxCwfZ.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-CTaBSdXk.mjs";import{runVoiceTurn as oe}from"./packem_shared/runVoiceTurn-PkMsfG_v.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-C4xqSw82.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,j as browserTool,k as buildModelMessages,p as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,q as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,Q as defineSkill,z as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
1
+ import{r as t,s as r}from"./packem_shared/agent-loop-CR27O7MC.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-CgZb6ycK.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-BVy7RzqD.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-uEeT0WuM.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as j,containerTool as q,fsTool as z}from"./sandbox.mjs";import{defineSkill as Q,isSkillDefinition as Y}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-BkPBpwRR.mjs";import{r as oe}from"./packem_shared/voice-turn-7a1NoDHS.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-D3BN5OWk.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,j as browserTool,k as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,q as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,Q as defineSkill,z as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
package/dist/naming.mjs CHANGED
@@ -1 +1 @@
1
- const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,l=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,r=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{t as agentBindingName,s as agentClassName,l as agentDefaultName,r as voiceBindingName,o as voiceClassName};
1
+ const a=/([a-z0-9])([A-Z])/gu,t=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,s=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,c=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,l=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{s as agentBindingName,t as agentClassName,c as agentDefaultName,l as voiceBindingName,o as voiceClassName};
@@ -0,0 +1 @@
1
+ const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};