@lunora/agent 0.0.0 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +48 -43
  3. package/dist/channels.d.mts +54 -0
  4. package/dist/channels.d.ts +54 -0
  5. package/dist/channels.mjs +181 -0
  6. package/dist/component.d.mts +101 -0
  7. package/dist/component.d.ts +101 -0
  8. package/dist/component.mjs +407 -0
  9. package/dist/inbound.d.mts +29 -0
  10. package/dist/inbound.d.ts +29 -0
  11. package/dist/inbound.mjs +32 -0
  12. package/dist/index.d.mts +740 -0
  13. package/dist/index.d.ts +740 -0
  14. package/dist/index.mjs +18 -0
  15. package/dist/naming.d.mts +17 -0
  16. package/dist/naming.d.ts +17 -0
  17. package/dist/naming.mjs +8 -0
  18. package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +24 -0
  19. package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +297 -0
  20. package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +65 -0
  21. package/dist/packem_shared/agentAsTool-Dt8NlU6k.mjs +94 -0
  22. package/dist/packem_shared/base64-BVwtgRJV.mjs +18 -0
  23. package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +47 -0
  24. package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +69 -0
  25. package/dist/packem_shared/codeTool-CjgJOC9t.mjs +122 -0
  26. package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +97 -0
  27. package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +43 -0
  28. package/dist/packem_shared/common-DAeFCot5.mjs +61 -0
  29. package/dist/packem_shared/compileAgentWorkflow-BxJjHgtD.mjs +55 -0
  30. package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +93 -0
  31. package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +50 -0
  32. package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +192 -0
  33. package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +69 -0
  34. package/dist/packem_shared/defineAgent-D6maSbVc.mjs +148 -0
  35. package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +22 -0
  36. package/dist/packem_shared/functionTool-D6lCa2jB.mjs +20 -0
  37. package/dist/packem_shared/graph-component-aoUwO-f0.mjs +216 -0
  38. package/dist/packem_shared/memory-D4FPcBsX.mjs +12 -0
  39. package/dist/packem_shared/normalizeEntityName-CyEEWFkR.mjs +3 -0
  40. package/dist/packem_shared/runAgentLoop-Dhg4ZNvw.mjs +493 -0
  41. package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +211 -0
  42. package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +194 -0
  43. package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +36 -0
  44. package/dist/packem_shared/types.d-BWG0uUtX.d.mts +1015 -0
  45. package/dist/packem_shared/types.d-BWG0uUtX.d.ts +1015 -0
  46. package/dist/sandbox.d.mts +185 -0
  47. package/dist/sandbox.d.ts +185 -0
  48. package/dist/sandbox.mjs +109 -0
  49. package/dist/telemetry/index.d.mts +150 -0
  50. package/dist/telemetry/index.d.ts +150 -0
  51. package/dist/telemetry/index.mjs +4 -0
  52. package/package.json +88 -7
