@netgreener/runtime 0.1.9 → 0.1.10
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/CHANGELOG.md +12 -0
- package/dist/externalApiMeter.d.ts +8 -1
- package/dist/externalApiMeter.js +112 -21
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/mcpToolMeter.d.ts +101 -0
- package/dist/mcpToolMeter.js +496 -0
- package/dist/next.d.ts +28 -0
- package/dist/next.js +143 -10
- package/dist/nextConfig.d.ts +34 -0
- package/dist/nextConfig.js +73 -0
- package/dist/nextEntryTransform.d.ts +9 -0
- package/dist/nextEntryTransform.js +181 -0
- package/dist/runtime.d.ts +8 -1
- package/dist/runtime.js +51 -6
- package/dist/types.d.ts +8 -0
- package/examples/azure-functions-gate/.funcignore +6 -0
- package/examples/azure-functions-gate/README.md +25 -0
- package/examples/azure-functions-gate/host.json +15 -0
- package/examples/azure-functions-gate/package-lock.json +161 -0
- package/examples/azure-functions-gate/package.json +14 -0
- package/examples/azure-functions-gate/src/functions/health.js +27 -0
- package/loaders/next-entry-loader.cjs +14 -0
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog — @netgreener/runtime
|
|
2
2
|
|
|
3
|
+
## [0.1.10] — 2026-10-19
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- Next.js config wrapper and `loaders/next-entry-loader.cjs` for App Router route, page, and server-action observation
|
|
7
|
+
- Ephemeral invoke flush after the response closes
|
|
8
|
+
- `calls_unknown` on external API rows when a call has no token usage
|
|
9
|
+
|
|
10
|
+
## [0.1.9] — 2026-10-12
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- Public export `@netgreener/runtime/next`
|
|
14
|
+
|
|
3
15
|
## [0.1.8] — 2026-09-27
|
|
4
16
|
|
|
5
17
|
### Fixed
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* fetch meter via ALS so the same call is not double-counted.
|
|
13
13
|
*/
|
|
14
14
|
import type { ExternalApiV0 } from './types.js';
|
|
15
|
-
export declare function providerForHost(host: string): string;
|
|
15
|
+
export declare function providerForHost(host: string, url?: string): string;
|
|
16
16
|
export declare function hostFromUrl(url: unknown): string;
|
|
17
17
|
export declare function modelFromUrl(url: unknown): string | null;
|
|
18
18
|
export declare function tokensFromUsage(usage: Record<string, unknown>): [number, number];
|
|
@@ -48,6 +48,7 @@ export declare class StreamUsageMeter {
|
|
|
48
48
|
error: boolean;
|
|
49
49
|
serviceUnit: string | null;
|
|
50
50
|
tenantId: string | null;
|
|
51
|
+
parentToolCallId?: string | null;
|
|
51
52
|
});
|
|
52
53
|
/** Resolves after ``finish`` (for flush / test coordination). */
|
|
53
54
|
whenFinished(): Promise<void>;
|
|
@@ -82,6 +83,7 @@ export declare class ExternalApiAggregator {
|
|
|
82
83
|
private byTenant;
|
|
83
84
|
private excludedHosts;
|
|
84
85
|
setExcludedHosts(hosts: Iterable<string>): void;
|
|
86
|
+
excludesHost(host: string): boolean;
|
|
85
87
|
private isExcluded;
|
|
86
88
|
hasData(): boolean;
|
|
87
89
|
private recordProvider;
|
|
@@ -94,6 +96,7 @@ export declare class ExternalApiAggregator {
|
|
|
94
96
|
serviceUnit?: string | null;
|
|
95
97
|
model?: string | null;
|
|
96
98
|
tenantId?: string | null;
|
|
99
|
+
url?: string;
|
|
97
100
|
}): void;
|
|
98
101
|
private providerRow;
|
|
99
102
|
buildV0(): ExternalApiV0 | null;
|
|
@@ -102,6 +105,10 @@ export declare class ExternalApiAggregator {
|
|
|
102
105
|
mergeSnapshot(snapshot: ExternalApiAggregator): void;
|
|
103
106
|
clear(): void;
|
|
104
107
|
}
|
|
108
|
+
/** In-flight metered ``fetch`` calls, including a stream usage parse still running. */
|
|
109
|
+
export declare function outboundHttpInFlight(): number;
|
|
110
|
+
/** Resolves immediately when no metered ``fetch`` is in flight. */
|
|
111
|
+
export declare function whenOutboundHttpIdle(): Promise<void>;
|
|
105
112
|
export declare function _awaitPendingUsageParses(): Promise<void>;
|
|
106
113
|
export declare function getExternalAggregator(): ExternalApiAggregator;
|
|
107
114
|
export declare function getOriginalFetch(): typeof fetch | null;
|
package/dist/externalApiMeter.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* fetch meter via ALS so the same call is not double-counted.
|
|
13
13
|
*/
|
|
14
14
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
15
|
+
import { activeMcpToolCallId, recordHttpInToolContext } from './mcpToolMeter.js';
|
|
15
16
|
import { createRequire } from 'node:module';
|
|
16
17
|
import { getTenantContext } from './tenantContext.js';
|
|
17
18
|
import { attributionServiceUnit } from './requestContext.js';
|
|
@@ -39,7 +40,13 @@ const HOST_PROVIDER_PATTERNS = [
|
|
|
39
40
|
['textract.', 'aws_textract'],
|
|
40
41
|
['documentai.googleapis.com', 'google_document_ai'],
|
|
41
42
|
['vision.googleapis.com', 'google_document_ai'],
|
|
43
|
+
['aiplatform.googleapis.com', 'vertex'],
|
|
44
|
+
['gmail.googleapis.com', 'gmail'],
|
|
42
45
|
['generativelanguage.googleapis.com', 'google'],
|
|
46
|
+
['graph.microsoft.com', 'microsoft_graph'],
|
|
47
|
+
['api.pipedream.com', 'pipedream'],
|
|
48
|
+
['pipedream.com', 'pipedream'],
|
|
49
|
+
['finmo.ca', 'finmo'],
|
|
43
50
|
['googleapis.com', 'google'],
|
|
44
51
|
['cohere.ai', 'cohere'],
|
|
45
52
|
['cohere.com', 'cohere'],
|
|
@@ -52,8 +59,18 @@ function registeredDomain(host) {
|
|
|
52
59
|
return parts.slice(-2).join('.');
|
|
53
60
|
return host;
|
|
54
61
|
}
|
|
55
|
-
export function providerForHost(host) {
|
|
62
|
+
export function providerForHost(host, url) {
|
|
56
63
|
const h = (host || '').toLowerCase().trim();
|
|
64
|
+
let path = '';
|
|
65
|
+
try {
|
|
66
|
+
path = new URL(String(url || '')).pathname.toLowerCase();
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
path = '';
|
|
70
|
+
}
|
|
71
|
+
// Drive shares www.googleapis.com with other Google APIs. The path is the identity.
|
|
72
|
+
if (h.includes('googleapis.com') && path.includes('/drive/'))
|
|
73
|
+
return 'google_drive';
|
|
57
74
|
for (const [needle, provider] of HOST_PROVIDER_PATTERNS) {
|
|
58
75
|
if (h.includes(needle))
|
|
59
76
|
return provider;
|
|
@@ -445,6 +462,7 @@ export class StreamUsageMeter {
|
|
|
445
462
|
usage: { input: this._inTok, output: this._outTok, model: this._model },
|
|
446
463
|
serviceUnit: this.opts.serviceUnit,
|
|
447
464
|
tenantId: this.opts.tenantId,
|
|
465
|
+
parentToolCallId: this.opts.parentToolCallId ?? null,
|
|
448
466
|
});
|
|
449
467
|
this._resolveFinish();
|
|
450
468
|
}
|
|
@@ -644,6 +662,7 @@ function emptyProvider(key) {
|
|
|
644
662
|
input_tokens: 0,
|
|
645
663
|
output_tokens: 0,
|
|
646
664
|
calls_with_usage: 0,
|
|
665
|
+
calls_unknown: 0,
|
|
647
666
|
hosts: new Set(),
|
|
648
667
|
models: new Set(),
|
|
649
668
|
by_model: new Map(),
|
|
@@ -657,6 +676,9 @@ export class ExternalApiAggregator {
|
|
|
657
676
|
setExcludedHosts(hosts) {
|
|
658
677
|
this.excludedHosts = new Set([...hosts].map((h) => h.toLowerCase().trim()).filter(Boolean));
|
|
659
678
|
}
|
|
679
|
+
excludesHost(host) {
|
|
680
|
+
return this.isExcluded(host);
|
|
681
|
+
}
|
|
660
682
|
isExcluded(host) {
|
|
661
683
|
if (isPrivateOrLocalHost(host))
|
|
662
684
|
return true;
|
|
@@ -699,6 +721,8 @@ export class ExternalApiAggregator {
|
|
|
699
721
|
const hasUsage = opts.inputTokens > 0 || opts.outputTokens > 0;
|
|
700
722
|
if (hasUsage)
|
|
701
723
|
p.calls_with_usage += 1;
|
|
724
|
+
else
|
|
725
|
+
p.calls_unknown += 1;
|
|
702
726
|
if (opts.inputTokens > 0)
|
|
703
727
|
p.input_tokens += opts.inputTokens;
|
|
704
728
|
if (opts.outputTokens > 0)
|
|
@@ -731,6 +755,8 @@ export class ExternalApiAggregator {
|
|
|
731
755
|
mAgg.errors += 1;
|
|
732
756
|
if (hasUsage)
|
|
733
757
|
mAgg.calls_with_usage += 1;
|
|
758
|
+
else
|
|
759
|
+
mAgg.calls_unknown = (mAgg.calls_unknown ?? 0) + 1;
|
|
734
760
|
if (opts.inputTokens > 0)
|
|
735
761
|
mAgg.input_tokens += opts.inputTokens;
|
|
736
762
|
if (opts.outputTokens > 0)
|
|
@@ -739,7 +765,7 @@ export class ExternalApiAggregator {
|
|
|
739
765
|
record(opts) {
|
|
740
766
|
if (this.isExcluded(opts.host))
|
|
741
767
|
return;
|
|
742
|
-
const provider = providerForHost(opts.host);
|
|
768
|
+
const provider = providerForHost(opts.host, opts.url);
|
|
743
769
|
const durationMs = opts.durationMs ?? 0;
|
|
744
770
|
const error = Boolean(opts.error);
|
|
745
771
|
const inputTokens = opts.inputTokens ?? 0;
|
|
@@ -799,6 +825,7 @@ export class ExternalApiAggregator {
|
|
|
799
825
|
calls: p.calls,
|
|
800
826
|
errors: p.errors,
|
|
801
827
|
calls_with_usage: p.calls_with_usage,
|
|
828
|
+
...(p.calls_unknown > 0 ? { calls_unknown: p.calls_unknown } : {}),
|
|
802
829
|
};
|
|
803
830
|
if (p.calls > 0) {
|
|
804
831
|
row.duration_ms_avg = Math.round((p.duration_ms_total / p.calls) * 1000) / 1000;
|
|
@@ -824,6 +851,7 @@ export class ExternalApiAggregator {
|
|
|
824
851
|
calls: m.calls,
|
|
825
852
|
errors: m.errors,
|
|
826
853
|
calls_with_usage: m.calls_with_usage,
|
|
854
|
+
...((m.calls_unknown ?? 0) > 0 ? { calls_unknown: m.calls_unknown } : {}),
|
|
827
855
|
};
|
|
828
856
|
if (m.input_tokens)
|
|
829
857
|
mRow.input_tokens = m.input_tokens;
|
|
@@ -900,6 +928,7 @@ export class ExternalApiAggregator {
|
|
|
900
928
|
target.input_tokens += source.input_tokens;
|
|
901
929
|
target.output_tokens += source.output_tokens;
|
|
902
930
|
target.calls_with_usage += source.calls_with_usage;
|
|
931
|
+
target.calls_unknown += source.calls_unknown;
|
|
903
932
|
for (const h of source.hosts) {
|
|
904
933
|
if (target.hosts.size >= 8)
|
|
905
934
|
break;
|
|
@@ -932,6 +961,7 @@ export class ExternalApiAggregator {
|
|
|
932
961
|
dst.input_tokens += src.input_tokens;
|
|
933
962
|
dst.output_tokens += src.output_tokens;
|
|
934
963
|
dst.calls_with_usage += src.calls_with_usage;
|
|
964
|
+
dst.calls_unknown = (dst.calls_unknown ?? 0) + (src.calls_unknown ?? 0);
|
|
935
965
|
}
|
|
936
966
|
}
|
|
937
967
|
mergeSnapshot(snapshot) {
|
|
@@ -986,6 +1016,32 @@ let originalFetch = null;
|
|
|
986
1016
|
let restoreAxios = null;
|
|
987
1017
|
let restoreUndici = null;
|
|
988
1018
|
const pendingUsageParses = [];
|
|
1019
|
+
let outboundHttpActive = 0;
|
|
1020
|
+
const outboundIdleWaiters = [];
|
|
1021
|
+
function outboundHttpEnter() {
|
|
1022
|
+
outboundHttpActive += 1;
|
|
1023
|
+
}
|
|
1024
|
+
function outboundHttpLeave() {
|
|
1025
|
+
if (outboundHttpActive > 0)
|
|
1026
|
+
outboundHttpActive -= 1;
|
|
1027
|
+
if (outboundHttpActive === 0) {
|
|
1028
|
+
const waiters = outboundIdleWaiters.splice(0);
|
|
1029
|
+
for (const wake of waiters)
|
|
1030
|
+
wake();
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
/** In-flight metered ``fetch`` calls, including a stream usage parse still running. */
|
|
1034
|
+
export function outboundHttpInFlight() {
|
|
1035
|
+
return outboundHttpActive;
|
|
1036
|
+
}
|
|
1037
|
+
/** Resolves immediately when no metered ``fetch`` is in flight. */
|
|
1038
|
+
export function whenOutboundHttpIdle() {
|
|
1039
|
+
if (outboundHttpActive === 0)
|
|
1040
|
+
return Promise.resolve();
|
|
1041
|
+
return new Promise((resolve) => {
|
|
1042
|
+
outboundIdleWaiters.push(resolve);
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
989
1045
|
function trackStreamMeter(meter) {
|
|
990
1046
|
pendingUsageParses.push(meter.whenFinished());
|
|
991
1047
|
}
|
|
@@ -1000,7 +1056,16 @@ function recordMeteredCall(opts) {
|
|
|
1000
1056
|
model: opts.usage.model || modelFromUrl(opts.url),
|
|
1001
1057
|
serviceUnit: opts.serviceUnit,
|
|
1002
1058
|
tenantId: opts.tenantId,
|
|
1059
|
+
url: opts.url,
|
|
1003
1060
|
});
|
|
1061
|
+
if (opts.parentToolCallId && !globalAgg.excludesHost(opts.host)) {
|
|
1062
|
+
recordHttpInToolContext({
|
|
1063
|
+
toolCallId: opts.parentToolCallId,
|
|
1064
|
+
host: opts.host,
|
|
1065
|
+
durationMs: opts.durationMs,
|
|
1066
|
+
error: opts.error,
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1004
1069
|
}
|
|
1005
1070
|
catch {
|
|
1006
1071
|
/* never break caller */
|
|
@@ -1080,9 +1145,18 @@ function installFetchWrap() {
|
|
|
1080
1145
|
// Snapshot inbound attribution when the outbound call starts — not after await.
|
|
1081
1146
|
const serviceUnitAtStart = attributionServiceUnit();
|
|
1082
1147
|
const tenantIdAtStart = getTenantContext()?.tenantId ?? null;
|
|
1148
|
+
const parentToolCallId = activeMcpToolCallId();
|
|
1083
1149
|
const start = performance.now();
|
|
1084
1150
|
let error = false;
|
|
1085
1151
|
let response;
|
|
1152
|
+
outboundHttpEnter();
|
|
1153
|
+
let released = false;
|
|
1154
|
+
const release = () => {
|
|
1155
|
+
if (released)
|
|
1156
|
+
return;
|
|
1157
|
+
released = true;
|
|
1158
|
+
outboundHttpLeave();
|
|
1159
|
+
};
|
|
1086
1160
|
try {
|
|
1087
1161
|
response = await outboundMeterOwnerAls.run('fetch', () => base(input, init));
|
|
1088
1162
|
if (response.status >= 400)
|
|
@@ -1104,33 +1178,41 @@ function installFetchWrap() {
|
|
|
1104
1178
|
usage,
|
|
1105
1179
|
serviceUnit: serviceUnitAtStart,
|
|
1106
1180
|
tenantId: tenantIdAtStart,
|
|
1181
|
+
parentToolCallId,
|
|
1107
1182
|
});
|
|
1108
1183
|
};
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
const captured = response;
|
|
1114
|
-
const parse = async () => {
|
|
1115
|
-
try {
|
|
1116
|
-
return await extractUsageFromResponse(captured, url);
|
|
1117
|
-
}
|
|
1118
|
-
catch {
|
|
1119
|
-
return { input: 0, output: 0, model: modelFromUrl(url) };
|
|
1120
|
-
}
|
|
1121
|
-
};
|
|
1122
|
-
if (isStreamingContentType(captured)) {
|
|
1123
|
-
pendingUsageParses.push(parse().then(recordUsage));
|
|
1184
|
+
try {
|
|
1185
|
+
if (!response) {
|
|
1186
|
+
recordUsage({ input: 0, output: 0, model: modelFromUrl(url) });
|
|
1187
|
+
release();
|
|
1124
1188
|
}
|
|
1125
1189
|
else {
|
|
1126
|
-
|
|
1127
|
-
|
|
1190
|
+
const captured = response;
|
|
1191
|
+
const parse = async () => {
|
|
1192
|
+
try {
|
|
1193
|
+
return await extractUsageFromResponse(captured, url);
|
|
1194
|
+
}
|
|
1195
|
+
catch {
|
|
1196
|
+
return { input: 0, output: 0, model: modelFromUrl(url) };
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
if (isStreamingContentType(captured)) {
|
|
1200
|
+
pendingUsageParses.push(parse().then(recordUsage).finally(release));
|
|
1128
1201
|
}
|
|
1129
|
-
|
|
1130
|
-
|
|
1202
|
+
else {
|
|
1203
|
+
try {
|
|
1204
|
+
recordUsage(await parse());
|
|
1205
|
+
}
|
|
1206
|
+
catch {
|
|
1207
|
+
recordUsage({ input: 0, output: 0, model: modelFromUrl(url) });
|
|
1208
|
+
}
|
|
1209
|
+
release();
|
|
1131
1210
|
}
|
|
1132
1211
|
}
|
|
1133
1212
|
}
|
|
1213
|
+
catch {
|
|
1214
|
+
release();
|
|
1215
|
+
}
|
|
1134
1216
|
}
|
|
1135
1217
|
};
|
|
1136
1218
|
wrapped._netgreenerWrapped = true;
|
|
@@ -1166,6 +1248,7 @@ function installAxiosWrap() {
|
|
|
1166
1248
|
const host = hostFromUrl(url);
|
|
1167
1249
|
const serviceUnitAtStart = attributionServiceUnit();
|
|
1168
1250
|
const tenantIdAtStart = getTenantContext()?.tenantId ?? null;
|
|
1251
|
+
const parentToolCallId = activeMcpToolCallId();
|
|
1169
1252
|
const start = performance.now();
|
|
1170
1253
|
let error = false;
|
|
1171
1254
|
const invoke = () => originalRequest.apply(this, args);
|
|
@@ -1180,6 +1263,7 @@ function installAxiosWrap() {
|
|
|
1180
1263
|
usage: { input: 0, output: 0, model: modelFromUrl(url) },
|
|
1181
1264
|
serviceUnit: serviceUnitAtStart,
|
|
1182
1265
|
tenantId: tenantIdAtStart,
|
|
1266
|
+
parentToolCallId,
|
|
1183
1267
|
});
|
|
1184
1268
|
return result;
|
|
1185
1269
|
}
|
|
@@ -1204,6 +1288,7 @@ function installAxiosWrap() {
|
|
|
1204
1288
|
error,
|
|
1205
1289
|
serviceUnit: serviceUnitAtStart,
|
|
1206
1290
|
tenantId: tenantIdAtStart,
|
|
1291
|
+
parentToolCallId,
|
|
1207
1292
|
});
|
|
1208
1293
|
if (attachStreamUsageMeter(resp.data, meter)) {
|
|
1209
1294
|
trackStreamMeter(meter);
|
|
@@ -1227,6 +1312,7 @@ function installAxiosWrap() {
|
|
|
1227
1312
|
usage,
|
|
1228
1313
|
serviceUnit: serviceUnitAtStart,
|
|
1229
1314
|
tenantId: tenantIdAtStart,
|
|
1315
|
+
parentToolCallId,
|
|
1230
1316
|
});
|
|
1231
1317
|
return result;
|
|
1232
1318
|
};
|
|
@@ -1283,6 +1369,7 @@ function installUndiciWrap() {
|
|
|
1283
1369
|
const host = hostFromUrl(url);
|
|
1284
1370
|
const serviceUnitAtStart = attributionServiceUnit();
|
|
1285
1371
|
const tenantIdAtStart = getTenantContext()?.tenantId ?? null;
|
|
1372
|
+
const parentToolCallId = activeMcpToolCallId();
|
|
1286
1373
|
const start = performance.now();
|
|
1287
1374
|
const finish = (result, threw) => {
|
|
1288
1375
|
const durationMs = performance.now() - start;
|
|
@@ -1303,6 +1390,7 @@ function installUndiciWrap() {
|
|
|
1303
1390
|
error,
|
|
1304
1391
|
serviceUnit: serviceUnitAtStart,
|
|
1305
1392
|
tenantId: tenantIdAtStart,
|
|
1393
|
+
parentToolCallId,
|
|
1306
1394
|
});
|
|
1307
1395
|
if (attachStreamUsageMeter(body, meter)) {
|
|
1308
1396
|
trackStreamMeter(meter);
|
|
@@ -1318,6 +1406,7 @@ function installUndiciWrap() {
|
|
|
1318
1406
|
usage: { input: 0, output: 0, model: modelFromUrl(url) },
|
|
1319
1407
|
serviceUnit: serviceUnitAtStart,
|
|
1320
1408
|
tenantId: tenantIdAtStart,
|
|
1409
|
+
parentToolCallId,
|
|
1321
1410
|
});
|
|
1322
1411
|
return result;
|
|
1323
1412
|
};
|
|
@@ -1376,6 +1465,8 @@ function installUndiciWrap() {
|
|
|
1376
1465
|
/** Test helper — reset install state. */
|
|
1377
1466
|
export function _resetOutboundInstrumentationForTests() {
|
|
1378
1467
|
pendingUsageParses.length = 0;
|
|
1468
|
+
outboundHttpActive = 0;
|
|
1469
|
+
outboundIdleWaiters.length = 0;
|
|
1379
1470
|
if (originalFetch && typeof globalThis.fetch === 'function') {
|
|
1380
1471
|
globalThis.fetch = originalFetch;
|
|
1381
1472
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -29,10 +29,12 @@ export { NetGreenerRuntime, getRuntime, _resetRuntimeForTests, type FlushKind, t
|
|
|
29
29
|
export { netgreenerExpressMiddleware, getExpressRuntime, type ExpressRequest, type ExpressResponse, type ExpressNext, } from './express.js';
|
|
30
30
|
export { netgreenerFastifyPlugin, getFastifyRuntime, fastifyRouteTemplate, bindFastifyTenant, type FastifyLike, type FastifyRequestLike, type FastifyReplyLike, } from './fastify.js';
|
|
31
31
|
export { applyNetGreenerNestHooks, detectNestHttpAdapter, getNestRuntime, netgreenerNestExpressMiddleware, netgreenerNestFastifyPlugin, type NestApplicationLike, type NestHttpAdapterKind, } from './nest.js';
|
|
32
|
-
export { UNKNOWN_NEXT_ROUTE_TEMPLATE, flushNetGreenerNext, getNextRuntime, nextRouteTemplate, registerNetGreenerNext, scheduleNetGreenerFlush, withNetGreenerRoute, type NetGreenerNextOptions, type NextRequestLike, type NextRouteContext, } from './next.js';
|
|
32
|
+
export { UNKNOWN_NEXT_ROUTE_TEMPLATE, flushNetGreenerNext, getNextRuntime, nextRouteTemplate, observeNextAction, observeNextPage, observeNextRoute, registerNetGreenerNext, scheduleNetGreenerFlush, withNetGreenerRoute, type NetGreenerNextOptions, type NextRequestLike, type NextRouteContext, } from './next.js';
|
|
33
|
+
export { withNetGreener, type NextConfigLike } from './nextConfig.js';
|
|
33
34
|
export { attachWindowTenantToRunContext, getTenantContext, loadTenantConfig, normalizeTenantId, resolveTenantFromHttpRequest, resolveTenantFromTaskData, runWithTenantContext, setTenantContext, tenantConfigFromRuntime, type TenantConfig, type TenantContext, } from './tenantContext.js';
|
|
34
35
|
export { ExternalApiAggregator, buildExternalV0, clearExternalAggregator, getExternalAggregator, installOutboundInstrumentation, providerForHost, usageFromClientBody, _resetOutboundInstrumentationForTests, } from './externalApiMeter.js';
|
|
35
36
|
export { attributionServiceUnit, getRequestAttribution, runWithRequestAttribution, } from './requestContext.js';
|
|
37
|
+
export { McpToolBudgetBlocked, activeMcpToolCallId, beginToolCall, budgetMode, buildMcpLatencyV0, buildMcpToolV0, clearMcpToolLedger, finishToolCall, getMcpToolLedger, installMcpClientInstrumentation, recordHttpInToolContext, runWithMcpToolCall, type McpBudgetAction, type McpHttpLinkRow, type McpToolCallRow, type McpToolDecision, } from './mcpToolMeter.js';
|
|
36
38
|
export { getBullMqRuntime, netgreenerBullMqProcessor, runBullMqJobWithNetGreener, type BullMqJobLike, type BullMqProcessorOptions, } from './bullmq.js';
|
|
37
39
|
export { bindProcessTenant, flushProcessRuntime, runWithProcessTenant, startProcessRuntime, type ProcessRuntimeOptions, } from './processRuntime.js';
|
|
38
40
|
export { buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, buildServiceManifestFromPaths, listCandidateSourceFiles, NON_RESOURCE_CATEGORIES, RESOURCE_DOMAINS, admitAnalyzeCandidate, isNonResourceCategory, languageForPath, toResourceFindingCandidate, detectRetryAmplificationHits, detectApiOverconsumptionHits, detectUnboundedParallelismHits, detectPollingIdleHits, detectProcessChurnHits, detectRepeatedWorkHits, detectPerItemInsteadOfBatchHits, detectModelLoadInLoopHits, detectFullDatasetInMemoryHits, detectRepeatedFileReadHits, detectAllHitsAst, detectHotPathHitsAst, detectApiOverconsumptionHitsAst, detectPollingIdleHitsAst, detectProcessChurnHitsAst, detectRepeatedFileReadHitsAst, detectRepeatedWorkHitsAst, detectRetryAmplificationHitsAst, detectUnboundedParallelismHitsAst, detectFullDatasetInMemoryHitsAst, detectPerItemInsteadOfBatchHitsAst, detectModelLoadInLoopHitsAst, collectPreferAstHits, detectApiOverconsumptionHitsPreferAst, detectPollingIdleHitsPreferAst, detectProcessChurnHitsPreferAst, detectRepeatedFileReadHitsPreferAst, detectRepeatedWorkHitsPreferAst, detectRetryAmplificationHitsPreferAst, detectUnboundedParallelismHitsPreferAst, detectFullDatasetInMemoryHitsPreferAst, detectPerItemInsteadOfBatchHitsPreferAst, detectModelLoadInLoopHitsPreferAst, isTypescriptAnalyzeAvailable, tryLoadTypescript, allResourceFindingsValid, filterValidResourceFindings, validateResourceFindingCandidate, countGateFindings, findingsExceedFailThreshold, formatAnalyzeGateFailureMessage, resolveAnalyzeGateLimit, buildAnalyzeGateSummary, buildResourceAnalyzeResultFromPaths, buildResourceFindingsFromSources, type ServiceEndpointUnit, type ServiceFileExtraction, type ServiceManifestV0, type ServiceTaskUnit, type ListCandidateSourceFilesOptions, type AdmissionDecision, type NonResourceCategory, type ResourceDomain, type ResourceCandidateHit, type ResourceFindingCandidateV1, type ResourcePrimaryDomain, type BuildResourceFindingsOptions, type ResourceAnalyzeResultV0, type ResourceFindingValidation, type ResourceFindingValidationError, type AnalyzeGateLimit, type AnalyzeGateSummaryV0, type AstHitBundle, } from './analyze/index.js';
|
package/dist/index.js
CHANGED
|
@@ -28,10 +28,12 @@ export { NetGreenerRuntime, getRuntime, _resetRuntimeForTests, } from './runtime
|
|
|
28
28
|
export { netgreenerExpressMiddleware, getExpressRuntime, } from './express.js';
|
|
29
29
|
export { netgreenerFastifyPlugin, getFastifyRuntime, fastifyRouteTemplate, bindFastifyTenant, } from './fastify.js';
|
|
30
30
|
export { applyNetGreenerNestHooks, detectNestHttpAdapter, getNestRuntime, netgreenerNestExpressMiddleware, netgreenerNestFastifyPlugin, } from './nest.js';
|
|
31
|
-
export { UNKNOWN_NEXT_ROUTE_TEMPLATE, flushNetGreenerNext, getNextRuntime, nextRouteTemplate, registerNetGreenerNext, scheduleNetGreenerFlush, withNetGreenerRoute, } from './next.js';
|
|
31
|
+
export { UNKNOWN_NEXT_ROUTE_TEMPLATE, flushNetGreenerNext, getNextRuntime, nextRouteTemplate, observeNextAction, observeNextPage, observeNextRoute, registerNetGreenerNext, scheduleNetGreenerFlush, withNetGreenerRoute, } from './next.js';
|
|
32
|
+
export { withNetGreener } from './nextConfig.js';
|
|
32
33
|
export { attachWindowTenantToRunContext, getTenantContext, loadTenantConfig, normalizeTenantId, resolveTenantFromHttpRequest, resolveTenantFromTaskData, runWithTenantContext, setTenantContext, tenantConfigFromRuntime, } from './tenantContext.js';
|
|
33
34
|
export { ExternalApiAggregator, buildExternalV0, clearExternalAggregator, getExternalAggregator, installOutboundInstrumentation, providerForHost, usageFromClientBody, _resetOutboundInstrumentationForTests, } from './externalApiMeter.js';
|
|
34
35
|
export { attributionServiceUnit, getRequestAttribution, runWithRequestAttribution, } from './requestContext.js';
|
|
36
|
+
export { McpToolBudgetBlocked, activeMcpToolCallId, beginToolCall, budgetMode, buildMcpLatencyV0, buildMcpToolV0, clearMcpToolLedger, finishToolCall, getMcpToolLedger, installMcpClientInstrumentation, recordHttpInToolContext, runWithMcpToolCall, } from './mcpToolMeter.js';
|
|
35
37
|
export { getBullMqRuntime, netgreenerBullMqProcessor, runBullMqJobWithNetGreener, } from './bullmq.js';
|
|
36
38
|
export { bindProcessTenant, flushProcessRuntime, runWithProcessTenant, startProcessRuntime, } from './processRuntime.js';
|
|
37
39
|
export { buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, buildServiceManifestFromPaths, listCandidateSourceFiles, NON_RESOURCE_CATEGORIES, RESOURCE_DOMAINS, admitAnalyzeCandidate, isNonResourceCategory, languageForPath, toResourceFindingCandidate, detectRetryAmplificationHits, detectApiOverconsumptionHits, detectUnboundedParallelismHits, detectPollingIdleHits, detectProcessChurnHits, detectRepeatedWorkHits, detectPerItemInsteadOfBatchHits, detectModelLoadInLoopHits, detectFullDatasetInMemoryHits, detectRepeatedFileReadHits, detectAllHitsAst, detectHotPathHitsAst, detectApiOverconsumptionHitsAst, detectPollingIdleHitsAst, detectProcessChurnHitsAst, detectRepeatedFileReadHitsAst, detectRepeatedWorkHitsAst, detectRetryAmplificationHitsAst, detectUnboundedParallelismHitsAst, detectFullDatasetInMemoryHitsAst, detectPerItemInsteadOfBatchHitsAst, detectModelLoadInLoopHitsAst, collectPreferAstHits, detectApiOverconsumptionHitsPreferAst, detectPollingIdleHitsPreferAst, detectProcessChurnHitsPreferAst, detectRepeatedFileReadHitsPreferAst, detectRepeatedWorkHitsPreferAst, detectRetryAmplificationHitsPreferAst, detectUnboundedParallelismHitsPreferAst, detectFullDatasetInMemoryHitsPreferAst, detectPerItemInsteadOfBatchHitsPreferAst, detectModelLoadInLoopHitsPreferAst, isTypescriptAnalyzeAvailable, tryLoadTypescript, allResourceFindingsValid, filterValidResourceFindings, validateResourceFindingCandidate, countGateFindings, findingsExceedFailThreshold, formatAnalyzeGateFailureMessage, resolveAnalyzeGateLimit, buildAnalyzeGateSummary, buildResourceAnalyzeResultFromPaths, buildResourceFindingsFromSources, } from './analyze/index.js';
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Same-process MCP tool observation for the Node runtime.
|
|
3
|
+
*
|
|
4
|
+
* Matches the Python week-1 counter and week-2 duration rows. The active
|
|
5
|
+
* tool-call id lives in AsyncLocalStorage. A fetch that starts while that id
|
|
6
|
+
* is set records a link. The link is not written onto external_api_v0.
|
|
7
|
+
*
|
|
8
|
+
* The counter is this process only. Warn is the default. Block is opt-in and
|
|
9
|
+
* does not invoke the tool. A configured estimate is not added to API cost.
|
|
10
|
+
* The official TypeScript MCP client is not patched. Calls are recorded only
|
|
11
|
+
* when this process calls beginToolCall. A missing client hook is not monitoring.
|
|
12
|
+
*
|
|
13
|
+
* Raw tool arguments, results, and HTTP bodies are not stored.
|
|
14
|
+
*/
|
|
15
|
+
export declare class McpToolBudgetBlocked extends Error {
|
|
16
|
+
constructor(message: string);
|
|
17
|
+
}
|
|
18
|
+
export type McpBudgetAction = 'allow' | 'warn' | 'block';
|
|
19
|
+
export type McpToolCallRow = {
|
|
20
|
+
server: string;
|
|
21
|
+
tool: string;
|
|
22
|
+
started_at: string;
|
|
23
|
+
duration_ms: number;
|
|
24
|
+
success: boolean;
|
|
25
|
+
attempt: number;
|
|
26
|
+
budget_action: McpBudgetAction;
|
|
27
|
+
invoked: boolean;
|
|
28
|
+
call_id: string;
|
|
29
|
+
execution_id?: string;
|
|
30
|
+
tenant_id?: string;
|
|
31
|
+
estimated_usd?: number;
|
|
32
|
+
estimate_label?: 'configured';
|
|
33
|
+
budget_reason?: string;
|
|
34
|
+
};
|
|
35
|
+
export type McpHttpLinkRow = {
|
|
36
|
+
tool_call_id: string;
|
|
37
|
+
host: string;
|
|
38
|
+
duration_ms: number;
|
|
39
|
+
error: boolean;
|
|
40
|
+
};
|
|
41
|
+
export type McpToolDecision = {
|
|
42
|
+
callId: string;
|
|
43
|
+
server: string;
|
|
44
|
+
tool: string;
|
|
45
|
+
attempt: number;
|
|
46
|
+
action: McpBudgetAction;
|
|
47
|
+
reason: string | null;
|
|
48
|
+
};
|
|
49
|
+
export declare function budgetMode(): 'warn' | 'block';
|
|
50
|
+
export declare function activeMcpToolCallId(): string | null;
|
|
51
|
+
export declare function runWithMcpToolCall<T>(callId: string, fn: () => T): T;
|
|
52
|
+
export declare class McpToolLedger {
|
|
53
|
+
private calls;
|
|
54
|
+
private httpLinks;
|
|
55
|
+
private dropped;
|
|
56
|
+
private budgetTotals;
|
|
57
|
+
private budgetPairs;
|
|
58
|
+
hasCalls(): boolean;
|
|
59
|
+
beginToolCall(server: string, tool: string): McpToolDecision;
|
|
60
|
+
finishToolCall(decision: McpToolDecision, opts: {
|
|
61
|
+
success: boolean;
|
|
62
|
+
durationMs: number;
|
|
63
|
+
startedAt?: string;
|
|
64
|
+
}): void;
|
|
65
|
+
recordHttpLink(row: {
|
|
66
|
+
toolCallId: string;
|
|
67
|
+
host: string;
|
|
68
|
+
durationMs: number;
|
|
69
|
+
error: boolean;
|
|
70
|
+
}): void;
|
|
71
|
+
takeSnapshot(): McpToolLedger;
|
|
72
|
+
mergeSnapshot(snapshot: McpToolLedger): void;
|
|
73
|
+
buildV0(): Record<string, unknown> | null;
|
|
74
|
+
clear(): void;
|
|
75
|
+
private append;
|
|
76
|
+
}
|
|
77
|
+
export declare function getMcpToolLedger(): McpToolLedger;
|
|
78
|
+
export declare function beginToolCall(server: string, tool: string): McpToolDecision;
|
|
79
|
+
export declare function finishToolCall(decision: McpToolDecision, opts: {
|
|
80
|
+
success: boolean;
|
|
81
|
+
durationMs: number;
|
|
82
|
+
startedAt?: string;
|
|
83
|
+
}): void;
|
|
84
|
+
export declare function recordHttpInToolContext(row: {
|
|
85
|
+
toolCallId: string | null;
|
|
86
|
+
host: string;
|
|
87
|
+
durationMs: number;
|
|
88
|
+
error: boolean;
|
|
89
|
+
}): void;
|
|
90
|
+
export declare function buildMcpToolV0(): Record<string, unknown> | null;
|
|
91
|
+
export declare function httpDurationMs(externalV0: Record<string, unknown> | null | undefined): number;
|
|
92
|
+
export declare function mcpDurationMs(mcpV0: Record<string, unknown> | null | undefined, failedOnly?: boolean): number;
|
|
93
|
+
export declare function buildMcpLatencyV0(mcpV0: Record<string, unknown> | null | undefined, externalV0: Record<string, unknown> | null | undefined, wallSeconds: number | null): Record<string, unknown> | null;
|
|
94
|
+
export declare function clearMcpToolLedger(): void;
|
|
95
|
+
/**
|
|
96
|
+
* Official MCP client patching stays off until one SDK version is installed
|
|
97
|
+
* and its callTool signature is tested. A command basename is not a server name.
|
|
98
|
+
* This returns false so a caller cannot treat the hook as active.
|
|
99
|
+
*/
|
|
100
|
+
export declare function installMcpClientInstrumentation(): boolean;
|
|
101
|
+
export declare function _resetMcpToolMeterForTests(): void;
|