@lunora/agent 0.0.0 → 1.0.0-alpha.2
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/LICENSE.md +105 -0
- package/README.md +38 -31
- package/dist/channels.d.mts +66 -0
- package/dist/channels.d.ts +66 -0
- package/dist/channels.mjs +181 -0
- package/dist/component.d.mts +115 -0
- package/dist/component.d.ts +115 -0
- package/dist/component.mjs +407 -0
- package/dist/inbound.d.mts +34 -0
- package/dist/inbound.d.ts +34 -0
- package/dist/inbound.mjs +32 -0
- package/dist/index.d.mts +848 -0
- package/dist/index.d.ts +848 -0
- package/dist/index.mjs +18 -0
- package/dist/naming.d.mts +30 -0
- package/dist/naming.d.ts +30 -0
- package/dist/naming.mjs +8 -0
- package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +24 -0
- package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +297 -0
- package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +65 -0
- package/dist/packem_shared/agentAsTool-Dt8NlU6k.mjs +94 -0
- package/dist/packem_shared/base64-BVwtgRJV.mjs +18 -0
- package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +47 -0
- package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +69 -0
- package/dist/packem_shared/codeTool-CjgJOC9t.mjs +122 -0
- package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +97 -0
- package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +43 -0
- package/dist/packem_shared/common-DAeFCot5.mjs +61 -0
- package/dist/packem_shared/compileAgentWorkflow-BxJjHgtD.mjs +55 -0
- package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +93 -0
- package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +50 -0
- package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +192 -0
- package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +69 -0
- package/dist/packem_shared/defineAgent-D6maSbVc.mjs +148 -0
- package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +22 -0
- package/dist/packem_shared/functionTool-D6lCa2jB.mjs +20 -0
- package/dist/packem_shared/graph-component-aoUwO-f0.mjs +216 -0
- package/dist/packem_shared/memory-D4FPcBsX.mjs +12 -0
- package/dist/packem_shared/normalizeEntityName-CyEEWFkR.mjs +3 -0
- package/dist/packem_shared/runAgentLoop-Dhg4ZNvw.mjs +493 -0
- package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +211 -0
- package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +194 -0
- package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +36 -0
- package/dist/packem_shared/types.d-BhJFTvz_.d.mts +1114 -0
- package/dist/packem_shared/types.d-BhJFTvz_.d.ts +1114 -0
- package/dist/sandbox.d.mts +200 -0
- package/dist/sandbox.d.ts +200 -0
- package/dist/sandbox.mjs +109 -0
- package/dist/telemetry/index.d.mts +173 -0
- package/dist/telemetry/index.d.ts +173 -0
- package/dist/telemetry/index.mjs +4 -0
- 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,52 @@
|
|
|
1
1
|
# @lunora/agent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Experimental** — this package is outside the Lunora 1.0 stability promise: its API may change in any release, without a major version bump.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
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.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```ts
|
|
8
|
+
// lunora/agents.ts
|
|
9
|
+
import { defineAgent, defineAgentTool } from "@lunora/agent";
|
|
10
|
+
import { jsonSchema } from "@lunora/ai";
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
export const support = defineAgent({
|
|
13
|
+
instructions: "You are a helpful support agent.",
|
|
14
|
+
memory: { source: "rag:searchDocs" }, // an action over @lunora/ai/rag's retrieve
|
|
15
|
+
model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
16
|
+
tools: {
|
|
17
|
+
getWeather: defineAgentTool({
|
|
18
|
+
description: "Look up the current weather for a city.",
|
|
19
|
+
execute: async ({ city }, { idempotencyKey, run }) => run({ __lunoraRef: "weather:lookup" }, { city, key: idempotencyKey }),
|
|
20
|
+
inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
|
|
21
|
+
}),
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
```
|
|
10
25
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
2. Enable secure, token-less publishing from CI/CD workflows
|
|
14
|
-
3. Establish provenance for packages published under this name
|
|
26
|
+
Codegen auto-registers the agent runtime functions (`agents:agentMessages`, …) and the
|
|
27
|
+
`ctx.agents.support` producer as soon as an agent is declared — no re-export boilerplate.
|
|
15
28
|
|
|
16
|
-
|
|
29
|
+
```ts
|
|
30
|
+
// lunora/schema.ts — merge the thread tables (auto-prefixed agent_threads / agent_messages):
|
|
31
|
+
export default defineSchema({ ... }).extend(agentExtension);
|
|
17
32
|
|
|
18
|
-
|
|
33
|
+
// start a run from a mutation/action:
|
|
34
|
+
const { id } = await ctx.agents.support.run({ input: message, owner: ctx.auth.userId, threadKey });
|
|
19
35
|
|
|
20
|
-
|
|
36
|
+
// watch it live from the client (every turn, tool call, and reply streams in):
|
|
37
|
+
useSubscription(api.agents.agentMessages, { key: threadKey });
|
|
38
|
+
```
|
|
21
39
|
|
|
22
|
-
|
|
40
|
+
## Why durable
|
|
23
41
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
42
|
+
- A **completed** step is memoized by Cloudflare Workflows — a resumed run never re-executes a finished tool call (no double-charged card).
|
|
43
|
+
- A **failed** step is retried at-least-once — side-effecting tools receive their deterministic step name as `ctx.idempotencyKey` to dedupe on.
|
|
44
|
+
- Message writes are keyed and idempotent — replays never duplicate the thread.
|
|
45
|
+
- Owned threads (`owner: ctx.auth.userId`) are readable only by their owner — a mismatch looks like a missing thread.
|
|
46
|
+
- The 10-minute action ceiling doesn't exist here: slow tools and long loops are just workflow steps.
|
|
28
47
|
|
|
29
|
-
|
|
48
|
+
See the package docs for the full API.
|
|
30
49
|
|
|
31
|
-
|
|
32
|
-
- Contains no executable code
|
|
33
|
-
- Provides no functionality
|
|
34
|
-
- Should not be installed as a dependency
|
|
35
|
-
- Exists only for administrative purposes
|
|
50
|
+
## License
|
|
36
51
|
|
|
37
|
-
|
|
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**
|
|
52
|
+
FSL-1.1-Apache-2.0
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-BhJFTvz_.mjs";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-BhJFTvz_.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
|
+
* @experimental
|
|
10
|
+
*/
|
|
11
|
+
declare const verifySlack: (options: {
|
|
12
|
+
body: string;
|
|
13
|
+
now?: number;
|
|
14
|
+
signature: string | undefined;
|
|
15
|
+
signingSecret: string;
|
|
16
|
+
timestamp: string | undefined;
|
|
17
|
+
tolerance?: number;
|
|
18
|
+
}) => Promise<boolean>;
|
|
19
|
+
/**
|
|
20
|
+
* Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
|
|
21
|
+
* @experimental
|
|
22
|
+
*/
|
|
23
|
+
declare const verifyGithub: (options: {
|
|
24
|
+
body: string;
|
|
25
|
+
secret: string;
|
|
26
|
+
signature: string | undefined;
|
|
27
|
+
}) => Promise<boolean>;
|
|
28
|
+
/**
|
|
29
|
+
* Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
|
|
30
|
+
* `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
|
|
31
|
+
* @experimental
|
|
32
|
+
*/
|
|
33
|
+
declare const verifyDiscord: (options: {
|
|
34
|
+
body: string;
|
|
35
|
+
publicKey: string;
|
|
36
|
+
signature: string | undefined;
|
|
37
|
+
timestamp: string | undefined;
|
|
38
|
+
}) => Promise<boolean>;
|
|
39
|
+
/**
|
|
40
|
+
* One agent wired into the inbound channel HTTP handler.
|
|
41
|
+
* @experimental
|
|
42
|
+
*/
|
|
43
|
+
interface AgentChannelTarget {
|
|
44
|
+
/** The agent definition — only its `onInbound` config is read. */
|
|
45
|
+
agent: Pick<AgentDefinition, "onInbound">;
|
|
46
|
+
/** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
|
|
47
|
+
binding: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
|
|
51
|
+
* @experimental
|
|
52
|
+
*/
|
|
53
|
+
type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
|
|
54
|
+
/**
|
|
55
|
+
* Build an HTTP handler that starts a durable agent run from a verified inbound
|
|
56
|
+
* webhook. The channel is detected from the signature headers; EACH eligible
|
|
57
|
+
* target is verified against ITS OWN secret before its mapper is offered the
|
|
58
|
+
* event (so one app's valid signature can't trigger another app's agent), and
|
|
59
|
+
* the first target that both verifies and claims starts a run on its Workflow
|
|
60
|
+
* binding. Returns `401` when NO target's signature verifies, `200` on a claim
|
|
61
|
+
* (or a Discord PONG), `204` when a verified event is declined by every mapper,
|
|
62
|
+
* and `400` for an unrecognized webhook.
|
|
63
|
+
* @experimental
|
|
64
|
+
*/
|
|
65
|
+
declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
|
|
66
|
+
export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-BhJFTvz_.js";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-BhJFTvz_.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
|
+
* @experimental
|
|
10
|
+
*/
|
|
11
|
+
declare const verifySlack: (options: {
|
|
12
|
+
body: string;
|
|
13
|
+
now?: number;
|
|
14
|
+
signature: string | undefined;
|
|
15
|
+
signingSecret: string;
|
|
16
|
+
timestamp: string | undefined;
|
|
17
|
+
tolerance?: number;
|
|
18
|
+
}) => Promise<boolean>;
|
|
19
|
+
/**
|
|
20
|
+
* Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
|
|
21
|
+
* @experimental
|
|
22
|
+
*/
|
|
23
|
+
declare const verifyGithub: (options: {
|
|
24
|
+
body: string;
|
|
25
|
+
secret: string;
|
|
26
|
+
signature: string | undefined;
|
|
27
|
+
}) => Promise<boolean>;
|
|
28
|
+
/**
|
|
29
|
+
* Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
|
|
30
|
+
* `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
|
|
31
|
+
* @experimental
|
|
32
|
+
*/
|
|
33
|
+
declare const verifyDiscord: (options: {
|
|
34
|
+
body: string;
|
|
35
|
+
publicKey: string;
|
|
36
|
+
signature: string | undefined;
|
|
37
|
+
timestamp: string | undefined;
|
|
38
|
+
}) => Promise<boolean>;
|
|
39
|
+
/**
|
|
40
|
+
* One agent wired into the inbound channel HTTP handler.
|
|
41
|
+
* @experimental
|
|
42
|
+
*/
|
|
43
|
+
interface AgentChannelTarget {
|
|
44
|
+
/** The agent definition — only its `onInbound` config is read. */
|
|
45
|
+
agent: Pick<AgentDefinition, "onInbound">;
|
|
46
|
+
/** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
|
|
47
|
+
binding: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
|
|
51
|
+
* @experimental
|
|
52
|
+
*/
|
|
53
|
+
type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
|
|
54
|
+
/**
|
|
55
|
+
* Build an HTTP handler that starts a durable agent run from a verified inbound
|
|
56
|
+
* webhook. The channel is detected from the signature headers; EACH eligible
|
|
57
|
+
* target is verified against ITS OWN secret before its mapper is offered the
|
|
58
|
+
* event (so one app's valid signature can't trigger another app's agent), and
|
|
59
|
+
* the first target that both verifies and claims starts a run on its Workflow
|
|
60
|
+
* binding. Returns `401` when NO target's signature verifies, `200` on a claim
|
|
61
|
+
* (or a Discord PONG), `204` when a verified event is declined by every mapper,
|
|
62
|
+
* and `400` for an unrecognized webhook.
|
|
63
|
+
* @experimental
|
|
64
|
+
*/
|
|
65
|
+
declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
|
|
66
|
+
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,115 @@
|
|
|
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
|
+
* @experimental
|
|
21
|
+
*/
|
|
22
|
+
declare const normalizeEntityName: (name: string) => string;
|
|
23
|
+
/** The two internal graph-memory functions the durable loop dispatches to. */
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Loose structural view of the registered sandbox action — wide enough for the
|
|
27
|
+
* concrete `RegisteredAction`, narrow enough for re-export + dispatch. Codegen
|
|
28
|
+
* registers the runtime value; it never needs the precise generics.
|
|
29
|
+
* @experimental
|
|
30
|
+
*/
|
|
31
|
+
interface SandboxRegisteredFunction {
|
|
32
|
+
readonly args: unknown;
|
|
33
|
+
readonly handler: (context: unknown, args: never) => unknown;
|
|
34
|
+
readonly kind: "action";
|
|
35
|
+
readonly visibility?: "internal" | "public";
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* `SandboxComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
|
|
39
|
+
* @experimental
|
|
40
|
+
*/
|
|
41
|
+
interface SandboxComponent {
|
|
42
|
+
invoke: SandboxRegisteredFunction;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Resolve a model-supplied `path` to an absolute R2 key UNDER `root`, rejecting
|
|
46
|
+
* any `..` that would escape the sandbox root. Every returned key is guaranteed
|
|
47
|
+
* to start with the normalized `root`, so the model can never read or write
|
|
48
|
+
* outside its own prefix — the fs sandbox's core isolation guarantee.
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Build the sandbox runtime component: the single internal action the
|
|
53
|
+
* batteries-included `browserTool`/`containerTool` dispatch to. Codegen
|
|
54
|
+
* auto-registers it at `sandbox:invoke` whenever `lunora/` imports a sandbox
|
|
55
|
+
* tool. It runs as an **action** because that is the only ctx codegen attaches
|
|
56
|
+
* `ctx.browser` to (and `ctx.containers` rides every ctx once a container is
|
|
57
|
+
* declared) — the durable tool step itself has neither.
|
|
58
|
+
* @experimental
|
|
59
|
+
*/
|
|
60
|
+
declare const sandboxComponent: () => SandboxComponent;
|
|
61
|
+
/**
|
|
62
|
+
* The agent thread tables, shipped as a schema extension so an app merges
|
|
63
|
+
* them with one call and they can never collide with app tables:
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* // lunora/schema.ts
|
|
67
|
+
* export default defineSchema({ ... }).extend(agentExtension);
|
|
68
|
+
* ```
|
|
69
|
+
*
|
|
70
|
+
* Message ordering follows the Convex-agent model: `seq` is the monotonic
|
|
71
|
+
* per-thread position (allocated from the thread's `messageCount` counter, so
|
|
72
|
+
* allocation is O(1) inside the serialized mutation), and `messageKey` is the
|
|
73
|
+
* deterministic idempotency key — a workflow replay that re-persists the same
|
|
74
|
+
* message is a no-op instead of a duplicate.
|
|
75
|
+
* @experimental
|
|
76
|
+
*/
|
|
77
|
+
declare const agentExtension: SchemaExtension;
|
|
78
|
+
/**
|
|
79
|
+
* `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
|
|
80
|
+
* @experimental
|
|
81
|
+
*/
|
|
82
|
+
interface AgentComponent {
|
|
83
|
+
extension: SchemaExtension;
|
|
84
|
+
functions: {
|
|
85
|
+
agentAppendMessage: AgentRegisteredFunction;
|
|
86
|
+
agentEnsureThread: AgentRegisteredFunction;
|
|
87
|
+
agentEpisodeRecall: AgentRegisteredFunction;
|
|
88
|
+
agentEpisodeUpsert: AgentRegisteredFunction;
|
|
89
|
+
agentGraphTraverse: AgentRegisteredFunction;
|
|
90
|
+
agentGraphUpsert: AgentRegisteredFunction;
|
|
91
|
+
agentMessages: AgentRegisteredFunction;
|
|
92
|
+
agentPatchThread: AgentRegisteredFunction;
|
|
93
|
+
agentResolveApproval: AgentRegisteredFunction;
|
|
94
|
+
agentRun: AgentRegisteredFunction;
|
|
95
|
+
agentSetState: AgentRegisteredFunction;
|
|
96
|
+
agentState: AgentRegisteredFunction;
|
|
97
|
+
agentThread: AgentRegisteredFunction;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Build the agent runtime component: the thread schema extension plus the
|
|
102
|
+
* functions the durable loop dispatches to (and the client subscribes to).
|
|
103
|
+
* Codegen auto-registers them under the `agents:*` namespace whenever
|
|
104
|
+
* `lunora/agents.ts` declares an agent — the loop's dispatch paths assume
|
|
105
|
+
* that namespace, and apps never re-export these by hand.
|
|
106
|
+
*
|
|
107
|
+
* Most mutations are **internal** (only the workflow's admin-authenticated
|
|
108
|
+
* dispatch may call them); the queries are public so a client can subscribe
|
|
109
|
+
* to `agents:agentMessages` for a live thread view. Two mutations are public:
|
|
110
|
+
* `agentResolveApproval` (a client resolves a HITL approval) and `agentRun`
|
|
111
|
+
* (an HTTP client starts a durable run) — both owner-gated.
|
|
112
|
+
* @experimental
|
|
113
|
+
*/
|
|
114
|
+
declare const agentComponent: () => AgentComponent;
|
|
115
|
+
export { AgentComponent, type SandboxComponent, type SandboxRegisteredFunction, agentComponent, agentExtension, normalizeEntityName, sandboxComponent };
|