@lunora/agent 1.0.0-alpha.16 → 1.0.0-alpha.160
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.
- package/dist/channels.d.mts +23 -12
- package/dist/channels.d.ts +23 -12
- package/dist/channels.mjs +1 -1
- package/dist/component.d.mts +2 -0
- package/dist/component.d.ts +2 -0
- package/dist/component.mjs +2 -2
- package/dist/inbound.d.mts +9 -7
- package/dist/inbound.d.ts +9 -7
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +62 -15
- package/dist/index.d.ts +62 -15
- package/dist/index.mjs +1 -1
- package/dist/naming.d.mts +3 -7
- package/dist/naming.d.ts +3 -7
- package/dist/naming.mjs +1 -1
- package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-Dc09ClZz.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
- package/dist/packem_shared/agent-loop-CQUKMFWA.mjs +3 -0
- package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
- package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
- package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
- package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-Dijgn4Cz.mjs +1 -0
- package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
- package/dist/packem_shared/createAgentContext-D3mf7LEU.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
- package/dist/packem_shared/defineAgent-CK3CpiOr.mjs +3 -0
- package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-BLOvjXGF.mjs +18 -0
- package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-DFDJPAyk.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-xFvfDZ2Q.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-CKX-iNXC.mjs +7 -0
- package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
- package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-CbYtFBw9.d.mts} +289 -27
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-CbYtFBw9.d.ts} +289 -27
- package/dist/packem_shared/voice-turn-BiDZeZwp.mjs +1 -0
- package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
- package/dist/reply.d.mts +40 -0
- package/dist/reply.d.ts +40 -0
- package/dist/reply.mjs +1 -0
- package/dist/sandbox.d.mts +114 -16
- package/dist/sandbox.d.ts +114 -16
- package/dist/sandbox.mjs +1 -1
- package/dist/skill-markdown.d.mts +36 -0
- package/dist/skill-markdown.d.ts +36 -0
- package/dist/skill-markdown.mjs +1 -0
- package/dist/telemetry/index.d.mts +152 -33
- package/dist/telemetry/index.d.ts +152 -33
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +18 -9
- package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
- package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
- package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
- package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
- package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
- package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
- package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
- package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
- package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
- package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
- package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
- package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
- package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
- package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
- package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
- package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
- package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
- package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
- package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
- package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
- package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
- package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
- package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
- package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
- package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
package/dist/channels.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
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
|
|
47
|
-
|
|
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
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
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
|
-
|
|
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,
|
|
85
|
+
export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
|
package/dist/channels.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
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
|
|
47
|
-
|
|
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
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
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
|
-
|
|
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,
|
|
85
|
+
export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
|
package/dist/channels.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
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};
|
package/dist/component.d.mts
CHANGED
|
@@ -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;
|
package/dist/component.d.ts
CHANGED
|
@@ -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;
|
package/dist/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as
|
|
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};
|
package/dist/inbound.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
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
|
|
15
|
-
|
|
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.
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* `
|
|
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-
|
|
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
|
|
15
|
-
|
|
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.
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* `
|
|
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{
|
|
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,9 +1,9 @@
|
|
|
1
|
-
import { A as AgentDefinition,
|
|
2
|
-
export type {
|
|
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 {
|
|
6
|
-
export {
|
|
5
|
+
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
|
|
6
|
+
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
|
|
7
7
|
import { createAi } from '@lunora/ai';
|
|
8
8
|
import { WorkflowDefinition } from '@lunora/workflow';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
@@ -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": "
|
|
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
|
|
233
|
-
*
|
|
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
|
|
263
|
-
*
|
|
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>,
|
|
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
|
|
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. */
|
|
@@ -808,15 +855,15 @@ declare class VoiceSessionDO {
|
|
|
808
855
|
}
|
|
809
856
|
/**
|
|
810
857
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
811
|
-
*
|
|
858
|
+
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
812
859
|
*
|
|
813
860
|
* ```ts
|
|
814
861
|
* import LunoraWorkflow from "@lunora/workflow/do";
|
|
815
862
|
* import { compileAgentWorkflow } from "@lunora/agent";
|
|
816
863
|
* import { support } from "../agents.js";
|
|
817
864
|
*
|
|
818
|
-
* export class SupportAgentWorkflow extends LunoraWorkflow
|
|
819
|
-
* public constructor(ctx: ConstructorParameters
|
|
865
|
+
* export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
866
|
+
* public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
820
867
|
* super(ctx, env, compileAgentWorkflow(support, "support"), "support");
|
|
821
868
|
* }
|
|
822
869
|
* }
|