agentrail-node 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,155 @@
1
- # Temporary Holding Version
1
+ # agentrail-node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node 22+ backend evidence for Agentrail: HTTP and fetch traces, application-verified identity, explicit journey milestones and structured logs. Uses OpenTelemetry's HTTP/protobuf exporters. The receiver must support `/ingest/otlp/v1/traces` and `/ingest/otlp/v1/logs` before installing this package.
4
+
5
+ ## Standalone startup
6
+
7
+ ```ts
8
+ // instrumentation.ts — load before application HTTP modules
9
+ import { init } from 'agentrail-node';
10
+
11
+ export const agentrail = await init({
12
+ collector: {
13
+ endpoint: 'https://api.example.com/ingest/otlp',
14
+ secret: process.env.AGENTRAIL_SOURCE_SECRET!, // a Node source
15
+ },
16
+ hashKey: process.env.AGENTRAIL_HASH_KEY!,
17
+ serviceName: 'orders-api',
18
+ outboundOrigins: ['https://inventory.internal'],
19
+ onError(error) {
20
+ console.error(error);
21
+ },
22
+ });
23
+ ```
24
+
25
+ The application validates its environment before initialization. Source credentials and the workspace hash key stay on the server. Never put them in a page. Start with `node --import ./instrumentation.js app.js`. `init` installs one tracer provider, logger provider, async context manager and HTTP/fetch instrumentation. Calling it again with the same options object returns the same client. It refuses an existing provider/context/propagator; use construction-time integration below. Shutdown is terminal for this installation.
26
+
27
+ A valid edge handoff continues its trace. Direct public calls and refused handoffs start fresh traces; a caller's trace is a directional link only. The HMAC binds method, exact forwarded path/query, parent, workspace key ID and a 60-second issue time. Keep clocks synchronized. Configure edge path/query rewrites with its `prepareOriginRequest` hook before signing. Arbitrary baggage and trace state do not leave managed requests. Only exact `outboundOrigins` receive signed context; the actual network destination determines admission, rather than an overridden Host header. Configure the same workspace key at each participating service. Exporter requests and this collector's incoming ingestion traffic are excluded.
28
+
29
+ ## Verified context and milestones
30
+
31
+ ```ts
32
+ // After authenticating the application request:
33
+ agentrail.identify({
34
+ kind: 'agent_registration',
35
+ id: authenticatedAgent.id,
36
+ actingUserId: authenticatedAgent.userId,
37
+ });
38
+
39
+ const result = await agentrail.milestone(
40
+ 'checkout.confirm',
41
+ { surface: 'custom', kind: 'checkout.confirm' },
42
+ async () => confirmOrder(),
43
+ );
44
+ ```
45
+
46
+ `identify` uses the active managed request, hashes IDs before export and never promotes generic OTel `user.id` or caller-declared attributes into verified identity. Outside a managed request it reports a capture error. Repeated identical assertions do nothing. A different assertion creates a distinct auth milestone while preserving the first principal. Concurrent requests have independent identity state. `milestone(name, context)` records an instant step; its callback overload scopes child spans, preserves the callback's result and rethrows its original error. Milestone names and kinds are bounded to 256 characters and should be stable operation names, without arguments or identifiers.
47
+
48
+ ## Your own servers
49
+
50
+ Calls your own services make to this one are not visitors or agents. Leave
51
+ them out with `ignoreIncomingRequest`, and check something only your servers
52
+ can send, such as a shared secret: a user agent or an address is what any
53
+ caller can claim.
54
+
55
+ ```ts
56
+ const internalSecret = process.env.INTERNAL_SECRET;
57
+ if (!internalSecret) throw new Error('INTERNAL_SECRET is not set');
58
+
59
+ init({
60
+ // ...
61
+ ignoreIncomingRequest: (request) =>
62
+ request.headers['x-my-internal'] === internalSecret,
63
+ });
64
+ ```
65
+
66
+ Check the secret is set before `init`. Unset, a request with no such header would match it, and every ordinary request would go unrecorded.
67
+
68
+ ## Structured logs
69
+
70
+ ```ts
71
+ import pinoLogger from 'pino';
72
+ import { pino } from 'agentrail-node/pino';
73
+ const logger = pinoLogger({ hooks: pino(agentrail) });
74
+ logger.error({ err: new TypeError('private detail') }, 'private detail');
75
+
76
+ agentrail.log({
77
+ severityNumber: 17,
78
+ errorType: 'PaymentDeclined',
79
+ eventName: 'checkout.failed',
80
+ });
81
+ ```
82
+
83
+ The optional Pino 9/10 hook captures synchronously in the caller's async context and composes an existing hook as its second argument. The original logger output is unchanged. The standard OTel log processor is also available. Default exports contain severity, error type, event name, a stable per-record ID and exact span correlation. Arguments, results, headers, arbitrary attributes, exception messages and message bodies are excluded. Generic logs never create journey proof. Set `logs.uncorrelated: false` to exclude logs outside managed requests.
84
+
85
+ Message text requires an explicit field allowlist, for example `logs: { includeFields: ['msg'] }` for Pino or `['message']` for a standard OTel body. `client.log` selects from `fields`. Only selected top-level scalar fields are serialized, with a 4096-character body limit. Fields are considered in allowlist order. String values are shortened before serialization, including JSON escaping and complete Unicode code points; fields whose keys or scalar values cannot fit are omitted, so the exported object stays valid JSON. Do not select credentials, raw identities or sensitive customer content. Span names for supporting operations are neutralized, exception events and status messages are dropped, URLs retain only valid `h` markers; a sanitized URL over 4096 characters is omitted while the entry and its trace evidence are retained, and resource exports contain service/component/hash-key metadata. Service names/instance IDs, routes, operation names, user agents and explicitly selected fields are customer-controlled context: choose non-sensitive values.
86
+
87
+ ## Existing OpenTelemetry provider
88
+
89
+ Create the processors **before** constructing the customer's provider. A running provider cannot recover spans its sampler already dropped.
90
+
91
+ ```ts
92
+ import { createProcessors } from 'agentrail-node';
93
+ import {
94
+ TracerProvider,
95
+ ParentBasedSampler,
96
+ TraceIdRatioBasedSampler,
97
+ } from '@opentelemetry/sdk-trace';
98
+ import { LoggerProvider } from '@opentelemetry/sdk-logs';
99
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
100
+ import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
101
+
102
+ const capture = createProcessors({
103
+ ...options,
104
+ propagator: customerPropagator,
105
+ });
106
+ const provider = new TracerProvider({
107
+ sampler: capture.sampler(
108
+ new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(0.1) }),
109
+ ),
110
+ spanProcessors: [customerProcessor, capture.spanProcessor],
111
+ });
112
+ const logProvider = new LoggerProvider({
113
+ processors: [customerLogProcessor, capture.logProcessor],
114
+ });
115
+ // In the existing startup, register provider/logProvider, its async context manager,
116
+ // capture.propagator and these request-aware hooks once:
117
+ const http = new HttpInstrumentation(capture.httpOptions);
118
+ const fetch = new UndiciInstrumentation(capture.undiciOptions);
119
+ http.setTracerProvider(provider);
120
+ fetch.setTracerProvider(provider);
121
+ ```
122
+
123
+ Pass the existing `TextMapPropagator` as `options.propagator`, then register the **returned** `capture.propagator` once. It delegates extraction/injection for unmanaged work and prevents a late customer injection from re-adding headers to managed fetches. Keeping the original propagator globally bypasses this boundary: Undici injects after its request hook. For multiple installations, chain the earlier installation's returned propagator as the next one's base. Request-aware hooks still bind the actual destination/method/target before signing.
124
+
125
+ Retain other customer instrumentation; install only one HTTP and one Undici instrumentation, passing these options to them. Keep the request-aware propagator and HTTP hooks together: extraction alone cannot verify method and path. The factory registers no globals and never changes another exporter's input. The sampler promotes dropped managed spans to **record-only**, preserving the customer's sampled flag. Standard sampled-only exporters retain their sampling; custom exporters that export record-only spans may see additional records. Without this sampler wrapper, dropped entries report `entry_not_recording`, and their ancestry is unavailable. Ordinary spans outside managed requests are not captured by the Agentrail span processor.
126
+
127
+ For Sentry, compose this sampler around `SentrySampler` while constructing the single customer-owned provider, retaining `SentrySpanProcessor` and its context manager, with `new SentryPropagator()` passed as the base and the returned capture propagator registered globally. A 100% Sentry sample rate still drops HEAD/OPTIONS; merely adding a processor cannot retain those spans. Agentrail's packed installation gate exercises this public composition. In framework admission mode, use the supplied request-aware incoming hook/propagator in the admitted scope and disable automatic incoming instrumentation, so there is one backend entry per request. Handler work after admission is captured; earlier authentication/body parsing is outside that scope.
128
+
129
+ Pinned compatible OTel family: API 1.9.1, core/trace/resources/context 2.10.0, logs/exporters/HTTP instrumentation 0.221.0, Undici instrumentation 0.31.0. This release supports those APIs; check dependency compatibility when composing a distribution.
130
+
131
+ ## Delivery and shutdown
132
+
133
+ Defaults per signal: 2048 records including the in-flight batch, batches of 128, a 1000 ms schedule, 5000 ms export timeout, and 10000 ms flush/shutdown deadlines. Override with `queue`. Positive integer limits are required, batch size cannot exceed capacity and flush/shutdown deadlines cannot be shorter than the export timeout. One batch is in flight per signal. The official exporter retries retryable OTLP responses within its export deadline; permanent rejections and exhausted retries are reported and dropped. This is a bounded memory queue, without disk persistence.
134
+
135
+ `await agentrail.flush()` drains capture within the configured bound. `await agentrail.shutdown()` stops instrumentation and drains once; call it during application shutdown. `diagnostics()` reports accepted, exported, dropped and pending records per signal. Overflow, export failure, deadline loss, refused handoff and missing capture context go to `onError` (console by default). SDK error reporting runs outside capture, including when routed through the same Pino or OTel logger, so diagnostics cannot feed their own full queue. If a synchronous `onError` callback throws, its exception and the original capture error are reported to the console outside capture, and queue cleanup continues. These capture outcomes do not replace an application response. Flush completion means attempts ended; inspect diagnostics/errors for delivery loss.
136
+
137
+ ## MCP callback adapter
138
+
139
+ ```ts
140
+ import { McpServer, type ToolCallback } from '@modelcontextprotocol/server';
141
+ import { mcp } from 'agentrail-node/mcp';
142
+ const server = new McpServer({ name: 'orders', version: '1' });
143
+ const capture = mcp({ client: agentrail });
144
+ const checkout: ToolCallback = async (ctx) => {
145
+ // Authentication happens in the application's HTTP/auth boundary.
146
+ return { content: [{ type: 'text', text: 'done' }] };
147
+ };
148
+ server.registerTool('checkout', {}, capture.tool('checkout', checkout));
149
+ // capture.resource(registeredName, handler) and capture.prompt(registeredName, handler)
150
+ // wrap their respective public registration callbacks too.
151
+ ```
152
+
153
+ The optional adapter targets `@modelcontextprotocol/server` 2.3.1 and public registration callbacks, without modifying private handlers or transports. Use a callback typed with the SDK's schema, for example `ToolCallback<typeof inputSchema>`, for typed tool arguments. With HTTP capture installed, each execution becomes a nested MCP step with a distinct span, exact log correlation and inherited application-verified identity. Outside an HTTP request, it starts its own managed operation. It captures the registered operation name, method, client name/version, protocol and error outcome; arguments, result text, resource URIs and prompt content stay off. Pass a stable registered resource name rather than the caller's URI.
154
+
155
+ MCP 2026-07-28 metadata comes from the request's public context envelope. Legacy 2025-11-25 HTTP calls retain protocol metadata; a stateless server may have no client name after its discarded initialize request. The adapter keeps no initialize cache across callers. Client info and supplied trace metadata remain untrusted and cannot assert a principal. `isError` results mark the operation as failed while preserving the original result. Thrown application errors retain their original identity. Tests exercise modern tool/resource/prompt requests and the official client's legacy HTTP exchange; other MCP SDK versions/transports have not been verified in this release.
@@ -0,0 +1,17 @@
1
+ import { type MilestoneContext, type VerifiedIdentity } from './options.js';
2
+ import { type StructuredLog } from './privacy.js';
3
+ import type { processors } from './processors.js';
4
+ import type { Runtime } from './runtime.js';
5
+ export interface AgentrailNode {
6
+ identify(identity: VerifiedIdentity): void;
7
+ milestone(name: string, details: MilestoneContext): void;
8
+ milestone<T>(name: string, details: MilestoneContext, run: () => T | Promise<T>): Promise<T>;
9
+ log(input: StructuredLog): void;
10
+ flush(): Promise<void>;
11
+ shutdown(): Promise<void>;
12
+ diagnostics(): {
13
+ spans: import('./queue.js').QueueStats;
14
+ logs: import('./queue.js').QueueStats;
15
+ };
16
+ }
17
+ export declare function createClient(runtime: Runtime, queues: ReturnType<typeof processors>): AgentrailNode;
package/dist/client.js ADDED
@@ -0,0 +1,95 @@
1
+ import { isCaptureSuppressed } from './suppression.js';
2
+ import { context, ROOT_CONTEXT, trace, SpanStatusCode, } from '@opentelemetry/api';
3
+ import { CaptureError, ConfigurationError, } from './options.js';
4
+ import { makeLog } from './privacy.js';
5
+ export function createClient(runtime, queues) {
6
+ function parent() {
7
+ const active = context.active();
8
+ if (runtime.state(active) !== undefined)
9
+ return active;
10
+ const external = trace.getSpanContext(active);
11
+ return ROOT_CONTEXT.setValue(runtime.stateKey, runtime.newState(false, external === undefined ? [] : [{ context: external }]));
12
+ }
13
+ function start(name, details, identity) {
14
+ if (!name.isWellFormed() ||
15
+ !details.kind.isWellFormed() ||
16
+ name.includes('\u0000') ||
17
+ details.kind.includes('\u0000') ||
18
+ name.length === 0 ||
19
+ name.length > 256 ||
20
+ details.kind.length === 0 ||
21
+ details.kind.length > 256)
22
+ throw new ConfigurationError('Milestone name and kind must contain 1–256 characters.');
23
+ const base = parent();
24
+ const marked = base.setValue(runtime.markKey, {
25
+ ...details,
26
+ name,
27
+ ...(identity === undefined ? {} : { identity }),
28
+ });
29
+ const state = runtime.state(base);
30
+ const span = trace.getTracer('agentrail-node').startSpan(name, {
31
+ links: trace.getSpanContext(base) === undefined ? (state?.links ?? []) : [],
32
+ }, marked);
33
+ if (!span.isRecording() && !isCaptureSuppressed(context.active()))
34
+ runtime.options.report(new CaptureError('entry_not_recording', 'traces', 1));
35
+ return { span, ctx: trace.setSpan(base, span) };
36
+ }
37
+ function milestone(name, details, run) {
38
+ const { span, ctx } = start(name, details);
39
+ if (run === undefined) {
40
+ span.end();
41
+ return;
42
+ }
43
+ return context.with(ctx, async () => {
44
+ try {
45
+ return await run();
46
+ }
47
+ catch (error) {
48
+ span.setStatus({ code: SpanStatusCode.ERROR });
49
+ if (error instanceof Error)
50
+ span.setAttribute('error.type', error.name);
51
+ throw error;
52
+ }
53
+ finally {
54
+ span.end();
55
+ }
56
+ });
57
+ }
58
+ return {
59
+ identify(identity) {
60
+ if (identity.id.length === 0 || identity.actingUserId === '')
61
+ throw new ConfigurationError('Verified identity IDs cannot be empty.');
62
+ const state = runtime.state(context.active());
63
+ if (state === undefined) {
64
+ runtime.options.report(new CaptureError('identity_outside_request', 'context', 1));
65
+ return;
66
+ }
67
+ const hashed = runtime.identity(identity);
68
+ if (state.identity === undefined)
69
+ state.identity = hashed;
70
+ else if (JSON.stringify(state.identity) !== JSON.stringify(hashed)) {
71
+ // Preserve the first assertion; contradictory assertions are explicit evidence.
72
+ const { span } = start('identity.asserted', { surface: 'auth', kind: 'auth.identity' }, hashed);
73
+ span.end();
74
+ }
75
+ },
76
+ milestone,
77
+ log(input) {
78
+ if (isCaptureSuppressed(context.active()))
79
+ return;
80
+ const record = makeLog(input, context.active(), runtime);
81
+ if (record !== undefined)
82
+ queues.logs.add(record);
83
+ },
84
+ async flush() {
85
+ await Promise.all([queues.spans.flush(), queues.logs.flush()]);
86
+ },
87
+ async shutdown() {
88
+ await Promise.all([queues.spans.shutdown(), queues.logs.shutdown()]);
89
+ },
90
+ diagnostics: () => ({
91
+ spans: queues.spans.diagnostics(),
92
+ logs: queues.logs.diagnostics(),
93
+ }),
94
+ };
95
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { TextMapPropagator } from '@opentelemetry/api';
2
+ import type { HttpInstrumentationConfig } from '@opentelemetry/instrumentation-http';
3
+ import type { UndiciInstrumentationConfig, UndiciRequest } from '@opentelemetry/instrumentation-undici';
4
+ import type { Runtime } from './runtime.js';
5
+ export declare function httpCapture(runtime: Runtime): {
6
+ propagator: TextMapPropagator<any>;
7
+ httpOptions: HttpInstrumentationConfig;
8
+ undiciOptions: UndiciInstrumentationConfig<UndiciRequest, import("@opentelemetry/instrumentation-undici").UndiciResponse>;
9
+ rememberPort(span: object, value: unknown): void;
10
+ };
package/dist/http.js ADDED
@@ -0,0 +1,177 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { ClientRequest } from 'node:http';
3
+ import { ROOT_CONTEXT, trace } from '@opentelemetry/api';
4
+ import { encodeTraceHandoff, readTraceHandoff, TRACE_HANDOFF_HEADER, parseTraceparent, } from 'agentrail-core';
5
+ import { isCaptureSuppressed } from './suppression.js';
6
+ import { CaptureError } from './options.js';
7
+ const ownedHeaders = [
8
+ 'traceparent',
9
+ 'sentry-trace',
10
+ 'tracestate',
11
+ 'baggage',
12
+ TRACE_HANDOFF_HEADER,
13
+ ];
14
+ function single(value) {
15
+ return typeof value === 'string' ? value : null;
16
+ }
17
+ export function httpCapture(runtime) {
18
+ const requests = new WeakMap();
19
+ const ports = new WeakMap();
20
+ const collector = new URL(runtime.options.endpoint);
21
+ const base = runtime.options.input.propagator;
22
+ const propagator = {
23
+ // Undici injects AFTER requestHook. Managed propagation is already signed/filtered there.
24
+ inject(ctx, carrier, setter) {
25
+ if (runtime.state(ctx) !== undefined || isCaptureSuppressed(ctx))
26
+ return;
27
+ base?.inject(ctx, carrier, setter);
28
+ },
29
+ extract(ctx, carrier, getter) {
30
+ const incoming = typeof carrier === 'object' && carrier !== null
31
+ ? requests.get(carrier)
32
+ : undefined;
33
+ return incoming ?? base?.extract(ctx, carrier, getter) ?? ROOT_CONTEXT;
34
+ },
35
+ fields: () => [...new Set([...ownedHeaders, ...(base?.fields() ?? [])])],
36
+ };
37
+ function sign(span, method, target, origin) {
38
+ if (!runtime.spans.has(span) || !runtime.options.origins.has(origin))
39
+ return {};
40
+ const sc = span.spanContext();
41
+ const traceparent = `00-${sc.traceId}-${sc.spanId}-${sc.traceFlags.toString(16).padStart(2, '0')}`;
42
+ const encoded = encodeTraceHandoff({
43
+ traceparent,
44
+ hashKeyId: runtime.keyId,
45
+ issuedAt: Date.now(),
46
+ method,
47
+ target,
48
+ });
49
+ return {
50
+ traceparent,
51
+ [TRACE_HANDOFF_HEADER]: encoded.tokenPrefix +
52
+ createHmac('sha256', runtime.options.input.hashKey)
53
+ .update(encoded.bytes)
54
+ .digest('hex'),
55
+ };
56
+ }
57
+ const httpOptions = {
58
+ requireParentforOutgoingSpans: true,
59
+ ignoreIncomingRequestHook: (request) => (request.socket.localPort ===
60
+ Number(collector.port || (collector.protocol === 'https:' ? 443 : 80)) &&
61
+ (request.url ?? '').startsWith(collector.pathname)) ||
62
+ (runtime.options.input.ignoreIncomingRequest?.(request) ?? false),
63
+ ignoreOutgoingRequestHook: (request) => (request.hostname ?? request.host) === collector.hostname &&
64
+ Number(request.port ?? (request.protocol === 'https:' ? 443 : 80)) ===
65
+ Number(collector.port || (collector.protocol === 'https:' ? 443 : 80)) &&
66
+ (request.path ?? '').startsWith(collector.pathname),
67
+ startIncomingSpanHook(request) {
68
+ const header = single(request.headers.traceparent);
69
+ const candidate = readTraceHandoff(single(request.headers[TRACE_HANDOFF_HEADER]), {
70
+ traceparent: header,
71
+ hashKeyId: runtime.keyId,
72
+ method: request.method ?? '',
73
+ target: request.url ?? '',
74
+ now: Date.now(),
75
+ });
76
+ let state;
77
+ let ctx = ROOT_CONTEXT;
78
+ if (candidate.kind === 'candidate' &&
79
+ timingSafeEqual(createHmac('sha256', runtime.options.input.hashKey)
80
+ .update(candidate.bytes)
81
+ .digest(), candidate.signature)) {
82
+ state = runtime.newState(true);
83
+ ctx = trace.setSpanContext(ctx, {
84
+ ...candidate.context,
85
+ traceFlags: Number.parseInt(candidate.traceparent.slice(-2), 16) & 1,
86
+ isRemote: true,
87
+ });
88
+ }
89
+ else {
90
+ const external = header === null ? null : parseTraceparent(header);
91
+ state = runtime.newState(false, external === null
92
+ ? []
93
+ : [
94
+ {
95
+ context: {
96
+ ...external,
97
+ traceFlags: header === null
98
+ ? 0
99
+ : Number.parseInt(header.slice(-2), 16) & 1,
100
+ isRemote: true,
101
+ },
102
+ },
103
+ ]);
104
+ if (candidate.kind === 'candidate' || candidate.reason !== 'missing')
105
+ runtime.options.report(new CaptureError('handoff_refused', 'context', 1));
106
+ }
107
+ requests.set(request.headers, ctx.setValue(runtime.stateKey, state));
108
+ return {};
109
+ },
110
+ startOutgoingSpanHook(request) {
111
+ // The SDK span processor gets these before requestHook. Never trust Host for destination allowlisting.
112
+ return {
113
+ 'agentrail.network.port': Number(request.port ?? (request.protocol === 'https:' ? 443 : 80)),
114
+ };
115
+ },
116
+ requestHook(span, request) {
117
+ if (!(request instanceof ClientRequest)) {
118
+ if (!span.isRecording())
119
+ runtime.options.report(new CaptureError('entry_not_recording', 'traces', 1));
120
+ return;
121
+ }
122
+ const metadata = runtime.spans.get(span);
123
+ if (metadata === undefined)
124
+ return;
125
+ for (const header of ownedHeaders)
126
+ request.removeHeader(header);
127
+ const port = ports.get(span);
128
+ // Public ClientRequest.host is the actual connection hostname; its Host header may be overridden.
129
+ const hostname = request.host.includes(':') && !request.host.startsWith('[')
130
+ ? `[${request.host}]`
131
+ : request.host;
132
+ const origin = new URL(`${request.protocol}//${hostname}${port === undefined ? '' : `:${port}`}`).origin;
133
+ for (const [key, value] of Object.entries(sign(span, request.method, request.path, origin)))
134
+ request.setHeader(key, value);
135
+ },
136
+ };
137
+ const undiciOptions = {
138
+ requireParentforSpans: true,
139
+ ignoreRequestHook: (request) => request.origin === collector.origin &&
140
+ request.path.startsWith(collector.pathname),
141
+ requestHook(span, request) {
142
+ if (!runtime.spans.has(span))
143
+ return;
144
+ stripUndiciHeaders(request);
145
+ for (const [key, value] of Object.entries(sign(span, request.method, request.path, new URL(request.origin).origin)))
146
+ request.addHeader(key, value);
147
+ },
148
+ };
149
+ return {
150
+ propagator,
151
+ httpOptions,
152
+ undiciOptions,
153
+ rememberPort(span, value) {
154
+ if (typeof value === 'number')
155
+ ports.set(span, value);
156
+ },
157
+ };
158
+ }
159
+ function stripUndiciHeaders(request) {
160
+ if (typeof request.headers === 'string')
161
+ request.headers = request.headers
162
+ .split('\r\n')
163
+ .filter((line) => !ownedHeaders.includes(line.slice(0, line.indexOf(':')).toLowerCase()))
164
+ .join('\r\n');
165
+ else {
166
+ const headers = [];
167
+ for (let i = 0; i < request.headers.length; i += 2) {
168
+ const name = request.headers[i];
169
+ const value = request.headers[i + 1];
170
+ if (typeof name === 'string' &&
171
+ value !== undefined &&
172
+ !ownedHeaders.includes(name.toLowerCase()))
173
+ headers.push(name, value);
174
+ }
175
+ request.headers = headers;
176
+ }
177
+ }