agentrail-core 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 +201 -0
- package/README.md +27 -0
- package/dist/collector.d.ts +75 -0
- package/dist/collector.js +182 -0
- package/dist/event.d.ts +114 -0
- package/dist/event.js +23 -0
- package/dist/hash.d.ts +17 -0
- package/dist/hash.js +40 -0
- package/dist/id.d.ts +10 -0
- package/dist/id.js +17 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/marker.d.ts +40 -0
- package/dist/marker.js +102 -0
- package/dist/session.d.ts +40 -0
- package/dist/session.js +69 -0
- package/dist/trace.d.ts +7 -0
- package/dist/trace.js +33 -0
- package/dist/version.d.ts +7 -0
- package/dist/version.js +7 -0
- package/package.json +28 -3
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,27 @@
|
|
|
1
|
+
# agentrail-core
|
|
2
|
+
|
|
3
|
+
What every Agentrail component shares, wherever the Fetch API and WebCrypto
|
|
4
|
+
run (Cloudflare Workers, Vercel's edge, Node, browsers): the event the
|
|
5
|
+
collector takes, as types; markers, minted and read (`parseMarker`) as the
|
|
6
|
+
collector's engine reads them; the keyed hash a workspace hashes addresses
|
|
7
|
+
and principals with, and its key's id; W3C trace context; the session
|
|
8
|
+
cookie, which ends after 30 minutes idle and a day at most, its id a UUIDv7
|
|
9
|
+
that carries its start; and the collector client. Its `send(event,
|
|
10
|
+
deadline)` resolves once the call carrying the event has ended: one call is
|
|
11
|
+
under way at a time, and what is sent meanwhile goes in the next, together.
|
|
12
|
+
It retries what the network or the collector failed after a random wait,
|
|
13
|
+
never sooner than a `Retry-After`, ends every call by its deadline, and
|
|
14
|
+
tells `onError` of every call given up.
|
|
15
|
+
|
|
16
|
+
`agentrail-edge` and `agentrail-browser` are built on it; a component of
|
|
17
|
+
your own can be too.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install agentrail-core
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Before 1.0, a minor version (0.1 to 0.2) may change what the package offers.
|
|
24
|
+
|
|
25
|
+
## Licence
|
|
26
|
+
|
|
27
|
+
[Apache-2.0](LICENSE).
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { AgentrailEvent, Component } from './event.js';
|
|
2
|
+
/**
|
|
3
|
+
* Sends a component's events to the collector, `POST <endpoint>/ingest/events`
|
|
4
|
+
* with the source's secret: an edge sends each request's event after the
|
|
5
|
+
* answer, through its platform's `waitUntil`, off the request's path.
|
|
6
|
+
*
|
|
7
|
+
* One call at a time. An event sent while no call is under way goes at once;
|
|
8
|
+
* one sent while a call is under way waits, and goes with every other that
|
|
9
|
+
* waited in the next call, as Kafka's producer batches with no linger: a
|
|
10
|
+
* quiet site sends a call per event, a busy one about a call per round trip
|
|
11
|
+
* to the collector. A call goes from a send still waiting on it: a platform
|
|
12
|
+
* cancels what a request left running once its `waitUntil` has ended, so a
|
|
13
|
+
* call never rides on a request that is done.
|
|
14
|
+
*
|
|
15
|
+
* A call that fails because the network or the collector did (no answer, a
|
|
16
|
+
* 5xx, a 429, or no answer within the try's time) is tried again, after a
|
|
17
|
+
* random part of 250 ms and then of 1 s, so components that failed together
|
|
18
|
+
* do not try again together, and never sooner than a `Retry-After` the
|
|
19
|
+
* collector sent; each try sends the same events, which the collector counts
|
|
20
|
+
* as duplicates once stored. A call ends by its events' deadline: no try or
|
|
21
|
+
* wait starts that would end past it. A call the collector refuses (any other
|
|
22
|
+
* 4xx: a revoked secret, an event it cannot read) is not tried again. Either
|
|
23
|
+
* way the events are given up and the failure goes to `onError`, which logs
|
|
24
|
+
* it unless told otherwise, so a lost collector never fails the platform
|
|
25
|
+
* awaiting a send. Anything else is a fault here, and is thrown.
|
|
26
|
+
*/
|
|
27
|
+
export interface CollectorOptions {
|
|
28
|
+
/** The collector's origin, such as `https://api.agentrail.dev`. */
|
|
29
|
+
readonly endpoint: string;
|
|
30
|
+
/** The source's secret, as created for this component. */
|
|
31
|
+
readonly secret: string;
|
|
32
|
+
readonly component: Component;
|
|
33
|
+
/** Events per call; the collector takes calls of up to 16 MB. */
|
|
34
|
+
readonly batchSize?: number;
|
|
35
|
+
/** Tries per call, the first included. */
|
|
36
|
+
readonly attempts?: number;
|
|
37
|
+
/**
|
|
38
|
+
* How long one try may take, its answer read included, before it counts
|
|
39
|
+
* as failed and is tried again; 10 s by default, and never past the
|
|
40
|
+
* call's deadline.
|
|
41
|
+
*/
|
|
42
|
+
readonly timeoutMs?: number;
|
|
43
|
+
/** Told of each call whose events were given up. Logs by default. */
|
|
44
|
+
readonly onError?: (error: Error) => void;
|
|
45
|
+
readonly fetch?: typeof fetch;
|
|
46
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
export interface Collector {
|
|
49
|
+
/**
|
|
50
|
+
* Sends an event, and resolves once the call carrying it has ended: taken,
|
|
51
|
+
* or given up and told to `onError`. `deadline`, in milliseconds since the
|
|
52
|
+
* epoch, is when that call must end, every try and wait included.
|
|
53
|
+
*/
|
|
54
|
+
send(event: AgentrailEvent, deadline: number): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
/** The collector refused a call: trying again would be refused again. */
|
|
57
|
+
export declare class CollectorRefusedError extends Error {
|
|
58
|
+
readonly status: number;
|
|
59
|
+
readonly name = "CollectorRefusedError";
|
|
60
|
+
constructor(status: number, message: string);
|
|
61
|
+
}
|
|
62
|
+
/** One try failed on the collector's side (a 5xx, a 429): worth another. */
|
|
63
|
+
export declare class CollectorFailedError extends Error {
|
|
64
|
+
readonly status: number;
|
|
65
|
+
readonly name = "CollectorFailedError";
|
|
66
|
+
constructor(status: number, message: string);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* No call got through: the network, or the collector, failed every try, or
|
|
70
|
+
* the deadline left no time for another.
|
|
71
|
+
*/
|
|
72
|
+
export declare class CollectorUnavailableError extends Error {
|
|
73
|
+
readonly name = "CollectorUnavailableError";
|
|
74
|
+
}
|
|
75
|
+
export declare function createCollector(options: CollectorOptions): Collector;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/** The collector refused a call: trying again would be refused again. */
|
|
2
|
+
export class CollectorRefusedError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
name = 'CollectorRefusedError';
|
|
5
|
+
constructor(status, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.status = status;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** One try failed on the collector's side (a 5xx, a 429): worth another. */
|
|
11
|
+
export class CollectorFailedError extends Error {
|
|
12
|
+
status;
|
|
13
|
+
name = 'CollectorFailedError';
|
|
14
|
+
constructor(status, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.status = status;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* No call got through: the network, or the collector, failed every try, or
|
|
21
|
+
* the deadline left no time for another.
|
|
22
|
+
*/
|
|
23
|
+
export class CollectorUnavailableError extends Error {
|
|
24
|
+
name = 'CollectorUnavailableError';
|
|
25
|
+
}
|
|
26
|
+
/** The longest wait before each try after the first; each wait is a random part of it. */
|
|
27
|
+
const BACKOFF_MS = [250, 1_000];
|
|
28
|
+
function retriable(status) {
|
|
29
|
+
return status === 429 || status >= 500;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* How long a `Retry-After` asks to wait, in milliseconds: delay-seconds or an
|
|
33
|
+
* HTTP date (RFC 9110, 10.2.3). Null for none, or for one that is neither: it
|
|
34
|
+
* asks for nothing this client can read.
|
|
35
|
+
*/
|
|
36
|
+
function retryAfterMs(value, now) {
|
|
37
|
+
if (value === null)
|
|
38
|
+
return null;
|
|
39
|
+
const text = value.trim();
|
|
40
|
+
if (/^\d+$/u.test(text))
|
|
41
|
+
return Number(text) * 1_000;
|
|
42
|
+
const at = Date.parse(text);
|
|
43
|
+
return Number.isNaN(at) ? null : Math.max(0, at - now);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The try outran its deadline. Fetch rejects with the signal's reason, a
|
|
47
|
+
* `TimeoutError`; a runtime that does not pass the reason on rejects with an
|
|
48
|
+
* `AbortError`, and the deadline's is the only signal a try has.
|
|
49
|
+
*/
|
|
50
|
+
function timedOut(error) {
|
|
51
|
+
return (error instanceof DOMException &&
|
|
52
|
+
(error.name === 'TimeoutError' || error.name === 'AbortError'));
|
|
53
|
+
}
|
|
54
|
+
export function createCollector(options) {
|
|
55
|
+
const { endpoint, secret, component, batchSize = 500, attempts = 3, timeoutMs = 10_000, onError = (error) => {
|
|
56
|
+
console.error('agentrail: events were not sent', error);
|
|
57
|
+
}, fetch: send = fetch, sleep = (ms) => new Promise((resolve) => {
|
|
58
|
+
setTimeout(resolve, ms);
|
|
59
|
+
}), } = options;
|
|
60
|
+
const url = new URL('/ingest/events', endpoint);
|
|
61
|
+
const queue = [];
|
|
62
|
+
/** The calls under way; null when none is. */
|
|
63
|
+
let out = null;
|
|
64
|
+
async function deliver(events, deadline) {
|
|
65
|
+
const body = JSON.stringify({
|
|
66
|
+
component: { ...component, surfaces: [...component.surfaces] },
|
|
67
|
+
events,
|
|
68
|
+
});
|
|
69
|
+
let last = null;
|
|
70
|
+
let tries = 0;
|
|
71
|
+
// What the collector last asked a try to wait, at least.
|
|
72
|
+
let asked = null;
|
|
73
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
74
|
+
const longest = BACKOFF_MS[Math.min(attempt, BACKOFF_MS.length) - 1];
|
|
75
|
+
// One call after another: a retry waits out the failure before it.
|
|
76
|
+
const wait = longest === undefined
|
|
77
|
+
? 0
|
|
78
|
+
: Math.max(Math.random() * longest, asked ?? 0);
|
|
79
|
+
if (Date.now() + wait >= deadline)
|
|
80
|
+
break;
|
|
81
|
+
if (longest !== undefined)
|
|
82
|
+
await sleep(wait);
|
|
83
|
+
const left = deadline - Date.now();
|
|
84
|
+
if (left <= 0)
|
|
85
|
+
break;
|
|
86
|
+
tries += 1;
|
|
87
|
+
let response;
|
|
88
|
+
// What the collector said; a success says nothing more worth reading.
|
|
89
|
+
let answer;
|
|
90
|
+
try {
|
|
91
|
+
// One deadline for the whole try: a collector that sends its headers
|
|
92
|
+
// and never finishes its body holds the try no longer than one that
|
|
93
|
+
// never answers.
|
|
94
|
+
response = await send(url, {
|
|
95
|
+
method: 'POST',
|
|
96
|
+
headers: {
|
|
97
|
+
authorization: `Bearer ${secret}`,
|
|
98
|
+
'content-type': 'application/json',
|
|
99
|
+
},
|
|
100
|
+
body,
|
|
101
|
+
signal: AbortSignal.timeout(Math.min(timeoutMs, left)),
|
|
102
|
+
});
|
|
103
|
+
answer = response.ok ? null : await response.text();
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
// Fetch rejects only when the network failed, before or while the
|
|
107
|
+
// answer arrived, or the deadline came first: nothing was read, so
|
|
108
|
+
// the call is tried again.
|
|
109
|
+
if (!(error instanceof TypeError) && !timedOut(error))
|
|
110
|
+
throw error;
|
|
111
|
+
last = error;
|
|
112
|
+
asked = null;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (answer === null) {
|
|
116
|
+
try {
|
|
117
|
+
await response.body?.cancel();
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
// The collector took the call: a body whose connection broke after
|
|
121
|
+
// its status changes nothing it said.
|
|
122
|
+
if (!(error instanceof TypeError))
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (!retriable(response.status))
|
|
128
|
+
throw new CollectorRefusedError(response.status, `The collector refused ${String(events.length)} events (${String(response.status)}): ${answer}`);
|
|
129
|
+
last = new CollectorFailedError(response.status, `The collector answered ${String(response.status)}: ${answer}`);
|
|
130
|
+
asked = retryAfterMs(response.headers.get('retry-after'), Date.now());
|
|
131
|
+
}
|
|
132
|
+
const outOfTime = tries < attempts;
|
|
133
|
+
throw new CollectorUnavailableError(`${String(events.length)} events were not sent after ${String(tries)} ${tries === 1 ? 'try' : 'tries'}${outOfTime ? ', with no time left before their deadline' : ''}.`, last === null ? undefined : { cause: last });
|
|
134
|
+
}
|
|
135
|
+
/** Sends what was taken off the queue, by the earliest deadline among it. */
|
|
136
|
+
async function sendTaken(taken) {
|
|
137
|
+
const deadline = Math.min(...taken.map((queued) => queued.deadline));
|
|
138
|
+
const events = taken.map((queued) => queued.event);
|
|
139
|
+
const batches = [];
|
|
140
|
+
for (let at = 0; at < events.length; at += batchSize)
|
|
141
|
+
batches.push(events.slice(at, at + batchSize));
|
|
142
|
+
await Promise.all(batches.map(async (batch) => {
|
|
143
|
+
try {
|
|
144
|
+
await deliver(batch, deadline);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
// Given up: told to onError, which logs unless told otherwise.
|
|
148
|
+
if (error instanceof CollectorRefusedError ||
|
|
149
|
+
error instanceof CollectorUnavailableError) {
|
|
150
|
+
onError(error);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
}));
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
async send(event, deadline) {
|
|
159
|
+
const queued = { event, deadline };
|
|
160
|
+
queue.push(queued);
|
|
161
|
+
// The call under way ends first, however it ends: the send that started
|
|
162
|
+
// it reports a fault.
|
|
163
|
+
while (out !== null)
|
|
164
|
+
await Promise.allSettled([out]);
|
|
165
|
+
// Carried by a call that has ended.
|
|
166
|
+
if (!queue.includes(queued))
|
|
167
|
+
return;
|
|
168
|
+
const calls = (async () => {
|
|
169
|
+
try {
|
|
170
|
+
await sendTaken(queue.splice(0, queue.length));
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
out = null;
|
|
174
|
+
}
|
|
175
|
+
})();
|
|
176
|
+
out = calls;
|
|
177
|
+
// This send waits on the call it started, so the request it belongs to
|
|
178
|
+
// keeps the call alive to its end.
|
|
179
|
+
await calls;
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
package/dist/event.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One event as a component sends it to the collector (`POST /ingest/events`):
|
|
3
|
+
* the journey engine's event less `tenant` and `observedAt`, which the
|
|
4
|
+
* collector stamps from the source's workspace and its own clock, and
|
|
5
|
+
* `hashKeyId`, which it stamps from the key the call names.
|
|
6
|
+
*
|
|
7
|
+
* The engine, private to Argus, holds the schema the collector checks; this
|
|
8
|
+
* package holds the same shape as types, so no component imports the
|
|
9
|
+
* engine. The edge's and the browser's tests check every call they send
|
|
10
|
+
* against the contract Argus writes (`packages/contract`).
|
|
11
|
+
*/
|
|
12
|
+
export declare const SURFACES: readonly ["edge", "firewall", "browser", "http", "mcp", "a2a", "genai", "auth", "payment", "custom"];
|
|
13
|
+
export type Surface = (typeof SURFACES)[number];
|
|
14
|
+
/** Whose clock wrote `start` and `end`. */
|
|
15
|
+
export type ClockSource = 'edge' | 'backend' | 'browser' | 'third_party';
|
|
16
|
+
export type SpanKind = 'server' | 'client' | 'internal' | 'producer' | 'consumer';
|
|
17
|
+
/** What a verified principal is. Self-reported identity is never a principal. */
|
|
18
|
+
export type PrincipalKind = 'user' | 'agent_registration' | 'agent_instance' | 'oauth_client' | 'api_key';
|
|
19
|
+
export type RegistrationPhase = 'created' | 'claim_completed' | 'expired' | 'revoked';
|
|
20
|
+
export interface SpanContext {
|
|
21
|
+
readonly traceId: string;
|
|
22
|
+
readonly spanId: string;
|
|
23
|
+
}
|
|
24
|
+
export interface AgentrailEvent {
|
|
25
|
+
/** Bumped when a field's meaning changes; stored events are read back. */
|
|
26
|
+
readonly schemaVersion: 1;
|
|
27
|
+
/** Minted here, so a duplicate delivery is the same event. */
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly surface: Surface;
|
|
30
|
+
/** What happened, e.g. `http.request`, `tool.call`. */
|
|
31
|
+
readonly kind: string;
|
|
32
|
+
/** This component's clock, milliseconds since the epoch. */
|
|
33
|
+
readonly start: number;
|
|
34
|
+
/** Null for a point event. */
|
|
35
|
+
readonly end: number | null;
|
|
36
|
+
readonly clock: ClockSource;
|
|
37
|
+
/** `argus` for our own components; `other` for anything else. */
|
|
38
|
+
readonly emittedBy: 'argus' | 'other';
|
|
39
|
+
/** OpenTelemetry resource: `service.name` and `service.instance.id`. */
|
|
40
|
+
readonly resource: {
|
|
41
|
+
readonly serviceName: string;
|
|
42
|
+
readonly serviceInstanceId: string | null;
|
|
43
|
+
};
|
|
44
|
+
readonly span: {
|
|
45
|
+
readonly traceId: string;
|
|
46
|
+
readonly spanId: string;
|
|
47
|
+
readonly parentSpanId: string | null;
|
|
48
|
+
readonly kind: SpanKind;
|
|
49
|
+
/** Entered from outside: a parent it names came from whoever called. */
|
|
50
|
+
readonly publicEntry: boolean;
|
|
51
|
+
readonly subtreeSpanIds: string[];
|
|
52
|
+
readonly links: SpanContext[];
|
|
53
|
+
} | null;
|
|
54
|
+
/** `session.id` and `session.previous_id`, set by our edge. */
|
|
55
|
+
readonly session: {
|
|
56
|
+
readonly id: string;
|
|
57
|
+
readonly previousId: string | null;
|
|
58
|
+
} | null;
|
|
59
|
+
readonly http: {
|
|
60
|
+
readonly method: string;
|
|
61
|
+
readonly host: string;
|
|
62
|
+
/** The path with the allowlisted query. */
|
|
63
|
+
readonly path: string;
|
|
64
|
+
readonly status: number | null;
|
|
65
|
+
readonly location: string | null;
|
|
66
|
+
readonly contentType: string | null;
|
|
67
|
+
/** The addresses on the site's own hosts a response named, as requested. */
|
|
68
|
+
readonly linksOut: string[];
|
|
69
|
+
} | null;
|
|
70
|
+
/** Self-reported or network facts: features, never proofs. */
|
|
71
|
+
readonly actor: {
|
|
72
|
+
/** Keyed hash of the client address. */
|
|
73
|
+
readonly egress: string | null;
|
|
74
|
+
readonly userAgent: string | null;
|
|
75
|
+
readonly client: string | null;
|
|
76
|
+
};
|
|
77
|
+
/** A verified identity, its ids keyed hashes. */
|
|
78
|
+
readonly principal: {
|
|
79
|
+
readonly kind: PrincipalKind;
|
|
80
|
+
readonly id: string;
|
|
81
|
+
readonly actingUserId: string | null;
|
|
82
|
+
} | null;
|
|
83
|
+
readonly registration: {
|
|
84
|
+
readonly id: string;
|
|
85
|
+
readonly phase: RegistrationPhase;
|
|
86
|
+
readonly claimedBy: string | null;
|
|
87
|
+
} | null;
|
|
88
|
+
readonly markers: {
|
|
89
|
+
/** Markers planted in this step's response. */
|
|
90
|
+
readonly served: {
|
|
91
|
+
readonly value: string;
|
|
92
|
+
readonly durable: boolean;
|
|
93
|
+
}[];
|
|
94
|
+
/** Marker strings found in this step's request, as received. */
|
|
95
|
+
readonly seen: string[];
|
|
96
|
+
};
|
|
97
|
+
/** What was hashed or dropped here, and why. */
|
|
98
|
+
readonly redactions: {
|
|
99
|
+
readonly field: string;
|
|
100
|
+
readonly reason: string;
|
|
101
|
+
}[];
|
|
102
|
+
}
|
|
103
|
+
/** The capture code that sent a call, and the surfaces it is set up to capture. */
|
|
104
|
+
export interface Component {
|
|
105
|
+
readonly name: string;
|
|
106
|
+
readonly version: string;
|
|
107
|
+
readonly surfaces: readonly Surface[];
|
|
108
|
+
/**
|
|
109
|
+
* The id of the workspace hash key it hashes with (`hashKeyIdOf`); absent
|
|
110
|
+
* for a component that hashes nothing. The collector refuses an event
|
|
111
|
+
* carrying a hashed value in a call that names no key.
|
|
112
|
+
*/
|
|
113
|
+
readonly hashKeyId?: string;
|
|
114
|
+
}
|
package/dist/event.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One event as a component sends it to the collector (`POST /ingest/events`):
|
|
3
|
+
* the journey engine's event less `tenant` and `observedAt`, which the
|
|
4
|
+
* collector stamps from the source's workspace and its own clock, and
|
|
5
|
+
* `hashKeyId`, which it stamps from the key the call names.
|
|
6
|
+
*
|
|
7
|
+
* The engine, private to Argus, holds the schema the collector checks; this
|
|
8
|
+
* package holds the same shape as types, so no component imports the
|
|
9
|
+
* engine. The edge's and the browser's tests check every call they send
|
|
10
|
+
* against the contract Argus writes (`packages/contract`).
|
|
11
|
+
*/
|
|
12
|
+
export const SURFACES = [
|
|
13
|
+
'edge',
|
|
14
|
+
'firewall',
|
|
15
|
+
'browser',
|
|
16
|
+
'http',
|
|
17
|
+
'mcp',
|
|
18
|
+
'a2a',
|
|
19
|
+
'genai',
|
|
20
|
+
'auth',
|
|
21
|
+
'payment',
|
|
22
|
+
'custom',
|
|
23
|
+
];
|
package/dist/hash.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The keyed hash a component applies before anything leaves the customer: a
|
|
3
|
+
* client address, a verified principal's id. HMAC-SHA256 with the
|
|
4
|
+
* workspace's hash key, cut to 32 hex characters, so every component of one
|
|
5
|
+
* workspace hashes one value alike and the engine can only ever compare two
|
|
6
|
+
* for equality (docs/research/agent-journey-correlation.md, 12.12).
|
|
7
|
+
*/
|
|
8
|
+
export declare function keyedHash(hashKey: string, value: string): Promise<string>;
|
|
9
|
+
/**
|
|
10
|
+
* The id a component's calls name its hash key by: the first 16 hex
|
|
11
|
+
* characters of the key's SHA-256. The collector stamps it on each event
|
|
12
|
+
* carrying a hashed value, and the linker compares hashed values only
|
|
13
|
+
* between events hashed with one key, so a workspace can replace its key.
|
|
14
|
+
* Argus works out the same id from the key it holds, so a key needs no id
|
|
15
|
+
* of its own; 64 bits of its hash say nothing of the key.
|
|
16
|
+
*/
|
|
17
|
+
export declare function hashKeyIdOf(hashKey: string): Promise<string>;
|
package/dist/hash.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The keyed hash a component applies before anything leaves the customer: a
|
|
3
|
+
* client address, a verified principal's id. HMAC-SHA256 with the
|
|
4
|
+
* workspace's hash key, cut to 32 hex characters, so every component of one
|
|
5
|
+
* workspace hashes one value alike and the engine can only ever compare two
|
|
6
|
+
* for equality (docs/research/agent-journey-correlation.md, 12.12).
|
|
7
|
+
*/
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
/** HMAC keys imported once per hash key, for the life of the runtime. */
|
|
10
|
+
const keys = new Map();
|
|
11
|
+
function keyOf(hashKey) {
|
|
12
|
+
const known = keys.get(hashKey);
|
|
13
|
+
if (known !== undefined)
|
|
14
|
+
return known;
|
|
15
|
+
const imported = crypto.subtle.importKey('raw', encoder.encode(hashKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
16
|
+
keys.set(hashKey, imported);
|
|
17
|
+
return imported;
|
|
18
|
+
}
|
|
19
|
+
/** The first `bytes` bytes of a digest, as lowercase hex. */
|
|
20
|
+
function hexOf(digest, bytes) {
|
|
21
|
+
return [...new Uint8Array(digest)]
|
|
22
|
+
.slice(0, bytes)
|
|
23
|
+
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
24
|
+
.join('');
|
|
25
|
+
}
|
|
26
|
+
export async function keyedHash(hashKey, value) {
|
|
27
|
+
const signature = await crypto.subtle.sign('HMAC', await keyOf(hashKey), encoder.encode(value));
|
|
28
|
+
return hexOf(signature, 16);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The id a component's calls name its hash key by: the first 16 hex
|
|
32
|
+
* characters of the key's SHA-256. The collector stamps it on each event
|
|
33
|
+
* carrying a hashed value, and the linker compares hashed values only
|
|
34
|
+
* between events hashed with one key, so a workspace can replace its key.
|
|
35
|
+
* Argus works out the same id from the key it holds, so a key needs no id
|
|
36
|
+
* of its own; 64 bits of its hash say nothing of the key.
|
|
37
|
+
*/
|
|
38
|
+
export async function hashKeyIdOf(hashKey) {
|
|
39
|
+
return hexOf(await crypto.subtle.digest('SHA-256', encoder.encode(hashKey)), 8);
|
|
40
|
+
}
|
package/dist/id.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ids for what a component mints (an event, a tab, a batch of frames): a
|
|
3
|
+
* random UUID, version 4, from `crypto.getRandomValues`. `crypto.randomUUID`
|
|
4
|
+
* mints the same, but a page has it only over HTTPS: on a site served over
|
|
5
|
+
* plain HTTP, the browser script would record nothing.
|
|
6
|
+
*/
|
|
7
|
+
/** Bytes as lowercase hex, two characters each. */
|
|
8
|
+
export declare function hexOf(bytes: Uint8Array): string;
|
|
9
|
+
/** A random UUID, version 4. */
|
|
10
|
+
export declare function newId(): string;
|
package/dist/id.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ids for what a component mints (an event, a tab, a batch of frames): a
|
|
3
|
+
* random UUID, version 4, from `crypto.getRandomValues`. `crypto.randomUUID`
|
|
4
|
+
* mints the same, but a page has it only over HTTPS: on a site served over
|
|
5
|
+
* plain HTTP, the browser script would record nothing.
|
|
6
|
+
*/
|
|
7
|
+
/** Bytes as lowercase hex, two characters each. */
|
|
8
|
+
export function hexOf(bytes) {
|
|
9
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
10
|
+
}
|
|
11
|
+
/** A random UUID, version 4. */
|
|
12
|
+
export function newId() {
|
|
13
|
+
const hex = hexOf(crypto.getRandomValues(new Uint8Array(16)));
|
|
14
|
+
// The version is 4; the variant's two bits are 10, the two after random.
|
|
15
|
+
const variant = (8 | (Number.parseInt(hex.charAt(16), 16) & 3)).toString(16);
|
|
16
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
17
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every Agentrail component shares, in any runtime with the Fetch API
|
|
3
|
+
* and WebCrypto: the event the collector takes, markers, the keyed hash,
|
|
4
|
+
* trace context, the session, and the client that sends events. Nothing
|
|
5
|
+
* here imports Node, the DOM or OpenTelemetry.
|
|
6
|
+
*/
|
|
7
|
+
export { SURFACES, type AgentrailEvent, type ClockSource, type Component, type PrincipalKind, type RegistrationPhase, type SpanContext, type SpanKind, type Surface, } from './event.js';
|
|
8
|
+
export { MAX_LINK_INDEX, MarkerError, linkMarker, mintMarker, newMarker, parseMarker, type ParsedMarker, } from './marker.js';
|
|
9
|
+
export { SessionTimeoutError, newSessionId, sessionCookie, sessionStartOf, type SessionCookie, type SessionCookieOptions, } from './session.js';
|
|
10
|
+
export { hashKeyIdOf, keyedHash } from './hash.js';
|
|
11
|
+
export { newId } from './id.js';
|
|
12
|
+
export { VERSION } from './version.js';
|
|
13
|
+
export { formatTraceparent, newSpanId, newTraceId, parseTraceparent, } from './trace.js';
|
|
14
|
+
export { CollectorFailedError, CollectorRefusedError, CollectorUnavailableError, createCollector, type Collector, type CollectorOptions, } from './collector.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every Agentrail component shares, in any runtime with the Fetch API
|
|
3
|
+
* and WebCrypto: the event the collector takes, markers, the keyed hash,
|
|
4
|
+
* trace context, the session, and the client that sends events. Nothing
|
|
5
|
+
* here imports Node, the DOM or OpenTelemetry.
|
|
6
|
+
*/
|
|
7
|
+
export { SURFACES, } from './event.js';
|
|
8
|
+
export { MAX_LINK_INDEX, MarkerError, linkMarker, mintMarker, newMarker, parseMarker, } from './marker.js';
|
|
9
|
+
export { SessionTimeoutError, newSessionId, sessionCookie, sessionStartOf, } from './session.js';
|
|
10
|
+
export { hashKeyIdOf, keyedHash } from './hash.js';
|
|
11
|
+
export { newId } from './id.js';
|
|
12
|
+
export { VERSION } from './version.js';
|
|
13
|
+
export { formatTraceparent, newSpanId, newTraceId, parseTraceparent, } from './trace.js';
|
|
14
|
+
export { CollectorFailedError, CollectorRefusedError, CollectorUnavailableError, createCollector, } from './collector.js';
|
package/dist/marker.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Planted markers: 64 random bits in Crockford base32 (13 characters) and a
|
|
3
|
+
* Luhn mod 32 check character; a link's marker adds a two-character lane
|
|
4
|
+
* before the check, so each link of a response is proven on its own. The
|
|
5
|
+
* engine reads them back case-folded, with Crockford's look-alikes, and
|
|
6
|
+
* refuses any whose check fails (docs/research/agent-journey-correlation.md,
|
|
7
|
+
* 5.2 and 15.1). This is the same arithmetic and the same reading as the
|
|
8
|
+
* engine's; `test/parity.test.ts` proves the two agree.
|
|
9
|
+
*/
|
|
10
|
+
/** The last lane a response's links can take; past it a link goes unmarked. */
|
|
11
|
+
export declare const MAX_LINK_INDEX: number;
|
|
12
|
+
/** A marker that is not one this package minted, or a lane out of range. */
|
|
13
|
+
export declare class MarkerError extends Error {
|
|
14
|
+
readonly name = "MarkerError";
|
|
15
|
+
}
|
|
16
|
+
/** A response marker from eight random bytes. */
|
|
17
|
+
export declare function mintMarker(random: Uint8Array): string;
|
|
18
|
+
/** A response marker from this runtime's strong random source. */
|
|
19
|
+
export declare function newMarker(): string;
|
|
20
|
+
/** How the engine reads a value: a marker, or why it is none. */
|
|
21
|
+
export type ParsedMarker = {
|
|
22
|
+
readonly valid: true;
|
|
23
|
+
/** The response marker, canonical, without its check character. */
|
|
24
|
+
readonly base: string;
|
|
25
|
+
/** The lane of a link's marker; null for a response's own. */
|
|
26
|
+
readonly link: number | null;
|
|
27
|
+
} | {
|
|
28
|
+
readonly valid: false;
|
|
29
|
+
readonly reason: 'length' | 'alphabet' | 'check';
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Reads a value as an agent sent it back, as the engine does: case-folded,
|
|
33
|
+
* `-` dropped, I and L read as 1 and O as 0; then 14 or 16 characters of the
|
|
34
|
+
* alphabet whose check character holds. Only a value it reads as valid is a
|
|
35
|
+
* marker: anything else, an image's `h=600` or a path's `/h/getting-started`,
|
|
36
|
+
* is the site's own.
|
|
37
|
+
*/
|
|
38
|
+
export declare function parseMarker(raw: string): ParsedMarker;
|
|
39
|
+
/** The marker for one link of a response: its lane. */
|
|
40
|
+
export declare function linkMarker(marker: string, index: number): string;
|
package/dist/marker.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Planted markers: 64 random bits in Crockford base32 (13 characters) and a
|
|
3
|
+
* Luhn mod 32 check character; a link's marker adds a two-character lane
|
|
4
|
+
* before the check, so each link of a response is proven on its own. The
|
|
5
|
+
* engine reads them back case-folded, with Crockford's look-alikes, and
|
|
6
|
+
* refuses any whose check fails (docs/research/agent-journey-correlation.md,
|
|
7
|
+
* 5.2 and 15.1). This is the same arithmetic and the same reading as the
|
|
8
|
+
* engine's; `test/parity.test.ts` proves the two agree.
|
|
9
|
+
*/
|
|
10
|
+
const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
11
|
+
const BASE = ALPHABET.length;
|
|
12
|
+
const PAYLOAD_LENGTH = 13;
|
|
13
|
+
const LANE_LENGTH = 2;
|
|
14
|
+
const RANDOM_BYTES = 8;
|
|
15
|
+
/** The last lane a response's links can take; past it a link goes unmarked. */
|
|
16
|
+
export const MAX_LINK_INDEX = BASE * BASE - 1;
|
|
17
|
+
/** A marker that is not one this package minted, or a lane out of range. */
|
|
18
|
+
export class MarkerError extends Error {
|
|
19
|
+
name = 'MarkerError';
|
|
20
|
+
}
|
|
21
|
+
function valueOf(character) {
|
|
22
|
+
const value = ALPHABET.indexOf(character);
|
|
23
|
+
if (value === -1)
|
|
24
|
+
throw new MarkerError(`Not in the marker alphabet: ${character}.`);
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
function checkValue(values) {
|
|
28
|
+
let sum = 0;
|
|
29
|
+
let factor = 2;
|
|
30
|
+
// From the last character back, doubling every other one.
|
|
31
|
+
for (const value of [...values].reverse()) {
|
|
32
|
+
const addend = factor * value;
|
|
33
|
+
sum += Math.floor(addend / BASE) + (addend % BASE);
|
|
34
|
+
factor = factor === 2 ? 1 : 2;
|
|
35
|
+
}
|
|
36
|
+
return (BASE - (sum % BASE)) % BASE;
|
|
37
|
+
}
|
|
38
|
+
function withCheck(values) {
|
|
39
|
+
return [...values, checkValue(values)]
|
|
40
|
+
.map((value) => ALPHABET.charAt(value))
|
|
41
|
+
.join('');
|
|
42
|
+
}
|
|
43
|
+
/** A response marker from eight random bytes. */
|
|
44
|
+
export function mintMarker(random) {
|
|
45
|
+
if (random.length !== RANDOM_BYTES)
|
|
46
|
+
throw new MarkerError(`A marker needs ${String(RANDOM_BYTES)} random bytes, not ${String(random.length)}.`);
|
|
47
|
+
let bits = 0n;
|
|
48
|
+
for (const byte of random)
|
|
49
|
+
bits = (bits << 8n) | BigInt(byte);
|
|
50
|
+
const values = [];
|
|
51
|
+
for (let index = PAYLOAD_LENGTH - 1; index >= 0; index -= 1)
|
|
52
|
+
values.push(Number((bits >> BigInt(index * 5)) & 31n));
|
|
53
|
+
return withCheck(values);
|
|
54
|
+
}
|
|
55
|
+
/** A response marker from this runtime's strong random source. */
|
|
56
|
+
export function newMarker() {
|
|
57
|
+
return mintMarker(crypto.getRandomValues(new Uint8Array(RANDOM_BYTES)));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Reads a value as an agent sent it back, as the engine does: case-folded,
|
|
61
|
+
* `-` dropped, I and L read as 1 and O as 0; then 14 or 16 characters of the
|
|
62
|
+
* alphabet whose check character holds. Only a value it reads as valid is a
|
|
63
|
+
* marker: anything else, an image's `h=600` or a path's `/h/getting-started`,
|
|
64
|
+
* is the site's own.
|
|
65
|
+
*/
|
|
66
|
+
export function parseMarker(raw) {
|
|
67
|
+
const text = raw
|
|
68
|
+
.toUpperCase()
|
|
69
|
+
.replaceAll('-', '')
|
|
70
|
+
.replaceAll('I', '1')
|
|
71
|
+
.replaceAll('L', '1')
|
|
72
|
+
.replaceAll('O', '0');
|
|
73
|
+
if (text.length !== PAYLOAD_LENGTH + 1 &&
|
|
74
|
+
text.length !== PAYLOAD_LENGTH + LANE_LENGTH + 1)
|
|
75
|
+
return { valid: false, reason: 'length' };
|
|
76
|
+
const values = [];
|
|
77
|
+
for (const character of text) {
|
|
78
|
+
const value = ALPHABET.indexOf(character);
|
|
79
|
+
if (value === -1)
|
|
80
|
+
return { valid: false, reason: 'alphabet' };
|
|
81
|
+
values.push(value);
|
|
82
|
+
}
|
|
83
|
+
const check = values.pop();
|
|
84
|
+
if (check !== checkValue(values))
|
|
85
|
+
return { valid: false, reason: 'check' };
|
|
86
|
+
const [high, low] = values.slice(PAYLOAD_LENGTH);
|
|
87
|
+
return {
|
|
88
|
+
valid: true,
|
|
89
|
+
base: text.slice(0, PAYLOAD_LENGTH),
|
|
90
|
+
link: high === undefined || low === undefined ? null : high * BASE + low,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** The marker for one link of a response: its lane. */
|
|
94
|
+
export function linkMarker(marker, index) {
|
|
95
|
+
if (marker.length !== PAYLOAD_LENGTH + 1)
|
|
96
|
+
throw new MarkerError(`Not a response marker: ${marker}.`);
|
|
97
|
+
if (!Number.isInteger(index) || index < 0 || index > MAX_LINK_INDEX)
|
|
98
|
+
throw new MarkerError(`A lane is 0 to ${String(MAX_LINK_INDEX)}, not ${String(index)}.`);
|
|
99
|
+
const values = Array.from(marker.slice(0, PAYLOAD_LENGTH), valueOf);
|
|
100
|
+
values.push(Math.floor(index / BASE), index % BASE);
|
|
101
|
+
return withCheck(values);
|
|
102
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** An idle timeout a cookie cannot carry. */
|
|
2
|
+
export declare class SessionTimeoutError extends Error {
|
|
3
|
+
readonly name = "SessionTimeoutError";
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* A session id minted at `now`, milliseconds since the epoch, from this
|
|
7
|
+
* runtime's strong random source. It needs no secure context, as
|
|
8
|
+
* `crypto.randomUUID` does.
|
|
9
|
+
*/
|
|
10
|
+
export declare function newSessionId(now: number): string;
|
|
11
|
+
/** When a session was minted, from its id; null for an id `newSessionId` could not have minted. */
|
|
12
|
+
export declare function sessionStartOf(id: string): number | null;
|
|
13
|
+
export interface SessionCookieOptions {
|
|
14
|
+
readonly name: string;
|
|
15
|
+
/** Seconds without a request after which the session ends; 30 minutes by default. */
|
|
16
|
+
readonly idleTimeout?: number | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* The domain the session is shared across, as `example.com` for
|
|
19
|
+
* `docs.example.com` and `app.example.com`; the one host that set it
|
|
20
|
+
* when absent.
|
|
21
|
+
*/
|
|
22
|
+
readonly domain?: string | undefined;
|
|
23
|
+
}
|
|
24
|
+
export interface SessionCookie {
|
|
25
|
+
/**
|
|
26
|
+
* The session a `Cookie` header or `document.cookie` holds, when it is one
|
|
27
|
+
* to go on with at `now`: minted as `newSessionId` mints, less than 24
|
|
28
|
+
* hours before. One minted after `now` is kept: a page's clock may run
|
|
29
|
+
* ahead of the edge's, and a page mints too.
|
|
30
|
+
*/
|
|
31
|
+
read(cookies: string, now: number): string | null;
|
|
32
|
+
/**
|
|
33
|
+
* The `Set-Cookie` value, or the `document.cookie` write, that keeps
|
|
34
|
+
* `session` for another idle timeout. Never `HttpOnly`: the browser script
|
|
35
|
+
* reads it.
|
|
36
|
+
*/
|
|
37
|
+
write(session: string, secure: boolean): string;
|
|
38
|
+
}
|
|
39
|
+
/** The session cookie a component reads and writes. */
|
|
40
|
+
export declare function sessionCookie(options: SessionCookieOptions): SessionCookie;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { hexOf } from './id.js';
|
|
2
|
+
/**
|
|
3
|
+
* A visitor's session, kept as web analytics and PostHog keep one: it ends
|
|
4
|
+
* after 30 minutes without a request, and lasts 24 hours at most. The edge
|
|
5
|
+
* and the browser script share it in one cookie, which each writes again
|
|
6
|
+
* with the idle timeout as its `Max-Age` on every answer or page view, so the
|
|
7
|
+
* browser drops it once the visitor has been idle that long. The id is a
|
|
8
|
+
* UUIDv7, which carries the time it was minted, so either tells a session's
|
|
9
|
+
* age from its id and keeps nothing else.
|
|
10
|
+
*/
|
|
11
|
+
/** Seconds without a request after which a session ends, unless a site sets its own. */
|
|
12
|
+
const SESSION_IDLE_TIMEOUT = 30 * 60;
|
|
13
|
+
/** How long a session lasts at most, idle or not, in milliseconds. */
|
|
14
|
+
const SESSION_MAX_LENGTH = 24 * 60 * 60 * 1000;
|
|
15
|
+
/** A UUIDv7: a 48-bit time in milliseconds, the version, the variant, the rest random. */
|
|
16
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
17
|
+
/** An idle timeout a cookie cannot carry. */
|
|
18
|
+
export class SessionTimeoutError extends Error {
|
|
19
|
+
name = 'SessionTimeoutError';
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A session id minted at `now`, milliseconds since the epoch, from this
|
|
23
|
+
* runtime's strong random source. It needs no secure context, as
|
|
24
|
+
* `crypto.randomUUID` does.
|
|
25
|
+
*/
|
|
26
|
+
export function newSessionId(now) {
|
|
27
|
+
const time = Math.floor(now).toString(16).padStart(12, '0');
|
|
28
|
+
const random = hexOf(crypto.getRandomValues(new Uint8Array(10)));
|
|
29
|
+
// The variant's two bits are 10; the two after them are random.
|
|
30
|
+
const variant = (8 | (Number.parseInt(random.charAt(3), 16) & 3)).toString(16);
|
|
31
|
+
return `${time.slice(0, 8)}-${time.slice(8)}-7${random.slice(0, 3)}-${variant}${random.slice(4, 7)}-${random.slice(7, 19)}`;
|
|
32
|
+
}
|
|
33
|
+
/** When a session was minted, from its id; null for an id `newSessionId` could not have minted. */
|
|
34
|
+
export function sessionStartOf(id) {
|
|
35
|
+
if (!SESSION_ID.test(id))
|
|
36
|
+
return null;
|
|
37
|
+
return Number.parseInt(id.slice(0, 8) + id.slice(9, 13), 16);
|
|
38
|
+
}
|
|
39
|
+
/** The session cookie a component reads and writes. */
|
|
40
|
+
export function sessionCookie(options) {
|
|
41
|
+
const { name, idleTimeout = SESSION_IDLE_TIMEOUT, domain } = options;
|
|
42
|
+
if (!Number.isSafeInteger(idleTimeout) || idleTimeout < 1)
|
|
43
|
+
throw new SessionTimeoutError(`A session's idle timeout is a whole number of seconds, at least 1, not ${String(idleTimeout)}.`);
|
|
44
|
+
return {
|
|
45
|
+
read(cookies, now) {
|
|
46
|
+
for (const part of cookies.split(';')) {
|
|
47
|
+
const [key, ...value] = part.trim().split('=');
|
|
48
|
+
if (key !== name)
|
|
49
|
+
continue;
|
|
50
|
+
const session = value.join('=');
|
|
51
|
+
const start = sessionStartOf(session);
|
|
52
|
+
return start !== null && now - start < SESSION_MAX_LENGTH
|
|
53
|
+
? session
|
|
54
|
+
: null;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
},
|
|
58
|
+
write(session, secure) {
|
|
59
|
+
return [
|
|
60
|
+
`${name}=${session}`,
|
|
61
|
+
'Path=/',
|
|
62
|
+
`Max-Age=${String(idleTimeout)}`,
|
|
63
|
+
...(domain === undefined ? [] : [`Domain=${domain}`]),
|
|
64
|
+
'SameSite=Lax',
|
|
65
|
+
...(secure ? ['Secure'] : []),
|
|
66
|
+
].join('; ');
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
package/dist/trace.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SpanContext } from './event.js';
|
|
2
|
+
export declare function newTraceId(): string;
|
|
3
|
+
export declare function newSpanId(): string;
|
|
4
|
+
/** The context a `traceparent` header names, or null when it names none validly. */
|
|
5
|
+
export declare function parseTraceparent(header: string | null): SpanContext | null;
|
|
6
|
+
/** A sampled `traceparent` naming this span as the parent. */
|
|
7
|
+
export declare function formatTraceparent(context: SpanContext): string;
|
package/dist/trace.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W3C trace context (`traceparent`), which every component speaks with
|
|
3
|
+
* OpenTelemetry's field names, without the OpenTelemetry SDK.
|
|
4
|
+
*/
|
|
5
|
+
const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/u;
|
|
6
|
+
const INVALID_TRACE = '0'.repeat(32);
|
|
7
|
+
const INVALID_SPAN = '0'.repeat(16);
|
|
8
|
+
function hex(bytes) {
|
|
9
|
+
return [...crypto.getRandomValues(new Uint8Array(bytes))]
|
|
10
|
+
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
11
|
+
.join('');
|
|
12
|
+
}
|
|
13
|
+
export function newTraceId() {
|
|
14
|
+
return hex(16);
|
|
15
|
+
}
|
|
16
|
+
export function newSpanId() {
|
|
17
|
+
return hex(8);
|
|
18
|
+
}
|
|
19
|
+
/** The context a `traceparent` header names, or null when it names none validly. */
|
|
20
|
+
export function parseTraceparent(header) {
|
|
21
|
+
const match = header === null ? null : TRACEPARENT.exec(header.trim());
|
|
22
|
+
const traceId = match?.[1];
|
|
23
|
+
const spanId = match?.[2];
|
|
24
|
+
if (traceId === undefined || spanId === undefined)
|
|
25
|
+
return null;
|
|
26
|
+
if (traceId === INVALID_TRACE || spanId === INVALID_SPAN)
|
|
27
|
+
return null;
|
|
28
|
+
return { traceId, spanId };
|
|
29
|
+
}
|
|
30
|
+
/** A sampled `traceparent` naming this span as the parent. */
|
|
31
|
+
export function formatTraceparent(context) {
|
|
32
|
+
return `00-${context.traceId}-${context.spanId}-01`;
|
|
33
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The version of every Agentrail package in this repository. They are
|
|
3
|
+
* released together, at one version, and each component reports it as its
|
|
4
|
+
* own in every call. `test/version.test.ts` holds it to every package's
|
|
5
|
+
* manifest.
|
|
6
|
+
*/
|
|
7
|
+
export declare const VERSION = "0.1.0";
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The version of every Agentrail package in this repository. They are
|
|
3
|
+
* released together, at one version, and each component reports it as its
|
|
4
|
+
* own in every call. `test/version.test.ts` holds it to every package's
|
|
5
|
+
* manifest.
|
|
6
|
+
*/
|
|
7
|
+
export const VERSION = '0.1.0';
|
package/package.json
CHANGED
|
@@ -1,11 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentrail-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "What every Agentrail component shares: the event the collector takes, markers, the keyed hash, W3C trace context, and the client that sends events.",
|
|
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/core"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/agentrail-co/agentrail-js/tree/main/packages/core#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
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "24.13.3",
|
|
29
|
+
"agentrail-contract": "0.0.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.build.json",
|
|
33
|
+
"typecheck": "tsc --noEmit",
|
|
34
|
+
"test": "vitest run"
|
|
10
35
|
}
|
|
11
|
-
}
|
|
36
|
+
}
|