@lunora/agent 1.0.0-alpha.22 → 1.0.0-alpha.220
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 +41 -2
- package/dist/component.d.ts +41 -2
- 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 +112 -17
- package/dist/index.d.ts +112 -17
- 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-B6FqQC80.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-mg6qrlU6-CT5Q5dbp.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-D7O6Fclt.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-DFF_g58r.mjs +2 -0
- package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
- package/dist/packem_shared/agent-loop-DzzRTrgP.mjs +3 -0
- package/dist/packem_shared/agentAsTool-BJi-uU4s.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-dpJANTDc.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-D07XhGKr.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-KtkWJyHR.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-Wlc1ZgWa.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-D9DbEj9I.mjs +3 -0
- package/dist/packem_shared/defineAgent-DrI8Hw7B.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-Baqdn0OK.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
- package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
- package/dist/packem_shared/otlpTelemetry-DC5n77sQ.mjs +1 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-COwgPdOl.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-DdQVm4Kv.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-Du0yENEO.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-DqYbp4ye.d.mts} +300 -27
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-DqYbp4ye.d.ts} +300 -27
- package/dist/packem_shared/voice-turn-CzFz5tWG.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BobmV4cD.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 +157 -16
- package/dist/sandbox.d.ts +157 -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 +165 -38
- package/dist/telemetry/index.d.ts +165 -38
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +19 -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-DqYbp4ye.mjs";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-DqYbp4ye.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-DqYbp4ye.js";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-DqYbp4ye.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
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { SchemaExtension } from '@lunora/server';
|
|
1
|
+
import { TableDefinition, SchemaExtension } from '@lunora/server';
|
|
2
|
+
/** The schema-extension key the agent tables merge under (`agent_*` physical names). */
|
|
3
|
+
declare const AGENT_EXTENSION_KEY: "agent";
|
|
2
4
|
/**
|
|
3
5
|
* Loose structural view of a registered Lunora function — wide enough for any
|
|
4
6
|
* concrete `RegisteredMutation`/`RegisteredQuery` (whose precise validator-map
|
|
@@ -11,6 +13,36 @@ interface AgentRegisteredFunction {
|
|
|
11
13
|
readonly kind: "mutation" | "query";
|
|
12
14
|
readonly visibility?: "internal" | "public";
|
|
13
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* The episodic-memory table, spread into the `agent` schema extension by
|
|
18
|
+
* `component.ts`. Owner-scoped (keyed by `owner`, not thread), so a run in one
|
|
19
|
+
* conversation recalls the timeline of the user's earlier runs across every
|
|
20
|
+
* thread. `.public()` + RLS-exempt like the thread/graph tables (package code,
|
|
21
|
+
* access-controlled inside the dispatched functions).
|
|
22
|
+
*
|
|
23
|
+
* Explicitly typed as a `Record` of `TableDefinition` values for the same
|
|
24
|
+
* `--isolatedDeclarations` reason as `graphTables` (an exported const with a
|
|
25
|
+
* computed key can't be inferred; see graph-component.ts).
|
|
26
|
+
*/
|
|
27
|
+
declare const episodeTables: Record<"episodes", TableDefinition>;
|
|
28
|
+
/** Bare table names — auto-prefixed with the extension key at merge time. */
|
|
29
|
+
declare const ENTITIES_BARE_TABLE = "entities";
|
|
30
|
+
declare const EDGES_BARE_TABLE = "edges";
|
|
31
|
+
/**
|
|
32
|
+
* The graph-memory tables, spread into the `agent` schema extension by
|
|
33
|
+
* `component.ts`. Owner-scoped (keyed by `owner`, not thread) so knowledge
|
|
34
|
+
* extracted in one conversation is traversable in the next, and `.public()` +
|
|
35
|
+
* RLS-exempt like the thread tables (package code, access-controlled inside the
|
|
36
|
+
* dispatched functions).
|
|
37
|
+
*
|
|
38
|
+
* Explicitly typed as a `Record` of `TableDefinition` values over its bare names
|
|
39
|
+
* because it is an EXPORTED const with computed (`[BARE]`) keys — under
|
|
40
|
+
* `--isolatedDeclarations` (packem's `.d.ts` emit) a bare exported object literal
|
|
41
|
+
* with computed keys can't have its type inferred (TS9038). The names stay
|
|
42
|
+
* literal so `.extend(agentExtension)` adds exact table names; row types come
|
|
43
|
+
* from codegen.
|
|
44
|
+
*/
|
|
45
|
+
declare const graphTables: Record<typeof EDGES_BARE_TABLE | typeof ENTITIES_BARE_TABLE, TableDefinition>;
|
|
14
46
|
/**
|
|
15
47
|
* The per-owner dedup key for an entity name: trim, collapse internal
|
|
16
48
|
* whitespace, lowercase. Deterministic (no locale) so a workflow replay or
|
|
@@ -47,6 +79,10 @@ interface SandboxComponent {
|
|
|
47
79
|
* @experimental
|
|
48
80
|
*/
|
|
49
81
|
declare const sandboxComponent: () => SandboxComponent;
|
|
82
|
+
/** Bare table names — auto-prefixed with the extension key at merge time. */
|
|
83
|
+
declare const THREADS_BARE_TABLE = "threads";
|
|
84
|
+
declare const MESSAGES_BARE_TABLE = "messages";
|
|
85
|
+
declare const RUN_QUEUE_BARE_TABLE = "run_queue";
|
|
50
86
|
/**
|
|
51
87
|
* The agent thread tables, shipped as a schema extension so an app merges
|
|
52
88
|
* them with one call and they can never collide with app tables:
|
|
@@ -63,7 +99,7 @@ declare const sandboxComponent: () => SandboxComponent;
|
|
|
63
99
|
* message is a no-op instead of a duplicate.
|
|
64
100
|
* @experimental
|
|
65
101
|
*/
|
|
66
|
-
declare const agentExtension: SchemaExtension
|
|
102
|
+
declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof MESSAGES_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
|
|
67
103
|
/**
|
|
68
104
|
* `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
|
|
69
105
|
* @experimental
|
|
@@ -72,11 +108,14 @@ interface AgentComponent {
|
|
|
72
108
|
extension: SchemaExtension;
|
|
73
109
|
functions: {
|
|
74
110
|
agentAppendMessage: AgentRegisteredFunction;
|
|
111
|
+
agentCompleteRun: AgentRegisteredFunction;
|
|
112
|
+
agentDeleteMessage: AgentRegisteredFunction;
|
|
75
113
|
agentEnsureThread: AgentRegisteredFunction;
|
|
76
114
|
agentEpisodeRecall: AgentRegisteredFunction;
|
|
77
115
|
agentEpisodeUpsert: AgentRegisteredFunction;
|
|
78
116
|
agentGraphTraverse: AgentRegisteredFunction;
|
|
79
117
|
agentGraphUpsert: AgentRegisteredFunction;
|
|
118
|
+
agentHistory: AgentRegisteredFunction;
|
|
80
119
|
agentMessages: AgentRegisteredFunction;
|
|
81
120
|
agentPatchThread: AgentRegisteredFunction;
|
|
82
121
|
agentResolveApproval: AgentRegisteredFunction;
|
package/dist/component.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { SchemaExtension } from '@lunora/server';
|
|
1
|
+
import { TableDefinition, SchemaExtension } from '@lunora/server';
|
|
2
|
+
/** The schema-extension key the agent tables merge under (`agent_*` physical names). */
|
|
3
|
+
declare const AGENT_EXTENSION_KEY: "agent";
|
|
2
4
|
/**
|
|
3
5
|
* Loose structural view of a registered Lunora function — wide enough for any
|
|
4
6
|
* concrete `RegisteredMutation`/`RegisteredQuery` (whose precise validator-map
|
|
@@ -11,6 +13,36 @@ interface AgentRegisteredFunction {
|
|
|
11
13
|
readonly kind: "mutation" | "query";
|
|
12
14
|
readonly visibility?: "internal" | "public";
|
|
13
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* The episodic-memory table, spread into the `agent` schema extension by
|
|
18
|
+
* `component.ts`. Owner-scoped (keyed by `owner`, not thread), so a run in one
|
|
19
|
+
* conversation recalls the timeline of the user's earlier runs across every
|
|
20
|
+
* thread. `.public()` + RLS-exempt like the thread/graph tables (package code,
|
|
21
|
+
* access-controlled inside the dispatched functions).
|
|
22
|
+
*
|
|
23
|
+
* Explicitly typed as a `Record` of `TableDefinition` values for the same
|
|
24
|
+
* `--isolatedDeclarations` reason as `graphTables` (an exported const with a
|
|
25
|
+
* computed key can't be inferred; see graph-component.ts).
|
|
26
|
+
*/
|
|
27
|
+
declare const episodeTables: Record<"episodes", TableDefinition>;
|
|
28
|
+
/** Bare table names — auto-prefixed with the extension key at merge time. */
|
|
29
|
+
declare const ENTITIES_BARE_TABLE = "entities";
|
|
30
|
+
declare const EDGES_BARE_TABLE = "edges";
|
|
31
|
+
/**
|
|
32
|
+
* The graph-memory tables, spread into the `agent` schema extension by
|
|
33
|
+
* `component.ts`. Owner-scoped (keyed by `owner`, not thread) so knowledge
|
|
34
|
+
* extracted in one conversation is traversable in the next, and `.public()` +
|
|
35
|
+
* RLS-exempt like the thread tables (package code, access-controlled inside the
|
|
36
|
+
* dispatched functions).
|
|
37
|
+
*
|
|
38
|
+
* Explicitly typed as a `Record` of `TableDefinition` values over its bare names
|
|
39
|
+
* because it is an EXPORTED const with computed (`[BARE]`) keys — under
|
|
40
|
+
* `--isolatedDeclarations` (packem's `.d.ts` emit) a bare exported object literal
|
|
41
|
+
* with computed keys can't have its type inferred (TS9038). The names stay
|
|
42
|
+
* literal so `.extend(agentExtension)` adds exact table names; row types come
|
|
43
|
+
* from codegen.
|
|
44
|
+
*/
|
|
45
|
+
declare const graphTables: Record<typeof EDGES_BARE_TABLE | typeof ENTITIES_BARE_TABLE, TableDefinition>;
|
|
14
46
|
/**
|
|
15
47
|
* The per-owner dedup key for an entity name: trim, collapse internal
|
|
16
48
|
* whitespace, lowercase. Deterministic (no locale) so a workflow replay or
|
|
@@ -47,6 +79,10 @@ interface SandboxComponent {
|
|
|
47
79
|
* @experimental
|
|
48
80
|
*/
|
|
49
81
|
declare const sandboxComponent: () => SandboxComponent;
|
|
82
|
+
/** Bare table names — auto-prefixed with the extension key at merge time. */
|
|
83
|
+
declare const THREADS_BARE_TABLE = "threads";
|
|
84
|
+
declare const MESSAGES_BARE_TABLE = "messages";
|
|
85
|
+
declare const RUN_QUEUE_BARE_TABLE = "run_queue";
|
|
50
86
|
/**
|
|
51
87
|
* The agent thread tables, shipped as a schema extension so an app merges
|
|
52
88
|
* them with one call and they can never collide with app tables:
|
|
@@ -63,7 +99,7 @@ declare const sandboxComponent: () => SandboxComponent;
|
|
|
63
99
|
* message is a no-op instead of a duplicate.
|
|
64
100
|
* @experimental
|
|
65
101
|
*/
|
|
66
|
-
declare const agentExtension: SchemaExtension
|
|
102
|
+
declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof MESSAGES_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
|
|
67
103
|
/**
|
|
68
104
|
* `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
|
|
69
105
|
* @experimental
|
|
@@ -72,11 +108,14 @@ interface AgentComponent {
|
|
|
72
108
|
extension: SchemaExtension;
|
|
73
109
|
functions: {
|
|
74
110
|
agentAppendMessage: AgentRegisteredFunction;
|
|
111
|
+
agentCompleteRun: AgentRegisteredFunction;
|
|
112
|
+
agentDeleteMessage: AgentRegisteredFunction;
|
|
75
113
|
agentEnsureThread: AgentRegisteredFunction;
|
|
76
114
|
agentEpisodeRecall: AgentRegisteredFunction;
|
|
77
115
|
agentEpisodeUpsert: AgentRegisteredFunction;
|
|
78
116
|
agentGraphTraverse: AgentRegisteredFunction;
|
|
79
117
|
agentGraphUpsert: AgentRegisteredFunction;
|
|
118
|
+
agentHistory: AgentRegisteredFunction;
|
|
80
119
|
agentMessages: AgentRegisteredFunction;
|
|
81
120
|
agentPatchThread: AgentRegisteredFunction;
|
|
82
121
|
agentResolveApproval: 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 _,initLunora as $,defineSchemaExtension as H}from"@lunora/server";import{v as e}from"@lunora/values";import{a as b,A as C,d as X,b as Q}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as W,graphComponent as Y}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as be}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as fe}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const k="agent_episodes",z=5,V=20,J=500,D=200,Z=/\s+/gu,ee=s=>s===void 0||!Number.isFinite(s)?z:Math.min(V,Math.max(1,Math.trunc(s))),te={episodes:_({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:ne,query:ie}=$.dataModel().create(),ae=()=>{const s=ne.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:d,ctx:l})=>{const m=d.summary.replaceAll(Z," ").trim().slice(0,J);if(m.length===0)return{recorded:!1};if(await l.db.query(k).withIndex("byOwnerMessageKey",c=>c.eq("owner",d.owner).eq("messageKey",d.messageKey)).first())return{recorded:!1};await l.db.insert(k,{createdAt:d.createdAt??Date.now(),messageKey:d.messageKey,owner:d.owner,summary:m,...d.threadKey===void 0?{}:{threadKey:d.threadKey}});const q=await l.db.query(k).withIndex("byOwnerCreatedAt",c=>c.eq("owner",d.owner)).order("asc").take(D+1);for(const c of q.slice(0,Math.max(0,q.length-D)))await l.db.delete(c._id);return{recorded:!0}}),r=ie.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:d,ctx:l})=>{const m=await l.db.query(k).withIndex("byOwnerCreatedAt",I=>I.eq("owner",d.owner)).order("desc").take(ee(d.limit));return m.length===0?{context:""}:{context:m.toReversed().map(I=>`- ${I.summary}`).join(`
|
|
2
|
+
`)}});return{agentEpisodeRecall:b(r),agentEpisodeUpsert:b(s)}},O="threads",L="messages",U="run_queue",p=`${C}_${O}`,E=`${C}_${L}`,v=`${C}_${U}`,M=5,oe=780*60*1e3,re=H(C,{tables:{[L]:_({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(),[O]:_({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")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),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(),[U]:_({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(),...W,...te}}),{mutation:f,query:T}=$.dataModel().create(),se=async(s,r,d)=>{if(r.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:l}=r,m=await s.query(v).withIndex("byThreadInstance",c=>c.eq("threadKey",r.key).eq("instanceId",l)).first();if(m)return{outcome:"queued",position:m.position};const I=await s.query(v).withIndex("byThread",c=>c.eq("threadKey",r.key)).collect();if(I.length>=M)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" run queue is full (depth ${String(M)}) — rejecting instance "${l}"`);const q=(I.at(-1)?.position??-1)+1;return await s.insert(v,{agent:r.agent,enqueuedAt:d,instanceId:l,position:q,threadKey:r.key}),{outcome:"queued",position:q}},de=async(s,r,d)=>{if(r.policy==="queue")return se(s,{agent:r.agent,instanceId:r.instanceId,key:r.key,priorInstanceId:r.priorInstanceId},d);if(r.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — onConcurrentRun="${r.policy}"`);return await s.patch(r.existingId,{error:null,status:"running",updatedAt:d,...r.instanceId===void 0?{}:{completedInstanceId:null,instanceId:r.instanceId}}),{outcome:"replaced",priorInstanceId:r.priorInstanceId}},ue=(s,r,d)=>{const l=s.instanceId;if(l===void 0||r===l||s.status!=="running"&&s.status!=="awaiting_input")return;const m=typeof s.updatedAt=="number"?s.updatedAt:0,I=s.status==="awaiting_input"?Q:oe;return d-m>I?void 0:l},he=()=>{const s=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",o=>o.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 o=ue(i,t.instanceId,a);return o!==void 0?de(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:o},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,...X({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),r=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 o=i.messageCount,u=Date.now();return await n.db.insert(E,{content:t.content,createdAt:u,messageKey:t.messageKey,role:t.role,seq:o,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:o+1,updatedAt:u}),{seq:o}}),d=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)}),l=f.input({error:e.optional(e.string()),ifInstanceId: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"))),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),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 o;i!==void 0?o=await n.db.query(p).withIndex("byKey",u=>u.eq("key",i)).first():a!==void 0&&(o=await n.db.query(p).withIndex("byInstance",u=>u.eq("instanceId",a)).first()),!(!o||t.ifInstanceId!==void 0&&o.instanceId!==t.ifInstanceId)&&await n.db.patch(o._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.summary===void 0?{}:{summary:t.summary},...t.summaryConfig===void 0?{}:{summaryConfig:t.summaryConfig},...t.summaryRebuiltSeq===void 0?{}:{summaryRebuiltSeq:t.summaryRebuiltSeq},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),m=T.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",A=>A.eq("key",t.key)).first(),i=a?.summary,o=a?.summaryThroughSeq,u=a?.summaryRebuiltSeq,y=a?.summaryConfig,h=typeof i=="string"&&i.length>0&&typeof o=="number",w=t.configKey===void 0||y===t.configKey,K=typeof u!="number"||typeof o=="number"&&o>=2*u+1,x=h&&w&&!K,R=await n.db.query(E).withIndex("byThread",A=>x?A.eq("threadKey",t.key).gt("seq",o):A.eq("threadKey",t.key)).collect();return x?{messages:R,summary:i}:h?{fallback:{summary:i,throughSeq:o},messages:R}:{messages:R}}),I=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",w=>w.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 w=await n.db.query(v).withIndex("byThreadInstance",K=>K.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return w&&await n.db.delete(w._id),{}}const y=(i.completedInstanceId===t.instanceId?[]:await n.db.query(v).withIndex("byThread",w=>w.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 h=y.instanceId;return await n.db.delete(y._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:h,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:h}}),q=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()})}),c=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},B=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 c(a,n.auth)}),j=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 c(a,n.auth)?.state}),P=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 c(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(E).withIndex("byThread",o=>o.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(E).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),F=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",h=>h.eq("key",t.threadKey)).first(),i=c(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 o=i.agent,{agents:u}=n,y=u?.[o];if(typeof y?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${o}"] 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}}),G=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 o=n.auth.userId??void 0,u=await n.db.query(p).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(u){const h=u.status,w=u.instanceId,K=u.owner;if((h==="running"||h==="awaiting_input")&&w!==void 0&&(K===void 0||K===o))return{id:w,threadKey:t.threadKey};if(K!==o)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,...o===void 0?{}:{owner:o},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),S=Y(),N=ae();return{extension:re,functions:{agentAppendMessage:b(r),agentCompleteRun:b(I),agentEnsureThread:b(s),agentEpisodeRecall:N.agentEpisodeRecall,agentEpisodeUpsert:N.agentEpisodeUpsert,agentGraphTraverse:S.agentGraphTraverse,agentGraphUpsert:S.agentGraphUpsert,agentHistory:b(m),agentMessages:P,agentDeleteMessage:b(d),agentPatchThread:b(l),agentResolveApproval:F,agentRun:G,agentSetState:b(q),agentState:j,agentThread:B}}};export{he as agentComponent,re as agentExtension,be as normalizeEntityName,fe 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-DqYbp4ye.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-DqYbp4ye.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};
|