package/LICENSE.md ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 anolilab and contributors
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or service
34
+ that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software that
39
+ exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee using
52
+ the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to the
59
+ infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN
79
+ IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following will
93
+ apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,45 +1,50 @@
1
1
  # @lunora/agent
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
4
-
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
-
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@lunora/agent`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
3
+ Durable AI agents for [Lunora](https://lunora.sh): `defineAgent` compiles a replay-safe tool-loop onto Cloudflare Workflows — each LLM turn and each tool call is a named durable step, thread messages persist idempotently in DO SQLite, and clients watch the conversation live over Lunora's reactive subscriptions.
4
+
5
+ ```ts
6
+ // lunora/agents.ts
7
+ import { defineAgent, defineAgentTool } from "@lunora/agent";
8
+ import { jsonSchema } from "@lunora/ai";
9
+
10
+ export const support = defineAgent({
11
+ instructions: "You are a helpful support agent.",
12
+ memory: { source: "rag:searchDocs" }, // an action over @lunora/ai/rag's retrieve
13
+ model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
14
+ tools: {
15
+ getWeather: defineAgentTool({
16
+ description: "Look up the current weather for a city.",
17
+ execute: async ({ city }, { idempotencyKey, run }) => run({ __lunoraRef: "weather:lookup" }, { city, key: idempotencyKey }),
18
+ inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
19
+ }),
20
+ },
21
+ });
22
+ ```
23
+
24
+ Codegen auto-registers the agent runtime functions (`agents:agentMessages`, …) and the
25
+ `ctx.agents.support` producer as soon as an agent is declared — no re-export boilerplate.
26
+
27
+ ```ts
28
+ // lunora/schema.ts — merge the thread tables (auto-prefixed agent_threads / agent_messages):
29
+ export default defineSchema({ ... }).extend(agentExtension);
30
+
31
+ // start a run from a mutation/action:
32
+ const { id } = await ctx.agents.support.run({ input: message, owner: ctx.auth.userId, threadKey });
33
+
34
+ // watch it live from the client (every turn, tool call, and reply streams in):
35
+ useSubscription(api.agents.agentMessages, { key: threadKey });
36
+ ```
37
+
38
+ ## Why durable
39
+
40
+ - A **completed** step is memoized by Cloudflare Workflows — a resumed run never re-executes a finished tool call (no double-charged card).
41
+ - A **failed** step is retried at-least-once — side-effecting tools receive their deterministic step name as `ctx.idempotencyKey` to dedupe on.
42
+ - Message writes are keyed and idempotent — replays never duplicate the thread.
43
+ - Owned threads (`owner: ctx.auth.userId`) are readable only by their owner — a mismatch looks like a missing thread.
44
+ - The 10-minute action ceiling doesn't exist here: slow tools and long loops are just workflow steps.
45
+
46
+ See the package docs for the full API.
47
+
48
+ ## License
49
+
50
+ FSL-1.1-Apache-2.0
@@ -0,0 +1,54 @@
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-BWG0uUtX.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-BWG0uUtX.mjs";
3
+ import '@lunora/mail/inbound';
4
+ import 'ai';
5
+ /**
6
+ * Verify a Slack request signature (`x-slack-signature` = `v0=` + HMAC over
7
+ * `v0:timestamp:body`), rejecting a stale timestamp to bound replay. `now` is
8
+ * injectable for deterministic tests (defaults to the wall clock).
9
+ */
10
+ declare const verifySlack: (options: {
11
+ body: string;
12
+ now?: number;
13
+ signature: string | undefined;
14
+ signingSecret: string;
15
+ timestamp: string | undefined;
16
+ tolerance?: number;
17
+ }) => Promise<boolean>;
18
+ /** Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body). */
19
+ declare const verifyGithub: (options: {
20
+ body: string;
21
+ secret: string;
22
+ signature: string | undefined;
23
+ }) => Promise<boolean>;
24
+ /**
25
+ * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
26
+ * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
27
+ */
28
+ declare const verifyDiscord: (options: {
29
+ body: string;
30
+ publicKey: string;
31
+ signature: string | undefined;
32
+ timestamp: string | undefined;
33
+ }) => Promise<boolean>;
34
+ /** One agent wired into the inbound channel HTTP handler. */
35
+ interface AgentChannelTarget {
36
+ /** The agent definition — only its `onInbound` config is read. */
37
+ agent: Pick<AgentDefinition, "onInbound">;
38
+ /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
39
+ binding: string;
40
+ }
41
+ /** The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route. */
42
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
43
+ /**
44
+ * Build an HTTP handler that starts a durable agent run from a verified inbound
45
+ * webhook. The channel is detected from the signature headers; EACH eligible
46
+ * target is verified against ITS OWN secret before its mapper is offered the
47
+ * event (so one app's valid signature can't trigger another app's agent), and
48
+ * the first target that both verifies and claims starts a run on its Workflow
49
+ * binding. Returns `401` when NO target's signature verifies, `200` on a claim
50
+ * (or a Discord PONG), `204` when a verified event is declined by every mapper,
51
+ * and `400` for an unrecognized webhook.
52
+ */
53
+ declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
54
+ export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
@@ -0,0 +1,54 @@
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-BWG0uUtX.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-BWG0uUtX.js";
3
+ import '@lunora/mail/inbound';
4
+ import 'ai';
5
+ /**
6
+ * Verify a Slack request signature (`x-slack-signature` = `v0=` + HMAC over
7
+ * `v0:timestamp:body`), rejecting a stale timestamp to bound replay. `now` is
8
+ * injectable for deterministic tests (defaults to the wall clock).
9
+ */
10
+ declare const verifySlack: (options: {
11
+ body: string;
12
+ now?: number;
13
+ signature: string | undefined;
14
+ signingSecret: string;
15
+ timestamp: string | undefined;
16
+ tolerance?: number;
17
+ }) => Promise<boolean>;
18
+ /** Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body). */
19
+ declare const verifyGithub: (options: {
20
+ body: string;
21
+ secret: string;
22
+ signature: string | undefined;
23
+ }) => Promise<boolean>;
24
+ /**
25
+ * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
26
+ * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
27
+ */
28
+ declare const verifyDiscord: (options: {
29
+ body: string;
30
+ publicKey: string;
31
+ signature: string | undefined;
32
+ timestamp: string | undefined;
33
+ }) => Promise<boolean>;
34
+ /** One agent wired into the inbound channel HTTP handler. */
35
+ interface AgentChannelTarget {
36
+ /** The agent definition — only its `onInbound` config is read. */
37
+ agent: Pick<AgentDefinition, "onInbound">;
38
+ /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
39
+ binding: string;
40
+ }
41
+ /** The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route. */
42
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
43
+ /**
44
+ * Build an HTTP handler that starts a durable agent run from a verified inbound
45
+ * webhook. The channel is detected from the signature headers; EACH eligible
46
+ * target is verified against ITS OWN secret before its mapper is offered the
47
+ * event (so one app's valid signature can't trigger another app's agent), and
48
+ * the first target that both verifies and claims starts a run on its Workflow
49
+ * binding. Returns `401` when NO target's signature verifies, `200` on a claim
50
+ * (or a Discord PONG), `204` when a verified event is declined by every mapper,
51
+ * and `400` for an unrecognized webhook.
52
+ */
53
+ declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
54
+ export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
@@ -0,0 +1,181 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+
3
+ const DEFAULT_TIMESTAMP_TOLERANCE = 300;
4
+ const NON_HEX = /[^0-9a-f]/iu;
5
+ const encoder = new TextEncoder();
6
+ const utf8 = (value) => new Uint8Array(encoder.encode(value));
7
+ const hexToBytes = (hex) => {
8
+ if (hex.length % 2 !== 0 || NON_HEX.test(hex)) {
9
+ throw new LunoraError("BAD_REQUEST", "@lunora/agent: malformed hex signature");
10
+ }
11
+ const bytes = new Uint8Array(hex.length / 2);
12
+ for (let index = 0; index < bytes.length; index += 1) {
13
+ bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
14
+ }
15
+ return bytes;
16
+ };
17
+ const verifyHmacSha256 = async (secret, message, signatureHex) => {
18
+ try {
19
+ const key = await crypto.subtle.importKey("raw", utf8(secret), { hash: "SHA-256", name: "HMAC" }, false, ["verify"]);
20
+ return await crypto.subtle.verify("HMAC", key, hexToBytes(signatureHex), utf8(message));
21
+ } catch {
22
+ return false;
23
+ }
24
+ };
25
+ const isFreshTimestamp = (timestampSeconds, nowSeconds, tolerance) => Number.isFinite(timestampSeconds) && Math.abs(nowSeconds - timestampSeconds) <= tolerance;
26
+ const verifySlack = async (options) => {
27
+ const { body, now = Date.now() / 1e3, signature, signingSecret, timestamp, tolerance = DEFAULT_TIMESTAMP_TOLERANCE } = options;
28
+ if (!signature || !timestamp || !signature.startsWith("v0=")) {
29
+ return false;
30
+ }
31
+ if (!isFreshTimestamp(Number(timestamp), now, tolerance)) {
32
+ return false;
33
+ }
34
+ return verifyHmacSha256(signingSecret, `v0:${timestamp}:${body}`, signature.slice("v0=".length));
35
+ };
36
+ const verifyGithub = async (options) => {
37
+ const { body, secret, signature } = options;
38
+ if (!signature?.startsWith("sha256=")) {
39
+ return false;
40
+ }
41
+ return verifyHmacSha256(secret, body, signature.slice("sha256=".length));
42
+ };
43
+ const verifyDiscord = async (options) => {
44
+ const { body, publicKey, signature, timestamp } = options;
45
+ if (!signature || !timestamp) {
46
+ return false;
47
+ }
48
+ try {
49
+ const key = await crypto.subtle.importKey("raw", hexToBytes(publicKey), { name: "Ed25519" }, false, ["verify"]);
50
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, hexToBytes(signature), utf8(timestamp + body));
51
+ } catch {
52
+ return false;
53
+ }
54
+ };
55
+ const detectChannel = (headers) => {
56
+ if (headers.has("x-slack-signature")) {
57
+ return "slack";
58
+ }
59
+ if (headers.has("x-hub-signature-256")) {
60
+ return "github";
61
+ }
62
+ if (headers.has("x-signature-ed25519")) {
63
+ return "discord";
64
+ }
65
+ return void 0;
66
+ };
67
+ const resolveSecret = (secret, env) => {
68
+ if (typeof secret === "function") {
69
+ return secret(env);
70
+ }
71
+ const value = env[secret];
72
+ return typeof value === "string" ? value : void 0;
73
+ };
74
+ const verifyChannel = async (channel, secret, headers, body) => {
75
+ switch (channel) {
76
+ case "discord": {
77
+ return verifyDiscord({
78
+ body,
79
+ publicKey: secret,
80
+ signature: headers.get("x-signature-ed25519") ?? void 0,
81
+ timestamp: headers.get("x-signature-timestamp") ?? void 0
82
+ });
83
+ }
84
+ case "github": {
85
+ return verifyGithub({ body, secret, signature: headers.get("x-hub-signature-256") ?? void 0 });
86
+ }
87
+ case "slack": {
88
+ return verifySlack({
89
+ body,
90
+ signature: headers.get("x-slack-signature") ?? void 0,
91
+ signingSecret: secret,
92
+ timestamp: headers.get("x-slack-request-timestamp") ?? void 0
93
+ });
94
+ }
95
+ default: {
96
+ return false;
97
+ }
98
+ }
99
+ };
100
+ const discordPongResponse = (channel, body) => {
101
+ if (channel !== "discord") {
102
+ return void 0;
103
+ }
104
+ try {
105
+ if (JSON.parse(body).type === 1) {
106
+ return Response.json({ type: 1 });
107
+ }
108
+ } catch {
109
+ }
110
+ return void 0;
111
+ };
112
+ const UNSAFE_INSTANCE_ID = /[^\w-]/gu;
113
+ const DUPLICATE_INSTANCE = /already[\s-]?exists/iu;
114
+ const ack = () => new Response(void 0, { status: 200 });
115
+ const isDuplicateInstanceError = (error) => DUPLICATE_INSTANCE.test(error instanceof Error ? error.message : String(error));
116
+ const deliveryId = (channel, headers, body) => {
117
+ if (channel === "github") {
118
+ return headers.get("x-github-delivery") ?? void 0;
119
+ }
120
+ try {
121
+ const parsed = JSON.parse(body);
122
+ const raw = channel === "slack" ? parsed.event_id : parsed.id;
123
+ return typeof raw === "string" ? raw : void 0;
124
+ } catch {
125
+ return void 0;
126
+ }
127
+ };
128
+ const startChannelRun = async (workflow, run, channel, id) => {
129
+ const sanitizedId = id === void 0 ? "" : id.replaceAll(UNSAFE_INSTANCE_ID, "");
130
+ if (sanitizedId === "") {
131
+ await workflow.create({ params: run });
132
+ return ack();
133
+ }
134
+ try {
135
+ await workflow.create({ id: `${channel}-${sanitizedId}`.slice(0, 60), params: run });
136
+ } catch (error) {
137
+ if (isDuplicateInstanceError(error)) {
138
+ return ack();
139
+ }
140
+ throw error;
141
+ }
142
+ return ack();
143
+ };
144
+ const dispatchAgentChannel = (targets) => async (request, env) => {
145
+ const body = await request.text();
146
+ const channel = detectChannel(request.headers);
147
+ if (channel === void 0) {
148
+ return new Response("Unrecognized webhook", { status: 400 });
149
+ }
150
+ const eligible = targets.map((target) => {
151
+ return { config: target.agent.onInbound, target };
152
+ }).filter((entry) => entry.config?.channel === channel);
153
+ const event = { channel, headers: request.headers, json: () => JSON.parse(body), rawBody: body };
154
+ let verifiedAny = false;
155
+ for (const { config, target } of eligible) {
156
+ const secret = resolveSecret(config.secret, env);
157
+ if (secret === void 0 || !await verifyChannel(channel, secret, request.headers, body)) {
158
+ continue;
159
+ }
160
+ verifiedAny = true;
161
+ const pong = discordPongResponse(channel, body);
162
+ if (pong) {
163
+ return pong;
164
+ }
165
+ const run = await config.map(event);
166
+ if (!run) {
167
+ continue;
168
+ }
169
+ const workflow = env[target.binding];
170
+ if (!workflow || typeof workflow.create !== "function") {
171
+ throw new LunoraError(
172
+ "INTERNAL",
173
+ `@lunora/agent: no Workflow binding "${target.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`
174
+ );
175
+ }
176
+ return await startChannelRun(workflow, run, channel, deliveryId(channel, request.headers, body));
177
+ }
178
+ return verifiedAny ? new Response(void 0, { status: 204 }) : new Response("Invalid signature", { status: 401 });
179
+ };
180
+
181
+ export { dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
@@ -0,0 +1,101 @@
1
+ import { SchemaExtension } from '@lunora/server';
2
+ /**
3
+ * Loose structural view of a registered Lunora function — wide enough for any
4
+ * concrete `RegisteredMutation`/`RegisteredQuery` (whose precise validator-map
5
+ * generics make them invariant), narrow enough for re-export, dispatch, and
6
+ * tests. Codegen registers the runtime value; it never needs the generics.
7
+ */
8
+ interface AgentRegisteredFunction {
9
+ readonly args: unknown;
10
+ readonly handler: (context: unknown, args: never) => unknown;
11
+ readonly kind: "mutation" | "query";
12
+ readonly visibility?: "internal" | "public";
13
+ }
14
+ /** Stamp a registered function internal — server-side callable only. */
15
+
16
+ /**
17
+ * The per-owner dedup key for an entity name: trim, collapse internal
18
+ * whitespace, lowercase. Deterministic (no locale) so a workflow replay or
19
+ * retry writes the exact same key — the graph upsert stays idempotent.
20
+ */
21
+ declare const normalizeEntityName: (name: string) => string;
22
+ /** The two internal graph-memory functions the durable loop dispatches to. */
23
+
24
+ /**
25
+ * Loose structural view of the registered sandbox action — wide enough for the
26
+ * concrete `RegisteredAction`, narrow enough for re-export + dispatch. Codegen
27
+ * registers the runtime value; it never needs the precise generics.
28
+ */
29
+ interface SandboxRegisteredFunction {
30
+ readonly args: unknown;
31
+ readonly handler: (context: unknown, args: never) => unknown;
32
+ readonly kind: "action";
33
+ readonly visibility?: "internal" | "public";
34
+ }
35
+ interface SandboxComponent {
36
+ invoke: SandboxRegisteredFunction;
37
+ }
38
+ /**
39
+ * Resolve a model-supplied `path` to an absolute R2 key UNDER `root`, rejecting
40
+ * any `..` that would escape the sandbox root. Every returned key is guaranteed
41
+ * to start with the normalized `root`, so the model can never read or write
42
+ * outside its own prefix — the fs sandbox's core isolation guarantee.
43
+ */
44
+ /**
45
+ * Build the sandbox runtime component: the single internal action the
46
+ * batteries-included `browserTool`/`containerTool` dispatch to. Codegen
47
+ * auto-registers it at `sandbox:invoke` whenever `lunora/` imports a sandbox
48
+ * tool. It runs as an **action** because that is the only ctx codegen attaches
49
+ * `ctx.browser` to (and `ctx.containers` rides every ctx once a container is
50
+ * declared) — the durable tool step itself has neither.
51
+ */
52
+ declare const sandboxComponent: () => SandboxComponent;
53
+ /**
54
+ * The agent thread tables, shipped as a schema extension so an app merges
55
+ * them with one call and they can never collide with app tables:
56
+ *
57
+ * ```ts
58
+ * // lunora/schema.ts
59
+ * export default defineSchema({ ... }).extend(agentExtension);
60
+ * ```
61
+ *
62
+ * Message ordering follows the Convex-agent model: `seq` is the monotonic
63
+ * per-thread position (allocated from the thread's `messageCount` counter, so
64
+ * allocation is O(1) inside the serialized mutation), and `messageKey` is the
65
+ * deterministic idempotency key — a workflow replay that re-persists the same
66
+ * message is a no-op instead of a duplicate.
67
+ */
68
+ declare const agentExtension: SchemaExtension;
69
+ interface AgentComponent {
70
+ extension: SchemaExtension;
71
+ functions: {
72
+ agentAppendMessage: AgentRegisteredFunction;
73
+ agentEnsureThread: AgentRegisteredFunction;
74
+ agentEpisodeRecall: AgentRegisteredFunction;
75
+ agentEpisodeUpsert: AgentRegisteredFunction;
76
+ agentGraphTraverse: AgentRegisteredFunction;
77
+ agentGraphUpsert: AgentRegisteredFunction;
78
+ agentMessages: AgentRegisteredFunction;
79
+ agentPatchThread: AgentRegisteredFunction;
80
+ agentResolveApproval: AgentRegisteredFunction;
81
+ agentRun: AgentRegisteredFunction;
82
+ agentSetState: AgentRegisteredFunction;
83
+ agentState: AgentRegisteredFunction;
84
+ agentThread: AgentRegisteredFunction;
85
+ };
86
+ }
87
+ /**
88
+ * Build the agent runtime component: the thread schema extension plus the
89
+ * functions the durable loop dispatches to (and the client subscribes to).
90
+ * Codegen auto-registers them under the `agents:*` namespace whenever
91
+ * `lunora/agents.ts` declares an agent — the loop's dispatch paths assume
92
+ * that namespace, and apps never re-export these by hand.
93
+ *
94
+ * Most mutations are **internal** (only the workflow's admin-authenticated
95
+ * dispatch may call them); the queries are public so a client can subscribe
96
+ * to `agents:agentMessages` for a live thread view. Two mutations are public:
97
+ * `agentResolveApproval` (a client resolves a HITL approval) and `agentRun`
98
+ * (an HTTP client starts a durable run) — both owner-gated.
99
+ */
100
+ declare const agentComponent: () => AgentComponent;
101
+ export { AgentComponent, type SandboxComponent, type SandboxRegisteredFunction, agentComponent, agentExtension, normalizeEntityName, sandboxComponent };