agentrail-edge 0.0.0 → 0.1.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,97 @@
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`, so
7
+ recording never slows a 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
+ ## Options
74
+
75
+ - `hosts`: the site's own hosts, and how a link to each is marked: `'query'`
76
+ adds the `h` parameter, `'path'` an `/h/<marker>` prefix, for a host whose
77
+ calls an extra parameter would break.
78
+ - `queryAllowlist`: query parameters a recorded path keeps; every other is
79
+ dropped, and named as dropped.
80
+ - `identify(request)`: the verified principal behind a request, by the site's
81
+ own check of its method, URL and headers. It runs after the answer. A
82
+ check that throws is told to `onError` as an `IdentifyError`, and the
83
+ request is recorded without a principal.
84
+ - `sessionIdleTimeout`: seconds without a request after which a session
85
+ ends; 1800 (30 minutes) by default.
86
+ - `sessionCookieDomain`: the domain a session is shared across, as
87
+ `example.com` for `docs.example.com` and `app.example.com`; by default,
88
+ the one host. Give the browser script the same two values.
89
+ - `sessionCookie`, `service`, `fetch`: the session cookie's name, the
90
+ service the events name, and the fetch the collector's calls go through.
91
+ - `onError(error)`: told of events that could not be sent, and of an
92
+ `identify` that threw; they are logged otherwise. Neither ever reaches the
93
+ visitor.
94
+
95
+ ## Licence
96
+
97
+ [Apache-2.0](LICENSE).
package/dist/edge.d.ts ADDED
@@ -0,0 +1,86 @@
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
+ /**
8
+ * What the site's own check reads of a request: never its body, which has
9
+ * gone to the origin by the time the check runs.
10
+ */
11
+ export type RequestHead = Pick<Request, 'method' | 'url' | 'headers'>;
12
+ /** A verified identity the site's own check found; its ids are hashed before they leave. */
13
+ export interface Principal {
14
+ readonly kind: PrincipalKind;
15
+ readonly id: string;
16
+ readonly actingUserId?: string | null;
17
+ }
18
+ export interface EdgeOptions {
19
+ /** Where events go, and the edge source's secret. */
20
+ readonly collector: {
21
+ readonly endpoint: string;
22
+ readonly secret: string;
23
+ };
24
+ /** The workspace's hash key, which every component of it hashes with. */
25
+ readonly hashKey: string;
26
+ /** The site's own hosts, whose links an agent-facing answer marks, and how. */
27
+ readonly hosts: MarkedHosts;
28
+ /** Query parameters kept on a recorded path; every other is dropped. */
29
+ readonly queryAllowlist?: readonly string[];
30
+ /** The session cookie's name. */
31
+ readonly sessionCookie?: string;
32
+ /**
33
+ * Seconds without a request after which a visitor's session ends; 30
34
+ * minutes by default. The browser script on the same site takes the same.
35
+ */
36
+ readonly sessionIdleTimeout?: number;
37
+ /**
38
+ * The domain a visitor's session is shared across, as `example.com` for
39
+ * `docs.example.com` and `app.example.com`; by default, the one host.
40
+ */
41
+ readonly sessionCookieDomain?: string;
42
+ /**
43
+ * The verified principal behind a request, by the site's own check of its
44
+ * method, URL and headers. It runs after the answer.
45
+ */
46
+ readonly identify?: (request: RequestHead) => Principal | null | Promise<Principal | null>;
47
+ /** The service the events name; the request's host by default. */
48
+ readonly service?: string;
49
+ /**
50
+ * Told of events that could not be sent, and of an `identify` that threw.
51
+ * Logs by default.
52
+ */
53
+ readonly onError?: (error: Error) => void;
54
+ /** The fetch the collector's calls go through; the platform's own by default. */
55
+ readonly fetch?: typeof fetch;
56
+ }
57
+ /** What the platform the edge runs on provides. */
58
+ export interface EdgeAdapter {
59
+ /** The client's address, as the platform saw it; null when it says none. */
60
+ clientAddress(request: Request): string | null;
61
+ /** Keeps the platform running work past the answer. */
62
+ waitUntil(work: Promise<unknown>): void;
63
+ /** Sends the request on to the site. */
64
+ origin(request: Request): Promise<Response>;
65
+ /** This edge instance, when the platform names one. */
66
+ readonly instance: string | null;
67
+ }
68
+ export interface Edge {
69
+ /** Answers a request through the origin, and records it. */
70
+ handle(request: Request, adapter: EdgeAdapter): Promise<Response>;
71
+ }
72
+ export declare function createEdge(options: EdgeOptions): Edge;
73
+ /** Cloudflare Workers: the platform's client address, and the Worker's `waitUntil`. */
74
+ export declare function cloudflare(context: {
75
+ waitUntil(work: Promise<unknown>): void;
76
+ }, origin?: (request: Request) => Promise<Response>): EdgeAdapter;
77
+ /**
78
+ * Vercel (Routing Middleware, `proxy.ts`): the address Vercel's edge saw,
79
+ * and `waitUntil` from `@vercel/functions`. Middleware cannot rewrite an
80
+ * answer it passes on, so `origin` fetches the site itself, from its own
81
+ * origin.
82
+ */
83
+ export declare function vercel(options: {
84
+ readonly waitUntil: (work: Promise<unknown>) => void;
85
+ readonly origin: (request: Request) => Promise<Response>;
86
+ }): EdgeAdapter;
package/dist/edge.js ADDED
@@ -0,0 +1,411 @@
1
+ import { createCollector, 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
+ *
18
+ * The events go to the collector after the answer, through the platform's
19
+ * `waitUntil`, so recording never slows a request. Requests one edge answers
20
+ * share calls: what is sent while a call is out goes in the next, together,
21
+ * so a site creates its edge once, not per request.
22
+ */
23
+ /** A path's leading `/h/<segment>`: a link's marker, when the segment reads as one. */
24
+ const PATH_MARKER = /^\/h\/([^/]+)/u;
25
+ /** The most of an agent-facing answer read to mark its links; a larger one passes as it came. */
26
+ const MARKABLE_BYTES = 2 * 1024 * 1024;
27
+ /**
28
+ * How long after the origin answered the call carrying a request's event may
29
+ * run, every try and wait included. Cloudflare gives `waitUntil` 30 s after
30
+ * the answer is sent, the least of the platforms, and cancels what is still
31
+ * running then; counted from before it is sent, 25 s leaves room for a slow
32
+ * `identify`.
33
+ */
34
+ const SEND_WITHIN_MS = 25_000;
35
+ /** The site's `identify` threw: the request is recorded without a principal. */
36
+ export class IdentifyError extends Error {
37
+ name = 'IdentifyError';
38
+ }
39
+ /**
40
+ * The markers a query carries in `h`, and the query without them, every
41
+ * other pair exactly as it came: a value that does not read as a marker is
42
+ * the site's own, and stays.
43
+ */
44
+ function markersOffQuery(search) {
45
+ const markers = [];
46
+ const rest = search
47
+ .slice(1)
48
+ .split('&')
49
+ .filter((pair) => {
50
+ const [entry] = new URLSearchParams(pair);
51
+ if (entry?.[0] !== MARKER_PARAMETER || !parseMarker(entry[1]).valid)
52
+ return true;
53
+ markers.push(entry[1]);
54
+ return false;
55
+ });
56
+ return { markers, rest: rest.join('&') };
57
+ }
58
+ /**
59
+ * An answer whose links are marked: a whole one (a `200` to a `GET`, so never
60
+ * a range) in Markdown, or `llms.txt` or a `.md` path served as text.
61
+ */
62
+ function isAgentFacing(method, url, response) {
63
+ if (method !== 'GET' || response.status !== 200)
64
+ return false;
65
+ const type = (response.headers.get('content-type') ?? '').toLowerCase();
66
+ if (type.startsWith('text/markdown') || type.startsWith('text/x-markdown'))
67
+ return true;
68
+ return (type.startsWith('text/plain') &&
69
+ /(?:\/llms(?:-full)?\.txt|\.md)$/u.test(url.pathname));
70
+ }
71
+ /**
72
+ * The origin's headers for a body this edge has read: a fetch hands it over
73
+ * decoded, so neither the origin's encoding nor its length is the body's.
74
+ */
75
+ function headersOfRead(response) {
76
+ const headers = new Headers(response.headers);
77
+ headers.delete('content-length');
78
+ headers.delete('content-encoding');
79
+ return headers;
80
+ }
81
+ /**
82
+ * The answer's text, when it is at most `limit` bytes. A larger answer comes
83
+ * back as a response that sends what was read and then the rest, as it came.
84
+ */
85
+ async function readUpTo(response, body, limit) {
86
+ const reader = body.getReader();
87
+ const decoder = new TextDecoder();
88
+ const chunks = [];
89
+ let size = 0;
90
+ for (;;) {
91
+ const next = await reader.read();
92
+ if (next.done)
93
+ break;
94
+ chunks.push(next.value);
95
+ size += next.value.byteLength;
96
+ if (size > limit) {
97
+ const rest = new ReadableStream({
98
+ start(controller) {
99
+ for (const chunk of chunks)
100
+ controller.enqueue(chunk);
101
+ },
102
+ async pull(controller) {
103
+ const more = await reader.read();
104
+ if (more.done)
105
+ controller.close();
106
+ else
107
+ controller.enqueue(more.value);
108
+ },
109
+ cancel: (reason) => reader.cancel(reason),
110
+ });
111
+ return new Response(rest, {
112
+ status: response.status,
113
+ statusText: response.statusText,
114
+ headers: headersOfRead(response),
115
+ });
116
+ }
117
+ }
118
+ return (chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join('') +
119
+ decoder.decode());
120
+ }
121
+ export function createEdge(options) {
122
+ const { hashKey, hosts, identify, service } = options;
123
+ const onError = options.onError ??
124
+ ((error) => {
125
+ console.error('agentrail:', error);
126
+ });
127
+ const cookie = sessionCookie({
128
+ name: options.sessionCookie ?? 'agentrail_session',
129
+ idleTimeout: options.sessionIdleTimeout,
130
+ domain: options.sessionCookieDomain,
131
+ });
132
+ const allowlist = new Set([
133
+ MARKER_PARAMETER,
134
+ ...(options.queryAllowlist ?? []),
135
+ ]);
136
+ // Every call names the key its events were hashed with. Its id is a
137
+ // digest, which WebCrypto only gives asynchronously, so the collector is
138
+ // ready from the first send on, never on a request's path.
139
+ const collector = hashKeyIdOf(hashKey).then((hashKeyId) => createCollector({
140
+ endpoint: options.collector.endpoint,
141
+ secret: options.collector.secret,
142
+ component: {
143
+ name: 'agentrail-edge',
144
+ version: VERSION,
145
+ surfaces: ['edge'],
146
+ hashKeyId,
147
+ },
148
+ onError,
149
+ ...(options.fetch ? { fetch: options.fetch } : {}),
150
+ }));
151
+ /** A path as it is recorded: the allowlisted query only. */
152
+ function recordedPath(url) {
153
+ const kept = new URLSearchParams([...url.searchParams].filter(([name]) => allowlist.has(name)));
154
+ return {
155
+ path: `${url.pathname}${kept.size === 0 ? '' : `?${kept.toString()}`}`,
156
+ dropped: [...url.searchParams.keys()].some((name) => !allowlist.has(name)),
157
+ };
158
+ }
159
+ /** A redirect's target as it is recorded: the allowlisted query only, no fragment. */
160
+ function recordedLocation(location, base) {
161
+ if (location === null)
162
+ return { location: null, redaction: null };
163
+ let target;
164
+ try {
165
+ target = new URL(location, base);
166
+ }
167
+ catch (error) {
168
+ // A target the edge cannot read, it cannot strip either: it stays here.
169
+ if (error instanceof TypeError)
170
+ return { location: null, redaction: 'unparsable' };
171
+ throw error;
172
+ }
173
+ const { path, dropped } = recordedPath(target);
174
+ return {
175
+ location: `${target.protocol}//${target.host}${path}`,
176
+ redaction: dropped ? 'query_outside_allowlist' : null,
177
+ };
178
+ }
179
+ /**
180
+ * The principal the site's own check names. A check that throws is the
181
+ * site's to fix, and is told to `onError`; the request is still a step the
182
+ * agent took, recorded without the principal the check could not name.
183
+ */
184
+ async function principalOf(request) {
185
+ if (identify === undefined)
186
+ return null;
187
+ try {
188
+ return await identify(request);
189
+ }
190
+ catch (error) {
191
+ onError(new IdentifyError("The site's identify threw; the request is recorded without a principal.", { cause: error }));
192
+ return null;
193
+ }
194
+ }
195
+ async function marked(method, url, response, observed) {
196
+ const length = Number(response.headers.get('content-length') ?? '0');
197
+ if (!isAgentFacing(method, url, response) ||
198
+ response.body === null ||
199
+ length > MARKABLE_BYTES)
200
+ return response;
201
+ const text = await readUpTo(response, response.body, MARKABLE_BYTES);
202
+ if (text instanceof Response)
203
+ return text;
204
+ const result = markLinks(text, url, hosts, (link) => {
205
+ return `${link.host}${recordedPath(link).path}`;
206
+ });
207
+ observed.served = result.served;
208
+ observed.linksOut = result.linksOut;
209
+ const headers = headersOfRead(response);
210
+ // The body is now this reader's alone.
211
+ headers.delete('etag');
212
+ if (result.served !== null)
213
+ headers.set('cache-control', 'private, no-store');
214
+ return new Response(result.body, {
215
+ status: response.status,
216
+ statusText: response.statusText,
217
+ headers,
218
+ });
219
+ }
220
+ async function eventOf(input) {
221
+ const { request, url, observed } = input;
222
+ // With its port, as a link to it is recorded.
223
+ const host = url.host;
224
+ const { path, dropped } = recordedPath(url);
225
+ const location = recordedLocation(observed.location, url);
226
+ const principal = await principalOf(request);
227
+ const actingUserId = principal?.actingUserId ?? null;
228
+ return {
229
+ schemaVersion: 1,
230
+ id: crypto.randomUUID(),
231
+ surface: 'edge',
232
+ kind: 'http.request',
233
+ start: input.start,
234
+ end: input.end,
235
+ clock: 'edge',
236
+ emittedBy: 'argus',
237
+ resource: {
238
+ serviceName: service ?? host,
239
+ serviceInstanceId: input.instance,
240
+ },
241
+ span: {
242
+ traceId: input.span.traceId,
243
+ spanId: input.span.spanId,
244
+ parentSpanId: null,
245
+ kind: 'server',
246
+ publicEntry: true,
247
+ subtreeSpanIds: [],
248
+ links: input.caller === null ? [] : [input.caller],
249
+ },
250
+ session: { id: input.session, previousId: null },
251
+ http: {
252
+ method: request.method,
253
+ host,
254
+ path,
255
+ status: observed.status,
256
+ location: location.location,
257
+ contentType: observed.contentType,
258
+ linksOut: [...observed.linksOut],
259
+ },
260
+ actor: {
261
+ egress: input.address === null
262
+ ? null
263
+ : await keyedHash(hashKey, input.address),
264
+ userAgent: request.headers.get('user-agent'),
265
+ client: null,
266
+ },
267
+ principal: principal === null
268
+ ? null
269
+ : {
270
+ kind: principal.kind,
271
+ id: await keyedHash(hashKey, principal.id),
272
+ actingUserId: actingUserId === null
273
+ ? null
274
+ : await keyedHash(hashKey, actingUserId),
275
+ },
276
+ registration: null,
277
+ markers: {
278
+ served: observed.served === null
279
+ ? []
280
+ : [{ value: observed.served, durable: false }],
281
+ seen: [...input.seen],
282
+ },
283
+ redactions: [
284
+ ...(input.address === null
285
+ ? []
286
+ : [{ field: 'actor.egress', reason: 'keyed_hash' }]),
287
+ ...(principal === null
288
+ ? []
289
+ : [{ field: 'principal.id', reason: 'keyed_hash' }]),
290
+ ...(dropped
291
+ ? [{ field: 'http.path', reason: 'query_outside_allowlist' }]
292
+ : []),
293
+ ...(location.redaction === null
294
+ ? []
295
+ : [{ field: 'http.location', reason: location.redaction }]),
296
+ ],
297
+ };
298
+ }
299
+ return {
300
+ async handle(request, adapter) {
301
+ const start = Date.now();
302
+ const url = new URL(request.url);
303
+ const query = markersOffQuery(url.search);
304
+ const segment = PATH_MARKER.exec(url.pathname)?.[1];
305
+ const pathMarker = segment !== undefined && parseMarker(segment).valid ? segment : null;
306
+ const seen = pathMarker === null ? query.markers : [...query.markers, pathMarker];
307
+ // What the origin sees: the markers taken off and nothing else of the
308
+ // address changed, and this edge's trace.
309
+ const originUrl = new URL(url);
310
+ if (query.markers.length > 0)
311
+ originUrl.search = query.rest;
312
+ if (pathMarker !== null)
313
+ originUrl.pathname =
314
+ url.pathname.slice(`/h/${pathMarker}`.length) || '/';
315
+ const caller = parseTraceparent(request.headers.get('traceparent'));
316
+ const span = { traceId: newTraceId(), spanId: newSpanId() };
317
+ const headers = new Headers(request.headers);
318
+ headers.set('traceparent', formatTraceparent(span));
319
+ // The caller's vendor state belongs to the caller's trace.
320
+ headers.delete('tracestate');
321
+ const forwarded = new Request(originUrl, {
322
+ method: request.method,
323
+ headers,
324
+ body: request.body,
325
+ redirect: 'manual',
326
+ // A visitor who goes away stops the origin's work too.
327
+ signal: request.signal,
328
+ // A streamed body needs it; Workers and Node both take it.
329
+ duplex: 'half',
330
+ });
331
+ // What `identify` reads once the answer is sent: the body is the origin's.
332
+ const head = {
333
+ method: request.method,
334
+ url: request.url,
335
+ headers: new Headers(request.headers),
336
+ };
337
+ // A session a day old starts the next, which names no previous one:
338
+ // the engine would join the two again. One idle too long the browser
339
+ // has already dropped.
340
+ const session = cookie.read(request.headers.get('cookie') ?? '', start) ??
341
+ newSessionId(start);
342
+ const observed = {
343
+ status: null,
344
+ location: null,
345
+ contentType: null,
346
+ served: null,
347
+ linksOut: [],
348
+ };
349
+ try {
350
+ // Links resolve against the address the origin answered for, so a
351
+ // relative one never carries the marker this request came with.
352
+ const answer = await marked(request.method, originUrl, await adapter.origin(forwarded), observed);
353
+ observed.status = answer.status;
354
+ observed.location = answer.headers.get('location');
355
+ observed.contentType = answer.headers.get('content-type');
356
+ // On every answer, so the session lasts another idle timeout.
357
+ const withCookie = new Response(answer.body, answer);
358
+ withCookie.headers.append('set-cookie', cookie.write(session, url.protocol === 'https:'));
359
+ return withCookie;
360
+ }
361
+ finally {
362
+ // One event per request however its answer ended: a request the
363
+ // origin could not answer is still a step the agent took.
364
+ const end = Date.now();
365
+ adapter.waitUntil((async () => {
366
+ const sending = await collector;
367
+ await sending.send(await eventOf({
368
+ request: head,
369
+ url,
370
+ address: adapter.clientAddress(request),
371
+ instance: adapter.instance,
372
+ start,
373
+ end,
374
+ span,
375
+ caller,
376
+ session,
377
+ seen,
378
+ observed,
379
+ }), end + SEND_WITHIN_MS);
380
+ })());
381
+ }
382
+ },
383
+ };
384
+ }
385
+ /** Cloudflare Workers: the platform's client address, and the Worker's `waitUntil`. */
386
+ export function cloudflare(context, origin = (request) => fetch(request)) {
387
+ return {
388
+ clientAddress: (request) => request.headers.get('cf-connecting-ip'),
389
+ waitUntil: (work) => {
390
+ context.waitUntil(work);
391
+ },
392
+ origin,
393
+ instance: null,
394
+ };
395
+ }
396
+ /**
397
+ * Vercel (Routing Middleware, `proxy.ts`): the address Vercel's edge saw,
398
+ * and `waitUntil` from `@vercel/functions`. Middleware cannot rewrite an
399
+ * answer it passes on, so `origin` fetches the site itself, from its own
400
+ * origin.
401
+ */
402
+ export function vercel(options) {
403
+ return {
404
+ clientAddress: (request) => request.headers.get('x-real-ip') ??
405
+ request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
406
+ null,
407
+ waitUntil: options.waitUntil,
408
+ origin: options.origin,
409
+ instance: null,
410
+ };
411
+ }
@@ -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, cloudflare, createEdge, vercel, type Edge, type EdgeAdapter, type EdgeOptions, 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, 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.1.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.1.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
+ }