agentrail-edge 0.0.0 → 0.2.0

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # agentrail-edge
2
+
3
+ The Agentrail edge, in front of a site on the Fetch API: Cloudflare Workers,
4
+ Vercel Routing Middleware, or anything else that speaks it. Each request is
5
+ answered through the site's origin and recorded as one event, sent to the
6
+ Agentrail collector after the answer through the platform's `waitUntil`. A local
7
+ HMAC operation signs the origin trace handoff before forwarding the request.
8
+
9
+ In an answer meant for agents (Markdown, `llms.txt`), every link to the
10
+ site's own hosts is marked, so the request an agent makes by following one
11
+ is joined to the page it came from. The marker comes off before the origin
12
+ sees the request, and only a real one: an `h` parameter or an `/h/` path
13
+ that does not read as a marker (an image's `h=600`) is the site's own, and
14
+ the request reaches the origin exactly as it was sent. A visitor's address,
15
+ and any verified principal, leave the edge only hashed with the workspace's
16
+ hash key.
17
+
18
+ Requests one edge answers share collector calls: an event goes at once when
19
+ no call is under way, and waits for the next one, with every other that
20
+ waited, when one is. A quiet site sends a call per request; a busy one
21
+ about one per round trip to the collector. A call that failed is tried
22
+ again after a random wait, so isolates that failed together do not retry
23
+ together, and never sooner than a `Retry-After` the collector sends. Every
24
+ call ends within 25 seconds of its request's answer, inside the 30 seconds
25
+ Cloudflare gives `waitUntil`; one that cannot is given up and told to
26
+ `onError`, never left for the platform to cancel unseen.
27
+
28
+ A visitor's session is a cookie the edge sets and the browser script reads
29
+ (`agentrail_session`). As in web analytics, it ends after 30 minutes
30
+ without a request, and a day after it began: every answer writes it again
31
+ for another 30 minutes.
32
+
33
+ ```sh
34
+ npm install agentrail-edge
35
+ ```
36
+
37
+ Before 1.0, a minor version (0.1 to 0.2) may change what the package offers.
38
+
39
+ ## Cloudflare Workers
40
+
41
+ The secret and the hash key come from Agentrail's setup page, as the
42
+ `AGENTRAIL_SECRET` and `AGENTRAIL_HASH_KEY` environment variables; the
43
+ collector's address is the one the setup page shows. Create the edge once,
44
+ on the first request, so the requests an isolate answers share calls; one
45
+ created per request still works, and sends a call per request.
46
+
47
+ ```js
48
+ import { cloudflare, createEdge } from 'agentrail-edge';
49
+
50
+ let edge;
51
+
52
+ export default {
53
+ fetch(request, env, ctx) {
54
+ edge ??= createEdge({
55
+ collector: {
56
+ endpoint: 'https://<collector>/ingest/events',
57
+ secret: env.AGENTRAIL_SECRET,
58
+ },
59
+ hashKey: env.AGENTRAIL_HASH_KEY,
60
+ hosts: { 'docs.example.com': 'query' },
61
+ });
62
+ return edge.handle(request, cloudflare(ctx));
63
+ },
64
+ };
65
+ ```
66
+
67
+ ## Vercel
68
+
69
+ In Routing Middleware, `vercel({ waitUntil, origin })` takes `waitUntil`
70
+ from `@vercel/functions` and fetches the site itself, since middleware cannot
71
+ rewrite an answer it passes on. Create the edge once, outside the handler.
72
+
73
+ ## Backend trace handoff
74
+
75
+ Each forwarded request carries a new `traceparent` and an
76
+ `x-agentrail-trace-handoff` token authenticated with the workspace hash key.
77
+ The token binds the trace parent, key ID, issue time, HTTP method and final
78
+ origin path/query. The backend accepts it for 60 seconds. The caller's handoff,
79
+ tracestate and baggage are removed; the handoff response header is removed
80
+ before answering the visitor. A signing failure reaches `onError` as
81
+ `TraceHandoffSigningError` and the application request continues unsigned.
82
+
83
+ Apply path/query rewrites in `EdgeAdapter.prepareOriginRequest(request)`, or
84
+ `vercel({ waitUntil, prepareOriginRequest, origin })`. Signing happens after
85
+ that hook. The `origin` callback sends the prepared request; host-only changes
86
+ preserve the signature. A path/query change inside `origin` prevents backend
87
+ verification. `agentrail-node` starts a new trace for unsigned or refused
88
+ handoffs and keeps the caller's context as a directional span link.
89
+
90
+ ## Options
91
+
92
+ - `hosts`: the site's own hosts, and how a link to each is marked: `'query'`
93
+ adds the `h` parameter, `'path'` an `/h/<marker>` prefix, for a host whose
94
+ calls an extra parameter would break.
95
+ - `queryAllowlist`: query parameters a recorded path keeps; every other is
96
+ dropped, and named as dropped.
97
+ - `identify(request)`: the verified principal behind a request, by the site's
98
+ own check of its method, URL and headers. It runs after the answer. A
99
+ check that throws is told to `onError` as an `IdentifyError`, and the
100
+ request is recorded without a principal.
101
+ - `ignoreRequest(request)`: requests passed to the origin untouched and
102
+ recorded nowhere. See [Your own servers](#your-own-servers).
103
+ - `sessionIdleTimeout`: seconds without a request after which a session
104
+ ends; 1800 (30 minutes) by default.
105
+ - `sessionCookieDomain`: the domain a session is shared across, as
106
+ `example.com` for `docs.example.com` and `app.example.com`; by default,
107
+ the one host. Give the browser script the same two values.
108
+ - `sessionCookie`, `service`, `fetch`: the session cookie's name, the
109
+ service the events name, and the fetch the collector's calls go through.
110
+ - `signers`: registrable hosts, beside the known signers, whose Web Bot
111
+ Auth key directories the edge may read; a signature by any other host is
112
+ recorded as a claim it did not check, and that host is never contacted.
113
+ - `onError(error)`: told of events that could not be sent, and of an
114
+ `identify` that threw; they are logged otherwise. Neither ever reaches the
115
+ visitor.
116
+
117
+ ## Your own servers
118
+
119
+ Calls your own servers make through this edge are not visitors or agents. A
120
+ page rendered on the server that reads your API would otherwise record a step
121
+ for every read, all from a few addresses at a steady rate, and those steps
122
+ crowd out the journeys you want to see.
123
+
124
+ Leave them out with something only your servers can send:
125
+
126
+ ```ts
127
+ const edge = createEdge({
128
+ // ...
129
+ ignoreRequest: (request) =>
130
+ request.headers.get('x-my-internal') === env.INTERNAL_SECRET,
131
+ });
132
+ ```
133
+
134
+ A user agent or an address will not do: any caller can claim one, and a caller
135
+ who matched it would never be recorded. Compare a secret in constant time
136
+ where your platform offers it.
137
+
138
+ ## What it records of the caller
139
+
140
+ Beside the user agent, each event carries what the caller and the network
141
+ said of it, for the collector to read as features (never as proofs) when it
142
+ asks who the caller is: the `Accept` sent, and the `Sec-Fetch-Site`, `-Mode`
143
+ and `-Dest` a browser sends and a programmatic fetcher does not; what the
144
+ platform says of the client, where it says anything (`cloudflare(ctx)` reads
145
+ `request.cf`: the autonomous system and country on every plan, the JA4
146
+ fingerprint and the verified-bot category where the zone has Bot Management;
147
+ `vercel()` reads `x-vercel-ip-country` and `x-vercel-ja4-digest`, and BotID's
148
+ verified bots stay in the app, where `checkBotId()` runs; an adapter of your
149
+ own gives `signals(request)` or nothing); and a Web Bot Auth signature,
150
+ checked against the keys the agent publishes. The check reads the agent's
151
+ key directory from the edge, once per its `max-age`, from the known signers'
152
+ hosts and those `signers` names and from no other, so a site's edge contacts
153
+ only hosts it has been told of; a directory that cannot be read leaves the
154
+ signature `directory_unreachable`, never `invalid`.
155
+ Nothing here is hashed, since nothing identifies a person: a fingerprint is
156
+ shared by every copy of one client.
157
+
158
+ ## Licence
159
+
160
+ [Apache-2.0](LICENSE).
package/dist/edge.d.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { type PrincipalKind } from 'agentrail-core';
2
+ import { type MarkedHosts } from './links.js';
3
+ /** The site's `identify` threw: the request is recorded without a principal. */
4
+ export declare class IdentifyError extends Error {
5
+ readonly name = "IdentifyError";
6
+ }
7
+ /** The site's `ignoreRequest` threw: the request is recorded as any other. */
8
+ export declare class IgnoreRequestError extends Error {
9
+ readonly name = "IgnoreRequestError";
10
+ }
11
+ /**
12
+ * What the site's own check reads of a request: never its body, which has
13
+ * gone to the origin by the time the check runs.
14
+ */
15
+ export type RequestHead = Pick<Request, 'method' | 'url' | 'headers'>;
16
+ /** A verified identity the site's own check found; its ids are hashed before they leave. */
17
+ export interface Principal {
18
+ readonly kind: PrincipalKind;
19
+ readonly id: string;
20
+ readonly actingUserId?: string | null;
21
+ }
22
+ export declare class TraceHandoffSigningError extends Error {
23
+ readonly name = "TraceHandoffSigningError";
24
+ }
25
+ export interface EdgeOptions {
26
+ /** Where events go, and the edge source's secret. */
27
+ readonly collector: {
28
+ readonly endpoint: string;
29
+ readonly secret: string;
30
+ };
31
+ /** The workspace's hash key, which every component of it hashes with. */
32
+ readonly hashKey: string;
33
+ /** The site's own hosts, whose links an agent-facing answer marks, and how. */
34
+ readonly hosts: MarkedHosts;
35
+ /** Query parameters kept on a recorded path; every other is dropped. */
36
+ readonly queryAllowlist?: readonly string[];
37
+ /** The session cookie's name. */
38
+ readonly sessionCookie?: string;
39
+ /**
40
+ * Seconds without a request after which a visitor's session ends; 30
41
+ * minutes by default. The browser script on the same site takes the same.
42
+ */
43
+ readonly sessionIdleTimeout?: number;
44
+ /**
45
+ * The domain a visitor's session is shared across, as `example.com` for
46
+ * `docs.example.com` and `app.example.com`; by default, the one host.
47
+ */
48
+ readonly sessionCookieDomain?: string;
49
+ /**
50
+ * The verified principal behind a request, by the site's own check of its
51
+ * method, URL and headers. It runs after the answer.
52
+ */
53
+ readonly identify?: (request: RequestHead) => Principal | null | Promise<Principal | null>;
54
+ /**
55
+ * Requests this edge passes to the origin untouched and records nothing
56
+ * of, by the site's own check of their method, URL and headers: the calls
57
+ * the site's own servers make, which are neither a visitor nor an agent.
58
+ * Check something only your servers can send, such as a shared secret: a
59
+ * user agent or an address is what any caller can claim. A check that
60
+ * throws is told to `onError` as an `IgnoreRequestError`, and the request
61
+ * is recorded as any other.
62
+ */
63
+ readonly ignoreRequest?: (request: RequestHead) => boolean;
64
+ /** The service the events name; the request's host by default. */
65
+ readonly service?: string;
66
+ /**
67
+ * Told of events that could not be sent, and of an `identify` that threw.
68
+ * Logs by default.
69
+ */
70
+ readonly onError?: (error: Error) => void;
71
+ /**
72
+ * Registrable hosts, beside the known signers, whose Web Bot Auth key
73
+ * directories this edge may read; a signature by any other host is
74
+ * recorded as an unsupported claim, and that host is never contacted.
75
+ */
76
+ readonly signers?: readonly string[];
77
+ /** The fetch the collector's calls go through; the platform's own by default. */
78
+ readonly fetch?: typeof fetch;
79
+ }
80
+ /**
81
+ * What the platform tells the edge of the client beyond its address, where
82
+ * it tells anything: features for the collector's classifier, never keys.
83
+ */
84
+ export interface PlatformSignals {
85
+ /** The client's autonomous system number. */
86
+ readonly asn: number | null;
87
+ /** The client's country, two letters. */
88
+ readonly country: string | null;
89
+ /** The client's TLS fingerprint, JA4. */
90
+ readonly ja4: string | null;
91
+ /** A bot the platform verified against its own directory. */
92
+ readonly verifiedBot: {
93
+ readonly category: string;
94
+ readonly name: string | null;
95
+ } | null;
96
+ }
97
+ /** What the platform the edge runs on provides. */
98
+ export interface EdgeAdapter {
99
+ /** The client's address, as the platform saw it; null when it says none. */
100
+ clientAddress(request: Request): string | null;
101
+ /** What else the platform says of the client; absent on a platform that says nothing. */
102
+ signals?(request: Request): PlatformSignals;
103
+ /** Keeps the platform running work past the answer. */
104
+ waitUntil(work: Promise<unknown>): void;
105
+ /** Sends the request on to the site. */
106
+ origin(request: Request): Promise<Response>;
107
+ /** Apply path/query rewrites here, before the final request is signed. */
108
+ prepareOriginRequest?(request: Request): Request | Promise<Request>;
109
+ /** This edge instance, when the platform names one. */
110
+ readonly instance: string | null;
111
+ }
112
+ export interface Edge {
113
+ /** Answers a request through the origin, and records it. */
114
+ handle(request: Request, adapter: EdgeAdapter): Promise<Response>;
115
+ }
116
+ export declare function createEdge(options: EdgeOptions): Edge;
117
+ /** Cloudflare Workers: the platform's client address, its word on the client, and the Worker's `waitUntil`. */
118
+ export declare function cloudflare(context: {
119
+ waitUntil(work: Promise<unknown>): void;
120
+ }, origin?: (request: Request) => Promise<Response>): EdgeAdapter;
121
+ /**
122
+ * Vercel (Routing Middleware, `proxy.ts`): the address Vercel's edge saw,
123
+ * and `waitUntil` from `@vercel/functions`. Middleware cannot rewrite an
124
+ * answer it passes on, so `origin` fetches the site itself, from its own
125
+ * origin.
126
+ */
127
+ export declare function vercel(options: {
128
+ readonly waitUntil: (work: Promise<unknown>) => void;
129
+ readonly origin: (request: Request) => Promise<Response>;
130
+ readonly prepareOriginRequest?: EdgeAdapter['prepareOriginRequest'];
131
+ }): EdgeAdapter;
package/dist/edge.js ADDED
@@ -0,0 +1,566 @@
1
+ import { createCollector, TRACE_HANDOFF_HEADER, signTraceHandoff, traceHandoffTarget, createSignatureVerifier, formatTraceparent, hashKeyIdOf, keyedHash, newSessionId, newSpanId, newTraceId, parseMarker, parseTraceparent, sessionCookie, VERSION, } from 'agentrail-core';
2
+ import { MARKER_PARAMETER, markLinks } from './links.js';
3
+ /**
4
+ * The edge adapter: in front of a customer's site, on the Fetch API, it
5
+ * records every request as one event and adds what proves which requests
6
+ * are one agent's journey (docs/research/agent-journey-correlation.md, 12):
7
+ *
8
+ * - a marker in every link of an agent-facing answer (Markdown, `llms.txt`),
9
+ * a lane per link, after the cache, so no two readers share one;
10
+ * - a session cookie it sets itself and the browser script reads too, which
11
+ * ends after 30 minutes without a request, and a day after it began;
12
+ * - a trace of its own for every request, passed to the origin in
13
+ * `traceparent`, with any caller's trace kept as a span link only: a public
14
+ * endpoint never takes its parent from outside;
15
+ * - the client address and any verified principal, hashed with the
16
+ * workspace's key before anything leaves;
17
+ * - what the caller and the network said of it, for the collector's
18
+ * classifier of who the caller is: the `Accept` and fetch metadata, the
19
+ * platform's word on the network and its verified bots, and a Web Bot
20
+ * Auth signature checked against the keys the agent publishes.
21
+ *
22
+ * The events go to the collector after the answer, through the platform's
23
+ * `waitUntil`, so recording never slows a request. Requests one edge answers
24
+ * share calls: what is sent while a call is out goes in the next, together,
25
+ * so a site creates its edge once, not per request.
26
+ */
27
+ /** A path's leading `/h/<segment>`: a link's marker, when the segment reads as one. */
28
+ const PATH_MARKER = /^\/h\/([^/]+)/u;
29
+ /** The most of an agent-facing answer read to mark its links; a larger one passes as it came. */
30
+ const MARKABLE_BYTES = 2 * 1024 * 1024;
31
+ /**
32
+ * How long after the origin answered the call carrying a request's event may
33
+ * run, every try and wait included. Cloudflare gives `waitUntil` 30 s after
34
+ * the answer is sent, the least of the platforms, and cancels what is still
35
+ * running then; counted from before it is sent, 25 s leaves room for a slow
36
+ * `identify`.
37
+ */
38
+ const SEND_WITHIN_MS = 25_000;
39
+ /** The longest `Accept` the collector takes; a longer one is cut. */
40
+ const ACCEPT_LENGTH = 256;
41
+ /** The longest `Sec-Fetch-*` value the collector takes; the browsers' are one word. */
42
+ const FETCH_METADATA_LENGTH = 32;
43
+ /** The longest JA4 the collector takes. */
44
+ const JA4_LENGTH = 64;
45
+ /** The longest verified-bot category the collector takes. */
46
+ const BOT_CATEGORY_LENGTH = 64;
47
+ /** The site's `identify` threw: the request is recorded without a principal. */
48
+ export class IdentifyError extends Error {
49
+ name = 'IdentifyError';
50
+ }
51
+ /** The site's `ignoreRequest` threw: the request is recorded as any other. */
52
+ export class IgnoreRequestError extends Error {
53
+ name = 'IgnoreRequestError';
54
+ }
55
+ export class TraceHandoffSigningError extends Error {
56
+ name = 'TraceHandoffSigningError';
57
+ }
58
+ /**
59
+ * The markers a query carries in `h`, and the query without them, every
60
+ * other pair exactly as it came: a value that does not read as a marker is
61
+ * the site's own, and stays.
62
+ */
63
+ function markersOffQuery(search) {
64
+ const markers = [];
65
+ const rest = search
66
+ .slice(1)
67
+ .split('&')
68
+ .filter((pair) => {
69
+ const [entry] = new URLSearchParams(pair);
70
+ if (entry?.[0] !== MARKER_PARAMETER || !parseMarker(entry[1]).valid)
71
+ return true;
72
+ markers.push(entry[1]);
73
+ return false;
74
+ });
75
+ return { markers, rest: rest.join('&') };
76
+ }
77
+ /**
78
+ * An answer whose links are marked: a whole one (a `200` to a `GET`, so never
79
+ * a range) in Markdown, or `llms.txt` or a `.md` path served as text.
80
+ */
81
+ function isAgentFacing(method, url, response) {
82
+ if (method !== 'GET' || response.status !== 200)
83
+ return false;
84
+ const type = (response.headers.get('content-type') ?? '').toLowerCase();
85
+ if (type.startsWith('text/markdown') || type.startsWith('text/x-markdown'))
86
+ return true;
87
+ return (type.startsWith('text/plain') &&
88
+ /(?:\/llms(?:-full)?\.txt|\.md)$/u.test(url.pathname));
89
+ }
90
+ /**
91
+ * The origin's headers for a body this edge has read: a fetch hands it over
92
+ * decoded, so neither the origin's encoding nor its length is the body's.
93
+ */
94
+ function headersOfRead(response) {
95
+ const headers = new Headers(response.headers);
96
+ headers.delete('content-length');
97
+ headers.delete('content-encoding');
98
+ return headers;
99
+ }
100
+ /**
101
+ * The answer's text, when it is at most `limit` bytes. A larger answer comes
102
+ * back as a response that sends what was read and then the rest, as it came.
103
+ */
104
+ async function readUpTo(response, body, limit) {
105
+ const reader = body.getReader();
106
+ const decoder = new TextDecoder();
107
+ const chunks = [];
108
+ let size = 0;
109
+ for (;;) {
110
+ const next = await reader.read();
111
+ if (next.done)
112
+ break;
113
+ chunks.push(next.value);
114
+ size += next.value.byteLength;
115
+ if (size > limit) {
116
+ const rest = new ReadableStream({
117
+ start(controller) {
118
+ for (const chunk of chunks)
119
+ controller.enqueue(chunk);
120
+ },
121
+ async pull(controller) {
122
+ const more = await reader.read();
123
+ if (more.done)
124
+ controller.close();
125
+ else
126
+ controller.enqueue(more.value);
127
+ },
128
+ cancel: (reason) => reader.cancel(reason),
129
+ });
130
+ return new Response(rest, {
131
+ status: response.status,
132
+ statusText: response.statusText,
133
+ headers: headersOfRead(response),
134
+ });
135
+ }
136
+ }
137
+ return (chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join('') +
138
+ decoder.decode());
139
+ }
140
+ export function createEdge(options) {
141
+ const { hashKey, hosts, identify, service } = options;
142
+ const onError = options.onError ??
143
+ ((error) => {
144
+ console.error('agentrail:', error);
145
+ });
146
+ const cookie = sessionCookie({
147
+ name: options.sessionCookie ?? 'agentrail_session',
148
+ idleTimeout: options.sessionIdleTimeout,
149
+ domain: options.sessionCookieDomain,
150
+ });
151
+ const allowlist = new Set([
152
+ MARKER_PARAMETER,
153
+ ...(options.queryAllowlist ?? []),
154
+ ]);
155
+ // Every call names the key its events were hashed with. Its id is a
156
+ // digest, which WebCrypto only gives asynchronously, so the collector is
157
+ // ready from the first send on, never on a request's path.
158
+ const keyId = hashKeyIdOf(hashKey);
159
+ const collector = keyId.then((hashKeyId) => createCollector({
160
+ endpoint: options.collector.endpoint,
161
+ secret: options.collector.secret,
162
+ component: {
163
+ name: 'agentrail-edge',
164
+ version: VERSION,
165
+ surfaces: ['edge'],
166
+ hashKeyId,
167
+ },
168
+ onError,
169
+ ...(options.fetch ? { fetch: options.fetch } : {}),
170
+ }));
171
+ // Checks each signed request against the keys its agent publishes; the
172
+ // directories are read once per `max-age` for the life of the edge.
173
+ const verify = createSignatureVerifier({
174
+ ...(options.fetch ? { fetch: options.fetch } : {}),
175
+ ...(options.signers ? { signers: options.signers } : {}),
176
+ });
177
+ async function requestForOrigin(request, adapter, span) {
178
+ const prepared = await (adapter.prepareOriginRequest?.(request) ?? request);
179
+ const headers = new Headers(prepared.headers);
180
+ const traceparent = formatTraceparent(span);
181
+ headers.set('traceparent', traceparent);
182
+ headers.delete('tracestate');
183
+ headers.delete('baggage');
184
+ headers.delete(TRACE_HANDOFF_HEADER);
185
+ try {
186
+ headers.set(TRACE_HANDOFF_HEADER, await signTraceHandoff({
187
+ traceparent,
188
+ hashKeyId: await keyId,
189
+ issuedAt: Date.now(),
190
+ method: prepared.method,
191
+ target: traceHandoffTarget(prepared.url),
192
+ }, hashKey));
193
+ }
194
+ catch (error) {
195
+ const failure = new TraceHandoffSigningError('Agentrail could not sign the origin trace handoff.', { cause: error });
196
+ // Reporting may throw in the site's callback; it belongs to waitUntil,
197
+ // so a capture failure still forwards the application request unsigned.
198
+ adapter.waitUntil(Promise.resolve().then(() => {
199
+ onError(failure);
200
+ }));
201
+ }
202
+ return new Request(prepared, { headers });
203
+ }
204
+ /** A path as it is recorded: the allowlisted query only. */
205
+ function recordedPath(url) {
206
+ const kept = new URLSearchParams([...url.searchParams].filter(([name]) => allowlist.has(name)));
207
+ return {
208
+ path: `${url.pathname}${kept.size === 0 ? '' : `?${kept.toString()}`}`,
209
+ dropped: [...url.searchParams.keys()].some((name) => !allowlist.has(name)),
210
+ };
211
+ }
212
+ /** A redirect's target as it is recorded: the allowlisted query only, no fragment. */
213
+ function recordedLocation(location, base) {
214
+ if (location === null)
215
+ return { location: null, redaction: null };
216
+ let target;
217
+ try {
218
+ target = new URL(location, base);
219
+ }
220
+ catch (error) {
221
+ // A target the edge cannot read, it cannot strip either: it stays here.
222
+ if (error instanceof TypeError)
223
+ return { location: null, redaction: 'unparsable' };
224
+ throw error;
225
+ }
226
+ const { path, dropped } = recordedPath(target);
227
+ return {
228
+ location: `${target.protocol}//${target.host}${path}`,
229
+ redaction: dropped ? 'query_outside_allowlist' : null,
230
+ };
231
+ }
232
+ /**
233
+ * The principal the site's own check names. A check that throws is the
234
+ * site's to fix, and is told to `onError`; the request is still a step the
235
+ * agent took, recorded without the principal the check could not name.
236
+ */
237
+ async function principalOf(request) {
238
+ if (identify === undefined)
239
+ return null;
240
+ try {
241
+ return await identify(request);
242
+ }
243
+ catch (error) {
244
+ onError(new IdentifyError("The site's identify threw; the request is recorded without a principal.", { cause: error }));
245
+ return null;
246
+ }
247
+ }
248
+ async function marked(method, url, response, observed) {
249
+ const length = Number(response.headers.get('content-length') ?? '0');
250
+ if (!isAgentFacing(method, url, response) ||
251
+ response.body === null ||
252
+ length > MARKABLE_BYTES)
253
+ return response;
254
+ const text = await readUpTo(response, response.body, MARKABLE_BYTES);
255
+ if (text instanceof Response)
256
+ return text;
257
+ const result = markLinks(text, url, hosts, (link) => {
258
+ return `${link.host}${recordedPath(link).path}`;
259
+ });
260
+ observed.served = result.served;
261
+ observed.linksOut = result.linksOut;
262
+ const headers = headersOfRead(response);
263
+ // The body is now this reader's alone.
264
+ headers.delete('etag');
265
+ if (result.served !== null)
266
+ headers.set('cache-control', 'private, no-store');
267
+ return new Response(result.body, {
268
+ status: response.status,
269
+ statusText: response.statusText,
270
+ headers,
271
+ });
272
+ }
273
+ async function eventOf(input) {
274
+ const { request, url, observed } = input;
275
+ // With its port, as a link to it is recorded.
276
+ const host = url.host;
277
+ const { path, dropped } = recordedPath(url);
278
+ const location = recordedLocation(observed.location, url);
279
+ const principal = await principalOf(request);
280
+ const actingUserId = principal?.actingUserId ?? null;
281
+ const signature = await verify(request);
282
+ const { signals } = input;
283
+ return {
284
+ schemaVersion: 1,
285
+ id: crypto.randomUUID(),
286
+ surface: 'edge',
287
+ kind: 'http.request',
288
+ start: input.start,
289
+ end: input.end,
290
+ clock: 'edge',
291
+ emittedBy: 'argus',
292
+ resource: {
293
+ serviceName: service ?? host,
294
+ serviceInstanceId: input.instance,
295
+ },
296
+ span: {
297
+ traceId: input.span.traceId,
298
+ spanId: input.span.spanId,
299
+ parentSpanId: null,
300
+ kind: 'server',
301
+ publicEntry: true,
302
+ subtreeSpanIds: [],
303
+ links: input.caller === null ? [] : [input.caller],
304
+ },
305
+ session: { id: input.session, previousId: null },
306
+ http: {
307
+ method: request.method,
308
+ host,
309
+ path,
310
+ status: observed.status,
311
+ location: location.location,
312
+ contentType: observed.contentType,
313
+ linksOut: [...observed.linksOut],
314
+ },
315
+ actor: {
316
+ egress: input.address === null
317
+ ? null
318
+ : await keyedHash(hashKey, input.address),
319
+ userAgent: request.headers.get('user-agent'),
320
+ client: null,
321
+ clientVersion: null,
322
+ protocol: null,
323
+ accept: cut(request.headers.get('accept'), ACCEPT_LENGTH),
324
+ fetchMetadata: fetchMetadataOf(request.headers),
325
+ network: signals === null
326
+ ? null
327
+ : {
328
+ asn: signals.asn,
329
+ country: signals.country,
330
+ ja4: cut(signals.ja4, JA4_LENGTH),
331
+ },
332
+ signature,
333
+ verifiedBot: signals?.verifiedBot === null || signals === null
334
+ ? null
335
+ : {
336
+ category: signals.verifiedBot.category.slice(0, BOT_CATEGORY_LENGTH),
337
+ name: signals.verifiedBot.name,
338
+ },
339
+ },
340
+ principal: principal === null
341
+ ? null
342
+ : {
343
+ kind: principal.kind,
344
+ id: await keyedHash(hashKey, principal.id),
345
+ actingUserId: actingUserId === null
346
+ ? null
347
+ : await keyedHash(hashKey, actingUserId),
348
+ },
349
+ registration: null,
350
+ markers: {
351
+ served: observed.served === null
352
+ ? []
353
+ : [{ value: observed.served, durable: false }],
354
+ seen: [...input.seen],
355
+ },
356
+ redactions: [
357
+ ...(input.address === null
358
+ ? []
359
+ : [{ field: 'actor.egress', reason: 'keyed_hash' }]),
360
+ ...(principal === null
361
+ ? []
362
+ : [{ field: 'principal.id', reason: 'keyed_hash' }]),
363
+ ...(dropped
364
+ ? [{ field: 'http.path', reason: 'query_outside_allowlist' }]
365
+ : []),
366
+ ...(location.redaction === null
367
+ ? []
368
+ : [{ field: 'http.location', reason: location.redaction }]),
369
+ ],
370
+ };
371
+ }
372
+ /** Whether the site's own check leaves this request out; a broken check leaves nothing out. */
373
+ function ignored(request, adapter) {
374
+ if (options.ignoreRequest === undefined)
375
+ return false;
376
+ try {
377
+ return options.ignoreRequest(request);
378
+ }
379
+ catch (error) {
380
+ const failure = new IgnoreRequestError("The site's ignoreRequest threw; the request is recorded.", { cause: error });
381
+ adapter.waitUntil(Promise.resolve().then(() => {
382
+ onError(failure);
383
+ }));
384
+ return false;
385
+ }
386
+ }
387
+ return {
388
+ async handle(request, adapter) {
389
+ if (ignored(request, adapter)) {
390
+ // The site's own rewrite still applies: it decides where a request
391
+ // goes, which is nothing to do with whether it is recorded.
392
+ const prepared = await (adapter.prepareOriginRequest?.(request) ??
393
+ request);
394
+ const headers = new Headers(prepared.headers);
395
+ // Only this edge signs a handoff, whatever the caller sent.
396
+ headers.delete(TRACE_HANDOFF_HEADER);
397
+ return adapter.origin(new Request(prepared, { headers }));
398
+ }
399
+ const start = Date.now();
400
+ const url = new URL(request.url);
401
+ const query = markersOffQuery(url.search);
402
+ const segment = PATH_MARKER.exec(url.pathname)?.[1];
403
+ const pathMarker = segment !== undefined && parseMarker(segment).valid ? segment : null;
404
+ const seen = pathMarker === null ? query.markers : [...query.markers, pathMarker];
405
+ // What the origin sees: the markers taken off and nothing else of the
406
+ // address changed, and this edge's trace.
407
+ const originUrl = new URL(url);
408
+ if (query.markers.length > 0)
409
+ originUrl.search = query.rest;
410
+ if (pathMarker !== null)
411
+ originUrl.pathname =
412
+ url.pathname.slice(`/h/${pathMarker}`.length) || '/';
413
+ const caller = parseTraceparent(request.headers.get('traceparent'));
414
+ const span = { traceId: newTraceId(), spanId: newSpanId() };
415
+ const headers = new Headers(request.headers);
416
+ headers.set('traceparent', formatTraceparent(span));
417
+ // The caller's vendor state belongs to the caller's trace.
418
+ headers.delete('tracestate');
419
+ headers.delete('baggage');
420
+ headers.delete(TRACE_HANDOFF_HEADER);
421
+ const forwarded = new Request(originUrl, {
422
+ method: request.method,
423
+ headers,
424
+ body: request.body,
425
+ redirect: 'manual',
426
+ // A visitor who goes away stops the origin's work too.
427
+ signal: request.signal,
428
+ // A streamed body needs it; Workers and Node both take it.
429
+ duplex: 'half',
430
+ });
431
+ // What `identify` reads once the answer is sent: the body is the origin's.
432
+ const head = {
433
+ method: request.method,
434
+ url: request.url,
435
+ headers: new Headers(request.headers),
436
+ };
437
+ // A session a day old starts the next, which names no previous one:
438
+ // the engine would join the two again. One idle too long the browser
439
+ // has already dropped.
440
+ const session = cookie.read(request.headers.get('cookie') ?? '', start) ??
441
+ newSessionId(start);
442
+ const observed = {
443
+ status: null,
444
+ location: null,
445
+ contentType: null,
446
+ served: null,
447
+ linksOut: [],
448
+ };
449
+ try {
450
+ // Links resolve against the address the origin answered for, so a
451
+ // relative one never carries the marker this request came with.
452
+ const answer = await marked(request.method, originUrl, await adapter.origin(await requestForOrigin(forwarded, adapter, span)), observed);
453
+ observed.status = answer.status;
454
+ observed.location = answer.headers.get('location');
455
+ observed.contentType = answer.headers.get('content-type');
456
+ // On every answer, so the session lasts another idle timeout.
457
+ const withCookie = new Response(answer.body, answer);
458
+ withCookie.headers.delete(TRACE_HANDOFF_HEADER);
459
+ withCookie.headers.append('set-cookie', cookie.write(session, url.protocol === 'https:'));
460
+ return withCookie;
461
+ }
462
+ finally {
463
+ // One event per request however its answer ended: a request the
464
+ // origin could not answer is still a step the agent took.
465
+ const end = Date.now();
466
+ adapter.waitUntil((async () => {
467
+ const sending = await collector;
468
+ await sending.send(await eventOf({
469
+ request: head,
470
+ url,
471
+ address: adapter.clientAddress(request),
472
+ signals: adapter.signals?.(request) ?? null,
473
+ instance: adapter.instance,
474
+ start,
475
+ end,
476
+ span,
477
+ caller,
478
+ session,
479
+ seen,
480
+ observed,
481
+ }), end + SEND_WITHIN_MS);
482
+ })());
483
+ }
484
+ },
485
+ };
486
+ }
487
+ /** A header or platform value cut to what the collector takes; null for none or an empty one. */
488
+ function cut(value, length) {
489
+ return typeof value === 'string' && value.length > 0
490
+ ? value.slice(0, length)
491
+ : null;
492
+ }
493
+ /** `Sec-Fetch-Site`, `-Mode` and `-Dest` together, as a browser sends all three. */
494
+ function fetchMetadataOf(headers) {
495
+ const site = cut(headers.get('sec-fetch-site'), FETCH_METADATA_LENGTH);
496
+ const mode = cut(headers.get('sec-fetch-mode'), FETCH_METADATA_LENGTH);
497
+ const dest = cut(headers.get('sec-fetch-dest'), FETCH_METADATA_LENGTH);
498
+ return site === null || mode === null || dest === null
499
+ ? null
500
+ : { site, mode, dest };
501
+ }
502
+ /** A two-letter country, as the platforms give one; anything else is none. */
503
+ function countryOf(value) {
504
+ return typeof value === 'string' && /^[A-Z]{2}$/u.test(value) ? value : null;
505
+ }
506
+ function recordOf(value) {
507
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
508
+ ? value
509
+ : null;
510
+ }
511
+ /**
512
+ * What Cloudflare tells a Worker of the client in `request.cf`: its
513
+ * autonomous system and country on every plan; its JA4 under
514
+ * `botManagement`, and the category of a verified bot, where the zone's
515
+ * plan has Bot Management.
516
+ */
517
+ function cloudflareSignals(request) {
518
+ const cf = recordOf(request.cf);
519
+ const bot = recordOf(cf?.botManagement);
520
+ const category = cut(typeof cf?.verifiedBotCategory === 'string' ? cf.verifiedBotCategory : null, BOT_CATEGORY_LENGTH);
521
+ return {
522
+ asn: typeof cf?.asn === 'number' ? cf.asn : null,
523
+ country: countryOf(cf?.country),
524
+ ja4: typeof bot?.ja4 === 'string' ? bot.ja4 : null,
525
+ verifiedBot: category === null ? null : { category, name: null },
526
+ };
527
+ }
528
+ /** Cloudflare Workers: the platform's client address, its word on the client, and the Worker's `waitUntil`. */
529
+ export function cloudflare(context, origin = (request) => fetch(request)) {
530
+ return {
531
+ clientAddress: (request) => request.headers.get('cf-connecting-ip'),
532
+ signals: cloudflareSignals,
533
+ waitUntil: (work) => {
534
+ context.waitUntil(work);
535
+ },
536
+ origin,
537
+ instance: null,
538
+ };
539
+ }
540
+ /**
541
+ * Vercel (Routing Middleware, `proxy.ts`): the address Vercel's edge saw,
542
+ * and `waitUntil` from `@vercel/functions`. Middleware cannot rewrite an
543
+ * answer it passes on, so `origin` fetches the site itself, from its own
544
+ * origin.
545
+ */
546
+ export function vercel(options) {
547
+ return {
548
+ clientAddress: (request) => request.headers.get('x-real-ip') ??
549
+ request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
550
+ null,
551
+ // Vercel's edge names the country and the JA4 in headers; its verified
552
+ // bots are BotID's, read by `checkBotId()` in the app, not here.
553
+ signals: (request) => ({
554
+ asn: null,
555
+ country: countryOf(request.headers.get('x-vercel-ip-country')),
556
+ ja4: request.headers.get('x-vercel-ja4-digest'),
557
+ verifiedBot: null,
558
+ }),
559
+ ...(options.prepareOriginRequest === undefined
560
+ ? {}
561
+ : { prepareOriginRequest: options.prepareOriginRequest }),
562
+ waitUntil: options.waitUntil,
563
+ origin: options.origin,
564
+ instance: null,
565
+ };
566
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The Agentrail edge adapter, for a customer's site on Cloudflare Workers,
3
+ * Vercel or anything else on the Fetch API: one event per request, sent to
4
+ * the collector, with markers, a session and a trace of its own.
5
+ */
6
+ export { IdentifyError, IgnoreRequestError, TraceHandoffSigningError, cloudflare, createEdge, vercel, type Edge, type EdgeAdapter, type EdgeOptions, type PlatformSignals, type Principal, type RequestHead, } from './edge.js';
7
+ export { MARKER_PARAMETER, markLinks, type MarkedHosts } from './links.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The Agentrail edge adapter, for a customer's site on Cloudflare Workers,
3
+ * Vercel or anything else on the Fetch API: one event per request, sent to
4
+ * the collector, with markers, a session and a trace of its own.
5
+ */
6
+ export { IdentifyError, IgnoreRequestError, TraceHandoffSigningError, cloudflare, createEdge, vercel, } from './edge.js';
7
+ export { MARKER_PARAMETER, markLinks } from './links.js';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Markers in an agent-facing answer: every link to the site's own hosts gets
3
+ * its own lane of one response marker, so an agent that follows a link, or k
4
+ * sub-agents that follow k links, carry back which link of which answer they
5
+ * read (docs/research/agent-journey-correlation.md, 5.2 and 15.1).
6
+ *
7
+ * A host's links carry their lane in the `h` query parameter, or as a
8
+ * `/h/<marker>` path prefix for an API whose calls an extra parameter would
9
+ * break. The edge takes either off again before the origin sees the request.
10
+ * Past the last lane a link goes unmarked.
11
+ */
12
+ export declare const MARKER_PARAMETER = "h";
13
+ /** How a host's links carry their lane. */
14
+ export type MarkedHosts = Readonly<Record<string, 'query' | 'path'>>;
15
+ export interface Marked {
16
+ readonly body: string;
17
+ /** The response marker, when any link was marked. */
18
+ readonly served: string | null;
19
+ /** Each address named, marked, as a request for it is recorded. */
20
+ readonly linksOut: string[];
21
+ }
22
+ /**
23
+ * The answer with its links to the site's hosts marked. `recorded` gives a
24
+ * marked link's address in the form a request for it is recorded in, so the
25
+ * engine can match the two.
26
+ */
27
+ export declare function markLinks(body: string, base: URL, hosts: MarkedHosts, recorded: (url: URL) => string): Marked;
package/dist/links.js ADDED
@@ -0,0 +1,92 @@
1
+ import { MAX_LINK_INDEX, linkMarker, newMarker } from 'agentrail-core';
2
+ /**
3
+ * Markers in an agent-facing answer: every link to the site's own hosts gets
4
+ * its own lane of one response marker, so an agent that follows a link, or k
5
+ * sub-agents that follow k links, carry back which link of which answer they
6
+ * read (docs/research/agent-journey-correlation.md, 5.2 and 15.1).
7
+ *
8
+ * A host's links carry their lane in the `h` query parameter, or as a
9
+ * `/h/<marker>` path prefix for an API whose calls an extra parameter would
10
+ * break. The edge takes either off again before the origin sees the request.
11
+ * Past the last lane a link goes unmarked.
12
+ */
13
+ export const MARKER_PARAMETER = 'h';
14
+ /**
15
+ * An absolute link, or a Markdown link's target, in an answer's text. Either
16
+ * may hold balanced parentheses one level deep (`/wiki/Agent_(software)`), so
17
+ * a link is never cut short at a parenthesis of its own. A target in angle
18
+ * brackets (`[Guide](</guide.md>)`, which may hold spaces) is left as
19
+ * written; an absolute link inside one is still marked in place.
20
+ */
21
+ const LINK = /(?<absolute>https?:\/\/(?:[^\s<>()"'`\]]|\([^\s<>()"'`\]]*\))+)|\]\((?<target>(?!<)(?:[^()\s]|\([^()\s]*\))+)(?=[)\s])/gu;
22
+ /** Punctuation that ends a sentence, not a bare link. */
23
+ const TRAILING = /[.,;:!?]+$/u;
24
+ /**
25
+ * The answer with its links to the site's hosts marked. `recorded` gives a
26
+ * marked link's address in the form a request for it is recorded in, so the
27
+ * engine can match the two.
28
+ */
29
+ export function markLinks(body, base, hosts, recorded) {
30
+ const marker = newMarker();
31
+ /** Each address's lane; null past the last. A fragment is not part of it. */
32
+ const lanes = new Map();
33
+ const linksOut = [];
34
+ function marked(link) {
35
+ const host = link.hostname.toLowerCase();
36
+ // The site's own entries only: a link to a host named `constructor` is
37
+ // not one of them.
38
+ if (!Object.hasOwn(hosts, host))
39
+ return null;
40
+ const mode = hosts[host];
41
+ const address = `${link.host}${link.pathname}${link.search}`;
42
+ let lane = lanes.get(address);
43
+ const first = lane === undefined;
44
+ if (lane === undefined) {
45
+ lane =
46
+ lanes.size > MAX_LINK_INDEX ? null : linkMarker(marker, lanes.size);
47
+ lanes.set(address, lane);
48
+ }
49
+ if (lane === null)
50
+ return null;
51
+ // Each link keeps its own fragment: one page's sections share its lane.
52
+ const target = new URL(link);
53
+ if (mode === 'query')
54
+ target.searchParams.set(MARKER_PARAMETER, lane);
55
+ else
56
+ target.pathname = `/h/${lane}${target.pathname === '/' ? '' : target.pathname}`;
57
+ if (first)
58
+ linksOut.push(recorded(target));
59
+ return target.href;
60
+ }
61
+ const rewritten = body.replace(LINK, (match, absolute, target, offset) => {
62
+ // A bare link that runs on into a parenthesis it could not match, one
63
+ // nested deeper, is left whole rather than marked part-way.
64
+ if (absolute !== undefined && body[offset + match.length] === '(')
65
+ return match;
66
+ // A sentence's full stop or comma after a bare link is not part of it.
67
+ const trailing = absolute === undefined ? '' : (TRAILING.exec(absolute)?.[0] ?? '');
68
+ const raw = absolute?.slice(0, absolute.length - trailing.length) ?? target;
69
+ // A link within the page is not a step to another.
70
+ if (raw === undefined || raw.startsWith('#'))
71
+ return match;
72
+ let link;
73
+ try {
74
+ link = new URL(raw, base);
75
+ }
76
+ catch (error) {
77
+ // Text that only looks like a link stays as it is.
78
+ if (error instanceof TypeError)
79
+ return match;
80
+ throw error;
81
+ }
82
+ const written = marked(link);
83
+ if (written === null)
84
+ return match;
85
+ return absolute === undefined ? `](${written}` : `${written}${trailing}`;
86
+ });
87
+ return {
88
+ body: rewritten,
89
+ served: linksOut.length === 0 ? null : marker,
90
+ linksOut,
91
+ };
92
+ }
package/package.json CHANGED
@@ -1,11 +1,39 @@
1
1
  {
2
2
  "name": "agentrail-edge",
3
- "version": "0.0.0",
4
- "description": "Placeholder. Install agentrail-edge 0.1.0 or later.",
3
+ "version": "0.2.0",
4
+ "description": "The Agentrail edge: in front of a site on Cloudflare Workers, Vercel or any Fetch API runtime, it records each request and marks the links agents follow.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/agentrail-co/agentrail-js.git",
9
9
  "directory": "packages/edge"
10
+ },
11
+ "homepage": "https://github.com/agentrail-co/agentrail-js/tree/main/packages/edge#readme",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "engines": {
25
+ "node": ">=22"
26
+ },
27
+ "dependencies": {
28
+ "agentrail-core": "0.2.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "24.13.3",
32
+ "agentrail-contract": "0.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.build.json",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest run"
10
38
  }
11
- }
39
+ }